Ethereum: Resolving Invalid BigNumber Error with Ethers.js
When working with Ethereum contracts, especially those created with the Truffle package of Ethers.js, encountering an invalid BigNumber value can be frustrating. This error usually occurs when trying to call an Ethereum contract function that expects a BigNumber as an argument.
Problem: Invalid BigNumber Error
In this article, we will look at the causes of the “BigNumber invalid value” error and provide solutions to resolve it in Ethers.js applications.
What is BigNumber?
BigNumber is a JavaScript library for representing arbitrary precision integers. It provides classes such as BigNumber, BigInt, and Decimal that support operations on large numbers.
Reason for the error
When you create an instance of “BigNumber”, you are essentially creating a number with infinite precision. However, when this value is passed as an argument to a contract function, it can cause problems if:
- The input is not properly formatted: If a BigNumber instance is created from a string or other incompatible format, it may not be in the expected state.
- The BigNumber instance was modified after creation: If a BigNumber instance is modified externally (e.g. via JavaScript), its internal state changes unexpectedly, leading to incorrect calculations.
Fix this error
To resolve the “BigNumber value is invalid” error, try the following solution:
Option 1: Validate the input and create a new BigNumber instance
Before calling the contract function with the BigNumber instance:
const mnemonic = 'my_mnemonic';
wallet = ethers. Wallet.fromMnemonic(mnemonic);
signer = wallet.connect(provider);
// Check if BigNumber instance has been modified externally
console.log(signer.address); //Ensure 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”
You can avoid the problems caused by external modification of the BigNumber instance by doing the following:
import BigNumber from 'bignumbers';
const mnemonic = 'own_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 remains immutable
const isoNumber = new BigNumber('1'); // Create a BigNumber instance
routerInstance = new ethers.Contract(routerAddress, {
methods: {
myFunction(bigNumber): Promise { ... } // Call the contract function with a valid BigNumber instance
}
});
By following these instructions or using one of the libraries listed above, you should be able to resolve the Invalid BigNumber value error and continue using your Ethers.js applications.