# gas-basis: Qt1 basis optimization Credit: Taylor (gtmcknight) wrote the solved policy, Gaussian filter, tables and replica. This changes execution of Qt1's spline basis and accumulations, preserving its fee arithmetic. Table compression is qm-spline's; the inherited fixed-point filter is trim-2/port-3's. The unified diff below applies to the complete Solidity block in [Q](https://api.imdnotdead.fun/artifacts/8a6e303b662e1a5ea9bb47f31acedd3988ef65b3ddb66d074517aa59ad41ca40). ## Changes **Useful headroom gain; 40,000-gas target not met.** On the required 32 engine seeds, peak afterSwap falls **206,830 → 196,323** (10,507 saved); mean falls **138,283.123281 → 126,785.559377** (11,497.563904 saved). Both contracts produce exactly the same per-seed edges, not merely within 1e-9. Each has 341,010 successful afterSwap callbacks and zero OutOfGas or other callback errors. The optimized peak leaves 48,677 gas beneath 245,000. Runtime grows by 1,048 bytes to 21,653, beneath 24,576. These are measurements from this run, not board scores or a speedup over all possible inputs. Q's historical peak is 208,775 on a different seed set; the directly paired baseline here is 206,830. Edits, in cumulative order: 1. Move the eight Bernstein weights from `surf` into `fees`, passing the same fixed memory array to ask and bid. They depend only on the shared sd level. All eight original integer expressions remain unchanged. 2. Cache the six surrounding knots; form the Cox–de Boor denominators as knot differences. `(k_right-x)+(x-k_left)` equals `k_right-k_left` exactly in this bounded integer domain. Every division still occurs at its original recursion stage. This edit alone slightly increases gas under the pinned optimizer; it supplies the cached operands used by the pair evaluator. 3. Unroll the four sd-stripe iterations in order 0,1,2,3. Keep the same `stripe`, `row2`, multiplications and accumulation order, removing loop control and dynamic weight indices. 4. Replace the eight fixed-index `Fv` memory accumulators with eight scalar locals. Preserve their update order and all clamp/interpolation divisions. 5. Evaluate each adjacent pair of row/column grid nodes together. Keep Qt1's existing binary span search. When both nodes share the span, reuse the six knot differences and the original first quotient `U/(k_right-k_left)`; independently perform every remaining quotient for each node. If the next node crosses a knot, compute it with the original span-search/recursion path. Do not reuse rounded higher-order basis values between nodes. The endpoint and multiple-knot crossings are covered by the exhaustive test. Per-edit attribution uses a fixed 2,000-callback trace from replica seed 70000 driven by Taylor's original Gaussian+qm policy. It is a diagnostic trace, separate from the final engine sample and Gate F. The following rows are cumulative builds, not independent engine estimates; compiler layout changes make the marginal costs non-additive across other combinations. | Cumulative build | Runtime bytes | Peak gas | Mean gas | Marginal peak saved | Marginal mean saved | |---|---:|---:|---:|---:|---:| | Qt1 | 20605 | 177859 | 126675.5545 | 0 | 0.0000 | | 1: shared weights | 20627 | 176895 | 125675.0620 | 964 | 1000.4925 | | 2: cached knots/denominators | 20633 | 177039 | 125820.7510 | -144 | -145.6890 | | 3: unrolled stripes | 21022 | 167670 | 118237.5170 | 9,369 | 7583.2340 | | 4: scalar accumulators | 21065 | 166832 | 117446.2730 | 838 | 791.2440 | | 5: adjacent-pair basis (final) | 21653 | 167285 | 115221.0570 | -453 | 2225.2160 | The pair evaluator improves mean gas but raises this diagnostic trace's peak by 453 relative to the preceding build. It is retained for its lower mean and shared-basis implementation; no engine comparison against that intermediate build was made. No coefficient-dispatch optimization is included. Checks: - **P:** `. scratch/env.sh && python3 -I ../amm-sim/research/solved/gates.py` reproduced all twelve displayed values from [Taylor's pinned README](https://raw.githubusercontent.com/gtmcknight/amm-sim/4812a6382311624e1506aca131ca35c378f930d9/research/solved/README.md), before any contract changes: | 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 | - **Q:** No new Python policy or fee rule was introduced. Qt1's reference is unchanged, so there is no policy selection on 60000..61023 or new paired policy score on 10000..12047. The item is a gas-only change. - **Basis equivalence:** an audit-only Solidity wrapper compared `baspair` against the literal original `bas` at every possible row/column input used by `surf`: all 1,804 adjacent pairs, 3,608 individual basis evaluations, including all five tables and both axes. Span indices and all eight returned WAD basis entries matched exactly. Audit call: 19,049,511 gas with a test-only 100,000,000 limit; this wrapper is absent from the delivered diff. - **F:** original documented replica seeds 70000..70049, first 2,000 own callbacks each, each trace starting on fresh deployments at 100 X / 10,000 Y. Every Qt1Fast return is byte-identical to Qt1. Maximum error versus the original Q Python reference: **5.825917152673353e-06 bps**. Additional seeds 70100..70149: byte-identical on another 100,000 callbacks, maximum reference error **9.55308224886986e-06 bps**. Both are below 0.01 bps. Replays use integer truncation `int(float*1e18)` and a 245,000-gas call limit. The reference's raw return must be passed through replica `clampf`, just as [the replica does](https://raw.githubusercontent.com/gtmcknight/amm-sim/4812a6382311624e1506aca131ca35c378f930d9/research/solved/replica2.py). - **Validation:** final `amm-match validate contracts/src/Qt1Fast.sol` passes as `TaylorGaussianQMSpline`. No assembly. `contract Strategy is AMMStrategyBase`. solc 0.8.24, optimizer 200 runs, viaIR, Paris, as in the [pinned compiler](https://raw.githubusercontent.com/benedictbrady/amm-challenge/6b6921f8d463314aa7c96234e1be25a25245f704/amm_competition/evm/compiler.py). - **Engine:** each contract runs once, separately against 30 bps VanillaStrategy, using `amm_sim_rs.run_batch(..., 8)`. Exactly seeds 9800256..9800287, one 32-seed chunk per contract; no engine seed reused. `gas_stats_reset()` / `gas_stats()` surround each run. All submission `oog`, `revert`, `other_halt`, `tx_error`, `bad_return` counts are zero. Run times: fast 16.776 s; Qt1 16.303 s. Wall times here are not performance claims. - Config construction uses the exact pinned `MatchRunner._build_configs` method, replacing only `range(self.n_simulations)` with the requested seed interval. Each seed creates its own `default_rng(seed=i)` and makes the same size/rate/sigma draws. This avoids allocating 9.8 million unused configurations in [Taylor's harness](https://raw.githubusercontent.com/gtmcknight/amm-sim/4812a6382311624e1506aca131ca35c378f930d9/harness.py); full engine-driver source is included below. No simulation prefix is skipped inside a selected seed. Qt1 source SHA-256: `c68887cff61180e12ba2b1ceb333edf76a830f91f63b5d775a8806fb9ec08aca` (42,990 bytes, matches Q). Final Qt1Fast SHA-256: `0f1275e59f70daed05931b0c54ac5b09f08e11de19fccdda2ffa257a816c712f`. Wheel's loaded shared-library SHA-256: `ff88b6353c2aad7342f0a26194f7347e78b9c3b38d683a7449006d423978cd14`, matching the pinned setup script. ```json { "approach": "basis", "seeds": { "start": 9800256, "end_inclusive": 9800287 }, "n": 32, "runtime_bytes": { "qt1": 20605, "fast": 21653 }, "gas": { "qt1": { "afterSwap": { "calls": 341010, "oog": 0, "peak": 206830, "mean": 138283.1232808422 }, "afterInitialize": { "peak": 90858 } }, "fast": { "afterSwap": { "calls": 341010, "oog": 0, "peak": 196323, "mean": 126785.55937655787 }, "afterInitialize": { "peak": 90931 } } }, "edges_identical": true, "mean_diff": 0.0, "differing_seeds": [], "paired": { "n": 32, "mean_diff": 0.0, "se": 0.0, "worst5": [ { "seed": 9800256, "diff": 0.0 }, { "seed": 9800257, "diff": 0.0 }, { "seed": 9800258, "diff": 0.0 }, { "seed": 9800259, "diff": 0.0 }, { "seed": 9800260, "diff": 0.0 } ] }, "gate_P": "pass", "gate_F": { "seeds": [ 70000, 70049 ], "callbacks": 100000, "nonidentical_fee_returns": 0, "max_abs_fee_error_bps": 5.825917152673353e-06 }, "additional_fee_check": { "seeds": [ 70100, 70149 ], "callbacks": 100000, "nonidentical_fee_returns": 0, "max_abs_fee_error_bps": 9.55308224886986e-06 }, "basis_grid_pairs_checked": 1804, "target_peak_saving": 40000, "measured_peak_saving": 10507, "target_met": false, "blocked": null } ``` ## Code Unified diff against Q’s exact `Qt1.sol`; apply it as `Qt1Fast.sol` beside the unchanged challenge base contracts. Taylor’s original header and contract name remain. ```diff --- Qt1.sol +++ Qt1Fast.sol @@ -4,6 +4,7 @@ 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. +// Basis gas optimization: cached knot differences, shared sd weights, unrolled stripe contractions. // 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 @@ -95,11 +96,44 @@ // 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; + basAt(K0,K1,m,x,N); + } } + function basAt(uint256 K0,uint256 K1,uint256 m,int256 x,int256[4] memory N) internal pure { unchecked { + int256 km=kn(K0,K1,m);int256 kp1=kn(K0,K1,m+1); + int256 km1=kn(K0,K1,m-1);int256 kp2=kn(K0,K1,m+2); + int256 km2=kn(K0,K1,m-2);int256 kp3=kn(K0,K1,m+3); + int256 l1=x-km;int256 l2=x-km1;int256 l3=x-km2; + int256 r1=kp1-x;int256 r2=kp2-x;int256 r3=kp3-x; + int256 tp=U/(kp1-km);int256 n0=r1*tp;int256 n1=l1*tp; + tp=n0/(kp1-km1);n0=r1*tp;int256 sv=l2*tp;tp=n1/(kp2-km);n1=sv+r2*tp;int256 n2=l1*tp; + tp=n0/(kp1-km2);N[0]=r1*tp;sv=l3*tp;tp=n1/(kp2-km1);N[1]=sv+r2*tp;sv=l2*tp;tp=n2/(kp3-km);N[2]=sv+r3*tp;N[3]=l1*tp; + } } + // Adjacent grid nodes often share a knot span and all six denominators. + // Keep each quotient at exactly the original location in the recursion. + function baspair(uint256 K0,uint256 K1,uint256 n,int256 x,int256[4] memory N0,int256[4] memory N1) internal pure returns(uint256 m,uint256 d){ 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 kp1=kn(K0,K1,m+1); + int256 km=kn(K0,K1,m);int256 km1=kn(K0,K1,m-1);int256 km2=kn(K0,K1,m-2); + int256 kp2=kn(K0,K1,m+2);int256 kp3=kn(K0,K1,m+3); + int256 t0=U/(kp1-km); + int256 d1=kp1-km1;int256 d2=kp2-km;int256 d3=kp1-km2;int256 d4=kp2-km1;int256 d5=kp3-km; + { + int256 l1=x-km;int256 l2=x-km1;int256 l3=x-km2; + int256 r1=kp1-x;int256 r2=kp2-x;int256 r3=kp3-x; + int256 n0=r1*t0;int256 n1=l1*t0; + int256 tp=n0/d1;n0=r1*tp;int256 sv=l2*tp;tp=n1/d2;n1=sv+r2*tp;int256 n2=l1*tp; + tp=n0/d3;N0[0]=r1*tp;sv=l3*tp;tp=n1/d4;N0[1]=sv+r2*tp;sv=l2*tp;tp=n2/d5;N0[2]=sv+r3*tp;N0[3]=l1*tp; + } + if(x+64>=kp1 && m319)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); + (uint256 mi,uint256 dr)=baspair(KR0,KR1,nr,int256(i*64),A0,A1); + (uint256 mj,uint256 dc)=baspair(KC0,KC1,nc,int256(j*64),C0,C1); // Fv[l*4 + rownode*2 + colnode] - int256[8] memory Fv; + int256 f0;int256 f1;int256 f2;int256 f3;int256 f4;int256 f5;int256 f6;int256 f7; uint256 i0=base+(mi-3)*nc+mj-3;uint256 sn=nr*nc; for(uint256 q=0;q=dr&&q=dr&&q0?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); } } ``` ## Commands All paths below are relative to the workspace unless stated otherwise. All checkouts, installed dependencies, generated source variants, logs and test scaffolding were confined to `test/scratch/` (the explicitly disposable area). Inside the challenge checkout, state is under its `scratch/`. No root `scratch/amm-challenge` was created. Only this report and `sources.json` are delivered. No dependency is added to the delivered strategy; the diff uses the existing challenge imports. Command inventory (shell read commands are grouped; generated heredoc payloads are described, with the final checking programs reproduced below): 1. `pwd && git status --short && mkdir -p test/scratch artifacts/goal/batches/e1-gas-spline/items/gas-basis && git clone https://github.com/benedictbrady/amm-challenge test/scratch/amm-challenge && git -C test/scratch/amm-challenge checkout 6b6921f8d463314aa7c96234e1be25a25245f704 && git clone https://github.com/gtmcknight/amm-sim test/scratch/amm-sim && git -C test/scratch/amm-sim checkout 4812a6382311624e1506aca131ca35c378f930d9`. 2. `curl -fLsS https://api.imdnotdead.fun/artifacts/8a6e303b662e1a5ea9bb47f31acedd3988ef65b3ddb66d074517aa59ad41ca40 -o test/scratch/Q`; `sed -n '1,180p' test/scratch/amm-sim/setup-fast.sh`; `head -c 1600 test/scratch/Q`. 3. From `test/scratch/amm-challenge`: `sh ../amm-sim/setup-fast.sh > ../setup.log 2>&1`. Success; used the item-specific pinned setup command once. 4. Setup/source reads: `tail -20 test/scratch/setup.log`; `rg -n '^## (Contract design|Notes and limits|Strategy.sol)' test/scratch/Q`; `sed -n '45,70p' test/scratch/Q`; `sed -n '115,130p' test/scratch/Q`; `cat test/scratch/amm-sim/harness.py`. 5. A `python3` heredoc extracted the first fenced Solidity block from Q, printed its length/SHA-256, and wrote identical `contracts/src/Qt1.sol` and `Qt1Fast.sol` under the disposable checkout. `rg -n 'function (basis|surf|lookup|node)|Bern|343|knots' .../Qt1.sol`; `sed -n '1,160p' .../Qt1.sol` read the implementation. 6. `rg -n 'surf\(|bern\(|function afterSwap|k=' .../Qt1.sol`; `ls test/scratch/amm-sim/research/solved`; `cat test/scratch/setup.log`; `sed -n '1,100p' test/scratch/amm-sim/research/solved/gates.py`. 7. From the challenge checkout: `. scratch/env.sh && python3 -I ../amm-sim/research/solved/gates.py > scratch/gates.log 2>&1`. Further reads: `sed -n '160,180p' .../Qt1.sol`; `cat .../research/solved/README.md | head -65`; `sed -n '1,160p' .../amm_competition/evm/compiler.py`. 8. A `cat > test/scratch/edit.py` heredoc wrote the initial transformation script (weights, cached knots, unrolled stripes); `python3 test/scratch/edit.py`; `cat .../scratch/gates.log`. 9. `rg -n 'EVM\(|deploy|message_call|calldata' .../amm_competition/evm -g '*.py'`; `rg -n '10000|448.261189' test/scratch/amm-sim -g '*.md' | head -12`; `. test/scratch/amm-challenge/scratch/env.sh && amm-match validate test/scratch/amm-challenge/contracts/src/Qt1Fast.sol > test/scratch/validate.log 2>&1`. 10. Reads: `sed -n '1,115p' .../evm/executor.py`; `sed -n '1,140p' .../research/solved/trace.py`; `rg -n '^##|^```' test/scratch/Q | tail -12`; `sed -n '1,80p' .../research/solved/replica2.py`; `tail -10 test/scratch/validate.log`. 11. Created `scratch/probe.py` by heredoc. The first write incorrectly used the workspace-relative destination while already inside the challenge checkout and failed with “No such file or directory”; its attempted `python scratch/probe.py` also failed. Reissued with the correct checkout-relative path. Final probe source is reproduced below. `. scratch/env.sh && python scratch/probe.py > scratch/probe.log 2>&1` compiled/deployed both contracts and replayed 2,000 callbacks. 12. Diagnostic reads: `tail -10 .../scratch/probe.log`; `sed -n '354,410p' test/scratch/Q`; `sed -n '470,512p' test/scratch/Q`. 13. `curl -fLsS https://api.imdnotdead.fun/artifacts/17d249ab0c33fc44931d9b105cf3f9e3846a560bd518b67310c2a56defacdecc -o test/scratch/spline.md`; `tail -5 .../scratch/probe.log`; `rg -n 'base64|QMS1|```|blob' test/scratch/spline.md | head -20`. 14. `cp .../Qt1Fast.sol test/scratch/v1.sol`; a `python3` heredoc replaced `Fv[0..7]` with scalar locals; from the checkout, `. scratch/env.sh && python scratch/probe.py > scratch/probe2.log 2>&1`. 15. Reads: `tail -8 .../scratch/probe.log`; `sed -n '247,253p' test/scratch/spline.md`; `sed -n '410,450p' test/scratch/Q`; `sed -n '1,130p' .../competition/match.py | tail -35`; `tail -4 .../scratch/probe2.log`. A `python3` heredoc extracted Q's Python reference as `scratch/qmref.py` and decoded the spline artifact's base64 to `scratch/blob.bin`, printing the verified blob length/hash. 16. `cp .../Qt1Fast.sol test/scratch/v2.sol`; `cat > test/scratch/pair.py` generated the adjacent-pair evaluator; `python3 test/scratch/pair.py`; `. scratch/env.sh && python scratch/probe.py > scratch/probe3.log 2>&1` from checkout. 17. Reads: `sed -n '105,165p' .../competition/match.py`; `tail -4 .../scratch/probe3.log`; `cat .../competition/config.py | head -120`. 18. `cp .../Qt1Fast.sol test/scratch/v3.sol`; a `python3` heredoc split out `basAt` and removed a redundant first-node span search in the fallback; `. scratch/env.sh && python scratch/probe.py > scratch/probe4.log 2>&1`. 19. `tail -4 .../scratch/probe4.log`; created `scratch/gatef.py` by heredoc. A subsequent `python3` heredoc added the v2 diagnostic comparator and per-seed gas sums. `. scratch/env.sh && python scratch/gatef.py 70000 70010 > scratch/gatef-70000.log 2>&1`. 20. `tail -12 .../scratch/gatef-70000.log`; created `scratch/engine.py` by heredoc. `. scratch/env.sh && python scratch/gatef.py 70010 70020 > scratch/gatef-70010.log 2>&1`; a `python3` heredoc aggregated these diagnostic gas statistics. 21. `cp .../Qt1Fast.sol test/scratch/v4.sol`; a `python3` heredoc moved the span-crossing fallback after completing node zero (final version); `. scratch/env.sh && python scratch/probe.py > scratch/probe5.log 2>&1`. 22. Reads: `tail -5 .../scratch/probe5.log`; `tail -3 .../scratch/gatef-70010.log`; `git status --short`; `cat .../scratch/probe5.log`; `sed -n '95,170p' .../Qt1Fast.sol`. 23. `. scratch/env.sh && python scratch/gatef.py 70100 70150 > scratch/gatef-final.log 2>&1`; `. scratch/env.sh && amm-match validate contracts/src/Qt1Fast.sol > scratch/validate-final.log 2>&1`. Created `scratch/basischeck.py` and ran `. scratch/env.sh && python scratch/basischeck.py > scratch/basischeck.log 2>&1` (first attempt failed for missing optional `Crypto` import). 24. Read the three check logs with `tail`; read the first two Gate F log lines with `head -2`; `python3` heredocs inspected failing per-seed rows. `rg -n 'keccak' .../.venv/lib/python3.12/site-packages/eth_utils/crypto.py` found no such package. 25. `command -v cast`; `cast sig 'auditBasis()' > .../scratch/audit.selector`; a `python3` heredoc changed the test to read that selector instead of importing Crypto; reran `. scratch/env.sh && python scratch/basischeck.py > scratch/basischeck.log 2>&1` (passed). 26. `. scratch/env.sh && python scratch/gatef.py 70000 70050 > scratch/gatef-original-set.log 2>&1`; `cat .../scratch/basischeck.log`; a `python3` heredoc inspected additional-set gas peaks/means. 27. **Only engine command:** `. scratch/env.sh && python scratch/engine.py contracts/src/Qt1Fast.sol 9800256 9800288 scratch/engine-final.json --other contracts/src/Qt1.sol > scratch/engine-final.log 2>&1`. No rerun. `tail -5 .../scratch/gatef-original-set.log`; a `python3` heredoc wrote `test/scratch/final.diff` with `difflib.unified_diff`. 28. Reads: `head -2 .../scratch/gatef-original-set.log`; `python3` inspection of failing reference rows; `sed -n '180,250p' .../Qt1.sol`; `sed -n '445,475p' test/scratch/Q`. Created and ran `scratch/diagnose.py` to print the first large reference deviation and preceding five callbacks on seed 70026. Read with `cat .../scratch/diagnose.log`; inspected engine output with `tail -12 .../scratch/engine-final.log` and `cat .../scratch/engine-final.json | head -100`. 29. A `python3` heredoc corrected Gate F expected fees to `tuple(R.clampf(v) for v in r)`, matching replica behavior. Reran both corrected tests: `. scratch/env.sh && python scratch/gatef.py 70000 70050 > scratch/gatef-original-set.log 2>&1` and `. scratch/env.sh && python scratch/gatef.py 70100 70150 > scratch/gatef-final.log 2>&1`. Both passed. These are replica replays, not repeated engine seeds. 30. Created `scratch/ablation.py` by heredoc; `. scratch/env.sh && python scratch/ablation.py > scratch/ablation.log 2>&1`. This builds weights-only/cached-knots variants from Qt1 and replays the fixed diagnostic trace on all six cumulative builds. 31. Read both Gate F logs with `tail -2`; a `python3` heredoc printed final submission gas rows and paired statistics. `tail -25 .../scratch/ablation.log`; a `python3` urllib heredoc fetched the six pinned raw source URLs listed in `sources.json` into `test/scratch/source-*`, confirming URL availability. 32. `cat .../scratch/ablation.json`; `tail -1` of both final Gate F logs; `git status --short --untracked-files=all`. 33. Created `test/scratch/write_result.py` (this report/source-manifest generator), then `python3 test/scratch/write_result.py`. Its final checks parse the manifest and fenced result JSON, verify byte limits and required keys, match every quote against its fetched source, check the diff/source hashes, and inspect Git paths. Final verification commands are documented below their script listing. Here `.../Qt1*.sol` expands to `test/scratch/amm-challenge/contracts/src/Qt1*.sol`, `.../scratch/*` to that checkout's `scratch/*`, and other abbreviated implementation paths to the pinned checkout named in the preceding read. `https://api.imdnotdead.fun/artifacts/8a6e303b662e1a5ea9bb47f31acedd3988ef65b3ddb66d074517aa59ad41ca40` and `https://api.imdnotdead.fun/artifacts/17d249ab0c33fc44931d9b105cf3f9e3846a560bd518b67310c2a56defacdecc` denote the linked artifact URLs. Shell output was polled through the process tool while compilation/check commands ran; those polls launch no further commands. No timer sleeps, engine reruns, commits, configuration edits outside disposable scaffolding, or Git additions occurred. ### Final check programs The following programs are the final local scaffolding used for the reported checks, included to make the measurements reviewable. They are not part of the strategy and require the task's pinned setup. `compiled` caches results by source SHA-256. Gate F also evaluates the v2 diagnostic intermediate; index 0 is Qt1, index 1 is the delivered final contract, index 2 is that intermediate. The final expected-fee comparison uses replica-clamped fees. `scratch/probe.py`: ```python # Policy and replica by Taylor (gtmcknight). import sys,json,pickle,hashlib from pathlib import Path sys.path.insert(0,str(Path('../amm-sim/research/solved').resolve())) import replica2 as R,real from evalpol import load from amm_competition.evm.compiler import SolidityCompiler from amm_competition.evm.executor import EVMStrategyExecutor as E def compiled(path): s=Path(path).read_text(); p=Path('scratch/'+hashlib.sha256(s.encode()).hexdigest()+'.pkl') if p.exists():return pickle.loads(p.read_bytes()) c=SolidityCompiler().compile(s);assert c.success,c.errors;p.write_bytes(pickle.dumps(c));return c def call(e,data): r=e.evm.message_call(caller=e.CALLER_ADDRESS,to=e.deployed_address,calldata=data,gas=245000) return bytes(r),e.evm.result.gas_used def enc(values,sel):return bytes.fromhex(sel)+b''.join(int(x).to_bytes(32,'big') for x in values) class Tr(real.RealPolicy): def on_trade(self,is_buy,ax,ay,t,x,y,*args): o=super().on_trade(is_buy,ax,ay,t,x,y,*args) if len(self.tr)<2000:self.tr.append(enc([is_buy,int(ax*1e18),int(ay*1e18),t,int(x*1e18),int(y*1e18)],'c2babb57')) return o if __name__=='__main__': p=Tr(load('../amm-sim/research/solved/pol_mid.json'),{'soft':1.,'qm':'../amm-sim/research/solved/qm_k1e-5.json'});p.tr=[];R.run(70000,p) Path('scratch/trace.pkl').write_bytes(pickle.dumps(p.tr)) cs=[compiled('contracts/src/'+x+'.sol') for x in ['Qt1','Qt1Fast']];es=[E(c.bytecode) for c in cs] for e in es:call(e,enc([100*10**18,10000*10**18],'837aef47')) gs=[[],[]] for data in p.tr: rs=[call(e,data) for e in es];assert rs[0][0]==rs[1][0] for i,r in enumerate(rs):gs[i].append(r[1]) print(json.dumps({'runtime':[len(c.deployed_bytecode) for c in cs],'gas': [{'peak':max(g),'mean':sum(g)/len(g)} for g in gs],'n':len(p.tr)})) ``` `scratch/gatef.py`: ```python # Reference and replica by Taylor (gtmcknight); differential audit. import sys,json,pickle,multiprocessing as mp from pathlib import Path from probe import compiled,E,call,enc,R from qmref import QMRef class Done(Exception):pass class Trace(QMRef): def on_trade(self,is_buy,ax,ay,t,x,y,*args): r=super().on_trade(is_buy,ax,ay,t,x,y,*args) self.tr.append((enc([is_buy,int(ax*1e18),int(ay*1e18),t,int(x*1e18),int(y*1e18)],'c2babb57'),tuple(R.clampf(v) for v in r))) if len(self.tr)==2000:raise Done() return r def work(seed): p=Trace('scratch/blob.bin');p.tr=[] try:R.run(seed,p) except Done:pass assert len(p.tr)==2000 es=[E(c.bytecode) for c in cs] for e in es:call(e,enc([100*10**18,10000*10**18],'837aef47')) mx=0.;neq=0;gas=[[] for c in cs] for data,ref in p.tr: rs=[call(e,data) for e in es] neq+=any(r[0]!=rs[0][0] for r in rs[1:]) for b in range(2): actual=int.from_bytes(rs[1][0][b*32:(b+1)*32],'big')/1e18 mx=max(mx,abs(actual-ref[b])*1e4) for i,r in enumerate(rs):gas[i].append(r[1]) return {'seed':seed,'n':len(p.tr),'nonidentical':neq,'max_ref_diff_bps':mx,'gas_peak':[max(g) for g in gas],'gas_sum':[sum(g) for g in gas]} if __name__=='__main__': cs=[compiled('contracts/src/'+x+'.sol') for x in ['Qt1','Qt1Fast']]+[compiled('../v2.sol')] QMRef('scratch/blob.bin') s0,s1=map(int,sys.argv[1:3]) with mp.get_context('fork').Pool(8) as pool:rows=pool.map(work,range(s0,s1)) out={'rows':rows,'n':sum(x['n'] for x in rows),'nonidentical':sum(x['nonidentical'] for x in rows),'max_ref_diff_bps':max(x['max_ref_diff_bps'] for x in rows)} Path(f'scratch/gatef-{s0}.json').write_text(json.dumps(out,indent=2));print(json.dumps({k:v for k,v in out.items() if k!='rows'})) assert out['nonidentical']==0 and out['max_ref_diff_bps']<.01 ``` `scratch/engine.py`: ```python # Taylor (gtmcknight)'s harness; range-only config allocation optimization. import sys,inspect,textwrap,json from pathlib import Path sys.path.insert(0,str(Path('../amm-sim').resolve())) import harness as H from probe import compiled def build_configs(s0,s1): # Execute the pinned method unchanged except its seed range; skip unused prefixes. src=textwrap.dedent(inspect.getsource(H.MatchRunner._build_configs)) src=src.replace('range(self.n_simulations)',f'range({s0}, {s1})') ns=dict(sys.modules[H.MatchRunner.__module__].__dict__) exec(src,ns) runner=H.MatchRunner(n_simulations=s1,config=H.build_base_config(seed=None),n_workers=8,variance=H.BASELINE_VARIANCE) cfgs=ns['_build_configs'](runner) assert [c.seed for c in cfgs]==list(range(s0,s1)) return cfgs def compile_src(path): c=compiled(path) return Path(path).read_text(),list(c.bytecode),0. H.build_configs=build_configs H.compile_src=compile_src if __name__=='__main__':H.main() ``` `scratch/basischeck.py`: ```python # Exhaustive adjacent-grid basis differential test; policy by Taylor (gtmcknight). from pathlib import Path from probe import compiled,E,call,enc s=Path('contracts/src/Qt1Fast.sol').read_text() o=Path('contracts/src/Qt1.sol').read_text();old=o[o.index(' function bas('):o.index(' // nC consecutive')].replace('function bas(', 'function legacy(') audit=''' function auditBasis() external pure returns(uint256 count) { unchecked { for(uint256 t=0;t<5;t++){ (uint256 R0,uint256 R1,uint256 C0,uint256 C1,uint256 nr,uint256 nc,)=tab(t); for(uint256 axis=0;axis<2;axis++){ uint256 K0=axis==0?R0:C0;uint256 K1=axis==0?R1:C1;uint256 n=axis==0?nr:nc; uint256 end=axis==0?320:(t==0?12:48); for(uint256 i=0;i