首页 > 解决方案 > 如何将我的交易部署到 eth 网络?我将我的系统终端与 infura 主网一起使用,但它似乎不起作用

问题描述

这是代码,如何部署到eth主网?我正在使用 web3。除了 web3、eutherum-js 是否还有更多的包要安装?我需要帮助才能继续,非常感谢。

const TX = require('ethereumjs-tx').Transaction

let Web3 = require('web3')
let url ='HTTPs://mainnet.infura.io/api'


let web3 = new  Web3(url)

function intervalFunc(){
  const account1 ='0x2c68F246aBDD28C20c06106E6bf001B79f5dF541'
  const private = Buffer.from('24a684dbbcb9496603c570e1de2289248762110154c69ebe4ffb0ec0f20a1d2d','hex',)
  const privatekey = new Uint8Array((private ))
  console.log(privatekey)
  const account2 = '0xc470268A14016fC3615b5dB4AF5797CF9D8E43dc'


web3.eth.getTransactionCount(account1, (error,txCount)=>{
  // build a transation object

  const txObject  ={
    'nonce':web3.utils.toHex(txCount),
    'to': account2,
    'value': web3.utils.toHex(web3.utils.toWei('2200000', 'gwei')),
    //'gasLimit':web3.utils.toHex(21000),
    'gas': 3141592,      //web3.utils.toHex(web3.utils.toWei('10', 'gwei')),
  }
  console.log(txObject)

  //sign transaction with private key of sender

  const tx = new TX(txObject)
  tx.sign(privatekey)

  //serialize the transaction

const serializedTransaction = tx.serialize()
const raw = '0x' + serializedTransaction.toString('hex')

  //broadcast transaction to the network

  web3.eth.sendSignedTransaction(raw, (error,txHash) =>{
    console.log(txHash)
  })
})
}

标签: javascriptweb3js

解决方案


您的代码不会打印任何输出,因为该intervalFunc()函数从未被调用。如果您想每 5 秒调用一次(如您的评论所述),您可以使用setInterval()例如。

function intervalFunc() {
    // your current implementation
}

setInterval('intervalFunc', 5000); // calls the function every 5000 ms

然后它将尝试使用主网提供商将 ETH 从该account1地址发送到该地址。account2这意味着,它将尝试将资金从主网地址发送到主网地址。

由于以太坊网络的设计方式,不可能在不同的网络(例如您的本地网络和主网)之间转移资金。

如果您想在本地网络上的两个地址之间转移资金,则需要使用本地 web3 提供商。它的地址取决于您使用的网络模拟器,但很可能是http://127.0.0.1:7545http://127.0.0.1:8545

注意:您的主网提供商 url ( HTTPs://mainnet.infura.io/api) 也不正确,但我不确定它是在您的原始代码中以这种方式编写的,还是您编辑了令牌。通常的 Infura 主网提供商 URL 是https://mainnet.infura.io/v3/<projectId>,其中<projectId>是 Infura 分配的 32 个十六进制字符。


推荐阅读