{"item": "a", "batch": "e09-confirm-sigma", "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 _anchorSigma(uint256 current, uint256 packed) internal pure returns (uint256) {\n        uint256 mean = uint80(packed >> 80);\n        if (uint32(packed >> 160) == 0) mean = current;\n        return wmul(1047182309813441000, _blend(current, mean, 682794863439784300));\n    }\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[15] = 400000000000000000 | (uint256(2000000000000000) << 160); 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 packedSigma = slots[6]; uint256 sigmaHat = uint80(packedSigma); 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(_anchorSigma(sigmaHat, packedSigma), 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                if (682794863439784300 > 0) {\n                    uint256 count = uint32(packedSigma >> 160);\n                    uint256 mean = uint80(packedSigma >> 80);\n                    if (count < 5377) count++;\n                    if (sigmaHat >= mean) mean += (sigmaHat - mean) / count;\n                    else mean -= (mean - sigmaHat) / count;\n                    packedSigma = (mean << 80) | (count << 160);\n                }\n\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        uint256 arbProbability;\n        (fastHat, uncertainty, arbProbability) = _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 originalLambda = lambdaHat; uint256 originalSize = sizeHat;\n\n        if (342406799193418304 > 0) {\n            uint256 packedFlow = slots[15];\n            uint256 rate = uint80(packedFlow);\n            uint256 count = uint80(packedFlow >> 80);\n            uint256 meanSize = uint80(packedFlow >> 160);\n            if (rate == 0) rate = 400000000000000000;\n            if (meanSize == 0) meanSize = 2000000000000000;\n            if (isNewStep) {\n                uint256 inst = count / silent;\n                if (inst > 3 * WAD) inst = 3 * WAD;\n                uint256 retention = _powWad(999000000000000000, silent > 64 ? 64 : silent);\n                rate = wmul(rate, retention) + wmul(inst, WAD-retention);\n                count = 0;\n            }\n            uint256 weight = firstInStep ? WAD-arbProbability : WAD;\n            uint256 correctedWeight = weight;\n            if (2 == 2) {\n                uint256 missing = wmul(feeUsed, 196030880396139429888);\n                if (missing > 333333333333333376) missing = 333333333333333376;\n                correctedWeight = wdiv(weight, WAD-missing);\n            }\n            count += correctedWeight;\n            uint256 learning = wmul(WAD-999000000000000000, weight);\n            meanSize = _blend(meanSize, tradeRatio, learning);\n            slots[15]=rate | (count << 80) | (meanSize << 160);\n            uint256 retailRate = wmul(rate, 366383424913407168);\n            uint256 retailSize = 2 == 0 ? sizeHat : wmul(meanSize,1883296158119298304);\n            lambdaHat = _blend(lambdaHat,retailRate,342406799193418304);\n            sizeHat = _blend(sizeHat,retailSize,342406799193418304);\n        }\n        uint256 flowSize = wmul(lambdaHat, sizeHat);\n        uint256 fBase = BASE_FEE + wmul(SIGMA_COEF, _anchorSigma(sigmaHat, packedSigma)) + 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(_anchorSigma(sigmaHat, packedSigma), toxSignal));\n\n        lambdaHat = originalLambda; sizeHat = originalSize;\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 | (682794863439784300 > 0 ? (packedSigma & ~uint256(type(uint80).max)) : 0); 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, 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),0);\n            }\n            return (x.mu,x.v,0);\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,prob);\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": "014ad7bd0e6f412183ab5c0ee1560bbe30182b35b10f18d62464f1df0909cfca", "candidate_source": "https://api.imd.fun/artifacts/9045cab1f8a51e8f1c6a4c2c93daa2b2f0d9bd274a68de064a1167c079c2a8b4 (code field, unchanged; sha256 verified)", "blocked": null, "valid": true, "seeds": {"first": 5108000, "last": 5109999, "n": 2000, "inclusive": true, "fresh": true}, "paired": {"n": 2000, "mean_diff": 0.11662226702047888, "se": 0.013117332446878726, "worst": [{"seed": 5109332, "d": -2.6856440825440586}, {"seed": 5108568, "d": -2.661641695907065}, {"seed": 5108913, "d": -2.3424897041254553}, {"seed": 5108450, "d": -2.153432114838097}, {"seed": 5109345, "d": -2.0561965453387074}], "sum_d": 233.24453404095777, "sum_d2": 715.1150195966975, "wins": 1188, "losses": 812}, "paired_baseline": "RS2 (sha256 f24b6ca198b744c380842c3a17964a6dc21f311bb04984b26733afa3fee8eaf2)", "retail_edge_delta": {"mean": 0.30036186787977737, "se": 0.013289431704195252}, "arb_edge_delta": {"mean": -0.18373960085929997, "se": 0.006461674121726015}, "reconciliation_max_abs": 1.1368683772161603e-13, "vs_stack": {"paired": {"n": 2000, "mean_diff": 0.44048915765324387, "se": 0.017439825218330703, "worst": [{"seed": 5109332, "d": -3.031482161737813}, {"seed": 5108977, "d": -2.9793921490979756}, {"seed": 5109643, "d": -2.8042535168754057}, {"seed": 5109519, "d": -2.5976517446354137}, {"seed": 5108913, "d": -2.2176452077389968}], "sum_d": 880.9783153064877, "sum_d2": 1604.043115596531, "wins": 1469, "losses": 531}, "retail_edge_delta": {"mean": 0.6701509573886844, "se": 0.017253611485236985}, "arb_edge_delta": {"mean": -0.22966179973544057, "se": 0.008073321931545049}, "reconciliation_max_abs": 1.1368683772161603e-13}, "rs2_vs_stack": {"paired": {"n": 2000, "mean_diff": 0.3238668906327649, "se": 0.014177849312151347, "worst": [{"seed": 5109232, "d": -2.186210153949901}, {"seed": 5108977, "d": -1.7265584312476676}, {"seed": 5109643, "d": -1.6943656697210372}, {"seed": 5109192, "d": -1.672595317229593}, {"seed": 5108868, "d": -1.508307754672046}], "sum_d": 647.7337812655298, "sum_d2": 1013.4231473463167, "wins": 1419, "losses": 581}, "retail_edge_delta": {"mean": 0.36978908950890693, "se": 0.014352019767386752}, "arb_edge_delta": {"mean": -0.045922198876140644, "se": 0.006000381182368854}, "reconciliation_max_abs": 1.1368683772161603e-13}, "gas": {"max_ok": 203135, "init_max_ok": 243121, "oog": 0, "other_halts": 0, "note": "max_ok = Submission afterSwap max successful gas; init_max_ok = Submission afterInitialize. oog/other_halts count Submission role; all-role (incl. Vanilla baseline) halts were also 0 in every arm."}, "arms": {"CAND": {"sha256": "014ad7bd0e6f412183ab5c0ee1560bbe30182b35b10f18d62464f1df0909cfca", "mean_edge": 523.1993078535264, "mean_retail_edge": 549.9426268338444, "mean_arb_edge": -26.74331898031803, "gas": {"max_ok": 203135, "init_max_ok": 243121, "oog": 0, "other_halts": 0, "all_roles_halts": 0}, "chunks": 100, "chunk_size": 20, "raw_counters_aggregated": [{"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": 21502473, "ok": 21502473, "max_ok_gas": 22592, "sum_ok_gas": 485159027904, "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": 243121, "sum_ok_gas": 486242000, "oog": 0, "revert": 0, "other_halt": 0, "tx_error": 0, "bad_return": 0}, {"role": "Submission", "callback": "afterSwap", "calls": 20486476, "ok": 20486476, "max_ok_gas": 203135, "sum_ok_gas": 2450844512618, "oog": 0, "revert": 0, "other_halt": 0, "tx_error": 0, "bad_return": 0}, {"role": "Submission", "callback": "getName", "calls": 2000, "ok": 2000, "max_ok_gas": 21629, "sum_ok_gas": 43258000, "oog": 0, "revert": 0, "other_halt": 0, "tx_error": 0, "bad_return": 0}]}, "RS2": {"sha256": "f24b6ca198b744c380842c3a17964a6dc21f311bb04984b26733afa3fee8eaf2", "mean_edge": 523.0826855865059, "mean_retail_edge": 549.6422649659646, "mean_arb_edge": -26.55957937945873, "gas": {"max_ok": 201460, "init_max_ok": 243099, "oog": 0, "other_halts": 0, "all_roles_halts": 0}, "chunks": 100, "chunk_size": 20, "raw_counters_aggregated": [{"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": 21351913, "ok": 21351913, "max_ok_gas": 22592, "sum_ok_gas": 481762113320, "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": 243099, "sum_ok_gas": 486198000, "oog": 0, "revert": 0, "other_halt": 0, "tx_error": 0, "bad_return": 0}, {"role": "Submission", "callback": "afterSwap", "calls": 20695992, "ok": 20695992, "max_ok_gas": 201460, "sum_ok_gas": 2438017315709, "oog": 0, "revert": 0, "other_halt": 0, "tx_error": 0, "bad_return": 0}, {"role": "Submission", "callback": "getName", "calls": 2000, "ok": 2000, "max_ok_gas": 21607, "sum_ok_gas": 43214000, "oog": 0, "revert": 0, "other_halt": 0, "tx_error": 0, "bad_return": 0}]}, "STACK": {"sha256": "2eaafc7960e520b8a7fd322ec8afaff8fa677c730228a961efb509cc30b25719", "mean_edge": 522.7588186958732, "mean_retail_edge": 549.2724758764557, "mean_arb_edge": -26.513657180582587, "gas": {"max_ok": 211588, "init_max_ok": 220962, "oog": 0, "other_halts": 0, "all_roles_halts": 0}, "chunks": 100, "chunk_size": 20, "raw_counters_aggregated": [{"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": 21452443, "ok": 21452443, "max_ok_gas": 22592, "sum_ok_gas": 484030640564, "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": 20667095, "ok": 20667095, "max_ok_gas": 211588, "sum_ok_gas": 2034183086302, "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}]}}, "calibration": {"strategy": "CH", "source": "https://raw.githubusercontent.com/ChengHua926/amm-challenge/d34a5199c59a4c44d5336a25f1436b4ae1f21104/contracts/src/Strategy.sol", "seeds": [0, 999], "n": 1000, "mean_edge": 525.5258821780835, "expected": 525.5258821780834, "abs_error": 1.1368683772161603e-13, "tolerance": 1e-06, "pass": true}, "hash_checks": {"artifact_json_sha256_matches_id": {"R": true, "H": true, "K": true, "candidate": true}, "code_sha256": {"RS2": true, "STACK": true, "candidate": true}}, "protocol": {"repo": "https://github.com/benedictbrady/amm-challenge", "commit": "6b6921f8d463314aa7c96234e1be25a25245f704", "simulator_wheel_sha256": "aedb68280aca34c110968f00148387c95885207913fb2cf19a1ab4c5cfd6887a", "harness": "H.harness_source from artifact 26cb8e86f05170308de2a4b24821ac7fad2a17077f8d94af6e0f31985343fe89, used verbatim as scratch/harness.py (configs: default_rng(seed) size,rate,sigma; 10000 steps; price seed=s, retail s+1 inside sim). Each arm alone vs VanillaStrategy via amm_sim_rs.run_batch(bytecode, Vanilla, configs, 8), chunks of 20, gas_stats_reset()/gas_stats() per chunk.", "commands": ["sh scratch/setup.sh", ". scratch/env.sh && python scratch/drive.py cal", ". scratch/env.sh && python scratch/drive.py arm {CAND|RS2|STACK} {5108000|5108400|5108800|5109200|5109600} 400", ". scratch/env.sh && python scratch/analyze.py"], "drive_source": "import sys,json,time,hashlib\nfrom pathlib import Path\nimport numpy as np\nsys.path.insert(0,'scratch')\nimport harness as h\nimport amm_sim_rs as sim\nfrom amm_competition.evm.compiler import SolidityCompiler\nmode=sys.argv[1]\ncomp=SolidityCompiler()\nvan=comp.compile(Path('contracts/src/VanillaStrategy.sol').read_text(),'VanillaStrategy'); assert van.success\nif mode=='cal':\n    t=time.time(); r=h.run(Path('scratch/CH.sol').read_text(),0,1000,van.bytecode,comp)\n    m=float(np.mean([x['edge'] for x in r['rows']]))\n    json.dump({'mean':m,'expected':525.5258821780834,'abs_err':abs(m-525.5258821780834),'sha256':r['sha256'],'raw_counters':r['raw_counters'],'secs':time.time()-t},open('scratch/cal.json','w'))\n    print(m, abs(m-525.5258821780834), r['raw_counters'], time.time()-t)\nelse:\n    arm=sys.argv[2]; start=int(sys.argv[3]); n=int(sys.argv[4])\n    t=time.time(); r=h.run(Path(f'scratch/{arm}.sol').read_text(),start,n,van.bytecode,comp)\n    r['secs']=time.time()-t\n    json.dump(r,open(f'scratch/arm_{arm}_{start}.json','w'))\n    print(arm,r['sha256'],r['raw_counters'],r['secs'])\n", "analyze_source": "import sys,json\nsys.path.insert(0,'scratch')\nimport numpy as np, harness as h\nS=[5108000,5108400,5108800,5109200,5109600]\ndef load(arm):\n    rows=[];chunks=[];shas=set();secs=0\n    for s in S:\n        d=json.load(open(f'scratch/arm_{arm}_{s}.json'))\n        rows+=d['rows'];chunks+=d['chunks'];shas.add(d['sha256']);secs+=d['secs']\n    assert len(shas)==1\n    return {'sha256':shas.pop(),'rows':rows,'raw_counters':h.aggregate(chunks),'n_chunks':len(chunks),'secs':secs}\nA={k:load(k) for k in ['CAND','RS2','STACK']}\nfor k,a in A.items():\n    seeds=sorted(r['seed'] for r in a['rows']); assert seeds==list(range(5108000,5110000)),k\ndef gas(a):\n    g={'max_ok':0,'init_max_ok':0,'oog':0,'other_halts':0}\n    for r in a['raw_counters']:\n        if r['role']!='Submission':\n            continue\n        if r['callback']=='afterSwap': g['max_ok']=r['max_ok_gas']\n        if r['callback']=='afterInitialize': g['init_max_ok']=r['max_ok_gas']\n        g['oog']+=r['oog']; g['other_halts']+=r['revert']+r['other_halt']+r['tx_error']+r['bad_return']\n    g['all_roles_halts']=sum(r[e] for r in a['raw_counters'] for e in ['oog','revert','other_halt','tx_error','bad_return'])\n    return g\ndef cmp(x,y):\n    c=h.compare(x,y)\n    a={r['seed']:r for r in x['rows']};b={r['seed']:r for r in y['rows']}\n    d=np.array([a[s]['edge']-b[s]['edge'] for s in sorted(a)])\n    c['paired']['sum_d']=float(d.sum());c['paired']['sum_d2']=float((d*d).sum())\n    c['paired']['wins']=int((d>0).sum());c['paired']['losses']=int((d<0).sum())\n    return c\nvr=cmp(A['CAND'],A['RS2']); vs=cmp(A['CAND'],A['STACK']); rs=cmp(A['RS2'],A['STACK'])\nG={k:gas(a) for k,a in A.items()}\nvalid=all(g['all_roles_halts']==0 for g in G.values())\nout={'vr':vr,'vs':vs,'rs2_vs_stack':rs,'gas':G,'valid':valid,\n 'arm_mean_edge':{k:float(np.mean([r['edge'] for r in a['rows']])) for k,a in A.items()},\n 'arm_mean_retail':{k:float(np.mean([r['retail'] for r in a['rows']])) for k,a in A.items()},\n 'arm_mean_arb':{k:float(np.mean([r['arb'] for r in a['rows']])) for k,a in A.items()},\n 'sha':{k:a['sha256'] for k,a in A.items()},'counters':{k:a['raw_counters'] for k,a in A.items()},\n 'chunks':{k:a['n_chunks'] for k,a in A.items()},'secs':{k:a['secs'] for k,a in A.items()}}\njson.dump(out,open('scratch/analysis.json','w'))\nprint(json.dumps({k:out[k] for k in ['vr','vs','rs2_vs_stack','gas','valid','arm_mean_edge','sha','chunks']},indent=0)[:5000])\n"}, "notes": ["Candidate frozen and hash-verified before any fresh seed was run; no tuning, retries or seed selection on 5108000..5109999.", "A first attempt to run the full 2000-seed candidate arm in one process was killed by a 10-minute tool timeout before writing any output (no results seen); the arm was then run as five consecutive 400-seed segments covering the same seeds. All 2000 seeds per arm included, none dropped.", "paired = candidate minus RS2; vs_stack = candidate minus STACK; rs2_vs_stack = RS2 minus STACK; d = arb + retail reconciles to 1.1e-13.", "SE = sample SD (ddof=1)/sqrt(n). sum_d and sum_d2 given for pooling.", "Local paired gain only; no board claim."]}