web3简单整合react系列-发起交易(三)
1、app.js
import logo from './logo.svg'; import './App.css'; //import './polyfill.js'; import Web3 from 'web3'; import React, {useEffect, useState} from 'react'; import {init, mintToken} from './Web3Client' function App() { const [minted, setMinted] = useState(false); const mint = () =>{ mintToken().then((tx) =>{ console.log(tx); setMinted(true); }).catch((err) => { console.log(err); }); }; return <div className='App'> { !minted ?<button onClick={() => mint()}>Mint token</button> :<p>Token minted successfully!</p> } </div>; } export default App;
2、web3clint
import Web3 from 'web3'; import TestTokenContractBuild from 'contracts/TestToken.json'; let selectedAccount; let testTokenContract; let isInitialized = false; //'../truffle/build/contracts/TestToken.json'; export const init = async () => { let provider = window.ethereum; if(typeof provider !== 'undefined'){ provider .request({method: 'eth_requestAccounts'}) .then(accounts =>{ selectedAccount = accounts[0]; console.log(`Selected Account is ${selectedAccount}$`); }).catch((err)=>{ console.log(err); }); // 监听metamask 账号改变 window.ethereum.on('accountsChanged', function(accounts){ selectedAccount = accounts[0]; console.log(`Selected Account is ${selectedAccount}$`); }); } const web3 = new Web3(provider); const networkId = await web3.eth.net.getId(); testTokenContract = new web3.eth.Contract( TestTokenContractBuild.abi, //TestTokenContractBuild.networks[networkId].address '0x15ab7f6ADF501971fdC5AEb4934a52A20104f8A2' ); isInitialized = true; }; export const mintToken = async () => { if(!isInitialized) { await init(); } return testTokenContract.methods .mint(selectedAccount) .send({from:selectedAccount} ); };
3、修改 package.json,加上如下
4、运行
点击 mint,