Create a Wallet Account
The first thing you will need to do when you are getting started with the wallet.rs library is to create a wallet account.
Account Approaches
Wallet.rs supports a multi-account approach and a single-account approach.
Code Example
The following example will:
- Create an account manager.
- Use it to store the Stronghold mnemonic.
- Create a wallet with the alias "Alice".
- Rust
- Nodejs
- Python
- Java
Dotenv
This example uses dotenv, which is not safe for use in production environments.
// Copyright 2021 IOTA Stiftung
// SPDX-License-Identifier: Apache-2.0
//! cargo run --example create_wallet --release
// In this example we will create a new wallet
// Rename `.env.example` to `.env` first
use std::{env, path::PathBuf};
use dotenv::dotenv;
use iota_wallet::{
account_manager::AccountManager,
iota_client::constants::SHIMMER_COIN_TYPE,
secret::{stronghold::StrongholdSecretManager, SecretManager},
ClientOptions, Result,
};
#[tokio::main]
async fn main() -> Result<()> {
// This example uses dotenv, which is not safe for use in production
dotenv().ok();
// Setup Stronghold secret_manager
let mut secret_manager = StrongholdSecretManager::builder()
.password(&env::var("STRONGHOLD_PASSWORD").unwrap())
.build(PathBuf::from("wallet.stronghold"))?;
// Only required the first time, can also be generated with `manager.generate_mnemonic()?`
let mnemonic = env::var("NON_SECURE_USE_OF_DEVELOPMENT_MNEMONIC").unwrap();
// The mnemonic only needs to be stored the first time
secret_manager.store_mnemonic(mnemonic).await?;
// Create the account manager with the secret_manager and client options
let client_options = ClientOptions::new().with_node(&env::var("NODE_URL").unwrap())?;
let manager = AccountManager::builder()
.with_secret_manager(SecretManager::Stronghold(secret_manager))
.with_client_options(client_options)
.with_coin_type(SHIMMER_COIN_TYPE)
.finish()
.await?;
// Create a new account
let _account = manager
.create_account()
.with_alias("Alice".to_string())
.finish()
.await?;
println!("Generated a new account");
Ok(())
}
Run the example by running the following command:
cargo run --example create_wallet --release
/**
* This example creates a new database and account
*/
const path = require('path')
require('dotenv').config({ path: path.resolve(__dirname, '.env') });
const { AccountManager, CoinType } = require('@iota/wallet');
async function run() {
try {
const manager = await createAccountManager();
const account = await manager.createAccount({
alias: 'Alice',
});
console.log('Account created:', account);
const secondAccount = await manager.createAccount({
alias: 'Bob',
});
console.log('Account created:', secondAccount);
} catch (error) {
console.log('Error: ', error);
}
process.exit(0);
}
async function createAccountManager() {
const accountManagerOptions = {
storagePath: './alice-database',
clientOptions: {
nodes: [process.env.NODE_URL],
localPow: true,
},
coinType: CoinType.Shimmer,
secretManager: {
Stronghold: {
snapshotPath: `./wallet.stronghold`,
password: `${process.env.SH_PASSWORD}`,
},
},
};
const manager = new AccountManager(accountManagerOptions);
await manager.storeMnemonic(process.env.MNEMONIC);
return manager;
}
run();
You can run the example by running the following command from the wallet/bindings/nodejs/examples/
folder:
node 1-create-account.js
from iota_wallet import IotaWallet, StrongholdSecretManager
# This example creates a new database and account
client_options = {
'nodes': ['https://api.testnet.shimmer.network'],
}
# Shimmer coin type
coin_type = 4219
secret_manager = StrongholdSecretManager("wallet.stronghold", "some_hopefully_secure_password")
wallet = IotaWallet('./alice-database', client_options, coin_type, secret_manager)
# Store the mnemonic in the Stronghold snapshot, this only needs to be done once
account = wallet.store_mnemonic("flame fever pig forward exact dash body idea link scrub tennis minute " +
"surge unaware prosper over waste kitten ceiling human knife arch situate civil")
account = wallet.create_account('Alice')
print(account)
You can run the example by running the following command from the binding/python/examples
folder:
python3 0-create-account.py
// Copyright 2022 IOTA Stiftung
// SPDX-License-Identifier: Apache-2.0
import org.iota.Wallet;
import org.iota.types.AccountHandle;
import org.iota.types.ClientConfig;
import org.iota.types.CoinType;
import org.iota.types.WalletConfig;
import org.iota.types.exceptions.InitializeWalletException;
import org.iota.types.exceptions.WalletException;
import org.iota.types.secret.StrongholdSecretManager;
public class CreateAccount {
public static void main(String[] args) throws WalletException, InitializeWalletException {
// This example assumes that a wallet has already been created using the ´SetupWallet.java´ example.
// If you haven't run the ´SetupWallet.java´ example yet, you must run it first to be able to load the wallet as shown below:
Wallet wallet = new Wallet(new WalletConfig()
.withClientOptions(new ClientConfig().withNodes(Env.NODE))
.withSecretManager(new StrongholdSecretManager(Env.STRONGHOLD_PASSWORD, null, Env.STRONGHOLD_VAULT_PATH))
.withCoinType(CoinType.Shimmer)
.withStoragePath(Env.STORAGE_PATH)
);
wallet.storeMnemonic(Env.MNEMONIC);
// Create an account.
AccountHandle a = wallet.createAccount(Env.ACCOUNT_NAME);
// Print the account.
System.out.println(a);
// In case you are done and don't need the wallet instance anymore you can destroy the instance to clean up memory.
// For this, check out the ´DestroyWallet.java´ example.
}
}
Expected Output
- Rust
- Nodejs
- Python
- Java
Generated a new account
Account created: Account {
meta: {
index: 0,
coinType: 4219,
alias: 'Alice',
publicAddresses: [ [Object] ],
internalAddresses: [],
addressesWithUnspentOutputs: [],
outputs: {},
lockedOutputs: [],
unspentOutputs: {},
transactions: {},
pendingTransactions: [],
incomingTransactions: {}
},
messageHandler: MessageHandler { messageHandler: [External: 7f29dde5bf80] }
}
Account created: Account {
meta: {
index: 1,
coinType: 4219,
alias: 'Bob',
publicAddresses: [ [Object] ],
internalAddresses: [],
addressesWithUnspentOutputs: [],
outputs: {},
lockedOutputs: [],
unspentOutputs: {},
transactions: {},
pendingTransactions: [],
incomingTransactions: {}
},
messageHandler: MessageHandler { messageHandler: [External: 7f29dde5bf80] }
}
{
'index': 0,
'coinType': 4219,
'alias': 'Alice',
'publicAddresses': [
{
'address': 'rms1qzpf0tzpf8yqej5zyhjl9k3km7y6j0xjnxxh7m2g3jtj2z5grej67sl6l46',
'keyIndex': 0,
'internal': False,
'used': False
}
],
'internalAddresses': [],
'addressesWithUnspentOutputs': [],
'outputs': {},
'lockedOutputs': [],
'unspentOutputs': {},
'transactions': {},
'pendingTransactions': [],
'incomingTransactions': {}
}
{
"index": 0,
"coinType": 4219,
"alias": "Hans",
"publicAddresses": [
{
"address": "rms1qpx0mcrqq7t6up73n4na0zgsuuy4p0767ut0qq67ngctj7pg4tm2ynsuynp",
"keyIndex": 0,
"isInternal": false,
"used": false
}
],
"internalAddresses": [],
"addressesWithUnspentOutputs": [],
"outputs": {},
"lockedOutputs": [],
"unspentOutputs": {},
"transactions": {},
"pendingTransactions": [],
"incomingTransactions": {}
}