replaceBigInts
Replaces all BigInt
values in an object using the provided replacer function. The target can be a scalar, array, or object.
The ReplaceBigInt
generic type implements the same funtionality at the type level.
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
The p.json()
column type uses the JSONB
data type in SQLite and Postgres, which does not support BigInt
values.
Use replaceBigInts
to prepare objects containing BigInt
values for insertion into p.json()
columns. In your schema, use the ReplaceBigInts
generic in the p.json()
type annotation.
import { createSchema } from "@ponder/core";
import type { ReplaceBigInts } from "@ponder/utils";
import type { TransactionReceipt, Hex } from "viem";
export default createSchema((p) => ({
UserOperation: p.createTable({
id: p.string(),
receipt: p.json<ReplaceBigInts<TransactionReceipt, Hex>>(),
// ...
}),
}));
import { ponder } from "@/generated";
import { replaceBigInts } from "@ponder/utils";
import { toHex } from "viem";
ponder.on("EntryPoint:UserOp", async ({ event, context }) => {
const { UserOperation } = context.db;
await UserOperation.create({
id: event.log.id,
data: {
receipt: replaceBigInts(event.transactionReceipt, toHex),
},
});
});
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.