Solidity Testing Hardhat – Fixing the ‘Dai/insufficient-allowance’ Revert Error During Testing

hardhatsoliditytesting

I am trying to test a simple function transferring Dai balance.

test –>

const [owner] = await ethers.getSigners();
const amount = await _hardhatPresaleERC20.calculateAmountTokensPurchased(1);
ownerBalanceDai = await _hardhatTokenDai.balanceOf(owner.address);
expect(amount).to.equal(10000);
const buyToken = await _hardhatPresaleERC20.buyToken(1);

Solidity –>

function buyToken(uint256 amountDaiTokens) external returns (bool) {
    uint256 amountTokenPurchased = calculateAmountTokensPurchased(
        amountDaiTokens
    );
    require(
        amountDaiTokens <= dai.balanceOf(msg.sender),
        "Buyer does not have enough tokens"
    );
    require(
        amountTokenPurchased <= calculateNumberOfTokenLeft(),
        "Not enough tokens"
    );
    dai.safeTransferFrom(msg.sender, address(this), amountDaiTokens);
    return true;
}

 

Error: VM Exception while processing transaction: reverted with reason string 'Dai/insufficient-allowance'

But I always get the same message, I don't understand what I'm doing wrong. I check the balances, but I can't complete the call?

Best Answer

A contract interaction involving an ERC20 transfer is more or less a two step process.

  1. The contract has to be given an allowance. This specifies how much of the token in question (e.g. DAI) the contract is allowed to spend from the user's wallet. See here how this permission works or study the ERC20 token format here.

  2. The contract can perform the transfer

So, before transferring the funds, you need go to the DAI contract and approve the spending. Pseudocode:

DAIContract.approve(spender, amount);

Translates to: My contract (the spender) can spend from the account calling this approve method (msg.sender) an amount of DAI

Related Topic