做法
安裝 ethers 套件。
| 1
 | npm install ethers --save
 | 
引入 ethers 套件和合約介面。
| 12
 3
 
 | import { ethers } from 'ethers';import ERC20Mock from '../build/contracts/ERC20Mock.json';
 import MyStake from '../build/contracts/MyStake.json';
 
 | 
建立 Web3 提供者。
| 12
 3
 4
 
 | const web3Provider = new ethers.providers.Web3Provider(window.ethereum);
 
 web3Provider.provider.on('accountsChanged', () => {});
 
 | 
建立合約實例。
| 12
 3
 4
 5
 6
 
 | const signer = web3Provider.getSigner();
 
 const ERC20Mock = new ethers.Contract(import.meta.env.VITE_ERC20MOCK_ADDRESS, ERC20Mock.abi, signer);
 
 const MyStake = new ethers.Contract(import.meta.env.VITE_MYSTAKE_ADDRESS, MyStake.abi, signer);
 
 | 
取得錢包帳戶。
| 1
 | const [account] = await web3Provider.send('eth_requestAccounts');
 | 
取得合約中的資料。
| 12
 3
 4
 5
 6
 
 | const decimals = await ERC20Mock.decimals();
 
 const allowance = await ERC20Mock.allowance(account, MyStake.address);
 
 const balanceOf = await ERC20Mock.balanceOf(account);
 
 | 
授權 MyStake 合約使用 ERC20Mock 合約中的代幣。
| 12
 3
 
 | const amount = ethers.BigNumber.from(2).pow(256).sub(1); const res = await ERC20Mock.approve(MyStake.address, amount);
 await res.wait();
 
 |