Error Handling in Web3.js: Converting BigInt to Event Listeners
When working with Web3.js, you often encounter situations where you need to handle events and responses in a specific way. Recently, I encountered an error when trying to convert a BigInt object into an event listener response using the library’s built-in functions.
The Problem: TypeError: I don’t know how to serialize a BigInt
In my case, the problem was that Web3.js is unable to serialize and deserialize BigInt objects. This can happen when you try to pass or receive large amounts of data between different parts of your application. However, some libraries (including Web3.js) do not support serializing BigInt objects.
The Solution: Custom Conversion Function
To overcome this problem, we need to create a custom function that converts BigInt objects into strings before sending them as an event listener response. We can use the BigInt.toString() method for this purpose.
Here is an example of how you can implement this:
const web3 = require('web3');
const Web3 = require('@web3/web3');
// Replace 'YOUR-WALLET-SECRET' with your actual wallet secret
const networkId = 1; // Ethereum network
const web3Provider = new web3.providers.HttpProvider('
const vendor = new web3.providers.HTTPProvider(networkId, web3Provider);
web3.eth.on('block', (block) => {
const bigIntBlockNumber = BigInt(block.number);
const transactionHash = BigInt(block.hash);
// Convert BigINT to string
const bigIntTransactionHash = bigIntTransactionHash.toString();
console.log(Event listener response: ${bigIntTransactionHash});
});
In this example, we create a custom function toString() that converts BigInt objects to strings. We then pass this function as the second argument to web3.eth.on('block', ...).
The benefit: no more type errors
Using our custom conversion function, we can successfully send and receive Web3.js events, even with large amounts of data (in this case, BigInt objects). The rest of the code remains the same.
Please note that you will need to replace YOUR-WALLET-SECRET, networkId, and bigIntTransactionHash with actual values ββspecific to your project. Also, make sure your wallet provider is configured correctly and active on your Ethereum network.

