Ethereum: Fixing the “Invalid BigNumber Value” Error with Ethers.js
When working with Ethereum contracts, especially those built with the Truffle suite using Ethers.js, it can be frustrating to encounter the “Invalid BigNumber Value” error. This error typically occurs when you try to call a function on an Ethereum contract that expects a BigNumber instance as an argument.
The Problem: “Invalid BigNumber Value” Error
In this article, we’ll explore the causes of the “Invalid BigNumber Value” error and provide solutions to fix the error in Ethers.js applications.
What is a BigNumber?
BigNumber is a JavaScript library for representing arbitrary-precision integers. It provides classes such as BigNumber, BigInt, and Decimal that support large number operations.
The reason for the error
When you create a BigNumber instance, you are essentially creating a number with infinite precision. However, if this value is passed as an argument to a contract function, problems may arise in the following cases:
- Input is not formatted correctly: If the BigNumber instance is created from a string or other incompatible format, it may not be in the expected state.
- BigNumber instance has been modified since it was created: If the BigNumber instance is modified externally (for example, using JavaScript code), its internal state changes unexpectedly, causing incorrect calculations.
Error Fix
To resolve the “Invalid BigNumber value” error, you can try the following:
Option 1: Validate input and create a new BigNumber instance
Before calling a contract function with a BigNumber instance:
const mnemonic = 'your_mnemonic';
wallet = ethers.Wallet.fromMnemonic(mnemonic);
signer = wallet.connect(provider);
// Check if the BigNumber instance has been modified externally
console.log(signer.address); // Make sure the instance remains unchanged
const routerAddress = '0x...'; // Replace with your contract address
routerInstance = new ethers.Contract(routerAddress, ...
Option 2: Use a library like ethers.js-bignumber
or @nomiclabs/ethers-abi
To avoid problems caused by external changes to BigNumber instances:
import BigNumber from 'big-number';
const mnemonic = 'your_mnemonic';
wallet = ethers.Wallet.fromMnemonic(mnemonic);
signer = wallet.connect(provider);
const routerAddress = '0x...'; // Replace with your contract address
// Use the BigNumber library to create a new instance that stays the same
const bigNumber = new BigNumber('1'); // Create an instance of BigNumber
routerInstance = new ethers.Contract(routerAddress, {
methods: {
myFunction(bigNumber): Promise { ... } // Call the contract function with a valid BigNumber instance
}
});
Following these steps or using one of the libraries above should resolve the “Invalid BigNumber value” error and continue working with your Ethers.js applications.
Leave a Reply