1

I am trying to implement a simple token transfer to a Vault but I'm having trouble approving the transaction and when I run tests using foundry, I receive this error:

[FAIL. Reason: ERC20: transfer amount exceeds allowance] testDeposit() (gas: 86770)

My code is for the deposit function is here:

function deposit(uint256 amount) external {
    console.log("RANDOM inside deposit = ");
    console.log(IERC20(underlyingToken).balanceOf(msg.sender));

    console.log("msg sender =");
    console.log(msg.sender);

    console.log("approve = ");
    console.log(IERC20(underlyingToken).approve(address(this), amount));

    // IERC20(underlyingToken).approve(msg.sender, amount);

    console.log("RANDOM inside deposit after approve = ");
    console.log(IERC20(underlyingToken).allowance(msg.sender, address(this)));


    IERC20(underlyingToken).transferFrom(msg.sender, address(this), amount);
    // // totalDeposited += amount;
    IPool(aavePool).supply(underlyingToken, amount, address(this), 0);

    totalUnderlyingDeposited += amount;
}

Thank you for the help in advance

1 Answers1

1

You can't have the vault give itself an allowance for the sender. That would defeat the whole point of the approval mechanism.

What your code IERC20(underlyingToken).approve(address(this), amount) actually does is give the vault permission to transfer any of its own tokens using transferFrom. Obviously this is a bit silly since the vault can just use transfer to do that.

Your commented-out code // IERC20(underlyingToken).approve(msg.sender, amount);, as you probably figured out, lets the sender transfer the vault's tokens.

The only way to let the vault do transferFrom(msg.sender, ..., ...) is if the sender interacts directly with the ERC20 by calling approve him/herself.

This means the user will need to do two transactions to do the first deposit into the vault: 1) approve the vault for an allowance sufficient to cover the deposit 2) do the deposit.

If the approval is for an "infinite" amount (max uint256), then subsequent deposits only require a single transaction each; however, this is not considered wise from a security standpoint.

C S
  • 1,363
  • 1
  • 17
  • 26