{"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 ANCHOR_WEIGHT = 20000000000000000;\n    uint256 constant ANCHOR_K = 8000000000000000000;\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 = 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        // Cache an interior retail routing observation: price in high 192 bits,\n        // timestamp in low 64 bits. A first print may be arbitrage, so exclude it.\n        if (!firstInStep && feeUsed > 30 * BPS && gamma > 0) {\n            uint256 anchor = trade.isBuy\n                ? wdiv(wmul(spot, gamma), WAD - 30 * BPS)\n                : wdiv(wmul(spot, WAD - 30 * BPS), gamma);\n            slots[11] = (anchor << 64) | trade.timestamp;\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, 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        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            staleHat = _dualAnchor(staleHat, sigmaHat, trade.timestamp);\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    function _dualAnchor(uint256 estimate, uint256 sigma, uint256 timestamp) internal view returns (uint256) {\n        uint256 packed = slots[11];\n        uint256 anchor = packed >> 64;\n        if (anchor == 0) return estimate;\n        uint256 age = timestamp - uint64(packed);\n        // Linear widening by k*sigmaHat for each elapsed step.\n        uint256 width = 30 * BPS + wmul(ANCHOR_K, sigma) * age;\n        // Once the band covers +/-100%, this observation is uninformative.\n        if (width >= WAD) return estimate;\n        uint256 lo = wmul(anchor, WAD-width);\n        uint256 hi = wmul(anchor, WAD+width);\n        uint256 clipped = estimate < lo ? lo : (estimate > hi ? hi : estimate);\n        return _blend(estimate, clipped, ANCHOR_WEIGHT);\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":"77854865f5d508eccf04acd0bfb002c691b78b2976535d9853f3c9ce79d59def","params":{"w":0.02,"k":8.0,"variant":"stale"},"mechanism":"On later-in-step retail fills with the RS2 interior-routing guard, infer Vanilla spot from fee-adjusted marginal-price equality and cache that price with its timestamp in unused slot 11. Pull the selected RS2 price estimate toward the nearest endpoint of a relative +/-30 bps interval widened linearly by k*sigmaHat per elapsed step, with weight w and no new afterInitialize storage write.","source":{"url":"https://benedict.dev/optimization-arena-learnings","quote":"EMA, dual anchor, or virtual reserves"},"search":{"method":"seed-85 shuffled finite grid; active mechanisms ranked by paired mean; neutral control checked separately","rng":"numpy.random.default_rng(85)","target_seconds":1500,"elapsed_seconds":1501.0982169599738,"evaluations":110,"grid":{"w":[0.01,0.02,0.05,0.1,0.25,0.5,0.75,1.0],"k":[0,0.25,0.5,1.0,2.0,4.0,8.0],"variant":["fast","slow","stale"]},"neutral_w":0,"blocks":[980576,981792,980832,981536,981728,982880],"seeds_per_evaluation":64,"best":{"evaluation":86,"params":{"w":0.02,"k":0,"variant":"stale"},"start":981536,"n":64,"paired":{"n":64,"mean_diff":0.026468300627323416,"se":0.01668257021810946,"worst":[{"seed":981558,"d":-0.25692847136724595},{"seed":981584,"d":-0.2294534871725773},{"seed":981572,"d":-0.2224275317946649},{"seed":981588,"d":-0.17300287038892748},{"seed":981561,"d":-0.15319089974457256}]},"retail_edge_delta":{"mean":0.10614728088644476,"se":0.0174682171949195},"arb_edge_delta":{"mean":-0.0796789802591168,"se":0.008253914229381317},"reconciliation_max_abs":8.881784197001252e-14,"gas":{"max_ok":202436,"init_max_ok":243099,"oog":0,"other_errors":0},"valid":true,"elapsed_seconds":1154.3568245798815,"sha256":"871d53dc453551c5ae4b4871ff6ba8bb901748ea08b60e632d81d593cec69dcc"},"recheck":[{"params":{"w":0.02,"k":0,"variant":"stale"},"search_evaluation":86,"paired":{"n":256,"mean_diff":-0.032997708075606536,"se":0.011869592887496895,"worst":[{"seed":983175,"d":-0.7991011620201789},{"seed":983036,"d":-0.7895709750822562},{"seed":983025,"d":-0.691407200923777},{"seed":983211,"d":-0.6113924707514116},{"seed":983179,"d":-0.606589703583154}]},"retail_edge_delta":{"mean":0.0722362193937316,"se":0.010547164407559121},"arb_edge_delta":{"mean":-0.10523392746933632,"se":0.0060760127561987065},"reconciliation_max_abs":1.0658141036401503e-13,"gas":{"max_ok":203948,"init_max_ok":243099,"oog":0,"other_errors":0},"sha256":"871d53dc453551c5ae4b4871ff6ba8bb901748ea08b60e632d81d593cec69dcc","valid":true},{"params":{"w":0.02,"k":1.0,"variant":"stale"},"search_evaluation":19,"paired":{"n":256,"mean_diff":-0.03542204769654833,"se":0.0074119841045215806,"worst":[{"seed":983175,"d":-0.6466296181774851},{"seed":983025,"d":-0.4990542473001369},{"seed":983151,"d":-0.4395051590533967},{"seed":983211,"d":-0.39401795393064276},{"seed":983036,"d":-0.38489043764730013}]},"retail_edge_delta":{"mean":0.060234512336926116,"se":0.0067839181729861114},"arb_edge_delta":{"mean":-0.09565656003347447,"se":0.004678665260920152},"reconciliation_max_abs":1.1368683772161603e-13,"gas":{"max_ok":204225,"init_max_ok":243099,"oog":0,"other_errors":0},"sha256":"7dc1a5c47a15efba2c08194b740c2ec049fba3c6be49021aaba659b6055eb37b","valid":true},{"params":{"w":0.02,"k":8.0,"variant":"stale"},"search_evaluation":91,"paired":{"n":256,"mean_diff":-0.008369050800080435,"se":0.006280990788244664,"worst":[{"seed":983175,"d":-0.5539021363155143},{"seed":983151,"d":-0.35708927866869544},{"seed":983123,"d":-0.34533745154533335},{"seed":983186,"d":-0.26973541324582584},{"seed":983240,"d":-0.26189662111971757}]},"retail_edge_delta":{"mean":0.0415025814961143,"se":0.0060207376156954},"arb_edge_delta":{"mean":-0.04987163229619358,"se":0.0029635369679791956},"reconciliation_max_abs":1.0658141036401503e-13,"gas":{"max_ok":204249,"init_max_ok":243099,"oog":0,"other_errors":0},"sha256":"77854865f5d508eccf04acd0bfb002c691b78b2976535d9853f3c9ce79d59def","valid":true}],"frozen_before_held_out":{"params":{"w":0.02,"k":8.0,"variant":"stale"},"sha256":"77854865f5d508eccf04acd0bfb002c691b78b2976535d9853f3c9ce79d59def","chosen_on":"983000..983255","held_out":"984000..984511","stack_confirmation":"5800000..5801999","recheck":{"params":{"w":0.02,"k":8.0,"variant":"stale"},"search_evaluation":91,"paired":{"n":256,"mean_diff":-0.008369050800080435,"se":0.006280990788244664,"worst":[{"seed":983175,"d":-0.5539021363155143},{"seed":983151,"d":-0.35708927866869544},{"seed":983123,"d":-0.34533745154533335},{"seed":983186,"d":-0.26973541324582584},{"seed":983240,"d":-0.26189662111971757}]},"retail_edge_delta":{"mean":0.0415025814961143,"se":0.0060207376156954},"arb_edge_delta":{"mean":-0.04987163229619358,"se":0.0029635369679791956},"reconciliation_max_abs":1.0658141036401503e-13,"gas":{"max_ok":204249,"init_max_ok":243099,"oog":0,"other_errors":0},"sha256":"77854865f5d508eccf04acd0bfb002c691b78b2976535d9853f3c9ce79d59def","valid":true},"selection":"best active mechanism; neutral is a separate control"},"log_columns":["evaluation","w","k","variant","start_seed","mean_diff","se","retail_delta","arb_delta","max_swap_gas","init_gas","valid"],"log":[[1,1.0,2.0,"stale",980576,-16.471037824501025,1.5468187757797656,1.589422511445056,-18.06046033594609,202529,243099,true],[2,0.1,0.5,"fast",980576,-0.5156364841897867,0.09992673525921414,0.2412160070679077,-0.7568524912576922,202474,243090,true],[3,1.0,0.25,"fast",980576,-4.086306843926464,0.7610124425954297,-0.026319704778970276,-4.059987139147499,202474,243090,true],[4,0.5,8.0,"slow",980576,-3.6906369686871177,0.5675460118204122,1.0772433299115614,-4.7678802985986835,202463,243099,true],[5,0.75,0.25,"stale",980576,-12.961591795402803,0.9160283956867814,-0.7879096838976816,-12.173682111505126,202529,243099,true],[6,0.25,0.25,"stale",980576,-1.57223132785799,0.15355590134373148,0.7436706606344687,-2.3159019884924588,202529,243099,true],[7,0.01,4.0,"stale",980576,-0.012839166235599109,0.010100519260227364,0.01174115199470016,-0.024580318230299714,202529,243099,true],[8,0.75,8.0,"stale",980576,-6.810928563646995,0.5394406627602646,1.772611120096557,-8.583539683743552,202529,243099,true],[9,0.5,0.25,"slow",980576,-6.672420869777798,0.5894410037082164,-0.013146384605591699,-6.659274485172207,202463,243099,true],[10,0.05,4.0,"slow",981792,-0.09050141829787517,0.030746960734975164,0.19599084776970077,-0.28649226606758105,202440,243099,true],[11,0.1,1.0,"fast",981792,-0.38278419877937164,0.07282792502521594,0.2990059576024393,-0.6817901563818161,202451,243090,true],[12,0.75,1.0,"fast",981792,-2.089349415861652,0.1993028006057854,1.1773316803335163,-3.26668109619517,202451,243090,true],[13,0.75,0,"fast",981792,-5.00885540710925,0.5893919553953059,-0.6351275479642311,-4.373727859145028,202451,243090,true],[14,0.1,0.25,"stale",981792,-0.29915215955251195,0.05211340815787557,0.39940269662667394,-0.6985548561791903,202506,243099,true],[15,0.1,0.25,"fast",981792,-0.47407575817453473,0.07876502785279252,0.3508771974296705,-0.8249529556042092,202451,243090,true],[16,1.0,0,"stale",981792,-148.26488504990607,8.057043173420594,-147.7838186579998,-0.4810663919062712,202743,243099,true],[17,0.5,0,"stale",981792,-20.196128979909094,2.157096620861984,-14.567925967114853,-5.628203012794246,202506,243099,true],[18,0.5,1.0,"stale",981792,-4.803158657756714,0.4525767964154015,1.2735557676523106,-6.076714425409028,202506,243099,true],[19,0.02,1.0,"stale",980832,0.0018021540485557708,0.011449429674595443,0.08221410954770558,-0.08041195549915187,201614,243099,true],[20,0.5,2.0,"stale",980832,-3.9773784403008543,0.3609170617494136,1.3373490621382347,-5.314727502439086,201618,243099,true],[21,0.05,8.0,"slow",980832,-0.00979205511466752,0.02317790397430724,0.22503164068515513,-0.23482369579981494,201567,243099,true],[22,0.5,0.25,"fast",980832,-2.0608151712957463,0.15465485480044155,0.6738862367483094,-2.7347014080440593,201563,243090,true],[23,0.02,8.0,"fast",980832,-0.003199575222283535,0.009150432983133346,0.044982082004837665,-0.04818165722712009,201587,243090,true],[24,0.75,0,"stale",980832,-74.19794328176965,4.364153454762581,-69.4086555425698,-4.789287739199839,202783,243099,true],[25,0.25,2.0,"stale",980832,-0.8957882168675333,0.0945578172673275,0.7288233357983618,-1.624611552665895,201610,243099,true],[26,0.75,1.0,"slow",980832,-7.597125749314403,0.6666277342100794,0.9700996931123642,-8.567225442426764,201543,243099,true],[27,0.02,0.25,"fast",980832,-0.03356184131781337,0.011975638084336012,0.08043080090910948,-0.11399264222692401,201591,243090,true],[28,0.05,8.0,"fast",981536,-0.061703901792248494,0.023486563758715575,0.09161280051511955,-0.15331670230736993,202381,243090,true],[29,0.25,4.0,"fast",981536,-0.605537333482574,0.08875198250365607,0.44899118888704237,-1.0545285223696168,202381,243090,true],[30,0.25,4.0,"slow",981536,-0.9043091636298239,0.12791944260412444,0.7673664452150923,-1.6716756088449145,202370,243099,true],[31,0.75,0,"slow",981536,-100.11545118033305,7.902524611945552,-100.74447760672172,0.6290264263886535,202370,243099,true],[32,0.05,0.5,"slow",981536,-0.17329838280358967,0.029973205402011996,0.30110591671899556,-0.47440429952259094,202370,243099,true],[33,0.1,0.5,"stale",981536,-0.19787100434501959,0.0352701324112711,0.3596222230524173,-0.557493227397434,202436,243099,true],[34,1.0,8.0,"stale",981536,-15.100879969762964,1.5842871506317922,2.198184160899694,-17.29906413066266,202436,243099,true],[35,0.1,4.0,"slow",981536,-0.2019731266315894,0.04181124509870013,0.3589928494115284,-0.5609659760431203,202370,243099,true],[36,0.5,2.0,"fast",981536,-1.3046864573110648,0.1383883725504673,0.8318628024011518,-2.1365492597122135,202381,243090,true],[37,1.0,4.0,"slow",981728,-13.830065766432286,1.5135975307556788,0.7566709488016148,-14.586736715233897,204432,243099,true],[38,0.01,2.0,"stale",981728,-0.01987227448535034,0.013405107649404346,0.009476132326954989,-0.029348406812304217,204490,243099,true],[39,0.75,8.0,"slow",981728,-9.551029144761838,1.2225371560320564,1.3404773089870705,-10.891506453748898,204427,243099,true],[40,0.75,4.0,"slow",981728,-9.550988859296705,1.2225289073437595,1.3404917226305137,-10.891480581927208,204427,243099,true],[41,1.0,0.5,"stale",981728,-24.754667930923414,2.6647965400152596,-0.6508925492668292,-24.103775381656583,204499,243099,true],[42,0.75,4.0,"fast",981728,-2.3257690953903243,0.2766982095129259,1.0446478725599393,-3.3704169679502565,204451,243090,true],[43,0.1,0.5,"slow",981728,-0.8203072369606952,0.1525672533409552,0.47657025648384366,-1.2968774934445388,204443,243099,true],[44,0.25,1.0,"slow",981728,-2.293417894598333,0.427454359432766,0.8654884784361494,-3.1589063730344766,204419,243099,true],[45,0.01,1.0,"stale",981728,-0.022576149072205176,0.013268832675953293,0.014217999081009403,-0.03679414815320675,204502,243099,true],[46,0.02,0,"fast",982880,-0.04544908187662777,0.02559400602639076,0.12152183089665147,-0.16697091277328224,201944,243090,true],[47,0.25,0,"fast",982880,-1.9309287761038627,0.16603118839500666,0.5755313837976548,-2.5064601599015193,199502,243090,true],[48,0.75,0.25,"slow",982880,-11.732532682384903,0.9573253030204915,-0.2558784350451653,-11.476654247339738,202240,243099,true],[49,1.0,8.0,"fast",982880,-3.4836380330479795,0.3264566704434546,0.9249891996487811,-4.408627232696764,202272,243090,true],[50,1.0,0,"slow",982880,-148.03574522482097,10.125652196969229,-151.32911586029553,3.2933706354745715,201569,243099,true],[51,0.75,0.5,"stale",982880,-13.176979115616398,0.9007103090984898,0.3047393885981817,-13.48171850421458,202331,243099,true],[52,0.01,0.25,"slow",982880,-0.04300914472568973,0.01882950451055447,0.07648645363633566,-0.11949559836202239,202252,243099,true],[53,0.75,0.5,"fast",982880,-2.7812554966238547,0.2678069442128924,0.9111810342274911,-3.6924365308513503,202275,243090,true],[54,0.02,4.0,"slow",982880,-0.04359107223416814,0.019496281277980237,0.0771061908284727,-0.12069726306263862,202240,243099,true],[55,0.5,0.5,"fast",980576,-2.13593115239373,0.3198688626647754,0.4427298933072299,-2.5786610457009567,202474,243090,true],[56,0.05,0.25,"fast",980576,-0.2814921892262543,0.054166233519556475,0.1350378718079046,-0.4165300610341595,202474,243090,true],[57,0.25,0.5,"stale",980576,-1.328786234380268,0.13396259655190598,0.7623040358216704,-2.0910902702019385,202529,243099,true],[58,0.02,0.5,"slow",980576,-0.1103354594160697,0.026535417279918764,0.09559867028427149,-0.20593412970033848,202463,243099,true],[59,0.25,1.0,"fast",980576,-1.1057224820305294,0.14797688063802467,0.48100310407783553,-1.586725586108368,202474,243090,true],[60,0.01,0.25,"stale",980576,-0.019336689271410634,0.015201163650441312,0.035494670425321395,-0.054831359696730586,202529,243099,true],[61,0.75,0.25,"fast",980576,-3.1192326825172048,0.5246355635415402,0.3478888774878053,-3.4671215600050074,202474,243090,true],[62,0.1,2.0,"slow",980576,-0.431922886763318,0.0900633630525933,0.34909507322176214,-0.7810179599850844,202463,243099,true],[63,0.01,0.5,"stale",980576,-0.017334432645936815,0.012624573681835203,0.03209074287200675,-0.049425175517944286,202529,243099,true],[64,0.05,2.0,"fast",981792,-0.10980060017802273,0.035519373116839274,0.1584239618840506,-0.26822456206207407,202451,243090,true],[65,0.1,1.0,"slow",981792,-0.47545286221102323,0.07809414947939465,0.4495642176425454,-0.9250170798535824,202440,243099,true],[66,1.0,1.0,"slow",981792,-11.83745832582795,1.039436930026407,1.023619462285402,-12.86107778811336,202440,243099,true],[67,1.0,1.0,"fast",981792,-2.8125075923328753,0.25170015015995484,1.2421463324726991,-4.054653924805576,202451,243090,true],[68,1.0,0.25,"stale",981792,-23.199366244405873,1.8268428921115851,-2.1558002066067425,-21.04356603779914,202506,243099,true],[69,0.01,4.0,"slow",981792,-0.024449763570381755,0.010012910145159183,0.031839212399007444,-0.056288975969395305,202440,243099,true],[70,0.25,0.25,"fast",981792,-1.250410812926824,0.14184839628267076,0.6463264015981727,-1.8967372145249997,202451,243090,true],[71,0.1,4.0,"stale",981792,-0.13702173542851526,0.03508897781609137,0.2505450453006519,-0.3875667807291722,202506,243099,true],[72,0.01,0,"slow",981792,-0.07742836031314138,0.026724561564374142,0.0006487390601419563,-0.07807709937328056,202440,243099,true],[73,0.1,2.0,"stale",980832,-0.13071654655787768,0.03347178014458967,0.31545653113080885,-0.446173077688682,201594,243099,true],[74,1.0,8.0,"slow",980832,-11.310270991250531,0.8834250343089215,0.6415954086885982,-11.951866399939131,201556,243099,true],[75,0.02,0.5,"stale",980832,-0.00938013544150973,0.011590939591692882,0.08716717410434782,-0.09654730954585217,201614,243099,true],[76,0.05,0,"stale",980832,-0.05868523301504602,0.03180175774405841,0.18638334689573366,-0.24506857991077508,201321,243099,true],[77,0.05,1.0,"stale",980832,-0.016953102714103885,0.02154396046714491,0.20231514582857013,-0.21926824854266969,201602,243099,true],[78,0.1,8.0,"fast",980832,-0.10616246418975006,0.03223835557214037,0.2576181612527826,-0.3637806254425338,201579,243090,true],[79,1.0,0.5,"slow",980832,-11.576319377104065,0.8970564380851832,0.4557908120275327,-12.032110189131595,201564,243099,true],[80,0.02,0,"slow",980832,-0.0427829023685975,0.02906610388141369,0.09961196180106136,-0.14239486416965236,201200,243099,true],[81,0.01,2.0,"fast",980832,-0.005802709312374255,0.0069800859588642515,0.025435254090797166,-0.03123796340316448,201555,243090,true],[82,0.05,1.0,"fast",981536,-0.11443609882443706,0.031077025507156096,0.16083504314763442,-0.2752711419720759,202381,243090,true],[83,0.25,0.25,"slow",981536,-2.2763395975002245,0.24774979357557544,0.7496302152538759,-3.0259698127540986,202370,243099,true],[84,0.01,4.0,"fast",981536,-0.004804304629276501,0.009716020086765505,0.024490387739564135,-0.029294692368841024,202381,243090,true],[85,0.25,0.5,"fast",981536,-0.9423820025132992,0.11444046172712549,0.607877789559824,-1.550259792073117,202381,243090,true],[86,0.02,0,"stale",981536,0.026468300627323416,0.01668257021810946,0.10614728088644476,-0.0796789802591168,202436,243099,true],[87,0.02,1.0,"fast",981536,-0.02498254210117512,0.013381246450884067,0.05699156123464544,-0.08197410333582006,202381,243090,true],[88,0.75,2.0,"stale",981536,-8.800868007969738,0.7964561383828013,1.6241995304213246,-10.425067538391055,202436,243099,true],[89,0.1,0,"slow",981536,-1.131773350659059,0.09951266034822538,-0.2788106743487795,-0.8529626763102782,202370,243099,true],[90,0.5,2.0,"slow",981536,-3.5210640353434677,0.4670345110525474,1.2423442383082595,-4.763408273651723,202370,243099,true],[91,0.02,8.0,"stale",981728,0.0005244364576766358,0.014057342082679744,0.039053954253757794,-0.03852951779607389,204510,243099,true],[92,0.1,8.0,"slow",981728,-0.3031670686883574,0.08908306662380724,0.32798589698901814,-0.6311529656773742,204427,243099,true],[93,0.02,0.25,"slow",981728,-0.15196138293632622,0.02839471617345243,0.0986271644085921,-0.25058854734491137,204447,243099,true],[94,0.01,1.0,"slow",981728,-0.05346637665016818,0.016622287056308804,0.04181757663815677,-0.095283953288326,204431,243099,true],[95,0.02,4.0,"stale",981728,-0.013509043100209617,0.014931963867440388,0.03628313809846162,-0.04979218119866963,204510,243099,true],[96,0.05,0.5,"stale",981728,-0.10477373425513647,0.027971620232460796,0.1782783339940286,-0.28305206824915957,204514,243099,true],[97,0.1,2.0,"fast",981728,-0.4536913457916594,0.08609436815292641,0.2489963182155579,-0.7026876640072137,204467,243090,true],[98,0.01,0.5,"slow",981728,-0.06903223049320584,0.0186554555634228,0.042079427038761885,-0.11111165753195912,204431,243099,true],[99,0.02,1.0,"slow",981728,-0.11422177502493636,0.024148826111918698,0.08058994130340746,-0.1948117163283356,204435,243099,true],[100,0.75,1.0,"stale",982880,-11.448264288466365,0.8737732495187245,1.1868019493394737,-12.635066237805843,202315,243099,true],[101,0.75,8.0,"fast",982880,-2.1938590521828214,0.20284559759468326,1.0352957359993882,-3.2291547881822114,202295,243090,true],[102,0.5,4.0,"stale",982880,-3.5737295615751306,0.31730857235078735,1.4607525987284777,-5.034482160303616,202327,243099,true],[103,0.25,2.0,"slow",982880,-1.4894707127518032,0.27483123029051126,0.8391070220239891,-2.3285777347757914,202252,243099,true],[104,0.02,8.0,"slow",982880,-0.027431533689443732,0.01755754868922856,0.06889952411719591,-0.09633105780664364,202256,243099,true],[105,0.1,4.0,"fast",982880,-0.29667672515133603,0.06695761240448421,0.22409249952007304,-0.5207692246714075,202295,243090,true],[106,1.0,0,"fast",982880,-7.816333824531918,1.169757776776431,-2.543352145083639,-5.2729816794482876,199502,243090,true],[107,0.01,0.5,"fast",982880,-0.01323233743689567,0.008537950334793272,0.02785695561800061,-0.04108929305489922,202287,243090,true],[108,0.5,4.0,"slow",982880,-4.114891008174451,0.5847230674219523,1.373528555848626,-5.488419564023081,202228,243099,true],[109,0.5,1.0,"fast",980576,-1.8151756272597304,0.2884404080141763,0.5491273959173757,-2.364303023177107,202474,243090,true],[110,1.0,1.0,"stale",980576,-17.673149752191705,1.6007846117307345,0.799456773091725,-18.472606525283425,202529,243099,true]],"rejected":0,"all_evaluations_oog":0},"held_out":{"baseline":"RS2","start":984000,"end":984511,"n":512,"mean_diff":0.010680318700312053,"se":0.0045935417204528775,"worst":[{"seed":984248,"d":-1.062841362501615},{"seed":984113,"d":-0.48356037447581457},{"seed":984027,"d":-0.2833615013633448},{"seed":984378,"d":-0.275000179641097},{"seed":984116,"d":-0.24602700680168255}],"candidate_mean_edge":522.8275085602019,"baseline_mean_edge":522.8168282415016,"valid":true,"candidate_gas":{"max_ok":205326,"init_max_ok":243099,"oog":0,"other_errors":0},"baseline_gas":{"max_ok":202221,"init_max_ok":243099,"oog":0,"other_errors":0},"reconciliation_max_abs":1.1368683772161603e-13},"retail_edge_delta":{"mean":0.05638009267703592,"se":0.004332639230810459},"arb_edge_delta":{"mean":-0.04569977397672369,"se":0.002630510613580636},"gas":{"max_ok":205326,"init_max_ok":243099,"oog":0,"other_errors":0,"scope":"Frozen candidate across its search, recheck, RS2 held-out and independent STACK confirmation runs; counters read/reset after each <=20-seed chunk."},"paired":{"n":2000,"mean_diff":0.3414987100538211,"se":0.013778393364032413,"worst":[{"seed":5800821,"d":-2.355975357942725},{"seed":5800086,"d":-2.0327169026475076},{"seed":5800091,"d":-1.8936418760581546},{"seed":5801995,"d":-1.572894681132766},{"seed":5801259,"d":-1.5399395661156632}]},"stack_confirmation":{"baseline":"STACK","source":"https://api.imd.fun/artifacts/c33720874aa1285e9dc766540b8a90410118a8e8b840d949ea0dcc211bdb27c1","start":5800000,"end":5801999,"paired":{"n":2000,"mean_diff":0.3414987100538211,"se":0.013778393364032413,"worst":[{"seed":5800821,"d":-2.355975357942725},{"seed":5800086,"d":-2.0327169026475076},{"seed":5800091,"d":-1.8936418760581546},{"seed":5801995,"d":-1.572894681132766},{"seed":5801259,"d":-1.5399395661156632}]},"retail_edge_delta":{"mean":0.42750796184198875,"se":0.013663013345304122},"arb_edge_delta":{"mean":-0.08600925178816633,"se":0.00616713255836572},"reconciliation_max_abs":1.1013412404281553e-13,"candidate_gas":{"max_ok":204980,"init_max_ok":243099,"oog":0,"other_errors":0},"stack_gas":{"max_ok":213581,"init_max_ok":220962,"oog":0,"other_errors":0},"valid":true,"candidate_mean_edge":522.9473546401986,"baseline_mean_edge":522.6058559301448,"selection_used":false},"checks":{"frozen_strategy_validation":"amm-match validate scratch/frozen.sol passed after freezing","setup":"Pinned checkout 6b6921f8d463314aa7c96234e1be25a25245f704; supplied setup ran once successfully, wheel SHA256 verified and StarterStrategy validated.","calibration":{"start":0,"n":1000,"mean_edge":525.5258821780834,"expected":525.5258821780834,"gas":{"max_ok":151647,"init_max_ok":185532,"oog":0,"other_errors":0}},"neutral":{"start":984600,"n":32,"edge_for_edge_identical":true,"source_identical":true,"paired":{"n":32,"mean_diff":0.0,"se":0.0,"worst":[{"seed":984600,"d":0.0},{"seed":984601,"d":0.0},{"seed":984602,"d":0.0},{"seed":984603,"d":0.0},{"seed":984604,"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},"baseline":{"url":"https://api.imd.fun/artifacts/19f2ec857df536e8ab62ab1da89ec6623332521ce46849f15bccff402c63e1e5","sha256":"f24b6ca198b744c380842c3a17964a6dc21f311bb04984b26733afa3fee8eaf2"},"thresholds":{"afterSwap_strictly_less_than":235000,"afterInitialize_strictly_less_than":245000,"any_halt_invalid":true}},"generator_source":"\"\"\"Generate a dual-anchor variant from the exact supplied RS2 source.\"\"\"\nfrom decimal import Decimal\n\ndef generate(base, w=0, k=1, variant='fast'):\n    assert variant in ('fast','slow','stale')\n    assert 0 <= w <= 1 and k >= 0\n    # Neutral emits the original source, preserving bytecode and every edge.\n    if w == 0:\n        return base\n    wwad=int(Decimal(str(w))*10**18)\n    kwad=int(Decimal(str(k))*10**18)\n    s=base.replace('contract Strategy is AMMStrategyBase {',f'''contract Strategy is AMMStrategyBase {{\n    uint256 constant ANCHOR_WEIGHT = {wwad};\n    uint256 constant ANCHOR_K = {kwad};''')\n    # Slot 11 is unused in RS2 (REVERT_U is zero); no initialization writes.\n    marker='        // Censored assumed-density posterior. No external or future inputs.'\n    update='''        // Cache an interior retail routing observation: price in high 192 bits,\n        // timestamp in low 64 bits. A first print may be arbitrage, so exclude it.\n        if (!firstInStep && feeUsed > 30 * BPS && gamma > 0) {\n            uint256 anchor = trade.isBuy\n                ? wdiv(wmul(spot, gamma), WAD - 30 * BPS)\n                : wdiv(wmul(spot, WAD - 30 * BPS), gamma);\n            slots[11] = (anchor << 64) | trade.timestamp;\n        }\n\n'''\n    assert marker in s\n    s=s.replace(marker,update+marker)\n    if variant=='fast':\n        s=s.replace('        slots[13] = uncertainty;', '        fastHat = _dualAnchor(fastHat, sigmaHat, trade.timestamp);\\n        slots[13] = uncertainty;')\n    elif variant=='slow':\n        s=s.replace(marker,'        pHat = _dualAnchor(pHat, sigmaHat, trade.timestamp);\\n\\n'+marker)\n    else:\n        s=s.replace('            uint256 staleTox =', '            staleHat = _dualAnchor(staleHat, sigmaHat, trade.timestamp);\\n            uint256 staleTox =')\n    helper='''    function _dualAnchor(uint256 estimate, uint256 sigma, uint256 timestamp) internal view returns (uint256) {\n        uint256 packed = slots[11];\n        uint256 anchor = packed >> 64;\n        if (anchor == 0) return estimate;\n        uint256 age = timestamp - uint64(packed);\n        // Linear widening by k*sigmaHat for each elapsed step.\n        uint256 width = 30 * BPS + wmul(ANCHOR_K, sigma) * age;\n        // Once the band covers +/-100%, this observation is uninformative.\n        if (width >= WAD) return estimate;\n        uint256 lo = wmul(anchor, WAD-width);\n        uint256 hi = wmul(anchor, WAD+width);\n        uint256 clipped = estimate < lo ? lo : (estimate > hi ? hi : estimate);\n        return _blend(estimate, clipped, ANCHOR_WEIGHT);\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 json,time,itertools,hashlib\nfrom pathlib import Path\nfrom harness import *\nfrom dual_anchor import generate\n\ndef gas(a):\n rows=a['raw_counters'];sub=[r for r in rows if r['role']=='Submission']\n return {'max_ok':max((r['max_ok_gas'] for r in sub if r['callback']=='afterSwap'),default=0),\n 'init_max_ok':max((r['max_ok_gas'] for r in sub if r['callback']=='afterInitialize'),default=0),\n 'oog':sum(r.get('oog',0) for r in rows),\n 'other_errors':sum(sum(r.get(e,0) for e in ['revert','other_halt','tx_error','bad_return']) for r in rows)}\ndef valid(g):return g['max_ok']<235000 and g['init_max_ok']<245000 and not g['oog'] and not g['other_errors']\n\ndef main():\n base=Path('scratch/RS2.sol').read_text(); c=SolidityCompiler()\n v=c.compile(Path('contracts/src/VanillaStrategy.sol').read_text(),'VanillaStrategy').bytecode\n rng=np.random.default_rng(85)\n grid=[{'w':w,'k':k,'variant':variant} for w,k,variant in itertools.product([.01,.02,.05,.1,.25,.5,.75,1.],[0,.25,.5,1.,2.,4.,8.],['fast','slow','stale'])]\n rng.shuffle(grid)\n starts=[980000+64*int(i) for i in rng.choice(46,size=6,replace=False)]\n cache={};logs=[];t=time.monotonic();idx=0\n while time.monotonic()-t<1500:\n  if idx>=len(grid):break\n  p=grid[idx];start=starts[(idx//9)%len(starts)]\n  if start not in cache:\n   cache[start]=run(base,start,64,v,c)\n   Path(f'scratch/search_base_{start}.json').write_text(json.dumps(cache[start]))\n   assert valid(gas(cache[start])),gas(cache[start])\n  source=generate(base,**p)\n  a=run(source,start,64,v,c);g=gas(a);summary=compare(a,cache[start])\n  row={'evaluation':idx+1,'params':p,'start':start,'n':64,**summary,'gas':g,'valid':valid(g),'elapsed_seconds':time.monotonic()-t,'sha256':a['sha256']}\n  logs.append(row)\n  Path(f'scratch/search_arm_{idx+1}.json').write_text(json.dumps(a))\n  Path('scratch/search_log.json').write_text(json.dumps({'seed':85,'target_seconds':1500,'elapsed_seconds':time.monotonic()-t,'grid_size':len(grid),'blocks':starts,'evaluations':logs}))\n  print(json.dumps(row),flush=True);idx+=1\n print('SEARCH_DONE',len(logs),time.monotonic()-t,flush=True)\nif __name__=='__main__':main()\n","confirmation_source":"import json,time,hashlib\nfrom pathlib import Path\nfrom harness import *\nfrom dual_anchor import generate\nfrom search import gas,valid\n\ndef save(name,x):Path('scratch/'+name+'.json').write_text(json.dumps(x,allow_nan=False))\ndef main():\n base=Path('scratch/RS2.sol').read_text();c=SolidityCompiler()\n v=c.compile(Path('contracts/src/VanillaStrategy.sol').read_text(),'VanillaStrategy').bytecode\n log=json.loads(Path('scratch/search_log.json').read_text())\n rows=sorted((r for r in log['evaluations'] if r['valid']),key=lambda r:r['paired']['mean_diff'],reverse=True)\n # Neutral is verified separately. Rank active mechanisms to measure even a loss.\n top=rows[:3];baseline=run(base,983000,256,v,c);save('recheck_base',baseline)\n assert valid(gas(baseline)),gas(baseline)\n print('RECHECK_BASE_DONE',gas(baseline),flush=True)\n checks=[]\n for rank,r in enumerate(top):\n  source=generate(base,**r['params']);a=run(source,983000,256,v,c);save('recheck_'+str(rank),a)\n  record={'params':r['params'],'search_evaluation':r['evaluation'],**compare(a,baseline),'gas':gas(a),'sha256':a['sha256'],'valid':valid(gas(a))}\n  checks.append(record);save('recheck_summary',checks);print('RECHECK',json.dumps(record),flush=True)\n best=max((r for r in checks if r['valid']),key=lambda r:r['paired']['mean_diff'])\n frozen=generate(base,**best['params']);Path('scratch/frozen.sol').write_text(frozen)\n save('freeze',{'params':best['params'],'sha256':hashlib.sha256(frozen.encode()).hexdigest(),'chosen_on':'983000..983255','held_out':'984000..984511','stack_confirmation':'5800000..5801999','recheck':best,'selection':'best active mechanism; neutral is a separate control'})\n print('FROZEN',best['params'],flush=True)\n a=run(frozen,984000,512,v,c);save('held_candidate',a);print('HELD_CANDIDATE_DONE',gas(a),flush=True)\n b=run(base,984000,512,v,c);save('held_rs2',b)\n held={**compare(a,b),'candidate_gas':gas(a),'rs2_gas':gas(b),'valid':valid(gas(a)) and valid(gas(b))}\n save('held_summary',held);print('HELD_SUMMARY',json.dumps(held),flush=True)\n # A single independent fresh confirmation against the goal's pinned STACK.\n a=run(frozen,5800000,2000,v,c);save('stack_candidate',a);print('STACK_CANDIDATE_DONE',gas(a),flush=True)\n b=run(Path('scratch/STACK.sol').read_text(),5800000,2000,v,c);save('stack_baseline',b)\n result={**compare(a,b),'candidate_gas':gas(a),'stack_gas':gas(b),'valid':valid(gas(a)) and valid(gas(b))}\n save('stack_summary',result);print('STACK_SUMMARY',json.dumps(result),flush=True)\nif __name__=='__main__':main()\n","notes":["All numerical performance and gas results are local measurements, not claims of a leaderboard submission or top-10 placement. SE is paired sample standard deviation (ddof=1) divided by sqrt(n); worst lists the five smallest candidate-minus-baseline seed deltas.","Each strategy ran alone against fixed-30-bps VanillaStrategy, using amm_sim_rs.run_batch with 8 workers and the supplied MatchRunner-compatible config construction. Gas counters include both market roles and all callback failures, with resets at <=20 seeds.","The mechanism uses only observable own-pool history. A first fill in a step cannot reliably be classified as retail and is excluded; later fills are retail, but the >30 bps guard is an interior-routing heuristic inherited from RS2. Corner routes and retail movement of Vanilla can violate the nominal fair-price band, so this interval is an estimator assumption, not a guaranteed bound.","Fast and slow variants modify their stored estimates; stale modifies only the price used for the stale-side fee decision. Sigma uses the current RS2 sigmaHat. Widening is linear in elapsed steps, not square-root time; a width >=100% disables the pull. The cached price/timestamp uses slot 11, unused at REVERT_U=0; initialization is unchanged.","w=0 emits the exact original RS2 source and was checked on 984600..984631. Active w=1,k=1 versions were also checked on these seeds solely for compilation/gas diagnostics; their returns were not used to rank the search.","The top three active candidates were rechecked on 983000..983255, then one source/hash was frozen before running 984000..984511 and the fresh 2000-seed STACK confirmation. Neutral was retained as a separate control rather than allowed to hide a measured active-mechanism loss.","No parameter or code change followed freezing. The broad goal STACK comparison is separate from the item-specific RS2 held-out comparison; top-level retail/arb deltas refer to RS2, and top-level paired refers to STACK.","Generator accepts the exact RS2 code identified by checks.baseline. Its neutral setting is generate(base,w=0); frozen settings are generate(base,**params). The embedded generator and harness, together with the search grid, seed, blocks and selection protocol, document reproducibility in the supplied pinned challenge environment; temporary setup dependencies are not part of the delivered Solidity.","Held-out measured gain versus RS2; interpret together with paired SE and the independent STACK comparison."]}