{"item": "e04-band-transport/b: retail displacement control (copy b)", "blocked": null, "seeds_kind": "tuning", "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    int256 constant D_AL = 42907455077250880;\n    int256 constant D_AU = 651419398181336;\n    int256 constant D_BL = 45753311851032560;\n    int256 constant D_BU = -3196000745897746;\n    int256 constant D_QL = 6264253142832674816;\n    int256 constant D_QU = -5864128493086456832;\n    int256 constant D_FW = 928582437377300352;\n    int256 constant D_RHO = 0;\n    int256 constant D_CAP = 3861258919996619;\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[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 arbProb;\n        (fastHat, uncertainty, arbProb) = _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        int256 disp = _trackDisp(isNewStep, firstInStep, spot, slots[2] >> 64, arbProb);\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 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        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        if (disp != 0) (bidFee, askFee) = _steer(disp, bidFee, askFee);\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    // Signed retail-induced spot displacement since step opening (slot 15).\n    function _trackDisp(bool isNewStep, bool first, uint256 spot, uint256 pre, uint256 arbProb) internal returns (int256 d) {\n        d = int256(slots[15]);\n        if (isNewStep) d = d * D_RHO / 1e18;\n        if (pre > 0) {\n            int256 r = (int256(spot) - int256(pre)) * 1e18 / int256(pre);\n            if (first) {\n                uint256 q = arbProb < WAD ? WAD - arbProb : 0;\n                r = r * int256(q) / 1e18 * D_FW / 1e18;\n            }\n            d += r;\n        }\n        if (d > D_CAP) d = D_CAP;\n        if (d < -D_CAP) d = -D_CAP;\n        slots[15] = uint256(d);\n    }\n    // Move band endpoints L=spot(1-bid), U=spot/(1-ask) and invert to fees.\n    function _steer(int256 d, uint256 bidFee, uint256 askFee) internal pure returns (uint256, uint256) {\n        int256 m = d < 0 ? -d : d;\n        int256 dm = d * m / 1e18;\n        int256 sL = (D_AL * d + D_BL * m + D_QL * dm) / 1e18;\n        int256 sU = (D_AU * d + D_BU * m + D_QU * dm) / 1e18;\n        if (sL != 0) {\n            int256 l = int256(WAD - bidFee) * (1e18 + sL) / 1e18; // L/spot\n            bidFee = l >= int256(WAD) ? 0 : (l <= int256(WAD - MAX_FEE) ? MAX_FEE : WAD - uint256(l));\n        }\n        if (sU != 0) {\n            if (sU <= -5e17) sU = -5e17;\n            int256 u = int256(WAD - askFee) * 1e18 / (1e18 + sU); // spot/U\n            askFee = u >= int256(WAD) ? 0 : (u <= int256(WAD - MAX_FEE) ? MAX_FEE : WAD - uint256(u));\n        }\n        return (bidFee, askFee);\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 \"disp_ctl\"; }\n}\n", "sha256": "d11fe36b99e607fefacdca7ff7875ea24c02063e27c53a705928d0ec13bcd4ad", "name": "disp_ctl", "anchor": {"name": "V10", "sha256": "cd9bdb45ab0537ad25c4fd90ca8618898cef6386de3df65f192eaef65fbca245", "source": "https://api.imdnotdead.fun/artifacts/33f54e81f3372088e9eced52c0174f310ac348af98ef5727b73785c088679194", "sha_verified": true}, "stack_sha_verified": "2eaafc7960e520b8a7fd322ec8afaff8fa677c730228a961efb509cc30b25719 (downloaded code matched; STACK not run here)", "params": {"AL": 0.042907455077250876, "AU": 0.0006514193981813359, "BL": 0.04575331185103256, "BU": -0.0031960007458977455, "QL": 6.264253142832675, "QU": -5.864128493086457, "FW": 0.9285824373773004, "RHO": 0.0, "CAP": 0.003861258919996619}, "mechanism": "Signed retail-induced spot displacement D since step opening (slot 15): at the first print of a step D += FW*(1-P(arb))*(spot-preSpot)/preSpot using V10 posterior arb probability; later prints add the full relative spot move (certain retail). D is clipped to +-CAP and reset (times RHO) at each new step. Both next band endpoints L=spot(1-bid), U=spot/(1-ask) of V10 are moved: L*=1+AL*D+BL*|D|+QL*D|D|, U*=1+AU*D+BU*|D|+QU*D|D|, then inverted to fees and clipped to [0,MAX_FEE]. V10 price/posterior updates are untouched; stored fees are the steered ones. With all gains 0 the code path is skipped (sL=sU=0), bit-identical to V10 (checked: 16 seeds 690000..690015, every edge equal).", "structures_compared": {"S1_translation": "AL=AU=t, CAP=0.01 (1 param)", "S2_width": "BL=-wL, BU=wU, CAP=0.01 (2 params; negative wL/wU = band narrows as |D| grows)", "S3_coupled": "AL,AU,BL,BU,QL,QU,FW,RHO,CAP (9 params, coupled translation+width+quadratic feedback, first-print weight, carry)"}, "generator_source": "\"\"\"Generator: V10 + retail displacement control of both band endpoints.\n\nParams (all WAD-scaled signed ints in Solidity, floats here):\n  AL, AU : translation gain of lower / upper endpoint per unit signed displacement D\n  BL, BU : width gain per unit |D| (L' = L(1+BL|D|), U' = U(1+BU|D|); BL<0,BU>0 widens)\n  QL, QU : signed-quadratic gain on D|D|\n  FW     : weight on first print of a step (multiplies (1 - P(arb)))\n  RHO    : carry of D into the next step (0 = reset at step opening)\n  CAP    : |D| saturation\nZero intervention (all gains 0) leaves V10 fees bit-identical.\n\"\"\"\nimport hashlib\nfrom pathlib import Path\n\nBASE = Path(__file__).resolve().parent.parent / 'dl' / 'V10.sol'\nNAMES = ['AL', 'AU', 'BL', 'BU', 'QL', 'QU', 'FW', 'RHO', 'CAP']\nDEFAULT = dict(AL=0.0, AU=0.0, BL=0.0, BU=0.0, QL=0.0, QU=0.0, FW=1.0, RHO=0.0, CAP=0.02)\n\n\ndef _rep(src, old, new, count=1):\n    assert src.count(old) == count, (old, src.count(old))\n    return src.replace(old, new)\n\n\ndef gen(params, name='disp_ctl'):\n    p = dict(DEFAULT)\n    p.update(params)\n    src = BASE.read_text()\n    consts = ''.join(f'    int256 constant D_{k} = {int(round(p[k] * 1e18))};\\n' for k in NAMES)\n    src = _rep(src, '    uint256 constant ELAPSED_CAP = 8;\\n', '    uint256 constant ELAPSED_CAP = 8;\\n' + consts)\n    # posterior also returns the arb probability of the first print\n    src = _rep(src, 'function _posterior(PosteriorInput memory x) internal pure returns (uint256, uint256) {',\n               'function _posterior(PosteriorInput memory x) internal pure returns (uint256, uint256, uint256) {')\n    src = _rep(src, 'return (_blend(x.mu,normal,k),wmul(x.v,WAD-k));', 'return (_blend(x.mu,normal,k),wmul(x.v,WAD-k),0);')\n    src = _rep(src, '            return (x.mu,x.v);\\n', '            return (x.mu,x.v,0);\\n')\n    src = _rep(src, '        return (mean,variance);\\n', '        return (mean,variance,prob);\\n')\n    src = _rep(src, '        (fastHat, uncertainty) = _posterior(PosteriorInput(',\n               '        uint256 arbProb;\\n        (fastHat, uncertainty, arbProb) = _posterior(PosteriorInput(')\n    # displacement tracking right after the posterior\n    track = '''        slots[13] = uncertainty;\n        int256 disp = _trackDisp(isNewStep, firstInStep, spot, slots[2] >> 64, arbProb);\n'''\n    src = _rep(src, '        slots[13] = uncertainty;\\n', track)\n    apply_ = '''        if (disp != 0) (bidFee, askFee) = _steer(disp, bidFee, askFee);\n        slots[0] = bidFee; slots[1] = askFee; slots[2] = (spot << 64) | trade.timestamp;'''\n    src = _rep(src, '        slots[0] = bidFee; slots[1] = askFee; slots[2] = (spot << 64) | trade.timestamp;', apply_)\n    helpers = '''\n    // Signed retail-induced spot displacement since step opening (slot 15).\n    function _trackDisp(bool isNewStep, bool first, uint256 spot, uint256 pre, uint256 arbProb) internal returns (int256 d) {\n        d = int256(slots[15]);\n        if (isNewStep) d = d * D_RHO / 1e18;\n        if (pre > 0) {\n            int256 r = (int256(spot) - int256(pre)) * 1e18 / int256(pre);\n            if (first) {\n                uint256 q = arbProb < WAD ? WAD - arbProb : 0;\n                r = r * int256(q) / 1e18 * D_FW / 1e18;\n            }\n            d += r;\n        }\n        if (d > D_CAP) d = D_CAP;\n        if (d < -D_CAP) d = -D_CAP;\n        slots[15] = uint256(d);\n    }\n    // Move band endpoints L=spot(1-bid), U=spot/(1-ask) and invert to fees.\n    function _steer(int256 d, uint256 bidFee, uint256 askFee) internal pure returns (uint256, uint256) {\n        int256 m = d < 0 ? -d : d;\n        int256 dm = d * m / 1e18;\n        int256 sL = (D_AL * d + D_BL * m + D_QL * dm) / 1e18;\n        int256 sU = (D_AU * d + D_BU * m + D_QU * dm) / 1e18;\n        if (sL != 0) {\n            int256 l = int256(WAD - bidFee) * (1e18 + sL) / 1e18; // L/spot\n            bidFee = l >= int256(WAD) ? 0 : (l <= int256(WAD - MAX_FEE) ? MAX_FEE : WAD - uint256(l));\n        }\n        if (sU != 0) {\n            if (sU <= -5e17) sU = -5e17;\n            int256 u = int256(WAD - askFee) * 1e18 / (1e18 + sU); // spot/U\n            askFee = u >= int256(WAD) ? 0 : (u <= int256(WAD - MAX_FEE) ? MAX_FEE : WAD - uint256(u));\n        }\n        return (bidFee, askFee);\n    }\n'''\n    src = _rep(src, '\\n    struct PosteriorInput {', helpers + '\\n    struct PosteriorInput {')\n    src = _rep(src, 'return \"censored_10\";', f'return \"{name}\";')\n    return src\n\n\ndef sha(src):\n    return hashlib.sha256(src.encode()).hexdigest()\n\n\nif __name__ == '__main__':\n    import sys\n    s = gen({})\n    Path(sys.argv[1]).write_text(s)\n    print(sha(s))\n", "harness_source": "import json, time, hashlib, os\nfrom pathlib import Path\n_S = Path(__file__).resolve().parent.parent / 'amm-challenge' / 'scratch'\nos.environ['SOLCX_BINARY_PATH'] = str(_S / 'solcx')\nos.environ['TMPDIR'] = str(_S / 'tmp')\nimport numpy as np\nimport amm_sim_rs as sim\nfrom amm_competition.evm.compiler import SolidityCompiler\nfrom amm_competition.competition.config import build_config\n\nROOT = Path(__file__).resolve().parent.parent / 'amm-challenge'\n_comp = SolidityCompiler()\n_van = None\n\n\ndef configs(start, n):\n    out = []\n    for s in range(start, start + n):\n        r = np.random.default_rng(s)\n        size = r.uniform(19, 21); rate = r.uniform(.6, 1); sigma = r.uniform(.000882, .001008)\n        out.append(build_config(seed=s, gbm_sigma=sigma, retail_arrival_rate=rate, retail_mean_size=size))\n    return out\n\n\ndef decomposition(r, initial_fee=0.0004):\n    # identical to V10 tuning harness\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.maximum(out * fair - paid, 0)\n    gross = np.maximum((np.sqrt(k * gb / fair) - x) / gb, 0)\n    received = y - k / (x + gb * gross)\n    sellprofit = np.maximum(received - gross * fair, 0)\n    arb = -float(np.sum(np.where(spots < fair, buyprofit, sellprofit)))\n    return arb, r.edges['submission'] - arb\n\n\ndef compile_src(src):\n    a = _comp.compile(src)\n    assert a.success, a.errors\n    return list(a.bytecode)\n\n\ndef vanilla():\n    global _van\n    if _van is None:\n        b = _comp.compile((ROOT / 'contracts/src/VanillaStrategy.sol').read_text(), 'VanillaStrategy')\n        assert b.success, b.errors\n        _van = list(b.bytecode)\n    return _van\n\n\ndef summarize_gas(raw):\n    \"\"\"raw = list of chunk gas_stats dicts/lists; returns afterSwap max_ok and halt totals for the submission role.\"\"\"\n    return raw\n\n\ndef run(src, seeds, decomp=True):\n    \"\"\"seeds: list of ints (contiguous chunks of <=20). Returns per-seed records and per-chunk gas.\"\"\"\n    bc = compile_src(src); vb = vanilla()\n    recs = {}; gas = []\n    seeds = list(seeds)\n    i = 0\n    while i < len(seeds):\n        st = seeds[i]; n = 1\n        while i + n < len(seeds) and n < 20 and seeds[i + n] == st + n:\n            n += 1\n        sim.gas_stats_reset()\n        res = sim.run_batch(bc, vb, configs(st, n), 8)\n        for r in res.results:\n            if decomp:\n                arb, ret = decomposition(r)\n            else:\n                arb = ret = None\n            recs[r.seed] = {'edge': r.edges['submission'], 'arb': arb, 'retail': ret}\n        gas.append({'start': st, 'n': n, 'raw': sim.gas_stats()})\n        del res\n        i += n\n    return recs, gas\n", "search_source": "\"\"\"CMA-ES (seed 406) over three displacement-control structures, rotating 32-seed CRN blocks\nin 690000..693999, paired against V10 on the same block. State persists in search_state.pkl so the\n20-minute budget can be split over several foreground invocations.\nusage: python search.py WORKDIR NGEN BUDGET_SECONDS_TOTAL\n\"\"\"\nimport sys, time, json, pickle\nsys.path.insert(0, sys.argv[1])\nfrom lib import *\nfrom gen import gen, sha\n\nW = Path(sys.argv[1]); NGEN = int(sys.argv[2]); BUDGET = float(sys.argv[3])\nSTATE = W / 'search_state.pkl'; LOG = W / 'search_log.jsonl'\nV10 = (W.parent / 'dl/V10.sol').read_text()\nBLOCK = 32; LO, HI = 690000, 693999\n\n# structure -> (names, x0 in param units, per-dimension scale, mapper)\ndef clip(v, a, b): return min(max(v, a), b)\nSTRUCT = {\n    'S1_translation': (['t'], [0.0], [0.03],\n                       lambda x: dict(AL=x[0], AU=x[0], CAP=0.01)),\n    'S2_width': (['wL', 'wU'], [0.0, 0.0], [0.03, 0.03],\n                 lambda x: dict(BL=-x[0], BU=x[1], CAP=0.01)),\n    'S3_coupled': (['AL', 'AU', 'BL', 'BU', 'QL', 'QU', 'FW', 'RHO', 'CAP'],\n                   [0, 0, 0, 0, 0, 0, 1.0, 0.0, 0.01],\n                   [0.03, 0.03, 0.03, 0.03, 3.0, 3.0, 0.4, 0.3, 0.004],\n                   lambda x: dict(AL=x[0], AU=x[1], BL=x[2], BU=x[3], QL=x[4], QU=x[5],\n                                  FW=clip(x[6], 0, 2), RHO=clip(x[7], 0, 0.95), CAP=clip(x[8], 0.001, 0.05))),\n}\nPOP = {'S1_translation': 3, 'S2_width': 4, 'S3_coupled': 6}\n\n\nclass CMA:\n    def __init__(self, n, lam, rng):\n        self.n = n; self.lam = lam; self.rng = rng\n        self.m = np.zeros(n); self.sigma = 1.0; self.C = np.eye(n)\n        self.pc = np.zeros(n); self.ps = np.zeros(n)\n        mu = max(1, lam // 2); w = np.log(mu + .5) - np.log(np.arange(1, mu + 1)); self.w = w / w.sum(); self.mu = mu\n        self.mueff = 1 / np.sum(self.w ** 2)\n        self.cc = (4 + self.mueff / n) / (n + 4 + 2 * self.mueff / n)\n        self.cs = (self.mueff + 2) / (n + self.mueff + 5)\n        self.c1 = 2 / ((n + 1.3) ** 2 + self.mueff)\n        self.cmu = min(1 - self.c1, 2 * (self.mueff - 2 + 1 / self.mueff) / ((n + 2) ** 2 + self.mueff))\n        self.ds = 1 + 2 * max(0, np.sqrt((self.mueff - 1) / (n + 1)) - 1) + self.cs\n        self.chi = np.sqrt(n) * (1 - 1 / (4 * n) + 1 / (21 * n * n)); self.g = 0\n\n    def ask(self):\n        d, B = np.linalg.eigh(self.C); d = np.sqrt(np.maximum(d, 1e-20))\n        self.B, self.D = B, d\n        z = self.rng.standard_normal((self.lam, self.n))\n        return [self.m + self.sigma * (B @ (d * zi)) for zi in z]\n\n    def tell(self, xs, f):  # minimise f\n        idx = np.argsort(f); xs = np.array(xs)[idx[:self.mu]]\n        old = self.m.copy(); self.m = self.w @ xs\n        y = (self.m - old) / self.sigma\n        Cinvsqrt = self.B @ np.diag(1 / self.D) @ self.B.T\n        self.ps = (1 - self.cs) * self.ps + np.sqrt(self.cs * (2 - self.cs) * self.mueff) * (Cinvsqrt @ y)\n        self.g += 1\n        hs = np.linalg.norm(self.ps) / np.sqrt(1 - (1 - self.cs) ** (2 * self.g)) < (1.4 + 2 / (self.n + 1)) * self.chi\n        self.pc = (1 - self.cc) * self.pc + hs * np.sqrt(self.cc * (2 - self.cc) * self.mueff) * y\n        ys = (xs - old) / self.sigma\n        self.C = (1 - self.c1 - self.cmu) * self.C + self.c1 * (np.outer(self.pc, self.pc) + (1 - hs) * self.cc * (2 - self.cc) * self.C) \\\n            + self.cmu * sum(wi * np.outer(yi, yi) for wi, yi in zip(self.w, ys))\n        self.sigma *= np.exp((self.cs / self.ds) * (np.linalg.norm(self.ps) / self.chi - 1))\n\n\ndef gas_summary(chunks):\n    mx = 0; halts = {'oog': 0, 'revert': 0, 'other_halt': 0, 'tx_error': 0, 'bad_return': 0}; init = 0\n    for c in chunks:\n        for r in c['raw']:\n            if r['role'] != 'Submission':\n                continue\n            for k in halts: halts[k] += r[k]\n            if r['callback'] == 'afterSwap': mx = max(mx, r['max_ok_gas'])\n            if r['callback'] == 'afterInitialize': init = max(init, r['max_ok_gas'])\n    return dict(max_ok=mx, init_max_ok=init, **halts)\n\n\nif STATE.exists():\n    st = pickle.load(open(STATE, 'rb'))\nelse:\n    rng = np.random.default_rng(406)\n    st = dict(gen=0, used=0.0, cma={k: CMA(len(v[0]), POP[k], rng) for k, v in STRUCT.items()}, best=[])\n\nt_all = time.time()\nfor _ in range(NGEN):\n    if st['used'] >= BUDGET:\n        print('budget exhausted'); break\n    t0 = time.time()\n    g = st['gen']; start = LO + (g * BLOCK) % (HI - LO + 1)\n    seeds = list(range(start, start + BLOCK)); assert seeds[-1] <= HI\n    base, bg = run(V10, seeds, decomp=False)\n    entry = dict(gen=g, block=[start, start + BLOCK - 1], v10_mean=float(np.mean([base[s]['edge'] for s in seeds])),\n                 v10_gas=gas_summary(bg), evals=[])\n    for k, (names, x0, scale, mapper) in STRUCT.items():\n        es = st['cma'][k]; xs = es.ask(); fs = []\n        for x in xs:\n            p = mapper(np.array(x0) + np.array(scale) * x)\n            src = gen(p); h = sha(src)\n            rec, gch = run(src, seeds, decomp=False)\n            gs = gas_summary(gch)\n            d = np.array([rec[s]['edge'] - base[s]['edge'] for s in seeds])\n            bad = sum(gs[q] for q in ['oog', 'revert', 'other_halt', 'tx_error', 'bad_return'])\n            f = -d.mean() if bad == 0 else 1e9\n            fs.append(f)\n            ev = dict(structure=k, params={a: float(b) for a, b in p.items()}, sha256=h, mean_diff=float(d.mean()),\n                      se=float(d.std(ddof=1) / np.sqrt(len(d))), gas=gs)\n            entry['evals'].append(ev)\n            print(json.dumps({x_: ev[x_] for x_ in ['structure', 'mean_diff', 'se']}), json.dumps(ev['params']), gs['max_ok'], gs['oog'], flush=True)\n        es.tell(xs, fs)\n        entry.setdefault('cma_sigma', {})[k] = float(es.sigma)\n        entry.setdefault('cma_mean_params', {})[k] = {a: float(b) for a, b in mapper(np.array(x0) + np.array(scale) * es.m).items()}\n    dt = time.time() - t0; st['used'] += dt; st['gen'] += 1\n    entry['seconds'] = dt; entry['budget_used'] = st['used']\n    with open(LOG, 'a') as fh: fh.write(json.dumps(entry) + '\\n')\n    pickle.dump(st, open(STATE, 'wb'))\n    print('gen', g, 'seconds', round(dt), 'used', round(st['used']), flush=True)\n", "eval_source": "\"\"\"usage: python evalarm.py WORKDIR START N LABEL [SHA_FROM_LOG|V10] ...  -> saves eval_LABEL_START_N.json\"\"\"\nimport sys, json, time\nsys.path.insert(0, sys.argv[1])\nfrom lib import *\nfrom gen import gen, sha\ndef gas_summary(chunks):\n    mx = 0; halts = {'oog': 0, 'revert': 0, 'other_halt': 0, 'tx_error': 0, 'bad_return': 0}; init = 0\n    for c in chunks:\n        for r in c['raw']:\n            if r['role'] != 'Submission':\n                continue\n            for k in halts: halts[k] += r[k]\n            if r['callback'] == 'afterSwap': mx = max(mx, r['max_ok_gas'])\n            if r['callback'] == 'afterInitialize': init = max(init, r['max_ok_gas'])\n    return dict(max_ok=mx, init_max_ok=init, **halts)\nW = Path(sys.argv[1]); start, n = int(sys.argv[2]), int(sys.argv[3])\nevs = {}\nfor line in open(W / 'search_log.jsonl'):\n    for e in json.loads(line)['evals']:\n        evs[e['sha256']] = e\nfor spec in sys.argv[4:]:\n    label, key = spec.split('=')\n    if key == 'V10':\n        src = (W.parent / 'dl/V10.sol').read_text(); params = None\n    else:\n        e = [v for h, v in evs.items() if h.startswith(key)][0]; params = e['params']; src = gen(params)\n    t = time.time()\n    rec, g = run(src, range(start, start + n))\n    out = dict(label=label, sha256=sha(src), params=params, start=start, n=n, recs={str(k): v for k, v in rec.items()},\n               gas=gas_summary(g), gas_chunks=g, seconds=time.time() - t)\n    (W / f'eval_{label}_{start}_{n}.json').write_text(json.dumps(out))\n    (W / f'{label}.sol').write_text(src)\n    print(label, out['sha256'], np.mean([v['edge'] for v in rec.values()]), out['gas'], round(out['seconds']), flush=True)\n", "search": {"method": "Own numpy CMA-ES (mu/mu_w,lambda) per structure, one numpy default_rng(406) shared, x0 = zero intervention, pop S1=3,S2=4,S3=6; each generation one fresh 32-seed CRN block, all structures and V10 on the same block", "wall_seconds": 807.2, "generations": 3, "evaluations": 39, "stopped_reason": "Stopped after 3 generations (807 s of the 20-min cap) to keep the 55-min budget for recheck and held-out; search is incomplete/under-converged.", "log": [{"gen": 0, "block": [690000, 690031], "v10_block_mean": 511.09851009948295, "seconds": 267.8, "cma_sigma": {"S1_translation": 0.911072027091474, "S2_width": 1.0727092888820229, "S3_coupled": 0.9374190328237917}, "evals": [{"structure": "S1_translation", "sha256": "f9d2c48f099f0208", "params": {"AL": 0.048688, "AU": 0.048688, "CAP": 0.01}, "mean_diff": -0.3723, "se": 0.0913, "afterSwap_max_ok": 202680, "oog": 0, "other_halts": 0}, {"structure": "S1_translation", "sha256": "4cc264114ac4e1b9", "params": {"AL": -0.029758, "AU": -0.029758, "CAP": 0.01}, "mean_diff": -0.4492, "se": 0.0606, "afterSwap_max_ok": 198756, "oog": 0, "other_halts": 0}, {"structure": "S1_translation", "sha256": "71805c383664d291", "params": {"AL": -0.020106, "AU": -0.020106, "CAP": 0.01}, "mean_diff": -0.354, "se": 0.0481, "afterSwap_max_ok": 198768, "oog": 0, "other_halts": 0}, {"structure": "S2_width", "sha256": "43e31eb0c9dba811", "params": {"BL": 0.04367, "BU": -0.038789, "CAP": 0.01}, "mean_diff": 0.0707, "se": 0.0579, "afterSwap_max_ok": 198683, "oog": 0, "other_halts": 0}, {"structure": "S2_width", "sha256": "08435e97c2a1d4bf", "params": {"BL": -0.047169, "BU": 0.030324, "CAP": 0.01}, "mean_diff": -0.9167, "se": 0.0833, "afterSwap_max_ok": 188163, "oog": 0, "other_halts": 0}, {"structure": "S2_width", "sha256": "67f548b298dad4af", "params": {"BL": -0.008176, "BU": -0.015779, "CAP": 0.01}, "mean_diff": -0.0671, "se": 0.0374, "afterSwap_max_ok": 198485, "oog": 0, "other_halts": 0}, {"structure": "S2_width", "sha256": "aae6c1eac9a52360", "params": {"BL": -0.019724, "BU": 0.024783, "CAP": 0.01}, "mean_diff": -0.4227, "se": 0.0518, "afterSwap_max_ok": 188163, "oog": 0, "other_halts": 0}, {"structure": "S3_coupled", "sha256": "d2b459a8e42b1f16", "params": {"AL": -0.032858, "AU": 0.005627, "BL": -0.022652, "BU": 0.049877, "QL": 4.676481, "QU": -0.246469, "FW": 1.267043, "RHO": 0.235691, "CAP": 0.007937}, "mean_diff": -0.8272, "se": 0.0672, "afterSwap_max_ok": 188172, "oog": 0, "other_halts": 0}, {"structure": "S3_coupled", "sha256": "ae375b0971b2089d", "params": {"AL": 0.061384, "AU": 0.032197, "BL": 0.001758, "BU": 0.012564, "QL": -6.167762, "QU": 0.282694, "FW": 0.70398, "RHO": 0.0, "CAP": 0.007247}, "mean_diff": -0.134, "se": 0.0589, "afterSwap_max_ok": 202558, "oog": 0, "other_halts": 0}, {"structure": "S3_coupled", "sha256": "861734e57a64c6d1", "params": {"AL": 0.016794, "AU": 0.057128, "BL": -0.031981, "BU": -0.018932, "QL": -4.596759, "QU": -0.002184, "FW": 0.980878, "RHO": 0.0, "CAP": 0.011823}, "mean_diff": -0.9156, "se": 0.1022, "afterSwap_max_ok": 202601, "oog": 0, "other_halts": 0}, {"structure": "S3_coupled", "sha256": "26fad19422377e2c", "params": {"AL": -0.005823, "AU": 0.016094, "BL": -0.005946, "BU": 0.004159, "QL": 6.418458, "QU": 1.354588, "FW": 0.265163, "RHO": 0.0, "CAP": 0.011261}, "mean_diff": -0.2185, "se": 0.0555, "afterSwap_max_ok": 202401, "oog": 0, "other_halts": 0}, {"structure": "S3_coupled", "sha256": "82f9e7161d906403", "params": {"AL": 0.035671, "AU": -0.009525, "BL": 0.008262, "BU": -0.017084, "QL": -1.917266, "QU": 6.548535, "FW": 0.781144, "RHO": 0.0, "CAP": 0.010384}, "mean_diff": -0.1321, "se": 0.0859, "afterSwap_max_ok": 198647, "oog": 0, "other_halts": 0}, {"structure": "S3_coupled", "sha256": "46b4236147877217", "params": {"AL": 0.024104, "AU": -0.002244, "BL": 0.039029, "BU": 0.008296, "QL": 2.564007, "QU": -3.20918, "FW": 1.75774, "RHO": 0.0, "CAP": 0.00698}, "mean_diff": -0.1211, "se": 0.0828, "afterSwap_max_ok": 188309, "oog": 0, "other_halts": 0}]}, {"gen": 1, "block": [690032, 690063], "v10_block_mean": 520.5778491432316, "seconds": 265.2, "cma_sigma": {"S1_translation": 0.7734124320094232, "S2_width": 1.2397904599210086, "S3_coupled": 1.0024994607467523}, "evals": [{"structure": "S1_translation", "sha256": "9664dbd10da71622", "params": {"AL": 0.000889, "AU": 0.000889, "CAP": 0.01}, "mean_diff": -0.0237, "se": 0.0148, "afterSwap_max_ok": 193017, "oog": 0, "other_halts": 0}, {"structure": "S1_translation", "sha256": "6ca0c8c7cd16c771", "params": {"AL": 0.000208, "AU": 0.000208, "CAP": 0.01}, "mean_diff": -0.0025, "se": 0.0089, "afterSwap_max_ok": 193017, "oog": 0, "other_halts": 0}, {"structure": "S1_translation", "sha256": "2636ed331c39241e", "params": {"AL": -0.019407, "AU": -0.019407, "CAP": 0.01}, "mean_diff": -0.2655, "se": 0.0666, "afterSwap_max_ok": 193017, "oog": 0, "other_halts": 0}, {"structure": "S2_width", "sha256": "3319a300414e9920", "params": {"BL": 0.071371, "BU": -0.031577, "CAP": 0.01}, "mean_diff": 0.0483, "se": 0.0997, "afterSwap_max_ok": 200481, "oog": 0, "other_halts": 0}, {"structure": "S2_width", "sha256": "865dbafdbf5c3f65", "params": {"BL": 0.07012, "BU": -0.07514, "CAP": 0.01}, "mean_diff": -0.1308, "se": 0.1105, "afterSwap_max_ok": 193017, "oog": 0, "other_halts": 0}, {"structure": "S2_width", "sha256": "8bd2e37d9c65c6e1", "params": {"BL": 0.077654, "BU": -0.056971, "CAP": 0.01}, "mean_diff": -0.0098, "se": 0.1098, "afterSwap_max_ok": 193017, "oog": 0, "other_halts": 0}, {"structure": "S2_width", "sha256": "7dcb5b4b1503111b", "params": {"BL": 0.079928, "BU": -0.075462, "CAP": 0.01}, "mean_diff": -0.1648, "se": 0.1166, "afterSwap_max_ok": 193017, "oog": 0, "other_halts": 0}, {"structure": "S3_coupled", "sha256": "a74b8102b851cdb9", "params": {"AL": 0.004506, "AU": -0.020782, "BL": 0.049247, "BU": -0.003284, "QL": -4.636492, "QU": -5.797144, "FW": 1.363946, "RHO": 0.0, "CAP": 0.00954}, "mean_diff": -0.6422, "se": 0.0986, "afterSwap_max_ok": 192999, "oog": 0, "other_halts": 0}, {"structure": "S3_coupled", "sha256": "acdf4791f1ed3095", "params": {"AL": 0.049249, "AU": -0.044686, "BL": 0.055395, "BU": 0.002076, "QL": 2.316755, "QU": -6.029163, "FW": 1.609197, "RHO": 0.0, "CAP": 0.004179}, "mean_diff": -0.3317, "se": 0.0836, "afterSwap_max_ok": 200440, "oog": 0, "other_halts": 0}, {"structure": "S3_coupled", "sha256": "2a64dacb810b959c", "params": {"AL": 0.044314, "AU": -0.037083, "BL": 0.040271, "BU": 0.014785, "QL": 4.782164, "QU": -2.626747, "FW": 1.247869, "RHO": 0.0, "CAP": 0.013647}, "mean_diff": -1.9975, "se": 0.1746, "afterSwap_max_ok": 192999, "oog": 0, "other_halts": 0}, {"structure": "S3_coupled", "sha256": "d11fe36b99e607fe", "params": {"AL": 0.042907, "AU": 0.000651, "BL": 0.045753, "BU": -0.003196, "QL": 6.264253, "QU": -5.864128, "FW": 0.928582, "RHO": 0.0, "CAP": 0.003861}, "mean_diff": 0.0515, "se": 0.0783, "afterSwap_max_ok": 192999, "oog": 0, "other_halts": 0}, {"structure": "S3_coupled", "sha256": "e90af04ac8e9cfef", "params": {"AL": 0.038365, "AU": -0.00705, "BL": 0.047288, "BU": 0.015806, "QL": -0.278407, "QU": 0.382311, "FW": 1.660223, "RHO": 0.0, "CAP": 0.004495}, "mean_diff": -0.0108, "se": 0.0788, "afterSwap_max_ok": 192999, "oog": 0, "other_halts": 0}, {"structure": "S3_coupled", "sha256": "727d1b9f82625960", "params": {"AL": -0.010495, "AU": 0.037302, "BL": 0.012496, "BU": -0.04552, "QL": -3.215617, "QU": 6.350349, "FW": 1.299335, "RHO": 0.0, "CAP": 0.008475}, "mean_diff": -0.7072, "se": 0.1088, "afterSwap_max_ok": 192867, "oog": 0, "other_halts": 0}]}, {"gen": 2, "block": [690064, 690095], "v10_block_mean": 538.264351044852, "seconds": 274.3, "cma_sigma": {"S1_translation": 0.6093046186868928, "S2_width": 1.0574104288658588, "S3_coupled": 1.005458432468045}, "evals": [{"structure": "S1_translation", "sha256": "9d6b2663dda3dbea", "params": {"AL": -0.000776, "AU": -0.000776, "CAP": 0.01}, "mean_diff": -0.0295, "se": 0.0115, "afterSwap_max_ok": 193092, "oog": 0, "other_halts": 0}, {"structure": "S1_translation", "sha256": "431791fcbdb4740e", "params": {"AL": 0.021928, "AU": 0.021928, "CAP": 0.01}, "mean_diff": -0.0944, "se": 0.0582, "afterSwap_max_ok": 196368, "oog": 0, "other_halts": 0}, {"structure": "S1_translation", "sha256": "7d8ef1edcb8cb7d6", "params": {"AL": -0.004847, "AU": -0.004847, "CAP": 0.01}, "mean_diff": -0.1179, "se": 0.0283, "afterSwap_max_ok": 193092, "oog": 0, "other_halts": 0}, {"structure": "S2_width", "sha256": "0e6e6e5365961ba7", "params": {"BL": -0.011843, "BU": -0.015763, "CAP": 0.01}, "mean_diff": -0.1198, "se": 0.048, "afterSwap_max_ok": 192939, "oog": 0, "other_halts": 0}, {"structure": "S2_width", "sha256": "9fb009ea150e6901", "params": {"BL": 0.040487, "BU": -0.033429, "CAP": 0.01}, "mean_diff": -0.0068, "se": 0.0833, "afterSwap_max_ok": 196357, "oog": 0, "other_halts": 0}, {"structure": "S2_width", "sha256": "90fcfbd705178694", "params": {"BL": 0.066771, "BU": -0.041705, "CAP": 0.01}, "mean_diff": -0.0859, "se": 0.1076, "afterSwap_max_ok": 196381, "oog": 0, "other_halts": 0}, {"structure": "S2_width", "sha256": "386739c0aa3f65ab", "params": {"BL": 0.076556, "BU": -0.002756, "CAP": 0.01}, "mean_diff": -0.0587, "se": 0.0907, "afterSwap_max_ok": 196381, "oog": 0, "other_halts": 0}, {"structure": "S3_coupled", "sha256": "7aece34438b68a27", "params": {"AL": 0.082933, "AU": 0.004916, "BL": 0.039155, "BU": -0.000323, "QL": 9.97292, "QU": -1.534834, "FW": 0.993205, "RHO": 0.0, "CAP": 0.010145}, "mean_diff": -2.1617, "se": 0.1813, "afterSwap_max_ok": 196268, "oog": 0, "other_halts": 0}, {"structure": "S3_coupled", "sha256": "bf5db6f3b58a7395", "params": {"AL": -0.018258, "AU": 0.009731, "BL": 0.037816, "BU": -0.018367, "QL": 5.876623, "QU": -2.432112, "FW": 1.965403, "RHO": 0.0, "CAP": 0.006515}, "mean_diff": 0.0303, "se": 0.07, "afterSwap_max_ok": 196115, "oog": 0, "other_halts": 0}, {"structure": "S3_coupled", "sha256": "c1720749edfc0b66", "params": {"AL": 0.029648, "AU": 0.001404, "BL": 0.069528, "BU": 0.014883, "QL": 2.014466, "QU": -2.300132, "FW": 0.868532, "RHO": 0.0, "CAP": 0.005898}, "mean_diff": -0.002, "se": 0.0911, "afterSwap_max_ok": 196246, "oog": 0, "other_halts": 0}, {"structure": "S3_coupled", "sha256": "795e05fed0353c3c", "params": {"AL": 0.094113, "AU": 0.000993, "BL": 0.056587, "BU": 0.035397, "QL": 3.905151, "QU": -4.982721, "FW": 0.294054, "RHO": 0.0, "CAP": 0.001}, "mean_diff": -0.0414, "se": 0.0458, "afterSwap_max_ok": 196254, "oog": 0, "other_halts": 0}, {"structure": "S3_coupled", "sha256": "f91de30608b647fa", "params": {"AL": 0.013301, "AU": 0.018562, "BL": 0.042493, "BU": 0.0342, "QL": 2.424863, "QU": -7.126835, "FW": 0.433289, "RHO": 0.0, "CAP": 0.001}, "mean_diff": -0.0281, "se": 0.0432, "afterSwap_max_ok": 196273, "oog": 0, "other_halts": 0}, {"structure": "S3_coupled", "sha256": "f80086784e751428", "params": {"AL": 0.012812, "AU": -0.016863, "BL": 0.039956, "BU": -0.025641, "QL": 10.156395, "QU": -7.427009, "FW": 1.381984, "RHO": 0.0, "CAP": 0.006874}, "mean_diff": -0.4961, "se": 0.1148, "afterSwap_max_ok": 203113, "oog": 0, "other_halts": 0}]}]}, "recheck_694000_694255": {"A": {"sha256": "43e31eb0c9dba81140d02c7b5c82e20341550b7537d8adf232a9f27b1eec6683", "structure": "S2_width (gen0 block mean +0.0707)", "params": {"BL": 0.04366953090728598, "BU": -0.03878930710122989, "CAP": 0.01}, "paired": {"n": 256, "mean_diff": -0.06071651982201298, "se": 0.028684569628836667, "worst": [{"seed": 694100, "d": -1.5587283022923657}, {"seed": 694236, "d": -1.2326250823500686}, {"seed": 694131, "d": -1.2123355938445002}, {"seed": 694253, "d": -1.0243490249904426}, {"seed": 694123, "d": -1.005723535650759}]}, "retail_edge_delta": {"mean": 1.159556825317686, "se": 0.032079099187065314}, "arb_edge_delta": {"mean": -1.2202733451397012, "se": 0.01624054473212148}, "reconciliation": {"retail_plus_arb": -0.0607165198220152, "total": -0.06071651982201298, "abs_error": 2.220446049250313e-15}, "arm_means": {"v10": 524.6038646870915, "candidate": 524.5431481672695}, "gas": {"max_ok": 202348, "init_max_ok": 220975, "oog": 0, "revert": 0, "other_halt": 0, "tx_error": 0, "bad_return": 0}}, "B": {"sha256": "d11fe36b99e607fefacdca7ff7875ea24c02063e27c53a705928d0ec13bcd4ad", "structure": "S3_coupled (gen1 block mean +0.0515)", "params": {"AL": 0.042907455077250876, "AU": 0.0006514193981813359, "BL": 0.04575331185103256, "BU": -0.0031960007458977455, "QL": 6.264253142832675, "QU": -5.864128493086457, "FW": 0.9285824373773004, "RHO": 0.0, "CAP": 0.003861258919996619}, "paired": {"n": 256, "mean_diff": -0.03676092060635594, "se": 0.04162695338340437, "worst": [{"seed": 694100, "d": -2.036430033328088}, {"seed": 694178, "d": -1.0913672880157037}, {"seed": 694253, "d": -1.0391134367504264}, {"seed": 694254, "d": -1.0084921662552233}, {"seed": 694127, "d": -1.0043835555153464}]}, "retail_edge_delta": {"mean": 0.7060886097328152, "se": 0.031843397931346024}, "arb_edge_delta": {"mean": -0.7428495303391727, "se": 0.02612625762358992}, "reconciliation": {"retail_plus_arb": -0.036760920606357494, "total": -0.03676092060635594, "abs_error": 1.5543122344752192e-15}, "arm_means": {"v10": 524.6038646870915, "candidate": 524.5671037664852}, "gas": {"max_ok": 202247, "init_max_ok": 220959, "oog": 0, "revert": 0, "other_halt": 0, "tx_error": 0, "bad_return": 0}}, "V10_gas": {"max_ok": 192739, "init_max_ok": 220981, "oog": 0, "revert": 0, "other_halt": 0, "tx_error": 0, "bad_return": 0}}, "freeze": {"sha256": "d11fe36b99e607fefacdca7ff7875ea24c02063e27c53a705928d0ec13bcd4ad", "rule": "higher recheck mean of the two (both negative); frozen before held-out run", "novel": true}, "heldout_695000_695511": {"paired": {"n": 512, "mean_diff": -0.04066733023626756, "se": 0.020227261465642115, "worst": [{"seed": 695235, "d": -1.4783027198102445}, {"seed": 695395, "d": -1.2742142908685423}, {"seed": 695241, "d": -1.2733537877078334}, {"seed": 695126, "d": -1.0574616848291498}, {"seed": 695456, "d": -1.0559378051987096}]}, "retail_edge_delta": {"mean": 0.7277613712419916, "se": 0.0212116762606775}, "arb_edge_delta": {"mean": -0.7684287014782585, "se": 0.009239921621876089}, "reconciliation": {"retail_plus_arb": -0.040667330236266896, "total": -0.04066733023626756, "abs_error": 6.661338147750939e-16}, "arm_means": {"v10": 524.2872167320719, "candidate": 524.2465494018356}}, "paired": {"n": 512, "mean_diff": -0.04066733023626756, "se": 0.020227261465642115, "worst": [{"seed": 695235, "d": -1.4783027198102445}, {"seed": 695395, "d": -1.2742142908685423}, {"seed": 695241, "d": -1.2733537877078334}, {"seed": 695126, "d": -1.0574616848291498}, {"seed": 695456, "d": -1.0559378051987096}]}, "retail_edge_delta": {"mean": 0.7277613712419916, "se": 0.0212116762606775}, "arb_edge_delta": {"mean": -0.7684287014782585, "se": 0.009239921621876089}, "reconciliation": {"retail_plus_arb": -0.040667330236266896, "total": -0.04066733023626756, "abs_error": 6.661338147750939e-16, "method": "V10 decomposition: arb edge reconstructed from step fair prices, preceding spot and fees (closed-form optimal arb); retail = total - arb. Numerical reconstruction, so retail+arb = total by construction."}, "gas": {"candidate_heldout": {"max_ok": 199295, "oog": 0}, "V10_heldout": {"max_ok": 192838, "oog": 0}, "candidate_recheck": {"max_ok": 202247, "oog": 0}, "A_recheck": {"max_ok": 202348, "oog": 0}, "V10_recheck": {"max_ok": 192739, "oog": 0}, "search_max_afterSwap": 203113, "search_oog_total": 0, "afterInitialize_max_ok": {"candidate": 220959, "V10": 220981}, "scope": "afterSwap max_ok gas for Submission role; afterInitialize reported separately; amm_sim_rs.gas_stats_reset()/gas_stats() around every <=20-seed chunk of every arm."}, "halt_counts": {"candidate_heldout": {"oog": 0, "revert": 0, "other_halt": 0, "tx_error": 0, "bad_return": 0}, "V10_heldout": {"oog": 0, "revert": 0, "other_halt": 0, "tx_error": 0, "bad_return": 0}, "candidate_recheck": {"oog": 0, "revert": 0, "other_halt": 0, "tx_error": 0, "bad_return": 0}, "A_recheck": {"oog": 0, "revert": 0, "other_halt": 0, "tx_error": 0, "bad_return": 0}, "search_all": "0 for all 39 evaluated hashes and V10 search blocks"}, "seed_ledger": {"zero_intervention_check": "690000..690015 (16, also V10 and t=0.5 smoke: -48.7)", "search": [[690000, 690031], [690032, 690063], [690064, 690095]], "recheck": "694000..694255 (256; V10, A, B)", "heldout": "695000..695511 (512; V10, B; run once)", "dropped_seeds": 0, "seeds_ge_5000000_used": false}, "validation": {"amm_match_validate": "Strategy 'disp_ctl' validated successfully!", "compiled_with": "solc 0.8.24 via pinned SolidityCompiler", "setup": "amm-challenge @6b6921f8, pinned wheel sha256 checked, StarterStrategy validated", "CH_check": "not rerun (brief: CH already verified in V10)"}, "result_summary": "No gain. Retail-displacement steering of both band endpoints did not beat V10: held-out paired -0.0407 +- 0.0202 (n=512). Direct translation in either direction loses (t=+0.5 loses ~49; |t|~0.02-0.05 loses 0.3-0.45); widening loses up to ~0.9; narrowing the band with |D| and the coupled family hover at 0 within noise on 32-seed blocks and are negative on 256-seed recheck.", "limitations": ["Search was short: 3 CMA generations (39 evals, 32 seeds each), far from converged; 32-seed block SE (~0.05-0.1) is comparable to the effects sought.", "Only paired against V10; not against STACK; seeds_kind=tuning, no board claim.", "D uses relative spot change; only previous-print spot is used (causal).", "arb/retail split is a reconstruction (V10 method), not simulator counters."], "board_claim": null}