Skip to content
Business logic Audit finding Intermediate

Funds can be stuck due to wrong order of operations

The ERC20 quest contract lets the owner withdraw the protocol fee before recovering unclaimed tokens, and the recovery function does not account for a fee that has already been paid out. If the owner calls the functions in that order, the fee amount stays trapped in the contract and cannot be recovered.

carrotsmuggler Follow with adriro, hansfriese and 12 others

Originally disclosed on Code4rena

Submitted by carrotsmuggler, also found by adriro, hansfriese, hansfriese, Iurii3, hl_, bin2chen, KmanOfficial, peanuts, evan, ElKu, omis, AkshaySrivastav, mert_eren, and HollaDieWaldfee

https://github.com/rabbitholegg/quest-protocol/blob/8c4c1f71221570b14a0479c216583342bd652d8d/contracts/Erc20Quest.sol#L102-L104 https://github.com/rabbitholegg/quest-protocol/blob/8c4c1f71221570b14a0479c216583342bd652d8d/contracts/Erc20Quest.sol#L81-L87

The contract ERC20Quest.sol has two functions of interest here. The first is withdrawFee(), which is responsible for transferring out the fee amount from the contract once endTime has been passed, and the second is withdrawRemainingTokens() which recovers the remaining tokens in the contract which haven’t been claimed yet.

Function withdrawRemainingTokens():

function withdrawRemainingTokens(address to_) public override onlyOwner {
        super.withdrawRemainingTokens(to_);

        uint unclaimedTokens = (receiptRedeemers() - redeemedTokens) * rewardAmountInWeiOrTokenId;
        uint256 nonClaimableTokens = IERC20(rewardToken).balanceOf(address(this)) - protocolFee() - unclaimedTokens;
        IERC20(rewardToken).safeTransfer(to_, nonClaimableTokens);
    }

As evident from this excerpt, calling this recovery function subtracts the tokens which are already assigned to someone who completed the quest, and the fee, and returns the rest. However, there is no check for whether the fee has already been paid or not. The owner is expected to first call withdrawRemainingTokens(), and then call withdrawFee().

However, if the owner calls withdrawFee() before calling the function withdrawRemainingTokens(), the fee will be paid out by the first call, but the same fee amount will still be kept in the contract after the second function call, basically making it unrecoverable. Since there are no checks in place to prevent this, this is classified as a high severity since it is an easy mistake to make and leads to loss of funds of the owner.

Proof of Concept

This can be demonstrated with this test

describe('Funds stuck due to wrong order of function calls', async () => {
    it('should trap funds', async () => {
      await deployedFactoryContract.connect(firstAddress).mintReceipt(questId, messageHash, signature)
      await deployedQuestContract.start()
      await ethers.provider.send('evm_increaseTime', [86400])
      await deployedQuestContract.connect(firstAddress).claim()

      await ethers.provider.send('evm_increaseTime', [100001])
      await deployedQuestContract.withdrawFee()
      await deployedQuestContract.withdrawRemainingTokens(owner.address)

      expect(await deployedSampleErc20Contract.balanceOf(deployedQuestContract.address)).to.equal(200)
      expect(await deployedSampleErc20Contract.balanceOf(owner.address)).to.be.lessThan(
        totalRewardsPlusFee * 100 - 1 * 1000 - 200
      )
      await ethers.provider.send('evm_increaseTime', [-100001])
      await ethers.provider.send('evm_increaseTime', [-86400])
    })
  })

Even though the fee is paid, the contract still retains the fee amount. The owner receives less than the expected amount. This test is a modification of the test should transfer non-claimable rewards back to owner already present in ERC20Quest.spec.ts.

Tools Used

Hardhat

Recommended Mitigation Steps

Only allow fee to be withdrawn after the owner has withdrawn the funds.

// Declare a boolean to check if recovery happened
bool recoveryDone;

function withdrawRemainingTokens(address to_) public override onlyOwner {
        super.withdrawRemainingTokens(to_);

        uint unclaimedTokens = (receiptRedeemers() - redeemedTokens) * rewardAmountInWeiOrTokenId;
        uint256 nonClaimableTokens = IERC20(rewardToken).balanceOf(address(this)) - protocolFee() - unclaimedTokens;
        IERC20(rewardToken).safeTransfer(to_, nonClaimableTokens);

        // Set recovery bool
        recoveryDone = true;
    }
function withdrawFee() public onlyAdminWithdrawAfterEnd {
        // Check recovery
        require(recoveryDone,"Recover tokens before withdrawing Fees");
        IERC20(rewardToken).safeTransfer(protocolFeeRecipient, protocolFee());
    }

waynehoover (RabbitHole) disagreed with severity and commented:

I agree that this is an issue, but not a high risk issue. I expect high risk issues to be issues that can be called by anyone, not owners.

As owners there are plenty of ways we can sabotage our contracts (for example via the set* functions) it is an issue for an owner.

The owner understands how these functions work, so they can be sure to call them in the right order.

kirk-baird (judge) decreased severity to Medium and commented:

I agree with the sponsor that since this is an onlyOwner function that medium severity is more appropriate.

The likelihood of this issue is reduced as it can only be called by the owner.

Note: the ineffective onlyAdminWithdrawAfterEnd modifier not validating admin is raised in another issue.


The original report as published on Code4rena, by carrotsmuggler. Images and videos are our own copies; raw HTML is shown as text. View it on Code4rena.

Not written yet. The AI write-up for this report has not been written yet. The Original tab links to the source.

How it worked

Root cause

Likely the recovery function computes the non-claimable amount by subtracting the protocol fee without checking whether the fee has already been transferred out.

Impact

The owner could lose the fee amount, which stays stuck in the contract; the sponsor and judge note this needs the owner to call functions in the wrong order, so likelihood is reduced.

What the attacker needed

Owner calls functions in wrong order; quest has ended

The fix

The fee withdrawal should be blocked until the owner has recovered the remaining tokens, for example by tracking a recovery flag and requiring it before paying the fee.

How it was found

  1. Mint a receipt and start the quest.
  2. Advance time and have a participant claim the reward.
  3. Advance time past the end time.
  4. Call withdrawFee to pay the protocol fee.
  5. Call withdrawRemainingTokens to recover leftover tokens.
  6. Observe that the contract still holds the fee amount.

Explained by bugbounty.wiki with AI from the original and checked against quotes from it; it can still be wrong. Read the original before relying on a detail.

Not written yet. The AI write-up for this report has not been written yet. The Original tab links to the source.

A smart contract holds tokens for a reward campaign. The owner is meant to take back leftover tokens and then collect a fee, but nothing enforces that order. If the owner collects the fee first, the later recovery step still sets aside room for the fee, so that amount is left behind in the contract with no way to take it out.

What is Business logic?

The application works as coded but not as intended: a negative price, a skipped payment step, a limit that can be crossed.

More by carrotsmuggler

View all

42 more disclosed reports, best first.

More from RabbitHole Quest Protocol contest

View all

The newest disclosed reports for this program.

Similar reports

View all

Same bug class and techniques, clearest first.

Business logic flaws

The lesson behind this report.

The application works as coded but not as intended: a negative price, a skipped payment step, a limit that can be crossed.