DEV Community

ismaventuras
ismaventuras

Posted on

Interacting with Metamask using vanilla Javascript

When I first started using Metamask I wondered how applications could ask me to connect the extension or sign transactions. In this thread I will talk about how to control Metamask using code.

In the browser we have an object called window which allows us to access its properties, such as the size of the screen or the storage of cookies. What Metamask does is add or inject a new property called ethereum.

To connect we use the request function and as arguments the eth_requestAccounts method and an empty list of parameters.The next snippet asks to connect Metamask and shows the account on the screen. If it is not installed or if the request is cancelled, it will show an error.

Image description

The request method allows us to request information from the blockchain using the node we have in Metamask. The eth_requestAccounts method is defined in EIP1102 and is the standard way to connect a user to a dApp. But we can not only do that.

We can also extract information such as the ether balance from a wallet, the chainId or the last block of the blockchain selected in Metamask, among others. We can find all these methods in the Ethereum documentation. https://ethereum.github.io/execution-apis/api-documentation/

Note that these methods send their response encoded in hexadecimal. F.e, if we use eth_blockNumber to know the number of the last block, it will return something similar to this: 0x1cc57e6. The following snippet shows how to convert the value to base 10.

Image description

From here you just have to follow the official documentation of both Ethereum and Metamask to continue advancing, in the same way that we ask for information we can also send transactions, although you have to sign them first, but I'll leave that for another day.

I have made a small demo that you can see in the following link, the web asks to connect using Metamask to then show both the chain and the wallet information.

https://jsfiddle.net/ismaventuras/8kgvu4e2/4/

Top comments (0)