Tadle

Tadle
DeFi
30,000 USDC
View results
Submission Details
Severity: high
Valid

[HIGH] Missing Approval for Token Withdrawal Leads to Failed Refunds and `revert()` When Maker closes offer with `PreMarkets::closeOffer()` and tries to call `TokenManager::withdraw()` function.

Description

if user creates an offer with PreMarkets::createOffer() function and for some reason decides to close the offer immediately with PreMarkets::createOffer() function. after that user has to call the TokenManager::withdraw() function to get Refunded the amount he deposited when creating the offer. but Unfortunately The withdraw() function in the TokenManager contract does not call the CapitalPool::approve() function for the _tokenAddress, preventing the CapitalPool from transferring tokens back to the offer creator. This causes withdrawals to fail and revert() if offer creator wants to get his money back.

Impact

Users who create offers and then attempt to withdraw their funds after closing the offer will encounter failed withdrawals due to the lack of token transfer approval, resulting in the inability to retrieve deposited tokens.

Proof of Concept

  1. User creates an offer via PreMarkets::createOffer().

  2. User decides to close offer for whatever reason via PreMarkets::closeOffer().

  3. User now Tries to withdraw the tokens that he deposited when creating offer by calling TokenManager::withdraw() function.

  4. Unfortunately it fails and the TokenManager::withdraw() function call reverts due to ERC20InsufficientBalance.

function test_user_creates_offer_and_cannot_withdraw_after() external {
vm.startPrank(user);
uint256 balanceOfuserBefore = mockUSDCToken.balanceOf(user);
address offerAddr = GenerateAddress.generateOfferAddress(preMarktes.offerId());
address stockAddr = GenerateAddress.generateStockAddress(preMarktes.offerId());
preMarktes.createOffer(
CreateOfferParams(
marketPlace, // marketPlace
address(mockUSDCToken), // tokenAddress
1000, // points
0.01 * 1e18, // amount
12000, // collateralRate
300, // eachTradeTax
OfferType.Ask, // offerType 0.Ask/Sell 1.Bid/Buy
OfferSettleType.Turbo // isTurboMode 0.Protected 1.Turbo
)
);
uint256 transferedAmount = OfferLibraries.getDepositAmount( OfferType.Ask, 12000, 0.01 * 1e18, true, Math.Rounding.Ceil );
assertEq(balanceOfuserBefore - transferedAmount , mockUSDCToken.balanceOf(user));
preMarktes.closeOffer(stockAddr, offerAddr);
OfferInfo memory offerInfo = preMarktes.getOfferInfo(offerAddr);
uint256 expectedRefundAmount = OfferLibraries.getRefundAmount(
offerInfo.offerType,
offerInfo.amount,
offerInfo.points,
offerInfo.usedPoints,
offerInfo.collateralRate
);
vm.expectRevert(); // withdrawal will fail next line.
tokenManager.withdraw(address(mockUSDCToken), TokenBalanceType.MakerRefund);
uint256 balanceOfuserAfter = mockUSDCToken.balanceOf(user);
assertFalse(balanceOfuserAfter == balanceOfuserBefore + expectedRefundAmount); // current `user` balance is not equal equal to `user` balance before creating order plus refund amount.
console2.log("if the withdrawal were successfull, current user balance should've been:");
console2.log(" ", balanceOfuserBefore + expectedRefundAmount);
console2.log("since the withdrawal were not successfull, current user balance is: ");
console2.log(" ", mockUSDCToken.balanceOf(user));
vm.stopPrank();
}

run the test with following command:

forge test --match-test test_user_creates_offer_and_cannot_withdraw_after -vvvv

take a look at the logs:

Logs:
if the withdrawal were successfull, current user balance should've been:
100000000012000000000000000
since the withdrawal were not successfull, current user balance is:
99999999988000000000000000

Recommended Mitigation

Add an approval step in the withdraw() function to so CapitalPool authorizes TokenManager to transfer tokens back to users with _safe_transfer_from() function:

function withdraw( address _tokenAddress, TokenBalanceType _tokenBalanceType ) external whenNotPaused {
uint256 claimAbleAmount = userTokenBalanceMap[_msgSender()][_tokenAddress][_tokenBalanceType];
if (claimAbleAmount == 0) {
return;
}
address capitalPoolAddr = tadleFactory.relatedContracts(RelatedContractLibraries.CAPITAL_POOL);
if (_tokenAddress == wrappedNativeToken) {
/**
* @dev token is native token
* @dev transfer from capital pool to msg sender
* @dev withdraw native token to token manager contract
* @dev transfer native token to msg sender
*/
_transfer(
wrappedNativeToken,
capitalPoolAddr,
address(this),
claimAbleAmount,
capitalPoolAddr
);
IWrappedNativeToken(wrappedNativeToken).withdraw(claimAbleAmount);
payable(msg.sender).transfer(claimAbleAmount);
} else {
/**
* @dev token is ERC20 token
* @dev transfer from capital pool to msg sender
*/
+ ICapitalPool(capitalPoolAddr).approve(_tokenAddress);
_safe_transfer_from(
_tokenAddress,
capitalPoolAddr,
_msgSender(),
claimAbleAmount
);
}
emit Withdraw(
_msgSender(),
_tokenAddress,
_tokenBalanceType,
claimAbleAmount
);
}

This ensures successful withdrawals by allowing CapitalPool to transfer tokens back to users.

Updates

Lead Judging Commences

0xnevi Lead Judge 10 months ago
Submission Judgement Published
Validated
Assigned finding tags:

finding-TokenManager-safeTransferFrom-withdraw-missing-approve

This issue's severity has similar reasonings to #252, whereby If we consider the correct permissioned implementation for the `approve()` function within `CapitalPool.sol`, this would be a critical severity issue, because the withdrawal of funds will be permanently blocked and must be rescued by the admin via the `Rescuable.sol` contract, given it will always revert [here](https://github.com/Cyfrin/2024-08-tadle/blob/04fd8634701697184a3f3a5558b41c109866e5f8/src/core/CapitalPool.sol#L36-L38) when attempting to call a non-existent function selector `approve` within the TokenManager contract. Similarly, the argument here is the approval function `approve` was made permisionless, so if somebody beforehand calls approval for the TokenManager for the required token, the transfer will infact not revert when a withdrawal is invoked. I will leave open for escalation discussions, but based on my first point, I believe high severity is appropriate. It also has a slightly different root cause and fix whereby an explicit approval needs to be provided before a call to `_safe_transfer_from()`, if not, the alternative `_transfer()` function should be used to provide an approval, assuming a fix was implemented for issue #252

Support

FAQs

Can't find an answer? Chat with us on Discord, Twitter or Linkedin.