ethereum - 以太坊交易给出错误“无效发件人”
问题描述
我的合同是这样的——
pragma solidity >=0.4.25 <0.8.0;
contract Calculator {
uint public result;
event Added(address caller, uint a, uint b, uint res);
constructor() public {
result = 777;
}
function add(uint a, uint b) public returns (uint, address) {
result = a + b;
emit Added(msg.sender, a, b, result);
return (result, msg.sender);
}
}
上述合约部署在 Ropsten 测试网上。我正在尝试add(...)
使用事务调用该函数。我的代码看起来像这样 -
const accountAddress = rtUtil.getAccountAddress();
const accountPk = Buffer.from(rtUtil.getAccountAddressPk(), "hex");
const contract = await rtUtil.getCalculatorContract();
const data = contract.methods.add(3, 74).encodeABI();
const web3 = rtUtil.getWeb3();
const taxCount = await web3.eth.getTransactionCount(accountAddress);
const txObject = {
nonce: web3.utils.toHex(taxCount),
to: rtUtil.getCalculatorContractAddress(),
value: web3.utils.toHex(web3.utils.toWei('0', 'ether')),
gasLimit: web3.utils.toHex(2100000),
gasPrice: web3.utils.toHex(web3.utils.toWei('6', 'gwei')),
data: data
};
const commmon = new Common({chain: "ropsten", hardfork: "petersburg"});
const tx = Transaction.fromTxData(txObject, {commmon});
tx.sign(accountPk);
const serializedTx = tx.serialize();
const raw = web3.utils.toHex(serializedTx);
const transaction = await web3.eth.sendSignedTransaction(raw);
当我运行代码时,我得到错误 -
Uncaught Error: Returned error: invalid sender
Process exited with code 1
我的 Nodejs 版本是v15.1.0
我的package.json
依赖是 -
"dependencies": {
"@ethereumjs/common": "^2.0.0",
"@ethereumjs/tx": "^3.0.0",
"@truffle/contract": "^4.2.30",
"@truffle/hdwallet-provider": "^1.2.0",
"web3": "^1.3.0"
}
谁能告诉我我做错了什么?
提前致谢。
解决方案
在您的 txObject 中,您需要指定链 id。
将 Ropsten 的链 id,3 添加到 txObject 中。
const txObject = {
nonce: web3.utils.toHex(taxCount),
to: rtUtil.getCalculatorContractAddress(),
value: web3.utils.toHex(web3.utils.toWei('0', 'ether')),
gasLimit: web3.utils.toHex(2100000),
gasPrice: web3.utils.toHex(web3.utils.toWei('6', 'gwei')),
data: data,
chainId: web3.utils.toHex(3)
};
推荐阅读
- android - 要求启用企业帐户的 Google MAP API 密钥
- c++ - Visual Studio CMake 项目和 WSL 中的源同步
- c# - 在 C# 程序中,程序何时完成执行?
- android - Android Studio CMakeLists 错误:未定义的引用
- java - 带有thymeleaf和spring的注销链接
- .net-core - .net core signalR,用户离开组时如何知道组名
- r - 为什么 rbind 在尝试合并两个矩阵时表现得很奇怪?
- c# - 无法使用派生类实现属性
- postgresql - Postgres:即使授予了授权,也拒绝架构的权限
- php - password_verify 在另一台服务器上创建的密码失败