从nodejs后台的所有者账户发送令牌(自定义ERC20令牌)



我在Polygon网络上做了一个代币智能合约。服务器部分是NodeJS。

现在我正在尝试实现从令牌创建者的钱包向接收者的钱包发送令牌的功能。

合约中的转账方式直接取自OpenZeppelin的ERC20合约。

/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address to, uint256 amount) public virtual override returns (bool) {
address owner = _msgSender();
_transfer(owner, to, amount);
return true;
}

从服务器调用合约方法如下:

const web3Instance = new web3('providerUrl');
const tokenSmartContract = new this.web3Instance.eth.Contract(TokenABI, 'tokenAddress');
async sendTokenToWallet(amount, wallet) {
await this.tokenSmartContract.methods.transfer(wallet, amount).send();
}

但是没有发生转移。我知道我需要在某个地方使用发件人的私钥,但我不知道在哪里。

解决了我自己的问题。也许我的代码示例会帮助别人:

async sendTokenToWallet(amount, wallet) {
const tokenAmount = web3.utils.toWei(amount.toString(), 'ether');
const account = this.web3Instance.eth.accounts.privateKeyToAccount('0x' + 'privateKey');
this.web3Instance.eth.accounts.wallet.add(account);
this.web3Instance.eth.defaultAccount = account.address;
const nonce = await this.web3Instance.eth.getTransactionCount(account.address, 'latest');
const gasPrice = Math.floor(await this.web3Instance.eth.getGasPrice() * 1.10);
const gas = await this.tokenSmartContract.methods
.transfer(wallet, tokenAmount)
.estimateGas({ from: account.address });
await this.tokenSmartContract.methods
.transfer(wallet, tokenAmount)
.send({ from: account.address, gasPrice, nonce, gas });
}