⚠️

This documentation is for versions 0.1 – 0.6. You may want to view the latest version.

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.

index.ts
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.

ponder.schema.ts
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>>(),
    // ...
  }),
}));
src/index.ts
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.

EncodingReplacer typeReplacer function
Hex `0x${string}` numberToHex
StringstringString
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.