{"item":"censored-price","blocked":null,"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[3] = WAD; \n        slots[5] = initialX > 0 ? wdiv(initialY, initialX) : 100 * WAD;\n        slots[6] = 950000000000000; slots[7] = 800000000000000000; slots[8] = 2000000000000000;\n        slots[13] = 902500000000; slots[14] = slots[5]; \n        return (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 = uint64(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        uint256 sigmaForFast = sigmaHat;\n        uint256 fastHat = slots[14];\n        uint256 uncertainty = slots[13];\n        uint256 silent = trade.timestamp > lastTs ? trade.timestamp - lastTs : 0;\n        bool isNewStep = trade.timestamp > lastTs;\n        if (isNewStep) {\n            uint256 elapsedRaw = trade.timestamp - lastTs;\n            uint256 elapsed = elapsedRaw > ELAPSED_CAP ? ELAPSED_CAP : elapsedRaw;\n            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            // Process variance is propagated inside the censored update.\n            if (uncertainty > 100000000000000) uncertainty = 100000000000000;\n            stepTradeCount = 0;\n        }\n\n        bool firstInStep = stepTradeCount == 0;\n        uint256 spot = trade.reserveX > 0 ? wdiv(trade.reserveY, trade.reserveX) : pHat;\n        if (pHat == 0) pHat = spot;\n\n        uint256 feeUsed = trade.isBuy ? prevBidFee : prevAskFee;\n        uint256 gamma = feeUsed < WAD ? WAD - feeUsed : 0;\n        uint256 pImplied;\n        if (gamma == 0) { pImplied = spot; }\n        else { pImplied = trade.isBuy ? wmul(spot, gamma) : wdiv(spot, gamma); }\n\n        // S: infer a no-trade interval center from the last post-trade spot.\n        uint256 silenceScale = WAD;\n        if (firstInStep && silent > 1) {\n            uint256 g = silent - 1;\n            if (g > 1) g = 1;\n            uint256 w = WAD - _powWad(800000000000000000, g);\n            uint256 s = slots[2] >> 64;\n            if (s == 0) s = pHat;\n            uint256 c = (wmul(s, WAD - prevBidFee) + wdiv(s, WAD - prevAskFee)) / 2;\n            if (c >= pHat) pHat += wmul(w, c - pHat);\n            else pHat -= wmul(w, pHat - c);\n            silenceScale = WAD - wmul(300000000000000000, w);\n        }\n\n        {\n            uint256 ret = pHat > 0 ? wdiv(absDiff(pImplied, pHat), pHat) : 0;\n            uint256 alpha = firstInStep ? PHAT_ALPHA : PHAT_ALPHA_RETAIL;\n            uint256 prePhat = pHat;\n            bool secondPrint = !firstInStep && stepTradeCount == 1;\n            bool sameDir = false; bool oppDir = false;\n            if (secondPrint) {\n                bool up2 = pImplied >= pHat;\n                uint256 d1 = slots[12];\n                if (d1 != 0) { sameDir = (d1 == 1) == up2; oppDir = !sameDir; }\n                if (sameDir) alpha = PHAT_ALPHA_SAME;\n            }\n            if (firstInStep) { slots[12] = pImplied >= pHat ? 1 : 2; }\n            uint256 adaptiveGate = wmul(sigmaHat, GATE_SIGMA_MULT);\n            if (adaptiveGate < MIN_GATE) adaptiveGate = MIN_GATE;\n            alpha = wmul(alpha, silenceScale);\n            adaptiveGate = wmul(adaptiveGate, silenceScale);\n            if (ret <= adaptiveGate) { pHat = wmul(pHat, WAD - alpha) + wmul(pImplied, alpha); }\n            if (oppDir && REVERT_U > 0) {\n                uint256 pre = slots[11];\n                if (pre > pHat) pHat = pHat + wmul(pre - pHat, REVERT_U);\n                else pHat = pHat - wmul(pHat - pre, REVERT_U);\n            }\n            if (firstInStep) {\n                if (ret > RET_CAP) ret = RET_CAP;\n                sigmaHat = wmul(sigmaHat, SIGMA_DECAY) + wmul(ret, WAD - SIGMA_DECAY);\n            }\n        }\n\n        // Interior retail routing equalizes fee-adjusted marginal prices.\n        // Subsequent trades in a step cannot be the initial arbitrage trade.\n        if (!firstInStep && feeUsed > 30 * BPS && gamma > 0) {\n            uint256 normalSpot = trade.isBuy\n                ? wdiv(wmul(spot, gamma), WAD - 30 * BPS)\n                : wdiv(wmul(spot, WAD - 30 * BPS), gamma);\n            pHat = wmul(pHat, 90 * WAD / 100) + wmul(normalSpot, 10 * WAD / 100);\n        }\n\n        // Censored assumed-density posterior. No external or future inputs.\n        (fastHat, uncertainty) = _posterior(PosteriorInput(\n            fastHat, uncertainty, pImplied, spot, slots[2] >> 64,\n            prevBidFee, prevAskFee, firstInStep, silent, trade.isBuy,\n            trade.reserveY > 0 ? wdiv(trade.amountY, trade.reserveY) : 0\n        ));\n        slots[13] = uncertainty;\n        slots[14] = fastHat;\n        uint256 tradeRatio = trade.reserveY > 0 ? wdiv(trade.amountY, trade.reserveY) : 0;\n        if (tradeRatio > TRADE_RATIO_CAP) tradeRatio = TRADE_RATIO_CAP;\n\n        if (tradeRatio > SIGNAL_THRESHOLD) {\n            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 staleHat = wmul(pHat, 700000000000000000) + wmul(fastHat, 300000000000000000);\n            uint256 staleTox = wdiv(absDiff(spot, staleHat), staleHat);\n            if (staleTox > TOX_CAP) staleTox = TOX_CAP;\n            uint256 staleShift = wmul(STALE_DIR_COEF, staleTox);\n            uint256 attractShift = wmul(staleShift, STALE_ATTRACT_FRAC);\n            if (spot >= staleHat) {\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 (!firstInStep && tradeBoost > 16 * BPS) tradeBoost = 16 * BPS;\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        if (firstInStep) {\n            if (askFee > bidFee && bidFee > 30 * BPS) bidFee = 30 * BPS;\n            else if (bidFee > askFee && askFee > 30 * BPS) askFee = 30 * BPS;\n        }\n\n        if (bidFee > askFee && askFee > 36 * BPS) askFee = 36 * BPS;\n        else if (askFee > bidFee && bidFee > 36 * BPS) bidFee = 36 * BPS;\n\n        slots[0] = bidFee; slots[1] = askFee; slots[2] = (spot << 64) | 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\n    struct PosteriorInput {\n        uint256 mu; uint256 v; uint256 obs; uint256 spot; uint256 preSpot;\n        uint256 bid; uint256 ask; bool first; uint256 silent; bool buy; uint256 size;\n    }\n    function _posterior(PosteriorInput memory x) internal pure returns (uint256, uint256) {\n        if (x.mu == 0) x.mu = x.spot;\n        if (x.v < 10000000000) x.v = 10000000000;\n        uint256 lo = wmul(x.preSpot, WAD-x.bid);\n        uint256 hi = wdiv(x.preSpot, WAD-x.ask);\n        if (x.first) {\n            if (x.silent>1 && x.preSpot>0) {\n                uint256 elapsed=x.silent>8?8:x.silent;\n                x.v += 902500000000*(elapsed-1);\n                (x.mu,x.v)=_band(x.mu,x.v,lo,hi);\n            }\n            x.v+=902500000000;\n        }\n        uint256 mRetail = x.mu;\n        uint256 vRetail = x.v;\n        // A missing own-pool trade is a censored price observation.\n        if (x.first && x.preSpot > 0) {\n            (mRetail, vRetail) = _band(x.mu, x.v, lo, hi);\n        }\n        if (!x.first) {\n            // A later print is retail. Only an interior route is an observation\n            // of the other pool, with explicit observation uncertainty.\n            uint256 fee = x.buy ? x.bid : x.ask;\n            if (fee > 30 * BPS) {\n                uint256 normal = x.buy ? wdiv(wmul(x.spot, WAD-fee), WAD-30*BPS)\n                    : wdiv(wmul(x.spot, WAD-30*BPS), WAD-fee);\n                uint256 residual = wdiv(absDiff(normal, x.mu),x.mu);\n                uint256 noise = 9000000000000 + wmul(residual,residual);\n                uint256 k = wdiv(x.v,x.v+noise);\n                return (_blend(x.mu,normal,k),wmul(x.v,WAD-k));\n            }\n            return (x.mu,x.v);\n        }\n        uint256 e = wdiv(absDiff(x.obs,x.mu),x.mu);\n        uint256 totalV = x.v + 22500000000;\n        uint256 z = wdiv(wmul(e,e),totalV);\n        uint256 density = _powWad(wdiv(WAD,WAD+z/8),4);\n        uint256 odds = wmul(density,wdiv(4000000000000000,_isqrt(totalV*WAD)));\n        if (x.size > 3000000000000000) odds = wmul(odds,4*WAD/10);\n        if (x.silent > 1) odds = wmul(odds,8*WAD/10);\n        uint256 sd = _isqrt(x.v*WAD);\n        uint256 width = wdiv(hi-lo,x.mu);\n        uint256 distance = x.mu<lo?lo-x.mu:(x.mu>hi?x.mu-hi:0);\n        uint256 zBand = wdiv(wdiv(distance,x.mu),sd);\n        uint256 mass = wmul(wdiv(width,width+2*sd),wdiv(WAD,WAD+wmul(zBand,zBand)));\n        if (mass < WAD/100) mass = WAD/100;\n        odds = wdiv(odds,mass);\n        uint256 prob = wdiv(odds,WAD+odds);\n        uint256 kArb = wdiv(x.v,totalV);\n        uint256 mArb = _blend(x.mu,x.obs,kArb);\n        uint256 mean = _blend(mRetail,mArb,prob);\n        uint256 between = wdiv(absDiff(mArb,mRetail),x.mu);\n        uint256 variance = wmul(prob,wmul(x.v,WAD-kArb)) + wmul(WAD-prob,vRetail)\n            + wmul(wmul(prob,WAD-prob),wmul(between,between));\n        if (variance > 100000000000000) variance = 100000000000000;\n        return (mean,variance);\n    }\n    function _blend(uint256 a,uint256 b,uint256 w) internal pure returns(uint256) {\n        return b>=a ? a+wmul(b-a,w) : a-wmul(a-b,w);\n    }\n    function _band(uint256 mu,uint256 v,uint256 lo,uint256 hi) internal pure returns(uint256,uint256) {\n        // Soft interval likelihood avoids discontinuities at quadrature nodes.\n        uint256 sd=wmul(mu,_isqrt(v*WAD));\n        uint256[3] memory acc;\n        for(uint256 j=0;j<7;j++) {\n            uint256 p=j<3 ? (mu>(3-j)*sd?mu-(3-j)*sd:1) : mu+(j-3)*sd;\n            uint256 w=j==3?72:(j==2||j==4?45:(j==1||j==5?10:1));\n            uint256 distance=p<lo?lo-p:(p>hi?p-hi:0);\n            uint256 z=sd>0?wdiv(distance,sd):0;\n            uint256 likelihood=wdiv(WAD,WAD+4*wmul(z,z));\n            w=wmul(w*WAD,likelihood);\n            acc[0]+=w;acc[1]+=wmul(w,p);\n            uint256 d=wdiv(absDiff(p,mu),mu);\n            acc[2]+=wmul(w,wmul(d,d));\n        }\n        uint256 m=wdiv(acc[1],acc[0]);\n        uint256 d=wdiv(absDiff(m,mu),mu);\n        uint256 second=wdiv(acc[2],acc[0]);\n        return(m,second>wmul(d,d)?second-wmul(d,d):10000000000);\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    // Floor square root: bit-length seed and seven Newton steps (all uint256).\n    function _isqrt(uint256 x) internal pure returns (uint256 r) {\n        if (x == 0) return 0;\n        unchecked {\n            uint256 y = x;\n            r = 1;\n            if (y >> 128 != 0) { y >>= 128; r <<= 64; }\n            if (y >> 64 != 0) { y >>= 64; r <<= 32; }\n            if (y >> 32 != 0) { y >>= 32; r <<= 16; }\n            if (y >> 16 != 0) { y >>= 16; r <<= 8; }\n            if (y >> 8 != 0) { y >>= 8; r <<= 4; }\n            if (y >> 4 != 0) { y >>= 4; r <<= 2; }\n            if (y >> 2 != 0) { r <<= 1; }\n            r = (r + x / r) >> 1;\n            r = (r + x / r) >> 1;\n            r = (r + x / r) >> 1;\n            r = (r + x / r) >> 1;\n            r = (r + x / r) >> 1;\n            r = (r + x / r) >> 1;\n            r = (r + x / r) >> 1;\n            uint256 t = x / r;\n            return r < t ? r : t;\n        }\n    }\n\n    function getName() external pure override returns (string memory) { return \"censored_10\"; }\n}\n","sha256":"cd9bdb45ab0537ad25c4fd90ca8618898cef6386de3df65f192eaef65fbca245","harness_source":"\"\"\"Run from the pinned amm-challenge checkout, with the brief's environment active.\npython harness.py --start 5000000 --n 2000 --out measured.json candidate.sol STACK.sol\nDo not use confirmation seeds to choose or change a strategy.\n\"\"\"\nimport argparse,hashlib,json,math\nfrom pathlib import Path\nimport numpy as np\nimport amm_sim_rs as sim\nfrom amm_competition.evm.compiler import SolidityCompiler\n\n\ndef configs(start,n):\n    configs=[]\n    for seed in range(start,start+n):\n        rng=np.random.default_rng(seed)\n        size=rng.uniform(19.,21.)\n        rate=rng.uniform(.6,1.)\n        sigma=rng.uniform(.000882,.001008)\n        configs.append(sim.SimulationConfig(n_steps=10000,initial_price=100.,\n            initial_x=100.,initial_y=10000.,gbm_mu=0.,gbm_sigma=sigma,gbm_dt=1.,\n            retail_arrival_rate=rate,retail_mean_size=size,retail_size_sigma=1.2,\n            retail_buy_prob=.5,seed=seed))\n    return configs\n\n\ndef decomposition(r,initial_fee=.0004):\n    # Fees are outside reserves, so k stays fixed up to floating-point roundoff.\n    # The arb acts before retail, using the preceding step's final spot and fees.\n    steps=r.steps\n    fair=np.array([s.fair_price for s in steps])\n    spots=np.array([r.initial_fair_price]+[s.spot_prices['submission'] for s in steps[:-1]])\n    bids=np.array([initial_fee]+[s.fees['submission'][0] for s in steps[:-1]])\n    asks=np.array([initial_fee]+[s.fees['submission'][1] for s in steps[:-1]])\n    x0,y0=r.initial_reserves['submission'];k=x0*y0\n    x=np.sqrt(k/spots);y=np.sqrt(k*spots)\n    ga=1-asks;gb=1-bids\n    out=np.minimum(np.maximum(x-np.sqrt(k/(ga*fair)),0),.99*x)\n    paid=(k/(x-out)-y)/ga\n    buyprofit=np.where(out>0,np.maximum(out*fair-paid,0),0)\n    gross=np.maximum((np.sqrt(k*gb/fair)-x)/gb,0)\n    received=y-k/(x+gb*gross)\n    sellprofit=np.where(gross>0,np.maximum(received-gross*fair,0),0)\n    arb=-float(np.sum(np.where(spots<fair,buyprofit,sellprofit)))\n    return arb,r.edges['submission']-arb\n\n\ndef aggregate(chunks):\n    out={}\n    for chunk in chunks:\n        for row in chunk['raw']:\n            key=(row['role'],row['callback'])\n            dest=out.setdefault(key,{'role':row['role'],'callback':row['callback']})\n            for k,v in row.items():\n                if k in ['role','callback']:continue\n                dest[k]=max(dest.get(k,0),v) if k=='max_ok_gas' else dest.get(k,0)+v\n    return list(out.values())\n\n\ndef run(source,start,n,vanilla,compiler):\n    compiled=compiler.compile(source)\n    assert compiled.success,compiled.errors\n    rows=[];chunks=[]\n    for first in range(start,start+n,20):\n        count=min(20,start+n-first)\n        sim.gas_stats_reset()\n        batch=sim.run_batch(list(compiled.bytecode),list(vanilla),configs(first,count),8)\n        results=batch.results\n        assert sorted(r.seed for r in results)==list(range(first,first+count))\n        for r in results:\n            arb,retail=decomposition(r)\n            rows.append({'seed':r.seed,'edge':r.edges['submission'],'arb':arb,'retail':retail})\n        chunks.append({'start':first,'raw':sim.gas_stats()})\n        del results,batch\n    return {'sha256':hashlib.sha256(source.encode()).hexdigest(),'rows':rows,\n            'raw_counters':aggregate(chunks),'chunks':chunks}\n\n\ndef stats(d):\n    d=np.asarray(d,dtype=float)\n    return {'mean':float(d.mean()),'se':float(d.std(ddof=1)/np.sqrt(len(d)))}\n\n\ndef compare(candidate,stack):\n    a={r['seed']:r for r in candidate['rows']};b={r['seed']:r for r in stack['rows']}\n    assert a.keys()==b.keys()\n    seeds=sorted(a)\n    d=np.array([a[s]['edge']-b[s]['edge'] for s in seeds])\n    arb=np.array([a[s]['arb']-b[s]['arb'] for s in seeds])\n    retail=np.array([a[s]['retail']-b[s]['retail'] for s in seeds])\n    assert np.max(np.abs(d-arb-retail))<1e-8\n    summary=stats(d)\n    return {'paired':{'n':len(d),'mean_diff':summary['mean'],'se':summary['se'],\n                'worst':[{'seed':seeds[i],'d':float(d[i])} for i in np.argsort(d)[:5]]},\n            'retail_edge_delta':stats(retail),'arb_edge_delta':stats(arb),\n            'reconciliation_max_abs':float(np.max(np.abs(d-arb-retail)))}\n\n\nif __name__=='__main__':\n    p=argparse.ArgumentParser()\n    p.add_argument('--start',type=int,required=True);p.add_argument('--n',type=int,required=True)\n    p.add_argument('--out',required=True);p.add_argument('candidate');p.add_argument('stack')\n    args=p.parse_args()\n    compiler=SolidityCompiler()\n    vanilla=compiler.compile(Path('contracts/src/VanillaStrategy.sol').read_text(),'VanillaStrategy')\n    assert vanilla.success,vanilla.errors\n    candidate=run(Path(args.candidate).read_text(),args.start,args.n,vanilla.bytecode,compiler)\n    stack=run(Path(args.stack).read_text(),args.start,args.n,vanilla.bytecode,compiler)\n    out=compare(candidate,stack);out.update(candidate=candidate,stack=stack)\n    errors=['oog','revert','other_halt','tx_error','bad_return']\n    out['valid']=all(not any(row.get(e,0) for e in errors)\n        for arm in [candidate,stack] for row in arm['raw_counters'])\n    Path(args.out).write_text(json.dumps(out,allow_nan=False))\n    print(json.dumps({k:v for k,v in out.items() if k not in ['candidate','stack']}))\n","calibration_harness_source":"import json,time\nfrom pathlib import Path\nimport numpy as np\nimport amm_sim_rs as sim\nfrom amm_competition.evm.compiler import SolidityCompiler\nfrom amm_competition.competition.config import build_config\n\ndef configs(start,n):\n    out=[]\n    for s in range(start,start+n):\n        r=np.random.default_rng(s)\n        size=r.uniform(19,21);rate=r.uniform(.6,1);sigma=r.uniform(.000882,.001008)\n        out.append(build_config(seed=s,gbm_sigma=sigma,retail_arrival_rate=rate,retail_mean_size=size))\n    return out\nif __name__=='__main__':\n    compiler=SolidityCompiler()\n    a=compiler.compile(Path('scratch/CH.sol').read_text());b=compiler.compile(Path('contracts/src/VanillaStrategy.sol').read_text(),'VanillaStrategy')\n    assert a.success,a.errors\n    assert b.success,b.errors\n    sim.gas_stats_reset();t=time.time()\n    edges=[];stats=[]\n    for start in range(0,1000,20):\n        sim.gas_stats_reset()\n        results=sim.run_batch(list(a.bytecode),list(b.bytecode),configs(start,20),8)\n        edges.extend(r.edges['submission'] for r in results.results)\n        stats.append({'start':start,'raw':sim.gas_stats()})\n        if start==0: print('result fields',dir(results.results[0]),flush=True)\n        del results\n        print('calibration',start+20,'elapsed',time.time()-t,flush=True)\n    result={'n':len(edges),'mean':float(np.mean(edges)),'expected':525.5258821780834,'absolute_error':abs(float(np.mean(edges))-525.5258821780834),'elapsed':time.time()-t,'gas':stats}\n    print(json.dumps(result),flush=True)\n    Path('scratch/calibration.json').write_text(json.dumps(result))\n","tuning_harness_source":"import json,time,sys,hashlib\nfrom pathlib import Path\nimport numpy as np\nimport amm_sim_rs as sim\nfrom amm_competition.evm.compiler import SolidityCompiler\nfrom calibrate import configs\n\ndef decomposition(r, initial_fee=0.0004):\n    steps=r.steps\n    fair=np.array([s.fair_price for s in steps])\n    spots=np.array([r.initial_fair_price]+[s.spot_prices['submission'] for s in steps[:-1]])\n    bids=np.array([initial_fee]+[s.fees['submission'][0] for s in steps[:-1]])\n    asks=np.array([initial_fee]+[s.fees['submission'][1] for s in steps[:-1]])\n    x0,y0=r.initial_reserves['submission'];k=x0*y0\n    x=np.sqrt(k/spots);y=np.sqrt(k*spots)\n    ga=1-asks;gb=1-bids\n    out=np.minimum(np.maximum(x-np.sqrt(k/(ga*fair)),0),.99*x)\n    paid=(k/(x-out)-y)/ga\n    buyprofit=np.maximum(out*fair-paid,0)\n    gross=np.maximum((np.sqrt(k*gb/fair)-x)/gb,0)\n    received=y-k/(x+gb*gross)\n    sellprofit=np.maximum(received-gross*fair,0)\n    arb=-float(np.sum(np.where(spots<fair,buyprofit,sellprofit)))\n    return arb,r.edges['submission']-arb\n\ndef run(name,start,n):\n    compiler=SolidityCompiler()\n    source=Path('scratch/'+name+'.sol').read_text()\n    a=compiler.compile(source);b=compiler.compile(Path('contracts/src/VanillaStrategy.sol').read_text(),'VanillaStrategy')\n    assert a.success,a.errors\n    assert b.success,b.errors\n    edges=[];stats=[];t=time.time()\n    for i in range(start,start+n,20):\n        sim.gas_stats_reset()\n        results=sim.run_batch(list(a.bytecode),list(b.bytecode),configs(i,min(20,start+n-i)),8)\n        for r in results.results:\n            arb,retail=decomposition(r)\n            edges.append({'seed':r.seed,'edge':r.edges['submission'],'arb':arb,'retail':retail})\n        stats.append({'start':i,'raw':sim.gas_stats()})\n        del results\n    out={'name':name,'sha256':hashlib.sha256(source.encode()).hexdigest(),'start':start,'n':n,'mean':float(np.mean([e['edge'] for e in edges])),'edges':edges,'gas_chunks':stats,'seconds':time.time()-t}\n    Path(f'scratch/{name}-{start}-{n}.json').write_text(json.dumps(out))\n    print(json.dumps({k:v for k,v in out.items() if k not in ['edges','gas_chunks']}),flush=True)\n    print(json.dumps(stats[-1]),flush=True)\n    return out\nif __name__=='__main__':\n    start,n=map(int,sys.argv[1:3])\n    for name in sys.argv[3:]:run(name,start,n)\n","decomposition_check_source":"import json\nfrom pathlib import Path\nimport amm_sim_rs as sim\nfrom amm_competition.evm.compiler import SolidityCompiler\nfrom amm_competition.competition.config import build_config\nfrom search import decomposition\ncompiler=SolidityCompiler()\na=compiler.compile(Path('scratch/STACK.sol').read_text());b=compiler.compile(Path('contracts/src/VanillaStrategy.sol').read_text(),'VanillaStrategy')\nassert a.success and b.success\nconfigs=[build_config(seed=i,gbm_sigma=.00095,retail_arrival_rate=0,retail_mean_size=20) for i in range(11000,11032)]\nfor cfg in configs: cfg.n_steps=100\nsim.gas_stats_reset();results=sim.run_batch(list(a.bytecode),list(b.bytecode),configs,8)\nchecks=[]\nfor r in results.results:\n    if r.retail_volume_y['submission']!=0: continue\n    arb,retail=decomposition(r)\n    checks.append({'seed':r.seed,'total':r.edges['submission'],'reconstructed_arb':arb,'residual_retail_should_be_zero':retail})\nassert len(checks)>=5,checks\nassert max(abs(c['residual_retail_should_be_zero']) for c in checks)<1e-6,checks\nPath('scratch/decomposition-check.json').write_text(json.dumps(checks))\nprint(json.dumps(checks))\n","calibration":{"strategy_url":"https://raw.githubusercontent.com/ChengHua926/amm-challenge/d34a5199c59a4c44d5336a25f1436b4ae1f21104/contracts/src/Strategy.sol","sha256":"6dd68f77a70900319460215374143dbd5d924198450a46d9f5f91f6b1e3d35c3","seeds":{"start":0,"stop_exclusive":1000},"n":1000,"mean_edge":525.5258821780834,"expected":525.5258821780834,"absolute_error":0.0,"tolerance":1e-06,"passed":true,"gas":{"max_ok":151647,"oog":0,"revert":0,"other_halt":0,"tx_error":0,"bad_return":0,"raw_counters":[{"role":"Baseline","callback":"afterInitialize","calls":1000,"ok":1000,"max_ok_gas":21796,"sum_ok_gas":21796000,"oog":0,"revert":0,"other_halt":0,"tx_error":0,"bad_return":0},{"role":"Baseline","callback":"afterSwap","calls":10741746,"ok":10741746,"max_ok_gas":22592,"sum_ok_gas":242365461576,"oog":0,"revert":0,"other_halt":0,"tx_error":0,"bad_return":0},{"role":"Baseline","callback":"getName","calls":1000,"ok":1000,"max_ok_gas":21526,"sum_ok_gas":21526000,"oog":0,"revert":0,"other_halt":0,"tx_error":0,"bad_return":0},{"role":"Submission","callback":"afterInitialize","calls":1000,"ok":1000,"max_ok_gas":185532,"sum_ok_gas":185532000,"oog":0,"revert":0,"other_halt":0,"tx_error":0,"bad_return":0},{"role":"Submission","callback":"afterSwap","calls":10445223,"ok":10445223,"max_ok_gas":151647,"sum_ok_gas":811927105393,"oog":0,"revert":0,"other_halt":0,"tx_error":0,"bad_return":0},{"role":"Submission","callback":"getName","calls":1000,"ok":1000,"max_ok_gas":21530,"sum_ok_gas":21530000,"oog":0,"revert":0,"other_halt":0,"tx_error":0,"bad_return":0}]},"recovery":"The initial 1000-config calibration process exited 137 before returning results. The same calibration was completed in disjoint 20-config chunks, without changing any simulation parameter or seed."},"variant_tuning_log":[{"stage":"screen","variant":"V0","structure":"Assumed-uniform interval moment update, mixture of arb endpoint and uncertain retail observations.","sha256":"2542aa0db09bf857aee8f3af157935caeaa0b870120e2df6ae111e3e985de3cb","seeds":{"start":10000,"stop_exclusive":10100},"mean_edge":519.9656132244214,"paired":{"n":100,"mean_diff":-0.7112540853869614,"se":0.07854888945739864,"worst":[{"seed":10085,"d":-3.0100861690684724},{"seed":10089,"d":-2.918878188272629},{"seed":10078,"d":-2.863113711349797},{"seed":10092,"d":-2.37554642622581},{"seed":10065,"d":-2.2149864520622486}]},"gas":{"max_ok":190072,"oog":0,"revert":0,"other_halt":0,"tx_error":0,"bad_return":0},"afterSwap_raw":{"role":"Submission","callback":"afterSwap","calls":1026271,"ok":1026271,"max_ok_gas":190072,"sum_ok_gas":99901962399,"oog":0,"revert":0,"other_halt":0,"tx_error":0,"bad_return":0},"valid":true},{"stage":"screen","variant":"V1","structure":"Hard-truncated seven-point Gaussian quadrature for interval observations.","sha256":"73b88e99d5b7de7fecc8c90c8da6ec58283c6903a9d27c83c77d4774a9cef51f","seeds":{"start":10000,"stop_exclusive":10100},"mean_edge":519.3888057658659,"paired":{"n":100,"mean_diff":-1.2880615439424263,"se":0.08943353408656568,"worst":[{"seed":10089,"d":-5.607281258840658},{"seed":10085,"d":-3.6437102406183612},{"seed":10065,"d":-3.3258551480268466},{"seed":10092,"d":-3.2622390881635965},{"seed":10078,"d":-3.168057151140488}]},"gas":{"max_ok":190072,"oog":0,"revert":0,"other_halt":0,"tx_error":0,"bad_return":0},"afterSwap_raw":{"role":"Submission","callback":"afterSwap","calls":1034254,"ok":1034254,"max_ok_gas":190072,"sum_ok_gas":107382270544,"oog":0,"revert":0,"other_halt":0,"tx_error":0,"bad_return":0},"valid":true},{"stage":"screen","variant":"V2","structure":"Soft rational interval likelihood on seven Gaussian quadrature nodes.","sha256":"7181143e7f7fb28206343cd2e2ffd72c2c2638c26f51efdc45b704c36fdfecb0","seeds":{"start":10000,"stop_exclusive":10100},"mean_edge":520.4369688166071,"paired":{"n":100,"mean_diff":-0.23989849320139342,"se":0.05340811539112751,"worst":[{"seed":10089,"d":-1.5644937561581855},{"seed":10005,"d":-1.5351019454674883},{"seed":10078,"d":-1.4777835037887144},{"seed":10049,"d":-1.3745983665821768},{"seed":10045,"d":-1.1925906336823573}]},"gas":{"max_ok":190076,"oog":0,"revert":0,"other_halt":0,"tx_error":0,"bad_return":0},"afterSwap_raw":{"role":"Submission","callback":"afterSwap","calls":1022067,"ok":1022067,"max_ok_gas":190076,"sum_ok_gas":108704073176,"oog":0,"revert":0,"other_halt":0,"tx_error":0,"bad_return":0},"valid":true},{"stage":"screen","variant":"V3","structure":"Soft interval likelihood propagated sequentially across missing timesteps (capped at eight).","sha256":"d345b3455e8f668e7c4006d0cb01a90aaedcf528f35f312143d3742b837df253","seeds":{"start":10000,"stop_exclusive":10100},"mean_edge":520.517076404898,"paired":{"n":100,"mean_diff":-0.15979090491046632,"se":0.05185180503870299,"worst":[{"seed":10089,"d":-1.5251594302789044},{"seed":10078,"d":-1.5243719846082513},{"seed":10019,"d":-1.1888266681588675},{"seed":10062,"d":-1.0259981698170577},{"seed":10065,"d":-1.004827821104925}]},"gas":{"max_ok":249302,"oog":0,"revert":0,"other_halt":0,"tx_error":0,"bad_return":0},"afterSwap_raw":{"role":"Submission","callback":"afterSwap","calls":1023640,"ok":1023640,"max_ok_gas":249302,"sum_ok_gas":114209567475,"oog":0,"revert":0,"other_halt":0,"tx_error":0,"bad_return":0},"valid":true},{"stage":"screen","variant":"V4","structure":"V3 also replaces the slow toxicity-price estimate with the posterior mean.","sha256":"e49207a9f7e741fc24d6b04db92c9a5b7aea78b821adf925553d60dadcd1546f","seeds":{"start":10000,"stop_exclusive":10100},"mean_edge":513.6284459515055,"paired":{"n":100,"mean_diff":-7.048421358302908,"se":0.2171322012783244,"worst":[{"seed":10089,"d":-13.068200208919393},{"seed":10084,"d":-12.160556419781301},{"seed":10053,"d":-11.94375801247645},{"seed":10045,"d":-11.557376104163836},{"seed":10097,"d":-10.867756146858483}]},"gas":{"max_ok":249267,"oog":0,"revert":0,"other_halt":0,"tx_error":0,"bad_return":0},"afterSwap_raw":{"role":"Submission","callback":"afterSwap","calls":911827,"ok":911827,"max_ok_gas":249267,"sum_ok_gas":102992955718,"oog":0,"revert":0,"other_halt":0,"tx_error":0,"bad_return":0},"valid":true},{"stage":"screen","variant":"V5","structure":"Single aggregate censored update for missing timesteps, followed by current-step process noise.","sha256":"ab695ee28ff85b920753797c794298b66eb7ee107d45e5d3fc84e58dd4a7dce5","seeds":{"start":10000,"stop_exclusive":10100},"mean_edge":520.5238048493075,"paired":{"n":100,"mean_diff":-0.1530624605008967,"se":0.05215481041259253,"worst":[{"seed":10078,"d":-1.4613485557205195},{"seed":10089,"d":-1.3556861466393002},{"seed":10019,"d":-1.0836955945734417},{"seed":10095,"d":-0.9289056619404619},{"seed":10006,"d":-0.9118339581533519}]},"gas":{"max_ok":190538,"oog":0,"revert":0,"other_halt":0,"tx_error":0,"bad_return":0},"afterSwap_raw":{"role":"Submission","callback":"afterSwap","calls":1022942,"ok":1022942,"max_ok_gas":190538,"sum_ok_gas":111827528504,"oog":0,"revert":0,"other_halt":0,"tx_error":0,"bad_return":0},"valid":true},{"stage":"screen","variant":"V6","structure":"V5 replaces the complete stale-price signal with the posterior mean, retaining slow toxicity price.","sha256":"16cd05426c296d0ed329f2ca5ca01160fb771de50d2c6fef658fd27c936e34c8","seeds":{"start":10000,"stop_exclusive":10100},"mean_edge":514.5912362849175,"paired":{"n":100,"mean_diff":-6.085631024890764,"se":0.2006652705282017,"worst":[{"seed":10084,"d":-11.549146140512676},{"seed":10089,"d":-11.05735974963352},{"seed":10062,"d":-10.398110472484575},{"seed":10019,"d":-9.640056827266221},{"seed":10075,"d":-9.420639744632467}]},"gas":{"max_ok":190311,"oog":0,"revert":0,"other_halt":0,"tx_error":0,"bad_return":0},"afterSwap_raw":{"role":"Submission","callback":"afterSwap","calls":897876,"ok":897876,"max_ok_gas":190311,"sum_ok_gas":99032006690,"oog":0,"revert":0,"other_halt":0,"tx_error":0,"bad_return":0},"valid":true},{"stage":"screen","variant":"V7","structure":"V5 replaces both slow toxicity price and stale-price signal with posterior mean.","sha256":"2421be26fe7f924a93035440f91da66f5f9b150f8f1dd6e23b4b314f4415a9ff","seeds":{"start":10000,"stop_exclusive":10100},"mean_edge":513.3313856738725,"paired":{"n":100,"mean_diff":-7.345481635935816,"se":0.21451754098022047,"worst":[{"seed":10089,"d":-13.299793391909134},{"seed":10084,"d":-12.497020409434754},{"seed":10014,"d":-11.700742649738004},{"seed":10053,"d":-11.637065168038248},{"seed":10019,"d":-11.192099848651651}]},"gas":{"max_ok":190408,"oog":0,"revert":0,"other_halt":0,"tx_error":0,"bad_return":0},"afterSwap_raw":{"role":"Submission","callback":"afterSwap","calls":904047,"ok":904047,"max_ok_gas":190408,"sum_ok_gas":99296659303,"oog":0,"revert":0,"other_halt":0,"tx_error":0,"bad_return":0},"valid":true},{"stage":"screen","variant":"V8","structure":"V5 treats later interior-routing prints as intervals instead of noisy point observations.","sha256":"7b65d7714832e42b6eb8c6b7c710777d63ffa7cb08079c27382d55c6e14d2987","seeds":{"start":10000,"stop_exclusive":10100},"mean_edge":520.4828198576149,"paired":{"n":100,"mean_diff":-0.1940474521934783,"se":0.04965562408979336,"worst":[{"seed":10031,"d":-1.3727784273804673},{"seed":10078,"d":-1.3467343752563465},{"seed":10062,"d":-1.2700726635248998},{"seed":10089,"d":-1.2369592811937764},{"seed":10097,"d":-1.1858604694538144}]},"gas":{"max_ok":190538,"oog":0,"revert":0,"other_halt":0,"tx_error":0,"bad_return":0},"afterSwap_raw":{"role":"Submission","callback":"afterSwap","calls":1023855,"ok":1023855,"max_ok_gas":190538,"sum_ok_gas":114425432626,"oog":0,"revert":0,"other_halt":0,"tx_error":0,"bad_return":0},"valid":true},{"stage":"screen","variant":"V9","structure":"V5 excludes later retail routing prints; only first-trade mixture and silence observations.","sha256":"3e09f5be245e91673a2931fdc235e7a03ed823ff5ed291f77931cf383d0d49a4","seeds":{"start":10000,"stop_exclusive":10100},"mean_edge":520.4391226890967,"paired":{"n":100,"mean_diff":-0.2377446207116708,"se":0.06619299370312048,"worst":[{"seed":10089,"d":-4.257520083024815},{"seed":10005,"d":-1.3969721225035414},{"seed":10006,"d":-1.324362052753827},{"seed":10066,"d":-1.3000849506204304},{"seed":10078,"d":-1.1359321532975173}]},"gas":{"max_ok":190519,"oog":0,"revert":0,"other_halt":0,"tx_error":0,"bad_return":0},"afterSwap_raw":{"role":"Submission","callback":"afterSwap","calls":1021170,"ok":1021170,"max_ok_gas":190519,"sum_ok_gas":110324405514,"oog":0,"revert":0,"other_halt":0,"tx_error":0,"bad_return":0},"valid":true},{"stage":"screen","variant":"V10","structure":"V5 divides arb/retail odds by an approximate probability mass of the retail no-trade interval.","sha256":"cd9bdb45ab0537ad25c4fd90ca8618898cef6386de3df65f192eaef65fbca245","seeds":{"start":10000,"stop_exclusive":10100},"mean_edge":520.8536666905114,"paired":{"n":100,"mean_diff":0.17679938070298817,"se":0.058066702053186516,"worst":[{"seed":10089,"d":-1.1417418935604928},{"seed":10047,"d":-1.0024262694161052},{"seed":10005,"d":-0.9498850094537374},{"seed":10084,"d":-0.867511674203115},{"seed":10079,"d":-0.8590733227644023}]},"gas":{"max_ok":192838,"oog":0,"revert":0,"other_halt":0,"tx_error":0,"bad_return":0},"afterSwap_raw":{"role":"Submission","callback":"afterSwap","calls":1015219,"ok":1015219,"max_ok_gas":192838,"sum_ok_gas":112511130606,"oog":0,"revert":0,"other_halt":0,"tx_error":0,"bad_return":0},"valid":true},{"stage":"screen","variant":"V11","structure":"V5 rejects later routing updates whose direction disagrees with the current implied endpoint.","sha256":"beb39bf9558b37e3ca2ab2a354c3ce2ee0f6c60fa033399974be67c53f938ed7","seeds":{"start":10000,"stop_exclusive":10100},"mean_edge":520.5323747150735,"paired":{"n":100,"mean_diff":-0.14449259473490655,"se":0.05319655758998669,"worst":[{"seed":10089,"d":-1.5117925674572916},{"seed":10078,"d":-1.4162137533710393},{"seed":10005,"d":-1.3349685935451703},{"seed":10031,"d":-0.9965375368566356},{"seed":10052,"d":-0.928309130632897}]},"gas":{"max_ok":190538,"oog":0,"revert":0,"other_halt":0,"tx_error":0,"bad_return":0},"afterSwap_raw":{"role":"Submission","callback":"afterSwap","calls":1021597,"ok":1021597,"max_ok_gas":190538,"sum_ok_gas":110984185299,"oog":0,"revert":0,"other_halt":0,"tx_error":0,"bad_return":0},"valid":true},{"stage":"shortlist","variant":"V2","structure":"Soft rational interval likelihood on seven Gaussian quadrature nodes.","sha256":"7181143e7f7fb28206343cd2e2ffd72c2c2638c26f51efdc45b704c36fdfecb0","seeds":{"start":12000,"stop_exclusive":12500},"mean_edge":516.9904455793923,"paired":{"n":500,"mean_diff":-0.2712646059675557,"se":0.026701612136902815,"worst":[{"seed":12247,"d":-2.6346077977628397},{"seed":12313,"d":-2.0797587913906455},{"seed":12208,"d":-2.0604996962296696},{"seed":12459,"d":-1.9553368880877429},{"seed":12496,"d":-1.9511347732511126}]},"gas":{"max_ok":191973,"oog":0,"revert":0,"other_halt":0,"tx_error":0,"bad_return":0},"afterSwap_raw":{"role":"Submission","callback":"afterSwap","calls":5115346,"ok":5115346,"max_ok_gas":191973,"sum_ok_gas":543887888696,"oog":0,"revert":0,"other_halt":0,"tx_error":0,"bad_return":0},"valid":true},{"stage":"shortlist","variant":"V5","structure":"Single aggregate censored update for missing timesteps, followed by current-step process noise.","sha256":"ab695ee28ff85b920753797c794298b66eb7ee107d45e5d3fc84e58dd4a7dce5","seeds":{"start":12000,"stop_exclusive":12500},"mean_edge":517.0858701818568,"paired":{"n":500,"mean_diff":-0.1758400035030543,"se":0.027760545025748644,"worst":[{"seed":12247,"d":-2.4344666321730415},{"seed":12088,"d":-2.377076881997141},{"seed":12208,"d":-2.3691504813857023},{"seed":12359,"d":-2.1163729712643544},{"seed":12313,"d":-1.9956142497048859}]},"gas":{"max_ok":192495,"oog":0,"revert":0,"other_halt":0,"tx_error":0,"bad_return":0},"afterSwap_raw":{"role":"Submission","callback":"afterSwap","calls":5120212,"ok":5120212,"max_ok_gas":192495,"sum_ok_gas":559591664274,"oog":0,"revert":0,"other_halt":0,"tx_error":0,"bad_return":0},"valid":true},{"stage":"shortlist","variant":"V10","structure":"V5 divides arb/retail odds by an approximate probability mass of the retail no-trade interval.","sha256":"cd9bdb45ab0537ad25c4fd90ca8618898cef6386de3df65f192eaef65fbca245","seeds":{"start":12000,"stop_exclusive":12500},"mean_edge":517.3792537609072,"paired":{"n":500,"mean_diff":0.1175435755474075,"se":0.026433708870234766,"worst":[{"seed":12247,"d":-1.7786559129686452},{"seed":12459,"d":-1.704513735134185},{"seed":12003,"d":-1.6645249635517985},{"seed":12208,"d":-1.4980718508765563},{"seed":12016,"d":-1.4111727153466518}]},"gas":{"max_ok":194783,"oog":0,"revert":0,"other_halt":0,"tx_error":0,"bad_return":0},"afterSwap_raw":{"role":"Submission","callback":"afterSwap","calls":5081195,"ok":5081195,"max_ok_gas":194783,"sum_ok_gas":562980721491,"oog":0,"revert":0,"other_halt":0,"tx_error":0,"bad_return":0},"valid":true}],"freeze":{"name":"V10","sha256":"cd9bdb45ab0537ad25c4fd90ca8618898cef6386de3df65f192eaef65fbca245","timestamp_utc":"2026-11-08T18:19:06.794644+00:00","selection_rule":"Highest mean paired gain among gas-valid second-block shortlist variants V2, V5, V10. The smoke test was a harness check, not a selection criterion.","shortlist_seeds":{"start":12000,"stop_exclusive":12500},"shortlist_n":500,"shortlist_mean_diff":0.1175435755474075,"shortlist_se":0.026433708870234766,"confirmation_results_seen_at_freeze":false},"protocol":{"repository":"https://github.com/benedictbrady/amm-challenge","commit":"6b6921f8d463314aa7c96234e1be25a25245f704","simulator_wheel":"amm_sim_rs-0.1.0.post1-cp310-abi3-manylinux2014_x86_64.manylinux_2_17_x86_64.whl","wheel_url":"https://github.com/gtmcknight/amm-sim/releases/download/sim-6b6921f8/amm_sim_rs-0.1.0.post1-cp310-abi3-manylinux2014_x86_64.manylinux_2_17_x86_64.whl","wheel_sha256":"aedb68280aca34c110968f00148387c95885207913fb2cf19a1ab4c5cfd6887a","runtime":{"python":"3.12.3","numpy":"2.5.4","py-solc-x":"2.1.0","pyrevm":"0.3.7"},"compiler":{"version":"0.8.24","optimizer":{"enabled":true,"runs":200},"viaIR":true,"evmVersion":"paris","entry":"Strategy.sol:Strategy","service":"amm_competition.evm.compiler.SolidityCompiler"},"configs":{"generator":"numpy.random.default_rng(seed), draw size then rate then sigma, all three uniform","retail_mean_size":[19.0,21.0],"retail_arrival_rate":[0.6,1.0],"gbm_sigma":[0.000882,0.001008],"n_steps":10000,"initial_price":100.0,"initial_x":100.0,"initial_y":10000.0,"gbm_mu":0.0,"gbm_dt":1.0,"retail_size_sigma":1.2,"retail_buy_prob":0.5,"price_seed":"seed","retail_seed":"seed+1"},"match":"Each arm independently calls amm_sim_rs.run_batch(arm, VanillaStrategy, configs, 8); never candidate against STACK.","chunk_size":20,"confirmation_seeds":{"start":5000000,"stop_exclusive":5002000},"confirmation_policy":"One completed run of the frozen hash and one STACK run on the 2000 confirmation seeds; no confirmation results used for selection or tuning and no seed removal. An immediately interrupted launch is disclosed under validation.","paired_formula":"d_i=edge_candidate_i-edge_STACK_i; SE=std(d,ddof=1)/sqrt(n). Worst is the five smallest d values.","gas_policy":"Reset gas_stats before every arm/chunk and snapshot immediately afterward. raw_counters retain all counter fields, summed over disjoint chunks except max_ok_gas, which is maximized. max_ok refers only to Submission/afterSwap. Any error counter invalidates the hash.","storage":"Only inherited uint256[32] slots; compiler storage validation passed. Uses causal TradeInfo, previous fees, timestamp, and stored state."},"commands":{"checkout":"git clone https://github.com/benedictbrady/amm-challenge test/scratch/amm-challenge && git -C test/scratch/amm-challenge checkout 6b6921f8d463314aa7c96234e1be25a25245f704","setup":"From checkout root: sh scratch/setup.sh (once); exact setup source supplied below.","setup_source":"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 SOLCX_BINARY_PATH=$R/solcx VIRTUAL_ENV=$PWD/.venv PATH=$PWD/.venv/bin:$R/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/;}\nW=amm_sim_rs-0.1.0.post1-cp310-abi3-manylinux2014_x86_64.manylinux_2_17_x86_64.whl;curl -LsSf https://github.com/gtmcknight/amm-sim/releases/download/sim-6b6921f8/$W -o $R/$W\necho \"aedb68280aca34c110968f00148387c95885207913fb2cf19a1ab4c5cfd6887a  $R/$W\"|sha256sum -c -\nuv venv --python 3.12 .venv;uv pip install $R/$W numpy py-solc-x==2.1.0 pyrevm==0.3.7;uv pip install --no-deps -e .\npython -c \"import solcx;solcx.install_solc('0.8.24')\"\namm-match validate contracts/src/StarterStrategy.sol\n","calibration":". scratch/env.sh && python scratch/calibrate.py","screen":[". scratch/env.sh && python scratch/search.py 10000 100 STACK V0 V1 V2",". scratch/env.sh && python scratch/search.py 10000 100 V2 V3 V4",". scratch/env.sh && python scratch/search.py 10000 100 V3 V4",". scratch/env.sh && python scratch/search.py 10000 100 V5 V6 V7",". scratch/env.sh && python scratch/search.py 10000 100 V8 V9 V10 V11"],"shortlist":". scratch/env.sh && python scratch/search.py 12000 500 STACK V2 V5 V10","harness_smoke":". scratch/env.sh && python scratch/harness.py --start 13000 --n 20 --out scratch/harness-smoke.json scratch/V10.sol scratch/STACK.sol","confirmation":". scratch/env.sh && python scratch/harness.py --start 5000000 --n 2000 --out scratch/confirmation.json scratch/V10.sol scratch/STACK.sol","reproduce":"Extract harness_source as scratch/harness.py, code as scratch/V10.sol, and the verified baseline artifact code as scratch/STACK.sol. Run in the pinned checkout with its base contracts and the listed runtime dependencies. Calibration uses the same configs and compile service with the CH source; mean the submission edge over seeds 0..999."},"arm_means":{"candidate":{"edge":525.0387909803765,"retail":552.1684884517712,"arb":-27.12969747139475},"stack":{"edge":524.9015588914802,"retail":553.3042932508379,"arb":-28.402734359357588}},"paired":{"n":2000,"mean_diff":0.1372320888962471,"se":0.01363197915215346,"worst":[{"seed":5000729,"d":-2.8918776608781513},{"seed":5000740,"d":-2.4534075259305723},{"seed":5000416,"d":-2.1026969270328095},{"seed":5001708,"d":-1.9466184932592796},{"seed":5000994,"d":-1.889225194354026}]},"retail_edge_delta":{"mean":-1.135804799066593,"se":0.013995494300275123},"arb_edge_delta":{"mean":1.2730368879628409,"se":0.006935307161576756},"gas":{"candidate":{"max_ok":194870,"oog":0,"revert":0,"other_halt":0,"tx_error":0,"bad_return":0,"raw_counters":[{"role":"Baseline","callback":"afterInitialize","calls":2000,"ok":2000,"max_ok_gas":21796,"sum_ok_gas":43592000,"oog":0,"revert":0,"other_halt":0,"tx_error":0,"bad_return":0},{"role":"Baseline","callback":"afterSwap","calls":21435829,"ok":21435829,"max_ok_gas":22592,"sum_ok_gas":483656194160,"oog":0,"revert":0,"other_halt":0,"tx_error":0,"bad_return":0},{"role":"Baseline","callback":"getName","calls":2000,"ok":2000,"max_ok_gas":21526,"sum_ok_gas":43052000,"oog":0,"revert":0,"other_halt":0,"tx_error":0,"bad_return":0},{"role":"Submission","callback":"afterInitialize","calls":2000,"ok":2000,"max_ok_gas":220981,"sum_ok_gas":441962000,"oog":0,"revert":0,"other_halt":0,"tx_error":0,"bad_return":0},{"role":"Submission","callback":"afterSwap","calls":20446829,"ok":20446829,"max_ok_gas":194870,"sum_ok_gas":2263400126484,"oog":0,"revert":0,"other_halt":0,"tx_error":0,"bad_return":0},{"role":"Submission","callback":"getName","calls":2000,"ok":2000,"max_ok_gas":21594,"sum_ok_gas":43188000,"oog":0,"revert":0,"other_halt":0,"tx_error":0,"bad_return":0}]},"STACK":{"max_ok":213581,"oog":0,"revert":0,"other_halt":0,"tx_error":0,"bad_return":0,"raw_counters":[{"role":"Baseline","callback":"afterInitialize","calls":2000,"ok":2000,"max_ok_gas":21796,"sum_ok_gas":43592000,"oog":0,"revert":0,"other_halt":0,"tx_error":0,"bad_return":0},{"role":"Baseline","callback":"afterSwap","calls":21479648,"ok":21479648,"max_ok_gas":22592,"sum_ok_gas":484644302500,"oog":0,"revert":0,"other_halt":0,"tx_error":0,"bad_return":0},{"role":"Baseline","callback":"getName","calls":2000,"ok":2000,"max_ok_gas":21526,"sum_ok_gas":43052000,"oog":0,"revert":0,"other_halt":0,"tx_error":0,"bad_return":0},{"role":"Submission","callback":"afterInitialize","calls":2000,"ok":2000,"max_ok_gas":220962,"sum_ok_gas":441924000,"oog":0,"revert":0,"other_halt":0,"tx_error":0,"bad_return":0},{"role":"Submission","callback":"afterSwap","calls":20690513,"ok":20690513,"max_ok_gas":213581,"sum_ok_gas":2036247910698,"oog":0,"revert":0,"other_halt":0,"tx_error":0,"bad_return":0},{"role":"Submission","callback":"getName","calls":2000,"ok":2000,"max_ok_gas":21576,"sum_ok_gas":43152000,"oog":0,"revert":0,"other_halt":0,"tx_error":0,"bad_return":0}]}},"gas_scope":"Top-level gas counters are for confirmation. Tuning counters and maxima are in the tuning log. Validity also checks every saved tuning run of the selected hash and STACK for any halt/error.","edge_decomposition":{"method":"Reconstruct negative optimal arb profit from step fair prices, preceding final spot and fees, constant k=initial_x*initial_y, and the pinned closed-form arb/quote formulas. Initial fee is 0.0004. Retail edge is reported total edge minus reconstructed arb edge. These are numerical reconstructions, not simulator-provided trade-type counters.","check":"32 diagnostic seeds 11000..11031, 100 steps, arrival input 0 (simulator floors it to 0.01); the 10 paths with observed zero submission retail volume independently match reconstructed arb and total edge.","check_n":10,"max_abs_arb_check_error":5.179509598995935e-11,"reconciliation_max_abs":2.2737367544323206e-13,"mean_reconciliation_abs":8.881784197001252e-16,"se_note":"Retail and arb SEs are computed on their own paired deltas; covariance means their SEs do not add."},"validation":{"harness_smoke":{"paired":{"n":20,"mean_diff":0.47913799465114837,"se":0.16437950174434668,"worst":[{"seed":13012,"d":-0.46240337567292045},{"seed":13018,"d":-0.3569013068240565},{"seed":13006,"d":-0.3527011157473794},{"seed":13014,"d":-0.34338187557750643},{"seed":13016,"d":-0.22541198088117653}]},"retail_edge_delta":{"mean":-0.8628548213899847,"se":0.16924644883573736},"arb_edge_delta":{"mean":1.3419928160411279,"se":0.09501235620742116},"reconciliation_max_abs":6.750155989720952e-14,"valid":true},"compile_repairs":"Initial soft-quadrature V2 and sequential V3 failed viaIR Yul stack-depth compilation. Memory accumulators and a memory input struct fixed compilation before those hashes were measured. No metrics are assigned to failed sources.","launch_interruption":"The first freeze helper failed with ModuleNotFoundError for harness. Because that shell was not fail-fast, the following harness compilation launched and was immediately interrupted with exit 130. No confirmation results or gas counters were returned or inspected from it. The helper import path was corrected, fail-fast execution enabled, the hash frozen from tuning only, and the complete measurement launched. This interruption is disclosed rather than counted as a completed confirmation.","source_passages":"All passages in sources.json were fetched and checked as exact substrings."},"valid":true,"reasons":[],"interpretation":{"selected_variant":"V10","goal_gain_required_approximately":5.0,"meets_required_local_gain":false,"board_claim":null,"fallback_sha256":"2eaafc7960e520b8a7fd322ec8afaff8fa677c730228a961efb509cc30b25719","scope":"The posterior replaces STACK fastHat and its uncertainty propagation. Slow pHat and the fee family remain as a fallback blend. Full replacement of the stale-price or toxicity-price signals was also screened and lost; those losses are retained in the tuning log.","limitations":["The Gaussian/quadrature posterior and retail/arb likelihoods are approximations, not an exact model of routed order flow.","The interval-mass correction is an approximate rational likelihood.","Offline rerunning the harness requires the pinned simulator, compiler and Python packages; their binaries are not embedded in this JSON.","No leaderboard submission or leaderboard improvement is claimed."]}}