cDAI.mint(_amount) showing error 'Dai/insufficient-allowance'

I have the following code in solidity:

pragma solidity ^0.8;

contract A{

    constructor() {
        dai = IERC20(0x6B175474E89094C44Da98b954EedeAC495271d0F);
        cDai = cTokenInterface(0x5d3a536E4D6DbD6114cc1Ead35777bAB948E3643);
        owner = msg.sender;
    }

    IERC20 public dai;
    cTokenInterface public cDai;
    address public owner;

    uint public investedDai;

    function deposit(uint _amount) external {
            dai.transferFrom(msg.sender, address(this) , _amount);
            dai.approve(address(cDai),_amount);
            cDai.mint(_amount);
        }
}

I am facing a problem when calling the deposit function with parameters when testing the smart contracts. Additional information, I have forked mainnet and using the DAI whale account to make transactions.

This contract is working perfectly on RemixIDE when connected to Kovan testnet, i.e., using the tokens (DAI and cDAI) addresses on the Kovan testnet. On deploying the contract on the Kovan testnet, the contract address should be approved on the DAI contract by calling the approve(address_of_the_contract_A, allowedAmount) function before calling deposit(_amount) on contract A.

On testing the contract (after deploying and approving the smart contract’s address), an error is thrown Error: VM Exception while processing transaction: reverted with reason string 'Dai/insufficient-allowance'. There is some error that I am not able to resolve. although in the test script, I am trying to mint, i.e. cDAI.mint(amount), else I am getting the error Error: Transaction reverted without a reason string.

Anyleads will be helpful. I am using Hardhat.

This error could either be happening in this line dai.transferFrom(msg.sender, address(this) , _amount); or this cDai.mint(_amount); My guess is the error is in the former line and you aren’t approving the “A” contract. Can you use console logging to determine which line the error is in?

@joeysantoro Thank you for your kind reply!
Actually, I figured out the error, but maybe you can tell me why is there some error!

The actual piece of code looked like this

function deposit(uint _amount) external {
            // SOME CALCULATIONS
            dai.transferFrom(msg.sender, address(this) , _amount);
            dai.approve(address(cDai),_amount);
            cDai.mint(_amount);
        }

The above was giving an error.

but on interchanging lines, like the following:

function deposit(uint _amount) external {
            dai.transferFrom(msg.sender, address(this) , _amount);
            dai.approve(address(cDai),_amount);
            cDai.mint(_amount);
           // SOME CALCULATIONS
        }

It works fine.

Do you have any idea why it works like this?