0

I am trying to print the balance of the smart contracts using web3 but it doesn't show any error but on the client-side application it appears as follows:

Your Balance: [object Promise]

/contracts/mycontract.sol:

function () external payable {
        // payable fallback to receive and store ETH
        if(msg.value < 10 ether){
        revert();
        }
        balanceOf[msg.sender] += msg.value;
    }

    function getBalance() external view returns (uint) {
        return address(this).balance;   //this keyword refers to the smart contract address
    }

/src/js/app.js:

 App.contracts.kyc.deployed().then(function(instance) {
          kycInstance = instance;          
    var bal=kycInstance.getBalance();
              $("#SmartBalance").html("Your Balance: " + bal);
        // #smartbalance is an id for the HTML file
});
1

Javascript function kycInstance.getBalance returns a Promise object which you need to resolve in order to get the actual value returned from the corresponding Solidity function.

One way to do it, for example, is by changing this:

kycInstance.getBalance();
$("#SmartBalance").html("Your Balance: " + bal);

To this:

kycInstance.getBalance().then(function(bal) {
    $("#SmartBalance").html("Your Balance: " + bal);
});

Note that since the Solidity function returns a uint, the type of bal in Javascript depends on the web3.js version that you're using:

  • On web3.js v0.x: typeof bal == BigNumber
  • On web3.js v1.x: typeof bal == String

So if you're using web3.js v0.x, then you would better print "Your Balance: " + bal.toFixed().

| improve this answer | |
  • I tried this code, but I am getting an error as follows on the client-side console when I inspect: Uncaught (in promise) Error: Invalid number of arguments to Solidity function – Shras299 May 16 at 14:30

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.