{"item":"a","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[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        (fastHat, uncertainty) = _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 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        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) {\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));\n            }\n            return (x.mu,x.v);\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);\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":"cd9bdb45ab0537ad25c4fd90ca8618898cef6386de3df65f192eaef65fbca245","settings":{"base":"V10","base_sha256":"cd9bdb45ab0537ad25c4fd90ca8618898cef6386de3df65f192eaef65fbca245","stack_sha256":"2eaafc7960e520b8a7fd322ec8afaff8fa677c730228a961efb509cc30b25719","STALE_ATTRACT_FRAC":1.05,"post_stale_lower_fee_multiplier":1.0,"first_in_step_lower_cap_bps":30,"screen_seeds":{"start":480000,"stop_exclusive":480128},"shortlist_seeds":{"start":480128,"stop_exclusive":480512},"combo_settings":{},"frozen":{"name":"combo","sha256":"cd9bdb45ab0537ad25c4fd90ca8618898cef6386de3df65f192eaef65fbca245","selection":"highest mean paired gain versus V10 on seeds 480128..480511; no confirmation selection"}},"screen":[{"axis":"A","value":1.3,"n":128,"mean_diff":-0.556554454830585,"se":0.04450859834883098},{"axis":"A","value":1.6,"n":128,"mean_diff":-1.5468459376981838,"se":0.05743759183153688},{"axis":"A","value":2.0,"n":128,"mean_diff":-2.7181914333159445,"se":0.06477597691419175},{"axis":"B","value":0.85,"n":128,"mean_diff":-0.421240158164395,"se":0.04180939112413315},{"axis":"B","value":0.9,"n":128,"mean_diff":-0.2482874732522773,"se":0.028946084856249124},{"axis":"B","value":0.95,"n":128,"mean_diff":-0.10153360480085194,"se":0.025010339224656515},{"axis":"C","value":26,"n":128,"mean_diff":-0.018527335435741143,"se":0.01332824217253798},{"axis":"C","value":28,"n":128,"mean_diff":-0.002166037355830319,"se":0.009170983413432657}],"shortlist":[{"name":"combo","vs_v10":{"n":384,"mean_diff":0.0,"se":0.0,"worst":[{"seed":480128,"d":0.0},{"seed":480129,"d":0.0},{"seed":480130,"d":0.0},{"seed":480131,"d":0.0},{"seed":480132,"d":0.0}]},"retail_edge_delta":{"mean":0.0,"se":0.0},"arb_edge_delta":{"mean":0.0,"se":0.0},"gas":{"max_ok":192838,"oog":0,"revert":0,"other_halt":0,"tx_error":0,"bad_return":0}},{"name":"C28","vs_v10":{"n":384,"mean_diff":-0.004624628836863505,"se":0.004758737198527349,"worst":[{"seed":480239,"d":-0.59068742970112},{"seed":480291,"d":-0.42546206868553327},{"seed":480385,"d":-0.33346145549239736},{"seed":480285,"d":-0.33075957855430715},{"seed":480227,"d":-0.29012960053563575}]},"retail_edge_delta":{"mean":0.0018993150405721693,"se":0.004937266287288224},"arb_edge_delta":{"mean":-0.006523943877434268,"se":0.0016556242959094335},"gas":{"max_ok":192838,"oog":0,"revert":0,"other_halt":0,"tx_error":0,"bad_return":0}},{"name":"C26","vs_v10":{"n":384,"mean_diff":-0.01750121227830374,"se":0.006875077128051377,"worst":[{"seed":480153,"d":-0.5989939064422742},{"seed":480291,"d":-0.5530698496972946},{"seed":480252,"d":-0.41261290439933873},{"seed":480482,"d":-0.31808150237475274},{"seed":480239,"d":-0.302240153922412}]},"retail_edge_delta":{"mean":0.0011414016427557054,"se":0.006950712609332291},"arb_edge_delta":{"mean":-0.018642613921058326,"se":0.0027676449821427505},"gas":{"max_ok":192838,"oog":0,"revert":0,"other_halt":0,"tx_error":0,"bad_return":0}}],"confirm":{"seeds":{"start":5020000,"stop_exclusive":5022000},"vs_stack":{"n":2000,"mean_diff":0.11694634196808508,"se":0.015019437639641227,"worst":[{"seed":5020480,"d":-4.7258718593310505},{"seed":5021265,"d":-4.369598290005683},{"seed":5021246,"d":-3.640898793166457},{"seed":5021629,"d":-3.0038913864599976},{"seed":5021989,"d":-2.604752314195707}]},"vs_v10":{"n":2000,"mean_diff":0.0,"se":0.0,"worst":[{"seed":5020000,"d":0.0},{"seed":5020001,"d":0.0},{"seed":5020002,"d":0.0},{"seed":5020003,"d":0.0},{"seed":5020004,"d":0.0}]},"retail_edge_delta":{"mean":-1.1413228240546553,"se":0.014977487518045528},"arb_edge_delta":{"mean":1.25826916602274,"se":0.008088000581186904},"gas":{"max_ok":194858,"oog":0,"arms":{"candidate":{"max_ok":194858,"oog":0,"revert":0,"other_halt":0,"tx_error":0,"bad_return":0,"raw_counters":[{"role":"Baseline","callback":"afterInitialize","calls":2000,"ok":2000,"max_ok_gas":21796,"sum_ok_gas":43592000,"oog":0,"revert":0,"other_halt":0,"tx_error":0,"bad_return":0},{"role":"Baseline","callback":"afterSwap","calls":21367098,"ok":21367098,"max_ok_gas":22592,"sum_ok_gas":482105456268,"oog":0,"revert":0,"other_halt":0,"tx_error":0,"bad_return":0},{"role":"Baseline","callback":"getName","calls":2000,"ok":2000,"max_ok_gas":21526,"sum_ok_gas":43052000,"oog":0,"revert":0,"other_halt":0,"tx_error":0,"bad_return":0},{"role":"Submission","callback":"afterInitialize","calls":2000,"ok":2000,"max_ok_gas":220981,"sum_ok_gas":441962000,"oog":0,"revert":0,"other_halt":0,"tx_error":0,"bad_return":0},{"role":"Submission","callback":"afterSwap","calls":20393960,"ok":20393960,"max_ok_gas":194858,"sum_ok_gas":2258462882387,"oog":0,"revert":0,"other_halt":0,"tx_error":0,"bad_return":0},{"role":"Submission","callback":"getName","calls":2000,"ok":2000,"max_ok_gas":21594,"sum_ok_gas":43188000,"oog":0,"revert":0,"other_halt":0,"tx_error":0,"bad_return":0}]},"STACK":{"max_ok":213569,"oog":0,"revert":0,"other_halt":0,"tx_error":0,"bad_return":0,"raw_counters":[{"role":"Baseline","callback":"afterInitialize","calls":2000,"ok":2000,"max_ok_gas":21796,"sum_ok_gas":43592000,"oog":0,"revert":0,"other_halt":0,"tx_error":0,"bad_return":0},{"role":"Baseline","callback":"afterSwap","calls":21409777,"ok":21409777,"max_ok_gas":22592,"sum_ok_gas":483067789424,"oog":0,"revert":0,"other_halt":0,"tx_error":0,"bad_return":0},{"role":"Baseline","callback":"getName","calls":2000,"ok":2000,"max_ok_gas":21526,"sum_ok_gas":43052000,"oog":0,"revert":0,"other_halt":0,"tx_error":0,"bad_return":0},{"role":"Submission","callback":"afterInitialize","calls":2000,"ok":2000,"max_ok_gas":220962,"sum_ok_gas":441924000,"oog":0,"revert":0,"other_halt":0,"tx_error":0,"bad_return":0},{"role":"Submission","callback":"afterSwap","calls":20639369,"ok":20639369,"max_ok_gas":213569,"sum_ok_gas":2031636112641,"oog":0,"revert":0,"other_halt":0,"tx_error":0,"bad_return":0},{"role":"Submission","callback":"getName","calls":2000,"ok":2000,"max_ok_gas":21576,"sum_ok_gas":43152000,"oog":0,"revert":0,"other_halt":0,"tx_error":0,"bad_return":0}]},"V10":{"max_ok":194858,"oog":0,"revert":0,"other_halt":0,"tx_error":0,"bad_return":0,"raw_counters":[{"role":"Baseline","callback":"afterInitialize","calls":2000,"ok":2000,"max_ok_gas":21796,"sum_ok_gas":43592000,"oog":0,"revert":0,"other_halt":0,"tx_error":0,"bad_return":0},{"role":"Baseline","callback":"afterSwap","calls":21367098,"ok":21367098,"max_ok_gas":22592,"sum_ok_gas":482105456268,"oog":0,"revert":0,"other_halt":0,"tx_error":0,"bad_return":0},{"role":"Baseline","callback":"getName","calls":2000,"ok":2000,"max_ok_gas":21526,"sum_ok_gas":43052000,"oog":0,"revert":0,"other_halt":0,"tx_error":0,"bad_return":0},{"role":"Submission","callback":"afterInitialize","calls":2000,"ok":2000,"max_ok_gas":220981,"sum_ok_gas":441962000,"oog":0,"revert":0,"other_halt":0,"tx_error":0,"bad_return":0},{"role":"Submission","callback":"afterSwap","calls":20393960,"ok":20393960,"max_ok_gas":194858,"sum_ok_gas":2258462882387,"oog":0,"revert":0,"other_halt":0,"tx_error":0,"bad_return":0},{"role":"Submission","callback":"getName","calls":2000,"ok":2000,"max_ok_gas":21594,"sum_ok_gas":43188000,"oog":0,"revert":0,"other_halt":0,"tx_error":0,"bad_return":0}]}}},"valid":true,"arm_means":{"candidate":{"total_edge":524.8165776453035,"retail_edge":551.5158013432825,"arb_edge":-26.69922369797904},"STACK":{"total_edge":524.6996313033355,"retail_edge":552.6571241673372,"arb_edge":-27.957492864001775},"V10":{"total_edge":524.8165776453035,"retail_edge":551.5158013432825,"arb_edge":-26.69922369797904}},"vs_v10_retail_edge_delta":{"mean":0.0,"se":0.0},"vs_v10_arb_edge_delta":{"mean":0.0,"se":0.0},"reconciliation_max_abs":1.1368683772161603e-13},"notes":{"outcome":"All eight cheaper-fee screens had negative mean paired gains versus V10; both cap finalists also lost on the next 384 seeds. The frozen result is V10 unchanged. Local paired experiment only; no leaderboard submission or top-10 claim.","calibration":{"n":1000,"seeds":"0..999","mean_edge":525.5258821780834,"expected":525.5258821780834,"absolute_error":0.0,"gas":{"max_ok":151647,"oog":0,"revert":0,"other_halt":0,"tx_error":0,"bad_return":0,"raw_counters":[{"role":"Baseline","callback":"afterInitialize","calls":1000,"ok":1000,"max_ok_gas":21796,"sum_ok_gas":21796000,"oog":0,"revert":0,"other_halt":0,"tx_error":0,"bad_return":0},{"role":"Baseline","callback":"afterSwap","calls":10741746,"ok":10741746,"max_ok_gas":22592,"sum_ok_gas":242365461576,"oog":0,"revert":0,"other_halt":0,"tx_error":0,"bad_return":0},{"role":"Baseline","callback":"getName","calls":1000,"ok":1000,"max_ok_gas":21526,"sum_ok_gas":21526000,"oog":0,"revert":0,"other_halt":0,"tx_error":0,"bad_return":0},{"role":"Submission","callback":"afterInitialize","calls":1000,"ok":1000,"max_ok_gas":185532,"sum_ok_gas":185532000,"oog":0,"revert":0,"other_halt":0,"tx_error":0,"bad_return":0},{"role":"Submission","callback":"afterSwap","calls":10445223,"ok":10445223,"max_ok_gas":151647,"sum_ok_gas":811927105393,"oog":0,"revert":0,"other_halt":0,"tx_error":0,"bad_return":0},{"role":"Submission","callback":"getName","calls":1000,"ok":1000,"max_ok_gas":21530,"sum_ok_gas":21530000,"oog":0,"revert":0,"other_halt":0,"tx_error":0,"bad_return":0}]}},"method":"Each strategy independently against VanillaStrategy via amm_sim_rs.run_batch(arm, Vanilla, configs, 8). No two candidates share a market. Configs use default_rng(seed), drawing size U[19,21], rate U[.6,1], sigma U[.000882,.001008] in that order; price seed=seed and retail seed=seed+1. 10000 steps, initial price=100, X=100, Y=10000, mu=0, dt=1, retail size sigma=1.2 and buy probability=.5.","selection":"For each axis select its highest positive screen mean versus V10; combine those changes. Combo and the two singles with highest screen means advance. Freeze the highest shortlist mean versus V10 before confirmation; no confirmation-driven edits. Screen/shortlist runs retain every assigned seed. Confirmation is half-open [5020000,5022000), 2000 seeds; each distinct source executed once per seed; if frozen equals V10, vs_v10 is the exact self-difference and its arm counters alias the candidate.","stats":"Paired d=edge_candidate-edge_reference, se=sample standard deviation(ddof=1)/sqrt(n); worst lists the five smallest per-seed differences. Retail and arb deltas are means per seed with their own paired SEs; their SEs do not add.","mechanism":"A changes only STALE_ATTRACT_FRAC. B multiplies the numerically lower fee immediately after the stale block, before trade boost, tail compression and caps; equal fees are unchanged. C changes only the first-in-step lower-side cap; normalizer-observation 30 bps thresholds and the final 36 bps cap remain V10. No state-layout or permissions changes, no transfers or external calls. Fees remain clamped to [0,10%]; all data are causal TradeInfo and stored history. Simulator custody, constant-product accounting and independent market state are unchanged.","gas_policy":"gas_stats_reset before every arm/chunk and gas_stats immediately after. Raw counters sum calls and errors and maximize max_ok_gas over chunks. max_ok is Submission/afterSwap only; oog totals all roles/callbacks. All oog/revert/other_halt/tx_error/bad_return counters must be zero. Confirmation counters are separate from tuning. No dropped or retried seeds.","screen_gas":[{"axis":"A","value":1.3,"max_ok":192826,"oog":0,"revert":0,"other_halt":0,"tx_error":0,"bad_return":0},{"axis":"A","value":1.6,"max_ok":192826,"oog":0,"revert":0,"other_halt":0,"tx_error":0,"bad_return":0},{"axis":"A","value":2.0,"max_ok":192826,"oog":0,"revert":0,"other_halt":0,"tx_error":0,"bad_return":0},{"axis":"B","value":0.85,"max_ok":192909,"oog":0,"revert":0,"other_halt":0,"tx_error":0,"bad_return":0},{"axis":"B","value":0.9,"max_ok":192909,"oog":0,"revert":0,"other_halt":0,"tx_error":0,"bad_return":0},{"axis":"B","value":0.95,"max_ok":192909,"oog":0,"revert":0,"other_halt":0,"tx_error":0,"bad_return":0},{"axis":"C","value":26,"max_ok":192826,"oog":0,"revert":0,"other_halt":0,"tx_error":0,"bad_return":0},{"axis":"C","value":28,"max_ok":192826,"oog":0,"revert":0,"other_halt":0,"tx_error":0,"bad_return":0}],"screen_decomposition":[{"axis":"A","value":1.3,"retail_edge_delta":-0.39905342996186643,"arb_edge_delta":-0.15750102486871642},{"axis":"A","value":1.6,"retail_edge_delta":-1.2481297165675516,"arb_edge_delta":-0.2987162211306359},{"axis":"A","value":2.0,"retail_edge_delta":-2.257790016506061,"arb_edge_delta":-0.46040141680988},{"axis":"B","value":0.85,"retail_edge_delta":-0.30221427778726895,"arb_edge_delta":-0.11902588037712464},{"axis":"B","value":0.9,"retail_edge_delta":-0.16118340836298373,"arb_edge_delta":-0.08710406488929523},{"axis":"B","value":0.95,"retail_edge_delta":-0.05977577669842571,"arb_edge_delta":-0.04175782810242726},{"axis":"C","value":26,"retail_edge_delta":-0.0050080952231565945,"arb_edge_delta":-0.013519240212587047},{"axis":"C","value":28,"retail_edge_delta":0.004469713904005079,"arb_edge_delta":-0.0066357512598367585}],"reference_gas":{"480000":{"max_ok":192826,"oog":0,"revert":0,"other_halt":0,"tx_error":0,"bad_return":0},"480128":{"max_ok":192838,"oog":0,"revert":0,"other_halt":0,"tx_error":0,"bad_return":0}},"decomposition":{"method":"Negative optimal arb profit reconstructed from prior end-of-step spot+fees and current fair price, with constant k=initial_x*initial_y, initial fee=.0004; retail=edge-arb. This is numerical reconstruction, not direct trade-type edge instrumentation.","diagnostic":"32 seeds 480480..480511, 100 steps, retail_arrival_rate=0 (engine floors to .01); compare arb reconstruction with total edge only on independently identified paths having zero submission retail volume.","zero_retail_paths":12,"max_abs_error":9.750755758375362e-12},"behavioral_checks":{"calls":512,"fee_range":"0..0.1 WAD","first_in_step_lower_cap_bps":30,"isolation":true,"reset_determinism":true,"gas_note":"Gas validity comes from Rust gas_stats, not Python executor estimates."},"checks":{"passed":["Pinned checkout and wheel hash verified; setup completed once; StarterStrategy validated.","V10 and STACK source SHA256 hashes match brief.","CH 1000-seed calibration matches expected mean.","All candidates compile with pinned compiler; storage layout and forbidden-opcode checks pass.","Frozen candidate: amm-match validate scratch/frozen.sol passed.","All tuning and confirmation arms have complete seed coverage and zero error/halt counters.","512-call fee bounds, first-in-step cap, independent deployment and reset determinism checks passed.","Independent audit recomputed sample means and SEs, source hashes, seed coverage and halt counters.","JSON parse, sha256, byte limits and output scope checked."],"failed":[],"not_executed":["forge build / Foundry suite: pinned challenge is not a Foundry project (no foundry.toml); solc 0.8.24 challenge compiler used.","Slither: executable unavailable. Aderyn: executable present, not run; no compatible Foundry project.","No public transaction or leaderboard submission."]},"commands":["git clone https://github.com/benedictbrady/amm-challenge test/scratch/amm-challenge","git checkout 6b6921f8d463314aa7c96234e1be25a25245f704","sh scratch/setup.sh (once, succeeded)",". scratch/env.sh && python scratch/fetch.py",". scratch/env.sh && python scratch/calibrate.py",". scratch/env.sh && python scratch/experiment.py screen",". scratch/env.sh && python scratch/check_decomposition.py",". scratch/env.sh && amm-match validate scratch/frozen.sol",". scratch/env.sh && python scratch/behavior.py",". scratch/env.sh && python scratch/experiment.py confirm",". scratch/env.sh && python scratch/sources.py",". scratch/env.sh && python scratch/report.py",". scratch/env.sh && python scratch/audit.py"],"reproducibility":{"repository":"https://github.com/benedictbrady/amm-challenge","commit":"6b6921f8d463314aa7c96234e1be25a25245f704","wheel_sha256":"aedb68280aca34c110968f00148387c95885207913fb2cf19a1ab4c5cfd6887a","wheel_url":"https://github.com/gtmcknight/amm-sim/releases/download/sim-6b6921f8/amm_sim_rs-0.1.0.post1-cp310-abi3-manylinux2014_x86_64.manylinux_2_17_x86_64.whl","setup_source":"set -eu;R=$PWD/scratch;mkdir -p $R/tmp $R/bin $R/solcx\necho \"export TMPDIR=$R/tmp XDG_CACHE_HOME=$R/xc UV_CACHE_DIR=$R/uvc UV_PYTHON_INSTALL_DIR=$R/uvpy SOLCX_BINARY_PATH=$R/solcx VIRTUAL_ENV=$PWD/.venv PATH=$PWD/.venv/bin:$R/bin:\\$PATH\" >$R/env.sh;. $R/env.sh\ncommand -v uv >/dev/null||{ curl -LsSf https://github.com/astral-sh/uv/releases/latest/download/uv-x86_64-unknown-linux-gnu.tar.gz|tar --no-same-owner -xz -C $R/tmp;cp $R/tmp/uv-*/uv $R/bin/;}\nW=amm_sim_rs-0.1.0.post1-cp310-abi3-manylinux2014_x86_64.manylinux_2_17_x86_64.whl;curl -LsSf https://github.com/gtmcknight/amm-sim/releases/download/sim-6b6921f8/$W -o $R/$W\necho \"aedb68280aca34c110968f00148387c95885207913fb2cf19a1ab4c5cfd6887a  $R/$W\"|sha256sum -c -\nuv venv --python 3.12 .venv;uv pip install $R/$W numpy py-solc-x==2.1.0 pyrevm==0.3.7;uv pip install --no-deps -e .\npython -c \"import solcx;solcx.install_solc('0.8.24')\"\namm-match validate contracts/src/StarterStrategy.sol\n","compiler":"SolidityCompiler: solc 0.8.24, optimizer 200, viaIR=true, evmVersion=paris","base_dependencies":["contracts/src/AMMStrategyBase.sol","contracts/src/IAMMStrategy.sol"],"runtime":{"python":"3.12.16","numpy":"2.5.4","py_solc_x":"2.1.0","pyrevm":"0.3.7"}},"source_attribution":"External inputs and engine formulas are identified in sources.json with exact quotations. Performance statistics, gas, calibration and checks are measurements made in this run, not claims copied from those sources.","harness_source":"\"\"\"Run from the pinned amm-challenge checkout, with the brief's environment active.\npython harness.py --start 5000000 --n 2000 --out measured.json candidate.sol STACK.sol\nDo not use confirmation seeds to choose or change a strategy.\n\"\"\"\nimport argparse,hashlib,json,math\nfrom pathlib import Path\nimport numpy as np\nimport amm_sim_rs as sim\nfrom amm_competition.evm.compiler import SolidityCompiler\n\n\ndef configs(start,n):\n    configs=[]\n    for seed in range(start,start+n):\n        rng=np.random.default_rng(seed)\n        size=rng.uniform(19.,21.)\n        rate=rng.uniform(.6,1.)\n        sigma=rng.uniform(.000882,.001008)\n        configs.append(sim.SimulationConfig(n_steps=10000,initial_price=100.,\n            initial_x=100.,initial_y=10000.,gbm_mu=0.,gbm_sigma=sigma,gbm_dt=1.,\n            retail_arrival_rate=rate,retail_mean_size=size,retail_size_sigma=1.2,\n            retail_buy_prob=.5,seed=seed))\n    return configs\n\n\ndef decomposition(r,initial_fee=.0004):\n    # Fees are outside reserves, so k stays fixed up to floating-point roundoff.\n    # The arb acts before retail, using the preceding step's final spot and fees.\n    steps=r.steps\n    fair=np.array([s.fair_price for s in steps])\n    spots=np.array([r.initial_fair_price]+[s.spot_prices['submission'] for s in steps[:-1]])\n    bids=np.array([initial_fee]+[s.fees['submission'][0] for s in steps[:-1]])\n    asks=np.array([initial_fee]+[s.fees['submission'][1] for s in steps[:-1]])\n    x0,y0=r.initial_reserves['submission'];k=x0*y0\n    x=np.sqrt(k/spots);y=np.sqrt(k*spots)\n    ga=1-asks;gb=1-bids\n    out=np.minimum(np.maximum(x-np.sqrt(k/(ga*fair)),0),.99*x)\n    paid=(k/(x-out)-y)/ga\n    buyprofit=np.where(out>0,np.maximum(out*fair-paid,0),0)\n    gross=np.maximum((np.sqrt(k*gb/fair)-x)/gb,0)\n    received=y-k/(x+gb*gross)\n    sellprofit=np.where(gross>0,np.maximum(received-gross*fair,0),0)\n    arb=-float(np.sum(np.where(spots<fair,buyprofit,sellprofit)))\n    return arb,r.edges['submission']-arb\n\n\ndef aggregate(chunks):\n    out={}\n    for chunk in chunks:\n        for row in chunk['raw']:\n            key=(row['role'],row['callback'])\n            dest=out.setdefault(key,{'role':row['role'],'callback':row['callback']})\n            for k,v in row.items():\n                if k in ['role','callback']:continue\n                dest[k]=max(dest.get(k,0),v) if k=='max_ok_gas' else dest.get(k,0)+v\n    return list(out.values())\n\n\ndef run(source,start,n,vanilla,compiler):\n    compiled=compiler.compile(source)\n    assert compiled.success,compiled.errors\n    rows=[];chunks=[]\n    for first in range(start,start+n,20):\n        count=min(20,start+n-first)\n        sim.gas_stats_reset()\n        batch=sim.run_batch(list(compiled.bytecode),list(vanilla),configs(first,count),8)\n        results=batch.results\n        assert sorted(r.seed for r in results)==list(range(first,first+count))\n        for r in results:\n            arb,retail=decomposition(r)\n            rows.append({'seed':r.seed,'edge':r.edges['submission'],'arb':arb,'retail':retail})\n        chunks.append({'start':first,'raw':sim.gas_stats()})\n        print('progress',first,count,flush=True)\n        del results,batch\n    return {'sha256':hashlib.sha256(source.encode()).hexdigest(),'rows':rows,\n            'raw_counters':aggregate(chunks),'chunks':chunks}\n\n\ndef stats(d):\n    d=np.asarray(d,dtype=float)\n    return {'mean':float(d.mean()),'se':float(d.std(ddof=1)/np.sqrt(len(d)))}\n\n\ndef compare(candidate,stack):\n    a={r['seed']:r for r in candidate['rows']};b={r['seed']:r for r in stack['rows']}\n    assert a.keys()==b.keys()\n    seeds=sorted(a)\n    d=np.array([a[s]['edge']-b[s]['edge'] for s in seeds])\n    arb=np.array([a[s]['arb']-b[s]['arb'] for s in seeds])\n    retail=np.array([a[s]['retail']-b[s]['retail'] for s in seeds])\n    assert np.max(np.abs(d-arb-retail))<1e-8\n    summary=stats(d)\n    return {'paired':{'n':len(d),'mean_diff':summary['mean'],'se':summary['se'],\n                'worst':[{'seed':seeds[i],'d':float(d[i])} for i in np.argsort(d)[:5]]},\n            'retail_edge_delta':stats(retail),'arb_edge_delta':stats(arb),\n            'reconciliation_max_abs':float(np.max(np.abs(d-arb-retail)))}\n\n\nif __name__=='__main__':\n    p=argparse.ArgumentParser()\n    p.add_argument('--start',type=int,required=True);p.add_argument('--n',type=int,required=True)\n    p.add_argument('--out',required=True);p.add_argument('candidate');p.add_argument('stack')\n    args=p.parse_args()\n    compiler=SolidityCompiler()\n    vanilla=compiler.compile(Path('contracts/src/VanillaStrategy.sol').read_text(),'VanillaStrategy')\n    assert vanilla.success,vanilla.errors\n    candidate=run(Path(args.candidate).read_text(),args.start,args.n,vanilla.bytecode,compiler)\n    stack=run(Path(args.stack).read_text(),args.start,args.n,vanilla.bytecode,compiler)\n    out=compare(candidate,stack);out.update(candidate=candidate,stack=stack)\n    errors=['oog','revert','other_halt','tx_error','bad_return']\n    out['valid']=all(not any(row.get(e,0) for e in errors)\n        for arm in [candidate,stack] for row in arm['raw_counters'])\n    Path(args.out).write_text(json.dumps(out,allow_nan=False))\n    print(json.dumps({k:v for k,v in out.items() if k not in ['candidate','stack']}))\n","experiment_source":"import json,time,hashlib,subprocess\nfrom pathlib import Path\nimport numpy as np\nfrom harness import configs,decomposition,aggregate,compare,stats,SolidityCompiler\nimport amm_sim_rs as sim\nROOT=Path('scratch'); errors=['oog','revert','other_halt','tx_error','bad_return']\ndef gas(r):\n rows=r['raw_counters'];return dict(max_ok=max(x['max_ok_gas'] for x in rows if x['role']=='Submission' and x['callback']=='afterSwap'),**{k:sum(x.get(k,0) for x in rows) for k in errors},raw_counters=rows)\ndef runarm(name,start,n):\n out=ROOT/f'{name}_{start}_{n}.json'\n assert not out.exists(),out\n source=(ROOT/f'{name}.sol').read_text(); a=compiler.compile(source);assert a.success,a.errors\n rows=[];chunks=[];t=time.time()\n for first in range(start,start+n,8):\n  count=min(8,start+n-first);sim.gas_stats_reset()\n  batch=sim.run_batch(list(a.bytecode),list(vanilla.bytecode),configs(first,count),8)\n  results=batch.results;assert sorted(r.seed for r in results)==list(range(first,first+count))\n  for r in results:\n   arb,retail=decomposition(r);rows.append(dict(seed=r.seed,edge=r.edges['submission'],arb=arb,retail=retail))\n  chunks.append(dict(start=first,raw=sim.gas_stats()));del results,batch\n  print(name,first,count,'elapsed',round(time.time()-t,2),flush=True)\n result=dict(sha256=hashlib.sha256(source.encode()).hexdigest(),rows=rows,raw_counters=aggregate(chunks),elapsed=time.time()-t)\n result['gas']=gas(result);result['valid']=all(result['gas'][k]==0 for k in errors)\n out.write_text(json.dumps(result));assert result['valid'],result['gas'];return result\n\ndef variant(a=None,b=None,c=None):\n s=(ROOT/'V10.sol').read_text()\n if a is not None:s=s.replace('STALE_ATTRACT_FRAC = 1050000000000000000','STALE_ATTRACT_FRAC = '+str(round(a*1e18)))\n if b is not None:\n  needle='''        {\\n            bool tradeAligned'''\n  assert needle in s\n  s=s.replace(needle,'''        // Discount the lower fee immediately after the stale-price adjustment.\\n        if (bidFee < askFee) bidFee = wmul(bidFee, %d);\\n        else if (askFee < bidFee) askFee = wmul(askFee, %d);\\n\\n'''%(round(b*1e18),round(b*1e18))+needle)\n if c is not None:\n  old='''        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  assert old in s;s=s.replace(old,old.replace('30 * BPS',str(c)+' * BPS'))\n return s\n\ncompiler=SolidityCompiler();vanilla=compiler.compile(Path('contracts/src/VanillaStrategy.sol').read_text(),'VanillaStrategy');assert vanilla.success,vanilla.errors\nif __name__=='__main__':\n import sys\n mode=sys.argv[1]\n if mode=='screen':\n  base=runarm('V10',480000,128);screen=[]\n  for axis,values in [('A',[1.3,1.6,2.0]),('B',[.85,.9,.95]),('C',[26,28])]:\n   for v in values:\n    name=axis+str(v).replace('.','p');kw={dict(A='a',B='b',C='c')[axis]:v}\n    (ROOT/f'{name}.sol').write_text(variant(**kw));r=runarm(name,480000,128)\n    p=compare(r,base);entry=dict(axis=axis,value=v,name=name,n=128,mean_diff=p['paired']['mean_diff'],se=p['paired']['se'],gas=r['gas'],valid=r['valid'])\n    screen.append(entry);(ROOT/'screen.json').write_text(json.dumps(screen));print('SCREEN',json.dumps(entry),flush=True)\n  best=[]\n  for axis in ['A','B','C']:\n   x=max((r for r in screen if r['axis']==axis),key=lambda r:r['mean_diff'])\n   if x['mean_diff']>0:best.append(x)\n  kw={dict(A='a',B='b',C='c')[r['axis']]:r['value'] for r in best};(ROOT/'combo.sol').write_text(variant(**kw))\n  singles=sorted(screen,key=lambda r:r['mean_diff'],reverse=True)[:2]\n  shortlist=['combo']+[r['name'] for r in singles]\n  (ROOT/'selection.json').write_text(json.dumps(dict(combo_settings=kw,shortlist=shortlist)))\n  base=runarm('V10',480128,384);short=[]\n  for name in shortlist:\n   r=runarm(name,480128,384);p=compare(r,base)\n   short.append(dict(name=name,**p,gas=r['gas']));(ROOT/'shortlist.json').write_text(json.dumps(short));print('SHORTLIST',json.dumps(short[-1]),flush=True)\n  winner=max(short,key=lambda r:r['paired']['mean_diff'])['name']\n  (ROOT/'frozen.sol').write_text((ROOT/f'{winner}.sol').read_text())\n  freeze=dict(name=winner,sha256=hashlib.sha256((ROOT/'frozen.sol').read_bytes()).hexdigest(),selection='highest mean paired gain versus V10 on seeds 480128..480511; no confirmation selection')\n  (ROOT/'freeze.json').write_text(json.dumps(freeze));print('FROZEN',freeze,flush=True)\n  subprocess.run(['amm-match','validate','scratch/frozen.sol'],check=True)\n elif mode=='confirm':\n  assert (ROOT/'freeze.json').exists()\n  a=runarm('frozen',5020000,2000);b=runarm('STACK',5020000,2000)\n  identical_v10=(ROOT/'frozen.sol').read_bytes()==(ROOT/'V10.sol').read_bytes()\n  v=a if identical_v10 else runarm('V10',5020000,2000)\n  out=dict(seeds=dict(start=5020000,stop_exclusive=5022000),vs_stack=compare(a,b),vs_v10=compare(a,v),gas=dict(candidate=a['gas'],STACK=b['gas'],V10=v['gas']))\n  (ROOT/'confirm.json').write_text(json.dumps(out));print('CONFIRM',json.dumps(out),flush=True)\n"}}
