web3.js + Ganache 模拟以太坊账户间转账

转账前:

转账后:

javascript 复制代码
async function interact() {
  const web3 = new Web3(
    new Web3.providers.HttpProvider('http://127.0.0.1:7545')
  )
  web3.eth.Contract.handleRevert = true
  const accounts = await web3.eth.getAccounts()

  console.log(accounts)

  let balance1, balance2

  balance1 = await web3.eth.getBalance(accounts[0])

  balance2 = await web3.eth.getBalance(accounts[1])

  console.log(balance1, web3.utils.fromWei(balance1, 'ether'))
  console.log(balance2, web3.utils.fromWei(balance2, 'ether'))

  const transaction = {
    from: accounts[0],

    to: accounts[1],

    value: web3.utils.toWei('1', 'ether'),
  }

  const transactionHash = await web3.eth.sendTransaction(transaction)

  console.log('transactionHash', transactionHash)

  balance1 = await web3.eth.getBalance(accounts[0])

  balance2 = await web3.eth.getBalance(accounts[1])

  console.log(balance1, web3.utils.fromWei(balance1, 'ether'))
  console.log(balance2, web3.utils.fromWei(balance2, 'ether'))

  // const gasPrice = await web3.eth.getGasPrice()

  // console.log('gasUsed', transactionHash.gasUsed)
  // console.log('价格', web3.utils.fromWei(gasPrice, 'ether'))
  let total =  transactionHash.effectiveGasPrice * transactionHash.gasUsed + balance1 + balance2
  console.log('total', total)

  const block = await web3.eth.getBlockNumber()

  console.log('Last block:', block)
}

人工智能学习网站

https://chat.xutongbao.top

相关推荐
ProgramHan1 小时前
Web3革命——区块链技术重构数字世界的技术逻辑与产业未来
重构·web3·区块链
264玫瑰资源库2 小时前
问道数码兽 怀旧剧情回合手游源码搭建教程(反查重优化版)
java·开发语言·前端·游戏
普if加的帕2 小时前
java Springboot使用扣子Coze实现实时音频对话智能客服
java·开发语言·人工智能·spring boot·实时音视频·智能客服
拉不动的猪2 小时前
前端自做埋点,我们应该要注意的几个问题
前端·javascript·面试
安冬的码畜日常3 小时前
【AI 加持下的 Python 编程实战 2_10】DIY 拓展:从扫雷小游戏开发再探问题分解与 AI 代码调试能力(中)
开发语言·前端·人工智能·ai·扫雷游戏·ai辅助编程·辅助编程
烛阴3 小时前
Node.js中必备的中间件大全:提升性能、安全与开发效率的秘密武器
javascript·后端·express
dapp04023 小时前
Web3中心化交易所钱包-批量地址生成业务
web3
小杨升级打怪中3 小时前
前端面经-JS篇(三)--事件、性能优化、防抖与节流
前端·javascript·xss
电报号dapp1193 小时前
Web3实战:从零开发你的ERC20代币合约
web3·去中心化·区块链·智能合约
朝阳5813 小时前
Rust项目GPG签名配置指南
开发语言·后端·rust