{
  "mechanism": "KALMAN pHat",
  "approach": "Scalar Kalman fair-price filter with elapsed process variance, near-zero first-print observation noise, fee-band retail observation noise, and stored posterior uncertainty in the existing toxicity input. Tune only observation scale (0.1, 1, 10, 100); freeze the highest paired mean even when negative. This tested formulation is substantially worse than NP2.",
  "delta": "Replace PHAT_ALPHA=0.27, PHAT_ALPHA_RETAIL=0.06 and PHAT_ALPHA_SAME=0.12 with K=P/(P+R); remove unused second-print/revert logic (REVERT_U stays 0). Slot13 stores absolute price-squared WAD posterior P, initialized to (initialPrice*0.00095)^2. On each new step add (pHat*sigmaHat)^2*uncapped elapsed; sigmaHat is relative. R=100*(feeUsed*spot)^2/3, divided by 10000 for first-in-step prints; 100 is the selected OBS_SCALE (WAD constant 100000000000000000000). At an accepted gated observation update pHat=(1-K)*pHat+K*pImplied and P=(1-K)*P; rejected observations retain prior P. Feed covariance into toxicity as sqrt(tox^2+P/pHat^2), with existing cap/EMA. Preserve existing first-print slot11/12 writes, sigma update, gate, NP retail-routing blend, fee equations and every other constant. All operations use the source WAD rounding.",
  "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 OBS_SCALE = 100000000000000000000;\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        slots[13] = wmul(wmul(slots[5], slots[6]), wmul(slots[5], slots[6]));\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 posterior = slots[13];\n            if (isNewStep) {\n                uint256 priceSigma = wmul(pHat, sigmaHat);\n                posterior += wmul(priceSigma, priceSigma) * (trade.timestamp - lastTs);\n            }\n            uint256 band = wmul(feeUsed, spot);\n            uint256 obsVariance = wmul(wmul(band, band) / 3, OBS_SCALE);\n            // An initial print approximates an arbitrage band-edge observation.\n            if (firstInStep) obsVariance /= 10000;\n            uint256 alpha = posterior + obsVariance > 0 ? wdiv(posterior, posterior + obsVariance) : WAD;\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) {\n                pHat = wmul(pHat, WAD - alpha) + wmul(pImplied, alpha);\n                posterior = wmul(posterior, WAD - alpha);\n            }\n            slots[13] = posterior;\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 (pHat > 0) tox = sqrt(tox * tox + wdiv(slots[13], wmul(pHat, pHat)) * WAD);\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        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": "9acbd3b7259998b8209c291d80d40cd08928082142371520ee57f645d1428c42",
  "validate_ok": true,
  "max_gas": 212215,
  "np2_check": {
    "seeds": "0..999",
    "n": 1000,
    "mean": 526.1155722459862,
    "target": 526.1156,
    "absolute_error": 2.7754013785852294e-05,
    "pass_to_4dp": true,
    "code_sha256": "51f1c1a9d4999ee460eb8bbc66880da8074b173399a4f5d71f96671482e18ac0",
    "ch_mean": 525.5258821780834,
    "ch_target": 525.525882178,
    "ch_pass": true
  },
  "tune": [
    {
      "variant": "K0_1",
      "seeds": "10000..10499",
      "n": 500,
      "mean_diff": -127.48393595781245,
      "se": 0.9115175082448934
    },
    {
      "variant": "K1",
      "seeds": "10000..10499",
      "n": 500,
      "mean_diff": -127.48095168302048,
      "se": 0.911535729895252
    },
    {
      "variant": "K10",
      "seeds": "10000..10499",
      "n": 500,
      "mean_diff": -127.52324225111906,
      "se": 0.9122334927277947
    },
    {
      "variant": "K100",
      "seeds": "10000..10499",
      "n": 500,
      "mean_diff": -127.4175717719798,
      "se": 0.9099509086507432
    }
  ],
  "paired": {
    "seeds": "2020000..2021999",
    "n": 2000,
    "mean_diff": -127.18814795203053,
    "se": 0.4456680257390956,
    "worst": -200.25527547471472,
    "candidate_mean": 397.0603118281669,
    "np2_mean": 524.2484597801974,
    "worst5": [
      {
        "seed": 2020751,
        "diff": -200.25527547471472
      },
      {
        "seed": 2021942,
        "diff": -194.99116912525665
      },
      {
        "seed": 2021562,
        "diff": -192.34946043776313
      },
      {
        "seed": 2021353,
        "diff": -191.93914673933915
      },
      {
        "seed": 2021376,
        "diff": -191.52076154662757
      }
    ]
  },
  "next": "Reject this Kalman variant and retain NP2. A future experiment could model whether the first print was arbitrage or retail instead of treating all first prints as almost noiseless; that is a separate, untested mechanism.",
  "blocked": null,
  "methodology": {
    "simulator": "https://github.com/benedictbrady/amm-challenge",
    "commit": "6b6921f8d463314aa7c96234e1be25a25245f704",
    "comparison": "Each strategy separately vs VanillaStrategy (30bps); subtract submission edge per identical seed, never compare candidate and NP2 in the same market.",
    "draws": "numpy.default_rng(seed): size U(19,21), rate U(0.6,1.0), sigma U(0.000882,0.001008), in that order. All 12 config fields checked equal to MatchRunner._build_configs for seeds 0..9.",
    "config": {
      "n_steps": 10000,
      "initial_price": 100,
      "initial_x": 100,
      "initial_y": 10000,
      "gbm_mu": 0,
      "gbm_dt": 1,
      "retail_size_sigma": 1.2,
      "retail_buy_prob": 0.5,
      "price_seed": "seed",
      "retail_seed": "seed+1"
    },
    "execution": "Unmodified amm_sim_rs.run_batch, 8 workers, chunks of 25; edge arrays remain in seed order.",
    "statistics": "Mean of candidate edge minus NP2 edge. SE=sample SD(ddof=1)/sqrt(n); worst=minimum paired difference. All 2000 consecutive confirmation seeds completed. No candidate changes or repeated candidate confirmation after freezing.",
    "selection": "Highest paired tuning mean across four predeclared observation scales; no confirmation data observed.",
    "variants": "K0_1=OBS_SCALE 0.1; K1=1; K10=10; K100=100. Only this constant differs across tuning variants.",
    "np2_reconstruction": "TWO code plus the NP substring beginning // Interior retail routing and ending immediately before uint256 tradeRatio =, inserted immediately before the same TWO declaration; exact full hash checked.",
    "setup": "Ran workspace-contained setup once, omitting host-inspection platform commands under the access restriction. Setup, starter validation, CH target and NP2 target passed; no setup failure."
  },
  "checks": {
    "validate_stdout": "Validating strategy...\nCompiling strategy...\nStrategy 'no_cubic' validated successfully!",
    "gas": {
      "init_gas": 212215,
      "max_swap_gas": 146547,
      "max_gas": 212215,
      "calls": 5000,
      "all_success": true
    },
    "gas_scope": "pyrevm EVM.result.gas_used (not executor gas estimates); includes initialization and 5000 successful swap calls, excludes deployment. CP reserve updates on both sides, sizes 0.01%-9% of reserves, repeated timestamps and gaps 1/2/8/64/10000; all fee outputs in [0,0.1]. These are measured stress cases, not a proof for every input.",
    "filter": "PASS: initialization, elapsed process variance, first-print gain, posterior update, same-step no process increment; exact WAD arithmetic",
    "confirmation_code_frozen": true
  }
}
