Send a Transaction
Though it is possible to send transactions with iota.rs
, we strongly recommend that you use the official
wallet.rs
library together with the
stronghold.rs
enclave for value-based transfers. This combination
incorporates the best security practices while dealing with seeds, related addresses, and UTXO.
The following code example will:
- Create a
Client
which will connect to the Shimmer Testnet. - Create a
SecretManager
from a mnemonic. - Generate a public address.
- Build and post a block with an output address and amount to send.
- Log the transaction.
You can also find this guide in the native iota.js library
Code Example
- Rust
- Nodejs
- Python
- Java
This example uses dotenv, which is not safe to use in production environments.
// Copyright 2021 IOTA Stiftung
// SPDX-License-Identifier: Apache-2.0
//! In this example we will send a transaction.
//! Run: `cargo run --example transaction --release`.
use iota_client::{secret::SecretManager, Client, Result};
#[tokio::main]
async fn main() -> Result<()> {
// This example uses dotenv, which is not safe for use in production
// Configure your own mnemonic in ".env". Since the output amount cannot be zero, the mnemonic must contain non-zero
// balance
dotenv::dotenv().ok();
let node_url = std::env::var("NODE_URL").unwrap();
let client = Client::builder().with_node(&node_url)?.finish()?;
let secret_manager =
SecretManager::try_from_mnemonic(&std::env::var("NON_SECURE_USE_OF_DEVELOPMENT_MNEMONIC_1").unwrap())?;
let block = client
.block()
.with_secret_manager(&secret_manager)
// Insert the output address and amount to spent. The amount cannot be zero.
.with_output(
// We generate an address from our own mnemonic so that we send the funds to ourselves
&client.get_addresses(&secret_manager).with_range(1..2).finish().await?[0],
1_000_000,
)
.await?
.finish()
.await?;
println!("{block:#?}");
println!(
"Transaction sent: {}/block/{}",
std::env::var("EXPLORER_URL").unwrap(),
block.id()
);
Ok(())
}
Run the Example
Run the example by running the following command:
cargo run --example transaction --release
This example uses dotenv, which is not safe to use in production environments.
// Copyright 2021-2022 IOTA Stiftung
// SPDX-License-Identifier: Apache-2.0
import { Client, initLogger } from '@iota/client';
require('dotenv').config({ path: '../.env' });
// Run with command:
// node ./dist/09_transaction.js
// In this example we will send a transaction
async function run() {
initLogger();
if (!process.env.NODE_URL) {
throw new Error('.env NODE_URL is undefined, see .env.example');
}
const client = new Client({
// Insert your node URL in the .env.
nodes: [process.env.NODE_URL],
localPow: true,
});
try {
if (!process.env.NON_SECURE_USE_OF_DEVELOPMENT_MNEMONIC_1) {
throw new Error('.env mnemonic is undefined, see .env.example');
}
// Configure your own mnemonic in ".env". Since the output amount cannot be zero, the mnemonic must contain non-zero
// balance
const secretManager = {
mnemonic: process.env.NON_SECURE_USE_OF_DEVELOPMENT_MNEMONIC_1,
};
// We generate an address from our own mnemonic so that we send the funds to ourselves
const addresses = await client.generateAddresses(secretManager, {
range: {
start: 1,
end: 2,
},
});
// We prepare the transaction
// Insert the output address and amount to spend. The amount cannot be zero.
const blockIdAndBlock = await client.buildAndPostBlock(secretManager, {
output: {
address: addresses[0],
amount: '1000000',
},
});
console.log('Block: ', blockIdAndBlock, '\n');
console.log(
`Transaction sent: ${process.env.EXPLORER_URL}/block/${blockIdAndBlock[0]}`,
);
} catch (error) {
console.error('Error: ', error);
}
}
run().then(() => process.exit());
You can run the example by running the following command from the bindings/node/examples/
folder:
node dist/09_transaction.js
from iota_client import IotaClient, MnemonicSecretManager
# Create an IotaClient instance
client = IotaClient({'nodes': ['https://api.testnet.shimmer.network']})
secret_manager = MnemonicSecretManager("flame fever pig forward exact dash body idea link scrub tennis minute " +
"surge unaware prosper over waste kitten ceiling human knife arch situate civil")
options = {
"output": {
"address": 'rms1qzpf0tzpf8yqej5zyhjl9k3km7y6j0xjnxxh7m2g3jtj2z5grej67sl6l46',
"amount": '1000000',
}
}
# Create and post a block with a transaction
block = client.build_and_post_block(secret_manager, options)
print(f'{block}')
You can run the example by running the following command from the binding/python/examples
folder:
python3 09_transaction.py
This example uses dotenv, which is not safe to use in production environments.
// Copyright 2021-2022 IOTA Stiftung
// SPDX-License-Identifier: Apache-2.0
import { Client, initLogger } from '@iota/client';
require('dotenv').config({ path: '../.env' });
// Run with command:
// node ./dist/09_transaction.js
// In this example we will send a transaction
async function run() {
initLogger();
if (!process.env.NODE_URL) {
throw new Error('.env NODE_URL is undefined, see .env.example');
}
const client = new Client({
// Insert your node URL in the .env.
nodes: [process.env.NODE_URL],
localPow: true,
});
try {
if (!process.env.NON_SECURE_USE_OF_DEVELOPMENT_MNEMONIC_1) {
throw new Error('.env mnemonic is undefined, see .env.example');
}
// Configure your own mnemonic in ".env". Since the output amount cannot be zero, the mnemonic must contain non-zero
// balance
const secretManager = {
mnemonic: process.env.NON_SECURE_USE_OF_DEVELOPMENT_MNEMONIC_1,
};
// We generate an address from our own mnemonic so that we send the funds to ourselves
const addresses = await client.generateAddresses(secretManager, {
range: {
start: 1,
end: 2,
},
});
// We prepare the transaction
// Insert the output address and amount to spend. The amount cannot be zero.
const blockIdAndBlock = await client.buildAndPostBlock(secretManager, {
output: {
address: addresses[0],
amount: '1000000',
},
});
console.log('Block: ', blockIdAndBlock, '\n');
console.log(
`Transaction sent: ${process.env.EXPLORER_URL}/block/${blockIdAndBlock[0]}`,
);
} catch (error) {
console.error('Error: ', error);
}
}
run().then(() => process.exit());
You can run the example by running the following command from the bindings/node/examples/
folder:
node dist/09_transaction.js
Expected Output
- Rust
- Nodejs
- Python
- Java
Transaction sent: https://explorer.shimmer.network/testnet/block/0x0e4c43eb9402aad8af70bbabfc4eb43ca4b603feb77d7bbcec43ccd06d9389bb
Block: [
'0x8c48950b2796c5d60e5aafd481c34ef6395d078f28b69c3001372b89142a729a',
{
protocolVersion: 2,
parents: [
'0x0b367672968b2ae56e2f8e90dc669489776a914e37f3c31f862cd61261ca58d5',
'0x72034b2c23c772af077dc3fba9d60eb6363efe18f1fe32292baa529867e41947',
'0x85f6b7ba90b46e706cba223142475a1b0da41a333ff2bc84b1031c093eebdecf',
'0xb365c2c7e05c9a0edc7c7a1351711cf09f92b3fdb09957b5e7cac5577b395f63'
],
payload: { type: 6, essence: [Object], unlocks: [Array] },
nonce: '4611686018427398146'
}
]
Transaction sent: https://explorer.shimmer.network/testnet/block/0x8c48950b2796c5d60e5aafd481c34ef6395d078f28b69c3001372b89142a729a
[
'0x1f275f75b31471ab88b12522c5d1bb8ae9294e7aa24fda5845272440d6cec151',
{
'protocolVersion': 2,
'parents': [
'0x29d95dae99c84a62a29939b0da590eea51d6eee69596ab9b8d7547b765c996a0',
'0x6c6a7909aa7075f69be9e1b86469dc54b37e446a31ad130ad96081a5eb1426a2',
'0x9898a2148e28caa76861f69cf8b044ab86f458ddea5b8378f43777410387ba3e',
'0xbcc5f3cab065451107b6df603e0d3d8a99a3627147cacba90ed7f260a635e4a4'
],
'payload': {
'type': 6,
'essence': {
'type': 1,
'networkId': '1856588631910923207',
'inputs': [
{
'type': 0,
'transactionId': '0x3b6cba154609957899bbcaafafa4354b2207ab95ef27bdda92f86fbe06194c47',
'transactionOutputIndex': 0
},
{
'type': 0,
'transactionId': '0x3c0fc948789431e1a86b378fe3bd847f8c0634176e70986aa05a6dacba9a137a',
'transactionOutputIndex': 0
},
{
'type': 0,
'transactionId': '0x43380de68c5ca72f4ab2ee276c297d1ffb05330068373a9714d3a57a019a0cd3',
'transactionOutputIndex': 127
}
],
'inputsCommitment': '0x5e3b2fa09083546c2218b3e56b1c35225ba8df0dc027ae62e70f44d3e09af919',
'outputs': [
{
'type': 3,
'amount': '1000000',
'unlockConditions': [
{
'type': 0,
'address': {
'type': 0,
'pubKeyHash': '0x8297ac4149c80cca8225e5f2da36df89a93cd2998d7f6d488c97250a881e65af'
}
}
]
},
{
'type': 3,
'amount': '97335202',
'unlockConditions': [
{
'type': 0,
'address': {
'type': 0,
'pubKeyHash': '0x8297ac4149c80cca8225e5f2da36df89a93cd2998d7f6d488c97250a881e65af'
}
}
]
}
]
},
'unlocks': [
{
'type': 0,
'signature': {
'type': 0,
'publicKey': '0xe62838fda7e8b77bf80e49967f0f089ae2a7230547d5231649732952f6336fae',
'signature': '0x9bacfc3064e458994e19253eac4b1d299d0b1dc27ea7910228a6b8fe77022ed7a9296541ad9c159e688a9b7943eb5494d433e32eb56c7afbf14282a12a927d06'
}
},
{
'type': 1,
'reference': 0
},
{
'type': 1,
'reference': 0
}
]
},
'nonce': '6148914691236584594'
}
]
Block: [
'0x8c48950b2796c5d60e5aafd481c34ef6395d078f28b69c3001372b89142a729a',
{
protocolVersion: 2,
parents: [
'0x0b367672968b2ae56e2f8e90dc669489776a914e37f3c31f862cd61261ca58d5',
'0x72034b2c23c772af077dc3fba9d60eb6363efe18f1fe32292baa529867e41947',
'0x85f6b7ba90b46e706cba223142475a1b0da41a333ff2bc84b1031c093eebdecf',
'0xb365c2c7e05c9a0edc7c7a1351711cf09f92b3fdb09957b5e7cac5577b395f63'
],
payload: { type: 6, essence: [Object], unlocks: [Array] },
nonce: '4611686018427398146'
}
]
Transaction sent: https://explorer.shimmer.network/testnet/block/0x8c48950b2796c5d60e5aafd481c34ef6395d078f28b69c3001372b89142a729a