Chapter 8 of 9

The web page and MetaMask

Goal. Understand how a web page asks the wallet to sign, and why reading and writing differ.

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.

Analogy. The page is the waiter bringing the bill: it writes down what you want, but you apply the stamp to pay, every time, after reading the amount.

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();

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

Going deeper