0

I made a smart contract for token on the Polygon network. The server part is NodeJS.

Now I'm trying to implement the functionality of sending tokens to the recipient's wallet from the token creator's wallet.

The transfer method in the contract is simply taken from OpenZeppelin's ERC20 contract.

    /**
     * @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;
    }

Calling the contract method from the server looks like this:

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();
}

But no transfer happens. I know I need to use the sender's private key somewhere, but I can't figure out where.

1 Answer 1

1

Solved my own problem. Maybe my code example will help someone:

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.