0

I am developing an Ethereum smart contract where I want to deposit an ERC 20 token to. It seems that I can deposit it directly by sending the token from MetaMask to the contract address, but I also want to execute some logic when depositing to it. So I created a deposit function. My code of the contract is as follows:

//SPDX-License-Identifier: MIT
pragma solidity 0.8.0;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
contract Orders is Ownable {
uint256 public counter;
address token;
constructor(address _token) {
    token = _token;
}
function deposit(uint _amount) public payable {
    IERC20(token).approve(address(this), _amount);
    IERC20(token).allowance(msg.sender, address(this));
    IERC20(token).transferFrom(msg.sender, address(this), _amount);
    counter = counter + 1;
}
// This function allow you to see how many tokens have the smart contract
function getContractBalance() public onlyOwner view returns(uint){
return IERC20(token).balanceOf(address(this));
}
}

I use Remix to compile the contract and deploy it on the Goerli testnet. I deploy it with the USDC testnet coin address (0x07865c6E87B9F70255377e024ace6630C1Eaa37F), which works successful. But when I call the deposit function with a 1 as a parameter from Remix, the transaction fails with "Fail with error 'ERC20: transfer amount exceeds allowance'" as the error: https://goerli.etherscan.io/tx/0x5ae6bf73813d903bb822be3b6d877bc6db040edcae8ed097eab6ae8c7c6e582c

When I delete the approve and allowance call, I still get the error.

Can you please help me resolve it?

One hypothesis I have based on a comment I saw on StackExchange is that it may not work in Remix ... but I am not sure, maybe my code is not correct. Thank you very much in advance!

1 Answer 1

1

Your approval is incorrect.

Your contract cannot approve the token of the caller.

You have to call the approval from the holder wallet to the token contract.

approve(aContract, forAmount)

Then you can call the deposit and check the allowance.

allowance(msg.sender, yourContract) -> return a number that should == amount

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.