{
 "item": "e08-sticky-dev/b",
 "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        uint256 sticky;\n        {\n            sticky = slots[16];\n            if (isNewStep) {\n                uint256 el = trade.timestamp - lastTs;\n                if (el > ELAPSED_CAP) el = ELAPSED_CAP;\n                sticky = wmul(sticky, _powWad(514774297777618944, el));\n            }\n            if (tox > sticky) sticky = tox;\n            slots[16] = sticky;\n        }\n        toxSignal = wmul(toxEma, 1000000000000000000) + wmul(sticky, 0);\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        fMid = fMid + wmul(7317663678107785216, wmul(toxSignal, wmul(toxSignal, 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            staleTox = wmul(staleTox, 950852009613053440) + wmul(sticky, 49147990386946632);\n            if (staleTox > TOX_CAP) staleTox = TOX_CAP;\n            uint256 staleShift = wmul(STALE_DIR_COEF, staleTox);\n            uint256 attractShift = wmul(staleShift, STALE_ATTRACT_FRAC);\n            if (spot >= staleHat) {\n                bidFee = bidFee + staleShift;\n                askFee = askFee > attractShift ? askFee - attractShift : 0;\n            } else {\n                askFee = askFee + staleShift;\n                bidFee = bidFee > attractShift ? bidFee - attractShift : 0;\n            }\n        }\n\n        {\n            bool tradeAligned = (trade.isBuy && spot >= pHat) || (!trade.isBuy && spot < pHat);\n            if (tradeAligned) {\n                uint256 tradeBoost = wmul(TRADE_TOX_BOOST, tradeRatio);\n                if (!firstInStep && tradeBoost > 16 * BPS) tradeBoost = 16 * BPS;\n                if (trade.isBuy) { bidFee = bidFee + tradeBoost; }\n                else { askFee = askFee + tradeBoost; }\n            }\n        }\n\n        if (sellPressure) {\n            bidFee = clampFee(_compressTailWithSlope(bidFee, TAIL_SLOPE_PROTECT));\n            askFee = clampFee(_compressTailWithSlope(askFee, TAIL_SLOPE_ATTRACT));\n        } else {\n            askFee = clampFee(_compressTailWithSlope(askFee, TAIL_SLOPE_PROTECT));\n            bidFee = clampFee(_compressTailWithSlope(bidFee, TAIL_SLOPE_ATTRACT));\n        }\n\n        if (firstInStep) {\n            if (askFee > bidFee && bidFee > 30 * BPS) bidFee = 30 * BPS;\n            else if (bidFee > askFee && askFee > 30 * BPS) askFee = 30 * BPS;\n        }\n\n        if (bidFee > askFee && askFee > 36 * BPS) askFee = 36 * BPS;\n        else if (askFee > bidFee && bidFee > 36 * BPS) bidFee = 36 * BPS;\n\n        slots[0] = bidFee; slots[1] = askFee; slots[2] = (spot << 64) | trade.timestamp;\n        slots[3] = dirState; slots[4] = actEma; slots[5] = pHat;\n        slots[6] = sigmaHat; slots[7] = lambdaHat; slots[8] = sizeHat;\n        slots[9] = toxEma; slots[10] = stepTradeCount;\n\n        return (bidFee, askFee);\n    }\n\n\n    struct PosteriorInput {\n        uint256 mu; uint256 v; uint256 obs; uint256 spot; uint256 preSpot;\n        uint256 bid; uint256 ask; bool first; uint256 silent; bool buy; uint256 size;\n    }\n    function _posterior(PosteriorInput memory x) internal pure returns (uint256, uint256, 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": "d8501ff2a2b9307ba02e137ad90ece8e644b9c42fb17071d2f947349688d5ea0",
 "params": {
  "d": 0.514774297777619,
  "w_fee": 0.0,
  "w_stale": 0.04914799038694663,
  "c3_cubic_coef": 7.3176636781077855
 },
 "parameter_notes": "d = per-step retention of the peak-hold, applied as d^min(elapsed,8) on each new step; w_fee = weight of sticky in toxSignal (feeds TOX_COEF, TOX_QUAD_COEF, SIGMA_TOX_COEF and DIR_TOX_COEF skew); w_stale = weight of sticky in the stale-side shift magnitude; c3 = WAD coefficient of a NEW cubic term c3*toxSignal^3 added to fMid. RS2 has no cubic toxicity term (only linear+quadratic), so the brief's 'multiplier on the cubic term' was implemented as the coefficient of an added cubic term, neutral 0.",
 "mechanism": "A new slot (slots[16]) holds a peak of the instantaneous deviation tox=|spot-pHat|/pHat (capped at TOX_CAP): sticky = max(tox, sticky*d^elapsed), which decays only on new steps. (1-w_fee)*toxEma + w_fee*sticky replaces toxEma in the toxicity fee terms, (1-w_stale)*staleTox + w_stale*sticky replaces staleTox in the stale-side shift, and an optional cubic toxicity term c3*toxSignal^3 is added to the mid fee.",
 "source": {
  "url": "https://benedict.dev/optimization-arena-learnings",
  "quote": "uint256 stickyDev = max(dev, wmul(STICKY_D,",
  "context": "The fragment appears only as one truncated line of a decorative code figure in the section 'Distilling Insights from Optimized Code' (caption: '8 wildly different implementations should distill down to a few shared insights'). The page gives no decay value, no description of how stickyDev is used, and nothing about a cubic term; this mechanism's details are our own design from the brief."
 },
 "neutral_check": {
  "seeds": "649950..649981",
  "n": 32,
  "setting": "w_fee=0,w_stale=0,c3=0 with the sticky code path forced in (d=0.9)",
  "max_abs_edge_diff_vs_rs2": 0.0,
  "also": "with the default (unforced) neutral setting the generator returns RS2 byte for byte"
 },
 "search": {
  "method": "CMA-ES (own numpy implementation, default_rng(89), pop 8, mu 4) over [d 0.5..0.99, w_fee 0..1, w_stale, c3] in a [0,1]-normalized box; each generation used a fresh 64-seed block 646100+64*gen, with RS2 run once per block; fitness = paired mean edge diff vs RS2, invalid = -1000 (none occurred)",
  "evaluations": 72,
  "generations": 9,
  "seeds_used": "646100..646675",
  "wall_seconds": 1499,
  "phase_change": "Gens 0-2 used w_stale 0..1 and c3 0..400; c3 >= 50 lost 14 to 86 and w_stale >= 0.37 lost 0.5 to 1.6, so after gen 2 the box was rescaled to w_stale 0..0.5 and c3 0..10, resetting C and the paths with sigma 0.25. Gens 3-8 ran on the rescaled box.",
  "best": {
   "p": [
    0.5037992647980342,
    0.15916177240033247,
    0.0,
    8.442088111149674
   ],
   "block": 646548,
   "mean_diff": 0.22956366686050966,
   "se": 0.07945441282967121
  },
  "observations": "Gen 0-2: every non-trivial sticky weight lost (e.g. d=0.86,w_fee=0.08,w_stale=0.57: -2.26; d=0.60,w_fee=0.42,w_stale=0.51: -1.44; d=0.76,w_fee=0.32,w_stale=0.23: -0.27). After rescaling, gains came with c3 of about 3-9; CMA drove w_stale to about 0-0.06 and kept w_fee small (mean at gen 8: d 0.60, w_fee 0.11, w_stale 0.016, c3 7.9)."
 },
 "recheck": {
  "seeds": "649000..649255",
  "n": 256,
  "rs2_gas": {
   "swap": 199203,
   "init": 243099,
   "bad": 0
  },
  "candidates": [
   {
    "p": [
     0.5037992647980342,
     0.15916177240033247,
     0.0,
     8.442088111149674
    ],
    "search_score": 0.22956366686050966,
    "n": 256,
    "mean_diff": 0.08233589379852191,
    "se": 0.04478390843091716,
    "gas": {
     "swap": 220083,
     "init": 243103,
     "bad": 0
    },
    "valid": true
   },
   {
    "p": [
     0.5331740700353155,
     0.0,
     0.058377351221173754,
     6.132516090921386
    ],
    "search_score": 0.19156992696371145,
    "n": 256,
    "mean_diff": 0.08719477988731894,
    "se": 0.04001820824793229,
    "gas": {
     "swap": 220301,
     "init": 243099,
     "bad": 0
    },
    "valid": true
   },
   {
    "p": [
     0.514774297777619,
     0.0,
     0.04914799038694663,
     7.3176636781077855
    ],
    "search_score": 0.17522021499164264,
    "n": 256,
    "mean_diff": 0.1235451484528085,
    "se": 0.04255101764153033,
    "gas": {
     "swap": 220301,
     "init": 243099,
     "bad": 0
    },
    "valid": true
   }
  ],
  "frozen": "third candidate (highest recheck mean)"
 },
 "held_out": {
  "seeds": "649400..649911",
  "n": 512,
  "mean_diff": 0.12644215406797144,
  "se": 0.030462302159182962,
  "worst": [
   {
    "seed": 649893,
    "d": -7.4289583791663745
   },
   {
    "seed": 649512,
    "d": -4.358782553198694
   },
   {
    "seed": 649505,
    "d": -3.7660013731500612
   },
   {
    "seed": 649666,
    "d": -3.4586018062191215
   },
   {
    "seed": 649795,
    "d": -2.8723528474514524
   }
  ],
  "arm_means": {
   "cand": 526.0954635546022,
   "rs2": 525.9690214005343
  },
  "rs2_sha256": "f24b6ca198b744c380842c3a17964a6dc21f311bb04984b26733afa3fee8eaf2"
 },
 "retail_edge_delta": {
  "mean": -0.23745044524708847,
  "se": 0.032824425529109906
 },
 "arb_edge_delta": {
  "mean": 0.3638925993150621,
  "se": 0.015633969386306353
 },
 "reconciliation_max_abs": 1.0302869668521453e-13,
 "gas": {
  "max_ok": 226113,
  "init_max_ok": 243099,
  "oog": 0,
  "other_halts_reverts_errors": 0,
  "rs2_max_ok_same_seeds": 202398,
  "limits": "afterSwap < 235000, afterInitialize < 245000; afterInitialize unchanged (no new slot written there)",
  "search_max_ok_over_all_evals": 223839,
  "search_halts_total": 0
 },
 "ablation_held_out": {
  "note": "Run on the same held-out seeds after freezing; not used for selection.",
  "cubic_only_vs_rs2": {
   "params": {
    "d": 0.514774297777619,
    "w_fee": 0,
    "w_stale": 0,
    "c3": 7.3176636781077855
   },
   "n": 512,
   "mean_diff": 0.10818400657545613,
   "se": 0.0286364929135403,
   "worst": [
    {
     "seed": 649893,
     "d": -7.277598701738839
    },
    {
     "seed": 649512,
     "d": -4.144625264222441
    },
    {
     "seed": 649505,
     "d": -3.8712288896384734
    },
    {
     "seed": 649666,
     "d": -3.1157321384778243
    },
    {
     "seed": 649836,
     "d": -2.7485953139328103
    }
   ],
   "retail_edge_delta": {
    "mean": -0.4332059988635747,
    "se": 0.031266791194369224
   },
   "arb_edge_delta": {
    "mean": 0.5413900054390324,
    "se": 0.015105816294720058
   },
   "gas_max_ok": 225861
  },
  "frozen_vs_cubic_only": {
   "n": 512,
   "mean_diff": 0.01825814749251531,
   "se": 0.010520607583777358,
   "worst": [
    {
     "seed": 649628,
     "d": -0.9455186029081233
    },
    {
     "seed": 649701,
     "d": -0.8873982851484925
    },
    {
     "seed": 649795,
     "d": -0.6946705452535298
    },
    {
     "seed": 649903,
     "d": -0.6425057991306176
    },
    {
     "seed": 649672,
     "d": -0.6250772179258774
    }
   ]
  }
 },
 "notes": [
  "Measured on held-out data: frozen vs RS2 = +0.126 +/- 0.030 (n=512). Most of that comes from the added cubic toxicity term, not from the sticky peak-hold: cubic-only gives +0.108 +/- 0.029, and the sticky stale-shift (w_stale=0.049) adds only +0.018 +/- 0.011 on top, which is not significant at 2 se.",
  "The sticky peak-hold itself, as asked (feeding toxicity fees and the stale shift), was neutral to negative at every material weight. The search favoured w_fee=0 and w_stale ~0.05. Conclusion: the sticky deviation mechanism gives RS2 no meaningful gain. A small cubic term (c3 about 6-8) gives about +0.1 local, roughly +0.07 on the board at the 0.65 transfer rate; that is far short of the +5 the goal needs.",
  "The frozen strategy trades retail edge (-0.237) for less arbitrage loss (+0.364): it charges higher fees when toxicity is high.",
  "afterSwap max gas rose to 226113 on held-out seeds, versus 202398 for RS2 on the same seeds. The cost is in seed-dependent paths (search blocks reached 223839 even for some RS2-like settings), and it stays under the 235000 limit, but the margin is about 8.9k.",
  "Seed blocks used only as the brief specified: search 646100..646675 (within 646100..648999), recheck 649000..649255, held-out 649400..649911 used once, neutral check 649950..649981. No 5000000+ confirmation vs STACK was run (not requested for this item).",
  "Harness: functions from the harness_source of artifact 33f54e81... (each strategy alone vs VanillaStrategy, gas_stats per 20-seed chunk, arb/retail decomposition)."
 ]
}