# gd-ab-1 — ComboG gas diet, frozen GATE=1 Credit: Taylor (gtmcknight), original solved Gaussian filter, qm tables, fee policy, and replica (`amm-sim` commit `4812a6382311624e1506aca131ca35c378f930d9`). COMBO and the TwoComp port build on that work. Local result: mixed dt=1 fits the **205,000 pyrevm gas** budget on seeds 70000..70004. Frozen runtime is **22,058 bytes**. Gate P, effective-fee F (50 × 2,000 callbacks), and `amm-match validate` pass. No board score or board submission is claimed. All figures below are measurements from this run unless explicitly attributed to an input. ## Platform, setup, and Gate P Platform: `Linux x86_64`. Cloned the challenge at `6b6921f8d463314aa7c96234e1be25a25245f704` under disposable `test/scratch/amm-challenge`; all working state was inside that tree or its sibling `test/scratch/taylor`. Ran the exact pinned [K/tools/setup.sh](https://raw.githubusercontent.com/identity-md-launches/goal-3170-beat-network-s-amm-entry/4eb3e985fd31e3cd17832501b95b6d2491aca73d/tools/setup.sh) once as `sh scratch/setup.sh` from the checkout root. Setup succeeded, including solc 0.8.24, StarterStrategy validation, and engine shared-object SHA-256 `ff88b6353c2aad7342f0a26194f7347e78b9c3b38d683a7449006d423978cd14`. No setup blocker. Every long command was bounded with `timeout 470` (below eight minutes). Before editing policy code, plain `python3 -I gates.py` in Taylor’s pinned `research/solved` reproduced [gates.py](https://raw.githubusercontent.com/gtmcknight/amm-sim/4812a6382311624e1506aca131ca35c378f930d9/research/solved/gates.py): ```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 ``` ## Inputs and fee-identical gas changes [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`. Applying [P’s unified diff](https://api.imdnotdead.fun/artifacts/4cc25dfb91f2ca8a957de08c6a38bbd3e4aed7fb288be8242e5677ea77bbf0b1) with `patch -p1` reproduced P’s ungated port source `e4c64fa8e2e797ba6154d2436cc883f7ca8065cf26afd2d2fa5e3aaa2c97d93e`, runtime 21,853 bytes. Its seed-70000 mixed dt=1 peak was 215,761 at callback 2020. P’s 216,964 figure reproduced separately on seed **70001**, callback 11606; that is also the seed recorded in P’s table. It is not seed 70000’s peak. Measured each stage on a complete seed-70000 replay with the same ungated Python reference. Savings below compare the maximum mixed dt=1 gas at each stage; the maximizing callback can change. Positive saving means less gas. | Stage | Change | dt=1 peak | Saving vs previous | Runtime bytes | Peak callback | |---|---|---:|---:|---:|---:| | baseline | P port | 215761 | — | 21853 | 2020 | | diet-0 | Grid memory struct + sdBasis helper (compiler support) | 216724 | -963 | 21988 | 2020 | | diet-a | (a) sd=0 phase-0 shortcut; omit unused k+1 Bernstein | 215710 | 1014 | 21910 | 2020 | | diet-b | (b) SP upper-bound span searches | 210087 | 5623 | 21930 | 6713 | | diet-c | (c) zero-sd coefficient shortcut | 201077 | 9010 | 22061 | 6713 | | diet-d | Rejected: reuse table buffer, clearing omitted W[1] | 201294 | -217 | 22209 | 6713 | Retained baseline→C saving: **14,684 gas**. The support refactor costs 963 gas; (a) saves 1,014 relative to that control (net 51 relative to P); (b) saves 5,623; (c) saves 9,010. D regressed by 217 on seed 70000 (227 at the five-seed dt=1 maximum) and is excluded from the frozen contract. The direct (a) edit initially hit solc’s Yul stack limit; splitting the shared quote loop compiled to 31,289 bytes and was rejected. The retained `Grid` struct shortens live scalar lifetimes while preserving P’s single shared lookup loop. It changes no storage. The source hashes below distinguish these successful stages from the abandoned compilations. | Stage | Source SHA-256 | |---|---| | baseline | `e4c64fa8e2e797ba6154d2436cc883f7ca8065cf26afd2d2fa5e3aaa2c97d93e` | | diet-0 | `936e25fa07bbed91f6434f263611a740737c7edc6c618c2bac67c05719081068` | | diet-a | `a046098b8a890c4fda658ebfa5ca9e72dbf3c6f0738bf25ef77b3628671ce8cd` | | diet-b | `3555d42ae39f0ab23af261382b978e3d6839fa46efd8d19c3f6381ce8b19136b` | | diet-c | `271d61832dfa4c1faedb3f8b903be064abd4ae4da056f6f8c63596312234b386` | | diet-d | `9d74f99e8019fd521cc692c1365de9503ecf50b76a6c47cce30378ba989e2f5a` | Every successful stage produced the **same 8,987-callback fee-output SHA-256** on seed 70000: `d7b04c61ff32f7eaf576340366ef353084929133c0313f3ae8d437b4f2647ce6`. The five-seed ungated C and rejected D runs also have identical aggregate fee-output SHA-256 `53710c6607f376b55db85f6253ed808f56beb7ed7dbaff63297c52f9b49520d0`. These hashes concatenate both 32-byte returned fees for every afterSwap callback, in seed/callback order; initialization is excluded. Why the trims preserve fees: (a) when `ph==0 && sd==0`, the original search gives k=0 and tt=0, so `B0=(U,0,0,0)` and B1 cannot contribute. Other tt=0 lookups also omit the unused B1 construction. (b) [SP’s patch](https://api.imdnotdead.fun/artifacts/cc5f5917337662ddf10ac494ed6593d06322b46d50fb475b99108cb9f3f15686) computes the same upper bound over packed knots, including equality advancing to the next span. (c) only when `!two && B0[0]==U`, replace the coefficient combination `U*c0+0*c1+0*c2+0*c3` by `U*c0`; preserve every node sum, clamp, division, spline basis calculation, bilinear operation, table word and fee conversion. In the general case both sd evaluations remain. No assembly or new storage is introduced. ## Complete ungated gas probe and gate selection C was probed **ungated** (contract GATE=1,000,000,000; matching Python class), on all five complete replica runs, seeds 70000..70004, with a fresh deployment per seed. Every callback first received 245,000 gas. The harness below retries an OOG with 1,000,000 gas while retaining the failure count; no recovery was needed. Callback indices are zero-based. Peaks are pyrevm `result.gas_used`, not engine transaction gas. | dt bucket | Mixed callbacks | Peak gas | Peak seed | Peak callback | OOG | |---|---:|---:|---:|---:|---:| | 1 | 21500 | 203136 | 70004 | 8342 | 0 | | 2 | 4103 | 208069 | 70004 | 2905 | 0 | | 3 | 1657 | 207200 | 70003 | 2587 | 0 | | 4 | 715 | 206025 | 70004 | 2365 | 0 | | 5-6 | 509 | 218148 | 70003 | 975 | 0 | | 7-9 | 149 | 225296 | 70000 | 983 | 0 | | 10-12 | 25 | 237385 | 70002 | 2486 | 0 | | >=13 | 8 | 235607 | 70004 | 8392 | 0 | Total callbacks: 51801; non-mixed: 23135; non-mixed peak: **166518**; non-mixed OOG: 0; all OOG: 0. Ungated overall peak: 237385. Largest incidental effective-fee error: 2.5179387828228e-06 bps (seed 70004, callback 2030). **Selected GATE=1**, the largest admissible member of `{1,2,3,4,6,9,ungated}`: dt=1’s 203,136 and the non-mixed 166,518 both fit 205,000. Every larger gate includes dt=2, whose 208,069 fails. Larger buckets also exceed the target. Gate choice used gas only. Set the same `GATE=1` in Solidity and as `ComboG.GATE`; the fallback “none fits” branch was not needed. ## Frozen contract and F Source SHA-256: `f904a486b1dcfbd6fcf40aa48920d1bb6b79ad2ac1c99a2cbbb16d4272c2c616`. Runtime: **22,058 bytes** (limit 24,576). Compiler: pinned [challenge compiler](https://raw.githubusercontent.com/benedictbrady/amm-challenge/6b6921f8d463314aa7c96234e1be25a25245f704/amm_competition/evm/compiler.py), solc 0.8.24, optimizer 200 runs, viaIR, Paris. `amm-match validate scratch/candidate.sol`: PASS, `Strategy 'TaylorComboGQmTrim2' validated successfully!`. F used [K/tools/check.py](https://raw.githubusercontent.com/identity-md-launches/goal-3170-beat-network-s-amm-entry/4eb3e985fd31e3cd17832501b95b6d2491aca73d/tools/check.py) with its effective-fee comparison against the reference clamped to [0,0.1]. Only diagnostic bookkeeping was added: record the callback at the running maximum and report `oog=0` on completed seeds; any call exception still aborts. There is no recovery in F. ```json { "pass": true, "seeds": "[70000,70050)", "callbacks": 100000, "max_bps": 3.0968576748141574e-06, "seed": 70003, "callback": 655, "pyrevm_peak": 203056, "peak_seed": 70042, "oog": 0, "seconds": 106.1876745223999 } ``` Per-seed F maxima (bps) and pyrevm peaks; each row has exactly 2,000 callbacks and zero OOG: | Seed | Max bps | Peak gas | |---:|---:|---:| | 70000 | 1.23008846165e-06 | 194695 | | 70001 | 1.25828750631e-06 | 201133 | | 70002 | 1.6273774342e-06 | 201320 | | 70003 | 3.09685767481e-06 | 200655 | | 70004 | 1.56127663315e-06 | 193997 | | 70005 | 1.29077812458e-06 | 201168 | | 70006 | 1.60222788596e-06 | 194128 | | 70007 | 1.4619280439e-06 | 192611 | | 70008 | 1.2764931473e-06 | 200790 | | 70009 | 1.11413981773e-06 | 202539 | | 70010 | 1.34741997291e-06 | 200717 | | 70011 | 1.31453592803e-06 | 200718 | | 70012 | 1.24099796411e-06 | 200591 | | 70013 | 1.10497465344e-06 | 200674 | | 70014 | 1.87480423764e-06 | 200588 | | 70015 | 1.21012839289e-06 | 199853 | | 70016 | 1.94863760544e-06 | 193277 | | 70017 | 1.04452080665e-06 | 200186 | | 70018 | 1.66559169235e-06 | 190807 | | 70019 | 1.14521333389e-06 | 200575 | | 70020 | 1.89813478303e-06 | 200345 | | 70021 | 2.1809881505e-06 | 200802 | | 70022 | 1.78298439164e-06 | 200727 | | 70023 | 1.81240802748e-06 | 200365 | | 70024 | 1.51269344707e-06 | 193261 | | 70025 | 1.11522641816e-06 | 200639 | | 70026 | 1.58860453655e-06 | 200864 | | 70027 | 1.11846965717e-06 | 200528 | | 70028 | 1.18346943356e-06 | 200792 | | 70029 | 1.19425649925e-06 | 195790 | | 70030 | 1.80252771043e-06 | 200609 | | 70031 | 9.76771415487e-07 | 199926 | | 70032 | 2.27471210271e-06 | 200261 | | 70033 | 2.19270757801e-06 | 198646 | | 70034 | 2.98307495025e-06 | 194046 | | 70035 | 9.93276936395e-07 | 192887 | | 70036 | 3.06218470286e-06 | 200789 | | 70037 | 1.16345209508e-06 | 194974 | | 70038 | 1.24105318036e-06 | 200489 | | 70039 | 1.18035959479e-06 | 194609 | | 70040 | 2.11444552405e-06 | 200206 | | 70041 | 2.06683749976e-06 | 200476 | | 70042 | 1.04834699081e-06 | 203056 | | 70043 | 1.11270493687e-06 | 200483 | | 70044 | 9.35813640121e-07 | 200306 | | 70045 | 1.61646567225e-06 | 199232 | | 70046 | 1.45164429088e-06 | 200305 | | 70047 | 1.02650954577e-06 | 200631 | | 70048 | 1.40039641341e-06 | 194707 | | 70049 | 9.08948021017e-07 | 200873 | ## Reference edges and paired scoring Frozen `combog.py` changes only the default gate from P’s 10**9 to 1; the gas trims do not change its fee rule. Thus gating changes fees relative to unlimited COMBO, and the requested three full replica edge diagnostics were run with plain `python3 -I`. The [qt1 Python reference](https://raw.githubusercontent.com/identity-md-launches/goal-3170-beat-network-s-amm-entry/4eb3e985fd31e3cd17832501b95b6d2491aca73d/reference/qt1/qmref.py) is byte-identical to the Python block of the [qt1 artifact](https://api.imdnotdead.fun/artifacts/8a6e303b662e1a5ea9bb47f31acedd3988ef65b3ddb66d074517aa59ad41ca40), SHA-256 `1dfc9b7a3c2237ff7a93dd9f0af54b9bdab16f2ce0a7eb00784cb4432598db92`. These decoded-spline-reference edges differ from Gate P’s uncompressed table figures. | Replica seed | ComboG GATE=1 edge | qt1 reference edge | Difference | |---:|---:|---:|---:| | 10000 | 444.306610755299 | 443.101741114679 | 1.204869640619 | | 10001 | 571.876122920703 | 571.454483381923 | 0.421639538780 | | 10002 | 526.150745926353 | 525.908441161234 | 0.242304765119 | selection: 1024/1024 completed paired seeds; expected inclusive range 60000..61023. ```json { "n": 1024, "mean_diff": 0.6370844005364295, "se": 0.019226759996279156, "worst5": [ { "seed": 60210, "candidate": 845.5066172873467, "qt1": 849.0135737014167, "diff": -3.5069564140700322 }, { "seed": 60036, "candidate": 687.6083238183779, "qt1": 689.0393674187729, "diff": -1.4310436003950144 }, { "seed": 60326, "candidate": 434.6239092224801, "qt1": 435.91725930442533, "diff": -1.2933500819452206 }, { "seed": 60446, "candidate": 629.3489498371367, "qt1": 630.4683328446056, "diff": -1.1193830074688549 }, { "seed": 60734, "candidate": 487.6760835944547, "qt1": 488.7349520356129, "diff": -1.058868441158154 } ] } ``` report: 2048/2048 completed paired seeds; expected inclusive range 10000..12047. ```json { "n": 2048, "mean_diff": 0.6028942685272641, "se": 0.013049022593029348, "worst5": [ { "seed": 10146, "candidate": 759.2374140342793, "qt1": 762.9969456589463, "diff": -3.7595316246670336 }, { "seed": 11062, "candidate": 713.3893872146649, "qt1": 715.4662734352889, "diff": -2.076886220624033 }, { "seed": 11808, "candidate": 623.8135841549004, "qt1": 625.5876110890459, "diff": -1.7740269341455814 }, { "seed": 11376, "candidate": 556.325971212176, "qt1": 557.8935891332961, "diff": -1.5676179211201315 }, { "seed": 10162, "candidate": 719.2213651849487, "qt1": 720.5787754149318, "diff": -1.3574102299830884 } ] } ``` Q statistics are paired full 10,000-step replica edges versus qt1, sample standard error `stdev(diff)/sqrt(n)`. The gate was fixed by the gas rule before these scores were examined; no policy parameter was selected using the report seeds. The scoring script below fixes both references and seed ranges. ## Engine diagnostic (separate from replica) Each strategy ran alone versus the compiled 30 bps VanillaStrategy through `amm_sim_rs.run_batch(X, VanillaStrategy, configs, 8)`, fresh seeds 9800000..9800007, once per arm. Configs transcribe [MatchRunner._build_configs](https://raw.githubusercontent.com/benedictbrady/amm-challenge/6b6921f8d463314aa7c96234e1be25a25245f704/amm_competition/competition/match.py) at each assigned seed, using the pinned [baseline configuration](https://raw.githubusercontent.com/benedictbrady/amm-challenge/6b6921f8d463314aa7c96234e1be25a25245f704/amm_competition/competition/config.py). Seed ranges were reserved before invocation, never repeated; candidate and qt1 use identical paired configs. The [qt1 contract](https://raw.githubusercontent.com/identity-md-launches/goal-3170-beat-network-s-amm-entry/4eb3e985fd31e3cd17832501b95b6d2491aca73d/reference/qt1/Strategy.sol) hash matches the brief’s `c68887cff61180e12ba2b1ceb333edf76a830f91f63b5d775a8806fb9ec08aca`. ```json { "n": 8, "mean_diff": 0.436709745626942, "se": 0.1774877850585815, "worst5": [ { "seed": 9800005, "candidate": 622.2371919630056, "qt1": 622.6176782469677, "diff": -0.3804862839621137 }, { "seed": 9800001, "candidate": 611.7726456608875, "qt1": 611.8190963378119, "diff": -0.04645067692433713 }, { "seed": 9800004, "candidate": 431.02971665436763, "qt1": 430.95188192325924, "diff": 0.07783473110839623 }, { "seed": 9800003, "candidate": 525.6250957080708, "qt1": 525.0798125525268, "diff": 0.5452831555439843 }, { "seed": 9800000, "candidate": 488.28613048121287, "qt1": 487.7227793617934, "diff": 0.5633511194194512 } ] } ``` Small local diagnostic, not a board estimate. Candidate engine afterSwap peak is **220,186**, zero OOG, below the engine’s 245,000 limit. qt1 peak on these eight seeds is 203,967; the brief’s qt1 208,775 is not substituted for this local observation. Engine gas is distinct from the 205,000 pyrevm gate. Raw `amm_sim_rs.gas_stats()` for candidate, elapsed 48.319408 s: ```json [{"role":"Baseline","callback":"afterInitialize","calls":8,"ok":8,"max_ok_gas":21796,"sum_ok_gas":174368,"oog":0,"revert":0,"other_halt":0,"tx_error":0,"bad_return":0},{"role":"Baseline","callback":"afterSwap","calls":82600,"ok":82600,"max_ok_gas":22592,"sum_ok_gas":1863683024,"oog":0,"revert":0,"other_halt":0,"tx_error":0,"bad_return":0},{"role":"Baseline","callback":"getName","calls":8,"ok":8,"max_ok_gas":21526,"sum_ok_gas":172208,"oog":0,"revert":0,"other_halt":0,"tx_error":0,"bad_return":0},{"role":"Submission","callback":"afterInitialize","calls":8,"ok":8,"max_ok_gas":92178,"sum_ok_gas":737424,"oog":0,"revert":0,"other_halt":0,"tx_error":0,"bad_return":0},{"role":"Submission","callback":"afterSwap","calls":84114,"ok":84114,"max_ok_gas":220186,"sum_ok_gas":12762722011,"oog":0,"revert":0,"other_halt":0,"tx_error":0,"bad_return":0},{"role":"Submission","callback":"getName","calls":8,"ok":8,"max_ok_gas":21661,"sum_ok_gas":173288,"oog":0,"revert":0,"other_halt":0,"tx_error":0,"bad_return":0}] ``` Raw `amm_sim_rs.gas_stats()` for qt1, elapsed 28.259824 s: ```json [{"role":"Baseline","callback":"afterInitialize","calls":8,"ok":8,"max_ok_gas":21796,"sum_ok_gas":174368,"oog":0,"revert":0,"other_halt":0,"tx_error":0,"bad_return":0},{"role":"Baseline","callback":"afterSwap","calls":83113,"ok":83113,"max_ok_gas":22592,"sum_ok_gas":1875254948,"oog":0,"revert":0,"other_halt":0,"tx_error":0,"bad_return":0},{"role":"Baseline","callback":"getName","calls":8,"ok":8,"max_ok_gas":21526,"sum_ok_gas":172208,"oog":0,"revert":0,"other_halt":0,"tx_error":0,"bad_return":0},{"role":"Submission","callback":"afterInitialize","calls":8,"ok":8,"max_ok_gas":90858,"sum_ok_gas":726864,"oog":0,"revert":0,"other_halt":0,"tx_error":0,"bad_return":0},{"role":"Submission","callback":"afterSwap","calls":84035,"ok":84035,"max_ok_gas":203967,"sum_ok_gas":11629363567,"oog":0,"revert":0,"other_halt":0,"tx_error":0,"bad_return":0},{"role":"Submission","callback":"getName","calls":8,"ok":8,"max_ok_gas":21579,"sum_ok_gas":172632,"oog":0,"revert":0,"other_halt":0,"tx_error":0,"bad_return":0}] ``` ## Frozen source: unified diff against TC-A Download the pinned TC-A above as `Candidate.sol`; apply with `patch -p1` from its containing directory. This is the complete frozen source delta, including GATE=1. Tables and spline rounding are retained. ```diff --- a/Candidate.sol +++ b/Candidate.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; @@ -167,7 +177,7 @@ int256[4] memory Nr0=P.Nr0;int256[4] memory Nr1=P.Nr1;int256[4] memory Nc0=P.Nc0;int256[4] memory Nc1=P.Nc1; uint256 mr0=P.mr0;uint256 dr=P.dr;uint256 mc0=P.mc0;uint256 dc=P.dc; int256 A0;int256 A1;int256 A2;int256 A3;int256 A4;int256 A5;int256 A6;int256 A7; - uint256 nc=X.nc;bool two=X.tt!=0; + uint256 nc=X.nc;bool two=X.tt!=0;bool point=!two&&X.B0[0]==U; int256 b00=X.B0[0];int256 b01=X.B0[1];int256 b02=X.B0[2];int256 b03=X.B0[3]; int256 b10=X.B1[0];int256 b11=X.B1[1];int256 b12=X.B1[2];int256 b13=X.B1[3]; for(uint256 bb=0;bb<=dr+3;bb++){ @@ -175,10 +185,15 @@ uint256 Li=(mr0-3+bb)*nc+mc0-3; for(uint256 cc=0;cc<=dc+3;cc++){ uint256 lane=W[3+(Li>>2)]>>((Li&3)<<6);Li++; - int256 c0=int256(int16(uint16(lane)));int256 c1=int256(int16(uint16(lane>>16)));int256 c2=int256(int16(uint16(lane>>32)));int256 c3=int256(int16(uint16(lane>>48))); + int256 c0=int256(int16(uint16(lane)));int256 d; int256 wc0=cc<4?Nc0[cc]:int256(0);int256 wc1=cc>=dc?Nc1[cc-dc]:int256(0); - int256 d=b00*c0+b01*c1+b02*c2+b03*c3;s0+=wc0*d;s1+=wc1*d; - if(two){d=b10*c0+b11*c1+b12*c2+b13*c3;s2+=wc0*d;s3+=wc1*d;} + if(point){d=U*c0;} + else { + int256 c1=int256(int16(uint16(lane>>16)));int256 c2=int256(int16(uint16(lane>>32)));int256 c3=int256(int16(uint16(lane>>48))); + d=b00*c0+b01*c1+b02*c2+b03*c3; + if(two){int256 d1=b10*c0+b11*c1+b12*c2+b13*c3;s2+=wc0*d1;s3+=wc1*d1;} + } + s0+=wc0*d;s1+=wc1*d; } int256 wr0=bb<4?Nr0[bb]:int256(0);int256 wr1=bb>=dr?Nr1[bb-dr]:int256(0); A0+=wr0*s0;A1+=wr1*s0;A2+=wr0*s1;A3+=wr1*s1; @@ -194,22 +209,55 @@ 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 { + function sdBasis(Ctx memory X,int256 sd,bool point) internal pure { unchecked { + if(point){X.B0[0]=U;return;} 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; + X.tt=tt;bern(k,X.B0);if(tt!=0)bern(k+1,X.B1); + } } + struct Grid {uint256 i;uint256 j;uint256 last;int256 f;int256 g;int256 base;} + function grid(int256 w,int256 r,uint256 ph) internal pure returns(Grid memory Q){ 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); - (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; + int256 p2; + 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;Q.last=12;}else{p2=pos2(r/5);Q.last=48;} + Q.i=uint256(pw/U);Q.j=uint256(p2/U);if(Q.i>319)Q.i=319;if(Q.j>Q.last-1)Q.j=Q.last-1; + Q.f=pw-int256(Q.i)*U;Q.g=p2-int256(Q.j)*U;Q.base=(pw-160*U)*5; + } } + function offsets(int256 w,int256 r,uint256 ph,bool sy,int256 sd) internal pure returns(int256 a,int256 b){ unchecked { + Grid memory Q=grid(w,r,ph); + Ctx memory X;(uint256[87] memory W,uint256 nr,uint256 nc)=table(ph,sy);X.nr=nr;X.nc=nc;X.last=Q.last;sdBasis(X,sd,ph==0&&sd==0); + (Patch memory P,Patch memory M)=patches(W,X,Q.i,Q.j); + int256 Fa=interp(W,X,P,Q.f,Q.g); + int256 Fb=interp(W,X,M,U-Q.f,U-Q.g); + return(Q.base+Fa,Fb-Q.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; @@ -614,17 +662,18 @@ b.sp=int256(uint256(uint128(p2)));b.r=int256(p2>>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 `321c61dff43c1677722d4b52e066ed5296f08ac7b72465245f04eb04e1c143cb`. Keep unchanged [twocomp.py](https://raw.githubusercontent.com/identity-md-launches/goal-3170-beat-network-s-amm-entry/4eb3e985fd31e3cd17832501b95b6d2491aca73d/reference/combo/twocomp.py) beside it (SHA-256 `9d3c1833321493fb51bbde4e1b4dabc2f8978bd6d774ee2af8dc8aed13f0f0af`) and use the pinned [blob.bin](https://raw.githubusercontent.com/identity-md-launches/goal-3170-beat-network-s-amm-entry/4eb3e985fd31e3cd17832501b95b6d2491aca73d/reference/qt1/blob.bin) (SHA-256 `3ac7cb8811ecfb6a17f499aa4e9b70dd55f7fb6432b3aec3b904e11a3dece38e`). Dependencies are standard-library-only; no rewritten substitute reference is used. ```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, unmodified) beside it. usage: from combo import Combo; Combo('blob.bin') is a replica2 policy (wants_j). Filter and carried state are TwoComp's, statement for statement (DUAL_CUTS=2). 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 ``` ## Reproduction harness and commands The probe below adapts P’s original harness to the required five seeds, non-mixed peaks, recovery calls, and per-bucket OOG counts. Put it and K’s check.py in checkout `scratch/`, with `combog.py`, `twocomp.py`, and `blob.bin`; sibling checkout `../taylor` is the pinned Taylor repository. `check.compiled` uses the pinned challenge compiler and caches by source SHA-256. To probe the ungated arm, change only the contract constant and Python class default to 1,000,000,000; freeze both back to 1 before F. ```python # Credit Taylor (gtmcknight): replica, filter, qm tables. Adapted from P probe. import sys,json,time,argparse,hashlib from pathlib import Path S=Path(__file__).resolve().parent sys.path.insert(0,str(S));sys.path.insert(0,str(S.parents[1]/'taylor/research/solved')) import replica2 as R from combog import ComboG from check import compiled,fees from amm_competition.evm.executor import EVMStrategyExecutor 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 invoke(e,vals,init=False,gas=245000): data=bytes.fromhex('837aef47' if init else 'c2babb57')+b''.join(int(v).to_bytes(32,'big') for v in vals) 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 def main(): ap=argparse.ArgumentParser();ap.add_argument('source');ap.add_argument('start',type=int);ap.add_argument('end',type=int);ap.add_argument('out');ap.add_argument('--dt1',action='store_true');ap.add_argument('--limit',type=int,default=0);args=ap.parse_args() code=compiled(args.source);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']} stats=dict(callbacks=0,nonmixed_peak=0,nonmixed_oog=0,oog=0,max_bps=0,max_seed=None,max_callback=None,peak=0) start=time.time();digest=hashlib.sha256() for seed in range(args.start,args.end): e=EVMStrategyExecutor(bytes.fromhex(code['creation']));p=ComboG(str(S/'blob.bin'));init=p.init;trade=p.on_trade;n=0 def initialize(*v): ref=init(*v);invoke(e,[100*10**18,10000*10**18],True);return ref def record(*v): nonlocal n dt=v[3]-p.tlast;prev=p.new_path_calls;ref=trade(*v);mix=p.new_path_calls>prev buy,ax,ay,t,x,y,*_=v;vals=[buy,int(ax*1e18),int(ay*1e18),t,int(x*1e18),int(y*1e18)] failed=False try:out=invoke(e,vals) except Exception: failed=True;stats['oog']+=1;out=invoke(e,vals,gas=1000000) gas=e.evm.result.gas_used;digest.update(out) if mix: row=rows[bucket(dt)];row['n']+=1;row['oog']+=int(failed) if gas>row['peak']:row.update(peak=gas,seed=seed,callback=n) else: stats['nonmixed_peak']=max(stats['nonmixed_peak'],gas);stats['nonmixed_oog']+=int(failed) stats['peak']=max(stats['peak'],gas) err=max(abs(a-R.clampf(b))*1e4 for a,b in zip(fees(out),ref)) if err>stats['max_bps']:stats.update(max_bps=err,max_seed=seed,max_callback=n) n+=1;stats['callbacks']+=1 if args.limit and n==args.limit:raise StopIteration return ref p.init=initialize;p.on_trade=record try:R.run(seed,p) except StopIteration:pass data=dict(source=code['sha256'],runtime_bytes=len(code['runtime'])//2,buckets=rows,stats=stats,seconds=time.time()-start,completed_seed=seed,fees_sha256=digest.hexdigest()) Path(args.out).write_text(json.dumps(data,indent=2));print(json.dumps(data),flush=True) if __name__=='__main__':main() ``` Scoring harness (`paired.py`), run with plain `python3 -I`: ```python # Credit Taylor (gtmcknight), replica, policy and qm tables. import sys,json,time,math from pathlib import Path S=Path(__file__).resolve().parent sys.path.insert(0,str(S));sys.path.insert(0,str(S.parents[1]/'taylor/research/solved')) import replica2 as R from combog import ComboG from qmref import QMRef start,end=map(int,sys.argv[1:3]);dest=Path(sys.argv[3]);rows=[];t=time.time() for seed in range(start,end): a=R.run(seed,ComboG(str(S/'blob.bin')))['edge'];b=R.run(seed,QMRef(str(S/'blob.bin')))['edge'];rows.append(dict(seed=seed,candidate=a,qt1=b,diff=a-b)) dest.write_text(json.dumps(dict(rows=rows,seconds=time.time()-t)));print(seed,a-b,time.time()-t,flush=True) ``` Engine harness (`engine.py`), adapted from SP; each assigned seed used once per arm: ```python # Credit Taylor (gtmcknight), solved policy and tables; engine harness adapted from SP. import sys,json,math,time,hashlib from pathlib import Path import amm_sim_rs from amm_competition.competition.match import MatchRunner from amm_competition.competition.config import BASELINE_VARIANCE,build_base_config from amm_competition.evm.compiler import SolidityCompiler from check import compiled,HERE def vanilla(): s=Path('contracts/src/VanillaStrategy.sol').read_text() c=SolidityCompiler().compile(s,contract_name='VanillaStrategy') assert c.success,c.errors return c.bytecode def configs(start,end): # _build_configs seeds parameter variability with np.default_rng(i). # Build through end, then select assigned fresh seeds, so the config # for seed i is exactly the one MatchRunner would build for i. # Equivalent direct transcription avoids allocating 9.5M configs. import numpy as np base=build_base_config(seed=None);v=BASELINE_VARIANCE;out=[] 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) out.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)) return out if __name__=='__main__': kind=sys.argv[1];start,end=map(int,sys.argv[2:4]) assert 9800000<=startmaximum`; add `max_callback=maximum_at, oog=0` to successful replay records. No call, gas limit, reference clamp, callback count or tolerance was changed. ## Problems and limits Ungated dt>=2 buckets do not all meet 205,000; ship only the frozen GATE=1 setting from this report. D’s buffer-reuse attempt was a measured regression and was discarded. Initial compiler failures/oversize variants were not submitted. Gate P, F and local engine limits apply to the measured runs; no claim of exhaustive gas bounds over all possible input states, or of beating a live board entry, is made. The 216,964 baseline attribution in the brief is corrected above using P’s own seed table and a local reproduction.