Generate Addresses
You can generate an IOTA address using the Client.get_addresses()
function that will return a list of tuples with the
generated addresses.
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.
- Generate an internal address.
- Generate an offline address.
Iota.js
You can also find this guide in the native iota.js library
Code Example
- Rust
- Nodejs
- Python
- Java
Dotenv
This example uses dotenv, which is not safe to use in production environments.
// Copyright 2021 IOTA Stiftung
// SPDX-License-Identifier: Apache-2.0
//! cargo run --example generate_addresses --release -- [NODE URL]
use iota_client::{
api::GetAddressesBuilder,
secret::{mnemonic::MnemonicSecretManager, SecretManager},
Client, Result,
};
#[tokio::main]
async fn main() -> Result<()> {
// This example uses dotenv, which is not safe for use in production
dotenv::dotenv().ok();
// Take the node URL from command line argument or use one from env as default.
let node_url = std::env::args()
.nth(1)
.unwrap_or_else(|| std::env::var("NODE_URL").unwrap());
// Create a client instance
let client = Client::builder()
.with_node(&node_url)? // Insert your node URL here
.finish()?;
let secret_manager = SecretManager::Mnemonic(MnemonicSecretManager::try_from_mnemonic(
&std::env::var("NON_SECURE_USE_OF_DEVELOPMENT_MNEMONIC_1").unwrap(),
)?);
// Generate addresses with default account index and range
let addresses = client.get_addresses(&secret_manager).finish().await?;
println!("List of generated public addresses:\n{addresses:#?}\n");
// Generate addresses with custom account index and range
let addresses = client
.get_addresses(&secret_manager)
.with_account_index(0)
.with_range(0..4)
.finish()
.await?;
println!("List of generated public addresses:\n{addresses:#?}\n");
// Generating addresses with `client.get_addresses(&secret_manager)`, will by default get the bech32_hrp (Bech32
// human readable part) from the node info, generating it "offline" requires setting it with
// `with_bech32_hrp(bech32_hrp)`
let addresses = GetAddressesBuilder::new(&secret_manager)
.with_bech32_hrp(client.get_bech32_hrp().await?)
.with_account_index(0)
.with_range(0..4)
.finish()
.await?;
println!("List of offline generated public addresses:\n{addresses:#?}\n");
Ok(())
}
Run the Example
Run the example by running the following command:
cargo run --example generate_addresses --release -- https://api.testnet.shimmer.network
- You can replace
https://api.testnet.shimmer.network
with any node url.
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,
CoinType,
initLogger,
SHIMMER_TESTNET_BECH32_HRP,
} from '@iota/client';
require('dotenv').config({ path: '../.env' });
// Run with command:
// node ./dist/02_generate_addresses.js
// In this example we will create addresses from a mnemonic defined in .env
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],
});
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,
};
// Generate public address with custom account index and range.
const address = await client.generateAddresses(secretManager, {
accountIndex: 0,
range: {
start: 0,
end: 1,
},
});
console.log('First public address:', address, '\n');
// Generate an internal address with custom account index and range.
const internalAddress = await client.generateAddresses(secretManager, {
accountIndex: 0,
range: {
start: 0,
end: 1,
},
internal: true,
});
console.log('First internal address:', internalAddress, '\n');
// Generate addresses with providing all inputs, that way it can also be done offline without a node.
const offlineGeneratedAddresses = await client.generateAddresses(
secretManager,
{
coinType: CoinType.Shimmer,
accountIndex: 0,
range: {
start: 0,
end: 2,
},
internal: false,
// Generating addresses with client.generateAddresses(secretManager, {}), will by default get the bech32_hrp (Bech32
// human readable part) from the node info, generating it "offline" requires setting it in the generateAddressesOptions
bech32Hrp: SHIMMER_TESTNET_BECH32_HRP,
},
);
console.log(
'List of offline generated public addresses:',
offlineGeneratedAddresses,
);
} 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/02_generate_addresses.js
from iota_client import IotaClient, MnemonicSecretManager
# Create an IotaClient instance
client = IotaClient({'nodes': ['https://api.testnet.shimmer.network']})
# In this example we will create addresses from a mnemonic
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")
# Generate public address with custom account index and range.
address = client.generate_addresses(secret_manager, {
"accountIndex": 0,
"range": {
"start": 0,
"end": 1,
},
})
print(f'Address: {address[0]}')
You can run the example by running the following command from the binding/python/examples
folder:
python3 02_generate_addresses.py
import org.iota.Client;
import org.iota.types.ClientConfig;
import org.iota.types.expections.ClientException;
import org.iota.types.expections.InitializeClientException;
import org.iota.types.secret.GenerateAddressesOptions;
import org.iota.types.secret.MnemonicSecretManager;
import org.iota.types.secret.Range;
public class GenerateAddresses {
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"}));
// Generate the addresses from the given mnemonic.
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[] addresses = client.generateAddresses(secretManager, new GenerateAddressesOptions().withRange(new Range(0, 5)));
// Print the addresses.
for (String address : addresses) {
System.out.println(address);
}
}
}
Expected Output
- Rust
- Nodejs
- Python
- Java
First public address: rms1qpllaj0pyveqfkwxmnngz2c488hfdtmfrj3wfkgxtk4gtyrax0jaxzt70zy
First public address: [ 'rms1qpllaj0pyveqfkwxmnngz2c488hfdtmfrj3wfkgxtk4gtyrax0jaxzt70zy' ]
First internal address: [ 'rms1qp6w3v03qwtwkh52avtdvejpdqp8yfpk4z94m5dg3evuzu9hynyucvmxd59' ]
List of offline generated public addresses: [
'rms1qpllaj0pyveqfkwxmnngz2c488hfdtmfrj3wfkgxtk4gtyrax0jaxzt70zy',
'rms1qzzk86qv30l4e85ljtccxa0ruy8y7u8zn2dle3g8dv2tl2m4cu227a7n2wj'
]
Address: rms1qzpf0tzpf8yqej5zyhjl9k3km7y6j0xjnxxh7m2g3jtj2z5grej67sl6l46
rms1qpllaj0pyveqfkwxmnngz2c488hfdtmfrj3wfkgxtk4gtyrax0jaxzt70zy
rms1qzzk86qv30l4e85ljtccxa0ruy8y7u8zn2dle3g8dv2tl2m4cu227a7n2wj
rms1qqjrtmslm36l3lyd8086w9qdxd9mudu2z2qyywlltpycn2ftxsdmu9ulj47
rms1qzz75j5h7vd5melxwersz49jja36m2vvnawedu0l6rlhg70ylzqp52lx8zf
rms1qzvs2rvq5ef79vhuel354mnvzfz049gyyf808zmjculuatt56u92vc4v4p3