{"item":"a","batch":"e04-size-tail-design","kind":"static design (source analysis); no market simulation, no confirmation seeds","blocked":null,"paired":{"n":0,"mean_diff":null,"se":null,"worst":null},"gas":null,"retail_edge_delta":null,"arb_edge_delta":null,"code":null,"sha256":null,"summary":"Distribution-aware retail pricing (DAR). Both pools always have k=1e6 (fees go to separate buckets), so the exact clipped router depends only on our spot s1, the normalizer spot s2 (hidden) and the fees. Per arriving order, our leg is Y1=clamp(a+bT,0,T): orders below a size threshold go all-or-nothing, and the tail is split at the constant ratio b~1/2. Taking the expectation over the full lognormal size distribution (sigma 1.2) gives three static facts, all on synthetic declared states: (1) per-order edge is 1.5-3.6x the edge at mean size (a Jensen effect from slippage convexity, E[T^2]/M^2=e^1.44=4.22); (2) a one-step charge for future arb cost removes 31-48% of that edge, because the arb buys back most of the slippage; (3) the fee that maximizes edge minus arb charge acts as a QUOTE TARGET. On the side that pulls our spot back toward p, the quote sits at about p*exp(+/-41..43 bps), i.e. 11-13 bps outside the normalizer's 30 bp quote, and the fee moves one bp per bp of spot deviation (slope 1.0; V10's stale lean has slope ~0.69-0.72). On the side that pushes spot away, the fee hits a convex floor of 17-30 bps set by the arb charge, where the uncharged (kappa=0) optimum keeps falling 1:1 to 21, 11 and 1 bps at u=20, 30 and 40 bps, and the mean-size optimizer gives 0. The policy family is a residual on V10: f=f_V10+eta*clip(f_DAR(u_hat,side,f_other)-f_V10,+-Dmax), with f_DAR read from an offline-generated table keyed by u_hat=ln(spot/p_hat) in bps. It does not reduce to the failed share optimizer (its chosen fees differ by 2-24 bps across 12 state/side cells, and by only 2 bps in one cell; see collapse_test). Expected board effect: unknown; nothing here is a simulation gain.","cited_sources":[{"path":"amm_sim_rs/src/market/router.rs","lines":"35-75 (buy split, clamp line 71), 77-117 (sell split), 188 (MIN_AMOUNT), 194-245 (two-AMM routing, sell input total_x=size/fair_price line 221, ours executed first)","url":"https://raw.githubusercontent.com/benedictbrady/amm-challenge/6b6921f8d463314aa7c96234e1be25a25245f704/amm_sim_rs/src/market/router.rs"},{"path":"amm_sim_rs/src/market/retail.rs","lines":"56-60 (Poisson, LogNormal mu=ln(mean)-sigma^2/2), 75-99 (per-step orders, size then side)","url":"https://raw.githubusercontent.com/benedictbrady/amm-challenge/6b6921f8d463314aa7c96234e1be25a25245f704/amm_sim_rs/src/market/retail.rs"},{"path":"amm_sim_rs/src/market/arbitrageur.rs","lines":"35-48 (direction), 54-98 (buy-X arb, 99% cap line 73), 104-146 (sell-X arb)","url":"https://raw.githubusercontent.com/benedictbrady/amm-challenge/6b6921f8d463314aa7c96234e1be25a25245f704/amm_sim_rs/src/market/arbitrageur.rs"},{"path":"amm_sim_rs/src/amm/cfmm.rs","lines":"119-169 (quotes, fee on input), 199-290 (execution: fees to separate bucket, reserves keep k), 293-298 (afterSwap fee update; error keeps fees)","url":"https://raw.githubusercontent.com/benedictbrady/amm-challenge/6b6921f8d463314aa7c96234e1be25a25245f704/amm_sim_rs/src/amm/cfmm.rs"},{"path":"amm_sim_rs/src/simulation/engine.rs","lines":"136-162 (price step, one arb per pool, retail routing, edge = -arb profit + retail trade edge at contemporaneous fair price)","url":"https://raw.githubusercontent.com/benedictbrady/amm-challenge/6b6921f8d463314aa7c96234e1be25a25245f704/amm_sim_rs/src/simulation/engine.rs"},{"path":"amm_competition/competition/config.py","lines":"25-48 (initial_x=100, initial_y=10000, retail_size_sigma=1.2, mean size U(19,21), rate U(0.6,1.0), sigma U(0.000882,0.001008))","url":"https://raw.githubusercontent.com/benedictbrady/amm-challenge/6b6921f8d463314aa7c96234e1be25a25245f704/amm_competition/competition/config.py"},{"path":"contracts/src/VanillaStrategy.sol","lines":"12 (FEE = 30 bps)","url":"https://raw.githubusercontent.com/benedictbrady/amm-challenge/6b6921f8d463314aa7c96234e1be25a25245f704/contracts/src/VanillaStrategy.sol"},{"path":"V10 Strategy.sol (artifact code field)","lines":"Strategy lines 42 (STALE_DIR_COEF), 198-211 (stale lean on spot vs staleHat=0.7 pHat+0.3 fastHat), 139-144 and 271-283 (interior retail route reveals normalizer spot), 147-153 (posterior fastHat, uncertainty in slots 13-14), 231-237 (30/36 bp caps), 239-242 (slot layout 0-14)","url":"https://api.imdnotdead.fun/artifacts/33f54e81f3372088e9eced52c0174f310ac348af98ef5727b73785c088679194"},{"path":"V10 artifact measured fields (data, not re-measured)","lines":"paired n=2000 mean_diff 0.1372 se 0.0136 vs STACK; gas max_ok 194870, oog 0; retail delta -1.136, arb delta +1.273","url":"https://api.imdnotdead.fun/artifacts/33f54e81f3372088e9eced52c0174f310ac348af98ef5727b73785c088679194"},{"path":"rules artifact","lines":"retail_split, arb_rule, fee_semantics, retail_size sections","url":"https://api.imdnotdead.fun/artifacts/ddbbaac58282566e0505d895c83daf348487cc322e8c482e61d4d87e6e4628de"}],"assumptions":["A1 k1=k2=K=1e6 for the entire run: initial 100x10000 and fees accumulate outside reserves (cfmm.rs 206-210, 237-241, 268-272). So y_i=sqrt(K s_i), x_i=sqrt(K/s_i), and router r=sqrt(g1/g2).","A2 Normalizer fee fixed at 30 bps (VanillaStrategy.sol 12); g2=0.997.","A3 Size T~LogNormal(ln M - s^2/2, s), s=1.2, M~U(19,21) per seed (unobserved; DAR uses M=20). Buy orders spend T in Y; sell orders give T/p X (router.rs 221) and are clipped at 1e-4 per leg.","A4 One-step horizon for the arb charge: the next step's GBM move has sd sp=9.4e-4 (midpoint of the sigma range), and the fees used are the current (fb,fa). Later retail, later fee changes and multi-step drift are ignored.","A5 Fair price is unobserved. p_hat=V10 fastHat (slots[14]), with relative variance v=slots[13]. The synthetic tables set p=p_hat; a psd=10 bp perturbation left the argmax unchanged (exp2, closed form). Argmax tables are on a 1-2 bp fee grid over 0-100 bps.","A6 Prior on w2=ln(s2/p): mass pe on band-edge atoms +-delta2 (delta2=-ln 0.997=30.05 bps), split equally, and 1-pe uniform on (-delta2,delta2). Tables use pe=0.5, with sensitivity at pe 0 and 1. This is a modelling choice: calibrate offline from simulator traces.","A7 Retail orders inside one step are routed in sequence with updated reserves and fees (router.rs 276-279). DAR prices one marginal order at a time; the order-count weight nu cancels in the per-side argmax."],"equations":{"units":"Prices are Y per X. Fees are fractions (1 bp=1e-4; WAD 1e14 per bp on chain). Edge is in Y. u=ln(s1/p), w2=ln(s2/p).","router_buy":"a=(r*y2-y1)/(g1+r*g2), b=r*g2/(g1+r*g2), r=sqrt(g1/g2), g1=1-askFee. Y1(T)=clamp(a+b*T,0,T); a leg is executed only if it is >1e-4.","router_sell":"Same with x_i in place of y_i, g1=1-bidFee, T_x=S/p: X1=clamp(a'+b'*T_x,0,T_x).","thresholds":"a<0: Y1=0 for T<t0=-a/b (fully censored small orders). a>0: Y1=T for T<t1=a/(1-b) (we take the whole small order). For T>>|a|, Y1/T->b, which does not depend on s1 or s2.","lognormal_partial_moments":"S_n(t)=E[T^n 1{T>t}]=exp(n*mu+n^2 s^2/2)*Phi((mu+n s^2-ln t)/s); L_n=M_n-S_n. For a<0: E[Y1]=a S0(t0)+b S1(t0), E[Y1^2]=a^2 S0+2ab S1+b^2 S2 (at t0). For a>0: E[Y1]=L1(t1)+a S0(t1)+b S1(t1) (analogous for the square).","flow_gradient":"For a<0, dE[Y1]/da=P(T>t0), a smooth survival probability. The mean-size rule instead has dY1(M)/da = 1{M>t0} (a step), so it sees no gradient when M<t0 even though 72.6% of Y volume comes from orders above M.","edge_buy_leg":"e_a(Y)=Y - p*x1*g1*Y/(y1+g1*Y) ~= Y(1-g1 p/s1) + (p/s1) g1^2 Y^2/y1. Post-trade s1'=(y1+g1 Y)^2/K.","edge_sell_leg":"e_b(X)=p X - y1*g1*X/(x1+g1 X); s1'=K/(x1+g1 X)^2.","arb_profit_exact":"Sell-X arb (s>p/gb): sqrt(K)*(sqrt(s)-sqrt(p/gb))^2/sqrt(s). Buy-X arb (s<ga*p): sqrt(K)*(sqrt(s/ga)-sqrt(p))^2/sqrt(s). This is the same as arbitrageur.rs when the 99% cap does not bind (check C5).","arb_charge_hinge":"C(u)=(y1/4)*[((u-db)_+)^2+sp^2*1{u>db} + ((-u-da)_+)^2+sp^2*1{-u>da}], with db=-ln(1-bidFee), da=-ln(1-askFee). This is the small-u expansion of the exact profit, evaluated at the post-retail spot.","objective":"J_side(f)=E_{w2~prior}E_{T~LN}[ e(leg(T;f)) - kappa*(C(u'(leg))-C(u0)) ], per arriving order of that side, in Y. f_DAR(side)=argmax_f J_side(f) over [0,100] bps.","policy":"f_side = clampFee( f_V10 + eta*clip(f_DAR(u_hat,side,f_other_V10)-f_V10, -Dmax, +Dmax) ), with u_hat=ln(spot/p_hat). eta=0 gives V10 exactly."},"observable_state_and_update_order":["Observable in afterSwap: isBuy, amountX, amountY, timestamp, reserveX, reserveY (post-trade, excluding fees). From these: spot, K (=reserveX*reserveY, which checks A1), own fees (slots 0-1).","Order: (1) V10 runs unchanged and produces pHat, fastHat, uncertainty and (bid0,ask0). (2) u_hat=ln(spot/p_ref), with p_ref=fastHat (or the V10 staleHat blend; this is an ablation). (3) Look up f_DAR for both sides by bilinear interpolation over (u_hat bucket, f_other bucket). (4) Apply the residual with eta and Dmax. (5) Apply V10's existing 30/36 bp caps unchanged, or drop them in ablation D3. (6) Store nothing new for A1-T. A1-Q stores no extra state either.","The fee returned after the first trade of a step (usually the arb) prices that step's retail and also the next step's arb if no trade follows. The kappa term prices only retail-induced displacement; the arb-band effect of the fee itself is left to V10 (rho=0) or added in ablation D5."],"hidden_variables_offline_only":["p (fair price)","s2 / w2 (normalizer spot)","M (per-seed retail mean size)","sp (per-seed gbm sigma)","lambda (arrival rate)","Used only to build the tables and to calibrate the prior pe and the kappa-validation from simulator traces on tuning seeds. None of them is read on chain."],"structural_alternatives":[{"id":"A0","name":"V10 identity","rule":"eta=0; returns V10 fees bit-for-bit.","role":"control; must reproduce the V10 sha behaviour exactly"},{"id":"A1-T","name":"Tabulated DAR quote targeting (primary)","rule":"f_DAR from an offline table J_q argmax[u_hat in -60..60 bps step 5][f_other in 0..80 step 10][side], kappa in {0.5,1}, pe in {0.25,0.5,0.75}; residual applied with eta, Dmax.","why_distinct":"Anchors the QUOTE to p_hat with slope 1 on the restoring side and an arb-charged convex floor on the away side. V10's lean has slope ~0.69-0.72 on stale deviation, with no floor kink."},{"id":"A1-Q","name":"Online DAR quadrature","rule":"At each afterSwap, evaluate J_q on 3 candidates {f0-d, f0, f0+d} per side with 5 lognormal nodes x 3 w2 nodes, and move to the best candidate.","why_distinct":"Same model, no table. Can use the live f_other and p uncertainty. Costs more gas."},{"id":"A2","name":"Censoring-threshold quantile targeting","rule":"Choose f so that the routing threshold t0(f) (a<0 regime) sits at lognormal quantile q in [0.3,0.8] at w2=0: solve a(f)+b(f)*Q_LN(q)=0. Closed form in sqrt(g1), no table.","why_distinct":"One-parameter shape family that targets which order sizes we serve. It approximates A1 when kappa=0."},{"id":"A3","name":"Mean-size share optimizer (known-failed family; negative control)","rule":"argmax f*Y1(M)","role":"collapse test: A1 must differ from it in reachable states"},{"id":"A4","name":"Closed-form DAR with Taylor arb charge (rejected statically)","rule":"moments E[Y1],E[Y1^2] plus a quadratic Taylor expansion of C in Y1","reason_rejected":"With kappa=0 it matches exact quadrature within 1.4%. With kappa=1 at the interior state it gives J=0.0739 against exact 0.0479, because tail orders cross the band edge and the local Taylor expansion misses this (exp2). The tail must be integrated with nodes."}],"static_results_synthetic":{"label":"STATIC calculations on synthetic declared latent states (p=100, K=1e6, M=20, s=1.2). These are not simulation gains.","states":"post_sellX_arb: s1=p/(1-fb0) (band edge after the arb sold X to us). post_buyX_arb: s1=p(1-fa0). interior: s1=p. Fee pairs: sym30=(30,30) bps; leanBid45Ask20=(45,20) bps.","jensen_ratio_E_LN_edge_over_edge_at_mean_size":"1.52-3.56 across 36 state/side/pe cells (exp.py). Largest (3.56) on the away side at the band edge with the lean fee pair, where the mean-size order is almost fully censored. Interior sym30 at pe=0.5: 1.68.","arb_charge_share_of_edge":"J_k1/J_k0 = 0.52-0.69 (one-step charge with kappa=1).","optimal_fee_table_exp3":[{"fees":"sym30","state":"post_sellX_arb","side":"buy","J_exact_k1":0.03665,"J_q7_k1":0.03602,"J_q5_k1_w3":0.03647,"J_exact_k0":0.069,"J_q7_k0":0.06902,"fstar_exact_k1":24.0,"fstar_q7_k1":24.0,"fstar_q5w3_k1":28.0},{"fees":"sym30","state":"post_sellX_arb","side":"sell","J_exact_k1":0.03759,"J_q7_k1":0.03659,"J_q5_k1_w3":0.0363,"J_exact_k0":0.05725,"J_q7_k0":0.05731,"fstar_exact_k1":72.0,"fstar_q7_k1":72.0,"fstar_q5w3_k1":70.0},{"fees":"sym30","state":"interior","side":"buy","J_exact_k1":0.04793,"J_q7_k1":0.04784,"J_q5_k1_w3":0.04773,"J_exact_k0":0.07326,"J_q7_k0":0.07309,"fstar_exact_k1":46.0,"fstar_q7_k1":42.0,"fstar_q5w3_k1":42.0},{"fees":"sym30","state":"interior","side":"sell","J_exact_k1":0.04793,"J_q7_k1":0.04784,"J_q5_k1_w3":0.04773,"J_exact_k0":0.07326,"J_q7_k0":0.07309,"fstar_exact_k1":46.0,"fstar_q7_k1":42.0,"fstar_q5w3_k1":42.0},{"fees":"sym30","state":"post_buyX_arb","side":"buy","J_exact_k1":0.03759,"J_q7_k1":0.03665,"J_q5_k1_w3":0.03636,"J_exact_k0":0.05725,"J_q7_k0":0.05731,"fstar_exact_k1":72.0,"fstar_q7_k1":72.0,"fstar_q5w3_k1":70.0},{"fees":"sym30","state":"post_buyX_arb","side":"sell","J_exact_k1":0.03665,"J_q7_k1":0.03612,"J_q5_k1_w3":0.03656,"J_exact_k0":0.069,"J_q7_k0":0.06902,"fstar_exact_k1":24.0,"fstar_q7_k1":24.0,"fstar_q5w3_k1":28.0},{"fees":"leanBid45Ask20","state":"post_sellX_arb","side":"buy","J_exact_k1":0.03584,"J_q7_k1":0.03616,"J_q5_k1_w3":0.03694,"J_exact_k0":0.06668,"J_q7_k0":0.06651,"fstar_exact_k1":10.0,"fstar_q7_k1":10.0,"fstar_q5w3_k1":12.0},{"fees":"leanBid45Ask20","state":"post_sellX_arb","side":"sell","J_exact_k1":0.03885,"J_q7_k1":0.03994,"J_q5_k1_w3":0.03974,"J_exact_k0":0.05724,"J_q7_k0":0.05731,"fstar_exact_k1":88.0,"fstar_q7_k1":86.0,"fstar_q5w3_k1":86.0},{"fees":"leanBid45Ask20","state":"interior","side":"buy","J_exact_k1":0.0482,"J_q7_k1":0.04761,"J_q5_k1_w3":0.04785,"J_exact_k0":0.07018,"J_q7_k0":0.06962,"fstar_exact_k1":44.0,"fstar_q7_k1":42.0,"fstar_q5w3_k1":40.0},{"fees":"leanBid45Ask20","state":"interior","side":"sell","J_exact_k1":0.04739,"J_q7_k1":0.04792,"J_q5_k1_w3":0.04716,"J_exact_k0":0.0737,"J_q7_k0":0.07405,"fstar_exact_k1":48.0,"fstar_q7_k1":44.0,"fstar_q5w3_k1":42.0},{"fees":"leanBid45Ask20","state":"post_buyX_arb","side":"buy","J_exact_k1":0.0388,"J_q7_k1":0.03776,"J_q5_k1_w3":0.03756,"J_exact_k0":0.05725,"J_q7_k0":0.05731,"fstar_exact_k1":62.0,"fstar_q7_k1":62.0,"fstar_q5w3_k1":60.0},{"fees":"leanBid45Ask20","state":"post_buyX_arb","side":"sell","J_exact_k1":0.03594,"J_q7_k1":0.03537,"J_q5_k1_w3":0.03622,"J_exact_k0":0.06671,"J_q7_k0":0.06653,"fstar_exact_k1":34.0,"fstar_q7_k1":34.0,"fstar_q5w3_k1":38.0}],"fstar_vs_u1_sym_fother30_pe0.5_exp4":[{"u1_bps":-40,"ask_k0":80.0,"bid_k0":1.0,"ask_k1":81.0,"bid_k1":17.0},{"u1_bps":-30,"ask_k0":70.0,"bid_k0":11.0,"ask_k1":71.0,"bid_k1":25.0},{"u1_bps":-20,"ask_k0":60.0,"bid_k0":21.0,"ask_k1":61.0,"bid_k1":30.0},{"u1_bps":-10,"ask_k0":50.0,"bid_k0":31.0,"ask_k1":51.0,"bid_k1":35.0},{"u1_bps":0,"ask_k0":40.0,"bid_k0":40.0,"ask_k1":43.0,"bid_k1":43.0},{"u1_bps":10,"ask_k0":31.0,"bid_k0":50.0,"ask_k1":35.0,"bid_k1":51.0},{"u1_bps":20,"ask_k0":21.0,"bid_k0":60.0,"ask_k1":30.0,"bid_k1":61.0},{"u1_bps":30,"ask_k0":11.0,"bid_k0":70.0,"ask_k1":25.0,"bid_k1":71.0},{"u1_bps":40,"ask_k0":1.0,"bid_k0":80.0,"ask_k1":17.0,"bid_k1":81.0}],"reading":"With kappa=0, ask f*~=40-u1 bps and bid f*~=40+u1 bps: an absolute quote about 40 bps from p, independent of s1. With kappa=1, the restoring side stays at slope 1 (quote ~41-43 bps from p) and the away side floors at 17-30 bps. The q5/w3 on-chain approximation is within 6 bps of the exact f* in all 12 cells, and q7 is within 4 bps."},"collapse_test":{"A1_vs_A3_fstar_bps_pe0.5":"interior: DAR k1 46 vs share-opt 34. post-arb restoring side: 72 vs 50 (sym), 88 vs 64 (lean). post-arb away side: 24 vs 30 (sym), 10 vs 22 (lean). Near-collapse cell: lean post_buyX_arb sell side, DAR 34 vs share-opt 32. Interior lean: 44/48 vs 34. Mean-size exact-edge optimizer: 0-4 on the away side.","verdict":"Not a collapse in the static model. A3 is recovered only in the limit s->0, kappa=0, slippage dropped (check C6: the ratio goes to 1 as s->0). Risk: A1-T is a function of (u_hat, f_other) only, so if V10's lean already sits near slope 1 in effective terms, A1-T may turn out to be a constant change. Ablation D1 measures this directly."},"checks":{"label":"deterministic, offline, from test/scratch/checks.py; results copied verbatim","results":{"C1_mean":19.99999999999999,"C1_E2_over_M2":4.22069581699655,"C1_exp_sig2":4.220695816996552,"C1_median":9.73504511919943,"C1_vol_share_above_mean":0.7257468822499259,"C1_Phi(sig/2)":0.7257468822499265,"C1_count_share_above_mean":0.27425311775007355,"C2_interior_marginal_price_reldiff":1.4104897873356766e-16,"C2_sum":50.0,"C2_ab_vs_exact_absdiff":4.440892098500626e-13,"C3_moment_closed_vs_quad_maxrel":7.610862113261332e-07,"C4_dEY1_da":0.49107347415588976,"C4_survival_P(T>t0)":0.491073474140711,"C5_arb_closed_vs_alg_maxabs":1.1446954495397677e-12,"C6_ratio_dist_over_meansize_sig1.2":1.7844771489064444,"C6_ratio_dist_over_meansize_sig0.3":1.0233666830513388,"C6_ratio_dist_over_meansize_sig0.05":1.0006212556604712,"C6_ratio_dist_over_meansize_sig0.01":1.0000248205958155,"C7_EY1_monotone_in_fee":true,"C7_zero_fee_at_fair_edge_ge0":true,"C8_buy":0.07125451089442651,"C8_sell":0.07125451089134681,"C9_T999":396.9190174289116,"C9_2nd_order_edge_relerr_at_T999":0.036673875808575576},"interpretation":{"C1":"Lognormal identities hold: mean 20, E[T^2]/M^2=e^{1.44}=4.2207, median 9.735, Y-volume share of orders above the mean = Phi(0.6) = 0.7257, count share 0.274.","C2":"Router: legs sum to T, post-trade fee-adjusted marginal prices are equal when interior (relative error 1e-16), and the a,b form equals the router.rs formula.","C3":"Closed-form clamped moments vs quadrature: max relative error 7.6e-7.","C4":"dE[Y1]/da equals the survival P(T>t0)=0.4911.","C5":"The closed-form arb profit matches a re-implementation of arbitrageur.rs to 1.1e-12.","C6":"The ratio of distribution to mean-size edge goes to 1 as s->0 (1.784 at s=1.2, 1.00002 at s=0.01).","C7":"E[Y1] does not increase in own fee. At zero fee with s1=p, the edge is >=0 (slippage only).","C8":"Buy/sell mirror symmetry at s1=s2=p with equal fees: J equal to 4e-12.","C9":"The second-order edge expansion has 3.7% relative error at the 99.9th percentile size (397 Y). Hence the exact edge is used at the nodes."}},"solidity_pseudocode":"// appended after V10 fee computation, before slots write; A1-T\n// table: bytes constant TBL; entry = uint8 fee bps; index ((side*NF+jf)*NU+iu)\nint256 uBps = _lnRatioBps(spot, fastHat);            // ln via (s-p)/p*(1-(s-p)/(2p)) ok for |u|<100bps\nuint256 fa = _dar(0, uBps, bidFee); uint256 fb = _dar(1, uBps, askFee);\naskFee = _residual(askFee, fa); bidFee = _residual(bidFee, fb);\nfunction _dar(uint s,int u,uint fo) internal pure returns(uint){ // bilinear in u (step 5bp, -60..60), fo (step 10bp, 0..80)\n  (uint iu,uint wu)=_bucket(u+60,5,24); (uint jf,uint wf)=_bucket(fo/BPS,10,8);\n  return BPS*_bilerp(TBL,s,iu,jf,wu,wf); }\nfunction _residual(uint f0,uint fd) internal pure returns(uint){ int d=int(fd)-int(f0); d=d>DMAX?DMAX:(d<-DMAX?-DMAX:d); return clampFee(uint(int(f0)+d*ETA/WAD)); }\n// A1-Q: for c in {f0-D,f0,f0+D}: J=sum_{w2 in 3} sum_{z in GH5} pw*wz*(edge(leg(T_z;c)) - KAPPA*(hinge(u')-hinge(u0))); T_z constants in WAD; y2=1000*sqrt(s2) via _isqrt","state_layout":"A1-T needs no new storage: it reads slots[14] (fastHat), slots[5] (pHat) and slots[0..1], and the table is a bytecode constant (2 sides x 9 f_other x 25 u = 450 bytes). A1-Q needs no new storage either. Optional slot 15: the last observed normalizer spot from an interior route (V10 lines 139-144), to tighten the w2 prior to a point.","gas_design":{"label":"UNMEASURED estimates","V10_measured_max_ok":194870,"limit":250000,"A1_T":"~1.5-3k gas (one ln approximation, 2 bilinear lookups of 4 bytes each, a few mul/div)","A1_Q":"2 sides x 3 candidates x 3 w2 x 5 nodes = 90 leg evaluations at ~300-450 gas, plus 6 _isqrt; ~30-45k. Too close to the 55k headroom: run it only on firstInStep, or use 2 candidates. The worker must measure with gas_stats and reject any OOG.","bounded":"no loops depend on input; maximum iterations fixed at compile time"},"prototype_source_python":"# Offline static prototype: distribution-aware retail-tail pricing (DAR). No simulator use.\nimport math\nK=1e6; G2=0.997; SIG=1.2; MEAN=20.0; MIN_AMT=1e-4\nPhi=lambda z:0.5*math.erfc(-z/math.sqrt(2))\ndef ln_mu(M,s=SIG): return math.log(M)-0.5*s*s\ndef S(n,t,M,s=SIG):  # E[T^n 1{T>t}], T~LN(ln M - s^2/2, s)\n    mu=ln_mu(M,s); Mn=math.exp(n*mu+0.5*n*n*s*s)\n    if t<=0: return Mn\n    return Mn*Phi((mu+n*s*s-math.log(t))/s)\ndef L(n,t,M,s=SIG): return math.exp(n*ln_mu(M,s)+0.5*n*n*s*s)-S(n,t,M,s)\ndef ab(Rin1,Rin2,g1,g2=G2):  # router.rs:40-75/82-117 with x*y=K for both pools\n    r=math.sqrt(g1/g2); d=g1+r*g2   # r=sqrt(x1 g1 y1)/sqrt(x2 g2 y2)=sqrt(g1/g2) when k1=k2\n    return (r*Rin2-Rin1)/d, r*g2/d\ndef leg(T,a,b): return min(max(a+b*T,0.0),T)\ndef moments(a,b,M,s=SIG):  # closed-form E[Y1],E[Y1^2], Y1=clamp(a+bT,0,T)\n    if a<0:\n        t0=-a/b\n        return a*S(0,t0,M,s)+b*S(1,t0,M,s), a*a*S(0,t0,M,s)+2*a*b*S(1,t0,M,s)+b*b*S(2,t0,M,s)\n    t1=a/(1-b) if b<1 else float('inf')\n    if t1==float('inf'): return L(1,1e300,M,s),L(2,1e300,M,s)\n    return (L(1,t1,M,s)+a*S(0,t1,M,s)+b*S(1,t1,M,s),\n            L(2,t1,M,s)+a*a*S(0,t1,M,s)+2*a*b*S(1,t1,M,s)+b*b*S(2,t1,M,s))\ndef grid(M,s=SIG,n=6000,w=8.0):  # midpoint rule in log space\n    mu=ln_mu(M,s); h=2*w/n; out=[]\n    for i in range(n):\n        z=-w+(i+0.5)*h; out.append((math.exp(mu+s*z), math.exp(-0.5*z*z)/math.sqrt(2*math.pi)*h))\n    return out\n# exact per-leg edge (engine.rs:155-159) and post-trade spot; Y units\ndef edge_buy(Y,s1,p,fa):  # trader buys X paying Y gross; AMM sells X\n    g=1-fa; y=math.sqrt(K*s1); x=K/y; dx=x*g*Y/(y+g*Y); return Y-p*dx, (y+g*Y)**2/K\ndef edge_sell(X,s1,p,fb):  # trader sells X gross; AMM buys X\n    g=1-fb; y=math.sqrt(K*s1); x=K/y; dy=y*g*X/(x+g*X); return p*X-dy, K/(x+g*X)**2\ndef arb_profit(s,p,fb,fa):  # closed forms of arbitrageur.rs:54-146 (no 99% cap binding)\n    rk=math.sqrt(K)\n    if s>p/(1-fb): return rk*(math.sqrt(s)-math.sqrt(p/(1-fb)))**2/math.sqrt(s)\n    if s<(1-fa)*p: return rk*(math.sqrt(s/(1-fa))-math.sqrt(p))**2/math.sqrt(s)\n    return 0.0\nGH=[(-6+(i+0.5)*0.3,math.exp(-0.5*(-6+(i+0.5)*0.3)**2)*0.3) for i in range(40)]  # midpoint N(0,1) nodes, unnormalized\ndef arb_cost(s,p,fb,fa,sp=0.00094):  # E over next GBM step (price_process.rs)\n    return sum(w*arb_profit(s,p*math.exp(-0.5*sp*sp+sp*z),fb,fa) for z,w in GH)/math.sqrt(2*math.pi)\ndef w2_nodes(pe=0.5,n=5):  # prior on w2=ln(s2/p): pe mass on band-edge atoms, rest uniform\n    d=-math.log(G2); u=[(-d+(2*i+1)*d/n,(1-pe)/n) for i in range(n)]\n    return u+[(-d,pe/2),(d,pe/2)]\ndef J_side(side,f,s1,p,fother,w2s,kappa=0.0,M=MEAN,s=SIG,n=1200,meansize=False):\n    \"\"\"Expected (edge - kappa*delta arb cost) per arriving order of this side; Y units.\"\"\"\n    fb,fa=(f,fother) if side=='sell' else (fother,f)\n    C0=arb_cost(s1,p,fb,fa) if kappa else 0.0\n    tot=0.0\n    for w2,pw in w2s:\n        s2=p*math.exp(w2)\n        if side=='buy':\n            a,b=ab(math.sqrt(K*s1),math.sqrt(K*s2),1-f); Mx=M\n        else:\n            a,b=ab(K/math.sqrt(K*s1),K/math.sqrt(K*s2),1-f); Mx=M/p   # T_x=S/p (router.rs:221)\n        pts=[(Mx,1.0)] if meansize else grid(Mx,s,n)\n        acc=0.0\n        for T,wt in pts:\n            q=leg(T,a,b)\n            if q<=MIN_AMT: continue\n            e,s1n=(edge_buy(q,s1,p,f) if side=='buy' else edge_sell(q,s1,p,f))\n            if kappa: e-=kappa*(arb_cost(s1n,p,fb,fa)-C0)\n            acc+=wt*e\n        tot+=pw*acc\n    return tot\ndef share_opt_obj(side,f,s1,p,w2s,M=MEAN):  # failed family: fee x routed input at mean size\n    tot=0.0\n    for w2,pw in w2s:\n        s2=p*math.exp(w2)\n        if side=='buy': a,b=ab(math.sqrt(K*s1),math.sqrt(K*s2),1-f); T=M\n        else: a,b=ab(K/math.sqrt(K*s1),K/math.sqrt(K*s2),1-f); T=M/p\n        q=leg(T,a,b); tot+=pw*f*(q if side=='buy' else q*p)\n    return tot\ndef C_quad(u,p,y,db,da,sp=0.00094):  # E[(arb profit)] ~ y/4*E[(u+sp Z-db)_+^2 + (-(u+sp Z)-da)_+^2]; on-chain form\n    def pp(m): z=m/sp; return (m*m+sp*sp)*Phi(z)+m*sp*math.exp(-0.5*z*z)/math.sqrt(2*math.pi)\n    return 0.25*y*(pp(u-db)+pp(-u-da))\ndef J_cf(side,f,s1,p,fother,w2s,kappa=0.0,M=MEAN,s=SIG,psd=0.0):\n    \"\"\"Closed-form (on-chain) version: moments of clamped leg, 2nd-order edge, quadratic arb charge in leg size.\"\"\"\n    fb,fa=(f,fother) if side=='sell' else (fother,f); g=1-f\n    pn=[(p,1.0)] if psd==0 else [(p*math.exp(-psd),0.25),(p,0.5),(p*math.exp(psd),0.25)]\n    y1=math.sqrt(K*s1); x1=K/y1; tot=0.0\n    for pv,pwp in pn:\n      u0=math.log(s1/pv); db=-math.log(1-fb); da=-math.log(1-fa)\n      for w2,pw in w2s:\n        s2=pv*math.exp(w2)\n        if side=='buy':\n            a,b=ab(y1,math.sqrt(K*s2),g); m1,m2=moments(a,b,M,s)\n            c=g*pv/s1; e=m1*(1-c)+c*g*m2/y1; du=2*g/y1          # du/dY1 of ln s1\n        else:\n            a,b=ab(x1,K/math.sqrt(K*s2),g); m1,m2=moments(a,b,M/pv,s)\n            c=g*s1/pv; e=pv*(m1*(1-c)+c*g*m2/x1); du=-2*g/x1\n        if kappa:\n            h=1e-4; C=lambda d:C_quad(u0+d,pv,y1,db,da)\n            c1=(C(h)-C(-h))/(2*h); c2=(C(h)-2*C(0)+C(-h))/(h*h)\n            e-=kappa*(c1*du*m1+0.5*c2*du*du*m2)\n        tot+=pwp*pw*e\n    return tot\n# probabilists' Gauss-Hermite nodes/weights (sum w = 1), n=5 and 7\nGH5=[(-2.856970013872806,0.011257411327720691),(-1.355626179974266,0.22207592200561266),(0.0,0.5333333333333333),(1.355626179974266,0.22207592200561266),(2.856970013872806,0.011257411327720691)]\nGH7=[(-3.750439717725742,0.0005482688559722184),(-2.366759410734541,0.030757123967586496),(-1.154405394739968,0.24012317860501275),(0.0,0.45714285714285713),(1.154405394739968,0.24012317860501275),(2.366759410734541,0.030757123967586496),(3.750439717725742,0.0005482688559722184)]\ndef hinge_C(u,y,db,da,sp=0.00094):  # sigma-smoothing dropped except +sp^2 inside band edges' active branch\n    m1=u-db; m2=-u-da; return 0.25*y*((m1*m1+sp*sp if m1>0 else 0)+(m2*m2+sp*sp if m2>0 else 0))\ndef J_q(side,f,s1,p,fother,w2s,kappa=0.0,M=MEAN,s=SIG,nodes=GH7):\n    \"\"\"On-chain form: fixed lognormal nodes in T, exact clipped router leg, exact edge, hinge arb charge.\"\"\"\n    fb,fa=(f,fother) if side=='sell' else (fother,f); g=1-f; y1=math.sqrt(K*s1); x1=K/y1\n    db=-math.log(1-fb); da=-math.log(1-fa); u0=math.log(s1/p); C0=hinge_C(u0,y1,db,da); tot=0.0\n    for w2,pw in w2s:\n        s2=p*math.exp(w2)\n        if side=='buy': a,b=ab(y1,math.sqrt(K*s2),g); Mx=M\n        else: a,b=ab(x1,K/math.sqrt(K*s2),g); Mx=M/p\n        for z,wz in nodes:\n            T=Mx*math.exp(-0.5*s*s+s*z); q=leg(T,a,b)\n            if q<=MIN_AMT: continue\n            e,s1n=(edge_buy(q,s1,p,f) if side=='buy' else edge_sell(q,s1,p,f))\n            if kappa: e-=kappa*(hinge_C(math.log(s1n/p),y1,db,da)-C0)   # y1 held fixed: 2nd-order\n            tot+=pw*wz*e\n    return tot\n","worker_plan_55min":["0-8: setup per brief and verify the CH calibration (525.5258821780834). Compile V10; check that A0 (eta=0) is byte-equivalent in behaviour (paired diff exactly 0 on 50 seeds).","8-18: generate the A1-T table offline with proto.J_q (kappa in {0.5,1}, pe in {0.25,0.5,0.75}; ~30 s each). Optional: calibrate pe from 20 tuning-seed traces using the hidden s2 and p from run results (steps.spot_prices['normalizer'], fair_price), as the fraction of steps with |w2| within 2 bps of the band edge.","18-40: screen on tuning seeds 10000.. (500 seeds per arm, paired vs STACK and vs V10): grid eta in {0.25,0.5,1}, Dmax in {10,20,40} bps, kappa in {0.5,1}, p_ref in {fastHat, staleHat}. Report retail and arb deltas and gas_stats. Drop any arm with OOG>0.","40-48: ablations D1-D5 on the best arm (500 fresh tuning seeds).","48-55: if best arm beats V10 by >2 SE on a second 1000-seed tuning block, freeze it and run confirmation vs STACK once on >=2000 fresh seeds from 5000000 up (not reused); else report negative."],"required_inputs":["V10 code (sha cd9bdb45...)","STACK code (sha 2eaafc79...)","pinned simulator wheel and checkout per brief","this prototype"],"objective_and_ranges":{"objective":"mean paired edge diff vs STACK (and vs V10) on tuning seeds; constraint OOG=0","eta":"[0,1]","Dmax_bps":"[5,40]","kappa":"[0,1.5]","pe":"[0,1]","table_u_range_bps":"[-60,60]","M":"20 (sensitivity 19,21)","s":"1.2 fixed by config"},"falsification_and_ablation":["F1 reject if the best A1 arm does not beat V10 by >2 SE on 1000 tuning seeds, or if the retail gain comes with an arb loss of larger magnitude (the pattern of the failed shadow overlay: arb +.132, retail -.156).","F2 reject the size mechanism if A1-T built with s=0.05 (mean-size table) performs within 1 SE of A1-T built with s=1.2.","F3 reject 'distinct from share optimizer' if the A3 table (argmax f*Y1(M)) under the same eta/Dmax is within 1 SE of A1-T.","D1 slope test: replace the table with a linear quote rule f=q0 -/+ beta*u, beta in {0.7,1.0}, q0=40. If the linear rule matches the table, the floor kink is not doing anything.","D2 kappa=0 vs kappa=1 table (value of the arb charge).","D3 keep vs drop V10's 30/36 bp caps (they clip the DAR restoring-side fees of 60-88 bps).","D4 pe in {0,1}, and a point prior from the interior-route s2 observation.","D5 add rho*[C(u;f)-C(u;f0)] for the arb-band effect, rho in {0,0.5,1}.","Sign check on traces: in steps where A1 raises the restoring-side fee, the realised retail edge per routed unit should rise and the routed volume fall (compare against V10 on the same seeds)."],"limitations":["One-step myopic arb charge; there is no dynamic programme over later steps.","The w2 prior is not calibrated. pe changes the away-side f* by up to 12 bps (exp.py).","V10's caps (lines 231-237) conflict with the 60-88 bp restoring-side fees DAR prefers, so the residual partly fights V10 logic (ablation D3).","There is no evidence that any static gain transfers. Prior record: constant changes and fee rules written from scratch failed (brief).","p_hat error shifts the quote 1:1. V10 posterior quality is a binding input."]}