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

相关推荐
哈哈不让取名字5 分钟前
分布式日志系统实现
开发语言·c++·算法
3GPP仿真实验室5 分钟前
【MATLAB源码】6G:感知辅助毫米波 MIMO 信道估计仿真平台
开发语言·matlab·智能电视
catchadmin19 分钟前
Laravel12 + Vue3 的免费可商用 PHP 管理后台 CatchAdmin V5.1.1 发布
开发语言·php
编程(变成)小辣鸡36 分钟前
JVM、JRE和JDK 的关系
java·开发语言·jvm
a程序小傲1 小时前
得物Java面试被问:流批一体架构的实现和状态管理
java·开发语言·数据库·redis·缓存·面试·架构
xb11321 小时前
C#异步编程入门概念及核心概念
开发语言·c#
黎雁·泠崖1 小时前
Java继承:成员变量访问(就近原则+this/super用法)
java·开发语言
摘星编程1 小时前
React Native + OpenHarmony:Modal确认取消弹窗
javascript·react native·react.js
ShineWinsu1 小时前
对于C++:模版初阶的解析
开发语言·c++·面试·笔试·函数··模版