发送ERC-20令牌失败.事务成功,但未发送任何令牌



当我运行以下代码时,它准确地获得了两个地址的令牌余额,交易甚至完成了(我可以在测试网上看到它(,尽管没有发送令牌。

我尝试了很多方法,包括用以下内容替换已签名的交易件:

await contract.methods.transfer(toAddress, 100000).send({
from: fromAddress
});

但是由于CCD_ 1错误而失败。

我发送代币的代码:

const Web3 = require("web3");
const { hdkey } = require("ethereumjs-wallet");
const bip39 = require("bip39");
const token = require("./token.json");
const mnemonic = "12 word phrase";
const provider = "https://apis.ankr.com/.../binance/full/test";
(async() => {
try {
const seed = await bip39.mnemonicToSeed(mnemonic);
const root = hdkey.fromMasterSeed(seed);
const web3 = new Web3(provider);
const addrNode = root.derivePath(`m/44'/60'/0'/0/0`);
const wallet = addrNode.getWallet();
// #0 in the hdwallet, the owner of the tokens
const fromAddress = wallet.getAddressString();
// #1 in the hdwallet, already has a token balance
const toAddress = "0x...";
const contract = new web3.eth.Contract(token.abi, token.contract_address);
let fromAddressBalance = await contract.methods.balanceOf(fromAddress).call();
let toAddressBalance = await contract.methods.balanceOf(toAddress).call();
console.log(`Pre Transaction: Sender: ${fromAddressBalance} TOKENS / Wallet: ${toAddressBalance} TOKENS`);
// token has 3 decimal places, this is 100.000
const encodedABI = contract.methods.transfer(toAddress, 100000).encodeABI();
const tx = {
from: fromAddress,
to: toAddress,
gas: 2000000,
value: 0x0,
data: encodedABI
}; 
const signed = await web3.eth.accounts.signTransaction(tx, wallet.privateKey.toString("hex"));
const trans = await web3.eth.sendSignedTransaction(signed.rawTransaction);
fromAddressBalance = await contract.methods.balanceOf(fromAddress).call();
toAddressBalance = await contract.methods.balanceOf(toAddress).call();

console.log(`Post Transaction: Sender: ${fromAddressBalance} TOKENS / Wallet: ${toAddressBalance} TOKENS`);
} catch (err) {
console.error(err.stack);
}
process.exit();
})();

有一些错误,一旦修复就解决了我的问题。我还没有回去测试是谁做的,或者是否需要所有这些,但我想把它留给未来的探险家。

  • 我用以太坊js钱包创建了一个钱包,然后将其用于web3。你必须让web3知道钱包的情况
const account = web3.eth.accounts.privateKeyToAccount(privateKey);
web3.eth.accounts.wallet.create();
web3.eth.accounts.wallet.add(account);
  • 私钥地址需要以0x开头。来源:https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#privatekeytoaccount
const privateKey = `0x${wallet.privateKey.toString("hex")}`;
  • 这最终无关紧要,也不是正确的转账方式,但值得注意的是,我将签署的交易发送给了第三方,而不是合同,发送交易的正确方式应该是
const tx = {
from: fromAddress,
to: token.contract_address,
gas: 2000000,
value: 0x0,
data: encodedABI
}; 

最终,我需要利用合同的转移方法,而不是签署/发送交易

const result = await contract.methods.transfer(toAddress, 100).send({
from: fromAddress,
gas: 2000000
});

相关内容

最新更新