{
  "delta": "NP2 plus one guarded router-undercut override after first print of each step (arb proxy). Recover fair from post-spot and feeUsed; expected normalizer spot=fair. After AMM sells X, target bid=1-(0.997+m)*fair/spot; mirror target ask=1-spot/(fair/0.997-m*fair). Targets floored at zero. Apply only if target+feeUsed>=emin; otherwise retain NP2 favored-side fee. Opposite side is at least feeUsed. Later prints use existing NP2/TWO logic. Final m=1 bps, emin=500 bps. No other baseline constants changed.",
  "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 (spot >= pHat) {\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        // Router undercut: first print is the available arb proxy; no actor flag is exposed.\n        // The normalizer's expected spot is fair (center of its 30 bps no-arb band).\n        // Recover fair from our post-arb spot and the fee actually charged.\n        // If target cannot meet the edge floor, retain the NP2 fee on that side.\n        // On later retail prints, retain the unmodified NP2/TWO fee calculation above.\n        if (firstInStep && gamma > 0 && spot > 0) {\n            uint256 margin = 1 * BPS;\n            uint256 edgeFloor = 500 * BPS;\n            uint256 minFee = edgeFloor > feeUsed ? edgeFloor - feeUsed : 0;\n            uint256 target;\n            if (!trade.isBuy) {\n                // After AMM sells X to arb, attract sellers (AMM bid).\n                uint256 receiveRatio = wdiv(wmul(pImplied, WAD - 30 * BPS + margin), spot);\n                target = receiveRatio < WAD ? WAD - receiveRatio : 0;\n                if (target >= minFee) bidFee = clampFee(target);\n                if (askFee < feeUsed) askFee = feeUsed;\n            } else {\n                // After AMM buys X from arb, attract buyers (AMM ask).\n                uint256 normalAsk = wdiv(pImplied, WAD - 30 * BPS);\n                uint256 discount = wmul(pImplied, margin);\n                uint256 pay = normalAsk > discount ? normalAsk - discount : 1;\n                uint256 payRatio = wdiv(spot, pay);\n                target = payRatio < WAD ? WAD - payRatio : 0;\n                if (target >= minFee) askFee = clampFee(target);\n                if (bidFee < feeUsed) bidFee = feeUsed;\n            }\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 \"router_a\"; }\n}\n",
  "sha256": "4d621ce5ffdc091b139442cfa3cc5c00c7c11dd66e3aa3467796b9799f63af60",
  "np2_check": {
    "n": 1000,
    "seeds": [
      0,
      999
    ],
    "expected_rounded": 526.1156,
    "mean": 526.1155722459862,
    "pass": true,
    "sha256": "51f1c1a9d4999ee460eb8bbc66880da8074b173399a4f5d71f96671482e18ac0",
    "ch": {
      "n": 1000,
      "mean": 525.5258821780834,
      "expected": 525.525882178,
      "pass": true,
      "sha256": "6dd68f77a70900319460215374143dbd5d924198450a46d9f5f91f6b1e3d35c3"
    }
  },
  "tune": {
    "seeds": [
      [
        12000,
        12159
      ],
      [
        13000,
        13399
      ]
    ],
    "best_mean_diff": -25.748065425046402,
    "final_constants_bps": {
      "m": 1,
      "emin": 500
    },
    "coarse": [
      {
        "m": 1,
        "emin": 0,
        "n": 160,
        "mean_diff": -115.89176789440228,
        "se": 1.8858590770405832,
        "worst": -206.97069309801344
      },
      {
        "m": 1,
        "emin": 20,
        "n": 160,
        "mean_diff": -115.89176789440228,
        "se": 1.8858590770405832,
        "worst": -206.97069309801344
      },
      {
        "m": 1,
        "emin": 30,
        "n": 160,
        "mean_diff": -50.16326266937345,
        "se": 1.401513599988755,
        "worst": -115.6268544036335
      },
      {
        "m": 1,
        "emin": 40,
        "n": 160,
        "mean_diff": -43.20577122601193,
        "se": 1.4018648163325624,
        "worst": -114.16318300122555
      },
      {
        "m": 1,
        "emin": 50,
        "n": 160,
        "mean_diff": -37.874626161938785,
        "se": 1.3711958753273918,
        "worst": -112.23795324959542
      },
      {
        "m": 1,
        "emin": 60,
        "n": 160,
        "mean_diff": -34.72177315390996,
        "se": 1.3421522355494564,
        "worst": -108.57069065514963
      },
      {
        "m": 1,
        "emin": 80,
        "n": 160,
        "mean_diff": -30.30164607264559,
        "se": 1.1030292042631,
        "worst": -85.29039581049324
      },
      {
        "m": 1,
        "emin": 100,
        "n": 160,
        "mean_diff": -28.373163705851766,
        "se": 1.0825509398873276,
        "worst": -85.08761598825964
      },
      {
        "m": 1,
        "emin": 150,
        "n": 160,
        "mean_diff": -26.271017149153614,
        "se": 0.9633288945718251,
        "worst": -84.91562496389099
      },
      {
        "m": 1,
        "emin": 200,
        "n": 160,
        "mean_diff": -25.442921518682954,
        "se": 0.9032102323660733,
        "worst": -80.6820851361274
      },
      {
        "m": 5,
        "emin": 40,
        "n": 160,
        "mean_diff": -43.20577122601193,
        "se": 1.4018648163325624,
        "worst": -114.16318300122555
      },
      {
        "m": 10,
        "emin": 40,
        "n": 160,
        "mean_diff": -43.20577122601193,
        "se": 1.4018648163325624,
        "worst": -114.16318300122555
      },
      {
        "m": 1,
        "emin": 250,
        "n": 160,
        "mean_diff": -25.152043889194722,
        "se": 0.9042807151351491,
        "worst": -80.4272051241528
      },
      {
        "m": 1,
        "emin": 350,
        "n": 160,
        "mean_diff": -24.908896782103454,
        "se": 0.9020553822138551,
        "worst": -80.4272051241528
      },
      {
        "m": 1,
        "emin": 500,
        "n": 160,
        "mean_diff": -24.693283796787206,
        "se": 0.9020492870863976,
        "worst": -80.4272051241528
      }
    ],
    "refined": [
      {
        "m": 1,
        "emin": 500,
        "n": 400,
        "mean_diff": -25.748065425046402,
        "se": 0.6796035009696868,
        "worst": -96.22690195521443
      },
      {
        "m": 1,
        "emin": 350,
        "n": 400,
        "mean_diff": -25.814431129805797,
        "se": 0.6844061587681767,
        "worst": -96.22690195521443
      },
      {
        "m": 1,
        "emin": 250,
        "n": 400,
        "mean_diff": -25.94802695795247,
        "se": 0.6862167412136364,
        "worst": -96.22690195521443
      }
    ],
    "selection": "Top three coarse settings re-evaluated on 400 tuning seeds; choose largest refined paired mean, then lower emin and m. Frozen before reserved holdout. Earlier discarded implementations used tuning seeds 10000..10599 and 11000..11399 only; none used confirmation seeds."
  },
  "paired": {
    "n": 2000,
    "mean_diff": -26.726126100689385,
    "se": 0.3506906569088013,
    "worst": -166.9545351751368,
    "seeds": [
      2340000,
      2341999
    ],
    "candidate_mean": 500.409850089316,
    "np2_mean": 527.1359761900054,
    "worst5": [
      {
        "seed": 2340264,
        "diff": -166.9545351751368
      },
      {
        "seed": 2340438,
        "diff": -147.45064783215304
      },
      {
        "seed": 2341194,
        "diff": -125.09380437414632
      },
      {
        "seed": 2341812,
        "diff": -123.32947187388856
      },
      {
        "seed": 2340008,
        "diff": -120.76992082829327
      }
    ]
  },
  "arb_volume": {
    "unit": "Y per 10000-step simulation",
    "candidate_mean": 17620.865548703536,
    "np2_mean": 24160.909026845355,
    "mean_diff": -6540.043478141816,
    "relative_change": -0.27068697915608764
  },
  "retail_volume": {
    "unit": "Y per 10000-step simulation",
    "candidate_mean": 65415.11075070301,
    "np2_mean": 77519.10077123897,
    "mean_diff": -12103.990020535963,
    "relative_change": -0.15614203338419996
  },
  "gas": {
    "init_gas": 189971,
    "max_swap_gas": 155077,
    "calls": 2000,
    "limit": 249999,
    "all_succeeded": true,
    "fee_bounds_and_guarded_edge_floor": true
  },
  "blocked": null,
  "next": "Do not promote: reserved confirmation loses 26.7261 edge per seed vs NP2. First print can be retail; test reliable arb classification before further router tuning. High edge thresholds suppress most overrides.",
  "methodology": {
    "simulator_commit": "6b6921f8d463314aa7c96234e1be25a25245f704",
    "pairing": "Separate candidate-vs-Vanilla and NP2-vs-Vanilla markets for identical seeds; subtract submission edges per seed. amm_sim_rs.run_batch, 8 workers, chunks of 16. Sample SE uses ddof=1. Worst is minimum per-seed difference.",
    "draws": "numpy.default_rng(s): size U(19,21), rate U(0.6,1), sigma U(0.000882,0.001008), in that order; config.seed=s, Rust price seed=s, retail seed=s+1. 10000 steps; initial price=100, x=100, y=10000, mu=0, dt=1, retail buy probability=.5, size sigma=1.2.",
    "confirmation": "Exactly one frozen candidate on seeds 2340000..2341999, an unused 2000-seed subset of the specified reserved block; no tuning afterward.",
    "validate": "amm-match validate scratch/router.sol passed after freeze.",
    "gas": "Actual pyrevm EVM.result.gas_used from 2000 synthetic swap calls using tuning-domain random seed 12345; both sides, timestamp gaps, varied reserves and sizes. Includes fee bounds, nonfavored fee minimum, and exact guarded target checks. Measured maximum, not proof of a global worst-case bound."
  },
  "notes": [
    "No measurements or source values were fabricated; all required evaluation fields are measured locally.",
    "Fair recovery is exact up to WAD rounding only for a true optimal arb print. There is no actor flag, so first-in-step is a fallible proxy and can classify retail as arb.",
    "Expected normalizer spot=fair is a modeling assumption (center of its symmetric multiplicative no-arb band), not an observed normalizer price. Fee+feeUsed is the requested bps edge approximation.",
    "Floor-zero saturation may be unable to beat the expected normalizer price when our post-arb spot is outside its competitive range. If minimum edge conflicts with target, skip the favored-side override; opposite-side minimum still applies.",
    "Higher emin can make this mechanism effectively inactive. A negative paired result is evidence against promotion, not a claimed improvement.",
    "Baseline scoring is not evidence of hook success because the pinned simulator can retain fees after a hook failure; gas and formula stress checks are reported separately."
  ]
}
