replaceBigInts
Replaces all instances of BigInt in an object with a new value, specified by a replacer function.
Usage
This example simply converts BigInt values to a string.
import { replaceBigInts } from "@ponder/utils";
const obj = { a: 100n, b: [-12n, 3_000_000_000n] };
const result = replaceBigInts(obj, (v) => String(v));
// ?^ { a: '100', b: [ '-12', '3000000000' ] }Usage in Ponder
Here are a few common scenarios where you might want to replace BigInt values in a Ponder app.
json columns
The json column type does not support BigInt values. Use replaceBigInts to prepare objects containing BigInt values for insertion.
import { ponder } from "ponder:registry";
import { userOperations } from "ponder:schema";
import { replaceBigInts } from "@ponder/utils";
import { toHex } from "viem";
ponder.on("EntryPoint:UserOp", async ({ event, context }) => {
await context.db.insert(userOperations).values({
id: event.log.id,
receipt: replaceBigInts(event.transactionReceipt, toHex),
});
});To maintain type safety for column values, use the ReplaceBigInts helper type in the column $type annotation.
import { onchainTable } from "ponder";
import type { ReplaceBigInts } from "@ponder/utils";
import type { TransactionReceipt, Hex } from "viem";
export const userOperations = onchainTable("user_operations", (t) => ({
id: t.text().primaryKey(),
receipt: t.json<ReplaceBigInts<TransactionReceipt, Hex>>(),
}));HTTP responses
The GraphQL API automatically serializes BigInt values to strings before returning them in HTTP responses. In API functions, you need to handle this serialization process manually.
import { ponder } from "ponder:registry";
import { accounts } from "ponder:schema";
import { replaceBigInts } from "@ponder/utils";
import { numberToHex } from "viem";
ponder.get("/whale-balances", async (c) => {
const rows = await c.db
.select({
address: accounts.address,
ethBalance: accounts.ethBalance,
dogeBalance: accounts.dogeBalance,
})
.from(accounts)
.where(eq(accounts.address, address));
const result = replaceBigInts(rows, (v) => numberToHex(v));
return c.json(result);
});Replacer functions
Here are three common ways to replace BigInt values.
| Encoding | Replacer type | Replacer function |
|---|---|---|
| Hex | `0x${string}` | numberToHex |
| String | string | String |
| Lossless string | `#bigint.${string}` | (x) => `#bigint.${String(x)}` |
See the Wagmi FAQ for more information on BigInt serialization.
Parameters
value
- Type:
any
The scalar, array, or object containing BigInt values to be replaced.
replacer
- Type:
(value: bigint) => JSONSerializable
A custom replacer function that will be called for each BigInt value.
Returns
value
The scalar, array, or object with all BigInt values replaced.