degenbot-simulation 0.6.0-alpha.14

In-process revm simulation executor + dispatch fan-out (pyo3-free core; ADR-019 D4 fold).
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
//! Executor grammar harness.
//!
//! The missing third correctness tool for the swap-encoding grammar: byte
//! parity (the golden corpus) only pins bytes and proves nothing at runtime,
//! while a live sim needs a captured mainnet path per family. This harness
//! deploys the **real** `cmd_executor` bytecode + synthesized pools into a
//! fresh revm `CacheDB<EmptyDB>` and runs a path's
//! [`encode_cmd_stream`](degenbot_executor::composers::encode_cmd_stream)
//! payload through `execute()`, reporting whether it executes, which pools it
//! touched (via `Swap` events), and how it failed — with the production
//! `FailBucket` vocabulary. A composer change therefore regresses only its
//! permutation, with a visible result instead of a silent byte-only assumption.
//!
//! Design (ADR-020 "extend the tier-3 oracles"): reuse the real `cmd_executor`
//! artifact (deploy-proven by [`crate::oracle`]'s fixture driver) + the SWAP
//! math already proven by the tier-3 V2 oracles. The only synthesized pieces
//! are a minimal full-ERC20 `Token` and a Uniswap-V2-faithful `Pair` (see
//! `tier3-oracle/src-harness/V2ExecutorStub.sol`) — enough custody/ordering to
//! exercise the executor's command stream + flash/repay, the exact funding-
//! topology risk the funding-topology conversions are blocked on.
//!
//! This is a fixture/investigation harness (the revm-deploy + seed + execute
//! spine), so it carries the same permits as the `oracle` fixture driver: it
//! may panic/expect on a bad artifact or a broken fixture step (a harness
//! problem, not a verdict) and its doc is `# Errors`/`# Panics`-annotated.
#![expect(
    clippy::expect_used,
    clippy::panic,
    clippy::unwrap_used,
    clippy::missing_errors_doc,
    clippy::missing_panics_doc,
    clippy::doc_markdown,
    clippy::cast_possible_wrap,
    clippy::too_many_arguments
)]

use alloy::primitives::aliases::{I24, U24};
use alloy::primitives::{keccak256, Address, Bytes, U160, U256, U512};
use alloy::sol_types::{SolCall, SolValue};
use revm::context::TxEnv;
use revm::context_interface::result::Output;
use revm::primitives::TxKind;
use revm::{ExecuteCommitEvm, ExecuteEvm};
use std::path::PathBuf;

use crate::oracle::{
    call_bytes, decode_error_string, deploy, native_balance_of, new_fixture_evm,
    set_code_size_limits, set_disable_nonce_check, set_native_balance, set_tx_gas_limit_cap,
    transact, FixtureEvm, TxSpec, Verdict,
};

pub mod declarative;
pub use declarative::{assert_erc6909_capture, assert_profitable, ChainResult, Hop, HopPool};

/// Repo root = this crate + four up.
fn repo_root() -> PathBuf {
    PathBuf::from(env!("CARGO_MANIFEST_DIR"))
        .join("../../../..")
        .canonicalize()
        .expect("canonicalize repo root")
}

/// Read a whole hex file (`0x`-less or prefixed, whitespace tolerated).
fn load_hex(rel: &str) -> Vec<u8> {
    let raw = std::fs::read_to_string(repo_root().join(rel))
        .unwrap_or_else(|e| panic!("read {rel}: {e}"));
    let s: String = raw.trim().chars().filter(|c| !c.is_whitespace()).collect();
    let s = s.strip_prefix("0x").unwrap_or(&s);
    alloy::hex::decode(s).expect("hex decodes")
}

/// ABI-encode the two `__init__(address weth, address pool_manager)` args.
fn executor_deploy_args(weth: Address, pool_manager: Address) -> Vec<u8> {
    (weth, pool_manager).abi_encode()
}

/// Load a `Token`/`Pair`-style foundry artifact's creation bytecode
/// (`bytecode.object`) from `tier3-oracle/artifacts/harness/<contract>.json`.
fn load_stub_creation(contract: &str) -> Vec<u8> {
    let rel = format!("tier3-oracle/artifacts/harness/{contract}.json");
    let raw = std::fs::read_to_string(repo_root().join(&rel))
        .unwrap_or_else(|e| panic!("read {rel}: {e}"));
    crate::oracle::parse_foundry_creation_bytecode(&raw)
        .unwrap_or_else(|e| panic!("parse {contract}: {e}"))
}

/// A single synthesized V2 pool: one `Pair` contract + its two `Token`s,
/// in the pair's **sorted** token order, with the seeded (sorted) reserves.
#[derive(Debug, Clone, Copy)]
pub struct V2Pool {
    pub pair: Address,
    /// The pair's `token0` (lower address).
    pub token0: Address,
    /// The pair's `token1` (higher address).
    pub token1: Address,
    /// Seeded reserve of `token0`.
    pub reserve0: u128,
    /// Seeded reserve of `token1`.
    pub reserve1: u128,
}

/// A single synthesized V3 pool: one `PoolV3` contract + its two `Token`s
/// (order fixed by the harness, matching `PoolV3.initialize`, which does not
/// sort).
#[derive(Debug, Clone, Copy)]
pub struct V3Pool {
    pub pool: Address,
    pub token0: Address,
    pub token1: Address,
    /// Fee in hundredths of a bip (e.g. 3000 = 0.3%).
    pub fee: u32,
    /// Q64.96 sqrt price.
    pub sqrt_price: U256,
    /// Active liquidity.
    pub liquidity: u128,
}

/// A single synthesized V4 pool inside the shared `PoolManager` stub: a
/// `(currency0, currency1, fee, tick_spacing)` pool key + its seeded price/
/// liquidity.
#[derive(Debug, Clone, Copy)]
pub struct V4Pool {
    pub currency0: Address,
    pub currency1: Address,
    /// Fee in hundredths of a bip (uint24).
    pub fee: u32,
    pub tick_spacing: i32,
    pub sqrt_price: U256,
    pub liquidity: u128,
}

/// A running harness: the real executor + a set of synthesized tokens/pools in
/// one fresh revm `CacheDB<EmptyDB>`.
pub struct Harness {
    pub evm: FixtureEvm,
    pub executor: Address,
    /// The token address the executor treats as WETH (its immutable `WETH_ADDR`).
    pub weth: Address,
    /// The deployed PoolManager stub (the executor's immutable `POOL_MANAGER_ADDR`).
    pub pool_manager: Address,
    /// All deployed V2 pools (in `add_pool` call order).
    pub pools: Vec<V2Pool>,
    /// All deployed V3 pools (in `add_v3_pool` call order).
    pub v3_pools: Vec<V3Pool>,
    /// All registered V4 pools (in `add_v4_pool` call order).
    pub v4_pools: Vec<V4Pool>,
    /// All deployed tokens (deduped across pools, `add_pool` discovery order).
    pub tokens: Vec<Address>,
}

impl Harness {
    /// Build a fresh harness: revm over `CacheDB<EmptyDB>`, deploy the real
    /// executor (creation bytes + weth/pm constructor args) + a WETH token.
    pub fn new() -> Result<Self, String> {
        let mut evm = new_fixture_evm();
        set_disable_nonce_check(&mut evm, true);
        set_code_size_limits(&mut evm, None); // executor init + runtime are large
                                              // The executor creation + a long command stream can exceed the default
                                              // EIP-7825 per-tx cap; lift it for the harness.
        set_tx_gas_limit_cap(&mut evm, u64::MAX);

        // Deploy a WETH token first; its address is the executor's WETH_ADDR.
        let weth = deploy(
            &mut evm,
            Bytes::from(load_stub_creation("Token")),
            8_000_000,
        )?;

        // Deploy the PoolManager stub before the executor — its address is the
        // executor's immutable POOL_MANAGER_ADDR (V4 paths route swaps/deltas
        // through it).
        let pm = deploy(
            &mut evm,
            Bytes::from(load_stub_creation("PoolManager")),
            8_000_000,
        )?;
        let mut init = load_hex("tier3-oracle/artifacts/executor/cmd_executor.creation.hex");
        init.extend_from_slice(&executor_deploy_args(weth, pm));
        let executor = deploy(&mut evm, Bytes::from(init), 30_000_000)?;

        Ok(Self {
            evm,
            executor,
            weth,
            pool_manager: pm,
            pools: Vec::new(),
            v3_pools: Vec::new(),
            v4_pools: Vec::new(),
            tokens: vec![weth],
        })
    }

    /// Deploy any committed stub artifact (`Token`/`Pair`/`PoolV3`/… by name)
    /// at a fresh CREATE address and return it.
    pub fn deploy_stub(&mut self, name: &str) -> Result<Address, String> {
        deploy(
            &mut self.evm,
            Bytes::from(load_stub_creation(name)),
            8_000_000,
        )
    }

    /// Deploy a fresh `Token` (a ^0.8 minimal full-ERC20) and return its address.
    pub fn add_token(&mut self) -> Result<Address, String> {
        let t = deploy(
            &mut self.evm,
            Bytes::from(load_stub_creation("Token")),
            8_000_000,
        )?;
        self.tokens.push(t);
        Ok(t)
    }

    /// Deploy a V2 pair over `token_a`/`token_b`, seed reserves (mint to the
    /// pair + `sync`), return the pool. The pair's interior `token0`/`token1`
    /// are **sorted by address** (matching `Pair.initialize`), so the returned
    /// `V2Pool` is in that sorted order; `reserve_a`/`reserve_b` must be passed
    /// in the same order as `token_a`/`token_b`.
    pub fn add_pool(
        &mut self,
        token_a: Address,
        token_b: Address,
        reserve_a: u128,
        reserve_b: u128,
    ) -> Result<V2Pool, String> {
        let pair = deploy(
            &mut self.evm,
            Bytes::from(load_stub_creation("Pair")),
            8_000_000,
        )?;
        // initialize(tokenA, tokenB) — sorts internally.
        let _ = self.call(pair, &init_pair(token_a, token_b), 500_000)?;

        // Map reserves to the pair's sorted token order.
        let (t0, r0) = if token_a < token_b {
            (token_a, reserve_a)
        } else {
            (token_b, reserve_b)
        };
        let (t1, r1) = if token_a < token_b {
            (token_b, reserve_b)
        } else {
            (token_a, reserve_a)
        };

        // Seed reserves: mint `r0`/`r1` of each token to the pair, then `sync()`
        // so slot reserves equal the live balances (ADR-020 D4).
        self.call(t0, &mint_to(pair, r0), 200_000)?;
        self.call(t1, &mint_to(pair, r1), 200_000)?;
        let _ = self.call(pair, &sync_selector(), 200_000)?;

        for t in [t0, t1] {
            if !self.tokens.contains(&t) {
                self.tokens.push(t);
            }
        }
        let pool = V2Pool {
            pair,
            token0: t0,
            token1: t1,
            reserve0: r0,
            reserve1: r1,
        };
        self.pools.push(pool);
        Ok(pool)
    }

    /// Deploy a V3 pool over `token_a`/`token_b` at `fee` (hundredths of a
    /// bip), set its Q64.96 price + liquidity, and mint `amt_a`/`amt_b` of
    /// each token to the pool (so it can send swap output). Token order is
    /// fixed by the caller (matching `PoolV3.initialize`, which does not
    /// sort) — `a` is `token0`, `b` is `token1`.
    pub fn add_v3_pool(
        &mut self,
        token_a: Address,
        token_b: Address,
        fee: u32,
        sqrt_price: U256,
        liquidity: u128,
        amt_a: u128,
        amt_b: u128,
    ) -> Result<V3Pool, String> {
        let pool = deploy(
            &mut self.evm,
            Bytes::from(load_stub_creation("PoolV3")),
            8_000_000,
        )?;
        let _ = self.call(pool, &init_v3(token_a, token_b, fee), 500_000)?;
        let _ = self.call(pool, &set_v3_price(sqrt_price), 200_000)?;
        let _ = self.call(pool, &set_v3_liquidity(liquidity), 200_000)?;
        self.call(token_a, &mint_to(pool, amt_a), 200_000)?;
        self.call(token_b, &mint_to(pool, amt_b), 200_000)?;
        for t in [token_a, token_b] {
            if !self.tokens.contains(&t) {
                self.tokens.push(t);
            }
        }
        let v3 = V3Pool {
            pool,
            token0: token_a,
            token1: token_b,
            fee,
            sqrt_price,
            liquidity,
        };
        self.v3_pools.push(v3);
        Ok(v3)
    }

    /// Register a V4 pool in the shared `PoolManager` stub: `initialize` the
    /// `(c0,c1,fee,ts)` pool at `sqrt_price`/`liquidity`, then `_fund` the PM
    /// with `fund_c0`/`fund_c1` of each currency (the PM's holdings back the
    /// executor's `take` of positive deltas).
    pub fn add_v4_pool(
        &mut self,
        c0: Address,
        c1: Address,
        fee: u32,
        tick_spacing: i32,
        sqrt_price: U256,
        liquidity: u128,
        fund_c0: u128,
        fund_c1: u128,
    ) -> Result<V4Pool, String> {
        let _ = self.call(
            self.pool_manager,
            &init_v4(c0, c1, fee, tick_spacing, sqrt_price, liquidity),
            500_000,
        )?;
        for (c, amt) in [(c0, fund_c0), (c1, fund_c1)] {
            let _ = self.call(self.pool_manager, &fund_v4(c, amt), 200_000)?;
            // Native currency has no ERC-20 to mint, so seed the PM's actual
            // native balance too (it's what `take` of a native delta sends).
            if c == Address::ZERO {
                let held = native_balance_of(&mut self.evm, self.pool_manager);
                set_native_balance(&mut self.evm, self.pool_manager, held + U256::from(amt));
            }
        }
        for t in [c0, c1] {
            if !self.tokens.contains(&t) {
                self.tokens.push(t);
            }
        }
        let v4 = V4Pool {
            currency0: c0,
            currency1: c1,
            fee,
            tick_spacing,
            sqrt_price,
            liquidity,
        };
        self.v4_pools.push(v4);
        Ok(v4)
    }

    /// Give `who` `amount` of `token` (mint — the harness's free liquidity).
    /// For the native currency (`Address::ZERO`), sets the recipient's revm
    /// native balance instead (there is no ERC-20 to mint). Minting WETH also
    /// credits the WETH contract the **matching native backing** — real WETH9
    /// is always deposit-backed, and `WETH_WITHDRAW` needs the contract to hold
    /// native to pay out (the executor can't withdraw unbacked minted WETH).
    pub fn fund(&mut self, token: Address, who: Address, amount: u128) -> Result<(), String> {
        if token == Address::ZERO {
            let held = native_balance_of(&mut self.evm, who);
            set_native_balance(&mut self.evm, who, held + U256::from(amount));
            return Ok(());
        }
        self.call(token, &mint_to(who, amount), 200_000)
            .map(|_| ())?;
        if token == self.weth {
            // Back the mint: give the WETH contract native so `withdraw` can pay.
            let backing = native_balance_of(&mut self.evm, token);
            set_native_balance(&mut self.evm, token, backing + U256::from(amount));
        }
        Ok(())
    }

    /// Set an account's native (ETH) balance directly (preserving its code).
    pub fn set_native_balance(&mut self, who: Address, amount: U256) {
        set_native_balance(&mut self.evm, who, amount);
    }

    /// Read an account's native (ETH) balance.
    pub fn native_balance_of(&mut self, who: Address) -> Result<U256, String> {
        Ok(native_balance_of(&mut self.evm, who))
    }

    /// Have the executor approve `pool` for both of its tokens to `max`
    /// (so the pair's `swap` `transferFrom(executor, …)` can pull).
    pub fn executor_approve_pair(&mut self, pool: V2Pool) -> Result<(), String> {
        for t in [pool.token0, pool.token1] {
            let data = approve_data(pool.pair, U256::MAX);
            self.call_as_executor(t, &data, 200_000)?;
        }
        Ok(())
    }

    /// A plain state-mutating call from the default caller (deployer).
    pub fn call(&mut self, to: Address, data: &[u8], gas: u64) -> Result<Bytes, String> {
        call_bytes(&mut self.evm, to, Bytes::copy_from_slice(data), gas)
    }

    /// Send a raw call from the executor address (e.g. `approve` on a token so
    /// the pairs can `transferFrom` the executor).
    pub fn call_as_executor(
        &mut self,
        to: Address,
        data: &[u8],
        gas: u64,
    ) -> Result<Bytes, String> {
        let tx = TxEnv::builder()
            .kind(TxKind::Call(to))
            .gas_limit(gas)
            .data(Bytes::copy_from_slice(data))
            .build()
            .expect("valid call tx env");
        match self.evm.transact(tx) {
            Ok(res) => {
                let out = match res.result {
                    revm::context_interface::result::ExecutionResult::Success {
                        output: Output::Call(b),
                        ..
                    } => b,
                    revm::context_interface::result::ExecutionResult::Success {
                        output: Output::Create(..),
                        ..
                    } => return Err("call returned Create".into()),
                    revm::context_interface::result::ExecutionResult::Revert { output, .. } => {
                        self.evm.commit(res.state);
                        return Err(format!("call_as_executor reverted: {output:?}"));
                    }
                    revm::context_interface::result::ExecutionResult::Halt { reason, .. } => {
                        self.evm.commit(res.state);
                        return Err(format!("call_as_executor halted: {reason:?}"));
                    }
                };
                self.evm.commit(res.state);
                Ok(out)
            }
            Err(e) => Err(format!("call_as_executor transact err: {e:?}")),
        }
    }

    /// Execute an encoded payload with `config=0` (skip profit check, no
    /// bribe) and classify the outcome.
    pub fn execute_payload(&mut self, payload: &[u8], gas: u64) -> Result<ExecOutcome, String> {
        self.execute_payload_config(payload, gas, U256::ZERO)
    }

    /// Execute an encoded payload with an explicit `execute()` `config` uint256
    /// (packed `check_mode`/bribe/expected_value — see [`execute_data_config`])
    /// and classify the outcome. Enables runtime proof of the `erc6909_profit`
    /// (`check_mode=2`) and bribe config axes.
    pub fn execute_payload_config(
        &mut self,
        payload: &[u8],
        gas: u64,
        config: U256,
    ) -> Result<ExecOutcome, String> {
        let data = execute_data_config(payload, config);
        match transact(
            &mut self.evm,
            TxSpec::Call {
                to: self.executor,
                data,
                gas,
            },
        ) {
            Verdict::Accepted { logs, .. } => {
                let swaps =
                    count_swap_events(&logs, &self.pools, &self.v3_pools, self.pool_manager);
                Ok(ExecOutcome::Accepted { swaps })
            }
            Verdict::Reverted(r) => {
                let reason = decode_error_string(&r);
                Ok(ExecOutcome::Reverted {
                    reason,
                    raw: r.to_vec(),
                })
            }
            Verdict::Halted(h) => Ok(ExecOutcome::Halted(h)),
        }
    }

    /// Read `token.balanceOf(account)`.
    pub fn balance_of(&mut self, token: Address, account: Address) -> Result<U256, String> {
        let out = self.call(token, &balance_of_data(account), 200_000)?;
        if out.len() < 32 {
            return Err(format!("balanceOf returned {} bytes", out.len()));
        }
        Ok(U256::from_be_bytes::<32>(
            out.as_ref()[..32].try_into().unwrap(),
        ))
    }

    /// Read `PM.balanceOf(account, uint160(currency))` — the executor's
    /// ERC6909 WETH balance held inside the PoolManager (the `erc6909_profit`
    /// capture destination and the value `check_mode=2` verifies).
    pub fn pm_balance_of(&mut self, account: Address, currency: Address) -> Result<U256, String> {
        let out = self.call(
            self.pool_manager,
            &pm_balance_of_data(account, currency),
            200_000,
        )?;
        if out.len() < 32 {
            return Err(format!("PM.balanceOf returned {} bytes", out.len()));
        }
        Ok(U256::from_be_bytes::<32>(
            out.as_ref()[..32].try_into().unwrap(),
        ))
    }

    /// Encode a fully-V2 path via the production entry (`encode_cmd_stream`)
    /// and execute it. Each hop is `(pool index into [`Self::pools`],
    /// `zero_for_one`); `hop_outputs[i]` are the per-hop solver outputs. This
    /// routes all-V2 through the Plan + validator path
    /// (`grammar_shape::derive_all_v2` → `build_walk`) exactly like
    /// production. Returns the classified outcome.
    pub fn run_v2_path(
        &mut self,
        pool_indices: &[usize],
        zfo: &[bool],
        optimal_input: u128,
        hop_outputs: &[u128],
        gas: u64,
    ) -> Result<ExecOutcome, String> {
        use degenbot_executor::composers::{HopInfo, PathInfo, V2HopInfo};
        let n = pool_indices.len();
        debug_assert_eq!(n, zfo.len());
        debug_assert_eq!(n, hop_outputs.len());

        let mut hops = Vec::with_capacity(n);
        for (i, &pi) in pool_indices.iter().enumerate() {
            let pool = self.pools[pi];
            let hop = V2HopInfo {
                pool_address: pool.pair,
                token0_address: pool.token0,
                token1_address: pool.token1,
                fee: 30, // 0.3% — matches the stub pair's K-check
                zfo: zfo[i],
            };
            hops.push(HopInfo::V2(hop));
        }
        let path = PathInfo::new(hops);
        self.run_path(&path, optimal_input, hop_outputs, gas)
    }

    /// Encode an arbitrary (mixed-V2/V3) `&PathInfo` via the production entry
    /// and execute it. `hop_outputs[i]` are the per-hop solver outputs;
    /// `consumed_inputs` defaults to `[optimal_input, hop_outputs[0], …]`.
    pub fn run_path(
        &mut self,
        path: &degenbot_executor::composers::PathInfo,
        optimal_input: u128,
        hop_outputs: &[u128],
        gas: u64,
    ) -> Result<ExecOutcome, String> {
        self.run_path_with_opts(
            path,
            optimal_input,
            hop_outputs,
            gas,
            degenbot_executor::composers::EncodeOptions::default(),
        )
    }

    /// Variant of [`Self::run_path`] with explicit [`EncodeOptions`]
    /// (funding axis etc.), threaded through to `encode_path_with_opts` — used
    /// by [`crate::harness::declarative::Harness::run_chain_with_opts`].
    ///
    /// Executes under the **production axis-aware config** (the same
    /// `config_for_options(opts, 0)` the arbitrage strategy packs):
    /// the on-chain profit check runs exactly like production (default
    /// Custody → `check_mode=1` active assert; `erc6909_profit` → `check_mode=2`).
    pub fn run_path_with_opts(
        &mut self,
        path: &degenbot_executor::composers::PathInfo,
        optimal_input: u128,
        hop_outputs: &[u128],
        gas: u64,
        opts: degenbot_executor::composers::EncodeOptions,
    ) -> Result<ExecOutcome, String> {
        let cmd = self.encode_path_with_opts(path, optimal_input, hop_outputs, opts)?;
        self.execute_payload_config(&cmd, gas, production_config(opts)?)
    }

    /// ADR-033 (D7) variant of [`Self::run_path_with_opts`] with CALLER-supplied
    /// `consumed_inputs` — the per-hop amounts the production solver commits
    /// after `clamp_cl_hop_capacity` re-aligns them — instead of this harness
    /// synthesizing the full-consumption chain (`[optimal_input,
    /// hop_outputs[0], …]`).
    pub fn run_path_with_consumed(
        &mut self,
        path: &degenbot_executor::composers::PathInfo,
        optimal_input: u128,
        hop_outputs: &[u128],
        consumed_inputs: &[u128],
        gas: u64,
        opts: degenbot_executor::composers::EncodeOptions,
    ) -> Result<ExecOutcome, String> {
        let cmd = self.encode_path_with_consumed(
            path,
            optimal_input,
            hop_outputs,
            consumed_inputs,
            opts,
        )?;
        self.execute_payload_config(&cmd, gas, production_config(opts)?)
    }

    /// ADR-033 (D7): encode with CALLER-supplied per-hop `consumed_inputs`
    /// — the production solver's committed amounts (the shape
    /// `clamp_cl_hop_capacity` re-aligns) — instead of synthesizing the
    /// full-consumption chain. The amounts still flow through the production
    /// `encode_cmd_stream` intake (`EncodeContext` + `EncodeRequest`).
    pub fn encode_path_with_consumed(
        &self,
        path: &degenbot_executor::composers::PathInfo,
        optimal_input: u128,
        hop_outputs: &[u128],
        consumed_inputs: &[u128],
        opts: degenbot_executor::composers::EncodeOptions,
    ) -> Result<Vec<u8>, String> {
        if hop_outputs.len() != path.hops.len() || consumed_inputs.len() != path.hops.len() {
            return Err(format!(
                "encode_path_with_consumed: per-hop arrays must have one entry per hop ({} hops, {} outputs, {} consumed)",
                path.hops.len(),
                hop_outputs.len(),
                consumed_inputs.len()
            ));
        }
        degenbot_executor::composers::encode_cmd_stream(
            &self.encode_context(),
            &degenbot_executor::composers::EncodeRequest::new(
                path.clone(),
                optimal_input,
                hop_outputs.to_vec(),
                consumed_inputs.to_vec(),
                opts,
            ),
        )
        .ok_or_else(|| "encode_cmd_stream returned None".to_string())
    }

    /// Encode a PathInfo through the production `encode_cmd_stream` (the raw
    /// payload `execute_payload`/`execute_data` then drive).
    pub fn encode_path(
        &self,
        path: &degenbot_executor::composers::PathInfo,
        optimal_input: u128,
        hop_outputs: &[u128],
    ) -> Result<Vec<u8>, String> {
        self.encode_path_with_opts(
            path,
            optimal_input,
            hop_outputs,
            degenbot_executor::composers::EncodeOptions::default(),
        )
    }

    /// ADR-033 encode intake context: the session-scoped deployment addresses
    /// (executor / PoolManager / WETH), derived once from what the harness
    /// deployed and shared by every `encode_path*` call (mirrors the
    /// arbitrage `SimulateContext::encode_context` projection).
    #[must_use]
    pub fn encode_context(&self) -> degenbot_executor::composers::EncodeContext {
        degenbot_executor::composers::EncodeContext::new(
            self.executor,
            self.pool_manager,
            self.weth,
        )
    }
    /// Encode a path with explicit [`EncodeOptions`] (runtime axis proof
    /// — funding source / profit capture / bribe).
    pub fn encode_path_with_opts(
        &self,
        path: &degenbot_executor::composers::PathInfo,
        optimal_input: u128,
        hop_outputs: &[u128],
        opts: degenbot_executor::composers::EncodeOptions,
    ) -> Result<Vec<u8>, String> {
        let n = path.hops.len();
        let consumed: Vec<u128> = std::iter::once(optimal_input)
            .chain(hop_outputs.iter().copied())
            .take(n)
            .collect();
        degenbot_executor::composers::encode_cmd_stream(
            &self.encode_context(),
            &degenbot_executor::composers::EncodeRequest::new(
                path.clone(),
                optimal_input,
                hop_outputs.to_vec(),
                consumed,
                opts,
            ),
        )
        .ok_or_else(|| "encode_cmd_stream returned None".to_string())
    }
}

/// The production axis-aware `execute()` config — the single point where the
/// harness meets the strategy's config expression
/// (Custody → `check_mode=1`, Erc6909 → `check_mode=2`, SweepToAddress →
/// `check_mode=3`).
fn production_config(opts: degenbot_executor::composers::EncodeOptions) -> Result<U256, String> {
    degenbot_executor::composers::config_for_options(opts, U256::ZERO)
        .map_err(|e| format!("config_for_options: {e}"))
}

/// Classification of an executed payload.
#[derive(Debug)]
pub enum ExecOutcome {
    /// The executor's `execute()` returned success and touched `swaps` pools.
    Accepted { swaps: usize },
    /// `execute()` reverted; `reason` is the decoded Solidity error string
    /// (e.g. `Some("UniswapV2: K")` when the pair's K-check tripped).
    Reverted {
        reason: Option<String>,
        raw: Vec<u8>,
    },
    /// The EVM halted (OOG / invalid opcode) with no verdict.
    Halted(String),
}

impl ExecOutcome {
    /// Whether the payload executed (reached every hop) rather than reverting
    /// in the command stream / a pool.
    #[must_use]
    pub fn executed(&self, expected_swaps: usize) -> bool {
        matches!(self, ExecOutcome::Accepted { swaps } if *swaps == expected_swaps)
    }
}

// ── calldata/selector helpers (alloy `sol!` encoders over the harness stubs) ──

alloy::sol! {
    /// Harness `Token` stub (tier3-oracle/src-harness/StubToken.sol): the
    /// mint/approve funding surface the pool-seeding calls drive.
    interface HarnessToken {
        function mint(address to, uint256 amount) external;
        function approve(address spender, uint256 amount) external returns (bool);
    }

    /// Harness V2 `Pair` stub (tier3-oracle/src-harness/V2ExecutorStub.sol):
    /// the seed + reserve-sync surface.
    interface HarnessPair {
        function initialize(address tokenA, address tokenB) external;
        function sync() external;
    }

    /// Harness V3 `PoolV3` stub (tier3-oracle/src-harness/V3ExecutorStub.sol):
    /// the seed surface.
    interface HarnessV3Pool {
        function initialize(address t0, address t1, uint24 fee_) external;
        function setPrice(uint160 p) external;
        function setLiquidity(uint128 l) external;
    }

    /// Harness V4 `PoolManager` stub (tier3-oracle/src-harness/V4ExecutorStub.sol):
    /// the seed + ERC-6909 claim-balance surface.
    interface HarnessV4PoolManager {
        function initialize(
            address c0,
            address c1,
            uint24 fee,
            int24 ts,
            uint160 sqrtPriceX96,
            uint128 liquidity
        ) external;
        function _fund(address currency, uint256 amt) external;
        function balanceOf(address owner, uint256 id) external view returns (uint256);
    }
}

fn init_pair(a: Address, b: Address) -> Vec<u8> {
    HarnessPair::initializeCall {
        tokenA: a,
        tokenB: b,
    }
    .abi_encode()
}
fn mint_to(to: Address, amount: u128) -> Vec<u8> {
    HarnessToken::mintCall {
        to,
        amount: U256::from(amount),
    }
    .abi_encode()
}
fn sync_selector() -> Vec<u8> {
    HarnessPair::syncCall {}.abi_encode()
}
fn approve_data(spender: Address, amount: U256) -> Vec<u8> {
    HarnessToken::approveCall { spender, amount }.abi_encode()
}
fn balance_of_data(account: Address) -> Vec<u8> {
    degenbot_rpc::abi::encode_balance_of(&account)
}
/// `PM.balanceOf(owner, id)` — the ERC-6909 claim balances, with
/// `id = uint256(uint160(currency))`.
fn pm_balance_of_data(account: Address, currency: Address) -> Vec<u8> {
    HarnessV4PoolManager::balanceOfCall {
        owner: account,
        id: U256::from_be_slice(currency.as_slice()),
    }
    .abi_encode()
}
/// The `execute(bytes,uint256)` call: selector + (bytes, config=0) ABI encoding.
#[must_use]
pub fn execute_data(payload: &[u8]) -> Bytes {
    execute_data_config(payload, U256::ZERO)
}
/// The `execute(bytes,uint256)` call: selector + (bytes, config) ABI encoding,
/// where `config` is the packed execute config (check_mode/bribe/expected_value).
///
/// Delegates to the production [`degenbot_executor::composers::encode_execute_call`]
/// (uses the proper `encode_rust` ABI encoder) so the config
/// lands in head\[1\] — NOT hand-rolled. The prior hand-rolled encoding wrote
/// `config` at the END of the calldata (after the bytes tail), so the contract
/// read `config = payload.len()` (a silent no-op config); the bug was latent
/// because the erc6909 capture mint is in the command stream (not config-gated)
/// and `check_mode=2`'s verification is skipped when `expected_value=0`. The
/// first test requiring the config to reach the contract (the bribe) exposed
/// it.
#[must_use]
pub fn execute_data_config(payload: &[u8], config: U256) -> Bytes {
    // encode_execute_call returns EncodedCall { to, data, value }; the calldata
    // is `data` (selector + ABI-encoded (bytes, uint256)). `to`/`value` are the
    // caller's concern (execute_payload_config transacts to self.executor).
    let executor = Address::ZERO; // unused (data only); the caller sets the target.
    match degenbot_executor::composers::encode_execute_call(executor, payload, config) {
        Ok(call) => Bytes::from(call.data),
        Err(e) => {
            // Should not happen with valid inputs; fall back to an empty payload
            // so the transact surfaces a clear contract revert rather than a panic.
            let _ = e;
            Bytes::new()
        }
    }
}

fn init_v3(a: Address, b: Address, fee: u32) -> Vec<u8> {
    HarnessV3Pool::initializeCall {
        t0: a,
        t1: b,
        fee_: U24::try_from(fee).expect("fee within uint24"),
    }
    .abi_encode()
}
/// A Q64.96 sqrt price as its `uint160` ABI word. A sqrt price is strictly
/// below 2^160, so the assert only fires on a malformed seed.
fn sqrt_price_word(p: U256) -> U160 {
    assert_eq!(p >> 160, U256::ZERO, "sqrt price does not fit uint160");
    let low: [u8; 20] = p.to_be_bytes::<32>()[12..32]
        .try_into()
        .expect("low 20 bytes");
    U160::from_be_bytes(low)
}

fn set_v3_price(p: U256) -> Vec<u8> {
    HarnessV3Pool::setPriceCall {
        p: sqrt_price_word(p),
    }
    .abi_encode()
}
fn set_v3_liquidity(l: u128) -> Vec<u8> {
    HarnessV3Pool::setLiquidityCall { l }.abi_encode()
}

fn init_v4(c0: Address, c1: Address, fee: u32, ts: i32, sqrt: U256, liq: u128) -> Vec<u8> {
    HarnessV4PoolManager::initializeCall {
        c0,
        c1,
        fee: U24::try_from(fee).expect("fee within uint24"),
        ts: I24::try_from(ts).expect("tick spacing within int24"),
        sqrtPriceX96: sqrt_price_word(sqrt),
        liquidity: liq,
    }
    .abi_encode()
}
fn fund_v4(currency: Address, amt: u128) -> Vec<u8> {
    HarnessV4PoolManager::_fundCall {
        currency,
        amt: U256::from(amt),
    }
    .abi_encode()
}

// ── V3 amount math (via the engine's proven `degenbot-concentrated-liquidity-math`) ──

/// Compute the exact-input V3 output for `amount_in` at `sqrt_price`/`liquidity`
/// with `fee` (hundredths of a bip), mirroring `PoolV3.swap` (single active
/// tick range, target = the unbounded limit, full input consumed). Returns the
/// output amount (token1 for `zero_for_one`, token0 otherwise).
#[must_use]
pub fn v3_amount_out(
    sqrt_price: U256,
    liquidity: u128,
    amount_in: u128,
    zero_for_one: bool,
    fee: u32,
) -> u128 {
    use degenbot_math::cl::sqrt_price_math::{
        get_amount0_delta, get_amount1_delta, get_next_sqrt_price_from_input,
    };
    let fee_retained = U256::from(1_000_000u64 - u64::from(fee));
    let amount_less_fee = full_mul_div(
        U256::from(amount_in),
        fee_retained,
        U256::from(1_000_000u64),
    );
    let next = get_next_sqrt_price_from_input(
        sqrt_price,
        liquidity as i128,
        amount_less_fee,
        zero_for_one,
    )
    .expect("valid v3 next price");
    let out = if zero_for_one {
        get_amount1_delta(next, sqrt_price, liquidity as i128, Some(false))
    } else {
        get_amount0_delta(next, sqrt_price, liquidity as i128, Some(false))
    }
    .expect("valid v3 amount delta");
    out.to::<u128>()
}

/// `min(a*b/denom, …)` rounded down — a tiny 512-bit mulDiv. Called by
/// `v3_amount_out` (and could live in `degenbot-concentrated-liquidity-math`; kept local to avoid widening).
fn full_mul_div(a: U256, b: U256, denom: U256) -> U256 {
    let prod = U512::from(a) * U512::from(b);
    let q = prod / U512::from(denom);
    q.to::<U256>()
}

fn count_swap_events(
    logs: &[revm::primitives::Log],
    pools: &[V2Pool],
    v3_pools: &[V3Pool],
    pool_manager: Address,
) -> usize {
    let v2_topic = keccak256(b"Swap(address,uint256,uint256,uint256,uint256,address)");
    let v3_topic = keccak256(b"SwapV3(address,uint256,uint160,int256)");
    let v4_topic = keccak256(b"V4Swap(bytes32,address,address,uint256,uint256)");
    logs.iter()
        .filter(|l| {
            if l.topics().first() == Some(&v2_topic) {
                pools.iter().any(|p| l.address == p.pair)
            } else if l.topics().first() == Some(&v3_topic) {
                v3_pools.iter().any(|p| l.address == p.pool)
            } else if l.topics().first() == Some(&v4_topic) {
                l.address == pool_manager
            } else {
                false
            }
        })
        .count()
}

#[cfg(test)]
mod tests {
    use super::*;
    use alloy::dyn_abi::DynSolValue;
    use alloy::primitives::I256;

    // Two independent oracles pin the calldata: selectors hard-coded from
    // `cast sig` (foundry — a different toolchain than alloy's `sol!`, so a
    // signature typo cannot pass), argument words from `DynSolValue` (a
    // different encoder path than the helpers' word assembly).

    const SEL_INIT_PAIR: [u8; 4] = [0x48, 0x5c, 0xc9, 0x55];
    const SEL_MINT: [u8; 4] = [0x40, 0xc1, 0x0f, 0x19];
    const SEL_SYNC: [u8; 4] = [0xff, 0xf6, 0xca, 0xe9];
    const SEL_APPROVE: [u8; 4] = [0x09, 0x5e, 0xa7, 0xb3];
    const SEL_BALANCE_OF_ERC20: [u8; 4] = [0x70, 0xa0, 0x82, 0x31];
    const SEL_BALANCE_OF_6909: [u8; 4] = [0x00, 0xfd, 0xd5, 0x8e];
    const SEL_INIT_V3: [u8; 4] = [0x33, 0x6c, 0x8d, 0x70];
    const SEL_SET_V3_PRICE: [u8; 4] = [0xd9, 0x0b, 0xda, 0x4e];
    const SEL_SET_V3_LIQUIDITY: [u8; 4] = [0x3d, 0x71, 0x8d, 0xa0];
    const SEL_INIT_V4: [u8; 4] = [0x81, 0x4c, 0xc4, 0xe3];
    const SEL_FUND_V4: [u8; 4] = [0x9a, 0x3b, 0xcc, 0xf9];

    /// Selector prefix + `DynSolValue` tuple head/tail encoding.
    fn ref_calldata(selector: [u8; 4], args: Vec<DynSolValue>) -> Vec<u8> {
        let mut out = selector.to_vec();
        out.extend_from_slice(&DynSolValue::Tuple(args).abi_encode());
        out
    }

    fn a(n: u8) -> Address {
        Address::new([n; 20])
    }

    #[test]
    fn init_pair_calldata() {
        assert_eq!(
            init_pair(a(0x11), a(0x22)),
            ref_calldata(
                SEL_INIT_PAIR,
                vec![DynSolValue::Address(a(0x11)), DynSolValue::Address(a(0x22))]
            )
        );
    }

    #[test]
    fn mint_to_calldata() {
        let to = a(0x33);
        for amount in [0u128, 1, 0xdead_beef, u128::MAX] {
            assert_eq!(
                mint_to(to, amount),
                ref_calldata(
                    SEL_MINT,
                    vec![
                        DynSolValue::Address(to),
                        DynSolValue::Uint(U256::from(amount), 256)
                    ]
                )
            );
        }
    }

    #[test]
    fn sync_selector_calldata() {
        assert_eq!(sync_selector(), SEL_SYNC.to_vec());
        assert_eq!(sync_selector().len(), 4);
    }

    #[test]
    fn approve_data_calldata() {
        let spender = a(0x44);
        // U256::MAX is the production approval the seeding path issues.
        for amount in [U256::ZERO, U256::from(1u8), U256::MAX] {
            assert_eq!(
                approve_data(spender, amount),
                ref_calldata(
                    SEL_APPROVE,
                    vec![
                        DynSolValue::Address(spender),
                        DynSolValue::Uint(amount, 256)
                    ]
                )
            );
        }
    }

    #[test]
    fn balance_of_data_calldata() {
        let account = a(0x55);
        assert_eq!(
            balance_of_data(account),
            ref_calldata(SEL_BALANCE_OF_ERC20, vec![DynSolValue::Address(account)])
        );
        // The workspace RPC encoder produces the same bytes.
        assert_eq!(
            balance_of_data(account),
            degenbot_rpc::abi::encode_balance_of(&account)
        );
    }

    #[test]
    fn pm_balance_of_data_calldata() {
        let (account, currency) = (a(0x66), a(0x77));
        assert_eq!(
            pm_balance_of_data(account, currency),
            ref_calldata(
                SEL_BALANCE_OF_6909,
                vec![
                    DynSolValue::Address(account),
                    DynSolValue::Uint(U256::from_be_slice(currency.as_slice()), 256)
                ]
            )
        );
    }

    #[test]
    fn init_v3_calldata() {
        assert_eq!(
            init_v3(a(0x11), a(0x22), 3000),
            ref_calldata(
                SEL_INIT_V3,
                vec![
                    DynSolValue::Address(a(0x11)),
                    DynSolValue::Address(a(0x22)),
                    DynSolValue::Uint(U256::from(3000u32), 24)
                ]
            )
        );
    }

    #[test]
    fn set_v3_price_calldata() {
        for p in [U256::from(4_295_128_739u64), U256::from(1u8) << 159] {
            assert_eq!(
                set_v3_price(p),
                ref_calldata(SEL_SET_V3_PRICE, vec![DynSolValue::Uint(p, 160)])
            );
        }
    }

    #[test]
    fn set_v3_liquidity_calldata() {
        for l in [0u128, u128::MAX] {
            assert_eq!(
                set_v3_liquidity(l),
                ref_calldata(
                    SEL_SET_V3_LIQUIDITY,
                    vec![DynSolValue::Uint(U256::from(l), 128)]
                )
            );
        }
    }

    #[test]
    fn init_v4_calldata() {
        let sqrt = U256::from(4_295_128_739u64);
        assert_eq!(
            init_v4(a(0x11), a(0x22), 3000, 60, sqrt, 1_000),
            ref_calldata(
                SEL_INIT_V4,
                vec![
                    DynSolValue::Address(a(0x11)),
                    DynSolValue::Address(a(0x22)),
                    DynSolValue::Uint(U256::from(3000u32), 24),
                    DynSolValue::Int(I256::try_from(60i64).unwrap(), 24),
                    DynSolValue::Uint(sqrt, 160),
                    DynSolValue::Uint(U256::from(1_000u64), 128)
                ]
            )
        );
    }

    #[test]
    fn init_v4_negative_tick_spacing_is_sign_extended() {
        let cd = init_v4(
            a(0x11),
            a(0x22),
            3000,
            -60,
            U256::from(4_295_128_739u64),
            1_000,
        );
        // ts is the fourth ABI word (offset 4 + 3 * 32): canonical int24
        // encoding sign-extends, so every high byte is 0xff and the low byte
        // is -60 = 0xc4. A zero-extension word-packer produces different
        // (non-canonical) bytes here.
        assert!(
            cd[100..131].iter().all(|&b| b == 0xff),
            "ts word high bytes"
        );
        assert_eq!(cd[131], 0xc4, "ts word low byte");
    }

    #[test]
    fn fund_v4_calldata() {
        assert_eq!(
            fund_v4(a(0x88), 5_000),
            ref_calldata(
                SEL_FUND_V4,
                vec![
                    DynSolValue::Address(a(0x88)),
                    DynSolValue::Uint(U256::from(5_000u64), 256)
                ]
            )
        );
    }

    #[test]
    fn executor_deploy_args_calldata() {
        let args = executor_deploy_args(a(0x11), a(0x22));
        assert_eq!(
            args,
            DynSolValue::Tuple(vec![
                DynSolValue::Address(a(0x11)),
                DynSolValue::Address(a(0x22))
            ])
            .abi_encode()
        );
        assert_eq!(args.len(), 64);
        assert!(args[0..12].iter().all(|&b| b == 0));
        assert_eq!(&args[12..32], &a(0x11).into_array());
        assert!(args[32..44].iter().all(|&b| b == 0));
        assert_eq!(&args[44..64], &a(0x22).into_array());
    }

    // The builders are the encoders: every helper's output is byte-identical
    // to the sol! Call encoding it is named for (and, for balanceOf, the
    // workspace RPC encoder). Hand-assembled words that diverge from the
    // encoder fail these asserts.
    #[test]
    fn helpers_equal_encoder_output() {
        let (x, y) = (a(0x11), a(0x22));
        assert_eq!(
            init_pair(x, y),
            HarnessPair::initializeCall {
                tokenA: x,
                tokenB: y
            }
            .abi_encode()
        );
        assert_eq!(
            mint_to(x, 7),
            HarnessToken::mintCall {
                to: x,
                amount: U256::from(7u8)
            }
            .abi_encode()
        );
        assert_eq!(sync_selector(), HarnessPair::syncCall {}.abi_encode());
        assert_eq!(
            approve_data(x, U256::MAX),
            HarnessToken::approveCall {
                spender: x,
                amount: U256::MAX
            }
            .abi_encode()
        );
        assert_eq!(balance_of_data(x), degenbot_rpc::abi::encode_balance_of(&x));
        assert_eq!(
            pm_balance_of_data(x, y),
            HarnessV4PoolManager::balanceOfCall {
                owner: x,
                id: U256::from_be_slice(y.as_slice())
            }
            .abi_encode()
        );
        assert_eq!(
            init_v3(x, y, 3000),
            HarnessV3Pool::initializeCall {
                t0: x,
                t1: y,
                fee_: U24::from(3000u16)
            }
            .abi_encode()
        );
        assert_eq!(
            set_v3_price(U256::from(4_295_128_739u64)),
            HarnessV3Pool::setPriceCall {
                p: U160::from(4_295_128_739u64)
            }
            .abi_encode()
        );
        assert_eq!(
            set_v3_liquidity(u128::MAX),
            HarnessV3Pool::setLiquidityCall { l: u128::MAX }.abi_encode()
        );
        assert_eq!(
            init_v4(x, y, 3000, 60, U256::from(4_295_128_739u64), 1_000),
            HarnessV4PoolManager::initializeCall {
                c0: x,
                c1: y,
                fee: U24::from(3000u16),
                ts: I24::try_from(60i16).unwrap(),
                sqrtPriceX96: U160::from(4_295_128_739u64),
                liquidity: 1_000
            }
            .abi_encode()
        );
        assert_eq!(
            fund_v4(x, 5_000),
            HarnessV4PoolManager::_fundCall {
                currency: x,
                amt: U256::from(5_000u64)
            }
            .abi_encode()
        );
        assert_eq!(executor_deploy_args(x, y), (x, y).abi_encode());
    }
}