diff --git a/README.md b/README.md index 5c37a5bbb..8e9c4cdf0 100644 --- a/README.md +++ b/README.md @@ -218,3 +218,16 @@ yarn add @base-org/account 1. Fork this repo and clone it 1. From the root dir run `yarn install` 1. From the root dir run `yarn dev` + + +### 🧩 connectBaseWallet Helper +A lightweight function to connect MetaMask to the Base network and return an ethers.js signer. + +**Example usage:** +```ts +import { connectBaseWallet } from "./helpers/connectBaseWallet"; +const { signer } = await connectBaseWallet(); + +### 🧠 switchToBaseNetwork +Quick helper to prompt users to switch their MetaMask network to Base Mainnet. + diff --git a/src/helpers/connectBaseWallet.ts b/src/helpers/connectBaseWallet.ts new file mode 100644 index 000000000..ea43c3bb1 --- /dev/null +++ b/src/helpers/connectBaseWallet.ts @@ -0,0 +1,21 @@ +import { ethers } from "ethers"; + +/** + * Connects MetaMask to the Base network and returns an ethers.js signer. + */ +export async function connectBaseWallet() { + if (!window.ethereum) throw new Error("MetaMask not detected"); + + const provider = new ethers.BrowserProvider(window.ethereum); + const accounts = await provider.send("eth_requestAccounts", []); + const network = await provider.getNetwork(); + + // Base mainnet chain ID = 8453 + if (network.chainId !== 8453) { + throw new Error(`Wrong network: ${network.chainId}. Please switch to Base Mainnet.`); + } + + const signer = await provider.getSigner(); + console.log("Connected to Base as:", accounts[0]); + return { provider, signer, address: accounts[0] }; +} diff --git a/src/utils/switchToBase.ts b/src/utils/switchToBase.ts new file mode 100644 index 000000000..f7d94e47d --- /dev/null +++ b/src/utils/switchToBase.ts @@ -0,0 +1,19 @@ +/** + * Requests MetaMask to switch network to Base Mainnet. + */ +export async function switchToBaseNetwork() { + if (!window.ethereum) throw new Error("MetaMask not found"); + + await window.ethereum.request({ + method: "wallet_addEthereumChain", + params: [{ + chainId: "0x2105", // 8453 + chainName: "Base Mainnet", + nativeCurrency: { name: "Ether", symbol: "ETH", decimals: 18 }, + rpcUrls: ["https://mainnet.base.org"], + blockExplorerUrls: ["https://basescan.org"] + }] + }); + + console.log("Switched to Base network ✅"); +}