赞
踩
npm install -g ganache-cli
ganache-cli
ganache-cli <选项>
启动参数,去官网查看 https://www.npmjs.com/package/ganache-cli/v/6.4.2
不带启动参数,系统会默认生成10个账户
地址:127.0.0.1:8545
npm install web3
https://www.npmjs.com/package/web3
// 获取账户以及余额 import React, {useState, useEffect} from 'react' var Web3 = require('web3'); var web3 = new Web3(new Web3.providers.HttpProvider('http://localhost:8545')); export default function Demo3() { const [accounts, setAccounts] = useState([]) const [balanceMap, setBalanceMap] = useState([]) /** * 获取所有账户 */ const getAccounts = () => { web3.eth.getAccounts().then((_accounts = []) => { setAccounts(_accounts) getBalance(_accounts) }) } /** * 获取所有账户的余额 * @param accounts */ const getBalance = (accounts) => { const balanceMap = {} let c = accounts.length accounts.map(account => { web3.eth.getBalance(account).then(balance => { balanceMap[account] = web3.utils.fromWei(balance, 'ether') if (--c === 0) { setBalanceMap(balanceMap) } }) }) } useEffect(() => { getAccounts() }, []) return ( <div> <div> <table border="1"> <tr> <th>账户</th> <th>余额</th> </tr> { accounts.map((it, idx) => <tr key={idx}> <td>{it}</td> <td>{balanceMap[it]}</td> </tr>) } </table> </div> </div> ) }
转账
/** * 转账 */ const transfer = (_from,_to,balance) => { web3.eth.sendTransaction({ from:_from, to:_to, value:balance },function(error,result){ console.log(result); // 查看交易 viewTransactions(result) getAccounts() }) } transfer(accounts[0], accounts[accounts.length -2], web3.utils.toHex(web3.utils.toWei("3")))
创建账号
/**
* 创建账号
*/
const createAccount = (password) => {
web3.eth.personal.newAccount(password,function(error,result){
console.log(result);
getAccounts()
});
}
解锁账号
/**
* 解锁账号
*/
const unlockAccount = (addr,password) => {
web3.eth.personal.unlockAccount(addr,password,function(error,result){
console.log(result);
})
}
查看交易
/**
* 查看交易
* @param transactionHash
*/
const viewTransactions = (transactionHash) => {
web3.eth.getTransactionReceipt(transactionHash,function (err, result) {
if (err == null) {
console.log('transaction:', result);
} else {
console.log('error:', err);
}
})
}
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。