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

相关推荐
淼淼7633 分钟前
QT表格与数据
开发语言·qt
smile_Iris3 分钟前
Day 38 GPU训练及类的call方法
开发语言·python
NuLL10 分钟前
全场景智能克隆工具:超越 JSON.parse(JSON.stringify())
javascript
编程小Y10 分钟前
Vue 3 + Vite
前端·javascript·vue.js
认真敲代码的小火龙31 分钟前
【JAVA项目】基于JAVA的养老院管理系统
java·开发语言·课程设计
AI科技星33 分钟前
统一场论质量定义方程:数学验证与应用分析
开发语言·数据结构·经验分享·线性代数·算法
扶苏-su33 分钟前
Java---事件处理机制
java·开发语言
小灰灰搞电子37 分钟前
Qt 实现炫酷锁屏源码分享
开发语言·qt·命令模式
电饭叔1 小时前
TypeError:unsupported operand type(s) for -: ‘method‘ and ‘int‘
开发语言·笔记·python
zfj3211 小时前
排查java应用内存溢出的工具和方法
java·开发语言·jvm·内存溢出