简体   繁体   中英

erc20 claim token transfer function doesn't work

I have this contract and trying to call the claimFreeToken function. Contract already doesn't have enough tokens but the function doesn't return an error and also token doesn't receive. Where did I overlook it?

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

import "@openzeppelin/contracts/token/ERC20/ERC20.sol";

contract TestToken is ERC20 {
    constructor(uint256 initialSupply) ERC20("Test Token", "TET") {
        _mint(msg.sender, initialSupply * (10**decimals()));
    }

    function claimFreeToken() public payable {
        transfer(msg.sender, 1000 * (10**decimals()));
    }
}

Your implementation makes token transferred from your wallet to your wallet on claiming, not from the contract.

The transfer function in ERC20 will send from the msg.sender to the specified address. So, in this case you are transferring from msg.sender to msg.sender .

The correct implementation should be like this,

function claimFreeToken() public payable {
    _transfer(address(this), msg.sender, 1000 * (10**decimals()));
}

Read more: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC20/ERC20.sol#L113

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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