testingblockchainsmartcontractschaierc20

transfer function does not working correctly on ERC20 presale smart contract while testing using Chai and Hardhat


I have written ERC20 token presale smart contract. I have defined token transfer function as follows:

function transferTokensToPresale(uint256 presaleSupplyAmount_) public onlyOwner returns (bool) {
        require(presaleSupplyAmount_ > 0, "Amount must be greater than zero");
        require(
            token.balanceOf(msg.sender) >= presaleSupplyAmount_,
            "Insufficient balance"
        );
        require(block.timestamp < startTime, "Presale has already started");

        //Send the tokens to the presale contract
        SafeERC20.safeTransferFrom(
            token,
            msg.sender,
            address(this),
            presaleSupplyAmount_
        );
        return true;
    }

But while I was testing the function with Hardhat and Chai, the transfer didn't occur. There was no transaction fails or errors.

The test script I wrote was as follows:

console.log("token amount before transferring token to presale contract--->", presale.tokensAvailable());
const tx = await presale.connect(owner).transferTokensToPresale(presaleSupply);
console.log("token amount before transferring token to presale contract--->", presale.tokensAvailable());

The token amount in presale contract before and after transaction are the same.

What is the reason?


Solution

  • The transferTokensToPresale function works correctly. The error occurs in your test script. You need to add await tx.wait();

    The correct codebase is like this:

    console.log("token amount before transferring token to presale contract--->", presale.tokensAvailable());
    const tx = await presale.connect(owner).transferTokensToPresale(presaleSupply);
    await tx.wait();
    console.log("token amount before transferring token to presale contract--->", presale.tokensAvailable());
    

    This will fix your errors.