cow-bridging 0.3.0

Cross-chain bridge aggregator for the CoW Protocol SDK (Across, Bungee).
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
//! Serde types mirroring the NEAR Intents (`1click.chaindefuser.com`) API wire shapes.
//!
//! **All types use `#[serde(rename_all = "camelCase")]`** — the API emits
//! camelCase (`amountIn`, `priceUpdatedAt`, `depositAddress`). This is
//! load-bearing; we got burned on Across/Bungee earlier by defaulting
//! to `snake_case`, so every struct in this module is explicit.
//!
//! Enum variants that map to `SCREAMING_SNAKE_CASE` API values (e.g.
//! `"EXACT_INPUT"`, `"ORIGIN_CHAIN"`) carry `#[serde(rename_all =
//! "SCREAMING_SNAKE_CASE")]` on the enum itself.
//!
//! Mirrors:
//! - `@defuse-protocol/one-click-sdk-typescript`: `TokenResponse`, `QuoteRequest`, `QuoteResponse`,
//!   `GetExecutionStatusResponse`
//! - `packages/bridging/src/providers/near-intents/*`: request / response envelopes for
//!   `/v0/attestation`

use serde::{Deserialize, Serialize};

// ── /v0/tokens ────────────────────────────────────────────────────────────

/// A single entry in the `GET /v0/tokens` response array.
///
/// Mirrors the Defuse `TokenResponse` interface:
///
/// ```text
/// interface TokenResponse {
///   assetId: string
///   decimals: number
///   blockchain: 'ETH' | 'BASE' | 'BTC' | 'SOL' | 'TON'
///   symbol: string
///   price: number
///   priceUpdatedAt: string  // ISO 8601 timestamp
///   contractAddress?: string  // Optional, undefined for native tokens
/// }
/// ```
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct DefuseToken {
    /// Unique identifier in the format `nep141:{address_or_chain_key}`.
    pub asset_id: String,
    /// ERC-20-style decimals (`6` for USDC, `18` for ETH, …).
    pub decimals: u8,
    /// Chain the asset lives on — raw Defuse blockchain key. See
    /// [`crate::near_intents::util::blockchain_key_to_chain_id`] for
    /// the `"eth"` / `"arb"` / `"btc"` / … → EIP-155 chain-id mapping.
    ///
    /// Stored as [`String`] (rather than a typed enum) so the
    /// deserializer doesn't fail when the Defuse API adds a new chain
    /// key — callers who want strict validation can match on the
    /// string themselves.
    pub blockchain: String,
    /// Short symbol (e.g. `"USDC"`, `"ETH"`).
    pub symbol: String,
    /// Last-known USD price.
    pub price: f64,
    /// ISO 8601 timestamp of the last price update.
    pub price_updated_at: String,
    /// Optional on-chain contract address. Absent for native tokens
    /// (ETH, BTC, SOL, native TON).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub contract_address: Option<String>,
}

// ── /v0/quote ─────────────────────────────────────────────────────────────

/// Swap-type discriminator on the quote request.
///
/// `EXACT_INPUT` = the caller specifies `amount` as the input; the API
/// computes the output. `FLEX_INPUT` = the API can tune the input to
/// hit a target output.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum NearSwapType {
    /// Caller commits to the input amount exactly.
    ExactInput,
    /// Caller leaves input flexible.
    FlexInput,
}

/// How the user will deposit the input funds.
///
/// The TS SDK only exposes `SIMPLE` today; we keep the enum extensible
/// for future variants.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum NearDepositMode {
    /// Simple deposit — the user transfers the asset to `depositAddress`.
    #[default]
    Simple,
}

/// Which chain is debited on deposit.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum NearDepositType {
    /// Deposit is made on the origin chain.
    #[default]
    OriginChain,
}

/// Where refunds go when the swap cannot complete.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum NearRefundType {
    /// Refund goes back to the origin chain.
    #[default]
    OriginChain,
}

/// Where the bought tokens land.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum NearRecipientType {
    /// Recipient is addressed on the destination chain.
    #[default]
    DestinationChain,
}

/// Partner / referrer fee entry attached to a quote request.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct NearAppFee {
    /// Address collecting the fee.
    pub recipient: String,
    /// Fee amount in basis points.
    pub fee: u32,
}

/// Body of `POST /v0/quote`.
///
/// Mirrors the Defuse `QuoteRequest` interface. Field names match the
/// wire format 1:1 (camelCase).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct NearQuoteRequest {
    /// If `true` the API treats the request as a dry-run; no deposit
    /// address is allocated.
    pub dry: bool,
    /// Swap-type selector.
    pub swap_type: NearSwapType,
    /// Deposit mode (TS ships `SIMPLE` only).
    pub deposit_mode: NearDepositMode,
    /// Slippage tolerance in basis points (50 = 0.5 %).
    pub slippage_tolerance: u32,
    /// Origin asset identifier (`nep141:…`).
    pub origin_asset: String,
    /// How the deposit reaches the bridge.
    pub deposit_type: NearDepositType,
    /// Destination asset identifier (`nep141:…`).
    pub destination_asset: String,
    /// Atomic input amount as a numeric string.
    pub amount: String,
    /// Refund destination address.
    pub refund_to: String,
    /// Refund-destination chain discriminator.
    pub refund_type: NearRefundType,
    /// Recipient address on the destination chain.
    pub recipient: String,
    /// Recipient-chain discriminator.
    pub recipient_type: NearRecipientType,
    /// Quote deadline (ISO 8601).
    pub deadline: String,
    /// Optional partner / referrer fees.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub app_fees: Option<Vec<NearAppFee>>,
    /// Optional quote waiting time in milliseconds.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub quote_waiting_time_ms: Option<u64>,
    /// Optional referral handle.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub referral: Option<String>,
    /// Optional virtual-chain recipient.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub virtual_chain_recipient: Option<String>,
    /// Optional virtual-chain refund recipient.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub virtual_chain_refund_recipient: Option<String>,
    /// Optional custom recipient-side message.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub custom_recipient_msg: Option<String>,
    /// Optional session ID for analytics.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub session_id: Option<String>,
    /// Optional wallets connected at quote time.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub connected_wallets: Option<Vec<String>>,
}

/// Inner `quote` object carried by `NearQuoteResponse` and
/// `NearExecutionStatusResponse.quoteResponse`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct NearQuote {
    /// Input amount echoed back (atomic string).
    pub amount_in: String,
    /// Human-formatted input amount (e.g. `"1.0"`).
    pub amount_in_formatted: String,
    /// USD value of `amount_in`.
    pub amount_in_usd: String,
    /// Minimum acceptable input amount.
    pub min_amount_in: String,
    /// Expected output amount (atomic string).
    pub amount_out: String,
    /// Human-formatted output amount.
    pub amount_out_formatted: String,
    /// USD value of `amount_out`.
    pub amount_out_usd: String,
    /// Minimum output respecting slippage.
    pub min_amount_out: String,
    /// Estimated completion time in seconds.
    pub time_estimate: u64,
    /// Quote deadline (ISO 8601).
    pub deadline: String,
    /// Timestamp after which the quote is inactive (ISO 8601).
    pub time_when_inactive: String,
    /// Address where the user must deposit the origin asset.
    pub deposit_address: String,
}

/// Body of `POST /v0/quote` response.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct NearQuoteResponse {
    /// Quote details.
    pub quote: NearQuote,
    /// Echo of the originating request.
    pub quote_request: NearQuoteRequest,
    /// Attestation signature from the NEAR Intents relayer
    /// (`ed25519:…` prefix).
    pub signature: String,
    /// Server-side issue timestamp (ISO 8601).
    pub timestamp: String,
}

// ── /v0/execution-status ──────────────────────────────────────────────────

/// Execution status enum mirroring the string values the API emits.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum NearExecutionStatus {
    /// Known deposit tx observed on the origin chain.
    KnownDepositTx,
    /// Deposit is pending — relayer hasn't picked it up yet.
    PendingDeposit,
    /// Partial deposit (amount mismatch, etc.).
    IncompleteDeposit,
    /// Relayer is processing the swap.
    Processing,
    /// Swap completed successfully.
    Success,
    /// Swap was refunded.
    Refunded,
    /// Swap failed.
    Failed,
}

/// On-chain transaction hash + explorer URL pair.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct NearChainTxHash {
    /// Transaction hash.
    pub hash: String,
    /// Explorer URL for the transaction.
    pub explorer_url: String,
}

/// Nested `swapDetails` object on an execution status response.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct NearSwapDetails {
    /// Defuse intent hashes.
    pub intent_hashes: Vec<String>,
    /// NEAR tx hashes (Defuse execution layer).
    pub near_tx_hashes: Vec<String>,
    /// Atomic input amount.
    pub amount_in: String,
    /// Human-formatted input amount.
    pub amount_in_formatted: String,
    /// USD value of input.
    pub amount_in_usd: String,
    /// Atomic output amount.
    pub amount_out: String,
    /// Human-formatted output amount.
    pub amount_out_formatted: String,
    /// USD value of output.
    pub amount_out_usd: String,
    /// Observed slippage (signed percentage).
    pub slippage: f64,
    /// Atomic refunded amount (0 if no refund).
    pub refunded_amount: String,
    /// Human-formatted refunded amount.
    pub refunded_amount_formatted: String,
    /// USD value of the refund.
    pub refunded_amount_usd: String,
    /// Origin-chain txs.
    pub origin_chain_tx_hashes: Vec<NearChainTxHash>,
    /// Destination-chain txs.
    pub destination_chain_tx_hashes: Vec<NearChainTxHash>,
}

/// Body of `GET /v0/execution-status/{deposit_address}` response.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct NearExecutionStatusResponse {
    /// Current status enum.
    pub status: NearExecutionStatus,
    /// Last-update timestamp (ISO 8601).
    pub updated_at: String,
    /// Swap details.
    pub swap_details: NearSwapDetails,
    /// Optional cached quote response (present once the relayer
    /// acknowledges the deposit).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub quote_response: Option<NearQuoteResponse>,
}

// ── /v0/attestation ───────────────────────────────────────────────────────

/// Body of `POST /v0/attestation` request.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct NearAttestationRequest {
    /// Deposit address from the matching `NearQuote`.
    pub deposit_address: String,
    /// Hex-encoded hash of the canonical quote payload.
    pub quote_hash: String,
}

/// Body of `POST /v0/attestation` response.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct NearAttestationResponse {
    /// `0x`-prefixed 65-byte secp256k1 signature from the attestor.
    pub signature: String,
    /// Signature-format version tag (currently `1`).
    pub version: u32,
}

#[cfg(all(test, not(target_arch = "wasm32")))]
#[allow(clippy::tests_outside_test_module, reason = "inner module + cfg guard for WASM test skip")]
mod tests {
    use super::*;

    #[test]
    fn defuse_token_optional_contract_address_deserializes() {
        let sample = r#"{
            "assetId": "nep141:eth",
            "decimals": 18,
            "blockchain": "eth",
            "symbol": "ETH",
            "price": 4463.25,
            "priceUpdatedAt": "2025-09-05T12:00:38.695Z"
        }"#;
        let t: DefuseToken = serde_json::from_str(sample).unwrap();
        assert_eq!(t.decimals, 18);
        assert_eq!(t.blockchain, "eth");
        assert!(t.contract_address.is_none());
    }

    #[test]
    fn defuse_token_accepts_unknown_blockchain_key() {
        // The enum-free `blockchain: String` means a future Defuse key
        // deserializes without breaking. Rust-side lookup happens in
        // `util::blockchain_key_to_chain_id`.
        let sample = r#"{
            "assetId": "nep141:future",
            "decimals": 18,
            "blockchain": "some-new-chain",
            "symbol": "FTR",
            "price": 1.0,
            "priceUpdatedAt": "2025-09-05T12:00:38.695Z"
        }"#;
        let t: DefuseToken = serde_json::from_str(sample).unwrap();
        assert_eq!(t.blockchain, "some-new-chain");
    }

    #[test]
    fn near_swap_type_serializes_as_screaming_snake_case() {
        let t = NearSwapType::ExactInput;
        assert_eq!(serde_json::to_string(&t).unwrap(), "\"EXACT_INPUT\"");
    }

    #[test]
    fn near_execution_status_roundtrips_all_variants() {
        for (v, expected) in [
            (NearExecutionStatus::KnownDepositTx, "\"KNOWN_DEPOSIT_TX\""),
            (NearExecutionStatus::PendingDeposit, "\"PENDING_DEPOSIT\""),
            (NearExecutionStatus::IncompleteDeposit, "\"INCOMPLETE_DEPOSIT\""),
            (NearExecutionStatus::Processing, "\"PROCESSING\""),
            (NearExecutionStatus::Success, "\"SUCCESS\""),
            (NearExecutionStatus::Refunded, "\"REFUNDED\""),
            (NearExecutionStatus::Failed, "\"FAILED\""),
        ] {
            let j = serde_json::to_string(&v).unwrap();
            assert_eq!(j, expected);
            let back: NearExecutionStatus = serde_json::from_str(&j).unwrap();
            assert_eq!(back, v);
        }
    }

    #[test]
    fn attestation_request_response_roundtrip() {
        let req = NearAttestationRequest {
            deposit_address: "0xdead000000000000000000000000000000000000".into(),
            quote_hash: "0xabc".into(),
        };
        let j = serde_json::to_string(&req).unwrap();
        assert!(j.contains("depositAddress"));
        assert!(j.contains("quoteHash"));
        let back: NearAttestationRequest = serde_json::from_str(&j).unwrap();
        assert_eq!(back, req);

        let resp = NearAttestationResponse { signature: "0x1234".into(), version: 1 };
        let j = serde_json::to_string(&resp).unwrap();
        let back: NearAttestationResponse = serde_json::from_str(&j).unwrap();
        assert_eq!(back, resp);
    }

    #[test]
    fn near_quote_request_serializes_camel_case() {
        let req = NearQuoteRequest {
            dry: false,
            swap_type: NearSwapType::ExactInput,
            deposit_mode: NearDepositMode::Simple,
            slippage_tolerance: 50,
            origin_asset: "nep141:eth".into(),
            deposit_type: NearDepositType::OriginChain,
            destination_asset: "nep141:btc".into(),
            amount: "1000000".into(),
            refund_to: "0xabc".into(),
            refund_type: NearRefundType::OriginChain,
            recipient: "bc1q…".into(),
            recipient_type: NearRecipientType::DestinationChain,
            deadline: "2099-01-01T00:00:00.000Z".into(),
            app_fees: None,
            quote_waiting_time_ms: None,
            referral: None,
            virtual_chain_recipient: None,
            virtual_chain_refund_recipient: None,
            custom_recipient_msg: None,
            session_id: None,
            connected_wallets: None,
        };
        let j = serde_json::to_string(&req).unwrap();
        assert!(j.contains("\"swapType\":\"EXACT_INPUT\""));
        assert!(j.contains("\"slippageTolerance\":50"));
        assert!(j.contains("\"originAsset\":\"nep141:eth\""));
        // Optional fields absent from JSON when None.
        assert!(!j.contains("appFees"));
        assert!(!j.contains("sessionId"));
    }

    #[test]
    fn defuse_token_with_contract_address_roundtrips() {
        let sample = r#"{
            "assetId": "nep141:usdc.e",
            "decimals": 6,
            "blockchain": "eth",
            "symbol": "USDC",
            "price": 1.0,
            "priceUpdatedAt": "2025-09-05T12:00:38.695Z",
            "contractAddress": "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48"
        }"#;
        let t: DefuseToken = serde_json::from_str(sample).unwrap();
        assert_eq!(
            t.contract_address.as_deref(),
            Some("0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48")
        );
        // Roundtrip preserves it.
        let j = serde_json::to_string(&t).unwrap();
        assert!(j.contains("contractAddress"));
    }
}