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

相关推荐
进击的尘埃1 小时前
拖拽搭建场景下的智能布局算法:栅格吸附、参考线与响应式出码
javascript
小猪努力学前端1 小时前
基于PixiJS的试玩广告开发-续篇
前端·javascript·游戏
wuhen_n2 小时前
v-model 的进阶用法:搞定复杂的父子组件数据通信
前端·javascript·vue.js
wuhen_n2 小时前
TypeScript 深度加持:让你的组合式函数拥有“钢筋铁骨”
前端·javascript·vue.js
滕青山2 小时前
基于 ZXing 的 Vue 在线二维码扫描器实现
前端·javascript·vue.js
swipe2 小时前
深入理解 JavaScript 中的 this 绑定机制:从原理到实战
前端·javascript·面试
兆子龙3 小时前
前端哨兵模式(Sentinel Pattern):优雅实现无限滚动加载
前端·javascript·算法
豆苗学前端3 小时前
彻底讲透浏览器渲染原理,吊打面试官
前端·javascript·面试
进击的尘埃3 小时前
可视化搭建引擎的撤销重做系统:Command 模式 + Immutable 快照实现操作历史树
javascript
Hilaku5 小时前
在 HTTP/3 普及的 2026 年,那些基于 Webpack 的性能优化经验,有一半该扔了
前端·javascript·面试