{"item":"a","batch":"e09-learn-head","code":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.24;\n\nimport {AMMStrategyBase} from \"./AMMStrategyBase.sol\";\nimport {TradeInfo} from \"./IAMMStrategy.sol\";\n\ncontract Strategy is AMMStrategyBase {\n    uint256 constant ELAPSED_CAP = 8;\n    uint256 constant SIGNAL_THRESHOLD = WAD / 650;\n    uint256 constant DIR_DECAY = 750000000000000000;\n    uint256 constant ACT_DECAY = 530000000000000000;\n    uint256 constant SIZE_DECAY = 530000000000000000;\n    uint256 constant TOX_DECAY = 910000000000000000;\n    uint256 constant SIGMA_DECAY = 690000000000000000;\n    uint256 constant LAMBDA_DECAY = 990000000000000000;\n    uint256 constant SIZE_BLEND_DECAY = 828000000000000000;\n    uint256 constant TOX_BLEND_DECAY = 51000000000000000;\n    uint256 constant ACT_BLEND_DECAY = 985000000000000000;\n    uint256 constant PHAT_ALPHA = 270000000000000000;\n    uint256 constant PHAT_ALPHA_RETAIL = 60000000000000000;\n    uint256 constant PHAT_ALPHA_SAME = 120000000000000000;\n    uint256 constant REVERT_U = 0;\n    uint256 constant DIR_IMPACT_MULT = 4;\n    uint256 constant GATE_SIGMA_MULT = 7200000000000000000;\n    uint256 constant MIN_GATE = 30000000000000000;\n    uint256 constant TRADE_TOX_BOOST = 3500 * BPS;\n    uint256 constant STALE_ATTRACT_FRAC = 1050000000000000000;\n    uint256 constant RET_CAP = WAD / 35;\n    uint256 constant TOX_CAP = WAD / 5;\n    uint256 constant TRADE_RATIO_CAP = WAD / 5;\n    uint256 constant LAMBDA_CAP = 1820000000000000000;\n    uint256 constant STEP_COUNT_CAP = 64;\n    uint256 constant BASE_FEE = 4 * BPS;\n    uint256 constant SIGMA_COEF = 200000000000000000;\n    uint256 constant LAMBDA_COEF = 12 * BPS;\n    uint256 constant FLOW_SIZE_COEF = 4842 * BPS;\n    uint256 constant TOX_COEF = 300 * BPS;\n    uint256 constant TOX_QUAD_COEF = 15000 * BPS;\n    uint256 constant ACT_COEF = 91843 * BPS;\n    uint256 constant DIR_COEF = 20 * BPS;\n    uint256 constant DIR_TOX_COEF = 100 * BPS;\n    uint256 constant STALE_DIR_COEF = 6850 * BPS;\n    uint256 constant SIGMA_TOX_COEF = 500 * BPS;\n    uint256 constant TAIL_KNEE = 600 * BPS;\n    uint256 constant TAIL_SLOPE_PROTECT = 930000000000000000;\n    uint256 constant TAIL_SLOPE_ATTRACT = 850000000000000000;\n\n    function afterInitialize(uint256 initialX, uint256 initialY) external override returns (uint256, uint256) {\n        slots[0] = BASE_FEE; slots[1] = BASE_FEE; slots[3] = WAD; \n        slots[5] = initialX > 0 ? wdiv(initialY, initialX) : 100 * WAD;\n        slots[6] = 950000000000000; slots[7] = 800000000000000000; slots[8] = 2000000000000000;\n        slots[15] = 400000000000000000 | (uint256(2000000000000000) << 160); slots[13] = 902500000000; slots[14] = slots[5]; \n        return (BASE_FEE, BASE_FEE);\n    }\n\n    function afterSwap(TradeInfo calldata trade) external override returns (uint256, uint256) {\n        uint256 prevBidFee = slots[0]; uint256 prevAskFee = slots[1]; uint256 lastTs = uint64(slots[2]);\n        uint256 dirState = slots[3]; uint256 actEma = slots[4]; uint256 pHat = slots[5];\n        uint256 sigmaHat = slots[6]; uint256 lambdaHat = slots[7]; uint256 sizeHat = slots[8];\n        uint256 toxEma = slots[9]; uint256 stepTradeCount = slots[10];\n\n        uint256 sigmaForFast = sigmaHat;\n        uint256 fastHat = slots[14];\n        uint256 uncertainty = slots[13];\n        uint256 silent = trade.timestamp > lastTs ? trade.timestamp - lastTs : 0;\n        bool isNewStep = trade.timestamp > lastTs;\n        if (isNewStep) {\n            uint256 elapsedRaw = trade.timestamp - lastTs;\n            uint256 elapsed = elapsedRaw > ELAPSED_CAP ? ELAPSED_CAP : elapsedRaw;\n            dirState = _decayCentered(dirState, DIR_DECAY, elapsed);\n            actEma = wmul(actEma, _powWad(ACT_DECAY, elapsed));\n            sizeHat = wmul(sizeHat, _powWad(SIZE_DECAY, elapsed));\n            toxEma = wmul(toxEma, _powWad(TOX_DECAY, elapsed));\n            if (stepTradeCount > 0 && elapsedRaw > 0) {\n                uint256 lambdaInst = (stepTradeCount * WAD) / elapsedRaw;\n                if (lambdaInst > LAMBDA_CAP) lambdaInst = LAMBDA_CAP;\n                lambdaHat = wmul(lambdaHat, LAMBDA_DECAY) + wmul(lambdaInst, WAD - LAMBDA_DECAY);\n            }\n            // Process variance is propagated inside the censored update.\n            if (uncertainty > 100000000000000) uncertainty = 100000000000000;\n            stepTradeCount = 0;\n        }\n\n        bool firstInStep = stepTradeCount == 0;\n        uint256 spot = trade.reserveX > 0 ? wdiv(trade.reserveY, trade.reserveX) : pHat;\n        if (pHat == 0) pHat = spot;\n\n        uint256 feeUsed = trade.isBuy ? prevBidFee : prevAskFee;\n        uint256 gamma = feeUsed < WAD ? WAD - feeUsed : 0;\n        uint256 pImplied;\n        if (gamma == 0) { pImplied = spot; }\n        else { pImplied = trade.isBuy ? wmul(spot, gamma) : wdiv(spot, gamma); }\n\n        // S: infer a no-trade interval center from the last post-trade spot.\n        uint256 silenceScale = WAD;\n        if (firstInStep && silent > 1) {\n            uint256 g = silent - 1;\n            if (g > 1) g = 1;\n            uint256 w = WAD - _powWad(800000000000000000, g);\n            uint256 s = slots[2] >> 64;\n            if (s == 0) s = pHat;\n            uint256 c = (wmul(s, WAD - prevBidFee) + wdiv(s, WAD - prevAskFee)) / 2;\n            if (c >= pHat) pHat += wmul(w, c - pHat);\n            else pHat -= wmul(w, pHat - c);\n            silenceScale = WAD - wmul(300000000000000000, w);\n        }\n\n        {\n            uint256 ret = pHat > 0 ? wdiv(absDiff(pImplied, pHat), pHat) : 0;\n            uint256 alpha = firstInStep ? PHAT_ALPHA : PHAT_ALPHA_RETAIL;\n            uint256 prePhat = pHat;\n            bool secondPrint = !firstInStep && stepTradeCount == 1;\n            bool sameDir = false; bool oppDir = false;\n            if (secondPrint) {\n                bool up2 = pImplied >= pHat;\n                uint256 d1 = slots[12];\n                if (d1 != 0) { sameDir = (d1 == 1) == up2; oppDir = !sameDir; }\n                if (sameDir) alpha = PHAT_ALPHA_SAME;\n            }\n            if (firstInStep) { slots[12] = pImplied >= pHat ? 1 : 2; }\n            uint256 adaptiveGate = wmul(sigmaHat, GATE_SIGMA_MULT);\n            if (adaptiveGate < MIN_GATE) adaptiveGate = MIN_GATE;\n            alpha = wmul(alpha, silenceScale);\n            adaptiveGate = wmul(adaptiveGate, silenceScale);\n            if (ret <= adaptiveGate) { pHat = wmul(pHat, WAD - alpha) + wmul(pImplied, alpha); }\n            if (oppDir && REVERT_U > 0) {\n                uint256 pre = slots[11];\n                if (pre > pHat) pHat = pHat + wmul(pre - pHat, REVERT_U);\n                else pHat = pHat - wmul(pHat - pre, REVERT_U);\n            }\n            if (firstInStep) {\n                if (ret > RET_CAP) ret = RET_CAP;\n                sigmaHat = wmul(sigmaHat, SIGMA_DECAY) + wmul(ret, WAD - SIGMA_DECAY);\n            }\n        }\n\n        // Interior retail routing equalizes fee-adjusted marginal prices.\n        // Subsequent trades in a step cannot be the initial arbitrage trade.\n        if (!firstInStep && feeUsed > 30 * BPS && gamma > 0) {\n            uint256 normalSpot = trade.isBuy\n                ? wdiv(wmul(spot, gamma), WAD - 30 * BPS)\n                : wdiv(wmul(spot, WAD - 30 * BPS), gamma);\n            pHat = wmul(pHat, 90 * WAD / 100) + wmul(normalSpot, 10 * WAD / 100);\n        }\n\n        // Censored assumed-density posterior. No external or future inputs.\n        uint256 arbProbability;\n        (fastHat, uncertainty, arbProbability) = _posterior(PosteriorInput(\n            fastHat, uncertainty, pImplied, spot, slots[2] >> 64,\n            prevBidFee, prevAskFee, firstInStep, silent, trade.isBuy,\n            trade.reserveY > 0 ? wdiv(trade.amountY, trade.reserveY) : 0\n        ));\n        slots[13] = uncertainty;\n        slots[14] = fastHat;\n        uint256 tradeRatio = trade.reserveY > 0 ? wdiv(trade.amountY, trade.reserveY) : 0;\n        if (tradeRatio > TRADE_RATIO_CAP) tradeRatio = TRADE_RATIO_CAP;\n\n        if (tradeRatio > SIGNAL_THRESHOLD) {\n            uint256 push = tradeRatio * DIR_IMPACT_MULT;\n            if (push > WAD / 4) push = WAD / 4;\n            if (trade.isBuy) {\n                dirState = dirState + push;\n                if (dirState > 2 * WAD) dirState = 2 * WAD;\n            } else {\n                dirState = dirState > push ? dirState - push : 0;\n            }\n            actEma = wmul(actEma, ACT_BLEND_DECAY) + wmul(tradeRatio, WAD - ACT_BLEND_DECAY);\n            sizeHat = wmul(sizeHat, SIZE_BLEND_DECAY) + wmul(tradeRatio, WAD - SIZE_BLEND_DECAY);\n            if (sizeHat > WAD) sizeHat = WAD;\n        }\n\n        uint256 tox = pHat > 0 ? wdiv(absDiff(spot, pHat), pHat) : 0;\n        if (tox > TOX_CAP) tox = TOX_CAP;\n        toxEma = wmul(toxEma, TOX_BLEND_DECAY) + wmul(tox, WAD - TOX_BLEND_DECAY);\n        uint256 toxSignal = toxEma;\n\n        stepTradeCount = stepTradeCount + 1;\n        if (stepTradeCount > STEP_COUNT_CAP) stepTradeCount = STEP_COUNT_CAP;\n\n        uint256 originalLambda = lambdaHat; uint256 originalSize = sizeHat;\n\n        if (342406799193418304 > 0) {\n            uint256 packedFlow = slots[15];\n            uint256 rate = uint80(packedFlow);\n            uint256 count = uint80(packedFlow >> 80);\n            uint256 meanSize = uint80(packedFlow >> 160);\n            if (rate == 0) rate = 400000000000000000;\n            if (meanSize == 0) meanSize = 2000000000000000;\n            if (isNewStep) {\n                uint256 inst = count / silent;\n                if (inst > 3 * WAD) inst = 3 * WAD;\n                uint256 retention = _powWad(999000000000000000, silent > 64 ? 64 : silent);\n                rate = wmul(rate, retention) + wmul(inst, WAD-retention);\n                count = 0;\n            }\n            uint256 weight = firstInStep ? WAD-arbProbability : WAD;\n            uint256 correctedWeight = weight;\n            if (2 == 2) {\n                uint256 missing = wmul(feeUsed, 196030880396139429888);\n                if (missing > 333333333333333376) missing = 333333333333333376;\n                correctedWeight = wdiv(weight, WAD-missing);\n            }\n            count += correctedWeight;\n            uint256 learning = wmul(WAD-999000000000000000, weight);\n            meanSize = _blend(meanSize, tradeRatio, learning);\n            slots[15]=rate | (count << 80) | (meanSize << 160);\n            uint256 retailRate = wmul(rate, 366383424913407168);\n            uint256 retailSize = 2 == 0 ? sizeHat : wmul(meanSize,1883296158119298304);\n            lambdaHat = _blend(lambdaHat,retailRate,342406799193418304);\n            sizeHat = _blend(sizeHat,retailSize,342406799193418304);\n        }\nint256[10] memory fx;\n        fx[0] = _nc((int256(spot)-int256(fastHat))*1000000/int256(fastHat>0?fastHat:1));\n        fx[1] = _nc((int256(spot)-int256(pHat))*1000000/int256(pHat>0?pHat:1));\n        fx[2] = _nc(int256(arbProbability/50000000000000)-10000);\n        fx[3] = _nc(int256(sigmaHat/2000000000000));\n        fx[4] = _nc(int256(lambdaHat/200000000000000));\n        fx[5] = _nc(int256(sizeHat/400000000000));\n        fx[6] = _nc(int256(toxSignal/2000000000000));\n        fx[7] = trade.isBuy ? int256(10000) : int256(-10000);\n        fx[8] = _nc(int256(stepTradeCount*2500));\n        fx[9] = _nc(int256(silent>8?8:silent)*1250);\n        (uint256 bidFee,uint256 askFee)=_head(fx);\n        lambdaHat=originalLambda;sizeHat=originalSize;\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\nfunction _head(int256[10] memory f) internal pure returns(uint256 bid,uint256 ask) {\nassembly (\"memory-safe\") {\nlet h0 := sdiv(add(add(add(add(add(add(add(add(add(add(48590000,mul(mload(add(f,0)),6)),mul(mload(add(f,32)),sub(0,4036))),mul(mload(add(f,64)),sub(0,179))),mul(mload(add(f,96)),sub(0,113))),mul(mload(add(f,128)),881)),mul(mload(add(f,160)),sub(0,108))),mul(mload(add(f,192)),sub(0,6321))),mul(mload(add(f,224)),933)),mul(mload(add(f,256)),sub(0,3737))),mul(mload(add(f,288)),sub(0,2323))),10000)\nif sgt(h0,10000) { h0 := 10000 }\nif slt(h0,sub(0,10000)) { h0 := sub(0,10000) }\nlet h1 := sdiv(add(add(add(add(add(add(add(add(add(add(sub(0,1640000),mul(mload(add(f,0)),sub(0,1017))),mul(mload(add(f,32)),3266)),mul(mload(add(f,64)),76)),mul(mload(add(f,96)),sub(0,4634))),mul(mload(add(f,128)),8790)),mul(mload(add(f,160)),sub(0,1926))),mul(mload(add(f,192)),sub(0,1934))),mul(mload(add(f,224)),1090)),mul(mload(add(f,256)),1827)),mul(mload(add(f,288)),sub(0,1931))),10000)\nif sgt(h1,10000) { h1 := 10000 }\nif slt(h1,sub(0,10000)) { h1 := sub(0,10000) }\nlet h2 := sdiv(add(add(add(add(add(add(add(add(add(add(104010000,mul(mload(add(f,0)),571)),mul(mload(add(f,32)),sub(0,9597))),mul(mload(add(f,64)),134)),mul(mload(add(f,96)),sub(0,2099))),mul(mload(add(f,128)),870)),mul(mload(add(f,160)),sub(0,2398))),mul(mload(add(f,192)),sub(0,7915))),mul(mload(add(f,224)),sub(0,10))),mul(mload(add(f,256)),270)),mul(mload(add(f,288)),22)),10000)\nif sgt(h2,10000) { h2 := 10000 }\nif slt(h2,sub(0,10000)) { h2 := sub(0,10000) }\nlet h3 := sdiv(add(add(add(add(add(add(add(add(add(add(sub(0,69470000),mul(mload(add(f,0)),683)),mul(mload(add(f,32)),2945)),mul(mload(add(f,64)),sub(0,900))),mul(mload(add(f,96)),2206)),mul(mload(add(f,128)),2303)),mul(mload(add(f,160)),2902)),mul(mload(add(f,192)),9349)),mul(mload(add(f,224)),1158)),mul(mload(add(f,256)),sub(0,3936))),mul(mload(add(f,288)),sub(0,2992))),10000)\nif sgt(h3,10000) { h3 := 10000 }\nif slt(h3,sub(0,10000)) { h3 := sub(0,10000) }\nlet h4 := sdiv(add(add(add(add(add(add(add(add(add(add(73990000,mul(mload(add(f,0)),1256)),mul(mload(add(f,32)),sub(0,1083))),mul(mload(add(f,64)),sub(0,342))),mul(mload(add(f,96)),sub(0,2291))),mul(mload(add(f,128)),140)),mul(mload(add(f,160)),sub(0,2193))),mul(mload(add(f,192)),sub(0,8089))),mul(mload(add(f,224)),1058)),mul(mload(add(f,256)),sub(0,847))),mul(mload(add(f,288)),sub(0,3920))),10000)\nif sgt(h4,10000) { h4 := 10000 }\nif slt(h4,sub(0,10000)) { h4 := sub(0,10000) }\nlet h5 := sdiv(add(add(add(add(add(add(add(add(add(add(sub(0,34450000),mul(mload(add(f,0)),sub(0,2965))),mul(mload(add(f,32)),sub(0,2988))),mul(mload(add(f,64)),794)),mul(mload(add(f,96)),772)),mul(mload(add(f,128)),sub(0,1087))),mul(mload(add(f,160)),sub(0,2839))),mul(mload(add(f,192)),4198)),mul(mload(add(f,224)),135)),mul(mload(add(f,256)),1608)),mul(mload(add(f,288)),sub(0,1635))),10000)\nif sgt(h5,10000) { h5 := 10000 }\nif slt(h5,sub(0,10000)) { h5 := sub(0,10000) }\nlet h6 := sdiv(add(add(add(add(add(add(add(add(add(add(sub(0,37350000),mul(mload(add(f,0)),945)),mul(mload(add(f,32)),1128)),mul(mload(add(f,64)),708)),mul(mload(add(f,96)),173)),mul(mload(add(f,128)),4337)),mul(mload(add(f,160)),5826)),mul(mload(add(f,192)),3104)),mul(mload(add(f,224)),sub(0,454))),mul(mload(add(f,256)),1290)),mul(mload(add(f,288)),165)),10000)\nif sgt(h6,10000) { h6 := 10000 }\nif slt(h6,sub(0,10000)) { h6 := sub(0,10000) }\nlet h7 := sdiv(add(add(add(add(add(add(add(add(add(add(1690000,mul(mload(add(f,0)),2468)),mul(mload(add(f,32)),sub(0,2644))),mul(mload(add(f,64)),sub(0,337))),mul(mload(add(f,96)),sub(0,1341))),mul(mload(add(f,128)),sub(0,3806))),mul(mload(add(f,160)),sub(0,7351))),mul(mload(add(f,192)),572)),mul(mload(add(f,224)),sub(0,33))),mul(mload(add(f,256)),sub(0,1013))),mul(mload(add(f,288)),sub(0,619))),10000)\nif sgt(h7,10000) { h7 := 10000 }\nif slt(h7,sub(0,10000)) { h7 := sub(0,10000) }\nbid := sdiv(add(add(add(add(add(add(add(add(36990000,mul(h0,sub(0,766))),mul(h1,957)),mul(h2,sub(0,2819))),mul(h3,3813)),mul(h4,sub(0,824))),mul(h5,sub(0,3258))),mul(h6,6091)),mul(h7,sub(0,7097))),10000)\nif slt(bid,0) { bid := 0 }\nif sgt(bid,100000) { bid := 100000 }\nbid := mul(bid,1000000000000)\nask := sdiv(add(add(add(add(add(add(add(add(16200000,mul(h0,sub(0,6087))),mul(h1,sub(0,147))),mul(h2,16011)),mul(h3,11659)),mul(h4,sub(0,6817))),mul(h5,5155)),mul(h6,4112)),mul(h7,sub(0,2872))),10000)\nif slt(ask,0) { ask := 0 }\nif sgt(ask,100000) { ask := 100000 }\nask := mul(ask,1000000000000)\n}\n}\nfunction _nc(int256 x) internal pure returns(int256) { return x>10000?int256(10000):(x< -10000?int256(-10000):x); }\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 \"RS2_NN901\"; }\n}\n","sha256":"fdb604548ae09fbc40a1496828137dc7fa147e0c1387915e2bef7997c8e2655a","blocked":null,"valid":true,"partial":false,"outcome":"Do not promote: the final paired result trails RS2.","reference":{"name":"RS2","url":"https://api.imdnotdead.fun/artifacts/19f2ec857df536e8ab62ab1da89ec6623332521ce46849f15bccff402c63e1e5","sha256":"f24b6ca198b744c380842c3a17964a6dc21f311bb04984b26733afa3fee8eaf2"},"paired":{"n":512,"mean_diff":-40.546597904569865,"se":0.9798243554438509,"worst":[{"seed":749818,"d":-176.16091254171351},{"seed":749580,"d":-145.47677664434457},{"seed":749797,"d":-143.84502244795726},{"seed":749769,"d":-140.02244458586472},{"seed":749617,"d":-122.03561167909834}]},"retail_edge_delta":{"mean":-12.514468830217996,"se":0.12164870942498618},"arb_edge_delta":{"mean":-28.032129074351865,"se":0.9655247530675086},"reconciliation_max_abs":1.1368683772161603e-13,"gas":{"max_ok":204004,"init_max_ok":243109,"oog":0,"other_halts":0,"scope":"all native evaluations of the selected hash, including training/monitor/recheck/final/probe","evaluations":[{"phase":"distilled","start":746108,"n":64,"gas":{"max_ok":198851,"init_max_ok":243109,"oog":0,"other_halts":0}},{"phase":"recheck","start":749000,"n":256,"gas":{"max_ok":201721,"init_max_ok":243109,"oog":0,"other_halts":0}},{"phase":"final","start":749400,"n":512,"gas":{"max_ok":204004,"init_max_ok":243109,"oog":0,"other_halts":0}},{"phase":"final_probe","start":749950,"n":32,"gas":{"max_ok":198766,"init_max_ok":243109,"oog":0,"other_halts":0}}]},"seeds":{"distill":{"first":746100,"last":746107,"n":8},"train_allowed":[746100,748719],"native_training_blocks":[{"first":746108,"last":746171,"n":64},{"first":746172,"last":746235,"n":64},{"first":746236,"last":746299,"n":64}],"training_candidate_runs":13,"training_candidate_seed_evaluations":832,"monitor":{"first":748800,"last":748863,"n_per_checkpoint":64,"checkpoints":3},"recheck":{"first":749000,"last":749255,"n_per_checkpoint":256,"checkpoints":2},"final":{"first":749400,"last":749911,"n":512,"selected_hash_runs":1},"probe":{"first":749950,"last":749981,"n":32},"any_seed_ge_5000000":false,"calibration":{"first":0,"last":999,"n_per_attempt":1000,"attempts":2}},"weights":{"format":"signed integer bytecode literals; divide by 10000","W1":[[6,-4036,-179,-113,881,-108,-6321,933,-3737,-2323],[-1017,3266,76,-4634,8790,-1926,-1934,1090,1827,-1931],[571,-9597,134,-2099,870,-2398,-7915,-10,270,22],[683,2945,-900,2206,2303,2902,9349,1158,-3936,-2992],[1256,-1083,-342,-2291,140,-2193,-8089,1058,-847,-3920],[-2965,-2988,794,772,-1087,-2839,4198,135,1608,-1635],[945,1128,708,173,4337,5826,3104,-454,1290,165],[2468,-2644,-337,-1341,-3806,-7351,572,-33,-1013,-619]],"b1":[4859,-164,10401,-6947,7399,-3445,-3735,169],"W2":[[-766,957,-2819,3813,-824,-3258,6091,-7097],[-6087,-147,16011,11659,-6817,5155,4112,-2872]],"b2":[3699,1620],"shape":[10,8,2],"trainable_count":106,"hidden":"hard clamp [-1,1]","outputs":"linear then clamp [0,10], multiplied by 0.01 to obtain fee; exact integer implementation in code","bounds_real":[-8,8]},"normalization":{"fixed_point_scale":10000,"clamp":[-1,1],"input_order":["100*(spot/fastHat-1)","100*(spot/pHat-1)","2*probArb-1","sigmaHat/0.02","RS2_corrected_lambdaHat/2","RS2_corrected_sizeHat/0.004","toxSignal/0.02","trade.isBuy ? 1 : -1","post_increment_stepTradeCount/4","min(silence,8)/8"],"rounding":"Solidity signed division truncates toward zero; integer definitions in generator_source are authoritative","causality":"Only callback calldata and RS2 estimator state; estimators and original lambda/size slot restoration retained; bid/ask stored in slots 0/1. No model initialization storage writes."},"calibration":{"mean":525.5258821780834,"expected":525.5258821780834,"pass":true,"seconds":272.8164539337158,"gas":{"max_ok":151647,"init_max_ok":185532,"oog":0,"other_halts":0,"afterSwap_calls":10445223,"init_calls":1000},"note":"First native 1000-seed run completed but a NumPy boolean caused report serialization to fail before the mean was persisted. The identical calibration block was repeated after correcting serialization. No failed calibration mean was observed."},"distillation":{"engine":"amm_sim_rs.run_batch, teacher quotes with low-order feature encoding","teacher_trace_sha256":"2c72279b570082faf98416e1752c10942c18e79605ae7451dd8f94ae86c14a00","seeds":[746100,746107],"n":8,"rows":52729,"steps_per_seed":10000,"iterations":10000,"last_batch_mse_fee_units":0.033623412342134465,"seconds":14.488519191741943,"feature_bits":7,"fee_quantum":8.796093022208e-06,"fee_label":"quantum midpoint; stored teacher quotes unchanged; encoded return perturbation below two fee quanta at the upper cap and below one otherwise","excluded_clamped_records":0,"gas":{"max_ok":205160,"init_max_ok":243103,"oog":0,"other_halts":0,"afterSwap_calls":79251,"init_calls":8},"fit_metrics":{"rows":52729,"label_quantiles":[0.0004398046511104,0.2678410325262336,0.8228745022275584,1.840081087594752,4.190898520431001,9.998958742994944],"full_dataset_mse_fee_units":0.027421101964093114,"mean_absolute_error_bps":5.783142011578153,"input_min":[-1.0,-1.0,-1.0,0.023622047244094446,0.2913385826771653,0.16535433070866135,0.007874015748031482,-1.0,0.2440944881889764,0.007874015748031482],"input_max":[1.0,1.0,1.0,0.68503937007874,0.5118110236220472,1.0,1.0,1.0,1.0,1.0],"nonnegative_feature_assertions_pass":true,"encoding_constraints":{"nonnegative_features":true,"trade_direction_binary":true,"step_position_codes":true,"silence_codes":true,"all_features_bounded":true}},"limitations":["Only the final quote of each step can be extracted through native step snapshots. Repeated unchanged quotes and the unencoded initial quote are excluded from the supervised dataset; all eight simulation seeds ran for 10000 steps.","Each of ten features is quantized to 7 bits; teacher fee labels use the midpoint of a 2**43-WAD-unit bucket. The encoded returned quote is slightly perturbed while stored teacher quotes remain RS2. Routing and subsequent observations therefore differ slightly from an uninstrumented RS2 trace.","An earlier Python-market trace prototype was discarded before ES; only native traces supplied this final initialization."]},"discarded_python_trace_prototypes":{"runs":2,"n_per_run":8,"first":746100,"last":746107,"steps_per_seed":10000,"used_for_final_initialization":false},"discarded_trace_attempt":{"discarded_sha256":"552ed7844c1535b6043a86eea81beb5a866e9ac1bcff3e8b0345220526a96c1a","n":8,"seeds":[746100,746107],"oog":0,"bad_return":3,"reason":"low-order feature payload pushed three capped teacher quotes above 0.1; entire hash discarded before training","repair":"cap quote base below MAX_FEE before encoding"},"discarded_ES_attempt":{"reason":"Six capped-quote records had malformed feature payloads because a Solidity rational constant expression left maxBase unaligned. ES was interrupted before any recheck/final; native trace encoding was repaired with typed integer division and nonnegative-feature assertions, then initialization and ES were restarted.","evaluations":[{"sha256":"a49ee3bea6c9b31517aba6ad99e92dd4cac8d7951e9af3fb475f2afd9030b22b","generation":-1,"member":-1,"start":746108,"n":64,"valid":true,"gas":{"max_ok":198901,"init_max_ok":243109,"oog":0,"other_halts":0},"mean_diff":-27.606594590158927,"se":2.1858146831873095},{"sha256":"e281e387ecb6fd35f3c5228e6bfae7f453c600ff8a969cb01e68a16eccf90078","generation":0,"member":0,"start":746108,"n":64,"valid":true,"gas":{"max_ok":199709,"init_max_ok":243109,"oog":0,"other_halts":0},"mean_diff":-34.909759902733754,"se":2.1398441163948148},{"sha256":"2f9ec7bd81480b722253c9b1ea3d8079ebf98c014da003d36741283936a21072","generation":0,"member":1,"start":746108,"n":64,"valid":true,"gas":{"max_ok":200048,"init_max_ok":243109,"oog":0,"other_halts":0},"mean_diff":-36.721921091911994,"se":2.2150903955399732},{"sha256":"eaf855d336743e11e0f15a16bbfec0123efe0e88a0297c6c1d7438bdc5d2140d","generation":0,"member":2,"start":746108,"n":64,"valid":true,"gas":{"max_ok":203703,"init_max_ok":243109,"oog":0,"other_halts":0},"mean_diff":-44.659305282989756,"se":2.2908647297460702},{"sha256":"887a82599d1508fa4111d163074f3348f582852de5d04ffcb408d84b349c4915","generation":0,"member":3,"start":746108,"n":64,"valid":true,"gas":{"max_ok":198895,"init_max_ok":243109,"oog":0,"other_halts":0},"mean_diff":-35.60758142007513,"se":2.178208272737065}],"monitor_curve":[{"sha256":"e281e387ecb6fd35f3c5228e6bfae7f453c600ff8a969cb01e68a16eccf90078","generation":0,"start":748800,"n":64,"valid":true,"gas":{"max_ok":198802,"init_max_ok":243109,"oog":0,"other_halts":0},"mean_diff":-32.44597455976891,"se":1.4237682912740801}],"partial":true,"count_note":"Counts describe persisted completed evaluations only; the in-flight native call interrupted with Ctrl-C has no reported metrics and is excluded. No recheck/final was started.","last_recorded_elapsed_seconds":241.55605362099595,"halting_hashes":[]},"nonzero_weight_probe":{"weights_rng":"numpy.default_rng(901).normal(0,0.1,106); set weights[104:]=0.3; use generator_source","sha256":"4e712b285360da919adce14161a903b70350ae4ded99c08cdfdde5a439e4c18d","first":749950,"last":749981,"n":32,"gas":{"max_ok":198799,"init_max_ok":243115,"oog":0,"other_halts":0,"afterSwap_calls":372441,"init_calls":32},"note":"Passed before ES; hidden/output weights nonzero and embedded in bytecode; no shrink required."},"search":{"algorithm":"diagonal CMA-ES over all 106 weights","seed":901,"population":4,"parents":2,"initial_sigma":0.015,"wall_budget_seconds":720,"generations_completed":3,"actual_elapsed_seconds":602.504922068998,"evaluations":[{"sha256":"fdb604548ae09fbc40a1496828137dc7fa147e0c1387915e2bef7997c8e2655a","generation":-1,"member":-1,"start":746108,"n":64,"valid":true,"gas":{"max_ok":198851,"init_max_ok":243109,"oog":0,"other_halts":0},"mean_diff":-41.851006277862226,"se":2.7094330577045316},{"sha256":"7523e5c4a715139eb491dc3752136431773c936b7e71934ee2b14f823babee1b","generation":0,"member":0,"start":746108,"n":64,"valid":true,"gas":{"max_ok":201305,"init_max_ok":243109,"oog":0,"other_halts":0},"mean_diff":-44.85546629862068,"se":2.5950882163405944},{"sha256":"c0a774a923cebe3d357a580ca771ed168ccf3f70bbecc1342b3e8c16896c11e1","generation":0,"member":1,"start":746108,"n":64,"valid":true,"gas":{"max_ok":201318,"init_max_ok":243109,"oog":0,"other_halts":0},"mean_diff":-45.68376055703372,"se":2.6774790700180184},{"sha256":"29d2091d5d928c6e114609ce2edf19ce963a13b9b147bbfa0d2945b41351888a","generation":0,"member":2,"start":746108,"n":64,"valid":true,"gas":{"max_ok":198851,"init_max_ok":243109,"oog":0,"other_halts":0},"mean_diff":-50.058627064610455,"se":2.799999166469869},{"sha256":"e8dd5ffa0c8d490c95f991a4d9ffc0ec31d809691a77dc6259b52b2348b978c5","generation":0,"member":3,"start":746108,"n":64,"valid":true,"gas":{"max_ok":201381,"init_max_ok":243109,"oog":0,"other_halts":0},"mean_diff":-44.14529045582793,"se":2.687481318607996},{"sha256":"72e5adea8c20be73ee50e5921589d54fbd5bfea1ef0033b1fbc3d2b571533dfb","generation":1,"member":0,"start":746172,"n":64,"valid":true,"gas":{"max_ok":200413,"init_max_ok":243109,"oog":0,"other_halts":0},"mean_diff":-44.67215896938265,"se":2.5398068412097294},{"sha256":"1204fe6a1a907c6a28e777aa2fcee8d40aaa8734386c58f12f9a43a70888bdd4","generation":1,"member":1,"start":746172,"n":64,"valid":true,"gas":{"max_ok":200431,"init_max_ok":243109,"oog":0,"other_halts":0},"mean_diff":-43.764488984386325,"se":2.5444621290204283},{"sha256":"75327f095fe6470c29d1ddc7048a8dcc670a39e96336ab11b0f7708b4774fc28","generation":1,"member":2,"start":746172,"n":64,"valid":true,"gas":{"max_ok":200905,"init_max_ok":243109,"oog":0,"other_halts":0},"mean_diff":-46.76474097274096,"se":2.4427718839527204},{"sha256":"d531c5b4400a3954b71105750a8aaa2d35e8fd79ccd40835c7d5ab949458220b","generation":1,"member":3,"start":746172,"n":64,"valid":true,"gas":{"max_ok":200980,"init_max_ok":243109,"oog":0,"other_halts":0},"mean_diff":-44.020628973481266,"se":2.51612230002432},{"sha256":"d29dc0cc4c1c6f7c46025af8b327b314702441d56e73144f40392fbcd563fa00","generation":2,"member":0,"start":746236,"n":64,"valid":true,"gas":{"max_ok":200394,"init_max_ok":243109,"oog":0,"other_halts":0},"mean_diff":-46.89566482547387,"se":2.8732242428811032},{"sha256":"28083fa54e1434d1ccf6804e1aa499773fad9f9b76e83b95aea17eaa87023153","generation":2,"member":1,"start":746236,"n":64,"valid":true,"gas":{"max_ok":200378,"init_max_ok":243112,"oog":0,"other_halts":0},"mean_diff":-48.807380586980344,"se":2.8893187626811296},{"sha256":"f8330ed678e55f125a62a2104dcca5e304421a686488dfd41833af2eddf455e2","generation":2,"member":2,"start":746236,"n":64,"valid":true,"gas":{"max_ok":200727,"init_max_ok":243103,"oog":0,"other_halts":0},"mean_diff":-45.99574297139375,"se":2.9171326001198175},{"sha256":"509abb8af7b873f0d5f85e79e71b543bd982eb26a7890c7159c5d51b71a0728a","generation":2,"member":3,"start":746236,"n":64,"valid":true,"gas":{"max_ok":198749,"init_max_ok":243109,"oog":0,"other_halts":0},"mean_diff":-45.816674960127514,"se":2.8680958588438874}],"selection":"Each generation uses one shared 64-seed CRN block for all four members; blocks rotate within the training range, with cached RS2 arms. Training-only ranking selects and freezes each generation champion before monitoring. Monitor gain/SE never enters CMA updates, ranking, recheck selection or final selection.","coverage":"Bounded search within the permitted training range; the full range was not exhausted.","stop":"Time budget guard: do not start another generation when its estimated duration would exceed the search budget.","invalid_hashes":[]},"ES_checkpoint":{"selected_generation":-1,"selected_sha256":"fdb604548ae09fbc40a1496828137dc7fa147e0c1387915e2bef7997c8e2655a","selected_training":{"sha256":"fdb604548ae09fbc40a1496828137dc7fa147e0c1387915e2bef7997c8e2655a","generation":-1,"member":-1,"start":746108,"n":64,"valid":true,"gas":{"max_ok":198851,"init_max_ok":243109,"oog":0,"other_halts":0},"mean_diff":-41.851006277862226,"se":2.7094330577045316},"selected_real_weights":[0.0005908430553757518,-0.4036130807737662,-0.017910177260250546,-0.011346718767024318,0.08807581138163668,-0.010792857759996954,-0.6320531107907003,0.09332250978876631,-0.3736958246120461,-0.2322642116113887,-0.10170138150654115,0.32663244148524434,0.007587764359266675,-0.4633509968201958,0.8789866166357553,-0.19263309803169062,-0.19339541078820102,0.10898951434593453,0.18270939922159873,-0.19305908566271346,0.05708625546769802,-0.9597371029362168,0.013389617853910374,-0.20988356552585694,0.08700793879925448,-0.23980956550077626,-0.7914726657353324,-0.0009899449959775682,0.027014194584615903,0.0021814036659659267,0.06827348171029436,0.29451319250258107,-0.09001492532026932,0.22062123168619793,0.23033325635022134,0.2901811614446646,0.9349193252555069,0.11575438342154121,-0.3936183618699752,-0.29916209815713046,0.12557628246371863,-0.10827876091063364,-0.03418829831996902,-0.22907487881473484,0.013993752616475553,-0.2192961081027258,-0.8088911066874079,0.10582986711746241,-0.08473873171060836,-0.39197126862593845,-0.2965059298511535,-0.29883435138028186,0.07940378422616567,0.07719003134624555,-0.10866140972822902,-0.2839349363974685,0.4197626922962022,0.013497519837359237,0.16079784191967178,-0.16348520663755742,0.09447520813520453,0.11277321360117643,0.07079438125763378,0.017266512414626962,0.43373117433674657,0.5826212672871924,0.31036599670611775,-0.04536311881945561,0.1290460605230748,0.01647951071713116,0.24684458508156193,-0.2644478311960607,-0.03372518924010663,-0.13414965090315972,-0.38057560477221497,-0.7350925299483212,0.0571694841503962,-0.0032545924163379252,-0.10133696575904455,-0.06186198628136665,0.48589757389990934,-0.016435006628792367,1.0400946368689485,-0.6947035625075053,0.7399434598080276,-0.3445044056218227,-0.3734699905119139,0.016876510478769056,-0.07657596526845095,0.09569820428996068,-0.28189091067441946,0.38128612275303314,-0.08238221558536402,-0.32577323090955934,0.6090815787213797,-0.7097474987878281,-0.6086776156554473,-0.014706128718223258,1.601078779276103,1.1659432485091399,-0.6817329936060065,0.5155033879353859,0.4111892057428238,-0.2872496439007136,0.36985471519597074,0.16198736865851196],"last_sigma":0.014149504861030325,"last_diag":[0.9826571273501458,0.9809242997139838,0.9833616833935758,0.9831956298111565,0.9897903349936482,0.9843044354724871,0.9802537695714453,0.9825817449562309,0.979945878508411,0.980553010964879,0.9849302063099581,0.9821738581437286,0.9796448965382795,0.9900759185643825,0.9815495264645899,0.9863345716833751,0.9834926489523654,0.9799994878535749,0.9806648103918172,0.984036317152651,0.9821060406876613,0.9826563564247952,0.979772800492665,0.9820393740086943,0.9836445177483406,0.9862151887663425,0.9797415579480284,0.9856093063022839,0.9827035981264367,0.98061574319572,0.980624520098213,0.9925209230458372,0.9820562954546901,0.980715093210201,0.9936556530709149,0.9835992669754798,0.980223428731094,0.9810105085153751,0.9936597072601279,0.9826268866725735,0.9793789661512472,0.9824687013078931,0.9795832233897843,0.987420581446695,0.9898363471584531,0.9832127156489467,0.9841641251416711,0.9799131988496627,0.9854638327833253,0.9805646297745477,0.9813438930805766,0.9814467125634599,0.987660050389752,0.9798849277192947,0.9800931236811642,0.9797302233335019,0.9808662735863792,0.9849752148737766,0.996051419003001,0.9853122781154626,0.986501018202978,0.9839881803634991,0.9856749127367717,0.9843504901463275,0.97976453699145,0.98088235805796,0.9828490236055525,0.9857844869182857,0.9828610488298588,0.9833584256176636,0.9816830544462586,0.9830033626580063,0.9855335897363264,1.0121759472376997,0.9954028058262064,0.9862377763992559,0.9990834321006666,0.9800824166216118,0.9818131389473371,0.991000291519085,0.9812539942104879,0.9841664683020398,0.9883983977085523,0.9842339515924511,0.9802402460323104,0.9806419485614393,0.9834849150923548,0.9802978456588292,0.9831844474364425,0.9837375640537892,0.9980624069959795,0.9849205121870991,0.9837046414532571,0.9910209856570283,0.9832295364175484,0.9818101849255007,0.9890157860038581,0.9845930350018506,0.9833196100423673,0.9810546883927572,0.9885699225289203,0.9817734204631312,0.9923973599249326,0.9877276704474045,0.9886382798461691,0.9840969368589624],"rng_state":{"bit_generator":"PCG64","state":{"state":323336514134836365502858139559588358428,"inc":168678710323447357454955047835026792803},"has_uint32":0,"uinteger":0},"freeze_rule":"Training-ranked top two unique hashes rechecked on 256 seeds; best valid recheck mean frozen before the single 512-seed final test."},"monitor_curve":[{"generation":0,"sha256":"e8dd5ffa0c8d490c95f991a4d9ffc0ec31d809691a77dc6259b52b2348b978c5","n":64,"mean_diff":-41.73160476722617,"se":1.989458346304328,"valid":true,"gas":{"max_ok":198755,"init_max_ok":243109,"oog":0,"other_halts":0}},{"generation":1,"sha256":"1204fe6a1a907c6a28e777aa2fcee8d40aaa8734386c58f12f9a43a70888bdd4","n":64,"mean_diff":-42.75285658482365,"se":1.9886877815816058,"valid":true,"gas":{"max_ok":202733,"init_max_ok":243109,"oog":0,"other_halts":0}},{"generation":2,"sha256":"509abb8af7b873f0d5f85e79e71b543bd982eb26a7890c7159c5d51b71a0728a","n":64,"mean_diff":-41.49540605898821,"se":1.9804850121477937,"valid":true,"gas":{"max_ok":200004,"init_max_ok":243109,"oog":0,"other_halts":0}}],"recheck":[{"paired":{"n":256,"mean_diff":-40.237605299068434,"se":1.4836561482691601,"worst":[{"seed":749187,"d":-169.40473094582728},{"seed":749155,"d":-148.46133711757807},{"seed":749033,"d":-127.02857227172615},{"seed":749015,"d":-125.6602255876204},{"seed":749137,"d":-122.92315208654725}]},"retail_edge_delta":{"mean":-12.756661607220341,"se":0.1812014312347604},"arb_edge_delta":{"mean":-27.48094369184809,"se":1.4880511651185155},"reconciliation_max_abs":2.2737367544323206e-13,"sha256":"fdb604548ae09fbc40a1496828137dc7fa147e0c1387915e2bef7997c8e2655a","valid":true,"gas":{"max_ok":201721,"init_max_ok":243109,"oog":0,"other_halts":0},"start":749000,"n":256,"generation":-1},{"paired":{"n":256,"mean_diff":-43.66711266104423,"se":1.4541582997705231,"worst":[{"seed":749187,"d":-162.93146991405126},{"seed":749155,"d":-154.1615441343214},{"seed":749015,"d":-123.85665939862929},{"seed":749137,"d":-122.49432982562985},{"seed":749033,"d":-120.87429150945718}]},"retail_edge_delta":{"mean":-16.7322792379655,"se":0.2065089116181163},"arb_edge_delta":{"mean":-26.93483342307872,"se":1.4586156667243633},"reconciliation_max_abs":1.7053025658242404e-13,"sha256":"1204fe6a1a907c6a28e777aa2fcee8d40aaa8734386c58f12f9a43a70888bdd4","valid":true,"gas":{"max_ok":202820,"init_max_ok":243109,"oog":0,"other_halts":0},"start":749000,"n":256,"generation":1}],"final_probe":{"paired":{"n":32,"mean_diff":-42.59236301939834,"se":4.456455969357538,"worst":[{"seed":749971,"d":-132.64588063141127},{"seed":749974,"d":-81.0249465223526},{"seed":749972,"d":-78.87389068463699},{"seed":749981,"d":-69.83780844338048},{"seed":749978,"d":-68.69363421057619}]},"retail_edge_delta":{"mean":-12.476031155242339,"se":0.3904608264870441},"arb_edge_delta":{"mean":-30.116331864155995,"se":4.656527299393672},"reconciliation_max_abs":9.592326932761353e-14,"sha256":"fdb604548ae09fbc40a1496828137dc7fa147e0c1387915e2bef7997c8e2655a","valid":true,"gas":{"max_ok":198766,"init_max_ok":243109,"oog":0,"other_halts":0},"start":749950,"n":32},"protocol":{"repo":"https://github.com/benedictbrady/amm-challenge","commit":"6b6921f8d463314aa7c96234e1be25a25245f704","harness_url":"https://api.imdnotdead.fun/artifacts/26cb8e86f05170308de2a4b24821ac7fad2a17077f8d94af6e0f31985343fe89","steps":10000,"workers":8,"chunk_max":20,"comparison":"Each candidate and RS2 run alone against VanillaStrategy; paired edges aligned by every seed. Native gas counters reset and collected for each arm/chunk. No seeds dropped.","SE":"sample standard deviation (ddof=1) / sqrt(n)","retail_arb":"H.decomposition reconstructs arb loss at the preceding spot and quote; retail is total edge minus arb. This is an analytic decomposition, not trader attribution exposed by the native API.","scope":"This item uses RS2 and the item-specific seed ranges; no STACK confirmation or leaderboard submission was performed."},"generator_source":"import numpy as np\nfrom pathlib import Path\nQ=10000\nBASE=Path('scratch/RS2.sol').read_text()\nFEATURES='''int256[10] memory fx;\n        fx[0] = _nc((int256(spot)-int256(fastHat))*1000000/int256(fastHat>0?fastHat:1));\n        fx[1] = _nc((int256(spot)-int256(pHat))*1000000/int256(pHat>0?pHat:1));\n        fx[2] = _nc(int256(arbProbability/50000000000000)-10000);\n        fx[3] = _nc(int256(sigmaHat/2000000000000));\n        fx[4] = _nc(int256(lambdaHat/200000000000000));\n        fx[5] = _nc(int256(sizeHat/400000000000));\n        fx[6] = _nc(int256(toxSignal/2000000000000));\n        fx[7] = trade.isBuy ? int256(10000) : int256(-10000);\n        fx[8] = _nc(int256(stepTradeCount*2500));\n        fx[9] = _nc(int256(silent>8?8:silent)*1250);\n'''\nHELP='''function _nc(int256 x) internal pure returns(int256) { return x>10000?int256(10000):(x< -10000?int256(-10000):x); }\n'''\ndef unpack(w):\n w=np.asarray(w);return w[:80].reshape(8,10),w[80:88],w[88:104].reshape(2,8),w[104:106]\ndef generate(w,trace=False):\n s=BASE\n # All estimator updates, including corrected flow, precede the learned mapping.\n if trace:\n  s=s.replace('uint256 flowSize =',FEATURES+'        uint256 flowSize =')\n  s=s.replace('return (bidFee, askFee);','uint256[12] memory output; output[0]=bidFee; output[1]=askFee; for(uint256 z=0;z<10;z++) output[z+2]=uint256(fx[z]); assembly (\"memory-safe\") { return(output,384) }')\n else:\n  a=s.index('        uint256 flowSize =');b=s.index('        slots[0] = bidFee;',a)\n  s=s[:a]+FEATURES+'''        (uint256 bidFee,uint256 askFee)=_head(fx);\n        lambdaHat=originalLambda;sizeHat=originalSize;\n'''+s[b:]\n  A,b,C,d=unpack(np.rint(np.clip(w,-8,8)*Q).astype(int))\n  lines=['function _head(int256[10] memory f) internal pure returns(uint256 bid,uint256 ask) {','assembly (\"memory-safe\") {']\n  def lit(i):return str(int(i)) if i>=0 else 'sub(0,'+str(int(-i))+')'\n  for h in range(8):\n   expr=lit(b[h]*Q)\n   for j in range(10):expr='add('+expr+',mul(mload(add(f,'+str(j*32)+')),'+lit(A[h,j])+'))'\n   lines+=['let h'+str(h)+' := sdiv('+expr+',10000)', 'if sgt(h'+str(h)+',10000) { h'+str(h)+' := 10000 }','if slt(h'+str(h)+',sub(0,10000)) { h'+str(h)+' := sub(0,10000) }']\n  for o,name in enumerate(['bid','ask']):\n   expr=lit(d[o]*Q)\n   for h in range(8):expr='add('+expr+',mul(h'+str(h)+','+lit(C[o,h])+'))'\n   lines += [name+' := sdiv('+expr+',10000)','if slt('+name+',0) { '+name+' := 0 }','if sgt('+name+',100000) { '+name+' := 100000 }',name+' := mul('+name+',1000000000000)']\n  lines+=['}','}'];s=s.replace('    struct PosteriorInput {','\\n'.join(lines)+'\\n    struct PosteriorInput {')\n s=s.replace('    struct PosteriorInput {',HELP+'    struct PosteriorInput {')\n s=s.replace('return \"censored_10\"','return \"RS2_NN901\"')\n return s\n","trainer_source":"from harness import *\nfrom generator import *\nimport time\nERRORS=['oog','revert','other_halt','tx_error','bad_return']\ndef gas(r):\n rows=r['raw_counters'];return {'max_ok':max([x.get('max_ok_gas',0) for x in rows if x['role']=='Submission' and x['callback']=='afterSwap'] or [0]),'init_max_ok':max([x.get('max_ok_gas',0) for x in rows if x['role']=='Submission' and x['callback']=='afterInitialize'] or [0]),'oog':sum(x.get('oog',0) for x in rows),'other_halts':sum(sum(x.get(k,0) for k in ERRORS[1:]) for x in rows)}\ndef good(r):\n g=gas(r);return g['oog']==0 and g['other_halts']==0 and g['max_ok']<235000 and g['init_max_ok']<245000\nc=SolidityCompiler();v=c.compile(Path('contracts/src/VanillaStrategy.sol').read_text(),'VanillaStrategy');assert v.success\nbase=Path('scratch/RS2.sol').read_text();cache={};allgas=[];evals=[];mon=[];checkpoints=[];invalid_hashes=set()\ndef baseline(start,n):\n key=(start,n)\n if key not in cache:\n  r=json.loads(Path('scratch/cache_'+str(start)+'.json').read_text()) if Path('scratch/cache_'+str(start)+'.json').exists() else run(base,start,n,v.bytecode,c);assert good(r),gas(r);cache[key]=r;allgas.append({'phase':'RS2','start':start,'n':n,'gas':gas(r)});Path('scratch/cache_'+str(start)+'.json').write_text(json.dumps(r))\n return cache[key]\ndef evaluate(w,start,n,phase):\n source=generate(w);sha=hashlib.sha256(source.encode()).hexdigest();r=run(source,start,n,v.bytecode,c);g=gas(r);\n if not good(r):invalid_hashes.add(sha)\n valid=good(r) and sha not in invalid_hashes;allgas.append({'phase':phase,'sha256':sha,'start':start,'n':n,'gas':g});summary=compare(r,baseline(start,n));summary.update(sha256=sha,valid=valid,gas=g,start=start,n=n)\n return summary\nassert json.load(open('scratch/calibration.json'))['pass']\nprobe=json.load(open('scratch/nonzero_probe.json'));assert good(probe),gas(probe)\nprint('probe',gas(probe),flush=True)\nrng=np.random.default_rng(901);mean=np.load('scratch/distilled.npy');n=len(mean);lam=4;mu=2\nwt=np.log(mu+.5)-np.log(np.arange(1,mu+1));wt/=wt.sum();mueff=1/sum(wt**2)\ncc=(4+mueff/n)/(n+4+2*mueff/n);cs=(mueff+2)/(n+mueff+5);c1=2/((n+1.3)**2+mueff)*(n+1.5)/3;cmu=min(1-c1,2*(mueff-2+1/mueff)/((n+2)**2+mueff)*(n+1.5)/3);damps=1+2*max(0,np.sqrt((mueff-1)/(n+1))-1)+cs;chi=np.sqrt(n)*(1-1/(4*n)+1/(21*n*n));pc=np.zeros(n);ps=np.zeros(n);diag=np.ones(n);sigma=.015\nstart_time=time.monotonic();durations=[]\ndef persist():\n Path('scratch/es_log.json').write_text(json.dumps({'evaluations':evals,'monitor_curve':mon,'checkpoints':checkpoints,'gas':allgas,'elapsed':time.monotonic()-start_time,'seed':901,'sigma':sigma,'diag':diag.tolist(),'mean':mean.tolist(),'pc':pc.tolist(),'ps':ps.tolist(),'rng_state':rng.bit_generator.state,'invalid_hashes':sorted(invalid_hashes)}))\n# Evaluate distilled checkpoint before any ES perturbation.\nr=evaluate(mean,746108,64,'distilled');r.update(generation=-1,member=-1);evals.append(r);checkpoints.append({'sha256':r['sha256'],'weights':mean.tolist(),'training':r,'generation':-1});persist();print('distilled',r,flush=True)\nfor gen in range(40):\n elapsed=time.monotonic()-start_time\n estimate=max(durations[-2:] or [360])\n if elapsed+estimate>12*60:break\n t=time.monotonic();start=746108+64*gen\n if start+63>748719:break\n z=rng.normal(size=(lam,n));ys=z*np.sqrt(diag);members=np.clip(mean+sigma*ys,-8,8);rank=[]\n for j,w in enumerate(members):\n  r=evaluate(w,start,64,'ES');r.update(generation=gen,member=j);evals.append(r);score=r['paired']['mean_diff'] if r['valid'] else -1e9;rank.append((score,j));print('eval',gen,j,score,r['gas'],flush=True);persist()\n rank.sort(reverse=True);ids=[j for score,j in rank[:mu]]\n if rank[0][0]<=-1e8:break\n # Freeze training-selected generation champion before monitoring.\n j=rank[0][1];r=evals[-lam+j];checkpoint={'sha256':r['sha256'],'weights':members[j].tolist(),'training':r,'generation':gen};checkpoints.append(checkpoint);Path('scratch/checkpoint_'+str(gen)+'.json').write_text(json.dumps(checkpoint));persist()\n old=mean.copy();mean=wt@members[ids];yw=(mean-old)/sigma;ps=(1-cs)*ps+np.sqrt(cs*(2-cs)*mueff)*yw/np.sqrt(diag);hsig=np.linalg.norm(ps)/np.sqrt(1-(1-cs)**(2*(gen+1)))/chi < 1.4+2/(n+1);pc=(1-cc)*pc+hsig*np.sqrt(cc*(2-cc)*mueff)*yw\n diag=(1-c1-cmu)*diag+c1*(pc**2+(1-hsig)*cc*(2-cc)*diag)+cmu*(wt@(ys[ids]**2));diag=np.clip(diag,1e-3,1e3);sigma*=np.exp(cs/damps*(np.linalg.norm(ps)/chi-1));sigma=float(np.clip(sigma,.0005,.1))\n monitor=evaluate(members[j],748800,64,'monitor');monitor.update(generation=gen,checkpoint_sha256=checkpoint['sha256']);mon.append(monitor);print('monitor',gen,monitor['paired'],flush=True);durations.append(time.monotonic()-t);persist()\n# Selection uses training only; monitors above are never read.\nranked=sorted([x for x in checkpoints if x['training']['valid'] and x['sha256'] not in invalid_hashes],key=lambda x:x['training']['paired']['mean_diff'],reverse=True);unique=[]\nfor x in ranked:\n if x['sha256'] not in [a['sha256'] for a in unique]:unique.append(x)\n if len(unique)==2:break\nassert len(unique)==2\nrechecks=[]\nfor ck in unique:\n r=evaluate(ck['weights'],749000,256,'recheck');r.update(generation=ck['generation']);rechecks.append(r);print('recheck',r,flush=True)\nPath('scratch/recheck.json').write_text(json.dumps(rechecks));eligible=[i for i,r in enumerate(rechecks) if r['valid']];assert eligible\nidx=max(eligible,key=lambda i:rechecks[i]['paired']['mean_diff']);frozen=unique[idx];Path('scratch/frozen.json').write_text(json.dumps(frozen));Path('scratch/final.sol').write_text(generate(frozen['weights']));print('FROZEN',frozen['sha256'],flush=True)\nfinal=evaluate(frozen['weights'],749400,512,'final');Path('scratch/final.json').write_text(json.dumps(final));print('final',final,flush=True)\nprobe=evaluate(frozen['weights'],749950,32,'final_probe');Path('scratch/final_probe.json').write_text(json.dumps(probe));persist();print('done',flush=True)\n","distiller_source":"from generator import *\nfrom harness import *\nimport time\nstart=time.time();rng=np.random.default_rng(901)\n# Each quote carries five 7-bit normalized features in a low-order mantissa.\n# Spacing 256 WAD units survives f64 conversion at every permitted fee.\n# Upper bits retain the teacher label to a fee quantum of 2**43 / 1e18.\ns=generate(np.ones(106)*.05,trace=True)\na=s.index('uint256[12] memory output;');b=s.index('\\n    }',a)\ns=s[:a]+'''uint256 packBid;uint256 packAsk;\n        for(uint256 j=0;j<5;j++) {\n            uint256 q0=uint256(fx[j]+10000)*127+10000;\n            uint256 q1=uint256(fx[j+5]+10000)*127+10000;\n            packBid |= (q0/20000) << (7*j);\n            packAsk |= (q1/20000) << (7*j);\n        }\n        uint256 baseBid=(bidFee/8796093022208)*8796093022208;\n        uint256 baseAsk=(askFee/8796093022208)*8796093022208;\n        uint256 feeLimit=100000000000000000;\n        uint256 quantum=8796093022208;\n        uint256 maxBase=(feeLimit/quantum-1)*quantum;\n        if(baseBid>maxBase)baseBid=maxBase;\n        if(baseAsk>maxBase)baseAsk=maxBase;\n        return (baseBid+packBid*256,baseAsk+packAsk*256);'''+s[b:]\nPath('scratch/teacher_trace.sol').write_text(s)\nc=SolidityCompiler();a=c.compile(s);v=c.compile(Path('contracts/src/VanillaStrategy.sol').read_text(),'VanillaStrategy');assert a.success,a.errors\nsim.gas_stats_reset();batch=sim.run_batch(list(a.bytecode),list(v.bytecode),configs(746100,8),8);gasrows=sim.gas_stats();assert all(not any(r.get(k,0) for k in ['oog','revert','other_halt','tx_error','bad_return']) for r in gasrows),gasrows\nX=[];Y=[];skipped=0;lastquotes={}\nfor r in sorted(batch.results,key=lambda r:r.seed):\n lastquotes[r.seed]=(.0004,.0004)\n for step in r.steps:\n  fees=step.fees['submission']\n  if fees==lastquotes.get(r.seed):continue\n  lastquotes[r.seed]=fees\n  if max(fees)>=.1 or min(fees)<0:skipped+=1;continue\n  # Recovery rounds to nearest 256, then strips the five packed 7-bit fields.\n  words=[int(round(f*1e18/256)) for f in fees]\n  codes=[w&((1<<35)-1) for w in words]\n  X.append([((codes[j//5]>>(7*(j%5)))&127)*2/127-1 for j in range(10)])\n  Y.append([((w>>35)*8796093022208+4398046511104)/1e16 for w in words])\nX=np.asarray(X);Y=np.asarray(Y);assert np.all(X[:,3]>=0) and np.all(X[:,4]>=0), 'negative nonnegative feature: encoding failure';np.savez('scratch/traces_native.npz',X=X,Y=Y)\nprint('native trace',len(X),time.time()-start,gasrows,flush=True)\nw=rng.normal(0,.25,106);w[104:]=Y.mean(axis=0);m=np.zeros(106);v=np.zeros(106)\nfor it in range(1,10001):\n ids=rng.integers(0,len(X),512);x=X[ids];y=Y[ids];A,b,C,d=unpack(w);z=x@A.T+b;h=np.clip(z,-1,1);pred=h@C.T+d;err=(pred-y)*2/len(x);gz=(err@C)*(abs(z)<1)\n grad=np.r_[(gz.T@x).ravel(),gz.sum(axis=0),(err.T@h).ravel(),err.sum(axis=0)];m=.9*m+.1*grad;v=.999*v+.001*grad**2;lr=.003 if it<=6000 else .001;w-=lr*(m/(1-.9**it))/(np.sqrt(v/(1-.999**it))+1e-8);w=np.clip(w,-8,8)\n if it%1000==0:print('fit',it,float(np.mean((pred-y)**2)),flush=True)\nnp.save('scratch/distilled.npy',w);Path('scratch/distilled.sol').write_text(generate(w));Path('scratch/distill_summary.json').write_text(json.dumps({'engine':'amm_sim_rs.run_batch, teacher quotes with low-order feature encoding','teacher_trace_sha256':hashlib.sha256(s.encode()).hexdigest(),'seeds':[746100,746107],'n':8,'rows':len(X),'steps_per_seed':10000,'iterations':10000,'last_batch_mse_fee_units':float(np.mean((pred-y)**2)),'seconds':time.time()-start,'feature_bits':7,'fee_quantum':8796093022208/1e18,'fee_label':'quantum midpoint; original RS2 stored quotes unchanged, returned quotes perturbed by less than two quanta at the upper fee cap, otherwise less than one quantum','excluded_clamped_records':skipped,'gas':gasrows}))\n","harness_source":"\"\"\"Run from the pinned amm-challenge checkout, with the brief's environment active.\npython harness.py --start 5000000 --n 2000 --out measured.json candidate.sol STACK.sol\nDo not use confirmation seeds to choose or change a strategy.\n\"\"\"\nimport argparse,hashlib,json,math\nfrom pathlib import Path\nimport numpy as np\nimport amm_sim_rs as sim\nfrom amm_competition.evm.compiler import SolidityCompiler\n\n\ndef configs(start,n):\n    configs=[]\n    for seed in range(start,start+n):\n        rng=np.random.default_rng(seed)\n        size=rng.uniform(19.,21.)\n        rate=rng.uniform(.6,1.)\n        sigma=rng.uniform(.000882,.001008)\n        configs.append(sim.SimulationConfig(n_steps=10000,initial_price=100.,\n            initial_x=100.,initial_y=10000.,gbm_mu=0.,gbm_sigma=sigma,gbm_dt=1.,\n            retail_arrival_rate=rate,retail_mean_size=size,retail_size_sigma=1.2,\n            retail_buy_prob=.5,seed=seed))\n    return configs\n\n\ndef decomposition(r,initial_fee=.0004):\n    # Fees are outside reserves, so k stays fixed up to floating-point roundoff.\n    # The arb acts before retail, using the preceding step's final spot and fees.\n    steps=r.steps\n    fair=np.array([s.fair_price for s in steps])\n    spots=np.array([r.initial_fair_price]+[s.spot_prices['submission'] for s in steps[:-1]])\n    bids=np.array([initial_fee]+[s.fees['submission'][0] for s in steps[:-1]])\n    asks=np.array([initial_fee]+[s.fees['submission'][1] for s in steps[:-1]])\n    x0,y0=r.initial_reserves['submission'];k=x0*y0\n    x=np.sqrt(k/spots);y=np.sqrt(k*spots)\n    ga=1-asks;gb=1-bids\n    out=np.minimum(np.maximum(x-np.sqrt(k/(ga*fair)),0),.99*x)\n    paid=(k/(x-out)-y)/ga\n    buyprofit=np.where(out>0,np.maximum(out*fair-paid,0),0)\n    gross=np.maximum((np.sqrt(k*gb/fair)-x)/gb,0)\n    received=y-k/(x+gb*gross)\n    sellprofit=np.where(gross>0,np.maximum(received-gross*fair,0),0)\n    arb=-float(np.sum(np.where(spots<fair,buyprofit,sellprofit)))\n    return arb,r.edges['submission']-arb\n\n\ndef aggregate(chunks):\n    out={}\n    for chunk in chunks:\n        for row in chunk['raw']:\n            key=(row['role'],row['callback'])\n            dest=out.setdefault(key,{'role':row['role'],'callback':row['callback']})\n            for k,v in row.items():\n                if k in ['role','callback']:continue\n                dest[k]=max(dest.get(k,0),v) if k=='max_ok_gas' else dest.get(k,0)+v\n    return list(out.values())\n\n\ndef run(source,start,n,vanilla,compiler):\n    compiled=compiler.compile(source)\n    assert compiled.success,compiled.errors\n    rows=[];chunks=[]\n    for first in range(start,start+n,20):\n        count=min(20,start+n-first)\n        sim.gas_stats_reset()\n        batch=sim.run_batch(list(compiled.bytecode),list(vanilla),configs(first,count),8)\n        results=batch.results\n        assert sorted(r.seed for r in results)==list(range(first,first+count))\n        for r in results:\n            arb,retail=decomposition(r)\n            rows.append({'seed':r.seed,'edge':r.edges['submission'],'arb':arb,'retail':retail})\n        chunks.append({'start':first,'raw':sim.gas_stats()})\n        del results,batch\n    return {'sha256':hashlib.sha256(source.encode()).hexdigest(),'rows':rows,\n            'raw_counters':aggregate(chunks),'chunks':chunks}\n\n\ndef stats(d):\n    d=np.asarray(d,dtype=float)\n    return {'mean':float(d.mean()),'se':float(d.std(ddof=1)/np.sqrt(len(d)))}\n\n\ndef compare(candidate,stack):\n    a={r['seed']:r for r in candidate['rows']};b={r['seed']:r for r in stack['rows']}\n    assert a.keys()==b.keys()\n    seeds=sorted(a)\n    d=np.array([a[s]['edge']-b[s]['edge'] for s in seeds])\n    arb=np.array([a[s]['arb']-b[s]['arb'] for s in seeds])\n    retail=np.array([a[s]['retail']-b[s]['retail'] for s in seeds])\n    assert np.max(np.abs(d-arb-retail))<1e-8\n    summary=stats(d)\n    return {'paired':{'n':len(d),'mean_diff':summary['mean'],'se':summary['se'],\n                'worst':[{'seed':seeds[i],'d':float(d[i])} for i in np.argsort(d)[:5]]},\n            'retail_edge_delta':stats(retail),'arb_edge_delta':stats(arb),\n            'reconciliation_max_abs':float(np.max(np.abs(d-arb-retail)))}\n\n\nif __name__=='__main__':\n    p=argparse.ArgumentParser()\n    p.add_argument('--start',type=int,required=True);p.add_argument('--n',type=int,required=True)\n    p.add_argument('--out',required=True);p.add_argument('candidate');p.add_argument('stack')\n    args=p.parse_args()\n    compiler=SolidityCompiler()\n    vanilla=compiler.compile(Path('contracts/src/VanillaStrategy.sol').read_text(),'VanillaStrategy')\n    assert vanilla.success,vanilla.errors\n    candidate=run(Path(args.candidate).read_text(),args.start,args.n,vanilla.bytecode,compiler)\n    stack=run(Path(args.stack).read_text(),args.start,args.n,vanilla.bytecode,compiler)\n    out=compare(candidate,stack);out.update(candidate=candidate,stack=stack)\n    errors=['oog','revert','other_halt','tx_error','bad_return']\n    out['valid']=all(not any(row.get(e,0) for e in errors)\n        for arm in [candidate,stack] for row in arm['raw_counters'])\n    Path(args.out).write_text(json.dumps(out,allow_nan=False))\n    print(json.dumps({k:v for k,v in out.items() if k not in ['candidate','stack']}))\n","reproduction":{"files":"Place generator_source, trainer_source, distiller_source, harness_source under scratch/ with the indicated Python filenames. Save the reference artifact code as scratch/RS2.sol and supply scratch/calibration.json and scratch/nonzero_probe.json from the included protocol. Run distill_native.py then train.py in the pinned checkout and configured environment. The generator uses the pinned RS2 source as its base.","dependencies":"The brief-supplied prebuilt simulator wheel, numpy, py-solc-x 2.1.0, pyrevm 0.3.7 and solc 0.8.24; full setup from the brief was used."},"checks":{"source_hash_match":true,"overall_elapsed_since_setup_script_seconds":2528.8062052726746,"CH_tolerance":1e-06,"gas_limits":{"afterSwap_lt":235000,"afterInitialize_lt":245000},"fixed_point_head_math":{"pass":true,"tested_candidate_sha256":"fdb604548ae09fbc40a1496828137dc7fa147e0c1387915e2bef7997c8e2655a","n":32,"cases":"29 evenly spaced native trace inputs plus all-zero/all-positive-bound/all-negative-bound vectors","max_abs_integer_difference":0},"quotes_verified_online":true,"no_board_gain_claim":true}}
