{"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[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 sigmaHat = slots[6]; uint256 lambdaHat = slots[7]; uint256 sizeHat = slots[8];\n        uint256 toxEma = slots[9]; uint256 stepTradeCount = uint8(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        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        // Run-level means, observed after RS2's flow correction on each callback.\n        // Packed in unused bits of slots[10]; zero means no observations yet.\n        uint256 anchor = slots[10] >> 8;\n        uint256 runAct = uint96(anchor);\n        uint256 runFlow = uint96(anchor >> 96);\n        uint256 runN = anchor >> 192;\n        if (runN < 4646) ++runN;\n        if (actEma >= runAct) runAct += (actEma-runAct)/runN;\n        else runAct -= (runAct-actEma)/runN;\n        if (flowSize >= runFlow) runFlow += (flowSize-runFlow)/runN;\n        else runFlow -= (runFlow-flowSize)/runN;\n        uint256 feeAct = _anchorValue(runAct,actEma,1332392442189290496);\n        flowSize = _anchorValue(runFlow,flowSize,216073432653406016);\n        anchor = runAct | (runFlow << 96) | (runN << 192);\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, feeAct);\n        fMid = fMid + wmul(SIGMA_TOX_COEF, wmul(sigmaHat, 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; slots[7] = lambdaHat; slots[8] = sizeHat;\n        slots[9] = toxEma; slots[10] = stepTradeCount | (anchor << 8);\n\n        return (bidFee, askFee);\n    }\n\n\n    function _anchorValue(uint256 mean,uint256 value,uint256 k) internal pure returns(uint256) {\n        if (value>=mean) return mean+wmul(value-mean,k);\n        uint256 delta=wmul(mean-value,k);\n        return mean>delta ? mean-delta : 0;\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":"0c3836cd5bb7c39acec190a40c574bc02b4a2a302bb1a1fc6696178cecce2484","params":{"act_k":1.3323924421892905,"flow_k":0.216073432653406,"N":4646},"params_exact":{"act_k_wad":"1332392442189290496","flow_k_wad":"216073432653406016","N":4646},"log":[{"params":[0.7400899738706427,0.33202619900758157,737],"start":920000,"n":64,"mean_diff":-0.24597069214292233,"se":0.0879445734329779,"fitness":-0.24597069214292233,"valid":true},{"params":[0.4627795404285503,0.9503306765946331,717],"start":920064,"n":64,"mean_diff":-0.3898189155822447,"se":0.07331131144195192,"fitness":-0.3898189155822447,"valid":true},{"params":[0.824366004570549,1.3535814629101912,2767],"start":920128,"n":64,"mean_diff":-0.0012681202564603922,"se":0.02602258158181805,"fitness":-0.0012681202564603922,"valid":true},{"params":[0.4962748000963281,0.5287447165494223,1443],"start":920192,"n":64,"mean_diff":-0.672801941462926,"se":0.07003564148091719,"fitness":-0.672801941462926,"valid":true},{"params":[0.06596805254522875,0.34826504787260415,1488],"start":920256,"n":64,"mean_diff":-1.8885285941401682,"se":0.13295260736600722,"fitness":-1.8885285941401682,"valid":true},{"params":[0.6064903113490799,1.3273089889791994,607],"start":920320,"n":64,"mean_diff":-0.14452743752818442,"se":0.05438009202741244,"fitness":-0.14452743752818442,"valid":true},{"params":[0.2620193716095107,1.3342117130780633,1376],"start":920384,"n":64,"mean_diff":-0.5561339655447117,"se":0.08531765301051808,"fitness":-0.5561339655447117,"valid":true},{"params":[1.2218123386065345,1.103742693094013,8688],"start":920448,"n":64,"mean_diff":-0.010144215878345797,"se":0.06115653844385419,"fitness":-0.010144215878345797,"valid":true},{"params":[0.97173902329454,1.18488860698488,3031],"start":920512,"n":64,"mean_diff":-0.027122913444245,"se":0.01582152902730985,"fitness":-0.027122913444245,"valid":true},{"params":[0.9635502789742305,0.8426723062072192,1080],"start":920576,"n":64,"mean_diff":0.04613824863321003,"se":0.028863205467862495,"fitness":0.04613824863321003,"valid":true},{"params":[0.5425646771567572,1.1251819606118911,5415],"start":920640,"n":64,"mean_diff":-0.2791467355242876,"se":0.055450933436775006,"fitness":-0.2791467355242876,"valid":true},{"params":[0.6500952834492167,0.5524931786307721,486],"start":920704,"n":64,"mean_diff":-0.35143603618163244,"se":0.07775859659334186,"fitness":-0.35143603618163244,"valid":true},{"params":[0.18151814206866124,0.7778804259404041,1316],"start":920768,"n":64,"mean_diff":-1.2582575067658386,"se":0.09920707291314314,"fitness":-1.2582575067658386,"valid":true},{"params":[1.2076958241319022,1.4863935430057782,863],"start":920832,"n":64,"mean_diff":-0.190604021079821,"se":0.0748571822590771,"fitness":-0.190604021079821,"valid":true},{"params":[0.726216953940247,1.0829050977129318,260],"start":920896,"n":64,"mean_diff":-0.11563527843825927,"se":0.05605535270345995,"fitness":-0.11563527843825927,"valid":true},{"params":[1.0767513338035142,1.2089217012997395,6483],"start":920960,"n":64,"mean_diff":-0.07246890290928132,"se":0.042148544092494244,"fitness":-0.07246890290928132,"valid":true},{"params":[0.47425603379946357,0.9185457346108434,1554],"start":921024,"n":64,"mean_diff":-0.5099426103186211,"se":0.08382779950243296,"fitness":-0.5099426103186211,"valid":true},{"params":[0.9637552002542531,0.3856849304395299,4637],"start":921088,"n":64,"mean_diff":-0.09086171096093754,"se":0.0429558562076138,"fitness":-0.09086171096093754,"valid":true},{"params":[0.6334502613677071,1.3630050421010704,7133],"start":921152,"n":64,"mean_diff":-0.04719797652259672,"se":0.09067416570464584,"fitness":-0.04719797652259672,"valid":true},{"params":[1.3353419977527659,0.960490148346279,7319],"start":921216,"n":64,"mean_diff":-0.09778017521264726,"se":0.05498844351119282,"fitness":-0.09778017521264726,"valid":true},{"params":[0.9517506683244851,1.2946378023538043,3783],"start":921280,"n":64,"mean_diff":-0.041588690568424624,"se":0.025837963030832255,"fitness":-0.041588690568424624,"valid":true},{"params":[1.2592823735501313,0.46767504677057864,9979],"start":921344,"n":64,"mean_diff":0.12045400240549498,"se":0.03427012152164992,"fitness":0.12045400240549498,"valid":true},{"params":[1.117729161432312,0.7034444324465684,6128],"start":921408,"n":64,"mean_diff":0.06379777868508629,"se":0.02679069057324397,"fitness":0.06379777868508629,"valid":true},{"params":[0.7662927256090115,1.0419903752520627,8901],"start":921472,"n":64,"mean_diff":-0.013927313967794674,"se":0.048305857572660066,"fitness":-0.013927313967794674,"valid":true},{"params":[1.425035541879234,1.047087897448411,9997],"start":921536,"n":64,"mean_diff":-0.0038298217056249584,"se":0.057375868713737045,"fitness":-0.0038298217056249584,"valid":true},{"params":[0.9806053765990631,0.5459908994773747,9944],"start":921600,"n":64,"mean_diff":-0.01732846046164127,"se":0.04598840661605083,"fitness":-0.01732846046164127,"valid":true},{"params":[1.3323924421892905,0.216073432653406,4646],"start":921664,"n":64,"mean_diff":0.11517840738539142,"se":0.03537479881821435,"fitness":0.11517840738539142,"valid":true},{"params":[1.0915805371224214,0.11207853270002183,4613],"start":921728,"n":64,"mean_diff":-0.03409315116150857,"se":0.04347379673238703,"fitness":-0.03409315116150857,"valid":true}],"recheck":{"start":923000,"n":256,"candidates":[{"params":[1.2592823735501313,0.46767504677057864,9979],"search_start":921344,"valid":true,"paired":{"n":256,"mean_diff":0.054519722272040605,"se":0.019448540235420163,"worst":[{"seed":923145,"d":-1.6812731241590768},{"seed":923016,"d":-1.0011112522818166},{"seed":923107,"d":-0.8101035163967936},{"seed":923131,"d":-0.7387142044112807},{"seed":923071,"d":-0.631277064656615}]},"retail_edge_delta":{"mean":-0.45858824725234526,"se":0.020615578193112872},"arb_edge_delta":{"mean":0.5131079695243839,"se":0.0077233326715187775},"reconciliation_max_abs":1.0658141036401503e-13,"gas":[{"role":"Baseline","callback":"afterInitialize","calls":256,"ok":256,"max_ok_gas":21796,"sum_ok_gas":5579776,"oog":0,"revert":0,"other_halt":0,"tx_error":0,"bad_return":0},{"role":"Baseline","callback":"afterSwap","calls":2741818,"ok":2741818,"max_ok_gas":22592,"sum_ok_gas":61863519200,"oog":0,"revert":0,"other_halt":0,"tx_error":0,"bad_return":0},{"role":"Baseline","callback":"getName","calls":256,"ok":256,"max_ok_gas":21526,"sum_ok_gas":5510656,"oog":0,"revert":0,"other_halt":0,"tx_error":0,"bad_return":0},{"role":"Submission","callback":"afterInitialize","calls":256,"ok":256,"max_ok_gas":243118,"sum_ok_gas":62238208,"oog":0,"revert":0,"other_halt":0,"tx_error":0,"bad_return":0},{"role":"Submission","callback":"afterSwap","calls":2628245,"ok":2628245,"max_ok_gas":199538,"sum_ok_gas":316273114741,"oog":0,"revert":0,"other_halt":0,"tx_error":0,"bad_return":0},{"role":"Submission","callback":"getName","calls":256,"ok":256,"max_ok_gas":21626,"sum_ok_gas":5536256,"oog":0,"revert":0,"other_halt":0,"tx_error":0,"bad_return":0}]},{"params":[1.3323924421892905,0.216073432653406,4646],"search_start":921664,"valid":true,"paired":{"n":256,"mean_diff":0.0669062810166785,"se":0.02124980976697438,"worst":[{"seed":923145,"d":-1.5327443730624282},{"seed":923131,"d":-0.8967502628313468},{"seed":923227,"d":-0.8743791261182423},{"seed":923157,"d":-0.7458600132675883},{"seed":923075,"d":-0.7312717124482333}]},"retail_edge_delta":{"mean":-0.5414369104595864,"se":0.021995666960115522},"arb_edge_delta":{"mean":0.6083431914762633,"se":0.009066354941312573},"reconciliation_max_abs":1.1013412404281553e-13,"gas":[{"role":"Baseline","callback":"afterInitialize","calls":256,"ok":256,"max_ok_gas":21796,"sum_ok_gas":5579776,"oog":0,"revert":0,"other_halt":0,"tx_error":0,"bad_return":0},{"role":"Baseline","callback":"afterSwap","calls":2746626,"ok":2746626,"max_ok_gas":22592,"sum_ok_gas":61972003020,"oog":0,"revert":0,"other_halt":0,"tx_error":0,"bad_return":0},{"role":"Baseline","callback":"getName","calls":256,"ok":256,"max_ok_gas":21526,"sum_ok_gas":5510656,"oog":0,"revert":0,"other_halt":0,"tx_error":0,"bad_return":0},{"role":"Submission","callback":"afterInitialize","calls":256,"ok":256,"max_ok_gas":243118,"sum_ok_gas":62238208,"oog":0,"revert":0,"other_halt":0,"tx_error":0,"bad_return":0},{"role":"Submission","callback":"afterSwap","calls":2621038,"ok":2621038,"max_ok_gas":199538,"sum_ok_gas":315469257097,"oog":0,"revert":0,"other_halt":0,"tx_error":0,"bad_return":0},{"role":"Submission","callback":"getName","calls":256,"ok":256,"max_ok_gas":21626,"sum_ok_gas":5536256,"oog":0,"revert":0,"other_halt":0,"tx_error":0,"bad_return":0}]},{"params":[1.117729161432312,0.7034444324465684,6128],"search_start":921408,"valid":true,"paired":{"n":256,"mean_diff":0.050633574016155425,"se":0.011343636863044366,"worst":[{"seed":923238,"d":-0.8532343544296737},{"seed":923114,"d":-0.5444370800121305},{"seed":923119,"d":-0.5074616632994662},{"seed":923122,"d":-0.4966927520496256},{"seed":923014,"d":-0.403749865051509}]},"retail_edge_delta":{"mean":-0.1435702982227427,"se":0.011801771855368645},"arb_edge_delta":{"mean":0.19420387223889776,"se":0.0043955609598002},"reconciliation_max_abs":1.0658141036401503e-13,"gas":[{"role":"Baseline","callback":"afterInitialize","calls":256,"ok":256,"max_ok_gas":21796,"sum_ok_gas":5579776,"oog":0,"revert":0,"other_halt":0,"tx_error":0,"bad_return":0},{"role":"Baseline","callback":"afterSwap","calls":2736545,"ok":2736545,"max_ok_gas":22592,"sum_ok_gas":61744531156,"oog":0,"revert":0,"other_halt":0,"tx_error":0,"bad_return":0},{"role":"Baseline","callback":"getName","calls":256,"ok":256,"max_ok_gas":21526,"sum_ok_gas":5510656,"oog":0,"revert":0,"other_halt":0,"tx_error":0,"bad_return":0},{"role":"Submission","callback":"afterInitialize","calls":256,"ok":256,"max_ok_gas":243118,"sum_ok_gas":62238208,"oog":0,"revert":0,"other_halt":0,"tx_error":0,"bad_return":0},{"role":"Submission","callback":"afterSwap","calls":2638890,"ok":2638890,"max_ok_gas":199538,"sum_ok_gas":317374757290,"oog":0,"revert":0,"other_halt":0,"tx_error":0,"bad_return":0},{"role":"Submission","callback":"getName","calls":256,"ok":256,"max_ok_gas":21626,"sum_ok_gas":5536256,"oog":0,"revert":0,"other_halt":0,"tx_error":0,"bad_return":0}]}],"selection":"largest paired mean on recheck 923000..923255"},"held_out":{"start":924000,"vs_rs2":{"n":512,"mean_diff":0.11057163065549047,"se":0.014084312952773478,"worst":[{"seed":924119,"d":-1.1281715588015686},{"seed":924419,"d":-0.9532726495183397},{"seed":924510,"d":-0.8998078817687656},{"seed":924085,"d":-0.8617116078820004},{"seed":924476,"d":-0.847320413565285}]},"retail_edge_delta":{"mean":-0.47915168153549403,"se":0.014732455377969432},"arb_edge_delta":{"mean":0.5897233121909824,"se":0.005426146630986634},"reconciliation_max_abs":1.1368683772161603e-13,"valid":true,"gas_by_arm":{"candidate":[{"role":"Baseline","callback":"afterInitialize","calls":512,"ok":512,"max_ok_gas":21796,"sum_ok_gas":11159552,"oog":0,"revert":0,"other_halt":0,"tx_error":0,"bad_return":0},{"role":"Baseline","callback":"afterSwap","calls":5503009,"ok":5503009,"max_ok_gas":22592,"sum_ok_gas":124164119024,"oog":0,"revert":0,"other_halt":0,"tx_error":0,"bad_return":0},{"role":"Baseline","callback":"getName","calls":512,"ok":512,"max_ok_gas":21526,"sum_ok_gas":11021312,"oog":0,"revert":0,"other_halt":0,"tx_error":0,"bad_return":0},{"role":"Submission","callback":"afterInitialize","calls":512,"ok":512,"max_ok_gas":243118,"sum_ok_gas":124476416,"oog":0,"revert":0,"other_halt":0,"tx_error":0,"bad_return":0},{"role":"Submission","callback":"afterSwap","calls":5247544,"ok":5247544,"max_ok_gas":204413,"sum_ok_gas":631483051600,"oog":0,"revert":0,"other_halt":0,"tx_error":0,"bad_return":0},{"role":"Submission","callback":"getName","calls":512,"ok":512,"max_ok_gas":21626,"sum_ok_gas":11072512,"oog":0,"revert":0,"other_halt":0,"tx_error":0,"bad_return":0}],"rs2":[{"role":"Baseline","callback":"afterInitialize","calls":512,"ok":512,"max_ok_gas":21796,"sum_ok_gas":11159552,"oog":0,"revert":0,"other_halt":0,"tx_error":0,"bad_return":0},{"role":"Baseline","callback":"afterSwap","calls":5472779,"ok":5472779,"max_ok_gas":22592,"sum_ok_gas":123481987660,"oog":0,"revert":0,"other_halt":0,"tx_error":0,"bad_return":0},{"role":"Baseline","callback":"getName","calls":512,"ok":512,"max_ok_gas":21526,"sum_ok_gas":11021312,"oog":0,"revert":0,"other_halt":0,"tx_error":0,"bad_return":0},{"role":"Submission","callback":"afterInitialize","calls":512,"ok":512,"max_ok_gas":243099,"sum_ok_gas":124466688,"oog":0,"revert":0,"other_halt":0,"tx_error":0,"bad_return":0},{"role":"Submission","callback":"afterSwap","calls":5300125,"ok":5300125,"max_ok_gas":203103,"sum_ok_gas":624296715762,"oog":0,"revert":0,"other_halt":0,"tx_error":0,"bad_return":0},{"role":"Submission","callback":"getName","calls":512,"ok":512,"max_ok_gas":21607,"sum_ok_gas":11062784,"oog":0,"revert":0,"other_halt":0,"tx_error":0,"bad_return":0}]}},"gas":{"max_ok":204413,"init_max_ok":243118,"oog":0,"halts":{"oog":0,"revert":0,"other_halt":0,"tx_error":0,"bad_return":0}},"parity":{"start":924600,"n":32,"paired":{"n":32,"mean_diff":0.0,"se":0.0,"worst":[{"seed":924600,"d":0.0},{"seed":924601,"d":0.0},{"seed":924602,"d":0.0},{"seed":924603,"d":0.0},{"seed":924604,"d":0.0}]},"retail_edge_delta":{"mean":0.0,"se":0.0},"arb_edge_delta":{"mean":0.0,"se":0.0},"reconciliation_max_abs":0.0,"source_identical":false,"full_overlay_state_updates":true,"fee_weights":[1,1],"rows_identical":true,"valid":true},"generator_source":"def generate(base,p,force_overlay=False):\n    ka,kf,n=p\n    ka=round(ka*10**18);kf=round(kf*10**18);n=int(round(n))\n    assert 0<=ka<=15*10**17 and 0<=kf<=15*10**17 and 100<=n<=10000\n    # Keeping k=1 as a literal bypass makes the disabled overlay RS2 exactly.\n    if ka==10**18 and kf==10**18 and not force_overlay:return base\n    s=base.replace('uint256 stepTradeCount = slots[10];','uint256 stepTradeCount = uint8(slots[10]);')\n    old='        uint256 flowSize = wmul(lambdaHat, sizeHat);'\n    insert=f'''        uint256 flowSize = wmul(lambdaHat, sizeHat);\n        // Run-level means, observed after RS2's flow correction on each callback.\n        // Packed in unused bits of slots[10]; zero means no observations yet.\n        uint256 anchor = slots[10] >> 8;\n        uint256 runAct = uint96(anchor);\n        uint256 runFlow = uint96(anchor >> 96);\n        uint256 runN = anchor >> 192;\n        if (runN < {n}) ++runN;\n        if (actEma >= runAct) runAct += (actEma-runAct)/runN;\n        else runAct -= (runAct-actEma)/runN;\n        if (flowSize >= runFlow) runFlow += (flowSize-runFlow)/runN;\n        else runFlow -= (runFlow-flowSize)/runN;\n        uint256 feeAct = _anchorValue(runAct,actEma,{ka});\n        flowSize = _anchorValue(runFlow,flowSize,{kf});\n        anchor = runAct | (runFlow << 96) | (runN << 192);'''\n    assert old in s;s=s.replace(old,insert)\n    s=s.replace('wmul(ACT_COEF, actEma)','wmul(ACT_COEF, feeAct)')\n    s=s.replace('slots[10] = stepTradeCount;','slots[10] = stepTradeCount | (anchor << 8);')\n    helper='''    function _anchorValue(uint256 mean,uint256 value,uint256 k) internal pure returns(uint256) {\n        if (value>=mean) return mean+wmul(value-mean,k);\n        uint256 delta=wmul(mean-value,k);\n        return mean>delta ? mean-delta : 0;\n    }\n\n'''\n    s=s.replace('    struct PosteriorInput {',helper+'    struct PosteriorInput {')\n    return s\n","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","search_source":"import sys,time,json,math\nfrom pathlib import Path\nsys.path.insert(0,'scratch')\nfrom harness import *\nfrom generator import generate\nimport cma\nbase=json.load(open('scratch/rs2.json'))['code']\nc=SolidityCompiler();v=c.compile(Path('contracts/src/VanillaStrategy.sol').read_text(),'VanillaStrategy');assert v.success\nerrors=['oog','revert','other_halt','tx_error','bad_return']\ndef valid(r):\n return all(not any(row.get(e,0) for e in errors) for row in r['raw_counters']) and all(row['max_ok_gas'] < (235000 if row['callback']=='afterSwap' else 245000) for row in r['raw_counters'] if row['role']=='Submission' and row['callback']!='getName')\ndef params(x):return [float(x[0]),float(x[1]),int(round(10**x[2]))]\nes=cma.CMAEvolutionStrategy([.65,.65,3.0],.35,{'seed':43,'bounds':[[0,0,2],[1.5,1.5,4]],'popsize':6,'verbose':-9})\nlogs=[];start=time.monotonic();idx=0\nwhile idx+6<=46 and time.monotonic()-start<1450:\n xs=es.ask();ys=[]\n for x in xs:\n  if time.monotonic()-start>=1500:break\n  p=params(x);first=920000+64*idx\n  a=run(generate(base,p),first,64,v.bytecode,c);b=run(base,first,64,v.bytecode,c)\n  cmp=compare(a,b);ok=valid(a) and valid(b);score=cmp['paired']['mean_diff'] if ok else -1000\n  entry={'params':p,'start':first,'n':64,'mean_diff':cmp['paired']['mean_diff'],'se':cmp['paired']['se'],'fitness':score,'valid':ok,'gas':a['raw_counters'],'baseline_gas':b['raw_counters'],'elapsed':time.monotonic()-start}\n  logs.append(entry);ys.append(-score);idx+=1\n  Path('scratch/search_log.json').write_text(json.dumps(logs));print(json.dumps({k:entry[k] for k in ['params','start','mean_diff','se','valid','elapsed']}),flush=True)\n if len(ys)!=len(xs):break\n es.tell(xs,ys)\nprint('DONE',idx,time.monotonic()-start,flush=True)\n","confirmation_source":"import sys,json,time,hashlib\nfrom pathlib import Path\nsys.path.insert(0,'scratch')\nfrom harness import *\nfrom generator import generate\nbase=json.load(open('scratch/rs2.json'))['code'];logs=json.load(open('scratch/search_log.json'))\nrank=sorted([r for r in logs if r['valid']],key=lambda r:r['fitness'],reverse=True)\nassert len(rank)>=3\nselected=rank[:3]\nc=SolidityCompiler();v=c.compile(Path('contracts/src/VanillaStrategy.sol').read_text(),'VanillaStrategy');assert v.success\nerrors=['oog','revert','other_halt','tx_error','bad_return']\ndef valid(r):\n return all(not any(row.get(e,0) for e in errors) for row in r['raw_counters']) and all(row['max_ok_gas'] < (235000 if row['callback']=='afterSwap' else 245000) for row in r['raw_counters'] if row['role']=='Submission' and row['callback']!='getName')\ndef save(name,r):Path('scratch/'+name+'.json').write_text(json.dumps(r))\n# Re-check: one common block, baseline evaluated independently against Vanilla.\nb=run(base,923000,256,v.bytecode,c);save('recheck_rs2',b);checks=[]\nfor i,l in enumerate(selected):\n a=run(generate(base,l['params']),923000,256,v.bytecode,c);save('recheck_'+str(i),a)\n cp=compare(a,b);row={'params':l['params'],'search_start':l['start'],'valid':valid(a) and valid(b),**cp,'gas':a['raw_counters']};checks.append(row);save('recheck_summary',checks)\n print('RECHECK',i,json.dumps(row),flush=True)\nwin=max([r for r in checks if r['valid']],key=lambda r:r['paired']['mean_diff'])\np=win['params'];source=generate(base,p)\nfreeze={'params':p,'sha256':hashlib.sha256(source.encode()).hexdigest(),'selection':'largest paired mean on recheck 923000..923255','source':source};save('freeze',freeze)\nprint('FROZEN',p,flush=True)\na=run(source,924000,512,v.bytecode,c);save('held_candidate',a)\nb=run(base,924000,512,v.bytecode,c);save('held_rs2',b)\nheld=compare(a,b);held['valid']=valid(a) and valid(b);save('held_summary',held);print('HELD',json.dumps(held),flush=True)\noff=generate(base,[1.,1.,p[2]],force_overlay=True)\npa=run(off,924600,32,v.bytecode,c);save('parity_off',pa)\npb=run(base,924600,32,v.bytecode,c);save('parity_rs2',pb)\nparity=compare(pa,pb);parity.update(source_identical=off==base,full_overlay_state_updates=True,fee_weights=[1,1],rows_identical=pa['rows']==pb['rows'],valid=valid(pa) and valid(pb));save('parity_summary',parity);print('PARITY',json.dumps(parity),flush=True)\n","calibration":{"source":"https://raw.githubusercontent.com/ChengHua926/amm-challenge/d34a5199c59a4c44d5336a25f1436b4ae1f21104/contracts/src/Strategy.sol","start":0,"n":1000,"mean":525.5258821780834,"expected":525.5258821780834,"exact_match":true,"gas":[{"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}]},"protocol":{"repo":"https://github.com/benedictbrady/amm-challenge","commit":"6b6921f8d463314aa7c96234e1be25a25245f704","rs2_source":"https://api.imdnotdead.fun/artifacts/19f2ec857df536e8ab62ab1da89ec6623332521ce46849f15bccff402c63e1e5","rs2_sha256":"f24b6ca198b744c380842c3a17964a6dc21f311bb04984b26733afa3fee8eaf2","method_source":"https://api.imdnotdead.fun/artifacts/33f54e81f3372088e9eced52c0174f310ac348af98ef5727b73785c088679194","opponent":"VanillaStrategy","workers":8,"search_seed":43,"cma_version":"4.5.0","parameter_order":["act_k","flow_k","N"],"search_seconds_last_completed":1452.2033830401488,"search_cutoff":{"ready":true,"n":28,"elapsed":1452.2251122710295},"simulator_wheel_sha256":"aedb68280aca34c110968f00148387c95885207913fb2cf19a1ab4c5cfd6887a"},"notes":["All performance figures are local measurements, not leaderboard claims. No seeds >= 5000000 were run; item-specific ranges take precedence over the general goal confirmation range.","Running means observe actEma and RS2-corrected lambdaHat*sizeHat once per afterSwap, immediately before the fee terms. Count starts at zero and advances to N. At N the prescribed capped-count update continues with weight 1/N.","Target terms read mean + k*(value-mean). Negative extrapolations for k>1 are saturated to zero so unsigned fee signals remain valid. Persistent actEma and sizeHat state retain their original 0.53 decay.","Two uint96 means and a count are packed above the existing uint8 step count in slots[10]; afterInitialize is unmodified and performs no extra write. Price, stale-shift, posterior and all other coefficient terms are unchanged.","Parity sets both k=1 but forces all mean/count updates to execute, comparing independent runs against RS2; this tests storage packing and fee equality with overlay effect off. Normal generation optimizes both-k=1 to literal RS2. A single gas-only probe of [.5,.5,1000] used seed 924600 before search; it was not fitness or used to select parameters.","CMA-ES searches k in [0,1.5] and log10(N) in [2,4], rounding N to an integer. Each fitness evaluation uses a previously unused 64-seed block from 920000. Top three fitness scores are rechecked on the common 256 seeds; winner frozen before either 512-seed held-out arm.","Gas aggregates every completed search arm, recheck, held-out, parity and gas probe; CH calibration is reported separately. Any halt invalidates the arm. Search was externally interrupted immediately after checkpoint 28 to enforce the <=25 minute cap; no incomplete evaluation was scored or selected. No board submission was made.","Held-out point estimate was positive and its approximate mean +/- 1.96*SE interval excluded zero."]}