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

相关推荐
之歆12 分钟前
HA 高可用集群指南
java·开发语言
lsx20240638 分钟前
电子商务网站主机:选择与维护指南
开发语言
专注VB编程开发20年38 分钟前
WebView2 处理跨域访问限制,Frame脚本执行,难度比CEF大10倍
前端·javascript·.net
wangluoqi1 小时前
c++ 逆元 小总结
开发语言·c++
BackCatK Chen1 小时前
第十五章 吃透C语言结构与数据形式:struct/union/typedef全解析
c语言·开发语言·数据结构·typedef·结构体·函数指针·联合体
瓦特what?1 小时前
插 入 排 序
开发语言·c++
m0_531237171 小时前
C语言-初始化赋值,函数,变量的作用域与生命周期
c语言·开发语言
Highcharts.js1 小时前
Highcharts角度仪表(Angular Gauge)完全指南:从速度表到工业监控,一文学会gauge与solidgauge实战开发
javascript·angular.js·开发文档·highcharts·图表开发·实心仪表
张3蜂1 小时前
Python venv 详解:为什么要用、怎么用、怎么用好
开发语言·python
zyeyeye1 小时前
自定义类型:结构体
c语言·开发语言·数据结构·c++·算法