{
  "blocked": null,
  "replica_source": "\"\"\"Scalar market replica of amm-challenge @6b6921f8.\nRequires numpy; numba is optional (plain Python fallback is slower).\nNo network, EVM, Solidity compiler or external files needed at runtime.\nrun_many returns rows [edge, retail_edge, arb_edge, retail_volume].\nPrice/retail RNG streams are independent; paths intentionally differ from Rust.\nUse the __main__ guard when invoking run_many from a script.\n\"\"\"\nimport math\nimport multiprocessing as mp\nimport numpy as np\ntry:\n    from numba import njit\nexcept ImportError:\n    def njit(*args, **kwargs):\n        def wrap(f): return f\n        return wrap\n\nTH_NAMES = ['ELAPSED_CAP', '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', 'DIR_IMPACT_MULT', 'GATE_SIGMA_MULT', 'MIN_GATE', 'TRADE_TOX_BOOST', 'STALE_ATTRACT_FRAC', 'RET_CAP', 'TOX_CAP', 'TRADE_RATIO_CAP', 'LAMBDA_CAP', 'STEP_COUNT_CAP', '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_SIGMA', 'INIT_LAMBDA', 'INIT_SIZE', 'MAX_FEE', 'FLAT_FEE']\nTH = np.array([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, 4.0, 7.2, 0.03, 0.35, 1.05, 0.02857142857142857, 0.2, 0.2, 1.82, 64.0, 0.0004, 0.2, 0.0012, 0.4842, 0.03, 1.5, 9.1843, 0.002, 0.01, 0.685, 0.05, 0.06, 0.93, 0.85, 0.00095, 0.8, 0.002, 0.1, -1.0], dtype=np.float64)\nELAPSED_CAP = 0\nSIGNAL_THRESHOLD = 1\nDIR_DECAY = 2\nACT_DECAY = 3\nSIZE_DECAY = 4\nTOX_DECAY = 5\nSIGMA_DECAY = 6\nLAMBDA_DECAY = 7\nSIZE_BLEND_DECAY = 8\nTOX_BLEND_DECAY = 9\nACT_BLEND_DECAY = 10\nPHAT_ALPHA = 11\nPHAT_ALPHA_RETAIL = 12\nDIR_IMPACT_MULT = 13\nGATE_SIGMA_MULT = 14\nMIN_GATE = 15\nTRADE_TOX_BOOST = 16\nSTALE_ATTRACT_FRAC = 17\nRET_CAP = 18\nTOX_CAP = 19\nTRADE_RATIO_CAP = 20\nLAMBDA_CAP = 21\nSTEP_COUNT_CAP = 22\nBASE_FEE = 23\nSIGMA_COEF = 24\nLAMBDA_COEF = 25\nFLOW_SIZE_COEF = 26\nTOX_COEF = 27\nTOX_QUAD_COEF = 28\nACT_COEF = 29\nDIR_COEF = 30\nDIR_TOX_COEF = 31\nSTALE_DIR_COEF = 32\nSIGMA_TOX_COEF = 33\nTAIL_KNEE = 34\nTAIL_SLOPE_PROTECT = 35\nTAIL_SLOPE_ATTRACT = 36\nINIT_SIGMA = 37\nINIT_LAMBDA = 38\nINIT_SIZE = 39\nMAX_FEE = 40\nFLAT_FEE = 41\n\n# STRATEGY BEGIN\n@njit(cache=True)\ndef strat_init(S, TH, x0, y0):\n    S[:] = 0.\n    if TH[FLAT_FEE] >= 0.:\n        S[0] = S[1] = min(TH[MAX_FEE], max(0., TH[FLAT_FEE]))\n        return S[0], S[1]\n    S[0] = S[1] = TH[BASE_FEE]\n    S[3] = 1.\n    S[5] = y0/x0 if x0 > 0. else 100.\n    S[6] = TH[INIT_SIGMA]\n    S[7] = TH[INIT_LAMBDA]\n    S[8] = TH[INIT_SIZE]\n    return S[0], S[1]\n\n@njit(cache=True)\ndef strat_after(S, TH, is_buy, amount_x, amount_y, timestamp, reserve_x, reserve_y):\n    if TH[FLAT_FEE] >= 0.:\n        return S[0], S[1]\n    prev_bid, prev_ask, last_ts = S[0], S[1], S[2]\n    direction, activity, phat = S[3], S[4], S[5]\n    sigma, lam, size = S[6], S[7], S[8]\n    tox_ema, count = S[9], S[10]\n    if timestamp > last_ts:\n        elapsed_raw = timestamp-last_ts\n        elapsed = min(elapsed_raw, TH[ELAPSED_CAP])\n        direction = 1.+(direction-1.)*TH[DIR_DECAY]**elapsed\n        activity *= TH[ACT_DECAY]**elapsed\n        size *= TH[SIZE_DECAY]**elapsed\n        tox_ema *= TH[TOX_DECAY]**elapsed\n        if count > 0. and elapsed_raw > 0.:\n            inst = min(count/elapsed_raw, TH[LAMBDA_CAP])\n            lam = lam*TH[LAMBDA_DECAY]+inst*(1.-TH[LAMBDA_DECAY])\n        count = 0.\n    first = count == 0.\n    spot = reserve_y/reserve_x if reserve_x > 0. else phat\n    if phat == 0.: phat = spot\n    gamma = max(0., 1.-(prev_bid if is_buy else prev_ask))\n    implied = spot if gamma == 0. else (spot*gamma if is_buy else spot/gamma)\n    ret = abs(implied-phat)/phat if phat > 0. else 0.\n    alpha = TH[PHAT_ALPHA] if first else TH[PHAT_ALPHA_RETAIL]\n    gate = max(TH[MIN_GATE], sigma*TH[GATE_SIGMA_MULT])\n    if ret <= gate: phat = phat*(1.-alpha)+implied*alpha\n    if first:\n        sigma = sigma*TH[SIGMA_DECAY]+min(ret,TH[RET_CAP])*(1.-TH[SIGMA_DECAY])\n    ratio = min(amount_y/reserve_y if reserve_y > 0. else 0.,TH[TRADE_RATIO_CAP])\n    if ratio > TH[SIGNAL_THRESHOLD]:\n        push = min(ratio*TH[DIR_IMPACT_MULT], .25)\n        direction = min(2.,direction+push) if is_buy else max(0.,direction-push)\n        activity = activity*TH[ACT_BLEND_DECAY]+ratio*(1.-TH[ACT_BLEND_DECAY])\n        size = min(1.,size*TH[SIZE_BLEND_DECAY]+ratio*(1.-TH[SIZE_BLEND_DECAY]))\n    tox = min(abs(spot-phat)/phat if phat > 0. else 0.,TH[TOX_CAP])\n    tox_ema = tox_ema*TH[TOX_BLEND_DECAY]+tox*(1.-TH[TOX_BLEND_DECAY])\n    count = min(count+1.,TH[STEP_COUNT_CAP])\n    mid = (TH[BASE_FEE]+TH[SIGMA_COEF]*sigma+TH[LAMBDA_COEF]*lam+\n           TH[FLOW_SIZE_COEF]*lam*size+TH[TOX_COEF]*tox_ema+\n           TH[TOX_QUAD_COEF]*tox_ema*tox_ema+TH[ACT_COEF]*activity+\n           TH[SIGMA_TOX_COEF]*sigma*tox_ema)\n    dev = abs(direction-1.)\n    sell_pressure = direction >= 1.\n    skew = TH[DIR_COEF]*dev+TH[DIR_TOX_COEF]*dev*tox_ema\n    if sell_pressure: bid, ask = mid+skew, max(0.,mid-skew)\n    else: bid, ask = max(0.,mid-skew), mid+skew\n    stale = TH[STALE_DIR_COEF]*tox_ema\n    attract = stale*TH[STALE_ATTRACT_FRAC]\n    if spot >= phat: bid, ask = bid+stale, max(0.,ask-attract)\n    else: ask, bid = ask+stale, max(0.,bid-attract)\n    aligned = (is_buy and spot >= phat) or (not is_buy and spot < phat)\n    if aligned:\n        boost = TH[TRADE_TOX_BOOST]*ratio\n        if is_buy: bid += boost\n        else: ask += boost\n    knee = TH[TAIL_KNEE]\n    bid_slope = TH[TAIL_SLOPE_PROTECT] if sell_pressure else TH[TAIL_SLOPE_ATTRACT]\n    ask_slope = TH[TAIL_SLOPE_ATTRACT] if sell_pressure else TH[TAIL_SLOPE_PROTECT]\n    if bid > knee: bid = knee+(bid-knee)*bid_slope\n    if ask > knee: ask = knee+(ask-knee)*ask_slope\n    bid = min(TH[MAX_FEE], max(0.,bid))\n    ask = min(TH[MAX_FEE], max(0.,ask))\n    S[0],S[1],S[2],S[3],S[4],S[5] = bid,ask,timestamp,direction,activity,phat\n    S[6],S[7],S[8],S[9],S[10] = sigma,lam,size,tox_ema,count\n    return bid,ask\n# STRATEGY END\n\n# Explicit independent streams so retail draws cannot move the price path.\n# xorshift64* with SplitMix64 seed expansion; Box-Muller normals; Knuth Poisson.\n# These have the Rust distributions, not Rust's Pcg64/Ziggurat bit sequences.\n@njit(cache=True)\ndef _seed(seed):\n    z = np.uint64(seed)+np.uint64(0x9e3779b97f4a7c15)\n    z = (z^(z>>np.uint64(30)))*np.uint64(0xbf58476d1ce4e5b9)\n    z = (z^(z>>np.uint64(27)))*np.uint64(0x94d049bb133111eb)\n    z = z^(z>>np.uint64(31))\n    return z if z != np.uint64(0) else np.uint64(1)\n\n@njit(cache=True)\ndef _uniform(state):\n    state ^= state>>np.uint64(12)\n    state ^= state<<np.uint64(25)\n    state ^= state>>np.uint64(27)\n    out = state*np.uint64(0x2545f4914f6cdd1d)\n    # Open interval avoids log(0); 52 bits also works in the Python fallback.\n    return state,(float(out>>np.uint64(12))+.5)/4503599627370496.\n\n@njit(cache=True)\ndef _normal(state):\n    state,u = _uniform(state)\n    state,v = _uniform(state)\n    return state,math.sqrt(-2.*math.log(u))*math.cos(2.*math.pi*v)\n\n@njit(cache=True)\ndef _poisson(state, rate):\n    limit = math.exp(-max(rate,.01))\n    prod = 1.\n    n = 0\n    while prod > limit:\n        state,u = _uniform(state)\n        prod *= u\n        n += 1\n    return state,n-1\n\n# pool rows: reserve_x, reserve_y, bid_fee, ask_fee.\n# Fees leave liquidity, so updating reserves uses only net input.\n@njit(cache=True)\ndef _execute(P, j, is_buy, amount, with_y, t, S, TH):\n    x,y = P[j,0],P[j,1]\n    fee = P[j,2] if is_buy else P[j,3]\n    gamma = min(1.,max(0.,1.-fee))\n    if amount <= 0. or gamma <= 0.: return 0.,0.,False\n    if is_buy:\n        ax = amount\n        net = ax*gamma\n        ny = x*y/(x+net)\n        ay = y-ny\n        if ay <= 0.: return 0.,0.,False\n        P[j,0],P[j,1] = x+(ax-ax*fee),y-ay\n    elif with_y:\n        ay = amount\n        net = ay*gamma\n        nx = x*y/(y+net)\n        ax = x-nx\n        if ax <= 0.: return 0.,0.,False\n        P[j,0],P[j,1] = x-ax,y+(ay-ay*fee)\n    else:\n        ax = amount\n        if ax >= x: return 0.,0.,False\n        ny = x*y/(x-ax)\n        net = ny-y\n        if net <= 0.: return 0.,0.,False\n        ay = net/gamma\n        fee_amount = ay-net\n        P[j,0],P[j,1] = x-ax,y+(ay-fee_amount)\n    if j == 0:\n        b,a = strat_after(S,TH,is_buy,ax,ay,t,P[j,0],P[j,1])\n        P[j,2],P[j,3] = min(.1,max(0.,b)),min(.1,max(0.,a))\n    return ax,ay,True\n\n@njit(cache=True)\ndef _arbitrage(P, j, price, t, S, TH):\n    x,y = P[j,0],P[j,1]\n    spot = y/x\n    if spot == price: return 0.\n    is_buy = spot > price\n    gamma = 1.-(P[j,2] if is_buy else P[j,3])\n    if gamma <= 0. or price <= 0.: return 0.\n    if is_buy:\n        amount = (math.sqrt(x*y*gamma/price)-x)/gamma\n        if amount <= 0.: return 0.\n        ay = y-x*y/(x+amount*gamma)\n        profit = ay-amount*price\n    else:\n        amount = min(x-math.sqrt(x*y/(gamma*price)),x*.99)\n        if amount <= 0.: return 0.\n        ay = (x*y/(x-amount)-y)/gamma\n        profit = amount*price-ay\n    if ay <= 0. or profit <= 0.: return 0.\n    ax,ay,ok = _execute(P,j,is_buy,amount,False,t,S,TH)\n    return -profit if ok else 0.\n\n@njit(cache=True)\ndef _route(P, trader_buy, size, price, t, S, TH):\n    gamma1 = 1.-P[0,3 if trader_buy else 2]\n    gamma2 = 1.-P[1,3 if trader_buy else 2]\n    a1 = math.sqrt(P[0,0]*gamma1*P[0,1])\n    a2 = math.sqrt(P[1,0]*gamma2*P[1,1])\n    total = size if trader_buy else size/price\n    if a2 == 0.: first = total\n    else:\n        r = a1/a2\n        den = gamma1+r*gamma2\n        coord = 1 if trader_buy else 0\n        first = total/2. if den == 0. else (r*(P[1,coord]+gamma2*total)-P[0,coord])/den\n        first = min(total,max(0.,first))\n    edge,volume = 0.,0.\n    for j in range(2):\n        amount = first if j == 0 else total-first\n        if amount > .0001:\n            ax,ay,ok = _execute(P,j,not trader_buy,amount,trader_buy,t,S,TH)\n            if j == 0 and ok:\n                edge = ay-ax*price if trader_buy else ax*price-ay\n                volume = ay\n    return edge,volume\n\n@njit(cache=True)\ndef run_market(TH, seed, mean_size, rate, sigma, n_steps):\n    S = np.zeros(40,dtype=np.float64)\n    bid,ask = strat_init(S,TH,100.,10000.)\n    P = np.empty((2,4),dtype=np.float64)\n    P[0,0],P[0,1],P[0,2],P[0,3] = 100.,10000.,min(.1,max(0.,bid)),min(.1,max(0.,ask))\n    P[1,0],P[1,1],P[1,2],P[1,3] = 100.,10000.,.003,.003\n    pstate,rstate = _seed(seed),_seed(seed+1)\n    price = 100.\n    retail_edge,arb_edge,volume = 0.,0.,0.\n    log_mu = math.log(max(mean_size,.01))-.5*1.2*1.2\n    # Rust generates the whole order batch before routing. Streaming here\n    # is equivalent: callbacks never read or change either market RNG.\n    for t in range(n_steps):\n        pstate,z = _normal(pstate)\n        price *= math.exp(-.5*sigma*sigma+sigma*z)\n        arb_edge += _arbitrage(P,0,price,t,S,TH)\n        _arbitrage(P,1,price,t,S,TH)\n        rstate,n = _poisson(rstate,rate)\n        for k in range(n):\n            rstate,z = _normal(rstate)\n            size = math.exp(log_mu+1.2*z)\n            rstate,u = _uniform(rstate)\n            e,v = _route(P,u < .5,size,price,t,S,TH)\n            retail_edge += e\n            volume += v\n    return retail_edge+arb_edge,retail_edge,arb_edge,volume\n\ndef market_config(seed):\n    \"\"\"Exact MatchRunner._build_configs draw order and default ranges.\"\"\"\n    r = np.random.default_rng(int(seed))\n    return float(r.uniform(19.,21.)),float(r.uniform(.6,1.)),float(r.uniform(.000882,.001008))\n\ndef _worker(task):\n    th,seed,n_steps = task\n    size,rate,sigma = market_config(seed)\n    return run_market(th,int(seed),size,rate,sigma,n_steps)\n\ndef run_many(TH, seeds, procs=8, n_steps=10000):\n    \"\"\"One strategy alone versus Vanilla per seed; input order is preserved.\n    Pass procs=1 to avoid multiprocessing; zero markets returns shape (0,4).\n    Strategy edits belong only between the markers; all constants are in TH.\n    \"\"\"\n    th = np.ascontiguousarray(TH,dtype=np.float64)\n    seeds = [int(s) for s in seeds]\n    if not seeds: return np.empty((0,4),dtype=np.float64)\n    jobs = ((th,s,int(n_steps)) for s in seeds)\n    if procs <= 1:\n        return np.asarray([_worker(j) for j in jobs],dtype=np.float64)\n    # Fork permits cached machine code inheritance on the specified Linux host.\n    # The context manager joins all workers before returning.\n    with mp.get_context('fork').Pool(int(procs)) as pool:\n        return np.asarray(pool.map(_worker,jobs,chunksize=max(1,len(seeds)//(procs*8))),dtype=np.float64)\n\nif __name__ == '__main__':\n    import argparse,json,time\n    p = argparse.ArgumentParser()\n    p.add_argument('--n',type=int,default=256)\n    p.add_argument('--seed',type=int,default=0)\n    p.add_argument('--procs',type=int,default=8)\n    a = p.parse_args()\n    run_market(TH,0,20.,.8,.00095,1)\n    start = time.perf_counter()\n    rows = run_many(TH,range(a.seed,a.seed+a.n),a.procs)\n    secs = time.perf_counter()-start\n    print(json.dumps({'n':a.n,'mean':float(rows[:,0].mean()),\n                     'se':float(rows[:,0].std(ddof=1)/math.sqrt(a.n)),\n                     'seconds':secs,'markets_per_second':a.n/secs}))\n",
  "replica_source_sha256": "1e4c44b4bffbdeed65872ee15d46dbde209bf5aa11014329d13d100507b4040c",
  "th_names": [
    "ELAPSED_CAP",
    "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",
    "DIR_IMPACT_MULT",
    "GATE_SIGMA_MULT",
    "MIN_GATE",
    "TRADE_TOX_BOOST",
    "STALE_ATTRACT_FRAC",
    "RET_CAP",
    "TOX_CAP",
    "TRADE_RATIO_CAP",
    "LAMBDA_CAP",
    "STEP_COUNT_CAP",
    "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_SIGMA",
    "INIT_LAMBDA",
    "INIT_SIZE",
    "MAX_FEE",
    "FLAT_FEE"
  ],
  "th": [
    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,
    4.0,
    7.2,
    0.03,
    0.35,
    1.05,
    0.02857142857142857,
    0.2,
    0.2,
    1.82,
    64.0,
    0.0004,
    0.2,
    0.0012,
    0.4842,
    0.03,
    1.5,
    9.1843,
    0.002,
    0.01,
    0.685,
    0.05,
    0.06,
    0.93,
    0.85,
    0.00095,
    0.8,
    0.002,
    0.1,
    -1.0
  ],
  "validation": {
    "CH": {
      "real": {
        "n": 1000,
        "mean": 525.5258821780834,
        "se": 2.7894264590251843
      },
      "replica": {
        "n": 1000,
        "mean": 526.6263740034892,
        "se": 2.877991350408383
      },
      "diff": 1.1004918254058111,
      "se": 4.007958854995302,
      "z": 0.27457662746068817,
      "seeds": [
        0,
        999
      ],
      "replica_components": {
        "edge": 526.6263740034889,
        "retail_edge": 555.6421440265326,
        "arb_edge": -29.01577002304332,
        "retail_volume": 76959.92387659108
      },
      "gas": {
        "max_ok": 151647,
        "oog": 0,
        "after_swap_calls": 10445223,
        "revert": 0,
        "other_halt": 0,
        "tx_error": 0,
        "bad_return": 0
      }
    },
    "flat": {
      "real": {
        "n": 256,
        "mean": 347.9224335871958,
        "se": 3.1392846735449833
      },
      "replica": {
        "n": 256,
        "mean": 348.27948443948867,
        "se": 3.1073931466583566
      },
      "diff": 0.3570508522928435,
      "se": 4.417125810915255,
      "z": 0.08083329920341581,
      "seeds": [
        0,
        255
      ],
      "replica_components": {
        "edge": 348.2794844394888,
        "retail_edge": 580.1714436617904,
        "arb_edge": -231.8919592223014,
        "retail_volume": 81000.29073355938
      },
      "gas": {
        "max_ok": 22592,
        "oog": 0,
        "after_swap_calls": 2971306,
        "revert": 0,
        "other_halt": 0,
        "tx_error": 0,
        "bad_return": 0
      }
    }
  },
  "transfer": {
    "base_plus_3bps": {
      "real": {
        "n": 128,
        "se": 0.07657846719616337,
        "delta": -0.8949458610045338
      },
      "replica": {
        "n": 4096,
        "se": 0.015113137802125498,
        "delta": -0.9585254169128314
      },
      "diff": -0.06357955590829767,
      "se": 0.07805554799205439,
      "z": -0.8145424322018687,
      "real_seeds": [
        706100,
        706227
      ],
      "replica_seeds": [
        706100,
        710195
      ],
      "gas": {
        "max_ok": 150994,
        "oog": 0,
        "after_swap_calls": 1252020,
        "revert": 0,
        "other_halt": 0,
        "tx_error": 0,
        "bad_return": 0
      }
    },
    "stale_x0.8": {
      "real": {
        "n": 128,
        "se": 0.18239242275149145,
        "delta": -6.764372082761492
      },
      "replica": {
        "n": 4096,
        "se": 0.034233800614338956,
        "delta": -6.851756075894003
      },
      "diff": -0.08738399313251133,
      "se": 0.18557733962329853,
      "z": -0.47087641901695093,
      "real_seeds": [
        706100,
        706227
      ],
      "replica_seeds": [
        706100,
        710195
      ],
      "gas": {
        "max_ok": 150994,
        "oog": 0,
        "after_swap_calls": 1433856,
        "revert": 0,
        "other_halt": 0,
        "tx_error": 0,
        "bad_return": 0
      }
    },
    "lambda_x1.5": {
      "real": {
        "n": 128,
        "se": 0.1358366480253364,
        "delta": -4.114213852795671
      },
      "replica": {
        "n": 4096,
        "se": 0.028400049828551124,
        "delta": -4.000539724171688
      },
      "diff": 0.11367412862398307,
      "se": 0.13877376472886838,
      "z": 0.8191327002339084,
      "real_seeds": [
        706100,
        706227
      ],
      "replica_seeds": [
        706100,
        710195
      ],
      "gas": {
        "max_ok": 150994,
        "oog": 0,
        "after_swap_calls": 1146222,
        "revert": 0,
        "other_halt": 0,
        "tx_error": 0,
        "bad_return": 0
      }
    }
  },
  "transfer_baseline": {
    "real": {
      "n": 128,
      "mean": 518.755129699123,
      "se": 7.859958876848004
    },
    "replica": {
      "n": 4096,
      "mean": 526.1059870109675,
      "se": 1.4162020278822736
    },
    "gas": {
      "max_ok": 150994,
      "oog": 0,
      "after_swap_calls": 1339223,
      "revert": 0,
      "other_halt": 0,
      "tx_error": 0,
      "bad_return": 0
    }
  },
  "speed": {
    "processes": 8,
    "n_markets": 4096,
    "n_steps_per_market": 10000,
    "seconds": 1.1007481620181352,
    "markets_per_second": 3721.1054638422524,
    "jit_compilation_included": false,
    "process_startup_and_config_generation_included": true,
    "seed_start": 810000,
    "seed_end": 814095
  },
  "checks": {
    "CH": {
      "callbacks": 5000,
      "max_abs_fee_error": 7.840950111415168e-16,
      "max_relative_k_error": 5.10702591327572e-15
    },
    "base_plus_3bps": {
      "callbacks": 5000,
      "max_abs_fee_error": 7.840950111415168e-16,
      "max_relative_k_error": 2.886579864025407e-15
    },
    "stale_x0.8": {
      "callbacks": 5000,
      "max_abs_fee_error": 8.465450562766819e-16,
      "max_relative_k_error": 4.6629367034256575e-15
    },
    "lambda_x1.5": {
      "callbacks": 5000,
      "max_abs_fee_error": 8.014422459012849e-16,
      "max_relative_k_error": 4.773959005888173e-15
    },
    "configs": {
      "n": 256,
      "exact": true
    },
    "parallel_and_edge_decomposition": {
      "n": 16,
      "exact_serial_parallel": true
    },
    "flat_analytic": {
      "equal_split": true,
      "arb_no_arb_band": true
    },
    "plain_python_numpy_fallback": {
      "n_steps": 64,
      "seed": 9923,
      "exact_match": true
    }
  },
  "deviations": [
    "Random paths are intentionally unmatched: Rust uses rand_pcg::Pcg64 with rand_distr sampling; the replica uses independently seeded xorshift64* streams, SplitMix64 seed expansion, Box-Muller normals and Knuth Poisson. Price seed=seed and retail seed=seed+1; marginal distributions and configuration draws are preserved.",
    "Strategy math uses float64, without Solidity integer truncation or the Rust TradeInfo float-to-WAD-to-float round trip. Direct CH/variant callback checks bound observed fee errors, not every possible threshold crossing.",
    "No EVM execution, gas accounting, overflow, revert or OOG fallback is simulated. The supplied CH/flat/variants have zero OOG, revert, other_halt, tx_error and bad_return in real runs; any future candidate still needs real gas validation.",
    "run_market implements the canonical initial reserves 100 X/10000 Y, price 100, mu=0, dt=1, retail size sigma=1.2 and buy probability=0.5, versus one flat 30bps Vanilla pool. Only its arguments are configurable.",
    "The replica streams each step's retail orders instead of materializing a vector first. This preserves outcomes because callbacks cannot alter the independent market RNG streams; arrival count is sampled before any retail order.",
    "Output edge is accumulated as separate retail and arbitrage sums then added, rather than one Rust sum interleaved across all trades; float summation can differ at roundoff scale."
  ],
  "notes": [
    "This item builds and validates a market replica; no strategy optimization or STACK comparison was performed.",
    "All reported metrics are local measurements using the requested pinned checkout and wheel (SHA256 aedb68280aca34c110968f00148387c95885207913fb2cf19a1ab4c5cfd6887a). CH real mean exactly equals the supplied reference 525.5258821780834.",
    "Every real market ran its submission alone against VanillaStrategy, via amm_sim_rs.run_batch(submission, Vanilla, configs, 8), in batches of 16 to bound result memory. Gas was reset with amm_sim_rs.gas_stats_reset() per strategy run, then read using gas_stats(). max_ok refers only to successful Submission afterSwap calls; oog counts all Submission callbacks.",
    "Mean-validation diff = replica mean - real mean. Each per-engine se is sample SD/sqrt(n), ddof=1; validation se = sqrt(real_se^2+replica_se^2), a two-sample comparison despite overlapping seed labels. The RNG paths differ.",
    "Transfer real/replica deltas are variant-minus-CH within each engine, using common random numbers within that engine. Transfer se = sqrt(real_paired_se^2+replica_paired_se^2); diff = replica delta - real delta. No transfer seed was used for tuning.",
    "The three variants are separate interventions: BASE_FEE 4 to 7 bps (including initialization), STALE_DIR_COEF 0.685 to 0.548, and LAMBDA_COEF 0.0012 to 0.0018.",
    "run_many returns a float64 (n,4) array ordered by input seeds: edge, retail_edge, arb_edge, retail_volume (gross Y amounts). market_config exactly matches MatchRunner._build_configs draw order: default_rng(seed), uniform size [19,21], rate [0.6,1.0], sigma [0.000882,0.001008].",
    "Save replica_source verbatim to replica.py. Import TH, TH_NAMES, run_market and run_many; copy TH before edits. The two jitted strategy functions are between the requested markers and use float64[40] state with scalar/unscaled WAD values. All CH named constants are in TH.",
    "Runtime dependencies are NumPy and optionally Numba, installed by the requested setup. If Numba is unavailable the same code runs as plain Python/NumPy. It requires no Rust binary, Solidity compiler, checkout data, or network at market runtime. The 64-step NUMBA_DISABLE_JIT fallback check exactly matched the jitted four outputs.",
    "The standalone benchmark excludes JIT compilation but includes configuration generation and creating/joining eight worker processes. It was measured after real validation ended; earlier replica batches ran concurrently and measured lower throughput.",
    "The direct callback checks use 5000 deterministic synthetic valid reserve updates for CH and each variant, exercising repeated timestamps, elapsed=1/2/8/13, both directions, and large trades. Configuration equality checked seeds 0..255; serial/eight-process determinism and edge decomposition checked 16 full markets; flat equal splitting and no-arbitrage bands checked analytically.",
    "Primary pinned sources and exact remotely rechecked quotes are in sources.json. Reproduction source below embeds CH and recomputes the requested market statistics; callback_check_source separately reproduces the direct Solidity and analytic checks. Both use the requested setup environment."
  ],
  "reproduction_source": "CH_SOURCE = '// 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 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[2] = 0; slots[3] = WAD; slots[4] = 0;\\n        slots[5] = initialX > 0 ? wdiv(initialY, initialX) : 100 * WAD;\\n        slots[6] = 950000000000000; slots[7] = 800000000000000000; slots[8] = 2000000000000000;\\n        slots[9] = 0; slots[10] = 0;\\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 = 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        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            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        {\\n            uint256 ret = pHat > 0 ? wdiv(absDiff(pImplied, pHat), pHat) : 0;\\n            uint256 alpha = firstInStep ? PHAT_ALPHA : PHAT_ALPHA_RETAIL;\\n            uint256 adaptiveGate = wmul(sigmaHat, GATE_SIGMA_MULT);\\n            if (adaptiveGate < MIN_GATE) adaptiveGate = MIN_GATE;\\n            if (ret <= adaptiveGate) { pHat = wmul(pHat, WAD - alpha) + wmul(pImplied, alpha); }\\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        uint256 tradeRatio = trade.reserveY > 0 ? wdiv(trade.amountY, trade.reserveY) : 0;\\n        if (tradeRatio > TRADE_RATIO_CAP) tradeRatio = TRADE_RATIO_CAP;\\n\\n        if (tradeRatio > SIGNAL_THRESHOLD) {\\n            uint256 push = tradeRatio * DIR_IMPACT_MULT;\\n            if (push > WAD / 4) push = WAD / 4;\\n            if (trade.isBuy) {\\n                dirState = dirState + push;\\n                if (dirState > 2 * WAD) dirState = 2 * WAD;\\n            } else {\\n                dirState = dirState > push ? dirState - push : 0;\\n            }\\n            actEma = wmul(actEma, ACT_BLEND_DECAY) + wmul(tradeRatio, WAD - ACT_BLEND_DECAY);\\n            sizeHat = wmul(sizeHat, SIZE_BLEND_DECAY) + wmul(tradeRatio, WAD - SIZE_BLEND_DECAY);\\n            if (sizeHat > WAD) sizeHat = WAD;\\n        }\\n\\n        uint256 tox = pHat > 0 ? wdiv(absDiff(spot, pHat), pHat) : 0;\\n        if (tox > TOX_CAP) tox = TOX_CAP;\\n        toxEma = wmul(toxEma, TOX_BLEND_DECAY) + wmul(tox, WAD - TOX_BLEND_DECAY);\\n        uint256 toxSignal = toxEma;\\n\\n        stepTradeCount = stepTradeCount + 1;\\n        if (stepTradeCount > STEP_COUNT_CAP) stepTradeCount = STEP_COUNT_CAP;\\n\\n        uint256 flowSize = wmul(lambdaHat, sizeHat);\\n        uint256 fBase = BASE_FEE + wmul(SIGMA_COEF, sigmaHat) + wmul(LAMBDA_COEF, lambdaHat) + wmul(FLOW_SIZE_COEF, flowSize);\\n        uint256 fMid = fBase + wmul(TOX_COEF, toxSignal) + wmul(TOX_QUAD_COEF, wmul(toxSignal, toxSignal)) + wmul(ACT_COEF, actEma);\\n        fMid = fMid + wmul(SIGMA_TOX_COEF, wmul(sigmaHat, toxSignal));\\n\\n        uint256 dirDev; bool sellPressure;\\n        if (dirState >= WAD) { dirDev = dirState - WAD; sellPressure = true; }\\n        else { dirDev = WAD - dirState; sellPressure = false; }\\n\\n        uint256 skew = wmul(DIR_COEF, dirDev) + wmul(DIR_TOX_COEF, wmul(dirDev, toxSignal));\\n        uint256 bidFee; uint256 askFee;\\n        if (sellPressure) {\\n            bidFee = fMid + skew;\\n            askFee = fMid > skew ? fMid - skew : 0;\\n        } else {\\n            askFee = fMid + skew;\\n            bidFee = fMid > skew ? fMid - skew : 0;\\n        }\\n\\n        {\\n            uint256 staleShift = wmul(STALE_DIR_COEF, toxSignal);\\n            uint256 attractShift = wmul(staleShift, STALE_ATTRACT_FRAC);\\n            if (spot >= pHat) {\\n                bidFee = bidFee + staleShift;\\n                askFee = askFee > attractShift ? askFee - attractShift : 0;\\n            } else {\\n                askFee = askFee + staleShift;\\n                bidFee = bidFee > attractShift ? bidFee - attractShift : 0;\\n            }\\n        }\\n\\n        {\\n            bool tradeAligned = (trade.isBuy && spot >= pHat) || (!trade.isBuy && spot < pHat);\\n            if (tradeAligned) {\\n                uint256 tradeBoost = wmul(TRADE_TOX_BOOST, tradeRatio);\\n                if (trade.isBuy) { bidFee = bidFee + tradeBoost; }\\n                else { askFee = askFee + tradeBoost; }\\n            }\\n        }\\n\\n        if (sellPressure) {\\n            bidFee = clampFee(_compressTailWithSlope(bidFee, TAIL_SLOPE_PROTECT));\\n            askFee = clampFee(_compressTailWithSlope(askFee, TAIL_SLOPE_ATTRACT));\\n        } else {\\n            askFee = clampFee(_compressTailWithSlope(askFee, TAIL_SLOPE_PROTECT));\\n            bidFee = clampFee(_compressTailWithSlope(bidFee, TAIL_SLOPE_ATTRACT));\\n        }\\n\\n        slots[0] = bidFee; slots[1] = askFee; slots[2] = 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    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    function getName() external pure override returns (string memory) { return \"no_cubic\"; }\\n}\\n'\n\n\"\"\"Run from the pinned checkout after the requested setup, with replica.py saved\nfrom result.json['replica_source']. This script needs no network once setup and\nsource extraction are complete. Outputs fresh measurements, not fixed numbers.\nGas stats require the task-specified instrumented wheel.\n\"\"\"\nimport json,math,time\nimport numpy as np\nimport amm_sim_rs\nimport replica as r\nfrom amm_competition.evm.compiler import SolidityCompiler\nfrom amm_competition.evm.baseline import get_vanilla_bytecode_and_abi\n\n# CH_SOURCE is prepended as a literal by the artifact generator.\ndef configs(seeds):\n    out=[]\n    for seed in seeds:\n        size,rate,sigma=r.market_config(seed)\n        out.append(amm_sim_rs.SimulationConfig(10000,100.,100.,10000.,\n                   0.,sigma,1.,rate,size,1.2,.5,int(seed)))\n    return out\n\ndef stats(x):\n    x=np.asarray(x,dtype=float)\n    return {'n':len(x),'mean':float(x.mean()),\n            'se':float(x.std(ddof=1)/math.sqrt(len(x)))}\n\ndef gas_summary(gas):\n    rows=[x for x in gas if x['role']=='Submission']\n    swap=[x for x in rows if x['callback']=='afterSwap'][0]\n    return {'max_ok':swap['max_ok_gas'],'oog':sum(x['oog'] for x in rows),\n            'after_swap_calls':swap['calls'],\n            'revert':sum(x['revert'] for x in rows),\n            'other_halt':sum(x['other_halt'] for x in rows),\n            'tx_error':sum(x['tx_error'] for x in rows),\n            'bad_return':sum(x['bad_return'] for x in rows)}\n\ndef run_real(bc,vanilla,seeds):\n    amm_sim_rs.gas_stats_reset()\n    values=[]\n    # Small batches bound retained per-step result memory.\n    for i in range(0,len(seeds),16):\n        batch=amm_sim_rs.run_batch(list(bc),list(vanilla),configs(seeds[i:i+16]),8)\n        values.extend((int(x.seed),float(x.edges['submission'])) for x in batch.results)\n    by_seed=dict(values)\n    return np.array([by_seed[s] for s in seeds]),gas_summary(amm_sim_rs.gas_stats())\n\ndef run_all():\n    compiler=SolidityCompiler()\n    vanilla=get_vanilla_bytecode_and_abi()[0]\n    sources={'CH':CH_SOURCE,\n      'base_plus_3bps':CH_SOURCE.replace('BASE_FEE = 4 * BPS','BASE_FEE = 7 * BPS'),\n      'stale_x0.8':CH_SOURCE.replace('STALE_DIR_COEF = 6850 * BPS','STALE_DIR_COEF = 5480 * BPS'),\n      'lambda_x1.5':CH_SOURCE.replace('LAMBDA_COEF = 12 * BPS','LAMBDA_COEF = 18 * BPS')}\n    bytecodes={'flat':vanilla}\n    for name,source in sources.items():\n        compiled=compiler.compile(source)\n        assert compiled.success,compiled.errors\n        bytecodes[name]=compiled.bytecode\n    r.run_market(r.TH,0,20.,.8,.00095,1)\n    output={'validation':{},'transfer':{},'gas':{}}\n    for name,n in [('CH',1000),('flat',256)]:\n        seeds=list(range(n))\n        real,gas=run_real(bytecodes[name],vanilla,seeds)\n        th=r.TH.copy()\n        if name=='flat': th[r.FLAT_FEE]=.003\n        replica=r.run_many(th,seeds,8)[:,0]\n        rs,ps=stats(real),stats(replica)\n        output['validation'][name]={'real':rs,'replica':ps,\n            'diff':ps['mean']-rs['mean'],'se':math.hypot(rs['se'],ps['se'])}\n        output['gas'][name]=gas\n    real_seeds=list(range(706100,706228))\n    replica_seeds=list(range(706100,710196))\n    real_base,gas=run_real(bytecodes['CH'],vanilla,real_seeds)\n    output['gas']['CH_transfer']=gas\n    replica_base=r.run_many(r.TH,replica_seeds,8)[:,0]\n    for name,idx,value in [('base_plus_3bps',r.BASE_FEE,.0007),\n                           ('stale_x0.8',r.STALE_DIR_COEF,.548),\n                           ('lambda_x1.5',r.LAMBDA_COEF,.0018)]:\n        real,gas=run_real(bytecodes[name],vanilla,real_seeds)\n        th=r.TH.copy(); th[idx]=value\n        replica=r.run_many(th,replica_seeds,8)[:,0]\n        rs,ps=stats(real-real_base),stats(replica-replica_base)\n        output['transfer'][name]={'real':rs,'replica':ps,\n            'diff':ps['mean']-rs['mean'],'se':math.hypot(rs['se'],ps['se'])}\n        output['gas'][name]=gas\n    start=time.perf_counter()\n    r.run_many(r.TH,range(810000,814096),8)\n    secs=time.perf_counter()-start\n    output['speed']={'processes':8,'n_markets':4096,'seconds':secs,\n                     'markets_per_second':4096/secs}\n    assert output['validation']['CH']['real']['mean']==525.5258821780834\n    assert all(g['oog']==0 for g in output['gas'].values())\n    return output\n\nif __name__=='__main__':\n    print(json.dumps(run_all(),indent=2))\n",
  "callback_check_source": "import json, pathlib, math\nfrom decimal import Decimal\nimport numpy as np\nimport replica as r\nfrom amm_competition.evm.compiler import SolidityCompiler\nfrom amm_competition.evm.executor import EVMStrategyExecutor\nfrom amm_competition.core.trade import TradeInfo\nfrom amm_competition.competition.match import MatchRunner\nfrom amm_competition.competition.config import BASELINE_VARIANCE,build_base_config\nfrom reproduce import CH_SOURCE\nsrc=CH_SOURCE\nvariants=[('CH',r.TH.copy(),src)]\nfor name,idx,value,old,new in [\n('base_plus_3bps',r.BASE_FEE,.0007,'BASE_FEE = 4 * BPS','BASE_FEE = 7 * BPS'),\n('stale_x0.8',r.STALE_DIR_COEF,.548,'STALE_DIR_COEF = 6850 * BPS','STALE_DIR_COEF = 5480 * BPS'),\n('lambda_x1.5',r.LAMBDA_COEF,.0018,'LAMBDA_COEF = 12 * BPS','LAMBDA_COEF = 18 * BPS')]:\n th=r.TH.copy(); th[idx]=value\n variants.append((name,th,src.replace(old,new)))\nchecks={}\ncompiler=SolidityCompiler()\nfor name,th,source in variants:\n c=compiler.compile(source); assert c.success,c.errors\n evm=EVMStrategyExecutor(c.bytecode,c.abi)\n init=evm.after_initialize(Decimal(100),Decimal(10000)); assert init.success\n S=np.zeros(40); b,a=r.strat_init(S,th,100.,10000.)\n assert abs(float(init.bid_fee)-b)<1e-16 and abs(float(init.ask_fee)-a)<1e-16\n P=np.array([[100.,10000.,b,a],[100.,10000.,.003,.003]])\n rng=np.random.default_rng(440103)\n t=0; max_err=0.; max_k_error=0.\n for i in range(5000):\n  # Explicit elapsed=0,1,8,>8 and very large ratio events.\n  t += int(rng.choice([0,0,0,1,1,2,8,13]))\n  buy=bool(rng.random()<.5)\n  amount=float(rng.lognormal(-2,1.5))\n  amount=min(amount,P[0,0]*.15)\n  ax,ay,ok=r._execute(P,0,buy,amount,False,t,S,th)\n  assert ok\n  tr=TradeInfo('buy' if buy else 'sell',Decimal(str(ax)),Decimal(str(ay)),t,Decimal(str(P[0,0])),Decimal(str(P[0,1])))\n  out=evm.after_swap_fast(tr)\n  err=max(abs(out[0]/1e18-P[0,2]),abs(out[1]/1e18-P[0,3]))\n  max_err=max(max_err,err)\n  max_k_error=max(max_k_error,abs(P[0,0]*P[0,1]/1e6-1.))\n assert max_err<1e-12,(name,max_err)\n checks[name]={'callbacks':5000,'max_abs_fee_error':max_err,'max_relative_k_error':max_k_error}\n# Compare exact canonical config generation, independent of replica paths.\nrunner=MatchRunner(n_simulations=256,config=build_base_config(seed=0),n_workers=8,variance=BASELINE_VARIANCE)\nfor cfg in runner._build_configs():\n assert r.market_config(cfg.seed)==(cfg.retail_mean_size,cfg.retail_arrival_rate,cfg.gbm_sigma)\nchecks['configs']={'n':256,'exact':True}\nserial=r.run_many(r.TH,range(16),1)\nparallel=r.run_many(r.TH,range(16),8)\nassert np.array_equal(serial,parallel)\nassert np.allclose(serial[:,0],serial[:,1]+serial[:,2],rtol=0,atol=1e-12)\nchecks['parallel_and_edge_decomposition']={'n':16,'exact_serial_parallel':True}\n# Analytic split and arb marginal band checks on a fee-constant pool.\nth=r.TH.copy(); th[r.FLAT_FEE]=.003\nS=np.zeros(40); r.strat_init(S,th,100,10000)\nP=np.array([[100.,10000.,.003,.003],[100.,10000.,.003,.003]])\ne,v=r._route(P,True,20.,100.,0,S,th)\nassert math.isclose(v,10.,rel_tol=0,abs_tol=1e-12)\nassert np.allclose(P[0],P[1],rtol=1e-14,atol=1e-12)\nfor price in [101.,99.]:\n P=np.array([[100.,10000.,.003,.003],[100.,10000.,.003,.003]])\n edge=r._arbitrage(P,0,price,1,S,th); assert edge<0.\n spot=P[0,1]/P[0,0]\n assert price*.997-1e-10 <= spot <= price/.997+1e-10\nchecks['flat_analytic']={'equal_split':True,'arb_no_arb_band':True}\n\nprint(json.dumps(checks,indent=2))\n"
}
