fynd-core 0.107.1

Core solving logic for Fynd DEX router
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
//! Builds the controller-signed `user_data` payload for exclusive swaps.
//!
//! An exclusive leg (one carrying a committed amount, [`Swap::committed_amount_out`]) executes
//! through an on-chain extension that charges a per-swap fee so the taker's output tracks the
//! committed amount and the surplus goes to the pool's LPs. The committed amount is best-effort,
//! not a hard floor — the ≥committed guarantee lives upstream in the quote/router and price-guard
//! layer.
//!
//! For Ekubo's `SignedExclusiveSwap` extension the payload is the tycho
//! [`Swap::user_data`](tycho_execution) bytes `fee(8) | meta(32) | minBalanceUpdate(32) |
//! signature(65)`, where `fee` is the pool's config fee (a big-endian u64) that
//! `EkuboV3SwapEncoder` uses to rebuild the hop's poolConfig. The encoder appends the 2-byte
//! `sigLen` before the signature, so this module does not.
//!
//! `minBalanceUpdate` pins the payload to the amounts it was quoted for. The swap the extension
//! performs is described by `swapParameters`, which the executor passes outside the signature, so
//! these two balance minimums are the only signed constraint on size and direction. What stays
//! spendable is the band the two tolerances leave around the quote — see
//! `pinned_min_balance_update`.
//!
//! Requires the Ekubo `user_data` support added in `tycho-execution` 0.338.0 (the workspace pins
//! `>= 0.338.0`). All byte layouts and the EIP-712 digest are mirrored from the Ekubo contracts.

use std::sync::atomic::{AtomicU32, Ordering};

use alloy::{
    primitives::{keccak256, Address, B256, U256},
    signers::{local::PrivateKeySigner, SignerSync},
};
use num_bigint::BigUint;
use num_traits::ToPrimitive;
use tracing::warn;
use tycho_simulation::tycho_common::{models::protocol::ProtocolComponent, Bytes};

use crate::{
    bps,
    encoding::{now_unix_secs, DEFAULT_DEADLINE_WINDOW_SECS},
    SolveError, Swap,
};

/// Environment variable holding the pool controller's private key (hex, with or without `0x`).
pub(crate) const ENV_CONTROLLER_KEY: &str = "EXCLUSIVE_SWAP_CONTROLLER_KEY";

/// Environment variable overriding `DEFAULT_OUTPUT_CAP_TOLERANCE_BPS`.
pub(crate) const ENV_OUTPUT_CAP_TOLERANCE_BPS: &str = "EXCLUSIVE_SWAP_OUTPUT_CAP_BPS";

/// Output the pinned cap allows above the quoted amount, in basis points.
///
/// The cap has to survive a pool move in the taker's favour between quoting and execution, or the
/// taker's own swap reverts on it. A leg at the end of a route absorbs the drift of every hop
/// before it, and thin pools move far enough that a tight cap would revert ordinary trades, so the
/// default is wide. At 50% it still stops a payload being spent at a multiple of the size it was
/// quoted for. Every basis point is room a copycat can work with, so a deployment that has
/// measured its own drift can tighten this with the override.
const DEFAULT_OUTPUT_CAP_TOLERANCE_BPS: u32 = 5_000;

/// Reads the cap tolerance from the environment, falling back to
/// `DEFAULT_OUTPUT_CAP_TOLERANCE_BPS` when the variable is unset or unusable.
fn output_cap_tolerance_bps_env() -> u32 {
    let Ok(raw) = std::env::var(ENV_OUTPUT_CAP_TOLERANCE_BPS) else {
        return DEFAULT_OUTPUT_CAP_TOLERANCE_BPS;
    };
    match parse_output_cap_tolerance_bps(&raw) {
        Some(tolerance_bps) => tolerance_bps,
        None => {
            let denominator = bps::DENOMINATOR;
            warn!(
                value = %raw,
                default_bps = DEFAULT_OUTPUT_CAP_TOLERANCE_BPS,
                "{ENV_OUTPUT_CAP_TOLERANCE_BPS} must be an integer from 0 to \
                 {denominator} basis points; using the default",
            );
            DEFAULT_OUTPUT_CAP_TOLERANCE_BPS
        }
    }
}

/// Parses a cap tolerance in basis points, rejecting anything above the whole — a tolerance over
/// `10_000` bps would let a payload move twice the output it was quoted for.
fn parse_output_cap_tolerance_bps(raw: &str) -> Option<u32> {
    raw.trim()
        .parse::<u32>()
        .ok()
        .filter(|tolerance_bps| *tolerance_bps <= bps::DENOMINATOR)
}

/// Converts a request's slippage into the basis-point factor the input floor scales by.
///
/// The floor tracks the request's own slippage rather than a fixed tolerance, so the extension
/// never rejects input drift the router's `min_amount_out` would have accepted. That amount is the
/// route's floor in its terminal token and cannot bound a leg's input, but the fraction behind it
/// is unit-free and applies to any leg quantity.
///
/// Slippage is rounded up and clamped to the whole, which loosens the floor rather than tightening
/// it; a non-finite or non-positive value leaves no tolerance at all. The factor never goes below
/// zero, so the floor stays non-negative and keeps rejecting the reverse swap — whose `token_in`
/// delta is negative — however much slippage a request asks for.
fn input_floor_factor_bps(slippage: f64) -> u32 {
    if !slippage.is_finite() || slippage <= 0.0 {
        return bps::DENOMINATOR;
    }
    let whole = f64::from(bps::DENOMINATOR);
    // Clamped to `[0, whole]` before the cast, so the conversion cannot truncate or wrap.
    let tolerance_bps = (slippage * whole).ceil().min(whole) as u32;
    bps::DENOMINATOR - tolerance_bps
}

/// Produces controller-signed `user_data` payloads for exclusive swaps.
///
/// Holds the controller key, the chain id (bound into the EIP-712 domain), the nonce source, and
/// the deadline window. Construct it from the environment with [`ExclusiveSwapSigner::from_env`];
/// when the key variable is unset the encoder simply leaves exclusive legs unsigned.
///
/// The extension rejects a nonce it has already seen, so a nonce is `nonce_prefix` (drawn once per
/// process) in the high 32 bits and `nonce_counter` (payloads signed in this process) in the low
/// 32. A restart or a second replica draws its own prefix instead of resigning a spent range.
pub struct ExclusiveSwapSigner {
    signer: PrivateKeySigner,
    chain_id: u64,
    nonce_prefix: u32,
    nonce_counter: AtomicU32,
    deadline_window_secs: u32,
    authorized_locker: Address,
    output_cap_tolerance_bps: u32,
}

impl ExclusiveSwapSigner {
    /// Builds a signer from the `EXCLUSIVE_SWAP_CONTROLLER_KEY` env var: `Ok(None)` when unset
    /// (signing disabled), an error when set but invalid.
    ///
    /// `router_address` becomes the payload's authorized locker — see [`Self::new`].
    ///
    /// The nonce prefix is random, so no state has to persist across restarts and replicas need no
    /// coordination. The cap tolerance comes from `EXCLUSIVE_SWAP_OUTPUT_CAP_BPS`.
    pub fn from_env(chain_id: u64, router_address: &Bytes) -> Result<Option<Self>, SolveError> {
        let Ok(key) = std::env::var(ENV_CONTROLLER_KEY) else {
            return Ok(None);
        };
        let signer = key
            .parse::<PrivateKeySigner>()
            .map_err(|e| {
                SolveError::FailedEncoding(format!("invalid {ENV_CONTROLLER_KEY}: {e}"))
            })?;
        let locker = crate::rpc::to_address(router_address, "router address")
            .map_err(SolveError::FailedEncoding)?;
        Ok(Some(
            Self::new(signer, chain_id, rand::random(), DEFAULT_DEADLINE_WINDOW_SECS, locker)
                .with_output_cap_tolerance_bps(output_cap_tolerance_bps_env()),
        ))
    }

    /// Creates a signer from explicit parts.
    ///
    /// `nonce_prefix` is the high 32 bits of every nonce handed out; `deadline_window_secs` is
    /// added to the signing-time timestamp to form each payload's deadline.
    ///
    /// `authorized_locker` is the only address the extension lets execute the payload. It must be
    /// the contract that takes the Ekubo lock — the Tycho router. `Address::ZERO` would authorize
    /// every locker, which makes the signed bytes usable by whoever reads them out of the mempool.
    pub fn new(
        signer: PrivateKeySigner,
        chain_id: u64,
        nonce_prefix: u32,
        deadline_window_secs: u32,
        authorized_locker: Address,
    ) -> Self {
        Self {
            signer,
            chain_id,
            nonce_prefix,
            nonce_counter: AtomicU32::new(0),
            deadline_window_secs,
            authorized_locker,
            output_cap_tolerance_bps: DEFAULT_OUTPUT_CAP_TOLERANCE_BPS,
        }
    }

    /// Overrides how far above the quoted output the pinned cap sits, in basis points.
    ///
    /// [`Self::from_env`] sets this from `EXCLUSIVE_SWAP_OUTPUT_CAP_BPS`; this is the in-code path
    /// for a test or an embedder that configures the signer itself.
    #[must_use]
    pub fn with_output_cap_tolerance_bps(mut self, tolerance_bps: u32) -> Self {
        self.output_cap_tolerance_bps = tolerance_bps;
        self
    }

    /// The locker every payload from this signer authorizes.
    #[cfg(test)]
    pub(crate) fn authorized_locker(&self) -> Address {
        self.authorized_locker
    }

    /// Hands out the next unused nonce: `nonce_prefix` in the high 32 bits, the counter in the low
    /// 32.
    ///
    /// # Errors
    /// Errors from the 2³²-th payload on. Wrapping the counter would resign a spent nonce, so the
    /// signer stops instead and a restart draws a fresh prefix.
    fn next_nonce(&self) -> Result<u64, SolveError> {
        let counter = self
            .nonce_counter
            .fetch_update(Ordering::Relaxed, Ordering::Relaxed, |counter| counter.checked_add(1))
            .map_err(|_| {
                SolveError::FailedEncoding(
                    "exclusive swap nonce counter is exhausted; restart to draw a new prefix"
                        .to_string(),
                )
            })?;
        Ok((u64::from(self.nonce_prefix) << 32) | u64::from(counter))
    }

    /// Builds the signed `user_data` for one exclusive swap leg.
    ///
    /// The leg must carry a committed amount ([`Swap::committed_amount_out`]); the fee is derived
    /// from the quoted output so the realized output tracks it (best-effort — see the module docs).
    ///
    /// v1 supports only standard ERC-20 pools: `poolId` is rebuilt from the swap's token addresses,
    /// so a native-ETH pool (whose on-chain `PoolKey` uses `address(0)`) would yield a mismatched
    /// signature and revert.
    ///
    /// The payload is pinned to the leg's quoted amounts, with the input floor scaled by
    /// `slippage` — the request's own tolerance — see `pinned_min_balance_update`.
    ///
    /// # Errors
    /// Errors if the leg lacks a committed amount, the component is missing Ekubo pool attributes,
    /// a token address exceeds 32 bytes, the deadline overflows `u32`, a quoted amount overflows
    /// the extension's `i128` delta, the nonce counter is exhausted, or signing fails.
    pub(crate) fn build_user_data(&self, swap: &Swap, slippage: f64) -> Result<Bytes, SolveError> {
        let committed = swap
            .committed_amount_out()
            .ok_or_else(|| {
                SolveError::FailedEncoding(
                    "signed swap leg is missing committed_amount_out".to_string(),
                )
            })?;

        let fee = derive_fee_q32(swap.amount_out(), committed);
        let nonce = self.next_nonce()?;
        let deadline = now_unix_secs()?.saturating_add(u64::from(self.deadline_window_secs));
        let deadline = u32::try_from(deadline).map_err(|_| {
            SolveError::FailedEncoding("signed swap deadline overflows u32".to_string())
        })?;

        // The extension's `isAuthorized` accepts only this locker, so a third party that lifts the
        // signed bytes cannot execute them through its own contract. The locker is the router,
        // which anyone may call, so the pinned balance minimums do the rest of the work.
        let meta = signed_swap_meta(deadline, fee, nonce, self.authorized_locker);
        let min_balance_update = pinned_min_balance_update(
            swap,
            input_floor_factor_bps(slippage),
            bps::DENOMINATOR.saturating_add(self.output_cap_tolerance_bps),
        )?;

        let component = swap.protocol_component();
        let extension = pool_extension(component)?;
        let config = pool_config_word(component)?;
        let (token0, token1) = sorted_tokens(swap.token_in(), swap.token_out());
        let pool_id = pool_id(token0, token1, config)?;

        let digest = eip712_digest(self.chain_id, extension, pool_id, meta, min_balance_update);
        let signature = self
            .signer
            .sign_hash_sync(&digest)
            .map_err(|e| SolveError::FailedEncoding(format!("signed swap signing failed: {e}")))?;

        // `EkuboV3SwapEncoder` reads the leading fee(8) as the pool's config fee to rebuild the
        // hop's poolConfig. Take it from the same `config` word the poolId is derived from (bytes
        // [20..28]) so the executor resolves the pool the signature was made over.
        let config_fee = &config.as_slice()[20..28];

        let mut user_data = Vec::with_capacity(8 + 32 + 32 + 65);
        user_data.extend_from_slice(config_fee);
        user_data.extend_from_slice(meta.as_slice());
        user_data.extend_from_slice(min_balance_update.as_slice());
        user_data.extend_from_slice(&signature.as_bytes());
        Ok(Bytes::from(user_data))
    }
}

/// Packs a `SignedSwapMeta` word: `[255..224]` deadline(u32), `[223..192]` fee(u32, 0.32 fixed
/// point), `[191..128]` nonce(u64), `[127..0]` authorized-locker low 128 bits.
fn signed_swap_meta(deadline: u32, fee: u32, nonce: u64, authorized_locker: Address) -> B256 {
    let mut word = [0u8; 32];
    word[0..4].copy_from_slice(&deadline.to_be_bytes());
    word[4..8].copy_from_slice(&fee.to_be_bytes());
    word[8..16].copy_from_slice(&nonce.to_be_bytes());
    // Low 128 bits of the 20-byte locker address = its least-significant 16 bytes.
    word[16..32].copy_from_slice(&authorized_locker.as_slice()[4..20]);
    B256::from(word)
}

/// Builds the `PoolBalanceUpdate` that pins a swap to the amounts it was quoted for.
///
/// The extension compares the realized pool balance deltas against these minimums, and applies its
/// own fee only after that check. The pool gains `token_in`, so the minimum on that side is the
/// smallest input the swap may pay; it loses `token_out`, so the negative minimum on that side is
/// the largest output the pool may pay out, before the fee. The cap rejects an oversized swap, and
/// the floor rejects the reverse swap, whose `token_in` delta is negative and can never clear a
/// positive floor.
///
/// `floor_factor_bps` scales the quoted input into the floor and comes from the request's slippage
/// (see `input_floor_factor_bps`), so the floor never rejects drift the router would accept.
/// `cap_factor_bps` scales the quoted output into the cap and is a fixed tolerance, because
/// slippage bounds how much less a taker will accept and says nothing about how much more.
///
/// Deltas are ordered by token address to match the on-chain `PoolKey`. Both bounds are widened and
/// truncated, so the floor lands looser and the cap tighter by up to one base unit.
///
/// # Errors
/// Errors if either pinned amount overflows the extension's `i128` delta.
fn pinned_min_balance_update(
    swap: &Swap,
    floor_factor_bps: u32,
    cap_factor_bps: u32,
) -> Result<B256, SolveError> {
    let pool_token_in_delta = bps::scale_truncating(swap.amount_in(), floor_factor_bps)
        .to_i128()
        .ok_or_else(|| {
            SolveError::FailedEncoding(
                "pinned input floor overflows the extension's i128 balance delta".to_string(),
            )
        })?;
    let pool_token_out_delta = -bps::scale_truncating(swap.amount_out(), cap_factor_bps)
        .to_i128()
        .ok_or_else(|| {
            SolveError::FailedEncoding(
                "pinned output cap overflows the extension's i128 balance delta".to_string(),
            )
        })?;

    let (delta0, delta1) = if swap.token_in() <= swap.token_out() {
        (pool_token_in_delta, pool_token_out_delta)
    } else {
        (pool_token_out_delta, pool_token_in_delta)
    };

    let mut word = [0u8; 32];
    word[0..16].copy_from_slice(&delta0.to_be_bytes());
    word[16..32].copy_from_slice(&delta1.to_be_bytes());
    Ok(B256::from(word))
}

/// Derives the extension's 0.32 fixed-point fee so the taker's realized output tracks `committed`.
///
/// The fee is rounded down so the taker always receives at least the committed amount.
fn derive_fee_q32(gross: &BigUint, committed: &BigUint) -> u32 {
    if gross <= committed {
        return 0;
    }
    // The extension charges `ceil(gross · (fee << 32) / 2⁶⁴)`, so the largest fee that never takes
    // more than the surplus above the committed amount is `floor((gross − committed) · 2³² /
    // gross)`. Rounding down biases toward under-capture, keeping the taker at or above it.
    let surplus = gross - committed;
    let scaled = (surplus * BigUint::from(1u64 << 32)) / gross;
    scaled
        .min(BigUint::from(u32::MAX))
        .iter_u32_digits()
        .next()
        .unwrap_or(0)
}

/// Reads the Ekubo extension address from a component's static attributes.
fn pool_extension(component: &ProtocolComponent) -> Result<Address, SolveError> {
    let bytes = attribute(component, "extension")?;
    Address::try_from(bytes).map_err(|_| {
        SolveError::FailedEncoding("extension attribute is not a 20-byte address".to_string())
    })
}

/// Rebuilds the 32-byte `PoolConfig` word: `extension(20) ‖ fee(u64, 8) ‖ pool_type_config(4)`.
fn pool_config_word(component: &ProtocolComponent) -> Result<B256, SolveError> {
    let extension = attribute(component, "extension")?;
    let fee = attribute(component, "fee")?;
    let pool_type_config = attribute(component, "pool_type_config")?;

    if extension.len() != 20 {
        return Err(SolveError::FailedEncoding("extension attribute must be 20 bytes".to_string()));
    }
    if fee.len() != 8 {
        return Err(SolveError::FailedEncoding("fee attribute must be 8 bytes".to_string()));
    }
    if pool_type_config.len() != 4 {
        return Err(SolveError::FailedEncoding(
            "pool_type_config attribute must be 4 bytes".to_string(),
        ));
    }

    let mut word = [0u8; 32];
    word[0..20].copy_from_slice(extension);
    word[20..28].copy_from_slice(fee);
    word[28..32].copy_from_slice(pool_type_config);
    Ok(B256::from(word))
}

/// Computes `poolId = keccak256(token0₃₂ ‖ token1₃₂ ‖ poolConfig₃₂)`.
///
/// Each token is left-padded into a 32-byte word, so a token longer than 32 bytes is rejected
/// rather than panicking on the slice index.
fn pool_id(token0: &[u8], token1: &[u8], config: B256) -> Result<B256, SolveError> {
    if token0.len() > 32 || token1.len() > 32 {
        return Err(SolveError::FailedEncoding(
            "token address exceeds 32 bytes; cannot build poolId".to_string(),
        ));
    }
    let mut buf = [0u8; 96];
    buf[32 - token0.len()..32].copy_from_slice(token0);
    buf[64 - token1.len()..64].copy_from_slice(token1);
    buf[64..96].copy_from_slice(config.as_slice());
    Ok(keccak256(buf))
}

/// Orders two token addresses so `token0 < token1`, matching the on-chain `PoolKey`.
///
/// `pinned_min_balance_update` orders its two delta halves by the same comparison; if the two ever
/// disagreed, the extension would check the input floor against the output token.
fn sorted_tokens<'a>(token_in: &'a [u8], token_out: &'a [u8]) -> (&'a [u8], &'a [u8]) {
    if token_in <= token_out {
        (token_in, token_out)
    } else {
        (token_out, token_in)
    }
}

/// Computes the EIP-712 digest the `SignedExclusiveSwap` extension recovers the signer from.
fn eip712_digest(
    chain_id: u64,
    extension: Address,
    pool_id: B256,
    meta: B256,
    min_balance_update: B256,
) -> B256 {
    let domain_typehash = keccak256(
        b"EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)",
    );
    let name_hash = keccak256(b"Ekubo SignedExclusiveSwap");
    let version_hash = keccak256(b"1");

    let mut domain = Vec::with_capacity(32 * 5);
    domain.extend_from_slice(domain_typehash.as_slice());
    domain.extend_from_slice(name_hash.as_slice());
    domain.extend_from_slice(version_hash.as_slice());
    domain.extend_from_slice(&U256::from(chain_id).to_be_bytes::<32>());
    domain.extend_from_slice(B256::left_padding_from(extension.as_slice()).as_slice());
    let domain_separator = keccak256(&domain);

    let struct_typehash =
        keccak256(b"SignedSwap(bytes32 poolId,uint256 meta,bytes32 minBalanceUpdate)");
    let mut struct_input = Vec::with_capacity(32 * 4);
    struct_input.extend_from_slice(struct_typehash.as_slice());
    struct_input.extend_from_slice(pool_id.as_slice());
    struct_input.extend_from_slice(meta.as_slice());
    struct_input.extend_from_slice(min_balance_update.as_slice());
    let struct_hash = keccak256(&struct_input);

    let mut digest_input = Vec::with_capacity(2 + 64);
    digest_input.extend_from_slice(&[0x19, 0x01]);
    digest_input.extend_from_slice(domain_separator.as_slice());
    digest_input.extend_from_slice(struct_hash.as_slice());
    keccak256(&digest_input)
}

/// Reads a required static attribute as a byte slice.
fn attribute<'a>(component: &'a ProtocolComponent, key: &str) -> Result<&'a [u8], SolveError> {
    component
        .static_attributes
        .get(key)
        .map(AsRef::as_ref)
        .ok_or_else(|| SolveError::FailedEncoding(format!("component missing `{key}` attribute")))
}

#[cfg(test)]
mod tests {
    use std::{collections::HashMap, str::FromStr};

    use alloy::primitives::{b256, Address as EvmAddress, Signature};
    use chrono::NaiveDateTime;
    use rstest::rstest;
    use tycho_simulation::tycho_common::models::Chain as CommonChain;

    use super::*;
    use crate::algorithm::test_utils::MockProtocolSim;

    const CONTROLLER_KEY: &str =
        "0x1111111111111111111111111111111111111111111111111111111111111111";
    // SignedExclusiveSwap extension placeholder used by the tycho reference PR.
    const EXTENSION: &str = "0x5519ed5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e";
    // Stands in for the Tycho router, the only locker allowed to execute a payload.
    const LOCKER: Address = Address::repeat_byte(0x77);

    // Reimplements the extension's `computeFee` (ceil(amount * fee / 2^64)) to check the taker is
    // never charged more than the surplus.
    fn compute_fee(amount: u128, fee_x64: u64) -> u128 {
        let numerator = U256::from(amount) * U256::from(fee_x64) + U256::from(u64::MAX);
        u128::try_from(numerator >> 64).expect("fee fits in u128")
    }

    #[test]
    fn test_signed_swap_meta_packs_fields_in_order() {
        let deadline = 0x1122_3344u32;
        let fee = 0x5566_7788u32;
        let nonce = 0x99AA_BBCC_DDEE_FF00u64;
        let locker = EvmAddress::from([0xAB; 20]);

        let meta = signed_swap_meta(deadline, fee, nonce, locker);
        let bytes = meta.as_slice();

        assert_eq!(&bytes[0..4], &deadline.to_be_bytes());
        assert_eq!(&bytes[4..8], &fee.to_be_bytes());
        assert_eq!(&bytes[8..16], &nonce.to_be_bytes());
        // Low 128 bits of the locker = its last 16 bytes.
        assert_eq!(&bytes[16..32], &[0xABu8; 16]);
    }

    /// A 3% input floor — `input_floor_factor_bps(0.03)` — which the expectations below are
    /// written against.
    const FLOOR_FACTOR_3PCT: u32 = 9_700;

    /// The default 1% output cap, as the factor the packer takes.
    const CAP_FACTOR_1PCT: u32 = 10_100;

    /// The fixed `minBalanceUpdate` word the known-answer digests below were computed over.
    const FIXED_MIN_BALANCE_UPDATE: B256 =
        b256!("0x8000000000000000000000000000000080000000000000000000000000000000");

    /// Splits a packed `minBalanceUpdate` word into its two `i128` deltas.
    fn split_min_balance_update(word: B256) -> (i128, i128) {
        let halve = |bytes: &[u8]| i128::from_be_bytes(bytes.try_into().expect("16 bytes"));
        (halve(&word.as_slice()[0..16]), halve(&word.as_slice()[16..32]))
    }

    /// Mirrors the extension's own check: every realized delta must clear its minimum.
    ///
    /// Deltas are the pool's, so the token it gains is positive and the token it gives up is
    /// negative — the same frame `pinned_min_balance_update` packs.
    fn extension_accepts(min_balance_update: B256, realized: (i128, i128)) -> bool {
        let (min0, min1) = split_min_balance_update(min_balance_update);
        realized.0 >= min0 && realized.1 >= min1
    }

    #[rstest]
    #[case::one_percent(0.01, 9_900)]
    #[case::three_percent(0.03, FLOOR_FACTOR_3PCT)]
    #[case::no_slippage(0.0, 10_000)]
    // A request accepting everything leaves no floor on size — the sign still rejects the reverse.
    #[case::all_of_it(1.0, 0)]
    #[case::beyond_the_whole(5.0, 0)]
    // Rounded up, so the floor loosens rather than tightening onto a revert.
    #[case::rounds_up(0.000_05, 9_999)]
    #[case::negative_is_no_tolerance(-0.5, 10_000)]
    #[case::nan_is_no_tolerance(f64::NAN, 10_000)]
    fn test_input_floor_factor_bps(#[case] slippage: f64, #[case] expected: u32) {
        assert_eq!(input_floor_factor_bps(slippage), expected);
    }

    #[rstest]
    #[case::plain("250", Some(250))]
    #[case::whitespace_trimmed("  250  ", Some(250))]
    #[case::zero("0", Some(0))]
    #[case::the_whole("10000", Some(bps::DENOMINATOR))]
    // Above the whole would let a payload move twice the output it was quoted for.
    #[case::beyond_the_whole("10001", None)]
    #[case::not_a_number("loose", None)]
    #[case::negative("-100", None)]
    fn test_parse_output_cap_tolerance_bps(#[case] raw: &str, #[case] expected: Option<u32>) {
        assert_eq!(parse_output_cap_tolerance_bps(raw), expected);
    }

    #[test]
    fn test_output_cap_tolerance_overrides_the_default() {
        let signer = ExclusiveSwapSigner::new(CONTROLLER_KEY.parse().unwrap(), 1, 0, 120, LOCKER)
            .with_output_cap_tolerance_bps(500);
        let swap = swap_with_amounts(0x11, 0x22, 4_000_000, 3_000_000);
        let mut swap = swap;
        swap.set_committed_amount_out(BigUint::from(2_900_000u64));

        let user_data = signer
            .build_user_data(&swap, 0.03)
            .unwrap();

        // 5% above the quoted output instead of the default 50%.
        let (_, cap) = split_min_balance_update(B256::from_slice(&user_data.as_ref()[40..72]));
        assert_eq!(cap, -3_150_000);
    }

    #[test]
    fn test_input_floor_tracks_the_request_slippage() {
        let swap = swap_with_amounts(0x11, 0x22, 4_000_000, 3_000_000);

        let tight = pinned_min_balance_update(&swap, input_floor_factor_bps(0.01), CAP_FACTOR_1PCT)
            .unwrap();
        let loose = pinned_min_balance_update(&swap, input_floor_factor_bps(0.10), CAP_FACTOR_1PCT)
            .unwrap();

        // A request accepting more slippage gets a floor further below the quoted input.
        assert_eq!(split_min_balance_update(tight).0, 3_960_000);
        assert_eq!(split_min_balance_update(loose).0, 3_600_000);
        // The reverse swap stays rejected either way, whatever the floor.
        assert!(!extension_accepts(loose, (-3_000_000, 4_000_000)));
    }

    #[rstest]
    // token_in sorts first, so the input floor lands in delta0.
    #[case::token_in_is_token0(0x11, 0x22, 3_880_000, -3_030_000)]
    // token_out sorts first, so the halves swap.
    #[case::token_out_is_token0(0x22, 0x11, -3_030_000, 3_880_000)]
    fn test_pinned_min_balance_update_orders_and_signs_deltas(
        #[case] token_in: u8,
        #[case] token_out: u8,
        #[case] expected_delta0: i128,
        #[case] expected_delta1: i128,
    ) {
        // Distinct amounts, so each case pins which amount feeds which bound as well as the order.
        let swap = swap_with_amounts(token_in, token_out, 4_000_000, 3_000_000);

        let word = pinned_min_balance_update(&swap, FLOOR_FACTOR_3PCT, CAP_FACTOR_1PCT).unwrap();

        assert_eq!(split_min_balance_update(word), (expected_delta0, expected_delta1));
    }

    #[test]
    fn test_pinned_min_balance_update_brackets_the_quote() {
        let swap = swap_with_amounts(0x11, 0x22, 4_000_000, 3_000_000);

        let (floor, cap) = split_min_balance_update(
            pinned_min_balance_update(&swap, FLOOR_FACTOR_3PCT, CAP_FACTOR_1PCT).unwrap(),
        );

        // The floor never demands more than the quoted input, and the cap never allows less than
        // the quoted output; either would revert the taker's own swap.
        assert!(floor <= 4_000_000, "floor exceeds the quoted input");
        assert!(-cap >= 3_000_000, "cap is below the quoted output");
        // 3% of tolerance below the input, 1% above the output.
        assert_eq!(floor, 3_880_000);
        assert_eq!(cap, -3_030_000);
    }

    #[rstest]
    // The quoted trade itself: the pool gains the input and gives up the output.
    #[case::the_quoted_trade(4_000_000, -3_000_000, true)]
    // Twice the size breaches the cap on the pool's outflow.
    #[case::oversized(8_000_000, -6_000_000, false)]
    // The reverse direction cannot clear a positive floor on the input token.
    #[case::reversed(-3_000_000, 4_000_000, false)]
    // Drift inside both tolerances still clears.
    #[case::drift_within_tolerance(3_900_000, -3_020_000, true)]
    fn test_pinned_bounds_accept_the_quote_and_reject_the_rest(
        #[case] realized_delta0: i128,
        #[case] realized_delta1: i128,
        #[case] accepted: bool,
    ) {
        let swap = swap_with_amounts(0x11, 0x22, 4_000_000, 3_000_000);
        let word = pinned_min_balance_update(&swap, FLOOR_FACTOR_3PCT, CAP_FACTOR_1PCT).unwrap();

        assert_eq!(extension_accepts(word, (realized_delta0, realized_delta1)), accepted);
    }

    #[rstest]
    #[case::input_over_i128(u128::MAX, 3_000_000, "pinned input floor")]
    #[case::output_over_i128(4_000_000, u128::MAX, "pinned output cap")]
    fn test_pinned_min_balance_update_rejects_amount_over_i128(
        #[case] amount_in: u128,
        #[case] amount_out: u128,
        #[case] expected_bound: &str,
    ) {
        let swap = swap_with_amounts(0x11, 0x22, amount_in, amount_out);

        let error = pinned_min_balance_update(&swap, FLOOR_FACTOR_3PCT, CAP_FACTOR_1PCT)
            .expect_err("an amount over i128::MAX cannot be pinned")
            .to_string();

        assert!(error.contains(expected_bound), "{error} does not name the failing bound");
    }

    #[rstest]
    // Truncation erases the cap's 1% below 100 output units, leaving no room for a favourable
    // move — the cap lands exactly on the quote.
    #[case::headroom_truncated_away(99, -99)]
    #[case::zero_output(0, 0)]
    fn test_pinned_cap_headroom_truncates_at_small_amounts(
        #[case] amount_out: u128,
        #[case] expected_cap: i128,
    ) {
        let swap = swap_with_amounts(0x11, 0x22, 4_000_000, amount_out);

        let (_, cap) = split_min_balance_update(
            pinned_min_balance_update(&swap, FLOOR_FACTOR_3PCT, CAP_FACTOR_1PCT).unwrap(),
        );

        assert_eq!(cap, expected_cap);
    }

    #[rstest]
    #[case::committed_equals_gross(1000, 1000)]
    #[case::committed_exceeds_gross(1000, 2000)]
    fn test_derive_fee_q32_without_surplus(#[case] gross: u64, #[case] committed: u64) {
        assert_eq!(derive_fee_q32(&BigUint::from(gross), &BigUint::from(committed)), 0);
    }

    #[rstest]
    #[case::no_surplus(1_000_000, 1_000_000)]
    #[case::surplus_1_percent(1_000_000, 990_000)]
    #[case::surplus_50_percent(1_000_000, 500_000)]
    #[case::near_total_surplus(1_000_000, 1)]
    fn test_derive_fee_q32_never_shorts_taker(#[case] gross: u128, #[case] committed: u128) {
        let fee = derive_fee_q32(&BigUint::from(gross), &BigUint::from(committed));

        let fee_amount = compute_fee(gross, u64::from(fee) << 32);
        assert!(fee_amount <= gross - committed, "capture exceeds surplus");
        assert!(gross - fee_amount >= committed, "taker receives less than committed");
    }

    fn ekubo_component() -> ProtocolComponent {
        let static_attributes = HashMap::from([
            ("extension".to_string(), Bytes::from_str(EXTENSION).unwrap()),
            ("fee".to_string(), Bytes::from(0u64)),
            ("pool_type_config".to_string(), Bytes::from(0u32)),
        ]);
        ProtocolComponent::new(
            "ekubo-signed-pool",
            "ekubo_v3",
            "swap",
            CommonChain::Ethereum,
            vec![],
            vec![],
            static_attributes,
            Default::default(),
            Default::default(),
            NaiveDateTime::default(),
        )
    }

    #[test]
    fn test_pool_config_word_matches_packed_layout() {
        let config = pool_config_word(&ekubo_component()).unwrap();
        let expected = format!("{}{}", &EXTENSION[2..], "0".repeat(24));
        assert_eq!(alloy::hex::encode(config), expected);
    }

    #[test]
    fn test_sorted_tokens_orders_ascending() {
        let low: &[u8] = &[0x11u8; 20];
        let high: &[u8] = &[0x22u8; 20];
        assert_eq!(sorted_tokens(low, high), (low, high));
        assert_eq!(sorted_tokens(high, low), (low, high));
    }

    #[test]
    fn test_pool_id_independent_of_swap_direction() {
        let config = B256::ZERO;
        let low: &[u8] = &[0x11u8; 20];
        let high: &[u8] = &[0x22u8; 20];
        // Swapping token_in/token_out yields the same pool once sorted.
        let (a0, a1) = sorted_tokens(low, high);
        let (b0, b1) = sorted_tokens(high, low);
        assert_eq!(pool_id(a0, a1, config).unwrap(), pool_id(b0, b1, config).unwrap());
    }

    #[test]
    fn test_pool_id_rejects_over_long_token() {
        assert!(pool_id(&[0u8; 33], &[0x22u8; 20], B256::ZERO).is_err());
    }

    #[test]
    fn test_eip712_digest_signature_recovers_signer() {
        let signer: PrivateKeySigner = CONTROLLER_KEY.parse().unwrap();
        let extension = EvmAddress::from_str(EXTENSION).unwrap();
        let digest = eip712_digest(
            1,
            extension,
            keccak256(b"pool"),
            signed_swap_meta(1_000, 42, 7, EvmAddress::ZERO),
            FIXED_MIN_BALANCE_UPDATE,
        );

        let signature = signer.sign_hash_sync(&digest).unwrap();
        let recovered = signature
            .recover_address_from_prehash(&digest)
            .unwrap();
        assert_eq!(recovered, signer.address());
        // v byte is normalized to 27/28, matching the on-chain `abi.encodePacked(r, s, v)`.
        assert!(matches!(signature.as_bytes()[64], 27 | 28));
    }

    #[test]
    fn test_eip712_digest_matches_independent_oracle() {
        // Known-answer vector: the expected digest was computed independently with `cast keccak`
        // (foundry) from the Ekubo domain/struct definitions, pinning the domain strings, type
        // hashes, field ordering, and the meta packing against a non-alloy Keccak implementation.
        // Inputs: chainId=1, extension=EXTENSION, poolId=0x11..11, deadline=1000, fee=42, nonce=7,
        // locker=0, minBalanceUpdate=accept-any.
        let extension = EvmAddress::from_str(EXTENSION).unwrap();
        let pool_id = B256::from([0x11u8; 32]);
        let meta = signed_swap_meta(1_000, 42, 7, EvmAddress::ZERO);
        let min_bu = FIXED_MIN_BALANCE_UPDATE;

        let digest = eip712_digest(1, extension, pool_id, meta, min_bu);

        let expected =
            B256::from_str("0xd47eb1b9f473ba6fa851d6dee23ab3ae57ee989187256835206411cea3baa0e0")
                .unwrap();
        assert_eq!(digest, expected);
    }

    fn swap_with_amounts(token_in: u8, token_out: u8, amount_in: u128, amount_out: u128) -> Swap {
        Swap::new(
            "ekubo-signed-pool".to_string(),
            "ekubo_v3".to_string(),
            Bytes::from([token_in; 20].as_ref()),
            Bytes::from([token_out; 20].as_ref()),
            BigUint::from(amount_in),
            BigUint::from(amount_out),
            BigUint::from(50_000u64),
            ekubo_component(),
            Box::new(MockProtocolSim::default()),
        )
    }

    fn signed_swap(committed: Option<u64>) -> Swap {
        let mut swap = swap_with_amounts(0x11, 0x22, 1_000_000, 1_000_000);
        if let Some(committed) = committed {
            swap.set_committed_amount_out(BigUint::from(committed));
        }
        swap
    }

    #[test]
    fn test_build_user_data_layout() {
        let signer = ExclusiveSwapSigner::new(CONTROLLER_KEY.parse().unwrap(), 1, 0, 120, LOCKER);
        let swap = signed_swap(Some(990_000));

        let user_data = signer
            .build_user_data(&swap, 0.03)
            .unwrap();
        let bytes = user_data.as_ref();

        // Offsets mirror tycho `EkuboV3SwapEncoder::parse_signed_user_data`:
        // fee(8) | meta(32) | minBalanceUpdate(32) | signature(65).
        assert_eq!(bytes.len(), 8 + 32 + 32 + 65);
        let config = pool_config_word(swap.protocol_component()).unwrap();
        assert_eq!(&bytes[0..8], &config.as_slice()[20..28]); // pool config fee
                                                              // Pinned against literals, not a second call to the packer: the fixture quotes 1_000_000
                                                              // in and out, so the floor is 3% below and the cap 50% above.
        assert_eq!(
            split_min_balance_update(B256::from_slice(&bytes[40..72])),
            (970_000, -1_500_000)
        );

        // The signature recovers over the digest rebuilt from the payload's meta and minBU.
        let extension = EvmAddress::from_str(EXTENSION).unwrap();
        let meta = B256::from_slice(&bytes[8..40]);
        let min_bu = B256::from_slice(&bytes[40..72]);
        let (token0, token1) = sorted_tokens(swap.token_in(), swap.token_out());
        let pool_id = pool_id(token0, token1, config).unwrap();
        let digest = eip712_digest(1, extension, pool_id, meta, min_bu);

        let signature = Signature::try_from(&bytes[72..]).unwrap();
        assert_eq!(
            signature
                .recover_address_from_prehash(&digest)
                .unwrap(),
            signer.signer.address()
        );
    }

    #[test]
    fn test_build_user_data_requires_committed_amount() {
        let signer = ExclusiveSwapSigner::new(CONTROLLER_KEY.parse().unwrap(), 1, 0, 120, LOCKER);
        assert!(signer
            .build_user_data(&signed_swap(None), 0.03)
            .is_err());
    }

    /// Reads the nonce out of a `user_data` payload: it lives in meta bits [191..128] = meta bytes
    /// [8..16], and meta starts after the fee(8) prefix.
    fn payload_nonce(user_data: &Bytes) -> u64 {
        u64::from_be_bytes(
            user_data.as_ref()[16..24]
                .try_into()
                .unwrap(),
        )
    }

    #[test]
    fn test_nonce_increments_per_payload() {
        let signer = ExclusiveSwapSigner::new(CONTROLLER_KEY.parse().unwrap(), 42, 7, 120, LOCKER);
        let swap = signed_swap(Some(990_000));

        let first = signer
            .build_user_data(&swap, 0.03)
            .unwrap();
        let second = signer
            .build_user_data(&swap, 0.03)
            .unwrap();

        assert_eq!(payload_nonce(&first), 7 << 32);
        assert_eq!(payload_nonce(&second), (7 << 32) + 1);
    }

    #[test]
    fn test_nonce_ranges_disjoint_across_prefixes() {
        let key: PrivateKeySigner = CONTROLLER_KEY.parse().unwrap();
        let swap = signed_swap(Some(990_000));
        // Two processes (a restart, or a second replica) each draw their own prefix.
        let first = ExclusiveSwapSigner::new(key.clone(), 42, 1, 120, LOCKER);
        let second = ExclusiveSwapSigner::new(key, 42, 2, 120, LOCKER);

        let mut nonces = Vec::new();
        for _ in 0..4 {
            nonces.push(payload_nonce(
                &first
                    .build_user_data(&swap, 0.03)
                    .unwrap(),
            ));
            nonces.push(payload_nonce(
                &second
                    .build_user_data(&swap, 0.03)
                    .unwrap(),
            ));
        }

        let unique: std::collections::HashSet<u64> = nonces.iter().copied().collect();
        assert_eq!(unique.len(), nonces.len());
    }

    #[test]
    fn test_payload_binds_authorized_locker() {
        let signer = ExclusiveSwapSigner::new(CONTROLLER_KEY.parse().unwrap(), 1, 0, 120, LOCKER);

        let user_data = signer
            .build_user_data(&signed_swap(Some(990_000)), 0.03)
            .unwrap();

        // meta starts after the fee(8) prefix; its low 128 bits carry the locker's last 16 bytes.
        let meta = B256::from_slice(&user_data.as_ref()[8..40]);
        assert_eq!(&meta.as_slice()[16..32], &LOCKER.as_slice()[4..20]);
    }

    #[test]
    fn test_nonce_avoids_reserved_sentinel() {
        // The extension never consumes `u64::MAX` — a payload carrying it stays replayable until
        // its deadline. The counter stops one short of `u32::MAX`, so even the widest prefix
        // cannot compose that value.
        let signer =
            ExclusiveSwapSigner::new(CONTROLLER_KEY.parse().unwrap(), 42, u32::MAX, 120, LOCKER);
        let swap = signed_swap(Some(990_000));
        signer
            .nonce_counter
            .store(u32::MAX - 1, Ordering::Relaxed);

        assert_eq!(
            payload_nonce(
                &signer
                    .build_user_data(&swap, 0.03)
                    .unwrap()
            ),
            u64::MAX - 1
        );
        assert!(signer
            .build_user_data(&swap, 0.03)
            .is_err());
    }

    #[test]
    fn test_exhausted_nonce_counter() {
        let signer = ExclusiveSwapSigner::new(CONTROLLER_KEY.parse().unwrap(), 42, 1, 120, LOCKER);
        let swap = signed_swap(Some(990_000));
        signer
            .nonce_counter
            .store(u32::MAX, Ordering::Relaxed);

        // The counter must stop rather than wrap onto nonces this prefix already spent.
        assert!(signer
            .build_user_data(&swap, 0.03)
            .is_err());
        assert!(signer
            .build_user_data(&swap, 0.03)
            .is_err());
    }
}