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

相关推荐
xiaoshuaishuai86 小时前
C# DeepSeek V4 与 V3对比
开发语言·c#·量子计算
bluetata7 小时前
AI 浪潮与破局:TypeScript 生态实战,让 AI 为你所用
javascript·人工智能·typescript
shehuiyuelaiyuehao7 小时前
算法18,二分查找
java·开发语言·算法
IT策士7 小时前
Python mcp研究:入门到精通
开发语言·python·qt
布局呆星7 小时前
Vue Router 核心知识点梳理
前端·javascript·vue.js
罗技1237 小时前
告别“兼容模式“:Easysearch 有了自己的官方 Python 客户端
开发语言·python
weixin_446729167 小时前
java网络通讯
java·开发语言
IT策士7 小时前
Python 常见的设计模型:入门到精通
开发语言·python
不会写DN7 小时前
如何通过 Python 实现招聘平台自动投递
开发语言·前端·python
JiaWen技术圈7 小时前
增量静态再生(ISR)详解:Next.js 中的实现与应用
javascript·git·ubuntu