Skip to main content

breez_sdk_spark/token_conversion/
models.rs

1use std::fmt;
2use std::str::FromStr;
3
4use flashnet::{BTC_ASSET_ADDRESS, Pool};
5use serde::{Deserialize, Serialize};
6
7use crate::SdkError;
8
9use crate::utils::serde_helpers::{serde_option_u128_as_string, serde_u128_as_string};
10
11/// Default maximum slippage for conversions in basis points (0.1%)
12pub const DEFAULT_CONVERSION_MAX_SLIPPAGE_BPS: u32 = 10;
13/// Default timeout for conversion operations in seconds
14pub const DEFAULT_CONVERSION_TIMEOUT_SECS: u32 = 30;
15/// Default integrator pubkey used when executing conversions
16pub const DEFAULT_INTEGRATOR_PUBKEY: &str =
17    "037e26d9d62e0b3df2d3e66805f61de2a33914465297abf76817296a92ac3f2379";
18/// Default integrator fee BPS used when simulating/executing conversions
19pub const DEFAULT_INTEGRATOR_FEE_BPS: u32 = 5;
20
21/// Fee attribution for a conversion, indicating which side of the conversion
22/// (sent or received) the pool fee is denominated in. The two variants are
23/// mutually exclusive — a pool fee is always denominated in one asset.
24pub(crate) enum FeeSplit {
25    /// Fee is on the sent (outbound/`asset_in`) payment, denominated in `asset_in`.
26    Sent(u128),
27    /// Fee is on the received (inbound/`asset_out`) payment, denominated in `asset_out`.
28    Received(u128),
29}
30
31/// Response from estimating a conversion, used when preparing a payment that requires conversion
32#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
33#[derive(Debug, Clone, Serialize)]
34pub struct ConversionEstimate {
35    /// The conversion options used for the estimate
36    pub options: ConversionOptions,
37    /// The input amount for the conversion.
38    /// For `FromBitcoin`: the satoshis required to produce the desired token output.
39    /// For `ToBitcoin`: the token amount being converted.
40    pub amount_in: u128,
41    /// The estimated output amount from the conversion.
42    /// For `FromBitcoin`: the estimated token amount received.
43    /// For `ToBitcoin`: the estimated satoshis received.
44    pub amount_out: u128,
45    /// The fee estimated for the conversion.
46    /// Denominated in satoshis if converting from Bitcoin, otherwise in the token base units.
47    pub fee: u128,
48    /// The reason the conversion amount was adjusted, if applicable.
49    pub amount_adjustment: Option<AmountAdjustmentReason>,
50}
51
52/// The purpose of the conversion, which is used to provide context for the conversion
53/// if its related to an ongoing payment or a self-transfer.
54#[cfg_attr(feature = "uniffi", derive(uniffi::Enum))]
55#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
56pub enum ConversionPurpose {
57    /// Conversion is associated with an ongoing payment
58    OngoingPayment {
59        /// The payment request of the ongoing payment
60        payment_request: String,
61    },
62    /// Conversion is for self-transfer
63    SelfTransfer,
64    /// Conversion triggered automatically
65    AutoConversion,
66}
67
68/// Specifies how to determine the conversion amount.
69#[derive(Debug, Clone)]
70pub(crate) enum ConversionAmount {
71    /// Specify the minimum output amount - the input will be calculated.
72    /// Used for payment conversions where we know the required output.
73    MinAmountOut(u128),
74    /// Specify the exact input amount - used for auto-conversion where we know the sats balance.
75    AmountIn(u128),
76}
77
78/// How an executed swap departed from the terms the client signed.
79///
80/// The input is spent either way, so the conversion completes rather than being
81/// refunded. This records that it did not deliver what was signed for.
82#[cfg_attr(feature = "uniffi", derive(uniffi::Enum))]
83#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
84pub enum SwapDegradation {
85    /// Delivered less than the minimum the intent signed.
86    BelowMinimum,
87    /// Delivered an asset other than the one the intent named.
88    UnexpectedAsset,
89    /// Accepted without naming the amount, the asset, or the transfer carrying
90    /// it.
91    MissingInfo,
92}
93
94impl From<flashnet::SwapDegradation> for SwapDegradation {
95    fn from(d: flashnet::SwapDegradation) -> Self {
96        match d {
97            flashnet::SwapDegradation::BelowMinimum => Self::BelowMinimum,
98            flashnet::SwapDegradation::UnexpectedAsset => Self::UnexpectedAsset,
99            flashnet::SwapDegradation::MissingInfo => Self::MissingInfo,
100        }
101    }
102}
103
104/// The reason why a conversion amount was adjusted from the originally requested value.
105#[cfg_attr(feature = "uniffi", derive(uniffi::Enum))]
106#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
107pub enum AmountAdjustmentReason {
108    /// The amount was increased to meet the minimum conversion limit.
109    FlooredToMinLimit,
110    /// The amount was increased to convert the full token balance,
111    /// avoiding a remaining balance below the minimum conversion limit (token dust).
112    IncreasedToAvoidDust,
113}
114
115/// The status of the conversion
116#[cfg_attr(feature = "uniffi", derive(uniffi::Enum))]
117#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
118pub enum ConversionStatus {
119    /// Conversion is in-flight (queued or started, not yet completed)
120    Pending,
121    /// The conversion was successful
122    Completed,
123    /// The conversion failed (e.g., the initial send payment failed)
124    Failed,
125    /// The conversion failed and no refund was made yet, which requires action by the SDK to
126    /// perform the refund. This can happen if there was a failure during the conversion process.
127    RefundNeeded,
128    /// The conversion failed and a refund was made
129    Refunded,
130}
131
132impl fmt::Display for ConversionStatus {
133    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
134        match self {
135            ConversionStatus::Pending => write!(f, "pending"),
136            ConversionStatus::Completed => write!(f, "completed"),
137            ConversionStatus::Failed => write!(f, "failed"),
138            ConversionStatus::RefundNeeded => write!(f, "refund_needed"),
139            ConversionStatus::Refunded => write!(f, "refunded"),
140        }
141    }
142}
143
144impl FromStr for ConversionStatus {
145    type Err = String;
146
147    fn from_str(s: &str) -> Result<Self, Self::Err> {
148        match s {
149            "pending" => Ok(ConversionStatus::Pending),
150            "completed" => Ok(ConversionStatus::Completed),
151            "failed" => Ok(ConversionStatus::Failed),
152            "refund_needed" => Ok(ConversionStatus::RefundNeeded),
153            "refunded" => Ok(ConversionStatus::Refunded),
154            _ => Err(format!("Invalid conversion status '{s}'")),
155        }
156    }
157}
158
159/// Details of the asset conversion attached to a payment, when the payment
160/// involves a swap or cross-chain bridge in addition to the on-Spark transfer.
161///
162/// The variant identifies which provider handled the conversion:
163/// - [`ConversionInfo::Amm`] for Spark token swaps via Flashnet AMM pools.
164/// - [`ConversionInfo::Orchestra`] for cross-chain transfers via Flashnet
165///   Orchestra, in either direction (Spark → external chain, or external
166///   chain → Spark).
167/// - [`ConversionInfo::Boltz`] for sats → stable-coin reverse swaps via Boltz.
168#[cfg_attr(feature = "uniffi", derive(uniffi::Enum))]
169#[derive(Clone, Serialize, Deserialize, PartialEq)]
170#[serde(tag = "type")]
171pub enum ConversionInfo {
172    /// AMM (Flashnet pool-based) conversion — Spark ↔ Spark token swaps.
173    #[serde(rename = "amm")]
174    Amm {
175        /// The pool id associated with the conversion
176        pool_id: String,
177        /// The conversion id shared by both sides of the conversion
178        conversion_id: String,
179        /// The status of the conversion
180        status: ConversionStatus,
181        /// The fee paid for the conversion.
182        /// Denominated in satoshis if converting from Bitcoin, otherwise in the token base units.
183        #[serde(default, with = "serde_option_u128_as_string")]
184        fee: Option<u128>,
185        /// The purpose of the conversion
186        purpose: Option<ConversionPurpose>,
187        /// The reason the conversion amount was adjusted, if applicable.
188        #[serde(default)]
189        amount_adjustment: Option<AmountAdjustmentReason>,
190        /// How the swap departed from the signed terms, if it did. Set on a
191        /// conversion that completed without delivering what was signed for.
192        #[serde(default)]
193        degradation: Option<SwapDegradation>,
194    },
195    /// Orchestra cross-chain conversion via the Flashnet orchestration API,
196    /// in either direction.
197    ///
198    /// `chain`, `asset`, `asset_decimals` and `asset_contract` always describe
199    /// the external (non-Spark) side: the destination on a send, the source on
200    /// a receive. Amounts follow the direction of the transfer, so read each
201    /// amount field's own denomination.
202    #[serde(rename = "orchestra")]
203    Orchestra {
204        /// The Orchestra order id returned by `/v1/orchestration/submit`.
205        order_id: String,
206        /// The Orchestra quote id used to create this order.
207        quote_id: String,
208        /// Opaque token required for querying order status.
209        #[serde(default)]
210        read_token: Option<String>,
211
212        /// Chain name (e.g. `"base"`, `"solana"`, `"tron"`).
213        chain: String,
214        /// Stable chain identifier (e.g. EVM `chainId` decimal string `"8453"`
215        /// for Base, SLIP-44 or similar for other chains). `None` if the
216        /// provider doesn't expose one for this route.
217        #[serde(default)]
218        chain_id: Option<String>,
219        /// Asset ticker (e.g. `"USDC"`, `"USDT"`).
220        #[serde(default)]
221        asset: String,
222        /// The target-chain address on a send, the receiving Spark address
223        /// on a receive.
224        recipient_address: String,
225        /// Amount paid in, in `asset` base units. On a send it is the Spark
226        /// amount expressed in `asset` via the rate the SDK used at prepare
227        /// time. On a receive it is the deposit the sender made on `chain`.
228        #[serde(default, with = "serde_option_u128_as_string")]
229        asset_amount_in: Option<u128>,
230        /// Estimated amount delivered to the receiving end, frozen at prepare
231        /// time. In `asset` base units on a send, and in Spark-side units on
232        /// a receive (sats for Bitcoin, token base units for a token).
233        #[serde(with = "serde_u128_as_string")]
234        estimated_out: u128,
235        /// Actual delivered amount, in the same units as `estimated_out`.
236        /// Unset until the order reaches a terminal state.
237        #[serde(default, with = "serde_option_u128_as_string")]
238        delivered_amount: Option<u128>,
239        /// Transaction on `chain`, the non-Spark side of the conversion: the
240        /// delivery on a send, the funding deposit on a receive. Format follows
241        /// the chain (e.g. `0x`-prefixed hex on EVM, a base58 signature on
242        /// Solana). Unset until that transaction exists.
243        #[serde(default)]
244        external_tx_hash: Option<String>,
245        /// The transaction that refunded the deposit, to the refund address given
246        /// for the order or, without one, to the payer. Set once the order is
247        /// refunded.
248        #[serde(default)]
249        refund_tx_hash: Option<String>,
250        status: ConversionStatus,
251        /// Best-available total fee, in `asset` base units.
252        /// Prepare-time estimate while pending, realized fee when Completed.
253        #[serde(default, with = "serde_option_u128_as_string")]
254        fee_amount: Option<u128>,
255        /// Orchestra service fee, including the partner fee when one is set.
256        #[serde(
257            default,
258            alias = "fee",
259            rename = "service_fee_amount",
260            with = "serde_option_u128_as_string"
261        )]
262        service_fee_amount: Option<u128>,
263        /// Asset the service fee is denominated in. Unset means BTC sats.
264        #[serde(default)]
265        service_fee_asset: Option<String>,
266        /// Decimals of `service_fee_asset`, for formatting `service_fee_amount`.
267        /// Unset when the fee is in sats or the provider did not report them.
268        #[serde(default)]
269        service_fee_asset_decimals: Option<u32>,
270        /// Asset decimals (e.g. 6 for USDC).
271        asset_decimals: u32,
272        /// Token contract / mint address on `chain`. Unset when that side is
273        /// the chain's native asset.
274        #[serde(default)]
275        asset_contract: Option<String>,
276    },
277    /// Boltz reverse swap: cross-chain conversion via Lightning hold invoice.
278    ///
279    /// The swap's secrets and lifecycle state live on the synced Boltz swap row
280    /// keyed by `swap_id`, which also drives cross-instance recovery.
281    #[serde(rename = "boltz")]
282    Boltz {
283        /// The Boltz swap id returned by `POST /swap/reverse`.
284        swap_id: String,
285        /// The BOLT11 hold invoice paid on the Spark/Lightning side.
286        invoice: String,
287        /// Amount of the hold invoice in sats.
288        invoice_amount_sats: u64,
289        /// Cross-chain bridge tracking handle for bridged swaps: a `LayerZero`
290        /// message GUID for OFT (USDT0) routes, or a CCTP reference for USDC
291        /// routes. `None` for same-chain (Arbitrum-direct) delivery.
292        #[serde(default, alias = "lz_guid")]
293        bridge_ref: Option<String>,
294        /// DEX slippage tolerance (basis points) committed at prepare time.
295        max_slippage_bps: u32,
296        /// Whether the claim-time DEX quote drifted beyond `max_slippage_bps`.
297        #[serde(default)]
298        quote_degraded: bool,
299
300        /// Chain name (e.g. `"arbitrum"`, `"solana"`, `"tron"`).
301        chain: String,
302        /// Stable chain identifier (e.g. EVM `chainId` decimal string `"42161"`
303        /// for Arbitrum). `None` if the provider doesn't expose one for this
304        /// route.
305        #[serde(default)]
306        chain_id: Option<String>,
307        /// Asset ticker (e.g. `"USDT"`, `"USDT0"`).
308        #[serde(default)]
309        asset: String,
310        /// Recipient address on the target chain.
311        recipient_address: String,
312        /// Estimated amount in the asset's base units, frozen at prepare time.
313        #[serde(with = "serde_u128_as_string")]
314        estimated_out: u128,
315        /// Actual amount delivered. `None` until the claim receipt is processed.
316        #[serde(default, with = "serde_option_u128_as_string")]
317        delivered_amount: Option<u128>,
318        /// Current status of the reverse swap.
319        status: ConversionStatus,
320        /// Amount in expressed in the cross-chain asset's base units, via the
321        /// BTC/USD rate the SDK used at prepare time.
322        #[serde(default, with = "serde_option_u128_as_string")]
323        asset_amount_in: Option<u128>,
324        /// Best-available total fee in destination asset base units.
325        /// Prepare-time estimate while pending, realized fee on Completed.
326        #[serde(default, with = "serde_option_u128_as_string")]
327        fee_amount: Option<u128>,
328        /// Boltz spread in sats.
329        #[serde(
330            default,
331            alias = "fee",
332            rename = "service_fee_amount",
333            with = "serde_option_u128_as_string"
334        )]
335        service_fee_amount: Option<u128>,
336        /// Asset service fee is denominated in. Unset means BTC sats.
337        #[serde(default)]
338        service_fee_asset: Option<String>,
339        /// Asset decimals (e.g. 6 for USDT).
340        asset_decimals: u32,
341        /// Token contract / mint address on `chain`. Unset when that side is
342        /// the chain's native asset.
343        #[serde(default)]
344        asset_contract: Option<String>,
345    },
346}
347
348impl fmt::Debug for ConversionInfo {
349    #[allow(clippy::too_many_lines)]
350    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
351        match self {
352            ConversionInfo::Amm {
353                pool_id,
354                conversion_id,
355                status,
356                fee,
357                purpose,
358                amount_adjustment,
359                degradation,
360            } => f
361                .debug_struct("Amm")
362                .field("pool_id", pool_id)
363                .field("conversion_id", conversion_id)
364                .field("status", status)
365                .field("fee", fee)
366                .field("purpose", purpose)
367                .field("amount_adjustment", amount_adjustment)
368                .field("degradation", degradation)
369                .finish(),
370            ConversionInfo::Orchestra {
371                order_id,
372                quote_id,
373                read_token,
374                chain,
375                chain_id,
376                asset,
377                recipient_address,
378                asset_amount_in,
379                estimated_out,
380                delivered_amount,
381                external_tx_hash,
382                refund_tx_hash,
383                status,
384                fee_amount,
385                service_fee_amount,
386                service_fee_asset,
387                service_fee_asset_decimals,
388                asset_decimals,
389                asset_contract,
390            } => f
391                .debug_struct("Orchestra")
392                .field("order_id", order_id)
393                .field("quote_id", quote_id)
394                .field("read_token", &read_token.as_ref().map(|_| "<redacted>"))
395                .field("chain", chain)
396                .field("chain_id", chain_id)
397                .field("asset", asset)
398                .field("recipient_address", recipient_address)
399                .field("asset_amount_in", asset_amount_in)
400                .field("estimated_out", estimated_out)
401                .field("delivered_amount", delivered_amount)
402                .field("external_tx_hash", external_tx_hash)
403                .field("refund_tx_hash", refund_tx_hash)
404                .field("status", status)
405                .field("fee_amount", fee_amount)
406                .field("service_fee_amount", service_fee_amount)
407                .field("service_fee_asset", service_fee_asset)
408                .field("service_fee_asset_decimals", service_fee_asset_decimals)
409                .field("asset_decimals", asset_decimals)
410                .field("asset_contract", asset_contract)
411                .finish(),
412            ConversionInfo::Boltz {
413                swap_id,
414                invoice,
415                invoice_amount_sats,
416                bridge_ref,
417                max_slippage_bps,
418                quote_degraded,
419                chain,
420                chain_id,
421                asset,
422                recipient_address,
423                estimated_out,
424                delivered_amount,
425                status,
426                asset_amount_in,
427                fee_amount,
428                service_fee_amount,
429                service_fee_asset,
430                asset_decimals,
431                asset_contract,
432            } => f
433                .debug_struct("Boltz")
434                .field("swap_id", swap_id)
435                .field("invoice", invoice)
436                .field("invoice_amount_sats", invoice_amount_sats)
437                .field("bridge_ref", bridge_ref)
438                .field("max_slippage_bps", max_slippage_bps)
439                .field("quote_degraded", quote_degraded)
440                .field("chain", chain)
441                .field("chain_id", chain_id)
442                .field("asset", asset)
443                .field("recipient_address", recipient_address)
444                .field("estimated_out", estimated_out)
445                .field("delivered_amount", delivered_amount)
446                .field("status", status)
447                .field("asset_amount_in", asset_amount_in)
448                .field("fee_amount", fee_amount)
449                .field("service_fee_amount", service_fee_amount)
450                .field("service_fee_asset", service_fee_asset)
451                .field("asset_decimals", asset_decimals)
452                .field("asset_contract", asset_contract)
453                .finish(),
454        }
455    }
456}
457
458impl ConversionInfo {
459    /// The current status, regardless of conversion type.
460    pub fn status(&self) -> &ConversionStatus {
461        match self {
462            ConversionInfo::Amm { status, .. }
463            | ConversionInfo::Orchestra { status, .. }
464            | ConversionInfo::Boltz { status, .. } => status,
465        }
466    }
467
468    /// A mutable reference to the status, for in-place updates.
469    pub fn status_mut(&mut self) -> &mut ConversionStatus {
470        match self {
471            ConversionInfo::Amm { status, .. }
472            | ConversionInfo::Orchestra { status, .. }
473            | ConversionInfo::Boltz { status, .. } => status,
474        }
475    }
476
477    /// Headline fee: AMM pool fee in source units, or the cross-chain total
478    /// in destination-asset base units.
479    pub fn fee(&self) -> Option<u128> {
480        match self {
481            ConversionInfo::Amm { fee, .. } => *fee,
482            ConversionInfo::Orchestra { fee_amount, .. }
483            | ConversionInfo::Boltz { fee_amount, .. } => *fee_amount,
484        }
485    }
486
487    /// Whether this is an AMM (Flashnet pool) conversion.
488    pub fn is_amm(&self) -> bool {
489        matches!(self, ConversionInfo::Amm { .. })
490    }
491
492    /// Whether this is an Orchestra (cross-chain) conversion.
493    pub fn is_orchestra(&self) -> bool {
494        matches!(self, ConversionInfo::Orchestra { .. })
495    }
496
497    /// Whether this is a Boltz reverse swap.
498    pub fn is_boltz(&self) -> bool {
499        matches!(self, ConversionInfo::Boltz { .. })
500    }
501}
502
503#[cfg(test)]
504mod tests {
505    use super::*;
506
507    #[test]
508    fn every_degradation_keeps_its_meaning_across_the_boundary() {
509        // A hand-written mapping: swapping two arms would silently relabel a
510        // short delivery as a malformed response, which reads as a server bug
511        // rather than a shortfall.
512        for (from, want) in [
513            (
514                flashnet::SwapDegradation::BelowMinimum,
515                SwapDegradation::BelowMinimum,
516            ),
517            (
518                flashnet::SwapDegradation::UnexpectedAsset,
519                SwapDegradation::UnexpectedAsset,
520            ),
521            (
522                flashnet::SwapDegradation::MissingInfo,
523                SwapDegradation::MissingInfo,
524            ),
525        ] {
526            assert_eq!(SwapDegradation::from(from), want, "{from:?} was relabelled");
527        }
528    }
529
530    #[test]
531    fn boltz_conversion_info_roundtrip() {
532        let original = ConversionInfo::Boltz {
533            swap_id: "boltz_swap_abc".to_string(),
534            chain: "solana".to_string(),
535            chain_id: None,
536            asset: "USDT0".to_string(),
537            recipient_address: "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v".to_string(),
538            invoice: "lnbc1000n1pexample".to_string(),
539            invoice_amount_sats: 150_000,
540            asset_amount_in: Some(100_500_000),
541            estimated_out: 99_000_000,
542            delivered_amount: Some(98_750_000),
543            bridge_ref: Some("0xdeadbeef".to_string()),
544            status: ConversionStatus::Pending,
545            fee_amount: Some(1_500_000),
546            service_fee_amount: Some(2_500),
547            service_fee_asset: None,
548            max_slippage_bps: 100,
549            quote_degraded: false,
550            asset_decimals: 6,
551            asset_contract: Some("0xdAC17F958D2ee523a2206206994597C13D831ec7".to_string()),
552        };
553
554        let json = serde_json::to_string(&original).unwrap();
555        let decoded: ConversionInfo = serde_json::from_str(&json).unwrap();
556        assert_eq!(decoded, original);
557        assert!(decoded.is_boltz());
558        assert!(!decoded.is_orchestra());
559        assert!(!decoded.is_amm());
560        assert_eq!(decoded.status(), &ConversionStatus::Pending);
561        assert_eq!(decoded.fee(), Some(1_500_000));
562
563        // The `"type"` tag discriminator must match the rename attribute.
564        assert!(json.contains(r#""type":"boltz""#));
565        // u128 fields serialize as strings, not JSON numbers.
566        assert!(json.contains(r#""estimated_out":"99000000""#));
567    }
568
569    /// Pre-rename rows persisted in the wild only carried a `fee` key (the
570    /// provider service fee), and lacked `asset_amount_in`, `fee_amount`,
571    /// `service_fee_amount`, `service_fee_asset`. Reading such a row must:
572    /// - route the legacy `fee` value into `service_fee_amount`,
573    /// - default every new field to `None`,
574    /// - succeed for both provider variants.
575    #[test]
576    fn boltz_legacy_fee_alias_deserializes_into_service_fee_amount() {
577        let legacy = r#"{
578            "type": "boltz",
579            "swap_id": "swap_legacy",
580            "invoice": "lnbc1000n1pold",
581            "invoice_amount_sats": 100000,
582            "max_slippage_bps": 100,
583            "chain": "arbitrum",
584            "asset": "USDT",
585            "recipient_address": "0xrecipient",
586            "estimated_out": "1450000",
587            "status": "Pending",
588            "fee": "1500",
589            "asset_decimals": 6
590        }"#;
591        let decoded: ConversionInfo = serde_json::from_str(legacy).unwrap();
592        let ConversionInfo::Boltz {
593            asset_amount_in,
594            fee_amount,
595            service_fee_amount,
596            service_fee_asset,
597            ..
598        } = &decoded
599        else {
600            panic!("expected Boltz variant, got: {decoded:?}");
601        };
602        assert_eq!(*asset_amount_in, None);
603        assert_eq!(*fee_amount, None);
604        assert_eq!(
605            *service_fee_amount,
606            Some(1500),
607            "legacy `fee` key must map to `service_fee_amount`"
608        );
609        assert_eq!(*service_fee_asset, None);
610    }
611
612    #[test]
613    fn orchestra_legacy_fee_alias_deserializes_into_service_fee_amount() {
614        let legacy = r#"{
615            "type": "orchestra",
616            "order_id": "ord_legacy",
617            "quote_id": "q_legacy",
618            "chain": "base",
619            "asset": "USDC",
620            "recipient_address": "0xrecipient",
621            "estimated_out": "99500000",
622            "status": "Completed",
623            "fee": "500",
624            "asset_decimals": 6
625        }"#;
626        let decoded: ConversionInfo = serde_json::from_str(legacy).unwrap();
627        let ConversionInfo::Orchestra {
628            asset_amount_in,
629            fee_amount,
630            service_fee_amount,
631            service_fee_asset,
632            service_fee_asset_decimals,
633            ..
634        } = &decoded
635        else {
636            panic!("expected Orchestra variant, got: {decoded:?}");
637        };
638        assert_eq!(*asset_amount_in, None);
639        assert_eq!(*fee_amount, None);
640        assert_eq!(
641            *service_fee_amount,
642            Some(500),
643            "legacy `fee` key must map to `service_fee_amount`"
644        );
645        assert_eq!(*service_fee_asset, None);
646        assert_eq!(*service_fee_asset_decimals, None);
647    }
648
649    /// New writes must use the renamed `service_fee_amount` key (never the
650    /// legacy `fee`), and must emit the three new fields when populated.
651    #[test]
652    fn new_rows_use_renamed_keys_on_serialize() {
653        let info = ConversionInfo::Boltz {
654            swap_id: "s".to_string(),
655            chain: "arbitrum".to_string(),
656            chain_id: None,
657            asset: "USDT".to_string(),
658            recipient_address: "0xr".to_string(),
659            invoice: "lnbc".to_string(),
660            invoice_amount_sats: 100,
661            asset_amount_in: Some(1_500_000),
662            estimated_out: 1_450_000,
663            delivered_amount: None,
664            bridge_ref: None,
665            status: ConversionStatus::Pending,
666            fee_amount: Some(50_000),
667            service_fee_amount: Some(1_500),
668            service_fee_asset: Some("USD".to_string()),
669            max_slippage_bps: 100,
670            quote_degraded: false,
671            asset_decimals: 6,
672            asset_contract: None,
673        };
674        let json = serde_json::to_string(&info).unwrap();
675        assert!(
676            json.contains(r#""service_fee_amount":"1500""#),
677            "must serialize under the new key, got: {json}"
678        );
679        assert!(
680            !json.contains(r#""fee":"#),
681            "must not emit the legacy `fee` key, got: {json}"
682        );
683        assert!(json.contains(r#""asset_amount_in":"1500000""#));
684        assert!(json.contains(r#""fee_amount":"50000""#));
685        assert!(json.contains(r#""service_fee_asset":"USD""#));
686    }
687
688    /// Backward-compat round-trip — make sure a legacy row, once deserialized
689    /// and re-serialized, stays self-consistent (the upgrade path doesn't lose
690    /// the legacy value).
691    #[test]
692    fn legacy_row_roundtrip_after_upgrade() {
693        let legacy = r#"{
694            "type": "boltz",
695            "swap_id": "swap_legacy",
696            "invoice": "lnbc",
697            "invoice_amount_sats": 100000,
698            "max_slippage_bps": 100,
699            "chain": "arbitrum",
700            "asset": "USDT",
701            "recipient_address": "0xr",
702            "estimated_out": "1450000",
703            "status": "Pending",
704            "fee": "1500",
705            "asset_decimals": 6
706        }"#;
707        let decoded: ConversionInfo = serde_json::from_str(legacy).unwrap();
708        let re_encoded = serde_json::to_string(&decoded).unwrap();
709        let re_decoded: ConversionInfo = serde_json::from_str(&re_encoded).unwrap();
710        assert_eq!(
711            decoded, re_decoded,
712            "upgraded row must round-trip identically"
713        );
714    }
715
716    #[test]
717    fn boltz_status_mut_updates_status_in_place() {
718        let mut info = ConversionInfo::Boltz {
719            swap_id: "s1".to_string(),
720            chain: "arbitrum".to_string(),
721            chain_id: Some("42161".to_string()),
722            asset: "USDT".to_string(),
723            recipient_address: "0xdest".to_string(),
724            invoice: "lnbc".to_string(),
725            invoice_amount_sats: 100,
726            asset_amount_in: None,
727            estimated_out: 1,
728            delivered_amount: None,
729            bridge_ref: None,
730            status: ConversionStatus::Pending,
731            fee_amount: None,
732            service_fee_amount: None,
733            service_fee_asset: None,
734            max_slippage_bps: 100,
735            quote_degraded: false,
736            asset_decimals: 6,
737            asset_contract: None,
738        };
739        *info.status_mut() = ConversionStatus::Completed;
740        assert_eq!(info.status(), &ConversionStatus::Completed);
741    }
742}
743
744pub(crate) struct TokenConversionPool {
745    pub(crate) asset_in_address: String,
746    pub(crate) asset_out_address: String,
747    pub(crate) pool: Pool,
748}
749
750/// A priced conversion, together with the pool it was priced against.
751pub(crate) struct ResolvedConversion {
752    pub(crate) conversion_pool: TokenConversionPool,
753    /// The floor the swap intent will carry. For a requested output it is that
754    /// request, scaled by any rise of the input above the one it derived,
755    /// rather than the simulated output, which may be higher and would fail for
756    /// no reason. For a supplied input it is the simulated output less slippage.
757    pub(crate) min_amount_out: u128,
758    pub(crate) estimate: ConversionEstimate,
759}
760
761pub(crate) struct TokenConversionResponse {
762    /// The sent payment id for the conversion
763    pub(crate) sent_payment_id: String,
764    /// The received payment id for the conversion
765    pub(crate) received_payment_id: String,
766}
767
768/// Options for conversion when fulfilling a payment. When set, the SDK will
769/// perform a conversion before fulfilling the payment. If not set, the payment
770/// will only be fulfilled if the wallet has sufficient balance of the required asset.
771#[derive(Debug, Clone, Serialize, PartialEq)]
772#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
773pub struct ConversionOptions {
774    /// The type of conversion to perform when fulfilling the payment
775    pub conversion_type: ConversionType,
776    /// The optional maximum slippage in basis points (1/100 of a percent) allowed when
777    /// a conversion is needed to fulfill the payment. Defaults to 10 bps (0.1%) if not set.
778    /// The conversion will fail if the actual amount received is less than
779    /// `estimated_amount * (1 - max_slippage_bps / 10_000)`.
780    #[cfg_attr(feature = "uniffi", uniffi(default = None))]
781    pub max_slippage_bps: Option<u32>,
782    /// The optional timeout in seconds to wait for the conversion to complete
783    /// when fulfilling the payment. This timeout only concerns waiting for the received
784    /// payment of the conversion. If the timeout is reached before the conversion
785    /// is complete, the payment will fail. Defaults to 30 seconds if not set.
786    #[cfg_attr(feature = "uniffi", uniffi(default = None))]
787    pub completion_timeout_secs: Option<u32>,
788}
789
790#[derive(Debug, Clone, Serialize, PartialEq)]
791#[cfg_attr(feature = "uniffi", derive(uniffi::Enum))]
792pub enum ConversionType {
793    /// Converting from Bitcoin to a token
794    FromBitcoin,
795    /// Converting from a token to Bitcoin
796    ToBitcoin { from_token_identifier: String },
797}
798
799impl ConversionType {
800    /// Returns the asset addresses for the conversion type
801    ///
802    /// # Arguments
803    ///
804    /// * `token_identifier` - The token identifier when converting from Bitcoin to a token
805    ///
806    /// # Returns
807    ///
808    /// Result containing:
809    /// * (String, String): A tuple containing the asset in address and asset out address
810    /// * `SdkError`: If the token identifier is required but not provided
811    pub(crate) fn as_asset_addresses(
812        &self,
813        token_identifier: Option<&String>,
814    ) -> Result<(String, String), SdkError> {
815        Ok(match self {
816            ConversionType::FromBitcoin => (
817                BTC_ASSET_ADDRESS.to_string(),
818                token_identifier
819                    .ok_or(SdkError::InvalidInput(
820                        "Token identifier is required for from Bitcoin conversion".to_string(),
821                    ))?
822                    .clone(),
823            ),
824            ConversionType::ToBitcoin {
825                from_token_identifier,
826            } => (from_token_identifier.clone(), BTC_ASSET_ADDRESS.to_string()),
827        })
828    }
829}
830
831#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
832pub struct FetchConversionLimitsRequest {
833    /// The type of conversion, either from or to Bitcoin.
834    pub conversion_type: ConversionType,
835    /// The token identifier when converting to a token.
836    #[cfg_attr(feature = "uniffi", uniffi(default = None))]
837    pub token_identifier: Option<String>,
838}
839
840#[derive(Debug, Clone, Serialize)]
841#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
842pub struct FetchConversionLimitsResponse {
843    /// The minimum amount to be converted.
844    /// Denominated in satoshis if converting from Bitcoin, otherwise in the token base units.
845    pub min_from_amount: Option<u128>,
846    /// The minimum amount to be received from the conversion.
847    /// Denominated in satoshis if converting to Bitcoin, otherwise in the token base units.
848    pub min_to_amount: Option<u128>,
849}