我正在尝试使用 ERC20 转移功能将余额从合约部署者地址转移到另一个地址。
对于本地 Ganache 网络从部署者地址传输就像
await contract.transfer(receiverAddress, amount);
由于 Rinkeby 测试网不允许使用方法“eth_sendTransaction”并给出错误,因此我尝试创建如下所示的原始交易。执行以下编写的代码时没有收到错误,但接收方的余额也没有变化。
const result = {};
const contract = new web3.eth.Contract(token_artifact.abi, config.contractAddress);
const count = await web3.eth.getTransactionCount(config.deployerAddress);
const nonce = web3.utils.toHex(count);
const gasLimit = web3.utils.toHex(90000);
const gasPrice = web3.utils.toHex(web3.eth.gasPrice || web3.utils.toHex(2 * 1e9));
const value = web3.utils.toHex(web3.utils.toWei('0', 'wei'));
const data = contract.methods.transfer(receiver, amount).encodeABI();
const txData = {
nonce,
gasLimit,
gasPrice,
value,
data,
from: config.deployerAddress,
to: receiver
};
web3.eth.accounts.wallet.add(config.deployerPrivateKey);
const sentTx = await web3.eth.sendTransaction(txData);
result['receipt'] = sentTx;
来自 Rinkeby 测试网的回复:
{
"receipt": {
"blockHash": "0xcb259fa6c63153f08b51153cf9f575342d7dd0b9c091c34da0af5d204d1aff14",
"blockNumber": 8985823,
"contractAddress": null,
"cumulativeGasUsed": 21572,
"effectiveGasPrice": "0x77359400",
"from": "0x6d10f3f1d65fadcd1b6cb15e28f98bcfb0f4e9e5",
"gasUsed": 21572,
"logs": [],
"logsBloom": "0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000",
"status": true,
"to": "0xbc0422d1b7e2f7ad4090acb6896779c56b3af331",
"transactionHash": "0xdd86d849769e87fef0fd99f2034a5d32821c0dc565c900a5ed1274edbd956b41",
"transactionIndex": 0,
"type": "0x0"
}
}
[注意:我可以检查给定地址的总供应量和余额。]
let data = {};
const contract = require('@truffle/contract');
const Token = contract(token_artifact);
Token.setProvider(web3.currentProvider);
const instance = await Token.at(config.contractAddress);
const result = await Promise.all([instance.totalSupply(), instance.balanceOf(address)]);
data['totalSupply'] = result[0].toNumber();
data['balanceOf'] = result[1].toNumber();
resolve(data);
答案 0 :(得分:2)
在转移代币时,您需要与合约进行交互(即向合约发送交易)。不直接与令牌接收器。
因此您需要将交易的to
字段更改为合约地址。
// this field says that you want to transfer tokens to the `receiver`
const data = contract.methods.transfer(receiver, amount).encodeABI();
const txData = {
nonce,
gasLimit,
gasPrice,
value,
data, // containing info that you want to `transfer()` to the `receiver`
from: config.deployerAddress, // send transaction from your address
to: config.contractAddress // CHANGED; send transaction to the contract address
};