0

I'm trying to ask to a smart contract the balance of it. The code for obtain the balance in Solidity is this:

 function balance() external view returns (uint) {
        uint amount = address(this).balance;
        return amount;
    }

Unfortunately when I run the code what I obtain is a block as result:

enter image description here

What I'm doing wrong?

4
  • What JavaScript library are you using to query the Ethereum smart contract? Jul 12, 2022 at 7:56
  • I'm using React
    – Uderr
    Jul 12, 2022 at 8:04
  • contracts return uint in js environments always as big numbers, because js cannot handle and work with those very very big numbers. You need to use libraries to transfer it to a string or a normal number (if it is safe to do that without overflow or losing data) check this docs.ethers.io/v5/api/utils/bignumber
    – Majd TL
    Jul 12, 2022 at 8:06
  • @Uderr yeah, but React can be used with ethers.js, web3.js, etc. You have to specify what web3 library you're using. Jul 12, 2022 at 8:09

2 Answers 2

1

if you are using ethers.js to interact with your smart contract, it provides a way to interact with Bignumbers and convert them to native JavaScript types. Check this out https://docs.ethers.io/v5/api/utils/bignumber/.

0

Was facing a similar issue you can solve it by,

return amount.toNumber()

BigNumber.toNumber( ) ⇒ number Returns the value of BigNumber as a JavaScript value.

1
  • Just be aware that it might not work well for arbitrarily large numbers. For numbers bigger than Number.MAX_SAFE_INTEGER it will lose precision.
    – Ismael
    Mar 19 at 0:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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