Sending Transactions with web3.js

Published by Mario Oettler on

In this topic, we want to create and send a transaction with our web3.js library and MetaMask. For testing purposes, create another account on MetaMask.

We rely on the server structure from the topic Preparation.

We only change our Html file.

The following code shows the server.

// Here, we deliver the web3 library to the browser
// We copied the web3.min.js from the dist folder into our project.

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, './','dapps1_browser03.html')); 
    app.use(express.static(path.join(__dirname, './', 'public')));
});

It shows nothing new to us.

The following code shows the Html file with the JavaScript that creates the transaction:

<!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(res){
                        console.log(res);
                        window.web3 = new Web3(window.ethereum);
                        document.getElementById("send").addEventListener("click", (event) =>{
                            amount = document.getElementById("amount").value;
                            address = document.getElementById("recipientAddress").value;
                            console.log("amount: " + amount);
                            console.log("address: " + address);
                            web3.eth.sendTransaction({
                                from: res[0],
                                to: address,
                                value: web3.utils.toHex(amount),
                            }).then(function(res){
                                console.log(res);
                            })
                        })
                    })
                }else{
                    return false
                }
            })
            
        </script>
    </head>
    <body>
        <h1>Send Transaction</h1>
        <div>
            <input type = "text" id = "recipientAddress">
            <label for = "recipientAddress">Recipient Address</span>
            <input type = "text" id = "amount">
            <label for = "amount">Amount</span>
            <button id = "send">Send</button>
        </div>
    </body>
</html>

Now we explain the code.

In line 9, we connect to MetaMask and get the address of the account. It is displayed in the browser console.

In lines 13 and 14, we read the recipient address and the amount from the input field.

For simplicity, we do not verify or validate the values. In an actual application, it is essential to check if the user input is correct.

In lines 17 to 20, we call the method sendTransaction() of our web3.js library. This method takes several input parameters. The first parameter is the sender’s address. We obtain it from the connection with MetaMask when loading the website. Then, we add the recipient and amount. There are more parameters possible like gas, gasPrice, data, nonce, chain, etc. For our purpose, we let MetaMask fill in the rest in a default manner.

MetaMask takes care of filling in the required values, signing the transaction with the private key belonging to the sender’s address and publishing it to the network.

In lines 21 and 22, we catch the promise and display it in the browser console. It should include the block hash and the transaction hash.

And that’s everything necessary to send a simple transaction with web3.js and MetaMask.

Categories: