Search code examples
javascriptsoliditysmartcontractsweb3jstruffle

How to do basic arithmetic in Truffle testing using web3.js


I'm currently using Truffle to test smart contracts, but having difficulty with basic arithmetic.

If I try to add two numbers:

const firstNumber = web3.utils.toWei('1', 'ether'); // 1000000000000000000
const sum = firstNumber + 100

The result is like when two strings are attached 1000000000000000000100.

I tried converting firstNumber.toString() or using const { toBN } = web3.utils; but all have the same result.

I tried using add or mul like some examples here, but my Truffle simply says those methods don't exist.

I'm using Truffle v5.3.14 (core: 5.3.14) and Web3.js v1.4.0.


Solution

  • '1' is a string so you will receive string from .toWei. You can convert String to BN and use .add. For example:

    const firstNumber = web3.utils.toWei('1', 'ether'); // 1000000000000000000
    const sum = web3.utils.toBN(firstNumber).add(web3.utils.toBN('100')).toString();