{
  "np2_check": {
    "n": 1000,
    "seeds": "0..999",
    "expected_mean_edge": 526.1156,
    "mean_edge": 526.1155722459862,
    "passed": true,
    "sha256": "51f1c1a9d4999ee460eb8bbc66880da8074b173399a4f5d71f96671482e18ac0",
    "ch": {
      "n": 1000,
      "expected_mean_edge": 525.525882178,
      "mean_edge": 525.5258821780834,
      "sha256": "6dd68f77a70900319460215374143dbd5d924198450a46d9f5f91f6b1e3d35c3",
      "passed": true
    }
  },
  "design": "Simulator-only oracle of the current step fair price, with no lookahead or true sigma/retail parameters. Rust appends floor(fair_price*1e18) as a seventh calldata word to every afterSwap. NP2 is unchanged except assembly { pHat := calldataload(196) } immediately before tradeRatio, after its estimated-price/sigma and interior-routing blocks. All NP2 fee equations, constants, initialization and other updates remain. The true pHat is stored for the next callback; sigmaHat is still estimated, so its realized path can change through pHat feedback. Fees update only after actual swaps; no quote update precedes the first trade of a step. This is an information ablation of NP2, not a globally optimized oracle fee bound.",
  "paired": {
    "n": 2000,
    "seed_start": 2270000,
    "seed_end": 2271999,
    "mean_diff": -5.3865418338539985,
    "se": 0.05699967660579996,
    "np2_mean_edge": 528.2444856778865,
    "oracle_mean_edge": 522.8579438440325,
    "worst": [
      {
        "seed": 2270965,
        "diff": -13.6104767637529,
        "oracle_edge": 507.6125463016381,
        "np2_edge": 521.223023065391
      },
      {
        "seed": 2270882,
        "diff": -13.421851032302811,
        "oracle_edge": 563.3811080857573,
        "np2_edge": 576.8029591180601
      },
      {
        "seed": 2271530,
        "diff": -12.519057121226297,
        "oracle_edge": 550.3314365785709,
        "np2_edge": 562.8504936997972
      },
      {
        "seed": 2271965,
        "diff": -12.468378007743013,
        "oracle_edge": 442.6991019100732,
        "np2_edge": 455.1674799178162
      },
      {
        "seed": 2271783,
        "diff": -12.445556635753974,
        "oracle_edge": 579.3758348045588,
        "np2_edge": 591.8213914403128
      }
    ]
  },
  "blocked": null,
  "next": "Inference: target part of the +15.57 arb-edge gain using bounds from arbitrage prints and router equality, while preserving NP2 retail attraction. Decouple price estimation from fee skew. Untested: true-price substitution loses 20.96 retail edge and nets -5.39 under the fixed rule.",
  "methodology": {
    "simulator_commit": "6b6921f8d463314aa7c96234e1be25a25245f704",
    "comparison": "Separate oracle-vs-Vanilla and NP2-vs-Vanilla markets on identical seed configs; paired submission total edge differences. These are not oracle-vs-NP2 head-to-head games.",
    "config": "For each seed s: numpy.default_rng(s), draw size U(19,21), rate U(0.6,1.0), sigma U(0.000882,0.001008), in that order. cfg.seed=s. Price seed=s, retail seed=s+1. 10000 steps, initial price=100, x=100, y=10000, mu=0, dt=1, retail size sigma=1.2, buy probability=0.5.",
    "statistics": "Arithmetic means per simulation; mean_diff=oracle edge minus NP2 edge; SE=sample std(ddof=1)/sqrt(n). worst is five smallest individual paired differences. Edge and volume components are means per simulation in quote currency Y.",
    "freshness": "No tuning or fee optimization. Design frozen before any confirmation results; both variants evaluated once on seeds 2270000..2271999. Tuning seeds 10000..10019 used only for simulator identity check. No other seeds in the requested confirmation block were used.",
    "execution": "Exact requested item setup script succeeded once; amm-match validate StarterStrategy succeeded. amm_sim_rs.run_batch, eight workers, batches of 20. All original baseline checks used unmodified simulator. Patched simulator omits chart snapshots, sums fees directly, exposes arb/retail edge, and aborts on callback errors instead of retaining old fees.",
    "evidence": "All numerical performance claims are locally measured, not scores copied from cited sources. Sources document code and simulator semantics.",
    "source_roles": {
      "strategy_inputs": [
        "https://api.imd.fun/artifacts/528a6da78583c6142644a552c86670f9d25c20e39e92f4de44deae05ddc8cecd",
        "https://api.imd.fun/artifacts/da313379a2e69e9286668865e06b18dfcae25732c82b934b0fd9c2ef0d8c2ff5"
      ],
      "ch_reference": "https://raw.githubusercontent.com/ChengHua926/amm-challenge/d34a5199c59a4c44d5336a25f1436b4ae1f21104/contracts/src/Strategy.sol",
      "simulator": "https://github.com/benedictbrady/amm-challenge/tree/6b6921f8d463314aa7c96234e1be25a25245f704",
      "measurements": "Local run_batch results summarized here; measurement_script and simulator_patch describe how they were produced."
    }
  },
  "checks": {
    "patched_control": {
      "n": 20,
      "seed_start": 10000,
      "seed_end": 10019,
      "original_vs_patched_np2": "Bit-exact submission edge, arbitrage volume and retail volume on every seed.",
      "passed": true
    },
    "all_confirmation_callbacks_succeeded": true,
    "callback_price_transport": {
      "n": 6,
      "passed": true,
      "details": "Direct EVM afterSwap calls stored the supplied seventh calldata word exactly in slots[5], with changing prices, repeated timestamps, and a fractional WAD price."
    },
    "edge_decomposition_max_abs_error": 5.002220859751105e-12
  },
  "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        // Simulator-only current-step fair price, appended after TradeInfo.\n        assembly (\"memory-safe\") { pHat := calldataload(196) }\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        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",
  "sha256": "f78914b884fb9d534ed028fcd589e55c13c838a4bb417e452ab433292a4c275f",
  "simulator_patch": "diff --git a/amm_sim_rs/src/amm/cfmm.rs b/amm_sim_rs/src/amm/cfmm.rs\nindex 02e6645..0b2808b 100644\n--- a/amm_sim_rs/src/amm/cfmm.rs\n+++ b/amm_sim_rs/src/amm/cfmm.rs\n@@ -84,6 +84,10 @@ impl CFMM {\n         Ok(())\n     }\n \n+    pub fn set_oracle_price(&mut self, price: f64) {\n+        self.strategy.set_oracle_price(price);\n+    }\n+\n     /// Get current reserves.\n     pub fn reserves(&self) -> (f64, f64) {\n         (self.reserve_x, self.reserve_y)\n@@ -291,10 +295,9 @@ impl CFMM {\n \n     /// Update fees from strategy after a trade.\n     fn update_fees(&mut self, trade_info: &TradeInfo) {\n-        if let Ok((bid_fee, ask_fee)) = self.strategy.after_swap(trade_info) {\n-            self.current_fees = FeeQuote::new(bid_fee.clamp_fee(), ask_fee.clamp_fee());\n-        }\n-        // On error, keep current fees\n+        let (bid_fee, ask_fee) = self.strategy.after_swap(trade_info)\n+            .expect(\"afterSwap failed: oracle experiment must not silently retain stale fees\");\n+        self.current_fees = FeeQuote::new(bid_fee.clamp_fee(), ask_fee.clamp_fee());\n     }\n \n     /// Reset the AMM for a new simulation.\ndiff --git a/amm_sim_rs/src/evm/strategy.rs b/amm_sim_rs/src/evm/strategy.rs\nindex 1d06af1..538bd45 100644\n--- a/amm_sim_rs/src/evm/strategy.rs\n+++ b/amm_sim_rs/src/evm/strategy.rs\n@@ -56,6 +56,7 @@ pub struct EVMStrategy {\n     db: InMemoryDB,\n     /// Pre-allocated calldata buffer for after_swap (196 bytes)\n     trade_calldata: [u8; 196],\n+    oracle_price: Wad,\n }\n \n impl EVMStrategy {\n@@ -66,6 +67,7 @@ impl EVMStrategy {\n             bytecode: bytecode.clone(),\n             db: InMemoryDB::default(),\n             trade_calldata: [0u8; 196],\n+            oracle_price: Wad::from_f64(100.0),\n         };\n \n         strategy.deploy()?;\n@@ -172,6 +174,10 @@ impl EVMStrategy {\n             .ok_or_else(|| EVMError::InvalidReturnData(\"Failed to decode fee pair\".into()))\n     }\n \n+    pub fn set_oracle_price(&mut self, price: f64) {\n+        self.oracle_price = Wad::from_f64(price);\n+    }\n+\n     /// Handle a trade event and return updated fees.\n     ///\n     /// Returns (bid_fee, ask_fee) in WAD.\n@@ -181,7 +187,9 @@ impl EVMStrategy {\n         trade.encode_calldata(&mut self.trade_calldata);\n \n         // Copy calldata to avoid borrow conflict\n-        let calldata = self.trade_calldata;\n+        let mut calldata = [0u8; 228];\n+        calldata[..196].copy_from_slice(&self.trade_calldata);\n+        calldata[196..].copy_from_slice(&U256::from(self.oracle_price.0 as u128).to_be_bytes::<32>());\n         let result = self.call(&calldata, GAS_LIMIT_TRADE)?;\n \n         decode_fee_pair(&result)\ndiff --git a/amm_sim_rs/src/simulation/engine.rs b/amm_sim_rs/src/simulation/engine.rs\nindex 6834c43..8cb22dd 100644\n--- a/amm_sim_rs/src/simulation/engine.rs\n+++ b/amm_sim_rs/src/simulation/engine.rs\n@@ -113,8 +113,11 @@ impl SimulationEngine {\n         edges.insert(submission_name.clone(), 0.0);\n         edges.insert(baseline_name.clone(), 0.0);\n \n+        let mut arb_edges = edges.clone();\n+        let mut retail_edges = edges.clone();\n+\n         // Run simulation steps\n-        let mut steps = Vec::with_capacity(self.config.n_steps as usize);\n+        let steps = Vec::new();\n \n         // Store AMMs in a Vec for easier mutable access\n         let mut amms = vec![amm_submission, amm_baseline];\n@@ -136,11 +139,15 @@ impl SimulationEngine {\n         for t in 0..self.config.n_steps {\n             // 1. Generate new fair price\n             let fair_price = price_process.step();\n+            for amm in amms.iter_mut() {\n+                amm.set_oracle_price(fair_price);\n+            }\n \n             // 2. Arbitrageur extracts profit from each AMM\n             for amm in amms.iter_mut() {\n                 if let Some(arb_result) = arbitrageur.execute_arb(amm, fair_price, t as u64) {\n                     *arb_volume_y.get_mut(&arb_result.amm_name).unwrap() += arb_result.amount_y;\n+                    *arb_edges.get_mut(&arb_result.amm_name).unwrap() -= arb_result.profit;\n                     let entry = edges.entry(arb_result.amm_name).or_insert(0.0);\n                     // AMM edge is the negative of arbitrageur profit at true price\n                     *entry += -arb_result.profit;\n@@ -157,27 +164,17 @@ impl SimulationEngine {\n                 } else {\n                     trade.amount_y - trade.amount_x * fair_price\n                 };\n+                *retail_edges.get_mut(&trade.amm_name).unwrap() += trade_edge;\n                 let entry = edges.entry(trade.amm_name).or_insert(0.0);\n                 *entry += trade_edge;\n             }\n \n-            // 4. Capture step result and accumulate fees\n-            let step = capture_step(\n-                t,\n-                fair_price,\n-                &amms,\n-                &names,\n-                &initial_reserves,\n-                initial_fair_price,\n-            );\n-            // Accumulate fees for averaging\n-            for name in &names {\n-                if let Some((bid_fee, ask_fee)) = step.fees.get(name) {\n-                    *cumulative_bid_fees.get_mut(name).unwrap() += bid_fee;\n-                    *cumulative_ask_fees.get_mut(name).unwrap() += ask_fee;\n-                }\n+            // Oracle experiment: aggregate fees directly; no chart snapshots.\n+            for (amm, name) in amms.iter().zip(names.iter()) {\n+                let fees = amm.fees();\n+                *cumulative_bid_fees.get_mut(name).unwrap() += fees.bid_fee.to_f64();\n+                *cumulative_ask_fees.get_mut(name).unwrap() += fees.ask_fee.to_f64();\n             }\n-            steps.push(step);\n         }\n \n         // Calculate final PnL (reserves + accumulated fees)\n@@ -209,6 +206,8 @@ impl SimulationEngine {\n             strategies: vec![submission_name, baseline_name],\n             pnl,\n             edges,\n+            arb_edges,\n+            retail_edges,\n             initial_fair_price,\n             initial_reserves,\n             steps,\ndiff --git a/amm_sim_rs/src/types/result.rs b/amm_sim_rs/src/types/result.rs\nindex 0257335..d681ab5 100644\n--- a/amm_sim_rs/src/types/result.rs\n+++ b/amm_sim_rs/src/types/result.rs\n@@ -58,6 +58,12 @@ pub struct LightweightSimResult {\n     #[pyo3(get)]\n     pub edges: HashMap<String, f64>,\n \n+    #[pyo3(get)]\n+    pub arb_edges: HashMap<String, f64>,\n+\n+    #[pyo3(get)]\n+    pub retail_edges: HashMap<String, f64>,\n+\n     /// Initial fair price\n     #[pyo3(get)]\n     pub initial_fair_price: f64,\n",
  "arb_edge": {
    "oracle": -16.5460756536342,
    "np2": -32.11955496041246,
    "mean_diff": 15.573479306778259,
    "se": 0.04442023466093047
  },
  "retail_edge": {
    "oracle": 539.4040194976667,
    "np2": 560.364040638299,
    "mean_diff": -20.96002114063227,
    "se": 0.07721728981592121
  },
  "arb_volume": {
    "oracle": 13178.799400804368,
    "np2": 24166.78948857677,
    "mean_diff": -10987.990087772403,
    "se": 20.573811706406264
  },
  "retail_volume": {
    "oracle": 71028.62475003107,
    "np2": 77512.55850425587,
    "mean_diff": -6483.9337542247995,
    "se": 15.38183776118891
  },
  "interpretation": "The oracle reduces arbitrage losses and both trade volumes, but the retail-edge loss exceeds the arbitrage-edge saving. This experiment supplies no positive net gain from replacing pHat alone under NP2 fees. It does not establish a mathematical upper bound on strategies that jointly redesign tracking and fee response. SigmaHat and other state remain estimated; their paths and order routing respond endogenously.",
  "measurement_script": "import argparse,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.competition.config import build_config\n\nP=Path('scratch')\ndef compile_one(name,source):\n    p=P/(name+'.bin')\n    c=SolidityCompiler().compile(source)\n    if not c.success: raise RuntimeError(c.errors)\n    p.write_bytes(c.bytecode)\n    return c.bytecode\n\ndef config(s):\n    rng=np.random.default_rng(s)\n    size=rng.uniform(19.,21.);rate=rng.uniform(.6,1.);sigma=rng.uniform(.000882,.001008)\n    return build_config(seed=s,retail_mean_size=size,retail_arrival_rate=rate,gbm_sigma=sigma)\n\ndef run(name,start,n,chunk=20,workers=8):\n    bytecode=(P/(name+'.bin')).read_bytes();vanilla=(P/'Vanilla.bin').read_bytes()\n    out=P/(f'{name}-{start}-{n}.jsonl');assert not out.exists(),str(out)\n    begin=time.monotonic()\n    with out.open('w') as f:\n        for a in range(start,start+n,chunk):\n            seeds=range(a,min(a+chunk,start+n))\n            batch=amm_sim_rs.run_batch(list(bytecode),list(vanilla),[config(s) for s in seeds],workers)\n            for r in batch.results:\n                row={'seed':r.seed,'edge':r.edges['submission'],'arb_volume':r.arb_volume_y['submission'],'retail_volume':r.retail_volume_y['submission']}\n                if hasattr(r,'arb_edges'):\n                    row.update(arb_edge=r.arb_edges['submission'],retail_edge=r.retail_edges['submission'])\n                    assert abs(row['edge']-row['arb_edge']-row['retail_edge'])<1e-7\n                f.write(json.dumps(row)+'\\n')\n            f.flush()\n            print(json.dumps({'name':name,'done':min(a+chunk,start+n)-start,'n':n,'seconds':time.monotonic()-begin}),flush=True)\n    rows=[json.loads(l) for l in out.read_text().splitlines()]\n    result={k:float(np.mean([r[k] for r in rows])) for k in rows[0] if k!='seed'}\n    result.update(n=n,start=start,seconds=time.monotonic()-begin)\n    print(json.dumps(result),flush=True)\n    (P/(f'{name}-{start}-{n}-summary.json')).write_text(json.dumps(result,indent=2))\n\nif __name__=='__main__':\n    ap=argparse.ArgumentParser();ap.add_argument('name');ap.add_argument('start',type=int,nargs='?',default=0);ap.add_argument('n',type=int,nargs='?',default=1000);ap.add_argument('--chunk',type=int,default=20);a=ap.parse_args()\n    if a.name=='compile':\n        for name in ['CH','NP2']:\n            compile_one(name,(P/(name+'.sol')).read_text())\n        compile_one('Vanilla',Path('contracts/src/VanillaStrategy.sol').read_text().replace('contract VanillaStrategy','contract Strategy'))\n    else:run(a.name,a.start,a.n,a.chunk)\n",
  "callback_check_script": "from pathlib import Path\nfrom pyrevm import EVM\nimport json\nW=10**18\ncaller='0x2000000000000000000000000000000000000002'\nevm=EVM();addr=evm.deploy(deployer=caller,code=Path('scratch/Oracle.bin').read_bytes(),value=0,gas=10_000_000)\ndef u(n):return n.to_bytes(32,'big')\ninit=evm.message_call(caller=caller,to=addr,calldata=bytes.fromhex('837aef47')+u(100*W)+u(10000*W),value=0,gas=250000)\nassert len(init)==64\nprices=[100*W,101*W,99*W,110*W,90*W,100*W+123456789]\nmeasure=[]\nfor i,p in enumerate(prices):\n    ts=i//2+1\n    data=bytes.fromhex('c2babb57')+b''.join(u(n) for n in [i%2,W//100,W,ts,100*W,10000*W])+u(p)\n    assert len(data)==228\n    result=evm.message_call(caller=caller,to=addr,calldata=data,value=0,gas=250000)\n    assert len(result)==64\n    stored=evm.storage(addr,5)\n    assert stored==p,(i,stored,p)\n    fees=[int.from_bytes(result[k:k+32],'big') for k in (0,32)]\n    assert all(0<=f<=W//10 for f in fees)\n    measure.append({'timestamp':ts,'input_price_wad':p,'stored_pHat':stored,'fees_wad':fees})\nPath('scratch/callback-check.json').write_text(json.dumps({'passed':True,'n':len(measure),'cases':measure},indent=2)+'\\n')\nprint('Oracle callback stores exactly the supplied price, including repeated timestamps and fractional WAD prices: 6/6 passed.')\n",
  "setup_script": "set -eu;R=$PWD/scratch;mkdir -p $R/tmp $R/bin $R/solcx\necho \"export TMPDIR=$R/tmp XDG_CACHE_HOME=$R/xc UV_CACHE_DIR=$R/uvc UV_PYTHON_INSTALL_DIR=$R/uvpy RUSTUP_HOME=$R/rustup CARGO_HOME=$R/cargo SOLCX_BINARY_PATH=$R/solcx VIRTUAL_ENV=$PWD/.venv PATH=$PWD/.venv/bin:$R/bin:$R/cargo/bin:\\$PATH\" >$R/env.sh;. $R/env.sh\ncommand -v uv >/dev/null||{ curl -LsSf https://github.com/astral-sh/uv/releases/latest/download/uv-x86_64-unknown-linux-gnu.tar.gz|tar --no-same-owner -xz -C $R/tmp;cp $R/tmp/uv-*/uv $R/bin/;}\ncc --version >/dev/null 2>&1||{ curl -Ls https://micro.mamba.pm/api/micromamba/linux-64/latest -o $R/tmp/mm.tbz;python3 -c \"import sys,tarfile;tarfile.open(sys.argv[1]).extract('bin/micromamba',sys.argv[2])\" $R/tmp/mm.tbz $R;MAMBA_ROOT_PREFIX=$R/mamba $R/bin/micromamba create -yq -p $R/cenv -c conda-forge gcc;ln -sf $(ls $R/cenv/bin/*gcc|head -n1) $R/bin/cc;}\ncommand -v cargo >/dev/null||{ curl -sSf https://sh.rustup.rs|sh -s -- -y --profile minimal --no-modify-path;}\nuv venv --python 3.12 .venv;uv pip install -e . maturin\nmaturin develop --release --uv --manifest-path amm_sim_rs/Cargo.toml\namm-match validate contracts/src/StarterStrategy.sol\n",
  "reproduction": "Use setup_script once at the pinned checkout root. Source scratch/env.sh for later commands. Reconstruct NP2 as requested from the two artifact code fields; its SHA-256 must match np2_check.sha256. Save NP2.sol and CH.sol in scratch. Save measurement_script as scratch/measure.py and run its compile command. Original checks: CH 0 1000 and NP2 0 1000. For patched runs apply simulator_patch, rebuild with the setup maturin command, compile code as Oracle.sol to Oracle.bin, and copy NP2.bin to NP2Patched.bin. Run each against Vanilla using measure.py on seed_start and n in paired. Subtract rows by seed, never compare the two strategies inside one market. The extra callback calldata is required by this simulator-only Oracle.sol."
}
