Build a Basic Output
You can build a simple output using the Client.buildBasicOutput(options)
function.
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 a simple output.
Code Example
- Rust
- Nodejs
- Python
- Java
Dotenv
This example uses dotenv, which is not safe to use in production environments.
// Copyright 2022 IOTA Stiftung
// SPDX-License-Identifier: Apache-2.0
//! cargo run --example basic --release
use iota_client::{
block::output::{
feature::MetadataFeature,
unlock_condition::{
AddressUnlockCondition, ExpirationUnlockCondition, StorageDepositReturnUnlockCondition,
TimelockUnlockCondition, UnlockCondition,
},
BasicOutputBuilder, Feature,
},
secret::{mnemonic::MnemonicSecretManager, SecretManager},
utils::request_funds_from_faucet,
Client, Result,
};
/// In this example we will send basic outputs with different feature blocks
#[tokio::main]
async fn main() -> Result<()> {
// This example uses dotenv, which is not safe for use in production!
// Configure your own mnemonic in the ".env" file. Since the output amount cannot be zero, the seed must contain
// non-zero balance.
dotenv::dotenv().ok();
let node_url = std::env::var("NODE_URL").unwrap();
let faucet_url = std::env::var("FAUCET_URL").unwrap();
// Create a client instance.
let client = Client::builder().with_node(&node_url)?.finish()?;
let secret_manager = SecretManager::Mnemonic(MnemonicSecretManager::try_from_mnemonic(
&std::env::var("NON_SECURE_USE_OF_DEVELOPMENT_MNEMONIC_1").unwrap(),
)?);
let token_supply = client.get_token_supply().await?;
let address = client.get_addresses(&secret_manager).with_range(0..1).get_raw().await?[0];
println!(
"{}",
request_funds_from_faucet(&faucet_url, &address.to_bech32(client.get_bech32_hrp().await?)).await?
);
let basic_output_builder = BasicOutputBuilder::new_with_amount(1_000_000)?
.add_unlock_condition(UnlockCondition::Address(AddressUnlockCondition::new(address)));
let outputs = vec![
// most simple output
basic_output_builder.clone().finish_output(token_supply)?,
// with metadata feature block
basic_output_builder
.clone()
.add_feature(Feature::Metadata(MetadataFeature::new(vec![13, 37])?))
.finish_output(token_supply)?,
// with storage deposit return
basic_output_builder
.clone()
.with_amount(234_100)?
.add_unlock_condition(UnlockCondition::StorageDepositReturn(
StorageDepositReturnUnlockCondition::new(address, 234_000, token_supply)?,
))
.finish_output(token_supply)?,
// with expiration
basic_output_builder
.clone()
.add_unlock_condition(UnlockCondition::Expiration(ExpirationUnlockCondition::new(address, 1)?))
.finish_output(token_supply)?,
// with timelock
basic_output_builder
.clone()
.add_unlock_condition(UnlockCondition::Timelock(TimelockUnlockCondition::new(1)?))
.finish_output(token_supply)?,
];
let block = client
.block()
.with_secret_manager(&secret_manager)
.with_outputs(outputs)?
.finish()
.await?;
println!("Transaction sent: {node_url}/api/core/v2/blocks/{}", block.id());
println!("Block metadata: {node_url}/api/core/v2/blocks/{}/metadata", block.id());
let _ = client.retry_until_included(&block.id(), None, None).await?;
Ok(())
}
Run the Example
Run the example by running the following command:
cargo run --example basic --release
Dotenv
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/11_build_output.js
// Build a basic output
async function run() {
initLogger();
if (!process.env.NODE_URL) {
throw new Error('.env NODE_URL is undefined, see .env.example');
}
const client = new Client({
nodes: [process.env.NODE_URL],
});
try {
if (!process.env.NON_SECURE_USE_OF_DEVELOPMENT_MNEMONIC_1) {
throw new Error('.env mnemonic is undefined, see .env.example');
}
const secretManager = {
mnemonic: process.env.NON_SECURE_USE_OF_DEVELOPMENT_MNEMONIC_1,
};
const addresses = await client.generateAddresses(secretManager, {
range: {
start: 0,
end: 1,
},
});
const hexAddress = await client.bech32ToHex(addresses[0]);
// most simple basic output
const basicOutput = await client.buildBasicOutput({
amount: '1000000',
unlockConditions: [
{
type: 0,
address: {
type: 0,
pubKeyHash: hexAddress,
},
},
],
});
console.log(basicOutput);
} catch (error) {
console.error('Error: ', error);
}
}
run();
You can run the example by running the following command from the bindings/node/examples/
folder:
node dist/11_build_output.js
from iota_client import IotaClient, MnemonicSecretManager
# Create an IotaClient instance
client = IotaClient({'nodes': ['https://api.testnet.shimmer.network']})
basic_output = client.build_basic_output(
unlock_conditions=[
{
"type": 0,
"address": {
"type": 0,
"pubKeyHash": client.bech32_to_hex("rms1qzpf0tzpf8yqej5zyhjl9k3km7y6j0xjnxxh7m2g3jtj2z5grej67sl6l46"),
},
},
],
amount='1000000',
)
print(f'{basic_output}')
You can run the example by running the following command from the binding/python/examples
folder:
python3 11_build_output.py
How To Build A Basic Output
import org.iota.Client;
import org.iota.types.ClientConfig;
import org.iota.types.expections.ClientException;
import org.iota.types.Output;
import org.iota.types.UnlockCondition;
import org.iota.types.expections.InitializeClientException;
import org.iota.types.output_builder.BasicOutputBuilderParams;
import org.iota.types.secret.GenerateAddressesOptions;
import org.iota.types.secret.MnemonicSecretManager;
import org.iota.types.secret.Range;
public class BuildBasicOutput {
public static void main(String[] args) throws ClientException, InitializeClientException {
// Build the client.
Client client = new Client(new ClientConfig().withNodes(new String[]{"https://api.testnet.shimmer.network"}));
// Configure a simple Basic output.
MnemonicSecretManager secretManager = new MnemonicSecretManager("endorse answer radar about source reunion marriage tag sausage weekend frost daring base attack because joke dream slender leisure group reason prepare broken river");
String hexAddress = client.bech32ToHex(client.generateAddresses(secretManager, new GenerateAddressesOptions().withRange(new Range(0, 1)))[0]);
String amount = "1000000";
UnlockCondition[] unlockConditions = new UnlockCondition[]{new UnlockCondition("{ type: 0, address: { type: 0, pubKeyHash: \"" + hexAddress + "\"} }")};
BasicOutputBuilderParams params = new BasicOutputBuilderParams().withAmount(amount).withUnlockConditions(unlockConditions);
// Build the output.
Output output = client.buildBasicOutput(params);
// Print the output.
System.out.println(output.toString());
}
}
Expected Output
- Rust
- Nodejs
- Python
- Java
Transaction sent: https://api.testnet.shimmer.network/api/core/v2/blocks/0x7e85b3a62beeedafadbb3dc89a6f5813c34417dfe44fc7a679f3b42b0df3210e
Block metadata: https://api.testnet.shimmer.network/api/core/v2/blocks/0x7e85b3a62beeedafadbb3dc89a6f5813c34417dfe44fc7a679f3b42b0df3210e/metadata
{
type: 3,
amount: '1000000',
unlockConditions: [ { type: 0, address: [Object] } ]
}
{
'type': 3,
'amount': '1000000',
'unlockConditions': [
{
'type': 0,
'address': {
'type': 0,
'pubKeyHash': '0x8297ac4149c80cca8225e5f2da36df89a93cd2998d7f6d488c97250a881e65af'
}
}
]
}
{
"type": 3,
"amount": "1000000",
"unlockConditions": [
{
"type": 0,
"address": {
"type": 0,
"pubKeyHash": "0x7ffec9e1233204d9c6dce6812b1539ee96af691ca2e4d9065daa85907d33e5d3"
}
}
]
}