0

Context

I am learning web3 after having written some smart contracts on the Ropsten and Kovan test networks.

I'm trying to simply read the balance of an address and store it in a variable, in order to display it. The next steps would be to add smart contract interactions using a browser wallet such as Metamask.

I'd like to write a script that would run on the client side, one of the motivations being that the website would then be static.

Code and errors

I imported the web3js library with the following line, please tell me if there's a better way:

<script language="javascript" type="text/javascript" src="https://cdn.jsdelivr.net/gh/ethereum/web3.js@1.3.4/dist/web3.min.js"></script>

then, to connect to a provider, I created an Infura account and got a url associated to my project. In order not to display it entirely, I will write it like so

    var url = "https://kovan.infura.io/v3/my_project_id";

As you can see in the following code, I have created an input element where the user would write an address of which it would like to know the balance. When pressing the button, the paragraph should be changed and show the balance (in wei).


<body>
    <input type="text" id="address" placeholder="Enter an address here">
    <button onClick="displayBalance()">Get balance</button>
    <p id="showbal">This paragraph would show the balance</p>
</body>
<script>
    var url = "https://kovan.infura.io/v3/my_project_id";
    var web3 = new Web3(url);
    function displayBalance() {
        var addr = document.getElementById("address").value;
        web3.eth.getBalance(addr).then(function(result) {balance = result});
        document.getElementById("showbal").innerHTML = balance;
    }
</script>

The error I get when calling displayBalance() with a valid address in the input element is an Uncaught ReferenceError telling me that balance is not defined. Note that the error is shown on the last line of the function. Also, it is worth to be noted that I managed to obtain a successful result when running each instruction at a time in the browser console. My guess it that the promise hasn't finished running when the next line is executed.

2

The petition not return the balance value instantly. For that reason you need to call the balance as a promise and wait the result, then print to HTML.

You can co it with a callback function and wait the result. For ex:

function getETHBalanceOf(address){
 web3js.eth.getBalance(address).then(function(balance){
     myBalanceVar = balance;
     //Your HTML print
 }); 
}

Or you can call it with an async function and wait the result. For ex:

async function getTHEBalanceOf(address){
    myBalanceVar = await web3js.eth.getBalance(address);
    //Your HTML print               
}

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.