首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Kovan测试网上的“无效链Id”

Kovan测试网上的“无效链Id”
EN

Ethereum用户
提问于 2021-04-22 04:29:26
回答 2查看 4.6K关注 0票数 2

我正在尝试从我的主帐户启动一个事务(ETH的传输)到Kovan上的一个测试帐户,但是我从下面的代码中得到了错误Returned error: Invalid chain id.

代码语言:javascript
复制
const Web3 = require("web3");
const EthereumTx = require("ethereumjs-tx").Transaction;

const SK = process.env.PROD ? nice try ;)
const PK = process.env.PROD ? "0x5A8721b7DE69b3538a4cC61614628f7c1A6E59Fb"
  : "0x33Bcd8bf72D594B0974beFd830a29CeC55079976";
const url = process.env.PROD ? "https://kovan.infura.io/v3/2bd0c2e1f29f4ab9b47374c6b50023c5"
  : "http://127.0.0.1:8545";

const web3Provider = new Web3.providers.HttpProvider(url);
const web3 = new Web3(web3Provider);
const { toWei, numberToHex: toHex } = web3.utils;

const sendETH = async () => {
  const nonce = await web3.eth.getTransactionCount(PK);
  const tx = new EthereumTx({
    from: PK,
    to: "0x8631c939359FBb8cb336532b191ED80b20287CD1",
    value: toHex(toWei(".1")),
    gas: toHex("21000"),
    nonce,
  });
  tx.sign(Buffer.from(SK, "hex"));
  const serializedTx = tx.serialize();
  web3.eth.sendSignedTransaction("0x" + serializedTx.toString("hex"));
}
sendETH();

当我将PROD设置为false (在本地网络上进行测试)时,它工作得很好。然而,每当我将PROD设置为true (在Kovan上测试)时,我就会遇到这个顽固的错误。

EN

回答 2

Ethereum用户

发布于 2021-04-22 07:28:58

嘿,你要在科万身上做这个测试

代码语言:javascript
复制
const tx = new EthereumTx({
    from: PK,
    chainId: 42, // kovan chain id
    to: "0x8631c939359FBb8cb336532b191ED80b20287CD1",
    value: toHex(toWei(".1")),
    gas: toHex("21000"),
    nonce,
  });
票数 2
EN

Ethereum用户

发布于 2021-04-22 09:11:37

在深入研究EthereumTx的源文件之后,我发现指定chainId和硬叉的方法是向EthereumTx构造函数中添加第二个对象。

chainId字段接受一个数字(chainId)或一个字符串(链名),它只是作为一个查询来要求该链所需的数据。此字段默认为"mainnet"

hardfork字段的工作方式类似于chainId字段,但它只处理字符串。该字段的默认设置是"petersburg"

我的解决办法如下:

代码语言:javascript
复制
const tx = new EthereumTx({
    from: PK,
    to: "0x8631c939359FBb8cb336532b191ED80b20287CD1",
    value: toHex(toWei(".0001")),
    gas: toHex("21000"),
    nonce,
  }, { chain: 42 });

非常感谢viraj在评论中给出了他的解决方案

票数 1
EN
页面原文内容由Ethereum提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://ethereum.stackexchange.com/questions/97627

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档