• Core
  • FAQ

FAQ

BigInt Serialization

Using native BigInt with JSON.stringify will raise a TypeError as BigInt values are not serializable. Read more.

There are two techniques to mitigate this:

Lossless serialization

Lossless serialization means that BigInt will be converted to a format that can be deserialized later (e.g. 69420n"#bigint.69420"). The trade-off is that these values are not human-readable and are not intended to be displayed to the user.

Lossless serialization can be achieved with wagmi's serialize & deserialize

import { serialize, deserialize } from 'wagmi'
 
const serialized = serialize({ value: 69420n })
// '{"value":"#bigint.69420"}'
 
const deserialized = deserialize(serialized)
// { value: 69420n }

Lossy serialization

Lossy serialization means that the BigInt will be converted to a normal display string (e.g. 69420n"69420"). The trade-off is that you will not be able to deserialize the BigInt with JSON.parse as it can not distinguish between a normal string and a BigInt.

This method can be achieved by modifying JSON.stringify to include a BigInt replacer:

const replacer = (key, value) =>
  typeof value === 'bigint' ? value.toString() : value
 
JSON.stringify({ value: 69420n }, replacer)
// '{"value":"69420"}'