Sending Transactions via the Ethereum Provider Object

Published by Mario Oettler on

Now we want to use the provider API directly in order to send a transaction. Therefor you need to call the method eth_sendTransaction with the transaction parameters. The code for use in a browser looks as follows:

<!DOCTYPE html>
<html>
    <head>
        <script>
            window.addEventListener("load", (event)=>{
                if(window.ethereum){

                ethereum.request({method: 'eth_requestAccounts'}).then(function(account){
                    console.log("Accounts: " + account);
                    const transactionParameters = {
                        // nonce: '0x00', // is ignored by MetaMask. MetaMas sets the correct nonce itself.
                        // gasPrice: '0x60DB88400', // optional 26 GWei, Can be customized during transaction confirmation in MetaMask
                        // gas: '0x5710', // Optional customizalbe in MetaMask during confirmation
                        to: '0x4b8415542D49726dCd46A30DceAdBaBe73c2392E', // empty if smart contract creation
                        from: account[0],
                        value: '0x8AC7230489E80000', // 10 ETH
                        data: "", //optional
                        chainId: '0x539' // currently ignored by MetaMask Mainnet, Goerli, Sepolia, Ganache, etc. 
                    };

                    ethereum.request({
                        method: "eth_sendTransaction",
                        params: [transactionParameters],
                    }).then((result) => {
                        console.log(result);
                    })
                })
                  
                }else{
                    return false
                }
            })
            
        </script>
    </head>
    <body>
        <h1>Using the Provider API</h1>
        The transaction is created and send to MetaMask as soon as the page has loaded.
        The results are written to the console.
    </body>
</html>

In the parameters, some fields are optional and some are (currently) ignored by wallets like MetaMask. Meta Mask does not consider the nonce and the chain ID, for example. The (maximum) gas amount and gas price can be adjusted in MetaMask and are optional. The data field is optional, too, and depends on what the transaction is supposed to do.

Categories: