cow-rs 0.1.1

Rust SDK for the CoW Protocol: quoting, signing, posting and tracking orders, plus composable orders, on-chain reads and subgraph queries.
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
//! Quote amount calculations: fee breakdown, slippage, and cost stages.
//!
//! Ports the `quoteAmountsAndCosts` package from the `TypeScript` SDK.
//! All arithmetic uses [`U256`] to avoid overflow on token amounts.
//!
//! # Fee stages
//!
//! The `/quote` API returns amounts where protocol fee and network costs are
//! already baked in. This module reconstructs every intermediate stage:
//!
//! 1. **Before all fees** — spot-price amounts.
//! 2. **After protocol fees** (= before network costs).
//! 3. **After network costs**.
//! 4. **After partner fees**.
//! 5. **After slippage** — the minimum the user signs for.
//!
//! # Key functions
//!
//! | Function | Purpose |
//! |---|---|
//! | [`get_quote_amounts_and_costs`] | Full breakdown from `/quote` response |
//! | [`get_protocol_fee_amount`] | Reverse-engineer the protocol fee |
//! | [`get_quote_amounts_after_partner_fee`] | Apply partner fee to amounts |
//! | [`get_quote_amounts_after_slippage`] | Apply slippage tolerance |
//! | [`transform_order`] | Enrich an `Order` with `total_fee` and EthFlow fields |

use alloy_primitives::U256;

use crate::types::{HUNDRED_THOUSANDS, ONE_HUNDRED_BPS, OrderKind};

// ── Core types ───────────────────────────────────────────────────────────────

/// Sell and buy amounts at a particular fee stage.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct QuoteAmounts {
    /// Amount of the sell token (in atoms).
    pub sell_amount: U256,
    /// Amount of the buy token (in atoms).
    pub buy_amount: U256,
}

/// Network fee expressed in both sell and buy currency.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct QuoteNetworkFee {
    /// Network fee denominated in the sell token.
    pub amount_in_sell_currency: U256,
    /// Network fee denominated in the buy token.
    pub amount_in_buy_currency: U256,
}

/// A single fee component: absolute amount and its BPS rate.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct QuoteFeeComponent {
    /// Absolute fee amount (in the surplus token's atoms).
    pub amount: U256,
    /// Fee rate in basis points.
    pub bps: f64,
}

/// All cost components of a quote.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct QuoteCosts {
    /// Gas / network fee covering on-chain settlement.
    pub network_fee: QuoteNetworkFee,
    /// Partner fee (revenue share).
    pub partner_fee: QuoteFeeComponent,
    /// Protocol fee collected by `CoW` Protocol.
    pub protocol_fee: QuoteFeeComponent,
}

/// Complete breakdown of quote amounts at every fee stage.
///
/// See the `TypeScript` SDK's `QuoteAmountsAndCosts` for the canonical
/// description of each stage and how fees are layered.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct QuoteAmountsAndCostsResult {
    /// Whether the underlying order is a sell order.
    pub is_sell: bool,
    /// Cost breakdown.
    pub costs: QuoteCosts,
    /// Spot-price amounts before any fees.
    pub before_all_fees: QuoteAmounts,
    /// Amounts before network costs (same as `after_protocol_fees`).
    pub before_network_costs: QuoteAmounts,
    /// Amounts after protocol fees have been applied.
    pub after_protocol_fees: QuoteAmounts,
    /// Amounts after network costs have been applied.
    pub after_network_costs: QuoteAmounts,
    /// Amounts after partner fees have been applied.
    pub after_partner_fees: QuoteAmounts,
    /// Amounts after slippage tolerance has been applied.
    pub after_slippage: QuoteAmounts,
    /// Final amounts to sign in the order.
    pub amounts_to_sign: QuoteAmounts,
}

// ── Input types ──────────────────────────────────────────────────────────────

/// Order parameters needed by the quote-amount calculations.
///
/// These map to the fields returned by `POST /api/v1/quote`.
#[derive(Debug, Clone)]
pub struct QuoteOrderParams {
    /// Sell or buy.
    pub kind: OrderKind,
    /// Sell amount (after network costs for sell orders).
    pub sell_amount: U256,
    /// Buy amount (minimum for sell orders, exact for buy orders).
    pub buy_amount: U256,
    /// Network fee / gas cost amount.
    pub fee_amount: U256,
}

/// Parameters for [`get_quote_amounts_and_costs`].
#[derive(Debug, Clone)]
pub struct QuoteAmountsAndCostsParams {
    /// The order parameters from the `/quote` response.
    pub order_params: QuoteOrderParams,
    /// Protocol fee in BPS (may be fractional, e.g. `0.003`). `None` or `0` means no protocol fee.
    pub protocol_fee_bps: Option<f64>,
    /// Partner fee in BPS. `None` or `0` means no partner fee.
    pub partner_fee_bps: Option<u32>,
    /// Slippage tolerance in BPS.
    pub slippage_percent_bps: u32,
}

/// Parameters for [`get_protocol_fee_amount`].
#[derive(Debug, Clone)]
pub struct ProtocolFeeAmountParams {
    /// The order parameters from the `/quote` response.
    pub order_params: QuoteOrderParams,
    /// Protocol fee in BPS (may be fractional).
    pub protocol_fee_bps: f64,
}

// ── Protocol fee ─────────────────────────────────────────────────────────────

/// Derive the absolute protocol-fee amount from the quote response.
///
/// The `/quote` API returns amounts where the protocol fee is already
/// baked in. This function reverses the fee to recover the absolute amount.
///
/// # Parameters
///
/// * `params` — a [`ProtocolFeeAmountParams`] containing the order parameters and the protocol fee
///   rate in BPS.
///
/// For **sell orders** the fee was deducted from `buyAmount`:
/// ```text
/// protocolFee = buyAmount * bps / (ONE_HUNDRED_BPS * scale - bps_scaled)
/// ```
///
/// For **buy orders** the fee was added to `sellAmount`:
/// ```text
/// protocolFee = (sellAmount + feeAmount) * bps / (ONE_HUNDRED_BPS * scale + bps_scaled)
/// ```
#[must_use]
pub fn get_protocol_fee_amount(params: &ProtocolFeeAmountParams) -> U256 {
    let ProtocolFeeAmountParams { order_params, protocol_fee_bps } = params;

    if *protocol_fee_bps <= 0.0 {
        return U256::ZERO;
    }

    let is_sell = order_params.kind.is_sell();
    let sell_amount = order_params.sell_amount;
    let buy_amount = order_params.buy_amount;
    let fee_amount = order_params.fee_amount;

    let protocol_fee_scale = U256::from(HUNDRED_THOUSANDS);
    // Keep 5 decimal places of BPS precision while staying in integer domain.
    let protocol_fee_bps_scaled = (*protocol_fee_bps * HUNDRED_THOUSANDS as f64).round() as u64;
    let protocol_fee_bps_big = U256::from(protocol_fee_bps_scaled);

    if protocol_fee_bps_big.is_zero() {
        return U256::ZERO;
    }

    let one_hundred_bps = U256::from(ONE_HUNDRED_BPS);

    if is_sell {
        // SELL: protocolFee = buyAmount * bps / (ONE_HUNDRED_BPS * scale - bps)
        let denominator = one_hundred_bps * protocol_fee_scale - protocol_fee_bps_big;
        buy_amount * protocol_fee_bps_big / denominator
    } else {
        // BUY: protocolFee = (sellAmount + feeAmount) * bps / (ONE_HUNDRED_BPS * scale + bps)
        let denominator = one_hundred_bps * protocol_fee_scale + protocol_fee_bps_big;
        (sell_amount + fee_amount) * protocol_fee_bps_big / denominator
    }
}

// ── Partner fee ──────────────────────────────────────────────────────────────

/// Result of partner-fee calculation.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct PartnerFeeResult {
    /// Absolute partner-fee amount.
    pub partner_fee_amount: U256,
    /// Amounts after the partner fee has been applied.
    pub after_partner_fees: QuoteAmounts,
}

/// Calculate the partner-fee amount and adjust quote amounts accordingly.
///
/// The partner fee is computed relative to spot-price amounts
/// (`before_all_fees`) so it reflects the full trade volume, not volume
/// already reduced by protocol fee.
///
/// - **Sell orders**: partner fee is subtracted from `buyAmount`.
/// - **Buy orders**: partner fee is added to `sellAmount`.
///
/// # Parameters
///
/// * `after_network_costs` — amounts after network costs have been applied.
/// * `before_all_fees` — spot-price amounts (used as the fee base).
/// * `is_sell` — `true` for sell orders, `false` for buy orders.
/// * `partner_fee_bps` — partner fee rate in basis points.
///
/// # Returns
///
/// A [`PartnerFeeResult`] with the absolute fee amount and adjusted
/// amounts.
#[must_use]
pub fn get_quote_amounts_after_partner_fee(
    after_network_costs: &QuoteAmounts,
    before_all_fees: &QuoteAmounts,
    is_sell: bool,
    partner_fee_bps: u32,
) -> PartnerFeeResult {
    let one_hundred_bps = U256::from(ONE_HUNDRED_BPS);

    // Partner fee is based on spot-price amounts (before all fees).
    let surplus_amount =
        if is_sell { before_all_fees.buy_amount } else { before_all_fees.sell_amount };
    let partner_fee_amount = if partner_fee_bps > 0 {
        surplus_amount * U256::from(partner_fee_bps) / one_hundred_bps
    } else {
        U256::ZERO
    };

    let after_partner_fees = if is_sell {
        QuoteAmounts {
            sell_amount: after_network_costs.sell_amount,
            buy_amount: after_network_costs.buy_amount - partner_fee_amount,
        }
    } else {
        QuoteAmounts {
            sell_amount: after_network_costs.sell_amount + partner_fee_amount,
            buy_amount: after_network_costs.buy_amount,
        }
    };

    PartnerFeeResult { partner_fee_amount, after_partner_fees }
}

// ── Slippage ─────────────────────────────────────────────────────────────────

/// Apply slippage tolerance to amounts after all fees.
///
/// Slippage protects the user from price movements between quoting and
/// execution. It is always applied to the surplus (non-fixed) side:
///
/// - **Sell orders**: slippage reduces `buyAmount` (user accepts less).
/// - **Buy orders**: slippage increases `sellAmount` (user accepts more).
///
/// # Parameters
///
/// * `after_partner_fees` — amounts after partner fees have been applied.
/// * `is_sell` — `true` for sell orders, `false` for buy orders.
/// * `slippage_bps` — slippage tolerance in basis points.
///
/// # Returns
///
/// A [`QuoteAmounts`] with slippage applied to the surplus side.
#[must_use]
pub fn get_quote_amounts_after_slippage(
    after_partner_fees: &QuoteAmounts,
    is_sell: bool,
    slippage_bps: u32,
) -> QuoteAmounts {
    let one_hundred_bps = U256::from(ONE_HUNDRED_BPS);
    let slippage_bps_big = U256::from(slippage_bps);

    let slippage = |amount: U256| -> U256 { amount * slippage_bps_big / one_hundred_bps };

    if is_sell {
        QuoteAmounts {
            sell_amount: after_partner_fees.sell_amount,
            buy_amount: after_partner_fees.buy_amount - slippage(after_partner_fees.buy_amount),
        }
    } else {
        QuoteAmounts {
            sell_amount: after_partner_fees.sell_amount + slippage(after_partner_fees.sell_amount),
            buy_amount: after_partner_fees.buy_amount,
        }
    }
}

// ── Main entry point ─────────────────────────────────────────────────────────

/// Calculate all quote-amount stages and costs from a `/quote` API
/// response.
///
/// Takes the raw order parameters (where protocol fee and network costs
/// are already baked in) and reconstructs every intermediate amount stage:
///
/// 1. **Before all fees** — spot-price amounts.
/// 2. **After protocol fees** (= before network costs).
/// 3. **After network costs**.
/// 4. **After partner fees**.
/// 5. **After slippage** — the minimum the user signs for.
///
/// The returned [`QuoteAmountsAndCostsResult`] includes `amounts_to_sign`,
/// the final sell/buy amounts that should be placed in the signed order.
///
/// # Parameters
///
/// * `params` — a [`QuoteAmountsAndCostsParams`] containing the order parameters from the `/quote`
///   response, protocol/partner fee rates, and slippage tolerance.
///
/// # Returns
///
/// A [`QuoteAmountsAndCostsResult`] with amounts at every fee stage and
/// the complete cost breakdown.
#[must_use]
pub fn get_quote_amounts_and_costs(
    params: &QuoteAmountsAndCostsParams,
) -> QuoteAmountsAndCostsResult {
    let QuoteAmountsAndCostsParams {
        order_params,
        protocol_fee_bps,
        partner_fee_bps,
        slippage_percent_bps,
    } = params;

    let partner_fee = partner_fee_bps.map_or(0, |v| v);
    let protocol_fee = protocol_fee_bps.map_or(0.0, |v| v);
    let is_sell = order_params.kind.is_sell();

    let sell_amount = order_params.sell_amount;
    let buy_amount = order_params.buy_amount;
    let network_cost_amount = order_params.fee_amount;

    // Avoid division by zero when sell_amount is 0.
    let network_cost_in_buy = if sell_amount.is_zero() {
        U256::ZERO
    } else {
        buy_amount * network_cost_amount / sell_amount
    };

    // Reconstruct the protocol fee amount from the baked-in quote.
    let protocol_fee_amount = get_protocol_fee_amount(&ProtocolFeeAmountParams {
        order_params: order_params.clone(),
        protocol_fee_bps: protocol_fee,
    });

    // Stage 0: before all fees (spot price).
    let before_all_fees = if is_sell {
        QuoteAmounts {
            sell_amount: sell_amount + network_cost_amount,
            buy_amount: buy_amount + network_cost_in_buy + protocol_fee_amount,
        }
    } else {
        QuoteAmounts { sell_amount: sell_amount - protocol_fee_amount, buy_amount }
    };

    // Stage 1: after protocol fees (= before network costs).
    let after_protocol_fees = if is_sell {
        QuoteAmounts {
            sell_amount: before_all_fees.sell_amount,
            buy_amount: before_all_fees.buy_amount - protocol_fee_amount,
        }
    } else {
        QuoteAmounts { sell_amount, buy_amount: before_all_fees.buy_amount }
    };

    // Stage 2: after network costs.
    let after_network_costs = if is_sell {
        QuoteAmounts { sell_amount, buy_amount }
    } else {
        QuoteAmounts {
            sell_amount: sell_amount + network_cost_amount,
            buy_amount: after_protocol_fees.buy_amount,
        }
    };

    // Stage 3: after partner fees.
    let PartnerFeeResult { partner_fee_amount, after_partner_fees } =
        get_quote_amounts_after_partner_fee(
            &after_network_costs,
            &before_all_fees,
            is_sell,
            partner_fee,
        );

    // Stage 4: after slippage.
    let after_slippage =
        get_quote_amounts_after_slippage(&after_partner_fees, is_sell, *slippage_percent_bps);

    // Final amounts to sign.
    let amounts_to_sign = if is_sell {
        QuoteAmounts {
            sell_amount: before_all_fees.sell_amount,
            buy_amount: after_slippage.buy_amount,
        }
    } else {
        QuoteAmounts {
            sell_amount: after_slippage.sell_amount,
            buy_amount: before_all_fees.buy_amount,
        }
    };

    QuoteAmountsAndCostsResult {
        is_sell,
        costs: QuoteCosts {
            network_fee: QuoteNetworkFee {
                amount_in_sell_currency: network_cost_amount,
                amount_in_buy_currency: network_cost_in_buy,
            },
            partner_fee: QuoteFeeComponent { amount: partner_fee_amount, bps: partner_fee as f64 },
            protocol_fee: QuoteFeeComponent { amount: protocol_fee_amount, bps: protocol_fee },
        },
        before_all_fees,
        before_network_costs: after_protocol_fees,
        after_protocol_fees,
        after_network_costs,
        after_partner_fees,
        after_slippage,
        amounts_to_sign,
    }
}

// ── Transform order ──────────────────────────────────────────────────────────

/// Enrich an [`Order`](super::Order) by computing its `total_fee` field.
///
/// The total fee is the sum of `executed_fee_amount` and `executed_fee`
/// (both may be zero or non-zero independently). After computing the total
/// fee, `EthFlow` transformations are applied if applicable:
///
/// - `valid_to` is overwritten with the user's original validity.
/// - `owner` is overwritten with the on-chain user address.
/// - `sell_token` is replaced with
///   [`NATIVE_CURRENCY_ADDRESS`](crate::config::NATIVE_CURRENCY_ADDRESS).
///
/// Mirrors `transformOrder` from the `TypeScript` SDK.
///
/// # Parameters
///
/// * `order` — the [`Order`](super::Order) to enrich (consumed and returned).
///
/// # Returns
///
/// The enriched [`Order`](super::Order) with `total_fee` set.
#[must_use]
pub fn transform_order(mut order: super::Order) -> super::Order {
    // Compute total fee.
    let executed_fee_amount: U256 = order.executed_fee_amount.parse().map_or(U256::ZERO, |v| v);
    let executed_fee: U256 =
        order.executed_fee.as_deref().and_then(|s| s.parse().ok()).map_or(U256::ZERO, |v| v);
    order.total_fee = Some((executed_fee_amount + executed_fee).to_string());

    // Apply EthFlow transformations (no-op for regular orders).
    if let Some(ref ethflow_data) = order.ethflow_data {
        order.valid_to = ethflow_data.user_valid_to;
        if let Some(user) = order.onchain_user {
            order.owner = user;
        }
        order.sell_token = crate::config::NATIVE_CURRENCY_ADDRESS;
    }

    order
}

// ── Tests ────────────────────────────────────────────────────────────────────

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

    // Test fixtures from the TypeScript SDK test suite.
    fn sell_order() -> QuoteOrderParams {
        QuoteOrderParams {
            kind: OrderKind::Sell,
            sell_amount: U256::from_str_radix("156144455961718918", 10).unwrap(),
            fee_amount: U256::from_str_radix("3855544038281082", 10).unwrap(),
            buy_amount: U256::from_str_radix("18632013982", 10).unwrap(),
        }
    }

    fn buy_order() -> QuoteOrderParams {
        QuoteOrderParams {
            kind: OrderKind::Buy,
            sell_amount: U256::from_str_radix("168970833896526983", 10).unwrap(),
            fee_amount: U256::from_str_radix("2947344072902629", 10).unwrap(),
            buy_amount: U256::from_str_radix("2000000000", 10).unwrap(),
        }
    }

    // ── Network costs ────────────────────────────────────────────────────────

    #[test]
    fn sell_after_network_costs_equals_api_sell_amount() {
        let order_params = sell_order();
        let result = get_quote_amounts_and_costs(&QuoteAmountsAndCostsParams {
            order_params: order_params.clone(),
            slippage_percent_bps: 0,
            partner_fee_bps: None,
            protocol_fee_bps: None,
        });
        assert_eq!(result.after_network_costs.sell_amount, order_params.sell_amount);
    }

    #[test]
    fn sell_before_network_costs_is_sell_plus_fee() {
        let order_params = sell_order();
        let result = get_quote_amounts_and_costs(&QuoteAmountsAndCostsParams {
            order_params: order_params.clone(),
            slippage_percent_bps: 0,
            partner_fee_bps: None,
            protocol_fee_bps: None,
        });
        assert_eq!(
            result.before_network_costs.sell_amount,
            order_params.sell_amount + order_params.fee_amount
        );
    }

    #[test]
    fn buy_after_network_costs_is_sell_plus_fee() {
        let order_params = buy_order();
        let result = get_quote_amounts_and_costs(&QuoteAmountsAndCostsParams {
            order_params: order_params.clone(),
            slippage_percent_bps: 0,
            partner_fee_bps: None,
            protocol_fee_bps: None,
        });
        assert_eq!(
            result.after_network_costs.sell_amount,
            order_params.sell_amount + order_params.fee_amount
        );
    }

    #[test]
    fn buy_before_network_costs_is_raw_sell() {
        let order_params = buy_order();
        let result = get_quote_amounts_and_costs(&QuoteAmountsAndCostsParams {
            order_params: order_params.clone(),
            slippage_percent_bps: 0,
            partner_fee_bps: None,
            protocol_fee_bps: None,
        });
        assert_eq!(result.before_network_costs.sell_amount, order_params.sell_amount);
    }

    #[test]
    fn sell_buy_amount_includes_network_cost_in_buy_currency() {
        let order_params = sell_order();
        let result = get_quote_amounts_and_costs(&QuoteAmountsAndCostsParams {
            order_params: order_params.clone(),
            slippage_percent_bps: 0,
            partner_fee_bps: None,
            protocol_fee_bps: None,
        });
        let network_cost_in_buy =
            order_params.buy_amount * order_params.fee_amount / order_params.sell_amount;
        assert_eq!(
            result.before_network_costs.buy_amount,
            order_params.buy_amount + network_cost_in_buy
        );
        assert_eq!(result.after_network_costs.buy_amount, order_params.buy_amount);
    }

    #[test]
    fn buy_buy_amount_unchanged_by_network_costs() {
        let order_params = buy_order();
        let result = get_quote_amounts_and_costs(&QuoteAmountsAndCostsParams {
            order_params,
            slippage_percent_bps: 0,
            partner_fee_bps: None,
            protocol_fee_bps: None,
        });
        assert_eq!(result.after_network_costs.buy_amount, result.before_network_costs.buy_amount);
    }

    // ── Partner fee ──────────────────────────────────────────────────────────

    #[test]
    fn sell_partner_fee_subtracted_from_buy() {
        let order_params = sell_order();
        let partner_fee_bps = 100u32;
        let result = get_quote_amounts_and_costs(&QuoteAmountsAndCostsParams {
            order_params: order_params.clone(),
            slippage_percent_bps: 0,
            partner_fee_bps: Some(partner_fee_bps),
            protocol_fee_bps: None,
        });
        let network_cost_in_buy =
            order_params.buy_amount * order_params.fee_amount / order_params.sell_amount;
        let buy_before_all_fees = order_params.buy_amount + network_cost_in_buy;
        let expected =
            buy_before_all_fees * U256::from(partner_fee_bps) / U256::from(ONE_HUNDRED_BPS);
        assert_eq!(result.costs.partner_fee.amount, expected);
    }

    #[test]
    fn buy_partner_fee_added_to_sell() {
        let order_params = buy_order();
        let partner_fee_bps = 100u32;
        let result = get_quote_amounts_and_costs(&QuoteAmountsAndCostsParams {
            order_params: order_params.clone(),
            slippage_percent_bps: 0,
            partner_fee_bps: Some(partner_fee_bps),
            protocol_fee_bps: None,
        });
        let expected =
            order_params.sell_amount * U256::from(partner_fee_bps) / U256::from(ONE_HUNDRED_BPS);
        assert_eq!(result.costs.partner_fee.amount, expected);
    }

    // ── Slippage ─────────────────────────────────────────────────────────────

    #[test]
    fn sell_slippage_subtracted_from_buy() {
        let order_params = sell_order();
        let slippage_bps = 200u32;
        let result = get_quote_amounts_and_costs(&QuoteAmountsAndCostsParams {
            order_params: order_params.clone(),
            slippage_percent_bps: slippage_bps,
            partner_fee_bps: None,
            protocol_fee_bps: None,
        });
        let buy_after_network = order_params.buy_amount;
        let slippage = buy_after_network * U256::from(slippage_bps) / U256::from(ONE_HUNDRED_BPS);
        assert_eq!(result.after_slippage.buy_amount, buy_after_network - slippage);
    }

    #[test]
    fn buy_slippage_added_to_sell() {
        let order_params = buy_order();
        let slippage_bps = 200u32;
        let result = get_quote_amounts_and_costs(&QuoteAmountsAndCostsParams {
            order_params: order_params.clone(),
            slippage_percent_bps: slippage_bps,
            partner_fee_bps: None,
            protocol_fee_bps: None,
        });
        let sell_after_network = order_params.sell_amount + order_params.fee_amount;
        let slippage = sell_after_network * U256::from(slippage_bps) / U256::from(ONE_HUNDRED_BPS);
        assert_eq!(result.after_slippage.sell_amount, sell_after_network + slippage);
    }

    // ── Protocol fee ─────────────────────────────────────────────────────────

    #[test]
    fn sell_protocol_fee_calculated_correctly() {
        let order_params = sell_order();
        let protocol_fee_bps = 20.0;
        let result = get_quote_amounts_and_costs(&QuoteAmountsAndCostsParams {
            order_params: order_params.clone(),
            slippage_percent_bps: 0,
            partner_fee_bps: None,
            protocol_fee_bps: Some(protocol_fee_bps),
        });
        let bps = U256::from(protocol_fee_bps as u64);
        let denominator = U256::from(ONE_HUNDRED_BPS) - bps;
        let expected = order_params.buy_amount * bps / denominator;
        assert_eq!(result.costs.protocol_fee.amount, expected);
    }

    #[test]
    fn buy_protocol_fee_calculated_correctly() {
        let order_params = buy_order();
        let protocol_fee_bps = 20.0;
        let result = get_quote_amounts_and_costs(&QuoteAmountsAndCostsParams {
            order_params: order_params.clone(),
            slippage_percent_bps: 0,
            partner_fee_bps: None,
            protocol_fee_bps: Some(protocol_fee_bps),
        });
        let sell_after_network = order_params.sell_amount + order_params.fee_amount;
        let bps = U256::from(protocol_fee_bps as u64);
        let denominator = U256::from(ONE_HUNDRED_BPS) + bps;
        let expected = sell_after_network * bps / denominator;
        assert_eq!(result.costs.protocol_fee.amount, expected);
    }

    #[test]
    fn sell_before_all_fees_includes_protocol_fee_once() {
        let order_params = sell_order();
        let protocol_fee_bps = 20.0;
        let result = get_quote_amounts_and_costs(&QuoteAmountsAndCostsParams {
            order_params,
            slippage_percent_bps: 0,
            partner_fee_bps: None,
            protocol_fee_bps: Some(protocol_fee_bps),
        });
        assert_eq!(
            result.before_all_fees.buy_amount,
            result.before_network_costs.buy_amount + result.costs.protocol_fee.amount
        );
    }

    #[test]
    fn buy_before_all_fees_includes_protocol_fee_once() {
        let order_params = buy_order();
        let protocol_fee_bps = 20.0;
        let result = get_quote_amounts_and_costs(&QuoteAmountsAndCostsParams {
            order_params,
            slippage_percent_bps: 0,
            partner_fee_bps: None,
            protocol_fee_bps: Some(protocol_fee_bps),
        });
        assert_eq!(
            result.before_all_fees.sell_amount,
            result.before_network_costs.sell_amount - result.costs.protocol_fee.amount
        );
    }

    #[test]
    fn sell_fractional_protocol_fee_bps() {
        let order_params = sell_order();
        let protocol_fee_bps: f64 = 0.003;
        let result = get_quote_amounts_and_costs(&QuoteAmountsAndCostsParams {
            order_params: order_params.clone(),
            slippage_percent_bps: 0,
            partner_fee_bps: None,
            protocol_fee_bps: Some(protocol_fee_bps),
        });
        // Match the TypeScript test: bps = BigInt(0.003 * 100_000) = 300
        let bps = U256::from((protocol_fee_bps * HUNDRED_THOUSANDS as f64) as u64);
        let denominator = U256::from(ONE_HUNDRED_BPS) * U256::from(HUNDRED_THOUSANDS) - bps;
        let expected = order_params.buy_amount * bps / denominator;
        assert_eq!(result.costs.protocol_fee.amount, expected);
        // The TS test asserts amount == 5589
        assert_eq!(result.costs.protocol_fee.amount, U256::from(5589u64));
    }

    #[test]
    fn buy_fractional_protocol_fee_bps() {
        let order_params = buy_order();
        let protocol_fee_bps: f64 = 0.00071;
        let result = get_quote_amounts_and_costs(&QuoteAmountsAndCostsParams {
            order_params,
            slippage_percent_bps: 0,
            partner_fee_bps: None,
            protocol_fee_bps: Some(protocol_fee_bps),
        });
        // The TS test asserts amount == 12206189769
        assert_eq!(result.costs.protocol_fee.amount, U256::from(12_206_189_769u64));
    }

    #[test]
    fn sell_partner_fee_with_protocol_fee() {
        let order_params = sell_order();
        let protocol_fee_bps = 20.0;
        let partner_fee_bps = 100u32;
        let result = get_quote_amounts_and_costs(&QuoteAmountsAndCostsParams {
            order_params: order_params.clone(),
            slippage_percent_bps: 0,
            partner_fee_bps: Some(partner_fee_bps),
            protocol_fee_bps: Some(protocol_fee_bps),
        });

        let buy_after = order_params.buy_amount;
        let protocol_bps = U256::from(protocol_fee_bps as u64);
        let protocol_denom = U256::from(ONE_HUNDRED_BPS) - protocol_bps;
        let protocol_fee = buy_after * protocol_bps / protocol_denom;

        let network_cost_in_buy = buy_after * order_params.fee_amount / order_params.sell_amount;
        let buy_before_all_fees = buy_after + network_cost_in_buy + protocol_fee;
        let expected_partner =
            buy_before_all_fees * U256::from(partner_fee_bps) / U256::from(ONE_HUNDRED_BPS);
        assert_eq!(result.costs.partner_fee.amount, expected_partner);
        assert_eq!(result.after_partner_fees.buy_amount, buy_after - expected_partner);
    }

    #[test]
    fn buy_partner_fee_with_protocol_fee() {
        let order_params = buy_order();
        let protocol_fee_bps = 20.0;
        let partner_fee_bps = 100u32;
        let result = get_quote_amounts_and_costs(&QuoteAmountsAndCostsParams {
            order_params: order_params.clone(),
            slippage_percent_bps: 0,
            partner_fee_bps: Some(partner_fee_bps),
            protocol_fee_bps: Some(protocol_fee_bps),
        });

        let sell_amount = order_params.sell_amount;
        let fee_amount = order_params.fee_amount;
        let sell_after_network = sell_amount + fee_amount;

        let protocol_bps = U256::from(protocol_fee_bps as u64);
        let protocol_denom = U256::from(ONE_HUNDRED_BPS) + protocol_bps;
        let protocol_fee = sell_after_network * protocol_bps / protocol_denom;

        let sell_before_all_fees = sell_amount - protocol_fee;
        let expected_partner =
            sell_before_all_fees * U256::from(partner_fee_bps) / U256::from(ONE_HUNDRED_BPS);
        assert_eq!(result.costs.partner_fee.amount, expected_partner);
        assert_eq!(result.after_partner_fees.sell_amount, sell_after_network + expected_partner);
    }

    // ── Zero protocol fee ───────────────────────────────────────────────────

    #[test]
    fn sell_protocol_fee_zero_bps() {
        let order_params = sell_order();
        let amount = get_protocol_fee_amount(&ProtocolFeeAmountParams {
            order_params,
            protocol_fee_bps: 0.0,
        });
        assert_eq!(amount, U256::ZERO);
    }

    #[test]
    fn sell_protocol_fee_negative_bps() {
        let order_params = sell_order();
        let amount = get_protocol_fee_amount(&ProtocolFeeAmountParams {
            order_params,
            protocol_fee_bps: -1.0,
        });
        assert_eq!(amount, U256::ZERO);
    }

    // ── Zero sell amount (division by zero guard) ───────────────────────────

    #[test]
    fn sell_order_zero_sell_amount() {
        let order_params = QuoteOrderParams {
            kind: OrderKind::Sell,
            sell_amount: U256::ZERO,
            buy_amount: U256::from(1000u64),
            fee_amount: U256::from(100u64),
        };
        let result = get_quote_amounts_and_costs(&QuoteAmountsAndCostsParams {
            order_params,
            slippage_percent_bps: 50,
            partner_fee_bps: None,
            protocol_fee_bps: None,
        });
        assert_eq!(result.costs.network_fee.amount_in_buy_currency, U256::ZERO);
    }

    // ── Partner fee zero bps ────────────────────────────────────────────────

    #[test]
    fn partner_fee_zero_bps() {
        let amounts =
            QuoteAmounts { sell_amount: U256::from(1000u64), buy_amount: U256::from(500u64) };
        let result = get_quote_amounts_after_partner_fee(&amounts, &amounts, true, 0);
        assert_eq!(result.partner_fee_amount, U256::ZERO);
        assert_eq!(result.after_partner_fees.buy_amount, U256::from(500u64));
    }

    // ── Slippage ────────────────────────────────────────────────────────────

    #[test]
    fn sell_slippage_reduces_buy_amount() {
        let amounts =
            QuoteAmounts { sell_amount: U256::from(1000u64), buy_amount: U256::from(10_000u64) };
        let result = get_quote_amounts_after_slippage(&amounts, true, 100); // 1% slippage
        assert_eq!(result.sell_amount, U256::from(1000u64));
        assert!(result.buy_amount < U256::from(10_000u64));
    }

    #[test]
    fn buy_slippage_increases_sell_amount() {
        let amounts =
            QuoteAmounts { sell_amount: U256::from(10_000u64), buy_amount: U256::from(1000u64) };
        let result = get_quote_amounts_after_slippage(&amounts, false, 100); // 1% slippage
        assert!(result.sell_amount > U256::from(10_000u64));
        assert_eq!(result.buy_amount, U256::from(1000u64));
    }

    // ── Buy order full pipeline ─────────────────────────────────────────

    #[test]
    fn buy_order_amounts_to_sign_correct() {
        let order_params = buy_order();
        let result = get_quote_amounts_and_costs(&QuoteAmountsAndCostsParams {
            order_params,
            slippage_percent_bps: 50,
            partner_fee_bps: Some(50),
            protocol_fee_bps: Some(10.0),
        });
        // For buy orders, amounts_to_sign.sell_amount = after_slippage.sell_amount
        assert_eq!(result.amounts_to_sign.sell_amount, result.after_slippage.sell_amount);
        // For buy orders, amounts_to_sign.buy_amount = before_all_fees.buy_amount
        assert_eq!(result.amounts_to_sign.buy_amount, result.before_all_fees.buy_amount);
        assert!(!result.is_sell);
    }

    #[test]
    fn sell_order_amounts_to_sign_correct() {
        let order_params = sell_order();
        let result = get_quote_amounts_and_costs(&QuoteAmountsAndCostsParams {
            order_params,
            slippage_percent_bps: 50,
            partner_fee_bps: Some(50),
            protocol_fee_bps: Some(10.0),
        });
        // For sell orders, amounts_to_sign.sell_amount = before_all_fees.sell_amount
        assert_eq!(result.amounts_to_sign.sell_amount, result.before_all_fees.sell_amount);
        // For sell orders, amounts_to_sign.buy_amount = after_slippage.buy_amount
        assert_eq!(result.amounts_to_sign.buy_amount, result.after_slippage.buy_amount);
        assert!(result.is_sell);
    }

    // ── Transform order ─────────────────────────────────────────────────

    #[test]
    fn transform_order_sets_total_fee() {
        let json = serde_json::json!({
            "uid": "0xmockuid",
            "sellToken": "0xfff9976782d46cc05630d1f6ebab18b2324d6b14",
            "buyToken": "0x1c7d4b196cb0c7b01d743fbc6116a902379c7238",
            "receiver": "0x0000000000000000000000000000000000000000",
            "sellAmount": "1000",
            "buyAmount": "500",
            "validTo": 1700000000u32,
            "appData": "0x0000000000000000000000000000000000000000000000000000000000000000",
            "feeAmount": "10",
            "kind": "sell",
            "partiallyFillable": false,
            "creationDate": "2024-01-01T00:00:00Z",
            "owner": "0x0000000000000000000000000000000000000000",
            "executedSellAmount": "100",
            "executedSellAmountBeforeFees": "100",
            "executedBuyAmount": "50",
            "executedFeeAmount": "5",
            "invalidated": false,
            "status": "open",
            "signingScheme": "eip712",
            "signature": "0x",
        });
        let order: super::super::Order = serde_json::from_value(json).unwrap();
        let enriched = transform_order(order);
        assert!(enriched.total_fee.is_some());
        assert_eq!(enriched.total_fee.unwrap(), "5");
    }
}