Requesting Information from the Ethereum Provider

Published by Mario Oettler on

Again, we need our server file that delivers the website using Express.

You can find the code here:

var express = require("express");
var path    = require("path");
var app     = express();

app.listen(3000);
console.log("Listening to Port 3000");
app.get('/', function(req, res){
    res.sendFile(path.join(__dirname, './','providerAPI_browser01.html')); //Adjust path according to your project
});

The provider API works as follows:

ethereum.request({
	method: 'METHOD NAME,
	params})
.then(function(result){

})
.catch(function(error) => {
});

The name of the RPC method and its parameters are submitted.

Parameters are typically provided as array.

[‘value 1’, ‘value 2’]

or as an object

[{
param1: 'value 1',
param2: 'value 2',
param3: 'value3'
}]

The function returns a promise which is caught with then().

If an error occurs, we can catch it with catch().

You can find the code sample here:

<!DOCTYPE html>
<html>
    <head>
        <script src='web3.min.js'>
            
        </script>
        <script>
            window.addEventListener("load", (event)=>{
                if(window.ethereum){
                    ethereum.request({method: 'eth_requestAccounts'}).then(function(accounts){
                        console.log(accounts);
                        document.getElementById("accounts").innerHTML = accounts;

                        // Or by using our conveniance library web3.js
                        window.web3 = new Web3(window.ethereum);
                        web3.eth.getBlockNumber().then(function(blknr){
                            console.log(blknr);
                            document.getElementById("blockNumber_Web3").innerHTML = blknr;
                        })
                    })
                }else{
                    return false
                }
            })
        </script>
    </head>

    <body>
        <h1>My First DApp</h1>
        <div>Accounts </div>
        <div id = "accounts"></div>
        <div>Blocknumber by web3.js: </div>
        <div id = "blockNumber_Web3"></div>
    </body>
</html>

Don’t forget to change the file name in our JavaScript file.

Categories: