Using MetaMask & Ethers.js in web apps
Adding Web3 functionality to regular web browsers
ethereum
objectWe will interact with MetaMask in two ways:
.request(...)
.addListener(...)
(Also feeding it to Ethers.js)
Prompt the user to connect MetaMask to the web app
const accounts = await window.ethereum.request({
method: 'eth_requestAccounts',
});
Check which accounts the user currently allows the web app to access
const accounts = await ethereum.request({ method: 'eth_accounts' });
Event whenever accounts are changed (authorized, deauthorized, connected, switched)
ethereum.addListener('accountsChanged', (accounts) => {
// ...
});
Check out the useConnection
React hook in the example project that puts these to use
Install
$ npm install --save ethers
Import
import { ethers } from 'ethers';
Connect to MetaMask
const provider = new ethers.providers.Web3Provider(window.ethereum);
Create a contract handle
const contract = new ethers.Contract(
contractAddress,
contractAbi,
provider.getSigner(0),
);
or "ABI" for short
ABI
Description Ethers.js (or similar library) can read and know how to interact with a contract
JSON data format
Generate an ABI for a contract
$ solc --abi <path-to-contract>
or
$ solcjs --abi <path-to-contract>
For example:
$ solcjs --abi ./PyramidScheme.sol
Feed the ethers.Contract
constructor the ABI
Ethers generates proxies for each method
Calling a view method
contract.balanceOf(address);
Returns Promise<BigNumber>
Promise
- asynchronous pending result
BigNumber
- EVM deals with numbers larger than JS's built-in Number
type can precisely handle
Transactions (with optional attached ETH)
contract.signUp(recruiterAddress, {
// final `overrides` parameter
value: ethers.utils.parseEther('1'),
});
Go forth and build dApps!