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

相关推荐
久绊A5 分钟前
Hydra-SSH 破解安全防范
开发语言·php
阿昭L12 分钟前
c++中获取随机数
开发语言·c++
3壹18 分钟前
数据结构精讲:栈与队列实战指南
c语言·开发语言·数据结构·c++·算法
悟乙己27 分钟前
使用 Python 中的强化学习最大化简单 RAG 性能
开发语言·python·agent·rag·n8n
max50060031 分钟前
图像处理:实现多图点重叠效果
开发语言·图像处理·人工智能·python·深度学习·音视频
Jedi Hongbin1 小时前
Three.js shader内置矩阵注入
前端·javascript·three.js
RickyWasYoung1 小时前
【代码】matlab-遗传算法工具箱
开发语言·matlab
掘金安东尼2 小时前
Node.js 如何在 2025 年挤压 I/O 性能
前端·javascript·github
得物技术2 小时前
前端日志回捞系统的性能优化实践|得物技术
前端·javascript·性能优化
ZKshun2 小时前
[ 前端JavaScript的事件流机制 ] - 事件捕获、冒泡及委托原理
javascript