我正在尝试从我的主帐户启动一个事务(ETH的传输)到Kovan上的一个测试帐户,但是我从下面的代码中得到了错误Returned error: Invalid chain id.:
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上测试)时,我就会遇到这个顽固的错误。
发布于 2021-04-22 07:28:58
嘿,你要在科万身上做这个测试
const tx = new EthereumTx({
from: PK,
chainId: 42, // kovan chain id
to: "0x8631c939359FBb8cb336532b191ED80b20287CD1",
value: toHex(toWei(".1")),
gas: toHex("21000"),
nonce,
});发布于 2021-04-22 09:11:37
在深入研究EthereumTx的源文件之后,我发现指定chainId和硬叉的方法是向EthereumTx构造函数中添加第二个对象。
chainId字段接受一个数字(chainId)或一个字符串(链名),它只是作为一个查询来要求该链所需的数据。此字段默认为"mainnet"。
hardfork字段的工作方式类似于chainId字段,但它只处理字符串。该字段的默认设置是"petersburg"。
我的解决办法如下:
const tx = new EthereumTx({
from: PK,
to: "0x8631c939359FBb8cb336532b191ED80b20287CD1",
value: toHex(toWei(".0001")),
gas: toHex("21000"),
nonce,
}, { chain: 42 });非常感谢viraj在评论中给出了他的解决方案
https://ethereum.stackexchange.com/questions/97627
复制相似问题