React:Dapp开发-钱包简单操作
2022-07-22 本文已影响0人
精神病患者link常
参考文档:
https://docs.ethers.io/v5/getting-started/#installing
https://docs.metamask.io/guide/
实现功能
- 连接钱包并获取地址
- 获取钱包余额
- 添加或切换链(HECO为例)
- 添加代币(CAKE为例)
- 获取钱包内币的余额(USDT为例)
- 授权,合约可对币操作数量(USDT为例)
- 调用合约方法
- 获取各种币价
安装 ethers
库
yarn add ethers
1. 连接钱包并获取地址
export const ethereum = (window as any).ethereum;
function onConnectWallert(){
if (typeof ethereum === 'undefined') {
console.log('MetaMask is uninstall!');
return
}
ethereum.request({method: 'eth_requestAccounts'})
.then((res: any) => {
console.log('res==',res);
setAccount(res[0])
}).catch((err: any) => {
console.log('err==',err);
})
}
2. 获取钱包余额
import { formatUnits, parseUnits } from 'ethers/lib/utils';
async function getBalance(){
const balance:BigNumber = await provider.getBalance(account)
const balanceString = formatUnits(balance)
const balanceBigNumber = parseUnits(balanceString)
setBalance(balanceString)
}
3. 添加或切换链(HECO为例)
function onChangeToHECO(){
ethereum.request({
method: 'wallet_addEthereumChain',
params: [
{
chainId: BigNumber.from(128).toHexString(),
chainName: 'heco',
nativeCurrency: {
name: 'HT',
symbol: 'HT', // 2-6 characters long
decimals: 18
},
rpcUrls: ['https://http-mainnet.hecochain.com/'],
blockExplorerUrls: ['https://www.hecochain.com/']
}
]
}).then((res: any) => {
//添加成功
}).catch((err: any) => {
//添加失败
})
4. 添加代币(CAKE为例)
function onAddCoin(){
ethereum
.request({
method: 'wallet_watchAsset',
params: {
type: 'ERC20',
options: {
address: '0x0E09FaBB73Bd3Ade0a17ECC321fD13a19e81cE82',
symbol: 'CAKE',
decimals: 18,
image: 'https://assets-cdn.trustwallet.com/blockchains/smartchain/assets/0x0E09FaBB73Bd3Ade0a17ECC321fD13a19e81cE82/logo.png',
},
},
})
.then((success:boolean) => {
if (success) {
console.log('CAKE successfully added to wallet!');
} else {
throw new Error('Something went wrong.');
}
})
.catch(console.error);
}
5. 获取钱包内币的余额(USDT为例)
const provider = new ethers.providers.Web3Provider(ethereum)
async function getABIContract(){
// 合约地址 合约 provider or signer
// 如果是视图(View)方法,只是进行数据的读取,传入Provider就可以
// 如果需要更改合约状态,需要用户签名,则需要传入Signer。
// usdt bsc的地址 ERC20_ABI
const usdtContract = new ethers.Contract('0x55d398326f99059fF775485246999027B3197955', ERC20_ABI, provider);
const usdtBalance:BigNumber = await usdtContract.balanceOf(account)
const usdtBalanceString = formatUnits(usdtBalance)
console.log('usdtBalanceString==',usdtBalanceString);
setUsdtBalance(usdtBalanceString)
}
6. 授权,合约可对币操作数量(USDT为例)
function onApprove(){
// 币对合约进行授权,设置合约可以操作币的数量
const usdtContract = new ethers.Contract('0x55d398326f99059fF775485246999027B3197955', ERC20_ABI, provider.getSigner());
// 合约地址 币的数量(BigNumber)
usdtContract.approve('0x532A51643A057A307983aA90282F30c1490f14cC',BigNumber.from(1).then((res:any)=>{
console.log('res==',res);
})
7. 调用合约方法
const heroBoxContract = new ethers.Contract('0x532A51643A057A307983aA90282F30c1490f14cC', HeroBox_ABI, provider);
await heroBoxContract.abc(...)
8. 获取各种币价
function getCoinPrice(){
axios.get('https://min-api.cryptocompare.com/data/pricemultifull?fsyms=BTC,ETH&tsyms=USD').then((res:any)=>{
console.log('res===',res);
})
}