Get Outputs
You can use the indexer to query for specific outputs. You can query for any output type, just change the function to the output type you need
Client in Wallet
If you are using a wallet you can always get the client by calling the client()
/getClient()
/get_client()
method
The following code example will:
- Create a
Client
which will connect to the Shimmer Testnet. - Use the created client to query for outputs with the specified parameters.
- Print the first output found.
Code Example
- Rust
- Nodejs
- Python
sdk/examples/how_tos/client/get_outputs.rs
// Copyright 2022 IOTA Stiftung
// SPDX-License-Identifier: Apache-2.0
//! Gets all basic output ids associated with an address by querying the
//! `api/indexer/v1/outputs/basic` node endpoint.
//!
//! Make sure that the node has the indexer plugin enabled.
//! Make sure to provide a somewhat recently used address to make this example run successfully!
//!
//! Rename `.env.example` to `.env` first, then run the command:
//! ```sh
//! cargo run --release --all-features --example get_outputs [ADDRESS] [NODE_URL]
//! ```
use iota_sdk::{
client::{node_api::indexer::query_parameters::QueryParameter, Client, Result},
types::block::address::Bech32Address,
};
#[tokio::main]
async fn main() -> Result<()> {
// This example uses secrets in environment variables for simplicity which should not be done in production.
dotenvy::dotenv().ok();
// Take the node URL from command line argument or use one from env as default.
let node_url = std::env::args()
.nth(2)
.unwrap_or_else(|| std::env::var("NODE_URL").expect("NODE_URL not set"));
// Create a node client.
let client = Client::builder().with_node(&node_url)?.finish().await?;
// Take the address from command line argument or use a default one.
let address = Bech32Address::try_from_str(
std::env::args()
.nth(1)
.as_deref()
.unwrap_or("rms1qpllaj0pyveqfkwxmnngz2c488hfdtmfrj3wfkgxtk4gtyrax0jaxzt70zy"),
)?;
// Get output IDs of basic outputs that can be controlled by this address without further unlock constraints.
let output_ids_response = client
.basic_output_ids([
QueryParameter::Address(address),
QueryParameter::HasExpiration(false),
QueryParameter::HasTimelock(false),
QueryParameter::HasStorageDepositReturn(false),
])
.await?;
println!("First output of query:");
println!("ID: {:#?}", output_ids_response.first().expect("No outputs found"));
// Get the outputs by their IDs.
let outputs_response = client.get_outputs(&output_ids_response.items).await?;
println!("{:#?}", outputs_response.first().unwrap());
Ok(())
}
bindings/nodejs/examples/how_tos/client/get-outputs.ts
// Copyright 2021-2023 IOTA Stiftung
// SPDX-License-Identifier: Apache-2.0
import { Client, initLogger } from '@iota/sdk';
require('dotenv').config({ path: '.env' });
// Run with command:
// yarn run-example ./how_tos/client/get-outputs.ts
// In this example we will get the outputs of a known address
async function run() {
initLogger();
for (const envVar of ['NODE_URL']) {
if (!(envVar in process.env)) {
throw new Error(`.env ${envVar} is undefined, see .env.example`);
}
}
const client = new Client({
// Insert your node URL in the .env.
nodes: [process.env.NODE_URL as string],
});
try {
// Get output ids of basic outputs that can be controlled by this address without further unlock constraints
const outputIdsResponse = await client.basicOutputIds([
{
address:
'rms1qpllaj0pyveqfkwxmnngz2c488hfdtmfrj3wfkgxtk4gtyrax0jaxzt70zy',
},
{ hasExpiration: false },
{ hasTimelock: false },
{ hasStorageDepositReturn: false },
]);
console.log('First output of query:');
console.log('ID: ', outputIdsResponse.items[0]);
const outputs = await client.getOutputs(outputIdsResponse.items);
console.log(outputs[0]);
} catch (error) {
console.error('Error: ', error);
}
}
run().then(() => process.exit());
bindings/python/examples/how_tos/client/get_outputs.py
import json
import os
from dotenv import load_dotenv
from iota_sdk import Client, NodeIndexerAPI
load_dotenv()
node_url = os.environ.get('NODE_URL', 'https://api.testnet.shimmer.network')
# Create a Client instance
client = Client(nodes=[node_url])
query_parameters = NodeIndexerAPI.QueryParameters(
address='rms1qpllaj0pyveqfkwxmnngz2c488hfdtmfrj3wfkgxtk4gtyrax0jaxzt70zy',
has_expiration=False,
has_timelock=False,
has_storage_deposit_return=False
)
# Get output ids of basic outputs that can be controlled by this address
# without further unlock constraints.
output_ids_response = client.basic_output_ids(query_parameters)
print('First output of query:')
print(f'ID: {output_ids_response.items[0]}')
# Get the outputs by their id
outputs_with_metadata = client.get_outputs(output_ids_response.items)
print(f'{json.dumps(outputs_with_metadata[0].as_dict(), indent=4)}')
Expected Output
- Rust
- Nodejs
- Python
First output of query:
ID: OutputId(0x57a796e9b8c5fc96c330fa45c2658f37d04f631eedc85d8e1e23434ca599eb8c0000)
OutputWithMetadata {
output: BasicOutput {
amount: 12310426,
native_tokens: NativeTokens(
[],
),
unlock_conditions: UnlockConditions(
[
AddressUnlockCondition(
Ed25519Address(0x7ffec9e1233204d9c6dce6812b1539ee96af691ca2e4d9065daa85907d33e5d3),
),
],
),
features: Features(
[],
),
},
metadata: OutputMetadata {
block_id: BlockId(0x2a006e26f54f1221b4fa5738bf2b3501a0a2e7085ff8dcc03d0700f75bbcc43c),
output_id: OutputId(0x57a796e9b8c5fc96c330fa45c2658f37d04f631eedc85d8e1e23434ca599eb8c0000),
is_spent: false,
milestone_index_spent: None,
milestone_timestamp_spent: None,
transaction_id_spent: None,
milestone_index_booked: 5300818,
milestone_timestamp_booked: 1684939216,
ledger_index: 5794425,
},
}
First output of query:
ID: 0x57a796e9b8c5fc96c330fa45c2658f37d04f631eedc85d8e1e23434ca599eb8c0000
OutputResponse {
metadata: {
blockId: '0x2a006e26f54f1221b4fa5738bf2b3501a0a2e7085ff8dcc03d0700f75bbcc43c',
transactionId: '0x57a796e9b8c5fc96c330fa45c2658f37d04f631eedc85d8e1e23434ca599eb8c',
outputIndex: 0,
isSpent: false,
milestoneIndexBooked: 5300818,
milestoneTimestampBooked: 1684939216,
ledgerIndex: 5794505
},
output: BasicOutput {
type: 3,
amount: '12310426',
unlockConditions: [ [AddressUnlockCondition] ]
}
}
First output of query:
ID: 0x57a796e9b8c5fc96c330fa45c2658f37d04f631eedc85d8e1e23434ca599eb8c0000
{
"metadata": {
"blockId": "0x2a006e26f54f1221b4fa5738bf2b3501a0a2e7085ff8dcc03d0700f75bbcc43c",
"transactionId": "0x57a796e9b8c5fc96c330fa45c2658f37d04f631eedc85d8e1e23434ca599eb8c",
"outputIndex": 0,
"isSpent": false,
"milestoneIndexBooked": 5300818,
"milestoneTimestampBooked": 1684939216,
"ledgerIndex": 5794538
},
"output": {
"type": 3,
"amount": "12310426",
"unlockConditions": [
{
"type": 0,
"address": {
"type": 0,
"pubKeyHash": "0x7ffec9e1233204d9c6dce6812b1539ee96af691ca2e4d9065daa85907d33e5d3"
}
}
]
}
}