{
  "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 FLAT_FEE = 28 * BPS;\n    uint256 constant EDGE_SLOPE = 64 * BPS;\n    uint256 constant GAP_KNEE = 0 * WAD;\n    uint256 constant ELAPSED_CAP = 8;\n    uint256 constant SIGNAL_THRESHOLD = WAD / 650;\n    uint256 constant SIZE_DECAY = 530000000000000000;\n    uint256 constant SIGMA_DECAY = 690000000000000000;\n    uint256 constant LAMBDA_DECAY = 990000000000000000;\n    uint256 constant SIZE_BLEND_DECAY = 828000000000000000;\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 GATE_SIGMA_MULT = 7200000000000000000;\n    uint256 constant MIN_GATE = 30000000000000000;\n    uint256 constant RET_CAP = WAD / 35;\n    uint256 constant TRADE_RATIO_CAP = WAD / 5;\n    uint256 constant LAMBDA_CAP = 1820000000000000000;\n    uint256 constant STEP_COUNT_CAP = 64;\n\n    function afterInitialize(uint256 initialX, uint256 initialY) external override returns (uint256, uint256) {\n        slots[0] = FLAT_FEE; slots[1] = FLAT_FEE;\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];\n        return (FLAT_FEE, FLAT_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 pHat = slots[5];\n        uint256 sigmaHat = slots[6]; uint256 lambdaHat = slots[7]; uint256 sizeHat = slots[8];\n        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            sizeHat = wmul(sizeHat, _powWad(SIZE_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            sizeHat = wmul(sizeHat, SIZE_BLEND_DECAY) + wmul(tradeRatio, WAD - SIZE_BLEND_DECAY);\n            if (sizeHat > WAD) sizeHat = WAD;\n        }\n\n        stepTradeCount = stepTradeCount + 1;\n        if (stepTradeCount > STEP_COUNT_CAP) stepTradeCount = STEP_COUNT_CAP;\n\n        // Closed-form surrogate for marginal retail revenue versus arbitrage loss.\n        // Spot above fair exposes the bid (pool buys X); below fair exposes ask.\n        uint256 fair = wmul(pHat, 700000000000000000) + wmul(fastHat, 300000000000000000);\n        uint256 gap = fair > 0 ? wdiv(absDiff(spot, fair), fair) : 0;\n        uint256 z = wdiv(gap, sigmaHat > 0 ? sigmaHat : 1);\n        uint256 extra = z > GAP_KNEE ? wmul(EDGE_SLOPE, z - GAP_KNEE) : 0;\n        uint256 protectedFee = clampFee(FLAT_FEE + extra);\n        uint256 bidFee = spot >= fair ? protectedFee : FLAT_FEE;\n        uint256 askFee = spot >= fair ? FLAT_FEE : protectedFee;\n\n        slots[0] = bidFee; slots[1] = askFee; slots[2] = trade.timestamp;\n        slots[5] = pHat;\n        slots[6] = sigmaHat; slots[7] = lambdaHat; slots[8] = sizeHat;\n        slots[16] = spot;\n        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 getName() external pure override returns (string memory) { return \"ExpectedEdgeClosedForm\"; }\n}\n",
  "sha256": "be61a698f8c835dd63c552de2090dc9d8a5587e1144c2607c705d49818548ce9",
  "design": {
    "family": "Expected edge per side: closed-form exposed-side surcharge",
    "params": {
      "F0_bps": 28,
      "h_bps_per_sigma": 64,
      "g0": 0
    },
    "formula": "fair = 0.7*pHat + 0.3*fastHat; gap = abs(spot-fair)/fair; z = gap/max(sigmaHat,1 WAD integer unit); exposedFee = min(1000 bps, F0 + h*max(z-g0,0)); otherFee = F0.",
    "side": "Bid is exposed when spot >= fair; ask otherwise. Both fees initialize at F0.",
    "rationale": "The flat side represents the retail-revenue optimum; the positive-part surcharge approximates marginal arbitrage saving as normalized estimated mispricing grows.",
    "approximation": "This is the requested closed-form surrogate, not an exact maximizer of router-share revenue minus expected arbitrage loss. It does not evaluate router shares or Poisson tail probabilities at runtime. Lambda/size estimates are retained but do not enter this mapping.",
    "preserved_estimators": "V2 pHat, sigmaHat, fastHat/uncertainty, lambdaHat, sizeHat, step-count and silence inference update equations; fair blend remains 70/30. Fee-dependent observations naturally change under the new fees.",
    "gas_changes": "Replaced the old fee mapping; deleted direction/activity/toxicity state updates, their storage writes and unused helpers/constants; omitted zero initialization writes. No storage packing or sqrt changes.",
    "fee_grid_evaluations_per_call": 0,
    "information": "Only TradeInfo, constants and strategy-owned slots are read. No true price or seed is read.",
    "result": "Rejected for promotion: the frozen best tested variant underperforms V2 on the fresh holdout.",
    "limitation": "Sixteen settings cannot exclude improvements elsewhere in this family; no leaderboard submission or rank was measured."
  },
  "tuning": [
    {
      "id": "b2_00",
      "stage": "screen",
      "params": {
        "F0_bps": 28,
        "h_bps_per_sigma": 4,
        "g0": 1
      },
      "sha256": "cff4435e22ddabbc98245abbf8f81c0eb753977ee42014a9cb334fbca6307de5",
      "n": 256,
      "mean_diff": -161.4512425742156,
      "se": 2.533970663952859,
      "seeds": [
        80000,
        80256
      ],
      "max_ok": 209686,
      "oog": 0,
      "v2_oog": 3
    },
    {
      "id": "b2_01",
      "stage": "screen",
      "params": {
        "F0_bps": 28,
        "h_bps_per_sigma": 4,
        "g0": 2
      },
      "sha256": "625acc55e420a4c4851850b9684610b2a467b15152cc0fb8d8a2a15cd21f5a48",
      "n": 256,
      "mean_diff": -167.45168017445855,
      "se": 2.594517753317841,
      "seeds": [
        80000,
        80256
      ],
      "max_ok": 206979,
      "oog": 0,
      "v2_oog": 3
    },
    {
      "id": "b2_02",
      "stage": "screen",
      "params": {
        "F0_bps": 28,
        "h_bps_per_sigma": 12,
        "g0": 1
      },
      "sha256": "532691185ac1cfcb5d7b21676f3ef84ee0a83dc03cf794fb833dbd9ce93ec243",
      "n": 256,
      "mean_diff": -122.85755300060721,
      "se": 1.8151901780670072,
      "seeds": [
        80000,
        80256
      ],
      "max_ok": 209686,
      "oog": 0,
      "v2_oog": 3
    },
    {
      "id": "b2_03",
      "stage": "screen",
      "params": {
        "F0_bps": 28,
        "h_bps_per_sigma": 12,
        "g0": 2
      },
      "sha256": "d9a73975f4053a34ee01e52ca4fdc356f862287bc6f73b5e56675f5fd824ec1f",
      "n": 256,
      "mean_diff": -137.6837743091595,
      "se": 1.9820638332013236,
      "seeds": [
        80000,
        80256
      ],
      "max_ok": 206979,
      "oog": 0,
      "v2_oog": 3
    },
    {
      "id": "b2_04",
      "stage": "screen",
      "params": {
        "F0_bps": 28,
        "h_bps_per_sigma": 64,
        "g0": 0
      },
      "sha256": "be61a698f8c835dd63c552de2090dc9d8a5587e1144c2607c705d49818548ce9",
      "n": 256,
      "mean_diff": -61.29687494636833,
      "se": 0.7143850306847827,
      "seeds": [
        80000,
        80256
      ],
      "max_ok": 209811,
      "oog": 0,
      "v2_oog": 3
    },
    {
      "id": "b2_05",
      "stage": "screen",
      "params": {
        "F0_bps": 28,
        "h_bps_per_sigma": 64,
        "g0": 1
      },
      "sha256": "97d23d66128d43aacf12c2bd1b7cb2797911e4965285f70f15b43145c93da48c",
      "n": 256,
      "mean_diff": -110.32680490867065,
      "se": 1.6280627444175668,
      "seeds": [
        80000,
        80256
      ],
      "max_ok": 209686,
      "oog": 0,
      "v2_oog": 3
    },
    {
      "id": "b2_06",
      "stage": "screen",
      "params": {
        "F0_bps": 32,
        "h_bps_per_sigma": 64,
        "g0": 0
      },
      "sha256": "936c96e995dd7bfc705be0d65702e16d961a5f3edd4f9f5c041bce60e2ecbc50",
      "n": 256,
      "mean_diff": -62.61854176063995,
      "se": 0.7170957407691992,
      "seeds": [
        80000,
        80256
      ],
      "max_ok": 209811,
      "oog": 0,
      "v2_oog": 3
    },
    {
      "id": "b2_07",
      "stage": "screen",
      "params": {
        "F0_bps": 32,
        "h_bps_per_sigma": 64,
        "g0": 1
      },
      "sha256": "2fb015aa5e721164dbb909bc6d4151e5440cb8b5be44eed27803290d9b4a82ca",
      "n": 256,
      "mean_diff": -97.17099890556419,
      "se": 1.3643159547333923,
      "seeds": [
        80000,
        80256
      ],
      "max_ok": 209686,
      "oog": 0,
      "v2_oog": 3
    },
    {
      "id": "b2_08",
      "stage": "screen",
      "params": {
        "F0_bps": 36,
        "h_bps_per_sigma": 64,
        "g0": 0
      },
      "sha256": "db6c177e16755dee30482cfec3ab2012ca8777a061bf4171ecdf521d3bc5cb3f",
      "n": 256,
      "mean_diff": -65.09935613640808,
      "se": 0.7086742368688262,
      "seeds": [
        80000,
        80256
      ],
      "max_ok": 209634,
      "oog": 0,
      "v2_oog": 3
    },
    {
      "id": "b2_09",
      "stage": "screen",
      "params": {
        "F0_bps": 36,
        "h_bps_per_sigma": 64,
        "g0": 1
      },
      "sha256": "355f0cbbfb8073b6f16f5efc044894b702b4575c7ed63ca5e11f55c0c0204d9e",
      "n": 256,
      "mean_diff": -93.30969927770406,
      "se": 1.2079233324899665,
      "seeds": [
        80000,
        80256
      ],
      "max_ok": 209674,
      "oog": 0,
      "v2_oog": 3
    },
    {
      "id": "b2_10",
      "stage": "screen",
      "params": {
        "F0_bps": 32,
        "h_bps_per_sigma": 32,
        "g0": 0
      },
      "sha256": "490ac3459621ba705816f9d3f9759d627cc672858fafb0c488559e4498835c47",
      "n": 256,
      "mean_diff": -76.30593031233941,
      "se": 1.1193760941469133,
      "seeds": [
        80000,
        80256
      ],
      "max_ok": 209811,
      "oog": 0,
      "v2_oog": 3
    },
    {
      "id": "b2_11",
      "stage": "screen",
      "params": {
        "F0_bps": 32,
        "h_bps_per_sigma": 32,
        "g0": 1
      },
      "sha256": "8b794bb3d09afa2b1e0e02264c9b64ffcff3d37031ec53dc03137c924f6f85f2",
      "n": 256,
      "mean_diff": -96.42100402268731,
      "se": 1.3209036126340006,
      "seeds": [
        80000,
        80256
      ],
      "max_ok": 209686,
      "oog": 0,
      "v2_oog": 3
    },
    {
      "id": "b2_12",
      "stage": "screen",
      "params": {
        "F0_bps": 32,
        "h_bps_per_sigma": 128,
        "g0": 0
      },
      "sha256": "037b02f05da5a0f8a57af6d6011117abca7310ea7987d5f3cb9501927b836a10",
      "n": 256,
      "mean_diff": -89.12755727208643,
      "se": 0.9906388484473952,
      "seeds": [
        80000,
        80256
      ],
      "max_ok": 209811,
      "oog": 0,
      "v2_oog": 3
    },
    {
      "id": "b2_13",
      "stage": "screen",
      "params": {
        "F0_bps": 32,
        "h_bps_per_sigma": 128,
        "g0": 1
      },
      "sha256": "634bbf01d1c2eaa86e8ad7601a269238da218738028d1a6a12266e4c35e8a6a5",
      "n": 256,
      "mean_diff": -136.93397304232764,
      "se": 2.0044784204595243,
      "seeds": [
        80000,
        80256
      ],
      "max_ok": 209686,
      "oog": 0,
      "v2_oog": 3
    },
    {
      "id": "b2_14",
      "stage": "screen",
      "params": {
        "F0_bps": 32,
        "h_bps_per_sigma": 256,
        "g0": 0
      },
      "sha256": "de141bf8fadd87bab88b59f9264ff547fca096c21032830dc5bad326afcbefd9",
      "n": 256,
      "mean_diff": -177.86063458517535,
      "se": 1.7406368065649176,
      "seeds": [
        80000,
        80256
      ],
      "max_ok": 209811,
      "oog": 0,
      "v2_oog": 3
    },
    {
      "id": "b2_15",
      "stage": "screen",
      "params": {
        "F0_bps": 28,
        "h_bps_per_sigma": 80,
        "g0": 0
      },
      "sha256": "a268822553d256355874b8849d5570de0838d65b33db554d92a03fa9457306eb",
      "n": 256,
      "mean_diff": -65.06042766556037,
      "se": 0.74240207737436,
      "seeds": [
        80000,
        80256
      ],
      "max_ok": 209811,
      "oog": 0,
      "v2_oog": 3
    },
    {
      "id": "b2_04",
      "stage": "rerank",
      "params": {
        "F0_bps": 28,
        "h_bps_per_sigma": 64,
        "g0": 0
      },
      "sha256": "be61a698f8c835dd63c552de2090dc9d8a5587e1144c2607c705d49818548ce9",
      "n": 512,
      "mean_diff": -61.53412604625826,
      "se": 0.4857773900529825,
      "seeds": [
        82000,
        82512
      ],
      "max_ok": 209646,
      "oog": 0,
      "v2_oog": 23
    },
    {
      "id": "b2_06",
      "stage": "rerank",
      "params": {
        "F0_bps": 32,
        "h_bps_per_sigma": 64,
        "g0": 0
      },
      "sha256": "936c96e995dd7bfc705be0d65702e16d961a5f3edd4f9f5c041bce60e2ecbc50",
      "n": 512,
      "mean_diff": -62.920672281230985,
      "se": 0.4893165799621773,
      "seeds": [
        82000,
        82512
      ],
      "max_ok": 209646,
      "oog": 0,
      "v2_oog": 23
    }
  ],
  "paired": {
    "n": 2000,
    "mean_diff": -60.82034033228069,
    "se": 0.23814914249795968,
    "worst": [
      {
        "seed": 4200143,
        "diff": -110.91780559617251,
        "edge": 321.8910881411809,
        "v2_edge": 432.8088937373534
      },
      {
        "seed": 4201846,
        "diff": -99.99104445731575,
        "edge": 398.78447400360614,
        "v2_edge": 498.7755184609219
      },
      {
        "seed": 4201504,
        "diff": -97.4600719497555,
        "edge": 573.0941958922431,
        "v2_edge": 670.5542678419986
      },
      {
        "seed": 4201966,
        "diff": -91.3059956153703,
        "edge": 586.6066382502353,
        "v2_edge": 677.9126338656056
      },
      {
        "seed": 4201474,
        "diff": -91.19698991340397,
        "edge": 679.4038460971022,
        "v2_edge": 770.6008360105062
      }
    ]
  },
  "gas": {
    "max_ok": 209810,
    "oog": 0,
    "reverts": 0,
    "other_halts": 0,
    "tx_errors": 0,
    "bad_returns": 0,
    "init_max": 198828,
    "calls": {
      "afterInitialize": 2000,
      "afterSwap": 12315354,
      "getName": 2000
    },
    "callback_stats": [
      {
        "role": "Submission",
        "callback": "afterInitialize",
        "calls": 2000,
        "ok": 2000,
        "max_ok_gas": 198828,
        "sum_ok_gas": 397656000,
        "oog": 0,
        "revert": 0,
        "other_halt": 0,
        "tx_error": 0,
        "bad_return": 0
      },
      {
        "role": "Submission",
        "callback": "afterSwap",
        "calls": 12315354,
        "ok": 12315354,
        "max_ok_gas": 209810,
        "sum_ok_gas": 1168400938669,
        "oog": 0,
        "revert": 0,
        "other_halt": 0,
        "tx_error": 0,
        "bad_return": 0
      },
      {
        "role": "Submission",
        "callback": "getName",
        "calls": 2000,
        "ok": 2000,
        "max_ok_gas": 21536,
        "sum_ok_gas": 43072000,
        "oog": 0,
        "revert": 0,
        "other_halt": 0,
        "tx_error": 0,
        "bad_return": 0
      }
    ]
  },
  "v2_gas": {
    "max_ok": 244149,
    "oog": 26,
    "reverts": 0,
    "other_halts": 0,
    "tx_errors": 0,
    "bad_returns": 0,
    "init_max": 236377,
    "calls": {
      "afterInitialize": 2000,
      "afterSwap": 20691521,
      "getName": 2000
    },
    "callback_stats": [
      {
        "role": "Submission",
        "callback": "afterInitialize",
        "calls": 2000,
        "ok": 2000,
        "max_ok_gas": 236377,
        "sum_ok_gas": 472754000,
        "oog": 0,
        "revert": 0,
        "other_halt": 0,
        "tx_error": 0,
        "bad_return": 0
      },
      {
        "role": "Submission",
        "callback": "afterSwap",
        "calls": 20691521,
        "ok": 20691495,
        "max_ok_gas": 244149,
        "sum_ok_gas": 2304912568884,
        "oog": 26,
        "revert": 0,
        "other_halt": 0,
        "tx_error": 0,
        "bad_return": 0
      },
      {
        "role": "Submission",
        "callback": "getName",
        "calls": 2000,
        "ok": 2000,
        "max_ok_gas": 21545,
        "sum_ok_gas": 43090000,
        "oog": 0,
        "revert": 0,
        "other_halt": 0,
        "tx_error": 0,
        "bad_return": 0
      }
    ]
  },
  "seeds": {
    "convention": "Half-open ranges: start inclusive, end exclusive.",
    "screen": [
      80000,
      80256
    ],
    "rerank": [
      82000,
      82512
    ],
    "holdout": [
      4200000,
      4202000
    ],
    "holdout_used_once": true,
    "aborted_attempts": [
      [
        4150000,
        4152000
      ],
      [
        4160000,
        4162000
      ]
    ]
  },
  "freeze": {
    "id": "b2_04",
    "params": {
      "F0_bps": 28,
      "h_bps_per_sigma": 64,
      "g0": 0
    },
    "sha256": "be61a698f8c835dd63c552de2090dc9d8a5587e1144c2607c705d49818548ce9",
    "selection": "Highest rerank mean among two best admissible screen variants; chosen before holdout."
  },
  "blocked": null,
  "valid": true,
  "validity_rule": "Requester revised OOG rule: candidate oog <= V2 oog on identical seeds; no reverts, other halts, transaction errors or bad returns. No seeds are omitted from paired scores. The supplied harness strict validity flag is also reported separately.",
  "strict_harness_valid": false,
  "evidence": {
    "holdout_mean_candidate_edge": 464.53635531653595,
    "holdout_mean_v2_edge": 525.3566956488166,
    "holdout_run_seconds": {
      "candidate": 168.455,
      "v2": 280.541
    },
    "screen_v2_gas": {
      "max_ok": 243625,
      "oog": 3,
      "reverts": 0,
      "other_halts": 0,
      "tx_errors": 0,
      "bad_returns": 0,
      "init_max": 236377,
      "calls": {
        "afterInitialize": 256,
        "afterSwap": 2633082,
        "getName": 256
      },
      "callback_stats": [
        {
          "role": "Submission",
          "callback": "afterInitialize",
          "calls": 256,
          "ok": 256,
          "max_ok_gas": 236377,
          "sum_ok_gas": 60512512,
          "oog": 0,
          "revert": 0,
          "other_halt": 0,
          "tx_error": 0,
          "bad_return": 0
        },
        {
          "role": "Submission",
          "callback": "afterSwap",
          "calls": 2633082,
          "ok": 2633079,
          "max_ok_gas": 243625,
          "sum_ok_gas": 293545802763,
          "oog": 3,
          "revert": 0,
          "other_halt": 0,
          "tx_error": 0,
          "bad_return": 0
        },
        {
          "role": "Submission",
          "callback": "getName",
          "calls": 256,
          "ok": 256,
          "max_ok_gas": 21545,
          "sum_ok_gas": 5515520,
          "oog": 0,
          "revert": 0,
          "other_halt": 0,
          "tx_error": 0,
          "bad_return": 0
        }
      ]
    },
    "standard_error": "Sample standard deviation of per-seed candidate-minus-V2 differences, divided by sqrt(n).",
    "selection": "After the first low-slope failures, unused screen slots were expanded to larger slopes and lower knees. Exactly 16 unique variants were screened. The two highest admissible screen means were reranked; the higher rerank mean was frozen before validation and the single holdout.",
    "screen_parameter_bookkeeping": "Final tuning labels/hashes describe the compiled Solidity, correcting labels cached by the screen process before adaptive edits. Variant b2_14 was restored to its already-compiled 256-bps slope and independently reproduced all 256 per-seed screen edges bit-exactly; b2_15 used the 80-bps refinement. The proposed 48-bps refinement was never simulated.",
    "reproducibility": {
      "repository": "https://github.com/benedictbrady/amm-challenge",
      "commit": "6b6921f8d463314aa7c96234e1be25a25245f704",
      "v2_sha256": "28417e116f57f1029fdd1803832e852574902c1ae7253c05657f317db76da4ab",
      "setup": "Requester artifact scratch/setup.sh executed once; requester instrumentation.patch applied, then maturin develop --release --uv --manifest-path amm_sim_rs/Cargo.toml rebuilt.",
      "harness": "Requester artifact scratch/harness.py; screen imports its compile_src, build_configs, run and paired functions, caches one V2 run for the identical screen seeds, and invokes each candidate in its own run_batch against VanillaStrategy. Rerank invokes the unmodified harness with --other scratch/V2.sol. The completed holdout imports its unchanged compile_src, run and paired functions, using equivalent direct per-seed config construction and 128-seed batches. Independent market results are joined by seed; gas counts are summed and maxima are maximized across chunks. Each of the 2000 seeds is run exactly once per strategy.",
      "configs": "Screen/rerank use MatchRunner._build_configs and slice selected seeds. Completed holdout constructs only its 2000 selected seeds with identical default_rng(seed), size/rate/sigma draw order and every fixed field. Equality in all 12 config fields was checked on 512 rerank seeds. Every run_batch uses 8 workers, each candidate alone against VanillaStrategy. Completed holdout uses 16 chunks per strategy (15*128 + 80 seeds); each config creates fresh independent EVM strategies, so chunk boundaries cannot alter an individual market.",
      "compiler": "Solidity 0.8.24, optimizer enabled runs=200, viaIR=true, evmVersion=paris.",
      "holdout_command": "python scratch/holdout_chunked.py",
      "holdout_runner": "\"\"\"Memory-bounded independent-market holdout. Frozen strategy; no tuning.\"\"\"\nimport gc,hashlib,json,time\nfrom pathlib import Path\nimport numpy as np\nimport amm_sim_rs\nimport harness\nfrom amm_competition.competition.config import build_base_config,BASELINE_VARIANCE\nfrom amm_competition.evm.baseline import get_vanilla_bytecode_and_abi\n\n# Each seed owns its RNG; omitting unrelated prefix configs changes no draws.\ndef configs(s0,s1):\n b=build_base_config(seed=None);v=BASELINE_VARIANCE;out=[]\n for i in range(s0,s1):\n  rng=np.random.default_rng(seed=i)\n  size=rng.uniform(v.retail_mean_size_min,v.retail_mean_size_max) if v.vary_retail_mean_size else b.retail_mean_size\n  rate=rng.uniform(v.retail_arrival_rate_min,v.retail_arrival_rate_max) if v.vary_retail_arrival_rate else b.retail_arrival_rate\n  sigma=rng.uniform(v.gbm_sigma_min,v.gbm_sigma_max) if v.vary_gbm_sigma else b.gbm_sigma\n  out.append(amm_sim_rs.SimulationConfig(n_steps=b.n_steps,initial_price=b.initial_price,initial_x=b.initial_x,initial_y=b.initial_y,gbm_mu=b.gbm_mu,gbm_sigma=sigma,gbm_dt=b.gbm_dt,retail_arrival_rate=rate,retail_mean_size=size,retail_size_sigma=b.retail_size_sigma,retail_buy_prob=b.retail_buy_prob,seed=i))\n return out\n\ndef merge_runs(label,runs):\n stats={}\n for r in runs:\n  for x in r['stats']:\n   key=(x['role'],x['callback'])\n   if key not in stats:stats[key]=dict(x)\n   else:\n    for k,v in x.items():\n     if k in ('role','callback'):continue\n     if k=='max_ok_gas':stats[key][k]=max(stats[key][k],v)\n     else:stats[key][k]+=v\n return dict(label=label,seconds=round(sum(r['seconds'] for r in runs),3),n_sims=sum(r['n_sims'] for r in runs),error=next((r['error'] for r in runs if r['error']),None),valid=all(r['valid'] for r in runs),submission_errors={k:sum(r['submission_errors'][k] for r in runs) for k in harness.ERR_KEYS},max_ok_gas_afterSwap=max(r['max_ok_gas_afterSwap'] for r in runs),max_ok_gas_all=max(r['max_ok_gas_all'] for r in runs),stats=list(stats.values()))\n\nfreeze=json.loads(Path('scratch/freeze.json').read_text());src,bc,t=harness.compile_src('scratch/Frozen.sol')\nassert hashlib.sha256(src.encode()).hexdigest()==freeze['sha256']\n_,bc2,_=harness.compile_src('scratch/V2.sol');vanilla=list(get_vanilla_bytecode_and_abi()[0])\n# Confirm config identity again without any holdout simulations or parameter choices.\nref=harness.build_configs(82000,82512);direct=configs(82000,82512)\nkeys=json.loads(Path('scratch/config_equivalence.json').read_text())['fields']\nassert all(getattr(x,k)==getattr(y,k) for x,y in zip(ref,direct) for k in keys)\ndel ref,direct;gc.collect()\ns0,s1=4200000,4202000\nall_edges=[];all_runs=[]\nfor label,bytecode in [('A',bc),('B',bc2)]:\n edges={};runs=[]\n for start in range(s0,s1,128):\n  end=min(start+128,s1)\n  run,e=harness.run(label,bytecode,vanilla,configs(start,end))\n  assert len(e)==end-start,(label,start,run)\n  assert not (set(edges)&set(e));edges.update(e);runs.append(run)\n  Path(f'scratch/chunked_{label}_progress.json').write_text(json.dumps(dict(edges=edges,runs=runs)))\n  print(label,start,end,run['seconds'],run['submission_errors'],run['max_ok_gas_afterSwap'],flush=True)\n  gc.collect()\n assert len(edges)==2000\n all_edges.append(edges);all_runs.append(merge_runs(label,runs))\n print(label,'COMPLETE',flush=True)\nea,eb=all_edges;ra,rb=all_runs\np=harness.paired(ea,eb,range(s0,s1))\nres=dict(sha256=freeze['sha256'],seeds=[s0,s1],compile_seconds=round(t,3),runs=[ra,rb],valid=ra['valid'] and rb['valid'],paired=p,mean_edge_A=sum(x[0] for x in ea.values())/2000,mean_edge_B=sum(x[0] for x in eb.values())/2000,mean_vanilla_edge_A=sum(x[1] for x in ea.values())/2000,chunk_size=128,chunks_per_strategy=16)\nPath('scratch/holdout.json').write_text(json.dumps(res,indent=1))\nassert hashlib.sha256(Path('scratch/Frozen.sol').read_bytes()).hexdigest()==freeze['sha256']\nprint('COMPLETE',json.dumps(p),flush=True)\n",
      "config_equivalence": {
        "n": 512,
        "seeds": [
          82000,
          82512
        ],
        "fields": [
          "n_steps",
          "initial_price",
          "initial_x",
          "initial_y",
          "gbm_mu",
          "gbm_sigma",
          "gbm_dt",
          "retail_arrival_rate",
          "retail_mean_size",
          "retail_size_sigma",
          "retail_buy_prob",
          "seed"
        ],
        "all_fields_bit_exact": true
      },
      "aborted_attempts": [
        {
          "seeds": [
            4150000,
            4152000
          ],
          "command": "python scratch/harness.py scratch/Frozen.sol 4150000 4152000 scratch/holdout.json --other scratch/V2.sol",
          "returncode": -9,
          "error": "SIGKILL; empty log and no result JSON. The supplied builder allocates a full 4,152,000-config prefix before slicing."
        },
        {
          "seeds": [
            4160000,
            4162000
          ],
          "command": "python scratch/holdout_direct.py",
          "returncode": 137,
          "error": "Shell reported Killed during the candidate simulation batch after config construction succeeded; no scores returned."
        }
      ],
      "recovery": "Causes of SIGKILL were not certified. No scores from either aborted attempt were available or used. The completed holdout moved to a third disjoint fresh block, using bounded independent-market batches, without changing frozen code."
    },
    "validation": {
      "command": "amm-match validate scratch/Frozen.sol",
      "exit_code": 0,
      "output": "Validating strategy...\nCompiling strategy...\nStrategy 'ExpectedEdgeClosedForm' validated successfully!\n"
    }
  }
}
