Search code examples
web3jsbignumber.js

What's the point of converting to BN twice?


Debugging a smart contract test, I'm seeing the following operation:

const alice_Before = toBN(web3.utils.toBN(await web3.eth.getBalance(alice)));

where toBN is

 static toBN(num) {
    return web3.utils.toBN(num)
  }

if I console.log the two options they both look like this with a certain balance in the address:

BN {
  negative: 0,
  words: [ 39940619, 64700551, 7238971, 54128420, 49303 ],
  length: 5,
  red: null
}

Can anyone help understand why the BN conversion is having to be made twice?


Solution

  • It does not have to be made twice. web3.utils.toBN will return its input parameter if it is already a BN, so you may remove one of the conversions as the static function does nothing more than this.

    // Replaced toBN with the body, which is a call to web3.utils.toBN
    const alice_Before1 = web3.utils.toBN(web3.utils.toBN(await web3.eth.getBalance(alice)));
    const alice_Before2 = web3.utils.toBN(await web3.eth.getBalance(alice));
    
    // Results will be identical:
    console.log(alice_Before1);
    console.log(alice_Before2);