Skip to main content

Events

The EventMonitor module provides real-time monitoring of blockchain events.


Overview

EventMonitor enables:

  • Watching transaction state changes
  • Waiting for specific states
  • Querying transaction history
  • Subscribing to new transactions

Methods

watchTransaction()

Watch for state changes on a specific transaction.

// Level 2: Advanced API - Direct protocol control
// Start watching
const cleanup = client.events.watchTransaction(txId, (newState) => {
console.log('State changed to:', State[newState]);

if (newState === State.DELIVERED) {
console.log('Provider has delivered!');
}

if (newState === State.SETTLED) {
console.log('Transaction complete!');
cleanup(); // Stop watching
}
});

// Later: Stop watching manually
cleanup();

Parameters:

ParameterTypeDescription
txIdstringTransaction ID to watch
callback(state: State) => voidCalled on each state change

Returns: () => void - Cleanup function to stop watching


waitForState()

Wait for a transaction to reach a specific state.

// Level 2: Advanced API - Direct protocol control
try {
// Wait up to 60 seconds for DELIVERED state
await client.events.waitForState(txId, State.DELIVERED, 60000);
console.log('Transaction delivered!');
} catch (error) {
console.log('Timeout waiting for delivery');
}

Parameters:

ParameterTypeDefaultDescription
txIdstring-Transaction ID
targetStateState-State to wait for
timeoutMsnumber60000Timeout in milliseconds

getTransactionHistory()

Get all transactions for an address.

// Level 2: Advanced API - Direct protocol control
// Get transactions where address is requester
const asRequester = await client.events.getTransactionHistory(
myAddress,
'requester'
);

// Get transactions where address is provider
const asProvider = await client.events.getTransactionHistory(
myAddress,
'provider'
);

console.log(`${asRequester.length} transactions as requester`);
console.log(`${asProvider.length} transactions as provider`);

// Display each transaction
for (const tx of asRequester) {
console.log(`${tx.txId}: ${State[tx.state]} - $${tx.amount / 1000000n}`);
}

Returns: Promise<Transaction[]>


onTransactionCreated()

Subscribe to new transaction creation events.

// Level 2: Advanced API - Direct protocol control
// Subscribe to all new transactions
const cleanup = client.events.onTransactionCreated((event) => {
console.log('New transaction!');
console.log(' ID:', event.txId);
console.log(' Requester:', event.requester);
console.log(' Provider:', event.provider);
console.log(' Amount:', event.amount);
});

// Later: Unsubscribe
cleanup();

onEscrowCreated()

Subscribe to escrow creation events.

// Level 2: Advanced API - Direct protocol control
const cleanup = client.events.onEscrowCreated((event) => {
console.log('Escrow created!');
console.log(' Escrow ID:', event.escrowId);
console.log(' Amount:', event.amount);
});

onStateTransitioned()

Subscribe to all state transitions.

// Level 2: Advanced API - Direct protocol control
const cleanup = client.events.onStateTransitioned((event) => {
console.log(`${event.txId}: ${State[event.from]}${State[event.to]}`);
});

Event Types

TransactionCreated

Emitted when a new transaction is created.

// Level 2: Advanced API - Direct protocol control
interface TransactionCreatedEvent {
txId: string;
requester: string;
provider: string;
amount: bigint;
serviceHash?: string;
}

StateTransitioned

Emitted when transaction state changes.

// Level 2: Advanced API - Direct protocol control
interface StateTransitionedEvent {
txId: string;
from: State;
to: State;
}

EscrowCreated

Emitted when escrow is linked.

// Level 2: Advanced API - Direct protocol control
interface EscrowCreatedEvent {
escrowId: string;
txId: string;
amount: bigint;
requester: string;
provider: string;
}

EscrowReleased

Emitted when escrow funds are released.

// Level 2: Advanced API - Direct protocol control
interface EscrowReleasedEvent {
escrowId: string;
txId: string;
providerAmount: bigint;
feeAmount: bigint;
}

Example: Provider Listener

import { ACTPClient, State } from '@agirails/sdk';

async function runProviderListener() {
const client = await ACTPClient.create({
mode: 'testnet',
privateKey: process.env.PRIVATE_KEY!,
});

const myAddress = await client.getAddress();
console.log('Listening for jobs as:', myAddress);

// Listen for new transactions addressed to me
client.events.onTransactionCreated(async (event) => {
if (event.provider.toLowerCase() !== myAddress.toLowerCase()) {
return; // Not for me
}

console.log('New job received!');
console.log(' From:', event.requester);
console.log(' Amount:', event.amount / 1000000n, 'USDC');

// Watch this transaction for state changes
client.events.watchTransaction(event.txId, (state) => {
if (state === State.COMMITTED) {
console.log('Escrow locked - start working!');
// Trigger your AI agent work here
}
});
});

console.log('Provider listener running...');
}

Performance Notes

  • Testnet/Mainnet: Uses blockchain event subscriptions (WebSocket)
  • Mock Mode: Uses in-memory event emitter (instant)
  • History queries: May be slow for large transaction volumes
  • Recommendation: Use off-chain indexer for production queries

Next Steps

  • Kernel - Trigger state transitions
  • Escrow - Monitor fund movements
  • EAS - Create delivery attestations