繁体   English   中英

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

[英]Send token from owner account from nodejs backend (Custom ERC20 token)

我在 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 });
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM