1

I am implementing a simple smart contract in Solidity 0.5.9. One of the functions is called getSummary() which basically returns a summarized version of a vote:

function getSummary() public view returns (uint, uint, uint, address, bool) {
    return (
        reward,
        choices.length,
        votersCount,
        manager,
        pollActive
    );
}

I test this in Remix and get the results as I expect:

0: uint256: 9000000000000000
1: uint256: 2
2: uint256: 0
3: address: 0x1d174c79A9Fc825F2d625adEAa7035381D3a413e
4: bool: true

So far so good.

Now, I am working on a simple JavaScript frontend to display these results to the user, using web3-1.0.0, however I get the results in a weird format:

0: {…}
​​​
_ethersType: "BigNumber"
​​​
_hex: "0x1ff973cafa8000"
​​​
<prototype>: Object { fromTwos: fromTwos(), toTwos: toTwos(), abs: abs()
, … }
​​
1: {…}
​​​
_ethersType: "BigNumber"
​​​
_hex: "0x02"
​​​
<prototype>: Object { fromTwos: fromTwos(), toTwos: toTwos(), abs: abs()
, … }
​​
2: {…}
​​​
_ethersType: "BigNumber"
​​​
_hex: "0x00"
​​​
<prototype>: Object { fromTwos: fromTwos(), toTwos: toTwos(), abs: abs()
, … }
​​
3: "0x1d174c79A9Fc825F2d625adEAa7035381D3a413e"
​​
4: true

It looks like the Boolean and the Address are being returned in the correct format, whereas the integers are being returned as objects with the _hex property. I am pretty sure that I am seeing this for the first time and if I recall correctly, I haven't encountered such issue with previous smart contracts.

What am I doing wrong? Is this the expected behaviour? If yes, how can I correctly cast uint values from Solidity to display correctly on the frontend.

PS: I tried using web3.utils.toAscii(val) but values were transformed into funny characters, not to mention that this seems like a poor hack to do on every value I return.

2

Web3.js returns all uint types as BigNumber objects.

If you want to get the decimal string which represents the numeric value embedded in a BigNumber object, then you can call function toFixed on that object.

For example:

const [reward, length, votersCount, manager, pollActive] = await myContract.methods.getSummary();

console.log('reward:', reward.toFixed());
console.log('length:', length.toFixed());
console.log('votersCount:', votersCount.toFixed());

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.