Muh*_*man 7 javascript ethereum web3js erc20
我正在尝试使用以下代码将 erc20 代币从合约地址转移到 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);
    }
});
但我收到此错误:
交易错误 错误:返回错误:方法 eth_sendTransaction 不存在/不可用
我已经搜索了很多并尝试了这段代码,但它不起作用。可能是什么原因?这段代码是错误的,还是其他什么?
我正在使用 infura ropsten 网络节点。
除了错误消息之外,还有一些与您的问题相关的其他问题。
让我们从错误消息开始。
eth_sendTransaction 方法不存在/不可用
eth_sendTransaction()当您希望节点为您签署交易时使用(使用 ulocked 帐户)。但您连接到的节点不支持此方法。最有可能的是 Infura 或其他第三方节点提供商不为您持有您帐户的私钥。
因此,您需要在应用程序上签署交易,然后将签名的交易广播到您的节点。实现这一目标的方法很少。
例如,您可以使用web3.eth.signTransaction()对 tx 进行签名,然后使用web3.eth.sendSignedTransaction()将(签名的)tx 提交到您的节点。
或者您可以使用该accounts.wallet.add()方法,然后使用 Contract 实例send()方法 - 请参阅答案的中间部分。
您的代码片段创建了常规 ETH 传输 - 它不会创建代币传输。
您可以使用 Web3合约方法来帮助您构建传输 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.
| 归档时间: | 
 | 
| 查看次数: | 9834 次 | 
| 最近记录: |