0

I am very new to solidity, contracts, and truffle, and I ran across a disconnect between the results of calling the getBalance() function of this basic contract:

contract TruffleTutorial {

  address private owner;

  constructor() public {
      owner = msg.sender;
  }

  function getOwner() public view returns(address){
      return owner;
  }
      
function getBalance() public view returns(uint256){
      return owner.balance;
  }
}

The contract is about as simple as it gets, and when I tested it on remix, I got the balance of my test account as an unsigned integer, just as I had expected. When I tried to call the getBalance() function of a contract with the same exact code using the truffle console, I got a BN variable as such:

BN {
  negative: 0,
  words: [ 54327296, 54735606, 3094901, 596, <1 empty item> ],
  length: 4,
  red: null
}

Trying the getOwner() function works perfectly on both remix and truffle, but for some reason truffle seems to mess up with the getBalance() function. Again, I am very new to this, so anything helps!

0

The results you're seeing are actually the same. The difference comes from the way they're being formatted after reading from the contract.

Because JavaScript numbers work by default with integers, we need some sort of utility to understand bigger numbers that are > maximum int can hold. What truffle is giving you there is an instance of such a Big Number. It uses a library such as BN.js or bignumber.js to store this and allow you to do things like division or multiplication without worrying about the size. Remix I suppose just gives you the string version of this, while Truffle hands over a BN instance.

What to do? Try working with the BN instance or cast the result to a string e.g.

const balanceBN = ...getBalance();
const balanceString = balanceBN.toString();

You may also use toNumber() but, as explained above, if it exceeds the maximum integer, it won't work properly in JS.

2
  • Hi, thank you so much for your help on this. I followed your advice with a few tweaks. When I initially casted to a string, it showed up as '[object Promise]'. I assumed that the promise factor had to do with 'await', so I tried to this instead: let tutorial = await TruffleTutorial.deployed() let balance = await tutorial.getBalance() balance.toString() I got this result as a string: '180143889151358280000000000', a number that is 1.) not resembling the balance and 2.) much larger than ~100 eth. Any ideas? (ps. sorry for the improper formatting as well)
    – Owen
    Jan 15 at 18:36
  • Hmm not sure, have you changed anything in your truffle-config? Or in ganache if you're running with that open?
    – razgraf
    Jan 15 at 18:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.