Post a Data Block
You can post a data block by adding hex encoded data as options when you create a block.
The following code example will:
- Create a
Client
which will connect to the Shimmer Testnet. - Create the
options
with the hex encoded data. - Create a
SecretManager
from a mnemonic. - Create and post the block with the data from step 2.
- Generate a public address.
You can also find this guide in the native iota.js library
Post a Block
Code Example
- Rust
- Nodejs
- Python
- Java
This example uses dotenv, which is not safe to use in production environments.
// Copyright 2022 IOTA Stiftung
// SPDX-License-Identifier: Apache-2.0
//! Calls `POST /api/core/v2/blocks`.
//! Submits a block as a JSON payload.
//! Run: `cargo run --example node_api_core_post_block --release -- [NODE URL]`.
use iota_client::{Client, Result};
#[tokio::main]
async fn main() -> Result<()> {
// 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(|| {
// This example uses dotenv, which is not safe for use in production.
dotenv::dotenv().ok();
std::env::var("NODE_URL").unwrap()
});
// Create a client with that node.
let client = Client::builder().with_node(&node_url)?.finish()?;
// Create the block.
let block = client.block().finish().await?;
// Post the block.
let block_id = client.post_block(&block).await?;
println!("Posted: {block_id:?}");
Ok(())
}
Run the Example
Run the example by running the following command:
cargo run --example node_api_core_post_block --release -- https://api.testnet.shimmer.network
- You can replace
https://api.testnet.shimmer.network
with any node url.
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, hexToUtf8, initLogger, utf8ToHex } from '@iota/client';
require('dotenv').config({ path: '../.env' });
// Run with command:
// node ./dist/08_data_block.js
// In this example we will send a block with a tagged data payload
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],
});
const options = {
tag: utf8ToHex('Hello'),
data: utf8ToHex('Tangle'),
};
try {
const mnemonic = await client.generateMnemonic();
const secretManager = { mnemonic: mnemonic };
// Create block with tagged payload
const blockIdAndBlock = await client.buildAndPostBlock(
secretManager,
options,
);
console.log('Block:', blockIdAndBlock, '\n');
console.log(
`Block sent: ${process.env.EXPLORER_URL}/block/${blockIdAndBlock[0]}\n`,
);
const fetchedBlock = await client.getBlock(blockIdAndBlock[0]);
console.log('Block data: ', fetchedBlock);
const payload = fetchedBlock.payload;
if (payload && 'data' in payload && payload.data) {
console.log('Decoded data:', hexToUtf8(payload.data));
}
} 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/08_data_block.js
from iota_client import IotaClient
# Create an IotaClient instance
client = IotaClient({'nodes': ['https://api.testnet.shimmer.network']})
options = {
# `hello` hex encoded
"tag": '0x68656c6c6f',
"data": '0x68656c6c6f',
}
# Create and post a block with a tagged data payload
block = client.build_and_post_block(None, options)
print(f'{block}')
You can run the example by running the following command from the binding/python/examples
folder:
python3 08_data_block.py
import org.iota.Client;
import org.iota.types.Block;
import org.iota.types.ClientConfig;
import org.iota.types.expections.ClientException;
import org.iota.types.expections.InitializeClientException;
import org.iota.types.ids.BlockId;
public class PostBlock {
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"}));
// Set up a block for this example.
Block b = ExampleUtils.setUpBlock(client);
// Post the block.
BlockId id = client.postBlock(b);
// Print the id of the created block.
System.out.println(id);
}
}
Expected Output
- Rust
- Nodejs
- Python
- Java
Posted: BlockId(0x2f1de84a2977afeb413d44d8069c67e2df3f8da9ee6ba9dd62190e5256469169)
Block: [
'0x0f8c244774ced9003ec0f33f9677fbee849bfebf895f97d4378c881a4d9a9d48',
{
protocolVersion: 2,
parents: [
'0x5d06623466c838d442eb662774beab3104f389bcf72020936bbd8f7f3bf78a7e',
'0x75ceb6fe9cf7e0ac5a244f6cf6dc9ebd606814006b332740c88db04793ef79f3',
'0x7d46b355780a41c66b483d775842fa7488f87bd7f9d4d438ee85e9ded914dffb',
'0x8f68b3a47424ebeb77c4108096c38b8fbd7201f2e189dcf0a17929109195ec09'
],
payload: { type: 5, tag: '0x48656c6c6f', data: '0x54616e676c65' },
nonce: '10760600709663905547'
}
]
Block sent: https://explorer.shimmer.network/testnet/block/0x0f8c244774ced9003ec0f33f9677fbee849bfebf895f97d4378c881a4d9a9d48
Block data: {
protocolVersion: 2,
parents: [
'0x5d06623466c838d442eb662774beab3104f389bcf72020936bbd8f7f3bf78a7e',
'0x75ceb6fe9cf7e0ac5a244f6cf6dc9ebd606814006b332740c88db04793ef79f3',
'0x7d46b355780a41c66b483d775842fa7488f87bd7f9d4d438ee85e9ded914dffb',
'0x8f68b3a47424ebeb77c4108096c38b8fbd7201f2e189dcf0a17929109195ec09'
],
payload: { type: 5, tag: '0x48656c6c6f', data: '0x54616e676c65' },
nonce: '10760600709663905547'
}
Decoded data: Tangle
[
'0x97379a9baae8541834d5fdd4757b9ed145f3fae6af729d37f2d5cc026c3ec69f',
{
'protocolVersion': 2,
'parents': [
'0x151e3afa885362540bbe0696e7eacd4beeb009cb545fa4ab7124a9b0fad9c147',
'0x594b367a064ca9342fb255b9495f42e9a30d8426dbf7f2a6883aa0cb8ac08100',
'0x7d4533d18880170c6082a64f71466edbc1cb0c15f526fac75d436b4fbe05a2a8',
'0xc675b08d064bd20f7e2a061646ed9dccf7c0c8edd6f364541cbcbd5564e35a30'
],
'payload': {
'type': 5,
'tag': '0x68656c6c6f',
'data': '0x68656c6c6f'
},
'nonce': '12297829382473068203'
}
]
0x40223bd63a8fce5065920b68af00d34813de3c8593416b3e90f27fad5cd77520
Post a Raw Block
Code Example
- Rust
- Nodejs
- Python
- Java
This example uses dotenv, which is not safe to use in production environments.
// Copyright 2022 IOTA Stiftung
// SPDX-License-Identifier: Apache-2.0
//! Calls `POST /api/core/v2/blocks`.
//! Submits a block as raw bytes.
//! Run: `cargo run --example node_api_core_post_block_raw --release -- [NODE URL]`.
use iota_client::{Client, Result};
#[tokio::main]
async fn main() -> Result<()> {
// 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(|| {
// This example uses dotenv, which is not safe for use in production.
dotenv::dotenv().ok();
std::env::var("NODE_URL").unwrap()
});
// Create a client with that node.
let client = Client::builder().with_node(&node_url)?.finish()?;
// Create the block.
let block = client.block().finish().await?;
// Post the block as raw bytes.
let block_id = client.post_block_raw(&block).await?;
println!("Posted: {block_id:?}");
Ok(())
}
Run the Example
Run the example by running the following command:
cargo run --example node_api_core_post_block_raw --release -- https://api.testnet.shimmer.network
- You can replace
https://api.testnet.shimmer.network
with any node url.
This how to guide is not available in your language of choice at the moment. Please feel free to browse more examples which may suit your requirements.
from iota_client import IotaClient, MnemonicSecretManager
# Create an IotaClient instance
client = IotaClient({'nodes': ['https://api.testnet.shimmer.network']})
# Create and post a block without payload
block_id = client.build_and_post_block()[0]
blockBytes = client.get_block_raw(block_id)
# Post raw block
result = client.post_block_raw(blockBytes)
# Print block raw
print(f'{result}')
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.ids.BlockId;
public class PostBlockRaw {
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"}));
// Set up a block for this example.
byte[] blockBytes = ExampleUtils.setUpBlockRaw(client);
// Post the block.
BlockId id = client.postBlockRaw(blockBytes);
// Print the id of the created block.
System.out.println(id);
}
}
Expected Output
- Rust
- Nodejs
- Python
- Java
Posted: BlockId(0x9982248af2d1b41f5f9f5b439d113ebe9611b6ace17ae487f2b3104b00b9950e)
This how to guide is not available in your language of choice at the moment. Please feel free to browse more examples which may suit your requirements.
0x1004a5dee96c69a6951d71ce6c86dea378220a82a0202a20ec9163547e6fb4e2
0x601aab8d3b391923f44528e54caff74f1e869ba8c587ddf99d277dd140289f89