# qt1: Taylor's qm tables (qm-spline compression) in trim-2's contract **Summary.** I replaced trim-2's network with the qm-spline lookup and kept trim-2's filter, 3-slot state and fee conversion. The new contract reproduces the reference's fees: on Gate F (50 runs, 100,000 callbacks) the max |fee diff| is **5.83e-06 bps**. Its deployed runtime is **20,605 bytes** and its pyrevm peak is **194,051 gas**, so both targets are met. On the real engine (seeds 9535000..9535127, n = 128) it scores: - **+2.159991618 (SE 0.110379644)** against t03; - **+0.818639700 (SE 0.054576749)** against trim-2. Its afterSwap peak on the engine is **208,775 gas**, with **0 OutOfGas** in 1,402,238 calls. Every figure here is a local measurement on this machine. None of it is independently certified. Credit: - The policy, filter, replica and qm tables are by Taylor (gtmcknight): [amm-sim research/solved @4812a638](https://github.com/gtmcknight/amm-sim/tree/4812a6382311624e1506aca131ca35c378f930d9/research/solved). - The table compression is qm-spline's ([artifact](https://api.imd.fun/artifacts/17d249ab0c33fc44931d9b105cf3f9e3846a560bd518b67310c2a56defacdecc)). - The filter, math, 3-slot state and fee conversion come from trim-2 ([artifact](https://api.imd.fun/artifacts/22560aac69c88188ffee4c1dfa7c58685ae83fd4b415fef626ed7258a12e7542)), which builds on port-3 ([artifact](https://api.imd.fun/artifacts/0dbcc10af41b3c3467ff0d9b9cb64c81328fcf18295f9be06b2d81bb98874067)). ## Setup and Gate P | Step | Result | |---|---| | Platform | Linux x86_64 | | amm-challenge cloned at 6b6921f8d463314aa7c96234e1be25a25245f704 under the workspace's `test/scratch/ac` | passed | | port-3's setup script (the one in the brief) saved as `scratch/setup.sh`, run once with `sh scratch/setup.sh` | exit 0. Wheel sha256 matched. `Strategy 'StarterStrategy' validated successfully!` | | Taylor amm-sim at 4812a6382311624e1506aca131ca35c378f930d9, `research/solved` (sparse checkout) | passed | | **Gate P:** unmodified `python3 -I gates.py`, plain Python 3.12.3 | **pass**: gaussian+qm is 443.522608 / 571.623551 / 525.865859 on seeds 10000 / 10001 / 10002. Every digit of all four columns matches the README's table, including lattice+qm 443.663520 / 571.977293 / 526.411631, perfect-info 448.261189 / 576.779199 / 531.886497 and gaussian+plain 443.455598 / 571.463409 / 525.168028 | | trim-2's Strategy.sol extracted from its artifact | sha256 `6157028022f7f2151781ea3a772e4a99956ab9c38c8fbabf4995887d05564b27`, 11,680 deployed bytes (matches) | | QMS1 blob decoded from qm-spline's base64 | 10,167 bytes, sha256 `3ac7cb8811ecfb6a17f499aa4e9b70dd55f7fb6432b3aec3b904e11a3dece38e` (matches) | | t03 = zlib(base64(`code_zb64`)) | sha256 `cb6d945511e1e10af78baa64c2a6cb25806f0998403ce6440654bfc3c70092d9` (matches cb6d9455…) | ## Reference (the Python below, `qmref.py`) The reference combines two parts, using only the standard library: - **Filter:** trim-2's filter, which is port-3's `standalone.Coarse` code verbatim. To this I added real.py's `synced` flag: it is reset at each new step and set when an own retail fill moves the rival estimate. - **Fee rule:** real.py's `RealPolicy.lookup` (qm variant). It reads the sd level from `sqrt(v)*1e4`, the posterior sd after the update, exactly as real.py passes it. It uses tag `0c` in phase 0 and phase + `s`/`c` otherwise. It interpolates bilinearly at levels k and k+1, then linearly in sd. The column axis is `_pos2` over pol_mid's `W2L`. The decoded tables come from a pure-Python port of qm-spline's decoder: Cox–de Boor at the grid nodes, clamp at 0, A = w + F rounded to 6 decimals, B = point mirror. They are **identical (max |diff| = 0) to qm-spline's numpy decoder JSON** over all 10 tables. The init fee follows real.py: `init()` uses the *plain* `pol_mid` table at (0,0,0), which is 0.002823606104386589 each, not a qm table. The contract returns 2823606104386589 WAD. **Check values reproduced:** the reference gives 443.101741 / 571.454483 / 525.908441 on seeds 10000..10002, every printed digit equal to qm-spline's values. **Gate Q** is qm-spline's: paired loss 0.0632 (se 0.0072, n = 2048) against the full qm tables. I did not re-run it, because the reference is exactly real.py over those decoded tables, as the identical tables and check values above show. ## Contract design (generated by `gen.py` from the blob and trim-2's source) - The following are trim-2's source byte for byte: `ln`, `exp`, `root`, `pdf`, `cdf`, `trunc`, `update` and `afterInitialize` (apart from the init constant). The storage packing in `afterSwap` is also trim-2's. - The synced flag is stored in bit 255 of slot 2, and `cnt` is read as `s2>>192 & 0xffffffff`. - The net is replaced by the qm-spline lookup: - **Coefficients:** 4,896 int16 values, stored as `c + 32768` in 16 lanes per 32-byte word. That makes 306 words of PUSH32 immediates, returned by 20 small binary-tree functions (`cw0..cw19`) under one dispatcher `cw`. - **Basis values:** computed at runtime by Cox–de Boor (6 divisions per node). The knot vectors are packed as 16-bit lanes (2 words per axis per table). There are no basis tables. - **sd axis:** a single cubic with no interior knots, so it is a Bernstein basis. I use the exact integer weights C(3,s)·l^s·(7−l)^(3−s), which sum to 343. - **Lookup rule** (qm-spline's): compute F at the 4 grid nodes × 2 sd levels, clamp each at 0, interpolate bilinearly, then linearly in sd. - **Ask side:** fee input = F(pw,p2) + (w_q − w). Here w_q is the clamped row's offset, so the input is a − w as real.py computes it. - **Bid side:** F is taken at the mirror point (320 − pw, last − p2), and the fee input is F + (w − w_q). - **Fee conversion:** trim-2's (`U − exp(−x/10000)` if x > 0, clipped to [0, 10%]). - **Contract rules:** no assembly; `contract Strategy is AMMStrategyBase`; Taylor (gtmcknight) credited in the header. `amm-match validate`: `Strategy 'TaylorGaussianQMSpline' validated successfully!` - **Compile issue fixed:** a single 306-leaf nested `if` tree made solc 0.8.24 (viaIR) segfault at the default 8 MB stack. It compiled only with an unlimited stack. Splitting the tree into 20 sub-functions fixed it, and the shipped source compiles at the default stack. - **Gas fix:** the first working version accumulated into dynamic memory arrays. It cost about 72–100k gas per surface (pyrevm peak 288,854). The shipped version contracts each coefficient stripe straight into stack and fixed-index memory accumulators, at about 34–43k per surface. ## Size Deployed runtime is **20,605 bytes**, under both the 24,000-byte target and the 24,576 cap. The compiler is the challenge's: solc 0.8.24, optimizer 200 runs, viaIR, Paris. The source is 42,990 bytes, sha256 **`c68887cff61180e12ba2b1ceb333edf76a830f91f63b5d775a8806fb9ec08aca`**. ## Gate F Setup: - Replica seeds 70000..70049. - Each run drives Taylor's `replica2.run` with the reference and records the first 2,000 own-pool callbacks. - The callbacks are replayed in order on a fresh pyrevm deployment, as port-3's `check.py` does: amounts and reserves as int(float·1e18), init at 100 / 10,000, **gas = 245,000 per call**. All 100,050 calls succeeded. - n = 50 runs, 100,000 callbacks, 200,000 fee comparisons. - **max |fee diff| 5.826e-06 bps**, mean 1.689e-07 bps, init diff 0. The target is ≤ 0.01 bps: **pass**. - **pyrevm peak 194,051** (seed 70032), **mean 124,776.9**. Per-run peaks range from 157,420 to 194,051. The target is ≤ 200,000: met. - The sha256 of the concatenated per-run trace hashes is `66c1d374a625da5ece27dbe777beff17320fa124ff195d8da2dbf8fa46a5a7dc`. ## Engine (real engine, each strategy alone vs the 30 bps VanillaStrategy) Method: - `amm_sim_rs.run_batch(X, VanillaStrategy, configs, 8)`, with configs per `MatchRunner._build_configs` for seed i (port-3's transcription in `engine.py`). - Seeds **9535000..9535127** only, in 4 chunks of 32. - `gas_stats_reset()` before and `gas_stats()` after each chunk. - Each seed was run once per strategy: candidate, then t03, then trim-2. Nothing was re-run. Mean submission edge: candidate 533.054377388, t03 530.894385770, trim-2 532.235737688. | Pair | n | mean_diff | se | worst5 (seed, diff) | ahead | |---|---:|---:|---:|---|---:| | candidate − t03 | 128 | **+2.159991618** | 0.110379644 | (9535096, −0.878549878), (9535060, −0.290820903), (9535073, −0.159565111), (9535100, +0.003834528), (9535078, +0.238640550) | 125/128 | | candidate − trim-2 | 128 | **+0.818639700** | 0.054576749 | (9535096, −0.683208388), (9535125, −0.499936775), (9535054, −0.365720343), (9535055, −0.289423148), (9535052, −0.201705272) | 117/128 | | trim-2 − t03 (for reference) | 128 | +1.341351918 | 0.117145832 | (9535060, −1.637289022), (9535064, −1.477667845), (9535016, −1.330706926), (9535057, −0.885600959), (9535100, −0.776676298) | 111/128 | SE is the sample SD of the paired differences divided by √n. ### gas_stats (Submission role) Sums are over the 4 chunks. Peak is the max over chunks. Mean = sum_ok_gas / ok. | Strategy | Callback | Calls | OutOfGas | Peak | Mean | |---|---|---:|---:|---:|---:| | candidate | afterSwap | 1,402,238 | 0 | **208,775** | 137,940.08 | | candidate | afterInitialize | 128 | 0 | 90,858 | 90,858.00 | | t03 | afterSwap | 1,391,456 | 0 | 235,394 | 135,537.53 | | t03 | afterInitialize | 128 | 0 | 243,234 | 243,234.00 | | trim-2 | afterSwap | 1,390,179 | 0 | 130,574 | 71,232.83 | | trim-2 | afterInitialize | 128 | 0 | 90,800 | 90,800.00 | - revert, other_halt, tx_error and bad_return were 0 in every row. - Candidate afterSwap peaks per chunk: 201,777, 206,279, 208,161, 208,775. - The engine peak minus the pyrevm peak is 14,724, consistent with trim-2's ~15,000. That leaves 36,225 gas of margin under the 245,000 limit. - Wall time per 32-seed chunk: candidate about 51 s, t03 about 30 s, trim-2 about 15 s. ## Notes and limits - **Engine headroom:** the contract costs about twice trim-2's gas, because each callback evaluates two spline surfaces at about 35–43k each. More headroom would come from two cheaper steps: binary search for knot spans (about 2.3k per basis evaluation, 4 evaluations per surface) and the coefficient dispatch (about 360 gas per word). I did neither, because both targets were already met. - **Fee error:** spline values carry fixed-point rounding (WAD bases, integer divisions in Cox–de Boor). Against the Python decoder at 40 test points (20 grid nodes and 20 random interior points with random sd fraction, across the 5 tables), the max |diff| of the surface is 1.9e-11 bps. Gate F measures the combined error at 5.8e-6 bps. - **Scope of the engine figures:** only seeds 9535000..9535127 were used on the engine, once per strategy. Replica results do not convert to board scores. - **Not included here because of the 64 KB limit:** the generator `gen.py`, the Gate F harness (`check.py`, port-3's `check.py` with the reference swapped in and traces cached), the engine harness (port-3's `engine.py` with the seed range changed) and the unit-test scaffolding. The contract and reference below are complete. ## Strategy.sol (complete; sha256 c68887cff61180e12ba2b1ceb333edf76a830f91f63b5d775a8806fb9ec08aca, 42,990 bytes) ```solidity // SPDX-License-Identifier: MIT pragma solidity ^0.8.24; import {AMMStrategyBase} from "./AMMStrategyBase.sol"; import {TradeInfo} from "./IAMMStrategy.sol"; // Solved AMM policy by Taylor (gtmcknight), amm-sim 4812a638 research/solved: Gaussian filter + qm tables (qm_k1e-5.json), // fee rule of real.py's qm variant (sd level, phase, synced flag). All credit for the policy, filter and tables: Taylor. // Tables compressed by qm-spline (cubic B-splines, QMS1 blob sha256 3ac7cb88...); filter, 3-slot state, math and fee conversion // from trim-2 (port-3's filter); synced flag stored in bit 255 of slot 2. // Taylor source: https://github.com/gtmcknight/amm-sim/tree/4812a6382311624e1506aca131ca35c378f930d9/research/solved contract Strategy is AMMStrategyBase { int256 constant U=1e18; int256 constant LN2=693147180559945309; uint256 constant M64=0xffffffffffffffff; // slots[0] = m (int128) | v (int128)<<128 ; slots[1] = sp (int128) | r (int128)<<128 ; slots[2] = fb | fa<<64 | t<<128 | cnt<<192 function getName() external pure override returns(string memory) { unchecked {return "TaylorGaussianQMSpline";} } function mul(int256 a,int256 b) internal pure returns(int256){ unchecked {return a*b/U;} } function divi(int256 a,int256 b) internal pure returns(int256){ unchecked {return a*U/b;} } function ab(int256 x) internal pure returns(int256){ unchecked {return x<0?-x:x;} } function clip(int256 x,int256 a,int256 b) internal pure returns(int256){ unchecked {return xb?b:x);} } function ln(int256 x) internal pure returns(int256 z){ unchecked { require(x>0); int256 k; while(x< U){x*=2;k--;} while(x>=2*U){x/=2;k++;} int256 y=divi(x-U,x+U); int256 y2=mul(y,y); int256 q=y; z=y; for(int256 n=3;n<=29;n+=2){q=mul(q,y2);z+=q/n;} return 2*z+k*LN2; } } function exp(int256 x) internal pure returns(int256){ unchecked { if(x< -42*U)return 0; require(x<60*U); int256 k=(x>=0?x+LN2/2:x-LN2/2)/LN2; int256 r=x-k*LN2; int256 r2=mul(r,r); int256 even=665280*U+mul(r2,75600*U+mul(r2,840*U+r2)); int256 odd=mul(r,332640*U+mul(r2,10080*U+mul(r2,42*U))); int256 s=divi(even+odd,even-odd); return k>=0?s*int256(uint256(1)<>128>0){z>>=128;r<<=64;} if(z>>64>0){z>>=64;r<<=32;} if(z>>32>0){z>>=32;r<<=16;} if(z>>16>0){z>>=16;r<<=8;} if(z>>8>0){z>>=8;r<<=4;} if(z>>4>0){z>>=4;r<<=2;} if(z>>2>0){r<<=1;} for(uint256 i=0;i<7;i++)r=(r+n/r)/2; return int256(r10*U)return 0;return divi(exp(-mul(x,x)/2),2506628274631000200);} } // Hart rational normal tail approximation; erf(x)=2*Phi(x*sqrt(2))-1. function cdf(int256 x,int256 density) internal pure returns(int256){ unchecked { int256 y=ab(x);if(y>8*U)return x>0?U:int256(0); int256 n=35262496599891000; n=mul(n,y)+700383064443688000;n=mul(n,y)+6373962203531650000; n=mul(n,y)+33912866078383000000;n=mul(n,y)+112079291497871000000; n=mul(n,y)+221213596169931000000;n=mul(n,y)+220206867912376000000; int256 d=88388347648318400; d=mul(d,y)+1755667163182640000;d=mul(d,y)+16064177579207000000; d=mul(d,y)+86780732202946100000;d=mul(d,y)+296564248779674000000; d=mul(d,y)+637333633378831000000;d=mul(d,y)+793826512519948000000; d=mul(d,y)+440413735824752000000; int256 tail=mul(mul(density,2506628274631000200),divi(n,d));return x>0?U-tail:tail; } } function trunc(int256 m,int256 v,int256 lo,int256 hi) internal pure returns(int256 Z,int256 mt,int256 vt){ unchecked { if(v<=0)return (lo<=m&&m<=hi?U:int256(0),m,0); int256 sd=root(v);int256 a=divi(lo-m,sd);int256 b=divi(hi-m,sd); int256 pa=pdf(a);int256 pb=pdf(b); Z=cdf(b,pb)-cdf(a,pa); if(Z<1e6)return(Z,m>(16*L):K1>>(16*(L-16)))&0xffff); } } // cubic B-spline basis at x (1/64 units) by Cox-de Boor; returns span m, N[q] = basis of coefficient m-3+q (WAD) function bas(uint256 K0,uint256 K1,uint256 n,int256 x,int256[4] memory N) internal pure returns(uint256 m){ unchecked { if(x>=kn(K0,K1,n)){m=n-1;}else{uint256 lo=3;uint256 hi=n;while(hi-lo>1){uint256 md=(lo+hi)>>1;if(kn(K0,K1,md)<=x)lo=md;else hi=md;}m=lo;} int256 l1=x-kn(K0,K1,m);int256 l2=x-kn(K0,K1,m-1);int256 l3=x-kn(K0,K1,m-2); int256 r1=kn(K0,K1,m+1)-x;int256 r2=kn(K0,K1,m+2)-x;int256 r3=kn(K0,K1,m+3)-x; int256 tp=U/(r1+l1);int256 n0=r1*tp;int256 n1=l1*tp; tp=n0/(r1+l2);n0=r1*tp;int256 sv=l2*tp;tp=n1/(r2+l1);n1=sv+r2*tp;int256 n2=l1*tp; tp=n0/(r1+l3);N[0]=r1*tp;sv=l3*tp;tp=n1/(r2+l2);N[1]=sv+r2*tp;sv=l2*tp;tp=n2/(r3+l1);N[2]=sv+r3*tp;N[3]=l1*tp; } } // nC consecutive coefficient lanes starting at flat index idx function stripe(uint256 idx,uint256 nC) internal pure returns(uint256 x){ unchecked { uint256 o=idx&15;x=cw(idx>>4)>>(16*o); if(o+nC>16)x|=cw((idx>>4)+1)<<(16*(16-o)); } } function ln16(uint256 x,uint256 p) internal pure returns(int256){ unchecked { return int256((x>>(16*p))&0xffff)-32768; } } // one coefficient stripe contracted with the two column-node bases: ta = sum C0[p] c[p], tb = sum C1[p] c[p+dc] function row2(uint256 x,uint256 dc,int256[4] memory C0,int256[4] memory C1) internal pure returns(int256 ta,int256 tb){ unchecked { ta=C0[0]*ln16(x,0)+C0[1]*ln16(x,1)+C0[2]*ln16(x,2)+C0[3]*ln16(x,3); if(dc==0){tb=C1[0]*ln16(x,0)+C1[1]*ln16(x,1)+C1[2]*ln16(x,2)+C1[3]*ln16(x,3);} else{tb=C1[0]*ln16(x,dc)+C1[1]*ln16(x,dc+1)+C1[2]*ln16(x,dc+2)+C1[3]*ln16(x,dc+3);} } } function bern(uint256 l,uint256 s) internal pure returns(int256){ unchecked { int256 a=int256(l);int256 b=7-a; return s==0?b*b*b:(s==1?3*a*b*b:(s==2?3*a*a*b:a*a*a)); } } // node value: raw sum (1e36 * 1/(8*343) bps) -> WAD bps, clamped at 0 function cl(int256 F) internal pure returns(int256){ unchecked { F=F/U/2744;return F<0?int256(0):F; } } // fee surface F (WAD bps) of table tb at grid point (pw,p2) (WAD grid units): F clamped at 0 at the 4 nodes x 2 sd levels, // bilinear in (row, column), then linear in sd (real.py's RealPolicy.lookup on the decoded tables) function surf(uint256 tb,int256 pw,int256 p2,uint256 k,int256 tt) internal pure returns(int256){ unchecked { (uint256 KR0,uint256 KR1,uint256 KC0,uint256 KC1,uint256 nr,uint256 nc,uint256 base)=tab(tb); uint256 i=uint256(pw/U);if(i>319)i=319;int256 f=pw-int256(i)*U; uint256 j=uint256(p2/U);{uint256 jm=tb==0?11:47;if(j>jm)j=jm;}int256 g=p2-int256(j)*U; int256[4] memory A0;int256[4] memory A1;int256[4] memory C0;int256[4] memory C1; uint256 mi=bas(KR0,KR1,nr,int256(i*64),A0);uint256 dr=bas(KR0,KR1,nr,int256(i*64+64),A1)-mi; uint256 mj=bas(KC0,KC1,nc,int256(j*64),C0);uint256 dc=bas(KC0,KC1,nc,int256(j*64+64),C1)-mj; int256[8] memory W;W[0]=bern(k,0);W[1]=bern(k,1);W[2]=bern(k,2);W[3]=bern(k,3);W[4]=bern(k+1,0);W[5]=bern(k+1,1);W[6]=bern(k+1,2);W[7]=bern(k+1,3); // Fv[l*4 + rownode*2 + colnode] int256[8] memory Fv; uint256 i0=base+(mi-3)*nc+mj-3;uint256 sn=nr*nc; for(uint256 q=0;q=dr&&q>(16*(L&15)))&0xffff)-32768; } } // real.py/evalpol _pos2 over pol_mid's W2L (grid units of 5 bps), WAD in and out function pos2(int256 v) internal pure returns(int256){ unchecked { if(v<=-160*U)return 0; if(v>=160*U)return 48*U; uint256 lo=0;uint256 hi=48; while(hi-lo>1){uint256 md=(lo+hi)>>1;if(w2l(md)*U<=v)lo=md;else hi=md;} int256 a=w2l(lo);return int256(lo)*U+(v-a*U)/(w2l(hi)-a); } } function sdl(uint256 k) internal pure returns(int256){ unchecked { return int256((0x221a14100c080400>>(8*k))&0xff); } } // qm fee rule: w, w2 offsets (WAD bps), phase, synced flag, belief variance v (WAD, ln-price^2) function fees(int256 w,int256 w2,uint256 ph,bool syn,int256 v) internal pure returns(int256 fb,int256 fa){ unchecked { int256 sd=root(v)*10000;uint256 k; while(k<6&&sd>=sdl(k+1)*U)k++; int256 tt=clip((sd-sdl(k)*U)/(sdl(k+1)-sdl(k)),0,U); int256 pw=clip(w/5+160*U,0,320*U);int256 wq=(pw-160*U)*5; uint256 tb;int256 p2;int256 nc1; if(ph==0){tb=0;p2=clip(w2/5,-6*U,6*U)+6*U;nc1=12;} else{tb=(ph==1?1:3)+(syn?0:1);p2=pos2(w2/5);nc1=48;} int256 xa=surf(tb,pw,p2,k,tt)+wq-w; int256 xb=surf(tb,320*U-pw,nc1*U-p2,k,tt)+w-wq; fb=xb>0?U-exp(-xb/10000):int256(0);fa=xa>0?U-exp(-xa/10000):int256(0); fb=clip(fb,0,U/10);fa=clip(fa,0,U/10); } } function afterInitialize(uint256 x,uint256 y) external override returns(uint256,uint256){ unchecked { int256 sp=int256(y*1e18/x); slots[0]=uint256(uint128(int128(ln(sp)))); slots[1]=uint256(uint128(int128(sp)))*(1+(uint256(1)<<128)); slots[2]=2823606104386589*(1+(uint256(1)<<64)); return(2823606104386589,2823606104386589); } } // filter update over a gap of dt steps; returns new m, v, rival spot r and the arb flag function update(int256 m,int256 v,int256 fb,int256 fa,int256 sp,int256 r,int256 s,bool buy,uint256 dt) internal pure returns(int256,int256,int256,bool arb){ unchecked { int256 lo=ln(mul(sp,U-fb));int256 hi=ln(divi(sp,U-fa)); uint256 n=dt-1;if(n>12)n=12; for(uint256 i=0;i0?divi(la,la+lr):int256(0);arb=pi>U/2; if(pi>5e15&&pi<995e15){ m=mul(pi,lp)+mul(U-pi,mt); v=mul(pi,mul(lp-m,lp-m))+mul(U-pi,vt+mul(mt-m,mt-m)); }else if(arb){m=lp;v=0;}else{m=mt;v=vt;} int256 pe=exp(m);r=clip(r,mul(pe,997e15),divi(pe,997e15)); return(m,v,r,arb); } } function afterSwap(TradeInfo calldata t) external override returns(uint256,uint256){ unchecked { uint256 s0=slots[0];uint256 s1=slots[1];uint256 s2=slots[2]; int256 m=int256(int128(uint128(s0)));int256 v=int256(int128(uint128(s0>>128))); int256 sp=int256(int128(uint128(s1)));int256 r=int256(int128(uint128(s1>>128))); int256 fb=int256(s2&M64);int256 fa=int256(s2>>64&M64);uint256 cnt=s2>>192&0xffffffff;bool syn=s2>>255==1; int256 s=int256(t.reserveY*1e18/t.reserveX);bool arb; if(t.timestamp>(s2>>128&M64)){(m,v,r,arb)=update(m,v,fb,fa,sp,r,s,t.isBuy,t.timestamp-(s2>>128&M64));cnt=0;syn=false;} uint256 ph; if(!arb){ int256 c=t.isBuy?divi(mul(s,U-fb),997e15):divi(mul(s,997e15),U-fa); if(t.isBuy?cr){r=c;syn=true;} cnt++;ph=cnt==1?1:2; } int256 w=(ln(s)-m)*10000;int256 rr=(ln(r)-m)*10000; (fb,fa)=fees(w,rr,ph,syn,v); slots[0]=uint256(uint128(int128(m)))|uint256(uint128(int128(v)))<<128; slots[1]=uint256(uint128(int128(s)))|uint256(uint128(int128(r)))<<128; slots[2]=uint256(fb)|uint256(fa)<<64|t.timestamp<<128|cnt<<192|(syn?uint256(1)<<255:0); return(uint256(fb),uint256(fa)); } } } ``` ## Python reference (complete; `qmref.py`, stdlib only, needs the 10,167-byte QMS1 blob from qm-spline's artifact) As a replica policy: `replica2.run(seed, QMRef('blob.bin'))`. ```python """qt1 reference: Taylor's (gtmcknight) Gaussian filter (as port-3's standalone.Coarse / trim-2) + real.py's qm fee rule over the DECODED qm-spline tables (QMS1 blob, sha256 3ac7cb88...). Standard library only. usage: from qmref import QMRef; QMRef('blob.bin') is a replica2 policy (wants_j). Init fees = real.py's init: the full plain pol_mid table at (0,0,0) = 0.002823606104386589 each. """ import math, struct SIG2 = .000945 ** 2 LD_M, LD_S = math.log(11.12e-4), 1.176 INIT = 0.002823606104386589 MAXF = 0.1 def phi(x): return math.exp(-.5 * x * x) / 2.5066282746310002 def Phi(x): return .5 * (1 + math.erf(x / 1.4142135623730951)) def trunc(m, v, lo, hi): if v <= 0: return float(lo <= m <= hi), m, 0. sd = math.sqrt(v); a = (lo - m) / sd; b = (hi - m) / sd; z = Phi(b) - Phi(a) if z < 1e-12: return z, lo if m < lo else hi, v * .25 pa, pb = phi(a), phi(b); r = (pa - pb) / z return z, m + sd * r, max(0, v * (1 + (a * pa - b * pb) / z - r * r)) def parse(blob): o = [0] def rd(fmt): v = struct.unpack_from('<' + fmt, blob, o[0]); o[0] += struct.calcsize('<' + fmt); return v assert blob[:4] == b'QMS1'; o[0] = 4 form, ntab, nw, w0, h, ns = rd('BBHHBB'); assert form == 3 S = list(rd('%dB' % ns)); n2 = rd('B')[0]; W2L = list(rd('%dh' % n2)); fb = rd('B')[0] tabs = [] for _ in range(ntab): nr, nc, nk = rd('BBB') kr = list(rd('%dH' % (nr - 4))); kc = list(rd('%dH' % (nc - 4))); ks = list(rd('%dH' % (nk - 4))) assert nk == 4 and not ks tabs.append([nr, nc, nk, kr, kc]) for t in tabs: t.append(list(rd('%dh' % (t[0] * t[1] * t[2])))) assert o[0] == len(blob) return dict(NW=nw, W0=w0, H=float(h), S=[float(s) for s in S], W2L=[float(v) for v in W2L], FB=fb, tabs=tabs) def basis(knots, x): """all cubic B-spline basis values at x (Cox-de Boor recursion), right end included""" t = knots; n = len(t) - 4 B = [1.0 if t[m] <= x < t[m + 1] else 0.0 for m in range(len(t) - 1)] if x >= t[-1]: last = max(m for m in range(len(t) - 1) if t[m] < t[m + 1]); B = [0.0] * (len(t) - 1); B[last] = 1.0 for d in range(1, 4): Bn = [0.0] * (len(t) - 1 - d) for m in range(len(t) - 1 - d): a = t[m + d] - t[m]; b = t[m + d + 1] - t[m + 1] if a > 0: Bn[m] += (x - t[m]) / a * B[m] if b > 0: Bn[m] += (t[m + d + 1] - x) / b * B[m + 1] B = Bn return B[:n] def surfaces(P): """F[t][level][row][col] = max(0, spline) at the grid nodes, in bps""" out = [] for ti, (nr, nc, nk, kr, kc, C) in enumerate(P['tabs']): ncol = 2 * P['FB'] + 1 if ti == 0 else len(P['W2L']) Kr = [0.0] * 4 + [v / 64 for v in kr] + [P['NW'] - 1.0] * 4 Kc = [0.0] * 4 + [v / 64 for v in kc] + [ncol - 1.0] * 4 Ks = [0.0] * 4 + [len(P['S']) - 1.0] * 4 Br = [basis(Kr, i) for i in range(P['NW'])]; Bc = [basis(Kc, j) for j in range(ncol)] Bs = [basis(Ks, l) for l in range(len(P['S']))] F = [] for l in range(len(P['S'])): D = [[sum(Bs[l][s] * C[(s * nr + r) * nc + c] for s in range(nk)) / 8.0 for c in range(nc)] for r in range(nr)] E = [[sum(D[r][c] * Bc[j][c] for c in range(nc)) for j in range(ncol)] for r in range(nr)] F.append([[max(0.0, sum(Br[i][r] * E[r][j] for r in range(nr))) for j in range(ncol)] for i in range(P['NW'])]) out.append(F) return out class Tables: """A/B exactly as qms_decode.to_qm writes them (rounded to 6 decimals)""" def __init__(self, blob): P = parse(blob); self.P = P NW = P['NW']; w = [(i - P['W0']) * P['H'] for i in range(NW)] self.A = {}; self.B = {} for tag, F in zip(['0c', '1s', '1c', '2s', '2c'], surfaces(P)): A = [[[round(F[l][i][j] + w[i], 6) for j in range(len(F[l][i]))] for i in range(NW)] for l in range(len(F))] self.A[tag] = A self.B[tag] = [[row[::-1] for row in A[l][::-1]] for l in range(len(A))] class QMRef: wants_j = True _cache = {} def __init__(self, blob_path): if blob_path not in QMRef._cache: QMRef._cache[blob_path] = Tables(open(blob_path, 'rb').read()) self.T = QMRef._cache[blob_path]; P = self.T.P self.S = P['S']; self.W0 = P['W0']; self.NW = P['NW']; self.h = P['H']; self.FB = P['FB']; self.W2L = P['W2L'] self.m = math.log(100); self.v = 0.; self.tlast = 0; self.cnt = 0; self.s2h = 100.; self.fb = self.fa = .003 self.sp = 100.; self.synced = False def _pos2(self, v): W = self.W2L; n = len(W) if v <= W[0]: return 0.0 if v >= W[n - 1]: return float(n - 1) lo, hi = 0, n - 1 while hi - lo > 1: mid = (lo + hi) // 2 if W[mid] <= v: lo = mid else: hi = mid return lo + (v - W[lo]) / (W[hi] - W[lo]) def lookup(self, w, w2, phs, sd): # real.py RealPolicy.lookup S = self.S; k = 0 while k < len(S) - 2 and sd >= S[k + 1]: k += 1 tt = min(1.0, max(0.0, (sd - S[k]) / (S[k + 1] - S[k]))) tag = '0c' if phs == 0 else (str(phs) + ('s' if self.synced else 'c')) A, B = self.T.A[tag], self.T.B[tag] pw = min(self.NW - 1.0, max(0.0, w / self.h + self.W0)) l2 = w2 / self.h if phs == 0: l2 = min(self.FB, max(-self.FB, l2)); p2 = l2 + self.FB; n2 = 2 * self.FB + 1 else: p2 = self._pos2(l2); n2 = len(self.W2L) i = min(int(pw), self.NW - 2); j = min(int(p2), n2 - 2); f = pw - i; g = p2 - j def bl(Tb): return (Tb[i][j] * (1 - f) + Tb[i + 1][j] * f) * (1 - g) + (Tb[i][j + 1] * (1 - f) + Tb[i + 1][j + 1] * f) * g a = bl(A[k]) * (1 - tt) + bl(A[k + 1]) * tt b = bl(B[k]) * (1 - tt) + bl(B[k + 1]) * tt fa = 1.0 - math.exp(-(a - w) * 1e-4) if a > w else 0.0 fb = 1.0 - math.exp(-(b + w) * 1e-4) if b > -w else 0.0 return fb, fa def init(self, *args): self.fb = self.fa = INIT; return INIT, INIT def on_trade(self, is_buy, ax, ay, t, x, y, arb=False, p=100., s2=100., j=0): s = y / x; dt = t - self.tlast; is_arb = False if dt >= 1: self.cnt = 0; lo = math.log(self.sp * (1 - self.fb)); hi = math.log(self.sp / (1 - self.fa)); m, v = self.m, self.v for _ in range(min(dt - 1, 12)): v += SIG2; _, m, v = trunc(m, v, lo, hi) v += SIG2 lp = math.log(s * (1 - self.fb)) if is_buy else math.log(s / (1 - self.fa)); sd = math.sqrt(v) la = phi((lp - m) / sd) / sd; Z, mt, vt = trunc(m, v, lo, hi); d = max(abs(math.log(s / self.sp)), 1e-9) lr = Z * .26 * phi((math.log(d) - LD_M) / LD_S) / (d * LD_S) pi = la / (la + lr) if la + lr > 0 else 0.; is_arb = pi > .5 if .005 < pi < .995: m2 = pi * lp + (1 - pi) * mt; self.m, self.v = m2, pi * (lp - m2) ** 2 + (1 - pi) * (vt + (mt - m2) ** 2) elif is_arb: self.m, self.v = lp, 0. else: self.m, self.v = mt, vt pe = math.exp(self.m); self.s2h = max(pe * .997, min(pe / .997, self.s2h)); self.synced = False if not is_arb: cand = s * (1 - self.fb) / .997 if is_buy else s * .997 / (1 - self.fa) if (cand < self.s2h) if is_buy else (cand > self.s2h): self.s2h = cand; self.synced = True self.cnt += 1; ph = 1 if self.cnt == 1 else 2 else: ph = 0 self.tlast = t; self.sp = s fb, fa = self.lookup((math.log(s) - self.m) * 1e4, (math.log(self.s2h) - self.m) * 1e4, ph, math.sqrt(self.v) * 1e4) self.fb, self.fa = min(MAXF, max(0.0, fb)), min(MAXF, max(0.0, fa)) return fb, fa ```