Create a Block
The simplest block you can create is an empty block. You will only need connect your client to a node and then call the
Client.block(&self)
function.
The following code example will:
- Create a
Client
which will connect to the Shimmer Testnet. - Build and post an empty block.
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
//! This example sends a block with no payload.
//! Run: `cargo run --example block_no_payload --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 and send the block.
let block = client.block().finish().await?;
println!("{block:#?}");
println!(
"Block with no payload sent: {}/block/{}",
std::env::var("EXPLORER_URL").unwrap(),
block.id()
);
Ok(())
}
Run the Example
Run the example by running the following command:
cargo run --example simple_block --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/06_simple_block.js
// In this example we will send a block without a 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],
localPow: true,
});
try {
// Create block with no payload
const blockIdAndBlock = await client.buildAndPostBlock();
console.log('Block:', blockIdAndBlock, '\n');
console.log(
`Empty block sent: ${process.env.EXPLORER_URL}/block/${blockIdAndBlock[0]}`,
);
} 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/06_simple_block.js
from iota_client import IotaClient
# Create an IotaClient instance
client = IotaClient({'nodes': ['https://api.testnet.shimmer.network']})
# Create and post a block without payload
block = client.build_and_post_block()
print(f'{block}')
You can run the example by running the following command from the binding/python/examples
folder:
python3 06_simple_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;
import java.util.Map;
public class CreateBlock {
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"}));
// Create the most simple block.
Map.Entry<BlockId, Block> b = client.buildAndPostBlock(null, null);
// Print the block.
System.out.println(b);
}
}
Expected Output
- Rust
- Nodejs
- Python
- Java
Block {
protocol_version: 2,
parents: Parents(
BoxedSlicePrefix([
BlockId(0x2f68b25006f0e1b55ada3e9278e69796380971e97587c233d138c593139d255d),
BlockId(0x76d25ac0073d14381d9a38c61ecb9665241d771bd89564e467c7fdf98e770ddd),
BlockId(0xd072addb86a5a59a69b17d0e8fc3368771dc5ea7f7c2257045e508ae37f27a46),
BlockId(0xfea2e90318a1b234569a3d698e97906d2c6a0084eb571971bf9ce9c4d31ee6c9),
]),
),
payload: OptionalPayload(
None,
),
nonce: 4420,
}
Block with no payload sent: https://explorer.shimmer.network/testnet/block/0x9f794dde42c7be9cd209cc992f69e1f8b7b40578303825049079d8ac128aa20f
Block: [
'0x7531a0983f941e50b1764165d8cf1e205605c269f43796d18e38264ddfce8d06',
{
protocolVersion: 2,
parents: [
'0x649914f510d1f9e8bb54f3ea0c810f7b591377a36edae8698df8a5be7e080e36',
'0x76e0ce892ae9b3f0707ea6c068a3ee4faf98ac66e8089773a6ffe3951c6f111a',
'0x8461d818b5fca64848f475aae434d994592bf0f5648b3ff7470e75437768295d',
'0x994bcacab8bfc939a201e9ccf5a75eec2d047324a8a905cf1a4c1e09f3e1002a'
],
nonce: '3074457345618276659'
}
]
Empty block sent: https://explorer.shimmer.network/testnet/block/0x7531a0983f941e50b1764165d8cf1e205605c269f43796d18e38264ddfce8d06
[
'0xa76b3551777d24fd20a045b2ebae11346c9f7ce76e2351eccb044b8842769250',
{
'protocolVersion': 2,
'parents': [
'0x485f44a5528b341a179db493fdd19138096f823fc034ba207a9ed85ebee5a109',
'0x4a77573beb29edfa67ec00ee10577b31fe6a9e50b19ace0c833cfd1166069f7a',
'0xa8edca4bda2db44e7bd29dd9282eff6011ff73fc1e318ba5950a67387be562da',
'0xac283aa0ea563f81d7be39d2ae78bbadae838142e6d81280aeae02e96e35f013'
],
'nonce': '12297829382473042444'
}
]
{
"type": 3,
"amount": "1000000",
"unlockConditions": [
{
"type": 0,
"address": {
"type": 0,
"pubKeyHash": "0x7ffec9e1233204d9c6dce6812b1539ee96af691ca2e4d9065daa85907d33e5d3"
}
}
]
}