SolidityIn

Connecting a wallet with ethers.js

Lesson 29 of 40 · Frontends

A frontend talks to the blockchain through a provider. In the browser, a wallet extension such as MetaMask injects an object called window.ethereum. The ethers.js library wraps it so you can read data and ask the user to sign transactions. These examples use ethers version 6.

ethers has two main objects. A Provider is read-only: it can fetch balances and call view functions. A Signer represents the connected account and can send transactions, so each action needs the user's approval in the wallet.

Ask the wallet for access with eth_requestAccounts, and only after a click, not on page load. Also check the chain ID, because a user on the wrong network would send transactions somewhere you did not intend.

To call a contract you need its address and its ABI, the list of its functions. The compiler produces the ABI, and for simple cases you can write a human-readable ABI as an array of strings, as below.

import { BrowserProvider, Contract, formatEther } from "ethers";

const abi = [
  "function count() view returns (uint256)",
  "function increment()"
];
const address = "0xYourContractAddress";

async function connect() {
  const provider = new BrowserProvider(window.ethereum);
  await provider.send("eth_requestAccounts", []);
  const signer = await provider.getSigner();
  const net = await provider.getNetwork();
  if (net.chainId !== 11155111n) throw new Error("Switch to Sepolia");

  const counter = new Contract(address, abi, signer);
  const value = await counter.count();          // free read
  console.log("Count:", value.toString());
  console.log("Balance:", formatEther(await provider.getBalance(signer.address)));
  return counter;
}

Try it yourself

Deploy the Counter contract to Sepolia from Remix, put its address in this code, and add it to a web page with a Connect button.

Quick check: Which ethers object represents the account that approves transactions?