{
 "blocked": null,
 "item": "a",
 "target": {
  "name": "RS2 (getName 'censored_10')",
  "artifact": "https://api.imd.fun/artifacts/19f2ec857df536e8ab62ab1da89ec6623332521ce46849f15bccff402c63e1e5",
  "sha256_of_code": "f24b6ca198b744c380842c3a17964a6dc21f311bb04984b26733afa3fee8eaf2",
  "sha256_verified": true
 },
 "port_file": "rs2_port.py",
 "port_sha256": "c348f81163e1d3c5dc4a9cb8572f8994994eac2f0e678d2f27a591fd95b729c9",
 "port_source": "\"\"\"Float64 port of RS2 (\"censored_10\", sha256 f24b6ca198b744c380842c3a17964a6dc21f311bb04984b26733afa3fee8eaf2).\n\nAll WAD integers are represented as float64 fractions (value / 1e18). wmul -> a*b,\nwdiv -> a/b. Solidity truncates every wmul/wdiv to an integer wei (relative error\n<= ~1e-18 per op at the magnitudes used here), so the float port differs from the EVM\nonly at the ~1e-15 relative level unless a comparison sits exactly on a threshold.\n\nFunctions (numba.njit compatible, scalar float64 maths, no Python objects):\n  strat_init(S, TH, x0, y0)                -> (bid_fee, ask_fee)\n  strat_after(S, TH, is_buy, amount_x, amount_y, timestamp, reserve_x, reserve_y)\n                                           -> (bid_fee, ask_fee)\nS is float64[40] state (see SLOTS); TH is float64[len(TH_NAMES)] constants (TH_VALUES).\nis_buy is a float (1.0 = AMM buys X, i.e. trader sells X), timestamp a float step number.\n\"\"\"\nimport math\nimport numpy as np\n\ntry:\n    from numba import njit\nexcept Exception:  # pragma: no cover - port still runs as plain Python\n    def njit(*a, **k):\n        if a and callable(a[0]):\n            return a[0]\n        return lambda f: f\n\nBPS = 1e-4\n\n# ----------------------------------------------------------------------------------\n# Every numeric constant of the contract, in source order (named constants first as\n# declared, then inline literals as they occur in afterInitialize, afterSwap,\n# _posterior, _band, _compressTailWithSlope). Values are WAD fractions unless the\n# name says COUNT/STEPS/INT. WAD itself, slot indices, bit-shift widths (64/80/160)\n# and loop bounds of _band's 7-node quadrature / _powWad are structural, not listed.\n# ----------------------------------------------------------------------------------\n_TH = [\n    (\"ELAPSED_CAP_STEPS\", 8.0),\n    (\"SIGNAL_THRESHOLD\", 1.0 / 650.0),\n    (\"DIR_DECAY\", 0.75),\n    (\"ACT_DECAY\", 0.53),\n    (\"SIZE_DECAY\", 0.53),\n    (\"TOX_DECAY\", 0.91),\n    (\"SIGMA_DECAY\", 0.69),\n    (\"LAMBDA_DECAY\", 0.99),\n    (\"SIZE_BLEND_DECAY\", 0.828),\n    (\"TOX_BLEND_DECAY\", 0.051),\n    (\"ACT_BLEND_DECAY\", 0.985),\n    (\"PHAT_ALPHA\", 0.27),\n    (\"PHAT_ALPHA_RETAIL\", 0.06),\n    (\"PHAT_ALPHA_SAME\", 0.12),\n    (\"REVERT_U\", 0.0),\n    (\"DIR_IMPACT_MULT_INT\", 4.0),\n    (\"GATE_SIGMA_MULT\", 7.2),\n    (\"MIN_GATE\", 0.03),\n    (\"TRADE_TOX_BOOST\", 3500 * BPS),\n    (\"STALE_ATTRACT_FRAC\", 1.05),\n    (\"RET_CAP\", 1.0 / 35.0),\n    (\"TOX_CAP\", 1.0 / 5.0),\n    (\"TRADE_RATIO_CAP\", 1.0 / 5.0),\n    (\"LAMBDA_CAP\", 1.82),\n    (\"STEP_COUNT_CAP_INT\", 64.0),\n    (\"BASE_FEE\", 4 * BPS),\n    (\"SIGMA_COEF\", 0.2),\n    (\"LAMBDA_COEF\", 12 * BPS),\n    (\"FLOW_SIZE_COEF\", 4842 * BPS),\n    (\"TOX_COEF\", 300 * BPS),\n    (\"TOX_QUAD_COEF\", 15000 * BPS),\n    (\"ACT_COEF\", 91843 * BPS),\n    (\"DIR_COEF\", 20 * BPS),\n    (\"DIR_TOX_COEF\", 100 * BPS),\n    (\"STALE_DIR_COEF\", 6850 * BPS),\n    (\"SIGMA_TOX_COEF\", 500 * BPS),\n    (\"TAIL_KNEE\", 600 * BPS),\n    (\"TAIL_SLOPE_PROTECT\", 0.93),\n    (\"TAIL_SLOPE_ATTRACT\", 0.85),\n    # afterInitialize\n    (\"INIT_PHAT_DEFAULT\", 100.0),          # 100 * WAD when initialX == 0\n    (\"INIT_SIGMA\", 0.00095),               # 950000000000000\n    (\"INIT_LAMBDA\", 0.8),                  # 800000000000000000\n    (\"INIT_SIZE\", 0.002),                  # 2000000000000000\n    (\"INIT_FLOW_RATE\", 0.4),               # packed slots[15] low 80 bits\n    (\"INIT_FLOW_MEAN_SIZE\", 0.002),        # packed slots[15] bits 160+\n    (\"INIT_UNCERTAINTY\", 9.025e-7),        # 902500000000\n    # afterSwap\n    (\"UNC_STEP_CAP\", 1e-4),                # 100000000000000 (twice in one if)\n    (\"SILENCE_MIN_GAP_INT\", 1.0),          # silent > 1\n    (\"SILENCE_G_CAP_INT\", 1.0),            # g = silent-1 capped at 1\n    (\"SILENCE_DECAY\", 0.8),                # 800000000000000000\n    (\"SILENCE_CENTER_DIV_INT\", 2.0),       # (.. + ..) / 2\n    (\"SILENCE_SCALE_COEF\", 0.3),           # 300000000000000000\n    (\"ROUTE_FEE_THRESH\", 30 * BPS),        # feeUsed > 30 * BPS\n    (\"ROUTE_NORMAL_FEE\", 30 * BPS),        # WAD - 30 * BPS (both branches)\n    (\"ROUTE_PHAT_KEEP\", 0.90),             # 90 * WAD / 100\n    (\"ROUTE_PHAT_W\", 0.10),                # 10 * WAD / 100\n    (\"PUSH_CAP\", 0.25),                    # WAD / 4\n    (\"DIR_MAX\", 2.0),                      # 2 * WAD\n    (\"FLOW_GATE\", 0.342406799193418304),   # if (342406799193418304 > 0)\n    (\"FLOW_RATE_DEFAULT\", 0.4),\n    (\"FLOW_MEAN_SIZE_DEFAULT\", 0.002),\n    (\"FLOW_INST_CAP\", 3.0),                # 3 * WAD\n    (\"FLOW_RETENTION\", 0.999),\n    (\"FLOW_RETENTION_STEPS_CAP_INT\", 64.0),\n    (\"MISSING_MODE_INT\", 2.0),             # if (2 == 2)\n    (\"MISSING_COEF\", 196.030880396139429888),\n    (\"MISSING_CAP\", 0.333333333333333376),\n    (\"FLOW_LEARN_RETENTION\", 0.999),       # WAD - 999000000000000000\n    (\"RETAIL_RATE_MULT\", 0.366383424913407168),\n    (\"SIZE_MODE_INT\", 2.0),                # 2 == 0 ? sizeHat : ...\n    (\"RETAIL_SIZE_MULT\", 1.883296158119298304),\n    (\"LAMBDA_FLOW_BLEND\", 0.342406799193418304),\n    (\"SIZE_FLOW_BLEND\", 0.342406799193418304),\n    (\"STALE_PHAT_W\", 0.7),\n    (\"STALE_FAST_W\", 0.3),\n    (\"TRADE_BOOST_CAP_LATER\", 16 * BPS),\n    (\"FIRST_STEP_CHEAP_CAP\", 30 * BPS),    # used for both comparison and assignment\n    (\"CHEAP_SIDE_CAP\", 36 * BPS),          # used for both comparison and assignment\n    (\"MAX_FEE\", 0.1),                      # clampFee (AMMStrategyBase)\n    # _posterior\n    (\"POST_V_FLOOR\", 1e-8),                # 10000000000\n    (\"POST_ELAPSED_CAP_STEPS\", 8.0),\n    (\"POST_PROC_VAR_GAP\", 9.025e-7),       # 902500000000*(elapsed-1)\n    (\"POST_PROC_VAR_STEP\", 9.025e-7),      # x.v += 902500000000\n    (\"POST_ROUTE_FEE_THRESH\", 30 * BPS),\n    (\"POST_ROUTE_NORMAL_FEE\", 30 * BPS),\n    (\"POST_ROUTE_NOISE\", 9e-6),            # 9000000000000\n    (\"POST_ARB_OBS_VAR\", 2.25e-8),         # 22500000000\n    (\"POST_Z_DIV_INT\", 8.0),               # z/8\n    (\"POST_DENSITY_POW_INT\", 4.0),\n    (\"POST_ODDS_NUM\", 0.004),              # 4000000000000000\n    (\"POST_SIZE_THRESH\", 0.003),           # 3000000000000000\n    (\"POST_ODDS_SIZE_MULT\", 0.4),          # 4*WAD/10\n    (\"POST_ODDS_SILENT_MULT\", 0.8),        # 8*WAD/10\n    (\"POST_BAND_SD_MULT_INT\", 2.0),        # width + 2*sd\n    (\"POST_MASS_FLOOR\", 0.01),             # WAD/100\n    (\"POST_VAR_CAP\", 1e-4),                # 100000000000000\n    # _band\n    (\"BAND_W_OUTER_INT\", 1.0),\n    (\"BAND_W_2SD_INT\", 10.0),\n    (\"BAND_W_1SD_INT\", 45.0),\n    (\"BAND_W_CENTER_INT\", 72.0),\n    (\"BAND_LIK_COEF_INT\", 4.0),\n    (\"BAND_V_FLOOR\", 1e-8),                # 10000000000\n]\nTH_NAMES = [n for n, _ in _TH]\nTH_VALUES = np.array([v for _, v in _TH], dtype=np.float64)\nTH = TH_VALUES\nfor _i, _n in enumerate(TH_NAMES):\n    globals()[\"T_\" + _n] = _i\nN_TH = len(TH_NAMES)\n\n# State layout (S float64[40]); contract slot in brackets.\nS_BID, S_ASK, S_LASTTS, S_LASTSPOT = 0, 1, 2, 3\nS_DIR, S_ACT, S_PHAT, S_SIGMA, S_LAMBDA, S_SIZE, S_TOX, S_COUNT = 4, 5, 6, 7, 8, 9, 10, 11\nS_PRE11, S_D1, S_UNC, S_FAST = 12, 13, 14, 15\nS_FRATE, S_FCOUNT, S_FMEAN = 16, 17, 18\nS_LEN = 40\nSLOTS = [\n    (0, \"slots[0] prevBidFee\"),\n    (1, \"slots[1] prevAskFee\"),\n    (2, \"slots[2] low 64 bits: last timestamp\"),\n    (3, \"slots[2] >> 64: last post-trade spot (reserveY/reserveX)\"),\n    (4, \"slots[3] dirState (centered at 1.0, range [0,2])\"),\n    (5, \"slots[4] actEma\"),\n    (6, \"slots[5] pHat (slow fair-price estimate)\"),\n    (7, \"slots[6] sigmaHat\"),\n    (8, \"slots[7] lambdaHat (trades per step EMA)\"),\n    (9, \"slots[8] sizeHat (trade size / reserveY EMA)\"),\n    (10, \"slots[9] toxEma\"),\n    (11, \"slots[10] stepTradeCount\"),\n    (12, \"slots[11] 'pre' for REVERT_U (never written by RS2, always 0; dead since REVERT_U=0)\"),\n    (13, \"slots[12] first-trade direction of current step (1 up, 2 down, 0 none)\"),\n    (14, \"slots[13] posterior variance (uncertainty)\"),\n    (15, \"slots[14] posterior mean fastHat\"),\n    (16, \"slots[15] bits 0-79: flow rate\"),\n    (17, \"slots[15] bits 80-159: corrected trade count this step\"),\n    (18, \"slots[15] bits 160+: meanSize\"),\n]\n\n\n@njit(cache=False)\ndef _powi(f, e):\n    # _powWad: square-and-multiply, e integer >= 0\n    r = 1.0\n    n = int(e)\n    while n > 0:\n        if n & 1:\n            r = r * f\n        f = f * f\n        n >>= 1\n    return r\n\n\n@njit(cache=False)\ndef _blend(a, b, w):\n    if b >= a:\n        return a + (b - a) * w\n    return a - (a - b) * w\n\n\n@njit(cache=False)\ndef _compress(fee, slope, TH):\n    knee = TH[T_TAIL_KNEE]\n    if fee <= knee:\n        return fee\n    return knee + (fee - knee) * slope\n\n\n@njit(cache=False)\ndef _clampfee(fee, TH):\n    if fee < 0.0:\n        return 0.0\n    if fee > TH[T_MAX_FEE]:\n        return TH[T_MAX_FEE]\n    return fee\n\n\n@njit(cache=False)\ndef _band(mu, v, lo, hi, TH):\n    # sd = wmul(mu, isqrt(v*WAD)); isqrt is a floor sqrt (rel err <= 1e-9 at v~1e-8)\n    sd = mu * math.sqrt(v)\n    a0 = 0.0\n    a1 = 0.0\n    a2 = 0.0\n    for j in range(7):\n        if j < 3:\n            k = 3.0 - j\n            p = mu - k * sd if mu > k * sd else 1e-18  # Solidity uses 1 wei\n        else:\n            p = mu + (j - 3.0) * sd\n        if j == 3:\n            w = TH[T_BAND_W_CENTER_INT]\n        elif j == 2 or j == 4:\n            w = TH[T_BAND_W_1SD_INT]\n        elif j == 1 or j == 5:\n            w = TH[T_BAND_W_2SD_INT]\n        else:\n            w = TH[T_BAND_W_OUTER_INT]\n        if p < lo:\n            dist = lo - p\n        elif p > hi:\n            dist = p - hi\n        else:\n            dist = 0.0\n        z = dist / sd if sd > 0.0 else 0.0\n        lik = 1.0 / (1.0 + TH[T_BAND_LIK_COEF_INT] * (z * z))\n        w = w * lik\n        a0 += w\n        a1 += w * p\n        d = abs(p - mu) / mu\n        a2 += w * (d * d)\n    m = a1 / a0\n    d = abs(m - mu) / mu\n    second = a2 / a0\n    if second > d * d:\n        return m, second - d * d\n    return m, TH[T_BAND_V_FLOOR]\n\n\n@njit(cache=False)\ndef _posterior(mu, v, obs, spot, pre, bid, ask, first, silent, buy, size, TH):\n    if mu == 0.0:\n        mu = spot\n    if v < TH[T_POST_V_FLOOR]:\n        v = TH[T_POST_V_FLOOR]\n    lo = pre * (1.0 - bid)\n    hi = pre / (1.0 - ask)\n    if first:\n        if silent > 1.0 and pre > 0.0:\n            el = silent if silent <= TH[T_POST_ELAPSED_CAP_STEPS] else TH[T_POST_ELAPSED_CAP_STEPS]\n            v += TH[T_POST_PROC_VAR_GAP] * (el - 1.0)\n            mu, v = _band(mu, v, lo, hi, TH)\n        v += TH[T_POST_PROC_VAR_STEP]\n    mR = mu\n    vR = v\n    if first and pre > 0.0:\n        mR, vR = _band(mu, v, lo, hi, TH)\n    if not first:\n        fee = bid if buy else ask\n        if fee > TH[T_POST_ROUTE_FEE_THRESH]:\n            nf = TH[T_POST_ROUTE_NORMAL_FEE]\n            if buy:\n                normal = spot * (1.0 - fee) / (1.0 - nf)\n            else:\n                normal = spot * (1.0 - nf) / (1.0 - fee)\n            res = abs(normal - mu) / mu\n            noise = TH[T_POST_ROUTE_NOISE] + res * res\n            k = v / (v + noise)\n            return _blend(mu, normal, k), v * (1.0 - k), 0.0\n        return mu, v, 0.0\n    e = abs(obs - mu) / mu\n    totalV = v + TH[T_POST_ARB_OBS_VAR]\n    z = (e * e) / totalV\n    # z/8 is integer division of a WAD value in Solidity (<= 1 wei error)\n    density = _powi(1.0 / (1.0 + z / TH[T_POST_Z_DIV_INT]), TH[T_POST_DENSITY_POW_INT])\n    # _isqrt(totalV*WAD): floor integer sqrt -> sqrt(totalV) as a WAD fraction\n    odds = density * (TH[T_POST_ODDS_NUM] / math.sqrt(totalV))\n    if size > TH[T_POST_SIZE_THRESH]:\n        odds = odds * TH[T_POST_ODDS_SIZE_MULT]\n    if silent > 1.0:\n        odds = odds * TH[T_POST_ODDS_SILENT_MULT]\n    sd = math.sqrt(v)\n    width = (hi - lo) / mu\n    if mu < lo:\n        dist = lo - mu\n    elif mu > hi:\n        dist = mu - hi\n    else:\n        dist = 0.0\n    zB = (dist / mu) / sd\n    mass = (width / (width + TH[T_POST_BAND_SD_MULT_INT] * sd)) * (1.0 / (1.0 + zB * zB))\n    if mass < TH[T_POST_MASS_FLOOR]:\n        mass = TH[T_POST_MASS_FLOOR]\n    odds = odds / mass\n    prob = odds / (1.0 + odds)\n    kArb = v / totalV\n    mArb = _blend(mu, obs, kArb)\n    mean = _blend(mR, mArb, prob)\n    between = abs(mArb - mR) / mu\n    var = prob * (v * (1.0 - kArb)) + (1.0 - prob) * vR + (prob * (1.0 - prob)) * (between * between)\n    if var > TH[T_POST_VAR_CAP]:\n        var = TH[T_POST_VAR_CAP]\n    return mean, var, prob\n\n\n@njit(cache=False)\ndef strat_init(S, TH, x0, y0):\n    for i in range(S.shape[0]):\n        S[i] = 0.0\n    S[S_BID] = TH[T_BASE_FEE]\n    S[S_ASK] = TH[T_BASE_FEE]\n    S[S_DIR] = 1.0\n    S[S_PHAT] = y0 / x0 if x0 > 0.0 else TH[T_INIT_PHAT_DEFAULT]\n    S[S_SIGMA] = TH[T_INIT_SIGMA]\n    S[S_LAMBDA] = TH[T_INIT_LAMBDA]\n    S[S_SIZE] = TH[T_INIT_SIZE]\n    S[S_FRATE] = TH[T_INIT_FLOW_RATE]\n    S[S_FCOUNT] = 0.0\n    S[S_FMEAN] = TH[T_INIT_FLOW_MEAN_SIZE]\n    S[S_UNC] = TH[T_INIT_UNCERTAINTY]\n    S[S_FAST] = S[S_PHAT]\n    return TH[T_BASE_FEE], TH[T_BASE_FEE]\n\n\n@njit(cache=False)\ndef strat_after(S, TH, is_buy, amount_x, amount_y, timestamp, reserve_x, reserve_y):\n    buy = is_buy > 0.5\n    prevBid = S[S_BID]\n    prevAsk = S[S_ASK]\n    lastTs = S[S_LASTTS]\n    dirState = S[S_DIR]\n    actEma = S[S_ACT]\n    pHat = S[S_PHAT]\n    sigmaHat = S[S_SIGMA]\n    lambdaHat = S[S_LAMBDA]\n    sizeHat = S[S_SIZE]\n    toxEma = S[S_TOX]\n    cnt = S[S_COUNT]\n    fastHat = S[S_FAST]\n    unc = S[S_UNC]\n    silent = timestamp - lastTs if timestamp > lastTs else 0.0\n    isNewStep = timestamp > lastTs\n    if isNewStep:\n        elapsedRaw = timestamp - lastTs\n        elapsed = elapsedRaw if elapsedRaw <= TH[T_ELAPSED_CAP_STEPS] else TH[T_ELAPSED_CAP_STEPS]\n        # _decayCentered\n        mul = _powi(TH[T_DIR_DECAY], elapsed)\n        if dirState >= 1.0:\n            dirState = 1.0 + (dirState - 1.0) * mul\n        else:\n            below = (1.0 - dirState) * mul\n            dirState = 1.0 - below if below < 1.0 else 0.0\n        actEma = actEma * _powi(TH[T_ACT_DECAY], elapsed)\n        sizeHat = sizeHat * _powi(TH[T_SIZE_DECAY], elapsed)\n        toxEma = toxEma * _powi(TH[T_TOX_DECAY], elapsed)\n        if cnt > 0.0 and elapsedRaw > 0.0:\n            lam = cnt / elapsedRaw\n            if lam > TH[T_LAMBDA_CAP]:\n                lam = TH[T_LAMBDA_CAP]\n            lambdaHat = lambdaHat * TH[T_LAMBDA_DECAY] + lam * (1.0 - TH[T_LAMBDA_DECAY])\n        if unc > TH[T_UNC_STEP_CAP]:\n            unc = TH[T_UNC_STEP_CAP]\n        cnt = 0.0\n\n    first = cnt == 0.0\n    spot = reserve_y / reserve_x if reserve_x > 0.0 else pHat\n    if pHat == 0.0:\n        pHat = spot\n\n    feeUsed = prevBid if buy else prevAsk\n    gamma = 1.0 - feeUsed if feeUsed < 1.0 else 0.0\n    if gamma == 0.0:\n        pImpl = spot\n    else:\n        pImpl = spot * gamma if buy else spot / gamma\n\n    silenceScale = 1.0\n    if first and silent > TH[T_SILENCE_MIN_GAP_INT]:\n        g = silent - 1.0\n        if g > TH[T_SILENCE_G_CAP_INT]:\n            g = TH[T_SILENCE_G_CAP_INT]\n        w = 1.0 - _powi(TH[T_SILENCE_DECAY], g)\n        s = S[S_LASTSPOT]\n        if s == 0.0:\n            s = pHat\n        c = (s * (1.0 - prevBid) + s / (1.0 - prevAsk)) / TH[T_SILENCE_CENTER_DIV_INT]\n        if c >= pHat:\n            pHat += w * (c - pHat)\n        else:\n            pHat -= w * (pHat - c)\n        silenceScale = 1.0 - TH[T_SILENCE_SCALE_COEF] * w\n\n    ret = abs(pImpl - pHat) / pHat if pHat > 0.0 else 0.0\n    alpha = TH[T_PHAT_ALPHA] if first else TH[T_PHAT_ALPHA_RETAIL]\n    secondPrint = (not first) and cnt == 1.0\n    sameDir = False\n    oppDir = False\n    if secondPrint:\n        up2 = pImpl >= pHat\n        d1 = S[S_D1]\n        if d1 != 0.0:\n            sameDir = (d1 == 1.0) == up2\n            oppDir = not sameDir\n        if sameDir:\n            alpha = TH[T_PHAT_ALPHA_SAME]\n    if first:\n        S[S_D1] = 1.0 if pImpl >= pHat else 2.0\n    gate = sigmaHat * TH[T_GATE_SIGMA_MULT]\n    if gate < TH[T_MIN_GATE]:\n        gate = TH[T_MIN_GATE]\n    alpha = alpha * silenceScale\n    gate = gate * silenceScale\n    if ret <= gate:\n        pHat = pHat * (1.0 - alpha) + pImpl * alpha\n    if oppDir and TH[T_REVERT_U] > 0.0:\n        pre = S[S_PRE11]\n        if pre > pHat:\n            pHat = pHat + (pre - pHat) * TH[T_REVERT_U]\n        else:\n            pHat = pHat - (pHat - pre) * TH[T_REVERT_U]\n    if first:\n        if ret > TH[T_RET_CAP]:\n            ret = TH[T_RET_CAP]\n        sigmaHat = sigmaHat * TH[T_SIGMA_DECAY] + ret * (1.0 - TH[T_SIGMA_DECAY])\n\n    if (not first) and feeUsed > TH[T_ROUTE_FEE_THRESH] and gamma > 0.0:\n        nf = TH[T_ROUTE_NORMAL_FEE]\n        if buy:\n            normalSpot = (spot * gamma) / (1.0 - nf)\n        else:\n            normalSpot = (spot * (1.0 - nf)) / gamma\n        pHat = pHat * TH[T_ROUTE_PHAT_KEEP] + normalSpot * TH[T_ROUTE_PHAT_W]\n\n    sizeObs = amount_y / reserve_y if reserve_y > 0.0 else 0.0\n    fastHat, unc, arbP = _posterior(fastHat, unc, pImpl, spot, S[S_LASTSPOT],\n                                    prevBid, prevAsk, first, silent, buy, sizeObs, TH)\n    S[S_UNC] = unc\n    S[S_FAST] = fastHat\n    tr = sizeObs\n    if tr > TH[T_TRADE_RATIO_CAP]:\n        tr = TH[T_TRADE_RATIO_CAP]\n\n    if tr > TH[T_SIGNAL_THRESHOLD]:\n        push = tr * TH[T_DIR_IMPACT_MULT_INT]\n        if push > TH[T_PUSH_CAP]:\n            push = TH[T_PUSH_CAP]\n        if buy:\n            dirState = dirState + push\n            if dirState > TH[T_DIR_MAX]:\n                dirState = TH[T_DIR_MAX]\n        else:\n            dirState = dirState - push if dirState > push else 0.0\n        actEma = actEma * TH[T_ACT_BLEND_DECAY] + tr * (1.0 - TH[T_ACT_BLEND_DECAY])\n        sizeHat = sizeHat * TH[T_SIZE_BLEND_DECAY] + tr * (1.0 - TH[T_SIZE_BLEND_DECAY])\n        if sizeHat > 1.0:\n            sizeHat = 1.0\n\n    tox = abs(spot - pHat) / pHat if pHat > 0.0 else 0.0\n    if tox > TH[T_TOX_CAP]:\n        tox = TH[T_TOX_CAP]\n    toxEma = toxEma * TH[T_TOX_BLEND_DECAY] + tox * (1.0 - TH[T_TOX_BLEND_DECAY])\n    toxSig = toxEma\n\n    cnt = cnt + 1.0\n    if cnt > TH[T_STEP_COUNT_CAP_INT]:\n        cnt = TH[T_STEP_COUNT_CAP_INT]\n\n    origLambda = lambdaHat\n    origSize = sizeHat\n\n    if TH[T_FLOW_GATE] > 0.0:\n        rate = S[S_FRATE]\n        count = S[S_FCOUNT]\n        meanSize = S[S_FMEAN]\n        if rate == 0.0:\n            rate = TH[T_FLOW_RATE_DEFAULT]\n        if meanSize == 0.0:\n            meanSize = TH[T_FLOW_MEAN_SIZE_DEFAULT]\n        if isNewStep:\n            # count / silent: integer division of a WAD value by an integer (<= 1 wei)\n            inst = count / silent\n            if inst > TH[T_FLOW_INST_CAP]:\n                inst = TH[T_FLOW_INST_CAP]\n            sc = silent if silent <= TH[T_FLOW_RETENTION_STEPS_CAP_INT] else TH[T_FLOW_RETENTION_STEPS_CAP_INT]\n            retention = _powi(TH[T_FLOW_RETENTION], sc)\n            rate = rate * retention + inst * (1.0 - retention)\n            count = 0.0\n        weight = 1.0 - arbP if first else 1.0\n        cw = weight\n        if TH[T_MISSING_MODE_INT] == 2.0:\n            missing = feeUsed * TH[T_MISSING_COEF]\n            if missing > TH[T_MISSING_CAP]:\n                missing = TH[T_MISSING_CAP]\n            cw = weight / (1.0 - missing)\n        count += cw\n        learning = (1.0 - TH[T_FLOW_LEARN_RETENTION]) * weight\n        meanSize = _blend(meanSize, tr, learning)\n        S[S_FRATE] = rate\n        S[S_FCOUNT] = count\n        S[S_FMEAN] = meanSize\n        retailRate = rate * TH[T_RETAIL_RATE_MULT]\n        if TH[T_SIZE_MODE_INT] == 0.0:\n            retailSize = sizeHat\n        else:\n            retailSize = meanSize * TH[T_RETAIL_SIZE_MULT]\n        lambdaHat = _blend(lambdaHat, retailRate, TH[T_LAMBDA_FLOW_BLEND])\n        sizeHat = _blend(sizeHat, retailSize, TH[T_SIZE_FLOW_BLEND])\n\n    flowSize = lambdaHat * sizeHat\n    fBase = (TH[T_BASE_FEE] + TH[T_SIGMA_COEF] * sigmaHat + TH[T_LAMBDA_COEF] * lambdaHat\n             + TH[T_FLOW_SIZE_COEF] * flowSize)\n    fMid = (fBase + TH[T_TOX_COEF] * toxSig + TH[T_TOX_QUAD_COEF] * (toxSig * toxSig)\n            + TH[T_ACT_COEF] * actEma)\n    fMid = fMid + TH[T_SIGMA_TOX_COEF] * (sigmaHat * toxSig)\n\n    lambdaHat = origLambda\n    sizeHat = origSize\n    if dirState >= 1.0:\n        dirDev = dirState - 1.0\n        sellP = True\n    else:\n        dirDev = 1.0 - dirState\n        sellP = False\n    skew = TH[T_DIR_COEF] * dirDev + TH[T_DIR_TOX_COEF] * (dirDev * toxSig)\n    if sellP:\n        bid = fMid + skew\n        ask = fMid - skew if fMid > skew else 0.0\n    else:\n        ask = fMid + skew\n        bid = fMid - skew if fMid > skew else 0.0\n\n    staleHat = pHat * TH[T_STALE_PHAT_W] + fastHat * TH[T_STALE_FAST_W]\n    staleTox = abs(spot - staleHat) / staleHat\n    if staleTox > TH[T_TOX_CAP]:\n        staleTox = TH[T_TOX_CAP]\n    staleShift = TH[T_STALE_DIR_COEF] * staleTox\n    attract = staleShift * TH[T_STALE_ATTRACT_FRAC]\n    if spot >= staleHat:\n        bid = bid + staleShift\n        ask = ask - attract if ask > attract else 0.0\n    else:\n        ask = ask + staleShift\n        bid = bid - attract if bid > attract else 0.0\n\n    aligned = (buy and spot >= pHat) or ((not buy) and spot < pHat)\n    if aligned:\n        boost = TH[T_TRADE_TOX_BOOST] * tr\n        if (not first) and boost > TH[T_TRADE_BOOST_CAP_LATER]:\n            boost = TH[T_TRADE_BOOST_CAP_LATER]\n        if buy:\n            bid = bid + boost\n        else:\n            ask = ask + boost\n\n    if sellP:\n        bid = _clampfee(_compress(bid, TH[T_TAIL_SLOPE_PROTECT], TH), TH)\n        ask = _clampfee(_compress(ask, TH[T_TAIL_SLOPE_ATTRACT], TH), TH)\n    else:\n        ask = _clampfee(_compress(ask, TH[T_TAIL_SLOPE_PROTECT], TH), TH)\n        bid = _clampfee(_compress(bid, TH[T_TAIL_SLOPE_ATTRACT], TH), TH)\n\n    c30 = TH[T_FIRST_STEP_CHEAP_CAP]\n    if first:\n        if ask > bid and bid > c30:\n            bid = c30\n        elif bid > ask and ask > c30:\n            ask = c30\n    c36 = TH[T_CHEAP_SIDE_CAP]\n    if bid > ask and ask > c36:\n        ask = c36\n    elif ask > bid and bid > c36:\n        bid = c36\n\n    S[S_BID] = bid\n    S[S_ASK] = ask\n    S[S_LASTSPOT] = spot\n    S[S_LASTTS] = timestamp\n    S[S_DIR] = dirState\n    S[S_ACT] = actEma\n    S[S_PHAT] = pHat\n    S[S_SIGMA] = sigmaHat\n    S[S_LAMBDA] = lambdaHat\n    S[S_SIZE] = sizeHat\n    S[S_TOX] = toxEma\n    S[S_COUNT] = cnt\n    return bid, ask\n",
 "api": {
  "strat_init": "strat_init(S, TH, x0, y0) -> (bid_fee, ask_fee); zeroes S then sets afterInitialize slots",
  "strat_after": "strat_after(S, TH, is_buy, amount_x, amount_y, timestamp, reserve_x, reserve_y) -> (bid_fee, ask_fee); is_buy 1.0 = AMM buys X; all values TradeInfo WAD ints / 1e18; timestamp float step",
  "S": "float64[40]; indices 0-18 used (see slots), 19-39 unused",
  "TH": "float64[102] = TH_VALUES, names TH_NAMES; module also defines T_<NAME> index constants used inside the jitted code"
 },
 "th_names": [
  "ELAPSED_CAP_STEPS",
  "SIGNAL_THRESHOLD",
  "DIR_DECAY",
  "ACT_DECAY",
  "SIZE_DECAY",
  "TOX_DECAY",
  "SIGMA_DECAY",
  "LAMBDA_DECAY",
  "SIZE_BLEND_DECAY",
  "TOX_BLEND_DECAY",
  "ACT_BLEND_DECAY",
  "PHAT_ALPHA",
  "PHAT_ALPHA_RETAIL",
  "PHAT_ALPHA_SAME",
  "REVERT_U",
  "DIR_IMPACT_MULT_INT",
  "GATE_SIGMA_MULT",
  "MIN_GATE",
  "TRADE_TOX_BOOST",
  "STALE_ATTRACT_FRAC",
  "RET_CAP",
  "TOX_CAP",
  "TRADE_RATIO_CAP",
  "LAMBDA_CAP",
  "STEP_COUNT_CAP_INT",
  "BASE_FEE",
  "SIGMA_COEF",
  "LAMBDA_COEF",
  "FLOW_SIZE_COEF",
  "TOX_COEF",
  "TOX_QUAD_COEF",
  "ACT_COEF",
  "DIR_COEF",
  "DIR_TOX_COEF",
  "STALE_DIR_COEF",
  "SIGMA_TOX_COEF",
  "TAIL_KNEE",
  "TAIL_SLOPE_PROTECT",
  "TAIL_SLOPE_ATTRACT",
  "INIT_PHAT_DEFAULT",
  "INIT_SIGMA",
  "INIT_LAMBDA",
  "INIT_SIZE",
  "INIT_FLOW_RATE",
  "INIT_FLOW_MEAN_SIZE",
  "INIT_UNCERTAINTY",
  "UNC_STEP_CAP",
  "SILENCE_MIN_GAP_INT",
  "SILENCE_G_CAP_INT",
  "SILENCE_DECAY",
  "SILENCE_CENTER_DIV_INT",
  "SILENCE_SCALE_COEF",
  "ROUTE_FEE_THRESH",
  "ROUTE_NORMAL_FEE",
  "ROUTE_PHAT_KEEP",
  "ROUTE_PHAT_W",
  "PUSH_CAP",
  "DIR_MAX",
  "FLOW_GATE",
  "FLOW_RATE_DEFAULT",
  "FLOW_MEAN_SIZE_DEFAULT",
  "FLOW_INST_CAP",
  "FLOW_RETENTION",
  "FLOW_RETENTION_STEPS_CAP_INT",
  "MISSING_MODE_INT",
  "MISSING_COEF",
  "MISSING_CAP",
  "FLOW_LEARN_RETENTION",
  "RETAIL_RATE_MULT",
  "SIZE_MODE_INT",
  "RETAIL_SIZE_MULT",
  "LAMBDA_FLOW_BLEND",
  "SIZE_FLOW_BLEND",
  "STALE_PHAT_W",
  "STALE_FAST_W",
  "TRADE_BOOST_CAP_LATER",
  "FIRST_STEP_CHEAP_CAP",
  "CHEAP_SIDE_CAP",
  "MAX_FEE",
  "POST_V_FLOOR",
  "POST_ELAPSED_CAP_STEPS",
  "POST_PROC_VAR_GAP",
  "POST_PROC_VAR_STEP",
  "POST_ROUTE_FEE_THRESH",
  "POST_ROUTE_NORMAL_FEE",
  "POST_ROUTE_NOISE",
  "POST_ARB_OBS_VAR",
  "POST_Z_DIV_INT",
  "POST_DENSITY_POW_INT",
  "POST_ODDS_NUM",
  "POST_SIZE_THRESH",
  "POST_ODDS_SIZE_MULT",
  "POST_ODDS_SILENT_MULT",
  "POST_BAND_SD_MULT_INT",
  "POST_MASS_FLOOR",
  "POST_VAR_CAP",
  "BAND_W_OUTER_INT",
  "BAND_W_2SD_INT",
  "BAND_W_1SD_INT",
  "BAND_W_CENTER_INT",
  "BAND_LIK_COEF_INT",
  "BAND_V_FLOOR"
 ],
 "th_values": [
  8.0,
  0.0015384615384615385,
  0.75,
  0.53,
  0.53,
  0.91,
  0.69,
  0.99,
  0.828,
  0.051,
  0.985,
  0.27,
  0.06,
  0.12,
  0.0,
  4.0,
  7.2,
  0.03,
  0.35000000000000003,
  1.05,
  0.02857142857142857,
  0.2,
  0.2,
  1.82,
  64.0,
  0.0004,
  0.2,
  0.0012000000000000001,
  0.4842,
  0.030000000000000002,
  1.5,
  9.1843,
  0.002,
  0.01,
  0.685,
  0.05,
  0.060000000000000005,
  0.93,
  0.85,
  100.0,
  0.00095,
  0.8,
  0.002,
  0.4,
  0.002,
  9.025e-07,
  0.0001,
  1.0,
  1.0,
  0.8,
  2.0,
  0.3,
  0.003,
  0.003,
  0.9,
  0.1,
  0.25,
  2.0,
  0.3424067991934183,
  0.4,
  0.002,
  3.0,
  0.999,
  64.0,
  2.0,
  196.03088039613942,
  0.33333333333333337,
  0.999,
  0.36638342491340714,
  2.0,
  1.8832961581192984,
  0.3424067991934183,
  0.3424067991934183,
  0.7,
  0.3,
  0.0016,
  0.003,
  0.0036000000000000003,
  0.1,
  1e-08,
  8.0,
  9.025e-07,
  9.025e-07,
  0.003,
  0.003,
  9e-06,
  2.25e-08,
  8.0,
  4.0,
  0.004,
  0.003,
  0.4,
  0.8,
  2.0,
  0.01,
  0.0001,
  1.0,
  10.0,
  45.0,
  72.0,
  4.0,
  1e-08
 ],
 "th_notes": "Source order: the 39 declared constants (ELAPSED_CAP..TAIL_SLOPE_ATTRACT), then inline literals as they occur in afterInitialize, afterSwap, _posterior, _band, plus MAX_FEE from AMMStrategyBase.clampFee (applied at the clampFee calls). A literal used in several places is one entry per place (e.g. 342406799193418304 is FLOW_GATE, LAMBDA_FLOW_BLEND, SIZE_FLOW_BLEND; 30 bps appears as ROUTE_FEE_THRESH/ROUTE_NORMAL_FEE/FIRST_STEP_CHEAP_CAP/POST_ROUTE_*). Except FLOW_GATE/MISSING_MODE_INT/SIZE_MODE_INT, which are compared against their source literal, each entry can be varied on its own. Left out as structural: WAD, slot indices, the bit widths 64/80/160 of the slot packing, the 7-node loop bound and node offsets (j-3) of _band, the 0/1 in centred dirState arithmetic, the direction codes 1/2 kept in slots[12], and the 1-wei floor p=1 in _band. *_INT entries are integers in Solidity (multipliers, counts, divisors); their float value is used as the same integer.",
 "slots": [
  {
   "index": 0,
   "meaning": "slots[0] prevBidFee"
  },
  {
   "index": 1,
   "meaning": "slots[1] prevAskFee"
  },
  {
   "index": 2,
   "meaning": "slots[2] low 64 bits: last timestamp"
  },
  {
   "index": 3,
   "meaning": "slots[2] >> 64: last post-trade spot (reserveY/reserveX)"
  },
  {
   "index": 4,
   "meaning": "slots[3] dirState (centered at 1.0, range [0,2])"
  },
  {
   "index": 5,
   "meaning": "slots[4] actEma"
  },
  {
   "index": 6,
   "meaning": "slots[5] pHat (slow fair-price estimate)"
  },
  {
   "index": 7,
   "meaning": "slots[6] sigmaHat"
  },
  {
   "index": 8,
   "meaning": "slots[7] lambdaHat (trades per step EMA)"
  },
  {
   "index": 9,
   "meaning": "slots[8] sizeHat (trade size / reserveY EMA)"
  },
  {
   "index": 10,
   "meaning": "slots[9] toxEma"
  },
  {
   "index": 11,
   "meaning": "slots[10] stepTradeCount"
  },
  {
   "index": 12,
   "meaning": "slots[11] 'pre' for REVERT_U (never written by RS2, always 0; dead since REVERT_U=0)"
  },
  {
   "index": 13,
   "meaning": "slots[12] first-trade direction of current step (1 up, 2 down, 0 none)"
  },
  {
   "index": 14,
   "meaning": "slots[13] posterior variance (uncertainty)"
  },
  {
   "index": 15,
   "meaning": "slots[14] posterior mean fastHat"
  },
  {
   "index": 16,
   "meaning": "slots[15] bits 0-79: flow rate"
  },
  {
   "index": 17,
   "meaning": "slots[15] bits 80-159: corrected trade count this step"
  },
  {
   "index": 18,
   "meaning": "slots[15] bits 160+: meanSize"
  },
  {
   "index": "19-39",
   "meaning": "unused (zero)"
  }
 ],
 "diff_test": {
  "sequences": 220,
  "callbacks_per_sequence": 2000,
  "callbacks": 440220,
  "callbacks_note": "220 sequences x 2000 afterSwap callbacks, plus 1 afterInitialize per sequence, all compared",
  "max_abs_fee_diff_bps": 3.841996165654393e-09,
  "mean_abs_fee_diff_bps": 7.788136290840319e-12,
  "p99_abs_fee_diff_bps": 5.1230113901068405e-11,
  "share_above_0_01_bps": 0.0,
  "count_above_0_01_bps": 0,
  "share_above_1e-6_bps": 0.0,
  "first_divergence": null,
  "first_divergence_note": "No callback differed by more than 0.01 bps (or even 1e-6 bps), and none needed a fix. The largest difference was 3.8e-9 bps (seq 71, callback 1662: EVM ask 0.0573253046342929 vs port 0.057325304633908704). That is wmul/wdiv truncation and the floor isqrt piling up over ~1600 updates of chained EMA state.",
  "worst": {
   "seq": 71,
   "cb": 1662,
   "t": 1535,
   "evm": [
    0.0,
    0.0573253046342929
   ],
   "port": [
    0.0,
    0.057325304633908704
   ]
  },
  "coverage": {
   "arb_share": 0.27779545454545457,
   "first_in_step_share": 0.4002113636363636,
   "first_after_gap_share": 0.05944318181818182,
   "fee_bps_quantiles_bid_ask": {
    "0.05": [
     0.0,
     0.0
    ],
    "0.25": [
     0.0,
     0.0
    ],
    "0.5": [
     36.0,
     36.0
    ],
    "0.75": [
     111.882,
     110.254
    ],
    "0.95": [
     294.986,
     276.466
    ]
   },
   "share_max_fee_gt_30bps": 0.9967636363636364,
   "share_fee_at_1000bps_cap": 0.002259090909090909,
   "share_some_side_zero": 0.6387727272727273
  },
  "method": "EVM side: amm_competition.evm.adapter.EVMStrategyAdapter.from_source(RS2) with solc 0.8.24 and pyrevm 0.3.7, calling after_initialize and after_swap_wad, with reset() between sequences. Port side: rs2_port.strat_init/strat_after (njit). Both get the same WAD integers: the port gets int/1e18, the EVM gets Decimal(int)/1e18, which re-encodes to the same int. Market: a single CPMM starting at x=100 with fees kept outside the reserves, as in amm_sim_rs cfmm.rs. Fair price follows a GBM random walk. Each step has 0-4 trades; the first trade arbitrages to the edge of the fee band (closed form for a fee taken on the input) when profitable, and later trades arbitrage with p=0.1, otherwise they are lognormal retail fills of random side. In 15% of steps time jumps 2-11 steps, which exercises the silence, posterior-gap and flow-rate branches. Timestamps start at 0 as in engine.rs. The EVM's returned fees price the next trade. Even sequences use baseline settings (sigma U(0.000882,0.001008), mean size U(19,21) Y, retail size sigma 1.2, y0=10000). Odd sequences are stressed (sigma U(0.0006,0.003), mean size U(5,60), y0 U(5000,20000)). Fees are compared after every callback (max over bid and ask). Seeds are default_rng(1000+seq).",
  "harness_source": "import sys, json, time, math\nfrom decimal import Decimal, getcontext\nimport numpy as np\nsys.path.insert(0, sys.argv[1] if len(sys.argv) > 1 else '.')\ngetcontext().prec = 60\nfrom amm_competition.evm.adapter import EVMStrategyAdapter\nfrom amm_competition.core.trade import TradeInfo\nimport rs2_port as P\nfrom numba import njit\n\nNSEQ = int(sys.argv[2]) if len(sys.argv) > 2 else 200\nNCB = int(sys.argv[3]) if len(sys.argv) > 3 else 2000\nSRC = open(sys.argv[4]).read()\nWAD = 10 ** 18\n\nad = EVMStrategyAdapter.from_source(SRC, validate=False)\nafter = P.strat_after\nTH = P.TH_VALUES.copy()\n\n\ndef wad(x):\n    return int(Decimal(repr(float(x))) * WAD)\n\n\ndef dec(w):\n    return Decimal(w) / Decimal(WAD)\n\n\ndiffs = []\nfees = []\nflags = []\nfirst_div = None\nworst = (0, None)\nt0 = time.time()\nfor seq in range(NSEQ):\n    rng = np.random.default_rng(1000 + seq)\n    ad.reset()\n    realistic = seq % 2 == 0\n    if realistic:  # baseline-like: sim sigma, mean size, reserves\n        sigma = rng.uniform(0.000882, 0.001008)\n        msize = rng.uniform(19, 21)\n        x, y = 100.0, 10000.0\n    else:  # stress: wider vol, size, price level\n        sigma = rng.uniform(0.0006, 0.003)\n        msize = rng.uniform(5, 60)\n        x, y = 100.0, 10000.0 * rng.uniform(0.5, 2.0)\n    p = y / x\n    r = ad._executor.after_initialize(Decimal(wad(x)) / WAD, Decimal(wad(y)) / WAD)\n    bidw, askw = int(r.bid_fee * WAD), int(r.ask_fee * WAD)\n    S = np.zeros(40)\n    pb, pa = P.strat_init(S, TH, wad(x) / 1e18, wad(y) / 1e18)\n    diffs.append(max(abs(pb - bidw / 1e18), abs(pa - askw / 1e18)) * 1e4)\n    t = 0\n    ncb = 0\n    while ncb < NCB:\n        # time step; occasionally a gap of several steps\n        if rng.random() < 0.15:\n            gap = int(rng.integers(2, 12))\n        else:\n            gap = 1\n        for _ in range(gap):\n            p *= math.exp(sigma * rng.standard_normal())\n        if t == 0 and ncb == 0:\n            gap = 0\n        t += gap\n        ntr = int(rng.integers(0, 5))\n        trades = []\n        for k in range(ntr):\n            bf, af = bidw / 1e18, askw / 1e18\n            k_ = x * y\n            spot = y / x\n            arb = False\n            if k == 0 or rng.random() < 0.1:\n                if p < spot * (1 - bf) * 0.99999:\n                    # trader sells X until (1-bf)*k/x'^2 = p\n                    xn = math.sqrt((1 - bf) * k_ / p)\n                    dx = (xn - x) / (1 - bf)\n                    yn = k_ / xn\n                    isbuy, ax, ay = True, dx, y - yn\n                    arb = True\n                elif p > spot / (1 - af) * 1.00001:\n                    xn = math.sqrt(k_ / (p * (1 - af)))\n                    yn = k_ / xn\n                    dy = (yn - y) / (1 - af)\n                    isbuy, ax, ay = False, x - xn, dy\n                    arb = True\n            if not arb:\n                ss = 1.2 if realistic else 1.0\n                size = msize * math.exp(ss * rng.standard_normal() - 0.5 * ss * ss)\n                if rng.random() < 0.5:\n                    dyn = size * (1 - af)\n                    yn = y + dyn\n                    xn = k_ / yn\n                    isbuy, ax, ay = False, x - xn, size\n                else:\n                    dx = size / p\n                    xn = x + dx * (1 - bf)\n                    yn = k_ / xn\n                    isbuy, ax, ay = True, dx, y - yn\n            x, y = xn, yn\n            w_ax, w_ay, w_rx, w_ry = wad(ax), wad(ay), wad(x), wad(y)\n            ti = TradeInfo(side='buy' if isbuy else 'sell', amount_x=dec(w_ax), amount_y=dec(w_ay),\n                           timestamp=t, reserve_x=dec(w_rx), reserve_y=dec(w_ry))\n            bidw, askw = ad.after_swap_wad(ti)\n            pb, pa = after(S, TH, 1.0 if isbuy else 0.0, w_ax / 1e18, w_ay / 1e18, float(t),\n                           w_rx / 1e18, w_ry / 1e18)\n            d = max(abs(pb - bidw / 1e18), abs(pa - askw / 1e18)) * 1e4\n            diffs.append(d)\n            fees.append((bidw / 1e14, askw / 1e14))\n            flags.append((arb, k == 0, gap))\n            if d > worst[0]:\n                worst = (d, dict(seq=seq, cb=ncb, t=t, evm=(bidw / 1e18, askw / 1e18), port=(pb, pa)))\n            if d > 0.01 and first_div is None:\n                first_div = dict(seq=seq, cb=ncb, t=t, evm_bps=(bidw / 1e14, askw / 1e14),\n                                 port_bps=(pb * 1e4, pa * 1e4), arb=arb, isbuy=isbuy)\n            ncb += 1\n            if ncb >= NCB:\n                break\n    if seq % 20 == 0:\n        print(seq, len(diffs), max(diffs), time.time() - t0, flush=True)\nD = np.array(diffs)\nout = dict(sequences=NSEQ, callbacks_per_sequence=NCB, callbacks=int(len(D)) , max_abs_bps=float(D.max()),\n           mean_abs_bps=float(D.mean()), share_above_0_01bps=float((D > 0.01).mean()),\n           count_above_0_01bps=int((D > 0.01).sum()), share_above_1e_6bps=float((D > 1e-6).mean()),\n           p99_bps=float(np.quantile(D, 0.99)), first_divergence=first_div, worst=worst[1],\n           seconds=time.time() - t0)\nF = np.array(fees); G = np.array(flags, dtype=float)\nout['coverage'] = dict(arb_share=float(G[:, 0].mean()), first_in_step_share=float(G[:, 1].mean()),\n                       first_after_gap_share=float(((G[:, 2] > 1) & (G[:, 1] > 0)).mean()),\n                       fee_bps_quantiles_bid_ask={str(q): [round(float(np.quantile(F[:, 0], q)), 3),\n                                                           round(float(np.quantile(F[:, 1], q)), 3)]\n                                                  for q in (0.05, 0.25, 0.5, 0.75, 0.95)},\n                       share_max_fee_gt_30bps=float((F.max(1) > 30).mean()),\n                       share_fee_at_1000bps_cap=float((F.max(1) >= 999.999).mean()),\n                       share_some_side_zero=float((F.min(1) == 0).mean()))\nprint(json.dumps(out, indent=1))\njson.dump(out, open('difftest_out.json', 'w'), indent=1)\n",
  "runtime_s": 73.66242218017578
 },
 "njit_compiles": true,
 "njit_notes": "strat_init and strat_after are @numba.njit (numba 0.68.1, nopython). They compile (first call ~4.2 s including helpers) and run inside an outer njit market loop. The .py_func versions run the same code as plain Python. A TH liveness check passes: raising BASE_FEE by 1 bp changes the returned fees.",
 "speed": {
  "njit_ns_per_callback_incl_toy_market": 398.3,
  "pure_python_us_per_callback": 30.21,
  "evm_pyrevm_us_per_callback": 109.19,
  "speedup_njit_vs_evm": 274.1,
  "first_call_compile_s": 4.15,
  "note": "One core of this machine. 2,000,000 njit callbacks in one jitted loop (the RNG and CPMM maths are counted in the time) against 20,000 EVM after_swap_wad calls through the repository adapter."
 },
 "deviations": [
  "WAD integers are float64 fractions: wmul(a,b)->a*b and wdiv(a,b)->a/b without the wei truncation. The relative error per op is about 1e-16 (float) against at most 1 wei of truncation, so the observed fee error is at most 4e-9 bps.",
  "_isqrt(v*WAD) (bit-length seed, 7 Newton steps, floor) becomes math.sqrt(v). Floor sqrt of a value near 1e28 to 1e32 is off by under 1 part in 1e14. That matters only if a later comparison sits within that margin, and none did.",
  "Integer divisions z/8 (in the posterior density) and count/silent (flow instant rate) are exact float divisions in the port, a difference of at most 1 wei.",
  "_band uses p = 1 wei when mu <= k*sd. The port uses 1e-18, the same value.",
  "Packed slots[2] (spot<<64 | timestamp) and slots[15] (rate | count<<80 | meanSize<<160) are unpacked into S[2],S[3] and S[16..18]. The port does not model overflow of the 80-bit fields. In the contract count would leak into the meanSize bits only above ~1.2e6 WAD (count resets every step and is capped by about 64 trades x 1.5 weight), and rate would only overflow above 2^80 wei, while rate is bounded by FLOW_INST_CAP=3. Neither can happen.",
  "Threshold comparisons (ret <= gate, spot >= pHat, c >= pHat, b >= a in _blend, fee > 30 bps, tr > SIGNAL_THRESHOLD, prob/mass floors) can in principle flip when a value sits within ~1e-15 relative of the threshold. No flip appeared in 440k callbacks.",
  "Solidity checked arithmetic would revert on underflow or division by zero. The port has no such reverts. No revert happened on the EVM in the test, and every subtraction in RS2 is guarded or provably non-negative for fees <= 0.1.",
  "The REVERT_U branch (REVERT_U=0) and the size-mode/missing-mode switches are kept in the port, gated by the TH values. slots[11] is read but never written by RS2, so S[12] is always 0.",
  "Slot writes follow the contract's order. slots[12] (first-trade direction), slots[13]/[14] (posterior) and slots[15] (flow) are written mid-function and the rest at the end, so a mid-call read sees what the contract sees."
 ],
 "notes": [
  "Setup followed the brief: amm-challenge at 6b6921f8d463314aa7c96234e1be25a25245f704, the amm_sim_rs wheel sha256 checked, py-solc-x 2.1.0, pyrevm 0.3.7, and `amm-match validate contracts/src/StarterStrategy.sol` passed. numba 0.68.1 was installed for the njit check. The whole checkout, venv and scratch files were kept under test/scratch/ (previous attempts were rejected for writing scratch/ in the repo root). Only result.json and sources.json are delivered.",
  "The CH calibration check (mean edge 525.5258821780834 on seeds 0..999) belongs to the goal-level setup. This port item did not run it, because the item compares callbacks and runs no match.",
  "The test market is a single-pool replica: no competing vanilla pool and no router split, so every retail order fills against RS2. RS2's fees in it are often high (median 36 bps, p95 ~290 bps, 0.2% of callbacks at the 1000 bps cap, 64% with one side at 0). That covers every clamp, the 30/36 bps cheap-side caps, the tail compression, the >30 bps interior-route branch and the gap/silence branches. It does not reproduce the real sim's fee distribution, so do not read any edge level from it.",
  "To use the port in a fast replica, call strat_init(S, TH_VALUES, x0, y0) once per simulation and strat_after after each trade, passing the post-trade reserves and the gross trade amounts (amount_x, amount_y as in cfmm.rs TradeInfo), with timestamp = step index starting at 0.",
  "Gas was not measured here; this item ports and does not change RS2."
 ]
}