如何解决错误:返回错误:eth_sendTransaction 方法不存在
我正在尝试使用此代码将 erc20token 从合约地址转移到 eth 地址:
var _from = "from Address";
var contAddress = "contract address";
var _to = "to address";
var _Amount = '50';
var txnObject = {
"from":_from,"to": _to,"value": web3.utils.toWei(_Amount,'ether'),// "gas": 21000,(optional)
// "gasPrice": 4500000,(optional)
// "data": 'For testing' (optional)
// "nonce": 10 (optional)
}
web3.eth.sendTransaction(txnObject,function(error,result){
if(error){
console.log( "Transaction error",error);
}
else{
var txn_hash = result; //Get transaction hash
//$('#Tx').text(txn_hash);
alert(txn_hash);
}
});
但我收到此错误:
Transaction error Error: Returned error: The method eth_sendTransaction does not exist/is not available
我搜索了很多搜索并尝试了此代码,但没有奏效。可能是什么原因?这段代码是错误的还是别的什么?
注意:我使用的是 infura ropsten 网络节点。
解决方法
除了错误消息外,还有一些其他问题与您的问题相关。
让我们从错误消息开始。
eth_sendTransaction 方法不存在/不可用
eth_sendTransaction()
当您希望您的节点为您签署交易(使用 ulocked 帐户)时使用。但是您连接到不支持此方法的节点。很可能是 Infura 或其他第三方节点提供商,它们不会为您持有您帐户的私钥。
因此,您需要在您的应用程序上签署交易,然后将签署的交易广播到您的节点。实现这一目标的方法很少。
例如,您可以使用 web3.eth.signTransaction() 对 tx 进行签名,然后使用 web3.eth.sendSignedTransaction() 将(已签名的)tx 提交到您的节点。
或者您可以使用 accounts.wallet.add()
方法,然后使用 Contract 实例 send()
方法 - 请参阅答案的中间部分。
您的代码段创建了常规的 ETH 转移 - 它不会创建令牌转移。
您可以使用 Web3 Contract 方法来帮助您构建传输 ERC-20 代币的交易。
// this is one of the other ways to sign a transaction on your end
web3.eth.accounts.wallet.add(privateKeyToTheSenderAddress);
// for this case,you can use a generic ERC-20 ABI JSON interface
const myContract = new web3.eth.Contract(jsonInterface,contractAddress);
// invoke the `transfer()` method on the contract
// sign it using the private key corresponding to the `senderAddress`
// and broadcast the signed tx to your node
myContract.methods.transfer(toAddress,amount).send({from: senderAddress});
我不确定这是否只是问题的措辞不正确,还是逻辑错误。但是你不能转让属于合约的代币,除非合约代码允许你这样做。
为什么?因为你需要发件人的私钥才能转移他们的代币。这是因为 transfer()
方法通常是如何构建的:
function transfer(address _to,uint256 _amount) external returns (bool) {
balances[msg.sender] -= _amount; // decreases balance of the transaction sender
// ...
}
交易发送者需要使用他们的私钥签署交易。如果您希望发送方成为合约(以减少合约的代币余额),则需要拥有其私钥。你没有(实际上不可能知道合约的私钥)。
但如果交易发送方是授权地址,也许您的合同允许减少其余额。示例:
function withdrawTokensFromContract(uint256 _amount) external {
require(msg.sender == address(Ox123),'Not authorized');
balances[address(this)] -= _amount; // decreases balance of the contract
// ...
}
在这种情况下,如果您使用属于授权地址的私钥签署了交易,则可以减少合约的代币余额。
或者可能只是措辞不正确,您只是想将代币(存储在合约地址中)从 Address A
转移到 Address B
。在这种情况下,您可以安全地使用答案中间部分描述的 transfer()
方法,并使用属于 Address A
的私钥对交易进行签名。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。