{"code":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.24;\n\nimport {AMMStrategyBase} from \"./AMMStrategyBase.sol\";\nimport {TradeInfo} from \"./IAMMStrategy.sol\";\n\ncontract Strategy is AMMStrategyBase {\n    uint256 constant ELAPSED_CAP = 8;\n    uint256 constant SIGNAL_THRESHOLD = WAD / 650;\n    uint256 constant DIR_DECAY = 750000000000000000;\n    uint256 constant ACT_DECAY = 530000000000000000;\n    uint256 constant SIZE_DECAY = 530000000000000000;\n    uint256 constant TOX_DECAY = 910000000000000000;\n    uint256 constant SIGMA_DECAY = 690000000000000000;\n    uint256 constant LAMBDA_DECAY = 990000000000000000;\n    uint256 constant SIZE_BLEND_DECAY = 828000000000000000;\n    uint256 constant TOX_BLEND_DECAY = 51000000000000000;\n    uint256 constant ACT_BLEND_DECAY = 985000000000000000;\n    uint256 constant PHAT_ALPHA = 270000000000000000;\n    uint256 constant PHAT_ALPHA_RETAIL = 60000000000000000;\n    uint256 constant PHAT_ALPHA_SAME = 120000000000000000;\n    uint256 constant REVERT_U = 0;\n    uint256 constant DIR_IMPACT_MULT = 4;\n    uint256 constant GATE_SIGMA_MULT = 7200000000000000000;\n    uint256 constant MIN_GATE = 30000000000000000;\n    uint256 constant RET_CAP = WAD / 35;\n    uint256 constant TOX_CAP = WAD / 5;\n    uint256 constant TRADE_RATIO_CAP = WAD / 5;\n    uint256 constant LAMBDA_CAP = 1820000000000000000;\n    uint256 constant STEP_COUNT_CAP = 64;\n    uint256 constant BASE_FEE = 4 * BPS;\n\n    function afterInitialize(uint256 initialX, uint256 initialY) external override returns (uint256, uint256) {\n        slots[0] = BASE_FEE; slots[1] = BASE_FEE; slots[2] = 0; slots[3] = WAD; slots[4] = 0;\n        slots[5] = initialX > 0 ? wdiv(initialY, initialX) : 100 * WAD;\n        slots[6] = 950000000000000; slots[7] = 800000000000000000; slots[8] = 2000000000000000;\n        slots[13] = 902500000000; slots[14] = slots[5]; slots[15] = 0; slots[9] = 0; slots[10] = 0; slots[11] = 0; slots[12] = 0;\n        return (BASE_FEE, BASE_FEE);\n    }\n\n    function afterSwap(TradeInfo calldata trade) external override returns (uint256, uint256) {\n        uint256 prevBidFee = slots[0]; uint256 prevAskFee = slots[1]; uint256 lastTs = slots[2];\n        uint256 dirState = slots[3]; uint256 actEma = slots[4]; uint256 pHat = slots[5];\n        uint256 sigmaHat = slots[6]; uint256 lambdaHat = slots[7]; uint256 sizeHat = slots[8];\n        uint256 toxEma = slots[9]; uint256 stepTradeCount = slots[10];\n\n        uint256 sigmaForFast = sigmaHat;\n        uint256 fastHat = slots[14];\n        uint256 uncertainty = slots[13];\n        uint256 silent = trade.timestamp > lastTs ? trade.timestamp - lastTs : 0;\n        bool isNewStep = trade.timestamp > lastTs;\n        if (isNewStep) {\n            uint256 elapsedRaw = trade.timestamp - lastTs;\n            uint256 elapsed = elapsedRaw > ELAPSED_CAP ? ELAPSED_CAP : elapsedRaw;\n            dirState = _decayCentered(dirState, DIR_DECAY, elapsed);\n            actEma = wmul(actEma, _powWad(ACT_DECAY, elapsed));\n            sizeHat = wmul(sizeHat, _powWad(SIZE_DECAY, elapsed));\n            toxEma = wmul(toxEma, _powWad(TOX_DECAY, elapsed));\n            if (stepTradeCount > 0 && elapsedRaw > 0) {\n                uint256 lambdaInst = (stepTradeCount * WAD) / elapsedRaw;\n                if (lambdaInst > LAMBDA_CAP) lambdaInst = LAMBDA_CAP;\n                lambdaHat = wmul(lambdaHat, LAMBDA_DECAY) + wmul(lambdaInst, WAD - LAMBDA_DECAY);\n            }\n            uncertainty += wmul(sigmaForFast, sigmaForFast) * elapsedRaw;\n            if (uncertainty > 100000000000000) uncertainty = 100000000000000;\n            stepTradeCount = 0;\n        }\n\n        bool firstInStep = stepTradeCount == 0;\n        uint256 spot = trade.reserveX > 0 ? wdiv(trade.reserveY, trade.reserveX) : pHat;\n        if (pHat == 0) pHat = spot;\n\n        uint256 feeUsed = trade.isBuy ? prevBidFee : prevAskFee;\n        uint256 gamma = feeUsed < WAD ? WAD - feeUsed : 0;\n        uint256 pImplied;\n        if (gamma == 0) { pImplied = spot; }\n        else { pImplied = trade.isBuy ? wmul(spot, gamma) : wdiv(spot, gamma); }\n\n        // S: infer a no-trade interval center from the last post-trade spot.\n        uint256 silenceScale = WAD;\n        if (firstInStep && silent > 1) {\n            uint256 g = silent - 1;\n            if (g > 1) g = 1;\n            uint256 w = WAD - _powWad(800000000000000000, g);\n            uint256 s = slots[16];\n            if (s == 0) s = pHat;\n            uint256 c = (wmul(s, WAD - prevBidFee) + wdiv(s, WAD - prevAskFee)) / 2;\n            if (c >= pHat) pHat += wmul(w, c - pHat);\n            else pHat -= wmul(w, pHat - c);\n            silenceScale = WAD - wmul(300000000000000000, w);\n        }\n\n        {\n            uint256 ret = pHat > 0 ? wdiv(absDiff(pImplied, pHat), pHat) : 0;\n            uint256 alpha = firstInStep ? PHAT_ALPHA : PHAT_ALPHA_RETAIL;\n            uint256 prePhat = pHat;\n            bool secondPrint = !firstInStep && stepTradeCount == 1;\n            bool sameDir = false; bool oppDir = false;\n            if (secondPrint) {\n                bool up2 = pImplied >= pHat;\n                uint256 d1 = slots[12];\n                if (d1 != 0) { sameDir = (d1 == 1) == up2; oppDir = !sameDir; }\n                if (sameDir) alpha = PHAT_ALPHA_SAME;\n            }\n            if (firstInStep) { slots[11] = pHat; slots[12] = pImplied >= pHat ? 1 : 2; }\n            uint256 adaptiveGate = wmul(sigmaHat, GATE_SIGMA_MULT);\n            if (adaptiveGate < MIN_GATE) adaptiveGate = MIN_GATE;\n            alpha = wmul(alpha, silenceScale);\n            adaptiveGate = wmul(adaptiveGate, silenceScale);\n            if (ret <= adaptiveGate) { pHat = wmul(pHat, WAD - alpha) + wmul(pImplied, alpha); }\n            if (oppDir && REVERT_U > 0) {\n                uint256 pre = slots[11];\n                if (pre > pHat) pHat = pHat + wmul(pre - pHat, REVERT_U);\n                else pHat = pHat - wmul(pHat - pre, REVERT_U);\n            }\n            if (firstInStep) {\n                if (ret > RET_CAP) ret = RET_CAP;\n                sigmaHat = wmul(sigmaHat, SIGMA_DECAY) + wmul(ret, WAD - SIGMA_DECAY);\n            }\n        }\n\n        // Interior retail routing equalizes fee-adjusted marginal prices.\n        // Subsequent trades in a step cannot be the initial arbitrage trade.\n        if (!firstInStep && feeUsed > 30 * BPS && gamma > 0) {\n            uint256 normalSpot = trade.isBuy\n                ? wdiv(wmul(spot, gamma), WAD - 30 * BPS)\n                : wdiv(wmul(spot, WAD - 30 * BPS), gamma);\n            pHat = wmul(pHat, 90 * WAD / 100) + wmul(normalSpot, 10 * WAD / 100);\n        }\n\n        {\n            uint256 ret = fastHat > 0 ? wdiv(absDiff(pImplied, fastHat), fastHat) : 0;\n            uint256 alpha;\n            if (firstInStep) {\n                uint256 processSigma = sigmaForFast;\n                uint256 obsVar = uncertainty + wmul(processSigma, processSigma);\n                uint256 probArb;\n                uint256 z2 = wdiv(wmul(ret, ret), obsVar);\n                uint256 density = _powWad(wdiv(WAD, WAD + z2 / 16), 8);\n                uint256 sigmaObs = sqrt(obsVar * WAD);\n                uint256 odds = wmul(density, wdiv(6700000000000000, sigmaObs));\n                bool arbFlag = ret <= wmul(sigmaForFast, 1220000000000000000);\n                uint256 prior = arbFlag ? 650000000000000000 : 400000000000000000;\n                uint256 tr = trade.reserveY > 0 ? wdiv(trade.amountY, trade.reserveY) : 0;\n                if (tr > 3000000000000000) prior = wmul(prior, 6 * WAD / 10);\n                if (silent > 1) prior = wmul(prior, 8 * WAD / 10);\n                odds = wmul(odds, wdiv(prior, WAD - prior));\n                probArb = wdiv(odds, WAD + odds);\n                alpha = wmul(probArb, 600000000000000000) + wmul(WAD - probArb, 80000000000000000);\n                slots[15] = pImplied >= fastHat ? 1 : 2;\n                uncertainty = wmul(uncertainty, WAD - alpha);\n            } else {\n                if ((slots[15] == 1) == (pImplied >= fastHat)) alpha = PHAT_ALPHA_RETAIL;\n            }\n            uint256 gate = wmul(sigmaHat, GATE_SIGMA_MULT);\n            if (gate < MIN_GATE) gate = MIN_GATE;\n            if (ret <= gate) fastHat = wmul(fastHat, WAD - alpha) + wmul(pImplied, alpha);\n            slots[13] = uncertainty;\n        }\n\n        if (!firstInStep && feeUsed > 30 * BPS && gamma > 0) {\n            uint256 normalObs = trade.isBuy\n                ? wdiv(wmul(spot, gamma), WAD - 30 * BPS)\n                : wdiv(wmul(spot, WAD - 30 * BPS), gamma);\n            if ((slots[15] == 1) == (normalObs >= fastHat)) {\n                fastHat = wmul(fastHat, 9 * WAD / 10) + wmul(normalObs, WAD / 10);\n            }\n        }\n        slots[14] = fastHat;\n        uint256 tradeRatio = trade.reserveY > 0 ? wdiv(trade.amountY, trade.reserveY) : 0;\n        if (tradeRatio > TRADE_RATIO_CAP) tradeRatio = TRADE_RATIO_CAP;\n\n        if (tradeRatio > SIGNAL_THRESHOLD) {\n            uint256 push = tradeRatio * DIR_IMPACT_MULT;\n            if (push > WAD / 4) push = WAD / 4;\n            if (trade.isBuy) {\n                dirState = dirState + push;\n                if (dirState > 2 * WAD) dirState = 2 * WAD;\n            } else {\n                dirState = dirState > push ? dirState - push : 0;\n            }\n            actEma = wmul(actEma, ACT_BLEND_DECAY) + wmul(tradeRatio, WAD - ACT_BLEND_DECAY);\n            sizeHat = wmul(sizeHat, SIZE_BLEND_DECAY) + wmul(tradeRatio, WAD - SIZE_BLEND_DECAY);\n            if (sizeHat > WAD) sizeHat = WAD;\n        }\n\n        uint256 tox = pHat > 0 ? wdiv(absDiff(spot, pHat), pHat) : 0;\n        if (tox > TOX_CAP) tox = TOX_CAP;\n        toxEma = wmul(toxEma, TOX_BLEND_DECAY) + wmul(tox, WAD - TOX_BLEND_DECAY);\n        uint256 toxSignal = toxEma;\n\n        stepTradeCount = stepTradeCount + 1;\n        if (stepTradeCount > STEP_COUNT_CAP) stepTradeCount = STEP_COUNT_CAP;\n\n        // Keep V2's price blend fixed. Widths are relative fair-price uncertainty.\n        uint256 fair = wmul(pHat, 700000000000000000) + wmul(fastHat, 300000000000000000);\n        uint256 flowSize = wmul(lambdaHat, sizeHat);\n        uint256 protect = 12 * BPS + wmul(sigmaHat, 350000000000000000)\n            + wmul(flowSize, 400000000000000000) + wmul(tradeRatio, 200000000000000000);\n        uint256 attract = 24 * BPS + wmul(sigmaHat, 200000000000000000)\n            + wmul(flowSize, 300000000000000000);\n        // Bound each interval width before converting it into a fee.\n        if (protect > 150 * BPS) protect = 150 * BPS;\n        if (attract > 80 * BPS) attract = 80 * BPS;\n        bool high = spot >= fair;\n        uint256 lower = wmul(fair, WAD - (high ? protect : attract));\n        uint256 upper = wmul(fair, WAD + (high ? attract : protect));\n        uint256 bidFee = spot > lower ? wdiv(spot - lower, spot) : 0;\n        uint256 askFee = upper > spot ? wdiv(upper - spot, upper) : 0;\n        // Protective quotes may retreat further than liquidity-attracting quotes.\n        uint256 bidCap = high ? 250 * BPS : 45 * BPS;\n        uint256 askCap = high ? 45 * BPS : 250 * BPS;\n        if (bidFee > bidCap) bidFee = bidCap;\n        if (askFee > askCap) askFee = askCap;\n        if (bidFee < BPS) bidFee = BPS;\n        if (askFee < BPS) askFee = BPS;\n\n        slots[0] = bidFee; slots[1] = askFee; slots[2] = trade.timestamp;\n        slots[3] = dirState; slots[4] = actEma; slots[5] = pHat;\n        slots[6] = sigmaHat; slots[7] = lambdaHat; slots[8] = sizeHat;\n        slots[16] = spot;\n        slots[9] = toxEma; slots[10] = stepTradeCount;\n\n        return (bidFee, askFee);\n    }\n\n    function _powWad(uint256 factor, uint256 exp) internal pure returns (uint256 result) {\n        result = WAD;\n        while (exp > 0) {\n            if (exp & 1 == 1) result = wmul(result, factor);\n            factor = wmul(factor, factor);\n            exp >>= 1;\n        }\n    }\n\n    function _decayCentered(uint256 centered, uint256 decayFactor, uint256 elapsed) internal pure returns (uint256) {\n        uint256 mul = _powWad(decayFactor, elapsed);\n        if (centered >= WAD) { return WAD + wmul(centered - WAD, mul); }\n        uint256 below = wmul(WAD - centered, mul);\n        return below < WAD ? WAD - below : 0;\n    }\n\n    function getName() external pure override returns (string memory) { return \"corridor_p12a24\"; }\n}\n","sha256":"cb935deb4ca8bc0b01c15b1df63e119a90bdc069215c9b8de735a8f6dc9df0e7","paired":{"n":0,"mean_diff":null,"se":null,"worst":[]},"gas":{"max_ok":242492,"oog":4,"other_reverts":0,"other_halts":0,"execution_errors":0,"sha256":"cb935deb4ca8bc0b01c15b1df63e119a90bdc069215c9b8de735a8f6dc9df0e7","bytecode_keccak":"42d520c3528e0b948058aa7b6b10a2eac2d7ce0b5603a86f350d63896ba8c394","n_simulations":64,"stages":{"deployment":[64,1389403,0,0,0,0],"name":[64,21536,0,0,0,0],"initialize":[64,236368,0,0,0,0],"swap":[318639,242492,4,0,0,0]}},"baseline_gas":{"max_ok":243554,"oog":4,"other_reverts":0,"other_halts":0,"execution_errors":0,"sha256":"28417e116f57f1029fdd1803832e852574902c1ae7253c05657f317db76da4ab","bytecode_keccak":"369eada8e43393968ef8975d4e4570434e3308edfd7da9c50d901de7c2ff71a2","n_simulations":64,"stages":{"deployment":[64,1560600,0,0,0,0],"name":[64,21545,0,0,0,0],"initialize":[64,236377,0,0,0,0],"swap":[652602,243554,4,0,0,0]}},"valid":false,"blocked":{"step":"V2 baseline gas validation on seeds 10000..10063","error":"The required exact-hash V2 baseline incurred 4 EVM OutOfGas halts at the unchanged 250000 afterSwap gas limit. They were swallowed by the simulator fallback. The corridor gas-only check also incurred 4 OutOfGas halts. Any OOG invalidates the result, so no paired gain is reported and no confirmation seeds were consumed."},"conclusion":"Gas-invalid experimental corridor implementation supplied for diagnosis only. Both candidate and required exact-hash baseline failed the gas gate on the initial block. Do not promote this code. No performance claim, no tuning winner, and no leaderboard submission.","rule":{"name":"Asymmetric fair-price corridor","status":"p12a24 was selected for a gas-only check without examining candidate performance; other generated variants were not run.","parameters":{"protect_base_bps":12,"attract_base_bps":24,"protect_sigma_wad":350000000000000000,"attract_sigma_wad":200000000000000000,"protect_flow_wad":400000000000000000,"attract_flow_wad":300000000000000000,"protect_trade_wad":200000000000000000,"protect_width_cap_bps":150,"attract_width_cap_bps":80,"protect_fee_cap_bps":250,"attract_fee_cap_bps":45,"fee_floor_bps":1,"initial_fee_bps":4},"fair":"0.7*pHat + 0.3*fastHat, unchanged from V2","widths":"protect=min(150bps,12bps+0.35*sigmaHat+0.40*lambdaHat*sizeHat+0.20*tradeRatio); attract=min(80bps,24bps+0.20*sigmaHat+0.30*lambdaHat*sizeHat). Solidity uses WAD fractions and truncating arithmetic.","conversion":"When spot>=fair, lower=fair*(1-protect) and upper=fair*(1+attract); otherwise exchange the widths. bid=max(0,1-lower/spot); ask=max(0,1-spot/upper). Clamp to a 1bps floor and side-specific protective/attracting fee caps.","estimators":"V2 estimator update logic and 70/30 price blend retained; only observable inputs. Removed old additive midfee/skew/staleness/trade-boost/tail fee mapping. Unused mapping constants and tail helper removed."},"tuning":{"status":"Aborted at baseline gas gate","planned_variants":[{"id":"p4a12","protect_base_bps":4,"attract_base_bps":12,"sha256":"30caab068bc1aeae7dd9006e9d30337c77cc05b759fc3d8b750170a363b07799"},{"id":"p4a24","protect_base_bps":4,"attract_base_bps":24,"sha256":"4b49c5454987b73575f7f9601f134d25e57a938c47f26c86f51034f778134ba5"},{"id":"p4a36","protect_base_bps":4,"attract_base_bps":36,"sha256":"2c4f08aa9cd2ddecc77697e57022f4316d6b9306c52f50e6dc5e1b51d94856fe"},{"id":"p4a48","protect_base_bps":4,"attract_base_bps":48,"sha256":"d3e2119c7e2c44d807b369f61fd7eac37f997910d60f85ff642e5396bc1c9cdc"},{"id":"p12a12","protect_base_bps":12,"attract_base_bps":12,"sha256":"8574c13a1c19a7ffb10d9c3b846bc95234abad961b7e3c230bf7838aacbf0d77"},{"id":"p12a24","protect_base_bps":12,"attract_base_bps":24,"sha256":"cb935deb4ca8bc0b01c15b1df63e119a90bdc069215c9b8de735a8f6dc9df0e7"},{"id":"p12a36","protect_base_bps":12,"attract_base_bps":36,"sha256":"2bee3fc2f4ecc89b0199e8bacbc378809fc5f9e0bf1b4e29aea6f0cfbbb8c196"},{"id":"p12a48","protect_base_bps":12,"attract_base_bps":48,"sha256":"07f37e91529ac4411058aeaede18b3f03e4362bed76a7910d2f619bb2367be59"},{"id":"p24a12","protect_base_bps":24,"attract_base_bps":12,"sha256":"a4bf495a90ab99522e53d2445047c77569a58c32e4e17bda673da938e733844f"},{"id":"p24a24","protect_base_bps":24,"attract_base_bps":24,"sha256":"4f5edffa029a9ef5481a9aeda2b185aad1204f0b065119e8ca3e50e2acce09d8"},{"id":"p24a36","protect_base_bps":24,"attract_base_bps":36,"sha256":"9a4e867ca8235ad5bc70f2b546a3b912679d9ae9effa0894a267cb6d48ec8085"},{"id":"p24a48","protect_base_bps":24,"attract_base_bps":48,"sha256":"3161bb67b5f5ce423251e02a02f58e8c1840e44e8aafbdf3ffc582c3c9573e41"}],"evaluated_variants":[{"id":"p12a24","sha256":"cb935deb4ca8bc0b01c15b1df63e119a90bdc069215c9b8de735a8f6dc9df0e7","purpose":"gas safety only","gas":{"max_ok":242492,"oog":4,"other_reverts":0,"other_halts":0,"execution_errors":0,"sha256":"cb935deb4ca8bc0b01c15b1df63e119a90bdc069215c9b8de735a8f6dc9df0e7","bytecode_keccak":"42d520c3528e0b948058aa7b6b10a2eac2d7ce0b5603a86f350d63896ba8c394","n_simulations":64,"stages":{"deployment":[64,1389403,0,0,0,0],"name":[64,21536,0,0,0,0],"initialize":[64,236368,0,0,0,0],"swap":[318639,242492,4,0,0,0]}},"initialization_valid":true}],"initial_baseline_completed":true,"top_two_evaluated":false,"frozen_for_confirmation":false,"confirmation_performed":false,"retuned_after_confirmation":false},"seeds":{"baseline":{"start":10000,"end":10063,"n":64},"candidate":{"start":10000,"end":10063,"n":64},"counter_probes":{"seed":10000,"n_steps":10,"note":"Distinct probe contracts, not candidate performance runs."},"finalist_block":{"start":11000,"end":11255,"used":false},"confirmation":{"start":4000000,"end":4001999,"used":false},"measured_run_n_steps":10000,"workers":8,"markets":"V2 and corridor each run separately against VanillaStrategy; never head-to-head.","configuration":"numpy.random.default_rng(seed): uniform size [19,21], rate [0.6,1.0], sigma [0.000882,0.001008], in that order. Other fields from pinned build_config: price=100, reserves=(100,10000), mu=0, dt=1, retail size sigma=1.2, buy probability=0.5. Price RNG seed=seed; retail RNG seed=seed+1."},"reproduce":{"repository":"https://github.com/benedictbrady/amm-challenge","commit":"6b6921f8d463314aa7c96234e1be25a25245f704","baseline_url":"https://api.imd.fun/artifacts/1f4f14f040b309e004904672ec6e2bb051f97b8d1195602d36b35a54c05d6c0f","baseline_code":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.24;\n\nimport {AMMStrategyBase} from \"./AMMStrategyBase.sol\";\nimport {TradeInfo} from \"./IAMMStrategy.sol\";\n\ncontract Strategy is AMMStrategyBase {\n    uint256 constant ELAPSED_CAP = 8;\n    uint256 constant SIGNAL_THRESHOLD = WAD / 650;\n    uint256 constant DIR_DECAY = 750000000000000000;\n    uint256 constant ACT_DECAY = 530000000000000000;\n    uint256 constant SIZE_DECAY = 530000000000000000;\n    uint256 constant TOX_DECAY = 910000000000000000;\n    uint256 constant SIGMA_DECAY = 690000000000000000;\n    uint256 constant LAMBDA_DECAY = 990000000000000000;\n    uint256 constant SIZE_BLEND_DECAY = 828000000000000000;\n    uint256 constant TOX_BLEND_DECAY = 51000000000000000;\n    uint256 constant ACT_BLEND_DECAY = 985000000000000000;\n    uint256 constant PHAT_ALPHA = 270000000000000000;\n    uint256 constant PHAT_ALPHA_RETAIL = 60000000000000000;\n    uint256 constant PHAT_ALPHA_SAME = 120000000000000000;\n    uint256 constant REVERT_U = 0;\n    uint256 constant DIR_IMPACT_MULT = 4;\n    uint256 constant GATE_SIGMA_MULT = 7200000000000000000;\n    uint256 constant MIN_GATE = 30000000000000000;\n    uint256 constant TRADE_TOX_BOOST = 3500 * BPS;\n    uint256 constant STALE_ATTRACT_FRAC = 1050000000000000000;\n    uint256 constant RET_CAP = WAD / 35;\n    uint256 constant TOX_CAP = WAD / 5;\n    uint256 constant TRADE_RATIO_CAP = WAD / 5;\n    uint256 constant LAMBDA_CAP = 1820000000000000000;\n    uint256 constant STEP_COUNT_CAP = 64;\n    uint256 constant BASE_FEE = 4 * BPS;\n    uint256 constant SIGMA_COEF = 200000000000000000;\n    uint256 constant LAMBDA_COEF = 12 * BPS;\n    uint256 constant FLOW_SIZE_COEF = 4842 * BPS;\n    uint256 constant TOX_COEF = 300 * BPS;\n    uint256 constant TOX_QUAD_COEF = 15000 * BPS;\n    uint256 constant ACT_COEF = 91843 * BPS;\n    uint256 constant DIR_COEF = 20 * BPS;\n    uint256 constant DIR_TOX_COEF = 100 * BPS;\n    uint256 constant STALE_DIR_COEF = 6850 * BPS;\n    uint256 constant SIGMA_TOX_COEF = 500 * BPS;\n    uint256 constant TAIL_KNEE = 600 * BPS;\n    uint256 constant TAIL_SLOPE_PROTECT = 930000000000000000;\n    uint256 constant TAIL_SLOPE_ATTRACT = 850000000000000000;\n\n    function afterInitialize(uint256 initialX, uint256 initialY) external override returns (uint256, uint256) {\n        slots[0] = BASE_FEE; slots[1] = BASE_FEE; slots[2] = 0; slots[3] = WAD; slots[4] = 0;\n        slots[5] = initialX > 0 ? wdiv(initialY, initialX) : 100 * WAD;\n        slots[6] = 950000000000000; slots[7] = 800000000000000000; slots[8] = 2000000000000000;\n        slots[13] = 902500000000; slots[14] = slots[5]; slots[15] = 0; slots[9] = 0; slots[10] = 0; slots[11] = 0; slots[12] = 0;\n        return (BASE_FEE, BASE_FEE);\n    }\n\n    function afterSwap(TradeInfo calldata trade) external override returns (uint256, uint256) {\n        uint256 prevBidFee = slots[0]; uint256 prevAskFee = slots[1]; uint256 lastTs = slots[2];\n        uint256 dirState = slots[3]; uint256 actEma = slots[4]; uint256 pHat = slots[5];\n        uint256 sigmaHat = slots[6]; uint256 lambdaHat = slots[7]; uint256 sizeHat = slots[8];\n        uint256 toxEma = slots[9]; uint256 stepTradeCount = slots[10];\n\n        uint256 sigmaForFast = sigmaHat;\n        uint256 fastHat = slots[14];\n        uint256 uncertainty = slots[13];\n        uint256 silent = trade.timestamp > lastTs ? trade.timestamp - lastTs : 0;\n        bool isNewStep = trade.timestamp > lastTs;\n        if (isNewStep) {\n            uint256 elapsedRaw = trade.timestamp - lastTs;\n            uint256 elapsed = elapsedRaw > ELAPSED_CAP ? ELAPSED_CAP : elapsedRaw;\n            dirState = _decayCentered(dirState, DIR_DECAY, elapsed);\n            actEma = wmul(actEma, _powWad(ACT_DECAY, elapsed));\n            sizeHat = wmul(sizeHat, _powWad(SIZE_DECAY, elapsed));\n            toxEma = wmul(toxEma, _powWad(TOX_DECAY, elapsed));\n            if (stepTradeCount > 0 && elapsedRaw > 0) {\n                uint256 lambdaInst = (stepTradeCount * WAD) / elapsedRaw;\n                if (lambdaInst > LAMBDA_CAP) lambdaInst = LAMBDA_CAP;\n                lambdaHat = wmul(lambdaHat, LAMBDA_DECAY) + wmul(lambdaInst, WAD - LAMBDA_DECAY);\n            }\n            uncertainty += wmul(sigmaForFast, sigmaForFast) * elapsedRaw;\n            if (uncertainty > 100000000000000) uncertainty = 100000000000000;\n            stepTradeCount = 0;\n        }\n\n        bool firstInStep = stepTradeCount == 0;\n        uint256 spot = trade.reserveX > 0 ? wdiv(trade.reserveY, trade.reserveX) : pHat;\n        if (pHat == 0) pHat = spot;\n\n        uint256 feeUsed = trade.isBuy ? prevBidFee : prevAskFee;\n        uint256 gamma = feeUsed < WAD ? WAD - feeUsed : 0;\n        uint256 pImplied;\n        if (gamma == 0) { pImplied = spot; }\n        else { pImplied = trade.isBuy ? wmul(spot, gamma) : wdiv(spot, gamma); }\n\n        // S: infer a no-trade interval center from the last post-trade spot.\n        uint256 silenceScale = WAD;\n        if (firstInStep && silent > 1) {\n            uint256 g = silent - 1;\n            if (g > 1) g = 1;\n            uint256 w = WAD - _powWad(800000000000000000, g);\n            uint256 s = slots[16];\n            if (s == 0) s = pHat;\n            uint256 c = (wmul(s, WAD - prevBidFee) + wdiv(s, WAD - prevAskFee)) / 2;\n            if (c >= pHat) pHat += wmul(w, c - pHat);\n            else pHat -= wmul(w, pHat - c);\n            silenceScale = WAD - wmul(300000000000000000, w);\n        }\n\n        {\n            uint256 ret = pHat > 0 ? wdiv(absDiff(pImplied, pHat), pHat) : 0;\n            uint256 alpha = firstInStep ? PHAT_ALPHA : PHAT_ALPHA_RETAIL;\n            uint256 prePhat = pHat;\n            bool secondPrint = !firstInStep && stepTradeCount == 1;\n            bool sameDir = false; bool oppDir = false;\n            if (secondPrint) {\n                bool up2 = pImplied >= pHat;\n                uint256 d1 = slots[12];\n                if (d1 != 0) { sameDir = (d1 == 1) == up2; oppDir = !sameDir; }\n                if (sameDir) alpha = PHAT_ALPHA_SAME;\n            }\n            if (firstInStep) { slots[11] = pHat; slots[12] = pImplied >= pHat ? 1 : 2; }\n            uint256 adaptiveGate = wmul(sigmaHat, GATE_SIGMA_MULT);\n            if (adaptiveGate < MIN_GATE) adaptiveGate = MIN_GATE;\n            alpha = wmul(alpha, silenceScale);\n            adaptiveGate = wmul(adaptiveGate, silenceScale);\n            if (ret <= adaptiveGate) { pHat = wmul(pHat, WAD - alpha) + wmul(pImplied, alpha); }\n            if (oppDir && REVERT_U > 0) {\n                uint256 pre = slots[11];\n                if (pre > pHat) pHat = pHat + wmul(pre - pHat, REVERT_U);\n                else pHat = pHat - wmul(pHat - pre, REVERT_U);\n            }\n            if (firstInStep) {\n                if (ret > RET_CAP) ret = RET_CAP;\n                sigmaHat = wmul(sigmaHat, SIGMA_DECAY) + wmul(ret, WAD - SIGMA_DECAY);\n            }\n        }\n\n        // Interior retail routing equalizes fee-adjusted marginal prices.\n        // Subsequent trades in a step cannot be the initial arbitrage trade.\n        if (!firstInStep && feeUsed > 30 * BPS && gamma > 0) {\n            uint256 normalSpot = trade.isBuy\n                ? wdiv(wmul(spot, gamma), WAD - 30 * BPS)\n                : wdiv(wmul(spot, WAD - 30 * BPS), gamma);\n            pHat = wmul(pHat, 90 * WAD / 100) + wmul(normalSpot, 10 * WAD / 100);\n        }\n\n        {\n            uint256 ret = fastHat > 0 ? wdiv(absDiff(pImplied, fastHat), fastHat) : 0;\n            uint256 alpha;\n            if (firstInStep) {\n                uint256 processSigma = sigmaForFast;\n                uint256 obsVar = uncertainty + wmul(processSigma, processSigma);\n                uint256 probArb;\n                uint256 z2 = wdiv(wmul(ret, ret), obsVar);\n                uint256 density = _powWad(wdiv(WAD, WAD + z2 / 16), 8);\n                uint256 sigmaObs = sqrt(obsVar * WAD);\n                uint256 odds = wmul(density, wdiv(6700000000000000, sigmaObs));\n                bool arbFlag = ret <= wmul(sigmaForFast, 1220000000000000000);\n                uint256 prior = arbFlag ? 650000000000000000 : 400000000000000000;\n                uint256 tr = trade.reserveY > 0 ? wdiv(trade.amountY, trade.reserveY) : 0;\n                if (tr > 3000000000000000) prior = wmul(prior, 6 * WAD / 10);\n                if (silent > 1) prior = wmul(prior, 8 * WAD / 10);\n                odds = wmul(odds, wdiv(prior, WAD - prior));\n                probArb = wdiv(odds, WAD + odds);\n                alpha = wmul(probArb, 600000000000000000) + wmul(WAD - probArb, 80000000000000000);\n                slots[15] = pImplied >= fastHat ? 1 : 2;\n                uncertainty = wmul(uncertainty, WAD - alpha);\n            } else {\n                if ((slots[15] == 1) == (pImplied >= fastHat)) alpha = PHAT_ALPHA_RETAIL;\n            }\n            uint256 gate = wmul(sigmaHat, GATE_SIGMA_MULT);\n            if (gate < MIN_GATE) gate = MIN_GATE;\n            if (ret <= gate) fastHat = wmul(fastHat, WAD - alpha) + wmul(pImplied, alpha);\n            slots[13] = uncertainty;\n        }\n\n        if (!firstInStep && feeUsed > 30 * BPS && gamma > 0) {\n            uint256 normalObs = trade.isBuy\n                ? wdiv(wmul(spot, gamma), WAD - 30 * BPS)\n                : wdiv(wmul(spot, WAD - 30 * BPS), gamma);\n            if ((slots[15] == 1) == (normalObs >= fastHat)) {\n                fastHat = wmul(fastHat, 9 * WAD / 10) + wmul(normalObs, WAD / 10);\n            }\n        }\n        slots[14] = fastHat;\n        uint256 tradeRatio = trade.reserveY > 0 ? wdiv(trade.amountY, trade.reserveY) : 0;\n        if (tradeRatio > TRADE_RATIO_CAP) tradeRatio = TRADE_RATIO_CAP;\n\n        if (tradeRatio > SIGNAL_THRESHOLD) {\n            uint256 push = tradeRatio * DIR_IMPACT_MULT;\n            if (push > WAD / 4) push = WAD / 4;\n            if (trade.isBuy) {\n                dirState = dirState + push;\n                if (dirState > 2 * WAD) dirState = 2 * WAD;\n            } else {\n                dirState = dirState > push ? dirState - push : 0;\n            }\n            actEma = wmul(actEma, ACT_BLEND_DECAY) + wmul(tradeRatio, WAD - ACT_BLEND_DECAY);\n            sizeHat = wmul(sizeHat, SIZE_BLEND_DECAY) + wmul(tradeRatio, WAD - SIZE_BLEND_DECAY);\n            if (sizeHat > WAD) sizeHat = WAD;\n        }\n\n        uint256 tox = pHat > 0 ? wdiv(absDiff(spot, pHat), pHat) : 0;\n        if (tox > TOX_CAP) tox = TOX_CAP;\n        toxEma = wmul(toxEma, TOX_BLEND_DECAY) + wmul(tox, WAD - TOX_BLEND_DECAY);\n        uint256 toxSignal = toxEma;\n\n        stepTradeCount = stepTradeCount + 1;\n        if (stepTradeCount > STEP_COUNT_CAP) stepTradeCount = STEP_COUNT_CAP;\n\n        uint256 flowSize = wmul(lambdaHat, sizeHat);\n        uint256 fBase = BASE_FEE + wmul(SIGMA_COEF, sigmaHat) + wmul(LAMBDA_COEF, lambdaHat) + wmul(FLOW_SIZE_COEF, flowSize);\n        uint256 fMid = fBase + wmul(TOX_COEF, toxSignal) + wmul(TOX_QUAD_COEF, wmul(toxSignal, toxSignal)) + wmul(ACT_COEF, actEma);\n        fMid = fMid + wmul(SIGMA_TOX_COEF, wmul(sigmaHat, toxSignal));\n\n        uint256 dirDev; bool sellPressure;\n        if (dirState >= WAD) { dirDev = dirState - WAD; sellPressure = true; }\n        else { dirDev = WAD - dirState; sellPressure = false; }\n\n        uint256 skew = wmul(DIR_COEF, dirDev) + wmul(DIR_TOX_COEF, wmul(dirDev, toxSignal));\n        uint256 bidFee; uint256 askFee;\n        if (sellPressure) {\n            bidFee = fMid + skew;\n            askFee = fMid > skew ? fMid - skew : 0;\n        } else {\n            askFee = fMid + skew;\n            bidFee = fMid > skew ? fMid - skew : 0;\n        }\n\n        {\n            uint256 staleHat = wmul(pHat, 700000000000000000) + wmul(fastHat, 300000000000000000);\n            uint256 staleTox = wdiv(absDiff(spot, staleHat), staleHat);\n            if (staleTox > TOX_CAP) staleTox = TOX_CAP;\n            uint256 staleShift = wmul(STALE_DIR_COEF, staleTox);\n            uint256 attractShift = wmul(staleShift, STALE_ATTRACT_FRAC);\n            if (spot >= staleHat) {\n                bidFee = bidFee + staleShift;\n                askFee = askFee > attractShift ? askFee - attractShift : 0;\n            } else {\n                askFee = askFee + staleShift;\n                bidFee = bidFee > attractShift ? bidFee - attractShift : 0;\n            }\n        }\n\n        {\n            bool tradeAligned = (trade.isBuy && spot >= pHat) || (!trade.isBuy && spot < pHat);\n            if (tradeAligned) {\n                uint256 tradeBoost = wmul(TRADE_TOX_BOOST, tradeRatio);\n                if (trade.isBuy) { bidFee = bidFee + tradeBoost; }\n                else { askFee = askFee + tradeBoost; }\n            }\n        }\n\n        if (sellPressure) {\n            bidFee = clampFee(_compressTailWithSlope(bidFee, TAIL_SLOPE_PROTECT));\n            askFee = clampFee(_compressTailWithSlope(askFee, TAIL_SLOPE_ATTRACT));\n        } else {\n            askFee = clampFee(_compressTailWithSlope(askFee, TAIL_SLOPE_PROTECT));\n            bidFee = clampFee(_compressTailWithSlope(bidFee, TAIL_SLOPE_ATTRACT));\n        }\n\n        slots[0] = bidFee; slots[1] = askFee; slots[2] = trade.timestamp;\n        slots[3] = dirState; slots[4] = actEma; slots[5] = pHat;\n        slots[6] = sigmaHat; slots[7] = lambdaHat; slots[8] = sizeHat;\n        slots[16] = spot;\n        slots[9] = toxEma; slots[10] = stepTradeCount;\n\n        return (bidFee, askFee);\n    }\n\n    function _compressTailWithSlope(uint256 fee, uint256 slope) internal pure returns (uint256) {\n        if (fee <= TAIL_KNEE) return fee;\n        return TAIL_KNEE + wmul(fee - TAIL_KNEE, slope);\n    }\n\n    function _powWad(uint256 factor, uint256 exp) internal pure returns (uint256 result) {\n        result = WAD;\n        while (exp > 0) {\n            if (exp & 1 == 1) result = wmul(result, factor);\n            factor = wmul(factor, factor);\n            exp >>= 1;\n        }\n    }\n\n    function _decayCentered(uint256 centered, uint256 decayFactor, uint256 elapsed) internal pure returns (uint256) {\n        uint256 mul = _powWad(decayFactor, elapsed);\n        if (centered >= WAD) { return WAD + wmul(centered - WAD, mul); }\n        uint256 below = wmul(WAD - centered, mul);\n        return below < WAD ? WAD - below : 0;\n    }\n\n    function getName() external pure override returns (string memory) { return \"no_cubic\"; }\n}\n","baseline_sha256":"28417e116f57f1029fdd1803832e852574902c1ae7253c05657f317db76da4ab","baseline_replacements":{"if (g > 4) g = 4;":"if (g > 1) g = 1;","_powWad(925000000000000000, g)":"_powWad(800000000000000000, g)"},"compiler":"solc 0.8.24, optimizer enabled/runs=200, viaIR=true, evmVersion=paris; pinned SolidityCompiler and SolidityValidator. Built-in VanillaStrategy compiled under its actual contract name.","setup_status":"Setup script ran once and succeeded; StarterStrategy passed amm-match validate.","setup_source":"set -eu;R=$PWD/scratch;mkdir -p $R/tmp $R/bin $R/solcx\necho \"export TMPDIR=$R/tmp XDG_CACHE_HOME=$R/xc UV_CACHE_DIR=$R/uvc UV_PYTHON_INSTALL_DIR=$R/uvpy RUSTUP_HOME=$R/rustup CARGO_HOME=$R/cargo SOLCX_BINARY_PATH=$R/solcx VIRTUAL_ENV=$PWD/.venv PATH=$PWD/.venv/bin:$R/bin:$R/cargo/bin:\\$PATH\" >$R/env.sh;. $R/env.sh\ncommand -v uv >/dev/null||{ curl -LsSf https://github.com/astral-sh/uv/releases/latest/download/uv-x86_64-unknown-linux-gnu.tar.gz|tar --no-same-owner -xz -C $R/tmp;cp $R/tmp/uv-*/uv $R/bin/;}\ncc --version >/dev/null 2>&1||{ curl -Ls https://micro.mamba.pm/api/micromamba/linux-64/latest -o $R/tmp/mm.tbz;python3 -c \"import sys,tarfile;tarfile.open(sys.argv[1]).extract('bin/micromamba',sys.argv[2])\" $R/tmp/mm.tbz $R;MAMBA_ROOT_PREFIX=$R/mamba $R/bin/micromamba create -yq -p $R/cenv -c conda-forge gcc;ln -sf $(ls $R/cenv/bin/*gcc|head -n1) $R/bin/cc;}\ncommand -v cargo >/dev/null||{ curl -sSf https://sh.rustup.rs|sh -s -- -y --profile minimal --no-modify-path;}\nuv venv --python 3.12 .venv;uv pip install -e . maturin\nmaturin develop --release --uv --manifest-path amm_sim_rs/Cargo.toml\namm-match validate contracts/src/StarterStrategy.sol\n","counter_patch":"diff --git a/amm_sim_rs/src/evm/strategy.rs b/amm_sim_rs/src/evm/strategy.rs\nindex 1d06af1..d56be6a 100644\n--- a/amm_sim_rs/src/evm/strategy.rs\n+++ b/amm_sim_rs/src/evm/strategy.rs\n@@ -12,6 +12,31 @@ use thiserror::Error;\n use crate::types::trade_info::{encode_after_initialize, decode_fee_pair, TradeInfo, SELECTOR_GET_NAME};\n use crate::types::wad::Wad;\n \n+\n+use std::sync::{Arc, Mutex, OnceLock};\n+use std::sync::atomic::{AtomicU64, Ordering};\n+use std::collections::BTreeMap;\n+#[derive(Default)]\n+pub struct Counters { ok: AtomicU64, max_ok: AtomicU64, oog: AtomicU64, revert: AtomicU64, halt: AtomicU64, error: AtomicU64 }\n+static COUNTERS: OnceLock<Mutex<BTreeMap<String, Arc<[Counters; 4]>>>> = OnceLock::new();\n+fn counters(bytecode: &[u8]) -> Arc<[Counters; 4]> {\n+    let hash = format!(\"{:x}\", revm::primitives::keccak256(bytecode));\n+    COUNTERS.get_or_init(Default::default).lock().unwrap().entry(hash).or_insert_with(|| Arc::new(Default::default())).clone()\n+}\n+fn record(c: &Counters, r: &ExecutionResult) {\n+    match r {\n+        ExecutionResult::Success {gas_used, ..} => { c.ok.fetch_add(1, Ordering::Relaxed); c.max_ok.fetch_max(*gas_used, Ordering::Relaxed); },\n+        ExecutionResult::Revert {..} => { c.revert.fetch_add(1, Ordering::Relaxed); },\n+        ExecutionResult::Halt {reason, ..} => {\n+            if matches!(reason, revm::primitives::HaltReason::OutOfGas(_)) { c.oog.fetch_add(1, Ordering::Relaxed); }\n+            else { c.halt.fetch_add(1, Ordering::Relaxed); }\n+        }\n+    }\n+}\n+pub fn gas_snapshot() -> Vec<(String, Vec<(u64,u64,u64,u64,u64,u64)>)> {\n+    COUNTERS.get_or_init(Default::default).lock().unwrap().iter().map(|(k,v)| (k.clone(), v.iter().map(|c| (c.ok.load(Ordering::Relaxed), c.max_ok.load(Ordering::Relaxed), c.oog.load(Ordering::Relaxed), c.revert.load(Ordering::Relaxed), c.halt.load(Ordering::Relaxed), c.error.load(Ordering::Relaxed))).collect())).collect()\n+}\n+\n /// Errors that can occur during EVM execution.\n #[derive(Error, Debug)]\n pub enum EVMError {\n@@ -48,6 +73,7 @@ const CALLER_ADDRESS: Address = Address::new([\n ///\n /// Wraps a Solidity AMM strategy and executes it using revm.\n pub struct EVMStrategy {\n+    counters: Arc<[Counters; 4]>,\n     /// Strategy name (cached after first call)\n     name: String,\n     /// Compiled bytecode (for reset)\n@@ -62,6 +88,7 @@ impl EVMStrategy {\n     /// Create a new EVM strategy from compiled bytecode.\n     pub fn new(bytecode: Vec<u8>, default_name: String) -> Result<Self, EVMError> {\n         let mut strategy = Self {\n+            counters: counters(&bytecode),\n             name: default_name,\n             bytecode: bytecode.clone(),\n             db: InMemoryDB::default(),\n@@ -102,7 +129,8 @@ impl EVMStrategy {\n                 .build();\n \n             let result = evm.transact_commit()\n-                .map_err(|e| EVMError::DeploymentFailed(format!(\"{:?}\", e)))?;\n+                .map_err(|e| { self.counters[0].error.fetch_add(1, Ordering::Relaxed); EVMError::DeploymentFailed(format!(\"{:?}\", e)) })?;\n+            record(&self.counters[0], &result);\n \n             match result {\n                 ExecutionResult::Success { output, .. } => {\n@@ -195,6 +223,7 @@ impl EVMStrategy {\n \n     /// Make a call to the contract.\n     fn call(&mut self, calldata: &[u8], gas_limit: u64) -> Result<Vec<u8>, EVMError> {\n+        let stage = if calldata.len() == 4 { 1 } else if calldata.len() == 68 { 2 } else { 3 };\n         let mut evm = Evm::builder()\n             .with_db(&mut self.db)\n             .modify_tx_env(|tx| {\n@@ -207,7 +236,8 @@ impl EVMStrategy {\n             .build();\n \n         let result = evm.transact_commit()\n-            .map_err(|e| EVMError::ExecutionFailed(format!(\"{:?}\", e)))?;\n+            .map_err(|e| { self.counters[stage].error.fetch_add(1, Ordering::Relaxed); EVMError::ExecutionFailed(format!(\"{:?}\", e)) })?;\n+        record(&self.counters[stage], &result);\n \n         match result {\n             ExecutionResult::Success { output, .. } => {\ndiff --git a/amm_sim_rs/src/lib.rs b/amm_sim_rs/src/lib.rs\nindex 35d9e59..44c47c4 100644\n--- a/amm_sim_rs/src/lib.rs\n+++ b/amm_sim_rs/src/lib.rs\n@@ -65,10 +65,18 @@ fn run_single(\n         .map_err(|e| PyErr::new::<pyo3::exceptions::PyRuntimeError, _>(e.to_string()))\n }\n \n+#[pyfunction]\n+fn gas_snapshot() -> Vec<(String, Vec<(u64,u64,u64,u64,u64,u64)>)> { crate::evm::strategy::gas_snapshot() }\n+\n+#[pyfunction]\n+fn bytecode_key(b: Vec<u8>) -> String { format!(\"{:x}\", revm::primitives::keccak256(b)) }\n+\n /// Python module definition\n #[pymodule]\n fn amm_sim_rs(m: &Bound<'_, PyModule>) -> PyResult<()> {\n     m.add_function(wrap_pyfunction!(run_batch, m)?)?;\n+    m.add_function(wrap_pyfunction!(gas_snapshot, m)?)?;\n+    m.add_function(wrap_pyfunction!(bytecode_key, m)?)?;\n     m.add_function(wrap_pyfunction!(run_single, m)?)?;\n     m.add_class::<SimulationConfig>()?;\n     m.add_class::<LightweightSimResult>()?;\n","harness_source":"import json, hashlib, time, sys\nfrom pathlib import Path\nimport numpy as np\nimport amm_sim_rs\nfrom amm_competition.evm.compiler import SolidityCompiler\nfrom amm_competition.evm.validator import SolidityValidator\nfrom amm_competition.competition.config import build_config\n\n\ndef configs(start,n):\n    out=[]\n    for seed in range(start,start+n):\n        rng=np.random.default_rng(seed)\n        size=rng.uniform(19.,21.); rate=rng.uniform(.6,1.); sigma=rng.uniform(.000882,.001008)\n        out.append(build_config(seed=seed,gbm_sigma=sigma,retail_arrival_rate=rate,retail_mean_size=size))\n    return out\n\ndef compile_code(path):\n    code=Path(path).read_text(); validation=SolidityValidator().validate(code)\n    assert validation.valid or path == \"contracts/src/VanillaStrategy.sol\", validation.errors\n    comp=SolidityCompiler().compile(code, contract_name=\"VanillaStrategy\" if path == \"contracts/src/VanillaStrategy.sol\" else \"Strategy\")\n    assert comp.success, comp.errors\n    return comp.bytecode\n\ndef paired(a,b):\n    seeds=sorted(map(int,a)); d=np.array([a[str(s)]-b[str(s)] for s in seeds]); ix=np.argsort(d)[:5]\n    return dict(n=len(d),mean_diff=float(d.mean()),se=float(d.std(ddof=1)/np.sqrt(len(d))) if len(d)>1 else None,worst=[dict(seed=seeds[i],diff=float(d[i]),edge=a[str(seeds[i])],v2_edge=b[str(seeds[i])]) for i in ix])\n\ndef run(tag,start,n):\n    out=Path(f'scratch/run_{tag}_{start}_{n}.json')\n    assert not out.exists(), 'refusing to rerun seed block'\n    path=f'scratch/{tag}.sol' if tag!='Vanilla' else 'contracts/src/VanillaStrategy.sol'\n    code=Path(path).read_text(); bc=compile_code(path); vanilla=compile_code('contracts/src/VanillaStrategy.sol')\n    key=amm_sim_rs.bytecode_key(list(bc)); vk=amm_sim_rs.bytecode_key(list(vanilla)); cfg=configs(start,n)\n    t=time.monotonic(); result=amm_sim_rs.run_batch(list(bc),list(vanilla),cfg,8)\n    stats=dict(amm_sim_rs.gas_snapshot())\n    data=dict(id=tag,sha256=hashlib.sha256(code.encode()).hexdigest(),bytecode_keccak=key,seconds=time.monotonic()-t,edges={str(r.seed):r.edges['submission'] for r in result.results},gas=stats[key],vanilla_gas=stats[vk],stats_columns=['ok','max_ok','oog','revert','other_halt','execution_error'],stats_rows=['deployment','name','initialize','swap'])\n    out.write_text(json.dumps(data)); print(json.dumps({k:v for k,v in data.items() if k not in ['edges','vanilla_gas']}),flush=True)\nif __name__=='__main__': run(sys.argv[1],int(sys.argv[2]),int(sys.argv[3]))\n","counter_test_source":"from pathlib import Path\nimport amm_sim_rs\nfrom run import compile_code,configs\nhead='''// SPDX-License-Identifier: MIT\npragma solidity ^0.8.24;\nimport {AMMStrategyBase} from \"./AMMStrategyBase.sol\";\nimport {TradeInfo} from \"./IAMMStrategy.sol\";\ncontract Strategy is AMMStrategyBase {\nfunction afterInitialize(uint256,uint256) external override returns(uint256,uint256) {return (30*BPS,30*BPS);}\nfunction getName() external pure override returns(string memory) {return \"counter_probe\";}\nfunction afterSwap(TradeInfo calldata) external override returns(uint256,uint256) {BODY}\n}\n'''\nv=compile_code('contracts/src/VanillaStrategy.sol'); out={}\nfor name,body in [('oog','while (true) {slots[0] += 1;}'),('revert','revert(\"counter probe\");')]:\n    path=f'scratch/probe_{name}.sol';Path(path).write_text(head.replace('BODY',body)); bc=compile_code(path)\n    cfg=configs(10000,1);cfg[0].n_steps=10\n    amm_sim_rs.run_batch(list(bc),list(v),cfg,8)\n    st=dict(amm_sim_rs.gas_snapshot())[amm_sim_rs.bytecode_key(list(bc))]\n    assert st[2][0]==1 and st[3][2 if name=='oog' else 3]>0, st\n    out[name]=st\nPath('scratch/counter_tests.json').write_text(__import__('json').dumps(out));print(out)\n","counter_test_result":{"oog":[[1,187816,0,0,0,0],[1,21535,0,0,0,0],[1,21800,0,0,0,0],[0,0,10,0,0,0]],"revert":[[1,188308,0,0,0,0],[1,21526,0,0,0,0],[1,21796,0,0,0,0],[0,0,0,10,0,0]]},"file_mapping":{"scratch/setup.sh":"reproduce.setup_source","scratch/counter.patch":"reproduce.counter_patch","scratch/run.py":"reproduce.harness_source","scratch/check_counters.py":"reproduce.counter_test_source","scratch/V2.sol":"reproduce.baseline_code","scratch/p12a24.sol":"code"},"commands":["git clone https://github.com/benedictbrady/amm-challenge test/scratch/amm-challenge","git -C test/scratch/amm-challenge checkout 6b6921f8d463314aa7c96234e1be25a25245f704","cd test/scratch/amm-challenge; extract embedded files according to file_mapping","sh scratch/setup.sh",". scratch/env.sh && git apply scratch/counter.patch && maturin develop --release --uv --manifest-path amm_sim_rs/Cargo.toml",". scratch/env.sh && python scratch/check_counters.py",". scratch/env.sh && python scratch/run.py V2 10000 64",". scratch/env.sh && python scratch/run.py p12a24 10000 64"],"coverage":"Records both evm.transact_commit call sites immediately after ExecutionResult and before wrapper error returns; deployment/name/init/afterSwap are separate. Thus cfmm fallback cannot hide OOG/reverts. External calls are forbidden by the pinned compiler, so these contracts have no nested call-frame halts. Atomic counters keyed by creation-bytecode keccak are mapped to full-source SHA256. All actual candidate and V2 runs are included; probes have distinct hashes. No gas limits changed. Python harness errors were repaired before measurement: built-in VanillaStrategy requires its own contract name and is not a submission named Strategy.","stats_columns":["ok","max_ok","oog","revert","other_halt","execution_error"],"max_ok_scope":"Maximum successful name/init/afterSwap transaction gas, including intrinsic gas. Deployment has its own maximum in stages.deployment and a separate original 10000000 gas limit.","per_hash_coverage":[{"sha256":"cb935deb4ca8bc0b01c15b1df63e119a90bdc069215c9b8de735a8f6dc9df0e7","runs":1,"seeds":"10000..10063"},{"sha256":"28417e116f57f1029fdd1803832e852574902c1ae7253c05657f317db76da4ab","runs":1,"seeds":"10000..10063"}],"normalizer_gas":{"candidate_run":[[64,191464,0,0,0,0],[64,21526,0,0,0,0],[64,21796,0,0,0,0],[738354,22592,0,0,0,0]],"v2_run":[[64,191464,0,0,0,0],[64,21526,0,0,0,0],[64,21796,0,0,0,0],[673205,22592,0,0,0,0]]},"elapsed_simulation_seconds":{"candidate":33.515674324007705,"v2":56.81596248480491},"paired_formula_if_valid":"Join by seed; diff=candidate edge minus V2 edge; SE=sample SD(diff)/sqrt(n); worst=five smallest diffs. Not applied because baseline is gas-invalid.","run_evidence":{"candidate":{"id":"p12a24","sha256":"cb935deb4ca8bc0b01c15b1df63e119a90bdc069215c9b8de735a8f6dc9df0e7","bytecode_keccak":"42d520c3528e0b948058aa7b6b10a2eac2d7ce0b5603a86f350d63896ba8c394","seconds":33.515674324007705,"gas":[[64,1389403,0,0,0,0],[64,21536,0,0,0,0],[64,236368,0,0,0,0],[318639,242492,4,0,0,0]],"vanilla_gas":[[64,191464,0,0,0,0],[64,21526,0,0,0,0],[64,21796,0,0,0,0],[738354,22592,0,0,0,0]],"stats_columns":["ok","max_ok","oog","revert","other_halt","execution_error"],"stats_rows":["deployment","name","initialize","swap"]},"v2":{"id":"V2","sha256":"28417e116f57f1029fdd1803832e852574902c1ae7253c05657f317db76da4ab","bytecode_keccak":"369eada8e43393968ef8975d4e4570434e3308edfd7da9c50d901de7c2ff71a2","seconds":56.81596248480491,"gas":[[64,1560600,0,0,0,0],[64,21545,0,0,0,0],[64,236377,0,0,0,0],[652602,243554,4,0,0,0]],"vanilla_gas":[[64,191464,0,0,0,0],[64,21526,0,0,0,0],[64,21796,0,0,0,0],[673205,22592,0,0,0,0]],"stats_columns":["ok","max_ok","oog","revert","other_halt","execution_error"],"stats_rows":["deployment","name","initialize","swap"]}},"source_provenance":"Repository URLs and exact quotations are in sources.json. Strategy construction, gas counts, counter probes and hashes are local outputs of the embedded harness, not claims from external sources."}}