Chapter 8 of 9
The web page and MetaMask
The web page is the shop window: it shows the price and lets you buy and sell. But it does not hold your key, and must not. When it connects, MetaMask injects into the page an object called window.ethereum through which the page can ask; the last word stays with the wallet.
Reading and writing
Reading (for example the price or your balance) changes nothing on the blockchain: it is free and needs no signature. Writing (buying, selling) changes the state: it needs a signature and a small network fee (in test POL). In Solidity, read functions are marked view.
import { BrowserProvider, Contract, parseEther } from "ethers";
const provider = new BrowserProvider(window.ethereum);
await provider.send("eth_requestAccounts", []);
const signer = await provider.getSigner();
const abi = [
"function quoteBuy(uint256 polWei) view returns (uint256)",
"function buy() payable",
];
const token = new Contract(TOKEN_ADDRESS, abi, signer);
const fuel = await token.quoteBuy(parseEther("1"));
const tx = await token.buy({ value: parseEther("1") });
await tx.wait();
BrowserProviderconnects the library to the wallet in the browser (window.ethereum).eth_requestAccountsopens the MetaMask window: the user chooses whether to connect.getSigneris "who signs": the connected account.abilists the two functions used;tokencombines address, list and signer.quoteBuyis a read: it returns the tokens you would get, with no signature.token.buy({ value: ... })is a write: it sends 1 POL (parseEtherconverts it to units of 10-18) and MetaMask asks for confirmation.tx.wait()waits for the transaction to enter a block.
The project uses the wagmi and viem libraries, handier in a React app, but the mechanism is the same. The project's page also offers to switch network to Polygon Amoy, and without a wallet it still shows prices and history.
Try it
Open the browser console (F12) on any page with MetaMask installed and type typeof window.ethereum: if it answers "object", the page can talk to your wallet.
What you learned
- The page does not hold your key: it asks, and MetaMask signs after your confirmation.
- Reading is free and needs no signature; writing changes state and needs a signature and a fee.
window.ethereumis the bridge between page and wallet.