Skip to main content

Network Interactions with IotaClient

The IOTA TypeScript SDK provides a IotaClient class to connect to a network's JSON-RPC server. Use IotaClient for all JSON-RPC operations.

Connecting to an IOTA network

To establish a connection to a network, import IotaClient from @iota/iota-sdk/client and pass the relevant URL to the url parameter. The following example establishes a connection to Testnet and requests IOTA from that network's faucet.

import { getFullnodeUrl, IotaClient } from '@iota/iota-sdk/client';

// use getFullnodeUrl to define Devnet RPC location
const rpcUrl = getFullnodeUrl('devnet');

// create a client connected to devnet
const client = new IotaClient({ url: rpcUrl });

// get coins owned by an address
// replace <OWNER_ADDRESS> with actual address in the form of 0x123...
await client.getCoins({
owner: '<OWNER_ADDRESS>',
});

The getFullnodeUrl helper in the previous code provides the URL for the specified network, useful during development. In a production application, however, you should use the Mainnet RPC address. The function supports the following values:

  • localnet
  • devnet
  • testnet
  • mainnet

For local development, you can run cargo run --bin iota start --with-faucet --force-regenesis to spin up a local network with a local validator, a Full node, and a faucet server. Refer to the Local Network guide for more information.

Manually calling unsupported RPC methods

You can use IotaClient to call any RPC method the node you're connecting to exposes. Most RPC methods are built into IotaClient, but you can use call to leverage any methods available in the RPC.

import { getFullnodeUrl, IotaClient } from '@iota/iota-sdk/client';

const client = new IotaClient({ url: getFullnodeUrl('devnet') });

// asynchronously call iotax_getCommitteeInfo
const committeeInfo = await client.call('iotax_getCommitteeInfo', []);

For a full list of available RPC methods, see the RPC documentation.

Subscribing to events with IotaClient

In addition to calling RPC methods, you can use IotaClient to subscribe to network events:

import { getFullnodeUrl, IotaClient } from '@iota/iota-sdk/client';

const client = new IotaClient({
url: getFullnodeUrl('testnet'),
});

// naming the function unsubscribe may seem counterintuitive here, but you call it later to unsubscribe from the event
const unsubscribe = await client.subscribeEvent({
filter: {
Sender: '<SENDER_ADDRESS>',
},
onMessage(event) {
// handle subscription notification message here. This function is called once per subscription message.
},
});

// later, to unsubscribe
await unsubscribe();

Using subscriptions in Node.js

If you are using IotaClient in an environment that does not support the WebSocket API, including Node.js, you may need to provide your own implementation of the WebSocket API when creating your IotaClient. You can either use a global polyfill for the WebSocket class, or pass a compatible WebSocket implementation into IotaHTTPTransport (eg, using the ws package)

import { getFullnodeUrl, IotaClient, IotaHTTPTransport } from '@iota/iota-sdk/client';
import { WebSocket } from 'ws';

new IotaClient({
transport: new IotaHTTPTransport({
url: getFullnodeUrl('testnet'),
// The typescript definitions may not match perfectly, casting to never avoids these minor incompatibilities
WebSocketConstructor: WebSocket as never,
}),
});

Subscribing to transactions with IotaClient

Similar to subscribing to events, the IotaClient also supports subscribing to transactions:

import { getFullnodeUrl, IotaClient } from '@iota/iota-sdk/client';

const client = new IotaClient({
url: getFullnodeUrl('testnet'),
});

const unsubscribe = await client.subscribeTransaction({
filter: {
FromAddress: '<IOTA_ADDRESS>',
},
onMessage(event) {
// This function is called once per transaction.
},
});

// later, to unsubscribe:
await unsubscribe();

Customizing the transport

The IotaClient uses a Transport class to manage connections to the RPC node. The default IotaHTTPTransport makes both JSON RPC requests, as well as websocket requests for subscriptions. You can construct a custom transport instance if you need to pass any custom options, such as headers or timeout values.

import { getFullnodeUrl, IotaClient, IotaHTTPTransport } from '@iota/iota-sdk/client';

const client = new IotaClient({
transport: new IotaHTTPTransport({
url: 'https://my-custom-node.com/rpc',
websocket: {
reconnectTimeout: 1000,
url: 'https://my-custom-node.com/websockets',
},
rpc: {
headers: {
'x-custom-header': 'custom value',
},
},
}),
});

Pagination

IotaClient exposes a number of RPC methods that return paginated results. These methods return a result object with 3 fields:

  • data: The list of results for the current page
  • nextCursor: a cursor pointing to the next page of results
  • hasNextPage: a boolean indicating whether there are more pages of results

Some APIs also accept an order option that can be set to either ascending or descending to change the order in which the results are returned.

You can pass the nextCursor to the cursor option of the RPC method to retrieve the next page, along with a limit to specify the page size:

const page1 = await client.getCheckpoints({
limit: 10,
});

const page2 =
page1.hasNextPage &&
client.getCheckpoints({
cursor: page1.nextCursor,
limit: 10,
});

Methods

In addition to the RPC methods mentioned above, IotaClient also exposes some methods for working with Transactions.

executeTransactionBlock

const tx = new Transaction();

// add transaction data to tx...

const { bytes, signature } = tx.sign({ client, signer: keypair });

const result = await client.executeTransactionBlock({
transactionBlock: bytes,
signature,
requestType: 'WaitForLocalExecution',
options: {
showEffects: true,
},
});

Arguments

  • transactionBlock - either a Transaction or BCS serialized transaction data bytes as a Uint8Array or as a base-64 encoded string.
  • signer - A Keypair instance to sign the transaction
  • requestType: WaitForEffectsCert or WaitForLocalExecution. Determines when the RPC node should return the response. Default to be WaitForLocalExecution
  • options:
    • showBalanceChanges: Whether to show balance_changes. Default to be False
    • showEffects: Whether to show transaction effects. Default to be False
    • showEvents: Whether to show transaction events. Default to be False
    • showInput: Whether to show transaction input data. Default to be False
    • showObjectChanges: Whether to show object_changes. Default to be False
    • showRawInput: Whether to show bcs-encoded transaction input data

signAndExecuteTransaction

const tx = new Transaction();
// add transaction data to tx

const result = await client.signAndExecuteTransaction({
transaction: tx,
signer: keypair,
requestType: 'WaitForLocalExecution',
options: {
showEffects: true,
},
});

Arguments

  • transaction - BCS serialized transaction data bytes as a Uint8Array or as a base-64 encoded string.
  • signature - A signature, or list of signatures committed to the intent message of the transaction data, as a base-64 encoded string.
  • requestType: WaitForEffectsCert or WaitForLocalExecution. Determines when the RPC node should return the response. Default to be WaitForLocalExecution
  • options:
    • showBalanceChanges: Whether to show balance_changes. Default to be False
    • showEffects: Whether to show transaction effects. Default to be False
    • showEvents: Whether to show transaction events. Default to be False
    • showInput: Whether to show transaction input data. Default to be False
    • showObjectChanges: Whether to show object_changes. Default to be False
    • showRawInput: Whether to show bcs-encoded transaction input data

waitForTransaction

Wait for a transaction result to be available over the API. This can be used in conjunction with executeTransactionBlock to wait for the transaction to be available via the API. This currently polls the getTransactionBlock API to check for the transaction.

const tx = new Transaction();

const result = await client.signAndExecuteTransaction({
transaction: tx,
signer: keypair,
});

const transaction = await client.waitForTransaction({
digest: result.digest,
options: {
showEffects: true,
},
});

Arguments

  • digest - the digest of the queried transaction
  • signal - An optional abort signal that can be used to cancel the request
  • timeout - The amount of time to wait for a transaction. Defaults to one minute.
  • pollInterval - The amount of time to wait between checks for the transaction. Defaults to 2 seconds.
  • options:
    • showBalanceChanges: Whether to show balance_changes. Default to be False
    • showEffects: Whether to show transaction effects. Default to be False
    • showEvents: Whether to show transaction events. Default to be False
    • showInput: Whether to show transaction input data. Default to be False
    • showObjectChanges: Whether to show object_changes. Default to be False
    • showRawInput: Whether to show bcs-encoded transaction input data