Monitoring On-Chain Events in IOTA
Monitoring on-chain activity is essential for understanding and reacting to actions performed by smart contracts on the IOTA network. By following the events emitted by Move packages, you can track activities such as NFT minting or IOTA transactions as they happen. This guide shows you how to emit events in Move, query them, and follow new events as the network produces them.
Understanding Events in IOTA
Events in IOTA provide a structured way to capture and broadcast on-chain activities. Each event contains specific attributes that offer detailed information about what occurred.
Event Structure
An event object in IOTA consists of the following attributes:
id: JSON object containing the transaction digest ID and event sequence.packageId: The object ID of the package that emits the event.transactionModule: The module that performs the transaction.sender: The IOTA network address that triggered the event.type: The type of event being emitted.parsedJson: JSON object describing the event.bcs: Binary canonical serialization value.timestampMs: Unix epoch timestamp in milliseconds.
Exploring Available Events
To follow on-chain events, you first need to identify which events are available. While you can easily track events emitted by your own code, discovering events from external packages can be more challenging. The IOTA RPC provides the queryEvents method, which allows you to query on-chain packages and obtain a list of the events they emit.
Applying Event Filters
When targeting specific events for querying, you can use filters to refine your results. The filters a full node supports differ from the ones an indexer supports.
Emitting Events in Move
To emit events from your Move modules, you need to use the iota::event module.
Emitting events allows external applications to follow and respond to specific on-chain activities.
First, import the event module in your Move code:
use iota::event;
Then, within your function, you can emit an event using the emit function. For example:
public fun lock<T: key + store>(
obj: T,
ctx: &mut TxContext,
): (Locked<T>, Key) {
let key = Key { id: object::new(ctx) };
let mut lock = Locked {
id: object::new(ctx),
key: object::id(&key),
};
event::emit(LockCreated {
lock_id: object::id(&lock),
key_id: object::id(&key),
creator: ctx.sender(),
item_id: object::id(&obj)
});
// Adds the `object` as a DOF for the `lock` object
dof::add(&mut lock.id, LockedObjectKey {}, obj);
(lock, key)
}
Querying Events
- IOTA RPC
- Rust
- GraphQL
The IOTA RPC provides a queryEvents method to query on-chain packages and return available events. As an example, the following curl command queries the Deepbook package on Mainnet for a specific type of event:
curl -X POST https://api.testnet.iota.cafe:443 \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"id": 1,
"method": "iotax_queryEvents",
"params": [
{
"MoveModule": {
"package": "0x0000000000000000000000000000000000000000000000000000000000000002",
"module": "display",
"type": "0x0000…0002::display::Display<0xba68…286b::testnet_nft::TestnetNFT>"
}
},
null,
3,
false
]
}'
The TypeScript SDK provides a wrapper for the iotax_queryEvents method:
client.queryEvents.
You can use the following as an example on how to query for events using the query_events function. You should update
the PACKAGE_ID_CONST with a package of your choice.
use iota_sdk::{rpc_types::EventFilter, types::Identifier, IotaClientBuilder};
const PACKAGE_ID_CONST: &str = "";
#[tokio::main]
async fn main() -> Result<(), anyhow::Error> {
let iota_testnet = IotaClientBuilder::default()
.build("https://api.testnet.iota.cafe:443")
.await?;
let events = iota_testnet
.event_api()
.query_events(
EventFilter::MoveModule {
package: PACKAGE_ID_CONST.parse()?,
module: Identifier::new("dev_trophy")?,
},
None,
None,
false,
)
.await?;
for event in events.data {
println!("Event: {:?}", event.parsed_json);
}
Ok(())
}
You can use GraphQL to query events instead of JSON RPC. The following example queries are in the
iota-graphql-rpc crate in the IOTA repo.
Event Connection
# Retrieves all StakingRequestEvent events, showing the sender address, timestamp, event type, and additional metadata including the emitting module and raw data.
{
events(
filter: {
eventType: "0x3::validator::StakingRequestEvent"
}
) {
nodes {
sendingModule {
name
package { digest }
}
type {
repr
}
sender {
address
}
timestamp
json
bcs
}
}
}
Filter Events By Sender
# Get the first event sent by the specified transaction sender address.
query ByTxSender {
events(
first: 1
filter: {
sender: "0x0000000000000000000000000000000000000000000000000000000000000000"
}
) {
pageInfo {
hasNextPage
endCursor
}
nodes {
sendingModule {
name
}
type {
repr
}
sender {
address
}
timestamp
json
bcs
}
}
}
Filter Events By Emitting Package and Type
# Get the first event sent by the specified transaction sender address.
query ByTxSender {
events(
first: 1
filter: {
sender: "0x0000000000000000000000000000000000000000000000000000000000000000"
}
) {
pageInfo {
hasNextPage
endCursor
}
nodes {
sendingModule {
name
}
type {
repr
}
sender {
address
}
timestamp
json
bcs
}
}
}
The TypeScript SDK provides functionality to interact with the IOTA GraphQL service.
Following New Events
There are several ways to react to events as the network produces them:
- Poll
queryEventswith a cursor, so each request returns only the events since the previous one. - Subscribe through GraphQL with the TypeScript SDK.
- Stream checkpoints over gRPC and read the events of each transaction.
- Run a custom indexer, which processes every checkpoint with IOTA's data ingestion framework.
Polling is the simplest option and is most useful when the events you're monitoring don't fire often or you don't need to act on them right away. GraphQL subscriptions, gRPC streaming and a custom indexer deliver events close to when they happen.
Polling with queryEvents
queryEvents returns a nextCursor that points at the last event of the page. Passing it back as the cursor of the next request returns only newer events. A page without events has no nextCursor, so keep the previous cursor in that case. The following examples first look up the newest matching event, so they only print events emitted after they start, and then poll every five seconds.
- TypeScript
- Rust
import { getFullnodeUrl, IotaClient } from '@iota/iota-sdk/client';
const client = new IotaClient({ url: getFullnodeUrl('testnet') });
const query = { MoveModule: { package: '<PACKAGE_ID>', module: '<MODULE_NAME>' } };
// Start after the newest matching event, so only new events are printed.
let cursor = (await client.queryEvents({ query, limit: 1, order: 'descending' })).nextCursor;
while (true) {
const page = await client.queryEvents({ query, cursor, order: 'ascending' });
for (const event of page.data) {
console.log(event.parsedJson);
}
// An empty page has no cursor; keep the previous one so the next poll
// doesn't start again from the oldest event.
cursor = page.nextCursor ?? cursor;
if (!page.hasNextPage) {
await new Promise((resolve) => setTimeout(resolve, 5000));
}
}
See Rust SDK.
use std::time::Duration;
use iota_sdk::{rpc_types::EventFilter, types::Identifier, IotaClientBuilder};
const PACKAGE_ID_CONST: &str = "";
#[tokio::main]
async fn main() -> Result<(), anyhow::Error> {
let iota = IotaClientBuilder::default().build_testnet().await?;
let filter = EventFilter::MoveModule {
package: PACKAGE_ID_CONST.parse()?,
module: Identifier::new("dev_trophy")?,
};
// Start after the newest matching event, so only new events are printed.
let mut cursor = iota
.event_api()
.query_events(filter.clone(), None, 1, true)
.await?
.next_cursor;
loop {
let page = iota
.event_api()
.query_events(filter.clone(), cursor, None, false)
.await?;
for event in &page.data {
println!("Event: {:?}", event.parsed_json);
}
// An empty page has no cursor; keep the previous one so the next poll
// doesn't start again from the oldest event.
cursor = page.next_cursor.or(cursor);
if !page.has_next_page {
tokio::time::sleep(Duration::from_secs(5)).await;
}
}
}
Subscribing through GraphQL
The GraphQL service offers subscriptions for events and transactions, if its operator enabled them. In the TypeScript SDK, an IotaClient that uses the @iota/graphql-transport package serves subscribeEvent and subscribeTransaction through these GraphQL subscriptions. Install the package with npm install @iota/graphql-transport.
import { IotaClientGraphQLTransport } from '@iota/graphql-transport';
import { IotaClient } from '@iota/iota-sdk/client';
const client = new IotaClient({
transport: new IotaClientGraphQLTransport({
url: 'https://graphql.testnet.iota.cafe',
}),
});
// Call the returned function to stop the subscription.
const unsubscribe = await client.subscribeEvent({
filter: { Package: '<PACKAGE_ID>' },
onMessage: (event) => {
console.log(JSON.stringify(event, null, 2));
},
});
process.on('SIGINT', async () => {
await unsubscribe();
});
Event subscriptions support the Package and MoveModule filters, which select the module that emitted the event. To resume after an interruption without missing events, pass the digest of the last transaction you received as startAfter.
The transport connects to the /subscriptions path of the GraphQL URL over WebSocket. In an environment without a global WebSocket class, pass an implementation, for example from the ws package, as the WebSocketConstructor option of IotaClientGraphQLTransport.
Streaming Checkpoints with gRPC
The gRPC API streams checkpoints as the network produces them, including the events of each transaction, and lets you filter what it sends. See Stream Checkpoints for the TypeScript SDK. In Rust, the iota-sdk-grpc-client crate provides the gRPC client; see the SDK architecture.
Usage Examples with TypeScript SDK
The IOTA TypeScript SDK enables querying on-chain activity, such as emitted events and transaction blocks. Below are detailed usage examples for both queryEvents and queryTransactionBlocks.
The IOTA TypeScript SDK enables developers to interact with the IOTA Layer 1 blockchain in a structured and type-safe way. This includes retrieving smart contract events and querying transaction history. Below are detailed usage examples of two commonly used methods in the SDK:
queryEvents: To fetch emitted on-chain events (e.g., from NFTs or smart contracts).queryTransactionBlocks: To fetch raw transaction blocks based on filters such as sender, block type, or time range.
Querying Events with queryEvents
The queryEvents method allows you to retrieve specific events based on filters such as emitting package, module, or sender.
While events provide high-level data on interactions, such as user actions, contract calls, or state changes, the queryEvents method allows you to retrieve these events from the blockchain. You can filter these events by various criteria, such as the emitting package, module, or sender address. This is particularly useful for tracking smart contract execution, monitoring state changes, or auditing blockchain interactions.
The following example filters events emitted by a known Move module.
import { IotaClient } from '@iota/iota-sdk/client';
const client = new IotaClient({
url: 'https://api.testnet.iota.cafe',
});
async function queryEvents() {
try {
const events = await client.queryEvents({
query: {
MoveModule: {
package: '0x0000000000000000000000000000000000000000000000000000000000000002',
module: 'kiosk',
},
},
limit: 5,
});
console.log('Events:', JSON.stringify(events, null, 2));
} catch (error) {
console.error('Error querying events:', error);
}
}
queryEvents();
What this does:
- Connects to the IOTA Testnet fullnode.
- Uses a
MoveModulefilter to query a specific event type. - Limits the result to the 5 most recent events.
- Skips metadata to keep the response concise.
Querying Transaction Blocks with queryTransactionBlocks
The queryTransactionBlocks method retrieves transaction blocks based on filters such as sender or time range.
While events provide high-level data on interactions, sometimes it’s necessary to inspect the raw transaction blocks to understand the full lifecycle of an action—such as a payment, asset transfer, or contract interaction. The queryTransactionBlocks method allows you to retrieve these blocks, filtered by sender, transaction ID, or other criteria.
Here's a TypeScript example:
import { IotaClient } from '@iota/iota-sdk/client';
const client = new IotaClient({
url: 'https://api.testnet.iota.cafe',
});
async function queryTransactionBlocks() {
try {
const blocks = await client.queryTransactionBlocks({
filter: {
FromAddress: '0x2da66b11dbdd5ef21fb0e9d3c30cce27f92a67c0d012ee79fa5c13b614bdd5ab',
},
limit: 3,
});
console.log('Transaction Blocks:\n', JSON.stringify(blocks, null, 2));
} catch (error) {
console.error('Error querying transaction blocks:', error);
}
}
queryTransactionBlocks();
What this does:
- Retrieves the 3 latest transaction blocks for a specific sender address.
- Omits metadata from the response.
- Provides an easy way to track activity from known accounts or smart contracts.
Filtering Events
You can filter events when querying to receive only the events you are interested in.
The available filters depend on whether you query against a full node or an indexer endpoint.
Full Node Filters
The following filters are supported when querying a full node (e.g. api.mainnet.iota.cafe):
| Filter | Description | JSON-RPC Parameter Example |
|---|---|---|
Sender | Query by sender address | {"Sender":"0x008e9c621f4fdb210b873aab59a1e5bf32ddb1d33ee85eb069b348c234465106"} |
Transaction | Events emitted from the specified transaction | {"Transaction":"DGUe2TXiJdN3FI6MH1FwghYbiHw+NKu8Nh579zdFtUk="} |
MoveModule | Events emitted in the specified Move module. If the event is defined in Module A but emitted in a tx with Module B, query by Module B returns the event. | {"MoveModule":{"package":"<PACKAGE-ID>", "module":"nft"}} |
MoveEventType | Events with the given Move event struct name (struct tag), e.g. <PACKAGE-ID>::MyModule::Foo | {"MoveEventType":"<PACKAGE-ID>::nft::MintNFTEvent"} |
MoveEventModule | Events where the event struct is defined in the specified Move module. If the event is defined in Module A but emitted in a tx with Module B, query by Module A returns the event. | {"MoveEventModule":{"package":"<PACKAGE-ID>", "module":"nft"}} |
TimeRange | Events emitted in [start_time, end_time] interval (milliseconds since epoch, start inclusive, end exclusive) | {"TimeRange":{"startTime":"1669039504014", "endTime":"1669039604014"}} |
Indexer Filters
The following filters are supported when querying an indexer endpoint (e.g. indexer.mainnet.iota.cafe):
| Filter | Description | JSON-RPC Parameter Example |
|---|---|---|
Sender | Query by sender address | {"Sender":"0x008e9c621f4fdb210b873aab59a1e5bf32ddb1d33ee85eb069b348c234465106"} |
Transaction | Events emitted from the specified transaction | {"Transaction":"DGUe2TXiJdN3FI6MH1FwghYbiHw+NKu8Nh579zdFtUk="} |
Package | Events emitted in the specified package | {"Package":"<PACKAGE-ID>"} |
MoveModule | Events emitted in the specified Move module. If the event is defined in Module A but emitted in a tx with Module B, query by Module B returns the event. | {"MoveModule":{"package":"<PACKAGE-ID>", "module":"nft"}} |
MoveEventType | Events with the given Move event struct name (struct tag), e.g. <PACKAGE-ID>::MyModule::Foo | {"MoveEventType":"<PACKAGE-ID>::nft::MintNFTEvent"} |