Get Address Balance
You can retrieve the outputs for any given address using the Client.basicOutputIds(queryParameters) function. You can then use the retrieved outputs to calculate the balance.
The following code example will:
- Create a
Client
which will connect to the Shimmer Testnet. - Create a
SecretManager
from a mnemonic. - Get outputs for the generated address.
- Add the total amount of native tokens and outputs.
- Log the results from step 4 to console.
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 02_get_address_balance --release
//! In this example we will get the outputs of an address that have no additional unlock conditions and sum the amounts
//! and native tokens.
use iota_client::{
block::output::{NativeTokensBuilder, Output},
node_api::indexer::query_parameters::QueryParameter,
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();
let node_url = 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 =
MnemonicSecretManager::try_from_mnemonic(&std::env::var("NON_SECURE_USE_OF_DEVELOPMENT_MNEMONIC_1").unwrap())?;
let token_supply = client.get_token_supply().await?;
// Generate the first address
let addresses = client
.get_addresses(&SecretManager::Mnemonic(secret_manager))
.with_account_index(0)
.with_range(0..1)
.finish()
.await?;
// Get output ids of outputs that can be controlled by this address without further unlock constraints
let output_ids_response = client
.basic_output_ids(vec![
QueryParameter::Address(addresses[0].clone()),
QueryParameter::HasExpiration(false),
QueryParameter::HasTimelock(false),
QueryParameter::HasStorageDepositReturn(false),
])
.await?;
// Get the outputs by their id
let outputs_responses = client.get_outputs(output_ids_response.items).await?;
// Calculate the total amount and native tokens
let mut total_amount = 0;
let mut total_native_tokens = NativeTokensBuilder::new();
for output_response in outputs_responses {
let output = Output::try_from_dto(&output_response.output, token_supply)?;
if let Some(native_tokens) = output.native_tokens() {
total_native_tokens.add_native_tokens(native_tokens.clone())?;
}
total_amount += output.amount();
}
println!(
"Outputs controlled by {} have: {:?}i and native tokens: {:?}",
addresses[0],
total_amount,
total_native_tokens.finish_vec()?
);
Ok(())
}
Run the Example
Run the example by running the following command:
cargo run --example 02_get_address_balance --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/05_get_address_balance.js
// In this example we will get the outputs of an address that has no additional unlock
// conditions and sum the amounts and native tokens
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 the first address
const addresses = await client.generateAddresses(secretManager, {
accountIndex: 0,
range: {
start: 0,
end: 1,
},
});
// Get output ids of basic outputs that can be controlled by this address without further unlock constraints
const outputIdsResponse = await client.basicOutputIds([
{ address: addresses[0] },
{ hasExpiration: false },
{ hasTimelock: false },
{ hasStorageDepositReturn: false },
]);
// Get outputs by their IDs
const addressOutputs = await client.getOutputs(outputIdsResponse.items);
// Calculate the total amount and native tokens
let totalAmount = 0;
const totalNativeTokens: { [id: string]: number } = {};
for (const outputResponse of addressOutputs) {
const output = outputResponse['output'];
if ('nativeTokens' in output) {
output.nativeTokens?.forEach(
(token) =>
(totalNativeTokens[token.id] =
(totalNativeTokens[token.id] || 0) +
parseInt(token.amount)),
);
}
totalAmount += parseInt(output.amount);
}
console.log(
`Outputs controlled by ${addresses[0]} have: ${totalAmount} glow and native tokens: `,
totalNativeTokens,
);
} 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/05_get_address_balance.js
from iota_client import IotaClient
# Create an IotaClient instance
client = IotaClient({'nodes': ['https://api.testnet.shimmer.network']})
address = 'rms1qpllaj0pyveqfkwxmnngz2c488hfdtmfrj3wfkgxtk4gtyrax0jaxzt70zy'
# Get output ids of basic outputs that can be controlled by this address without further unlock constraints
output_ids_response = client.basic_output_ids([{"address": address},
{"hasExpiration": False},
{"hasTimelock": False},
{"hasStorageDepositReturn": False}, ])
print(f'{output_ids_response}')
# Get the outputs by their id
outputs = client.get_outputs(output_ids_response['items'])
print(f'{outputs}')
# Calculate the total amount and native tokens
total_amount = 0
native_tokens = []
for output_response in outputs:
output = output_response['output']
total_amount += int(output['amount'])
if 'nativeTokens' in output:
native_tokens.append(output['nativeTokens'])
print(
f'Outputs controlled by {address} have {total_amount} glow and native tokens: {native_tokens}')
You can run the example by running the following command from the binding/python/examples
folder:
python3 05_get_address_balance.py
import com.google.gson.JsonElement;
import org.iota.Client;
import org.iota.apis.NodeIndexerApi;
import org.iota.types.ClientConfig;
import org.iota.types.NativeToken;
import org.iota.types.Output;
import org.iota.types.OutputMetadata;
import org.iota.types.expections.ClientException;
import org.iota.types.expections.InitializeClientException;
import org.iota.types.ids.OutputId;
import org.iota.types.secret.GenerateAddressesOptions;
import org.iota.types.secret.MnemonicSecretManager;
import org.iota.types.secret.Range;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class GetAddressBalance {
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, 1)));
// Get the interesting output ids.
OutputId[] outputIds = client.getBasicOutputIds(new NodeIndexerApi.QueryParams()
.withParam("address", addresses[0])
.withParam("hasExpiration", false)
.withParam("hasTimelock", false)
.withParam("hasStorageDepositReturn", false)
).getItems();
// Get the outputs.
List<Map.Entry<Output, OutputMetadata>> outputs = client.getOutputs(outputIds);
// Calculate the total amount and native tokens.
int total = 0;
Map<String, Integer> nativeTokens = new HashMap();
for (Map.Entry<Output, OutputMetadata> entry : outputs) {
Output o = entry.getKey();
if (o.toJson().has("nativeTokens")) {
for(JsonElement elem: o.toJson().get("nativeTokens").getAsJsonArray()) {
NativeToken nativeToken = new NativeToken(elem.getAsJsonObject());
String tokenId = nativeToken.toJson().get("id").getAsString();
String amount = nativeToken.toJson().get("amount").getAsString().replace("0x", "");
if(nativeTokens.containsKey(tokenId))
nativeTokens.put(tokenId, nativeTokens.get(tokenId) + Integer.parseInt(amount, 16));
else
nativeTokens.put(tokenId, Integer.parseInt(amount, 16));
}
}
total += o.toJson().get("amount").getAsInt();
}
System.out.println("total balance: " + total);
System.out.println("native tokens: " + nativeTokens);
}
}
Expected Output
- Rust
- Nodejs
- Python
- Java
Outputs controlled by rms1qpllaj0pyveqfkwxmnngz2c488hfdtmfrj3wfkgxtk4gtyrax0jaxzt70zy
have: 2609275800i and nativetokens: [
NativeToken{
token_id: TokenId(0x085c6b799750bdf7e5a5c81144465a0676bc11dab74b997444ca369949341720e80100000000),
amount: 100
},
NativeToken{
token_id: TokenId(0x0822ceb3166ad125d310e6660f5fc292356f87f2f9566e982ea22154cec3847b3f0100000000),
amount: 100
},
NativeToken{
token_id: TokenId(0x08f708a29e9619e847916de76c2e167e87a704c235dcbd7cda018865be7f561b5a0100000000),
amount: 50
},
NativeToken{
token_id: TokenId(0x0808fb702d67fdb320b5959f152c0f962630515d904c71ed09447c341a6cc171de0100000000),
amount: 100
},
NativeToken{
token_id: TokenId(0x08f1802858831220b282ccc4c557676d61f79833869de378ce9a81f736976ce39f0100000000),
amount: 50
}
]
Outputs controlled by rms1qpllaj0pyveqfkwxmnngz2c488hfdtmfrj3wfkgxtk4gtyrax0jaxzt70zy have: 2609275800 glow and native tokens: {
'0x0808fb702d67fdb320b5959f152c0f962630515d904c71ed09447c341a6cc171de0100000000': 100,
'0x0822ceb3166ad125d310e6660f5fc292356f87f2f9566e982ea22154cec3847b3f0100000000': 100,
'0x085c6b799750bdf7e5a5c81144465a0676bc11dab74b997444ca369949341720e80100000000': 100,
'0x08f708a29e9619e847916de76c2e167e87a704c235dcbd7cda018865be7f561b5a0100000000': 50,
'0x08f1802858831220b282ccc4c557676d61f79833869de378ce9a81f736976ce39f0100000000': 50
}
Outputs controlled by rms1qpllaj0pyveqfkwxmnngz2c488hfdtmfrj3wfkgxtk4gtyrax0jaxzt70zy have
2609275800 glow and nativetokens: [
[
{
'id': '0x0808fb702d67fdb320b5959f152c0f962630515d904c71ed09447c341a6cc171de0100000000',
'amount': '0x64'
},
{
'id': '0x0822ceb3166ad125d310e6660f5fc292356f87f2f9566e982ea22154cec3847b3f0100000000',
'amount': '0x64'
},
{
'id': '0x085c6b799750bdf7e5a5c81144465a0676bc11dab74b997444ca369949341720e80100000000',
'amount': '0x64'
},
{
'id': '0x08f708a29e9619e847916de76c2e167e87a704c235dcbd7cda018865be7f561b5a0100000000',
'amount': '0x32'
}
],
[
{
'id': '0x08f1802858831220b282ccc4c557676d61f79833869de378ce9a81f736976ce39f0100000000',
'amount': '0x32'
}
]
]
total balance: 1900755293
native tokens: {0x0833b41872b4ef228c10a99456fb08088a52a71f3ff23330287f6c8978bc5dd6df0100000000=100, 0x089c130fa264a23492f5876e4c2673154689fa8e30945c7b60c59050b20336d2b70100000000=50, 0x083c39ef7bd9a2eb640df6a36319a7fd51d4ca190ffd5d14572c9ebb54bdc6ecab0200000000=69, 0x083118235071d4013edd2315210626ca85cf27e961a9670d81c30716dd0058a8220100000000=50, 0x08f708a29e9619e847916de76c2e167e87a704c235dcbd7cda018865be7f561b5a0200000000=32, 0x08f7763ffc30099b089045e06a4a24047787510cd01310b42fec9ca006267d4be80100000000=50}