Me On IT
Published on

MetaMask and More

Authors

I had the idea to integrate MetaMask into this blog, and this is what came out of it ...

Now, I'll briefly and concisely describe how I went about it.

The goal was to use the JavaScript library Ethers v6 to communicate with the Ethereum network.

So, it was about integrating MetaMask as a so-called BrowserProvider, as this is the key object through which Ethers connects to the Ethereum network.

And how do I now get such a BrowserProvider?

First, MetaMask injects itself into the DOM through a reference: window.ethereum. However, this proxy object can also be used by other browser extensions, e.g., the Brave Wallet of the Brave Browser.

Now that we know how to access MetaMask via JavaScript, it's just a matter of building the bridge to Ethers. It's as simple as this:

provider = new ethers.BrowserProvider(window.ethereum)

And if window.ethereum is not set, we set:

provider = new ethers.getDefaultProvider('mainnet')

The DefaultProvider is a read-only implementation of this interface, only intended to enable a few read accesses to the Ethereum network when no plugin is available in the browser.

So far so good -- so simple! It gets interesting when we want to use Ethers, and thus MetaMask, on a real website. But you'll learn about that in the next post.