@nvana-dharma/gen-anchor-events
v4.0.0
Published
Generate TypeScript event types from Anchor IDL files
Readme
gen-anchor-events
Generate TypeScript event types from Anchor IDL files.
Installation
As a global package:
npm install -g @mayflower-fi/gen-anchor-eventsAs a local dependency:
npm install --save-dev @mayflower-fi/gen-anchor-eventsUsage
Command Line Interface
After installation, you can use the gen-anchor-events command:
gen-anchor-events <idl-file> <output-file> [options]Arguments:
<idl-file>: Path to the IDL JSON file<output-file>: Path to the output TypeScript file
Options:
-v, --verbose: Enable verbose output-h, --help: Display help information-V, --version: Display version number
Examples:
Basic usage:
gen-anchor-events ./idl/mayflower.json ./src/events.tsWith verbose output:
gen-anchor-events ./idl/program.json ./generated/types.ts --verboseUsing npx (without global installation):
npx @mayflower-fi/gen-anchor-events ./idl/program.json ./src/events.tsFrom node_modules/.bin (when installed locally):
./node_modules/.bin/gen-anchor-events ./idl/program.json ./src/events.tsProgrammatic Usage
You can also use the library programmatically:
import { generateEventsFromIDL } from '@mayflower-fi/gen-anchor-events';
// Generate TypeScript events from IDL
generateEventsFromIDL('./idl/program.json', './src/events.ts');Input Format
The tool expects an Anchor IDL JSON file with the following structure:
{
"events": [
{
"name": "EventName",
"fields": [
{
"name": "fieldName",
"type": "u64" | "string" | "publicKey" | { "defined": "CustomType" }
}
]
}
],
"types": [
{
"name": "CustomType",
"type": {
"kind": "struct",
"fields": [
{
"name": "fieldName",
"type": "string"
}
]
}
}
]
}Output
The tool generates TypeScript interfaces for all events and their custom types, plus utility types and functions:
- Event interfaces (e.g.,
UserCreated,UserUpdated) - Custom type interfaces (e.g.,
UserData) EventRawtype for raw event dataParsedEventstype for organized event collectionsparseEvents()function for parsing raw events into organized collections
Example
Given an IDL with events, the tool generates:
// Generated event types from program.json
// Do not edit manually
import { BN, web3 } from "@coral-xyz/anchor";
export interface UserData {
name: string;
age: number;
balance: BN;
}
export interface UserCreated {
user: UserData;
timestamp: BN;
}
export type ParsedEvents = {
UserCreated: UserCreated[];
};
export function parseEvents(events: EventRaw[]): ParsedEvents {
// ... parsing logic
}