wp-evm-shadow 0.1.3

Shadow Exchange protocol facade for waterpump-evm (Ramses family, Sonic chain)
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
use alloy_primitives::{address, b256, Address, B256, U256};
use alloy_provider::{network::Ethereum, Provider};
use alloy_sol_types::SolCall;
use anyhow::{anyhow, Result};
use wp_evm_base::{chain::Chain, types::SlippageBps};
use wp_evm_ramses_interfaces::periphery::router::IRamsesPeripheryRouter;
use wp_evm_ramses_provider as ramses;
pub use wp_evm_ramses_provider::data::RamsesProtocolConfig;
use wp_evm_v3_provider::plan::PeripherySelectors;

/// Selectors for `IRamsesPeripheryRouter`. Despite Sonic's native being S/wS,
/// the function is still named `unwrapWETH9` — Ramses preserved Uniswap V3
/// periphery names verbatim. Selector-locked in `wp-evm-ramses-interfaces`.
const SELECTORS: PeripherySelectors = PeripherySelectors {
    multicall: IRamsesPeripheryRouter::multicallCall::SELECTOR,
    unwrap_native: IRamsesPeripheryRouter::unwrapWETH9Call::SELECTOR,
    sweep_token: IRamsesPeripheryRouter::sweepTokenCall::SELECTOR,
    refund_native: IRamsesPeripheryRouter::refundETHCall::SELECTOR,
};

pub use wp_evm_ramses_provider::data::{
    CollectFeesParams, ExactInParams, ExactOutParams, GaugeClaim, GaugeEarnedGrid, PlanFragment,
    PoolState, PositionState, Quote, RamsesAddLiquidityParams, RemoveAndCollectParams,
    RemoveLiquidityParams,
};
pub use wp_evm_ramses_provider::gauge::gauge_earned_grids;
pub use wp_evm_ramses_provider::position::{position_key, RamsesPositionView};
pub use wp_evm_ramses_provider::position_views::{PositionFees, PositionViewEntry};
pub use wp_evm_ramses_provider::quote::QuoteError;
pub use wp_evm_ramses_provider::Enumeration;
// M4-C: re-export raw planner + pool-address primitive for CLI dep-hygiene.
pub use wp_evm_ramses_provider::plan;
pub use wp_evm_ramses_provider::pool_address as pool_address_raw;
pub use wp_evm_v3_provider::pool_views::{PoolReadEntry, PoolViewData};

/// Batch-read Ramses (Shadow) pool snapshots through a single Multicall3.
pub async fn pool_views<P: Provider<Ethereum>>(
    provider: &P,
    pools: &[Address],
) -> Result<Vec<PoolReadEntry>> {
    wp_evm_v3_provider::pool_views::pool_views(
        provider,
        ramses::MULTICALL3_ADDRESS,
        pools,
        &ramses::pool_views::RamsesPoolViewSource,
    )
    .await
}

pub async fn position_token_pair<P: Provider<Ethereum>>(
    provider: &P,
    nfpm: Address,
    token_id: U256,
) -> Result<(Address, Address)> {
    ramses::hydrate::position_token_pair(provider, nfpm, token_id).await
}

pub const CONFIG: RamsesProtocolConfig = RamsesProtocolConfig {
    factory: address!("cD2d0637c94fe77C2896BbCBB174cefFb08DE6d7"),
    pool_deployer: address!("8BBDc15759a8eCf99A92E004E0C64ea9A5142d59"),
    router: address!("5543c6176feb9b4b179078205d7c29eea2e2d695"),
    position_mgr: address!("12E66C8F215DdD5d48d150c8f46aD0c6fB0F4406"),
    init_code_hash: b256!("c701ee63862761c31d620a4a083c61bdc1e81761e6b9c9267fd19afd22e0821d"),
    tick_spacings: &[1, 5, 10, 50, 100, 200],
    multicall: address!("cA11bde05977b3631167028862bE2a173976CA11"),
    quoter: None,
    voter: address!("9f59398d0a397b2eEB8a6123a6c7295cb0b0062D"),
};

pub fn config_for_chain(chain: Chain) -> Option<&'static RamsesProtocolConfig> {
    match chain {
        Chain::Sonic => Some(&CONFIG),
        Chain::Ethereum
        | Chain::Arbitrum
        | Chain::Optimism
        | Chain::Polygon
        | Chain::Base
        | Chain::Bsc
        | Chain::HyperEvm
        | Chain::Avalanche
        | Chain::Celo => None,
    }
}

pub fn factory(chain: Chain) -> Option<Address> {
    config_for_chain(chain).map(|c| c.factory)
}
pub fn pool_deployer(chain: Chain) -> Option<Address> {
    config_for_chain(chain).map(|c| c.pool_deployer)
}
pub fn position_manager(chain: Chain) -> Option<Address> {
    config_for_chain(chain).map(|c| c.position_mgr)
}
pub fn router(chain: Chain) -> Option<Address> {
    config_for_chain(chain).map(|c| c.router)
}
pub fn quoter(chain: Chain) -> Option<Address> {
    config_for_chain(chain).and_then(|c| c.quoter)
}
pub fn multicall(chain: Chain) -> Option<Address> {
    config_for_chain(chain).map(|c| c.multicall)
}
pub fn init_code_hash(chain: Chain) -> Option<B256> {
    config_for_chain(chain).map(|c| c.init_code_hash)
}
pub fn voter(chain: Chain) -> Option<Address> {
    config_for_chain(chain).map(|c| c.voter)
}
pub fn supports(chain: Chain) -> bool {
    config_for_chain(chain).is_some()
}

pub async fn pool_state<P: Provider<Ethereum>>(
    provider: &P,
    chain: Chain,
    pool: Address,
) -> Result<PoolState> {
    let cfg = config_for_chain(chain).ok_or_else(|| anyhow!("Shadow not deployed on {chain:?}"))?;
    ramses::hydrate::pool_state(provider, cfg.multicall, pool).await
}

pub async fn position_state<P: Provider<Ethereum>>(
    provider: &P,
    chain: Chain,
    token_id: U256,
) -> Result<PositionState> {
    let cfg = config_for_chain(chain).ok_or_else(|| anyhow!("Shadow not deployed on {chain:?}"))?;
    ramses::hydrate::position_state_shadow(provider, cfg.multicall, cfg.position_mgr, token_id)
        .await
}

pub async fn position_views<P: Provider<Ethereum>>(
    provider: &P,
    chain: Chain,
    token_ids: &[U256],
) -> Result<Vec<PositionViewEntry<RamsesPositionView>>> {
    let cfg = config_for_chain(chain).ok_or_else(|| anyhow!("Shadow not deployed on {chain:?}"))?;
    ramses::position_views::position_views(provider, cfg.multicall, cfg.position_mgr, token_ids)
        .await
}

pub async fn position_views_with_nfpm<P: Provider<Ethereum>>(
    provider: &P,
    chain: Chain,
    nfpm: Address,
    token_ids: &[U256],
) -> Result<Vec<PositionViewEntry<RamsesPositionView>>> {
    let multicall =
        config_for_chain(chain).map(|cfg| cfg.multicall).unwrap_or(ramses::MULTICALL3_ADDRESS);
    ramses::position_views::position_views(provider, multicall, nfpm, token_ids).await
}

pub async fn enumerate_owner_token_ids<P: Provider<Ethereum>>(
    provider: &P,
    chain: Chain,
    nfpm: Address,
    owner: Address,
) -> Result<Enumeration> {
    let multicall =
        config_for_chain(chain).map(|cfg| cfg.multicall).unwrap_or(ramses::MULTICALL3_ADDRESS);
    ramses::enumerate_owner_token_ids(provider, multicall, nfpm, owner, chain).await
}

pub async fn populate_positions_fees<P: Provider<Ethereum>>(
    provider: &P,
    chain: Chain,
    entries: &mut [PositionViewEntry<RamsesPositionView>],
) -> Result<()> {
    let cfg = config_for_chain(chain).ok_or_else(|| anyhow!("Shadow not deployed on {chain:?}"))?;
    ramses::position_views::populate_position_fees(provider, cfg.multicall, entries, |v| {
        pool_address(chain, v.token0, v.token1, v.tick_spacing, None)
    })
    .await
}

pub fn quote_exact_in(s: &PoolState, p: &ExactInParams) -> Result<Quote, QuoteError> {
    ramses::quote::exact_in(s, p)
}
pub fn quote_exact_out(s: &PoolState, p: &ExactOutParams) -> Result<Quote, QuoteError> {
    ramses::quote::exact_out(s, p)
}

pub async fn populate_ticks<P: Provider<Ethereum>>(
    provider: &P,
    chain: Chain,
    pool: Address,
    state: &mut PoolState,
) -> Result<()> {
    config_for_chain(chain).ok_or_else(|| anyhow!("Shadow not deployed on {chain:?}"))?;
    ramses::populate_ticks::populate_ticks(provider, pool, state).await
}

pub async fn quote_online_exact_in<P: Provider<Ethereum>>(
    provider: &P,
    chain: Chain,
    state: &PoolState,
    params: &ExactInParams,
) -> Result<Quote> {
    let cfg = config_for_chain(chain).ok_or_else(|| anyhow!("Shadow not deployed on {chain:?}"))?;
    let quoter = cfg.quoter.ok_or_else(|| anyhow!("Shadow quoter not registered on {chain:?}"))?;
    ramses::quote_online::quote_online_exact_in(provider, quoter, state, params).await
}

pub fn plan_swap_exact_in(
    s: &PoolState,
    q: &Quote,
    p: &ExactInParams,
    slippage: SlippageBps,
    deadline: u64,
    chain: Chain,
) -> Result<PlanFragment> {
    let cfg = config_for_chain(chain).ok_or_else(|| anyhow!("Shadow not deployed on {chain:?}"))?;
    Ok(ramses::plan::swap_exact_in(s, q, p, slippage, deadline, cfg.router))
}

pub fn plan_add_liquidity(
    p: &RamsesAddLiquidityParams,
    slippage: SlippageBps,
    deadline: u64,
    chain: Chain,
) -> Result<PlanFragment> {
    let cfg = config_for_chain(chain).ok_or_else(|| anyhow!("Shadow not deployed on {chain:?}"))?;
    Ok(ramses::plan::add_liquidity(p, slippage, deadline, cfg.position_mgr))
}

#[allow(clippy::too_many_arguments)]
pub fn plan_increase_liquidity(
    token_id: U256,
    token0: Address,
    token1: Address,
    amount0_desired: U256,
    amount1_desired: U256,
    slippage: SlippageBps,
    deadline: u64,
    chain: Chain,
) -> Result<PlanFragment> {
    let cfg = config_for_chain(chain).ok_or_else(|| anyhow!("Shadow not deployed on {chain:?}"))?;
    Ok(ramses::plan::increase_liquidity(
        token_id,
        token0,
        token1,
        amount0_desired,
        amount1_desired,
        slippage,
        deadline,
        cfg.position_mgr,
    ))
}

pub fn plan_remove_liquidity(
    p: &RemoveLiquidityParams,
    deadline: u64,
    chain: Chain,
) -> Result<PlanFragment> {
    let cfg = config_for_chain(chain).ok_or_else(|| anyhow!("Shadow not deployed on {chain:?}"))?;
    Ok(ramses::plan::remove_liquidity(p, deadline, cfg.position_mgr))
}

/// Build an atomic `multicall(decreaseLiquidity, collect, ..unwrap_tail)`
/// plan fragment for a Shadow Sonic NFPM position.
///
/// **Native wS unwrap (R26-future-1 follow-up):** when `recipient ==
/// Address::ZERO`, this composes the calldata as `multicall(decrease,
/// collect, unwrapWETH9, sweepToken)` against the NFPM rather than the
/// bare `multicall([decrease, collect])` of the non-native happy path.
/// Mirrors the existing `plan_collect_fees` native-S unwrap (#234) plus
/// the V3 facade's `plan_remove_liquidity_and_collect` (Slice 3.6).
///
/// Shadow's NFPM is a Ramses-fork of Uniswap V3 and inherits
/// `Multicall + PeripheryPayments` byte-for-byte (verified end-to-end
/// against deployed Shadow Sonic NFPM
/// `0x12E66C8F215DdD5d48d150c8f46aD0c6fB0F4406` in #234). Despite Sonic's
/// native being S/wS, the unwrap function is still named `unwrapWETH9`
/// — Ramses preserved Uniswap V3 periphery names verbatim.
///
/// For non-native recipients this is a thin pass-through —
/// `resolve_native_wrap_remove_and_collect` returns an empty
/// `post_calls` vec and the bare `multicall([decrease, collect])` is
/// emitted unwrapped.
pub fn plan_remove_liquidity_and_collect(
    p: &RemoveAndCollectParams,
    deadline: u64,
    chain: Chain,
) -> Result<PlanFragment> {
    let cfg = config_for_chain(chain).ok_or_else(|| anyhow!("Shadow not deployed on {chain:?}"))?;

    // No bridge — Shadow's RemoveAndCollectParams IS v3-core's (re-exported
    // through ramses-core::data). Pass `p` straight to the v3-provider
    // resolver.
    let wrap = wp_evm_v3_provider::plan::resolve_native_wrap_remove_and_collect(
        p,
        cfg.position_mgr,
        chain,
    )?;

    // Safety-critical for V3 forks: do not pass `recipient = 0` through
    // to the forked NFPM. Mirroring the `plan_collect_fees` and V3
    // facade Slice 3.5 defensive guard.
    let mut core_params = (*p).clone();
    core_params.recipient = wrap.effective_collect_recipient;

    let frag = ramses::plan::remove_liquidity_and_collect(&core_params, deadline, cfg.position_mgr);
    wp_evm_v3_provider::plan::compose_native_remove_collect_multicall(frag, &wrap, SELECTORS)
}

pub fn plan_collect_fees(p: &CollectFeesParams, chain: Chain) -> Result<PlanFragment> {
    let cfg = config_for_chain(chain).ok_or_else(|| anyhow!("Shadow not deployed on {chain:?}"))?;

    // Resolve `recipient == Address::ZERO` (native unwrap sentinel) by
    // composing `multicall(collect, unwrapWETH9, sweepToken)` against the
    // NFPM. Shadow's NFPM is a Ramses-fork of Uniswap V3 and inherits
    // `Multicall + PeripheryPayments` byte-for-byte (verified 2026-05-29
    // against deployed Shadow Sonic NFPM 0x12E66C8F215DdD5d48d150c8f46aD0c6fB0F4406):
    // `multicall(bytes[])` accepts empty array, `unwrapWETH9` accepts call.
    // Note: despite Sonic's native being S/wS, the function is still named
    // `unwrapWETH9` — Ramses fork preserved Uniswap naming verbatim.
    //
    // For non-native recipients this is a thin pass-through —
    // `resolve_native_wrap_collect` returns an empty `post_calls` vec
    // and the bare `collect()` calldata is emitted unwrapped.
    let wrap = wp_evm_v3_provider::plan::resolve_native_wrap_collect(p, cfg.position_mgr, chain)?;

    // Safety-critical for V3 forks: do not pass `recipient = 0` through
    // to the forked NFPM. Shadow is a V3 fork and we cannot rely on the
    // upstream V3 `recipient == 0 ? address(this) : recipient` substitution
    // surviving every fork. Mirroring V3 Slice 3.5's defensive guard.
    let core_params = CollectFeesParams {
        token_id: p.token_id,
        recipient: wrap.effective_recipient,
        token0: p.token0,
        token1: p.token1,
        caller: p.caller,
    };

    let frag = ramses::plan::collect_fees(&core_params, cfg.position_mgr);
    Ok(wp_evm_v3_provider::plan::compose_native_collect_multicall(frag, &wrap, SELECTORS))
}

pub fn pool_address(
    chain: Chain,
    token_a: Address,
    token_b: Address,
    tick_spacing: i32,
    init_code_hash_override: Option<B256>,
) -> Option<Address> {
    let cfg = config_for_chain(chain)?;
    let init_code_hash = init_code_hash_override.unwrap_or(cfg.init_code_hash);
    Some(ramses::pool_address::compute(
        cfg.pool_deployer,
        init_code_hash,
        token_a,
        token_b,
        tick_spacing,
    ))
}

pub async fn pending_emissions<P: Provider<Ethereum>>(
    provider: &P,
    chain: Chain,
    pool: Address,
    token_id: U256,
) -> Result<Option<wp_evm_ramses_provider::gauge::PendingEmissions>> {
    let cfg = config_for_chain(chain).ok_or_else(|| anyhow!("Shadow not deployed on {chain:?}"))?;
    wp_evm_ramses_provider::gauge::pending_emissions(
        provider,
        cfg.multicall,
        cfg.voter,
        pool,
        token_id,
    )
    .await
}

/// Pure: encode a batched Shadow gauge reward claim for fully-resolved
/// `claims`. Looks up the chain's Voter and delegates to the family encoder.
pub fn plan_claim_cl_gauge_rewards(chain: Chain, claims: &[GaugeClaim]) -> Result<PlanFragment> {
    let cfg = config_for_chain(chain).ok_or_else(|| anyhow!("Shadow not deployed on {chain:?}"))?;
    Ok(ramses::plan::claim_cl_gauge_rewards(cfg.voter, claims))
}

/// Async: resolve gauges + reward tokens + per-position `earned` for
/// `positions` (`(pool, token_id)` across any pools), prune per-pair zeros,
/// and encode ONE batched `claimClGaugeRewards`. Returns `Ok(None)` when
/// nothing is claimable (ungauged / empty reward tokens / all-zero earned).
/// Never gates on `isAlive`.
pub async fn claim_cl_gauge_rewards_online<P: Provider<Ethereum>>(
    provider: &P,
    chain: Chain,
    positions: &[(Address, U256)],
) -> Result<Option<PlanFragment>> {
    let cfg = config_for_chain(chain).ok_or_else(|| anyhow!("Shadow not deployed on {chain:?}"))?;
    let grids =
        ramses::gauge::gauge_earned_grids(provider, cfg.multicall, cfg.voter, positions).await?;
    // Prune + encode (or None) via the pure, unit-tested family helper — this
    // fn is now a thin reader + helper wrapper.
    Ok(ramses::plan::claim_cl_gauge_rewards_from_grids(cfg.voter, &grids))
}

#[cfg(test)]
mod tests {
    use super::*;
    use wp_evm_ramses_provider::data::TickInfo;

    #[test]
    fn gauge_earned_grids_is_reexported_at_facade() {
        // Type-level smoke: the reader fn is reachable as wp_evm_shadow::gauge_earned_grids.
        let _f = crate::gauge_earned_grids::<alloy_provider::RootProvider>;
    }

    #[test]
    fn config_router_is_known_shadow_address() {
        assert_eq!(CONFIG.router, address!("5543c6176feb9b4b179078205d7c29eea2e2d695"));
    }

    #[test]
    fn config_factory_is_known_shadow_address() {
        assert_eq!(CONFIG.factory, address!("cD2d0637c94fe77C2896BbCBB174cefFb08DE6d7"));
    }

    #[test]
    fn config_pool_deployer_matches_factory_ramsesv3pooldeployer_getter() {
        // 0x8BBDc15... was queried via factory.ramsesV3PoolDeployer()
        // against Sonic public RPC (2026-04-25). Locks the value to
        // prevent a future "fix-back to factory" regression.
        assert_eq!(CONFIG.pool_deployer, address!("8BBDc15759a8eCf99A92E004E0C64ea9A5142d59"));
    }

    #[test]
    fn pool_address_matches_canonical_usdce_ws_ts50_sonic() {
        let usdc_e = address!("29219dD400f2Bf60E5a23d13Be72B486D4038894");
        let ws = address!("039e2fb66102314Ce7b64Ce5CE3E5183bc94aD38");
        let pool = pool_address(Chain::Sonic, usdc_e, ws, 50, None).expect("Sonic supported");
        assert_eq!(pool, address!("324963c267C354c7660Ce8CA3F5f167E05649970"));
    }

    #[test]
    fn config_tick_spacings_match_shadow() {
        assert_eq!(CONFIG.tick_spacings, &[1, 5, 10, 50, 100, 200]);
    }

    /// Shadow `plan_add_liquidity` uses `RamsesAddLiquidityParams` with `tick_spacing`,
    /// not the v3-family `AddLiquidityParams` with `fee`.
    #[test]
    fn plan_add_liquidity_accepts_ramses_params_with_tick_spacing() {
        let p = RamsesAddLiquidityParams {
            token0: address!("A0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48"),
            token1: address!("C02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2"),
            tick_spacing: 50,
            tick_lower: -887_272,
            tick_upper: 887_272,
            amount0_desired: U256::from(1_000_000u64),
            amount1_desired: U256::from(500_000_000_000_000u64),
            recipient: address!("0000000000000000000000000000000000000099"),
        };
        let frag = plan_add_liquidity(&p, SlippageBps::new(50), 9_999_999_999, Chain::Sonic)
            .expect("Sonic supported");
        assert_eq!(frag.calls.len(), 1);
        assert_eq!(frag.calls[0].target, CONFIG.position_mgr);
        assert_eq!(frag.approvals.len(), 2);
        assert_eq!(frag.approvals[0].token, p.token0);
        assert_eq!(frag.approvals[1].token, p.token1);
        assert_eq!(frag.value, U256::ZERO);
    }

    fn fixture_usdc_weth() -> PoolState {
        let sqrt_price_x96 = U256::from_str_radix("3543191142285914205922034323214", 10).unwrap();
        PoolState {
            token0: address!("A0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48"),
            token1: address!("C02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2"),
            fee: 3000,
            tick_spacing: 50,
            sqrt_price_x96,
            liquidity: 2_000_000_000_000_000_000_000u128,
            tick: 76012,
            ticks: vec![
                TickInfo {
                    tick: 74950,
                    liquidity_net: 1_000_000_000_000_000_000_000i128,
                    liquidity_gross: 1_000_000_000_000_000_000_000u128,
                },
                TickInfo {
                    tick: 75950,
                    liquidity_net: 1_000_000_000_000_000_000_000i128,
                    liquidity_gross: 1_000_000_000_000_000_000_000u128,
                },
                TickInfo {
                    tick: 76050,
                    liquidity_net: -2_000_000_000_000_000_000_000i128,
                    liquidity_gross: 2_000_000_000_000_000_000_000u128,
                },
            ],
        }
    }

    #[test]
    fn quote_exact_in_delegates_to_ramses_family() {
        let state = fixture_usdc_weth();
        let params = ExactInParams {
            token_in: state.token0,
            token_out: state.token1,
            amount_in: U256::from(1_000_000u64),
            recipient: address!("0000000000000000000000000000000000000099"),
        };
        let quote = quote_exact_in(&state, &params).expect("quote should succeed");
        assert!(quote.amount_out > U256::ZERO);
        assert_eq!(quote.amount_in, params.amount_in);
    }

    #[test]
    fn plan_swap_exact_in_targets_shadow_router() {
        let state = fixture_usdc_weth();
        let 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,
        };
        let params = ExactInParams {
            token_in: state.token0,
            token_out: state.token1,
            amount_in: quote.amount_in,
            recipient: address!("0000000000000000000000000000000000000099"),
        };
        let frag = plan_swap_exact_in(
            &state,
            &quote,
            &params,
            SlippageBps::new(50),
            u64::MAX,
            Chain::Sonic,
        )
        .expect("Sonic supported");
        assert_eq!(frag.calls.len(), 1);
        assert_eq!(frag.calls[0].target, CONFIG.router);
        assert_eq!(frag.approvals.len(), 1);
    }

    #[test]
    fn quote_exact_out_delegates_to_ramses_family() {
        let state = fixture_usdc_weth();
        let params = ExactOutParams {
            token_in: state.token0,
            token_out: state.token1,
            amount_out: U256::from(500_000_000_000_000u64),
            recipient: address!("0000000000000000000000000000000000000099"),
        };
        let quote = quote_exact_out(&state, &params).expect("exact-out quote should succeed");
        assert!(quote.amount_in > U256::ZERO);
        assert_eq!(quote.amount_out, params.amount_out);
    }

    #[test]
    fn plan_remove_liquidity_targets_position_manager_no_approvals() {
        let params = RemoveLiquidityParams {
            token_id: U256::from(42u64),
            liquidity: 1_000_000_000_000u128,
            amount0_min: None,
            amount1_min: None,
        };
        let frag = plan_remove_liquidity(&params, u64::MAX, Chain::Sonic).expect("Sonic supported");
        assert_eq!(frag.calls.len(), 1);
        assert_eq!(frag.calls[0].target, CONFIG.position_mgr);
        assert!(frag.approvals.is_empty());
        assert_eq!(frag.value, U256::ZERO);
    }

    #[test]
    fn plan_collect_fees_targets_position_manager_no_approvals() {
        let params = CollectFeesParams {
            token_id: U256::from(42u64),
            recipient: address!("0000000000000000000000000000000000000099"),
            token0: address!("0000000000000000000000000000000000000001"),
            token1: address!("0000000000000000000000000000000000000002"),
            caller: Address::ZERO,
        };
        let frag = plan_collect_fees(&params, Chain::Sonic).expect("Sonic supported");
        assert_eq!(frag.calls.len(), 1);
        assert_eq!(frag.calls[0].target, CONFIG.position_mgr);
        assert!(frag.approvals.is_empty());
        assert_eq!(frag.value, U256::ZERO);
    }

    #[test]
    fn plan_claim_cl_gauge_rewards_targets_voter() {
        let claims = vec![GaugeClaim {
            gauge: address!("1111111111111111111111111111111111111111"),
            reward_tokens: vec![address!("aaaa000000000000000000000000000000000000")],
            token_ids: vec![U256::from(1u64)],
        }];
        let frag = plan_claim_cl_gauge_rewards(Chain::Sonic, &claims).expect("Sonic supported");
        assert_eq!(frag.calls.len(), 1);
        assert_eq!(frag.calls[0].target, CONFIG.voter);
        assert!(frag.approvals.is_empty());
        assert_eq!(&frag.calls[0].calldata[..4], &[0xea, 0xb3, 0x7e, 0xec]);
    }

    #[test]
    fn plan_claim_cl_gauge_rewards_rejects_unsupported_chain() {
        let claims = vec![GaugeClaim {
            gauge: Address::ZERO,
            reward_tokens: vec![Address::ZERO],
            token_ids: vec![U256::from(1u64)],
        }];
        assert!(plan_claim_cl_gauge_rewards(Chain::Base, &claims).is_err());
    }

    #[test]
    fn plan_collect_fees_native_recipient_emits_multicall_with_unwrap_and_sweep() {
        // Shadow Sonic — native pair is token0=someERC20 / token1=wS. ZERO recipient
        // = "user wants native S back, not wS" sentinel. Mirror of V3 Slice 3.5
        // (PR #210) and L21 Slice 1 (PR #232) — see Slipstream unit tests.
        // wS on Sonic: 0x039e2fB66102314Ce7b64Ce5Ce3E5183bc94aD38
        let params = CollectFeesParams {
            token_id: U256::from(1u64),
            recipient: Address::ZERO,
            token0: address!("29219dd400f2bf60e5a23d13be72b486d4038894"), // USDC.e (Sonic)
            token1: address!("039e2fb66102314ce7b64ce5ce3e5183bc94ad38"), // wS (Sonic native)
            caller: address!("dEaDbEEFdeAdBeEfDEadBeEFDeaDbEEfdeadbEEF"),
        };
        let frag = plan_collect_fees(&params, Chain::Sonic).expect("Sonic supported");

        assert_eq!(&frag.calls[0].calldata[..4], &[0xac, 0x96, 0x50, 0xd8]);
        assert_eq!(frag.calls[0].target, CONFIG.position_mgr);
        assert_eq!(frag.value, U256::ZERO);
        assert_eq!(frag.calls[0].value, U256::ZERO);
        assert!(
            frag.calls[0].calldata.windows(4).any(|w| w == [0x49, 0x40, 0x4b, 0x7c]),
            "native collect multicall must include unwrapWETH9(uint256,address) tail"
        );
        assert!(
            frag.calls[0].calldata.windows(4).any(|w| w == [0xdf, 0x2a, 0xb5, 0xbb]),
            "native collect multicall must include sweepToken(address,uint256,address) tail"
        );
    }

    #[test]
    fn plan_collect_fees_non_native_recipient_passthrough() {
        let params = CollectFeesParams {
            token_id: U256::from(1u64),
            recipient: address!("0000000000000000000000000000000000000099"),
            token0: address!("29219dd400f2bf60e5a23d13be72b486d4038894"), // USDC.e (Sonic)
            token1: address!("039e2fb66102314ce7b64ce5ce3e5183bc94ad38"), // wS (Sonic native)
            caller: Address::ZERO,
        };
        let frag = plan_collect_fees(&params, Chain::Sonic).expect("Sonic supported");
        let bare = ramses::plan::collect_fees(&params, CONFIG.position_mgr);

        assert_ne!(
            &frag.calls[0].calldata[..4],
            &[0xac, 0x96, 0x50, 0xd8],
            "non-native case must NOT be wrapped in multicall"
        );
        assert_eq!(
            frag.calls[0].calldata, bare.calls[0].calldata,
            "non-native pass-through must stay byte-identical to bare collect()"
        );
    }

    #[test]
    fn plan_collect_fees_no_native_side_rejects() {
        // Both sides ERC20 (no wS) with ZERO recipient — sentinel misuse;
        // nothing to unwrap. Must reject loudly.
        let params = CollectFeesParams {
            token_id: U256::from(1u64),
            recipient: Address::ZERO,
            token0: address!("29219dd400f2bf60e5a23d13be72b486d4038894"), // USDC.e (Sonic)
            token1: address!("0000000000000000000000000000000000000002"), // some other ERC20
            caller: address!("dEaDbEEFdeAdBeEfDEadBeEFDeaDbEEfdeadbEEF"),
        };
        let err = plan_collect_fees(&params, Chain::Sonic).unwrap_err();
        let msg = format!("{err:#}");
        assert!(msg.contains("neither") || msg.contains("native"), "got: {msg}");
    }

    // ---------------------------------------------------------------
    // plan_remove_liquidity_and_collect (native wS unwrap) — mirrors
    // plan_collect_fees tests above; same wS-paired position fixture.
    // ---------------------------------------------------------------

    fn fixture_remove_and_collect_params_ws_paired() -> RemoveAndCollectParams {
        RemoveAndCollectParams {
            token_id: U256::from(1u64),
            liquidity: 1_000_000u128,
            amount0_min: Some(U256::from(100u64)),
            amount1_min: Some(U256::from(200u64)),
            recipient: Address::ZERO,
            token0: address!("29219dd400f2bf60e5a23d13be72b486d4038894"), // USDC.e (Sonic)
            token1: address!("039e2fb66102314ce7b64ce5ce3e5183bc94ad38"), // wS (Sonic native)
            caller: address!("dEaDbEEFdeAdBeEfDEadBeEFDeaDbEEfdeadbEEF"),
        }
    }

    #[test]
    fn plan_remove_liquidity_and_collect_native_recipient_emits_4_call_multicall() {
        // wS-paired position (token1=wS) with ZERO recipient — sentinel
        // engages native unwrap. Outer call must be `multicall(bytes[])`
        // (selector `0xac9650d8`) carrying 4 inner calls:
        // [decreaseLiquidity, collect, unwrapWETH9, sweepToken].
        let params = fixture_remove_and_collect_params_ws_paired();
        let frag = plan_remove_liquidity_and_collect(&params, 9_999_999_999, Chain::Sonic)
            .expect("Sonic supported");

        assert_eq!(&frag.calls[0].calldata[..4], &[0xac, 0x96, 0x50, 0xd8]);
        assert_eq!(frag.calls[0].target, CONFIG.position_mgr);
        assert_eq!(frag.value, U256::ZERO);
        assert_eq!(frag.calls[0].value, U256::ZERO);
        assert!(frag.approvals.is_empty());

        // unwrapWETH9 = 0x49404b7c (Ramses preserves V3 naming despite
        // Sonic's native being S/wS).
        assert!(
            frag.calls[0].calldata.windows(4).any(|w| w == [0x49, 0x40, 0x4b, 0x7c]),
            "native remove+collect multicall must include unwrapWETH9(uint256,address) tail"
        );
        // sweepToken = 0xdf2ab5bb (universal across V3/Ramses/Velodrome).
        assert!(
            frag.calls[0].calldata.windows(4).any(|w| w == [0xdf, 0x2a, 0xb5, 0xbb]),
            "native remove+collect multicall must include sweepToken(address,uint256,address) tail"
        );

        // Decode outer multicall and assert exactly 4 inner calls in order.
        use alloy_sol_types::SolValue;
        let (inner,): (Vec<alloy_primitives::Bytes>,) =
            <(Vec<alloy_primitives::Bytes>,)>::abi_decode_params(&frag.calls[0].calldata[4..])
                .expect("decode outer multicall params");
        assert_eq!(inner.len(), 4, "expected 4 inner calls");
        assert_eq!(&inner[0][..4], &[0x0c, 0x49, 0xcc, 0xbe], "inner[0] = decreaseLiquidity");
        assert_eq!(&inner[1][..4], &[0xfc, 0x6f, 0x78, 0x65], "inner[1] = collect");
        assert_eq!(&inner[2][..4], &[0x49, 0x40, 0x4b, 0x7c], "inner[2] = unwrapWETH9");
        assert_eq!(&inner[3][..4], &[0xdf, 0x2a, 0xb5, 0xbb], "inner[3] = sweepToken");
    }

    #[test]
    fn plan_remove_liquidity_and_collect_non_native_recipient_passthrough() {
        // Explicit recipient (not ZERO) — sentinel does NOT engage; the
        // facade returns the bare `multicall([decrease, collect])` from
        // the family's core fn, byte-identical.
        let mut params = fixture_remove_and_collect_params_ws_paired();
        params.recipient = address!("0000000000000000000000000000000000000099");
        let frag = plan_remove_liquidity_and_collect(&params, 9_999_999_999, Chain::Sonic)
            .expect("Sonic supported");

        // Still outer multicall — the bare 2-call pair from the core fn.
        assert_eq!(&frag.calls[0].calldata[..4], &[0xac, 0x96, 0x50, 0xd8]);
        // The bare core fn would produce identical bytes given the same
        // recipient substitution we'd compute (effective_recipient ==
        // params.recipient since sentinel didn't engage).
        let bare =
            ramses::plan::remove_liquidity_and_collect(&params, 9_999_999_999, CONFIG.position_mgr);
        assert_eq!(
            frag.calls[0].calldata, bare.calls[0].calldata,
            "non-native pass-through must stay byte-identical to bare multicall([decrease, collect])"
        );
    }

    #[test]
    fn plan_remove_liquidity_and_collect_no_native_side_rejects() {
        // Both sides ERC20 (no wS) with ZERO recipient — sentinel misuse;
        // nothing to unwrap. Must reject loudly.
        let mut params = fixture_remove_and_collect_params_ws_paired();
        params.token1 = address!("0000000000000000000000000000000000000002");
        let err =
            plan_remove_liquidity_and_collect(&params, 9_999_999_999, Chain::Sonic).unwrap_err();
        let msg = format!("{err:#}");
        assert!(msg.contains("neither") || msg.contains("native"), "got: {msg}");
    }

    #[test]
    fn config_for_chain_returns_some_for_sonic_only() {
        assert_eq!(config_for_chain(Chain::Sonic), Some(&CONFIG));

        for unsupported in [
            Chain::Ethereum,
            Chain::Arbitrum,
            Chain::Optimism,
            Chain::Polygon,
            Chain::Base,
            Chain::Bsc,
            Chain::Avalanche,
            Chain::Celo,
        ] {
            assert!(
                config_for_chain(unsupported).is_none(),
                "shadow should not surface {unsupported:?}",
            );
        }
    }

    #[test]
    fn position_view_and_key_are_re_exported() {
        // Pure type-level smoke: this just has to compile.
        let _: fn(
            alloy_primitives::Address,
            alloy_primitives::U256,
            i32,
            i32,
        ) -> alloy_primitives::B256 = position_key;
        let _: std::marker::PhantomData<RamsesPositionView> = std::marker::PhantomData;
    }

    // -------------------------------------------------------------
    // Slice 3 Layer 2 chain-aware tests (per Slice 1+2 pattern)
    // -------------------------------------------------------------

    #[test]
    fn factory_returns_chain_specific_address_via_layer2() {
        assert_eq!(factory(Chain::Sonic), Some(CONFIG.factory));
        for unsupported in [
            Chain::Ethereum,
            Chain::Arbitrum,
            Chain::Optimism,
            Chain::Polygon,
            Chain::Base,
            Chain::Bsc,
            Chain::Avalanche,
            Chain::Celo,
        ] {
            assert_eq!(factory(unsupported), None);
        }
    }

    /// Structural canary for chain-aware multicall routing — replaces the
    /// pre-fix tautological getter check (which only proved
    /// `multicall(chain)` returns the right address, NOT that `pool_state`
    /// actually uses it).
    ///
    /// Skip pattern: requires `SONIC_RPC_URL` pointing at a Sonic archive
    /// node + `anvil` on PATH. Skips with eprintln otherwise — does NOT
    /// pass-by-default to avoid silent CI green when env is missing.
    #[tokio::test]
    async fn pool_state_routes_to_chain_specific_multicall() {
        let Some(rpc) = std::env::var("SONIC_RPC_URL").ok() else {
            eprintln!(
                "SKIP pool_state_routes_to_chain_specific_multicall: \
                 set SONIC_RPC_URL to a Sonic archive RPC to enable"
            );
            return;
        };
        let anvil = alloy::node_bindings::Anvil::new().fork(rpc).spawn();
        let provider = alloy::providers::ProviderBuilder::new().connect_http(anvil.endpoint_url());

        // Canonical Shadow Sonic USDC.e/wS ts=50 pool — verified via
        // `pool_address_matches_canonical_usdce_ws_ts50_sonic` above.
        let sonic_pool = address!("324963c267C354c7660Ce8CA3F5f167E05649970");
        let state = pool_state(&provider, Chain::Sonic, sonic_pool)
            .await
            .expect("Sonic pool_state must succeed via Layer 2 chain-aware routing");
        assert!(state.liquidity > 0, "Real on-chain Shadow pool should have non-zero liquidity");
    }

    #[test]
    fn pool_address_with_override_uses_override_not_config_hash() {
        let usdc_e = address!("29219dD400f2Bf60E5a23d13Be72B486D4038894");
        let ws = address!("039e2fb66102314Ce7b64Ce5CE3E5183bc94aD38");
        let custom_hash = b256!("ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");

        let with_override =
            pool_address(Chain::Sonic, usdc_e, ws, 50, Some(custom_hash)).expect("Sonic supported");
        let without_override =
            pool_address(Chain::Sonic, usdc_e, ws, 50, None).expect("Sonic supported");

        assert_ne!(with_override, without_override);
    }
}