Cannot estimate gas; transaction may fail or may require manual gas limit Aave error

Expert

Hello. I tried to use Aave contract in my own contract. But I got this error cannot estimate gas; transaction may fail or may require manual gas limit. Any one know how to solve it?

My sol contract is

import {IPool} from "@aave/core-v3/contracts/interfaces/IPool.sol";

contract MyContract{
    address private owner;
    constructor(){
        owner = msg.sender;
    }
    function submitOrder(address pool, address token, uint256 amount, address user) public payable{
        IPool(pool).supply(token, amount, user, 0);
    }
}

and my script file i use

let depositAmount = ethers.utils.parseEther("1");
let contractSigner = await contract.connect((await ethers.getSigners())[0]);
let (await contractSigner.submitOrder(poolAddress, tokenAddress, depositAmount, payerAddress)).wait();
.

II tested in my local network (Polygon) and I confirmed that I have enough token in my payerAddress.

I actually approve pooladdress for my token as a spender already. However, it seems I am still out of luck. I am wondering Do I need to transfer my token to my contract before my contract call Aave supply function?

let (await contractSigner.submitOrder(poolAddress, tokenAddress, depositAmount, payerAddress)).wait();

Answers 1

Before calling supply you must approve the pool to spend these tokens by calling the approve function on the underlying token (i.e. on the USDC contract if you are supplying USDC), passing the poolAddress as the spender parameter;

You can either send the tokens to your contract first, or have the user approve your contract to spend their tokens and call transferFrom to send funds from the user to your contract inside of submitOrder.