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

相关推荐
洛_尘30 分钟前
JAVA EE初阶 2: 多线程-初阶
java·开发语言
@卞1 小时前
C语言常见概念
c语言·开发语言
一只小阿乐2 小时前
react 封装弹框组件 传递数据
前端·javascript·react.js
wjs20242 小时前
Eclipse 关闭项目详解
开发语言
沐知全栈开发2 小时前
《隐藏(Hide)》
开发语言
lkbhua莱克瓦242 小时前
Java基础——方法
java·开发语言·笔记·github·学习方法
533_2 小时前
[element-plus] el-tree 动态增加节点,删除节点
前端·javascript·vue.js
catchadmin2 小时前
PHP 依赖管理器 Composer 2.9 发布
开发语言·php·composer
禁止摆烂_才浅2 小时前
前端开发小技巧-【JavaScript】- 获取元素距离 document 顶部的距离
前端·javascript·react.js
wshzd2 小时前
LLM之Agent(二十九)|LangChain 1.0核心组件介绍
前端·javascript·langchain