Slippage protection in AgentTax::dcaSell and BondingTax::swapForAsset is calculated at execution time, effectively retrieving the very same price that the trade will be executing at, ultimately providing no protection
The slippage protection in BondingTax::swapForAsset and AgentTax::dcaSell is computed from the price fetched at execution time, so the minimum output is derived from the very price the trade will execute at. An attacker could move the pool price just before the call, and the swap would still pass the check, letting the protocol or agent creators lose part of their fees.
Jeremias Follow with adam-idarrha, FavourOkerri and 7 others
Originally disclosed on Code4rena
Submitted by Jeremias, also found by adam-idarrha, FavourOkerri, joicygiore, maze, mbuba666, odessos42, slowbugmayor, testnate, and vasilishte
Finding description
Automated Market Makers define the price of asset based on a pool of two assets. The ratio at which they exchange, is defined by a curve of constant product. Except when liquidity is proportionally increased for both, the expected behaviour is that as one increases, the other decreases.
In a pair of token A and token B, if a user deposits the first token, the amount he would receive of the second token is defined as the amount of the other token (token B) that we have to take away for their product to remain constant. Thus, every time a swap occurs, prices does even if slightly, change.
Sometimes before a transaction occurs, users could have also called (and executed) a swap before us, adversely affecting the price ratio (and if the liquidity of the pool is low, that might be even more noticeable). This is an adverse situation we call slippage. To protect against that, some protocols take a minimum amount out.
However, this protection only makes sense (as the risk it protects against) from outside the transaction in which it occurs. Because once the transaction is executing, unless we work with reentrant tokens or something akin to that, the price we are going to work with is the same one that is being used to calculate slippage protection.
Calculating a percentage of acceptable loss from a price fetched at the time of execution then is of no use, since that is already the price that we will be exposed to, be it acceptable or not.
In BondingTax, the BondingTax::SwapForAsset function looks like this:
function swapForAsset() public onlyBondingRouter returns (bool, uint256) {
uint256 amount = IERC20(taxToken).balanceOf(address(this));
require(amount > 0, "Nothing to be swapped");
if (amount < minSwapThreshold) {
return (false, 0);
}
if (amount > maxSwapThreshold) {
amount = maxSwapThreshold;
}
address[] memory path = new address[](2);
path[0] = taxToken;
path[1] = assetToken;
@> uint256[] memory amountsOut = router.getAmountsOut(amount, path); //@audit this gets whatever the price already is at execution
require(amountsOut.length > 1, "Failed to fetch token price");
uint256 expectedOutput = amountsOut[1]; //@audit no protection
uint256 minOutput = (expectedOutput * (10000 - _slippage)) / 10000;
try router.swapExactTokensForTokens(amount, minOutput, path, treasury, block.timestamp + 300) returns (
uint256[] memory amounts
) {
emit SwapExecuted(amount, amounts[1]);
return (true, amounts[1]);
} catch {
emit SwapFailed(amount);
return (false, 0);
}
}
Here we see that the output is calculated from the price the function fetches at execution time:
@> uint256[] memory amountsOut = router.getAmountsOut(amount, path); //@audit calculated from current price
require(amountsOut.length > 1, "Failed to fetch token price");
uint256 expectedOutput = amountsOut[1]; //@audit expected output is calculated from amountsOut
uint256 minOutput = (expectedOutput * (10000 - _slippage)) / 10000;
This protection is insufficient. A similar implementation is tried in AgentTax::dcaSell:
function dcaSell(uint256[] memory agentIds, uint256 slippage, uint256 maxOverride) public onlyRole(EXECUTOR_ROLE) {
require(slippage <= DENOM, "Invalid slippage");
uint256 agentId;
for (uint i = 0; i < agentIds.length; i++) {
agentId = agentIds[i];
TaxAmounts memory agentAmounts = agentTaxAmounts[agentId];
uint256 amountToSwap = agentAmounts.amountCollected - agentAmounts.amountSwapped;
if (amountToSwap > maxOverride) {
amountToSwap = maxOverride;
}
@> uint256 minOutput = ((amountToSwap * (DENOM - slippage)) / DENOM); //@audit slippage is received as a ratio here
@> _swapForAsset(agentId, minOutput, maxOverride); //@audit a ratio over the price at execution
}
}
In both cases, the slippage protection is calculated at run-time. And that’s not a good enough protection against strong price or market movements occurring immediately before our call to uniswap is performed.
Impact
The risk at which the protocol is exposed thus, is that price movements could lead to swap being executed at not acceptable prices brought by market dynamics, with no protection. The protocol might lose part of the funds that are meant to go to their treasure in the swap, or creators of sentient categorized agents might lose part of their trading fees earned. Given that for now there is no public transaction pool in BASE, the severity might be deserving of medium.
Recommended mitigation steps
I think there are more than one considerations to make here.
Given that the purpose of one of these functions AgentTax::DcaSell is executing many swaps in a loop, setting a single slippage protection inside the call could be not ideal, as the transactions run one after the other; and if the last one hits slippage, all of them get a revert (but could be chosen if that behaviour is desired).
Also, the other of the mentioned functions (BondingTax::swapForAsset) is meant to be called by another contract at execution (FRouter::buy and FRouter::sell, to handle fees), thus passing slippage protection parameters as an argument might be difficult.
Some solutions could be:
-
For
AgentTax::DcaSell, use a current starting price associated with aTaxTokenat which execution of swap is acceptable to pass as an argument, and revert if it isn’t met.- To get the current price at execution time,
IUniswapV2Router01::getAmountsOutcould be used, passing a reference value as amount, and then calculating the price from it and the value returned, to compare it with the argument and check slippage.
- To get the current price at execution time,
function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts);
-
For
BondingTax::swapForAsset:- If the calls inside
FRouter::buyandFRouter::sellcould be removed, the implementation could also be similar as that suggested forAgentTax::DcaSell. - Otherwise, you could set in the contract a minimum acceptable price (or a series of them, if you were to implement many
taxTokens, for both contracts) in which you would consider more important to avoid the slippage lose than having the swap fail in the try-catch.
- If the calls inside
Proof of Concept
BondingTax::SwapForAssetis called by the bondingRouter, to swap ataxTokenfor theAssetToken.- Someone makes a very big swap exactly before the call in relevant pool.
- The call executes.
- We swapped fees cheaply.
- After our swap the price gets a correction rather quickly to its average, but we already made the swap at a disadvantageous price.
And in the other case:
AgentTax::DcaSellis called to process taxes.- Someone makes a very big swap exactly before the call in relevant pool.
- Since slippage protection intends to be calculated at run-time, it never hits, even though the price could have dropped very significantly. So our call executes.
- Swaps are performed successfully, and the protocol and the creators of agents would lose a significant part of their fees.
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 minimum output is derived from a price quote taken inside the same transaction as the swap, so it cannot detect adverse price movement that already happened.
Impact
Price movements could cause swaps to execute at unacceptable prices with no protection, so the protocol or agent creators could lose part of their fees; the author notes there is currently no public transaction pool on BASE, which may lower severity to medium.
What the attacker needed
Ability to swap in the relevant pool; trade executes after the price move
The fix
The minimum acceptable price should be passed in as an argument or stored in the contract, rather than derived from a quote taken at execution time.
How it was found
- BondingTax::SwapForAsset is called by the bonding router to swap a tax token for the asset token.
- Someone makes a very large swap in the relevant pool just before the call.
- The call executes and the swap goes through.
- The fees are swapped at a poor price, and the price corrects afterwards.
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 slippage limit is a minimum amount you accept back from a trade, so a bad price makes the trade fail. Here the minimum is worked out from the current price at the moment the trade runs, so it always matches that price and never blocks a bad trade. Someone who shifts the price just before the trade can make it go through at a worse rate.
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.