Good afternoon!
I have a question regarding testing Integer overflows with truffle.
The contract method is:
function sumNumbers(uint256 numberA, uint256 numberB) public view returns(uint256) {
return numberA.add(numberB);
}
My test code is as follows:
it('the sum should not overflow', async () => {
try {
// Trying to sum 2^256 + 5, which should overflow and throw an exception in the best case
const sumResult = await _erc20.sumNumbers(2e256, 5);
assert.ok(false, 'The contract should throw an exception to avoid overflowing and thus making bad calculations')
} catch(error) {
assert.ok(true, 'The contract is throwing which is the expected behaviour when you try to overflow')
console.log(error);
}
})
The test result is as follows:
RangeError: Invalid array length
at Object.padLeft (/app/node_modules/truffle/build/webpack:/~/web3/lib/utils/utils.js:81:1)
at SolidityTypeUInt.formatInputInt [as _inputFormatter] (/app/node_modules/truffle/build/webpack:/~/web3/lib/solidity/formatters.js:40:1)
at SolidityTypeUInt.SolidityType.encode (/app/node_modules/truffle/build/webpack:/~/web3/lib/solidity/type.js:188:1)
at /app/node_modules/truffle/build/webpack:/~/web3/lib/solidity/coder.js:91:1
at Array.map (<anonymous>)
at SolidityCoder.encodeParams (/app/node_modules/truffle/build/webpack:/~/web3/lib/solidity/coder.js:90:1)
at SolidityFunction.toPayload (/app/node_modules/truffle/build/webpack:/~/web3/lib/web3/function.js:92:1)
at SolidityFunction.call (/app/node_modules/truffle/build/webpack:/~/web3/lib/web3/function.js:131:1)
at SolidityFunction.execute (/app/node_modules/truffle/build/webpack:/~/web3/lib/web3/function.js:260:1)
at /app/node_modules/truffle/build/webpack:/packages/truffle-contract/contract.js:135:1
at new Promise (<anonymous>)
at /app/node_modules/truffle/build/webpack:/packages/truffle-contract/contract.js:126:1
I just can't figure out what is going wrong, except when I change the value 2e256 to a much lower value, say 5, I don't get this error.
Can anyone help me with this case?
Best Answer
Argument
numberA
of a functionsumNumbers
has a data typeuint256
. Maximum value thatnumberA
can store is 2^256-1.As
numberA
cannot store a number greater than 2^256-1 you are getting the error.As @smax correctly pointed out in javascript
2e10
is 20000000000. You should usebignumber.js
for passing a value as an argument to a function.