Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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()));
    }
}
like image 464
Ali Can Almaçimeni Avatar asked Feb 26 '26 14:02

Ali Can Almaçimeni


1 Answers

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

like image 137
turboza Avatar answered Mar 01 '26 04:03

turboza



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!