# Port 2: Taylor Gaussian plain policy The Solidity strategy beats t03 on the assigned engine seeds: paired mean **+1.4143** edge, SE 0.1990, n=64. It meets the 24,576-byte and 245,000-gas limits on this run. The design follows [Taylor (gtmcknight)'s solved policy](https://raw.githubusercontent.com/gtmcknight/amm-sim/4812a6382311624e1506aca131ca35c378f930d9/research/solved/README.md) and its [Gaussian implementation](https://raw.githubusercontent.com/gtmcknight/amm-sim/4812a6382311624e1506aca131ca35c378f930d9/research/solved/real.py). ## Setup | Step | Local outcome | | --- | --- | | Clone `benedictbrady/amm-challenge` at `6b6921f8d463314aa7c96234e1be25a25245f704` inside the assigned directory | success | | Clone `gtmcknight/amm-sim` at `4812a6382311624e1506aca131ca35c378f930d9`; read `research/solved/README.md` first | success | | Save and run the supplied `scratch/setup.sh` once from the challenge checkout | success; wheel SHA-256 `aedb68280aca34c110968f00148387c95885207913fb2cf19a1ab4c5cfd6887a` verified, Python 3.12 environment installed, solc 0.8.24 installed, starter strategy validated | | Prefix subsequent engine/solc commands with `. scratch/env.sh &&` | done | | Gate P, `python3 -I gates.py` before policy changes | reproduced all three rows exactly; the [gate runner](https://raw.githubusercontent.com/gtmcknight/amm-sim/4812a6382311624e1506aca131ca35c378f930d9/research/solved/gates.py) supplies the comparison | ```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 ``` ## Design The port keeps Taylor's mean, variance, last fees, last own spot, estimated rival spot, timestamp, retail count, and sync bit. These occupy four of the challenge's [32 fixed slots](https://raw.githubusercontent.com/benedictbrady/amm-challenge/6b6921f8d463314aa7c96234e1be25a25245f704/contracts/src/AMMStrategyBase.sol). It computes a fixed-point logarithm by range reduction and an atanh series, exponential by halving and a fourth-order series, normal PDF and rational CDF, square root, truncated-normal moments, arb/retail likelihood, and the phase-dependent bilinear table fee. The main branch and parameters follow [real.py](https://raw.githubusercontent.com/gtmcknight/amm-sim/4812a6382311624e1506aca131ca35c378f930d9/research/solved/real.py); all offsets come from [pol_mid.json](https://raw.githubusercontent.com/gtmcknight/amm-sim/4812a6382311624e1506aca131ca35c378f930d9/research/solved/pol_mid.json). The loop caps silent steps at 12. For gas, it accumulates their process variance and applies **one** truncated-normal moment update at the end, rather than Taylor's update after each silent step. This is the material approximation. The current step still uses the full truncated-normal update. The Python reference applies exactly the same silent-step rule and reads the packed bytes from the Solidity source. The log/exponential series introduce small numerical error; the end-to-end fee error is measured by Gate F below. The packed `int128` belief and `uint128` variance use far less than their ranges in the tested markets. A market outside those ranges would need explicit saturation. ## Table The original six offset matrices contain 71,262 values (321 own rows, 13 phase-0 or 49 phase-1/2 rival columns) in [Taylor's file](https://raw.githubusercontent.com/gtmcknight/amm-sim/4812a6382311624e1506aca131ca35c378f930d9/research/solved/pol_mid.json). `tablegen.py` samples 41 nonuniform own knots and 25 nonuniform rival knots, preserving all 13 phase-0 columns. The single blob is 10,464 bytes: 41 + 25 signed 16-bit knot words followed by `A0,B0,A1,B1,A2,B2` row-major matrices. Offsets are rounded to 0.1 bps. `Strategy.sol` contains the blob as a constant hex literal; `_read` is the one word lookup used by all interpolation. On all original grid values, reconstructed offset absolute error is mean 0.2782 bps, p99 9.015 bps, max 42.119 bps. Paired replica edge with the **same aggregated-silent filter**: | Seeds | n | Compressed mean | Full-table mean | Mean difference | SE | Worst five differences | | --- | ---: | ---: | ---: | ---: | ---: | --- | | selection 60000..61023 | 1024 | 528.943411 | 529.016498 | -0.073086 | 0.013999 | -2.445994, -1.701713, -1.676193, -1.502039, -1.461333 | | report 10000..12047 | 2048 | 532.267743 | 532.351218 | -0.083475 | 0.009721 | -4.777328, -2.437684, -2.019026, -1.440219, -1.434432 | The paired runs use `python3 -I reference.py choose` and `python3 -I reference.py hold`. The replica and original full policy are [Taylor's reference](https://raw.githubusercontent.com/gtmcknight/amm-sim/4812a6382311624e1506aca131ca35c378f930d9/research/solved/README.md); the table reader and aggregation hook are verbatim below. ## Gate F `gate_f.py` recorded the first 2,000 own-pool callbacks from each of 50 reference-driven [replica](https://raw.githubusercontent.com/gtmcknight/amm-sim/4812a6382311624e1506aca131ca35c378f930d9/research/solved/README.md) runs, seeds 70000..70049, then replayed each stream through a freshly deployed contract using pyrevm. Each callback records side, amounts, timestamp, and post-trade reserves; both fees are compared after the engine's 0..10% clamp. The reference reads the exact blob embedded in `Strategy.sol`. - Callbacks: **100,000** (50 × 2,000); replay failures: **0**. - Mean absolute error, max of bid/ask per callback: **0.000004614 bps**. - Maximum absolute error: **0.000563746 bps** (seed/callback/timestamp 70039/227/180), below 0.01 bps. ## Size `amm-match validate contracts/src/Strategy.sol` succeeds. The [pinned compiler settings](https://raw.githubusercontent.com/benedictbrady/amm-challenge/6b6921f8d463314aa7c96234e1be25a25245f704/amm_competition/evm/compiler.py) compile the deployed `Strategy` to **18,484 bytes**, 6,092 below the 24,576-byte limit. t03 compiles to 14,654 bytes. The t03 source was decoded from its [`code_zb64` artifact](https://api.imdnotdead.fun/artifacts/2333ecf28d4356bd232b85c1e55842e94e1ada05e1cd067830b5625dfdbc5336); decoded SHA-256 is `cb6d945511e1e10af78baa64c2a6cb25806f0998403ce6440654bfc3c70092d9`. ## Gas `amm_sim_rs.gas_stats()` for the port's 64 engine matches: `afterSwap` calls **697,644**, successful **697,644**, OutOfGas **0**, peak **225,081**, mean successful gas **126380.99**. Peak is 19,919 below 245,000. `afterInitialize` peak was 72,760 gas. The [VanillaStrategy](https://raw.githubusercontent.com/benedictbrady/amm-challenge/6b6921f8d463314aa7c96234e1be25a25245f704/contracts/src/VanillaStrategy.sol) uses a fixed 30 bps fee. ## Paired vs t03 Each strategy ran alone against that 30 bps VanillaStrategy with `amm_sim_rs.run_batch(X, VanillaStrategy, configs, 8)`. The 64 configs follow [`MatchRunner._build_configs`](https://raw.githubusercontent.com/benedictbrady/amm-challenge/6b6921f8d463314aa7c96234e1be25a25245f704/amm_competition/competition/match.py), with seeds replaced by the assigned range 9510064..9510127. The paired outcome is the difference between the strategies' own edge values on the same config and seed. ```json {"n":64,"mean_diff":1.414318451,"se":0.198959130,"worst5":[-2.397035298464573, -1.9183903826931896, -1.37002489728917, -1.1464575830912054, -1.0677501521778368]} ``` The final run has zero OutOfGas for both strategies. `engine.py` and the gas output in `engine_0_64.json` produced these figures. ## Problems The single silent-step truncation is an approximation of Taylor's per-step filter; the holdout table comparison isolates compression under that approximation. The contract passes the measured engine set and replay, but the 64 assigned seeds were also used in local debugging before the final run, so they are not a blind holdout. No lattice or qm tables were ported in this item. ## Code The following files are reproduced verbatim. `Strategy.sol` contains the packed table; the Python reference uses the pinned Taylor files cloned in Setup. `engine.py` is the paired engine harness, `gate_f.py` the callback recorder/replayer, `tablegen.py` and `build.py` construct the blob, `gas_probe.py` checks isolated callback gas, and `setup.sh` is the supplied setup script. ### Strategy.sol ```solidity // SPDX-License-Identifier: MIT pragma solidity ^0.8.24; // Gaussian plain-table AMM policy ported from Taylor (gtmcknight), amm-sim // commit 4812a6382311624e1506aca131ca35c378f930d9, research/solved/real.py. import {AMMStrategyBase} from "./AMMStrategyBase.sol"; import {TradeInfo} from "./IAMMStrategy.sol"; contract Strategy is AMMStrategyBase { int256 private constant U = 1e18; int256 private constant LN2 = 693147180559945309; int256 private constant SIG2 = 893025000000; int256 private constant G = 997000000000000000; int256 private constant RHO = 260000000000000000; int256 private constant LDS = 1176000000000000000; int256 private constant LDM = -6801595083153747000; bytes private constant TABLE = hex"e0c0e890ec78f060f448f63cf830f92afa24fb1efc18fc7cfce0fd44fda8fe0cfe70fed4ff38ff9c0000006400c8012c019001f4025802bc0320038403e804e205dc06d607d009c40bb80fa0138817701f40e0c0ec78f448f830fb1efcaefda8fe3efea2ff06ff6affce00000032009600fa015e01c20258035204e207d00bb813881f40ff0dff13ff18ff1cff20ff24ff28ff2bff2eff31ff34ff37ff39ff14ff1aff1fff23ff27ff2bff30ff34ff37ff3bff3eff41ff44ff1aff20ff25ff29ff2eff32ff37ff3bff3fff43ff47ff4aff4dff23ff28ff2dff33ff38ff3dff42ff47ff4bff50ff54ff58ff5bff31ff37ff3dff44ff4aff50ff56ff5cff62ff68ff6eff73ff78ff3dff44ff4bff52ff59ff61ff69ff70ff77ff7cff82ff85ff8cff4cff54ff5dff67ff70ff7aff83ff8eff96ff9800b100d600f0ff58ff62ff6cff76ff81ff8eff9affa3ffa400b200d900f70110ff66ff70ff7cff8aff99ffaaffb9007500b000db00fb0118012dff77ff84ff94ffa6ffbbfff1007a00b300dd00fc011b0136014dff8eff9fffb5ffd60020007e00b000dc00fe011e013c0154016bff9bffaeffcafff80054009200c000e8010a012a014801600177ffa9ffc0ffe50024006d00a300cf00f5011801360152016b0181ffc2ffdc00060047008300b400dc010001220141015d0177018cffe90003002b0061009400c000e7010b012c014b016701810196001e00390055007a00a300cc00f10115013501540171018a01a200770064007a009900b700d900fc011f0140015b017b019201ac00a400bf009b00a900c700e401050126014801660180019a01b100c100dc00b400be00d200ed010d012f014f016b018701a201ba010f00f300fc00d500dc00f70112013601580174019001ab01c301260108011400f000ec0101011b013b015c017c019601b501c9013e0124012b012c0106010b0126014101640185019f01ba01d3015901630146014b012e01220133014b016b018b01a901c501df017d0185017a016f015e01510146015c0176019701b601cd01ec019001b1019001aa01900190019001900190019001c501e201fc01f401f401f401f401f401f401f401f401f401f401f401f40213025802580258025802580258025802580258025802580258025802bc02bc02bc02bc02bc02bc02bc02bc02bc02bc02bc02bc02bc0320032003200320032003200320032003200320032003200320038403840384038403840384038403840384038403840384038403e803e803e803e803e803e803e803e803e803e803e803e803e804e204e204e204e204e204e204e204e204e204e204e204e204e205dc05dc05dc05dc05dc05dc05dc05dc05dc05dc05dc05dc05dc06d606d606d606d606d606d606d606d606d606d606d606d606d607d007d007d007d007d007d007d007d007d007d007d007d007d009c409c409c409c409c409c409c409c409c409c409c409c409c40bb80bb80bb80bb80bb80bb80bb80bb80bb80bb80bb80bb80bb80fa00fa00fa00fa00fa00fa00fa00fa00fa00fa00fa00fa00fa0138813881388138813881388138813881388138813881388138817701770177017701770177017701770177017701770177017701f401f401f401f401f401f401f401f401f401f401f401f401f401f401f401f401f401f401f401f401f401f401f401f401f401f40177017701770177017701770177017701770177017701770177013881388138813881388138813881388138813881388138813880fa00fa00fa00fa00fa00fa00fa00fa00fa00fa00fa00fa00fa00bb80bb80bb80bb80bb80bb80bb80bb80bb80bb80bb80bb80bb809c409c409c409c409c409c409c409c409c409c409c409c409c407d007d007d007d007d007d007d007d007d007d007d007d007d006d606d606d606d606d606d606d606d606d606d606d606d606d605dc05dc05dc05dc05dc05dc05dc05dc05dc05dc05dc05dc05dc04e204e204e204e204e204e204e204e204e204e204e204e204e203e803e803e803e803e803e803e803e803e803e803e803e803e80384038403840384038403840384038403840384038403840384032003200320032003200320032003200320032003200320032002bc02bc02bc02bc02bc02bc02bc02bc02bc02bc02bc02bc02bc0258025802580258025802580258025802580258025802580258021301f401f401f401f401f401f401f401f401f401f401f401f401fc01e201c501900190019001900190019001aa019001b1019001ec01cd01b601970176015c01460151015e016f017a0185017d01df01c501a9018b016b014b01330122012e014b01460163015901d301ba019f0185016401410126010b0106012c012b0124013e01c901b50196017c015c013b011b010100ec00f001140108012601c301ab0190017401580136011200f700dc00d500fc00f3010f01ba01a20187016b014f012f010d00ed00d200be00b400dc00c101b1019a0180016601480126010500e400c700a9009b00bf00a401ac0192017b015b0140011f00fc00d900b70099007a0064007701a2018a017101540135011500f100cc00a3007a00550039001e019601810167014b012c010b00e700c000940061002b0003ffe9018c0177015d01410122010000dc00b4008300470006ffdcffc20181016b01520136011800f500cf00a3006d0024ffe5ffc0ffa9017701600148012a010a00e800c000920054fff8ffcaffaeff9b016b0154013c011e00fe00dc00b0007e0020ffd6ffb5ff9fff8e014d0136011b00fc00dd00b3007afff1ffbbffa6ff94ff84ff77012d011800fb00db00b00075ffb9ffaaff99ff8aff7cff70ff66011000f700d900b2ffa4ffa3ff9aff8eff81ff76ff6cff62ff5800f000d600b1ff98ff96ff8eff83ff7aff70ff67ff5dff54ff4cff8cff85ff82ff7cff77ff70ff69ff61ff59ff52ff4bff44ff3dff78ff73ff6eff68ff62ff5cff56ff50ff4aff44ff3dff37ff31ff5bff58ff54ff50ff4bff47ff42ff3dff38ff33ff2dff28ff23ff4dff4aff47ff43ff3fff3bff37ff32ff2eff29ff25ff20ff1aff44ff41ff3eff3bff37ff34ff30ff2bff27ff23ff1fff1aff14ff39ff37ff34ff31ff2eff2bff28ff24ff20ff1cff18ff13ff0dfec7fec7fec8fecafecefed4fedcfee6feedfef3fef7fefbfefdfeffff02ff05ff07ff09ff0cff10ff14ff19ff1dff1fff21fecffecffed0fed2fed6fedbfee4feeefef4fefafeffff04ff06ff08ff0cff0fff11ff14ff17ff1aff1fff24ff28ff2bff2cfed4fed5fed6fed8fedcfee1feeafef3fefaff00ff06ff0bff0eff10ff14ff17ff19ff1cff1fff23ff28ff2dff31ff34ff36fedffedffee0fee2fee6feecfef3fefcff03ff0aff10ff16ff19ff1bff1fff23ff26ff29ff2cff30ff36ff3bff3fff42ff44feeffeeffef0fef2fef5fefaff01ff0aff12ff1aff21ff28ff2bff2eff34ff38ff3bff3eff42ff47ff4dff53ff580117011afef9fefafefbfefcff00ff05ff0bff15ff1eff26ff2fff37ff3bff3fff42ff41ff40ff40ff43ff480119012a01320139013cff09ff09ff0aff0cff10ff14ff1bff23ff2cff36ff41ff4bff4eff4eff4aff49ff4cff4dff50013301460156015e01640167ff12ff13ff14ff16ff19ff1eff24ff2dff37ff42ff4fff58ff5aff58ff52ff52ff55ff560138014f015f016f0178017e0180ff1fff1fff20ff22ff26ff2aff30ff38ff43ff50ff5fff64ff63ff61ff5dff60012f01440156016a017c018a01920198019aff27ff27ff28ff2aff33ff38ff3dff45ff51ff61ff71ff73ff71ff7000f4012c014f016201760188019901a801b001b501b8ff32ff33ff34ff35ff3fff4dff52ff58ff66ff78ff86ff88ff8600d20118014d016f0182019401a801b901c701d001d601d9ff36ff36ff37ff38ff43ff53ff5cff63ff71ff83ff96ff9b00b700e201250158017a018e01a101b501c601d501de01e401e6ff42ff43ff43ff44ff4fff63ff6eff73ff7eff94ffa9009300c600ef013101640186019a01ad01c001d201e201eb01f101f4ff58ff58ff59ff5aff66ff78ff88ff91ff9bffaeffd000a900d500fa013c0170019101a601b801cc01df01f001fa02000203ff60ff60ff61ff62ff72ff90ffb2ffbfffcaffdd003d00b800e201060147017b019c01b101c401d901ed01ff0208020f0212ff67ff67ff68ff69ff79ffa0ffc1ffe4fff8001d006900c600ed01110151018401a801bd01d101e701fb020e021902200224ff6dff6dff6eff6eff80ffa9ffdefff90013003e008e00d400f8011c015b018f01b001c501de01f6020b0221022d02340238ff71ff71ff71ff72ff88ffbaffea0009006d008f00a100e0010501240163019401bc01cf01e80202022002370245024f0254ff74ff74ff75ff76ff8cffcd00100041009600bd00ae00e9010b012d016c019d01c201d901ef021602310259026c02790282ff9cff9cff9cff9cff9cffd2001700d600bc00db00c700f501110134017101a701cc01e901fa0247027002a305dc05dc05dc000000000000000000000000005f00f4011a00f400dd00fe0118013a017f01b101d201f0022b02a0034a05dc05dc05dc05dc00640064006400640064006401170112013401370121010901240140018401bc01e401fd026702f7047805dc05dc05dc05dc00c800c800c800c800e500f70146015f015101570142011c0131014a018d01c201f3022c026e0304048105dc05dc05dc05dc012c012c012c012c012c01670167017f0174017a01670147012c015c019601cf0204024702750312048905dc05dc05dc05dc019001900190019001900190019001aa01ad01900190019001900190019001e70225024f029f035b04b505dc05dc05dc05dc01f401f401f401f401f401f401f401f401f401f401f401f401f401f401f401f40230026a02a8036404b905dc05dc05dc05dc02580258025802580258025802580258025802580258025802580258025802580258027702cf036d04bd05dc05dc05dc05dc02bc02bc02bc02bc02bc02bc02bc02bc02bc02bc02bc02bc02bc02bc02bc02bc02bc02bc02dc038f04c105dc05dc05dc05dc0320032003200320032003200320032003200320032003200320032003200320032003200320039904d105dc05dc05dc05dc038403840384038403840384038403840384038403840384038403840384038403840384038403a304d405dc05dc05dc05dc03e803e803e803e803e803e803e803e803e803e803e803e803e803e803e803e803e803e803e803e804d905dc05dc05dc05dc04e204e204e204e204e204e204e204e204e204e204e204e204e204e204e204e204e204e204e204e204e205dc05dc05dc05dc05dc05dc05dc05dc05dc05dc05dc05dc05dc05dc05dc05dc05dc05dc05dc05dc05dc05dc05dc05dc05dc05dc05dc05dc05dc06d606d606d606d606d606d606d606d606d606d606d606d606d606d606d606d606d606d606d606d606d606d606d606d606d607d007d007d007d007d007d007d007d007d007d007d007d007d007d007d007d007d007d007d007d007d007d007d007d007d009c409c409c409c409c409c409c409c409c409c409c409c409c409c409c409c409c409c409c409c409c409c409c409c409c40bb80bb80bb80bb80bb80bb80bb80bb80bb80bb80bb80bb80bb80bb80bb80bb80bb80bb80bb80bb80bb80bb80bb80bb80bb80fa00fa00fa00fa00fa00fa00fa00fa00fa00fa00fa00fa00fa00fa00fa00fa00fa00fa00fa00fa00fa00fa00fa00fa00fa0138813881388138813881388138813881388138813881388138813881388138813881388138813881388138813881388138817701770177017701770177017701770177017701770177017701770177017701770177017701770177017701770177017701f401f401f401f401f401f401f401f401f401f401f401f401f401f401f401f401f401f401f401f401f401f401f401f401f401f401f401f401f401f401f401f401f401f401f401f401f401f401f401f401f401f401f401f401f401f401f401f401f401f40177017701770177017701770177017701770177017701770177017701770177017701770177017701770177017701770177013881388138813881388138813881388138813881388138813881388138813881388138813881388138813881388138813880fa00fa00fa00fa00fa00fa00fa00fa00fa00fa00fa00fa00fa00fa00fa00fa00fa00fa00fa00fa00fa00fa00fa00fa00fa00bb80bb80bb80bb80bb80bb80bb80bb80bb80bb80bb80bb80bb80bb80bb80bb80bb80bb80bb80bb80bb80bb80bb80bb80bb809c409c409c409c409c409c409c409c409c409c409c409c409c409c409c409c409c409c409c409c409c409c409c409c409c407d007d007d007d007d007d007d007d007d007d007d007d007d007d007d007d007d007d007d007d007d007d007d007d007d006d606d606d606d606d606d606d606d606d606d606d606d606d606d606d606d606d606d606d606d606d606d606d606d606d605dc05dc05dc05dc05dc05dc05dc05dc05dc05dc05dc05dc05dc05dc05dc05dc05dc05dc05dc05dc05dc05dc05dc05dc05dc05dc05dc05dc05dc04e204e204e204e204e204e204e204e204e204e204e204e204e204e204e204e204e204e204e204e204e205dc05dc05dc05dc04d903e803e803e803e803e803e803e803e803e803e803e803e803e803e803e803e803e803e803e803e805dc05dc05dc05dc04d403a3038403840384038403840384038403840384038403840384038403840384038403840384038405dc05dc05dc05dc04d10399032003200320032003200320032003200320032003200320032003200320032003200320032005dc05dc05dc05dc04c1038f02dc02bc02bc02bc02bc02bc02bc02bc02bc02bc02bc02bc02bc02bc02bc02bc02bc02bc02bc05dc05dc05dc05dc04bd036d02cf02770258025802580258025802580258025802580258025802580258025802580258025805dc05dc05dc05dc04b9036402a8026a023001f401f401f401f401f401f401f401f401f401f401f401f401f401f401f401f405dc05dc05dc05dc04b5035b029f024f022501e701900190019001900190019001ad01aa019001900190019001900190019005dc05dc05dc05dc0489031202750247020401cf0196015c012c01470167017a0174017f01670167012c012c012c012c012c05dc05dc05dc05dc04810304026e022c01f301c2018d014a0131011c014201570151015f014600f700e500c800c800c800c805dc05dc05dc05dc047802f7026701fd01e401bc01840140012401090121013701340112011700640064006400640064006405dc05dc05dc05dc034a02a0022b01f001d201b1017f013a011800fe00dd00f4011a00f4005f00000000000000000000000005dc05dc05dc02a30270024701fa01e901cc01a701710134011100f500c700db00bc00d60017ffd2ff9cff9cff9cff9cff9c02820279026c02590231021601ef01d901c2019d016c012d010b00e900ae00bd009600410010ffcdff8cff76ff75ff74ff740254024f024502370220020201e801cf01bc019401630124010500e000a1008f006d0009ffeaffbaff88ff72ff71ff71ff7102380234022d0221020b01f601de01c501b0018f015b011c00f800d4008e003e0013fff9ffdeffa9ff80ff6eff6eff6dff6d022402200219020e01fb01e701d101bd01a801840151011100ed00c60069001dfff8ffe4ffc1ffa0ff79ff69ff68ff67ff670212020f020801ff01ed01d901c401b1019c017b0147010600e200b8003dffddffcaffbfffb2ff90ff72ff62ff61ff60ff600203020001fa01f001df01cc01b801a601910170013c00fa00d500a9ffd0ffaeff9bff91ff88ff78ff66ff5aff59ff58ff5801f401f101eb01e201d201c001ad019a01860164013100ef00c60093ffa9ff94ff7eff73ff6eff63ff4fff44ff43ff43ff4201e601e401de01d501c601b501a1018e017a0158012500e200b7ff9bff96ff83ff71ff63ff5cff53ff43ff38ff37ff36ff3601d901d601d001c701b901a801940182016f014d011800d2ff86ff88ff86ff78ff66ff58ff52ff4dff3fff35ff34ff33ff3201b801b501b001a80199018801760162014f012c00f4ff70ff71ff73ff71ff61ff51ff45ff3dff38ff33ff2aff28ff27ff27019a01980192018a017c016a01560144012fff60ff5dff61ff63ff64ff5fff50ff43ff38ff30ff2aff26ff22ff20ff1fff1f0180017e0178016f015f014f0138ff56ff55ff52ff52ff58ff5aff58ff4fff42ff37ff2dff24ff1eff19ff16ff14ff13ff1201670164015e015601460133ff50ff4dff4cff49ff4aff4eff4eff4bff41ff36ff2cff23ff1bff14ff10ff0cff0aff09ff09013c01390132012a0119ff48ff43ff40ff40ff41ff42ff3fff3bff37ff2fff26ff1eff15ff0bff05ff00fefcfefbfefafef9011a0117ff58ff53ff4dff47ff42ff3eff3bff38ff34ff2eff2bff28ff21ff1aff12ff0aff01fefafef5fef2fef0feeffeefff44ff42ff3fff3bff36ff30ff2cff29ff26ff23ff1fff1bff19ff16ff10ff0aff03fefcfef3feecfee6fee2fee0fedffedfff36ff34ff31ff2dff28ff23ff1fff1cff19ff17ff14ff10ff0eff0bff06ff00fefafef3feeafee1fedcfed8fed6fed5fed4ff2cff2bff28ff24ff1fff1aff17ff14ff11ff0fff0cff08ff06ff04fefffefafef4feeefee4fedbfed6fed2fed0fecffecfff21ff1fff1dff19ff14ff10ff0cff09ff07ff05ff02fefffefdfefbfef7fef3feedfee6fedcfed4fecefecafec8fec7fec7fec7fec7fec8fec9fecbfecffed5fedbfee0fee4fee7fee9feebfeecfeeefeeffef1fef2fef4fef6fef8fefbfefefeffff00fecffecffed0fed1fed3fed7feddfee3fee8feecfeeffef2fef3fef4fef7fef9fefbfefcfefeff00ff03ff06ff09ff0aff0bfed4fed5fed5fed7fed9feddfee2fee9feeefef2fef5fef9fefbfefcfeffff01ff03ff04ff06ff08ff0bff0eff11ff13ff13fedffedffee0fee1fee4fee7feedfef2fef7fefcff00ff04ff06ff08ff0aff0dff0fff11ff13ff15ff18ff1bff1eff20ff20feeffeeffef0fef1fef3fef6fefbff01ff06ff0cff11ff16ff19ff1aff1eff20ff22ff24ff26ff29ff2dff30ff32ff35ff36fef9fef9fefafefbfefdff01ff05ff0bff12ff18ff1eff25ff27ff2aff2bff27ff23ff22ff23ff26ff2aff2dff2fff32ff33ff09ff09ff0aff0bff0dff10ff14ff1bff21ff28ff31ff38ff3aff38ff34ff32ff33ff35ff37ff39ff3cff3fff41ff43ff44ff12ff12ff13ff14ff17ff1aff1eff24ff2bff34ff3dff43ff42ff40ff3cff3bff3cff3eff3fff41ff44014a014f01530155ff1fff1fff20ff21ff23ff26ff2aff30ff38ff42ff4bff4cff4bff49ff47ff49ff4bff4dff4fff51015b0165016b016f0171ff27ff27ff27ff29ff30ff33ff37ff3cff45ff51ff5aff5bff59ff58ff57ff5bff5e01560162016f017b01830189018d018eff32ff33ff33ff34ff3dff48ff4bff4fff5aff67ff70ff70ff70ff6f01160149016701760182018e019a01a301a901ad01aeff36ff36ff37ff37ff41ff4fff54ff59ff64ff72ff7aff7bff7bff7b0122015501730182018e019b01a701b001b601ba01bbff42ff42ff43ff44ff4dff5fff67ff6bff73ff7fff88ff8a00c200ec012f0160017f018d019a01a801b301bc01c201c601c7ff58ff58ff59ff59ff64ff76ff82ff89ff90ff9cffa200a100d100f8013b016d018a019901a601b301bf01c901ce01d301d5ff60ff60ff61ff61ff71ff92ffacffb7ffc1ffcaffd700b400df010401460178019501a501b201bf01cb01d601dc01e101e2ff67ff67ff67ff68ff78ff9cffc9ffdaffe5000a005c00c200eb010f0150018201a101b101be01cc01d901e401ea01ee01f0ff6dff6dff6dff6eff7fffaeffd8ffec0004002e008800d200f7011b015a018d01ad01bd01c701d501e701f301f901fe0200ff71ff71ff71ff72ff8bffd1fffcffff00180044009c00df010401230162019601b601c301d001e401f201ff020602110213ff74ff74ff75ff75ff8fffd700080031007300a900aa00e8010a012c016b019b01bc01cd01e001f001fe021f0227022c0230ff9cff9cff9cff9cff9cfff1003c00ae009900ce00c000f401100134017101a501c601d801ed02250239024c025902600265000000000000000000000000004500da010f00ea00d800fe0118013a017f01af01d201eb022e0271029a02e805dc05dc05dc00640064006400640064006401010137012a0130011d010801240140018401bb01e801fc02340279043f05dc05dc05dc05dc00c800c800c800c80126012d012f0156014a01520140011b0131014a018e01c801fa0223025a02c1044905dc05dc05dc05dc012c012c014c01530158015c017a0178016e017701650146012c015d019701e002200241026102cc045305dc05dc05dc05dc0190019001900190019001ad01ad0190019001900190019001900190019001e902270249028e033304a405dc05dc05dc05dc01f401f401f401f401f401f401f401f401f401f401f401f401f401f401f401f4023b02680297033e04a805dc05dc05dc05dc02580258025802580258025802580258025802580258025802580258025802580258027602c5034a04ad05dc05dc05dc05dc02bc02bc02bc02bc02bc02bc02bc02bc02bc02bc02bc02bc02bc02bc02bc02bc02bc02bc02e6038404b205dc05dc05dc05dc0320032003200320032003200320032003200320032003200320032003200320032003200320038f04cd05dc05dc05dc05dc038403840384038403840384038403840384038403840384038403840384038403840384038403a904d105dc05dc05dc05dc03e803e803e803e803e803e803e803e803e803e803e803e803e803e803e803e803e803e803e803e804d605dc05dc05dc05dc04e204e204e204e204e204e204e204e204e204e204e204e204e204e204e204e204e204e204e204e204e205dc05dc05dc05dc05dc05dc05dc05dc05dc05dc05dc05dc05dc05dc05dc05dc05dc05dc05dc05dc05dc05dc05dc05dc05dc05dc05dc05dc05dc06d606d606d606d606d606d606d606d606d606d606d606d606d606d606d606d606d606d606d606d606d606d606d606d606d607d007d007d007d007d007d007d007d007d007d007d007d007d007d007d007d007d007d007d007d007d007d007d007d007d009c409c409c409c409c409c409c409c409c409c409c409c409c409c409c409c409c409c409c409c409c409c409c409c409c40bb80bb80bb80bb80bb80bb80bb80bb80bb80bb80bb80bb80bb80bb80bb80bb80bb80bb80bb80bb80bb80bb80bb80bb80bb80fa00fa00fa00fa00fa00fa00fa00fa00fa00fa00fa00fa00fa00fa00fa00fa00fa00fa00fa00fa00fa00fa00fa00fa00fa0138813881388138813881388138813881388138813881388138813881388138813881388138813881388138813881388138817701770177017701770177017701770177017701770177017701770177017701770177017701770177017701770177017701f401f401f401f401f401f401f401f401f401f401f401f401f401f401f401f401f401f401f401f401f401f401f401f401f401f401f401f401f401f401f401f401f401f401f401f401f401f401f401f401f401f401f401f401f401f401f401f401f401f40177017701770177017701770177017701770177017701770177017701770177017701770177017701770177017701770177013881388138813881388138813881388138813881388138813881388138813881388138813881388138813881388138813880fa00fa00fa00fa00fa00fa00fa00fa00fa00fa00fa00fa00fa00fa00fa00fa00fa00fa00fa00fa00fa00fa00fa00fa00fa00bb80bb80bb80bb80bb80bb80bb80bb80bb80bb80bb80bb80bb80bb80bb80bb80bb80bb80bb80bb80bb80bb80bb80bb80bb809c409c409c409c409c409c409c409c409c409c409c409c409c409c409c409c409c409c409c409c409c409c409c409c409c407d007d007d007d007d007d007d007d007d007d007d007d007d007d007d007d007d007d007d007d007d007d007d007d007d006d606d606d606d606d606d606d606d606d606d606d606d606d606d606d606d606d606d606d606d606d606d606d606d606d605dc05dc05dc05dc05dc05dc05dc05dc05dc05dc05dc05dc05dc05dc05dc05dc05dc05dc05dc05dc05dc05dc05dc05dc05dc05dc05dc05dc05dc04e204e204e204e204e204e204e204e204e204e204e204e204e204e204e204e204e204e204e204e204e205dc05dc05dc05dc04d603e803e803e803e803e803e803e803e803e803e803e803e803e803e803e803e803e803e803e803e805dc05dc05dc05dc04d103a9038403840384038403840384038403840384038403840384038403840384038403840384038405dc05dc05dc05dc04cd038f032003200320032003200320032003200320032003200320032003200320032003200320032005dc05dc05dc05dc04b2038402e602bc02bc02bc02bc02bc02bc02bc02bc02bc02bc02bc02bc02bc02bc02bc02bc02bc02bc05dc05dc05dc05dc04ad034a02c502760258025802580258025802580258025802580258025802580258025802580258025805dc05dc05dc05dc04a8033e02970268023b01f401f401f401f401f401f401f401f401f401f401f401f401f401f401f401f405dc05dc05dc05dc04a40333028e0249022701e90190019001900190019001900190019001ad01ad0190019001900190019005dc05dc05dc05dc045302cc02610241022001e00197015d012c014601650177016e0178017a015c01580153014c012c012c05dc05dc05dc05dc044902c1025a022301fa01c8018e014a0131011b01400152014a0156012f012d012600c800c800c800c805dc05dc05dc05dc043f0279023401fc01e801bb0184014001240108011d0130012a0137010100640064006400640064006405dc05dc05dc02e8029a0271022e01eb01d201af017f013a011800fe00d800ea010f00da0045000000000000000000000000026502600259024c0239022501ed01d801c601a501710134011000f400c000ce009900ae003cfff1ff9cff9cff9cff9cff9c0230022c0227021f01fe01f001e001cd01bc019b016b012c010a00e800aa00a9007300310008ffd7ff8fff75ff75ff74ff7402130211020601ff01f201e401d001c301b6019601620123010400df009c00440018fffffffcffd1ff8bff72ff71ff71ff71020001fe01f901f301e701d501c701bd01ad018d015a011b00f700d20088002e0004ffecffd8ffaeff7fff6eff6dff6dff6d01f001ee01ea01e401d901cc01be01b101a101820150010f00eb00c2005c000affe5ffdaffc9ff9cff78ff68ff67ff67ff6701e201e101dc01d601cb01bf01b201a5019501780146010400df00b4ffd7ffcaffc1ffb7ffacff92ff71ff61ff61ff60ff6001d501d301ce01c901bf01b301a60199018a016d013b00f800d100a1ffa2ff9cff90ff89ff82ff76ff64ff59ff59ff58ff5801c701c601c201bc01b301a8019a018d017f0160012f00ec00c2ff8aff88ff7fff73ff6bff67ff5fff4dff44ff43ff42ff4201bb01ba01b601b001a7019b018e0182017301550122ff7bff7bff7bff7aff72ff64ff59ff54ff4fff41ff37ff37ff36ff3601ae01ad01a901a3019a018e01820176016701490116ff6fff70ff70ff70ff67ff5aff4fff4bff48ff3dff34ff33ff33ff32018e018d01890183017b016f01620156ff5eff5bff57ff58ff59ff5bff5aff51ff45ff3cff37ff33ff30ff29ff27ff27ff270171016f016b0165015bff51ff4fff4dff4bff49ff47ff49ff4bff4cff4bff42ff38ff30ff2aff26ff23ff21ff20ff1fff1f01550153014f014aff44ff41ff3fff3eff3cff3bff3cff40ff42ff43ff3dff34ff2bff24ff1eff1aff17ff14ff13ff12ff12ff44ff43ff41ff3fff3cff39ff37ff35ff33ff32ff34ff38ff3aff38ff31ff28ff21ff1bff14ff10ff0dff0bff0aff09ff09ff33ff32ff2fff2dff2aff26ff23ff22ff23ff27ff2bff2aff27ff25ff1eff18ff12ff0bff05ff01fefdfefbfefafef9fef9ff36ff35ff32ff30ff2dff29ff26ff24ff22ff20ff1eff1aff19ff16ff11ff0cff06ff01fefbfef6fef3fef1fef0feeffeefff20ff20ff1eff1bff18ff15ff13ff11ff0fff0dff0aff08ff06ff04ff00fefcfef7fef2feedfee7fee4fee1fee0fedffedfff13ff13ff11ff0eff0bff08ff06ff04ff03ff01fefffefcfefbfef9fef5fef2feeefee9fee2feddfed9fed7fed5fed5fed4ff0bff0aff09ff06ff03ff00fefefefcfefbfef9fef7fef4fef3fef2feeffeecfee8fee3feddfed7fed3fed1fed0fecffecfff00fefffefefefbfef8fef6fef4fef2fef1feeffeeefeecfeebfee9fee7fee4fee0fedbfed5fecffecbfec9fec8fec7fec7"; function _mul(int256 x, int256 y) private pure returns (int256) { return x*y/U; } function _div(int256 x, int256 y) private pure returns (int256) { return x*U/y; } function _abs(int256 x) private pure returns (int256) { return x < 0 ? -x : x; } function _ln(int256 x) private pure returns (int256) { require(x > 0); int256 k; while (x > 1500000000000000000) { x /= 2; ++k; } while (x < 750000000000000000) { x *= 2; --k; } int256 z = _div(x-U,x+U); int256 z2 = _mul(z,z); int256 t=z; int256 s=z; for (int256 i=3; i<=7; i+=2) { t=_mul(t,z2); s+=t/i; } return 2*s+k*LN2; } function _exp(int256 x) private pure returns (int256) { if (x <= -40000000000000000000) return 0; uint256 n; while (_abs(x) > 62500000000000000) { x /= 2; ++n; } int256 s=U; int256 t=U; for (int256 i=1;i<=4;++i) { t=_mul(t,x)/i; s+=t; } for (uint256 j=0;j= 8000000000000000000) return 0; return _mul(398942280401432677,_exp(-_mul(x,x)/2)); } function _Phi(int256 x) private pure returns (int256) { if (x <= -8000000000000000000) return 0; if (x >= 8000000000000000000) return U; int256 t=_div(U,U+_mul(231641900000000000,_abs(x))); int256 p=1330274429000000000; p=-1821255978000000000+_mul(t,p); p=1781477937000000000+_mul(t,p); p=-356563782000000000+_mul(t,p); p=319381530000000000+_mul(t,p); int256 tail=_mul(_phi(x),_mul(t,p)); return x>=0 ? U-tail : tail; } function _sqrt(int256 v) private pure returns (int256) { if (v<=0) return 0; return int256(sqrt(uint256(v)*uint256(U))); } function _trunc(int256 m,int256 v,int256 lo,int256 hi) private pure returns (int256 z,int256 mt,int256 vt) { if (v<=0) return (lo<=m && m<=hi ? U : int256(0),m,0); int256 sd=_sqrt(v); int256 a=_div(lo-m,sd); int256 b=_div(hi-m,sd); z=_Phi(b)-_Phi(a); if (z<1000000) return (z,m0 ? _mul(v,vv) : int256(0); } function _read(bytes memory tab,uint256 word) private pure returns (int256 v) { uint256 raw=uint256(uint8(tab[2*word]))*256+uint256(uint8(tab[2*word+1])); v=raw>=32768 ? int256(raw)-65536 : int256(raw); } function _locate(bytes memory tab,uint256 start,uint256 len,int256 q) private pure returns (uint256 i,int256 f) { int256 first=_read(tab,start)*U; if (q<=first) return (0,0); int256 last=_read(tab,start+len-1)*U; if (q>=last) return (len-2,U); uint256 hi=len-1; while (hi-i>1) { uint256 mid=(i+hi)/2; if (_read(tab,start+mid)*U<=q) i=mid; else hi=mid; } f=_div(q-_read(tab,start+i)*U,(_read(tab,start+i+1)-_read(tab,start+i))*U); } function _grid(bytes memory tab,uint256 off,uint256 cols,uint256 i,uint256 j, int256 f,int256 g) private pure returns (int256) { int256 v00=_read(tab,off+i*cols+j)*U; int256 v10=_read(tab,off+(i+1)*cols+j)*U; int256 v01=_read(tab,off+i*cols+j+1)*U; int256 v11=_read(tab,off+(i+1)*cols+j+1)*U; return _mul(v00+_mul(v10-v00,f),U-g)+_mul(v01+_mul(v11-v01,f),g); } function _fees(int256 w,int256 r,uint256 phase) private pure returns (uint256 fb,uint256 fa) { bytes memory tab=TABLE; (uint256 i,int256 f)=_locate(tab,0,41,w*100000); uint256 j; int256 g; uint256 cols; uint256 off; if (phase==0) { int256 q=r*100000; if (q< -300*U) q=-300*U; if (q>300*U) q=300*U; j=uint256((q+300*U)/(50*U)); if (j>11) j=11; g=_div(q+300*U-int256(j)*50*U,50*U); cols=13; off=66; } else { (j,g)=_locate(tab,41,25,r*100000); cols=25; off=66+2*41*13+(phase-1)*2*41*25; } int256 a=_grid(tab,off,cols,i,j,f,g); int256 b=_grid(tab,off+41*cols,cols,i,j,f,g); int256 ww=w*100000; int256 bid=b+ww; int256 ask=a-ww; int256 bv=bid>0 ? U-_exp(-bid/100000) : int256(0); int256 av=ask>0 ? U-_exp(-ask/100000) : int256(0); fb=clampFee(uint256(bv)); fa=clampFee(uint256(av)); } function afterInitialize(uint256 x,uint256 y) external override returns (uint256 fb,uint256 fa) { int256 s=int256(y*uint256(U)/x); fb=2825999324860051;fa=fb; // compressed table at w=r=0, phase 0 slots[0]=uint256(uint128(int128(_ln(s/100)))); slots[2]=fb | fa<<64; slots[3]=uint256(s) | uint256(s)<<128; slots[4]=0; } function afterSwap(TradeInfo calldata tr) external override returns (uint256 fb,uint256 fa) { int256 s=int256(tr.reserveY*uint256(U)/tr.reserveX); int256 lns=_ln(s/100); uint256 beliefSlot=slots[0]; int256 m=int256(int128(uint128(beliefSlot))); int256 v=int256(uint256(uint128(beliefSlot>>128))); uint256 feeSlot=slots[2]; int256 oldFb=int256(uint256(uint64(feeSlot)));int256 oldFa=int256(uint256(uint64(feeSlot>>64))); uint256 spotSlot=slots[3]; int256 sp=int256(uint256(uint128(spotSlot)));int256 s2=int256(uint256(uint128(spotSlot>>128))); uint256 state=slots[4];uint256 last=uint32(state); uint256 cnt=uint16(state>>32); bool synced=uint8(state>>48)!=0; bool isArb=false; if (tr.timestamp>last) { uint256 dt=tr.timestamp-last;cnt=0; int256 lnsp=_ln(sp/100); int256 lo=lnsp+_ln(U-oldFb); int256 hi=lnsp-_ln(U-oldFa); uint256 silent=dt-1;if (silent>12) silent=12; for (uint256 h=0;h0) (,m,v)=_trunc(m,v,lo,hi); v+=SIG2; int256 lp=tr.isBuy ? lns+_ln(U-oldFb) : lns-_ln(U-oldFa); int256 sd=_sqrt(v); int256 larb=_div(_phi(_div(lp-m,sd)),sd); (int256 z,int256 mt,int256 vt)=_trunc(m,v,lo,hi); int256 d=_abs(lns-lnsp); if (d<1000000000) d=1000000000; int256 ld=_div(_ln(d)-LDM,LDS); int256 lret=_mul(_mul(z,RHO),_div(_phi(ld),_mul(d,LDS))); int256 pi=larb+lret>0 ? _div(larb,larb+lret) : int256(0); isArb=pi>U/2; if (pi>5000000000000000 && pi<995000000000000000) { int256 m2=_mul(pi,lp)+_mul(U-pi,mt); int256 v2=_mul(pi,_mul(lp-m2,lp-m2)) +_mul(U-pi,vt+_mul(mt-m2,mt-m2)); m=m2;v=v2; } else if (isArb) {m=lp;v=0;} else {m=mt;v=vt;} int256 pe=100*_exp(m); int256 low=_mul(pe,G);int256 high=_div(pe,G); if(s2high)s2=high; synced=false; } if (!isArb) { int256 cand=tr.isBuy ? _div(_mul(s,U-oldFb),G) : _div(_mul(s,G),U-oldFa); if (tr.isBuy && cands2) {s2=cand;synced=true;} ++cnt; } uint256 phs=isArb ? 0 : (cnt<=1 ? 1 : 2); (fb,fa)=_fees(lns-m,_ln(s2/100)-m,phs); slots[0]=uint256(uint128(int128(m))) | uint256(uint128(uint256(v)))<<128; slots[2]=fb | fa<<64; slots[3]=uint256(s) | uint256(s2)<<128; slots[4]=tr.timestamp | cnt<<32 | (synced ? uint256(1)<<48 : 0); } function getName() external pure override returns (string memory) {return "TaylorGaussianPlain2";} } ``` ### reference.py ```python """Exact shipped-table Python reference for Taylor's Gaussian plain policy. Run from this directory: python3 -I reference.py [choose|hold]. """ import math, pathlib, struct, sys, multiprocessing, re ROOT=pathlib.Path(__file__).resolve().parent sys.path.insert(0,str(ROOT/'taylor/research/solved')) import real, replica2 _ORIGINAL_TRUNC=real.trunc _SILENT_LEFT=0 def _trunc_port(m,v,lo,hi): global _SILENT_LEFT if _SILENT_LEFT: _SILENT_LEFT-=1 # Aggregate the capped silent-step variance, then truncate once. # real.py adds SIG2 before each call to this hook. return _ORIGINAL_TRUNC(m,v,lo,hi) if not _SILENT_LEFT else (1.,m,v) return _ORIGINAL_TRUNC(m,v,lo,hi) real.trunc=_trunc_port SOURCE=(ROOT/'amm-challenge/contracts/src/Strategy.sol').read_text() RAW=bytes.fromhex(re.search(r'bytes private constant TABLE = hex"([0-9a-f]+)"',SOURCE).group(1)) WORDS=struct.unpack('>'+str(len(RAW)//2)+'h',RAW) W=WORDS[:41]; R=WORDS[41:66] assert len(RAW)==10464 def locate(knots,x): if x<=knots[0]: return 0,0. if x>=knots[-1]: return len(knots)-2,1. lo,hi=0,len(knots)-1 while hi-lo>1: mid=(lo+hi)//2 if knots[mid]<=x: lo=mid else: hi=mid return lo,(x-knots[lo])/(knots[lo+1]-knots[lo]) def lookup(w,r,p): i,f=locate(W,w*10) if p==0: z=max(-300.,min(300.,r*10)); j=min(11,int((z+300)//50)); g=(z+300-50*j)/50; cols=13 else: j,g=locate(R,r*10); cols=25 base=66+(0 if p==0 else 2*41*13+((p-1)*2*41*25)) def val(side): off=base+side*41*cols x=WORDS[off+i*cols+j]; y=WORDS[off+(i+1)*cols+j] x2=WORDS[off+i*cols+j+1]; y2=WORDS[off+(i+1)*cols+j+1] return ((x*(1-f)+y*f)*(1-g)+(x2*(1-f)+y2*f)*g)/10 a,b=val(0),val(1) fa=1-math.exp(-(a-w)*1e-4) if a>w else 0. fb=1-math.exp(-(b+w)*1e-4) if b>-w else 0. return fb,fa class PortReal(real.RealPolicy): def on_trade(self,is_buy,ax,ay,t,x,y,arb,p,s2,j): global _SILENT_LEFT _SILENT_LEFT=min(max(0,t-self.tlast-1),12) return super().on_trade(is_buy,ax,ay,t,x,y,arb,p,s2,j) class CompressedReal(PortReal): def __init__(self): super().__init__(real.load(str(ROOT/'taylor/research/solved/pol_mid.json')),{'soft':1}) def _fees(self,w,w2,ph): return lookup(w,w2,ph) def worker(args): seed,kind=args p=CompressedReal() if kind=='compressed' else PortReal(real.load(str(ROOT/'taylor/research/solved/pol_mid.json')),{'soft':1}) return seed,replica2.run(seed,p)['edge'] def score(seeds): jobs=[(s,k) for s in seeds for k in ('compressed','full')] with multiprocessing.Pool(8) as pool: out={(job[0],job[1]):edge for job,(_,edge) in zip(jobs,pool.map(worker,jobs,chunksize=4))} diffs=[out[s,'compressed']-out[s,'full'] for s in seeds] mean=sum(diffs)/len(diffs); se=(sum((x-mean)**2 for x in diffs)/(len(diffs)-1)/len(diffs))**.5 return {'n':len(diffs),'mean_diff':mean,'se':se,'worst5':sorted(diffs)[:5], 'compressed_mean':sum(out[s,'compressed'] for s in seeds)/len(seeds), 'full_mean':sum(out[s,'full'] for s in seeds)/len(seeds)} if __name__=='__main__': mode=sys.argv[1] seeds=range(60000,61024) if mode=='choose' else range(10000,12048) print(mode,score(seeds),flush=True) ``` ### engine.py ```python """Pinned Rust engine comparison, segmented: python engine.py .""" import json, pathlib, sys, statistics, math ROOT=pathlib.Path(__file__).resolve().parent sys.path.insert(0,str(ROOT/'amm-challenge')) import amm_sim_rs from amm_competition.evm.compiler import SolidityCompiler from amm_competition.competition.match import MatchRunner from amm_competition.competition.config import BASELINE_VARIANCE,build_base_config def compile_source(path,name='Strategy'): result=SolidityCompiler().compile(path.read_text(),contract_name=name) assert result.success,result.errors return result.bytecode,len(result.deployed_bytecode) def configs(start,count): runner=MatchRunner(n_simulations=64,config=build_base_config(seed=None), n_workers=8,variance=BASELINE_VARIANCE) allcfg=runner._build_configs() selected=allcfg[start:start+count] for i,c in enumerate(selected,start): c.seed=9510064+i return selected def main(start,count): ours,size=compile_source(ROOT/'amm-challenge/contracts/src/Strategy.sol') t03,tsize=compile_source(ROOT/'t03.sol') van,_=compile_source(ROOT/'amm-challenge/contracts/src/VanillaStrategy.sol','VanillaStrategy') cfg=configs(start,count) allout={};allgas={} for label,code in [('ours',ours),('t03',t03)]: amm_sim_rs.gas_stats_reset() out=amm_sim_rs.run_batch(code,van,cfg,8) allgas[label]=amm_sim_rs.gas_stats() print(label,'gas',allgas[label],flush=True) print(label,'first',out.results[0].seed,out.results[0].edges,flush=True) allout[label]={r.seed:r.edges['submission'] for r in out.results} diffs=[allout['ours'][c.seed]-allout['t03'][c.seed] for c in cfg] mean=statistics.mean(diffs) report={'start':start,'count':count,'deployed_size':size,'t03_size':tsize, 'diffs':diffs,'mean_diff':mean,'se':statistics.stdev(diffs)/math.sqrt(len(diffs)) if len(diffs)>1 else None, 'worst5':sorted(diffs)[:5],'gas':allgas, 'ours':allout['ours'],'t03':allout['t03']} (ROOT/f'engine_{start}_{count}.json').write_text(json.dumps(report,indent=2)) print('paired',report['mean_diff'],report['se'],flush=True) if __name__=='__main__':main(int(sys.argv[1]),int(sys.argv[2])) ``` ### gate_f.py ```python """Record replica callbacks and replay them through the EVM port. Run in the pinned checkout: python ../gate_f.py . Each run records the first N callbacks on the Python reference's own market. """ import json,pathlib,sys,math from decimal import Decimal as D ROOT=pathlib.Path(__file__).resolve().parent sys.path.insert(0,str(ROOT)) sys.path.insert(0,str(ROOT/'amm-challenge')) import reference from amm_competition.evm.compiler import SolidityCompiler from amm_competition.evm.executor import EVMStrategyExecutor from amm_competition.core.trade import TradeInfo class Done(Exception):pass class Recorder(reference.CompressedReal): def __init__(self,limit): super().__init__();self.limit=limit;self.callbacks=[] def on_trade(self,is_buy,ax,ay,t,x,y,arb,p,s2,j): if len(self.callbacks)>=self.limit: raise Done fees=super().on_trade(is_buy,ax,ay,t,x,y,arb,p,s2,j) self.callbacks.append((is_buy,ax,ay,t,x,y,fees)) return fees def main(first,count,n): src=(ROOT/'amm-challenge/contracts/src/Strategy.sol').read_text() comp=SolidityCompiler().compile(src);assert comp.success,comp.errors summary={'runs':count,'callbacks_per_run':n,'total':0,'mean_bps':None,'max_bps':0.,'max_case':None,'sum_bps':0.,'oog':0} for run in range(first,first+count): seed=70000+run;rec=Recorder(n) try:reference.replica2.run(seed,rec,n_steps=10000) except Done:pass assert len(rec.callbacks)==n,(seed,len(rec.callbacks)) exe=EVMStrategyExecutor(comp.bytecode) init=exe.after_initialize(D(100),D(10000));assert init.success,init.error for k,(buy,ax,ay,t,x,y,(fb,fa)) in enumerate(rec.callbacks): trade=TradeInfo(side='buy' if buy else 'sell',amount_x=D(str(ax)),amount_y=D(str(ay)), timestamp=t,reserve_x=D(str(x)),reserve_y=D(str(y))) try:vb,va=exe.after_swap_fast(trade) except Exception as e: summary['oog']+=1 print('failure',seed,k,str(e),flush=True) break fb=max(0.,min(.1,fb));fa=max(0.,min(.1,fa)) err=max(abs(vb/1e18-fb),abs(va/1e18-fa))*1e4 summary['sum_bps']+=err;summary['total']+=1 if err>summary['max_bps']: summary['max_bps']=err;summary['max_case']=[seed,k,t,fb,fa,vb/1e18,va/1e18] print('run',run,'max',summary['max_bps'],'total',summary['total'],flush=True) summary['mean_bps']=summary['sum_bps']/summary['total'] if summary['total'] else None (ROOT/f'gate_f_{first}_{count}_{n}.json').write_text(json.dumps(summary,indent=2)) print(summary,flush=True) if __name__=='__main__':main(*map(int,sys.argv[1:4])) ``` ### tablegen.py ```python """Sample Taylor's plain policy on a compact nonuniform grid. Wire format: big-endian signed int16, in deci-bps. The first 41 words are own-displacement knots, the next 25 are rival-displacement knots (both deci-bps). Next come A0,B0,A1,B1,A2,B2, row-major. Phase 0 has 13 columns at -30..30 bps; phases 1/2 have 25 columns from the header. No padding. """ import json, pathlib, struct ROOT = pathlib.Path(__file__).parent T = json.loads((ROOT / 'taylor/research/solved/pol_mid.json').read_text()) W = sorted(set(range(-100, 101, 10)) | {s*x for s in (-1, 1) for x in (125, 150, 175, 200, 250, 300, 400, 500, 600, 800)}) R = [-800,-500,-300,-200,-125,-85,-60,-45,-35,-25,-15,-5,0,5,15,25,35,45,60,85,125,200,300,500,800] assert len(W) == 41 and len(R) == 25 def pos2(x): q = T['W2L'] if x <= q[0]: return 0., 0 if x >= q[-1]: return 0., len(q)-1 for i in range(len(q)-1): if q[i] <= x < q[i+1]: return (x-q[i])/(q[i+1]-q[i]), i raise AssertionError def bl(a,w,r,phase): pw = min(320., max(0., w/5+160)); i = min(319,int(pw)); f = pw-i if phase == 0: pr = min(12.,max(0.,r/5+6)) else: g,j=pos2(r/5); pr = j+g j = min(len(a[0])-2,int(pr));g=pr-j return ((a[i][j]*(1-f)+a[i+1][j]*f)*(1-g) +(a[i][j+1]*(1-f)+a[i+1][j+1]*f)*g) words = [10*x for x in W+R] for p in range(3): cols = list(range(-30,31,5)) if p == 0 else R for side in 'AB': a = T[side+str(p)] for w in W: for r in cols: words.append(round(10*bl(a,w,r,p))) assert all(-32768 <= v <= 32767 for v in words) (ROOT/'table.bin').write_bytes(struct.pack('>'+str(len(words))+'h',*words)) print('rows',len(W),'rival',len(R),'words',len(words),'bytes',2*len(words)) ``` ### build.py ```python """Embed the checked-in packed table into the standalone Strategy.sol source.""" from pathlib import Path root=Path(__file__).resolve().parent source=(root/'Strategy.template.sol').read_text().replace('__TABLE_HEX__',(root/'table.bin').read_bytes().hex()) (root/'amm-challenge/contracts/src/Strategy.sol').write_text(source) print('source bytes',len(source)) ``` ### gas_probe.py ```python """Binary-search pyrevm call gas on isolated callbacks; run from challenge checkout.""" from pathlib import Path from decimal import Decimal as D from amm_competition.evm.compiler import SolidityCompiler from amm_competition.evm.executor import EVMStrategyExecutor from amm_competition.core.trade import TradeInfo code=SolidityCompiler().compile(Path('contracts/src/Strategy.sol').read_text()).bytecode for dt in [0,1,2,13]: lo,hi=100000,1000000 t=TradeInfo(side='buy',amount_x=D('.1'),amount_y=D('10'),timestamp=dt, reserve_x=D('100.1'),reserve_y=D('9990')) for _ in range(17): mid=(lo+hi)//2 exe=EVMStrategyExecutor(code) exe.after_initialize(D(100),D(10000)) exe.GAS_LIMIT_TRADE=mid try: exe.after_swap_fast(t);hi=mid except Exception:lo=mid+1 print(dt,hi,flush=True) ``` ### setup.sh ```sh set -eu;R=$PWD/scratch;mkdir -p $R/tmp $R/bin $R/solcx echo "export TMPDIR=$R/tmp XDG_CACHE_HOME=$R/xc UV_CACHE_DIR=$R/uvc UV_PYTHON_INSTALL_DIR=$R/uvpy SOLCX_BINARY_PATH=$R/solcx VIRTUAL_ENV=$PWD/.venv PATH=$PWD/.venv/bin:$R/bin:\$PATH" >$R/env.sh;. $R/env.sh command -v uv >/dev/null||{ curl -LsSf https://github.com/astral-sh/uv/releases/latest/download/uv-x86_64-unknown-linux-gnu.tar.gz|tar --no-same-owner -xz -C $R/tmp;cp $R/tmp/uv-*/uv $R/bin/;} W=amm_sim_rs-0.1.0.post1-cp310-abi3-manylinux2014_x86_64.manylinux_2_17_x86_64.whl;curl -LsSf https://github.com/gtmcknight/amm-sim/releases/download/sim-6b6921f8/$W -o $R/$W echo "aedb68280aca34c110968f00148387c95885207913fb2cf19a1ab4c5cfd6887a $R/$W"|sha256sum -c - uv venv --python 3.12 .venv;uv pip install $R/$W numpy numba cma py-solc-x==2.1.0 pyrevm==0.3.7;uv pip install --no-deps -e . python -c "import solcx;solcx.install_solc('0.8.24')" amm-match validate contracts/src/StarterStrategy.sol ```