🔹 1. Setup & Imports

import { ethers } from "ethers";


🔸 2. Provider (for read-only access)

// Browser wallet (MetaMask)
const provider = new ethers.providers.Web3Provider(window.ethereum);

// Backend or custom RPC
const provider = new ethers.providers.JsonRpcProvider("<https://rpc-url>");

Method Description
provider.getNetwork() Returns chain info (name, chainId)
provider.getBlockNumber() Latest block number
provider.getBalance(address) ETH balance of address
provider.getGasPrice() Current gas price
provider.getTransaction(txHash) Get tx details
provider.getCode(address) Get bytecode of a contract
provider.waitForTransaction(txHash) Wait for tx confirmation

🔸 3. Signer (to send transactions / sign data)

const signer = provider.getSigner(); // from MetaMask

Method Description
signer.getAddress() Get connected wallet address
signer.sendTransaction(tx) Send raw ETH transaction
signer.signMessage("msg") Sign a message
signer._signTypedData(domain, types, value) EIP-712 typed data signing
signer.connect(provider) Connect signer to another provider

🔸 4. Wallet (Backend or test wallet)

const wallet = new ethers.Wallet(privateKey, provider);


🔸 5. Contract (interacting with smart contracts)

const contract = new ethers.Contract(contractAddress, abi, signerOrProvider);

Method Description
contract.functionName(...args) Read/write function call
contract.callStatic.functionName(...) Simulate function (no state change)
contract.estimateGas.functionName(...) Estimate gas
contract.populateTransaction.functionName(...) Prepare tx but don't send
contract.connect(signer) Connect contract to new signer
contract.deploy() Deploy new contract (from factory)

🔸 6. Contract Events