Indexing function API
Indexing functions are user-defined functions that receive blockchain data (a log, block, or trace) and insert data into the database. You can register indexing functions within any .ts
file inside the src/
directory.
Registration
To register an indexing function, use the .on()
method of the ponder
object exported from "@/generated"
.
Values returned by indexing functions are ignored.
import { ponder } from "@/generated";
ponder.on("ContractName:EventName", async ({ event, context }) => {
const { args, log, block, transaction } = event;
const { db, network, client, contracts } = context;
// ...
});
Log event
The event
argument contains the decoded log arguments and the raw log, block, and transaction.
type LogEvent = {
name: string;
args: Args;
log: Log;
block: Block;
transaction: Transaction;
};
Log event arguments
The event.args
object contains event log arguments decoded using Viem's decodeEventLog function.
/** Sample `args` type for an ERC20 Transfer event. */
type Args = {
from: `0x${string}`;
to: `0x${string}`;
value: bigint;
};
Raw log, block, and transaction
The event.block
, event.transaction
, and event.log
objects contain raw blockchain data.
/** The log being processed. */
type Log = {
/** Globally unique identifier for this log (`${blockHash}-${logIndex}`). */
id: string;
/** The address from which this log originated */
address: `0x${string}`;
/** Hash of block containing this log */
blockHash: `0x${string}`;
/** Number of block containing this log */
blockNumber: bigint;
/** Contains the non-indexed arguments of the log */
data: `0x${string}`;
/** Index of this log within its block */
logIndex: number;
/** `true` if this log has been removed in a chain reorganization */
removed: boolean;
/** List of order-dependent topics */
topics: [`0x${string}`, ...`0x${string}`[]] | [];
/** Hash of the transaction that created this log */
transactionHash: `0x${string}`;
/** Index of the transaction that created this log */
transactionIndex: number;
};
/** The block containing the transaction that emitted the log being processed. */
type Block = {
/** Base fee per gas */
baseFeePerGas: bigint | null;
/** "Extra data" field of this block */
extraData: `0x${string}`;
/** Maximum gas allowed in this block */
gasLimit: bigint;
/** Total used gas by all transactions in this block */
gasUsed: bigint;
/** Block hash */
hash: `0x${string}`;
/** Logs bloom filter */
logsBloom: `0x${string}`;
/** Address that received this block’s mining rewards */
miner: `0x${string}`;
/** Block number */
number: bigint;
/** Parent block hash */
parentHash: `0x${string}`;
/** Root of the this block’s receipts trie */
receiptsRoot: `0x${string}`;
/** Size of this block in bytes */
size: bigint;
/** Root of this block’s final state trie */
stateRoot: `0x${string}`;
/** Unix timestamp of when this block was collated */
timestamp: bigint;
/** Total difficulty of the chain until this block */
totalDifficulty: bigint | null;
/** Root of this block’s transaction trie */
transactionsRoot: `0x${string}`;
};
/** The transaction that emitted the log being processed. */
type Transaction = {
/** Hash of block containing this transaction */
blockHash: `0x${string}`;
/** Number of block containing this transaction */
blockNumber: bigint;
/** Transaction sender */
from: `0x${string}`;
/** Gas provided for transaction execution */
gas: bigint;
/** Base fee per gas. */
gasPrice?: bigint | undefined;
/** Hash of this transaction */
hash: `0x${string}`;
/** Contract code or a hashed method call */
input: `0x${string}`;
/** Total fee per gas in wei (gasPrice/baseFeePerGas + maxPriorityFeePerGas). */
maxFeePerGas?: bigint | undefined;
/** Max priority fee per gas (in wei). */
maxPriorityFeePerGas?: bigint | undefined;
/** Unique number identifying this transaction */
nonce: number;
/** Transaction recipient or `null` if deploying a contract */
to: `0x${string}` | null;
/** Index of this transaction in the block */
transactionIndex: number;
/** Value in wei sent with this transaction */
value: bigint;
};
Transaction receipt
The event.transactionReceipt
object contains details about the transaction associated with the current log or trace. To enable transaction receipts, set includeTransactionReceipts
to true
in the contract config. Read more.
/** A confirmed Ethereum transaction receipt. */
export type TransactionReceipt = {
/** Hash of block containing this transaction */
blockHash: Hash;
/** Number of block containing this transaction */
blockNumber: bigint;
/** Address of new contract or `null` if no contract was created */
contractAddress: Address | null;
/** Gas used by this and all preceding transactions in this block */
cumulativeGasUsed: bigint;
/** Pre-London, it is equal to the transaction's gasPrice. Post-London, it is equal to the actual gas price paid for inclusion. */
effectiveGasPrice: bigint;
/** Transaction sender */
from: Address;
/** Gas used by this transaction */
gasUsed: bigint;
/** List of log objects generated by this transaction */
logs: Log[];
/** Logs bloom filter */
logsBloom: Hex;
/** `success` if this transaction was successful or `reverted` if it failed */
status: "success" | "reverted";
/** Transaction recipient or `null` if deploying a contract */
to: Address | null;
/** Hash of this transaction */
transactionHash: Hash;
/** Index of this transaction in the block */
transactionIndex: number;
/** Transaction type */
type: TransactionType;
};
Context
The context
argument passed to each indexing function contains database model objects and helper objects based on your config.
At runtime, the indexing engine uses a different context
object depending on the network the current event was emitted on. The TypeScript types for the context
object reflect this by creating a union of possible types for context.network
and context.contracts
.
type Context = {
db: Database;
network: { name: string; chainId: number };
client: ReadOnlyClient;
contracts: Record<
string,
{ abi: Abi; address?: `0x${string}`; startBlock?: number; endBlock?: number; }
>;
};
Database
The context.db
object is a live database connection. Read more about writing to the database.
import { ponder } from "@/generated";
import { persons, dogs } from "../ponder.schema";
ponder.on("Neighborhood:NewNeighbor", async ({ event, context }) => {
await context.db.insert(persons).values({ name: "bob", age: 30 });
await context.db.insert(dogs).values({ name: "jake", ownerName: "bob" });
const jake = await context.db.find(dogs, { name: "jake" });
});
Network
The context.network
object includes information about the network that the current event is from. The object is strictly typed according to the networks you defined in your config.
ponder.on("UniswapV3Factory:Ownership", async ({ event, context }) => {
context.network;
// ^? { name: "mainnet", chainId 1 } | { name: "base", chainId 8453 }
if (context.network.name === "mainnet") {
// Do mainnet-specific stuff!
}
});
Client
See the Read contract data guide for more details.
Contracts
See the Read contract data guide for more details.
"setup"
event
You can also define a setup function for each contract that runs before indexing begins.
- The indexing function does not receive an
event
argument, onlycontext
. - If you read from contracts in a
"setup"
indexing function, theblockNumber
for the request is set to the contract'sstartBlock
.
For example, you might have a singleton World
record that occasionally gets updated in indexing functions.
import { ponder } from "@/generated";
import { world } from "../ponder.schema";
ponder.on("FunGame:NewPlayer", async ({ context }) => {
await context.db
.insert(world)
.values({ id: 1, playerCount: 0 })
.onConflictDoUpdate((row) => ({
playerCount: row.playerCount + 1,
}));
});
Without the "setup"
event, you need to upsert the record in each indexing function that attempts to use it, which is clunky and bad for performance. Instead, use the "setup"
event to create the singleton record once at the beginning of indexing.
import { ponder } from "@/generated";
import { world } from "../ponder.schema";
ponder.on("FunGame:setup", async ({ context }) => {
await context.db.insert(world).values({
id: 1,
playerCount: 0,
});
});
ponder.on("FunGame:NewPlayer", async ({ context }) => {
await context.db
.update(world, { id: 1 })
.set((row) => ({
playerCount: row.playerCount + 1,
}));
});