Skip to main content

Events

Events are Field arrays that are emitted by zkApp methods and stored on an archive node. They provide an off-chain log of contract activity that can be used for indexing, user interfaces, and tracking app state changes.

Basic Events

Define and emit events from your zkApp methods:

export class EventContract extends SmartContract {
@state(Field) counter = State<Field>();

events = {
"counter-updated": Field,
};

init() {
super.init();
this.counter.set(Field(0));
}

@method async increment() {
const currentCounter = this.counter.getAndRequireEquals();
const newCounter = currentCounter.add(1);

this.counter.set(newCounter);
this.emitEvent("counter-updated", newCounter);
}
}

Event Structure

Events are arrays of Fields and can be structured for different use cases:

export class TransferEvent extends Struct({
from: PublicKey,
to: PublicKey,
amount: UInt64,
}) {}

export class TokenContract extends SmartContract {
@state(Field) totalSupply = State<Field>();

events = {
transfer: TransferEvent,
mint: UInt64,
};

@method async transfer(from: PublicKey, to: PublicKey, amount: UInt64) {
// Transfer logic here
this.emitEvent("transfer", new TransferEvent({ from, to, amount }));
}
}

Events are useful for creating audit trails, enabling off-chain indexing, and providing data for user interfaces.

Fetching Events

Use fetchEvents to retrieve previously emitted events from an archive node:

// Fetch events for a specific account
let accountKey: PublicKey; // Address of the account

const events = await fetchEvents({
publicKey: accountKey.toBase58(),
from: 0, // Optional: specify the range of blocks to fetch events from
to: 100, // Optional: specify the range of blocks to fetch events to
});

console.log("Events:", events);

API Reference

For detailed information about events, see: