{"item":"b","batch":"e08-arb-surge","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 = 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        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            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        // Arbitrage-streak surge: slots[16] = count | dir << 64 | lastTs << 72 | marker << 200.\n        {\n            uint256 streak = slots[16];\n            uint256 arbCount = uint64(streak);\n            uint256 arbDir = uint8(streak >> 64);\n            if (firstInStep) {\n                if (arbProbability > WAD / 2) {\n                    uint256 d = trade.isBuy ? 1 : 2;\n                    if (d == arbDir && trade.timestamp <= uint64(streak >> 72) + 3) arbCount += 1;\n                    else arbCount = 1;\n                    arbDir = d;\n                } else {\n                    arbCount = 0;\n                }\n                slots[16] = arbCount | (arbDir << 64) | (trade.timestamp << 72) | (uint256(1) << 200);\n            }\n            if (arbCount > 5) {\n                if (arbDir == 1) {\n                    bidFee = clampFee(bidFee + 42781456674494);\n                    askFee = askFee > 22204437666516 ? askFee - 22204437666516 : 0;\n                } else {\n                    askFee = clampFee(askFee + 42781456674494);\n                    bidFee = bidFee > 22204437666516 ? bidFee - 22204437666516 : 0;\n                }\n            }\n        }\n\n        slots[0] = bidFee; slots[1] = askFee; slots[2] = (spot << 64) | trade.timestamp;\n        slots[3] = dirState; slots[4] = actEma; slots[5] = pHat;\n        slots[6] = sigmaHat; slots[7] = lambdaHat; slots[8] = sizeHat;\n        slots[9] = toxEma; slots[10] = stepTradeCount;\n\n        return (bidFee, askFee);\n    }\n\n\n    struct PosteriorInput {\n        uint256 mu; uint256 v; uint256 obs; uint256 spot; uint256 preSpot;\n        uint256 bid; uint256 ask; bool first; uint256 silent; bool buy; uint256 size;\n    }\n    function _posterior(PosteriorInput memory x) internal pure returns (uint256, uint256, 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":"c7a761eddb9fd935874022fc790787548c2dd4da20e7c655b50fc7a2954939da","params":{"n":5,"b_bps":0.42781456674493684,"r":0.5190201407927721,"G":3,"order":["n","b_bps","r","G"],"exact":[5,0.42781456674493684,0.5190201407927721,3],"emitted_constants_wei":{"bump":42781456674494,"discount":22204437666516}},"mechanism":"One new slot (slots[16]) counts consecutive steps whose first print RS2's posterior classes as arbitrage (arbProbability > 0.5) in the same direction, resetting to 0 on a retail-classified first print and restarting at 1 on a direction change or when the previous arbitrage first print is more than G steps back. While the count exceeds n, the fee on the side the arbitrage keeps hitting is raised by b bps and the other side is lowered by r*b bps, applied after RS2's own fee caps.","source":{"url":"https://benedict.dev/optimization-arena-learnings","quote":"fee += SURGE_BUMP * (arbCou","rendered_line":"if (arbCount > 3) fee += SURGE_BUMP * (arbCou","note":"The fragment is one line of decorative code in an SVG figure and is cut off on the page after '(arbCou'. In the page HTML the '>' is written as '&gt;' between React comment markers, so the contiguous literal text is the shorter quote. No prose on the page explains the fragment; the nearest prose is 'estimating probabilities of arb trades and skewing based on information from the arbs'. The cut-off continuation suggests the original bump scales with a count expression; that scaled form was not tested (the brief fixes a flat b)."},"search":{"method":"CMA-ES, own numpy implementation, np.random.default_rng(91), pop 8, mu 4, initial sigma 0.25 on the [0,1]^4 box (clipped): n=1+round(5*x0), b=10*x1 bps, r=x2, G=1+round(7*x3). Initial mean n=3, b=2.5, r=0.5, G=3. Generation g used the fresh 64-seed block 666100+64*g, RS2 run once per block; fitness = paired mean edge diff vs RS2; an invalid arm would score -1000 (none occurred).","generations":10,"blocks":[666100,666739],"wall_seconds":1693.3521211147308,"budget_seconds":1500,"points_sampled":80,"evaluations":47,"evaluations_with_b_gt_0":44,"neutral_points_simulated":3,"neutral_points_not_simulated":33,"positive_evaluations":4,"best":{"params":[5,0.6426114393324349,0.6172238665248221,6],"sha256":"424becfc15b707d226ffc5614060be23bcb432704a33ea3c55aacdd43b79056c","block":[666292,666355],"n":64,"mean_diff":0.04537362198128303,"se":0.01839048597412393,"retail_edge_delta":-0.06783515428520559,"arb_edge_delta":0.11320877626648335},"final_cma_mean":{"params":[4,0.004443762607366439,0.3729083451515684,5],"sigma":0.1358096913397619},"by_bump_size":[{"b_bps_range":[0,0.5],"evaluations":8,"mean_of_mean_diff":-0.00505888,"mean_retail_delta":-0.064267,"mean_arb_delta":0.0592081,"positive":1},{"b_bps_range":[0.5,1],"evaluations":10,"mean_of_mean_diff":-0.0131307,"mean_retail_delta":-0.189796,"mean_arb_delta":0.176665,"positive":3},{"b_bps_range":[1,2],"evaluations":13,"mean_of_mean_diff":-0.0527463,"mean_retail_delta":-0.347589,"mean_arb_delta":0.294842,"positive":0},{"b_bps_range":[2,4],"evaluations":9,"mean_of_mean_diff":-0.114895,"mean_retail_delta":-0.580295,"mean_arb_delta":0.4654,"positive":0},{"b_bps_range":[4,10],"evaluations":4,"mean_of_mean_diff":-0.583376,"mean_retail_delta":-1.80611,"mean_arb_delta":1.22274,"positive":0}],"max_ok_over_all_evals":222703,"init_max_ok_over_all_evals":243103,"oog_total":0,"halts_total":0,"log_columns":["gen","n","b_bps","r","G","mean_diff","se","retail_delta","arb_delta","max_ok","simulated"],"log":[[0,3,4.31122,0.171969,2,-0.345694,0.0577026,-1.22474,0.87905,222608,true],[0,4,1.96101,0.423929,3,-0.092347,0.0336639,-0.452138,0.359791,222599,true],[0,2,1.01919,0.664768,4,-0.121594,0.0340221,-0.466756,0.345162,222608,true],[0,3,6.02214,0.291566,4,-0.559355,0.0948961,-1.78975,1.2304,222599,true],[0,4,7.12086,0.628233,3,-0.618436,0.0889577,-1.60013,0.981691,222599,true],[0,4,2.68252,0.634056,5,-0.150342,0.0418546,-0.638627,0.488286,222599,true],[0,3,2.51109,0.620194,4,-0.205963,0.0402988,-0.812737,0.606774,222599,true],[0,2,0.614459,0.822498,5,-0.0670594,0.0249492,-0.275834,0.208774,222608,true],[1,1,0.775791,0.675431,4,0.0121103,0.0376363,-0.361703,0.373813,219751,true],[1,1,0.0,0.937196,4,0.0,0.0,0.0,0.0,219756,true],[1,4,1.27235,0.229059,4,-0.00731093,0.026227,-0.268281,0.26097,219754,true],[1,2,6.86999,0.294955,5,-0.810017,0.10837,-2.60983,1.79981,219763,true],[1,1,1.40934,0.782782,4,-0.080209,0.0503506,-0.711202,0.630993,219751,true],[1,5,0.0,0.790251,2,0.0,0.0,0.0,0.0,219754,true],[1,4,0.0,1.0,5,0.0,0.0,0.0,0.0,219754,true],[1,4,0.795071,0.801113,6,0.0226561,0.0251712,-0.137711,0.160367,219754,true],[2,3,0.0,0.648584,5,0.0,0.0,0.0,0.0,null,false],[2,5,0.0,0.614753,3,0.0,0.0,0.0,0.0,null,false],[2,5,1.05678,0.725857,7,-0.0453943,0.0246008,-0.21351,0.168116,222587,true],[2,3,0.435654,0.582983,7,-0.0357848,0.01941,-0.149357,0.113573,222587,true],[2,2,0.117369,0.801982,5,-0.00722323,0.0111986,-0.0410433,0.0338201,222596,true],[2,3,0.0,0.590993,6,0.0,0.0,0.0,0.0,null,false],[2,2,0.0,0.621395,4,0.0,0.0,0.0,0.0,null,false],[2,5,0.0,0.607944,4,0.0,0.0,0.0,0.0,null,false],[3,5,0.642611,0.617224,6,0.0453736,0.0183905,-0.0678352,0.113209,219650,true],[3,3,0.0,0.663641,5,0.0,0.0,0.0,0.0,null,false],[3,4,0.0,0.744552,7,0.0,0.0,0.0,0.0,null,false],[3,5,0.427815,0.51902,3,0.029827,0.0129313,-0.0375599,0.0673869,219650,true],[3,4,2.20794,0.760511,3,-0.0952121,0.0340219,-0.496956,0.401744,219650,true],[3,3,0.0,0.652621,3,0.0,0.0,0.0,0.0,null,false],[3,5,1.27385,0.63791,3,-0.0222167,0.0317119,-0.205175,0.182958,219650,true],[3,4,1.44251,0.578122,7,-0.0442245,0.030914,-0.327874,0.28365,219650,true],[4,3,3.2027,0.883266,8,-0.221942,0.062891,-1.02316,0.801213,219767,true],[4,5,0.0,0.520436,4,0.0,0.0,0.0,0.0,null,false],[4,4,2.5439,0.482242,3,-0.116455,0.04727,-0.594984,0.478529,219767,true],[4,5,1.56617,0.56911,4,-0.0484069,0.0333491,-0.306371,0.257965,219767,true],[4,5,1.07495,0.46708,6,-0.0252486,0.0214783,-0.213385,0.188137,219767,true],[4,5,2.72456,0.65575,6,-0.0730496,0.0424666,-0.494507,0.421457,219767,true],[4,4,1.45442,0.817281,4,-0.0725826,0.0298171,-0.369007,0.296424,219767,true],[4,6,3.05104,0.506089,5,-0.0737579,0.0378918,-0.417426,0.343668,219767,true],[5,4,1.25266,0.311794,5,-0.0185661,0.0372555,-0.271323,0.252757,219766,true],[5,4,0.0,0.521431,3,0.0,0.0,0.0,0.0,null,false],[5,6,0.0,0.248763,5,0.0,0.0,0.0,0.0,null,false],[5,6,0.0,0.567241,6,0.0,0.0,0.0,0.0,null,false],[5,5,2.38588,0.580367,7,-0.0606191,0.0369809,-0.414867,0.354248,219766,true],[5,5,0.0,0.465191,6,0.0,0.0,0.0,0.0,null,false],[5,5,0.887074,0.706825,3,-0.00894648,0.0223726,-0.155421,0.146474,219766,true],[5,6,2.64705,0.447252,5,-0.0367122,0.0365898,-0.329391,0.292678,219766,true],[6,4,0.602341,0.329,2,-0.0151954,0.0173296,-0.126343,0.111148,219764,true],[6,5,0.0,0.445264,4,0.0,0.0,0.0,0.0,null,false],[6,3,0.0,0.401295,5,0.0,0.0,0.0,0.0,null,false],[6,4,0.0,0.149127,3,0.0,0.0,0.0,0.0,null,false],[6,5,0.0,0.444969,7,0.0,0.0,0.0,0.0,null,false],[6,3,0.0,0.536226,3,0.0,0.0,0.0,0.0,null,false],[6,5,0.0,0.339368,4,0.0,0.0,0.0,0.0,null,false],[6,4,0.0,0.514073,3,0.0,0.0,0.0,0.0,null,false],[7,4,1.30486,0.55062,4,-0.0448007,0.0310976,-0.291388,0.246587,222679,true],[7,3,0.0,0.413047,4,0.0,0.0,0.0,0.0,null,false],[7,2,0.0,0.374265,5,0.0,0.0,0.0,0.0,null,false],[7,5,0.0,0.57881,5,0.0,0.0,0.0,0.0,null,false],[7,6,0.0,0.13713,5,0.0,0.0,0.0,0.0,null,false],[7,4,0.0,0.478318,5,0.0,0.0,0.0,0.0,null,false],[7,6,0.802207,0.256876,6,-0.0432112,0.018237,-0.140439,0.0972281,222679,true],[7,4,0.307588,0.474146,4,-0.00800215,0.0127875,-0.0752561,0.067254,222679,true],[8,4,0.0,0.372176,6,0.0,0.0,0.0,0.0,null,false],[8,3,0.0,0.495325,4,0.0,0.0,0.0,0.0,null,false],[8,3,0.0,0.304675,5,0.0,0.0,0.0,0.0,null,false],[8,2,0.587091,0.550648,4,-0.0395504,0.0201491,-0.260926,0.221376,222608,true],[8,3,0.0,0.425123,5,0.0,0.0,0.0,0.0,null,false],[8,4,0.36876,0.268923,5,-0.00326827,0.012551,-0.0792691,0.0760009,222599,true],[8,4,0.0,0.526693,5,0.0,0.0,0.0,0.0,null,false],[8,3,0.0,0.231604,5,0.0,0.0,0.0,0.0,null,false],[9,3,0.328128,0.434354,4,-0.0109959,0.0177986,-0.107071,0.0960749,222703,true],[9,3,0.00935178,0.620409,6,-0.00148116,0.0027229,-0.00404293,0.00256177,222703,true],[9,3,0.616913,0.449247,5,-0.0167082,0.0230487,-0.193039,0.176331,222703,true],[9,5,0.958655,0.556524,5,-0.0207761,0.0196691,-0.178707,0.157931,222703,true],[9,3,0.0748895,0.348039,4,-0.00354248,0.00670565,-0.0205365,0.016994,222703,true],[9,3,0.0,0.467601,5,0.0,0.0,0.0,0.0,null,false],[9,4,0.0,0.257082,5,0.0,0.0,0.0,0.0,null,false],[9,3,1.30292,0.43175,6,-0.062801,0.0332489,-0.422243,0.359442,222703,true]]},"recheck":[{"params":[5,0.6426114393324349,0.6172238665248221,6],"sha256":"424becfc15b707d226ffc5614060be23bcb432704a33ea3c55aacdd43b79056c","search_mean_diff":0.04537362198128303,"search_se":0.01839048597412393,"search_block":[666292,666355],"seeds":[669000,669255],"n":256,"mean_diff":-0.0039590582667166085,"se":0.008248813006648146,"retail_edge_delta":{"mean":-0.107661729047138,"se":0.00847121584502573},"arb_edge_delta":{"mean":0.10370267078042394,"se":0.0029896829935868036},"max_ok":222586,"init_max_ok":243090,"oog":0,"halts":0,"frozen":false},{"params":[5,0.42781456674493684,0.5190201407927721,3],"sha256":"c7a761eddb9fd935874022fc790787548c2dd4da20e7c655b50fc7a2954939da","search_mean_diff":0.029826986553027623,"search_se":0.012931344018431162,"search_block":[666292,666355],"seeds":[669000,669255],"n":256,"mean_diff":-0.000503628777101861,"se":0.006454037445852831,"retail_edge_delta":{"mean":-0.0647714474275245,"se":0.006801175843373413},"arb_edge_delta":{"mean":0.0642678186504232,"se":0.002358829199193386},"max_ok":222586,"init_max_ok":243090,"oog":0,"halts":0,"frozen":true},{"params":[4,0.7950710414693041,0.8011132718473855,6],"sha256":"a90c511cc2dd448cd4e32ca49cb7913523da13da62849af71d2a5be35bb2e518","search_mean_diff":0.022656114312909814,"search_se":0.025171185829733073,"search_block":[666164,666227],"seeds":[669000,669255],"n":256,"mean_diff":-0.0009508045187436309,"se":0.013914250741305397,"retail_edge_delta":{"mean":-0.16916063399313486,"se":0.014888693699622606},"arb_edge_delta":{"mean":0.16820982947439478,"se":0.0037962421849432513},"max_ok":222586,"init_max_ok":243090,"oog":0,"halts":0,"frozen":false}],"freeze":{"sha256":"c7a761eddb9fd935874022fc790787548c2dd4da20e7c655b50fc7a2954939da","timestamp_utc":"2026-11-09T03:48:46Z","rule":"Top 3 search scores among points with b > 0 (b = 0 is RS2 itself) rechecked on 669000..669255; the one with the highest recheck mean was frozen before any held-out run. All three rechecks are within one standard error of zero, so the choice is not a meaningful ranking.","amm_match_validate":"passed"},"held_out":{"seeds":{"first":669400,"last":669911,"n":512},"baseline":"RS2","n":512,"mean_diff":-0.0032609272859467353,"se":0.004731368594997851,"worst":[{"seed":669784,"d":-0.46353628257918444},{"seed":669588,"d":-0.4236318781170212},{"seed":669465,"d":-0.3192911374206915},{"seed":669431,"d":-0.3135023982868006},{"seed":669909,"d":-0.31096765421523287}],"arm_mean_edge":{"frozen":517.786623354551,"rs2":517.789884281837,"stack":517.4718931704072},"arm_sha256":{"frozen":"c7a761eddb9fd935874022fc790787548c2dd4da20e7c655b50fc7a2954939da","rs2":"f24b6ca198b744c380842c3a17964a6dc21f311bb04984b26733afa3fee8eaf2","stack":"2eaafc7960e520b8a7fd322ec8afaff8fa677c730228a961efb509cc30b25719"},"reconciliation_max_abs":1.0658141036401503e-13,"context_vs_stack_same_block":{"note":"Not the goal confirmation (that needs a fresh >=2000-seed block from 5000000 up, not run here).","frozen_minus_stack":{"mean_diff":0.3147301841439415,"se":0.02679124970189787,"retail_edge_delta":{"mean":0.296007899164366,"se":0.02627073251990976},"arb_edge_delta":{"mean":0.018722284979578195,"se":0.01160466139269404}},"rs2_minus_stack":{"mean_diff":0.31799111142988823,"se":0.02651127075134119,"retail_edge_delta":{"mean":0.3669808999366988,"se":0.026112999708251615},"arb_edge_delta":{"mean":-0.04898978850680822,"se":0.011561907301113653}}}},"retail_edge_delta":{"mean":-0.07097300077233282,"se":0.004882717528616717},"arb_edge_delta":{"mean":0.06771207348638641,"se":0.0016933363901145786},"gas":{"max_ok":222703,"init_max_ok":243090,"oog":0,"other_halts":0,"scope":"frozen strategy over its search block, recheck block and held-out block","held_out":{"frozen":{"max_ok":222703,"init_max_ok":243090,"oog":0,"halts":0,"valid":true},"rs2":{"max_ok":200268,"init_max_ok":243099,"oog":0,"halts":0,"valid":true},"stack":{"max_ok":211588,"init_max_ok":220962,"oog":0,"halts":0,"valid":true}},"limits_checked":{"afterSwap_max_ok_lt":235000,"init_lt":245000},"rs2_recheck_max_ok":200510},"checks":{"calibration_CH":{"url":"https://raw.githubusercontent.com/ChengHua926/amm-challenge/d34a5199c59a4c44d5336a25f1436b4ae1f21104/contracts/src/Strategy.sol","sha256":"6dd68f77a70900319460215374143dbd5d924198450a46d9f5f91f6b1e3d35c3","seeds":[0,999],"n":1000,"mean_edge":525.5258821780834,"expected":525.5258821780834,"exact_match":true},"rs2_sha256_verified":true,"stack_sha256_verified":true,"neutral_parity":{"params":[3,0,0.5,2],"neutral_sha256":"2598dc6279781daed9820e04d2acc9a20fd97e0739cc9e99c2f4df5f756ee860","seeds":[669950,669981],"n":32,"exact_equal_edges":true,"max_abs_diff":0.0,"gas":{"neutral_max_ok":219755,"neutral_init_max_ok":243103,"rs2_max_ok":197277,"rs2_init_max_ok":243099},"also":"3 further b=0 points simulated in search generation 1 (block 666164..666227) gave exactly 0.0 per seed mean and se."},"frozen_rebuilt_from_generator":true},"generator_source":"\"\"\"Arbitrage-streak surge generator on RS2.  params = (n, b_bps, r, G).\"\"\"\nANCHOR = \"        slots[0] = bidFee; slots[1] = askFee; slots[2] = (spot << 64) | trade.timestamp;\"\n\ndef generate(base, p):\n    n, b, r, G = p\n    n = int(round(n)); G = int(round(G))\n    B = int(round(float(b) * 1e14))          # b bps in WAD (BPS = 1e14)\n    RB = int(round(float(r) * float(b) * 1e14))\n    assert base.count(ANCHOR) == 1\n    insert = f'''        // Arbitrage-streak surge: slots[16] = count | dir << 64 | lastTs << 72 | marker << 200.\n        {{\n            uint256 streak = slots[16];\n            uint256 arbCount = uint64(streak);\n            uint256 arbDir = uint8(streak >> 64);\n            if (firstInStep) {{\n                if (arbProbability > WAD / 2) {{\n                    uint256 d = trade.isBuy ? 1 : 2;\n                    if (d == arbDir && trade.timestamp <= uint64(streak >> 72) + {G}) arbCount += 1;\n                    else arbCount = 1;\n                    arbDir = d;\n                }} else {{\n                    arbCount = 0;\n                }}\n                slots[16] = arbCount | (arbDir << 64) | (trade.timestamp << 72) | (uint256(1) << 200);\n            }}\n            if (arbCount > {n}) {{\n                if (arbDir == 1) {{\n                    bidFee = clampFee(bidFee + {B});\n                    askFee = askFee > {RB} ? askFee - {RB} : 0;\n                }} else {{\n                    askFee = clampFee(askFee + {B});\n                    bidFee = bidFee > {RB} ? bidFee - {RB} : 0;\n                }}\n            }}\n        }}\n\n'''\n    return base.replace(ANCHOR, insert + ANCHOR)\n","notes":["Result: no gain. Held-out 669400..669911 (n 512, run once per arm after the freeze): frozen - RS2 = -0.0033 (se 0.0047); retail edge -0.0710 (se 0.0049), arb edge +0.0677 (se 0.0017). The surge removes arbitrage loss as intended but gives back the same amount of retail edge.","Search: 4 of 44 simulated points with b > 0 beat RS2 on their 64-seed block (best +0.0454, se 0.0184); losses grow with b (see search.by_bump_size) and in every evaluation the arb edge rose and the retail edge fell. The CMA mean drifted to the b = 0 bound, i.e. to RS2 itself. The three best points all rechecked at about zero (-0.0040, -0.0005, -0.0010 on 256 seeds), which is what block noise in the search scores would look like.","Recommendation: keep RS2 (sha256 f24b6ca1...) as the working strategy; the frozen code here is a measured null, not an improvement. Nothing here moves the goal's +5.0 over STACK.","Implementation choices not fixed by the brief: (a) the surge is applied at the end of afterSwap, after RS2's tail compression and its 30/36 bps low-side caps, with clampFee on the raised side and a floor of 0 on the lowered side; (b) streak state changes only on the first print of a step, later prints in the step keep the surge; (c) 'gap' is the timestamp difference between successive arbitrage-classified first prints, and a streak continues only if it is <= G (G = 1 means strictly consecutive steps); (d) slots[16] packs count | direction << 64 | timestamp << 72 plus a marker bit at 200, and afterInitialize is unchanged (no new slot written there). Placement before the caps was not tested.","Departures from the brief's search plan, all disclosed: the search ran 1693 s of measured wall time rather than 1500 s (the stop is checked between generations and generation 9 started at 1487 s); after generation 1, points whose b rounds to 0 wei were scored 0.0 without simulation (33 points) because they emit RS2's fees exactly, as the parity check and 3 simulated b = 0 points confirmed; before the search one probe (n 3, b 5, r 0.5, G 2) on the parity block 669950..669981 measured -0.472 (se 0.103) and was used to check timing and to start the CMA mean at b = 2.5 rather than mid-box.","Gas: the surge adds about 22k to the afterSwap peak (RS2 200,268 and 200,510 on the held-out and recheck blocks, frozen 222,703 and 222,586), consistent with the first write to the new slot; this was not profiled per opcode. No halt of any kind in any arm; all evaluations stayed under 235,000 afterSwap and 245,000 afterInitialize.","Method: each arm alone against VanillaStrategy via amm_sim_rs.run_batch(...,8) in 20-seed chunks with gas_stats_reset()/gas_stats() per chunk, configs as in the harness_source of artifact 33f54e81..., se = sd(ddof=1)/sqrt(n), arb/retail split by that harness's reconstruction, no seed dropped. Simulator wheel and repo commit as pinned in the brief; setup script ran without error.","Seeds used: 0..999 (calibration), 669950..669981 (parity and one probe), 666100..666739 (search), 669000..669255 (recheck), 669400..669911 (held-out). No seed from 5000000 up was used, so there is no STACK confirmation and no board claim; the STACK figures in held_out.context_vs_stack_same_block are context only."]}