Skip to main content

Browser 端使用示例

React 推荐使用的第三方库

通过 metamask API 交互

连接 metamask

async function connectWallet() {
const accounts = await window.ethereum.request({ method: 'eth_requestAccounts' })
console.log({ accounts })

通过 metamsk 转账 ETH

function sendETH() {
const provider = new ethers.providers.Web3Provider(window.ethereum)
const signer = provider.getSigner()
to: "",
value: utils.parseEther('0.1')

metamask 调用合约

// You can also use an ENS name for the contract address
const daiAddress = "dai.tokens.ethers.eth";

// The ERC-20 Contract ABI, which is a common contract interface
// for tokens (this is the Human-Readable ABI format)
const daiAbi = [
// Some details about the token
"function name() view returns (string)",
"function symbol() view returns (string)",

// Get the account balance
"function balanceOf(address) view returns (uint)",

// Send some of your tokens to someone else
"function transfer(address to, uint amount)",

// An event triggered whenever anyone transfers to someone else
"event Transfer(address indexed from, address indexed to, uint amount)"

// The Contract object
const daiContract = new ethers.Contract(daiAddress, daiAbi, provider);