1.判断浏览器有没有ethereum这个属性
import { ethers } from 'ethers' // 导入ethers
// 判断有没有ethereum
if(window.ethereum){ // 有的话执行连接操作
const provider = new ethers.BrowserProvider(window.ethereum); // 连接metamask
const signer = await provider.getSigner(); // 获取signer signer里面含有地址
}else{ // 没有的话可以让其跳转到官网下载
window.open('xxx')
}
像MetaMask这些钱包这都会往浏览器注入一个对象
比如:
MetaMask: "ethereum",
BitKeep: "bitkeep.ethereum",
TokenPocket: "ethereum.isTokenPocket",
2.provider是只读,signer可以进行链上操作
// 查询主网币余额
const getBalanceF = async (address: string) => {
try {
const balance = await provider.getBalance(address);
return balance;
} catch (e) {
console.log('函数错误',e)
}
};
// 签名消息
const sigMessageF = async (message: string) => {
try {
const sigMessage = await signer.signMessage(message);
return sigMessage;
} catch (e) {
console.log('函数错误',e)
}
};
// 发送交易(主网币)
const transferAccountsF = async (
address: string,
money: number,
decimals: number = 18
) => {
try {
const {hash} = await signer.sendTransaction({
to: address,
value: parseUnits(money.toString(), decimals),
});
return hash;
} catch (e) {
console.log('函数错误',e)
}
};
3.ethers new出合约
const address = '' // 合约地址
const abi = require('') // abi
const contract = new ethers.Contract(address, abi, signer); // new 出合约
以上就是连接metamask小狐狸钱包都操作,new出合约你就可以调用合约函数