# gd-abc: ComboG gas diet, GATE=1 fallback Credit: Taylor (gtmcknight), original solved policy, Gaussian filter, qm tables, and replica. IdentityMD's TwoComp and COMBO extend that work. All scores below are local figures, never board scores. The requested diet is implemented, but **the 205,000-gas target fails even at dt=1**. GATE=1 is the brief's fallback, not a qualifying gate or a recommendation to replace qt1. No board submission was made. ## Inputs, platform and setup Linux x86_64 (`uname -sm`). Setup passed: pinned challenge checkout `6b6921f8d463314aa7c96234e1be25a25245f704`; pinned [setup.sh](https://raw.githubusercontent.com/identity-md-launches/goal-3170-beat-network-s-amm-entry/4eb3e985fd31e3cd17832501b95b6d2491aca73d/tools/setup.sh) run once as `sh scratch/setup.sh`. Its engine shared-object check produced `ff88b6353c2aad7342f0a26194f7347e78b9c3b38d683a7449006d423978cd14`; solc 0.8.24 installed; StarterStrategy validated. No setup failure or missing requester input. All thirteen sources.json quotes were verified byte-for-byte against fresh URL responses. Input [TC-A](https://raw.githubusercontent.com/identity-md-launches/goal-3170-beat-network-s-amm-entry/4eb3e985fd31e3cd17832501b95b6d2491aca73d/contracts/Candidate.sol) SHA-256 verified as `b87234c89e094f4955578417c1266129b0f96e6dfda68e3fb8866e00eeda71a2`. Applied [P's unified COMBO diff](https://api.imdnotdead.fun/artifacts/4cc25dfb91f2ca8a957de08c6a38bbd3e4aed7fb288be8242e5677ea77bbf0b1) with `patch -p1`. Used its exact ComboG class and [TwoComp](https://raw.githubusercontent.com/identity-md-launches/goal-3170-beat-network-s-amm-entry/4eb3e985fd31e3cd17832501b95b6d2491aca73d/reference/combo/twocomp.py), with the [QMS1 blob](https://raw.githubusercontent.com/identity-md-launches/goal-3170-beat-network-s-amm-entry/4eb3e985fd31e3cd17832501b95b6d2491aca73d/reference/qt1/blob.bin). Reference baseline and Solidity qt1 were extracted from [qt1](https://api.imdnotdead.fun/artifacts/8a6e303b662e1a5ea9bb47f31acedd3988ef65b3ddb66d074517aa59ad41ca40); Solidity hash independently matched `c68887cff61180e12ba2b1ceb333edf76a830f91f63b5d775a8806fb9ec08aca`. State, checkouts, dependencies and logs were under `test/scratch/`; the challenge's working state was its nested `scratch/`. Commands after setup sourced its `scratch/env.sh`. Long commands used `timeout 470`, below eight minutes. Only this report and sources.json are delivered. ## Gate P, before edits Ran `python3 -I gates.py` from Taylor's `research/solved` at `4812a6382311624e1506aca131ca35c378f930d9`, using the setup Python. [Gate source](https://raw.githubusercontent.com/gtmcknight/amm-sim/4812a6382311624e1506aca131ca35c378f930d9/research/solved/gates.py). Passed: ```text seed perfect-info gaussian+plain gaussian+qm lattice+qm 10000 448.261189 443.455598 443.522608 443.663520 10001 576.779199 571.463409 571.623551 571.977293 10002 531.886497 525.168028 525.865859 526.411631 ``` ## Diet and savings (a) For sd=0 leave k=0 and tt=0 without searching; evaluate the k+1 Bernstein basis only if tt!=0. Existing `interp` already suppresses the second-level coefficient evaluation for tt=0. The setup moved into a pure `levels(sd,X)` helper because the initial inline version failed solc's Yul stack allocator. No assembly or storage was added. (b) Applied [SP's two upper-bound binary knot-span searches](https://api.imdnotdead.fun/artifacts/cc5f5917337662ddf10ac494ed6593d06322b46d50fb475b99108cb9f3f15686), preserving equality behavior. Exhaustive integer positions plus every decoded knot and its ±1 WAD-unit neighbors passed: 2,172 cases. Table assignments, spline arithmetic, node clamping and rounding remain unchanged. (c) Collapse at `i==1` in update rather than `i==2`, and cap silent steps at 9 rather than 12. The delivered TwoComp copy changes only `DUAL_CUTS = 1` and the TwoComp propagation cap to 9; its inherited standalone Gaussian reference remains capped at 12. These are policy changes, so F uses the changed reference. Seed 70000, ungated, complete replica runs. Savings compare the maximum among all mixed dt=1 callbacks at each stage; because the filter changes trajectories, the peak event can move. Callback indexes are zero-based. | Stage | Mixed dt=1 peak | Saving from previous | Saving from original | Peak callback | |---|---:|---:|---:|---:| | P port | 215,761 | 0 | 0 | 2020 | | (a) zero-sd setup | 215,494 | 267 | 267 | 2020 | | (b) SP spans | 209,886 | 5,608 | 5,875 | 6713 | | (c1) collapse at 1 | 209,874 | 12 | 5,887 | 6719 | | (c2) silent cap 9 | 209,874 | 0 | 5,887 | 6719 | The first two optimizations preserved the Python trajectory and maximum fee error on seed 70000. The collapse and cap stages use their corresponding reference settings. Full seed-70000 final ungated F-style error was below 0.01 bps. ## Final ungated probe, seeds 70000..70004 The probe uses 245,000 gas per callback, including ordinary callbacks, with a 1,000,000-gas recovery call after a failed call; a recovery is still counted failed. The measured run used ungated ComboG; the reproduction harness below explicitly sets `ComboG.GATE=10**9` before running. The contract is stage4, also ungated. Counts cover complete replica runs, not just the first 2,000 callbacks. | dt bucket | Mixed callbacks | Peak gas | OOG | Peak seed / callback | |---|---:|---:|---:|---| | 1 | 21,543 | 211,879 | 0 | 70004 / 8339 | | 2 | 4,090 | 216,863 | 0 | 70004 / 2908 | | 3 | 1,614 | 210,693 | 0 | 70000 / 7484 | | 4 | 710 | 213,556 | 0 | 70003 / 1978 | | 5-6 | 511 | 226,938 | 0 | 70003 / 975 | | 7-9 | 153 | 229,427 | 0 | 70000 / 989 | | 10-12 | 24 | 233,784 | 0 | 70002 / 5269 | | >=13 | 6 | 233,525 | 0 | 70002 / 2303 | | non-mixed | 23,180 | 162,019 | 0 | 70004 / 2200 | Total callbacks: 51,831; completed through seed 70004; maximum effective-fee error: 2.53422023817e-06 bps. Failed callbacks requiring recovery: 0. ## Frozen GATE and validation **GATE=1**, the required fallback. Every allowed gate includes dt=1, whose observed peak exceeds 205,000; therefore none of {1,2,3,4,6,9,ungated} qualifies. The non-mixed peak is below 205,000, but does not repair the dt=1 failure. The gas-budget decision uses measured ungated buckets, not a performance selection on the reporting seeds. Frozen Solidity SHA-256: `704b99f2a4245d09f93e2b6aa414722b2bec1f89a1650f521b01abad96e0183a`. Runtime: **22,163 bytes**, within 24,576. Compiler: setup's SolidityCompiler, solc 0.8.24, optimizer 200, viaIR enabled. ```text Validating strategy... Compiling strategy... Strategy 'TaylorComboGQmTrim2' validated successfully! ``` The delivered diff was applied independently to TC-A and reproduced the frozen source byte-for-byte. Both delivered Python blocks parse and match the files used for F. ## Gate F, EFFECTIVE fees Used the pinned [check.py](https://raw.githubusercontent.com/identity-md-launches/goal-3170-beat-network-s-amm-entry/4eb3e985fd31e3cd17832501b95b6d2491aca73d/tools/check.py), clamping the Python fee to [0,0.1] as specified. ```json { "seeds": 50, "callbacks": 100000, "max_bps": 3.057851959923502e-06, "seed": 70036, "callback": 1495, "pyrevm_peak": 211867, "oog": 0 } ``` ```json {"rows": [{"seed": 70036, "n": 2000, "max_callback": 1495, "peak_callback": 1131, "max_error_bps": {"candidate": 3.057851959923502e-06}, "peak": {"candidate": 209161}, "sum_gas": {"candidate": 268331453}, "sha256": {"candidate": "eeabd33152fd9e7bfd2dd7fc3b5bc8799c92caacdd91c5bdf6877b174113c015"}}], "seconds": 28.711753845214844} ``` F PASS: all 50 seeds × 2,000 callbacks completed and maximum <=0.01 bps. Callback locations come from an instrumented replay of the maximum-error seed. ## Replica edges and paired checks Frozen GATE=1, changed TwoComp, full 10,000-step replica runs, qt1's exact decoded-table QMRef baseline. ```json { "rows": [ { "seed": 10000, "candidate": 444.46773771519713, "qt1": 443.1017411146794, "diff": 1.3659966005177466 }, { "seed": 10001, "candidate": 572.1592812555439, "qt1": 571.454483381923, "diff": 0.7047978736209188 }, { "seed": 10002, "candidate": 526.0754260266397, "qt1": 525.908441161234, "diff": 0.16698486540565227 } ], "seconds": 51.73497748374939 } ``` Q choose 60000..61023: complete. Differences are candidate minus qt1, paired by seed. `worst5` means the five smallest individual differences. ```json { "n": 1024, "mean_diff": 0.6314628357616835, "se": 0.019390670024405223, "worst5": [ { "seed": 60210, "diff": -3.524529246255156 }, { "seed": 60036, "diff": -1.5797724778246902 }, { "seed": 60446, "diff": -1.1162942241827523 }, { "seed": 60326, "diff": -1.0765025944368176 }, { "seed": 60525, "diff": -0.987295836680687 } ] } ``` Q report 10000..12047: complete. Differences are candidate minus qt1, paired by seed. `worst5` means the five smallest individual differences. ```json { "n": 2048, "mean_diff": 0.6016110710677752, "se": 0.012953060830197101, "worst5": [ { "seed": 10146, "diff": -3.507265775623182 }, { "seed": 11062, "diff": -2.135362090073272 }, { "seed": 11808, "diff": -1.812142140384708 }, { "seed": 10162, "diff": -1.7405633132070761 }, { "seed": 11837, "diff": -1.3207671020787757 } ] } ``` ## Engine, each strategy alone vs 30 bps VanillaStrategy Fresh seeds 9800000..9800031 were each used once per strategy, shared only for the required pairing. Configuration construction follows [MatchRunner._build_configs](https://raw.githubusercontent.com/benedictbrady/amm-challenge/6b6921f8d463314aa7c96234e1be25a25245f704/amm_competition/competition/match.py): NumPy default_rng(seed), size/rate/sigma in that order, baseline variance, base n_steps and remaining fields. `amm_sim_rs.run_batch(X, VanillaStrategy, configs, 8)`. ```json { "n": 32, "mean_diff": 0.605029434409035, "se": 0.10209867942302321, "worst5": [ { "seed": 9800005, "diff": -0.3384046677929291 }, { "seed": 9800021, "diff": -0.23509345379170554 }, { "seed": 9800004, "diff": 0.029906886399771793 }, { "seed": 9800001, "diff": 0.07230077755571074 }, { "seed": 9800020, "diff": 0.08003830316272342 } ] } ``` qt1 `amm_sim_rs.gas_stats()`: ```json [{"role":"Baseline","callback":"afterInitialize","calls":32,"ok":32,"max_ok_gas":21796,"sum_ok_gas":697472,"oog":0,"revert":0,"other_halt":0,"tx_error":0,"bad_return":0},{"role":"Baseline","callback":"afterSwap","calls":344571,"ok":344571,"max_ok_gas":22592,"sum_ok_gas":7774450620,"oog":0,"revert":0,"other_halt":0,"tx_error":0,"bad_return":0},{"role":"Baseline","callback":"getName","calls":32,"ok":32,"max_ok_gas":21526,"sum_ok_gas":688832,"oog":0,"revert":0,"other_halt":0,"tx_error":0,"bad_return":0},{"role":"Submission","callback":"afterInitialize","calls":32,"ok":32,"max_ok_gas":90858,"sum_ok_gas":2907456,"oog":0,"revert":0,"other_halt":0,"tx_error":0,"bad_return":0},{"role":"Submission","callback":"afterSwap","calls":347934,"ok":347934,"max_ok_gas":208733,"sum_ok_gas":48019134017,"oog":0,"revert":0,"other_halt":0,"tx_error":0,"bad_return":0},{"role":"Submission","callback":"getName","calls":32,"ok":32,"max_ok_gas":21579,"sum_ok_gas":690528,"oog":0,"revert":0,"other_halt":0,"tx_error":0,"bad_return":0}] ``` candidate `amm_sim_rs.gas_stats()`: ```json [{"role":"Baseline","callback":"afterInitialize","calls":32,"ok":32,"max_ok_gas":21796,"sum_ok_gas":697472,"oog":0,"revert":0,"other_halt":0,"tx_error":0,"bad_return":0},{"role":"Baseline","callback":"afterSwap","calls":342592,"ok":342592,"max_ok_gas":22592,"sum_ok_gas":7729813544,"oog":0,"revert":0,"other_halt":0,"tx_error":0,"bad_return":0},{"role":"Baseline","callback":"getName","calls":32,"ok":32,"max_ok_gas":21526,"sum_ok_gas":688832,"oog":0,"revert":0,"other_halt":0,"tx_error":0,"bad_return":0},{"role":"Submission","callback":"afterInitialize","calls":32,"ok":32,"max_ok_gas":92194,"sum_ok_gas":2950208,"oog":0,"revert":0,"other_halt":0,"tx_error":0,"bad_return":0},{"role":"Submission","callback":"afterSwap","calls":348389,"ok":348389,"max_ok_gas":228941,"sum_ok_gas":53622426965,"oog":0,"revert":0,"other_halt":0,"tx_error":0,"bad_return":0},{"role":"Submission","callback":"getName","calls":32,"ok":32,"max_ok_gas":21677,"sum_ok_gas":693664,"oog":0,"revert":0,"other_halt":0,"tx_error":0,"bad_return":0}] ``` ## Problems and limits - The requested 205,000 mixed-gas goal is not achieved. GATE=1 is an explicitly failing fallback; this is a measured counterexample and reusable diet patch, not a candidate meeting this item's gas target. - The initial inline sd optimization failed compilation with a Yul stack-depth error; the pure helper repaired it without configuration changes. - The first F invocation reached its 470-second cap after seed 70013. The remaining F seeds ran in separate bounded chunks, with no change to source or reference. Q scoring likewise checkpoints each seed and resumes bounded chunks. - Replica figures and finite gas samples are local observations. No leaderboard improvement or universal gas bound is claimed. ## Commands and reproduction Paths below are relative to the challenge checkout. `test/scratch/` contains all ephemeral installations and state. Gate P was run in Taylor's solved directory with the absolute env.sh sourced. The exact pinned setup/check tools are linked above. Extract the final unified diff, combog.py and twocomp.py below verbatim. Apply the diff to the pinned TC-A with `patch -p1` in a directory holding `Strategy.sol`, then copy it to `scratch/candidate.sol`. Put Taylor's pinned solved files in `scratch/reference/taylor`, the pinned blob and qt1's exact qmref.py in `scratch/reference/qt1`, and the delivered Python modules in `scratch/reference/twocomp` and `scratch/reference/mix`. ```sh git clone https://github.com/benedictbrady/amm-challenge test/scratch/amm-challenge git -C test/scratch/amm-challenge checkout 6b6921f8d463314aa7c96234e1be25a25245f704 # Download K/tools/setup.sh to scratch/setup.sh; from checkout root: sh scratch/setup.sh # Taylor checkout at 4812a638; from research/solved, source absolute env.sh: python3 -I gates.py # All subsequent challenge commands have this prefix: . scratch/env.sh && timeout 470 python scratch/tools/probe.py 4 70000 70005 . scratch/env.sh && timeout 470 amm-match validate scratch/candidate.sol . scratch/env.sh && timeout 470 python scratch/tools/check.py scratch/candidate.sol combog.ComboG 70000 70050 scratch/F.json . scratch/env.sh && timeout 470 python scratch/tools/check.py scratch/candidate.sol combog.ComboG 70014 70025 scratch/F-middle.json . scratch/env.sh && timeout 470 python scratch/tools/check.py scratch/candidate.sol combog.ComboG 70025 70050 scratch/F-tail.json . scratch/env.sh && timeout 470 python3 -I scratch/tools/edges.py 10000 10003 scratch/edges3-final.json . scratch/env.sh && timeout 470 python3 -I scratch/tools/qbatch.py 60000 61024 . scratch/env.sh && timeout 470 python3 -I scratch/tools/qbatch.py 10000 12048 . scratch/env.sh && timeout 470 python scratch/tools/engine.py qt1 9800000 9800032 . scratch/env.sh && timeout 470 python scratch/tools/engine.py candidate 9800000 9800032 ``` ### Frozen unified diff against K/contracts/Candidate.sol ```diff --- a/Strategy.sol +++ b/Strategy.sol @@ -2,6 +2,7 @@ pragma solidity ^0.8.24; import {AMMStrategyBase} from "./AMMStrategyBase.sol"; import {TradeInfo} from "./IAMMStrategy.sol"; +// COMBO offset quoting port; credit Taylor (gtmcknight) for replica and solved policy. // Two-component posterior port; credit Taylor (gtmcknight) for policy, filter and tables. // Policy: Taylor's (gtmcknight) solved game, amm-sim 4812a638, research/solved: Gaussian filter (real.py) + qm tables // (qm_k1e-5.json, +3.77 vs HA on Taylor's replica). Filter, state and timing from trim-1 / port-3. @@ -17,9 +18,10 @@ // Taylor source: https://github.com/gtmcknight/amm-sim/tree/4812a6382311624e1506aca131ca35c378f930d9/research/solved contract Strategy is AMMStrategyBase { int256 constant U=1e18; + uint256 constant GATE=1; int256 constant LN2=693147180559945309; struct Belief { int256 m; int256 v; int256 fb; int256 fa; int256 sp; int256 r; uint256 t; uint256 cnt; bool sy; int256 pi; int256 lp; int256 mt; int256 vt; } - function getName() external pure override returns(string memory) { unchecked {return "TaylorTwoCompQmTrim2";} } + function getName() external pure override returns(string memory) { unchecked {return "TaylorComboGQmTrim2";} } 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;} } @@ -107,8 +109,12 @@ // Clamped cubic B-spline at integer x: span m (coefficients m-3..m) and the 4 nonzero bases N (WAD), Cox-de Boor. function basis(uint256[87] memory W,uint256 base,uint256 ni,uint256 last,uint256 x,int256[4] memory N) internal pure returns(uint256 m){ unchecked { int256 xu=int256(x)*U;int256 lastU=int256(last)*U;uint256 w0=W[base];uint256 w1=W[base+1]; - uint256 q; - while(q>((q&15)<<4))&0xffff)*int256(K64)<=xu)q++; + uint256 q;uint256 hi=ni; + while(q>1; + if(int256(((mid<16?w0:w1)>>((mid&15)<<4))&0xffff)*int256(K64)<=xu)q=mid+1; + else hi=mid; + } m=3+q; int256 l1=xu-kn(w0,w1,ni,lastU,m);int256 r1=kn(w0,w1,ni,lastU,m+1)-xu; int256 l2=xu-kn(w0,w1,ni,lastU,m-1);int256 r2=kn(w0,w1,ni,lastU,m+2)-xu; @@ -117,8 +123,12 @@ } } function basisPair(uint256[87] memory W,uint256 base,uint256 ni,uint256 last,uint256 x,int256[4] memory N,int256[4] memory M) internal pure returns(uint256 m){ unchecked { int256 xu=int256(x)*U;int256 lastU=int256(last)*U;uint256 w0=W[base];uint256 w1=W[base+1]; - uint256 q; - while(q>((q&15)<<4))&0xffff)*int256(K64)<=xu)q++; + uint256 q;uint256 hi=ni; + while(q>1; + if(int256(((mid<16?w0:w1)>>((mid&15)<<4))&0xffff)*int256(K64)<=xu)q=mid+1; + else hi=mid; + } m=3+q; int256 l1=xu-kn(w0,w1,ni,lastU,m);int256 r1=kn(w0,w1,ni,lastU,m+1)-xu; int256 l2=xu-kn(w0,w1,ni,lastU,m-1);int256 r2=kn(w0,w1,ni,lastU,m+2)-xu; @@ -194,22 +204,54 @@ if(sy){T2s(W);return(W,24,14);}T2c(W);return(W,12,8); } } // real.py RealPolicy.lookup: w, r, sd in WAD bps; returns (bid fee, ask fee) in WAD. - function fees(int256 w,int256 r,uint256 ph,bool sy,int256 sd) internal pure returns(int256 fb,int256 fa){ unchecked { - uint256 k;while(k<6&&sd>=S(k+1))k++; - int256 tt=(sd-S(k))*U/(S(k+1)-S(k));if(tt<0)tt=0;if(tt>U)tt=U; + // sd=0 needs only level zero; no interpolation into the next level. + function levels(int256 sd,Ctx memory X) internal pure { unchecked { + uint256 k;int256 tt; + if(sd!=0){while(k<6&&sd>=S(k+1))k++; + tt=(sd-S(k))*U/(S(k+1)-S(k));if(tt<0)tt=0;if(tt>U)tt=U;} + X.tt=tt;bern(k,X.B0);if(tt!=0)bern(k+1,X.B1); + } } + function offsets(int256 w,int256 r,uint256 ph,bool sy,int256 sd) internal pure returns(int256 a,int256 b){ unchecked { + int256 pw=w/5+160*U;if(pw<0)pw=0;if(pw>320*U)pw=320*U; int256 p2;uint256 last; if(ph==0){int256 l2=r/5;if(l2< -6*U)l2=-6*U;if(l2>6*U)l2=6*U;p2=l2+6*U;last=12;}else{p2=pos2(r/5);last=48;} uint256 i=uint256(pw/U);uint256 j=uint256(p2/U);if(i>319)i=319;if(j>last-1)j=last-1; int256 f=pw-int256(i)*U;int256 g=p2-int256(j)*U; - Ctx memory X;(uint256[87] memory W,uint256 nr,uint256 nc)=table(ph,sy);X.nr=nr;X.nc=nc;X.last=last;X.tt=tt;bern(k,X.B0);bern(k+1,X.B1); + Ctx memory X;(uint256[87] memory W,uint256 nr,uint256 nc)=table(ph,sy);X.nr=nr;X.nc=nc;X.last=last;levels(sd,X); (Patch memory P,Patch memory M)=patches(W,X,i,j); int256 Fa=interp(W,X,P,f,g); int256 Fb=interp(W,X,M,U-f,U-g); int256 base=(pw-160*U)*5; - int256 aw=base-w+Fa;int256 bw=w-base+Fb; + return(base+Fa,Fb-base); + } } + function convert(int256 a,int256 b,int256 w) internal pure returns(int256 fb,int256 fa){ unchecked { + int256 aw=a-w;int256 bw=b+w; fa=aw>0?U-exp(-aw/10000):int256(0);fb=bw>0?U-exp(-bw/10000):int256(0); fb=clip(fb,0,U/10);fa=clip(fa,0,U/10); + } } + function quote(Belief memory b,int256 s,bool buy,int256 oldR,uint256 ph,bool mixed) internal pure returns(int256 fb,int256 fa){ unchecked { + int256 ls=ln(s);int256 w=(ls-b.m)*10000; + int256 a;int256 d;uint256 n=mixed?2:1; + int256 lr=mixed?ln(oldR):ln(b.r); + for(uint256 i=0;irival;if(sy)rival=cand; + sd=root(b.vt)*10000; + } + qw=(ls-m)*10000;qr=(rival-m)*10000; + }else {qw=w;qr=(lr-b.m)*10000;phase=ph;sy=b.sy;sd=root(b.v)*10000;} + (int256 ai,int256 bi)=offsets(qw,qr,phase,sy,sd); + if(mixed){int256 weight=i==0?b.pi:U-b.pi;a+=mul(weight,ai);d+=mul(weight,bi);} + else {a=ai;d=bi;} + } + return convert(a,d,w); } } function T0c(uint256[87] memory W) internal pure { unchecked { W[0]=0x2b762af92aaf2a6729f0290226fe2610259925512507248a23b422211e0711d1; @@ -572,9 +614,9 @@ int256 lo=ln(mul(b.sp,U-b.fb));int256 hi=ln(divi(b.sp,U-b.fa)); Mix memory c=Mix(b.pi,b.lp,0,b.mt,b.vt); if(c.p==0){c.p=U;c.m0=c.m1;c.v0=c.v1;} - uint256 n=dt-1;if(n>12)n=12; + uint256 n=dt-1;if(n>9)n=9; for(uint256 i=0;i>128); b.fb=int256(uint256(uint64(p3)));b.fa=int256(uint256(uint64(p3>>64))); b.t=uint64(p3>>128);b.cnt=(p3>>192)&((uint256(1)<<63)-1);b.sy=p3>>255==1; - (b.m,b.v)=moments(b.pi,b.lp,0,b.mt,b.vt); int256 s=int256(t.reserveY*1e18/t.reserveX);bool arb; - if(t.timestamp>b.t)arb=update(b,s,t.isBuy,t.timestamp-b.t); + int256 oldR=b.r;uint256 dt=t.timestamp-b.t; + if(dt>0)arb=update(b,s,t.isBuy,dt); + else (b.m,b.v)=moments(b.pi,b.lp,0,b.mt,b.vt); uint256 ph; if(!arb){ int256 c=t.isBuy?divi(mul(s,U-b.fb),997e15):divi(mul(s,997e15),U-b.fa); if(t.isBuy?cb.r){b.r=c;b.sy=true;} b.cnt++;ph=b.cnt==1?1:2; } - int256 w=(ln(s)-b.m)*10000;int256 r=(ln(b.r)-b.m)*10000; - (b.fb,b.fa)=fees(w,r,ph,b.sy,root(b.v)*10000);b.sp=s;b.t=t.timestamp;save(b); + (b.fb,b.fa)=quote(b,s,t.isBuy,oldR,ph,dt>0&&dt<=GATE&&b.pi>5e15&&b.pi<995e15); + b.sp=s;b.t=t.timestamp;save(b); return(uint256(b.fb),uint256(b.fa)); } } } ``` ### Exact combog.py SHA-256: `683faa2cb163ce59db789c5f169b8d4e258287a3157aa52f54bcc9d3fe7ed36c`. ```python """COMBO = two-component filter + weighted-average offset quoting. Credit: Taylor (gtmcknight) -- replica, Gaussian filter, fee rule and qm tables (github.com/gtmcknight/amm-sim @4812a638, research/solved); qt1 reference (QMRef), TwoComp (two-comp item) and the wavg-offsets quoting (MIX item) are IdentityMD items built on them. Standard library only. Needs twocomp.py (the TC artifact's Code block, diet copy) beside it. usage: from combog import ComboG; ComboG('blob.bin') is a replica2 policy (wants_j). Filter and carried state use the diet TwoComp: DUAL_CUTS=1, silent cap 9. Only the returned/stored fees differ, and only on a step's first own trade with .005 < pi < .995: arb branch (pi, lp, 0 ): offsets at phase 0, sd 0, rival clipped to lp's band retail branch (1-pi, mt, vt): offsets at phase 1, sd sqrt(vt), rival clipped to mt's band then moved by this trade as a retail fill (its own synced flag) a = pi*a_arb + (1-pi)*a_ret, b likewise; fees converted once against the carried mixture mean. Both branches start from the pre-step rival estimate. Nothing is tuned. """ import math from twocomp import TwoComp, SIG2, LD_M, LD_S, MAXF, phi, trunc class ComboG(TwoComp): GATE = 1 def __init__(self, blob_path): super().__init__(blob_path) self.new_path_calls = 0 def lookup_offsets(self, w, w2, phs, sd, synced): """QMRef.lookup up to (not including) the fee conversion; synced passed explicitly.""" 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 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 return a, b 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; mix = None if dt >= 1: # ---- TwoComp filter, unchanged ---- self.cnt = 0 lo = math.log(self.sp * (1 - self.fb)); hi = math.log(self.sp / (1 - self.fa)) prior = self.propagate(dt, lo, hi) lp = math.log(s * (1 - self.fb)) if is_buy else math.log(s / (1 - self.fa)) la = 0.0; Z = 0.0; retail = [] for w, m, v in prior: sd = math.sqrt(v) la += w * phi((lp - m) / sd) / sd z, mt, vt = trunc(m, v, lo, hi) Z += w * z retail.append((w * z, mt, vt)) if Z > 1e-300: ret = [(w / Z, m, v) for w, m, v in retail] mt, vt = self.moments(ret) else: i = max(range(len(prior)), key=lambda i: prior[i][0]) _, mt, vt = retail[i] 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: self.comp = [(pi, lp, 0.), (1 - pi, mt, vt)] if dt <= self.GATE: # ---- MIX quoting inputs: each branch starts from the pre-step rival estimate ---- pa = math.exp(lp); pr = math.exp(mt); old_s2 = self.s2h s2_arb = max(pa * .997, min(pa / .997, old_s2)) s2_ret = max(pr * .997, min(pr / .997, old_s2)) cand_ret = s * (1 - self.fb) / .997 if is_buy else s * .997 / (1 - self.fa) synced_ret = (cand_ret < s2_ret) if is_buy else (cand_ret > s2_ret) if synced_ret: s2_ret = cand_ret mix = (pi, lp, mt, vt, s2_arb, s2_ret, synced_ret) elif is_arb: self.comp = [(1.0, lp, 0.)] else: self.comp = [(1.0, mt, vt)] self.m, self.v = self.moments(self.comp) 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 ls = math.log(s) if mix is None: # every other callback: TwoComp's quote fb, fa = self.lookup((ls - self.m) * 1e4, (math.log(self.s2h) - self.m) * 1e4, ph, math.sqrt(self.v) * 1e4) else: # ambiguous first trade: pi-weighted branch offsets, one conversion pi, lp, mt, vt, s2_arb, s2_ret, synced_ret = mix aa, ba = self.lookup_offsets((ls - lp) * 1e4, (math.log(s2_arb) - lp) * 1e4, 0, 0., False) ar, br = self.lookup_offsets((ls - mt) * 1e4, (math.log(s2_ret) - mt) * 1e4, 1, math.sqrt(vt) * 1e4, synced_ret) a = pi * aa + (1 - pi) * ar; b = pi * ba + (1 - pi) * br w = (ls - self.m) * 1e4 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 self.new_path_calls += 1 self.fb, self.fa = min(MAXF, max(0.0, fb)), min(MAXF, max(0.0, fa)) return fb, fa ``` ### Exact diet twocomp.py SHA-256: `b48ea5cab55f2d9fc141458e74ddfca272a435964afba480d0c2fcb687c61f9d`. ```python # Two-component lattice substitute, adapted from qt1 and Taylor (gtmcknight). """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 class TwoComp(QMRef): """Bounded two-component posterior; Taylor (gtmcknight) fee tables.""" DUAL_CUTS = 1 def __init__(self, blob_path): super().__init__(blob_path) self.comp = [(1.0, self.m, self.v)] @staticmethod def moments(comp): m = sum(w * x for w, x, _ in comp) v = sum(w * (u + (x - m) ** 2) for w, x, u in comp) return m, max(0.0, v) def propagate(self, dt, lo, hi): comp = self.comp for step in range(min(dt - 1, 9)): if step == self.DUAL_CUTS and len(comp) > 1: m, v = self.moments(comp) comp = [(1.0, m, v)] tmp = [] for w, m, v in comp: z, mt, vt = trunc(m, v + SIG2, lo, hi) tmp.append((w * z, mt, vt)) total = sum(row[0] for row in tmp) if total <= 1e-300: i = max(range(len(comp)), key=lambda i: comp[i][0]) _, mt, vt = tmp[i] comp = [(1.0, mt, vt)] else: comp = [(w / total, m, v) for w, m, v in tmp if w > 1e-300] return [(w, m, v + SIG2) for w, m, v in comp] 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)) prior = self.propagate(dt, lo, hi) lp = math.log(s * (1 - self.fb)) if is_buy else math.log(s / (1 - self.fa)) la = 0.0; Z = 0.0; retail = [] for w, m, v in prior: sd = math.sqrt(v) la += w * phi((lp - m) / sd) / sd z, mt, vt = trunc(m, v, lo, hi) Z += w * z retail.append((w * z, mt, vt)) if Z > 1e-300: ret = [(w / Z, m, v) for w, m, v in retail] mt, vt = self.moments(ret) else: i = max(range(len(prior)), key=lambda i: prior[i][0]) _, mt, vt = retail[i] 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: self.comp = [(pi, lp, 0.), (1 - pi, mt, vt)] elif is_arb: self.comp = [(1.0, lp, 0.)] else: self.comp = [(1.0, mt, vt)] self.m, self.v = self.moments(self.comp) 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 ``` ### probe.py ```python # Credit Taylor (gtmcknight): replica, Gaussian filter, policy and tables. import sys,json,time,types from pathlib import Path ROOT=Path(__file__).resolve().parents[1] for d in ['taylor','qt1','twocomp','mix']:sys.path.insert(0,str(ROOT/'reference'/d)) import replica2 as R from check import compiled,fees from amm_competition.evm.executor import EVMStrategyExecutor stage=int(sys.argv[1]);start=int(sys.argv[2]);end=int(sys.argv[3]) if stage<4: src=(ROOT/'reference/twocomp/twocomp.py').read_text().replace('min(dt - 1, 9)','min(dt - 1, 12)') if stage<3:src=src.replace('DUAL_CUTS = 1','DUAL_CUTS = 2') m=types.ModuleType('twocomp');exec(src,m.__dict__);sys.modules['twocomp']=m from combog import ComboG ComboG.GATE=10**9 code=compiled(str(ROOT/f'stage{stage}.sol')) rows={b:dict(n=0,peak=0,seed=None,callback=None,oog=0) for b in ['1','2','3','4','5-6','7-9','10-12','>=13','non-mixed']} def bucket(dt):return str(dt) if dt<=4 else '5-6' if dt<=6 else '7-9' if dt<=9 else '10-12' if dt<=12 else '>=13' def call(e,v,init=False,gas=245000): data=bytes.fromhex('837aef47' if init else 'c2babb57')+b''.join(int(x).to_bytes(32,'big') for x in v) out=e.evm.message_call(caller=e.CALLER_ADDRESS,to=e.deployed_address,calldata=data,value=0,gas=gas) if len(out)!=64:raise RuntimeError(('invalid result',out)) return out beg=time.time();total=0;maxerr=0;failures=[] for seed in range(start,end): e=EVMStrategyExecutor(bytes.fromhex(code['creation']));p=ComboG(str(ROOT/'reference/qt1/blob.bin'));init=p.init;trade=p.on_trade;n=0 def initialize(*args): ref=init(*args);call(e,[100*10**18,10000*10**18],True);return ref def record(*args): global n,total,maxerr dt=args[3]-p.tlast;prev=p.new_path_calls;ref=trade(*args);mix=p.new_path_calls>prev buy,ax,ay,t,x,y,*_=args;v=[buy,int(ax*1e18),int(ay*1e18),t,int(x*1e18),int(y*1e18)] row=rows[bucket(dt) if mix else 'non-mixed'];row['n']+=1 try:out=call(e,v) except Exception as exc: row['oog']+=1;failures.append(dict(seed=seed,callback=n,dt=dt,error=str(exc)));out=call(e,v,gas=1000000) gas=e.evm.result.gas_used if gas>row['peak']:row.update(peak=gas,seed=seed,callback=n) err=max(abs(a-R.clampf(b))*1e4 for a,b in zip(fees(out),ref));maxerr=max(maxerr,err) n+=1;total+=1 return ref p.init=initialize;p.on_trade=record edge=R.run(seed,p)['edge'] data=dict(stage=stage,buckets=rows,callbacks=total,max_error_bps=maxerr,failures=failures,seconds=time.time()-beg,completed_seed=seed,edge=edge) (ROOT/f'probe-stage{stage}-{start}.json').write_text(json.dumps(data,indent=2));print(json.dumps(data),flush=True) ``` ### engine.py ```python # Credit Taylor (gtmcknight): solved policy, Gaussian filter and qm tables. import sys,json,time from pathlib import Path import amm_sim_rs from amm_competition.competition.config import BASELINE_VARIANCE,build_base_config from amm_competition.evm.compiler import SolidityCompiler from check import compiled,HERE import numpy as np kind=sys.argv[1];start,end=map(int,sys.argv[2:4]) assert start>=9800000 and end>start code=compiled('scratch/'+kind+'.sol') s=SolidityCompiler().compile(Path('contracts/src/VanillaStrategy.sol').read_text(),contract_name='VanillaStrategy');assert s.success,s.errors base=build_base_config(seed=None);v=BASELINE_VARIANCE;cfg=[] for seed in range(start,end): rng=np.random.default_rng(seed) size=rng.uniform(v.retail_mean_size_min,v.retail_mean_size_max) rate=rng.uniform(v.retail_arrival_rate_min,v.retail_arrival_rate_max) sig=rng.uniform(v.gbm_sigma_min,v.gbm_sigma_max) cfg.append(amm_sim_rs.SimulationConfig(n_steps=base.n_steps,initial_price=base.initial_price,initial_x=base.initial_x,initial_y=base.initial_y,gbm_mu=base.gbm_mu,gbm_sigma=sig,gbm_dt=base.gbm_dt,retail_arrival_rate=rate,retail_mean_size=size,retail_size_sigma=base.retail_size_sigma,retail_buy_prob=base.retail_buy_prob,seed=seed)) dest=HERE/f'engine-{kind}-{start}-{end}.json';assert not dest.exists(),'seed already consumed for this strategy' dest.write_text(json.dumps(dict(status='started',sha256=code['sha256']))) amm_sim_rs.gas_stats_reset();beg=time.time() batch=amm_sim_rs.run_batch(list(bytes.fromhex(code['creation'])),list(s.bytecode),cfg,8) rows=[dict(seed=r.seed,edge=r.edges['submission'],normalizer_edge=r.edges['normalizer']) for r in batch.results] out=dict(status='done',rows=rows,gas=amm_sim_rs.gas_stats(),seconds=time.time()-beg,sha256=code['sha256']) dest.write_text(json.dumps(out,indent=2));print(json.dumps(out),flush=True) ``` ### qbatch.py ```python # Credit Taylor (gtmcknight): replica, policy and qm tables. from pathlib import Path import sys,json,time,multiprocessing as mp ROOT=Path(__file__).resolve().parents[1] for d in ['taylor','qt1','twocomp','mix']:sys.path.insert(0,str(ROOT/'reference'/d)) import replica2 as R from combog import ComboG from qmref import QMRef DEST=ROOT/'qrows';DEST.mkdir(exist_ok=True) def score(seed): dest=DEST/f'{seed}.json' if dest.exists():return json.loads(dest.read_text()) a=R.run(seed,ComboG(str(ROOT/'reference/qt1/blob.bin')))['edge'] b=R.run(seed,QMRef(str(ROOT/'reference/qt1/blob.bin')))['edge'] row=dict(seed=seed,candidate=a,qt1=b,diff=a-b,gate=ComboG.GATE) dest.write_text(json.dumps(row));return row if __name__=='__main__': start,end=map(int,sys.argv[1:3]);beg=time.time() # Populate immutable table caches before fork, shared across workers. ComboG(str(ROOT/'reference/qt1/blob.bin'));QMRef(str(ROOT/'reference/qt1/blob.bin')) with mp.Pool(8) as pool: for i,row in enumerate(pool.imap_unordered(score,range(start,end)),1): if i%32==0:print(json.dumps(dict(n=i,seed=row['seed'],seconds=time.time()-beg)),flush=True) ```