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

相关推荐
比昨天多敲两行16 分钟前
linux 线程概念与控制
java·开发语言·jvm
huaweichenai25 分钟前
php 根据每个类型的抽签范围实现抽签功能
开发语言·php
codeejun2 小时前
每日一Go-73、云原生成本优化 —— 资源限制 & 指标驱动扩容
开发语言·云原生·golang
888CC++2 小时前
如何在 C 语言中进行程序调试?
前端·javascript·算法
就叫_这个吧2 小时前
Java注解、元注解、自定义注解定义及应用
java·开发语言·注解
Sam_Deep_Thinking3 小时前
聊聊Java中的of
java·开发语言·架构
kyriewen4 小时前
我招了一个“Prompt工程师”来写前端,结果项目差点崩了
前端·javascript·面试
小新1104 小时前
从零开始 Vue.js
前端·javascript·vue.js
Delicate5 小时前
JavaScript的“变脸”艺术:类型转换戏法大揭秘
javascript
前端Hardy5 小时前
21.8 万周下载!这个 React 表格组件,10 行代码就能跑起来
前端·javascript·后端