Issue implementing an approveUSDT function in a contract

Hello! Iā€™m experimenting with a presale contract based on the BSC testnet, and in the contract Iā€™m attempting to achieve the purchase of my own token with USDT.

Using my own code within the contract itself, I cannot get approval to go through properly for the presale contract to spend my USDT on behalf of me.

However if I use the approve function within the ā€œwrite contractā€ section of the USDT token on BSCSCAN, it does work - and I can buy tokens after approval went through.

While approval via BSCSCAN works, this would not be convenient for further users of the contract. So I would need working code within the contract itself to cover approvals, but I havenā€™t been able to get any working as expected.

Example of the approval code:

function approveUSDT() public {
        
        IERC20 usdtToken = IERC20(0x337610d27c682E347C9cD60BD4b3b107C9d34dDd);

       require(usdtToken.approve(address(this), tokenAmount), "Approval failed");
        
       emit ApprovalSuccessful(msg.sender, tokenAmount);

}

What am I missing here? Thanks!

Hi @HATOKEN

What is the error you are seeing when you run your code?

Approval errors are always related to the understanding that, although you call the function within a contract, you are trying to approve through a contract that is not the owner.

In other words, you have to call the approval function of the USDT token, or the ERC20 you want to approve, outside the contract you are approving.

Because the contract you want to do that is not the owner of the tokens.