{
  "mechanism": "EXACT ARB-BLOCKING FEE (literal requested bid/ask orientation)",
  "approach": "Test six variants k=0.5/1/2, with zero or retained stale additive term on the geometric-floor side. Opposite side receives the existing attraction subtraction before unchanged trade boost/compression. Select highest paired tuning mean on 10000..10499; freeze code before one 2000-seed confirmation. Retained stale means its magnitude is added on the requested geometric side; the original stale side selection is replaced in both families.",
  "delta": "Replace only NP2 staleShift block and insert post-compression floor. staleShift=wmul(STALE_DIR_COEF,toxSignal), attractShift=wmul(staleShift,STALE_ATTRACT_FRAC). If pHat>spot, bidFee+=staleShift; askFee=max(askFee-attractShift,0). If pHat<spot, askFee+=staleShift; bidFee=max(bidFee-attractShift,0). At equality skip both shifts. Existing tradeBoost and tail compression remain. Immediately before storing fees, if spot>0 and pHat>spot, bidFee=max(bidFee,clampFee(wdiv(pHat,spot)-WAD+wmul(sigmaHat,1000000000000000000))); if spot>0 and pHat<spot, askFee=max(askFee,clampFee(WAD-wdiv(pHat,spot)+wmul(sigmaHat,1000000000000000000))). All other code/constants/storage unchanged; k=1; WAD rounding and NP2 10% fee cap retained.",
  "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[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        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            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        {\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            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        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 staleShift = wmul(STALE_DIR_COEF, toxSignal);\n            uint256 attractShift = wmul(staleShift, STALE_ATTRACT_FRAC);\n            if (pHat > spot) {\n                bidFee = bidFee + staleShift;\n                askFee = askFee > attractShift ? askFee - attractShift : 0;\n            } else if (pHat < spot) {\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        // Apply the geometric floor after tail compression.\n        if (spot > 0 && pHat > spot) {\n            uint256 blockFee = wdiv(pHat, spot) - WAD + wmul(sigmaHat, 1000000000000000000);\n            if (bidFee < blockFee) bidFee = clampFee(blockFee);\n        } else if (spot > 0 && pHat < spot) {\n            uint256 blockFee = WAD - wdiv(pHat, spot) + wmul(sigmaHat, 1000000000000000000);\n            if (askFee < blockFee) askFee = clampFee(blockFee);\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[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",
  "code_sha256": "4a82abd82d7090e22ee99c6deb96e43ae78fcc28b16ac1613acd1532b55d35da",
  "validate_ok": true,
  "max_gas": 189944,
  "np2_check": {
    "seeds": "0..999",
    "n": 1000,
    "mean_edge": 526.1155722459862,
    "se": 2.7896004178197593,
    "expected_rounded": 526.1156,
    "matches_4dp": true,
    "code_sha256": "51f1c1a9d4999ee460eb8bbc66880da8074b173399a4f5d71f96671482e18ac0",
    "ch_check": {
      "n": 1000,
      "seeds": "0..999",
      "mean_edge": 525.5258821780834,
      "expected": 525.525882178,
      "difference": 8.344613888766617e-11,
      "code_sha256": "6dd68f77a70900319460215374143dbd5d924198450a46d9f5f91f6b1e3d35c3"
    }
  },
  "tune": [
    {
      "variant": "exact_k0.5_replace",
      "seeds": "10000..10499",
      "n": 500,
      "mean_diff": -281.1358339271033,
      "se": 2.551790037512614,
      "code_sha256": "5d05414be69f32e4148dd21083be036898093ace164c40d4f58cdf0eab9e500e"
    },
    {
      "variant": "exact_k1_replace",
      "seeds": "10000..10499",
      "n": 500,
      "mean_diff": -272.45729044916436,
      "se": 2.5086009451761284,
      "code_sha256": "564750c08f321b774bec637df6804b7aef2c2c0ff1de510911d0216bb72291a4"
    },
    {
      "variant": "exact_k2_replace",
      "seeds": "10000..10499",
      "n": 500,
      "mean_diff": -289.31237820441646,
      "se": 2.555763286947859,
      "code_sha256": "879106c9b64048de3e2ab397ab8196f9000e4f4b9c921d0f68db29e6f3be67ff"
    },
    {
      "variant": "exact_k0.5_keep",
      "seeds": "10000..10499",
      "n": 500,
      "mean_diff": -275.62248336768374,
      "se": 2.540882295994691,
      "code_sha256": "378298b0dcd22c78fce9595964f9a54c530176d52df80297d3031ffdf819c063"
    },
    {
      "variant": "exact_k1_keep",
      "seeds": "10000..10499",
      "n": 500,
      "mean_diff": -272.34774793608875,
      "se": 2.515038215536433,
      "code_sha256": "4a82abd82d7090e22ee99c6deb96e43ae78fcc28b16ac1613acd1532b55d35da"
    },
    {
      "variant": "exact_k2_keep",
      "seeds": "10000..10499",
      "n": 500,
      "mean_diff": -289.5063115371461,
      "se": 2.56203562302825,
      "code_sha256": "e3ee2fa24eba22df0ec8a873f316d6f560d1303dc14f9d6158cc098d9bcc98d0"
    }
  ],
  "paired": {
    "seeds": "2000000..2001999",
    "n": 2000,
    "mean_diff": -272.4799317518055,
    "se": 1.194794781271022,
    "reference_mean_edge": 525.113995723438,
    "candidate_mean_edge": 252.63406397163251,
    "worst": [
      {
        "seed": 2000065,
        "diff": -576.1207019248865,
        "candidate_edge": 288.74276487182556,
        "reference_edge": 864.863466796712
      },
      {
        "seed": 2000316,
        "diff": -503.46485093139955,
        "candidate_edge": 323.9476508415549,
        "reference_edge": 827.4125017729544
      },
      {
        "seed": 2000730,
        "diff": -499.38504423880715,
        "candidate_edge": 270.698865938116,
        "reference_edge": 770.0839101769232
      },
      {
        "seed": 2000504,
        "diff": -477.41476402018384,
        "candidate_edge": 240.66482015670792,
        "reference_edge": 718.0795841768918
      },
      {
        "seed": 2001410,
        "diff": -453.11304465716347,
        "candidate_edge": 305.4183307230846,
        "reference_edge": 758.531375380248
      }
    ]
  },
  "next": "Reject this literal mechanism if the confirmed paired loss remains negative. The pinned simulator charges ask_fee when spot<fair and bid_fee when spot>fair. Inference from its fee-on-input equations: a future correctly oriented zero-arbitrage test would floor askFee at 1-spot/pHat when pHat>spot, and bidFee at 1-pHat/spot when pHat<spot. Those alternate formulas were not tested in this bounded item.",
  "blocked": null,
  "checks": {
    "validate_stdout": "Validating strategy...\nCompiling strategy...\nStrategy 'no_cubic' validated successfully!",
    "gas": {
      "variant": "exact_k1_keep",
      "n_swap_calls": 4000,
      "initialization_gas": 189944,
      "max_after_swap_gas": 132827,
      "max_gas": 189944,
      "floor_checks": 4000,
      "all_success": true,
      "measurement": "pyrevm EVM.result.gas_used; synthetic constant-product trades, both sides, sizes 0.001%..8%, timestamp increments 0/1/2/8/64"
    },
    "gas_scope": "Measured stress-test maximum, not a proof of a universal maximum. Read EVM.result.gas_used, not the executor gas estimate. 4000 swaps per variant; timestamp increments include same-step and elapsed-cap cases. Check 10% bounds and geometric floor from slots[5]/slots[6] after each call.",
    "all_six_validate_ok": true,
    "all_six_gas_checks": [
      {
        "variant": "exact_k0.5_replace",
        "n_swap_calls": 4000,
        "initialization_gas": 189980,
        "max_after_swap_gas": 132844,
        "max_gas": 189980,
        "floor_checks": 4000,
        "all_success": true,
        "measurement": "pyrevm EVM.result.gas_used; synthetic constant-product trades, both sides, sizes 0.001%..8%, timestamp increments 0/1/2/8/64"
      },
      {
        "variant": "exact_k1_replace",
        "n_swap_calls": 4000,
        "initialization_gas": 189980,
        "max_after_swap_gas": 132844,
        "max_gas": 189980,
        "floor_checks": 4000,
        "all_success": true,
        "measurement": "pyrevm EVM.result.gas_used; synthetic constant-product trades, both sides, sizes 0.001%..8%, timestamp increments 0/1/2/8/64"
      },
      {
        "variant": "exact_k2_replace",
        "n_swap_calls": 4000,
        "initialization_gas": 189980,
        "max_after_swap_gas": 132844,
        "max_gas": 189980,
        "floor_checks": 4000,
        "all_success": true,
        "measurement": "pyrevm EVM.result.gas_used; synthetic constant-product trades, both sides, sizes 0.001%..8%, timestamp increments 0/1/2/8/64"
      },
      {
        "variant": "exact_k0.5_keep",
        "n_swap_calls": 4000,
        "initialization_gas": 189944,
        "max_after_swap_gas": 132827,
        "max_gas": 189944,
        "floor_checks": 4000,
        "all_success": true,
        "measurement": "pyrevm EVM.result.gas_used; synthetic constant-product trades, both sides, sizes 0.001%..8%, timestamp increments 0/1/2/8/64"
      },
      {
        "variant": "exact_k1_keep",
        "n_swap_calls": 4000,
        "initialization_gas": 189944,
        "max_after_swap_gas": 132827,
        "max_gas": 189944,
        "floor_checks": 4000,
        "all_success": true,
        "measurement": "pyrevm EVM.result.gas_used; synthetic constant-product trades, both sides, sizes 0.001%..8%, timestamp increments 0/1/2/8/64"
      },
      {
        "variant": "exact_k2_keep",
        "n_swap_calls": 4000,
        "initialization_gas": 189944,
        "max_after_swap_gas": 132827,
        "max_gas": 189944,
        "floor_checks": 4000,
        "all_success": true,
        "measurement": "pyrevm EVM.result.gas_used; synthetic constant-product trades, both sides, sizes 0.001%..8%, timestamp increments 0/1/2/8/64"
      }
    ]
  },
  "methodology": {
    "simulator_commit": "6b6921f8d463314aa7c96234e1be25a25245f704",
    "setup": "Requested setup.sh completed once; StarterStrategy validated. Simulator remained unmodified.",
    "comparison": "Separate candidate-vs-Vanilla and NP2-vs-Vanilla run_batch calls; paired differences of submission edges. Never candidate and NP2 in one shared market.",
    "draws": "For each seed s, numpy.random.default_rng(s): size uniform(19,21), rate uniform(0.6,1.0), sigma uniform(0.000882,0.001008), in that order. n_steps=10000; initial_price=100; initial_x=100; initial_y=10000; mu=0; dt=1; retail_buy_prob=0.5; retail_size_sigma=1.2. price seed=s; retail seed=s+1.",
    "batching": "amm_sim_rs.run_batch with 8 workers, chunks of 50. Each candidate evaluated once on 500 tuning seeds. One frozen candidate evaluated once on confirmation seeds 2000000..2001999. Reference runs use exactly the same draws.",
    "statistics": "mean_diff=arithmetic mean(candidate_edge-NP2_edge); se=sample standard deviation(ddof=1)/sqrt(n). worst lists the five most negative per-seed differences.",
    "frozen": {
      "variant": "exact_k1_keep",
      "code_sha256": "4a82abd82d7090e22ee99c6deb96e43ae78fcc28b16ac1613acd1532b55d35da",
      "selection": {
        "variant": "exact_k1_keep",
        "seeds": "10000..10499",
        "n": 500,
        "mean_diff": -272.34774793608875,
        "se": 2.515038215536433
      },
      "confirmation_seeds": "2000000..2001999",
      "n": 2000
    },
    "selection": "Highest paired tuning mean among the six requested variants, even if negative; no holdout candidate evaluated before freeze."
  },
  "reproduction": {
    "runner_python": "import json,time,hashlib\nfrom pathlib import Path\nimport numpy as np\nimport amm_sim_rs\nfrom amm_competition.evm.compiler import SolidityCompiler\nfrom amm_competition.evm.baseline import get_vanilla_bytecode_and_abi\nfrom amm_competition.competition.config import build_config\nP=Path('scratch')\ncompiler=SolidityCompiler()\ndef compile(name):\n r=compiler.compile((P/(name+'.sol')).read_text()); assert r.success,r.errors\n return list(r.bytecode)\nvanilla=list(get_vanilla_bytecode_and_abi()[0])\ndef configs(start,n):\n out=[]\n for s in range(start,start+n):\n  rng=np.random.default_rng(s); size=rng.uniform(19,21); rate=rng.uniform(.6,1); sigma=rng.uniform(.000882,.001008)\n  out.append(build_config(seed=s,gbm_sigma=sigma,retail_arrival_rate=rate,retail_mean_size=size))\n return out\ndef run(name,start,n):\n f=P/f'{name}_{start}_{n}.json'\n if f.exists():return np.array(json.loads(f.read_text()))\n bc=compile(name); edges=[]; t=time.time()\n for a in range(start,start+n,50):\n  r=amm_sim_rs.run_batch(bc,vanilla,configs(a,min(50,start+n-a)),8)\n  edges.extend(x.edges['submission'] for x in r.results)\n  print(name,a,'mean',np.mean(edges),'seconds',time.time()-t,flush=True)\n f.write_text(json.dumps(edges)); return np.array(edges)\ndef stats(d):return {'n':len(d),'mean_diff':float(np.mean(d)),'se':float(np.std(d,ddof=1)/np.sqrt(len(d)))}\nif __name__=='__main__':\n import sys\n name,start,n=sys.argv[1],int(sys.argv[2]),int(sys.argv[3]); x=run(name,start,n);print('DONE',name,stats(x),flush=True)\n",
    "gas_test_python": "from experiment import *\nfrom amm_competition.evm.executor import EVMStrategyExecutor\nfrom amm_competition.core.trade import TradeInfo\nfrom decimal import Decimal as D\nimport sys\nname=sys.argv[1]; k=D(name.split('_')[1][1:]); bc=bytes(compile(name)); e=EVMStrategyExecutor(bc)\nr=e.after_initialize(D(100),D(10000));assert r.success,r.error\ninit=e.evm.result.gas_used; maximum=0; rng=np.random.default_rng(740913); x=D(100);y=D(10000);ts=0;floor_cases=0\nselector=bytes.fromhex('387dd9e9')\ndef slot(i):\n return int.from_bytes(e.evm.message_call(caller=e.CALLER_ADDRESS,to=e.deployed_address,calldata=selector+i.to_bytes(32,'big'),gas=50000),'big')\nfor i in range(4000):\n ts+=int(rng.choice([0,0,0,1,1,2,8,64])); buy=bool(rng.integers(2)); fraction=D(str(rng.uniform(.00001,.08))); oldx=x;oldy=y\n if buy:\n  x=oldx*(1+fraction);y=oldx*oldy/x\n else:\n  y=oldy*(1+fraction);x=oldx*oldy/y\n t=TradeInfo(side='buy' if buy else 'sell',amount_x=abs(x-oldx),amount_y=abs(y-oldy),timestamp=ts,reserve_x=x,reserve_y=y)\n bid,ask=e.after_swap_fast(t); gas=e.evm.result.gas_used;maximum=max(maximum,gas);assert gas<250000\n assert 0<=bid<=10**17 and 0<=ask<=10**17\n ph=slot(5);sig=slot(6);sp=int(y*10**18)*10**18//int(x*10**18)\n if ph>sp:\n  bound=min(10**17,ph*10**18//sp-10**18+sig*int(k*10**18)//10**18);assert bid>=bound;(floor_cases:=floor_cases+1)\n elif ph<sp:\n  bound=min(10**17,10**18-ph*10**18//sp+sig*int(k*10**18)//10**18);assert ask>=bound;(floor_cases:=floor_cases+1)\nresult={'variant':name,'n_swap_calls':4000,'initialization_gas':init,'max_after_swap_gas':maximum,'max_gas':max(init,maximum),'floor_checks':floor_cases,'all_success':True,'measurement':'pyrevm EVM.result.gas_used; synthetic constant-product trades, both sides, sizes 0.001%..8%, timestamp increments 0/1/2/8/64'}\n(P/(name+'_gas.json')).write_text(json.dumps(result));print(result)\n",
    "usage": "In the pinned simulator with the requested setup active, save code as scratch/<variant>.sol, NP2 reconstruction as scratch/NP2.sol, runner_python as scratch/experiment.py, and gas_test_python as scratch/gascheck.py. Run python scratch/experiment.py NAME START N for NP2 and candidate separately. Its JSON cache contains ordered submission edges. Subtract arrays and compute sample SE. Run amm-match validate scratch/<variant>.sol and python scratch/gascheck.py <variant>. The variant name encodes k, e.g. exact_k0.5_keep. CH source is the cited pinned ChengHua Strategy.sol."
  },
  "interpretation": {
    "status": "negative result",
    "literal_orientation": "The specified pHat>spot bid floor and pHat<spot ask floor were followed. This differs from the arbitrage-protection side in the pinned simulator. Exact floor is subject to integer WAD rounding and the existing 10% maximum fee.",
    "source_for_orientation": "https://raw.githubusercontent.com/benedictbrady/amm-challenge/6b6921f8d463314aa7c96234e1be25a25245f704/amm_sim_rs/src/market/arbitrageur.rs",
    "promotion": false
  }
}
