wp-evm-v3-core 0.1.3

Pure data + quote + plan for v3-family (CL) DEXes — no async dependencies
Documentation
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
//! Pure plan functions for the v3 family.
//!
//! Inputs: hydrated PoolState + computed Quote + params + slippage + deadline + config.
//! Output: a PlanFragment (calls + declared approvals + value).
//!
//! No I/O. Slippage and amount-min computation are pure functions of the
//! Quote produced upstream by the quote module.

use crate::data::{
    AddLiquidityParams, CollectFeesParams, ExactInParams, ExactOutParams, PlanFragment, PoolState,
    Quote, RemoveAndCollectParams, RemoveLiquidityParams, SwapRouterKind,
};
use alloy_primitives::Address;
use alloy_primitives::{aliases::U160, U256};
use alloy_sol_types::{sol, SolCall};
use wp_evm_base::types::{Call, SlippageBps, TokenApproval};
use wp_evm_v3_interfaces::periphery::router::IPeripheryRouter;

sol! {
    #[derive(Debug)]
    struct ExactInputSingleParams {
        address tokenIn;
        address tokenOut;
        uint24  fee;
        address recipient;
        uint256 deadline;
        uint256 amountIn;
        uint256 amountOutMinimum;
        uint160 sqrtPriceLimitX96;
    }

    function exactInputSingle(ExactInputSingleParams params)
        external payable returns (uint256 amountOut);
}

sol! {
    /// SwapRouter02 `exactInputSingle` — no `deadline` field
    /// (deadline checked externally via Multicall wrapper if needed).
    /// Selector: 0x04e45aaf.
    #[derive(Debug)]
    struct ExactInputSingleParamsV02 {
        address tokenIn;
        address tokenOut;
        uint24  fee;
        address recipient;
        uint256 amountIn;
        uint256 amountOutMinimum;
        uint160 sqrtPriceLimitX96;
    }

    /// V02 variant — same function name, different params shape.
    /// Rust binding lives in its own interface scope to avoid name collision.
    interface ISwapRouter02 {
        function exactInputSingle(ExactInputSingleParamsV02 params)
            external payable returns (uint256 amountOut);
    }
}

sol! {
    /// V1 SwapRouter `exactOutputSingle` — with `deadline` field.
    /// Selector: 0xdb3e2198.
    #[derive(Debug)]
    struct ExactOutputSingleParams {
        address tokenIn;
        address tokenOut;
        uint24  fee;
        address recipient;
        uint256 deadline;
        uint256 amountOut;
        uint256 amountInMaximum;
        uint160 sqrtPriceLimitX96;
    }

    function exactOutputSingle(ExactOutputSingleParams params)
        external payable returns (uint256 amountIn);
}

sol! {
    /// SwapRouter02 `exactOutputSingle` — no `deadline` field.
    /// Selector: 0x5023b4df.
    #[derive(Debug)]
    struct ExactOutputSingleParamsV02 {
        address tokenIn;
        address tokenOut;
        uint24  fee;
        address recipient;
        uint256 amountOut;
        uint256 amountInMaximum;
        uint160 sqrtPriceLimitX96;
    }

    /// V02 variant — same function name, different params shape.
    interface ISwapRouter02ExactOut {
        function exactOutputSingle(ExactOutputSingleParamsV02 params)
            external payable returns (uint256 amountIn);
    }
}

sol! {
    #[derive(Debug)]
    struct MintParams {
        address token0;
        address token1;
        uint24  fee;
        int24   tickLower;
        int24   tickUpper;
        uint256 amount0Desired;
        uint256 amount1Desired;
        uint256 amount0Min;
        uint256 amount1Min;
        address recipient;
        uint256 deadline;
    }
    function mint(MintParams params) external payable
        returns (uint256 tokenId, uint128 liquidity, uint256 amount0, uint256 amount1);

    #[derive(Debug)]
    struct IncreaseLiquidityParams {
        uint256 tokenId;
        uint256 amount0Desired;
        uint256 amount1Desired;
        uint256 amount0Min;
        uint256 amount1Min;
        uint256 deadline;
    }
    function increaseLiquidity(IncreaseLiquidityParams params) external payable
        returns (uint128 liquidity, uint256 amount0, uint256 amount1);

    #[derive(Debug)]
    struct DecreaseLiquidityParams {
        uint256 tokenId;
        uint128 liquidity;
        uint256 amount0Min;
        uint256 amount1Min;
        uint256 deadline;
    }
    function decreaseLiquidity(DecreaseLiquidityParams params) external payable
        returns (uint256 amount0, uint256 amount1);

    #[derive(Debug)]
    struct CollectParams {
        uint256 tokenId;
        address recipient;
        uint128 amount0Max;
        uint128 amount1Max;
    }
    function collect(CollectParams params) external payable
        returns (uint256 amount0, uint256 amount1);
}

/// Build a v3 router `exactInputSingle` plan fragment.
///
/// Pure. No chain interaction. The caller (hydrate or wrapper) must supply
/// the deadline as an absolute unix timestamp.
pub fn swap_exact_in(
    state: &PoolState,
    quote: &Quote,
    params: &ExactInParams,
    slippage: SlippageBps,
    deadline: u64,
    router: Address,
    kind: SwapRouterKind,
) -> PlanFragment {
    swap_exact_in_with_fee_fn(state, quote, params, slippage, deadline, router, kind, |s| s.fee)
}

/// Plan a v3 swap with an injectable fee function.
///
/// See `quote::exact_in_with_fee_fn` for the motivation. This variant exists
/// so Phase 4 protocols (Algebra / dynamic-fee CL) can emit calldata targeting
/// the correct fee tier without needing a v3-family API change.
///
/// Pure. No chain interaction.
#[allow(
    clippy::too_many_arguments,
    reason = "public planner API threads router ABI kind plus fee injection"
)]
pub fn swap_exact_in_with_fee_fn<F>(
    state: &PoolState,
    quote: &Quote,
    params: &ExactInParams,
    slippage: SlippageBps,
    deadline: u64,
    router: Address,
    kind: SwapRouterKind,
    fee_fn: F,
) -> PlanFragment
where
    F: Fn(&PoolState) -> u32,
{
    let effective_fee = fee_fn(state);
    let amount_out_min = apply_slippage_min(quote.amount_out, slippage);
    let fee_u24 = alloy_primitives::aliases::U24::from(effective_fee);

    let calldata = match kind {
        SwapRouterKind::V1 => {
            let call_params = ExactInputSingleParams {
                tokenIn: params.token_in,
                tokenOut: params.token_out,
                fee: fee_u24,
                recipient: params.recipient,
                deadline: U256::from(deadline),
                amountIn: params.amount_in,
                amountOutMinimum: amount_out_min,
                sqrtPriceLimitX96: U160::ZERO,
            };
            exactInputSingleCall { params: call_params }.abi_encode().into()
        }
        SwapRouterKind::V02 => {
            let call_params = ExactInputSingleParamsV02 {
                tokenIn: params.token_in,
                tokenOut: params.token_out,
                fee: fee_u24,
                recipient: params.recipient,
                amountIn: params.amount_in,
                amountOutMinimum: amount_out_min,
                sqrtPriceLimitX96: U160::ZERO,
            };
            ISwapRouter02::exactInputSingleCall { params: call_params }.abi_encode().into()
        }
    };

    PlanFragment {
        calls: vec![Call { target: router, calldata, value: U256::ZERO }],
        approvals: vec![TokenApproval {
            token: params.token_in,
            spender: router,
            min_amount: params.amount_in,
        }],
        value: U256::ZERO,
    }
}

/// Build a v3 router `exactOutputSingle` plan fragment.
///
/// `quote.amount_in` (from a prior `quote::exact_out` computation) is
/// used to derive `amountInMaximum = quote.amount_in * (1 + slippage)`.
/// The caller's `params.amount_out` flows through as `amountOut` (exact
/// target).
///
/// Pure. No chain interaction.
pub fn swap_exact_out(
    state: &PoolState,
    quote: &Quote,
    params: &ExactOutParams,
    slippage: SlippageBps,
    deadline: u64,
    router: Address,
    kind: SwapRouterKind,
) -> PlanFragment {
    swap_exact_out_with_fee_fn(state, quote, params, slippage, deadline, router, kind, |s| s.fee)
}

/// Plan a v3 exact-out swap with an injectable fee function.
#[allow(
    clippy::too_many_arguments,
    reason = "public planner API threads router ABI kind plus fee injection"
)]
pub fn swap_exact_out_with_fee_fn<F>(
    state: &PoolState,
    quote: &Quote,
    params: &ExactOutParams,
    slippage: SlippageBps,
    deadline: u64,
    router: Address,
    kind: SwapRouterKind,
    fee_fn: F,
) -> PlanFragment
where
    F: Fn(&PoolState) -> u32,
{
    let effective_fee = fee_fn(state);
    let amount_in_max = apply_slippage_max(quote.amount_in, slippage);
    let fee_u24 = alloy_primitives::aliases::U24::from(effective_fee);

    let calldata = match kind {
        SwapRouterKind::V1 => {
            let call_params = ExactOutputSingleParams {
                tokenIn: params.token_in,
                tokenOut: params.token_out,
                fee: fee_u24,
                recipient: params.recipient,
                deadline: U256::from(deadline),
                amountOut: params.amount_out,
                amountInMaximum: amount_in_max,
                sqrtPriceLimitX96: U160::ZERO,
            };
            exactOutputSingleCall { params: call_params }.abi_encode().into()
        }
        SwapRouterKind::V02 => {
            let call_params = ExactOutputSingleParamsV02 {
                tokenIn: params.token_in,
                tokenOut: params.token_out,
                fee: fee_u24,
                recipient: params.recipient,
                amountOut: params.amount_out,
                amountInMaximum: amount_in_max,
                sqrtPriceLimitX96: U160::ZERO,
            };
            ISwapRouter02ExactOut::exactOutputSingleCall { params: call_params }.abi_encode().into()
        }
    };

    PlanFragment {
        calls: vec![Call { target: router, calldata, value: U256::ZERO }],
        approvals: vec![TokenApproval {
            token: params.token_in,
            spender: router,
            min_amount: amount_in_max,
        }],
        value: U256::ZERO,
    }
}

/// Compute the minimum acceptable output given a quoted amount and slippage.
///
/// `amount_out_min = quoted * (10_000 - slippage_bps) / 10_000`
pub fn apply_slippage_min(quoted: U256, slippage: SlippageBps) -> U256 {
    let bps = U256::from(slippage.as_bps());
    let denom = U256::from(10_000u64);
    quoted * (denom - bps) / denom
}

/// Compute the maximum acceptable input for an exact-out swap.
pub fn apply_slippage_max(quoted: U256, slippage: SlippageBps) -> U256 {
    let bps = U256::from(slippage.as_bps());
    let denom = U256::from(10_000u64);
    quoted * (denom + bps) / denom
}

/// Build a v3 position-manager `mint` plan fragment (add liquidity).
///
/// Declares approvals for both tokens against the position manager.
/// `amount0Min` / `amount1Min` are derived from `slippage`.
pub fn add_liquidity(
    params: &AddLiquidityParams,
    slippage: SlippageBps,
    deadline: u64,
    position_manager: Address,
) -> PlanFragment {
    let mint_params = MintParams {
        token0: params.token0,
        token1: params.token1,
        fee: alloy_primitives::aliases::U24::from(params.fee),
        tickLower: alloy_primitives::aliases::I24::try_from(params.tick_lower)
            .expect("tick_lower within i24 range"),
        tickUpper: alloy_primitives::aliases::I24::try_from(params.tick_upper)
            .expect("tick_upper within i24 range"),
        amount0Desired: params.amount0_desired,
        amount1Desired: params.amount1_desired,
        amount0Min: apply_slippage_min(params.amount0_desired, slippage),
        amount1Min: apply_slippage_min(params.amount1_desired, slippage),
        recipient: params.recipient,
        deadline: U256::from(deadline),
    };
    let calldata = mintCall { params: mint_params }.abi_encode().into();
    PlanFragment {
        calls: vec![Call { target: position_manager, calldata, value: U256::ZERO }],
        approvals: vec![
            TokenApproval {
                token: params.token0,
                spender: position_manager,
                min_amount: params.amount0_desired,
            },
            TokenApproval {
                token: params.token1,
                spender: position_manager,
                min_amount: params.amount1_desired,
            },
        ],
        value: U256::ZERO,
    }
}

/// Build an `increaseLiquidity` plan fragment for an existing v3 NFT
/// position. Requires `tokenId` to refer to a position the caller (or
/// recipient of approval) already owns.
///
/// `token0` / `token1` are needed for the approval declaration and must
/// match the position's stored pair (the function does not validate this
/// — caller's responsibility, typically by hydrating the position first).
///
/// Slippage applies to the desired amounts via `apply_slippage_min`,
/// matching `add_liquidity`'s shape.
///
/// Approvals: token0 + token1 to NFPM (same as mint).
#[allow(
    clippy::too_many_arguments,
    reason = "public planner API mirrors NFPM increaseLiquidity parameters"
)]
pub fn increase_liquidity(
    token_id: U256,
    token0: Address,
    token1: Address,
    amount0_desired: U256,
    amount1_desired: U256,
    slippage: SlippageBps,
    deadline: u64,
    position_manager: Address,
) -> PlanFragment {
    let inc_params = IncreaseLiquidityParams {
        tokenId: token_id,
        amount0Desired: amount0_desired,
        amount1Desired: amount1_desired,
        amount0Min: apply_slippage_min(amount0_desired, slippage),
        amount1Min: apply_slippage_min(amount1_desired, slippage),
        deadline: U256::from(deadline),
    };
    let calldata = increaseLiquidityCall { params: inc_params }.abi_encode().into();
    PlanFragment {
        calls: vec![Call { target: position_manager, calldata, value: U256::ZERO }],
        approvals: vec![
            TokenApproval { token: token0, spender: position_manager, min_amount: amount0_desired },
            TokenApproval { token: token1, spender: position_manager, min_amount: amount1_desired },
        ],
        value: U256::ZERO,
    }
}

/// Build a decreaseLiquidity plan fragment for a v3 NFT position.
///
/// Slippage protection is the caller's responsibility: supply precomputed
/// `amount0_min` / `amount1_min` in `RemoveLiquidityParams` (typically
/// derived from a quote against the current pool state minus the desired
/// slippage tolerance). Passing `None` for both = zero protection — only
/// safe for private mempools.
///
/// No approvals needed — the position manager operates the NFT it minted.
pub fn remove_liquidity(
    params: &RemoveLiquidityParams,
    deadline: u64,
    position_manager: Address,
) -> PlanFragment {
    let dec = DecreaseLiquidityParams {
        tokenId: params.token_id,
        liquidity: params.liquidity,
        amount0Min: params.amount0_min.unwrap_or(U256::ZERO),
        amount1Min: params.amount1_min.unwrap_or(U256::ZERO),
        deadline: U256::from(deadline),
    };
    let calldata = decreaseLiquidityCall { params: dec }.abi_encode().into();
    PlanFragment {
        calls: vec![Call { target: position_manager, calldata, value: U256::ZERO }],
        approvals: vec![],
        value: U256::ZERO,
    }
}

/// Build an atomic `multicall(decreaseLiquidity, collect)` plan
/// fragment for a V3 NFT position.
///
/// `deadline` threads through `decreaseLiquidity`'s deadline param.
/// `collect`'s `amount0Max` / `amount1Max` are set to `u128::MAX`
/// (collect everything in `tokens_owed`).
///
/// This helper ALWAYS emits multicall — even for non-native recipient.
/// Callers who want one-or-the-other should use `remove_liquidity` or
/// `collect_fees` directly.
///
/// **Native unwrap is NOT done here** — this helper is pure encoding.
/// Facade-layer `plan_remove_liquidity_and_collect` composes
/// `unwrapWETH9` + `sweepToken` tails on top via the v3-provider
/// resolver (`resolve_native_wrap_remove_and_collect`).
///
/// **Architectural note**: Placing `remove_liquidity_and_collect` in
/// v3-core (not v3-provider) is intentional. Every existing v3-core
/// helper (`swap_exact_in`, `add_liquidity`, `remove_liquidity`,
/// `collect_fees`) emits a single call; this is the first
/// multicall-emitting v3-core helper. The (`decreaseLiquidity`,
/// `collect`) composition is family-wide pure encoding (no slippage /
/// native / chain logic), not facade-layer logic — so v3-core is the
/// correct home. Future composed primitives (e.g.
/// `mint_and_initialize_pool` for V3) would follow the same precedent.
/// Do **not** "migrate" this to v3-provider in a future consistency PR —
/// the encoding boundary is preserved.
pub fn remove_liquidity_and_collect(
    params: &RemoveAndCollectParams,
    deadline: u64,
    position_manager: Address,
) -> PlanFragment {
    // decreaseLiquidity calldata
    let dec_params = DecreaseLiquidityParams {
        tokenId: params.token_id,
        liquidity: params.liquidity,
        amount0Min: params.amount0_min.unwrap_or(U256::ZERO),
        amount1Min: params.amount1_min.unwrap_or(U256::ZERO),
        deadline: U256::from(deadline),
    };
    let decrease_calldata: alloy_primitives::Bytes =
        decreaseLiquidityCall { params: dec_params }.abi_encode().into();

    // collect calldata (recipient = params.recipient; amount caps = u128::MAX)
    let collect_params = CollectParams {
        tokenId: params.token_id,
        recipient: params.recipient,
        amount0Max: u128::MAX,
        amount1Max: u128::MAX,
    };
    let collect_calldata: alloy_primitives::Bytes =
        collectCall { params: collect_params }.abi_encode().into();

    // outer multicall (NFPM inherits Multicall)
    let multicall_data = vec![decrease_calldata, collect_calldata];
    let multicall_calldata =
        IPeripheryRouter::multicallCall { data: multicall_data }.abi_encode().into();

    PlanFragment {
        calls: vec![Call {
            target: position_manager,
            value: U256::ZERO,
            calldata: multicall_calldata,
        }],
        approvals: vec![],
        value: U256::ZERO,
    }
}

/// Build a v3 position-manager `collect` plan fragment (collect accrued fees).
///
/// Uses `u128::MAX` for both `amount0Max` and `amount1Max` — the standard
/// "collect everything" sentinel in the Uniswap V3 position manager.
pub fn collect_fees(params: &CollectFeesParams, position_manager: Address) -> PlanFragment {
    let coll = CollectParams {
        tokenId: params.token_id,
        recipient: params.recipient,
        amount0Max: u128::MAX,
        amount1Max: u128::MAX,
    };
    let calldata = collectCall { params: coll }.abi_encode().into();
    PlanFragment {
        calls: vec![Call { target: position_manager, calldata, value: U256::ZERO }],
        approvals: vec![],
        value: U256::ZERO,
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::data::{
        AddLiquidityParams, CollectFeesParams, RemoveAndCollectParams, RemoveLiquidityParams,
        SwapRouterKind, V3ProtocolConfig,
    };
    use alloy_primitives::{address, b256, Address};

    const TEST_CFG: V3ProtocolConfig = V3ProtocolConfig {
        factory: address!("0x1F98431c8aD98523631AE4a59f267346ea31F984"),
        pool_deployer: None,
        router: address!("0xE592427A0AEce92De3Edee1F18E0157C05861564"),
        swap_router_kind: SwapRouterKind::V1,
        position_mgr: address!("0xC36442b4a4522E871399CD717aBDD847Ab11FE88"),
        init_code_hash: b256!("0xe34f199b19b2b4f47f68442619d555527d244f78a3297ea89325f843f87b8b54"),
        fee_tiers: &[100, 500, 3000, 10000],
        multicall: address!("0xcA11bde05977b3631167028862bE2a173976CA11"),
        quoter: None,
    };

    fn dummy_pool_state(t0: Address, t1: Address) -> PoolState {
        PoolState {
            token0: t0,
            token1: t1,
            fee: 3000,
            tick_spacing: 60,
            sqrt_price_x96: U256::from(1u64) << 96,
            liquidity: 0,
            tick: 0,
            ticks: vec![],
        }
    }

    fn fixture_exact_in_params() -> ExactInParams {
        ExactInParams {
            token_in: address!("A0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48"),
            token_out: address!("C02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2"),
            amount_in: U256::from(1_000_000u64),
            recipient: address!("0000000000000000000000000000000000000099"),
        }
    }

    fn fixture_exact_out_params() -> ExactOutParams {
        ExactOutParams {
            token_in: address!("A0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48"),
            token_out: address!("C02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2"),
            amount_out: U256::from(500_000_000_000_000u64),
            recipient: address!("0000000000000000000000000000000000000099"),
        }
    }

    fn fixture_quote(state: &PoolState) -> Quote {
        Quote {
            amount_in: U256::from(1_000_000u64),
            amount_out: U256::from(500_000_000_000_000u64),
            sqrt_price_x96_after: state.sqrt_price_x96,
            price_impact_bps: 0,
        }
    }

    #[test]
    fn plan_swap_emits_one_call_with_router_target() {
        let token_in = address!("0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48");
        let token_out = address!("0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2");
        let s = dummy_pool_state(token_in, token_out);
        let q = Quote {
            amount_in: U256::from(1_000_000u64),
            amount_out: U256::from(500_000_000_000_000u64),
            sqrt_price_x96_after: s.sqrt_price_x96,
            price_impact_bps: 0,
        };
        let p = ExactInParams {
            token_in,
            token_out,
            amount_in: q.amount_in,
            recipient: address!("0x0000000000000000000000000000000000000099"),
        };
        let frag = swap_exact_in(
            &s,
            &q,
            &p,
            SlippageBps::new(50),
            9_999_999_999,
            TEST_CFG.router,
            SwapRouterKind::V1,
        );
        assert_eq!(frag.calls.len(), 1);
        assert_eq!(frag.calls[0].target, TEST_CFG.router);
        assert_eq!(frag.approvals.len(), 1);
        assert_eq!(frag.approvals[0].token, token_in);
        assert_eq!(frag.approvals[0].spender, TEST_CFG.router);
        assert_eq!(frag.approvals[0].min_amount, q.amount_in);
        assert_eq!(frag.value, U256::ZERO);
    }

    #[test]
    fn swap_exact_in_v1_emits_v1_selector() {
        let params = fixture_exact_in_params();
        let state = dummy_pool_state(params.token_in, params.token_out);
        let quote = fixture_quote(&state);
        let plan = swap_exact_in(
            &state,
            &quote,
            &params,
            SlippageBps::new(50),
            0,
            TEST_CFG.router,
            SwapRouterKind::V1,
        );
        assert_eq!(
            &plan.calls[0].calldata[..4],
            &[0x41, 0x4b, 0xf3, 0x89],
            "V1 selector must be 0x414bf389"
        );
    }

    #[test]
    fn swap_exact_in_v02_emits_v02_selector() {
        let params = fixture_exact_in_params();
        let state = dummy_pool_state(params.token_in, params.token_out);
        let quote = fixture_quote(&state);
        let plan = swap_exact_in(
            &state,
            &quote,
            &params,
            SlippageBps::new(50),
            0,
            TEST_CFG.router,
            SwapRouterKind::V02,
        );
        assert_eq!(
            &plan.calls[0].calldata[..4],
            &[0x04, 0xe4, 0x5a, 0xaf],
            "V02 selector must be 0x04e45aaf"
        );
    }

    #[test]
    fn swap_exact_in_v1_includes_deadline() {
        let params = fixture_exact_in_params();
        let state = dummy_pool_state(params.token_in, params.token_out);
        let quote = fixture_quote(&state);
        let v1_plan = swap_exact_in(
            &state,
            &quote,
            &params,
            SlippageBps::new(50),
            1_700_000_000,
            TEST_CFG.router,
            SwapRouterKind::V1,
        );
        let v02_plan = swap_exact_in(
            &state,
            &quote,
            &params,
            SlippageBps::new(50),
            1_700_000_000,
            TEST_CFG.router,
            SwapRouterKind::V02,
        );
        assert_eq!(
            v1_plan.calls[0].calldata.len(),
            v02_plan.calls[0].calldata.len() + 32,
            "V1 calldata must be 32 bytes longer than V02 (deadline field)"
        );
    }

    #[test]
    fn swap_exact_out_v1_emits_v1_selector() {
        let params = fixture_exact_out_params();
        let state = dummy_pool_state(params.token_in, params.token_out);
        let quote = fixture_quote(&state);
        let plan = swap_exact_out(
            &state,
            &quote,
            &params,
            SlippageBps::new(50),
            0,
            TEST_CFG.router,
            SwapRouterKind::V1,
        );
        assert_eq!(
            &plan.calls[0].calldata[..4],
            &[0xdb, 0x3e, 0x21, 0x98],
            "V1 selector must be 0xdb3e2198"
        );
    }

    #[test]
    fn swap_exact_out_v02_emits_v02_selector() {
        let params = fixture_exact_out_params();
        let state = dummy_pool_state(params.token_in, params.token_out);
        let quote = fixture_quote(&state);
        let plan = swap_exact_out(
            &state,
            &quote,
            &params,
            SlippageBps::new(50),
            0,
            TEST_CFG.router,
            SwapRouterKind::V02,
        );
        assert_eq!(
            &plan.calls[0].calldata[..4],
            &[0x50, 0x23, 0xb4, 0xdf],
            "V02 selector must be 0x5023b4df"
        );
    }

    #[test]
    fn swap_exact_out_v1_includes_deadline() {
        let params = fixture_exact_out_params();
        let state = dummy_pool_state(params.token_in, params.token_out);
        let quote = fixture_quote(&state);
        let v1_plan = swap_exact_out(
            &state,
            &quote,
            &params,
            SlippageBps::new(50),
            1_700_000_000,
            TEST_CFG.router,
            SwapRouterKind::V1,
        );
        let v02_plan = swap_exact_out(
            &state,
            &quote,
            &params,
            SlippageBps::new(50),
            1_700_000_000,
            TEST_CFG.router,
            SwapRouterKind::V02,
        );
        assert_eq!(
            v1_plan.calls[0].calldata.len(),
            v02_plan.calls[0].calldata.len() + 32,
            "V1 calldata must be 32 bytes longer than V02 (deadline field)"
        );
    }

    #[test]
    fn swap_exact_out_approval_min_amount_is_amount_in_max() {
        let params = fixture_exact_out_params();
        let state = dummy_pool_state(params.token_in, params.token_out);
        let quote = Quote {
            amount_in: U256::from(1_000_000u64),
            amount_out: params.amount_out,
            sqrt_price_x96_after: state.sqrt_price_x96,
            price_impact_bps: 0,
        };
        let plan = swap_exact_out(
            &state,
            &quote,
            &params,
            SlippageBps::new(50),
            0,
            TEST_CFG.router,
            SwapRouterKind::V1,
        );
        assert_eq!(
            plan.approvals[0].min_amount,
            U256::from(1_005_000u64),
            "approval min_amount must equal amount_in_max (worst case)"
        );
    }

    #[test]
    fn slippage_min_50bps_on_1eth() {
        let out =
            apply_slippage_min(U256::from(1_000_000_000_000_000_000u64), SlippageBps::new(50));
        // 1e18 * 9950 / 10000 = 9.95e17
        assert_eq!(out, U256::from(995_000_000_000_000_000u64));
    }

    #[test]
    fn slippage_max_50bps_on_1eth() {
        let out =
            apply_slippage_max(U256::from(1_000_000_000_000_000_000u64), SlippageBps::new(50));
        assert_eq!(out, U256::from(1_005_000_000_000_000_000u64));
    }

    #[test]
    fn plan_add_liquidity_targets_position_manager() {
        let p = AddLiquidityParams {
            token0: address!("0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48"),
            token1: address!("0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2"),
            fee: 3000,
            tick_lower: -201_000,
            tick_upper: -198_960,
            amount0_desired: U256::from(1_000_000u64),
            amount1_desired: U256::from(500_000_000_000_000u64),
            recipient: address!("0x0000000000000000000000000000000000000099"),
        };
        let frag = add_liquidity(&p, SlippageBps::new(50), 9_999_999_999, TEST_CFG.position_mgr);
        assert_eq!(frag.calls.len(), 1);
        assert_eq!(frag.calls[0].target, TEST_CFG.position_mgr);
        assert_eq!(frag.approvals.len(), 2);
        assert_eq!(frag.approvals[0].token, p.token0);
        assert_eq!(frag.approvals[0].spender, TEST_CFG.position_mgr);
        assert_eq!(frag.approvals[1].token, p.token1);
        assert_eq!(frag.approvals[1].spender, TEST_CFG.position_mgr);
        assert_eq!(frag.value, U256::ZERO);
    }

    #[test]
    fn plan_remove_liquidity_targets_position_manager_no_approvals() {
        let p = RemoveLiquidityParams {
            token_id: U256::from(42u64),
            liquidity: 1_000_000_000_000u128,
            amount0_min: None,
            amount1_min: None,
        };
        let frag = remove_liquidity(&p, 9_999_999_999, TEST_CFG.position_mgr);
        assert_eq!(frag.calls.len(), 1);
        assert_eq!(frag.calls[0].target, TEST_CFG.position_mgr);
        assert!(frag.approvals.is_empty());
        assert_eq!(frag.value, U256::ZERO);
    }

    #[test]
    fn plan_remove_liquidity_passes_min_amounts_when_supplied() {
        let p = RemoveLiquidityParams {
            token_id: U256::from(42u64),
            liquidity: 1_000_000_000_000u128,
            amount0_min: Some(U256::from(500_000u64)),
            amount1_min: Some(U256::from(1_000_000_000u64)),
        };
        let frag = remove_liquidity(&p, 9_999_999_999, TEST_CFG.position_mgr);
        // Decode the emitted calldata and assert the mins survived
        let decoded =
            decreaseLiquidityCall::abi_decode(&frag.calls[0].calldata).expect("decode ok");
        assert_eq!(decoded.params.amount0Min, U256::from(500_000u64));
        assert_eq!(decoded.params.amount1Min, U256::from(1_000_000_000u64));
    }

    #[test]
    fn plan_remove_liquidity_defaults_missing_mins_to_zero() {
        let p = RemoveLiquidityParams {
            token_id: U256::from(42u64),
            liquidity: 1_000_000_000_000u128,
            amount0_min: None,
            amount1_min: None,
        };
        let frag = remove_liquidity(&p, 9_999_999_999, TEST_CFG.position_mgr);
        let decoded =
            decreaseLiquidityCall::abi_decode(&frag.calls[0].calldata).expect("decode ok");
        assert_eq!(decoded.params.amount0Min, U256::ZERO);
        assert_eq!(decoded.params.amount1Min, U256::ZERO);
    }

    #[test]
    fn slippage_min_50bps_on_100k_weth() {
        // 100k WETH = 1e23 wei — well above u64::MAX.
        // Value must fit in U256 and the helper must not truncate.
        let quoted: U256 = U256::from(10u64).pow(U256::from(23u64));
        let out = apply_slippage_min(quoted, SlippageBps::new(50));
        let expected: U256 = quoted * U256::from(9950u64) / U256::from(10_000u64);
        assert_eq!(out, expected);
        // Also sanity check that we're actually in the range claimed
        assert!(out > U256::from(u64::MAX));
    }

    #[test]
    fn plan_collect_fees_targets_position_manager_no_approvals() {
        let p = CollectFeesParams {
            token_id: U256::from(42u64),
            recipient: address!("0x0000000000000000000000000000000000000099"),
            token0: address!("0x0000000000000000000000000000000000000001"),
            token1: address!("0x0000000000000000000000000000000000000002"),
            caller: Address::ZERO,
        };
        let frag = collect_fees(&p, TEST_CFG.position_mgr);
        assert_eq!(frag.calls.len(), 1);
        assert_eq!(frag.calls[0].target, TEST_CFG.position_mgr);
        assert!(frag.approvals.is_empty());
        assert_eq!(frag.value, U256::ZERO);
    }

    #[test]
    fn plan_collect_fees_calldata_round_trips_all_fields() {
        let p = CollectFeesParams {
            token_id: U256::from(42u64),
            recipient: address!("0000000000000000000000000000000000000099"),
            token0: address!("0000000000000000000000000000000000000001"),
            token1: address!("0000000000000000000000000000000000000002"),
            caller: Address::ZERO,
        };
        let frag = collect_fees(&p, TEST_CFG.position_mgr);

        let decoded = collectCall::abi_decode(&frag.calls[0].calldata).expect("decode ok");
        assert_eq!(decoded.params.tokenId, p.token_id);
        assert_eq!(decoded.params.recipient, p.recipient);
        assert_eq!(decoded.params.amount0Max, u128::MAX);
        assert_eq!(decoded.params.amount1Max, u128::MAX);
    }

    #[test]
    fn plan_remove_liquidity_and_collect_targets_nfpm_with_multicall_outer() {
        let p = RemoveAndCollectParams {
            token_id: U256::from(1u64),
            liquidity: 1000u128,
            amount0_min: Some(U256::from(99u64)),
            amount1_min: Some(U256::from(199u64)),
            recipient: address!("0000000000000000000000000000000000000099"),
            token0: address!("0000000000000000000000000000000000000001"),
            token1: address!("0000000000000000000000000000000000000002"),
            caller: Address::ZERO,
        };
        let frag = remove_liquidity_and_collect(&p, 9_999_999_999, TEST_CFG.position_mgr);
        assert_eq!(frag.calls.len(), 1);
        assert_eq!(frag.calls[0].target, TEST_CFG.position_mgr);
        assert_eq!(
            &frag.calls[0].calldata[..4],
            &[0xac, 0x96, 0x50, 0xd8],
            "outer call selector must be multicall"
        );
        assert!(frag.approvals.is_empty());
        assert_eq!(frag.value, U256::ZERO);
    }

    #[test]
    fn plan_remove_liquidity_and_collect_inner_decoded_correctly() {
        let p = RemoveAndCollectParams {
            token_id: U256::from(42u64),
            liquidity: 1_000_000_000_000u128,
            amount0_min: Some(U256::from(500_000u64)),
            amount1_min: Some(U256::from(1_000_000_000u64)),
            recipient: address!("0000000000000000000000000000000000000099"),
            token0: address!("0000000000000000000000000000000000000001"),
            token1: address!("0000000000000000000000000000000000000002"),
            caller: Address::ZERO,
        };
        let frag = remove_liquidity_and_collect(&p, 9_999_999_999, TEST_CFG.position_mgr);

        let outer = IPeripheryRouter::multicallCall::abi_decode(&frag.calls[0].calldata)
            .expect("decode outer multicall");
        assert_eq!(outer.data.len(), 2);
        assert_eq!(&outer.data[0][..4], decreaseLiquidityCall::SELECTOR.as_slice());
        assert_eq!(&outer.data[1][..4], collectCall::SELECTOR.as_slice());

        let decrease = decreaseLiquidityCall::abi_decode(&outer.data[0]).expect("decode decrease");
        assert_eq!(decrease.params.tokenId, p.token_id);
        assert_eq!(decrease.params.liquidity, p.liquidity);
        assert_eq!(decrease.params.amount0Min, U256::from(500_000u64));
        assert_eq!(decrease.params.amount1Min, U256::from(1_000_000_000u64));
        assert_eq!(decrease.params.deadline, U256::from(9_999_999_999u64));

        let collect = collectCall::abi_decode(&outer.data[1]).expect("decode collect");
        assert_eq!(collect.params.tokenId, p.token_id);
        assert_eq!(collect.params.recipient, p.recipient);
        assert_eq!(collect.params.amount0Max, u128::MAX);
        assert_eq!(collect.params.amount1Max, u128::MAX);
    }

    #[test]
    fn plan_remove_liquidity_and_collect_defaults_missing_mins_to_zero() {
        let p = RemoveAndCollectParams {
            token_id: U256::from(42u64),
            liquidity: 1_000_000_000_000u128,
            amount0_min: None,
            amount1_min: None,
            recipient: address!("0000000000000000000000000000000000000099"),
            token0: address!("0000000000000000000000000000000000000001"),
            token1: address!("0000000000000000000000000000000000000002"),
            caller: Address::ZERO,
        };
        let frag = remove_liquidity_and_collect(&p, 9_999_999_999, TEST_CFG.position_mgr);

        let outer = IPeripheryRouter::multicallCall::abi_decode(&frag.calls[0].calldata)
            .expect("decode outer multicall");
        let decrease = decreaseLiquidityCall::abi_decode(&outer.data[0]).expect("decode decrease");
        assert_eq!(decrease.params.amount0Min, U256::ZERO);
        assert_eq!(decrease.params.amount1Min, U256::ZERO);
    }

    #[test]
    fn swap_exact_in_calldata_round_trips_all_fields() {
        let token_in = address!("A0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48");
        let token_out = address!("C02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2");
        let s = dummy_pool_state(token_in, token_out); // fee: 3000
        let q = Quote {
            amount_in: U256::from(1_000_000u64),
            amount_out: U256::from(500_000_000_000_000u64),
            sqrt_price_x96_after: s.sqrt_price_x96,
            price_impact_bps: 0,
        };
        let recipient = address!("0000000000000000000000000000000000000099");
        let p = ExactInParams { token_in, token_out, amount_in: q.amount_in, recipient };
        let deadline = 1_700_000_000u64;
        let frag = swap_exact_in(
            &s,
            &q,
            &p,
            SlippageBps::new(50),
            deadline,
            TEST_CFG.router,
            SwapRouterKind::V1,
        );

        let decoded = exactInputSingleCall::abi_decode(&frag.calls[0].calldata).expect("decode ok");
        let params = decoded.params;
        assert_eq!(params.tokenIn, token_in);
        assert_eq!(params.tokenOut, token_out);
        assert_eq!(params.fee, alloy_primitives::aliases::U24::from(3000u32));
        assert_eq!(params.recipient, recipient);
        assert_eq!(params.deadline, U256::from(deadline));
        assert_eq!(params.amountIn, q.amount_in);
        // amountOutMinimum = amount_out * (10000 - 50) / 10000
        let expected_min = q.amount_out * U256::from(9950u64) / U256::from(10000u64);
        assert_eq!(params.amountOutMinimum, expected_min);
        assert_eq!(params.sqrtPriceLimitX96, alloy_primitives::aliases::U160::ZERO);
    }

    #[test]
    fn add_liquidity_calldata_round_trips_all_fields() {
        let p = AddLiquidityParams {
            token0: address!("A0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48"),
            token1: address!("C02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2"),
            fee: 3000,
            tick_lower: -201_000,
            tick_upper: -198_960,
            amount0_desired: U256::from(1_000_000u64),
            amount1_desired: U256::from(500_000_000_000_000u64),
            recipient: address!("0000000000000000000000000000000000000099"),
        };
        let deadline = 1_700_000_000u64;
        let frag = add_liquidity(&p, SlippageBps::new(100), deadline, TEST_CFG.position_mgr);

        let decoded = mintCall::abi_decode(&frag.calls[0].calldata).expect("decode ok");
        let mp = decoded.params;
        assert_eq!(mp.token0, p.token0);
        assert_eq!(mp.token1, p.token1);
        assert_eq!(mp.fee, alloy_primitives::aliases::U24::from(3000u32));
        assert_eq!(mp.tickLower, alloy_primitives::aliases::I24::try_from(-201_000i32).unwrap());
        assert_eq!(mp.tickUpper, alloy_primitives::aliases::I24::try_from(-198_960i32).unwrap());
        assert_eq!(mp.amount0Desired, p.amount0_desired);
        assert_eq!(mp.amount1Desired, p.amount1_desired);
        // amount0Min = amount0_desired * 9900 / 10000 (100 bps = 1%)
        let expected_min0 = p.amount0_desired * U256::from(9900u64) / U256::from(10000u64);
        assert_eq!(mp.amount0Min, expected_min0);
        let expected_min1 = p.amount1_desired * U256::from(9900u64) / U256::from(10000u64);
        assert_eq!(mp.amount1Min, expected_min1);
        assert_eq!(mp.recipient, p.recipient);
        assert_eq!(mp.deadline, U256::from(deadline));
    }

    #[test]
    fn plan_increase_liquidity_targets_position_manager_two_approvals() {
        let token0 = address!("A0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48");
        let token1 = address!("C02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2");
        let frag = increase_liquidity(
            U256::from(123_456u64),
            token0,
            token1,
            U256::from(1_000_000u64),
            U256::from(500_000_000_000_000u64),
            SlippageBps::new(50),
            9_999_999_999,
            TEST_CFG.position_mgr,
        );
        assert_eq!(frag.calls.len(), 1);
        assert_eq!(frag.calls[0].target, TEST_CFG.position_mgr);
        assert_eq!(frag.calls[0].value, U256::ZERO);
        assert_eq!(frag.approvals.len(), 2);
        assert_eq!(frag.approvals[0].token, token0);
        assert_eq!(frag.approvals[0].spender, TEST_CFG.position_mgr);
        assert_eq!(frag.approvals[0].min_amount, U256::from(1_000_000u64));
        assert_eq!(frag.approvals[1].token, token1);
        assert_eq!(frag.approvals[1].spender, TEST_CFG.position_mgr);
        assert_eq!(frag.approvals[1].min_amount, U256::from(500_000_000_000_000u64));
        assert_eq!(frag.value, U256::ZERO);
    }

    #[test]
    fn increase_liquidity_calldata_round_trips_all_fields() {
        let token0 = address!("A0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48");
        let token1 = address!("C02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2");
        let token_id = U256::from(987_654u64);
        let amount0 = U256::from(2_000_000u64);
        let amount1 = U256::from(750_000_000_000_000u64);
        let deadline = 1_700_000_000u64;
        let frag = increase_liquidity(
            token_id,
            token0,
            token1,
            amount0,
            amount1,
            SlippageBps::new(100),
            deadline,
            TEST_CFG.position_mgr,
        );

        let decoded =
            increaseLiquidityCall::abi_decode(&frag.calls[0].calldata).expect("decode ok");
        let ip = decoded.params;
        assert_eq!(ip.tokenId, token_id);
        assert_eq!(ip.amount0Desired, amount0);
        assert_eq!(ip.amount1Desired, amount1);
        // 100 bps = 1% slippage → amount*Min = amount*Desired * 9900 / 10000.
        let expected_min0 = amount0 * U256::from(9900u64) / U256::from(10000u64);
        assert_eq!(ip.amount0Min, expected_min0);
        let expected_min1 = amount1 * U256::from(9900u64) / U256::from(10000u64);
        assert_eq!(ip.amount1Min, expected_min1);
        assert_eq!(ip.deadline, U256::from(deadline));
    }

    /// Locks the `increaseLiquidity` selector against silent ABI drift.
    /// Verified vs `cast sig 'increaseLiquidity((uint256,uint256,uint256,uint256,uint256,uint256))'`.
    #[test]
    fn increase_liquidity_selector_matches_v3_canonical() {
        assert_eq!(increaseLiquidityCall::SELECTOR, [0x21, 0x9f, 0x5d, 0x17]);
    }

    #[test]
    fn swap_exact_in_with_fee_fn_injects_fee_into_calldata() {
        let token_in = address!("0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48");
        let token_out = address!("0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2");
        let s = dummy_pool_state(token_in, token_out); // fee: 3000 in the fixture
        let q = Quote {
            amount_in: U256::from(1_000_000u64),
            amount_out: U256::from(500_000_000_000_000u64),
            sqrt_price_x96_after: s.sqrt_price_x96,
            price_impact_bps: 0,
        };
        let p = ExactInParams {
            token_in,
            token_out,
            amount_in: q.amount_in,
            recipient: address!("0x0000000000000000000000000000000000000099"),
        };
        // Force fee to 500 (the 0.05% tier) via injection.
        let frag = swap_exact_in_with_fee_fn(
            &s,
            &q,
            &p,
            SlippageBps::new(50),
            9_999_999_999,
            TEST_CFG.router,
            SwapRouterKind::V1,
            |_| 500,
        );
        // Decode the emitted calldata and assert the fee field survived.
        let decoded = exactInputSingleCall::abi_decode(&frag.calls[0].calldata).expect("decode ok");
        assert_eq!(decoded.params.fee, alloy_primitives::aliases::U24::from(500u32));
    }

    // ── Issue #6: slippage boundary tests ────────────────────────────────────

    #[test]
    fn slippage_min_zero_bps_returns_full_amount() {
        // 0 bps = no slippage tolerance: the minimum acceptable output
        // equals the full quoted amount.
        let out = apply_slippage_min(U256::from(1_000_000u64), SlippageBps::new(0));
        assert_eq!(out, U256::from(1_000_000u64));
    }

    #[test]
    fn slippage_min_10000_bps_returns_zero() {
        // 10_000 bps = 100% slippage: caller accepts any output including
        // zero. The formula: 1_000_000 * (10_000 - 10_000) / 10_000 = 0.
        let out = apply_slippage_min(U256::from(1_000_000u64), SlippageBps::new(10_000));
        assert_eq!(out, U256::ZERO);
    }

    #[test]
    fn slippage_min_zero_quoted_returns_zero() {
        // Quoted amount of zero produces zero regardless of slippage bps.
        // No divide-by-zero risk because division is over denom (10_000),
        // not the quoted amount.
        let out = apply_slippage_min(U256::ZERO, SlippageBps::new(50));
        assert_eq!(out, U256::ZERO);
    }

    #[test]
    fn slippage_min_max_u256_does_not_overflow() {
        // U256::MAX * 9950 / 10000 must not panic. U256 arithmetic is
        // checked by default in debug builds via overflow assertions, but
        // here we use wrapping multiplication via the U256 primitive.
        // The intermediary `U256::MAX * 9950` overflows u256 if done
        // naively; the implementation must use U256 arithmetic which
        // naturally wraps at 2^256. Verify the result is in (0, MAX).
        let out = apply_slippage_min(U256::MAX, SlippageBps::new(50));
        // Expected: U256::MAX * 9950 / 10000. Since U256::MAX * 9950
        // overflows mod 2^256, the result will be large but < U256::MAX.
        assert!(out > U256::ZERO, "expected nonzero result for MAX input");
        assert!(out < U256::MAX, "expected result < MAX (slippage was applied)");
    }
}