web3简单整合react系列(四)-查看余额
app.js
import logo from './logo.svg'; import './App.css'; import Web3 from 'web3'; import React, {useEffect, useState} from 'react'; import {init, getOwnBalance} from './Web3Client' function App() { const[balance, setBalance] = useState(0); const fetchBalance = () =>{ getOwnBalance().then(balance =>{ setBalance(balance); }).catch(err =>{ }) }; return (<div className='App'> { } <p>Your balance is {balance}</p> <button onClick={() => fetchBalance()}>Refresh balance</button> </div> ); } export default App;
web3Client.js
import Web3 from 'web3'; import TestTokenContractBuild from 'contracts/TestToken.json'; let selectedAccount; let isInitialized = false; let erc20Contract; export const init = async () => { let provider = window.ethereum; const web3 = new Web3(provider); const networkId = await web3.eth.net.getId(); const erc20Abi = [ { "constant": true, "inputs": [ { "name": "_owner", "type": "address" } ], "name": "balanceOf", "outputs": [ { "name": "balance", "type": "uint256" } ], "payable": false, "stateMutability": "view", "type": "function" }, ]; erc20Contract = new web3.eth.Contract( erc20Abi,
// 对应token 的地址 '0x5592ec0cfb4dbc12d3ab100b257153436a1f0fea' ); isInitialized = true; }; export const getOwnBalance = async () => { // 初始化 if(!isInitialized) { await init(); } return erc20Contract.methods .balanceOf(selectedAccount) .call().then(balance =>{ return Web3.utils.fromWei(balance); }); };
3、运行