1use std::{
9 borrow::Borrow,
10 collections::HashMap,
11 error::Error,
12 fmt,
13 sync::Arc,
14 time::{Duration, SystemTime, UNIX_EPOCH},
15};
16
17use reqwest::{Client, Response, header::HeaderValue, redirect::Policy};
18use serde::{Deserialize, Serialize};
19use serde_json::{Map, Value};
20use tokio_util::sync::CancellationToken;
21use url::Url;
22
23use crate::{
24 config::RpcEndpointConfig,
25 generated::bridge_capabilities::{
26 BRIDGE_CAPABILITIES_AS_OF_DATE, BRIDGE_CAPABILITIES_CONTENT_DIGEST,
27 BRIDGE_CAPABILITIES_JSON,
28 },
29 token_catalog::{TokenStandard, TokenStatus, get_token_deployment},
30};
31
32const DEFAULT_BUILDER_ENDPOINT: &str = "https://tx-builder.mayan.finance";
33const DEFAULT_EXPLORER_ENDPOINT: &str = "https://explorer-api.mayan.finance/v3";
34const DEFAULT_TIMEOUT: Duration = Duration::from_secs(30);
35const DEFAULT_MINIMUM_QUOTE_VALIDITY_SECONDS: u64 = 60;
36const MAX_RESPONSE_BYTES: usize = 1024 * 1024;
37const MAX_RAW_QUOTE_BYTES: usize = 256 * 1024;
38const MAX_JSON_DEPTH: usize = 32;
39const MAX_QUOTES: usize = 16;
40const UINT64_DECIMAL_MAX_LENGTH: usize = 20;
41const UINT64_MAX: u128 = u64::MAX as u128;
42
43const ETHEREUM_CHAIN_ID: &str = "eip155:1";
44const SOLANA_CHAIN_ID: &str = "solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp";
45const ETHEREUM_NAME: &str = "ethereum";
46const SOLANA_NAME: &str = "solana";
47const ETHEREUM_EURC_DEPLOYMENT_ID: &str = "deployment-0011";
48const SOLANA_EURC_DEPLOYMENT_ID: &str = "deployment-0013";
49const ETHEREUM_USDC_DEPLOYMENT_ID: &str = "deployment-0008";
50const SOLANA_USDC_DEPLOYMENT_ID: &str = "deployment-0010";
51const ETHEREUM_EURC_ADDRESS: &str = "0x1abaea1f7c830bd89acc67ec4af516284b1bc33c";
52const SOLANA_EURC_ADDRESS: &str = "HzwqbKZw8HxMN6bF2yFZNrht3c2iXXzpKcFu7uBEDKtr";
53const ETHEREUM_USDC_ADDRESS: &str = "0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48";
54const SOLANA_USDC_ADDRESS: &str = "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v";
55const ETHEREUM_SWIFT_CONTRACT: &str = "0x40ffe85a28dc9993541449464d7529a922142960";
56const SOLANA_SWIFT_PROGRAM: &str = "mayan34VedncxdK2XobtvWFDXQASUTBXhUVzt2kKgny";
57const ETHEREUM_FORWARDER: &str = "0x337685fdab40d39bd02028545a4ffa7d287cc3e2";
58const SOLANA_JUPITER_V6: &str = "JUP6LkbZbjS1jKKwapdHNy74zcZ3tLUZoi5QNyVTaV4";
59const ETHEREUM_EURC_FORWARDER_SELECTOR: &str = "0x30dedc57";
60const ETHEREUM_USDC_FORWARDER_SELECTOR: &str = "0xe4269fc4";
61const MAYAN_USDC_MINT: &str = "A9mUU4qviSctJVPJdBJWkb28deg915LYJKrzQ19ji3FM";
62
63const DEPENDENCIES: &[&str] = &[
64 "mayan-hosted-quote-api",
65 "mayan-hosted-transaction-builder",
66 "mayan-hosted-source-swap-builder",
67 "swift-auction-solvers",
68 "relayers",
69 "wormhole-guardian-messaging",
70 "mayan-explorer-indexer",
71];
72const DIRECT_USDC_DEPENDENCIES: &[&str] = &[
73 "mayan-hosted-quote-api",
74 "mayan-hosted-transaction-builder",
75 "swift-auction-solvers",
76 "relayers",
77 "wormhole-guardian-messaging",
78 "mayan-explorer-indexer",
79];
80
81const BASE58_ALPHABET: &[u8] = b"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
82
83#[derive(Clone, Copy, Debug, Eq, PartialEq)]
85pub enum BridgeErrorCode {
86 InvalidArgument,
88 UnsupportedRoute,
90 ProviderAuthRequired,
92 ProviderTransport,
94 ProviderHttp,
96 ProviderInvalidResponse,
98 QuoteUnavailable,
100 QuoteExpired,
102 QuoteMismatch,
104 BuildInvalid,
106 StatusNotFound,
108 Timeout,
110 Aborted,
112 LocalRpcRequired,
114 SourceRpcTransport,
116 SourceRpcInvalidResponse,
118 LocalPlanInvalid,
120 LocalBuildInvalid,
122}
123
124impl BridgeErrorCode {
125 pub const BRIDGE_INVALID_ARGUMENT: Self = Self::InvalidArgument;
127 pub const BRIDGE_UNSUPPORTED_ROUTE: Self = Self::UnsupportedRoute;
129 pub const BRIDGE_PROVIDER_AUTH_REQUIRED: Self = Self::ProviderAuthRequired;
131 pub const BRIDGE_PROVIDER_TRANSPORT: Self = Self::ProviderTransport;
133 pub const BRIDGE_PROVIDER_HTTP: Self = Self::ProviderHttp;
135 pub const BRIDGE_PROVIDER_INVALID_RESPONSE: Self = Self::ProviderInvalidResponse;
137 pub const BRIDGE_QUOTE_UNAVAILABLE: Self = Self::QuoteUnavailable;
139 pub const BRIDGE_QUOTE_EXPIRED: Self = Self::QuoteExpired;
141 pub const BRIDGE_QUOTE_MISMATCH: Self = Self::QuoteMismatch;
143 pub const BRIDGE_BUILD_INVALID: Self = Self::BuildInvalid;
145 pub const BRIDGE_STATUS_NOT_FOUND: Self = Self::StatusNotFound;
147 pub const BRIDGE_TIMEOUT: Self = Self::Timeout;
149 pub const BRIDGE_ABORTED: Self = Self::Aborted;
151 pub const BRIDGE_LOCAL_RPC_REQUIRED: Self = Self::LocalRpcRequired;
153 pub const BRIDGE_SOURCE_RPC_TRANSPORT: Self = Self::SourceRpcTransport;
155 pub const BRIDGE_SOURCE_RPC_INVALID_RESPONSE: Self = Self::SourceRpcInvalidResponse;
157 pub const BRIDGE_LOCAL_PLAN_INVALID: Self = Self::LocalPlanInvalid;
159 pub const BRIDGE_LOCAL_BUILD_INVALID: Self = Self::LocalBuildInvalid;
161
162 #[must_use]
164 pub const fn as_str(self) -> &'static str {
165 match self {
166 Self::InvalidArgument => "BRIDGE_INVALID_ARGUMENT",
167 Self::UnsupportedRoute => "BRIDGE_UNSUPPORTED_ROUTE",
168 Self::ProviderAuthRequired => "BRIDGE_PROVIDER_AUTH_REQUIRED",
169 Self::ProviderTransport => "BRIDGE_PROVIDER_TRANSPORT",
170 Self::ProviderHttp => "BRIDGE_PROVIDER_HTTP",
171 Self::ProviderInvalidResponse => "BRIDGE_PROVIDER_INVALID_RESPONSE",
172 Self::QuoteUnavailable => "BRIDGE_QUOTE_UNAVAILABLE",
173 Self::QuoteExpired => "BRIDGE_QUOTE_EXPIRED",
174 Self::QuoteMismatch => "BRIDGE_QUOTE_MISMATCH",
175 Self::BuildInvalid => "BRIDGE_BUILD_INVALID",
176 Self::StatusNotFound => "BRIDGE_STATUS_NOT_FOUND",
177 Self::Timeout => "BRIDGE_TIMEOUT",
178 Self::Aborted => "BRIDGE_ABORTED",
179 Self::LocalRpcRequired => "BRIDGE_LOCAL_RPC_REQUIRED",
180 Self::SourceRpcTransport => "BRIDGE_SOURCE_RPC_TRANSPORT",
181 Self::SourceRpcInvalidResponse => "BRIDGE_SOURCE_RPC_INVALID_RESPONSE",
182 Self::LocalPlanInvalid => "BRIDGE_LOCAL_PLAN_INVALID",
183 Self::LocalBuildInvalid => "BRIDGE_LOCAL_BUILD_INVALID",
184 }
185 }
186
187 const fn message(self) -> &'static str {
188 match self {
189 Self::InvalidArgument => "Bridge request is invalid",
190 Self::UnsupportedRoute => "Bridge route is unsupported",
191 Self::ProviderAuthRequired => "Bridge provider authentication is required",
192 Self::ProviderTransport => "Bridge provider transport failed",
193 Self::ProviderHttp => "Bridge provider HTTP request failed",
194 Self::ProviderInvalidResponse => "Bridge provider response is invalid",
195 Self::QuoteUnavailable => "Bridge quote is unavailable",
196 Self::QuoteExpired => "Bridge quote is expired",
197 Self::QuoteMismatch => "Bridge quote does not match the request",
198 Self::BuildInvalid => "Bridge provider build is invalid",
199 Self::StatusNotFound => "Bridge status was not found",
200 Self::Timeout => "Bridge provider request timed out",
201 Self::Aborted => "Bridge provider request was aborted",
202 Self::LocalRpcRequired => "Bridge local source RPC is required",
203 Self::SourceRpcTransport => "Bridge source RPC transport failed",
204 Self::SourceRpcInvalidResponse => "Bridge source RPC response is invalid",
205 Self::LocalPlanInvalid => "Bridge local source-swap plan is invalid",
206 Self::LocalBuildInvalid => "Bridge local unsigned build is invalid",
207 }
208 }
209}
210
211impl fmt::Display for BridgeErrorCode {
212 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
213 formatter.write_str(self.as_str())
214 }
215}
216
217#[derive(Clone, Debug, Eq, PartialEq)]
219pub struct BridgeError {
220 code: BridgeErrorCode,
221 status: Option<u16>,
222}
223
224impl BridgeError {
225 #[must_use]
227 pub const fn code(&self) -> BridgeErrorCode {
228 self.code
229 }
230
231 #[must_use]
233 pub const fn code_string(&self) -> &'static str {
234 self.code.as_str()
235 }
236
237 #[must_use]
239 pub const fn status(&self) -> Option<u16> {
240 self.status
241 }
242}
243
244impl fmt::Display for BridgeError {
245 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
246 formatter.write_str(self.code.message())
247 }
248}
249
250impl Error for BridgeError {}
251
252pub type BridgeResult<T> = std::result::Result<T, BridgeError>;
254
255pub(crate) fn bridge_error(code: BridgeErrorCode) -> BridgeError {
256 BridgeError { code, status: None }
257}
258
259pub(crate) fn bridge_error_status(code: BridgeErrorCode, status: u16) -> BridgeError {
260 BridgeError {
261 code,
262 status: Some(status),
263 }
264}
265
266#[derive(Clone)]
268pub struct MayanSwiftV2LocalBuildConfig {
269 pub source_swap_endpoint: String,
271 pub ethereum_rpc: Option<RpcEndpointConfig>,
273 pub solana_rpc: Option<RpcEndpointConfig>,
275}
276
277impl Default for MayanSwiftV2LocalBuildConfig {
278 fn default() -> Self {
279 Self::new()
280 }
281}
282
283impl MayanSwiftV2LocalBuildConfig {
284 #[must_use]
286 pub fn new() -> Self {
287 Self {
288 source_swap_endpoint: "https://price-api.mayan.finance/v3".to_owned(),
289 ethereum_rpc: None,
290 solana_rpc: None,
291 }
292 }
293
294 #[must_use]
296 pub fn with_source_swap_endpoint(mut self, endpoint: impl Into<String>) -> Self {
297 self.source_swap_endpoint = endpoint.into();
298 self
299 }
300
301 #[must_use]
303 pub fn with_ethereum_rpc(mut self, endpoint: impl Into<RpcEndpointConfig>) -> Self {
304 self.ethereum_rpc = Some(endpoint.into());
305 self
306 }
307
308 #[must_use]
310 pub fn with_solana_rpc(mut self, endpoint: impl Into<RpcEndpointConfig>) -> Self {
311 self.solana_rpc = Some(endpoint.into());
312 self
313 }
314}
315
316impl fmt::Debug for MayanSwiftV2LocalBuildConfig {
317 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
318 formatter
319 .debug_struct("MayanSwiftV2LocalBuildConfig")
320 .field("source_swap_endpoint", &self.source_swap_endpoint)
321 .field("ethereum_rpc", &self.ethereum_rpc)
322 .field("solana_rpc", &self.solana_rpc)
323 .finish()
324 }
325}
326
327#[derive(Clone)]
329pub struct MayanSwiftV2BridgeConfig {
330 builder_endpoint: String,
331 explorer_endpoint: String,
332 builder_api_key: Option<String>,
333 allow_unauthenticated_build: bool,
334 minimum_quote_validity_seconds: u64,
335 timeout: Duration,
336 local_build: Option<MayanSwiftV2LocalBuildConfig>,
337}
338
339impl Default for MayanSwiftV2BridgeConfig {
340 fn default() -> Self {
341 Self::new()
342 }
343}
344
345impl MayanSwiftV2BridgeConfig {
346 #[must_use]
348 pub fn new() -> Self {
349 Self {
350 builder_endpoint: DEFAULT_BUILDER_ENDPOINT.to_owned(),
351 explorer_endpoint: DEFAULT_EXPLORER_ENDPOINT.to_owned(),
352 builder_api_key: None,
353 allow_unauthenticated_build: false,
354 minimum_quote_validity_seconds: DEFAULT_MINIMUM_QUOTE_VALIDITY_SECONDS,
355 timeout: DEFAULT_TIMEOUT,
356 local_build: None,
357 }
358 }
359
360 #[must_use]
362 pub fn with_builder_endpoint(mut self, endpoint: impl Into<String>) -> Self {
363 self.builder_endpoint = endpoint.into();
364 self
365 }
366
367 #[must_use]
369 pub fn with_explorer_endpoint(mut self, endpoint: impl Into<String>) -> Self {
370 self.explorer_endpoint = endpoint.into();
371 self
372 }
373
374 #[must_use]
376 pub fn with_builder_api_key(mut self, key: impl Into<String>) -> Self {
377 self.builder_api_key = Some(key.into());
378 self
379 }
380
381 #[must_use]
383 pub const fn with_allow_unauthenticated_build(mut self, allowed: bool) -> Self {
384 self.allow_unauthenticated_build = allowed;
385 self
386 }
387
388 #[must_use]
390 pub const fn with_minimum_quote_validity_seconds(mut self, seconds: u64) -> Self {
391 self.minimum_quote_validity_seconds = seconds;
392 self
393 }
394
395 #[must_use]
397 pub const fn with_timeout(mut self, timeout: Duration) -> Self {
398 self.timeout = timeout;
399 self
400 }
401
402 #[must_use]
404 pub fn with_local_build(mut self, local_build: MayanSwiftV2LocalBuildConfig) -> Self {
405 self.local_build = Some(local_build);
406 self
407 }
408}
409
410impl fmt::Debug for MayanSwiftV2BridgeConfig {
411 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
412 formatter
413 .debug_struct("MayanSwiftV2BridgeConfig")
414 .field("builder_endpoint", &self.builder_endpoint)
415 .field("explorer_endpoint", &self.explorer_endpoint)
416 .field(
417 "builder_api_key",
418 &self.builder_api_key.as_ref().map(|_| "[REDACTED]"),
419 )
420 .field(
421 "allow_unauthenticated_build",
422 &self.allow_unauthenticated_build,
423 )
424 .field(
425 "minimum_quote_validity_seconds",
426 &self.minimum_quote_validity_seconds,
427 )
428 .field("timeout", &self.timeout)
429 .field("local_build", &self.local_build)
430 .finish()
431 }
432}
433
434#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
436#[serde(deny_unknown_fields, rename_all = "camelCase")]
437pub struct MayanSwiftV2QuoteRequest {
438 pub source_chain_id: String,
440 pub destination_chain_id: String,
442 pub source_token_deployment_id: String,
444 pub destination_token_deployment_id: String,
446 pub amount_in: String,
448 pub slippage_bps: u64,
450}
451
452#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
454#[serde(deny_unknown_fields, rename_all = "camelCase")]
455pub struct MayanSwiftV2SourceSwap {
456 pub required: bool,
458 pub input_token_deployment_id: String,
460 pub intermediate_token_deployment_id: String,
462 pub intermediate_token_address: String,
464 pub intermediate_token_standard: String,
466 pub intermediate_token_decimals: u8,
468 pub provider_minimum_amount: String,
470 pub router_kind: Option<String>,
472 pub router_address: Option<String>,
474}
475
476#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
478#[serde(deny_unknown_fields, rename_all = "camelCase")]
479pub struct MayanSwiftV2Quote {
480 pub quote_kind: String,
482 pub provider_id: String,
484 pub source_chain_id: String,
486 pub destination_chain_id: String,
488 pub source_token_deployment_id: String,
490 pub destination_token_deployment_id: String,
492 pub amount_in: String,
494 pub expected_amount_out: String,
496 pub minimum_amount_out: String,
498 pub minimum_received: String,
500 pub deadline: String,
502 pub slippage_bps: u64,
504 pub quote_id: String,
506 pub provider_signature: String,
508 pub source_swap: MayanSwiftV2SourceSwap,
510 pub dependencies: Vec<String>,
512 pub quote_verification: String,
514 pub raw_signed_quote_json: String,
516}
517
518#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
520#[serde(deny_unknown_fields, rename_all = "camelCase")]
521pub struct MayanEvmUnsignedTransaction {
522 pub kind: String,
524 pub chain_id: String,
526 pub from: String,
528 pub to: String,
530 pub data: String,
532 pub value: String,
534}
535
536#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
538#[serde(deny_unknown_fields, rename_all = "camelCase")]
539pub struct MayanSolanaUnsignedTransaction {
540 pub kind: String,
542 pub chain_id: String,
544 pub fee_payer: String,
546 pub transaction_base64: String,
548}
549
550#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
552#[serde(untagged)]
553pub enum MayanSwiftV2UnsignedTransaction {
554 Evm(MayanEvmUnsignedTransaction),
556 Solana(MayanSolanaUnsignedTransaction),
558}
559
560#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
562#[serde(deny_unknown_fields, rename_all = "camelCase")]
563pub struct MayanSwiftV2BuildValidation {
564 pub level: String,
566 pub quote_signature_locally_verified: bool,
568 pub transaction_semantics_locally_verified: bool,
570 pub settlement_locally_verified: bool,
572}
573
574#[derive(Clone, Debug, Serialize)]
576#[serde(rename_all = "camelCase")]
577pub struct MayanSwiftV2Build {
578 pub build_kind: String,
580 pub provider_id: String,
582 pub quote: MayanSwiftV2Quote,
584 pub source_chain_id: String,
586 pub destination_chain_id: String,
588 pub transaction: MayanSwiftV2UnsignedTransaction,
590 pub allowance: Option<MayanSwiftV2Allowance>,
592 pub validation: MayanSwiftV2BuildValidation,
594 pub raw_provider_build_json: String,
596}
597
598#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
600#[serde(deny_unknown_fields, rename_all = "camelCase")]
601pub struct MayanSwiftV2Allowance {
602 pub token_deployment_id: String,
604 pub token_address: String,
606 pub owner: String,
608 pub spender: String,
610 pub required_amount: String,
612}
613
614#[derive(Clone, Debug, Deserialize, Serialize)]
616#[serde(deny_unknown_fields, rename_all = "camelCase")]
617pub struct MayanSwiftV2BuildRequest {
618 pub quote: MayanSwiftV2Quote,
620 pub swapper_address: String,
622 pub destination_address: String,
624 #[serde(skip_serializing_if = "Option::is_none")]
626 pub refund_address: Option<String>,
627}
628
629pub type MayanSwiftV2BuildUnsignedRequest = MayanSwiftV2BuildRequest;
631
632#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
634#[serde(deny_unknown_fields, rename_all = "camelCase")]
635pub struct MayanSwiftV2StatusRequest {
636 pub source_chain_id: String,
638 pub source_transaction_hash: String,
640}
641
642#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
644#[serde(deny_unknown_fields, rename_all = "camelCase")]
645pub struct MayanSwiftV2Status {
646 pub status_kind: String,
648 pub provider_id: String,
650 pub source_chain_id: String,
652 pub source_transaction_hash: String,
654 pub state: String,
656 pub provider_client_status: String,
658 pub provider_status: Option<String>,
660 pub status_verification: String,
662 pub raw_provider_status_json: String,
664}
665
666pub type MayanSwiftV2QuoteResult = Vec<MayanSwiftV2Quote>;
668pub type MayanSwiftV2BuildResult = MayanSwiftV2Build;
670pub type MayanSwiftV2StatusResult = MayanSwiftV2Status;
672pub type BridgeClient = MayanSwiftV2BridgeClient;
674
675#[derive(Clone, Debug)]
676pub(crate) struct JsonNode {
677 pub(crate) value: Value,
678 pub(crate) start: usize,
679 pub(crate) end: usize,
680 pub(crate) object_entries: Option<HashMap<String, JsonNode>>,
681 pub(crate) array_items: Option<Vec<JsonNode>>,
682 pub(crate) raw_number: Option<String>,
683}
684
685pub(crate) struct ProviderResponse {
686 pub(crate) text: String,
687 pub(crate) root: JsonNode,
688}
689
690pub(crate) struct StrictJsonParser<'a> {
691 source: &'a str,
692 index: usize,
693}
694
695impl<'a> StrictJsonParser<'a> {
696 pub(crate) fn new(source: &'a str) -> Self {
697 Self { source, index: 0 }
698 }
699
700 pub(crate) fn parse(mut self) -> BridgeResult<JsonNode> {
701 self.skip_whitespace();
702 let value = self.value(0)?;
703 self.skip_whitespace();
704 if self.index != self.source.len() {
705 return Err(bridge_error(BridgeErrorCode::ProviderInvalidResponse));
706 }
707 Ok(value)
708 }
709
710 fn value(&mut self, depth: usize) -> BridgeResult<JsonNode> {
711 if depth > MAX_JSON_DEPTH {
712 return Err(bridge_error(BridgeErrorCode::ProviderInvalidResponse));
713 }
714 let start = self.index;
715 let Some(character) = self.source.as_bytes().get(self.index).copied() else {
716 return Err(bridge_error(BridgeErrorCode::ProviderInvalidResponse));
717 };
718 match character {
719 b'{' => self.object(start, depth),
720 b'[' => self.array(start, depth),
721 b'"' => {
722 let value = self.string()?;
723 Ok(JsonNode {
724 value: Value::String(value),
725 start,
726 end: self.index,
727 object_entries: None,
728 array_items: None,
729 raw_number: None,
730 })
731 }
732 b't' if self.source[self.index..].starts_with("true") => {
733 self.index += 4;
734 Ok(self.scalar(start, Value::Bool(true)))
735 }
736 b'f' if self.source[self.index..].starts_with("false") => {
737 self.index += 5;
738 Ok(self.scalar(start, Value::Bool(false)))
739 }
740 b'n' if self.source[self.index..].starts_with("null") => {
741 self.index += 4;
742 Ok(self.scalar(start, Value::Null))
743 }
744 b'-' | b'0'..=b'9' => self.number(start),
745 _ => Err(bridge_error(BridgeErrorCode::ProviderInvalidResponse)),
746 }
747 }
748
749 fn scalar(&self, start: usize, value: Value) -> JsonNode {
750 JsonNode {
751 value,
752 start,
753 end: self.index,
754 object_entries: None,
755 array_items: None,
756 raw_number: None,
757 }
758 }
759
760 fn object(&mut self, start: usize, depth: usize) -> BridgeResult<JsonNode> {
761 self.index += 1;
762 self.skip_whitespace();
763 let mut entries = HashMap::new();
764 let mut values = Map::new();
765 if self.peek() == Some(b'}') {
766 self.index += 1;
767 return Ok(JsonNode {
768 value: Value::Object(values),
769 start,
770 end: self.index,
771 object_entries: Some(entries),
772 array_items: None,
773 raw_number: None,
774 });
775 }
776 loop {
777 if self.peek() != Some(b'"') {
778 return Err(bridge_error(BridgeErrorCode::ProviderInvalidResponse));
779 }
780 let key = self.string()?;
781 self.skip_whitespace();
782 if self.peek() != Some(b':') {
783 return Err(bridge_error(BridgeErrorCode::ProviderInvalidResponse));
784 }
785 self.index += 1;
786 self.skip_whitespace();
787 let child = self.value(depth + 1)?;
788 if entries.insert(key.clone(), child.clone()).is_some() {
789 return Err(bridge_error(BridgeErrorCode::ProviderInvalidResponse));
790 }
791 values.insert(key, child.value.clone());
792 self.skip_whitespace();
793 match self.peek() {
794 Some(b'}') => {
795 self.index += 1;
796 break;
797 }
798 Some(b',') => {
799 self.index += 1;
800 self.skip_whitespace();
801 }
802 _ => return Err(bridge_error(BridgeErrorCode::ProviderInvalidResponse)),
803 }
804 }
805 Ok(JsonNode {
806 value: Value::Object(values),
807 start,
808 end: self.index,
809 object_entries: Some(entries),
810 array_items: None,
811 raw_number: None,
812 })
813 }
814
815 fn array(&mut self, start: usize, depth: usize) -> BridgeResult<JsonNode> {
816 self.index += 1;
817 self.skip_whitespace();
818 let mut items = Vec::new();
819 if self.peek() == Some(b']') {
820 self.index += 1;
821 return Ok(JsonNode {
822 value: Value::Array(Vec::new()),
823 start,
824 end: self.index,
825 object_entries: None,
826 array_items: Some(items),
827 raw_number: None,
828 });
829 }
830 loop {
831 items.push(self.value(depth + 1)?);
832 self.skip_whitespace();
833 match self.peek() {
834 Some(b']') => {
835 self.index += 1;
836 break;
837 }
838 Some(b',') => {
839 self.index += 1;
840 self.skip_whitespace();
841 }
842 _ => return Err(bridge_error(BridgeErrorCode::ProviderInvalidResponse)),
843 }
844 }
845 let values = items.iter().map(|item| item.value.clone()).collect();
846 Ok(JsonNode {
847 value: Value::Array(values),
848 start,
849 end: self.index,
850 object_entries: None,
851 array_items: Some(items),
852 raw_number: None,
853 })
854 }
855
856 fn string(&mut self) -> BridgeResult<String> {
857 let start = self.index;
858 self.index += 1;
859 while self.index < self.source.len() {
860 let character = self.source.as_bytes()[self.index];
861 match character {
862 b'"' => {
863 self.index += 1;
864 let raw = &self.source[start..self.index];
865 return serde_json::from_str(raw)
866 .map_err(|_| bridge_error(BridgeErrorCode::ProviderInvalidResponse));
867 }
868 b'\\' => {
869 self.index += 1;
870 let Some(escape) = self.source.as_bytes().get(self.index).copied() else {
871 return Err(bridge_error(BridgeErrorCode::ProviderInvalidResponse));
872 };
873 if escape == b'u' {
874 if self.index + 4 >= self.source.len()
875 || !self.source.as_bytes()[self.index + 1..self.index + 5]
876 .iter()
877 .all(u8::is_ascii_hexdigit)
878 {
879 return Err(bridge_error(BridgeErrorCode::ProviderInvalidResponse));
880 }
881 self.index += 5;
882 } else if b"\"\\/bfnrt".contains(&escape) {
883 self.index += 1;
884 } else {
885 return Err(bridge_error(BridgeErrorCode::ProviderInvalidResponse));
886 }
887 }
888 0..=0x1f => {
889 return Err(bridge_error(BridgeErrorCode::ProviderInvalidResponse));
890 }
891 _ => self.index += 1,
892 }
893 }
894 Err(bridge_error(BridgeErrorCode::ProviderInvalidResponse))
895 }
896
897 fn number(&mut self, start: usize) -> BridgeResult<JsonNode> {
898 if self.peek() == Some(b'-') {
899 self.index += 1;
900 }
901 match self.peek() {
902 Some(b'0') => self.index += 1,
903 Some(b'1'..=b'9') => {
904 self.index += 1;
905 while self.peek().is_some_and(|value| value.is_ascii_digit()) {
906 self.index += 1;
907 }
908 }
909 _ => return Err(bridge_error(BridgeErrorCode::ProviderInvalidResponse)),
910 }
911 if self.peek() == Some(b'.') {
912 self.index += 1;
913 let fraction_start = self.index;
914 while self.peek().is_some_and(|value| value.is_ascii_digit()) {
915 self.index += 1;
916 }
917 if self.index == fraction_start {
918 return Err(bridge_error(BridgeErrorCode::ProviderInvalidResponse));
919 }
920 }
921 if self
922 .peek()
923 .is_some_and(|value| value == b'e' || value == b'E')
924 {
925 self.index += 1;
926 if self
927 .peek()
928 .is_some_and(|value| value == b'+' || value == b'-')
929 {
930 self.index += 1;
931 }
932 let exponent_start = self.index;
933 while self.peek().is_some_and(|value| value.is_ascii_digit()) {
934 self.index += 1;
935 }
936 if self.index == exponent_start {
937 return Err(bridge_error(BridgeErrorCode::ProviderInvalidResponse));
938 }
939 }
940 let raw = self.source[start..self.index].to_owned();
941 let value = serde_json::from_str::<Value>(&raw)
942 .map_err(|_| bridge_error(BridgeErrorCode::ProviderInvalidResponse))?;
943 if !value.is_number() {
944 return Err(bridge_error(BridgeErrorCode::ProviderInvalidResponse));
945 }
946 Ok(JsonNode {
947 value,
948 start,
949 end: self.index,
950 object_entries: None,
951 array_items: None,
952 raw_number: Some(raw),
953 })
954 }
955
956 fn peek(&self) -> Option<u8> {
957 self.source.as_bytes().get(self.index).copied()
958 }
959
960 fn skip_whitespace(&mut self) {
961 while self
962 .peek()
963 .is_some_and(|value| matches!(value, b' ' | b'\n' | b'\r' | b'\t'))
964 {
965 self.index += 1;
966 }
967 }
968}
969
970pub(crate) fn object_entry<'a>(node: &'a JsonNode, key: &str) -> Option<&'a JsonNode> {
971 node.object_entries.as_ref()?.get(key)
972}
973
974pub(crate) fn object_value<'a>(node: &'a JsonNode, key: &str) -> Option<&'a Value> {
975 Some(&object_entry(node, key)?.value)
976}
977
978pub(crate) fn required_node<'a>(node: &'a JsonNode, key: &str) -> BridgeResult<&'a JsonNode> {
979 object_entry(node, key).ok_or_else(|| bridge_error(BridgeErrorCode::ProviderInvalidResponse))
980}
981
982pub(crate) fn parse_provider_response(text: String) -> BridgeResult<ProviderResponse> {
983 let root = StrictJsonParser::new(&text).parse()?;
984 Ok(ProviderResponse { text, root })
985}
986
987#[allow(clippy::struct_field_names)]
988#[derive(Clone, Debug, Deserialize)]
989#[serde(deny_unknown_fields, rename_all = "camelCase")]
990struct BridgeCapability {
991 bridge_capability_id: String,
992 provider_id: String,
993 capability_kind: String,
994 source_chain_id: String,
995 destination_chain_id: String,
996 source_token_deployment_id: String,
997 destination_token_deployment_id: String,
998 source_token_address: String,
999 destination_token_address: String,
1000 source_token_standard: String,
1001 destination_token_standard: String,
1002 source_token_decimals: u8,
1003 destination_token_decimals: u8,
1004 source_provider_chain_name: String,
1005 destination_provider_chain_name: String,
1006 source_provider_chain_id: u8,
1007 destination_provider_chain_id: u8,
1008 source_wormhole_chain_id: u8,
1009 destination_wormhole_chain_id: u8,
1010 source_usdc_deployment_id: String,
1011 source_usdc_address: String,
1012 source_usdc_standard: String,
1013 source_usdc_decimals: u8,
1014 swift_contract: String,
1015 forwarder_address: Option<String>,
1016 forwarder_function_selector: Option<String>,
1017 jupiter_program_address: Option<String>,
1018 builder_endpoint: String,
1019 explorer_endpoint: String,
1020 dependencies: Vec<String>,
1021 status: String,
1022}
1023
1024#[derive(Clone, Copy, Debug, Eq, PartialEq)]
1025pub(crate) enum BridgeAsset {
1026 Eurc,
1027 Usdc,
1028}
1029
1030#[derive(Clone, Debug)]
1031pub(crate) struct DirectionFacts {
1032 pub(crate) asset: BridgeAsset,
1033 pub(crate) bridge_capability_id: &'static str,
1034 pub(crate) source_chain_id: &'static str,
1035 pub(crate) destination_chain_id: &'static str,
1036 pub(crate) source_token_deployment_id: &'static str,
1037 pub(crate) destination_token_deployment_id: &'static str,
1038 pub(crate) source_token_address: &'static str,
1039 pub(crate) destination_token_address: &'static str,
1040 pub(crate) source_token_standard: &'static str,
1041 pub(crate) destination_token_standard: &'static str,
1042 pub(crate) source_provider_chain_name: &'static str,
1043 pub(crate) destination_provider_chain_name: &'static str,
1044 pub(crate) source_provider_chain_id: u8,
1045 pub(crate) destination_provider_chain_id: u8,
1046 pub(crate) source_wormhole_chain_id: u8,
1047 pub(crate) destination_wormhole_chain_id: u8,
1048 pub(crate) source_usdc_deployment_id: &'static str,
1049 pub(crate) source_usdc_address: &'static str,
1050 pub(crate) source_usdc_standard: &'static str,
1051 pub(crate) swift_contract: &'static str,
1052 pub(crate) source_token_name: &'static str,
1053 pub(crate) destination_token_name: &'static str,
1054 pub(crate) source_token_mint: &'static str,
1055 pub(crate) destination_token_mint: &'static str,
1056 pub(crate) source_swap_required: bool,
1057}
1058
1059#[allow(clippy::too_many_lines)]
1060pub(crate) fn direction_facts(
1061 source_chain_id: &str,
1062 destination_chain_id: &str,
1063 source_token_deployment_id: &str,
1064 destination_token_deployment_id: &str,
1065) -> BridgeResult<DirectionFacts> {
1066 if source_chain_id == ETHEREUM_CHAIN_ID && destination_chain_id == SOLANA_CHAIN_ID {
1067 let asset = match (source_token_deployment_id, destination_token_deployment_id) {
1068 (ETHEREUM_EURC_DEPLOYMENT_ID, SOLANA_EURC_DEPLOYMENT_ID) => BridgeAsset::Eurc,
1069 (ETHEREUM_USDC_DEPLOYMENT_ID, SOLANA_USDC_DEPLOYMENT_ID) => BridgeAsset::Usdc,
1070 _ => return Err(bridge_error(BridgeErrorCode::UnsupportedRoute)),
1071 };
1072 let (
1073 source_token_address,
1074 destination_token_address,
1075 source_token_name,
1076 destination_token_name,
1077 source_token_mint,
1078 destination_token_mint,
1079 source_swap_required,
1080 ) = match asset {
1081 BridgeAsset::Eurc => (
1082 ETHEREUM_EURC_ADDRESS,
1083 SOLANA_EURC_ADDRESS,
1084 "EuroC",
1085 "EuroC",
1086 "",
1087 SOLANA_EURC_ADDRESS,
1088 true,
1089 ),
1090 BridgeAsset::Usdc => (
1091 ETHEREUM_USDC_ADDRESS,
1092 SOLANA_USDC_ADDRESS,
1093 "USD Coin",
1094 "USD Coin",
1095 MAYAN_USDC_MINT,
1096 SOLANA_USDC_ADDRESS,
1097 false,
1098 ),
1099 };
1100 return Ok(DirectionFacts {
1101 asset,
1102 bridge_capability_id: match asset {
1103 BridgeAsset::Eurc => "bridge-mayan-swift-v2-eurc-eth-sol",
1104 BridgeAsset::Usdc => "bridge-mayan-swift-v2-usdc-eth-sol",
1105 },
1106 source_chain_id: ETHEREUM_CHAIN_ID,
1107 destination_chain_id: SOLANA_CHAIN_ID,
1108 source_token_deployment_id: match asset {
1109 BridgeAsset::Eurc => ETHEREUM_EURC_DEPLOYMENT_ID,
1110 BridgeAsset::Usdc => ETHEREUM_USDC_DEPLOYMENT_ID,
1111 },
1112 destination_token_deployment_id: match asset {
1113 BridgeAsset::Eurc => SOLANA_EURC_DEPLOYMENT_ID,
1114 BridgeAsset::Usdc => SOLANA_USDC_DEPLOYMENT_ID,
1115 },
1116 source_token_address,
1117 destination_token_address,
1118 source_token_standard: "erc20",
1119 destination_token_standard: "spl-token",
1120 source_provider_chain_name: ETHEREUM_NAME,
1121 destination_provider_chain_name: SOLANA_NAME,
1122 source_provider_chain_id: 1,
1123 destination_provider_chain_id: 0,
1124 source_wormhole_chain_id: 2,
1125 destination_wormhole_chain_id: 1,
1126 source_usdc_deployment_id: ETHEREUM_USDC_DEPLOYMENT_ID,
1127 source_usdc_address: ETHEREUM_USDC_ADDRESS,
1128 source_usdc_standard: "erc20",
1129 swift_contract: ETHEREUM_SWIFT_CONTRACT,
1130 source_token_name,
1131 destination_token_name,
1132 source_token_mint,
1133 destination_token_mint,
1134 source_swap_required,
1135 });
1136 }
1137 if source_chain_id == SOLANA_CHAIN_ID && destination_chain_id == ETHEREUM_CHAIN_ID {
1138 let asset = match (source_token_deployment_id, destination_token_deployment_id) {
1139 (SOLANA_EURC_DEPLOYMENT_ID, ETHEREUM_EURC_DEPLOYMENT_ID) => BridgeAsset::Eurc,
1140 (SOLANA_USDC_DEPLOYMENT_ID, ETHEREUM_USDC_DEPLOYMENT_ID) => BridgeAsset::Usdc,
1141 _ => return Err(bridge_error(BridgeErrorCode::UnsupportedRoute)),
1142 };
1143 let (
1144 source_token_address,
1145 destination_token_address,
1146 source_token_name,
1147 destination_token_name,
1148 source_token_mint,
1149 destination_token_mint,
1150 source_swap_required,
1151 ) = match asset {
1152 BridgeAsset::Eurc => (
1153 SOLANA_EURC_ADDRESS,
1154 ETHEREUM_EURC_ADDRESS,
1155 "EuroC",
1156 "EuroC",
1157 SOLANA_EURC_ADDRESS,
1158 "",
1159 true,
1160 ),
1161 BridgeAsset::Usdc => (
1162 SOLANA_USDC_ADDRESS,
1163 ETHEREUM_USDC_ADDRESS,
1164 "USD Coin",
1165 "USD Coin",
1166 SOLANA_USDC_ADDRESS,
1167 MAYAN_USDC_MINT,
1168 false,
1169 ),
1170 };
1171 return Ok(DirectionFacts {
1172 asset,
1173 bridge_capability_id: match asset {
1174 BridgeAsset::Eurc => "bridge-mayan-swift-v2-eurc-sol-eth",
1175 BridgeAsset::Usdc => "bridge-mayan-swift-v2-usdc-sol-eth",
1176 },
1177 source_chain_id: SOLANA_CHAIN_ID,
1178 destination_chain_id: ETHEREUM_CHAIN_ID,
1179 source_token_deployment_id: match asset {
1180 BridgeAsset::Eurc => SOLANA_EURC_DEPLOYMENT_ID,
1181 BridgeAsset::Usdc => SOLANA_USDC_DEPLOYMENT_ID,
1182 },
1183 destination_token_deployment_id: match asset {
1184 BridgeAsset::Eurc => ETHEREUM_EURC_DEPLOYMENT_ID,
1185 BridgeAsset::Usdc => ETHEREUM_USDC_DEPLOYMENT_ID,
1186 },
1187 source_token_address,
1188 destination_token_address,
1189 source_token_standard: "spl-token",
1190 destination_token_standard: "erc20",
1191 source_provider_chain_name: SOLANA_NAME,
1192 destination_provider_chain_name: ETHEREUM_NAME,
1193 source_provider_chain_id: 0,
1194 destination_provider_chain_id: 1,
1195 source_wormhole_chain_id: 1,
1196 destination_wormhole_chain_id: 2,
1197 source_usdc_deployment_id: SOLANA_USDC_DEPLOYMENT_ID,
1198 source_usdc_address: SOLANA_USDC_ADDRESS,
1199 source_usdc_standard: "spl-token",
1200 swift_contract: SOLANA_SWIFT_PROGRAM,
1201 source_token_name,
1202 destination_token_name,
1203 source_token_mint,
1204 destination_token_mint,
1205 source_swap_required,
1206 });
1207 }
1208 Err(bridge_error(BridgeErrorCode::UnsupportedRoute))
1209}
1210
1211fn catalog_token_matches(
1212 deployment_id: &str,
1213 chain_id: &str,
1214 address: &str,
1215 standard: &str,
1216) -> bool {
1217 let Some(token) = get_token_deployment(deployment_id) else {
1218 return false;
1219 };
1220 token.chain_id == chain_id
1221 && token.address.is_some_and(|candidate| {
1222 if chain_id == ETHEREUM_CHAIN_ID {
1223 candidate.eq_ignore_ascii_case(address)
1224 } else {
1225 candidate == address
1226 }
1227 })
1228 && token.decimals == 6
1229 && token.status == TokenStatus::Active
1230 && match standard {
1231 "erc20" => token.standard == TokenStandard::Erc20,
1232 "spl-token" => token.standard == TokenStandard::SplToken,
1233 _ => false,
1234 }
1235}
1236
1237fn validate_catalog_direction(facts: &DirectionFacts) -> BridgeResult<()> {
1238 if !catalog_token_matches(
1239 facts.source_token_deployment_id,
1240 facts.source_chain_id,
1241 facts.source_token_address,
1242 facts.source_token_standard,
1243 ) || !catalog_token_matches(
1244 facts.destination_token_deployment_id,
1245 facts.destination_chain_id,
1246 facts.destination_token_address,
1247 facts.destination_token_standard,
1248 ) || !catalog_token_matches(
1249 facts.source_usdc_deployment_id,
1250 facts.source_chain_id,
1251 facts.source_usdc_address,
1252 facts.source_usdc_standard,
1253 ) {
1254 return Err(bridge_error(BridgeErrorCode::UnsupportedRoute));
1255 }
1256 Ok(())
1257}
1258
1259fn expected_dependencies(facts: &DirectionFacts) -> Vec<String> {
1260 let mut dependencies = if facts.asset == BridgeAsset::Usdc {
1261 DIRECT_USDC_DEPENDENCIES
1262 } else {
1263 DEPENDENCIES
1264 }
1265 .iter()
1266 .map(|value| (*value).to_owned())
1267 .collect::<Vec<_>>();
1268 if facts.asset == BridgeAsset::Eurc && facts.source_chain_id == SOLANA_CHAIN_ID {
1269 dependencies.push("jupiter-v6-source-swap".to_owned());
1270 }
1271 dependencies
1272}
1273
1274fn expected_forwarder_selector(facts: &DirectionFacts) -> Option<&'static str> {
1275 (facts.source_chain_id == ETHEREUM_CHAIN_ID).then_some(if facts.asset == BridgeAsset::Usdc {
1276 ETHEREUM_USDC_FORWARDER_SELECTOR
1277 } else {
1278 ETHEREUM_EURC_FORWARDER_SELECTOR
1279 })
1280}
1281
1282fn find_capability(facts: &DirectionFacts) -> BridgeResult<BridgeCapability> {
1283 if BRIDGE_CAPABILITIES_CONTENT_DIGEST.len() != 64 || BRIDGE_CAPABILITIES_AS_OF_DATE.len() != 10
1284 {
1285 return Err(bridge_error(BridgeErrorCode::UnsupportedRoute));
1286 }
1287 let capabilities: Vec<BridgeCapability> = serde_json::from_str(BRIDGE_CAPABILITIES_JSON)
1288 .map_err(|_| bridge_error(BridgeErrorCode::UnsupportedRoute))?;
1289 let Some(capability) = capabilities.into_iter().find(|entry| {
1290 entry.bridge_capability_id == facts.bridge_capability_id
1291 && entry.source_chain_id == facts.source_chain_id
1292 && entry.destination_chain_id == facts.destination_chain_id
1293 && entry.source_token_deployment_id == facts.source_token_deployment_id
1294 && entry.destination_token_deployment_id == facts.destination_token_deployment_id
1295 }) else {
1296 return Err(bridge_error(BridgeErrorCode::UnsupportedRoute));
1297 };
1298 let eth_source = facts.source_chain_id == ETHEREUM_CHAIN_ID;
1299 let expected_forwarder = eth_source.then(|| ETHEREUM_FORWARDER.to_owned());
1300 let expected_forwarder_selector = expected_forwarder_selector(facts).map(str::to_owned);
1301 let expected_jupiter =
1302 (facts.asset == BridgeAsset::Eurc && !eth_source).then(|| SOLANA_JUPITER_V6.to_owned());
1303 let matches = capability.provider_id == "mayan-swift-v2"
1304 && capability.capability_kind == "external-provider-dynamic"
1305 && capability
1306 .source_token_address
1307 .eq_ignore_ascii_case(facts.source_token_address)
1308 && (facts.destination_chain_id != ETHEREUM_CHAIN_ID
1309 || capability
1310 .destination_token_address
1311 .eq_ignore_ascii_case(facts.destination_token_address))
1312 && capability.destination_token_address == facts.destination_token_address
1313 && capability.source_token_standard == facts.source_token_standard
1314 && capability.destination_token_standard == facts.destination_token_standard
1315 && capability.source_token_decimals == 6
1316 && capability.destination_token_decimals == 6
1317 && capability.source_provider_chain_name == facts.source_provider_chain_name
1318 && capability.destination_provider_chain_name == facts.destination_provider_chain_name
1319 && capability.source_provider_chain_id == facts.source_provider_chain_id
1320 && capability.destination_provider_chain_id == facts.destination_provider_chain_id
1321 && capability.source_wormhole_chain_id == facts.source_wormhole_chain_id
1322 && capability.destination_wormhole_chain_id == facts.destination_wormhole_chain_id
1323 && capability.source_usdc_deployment_id == facts.source_usdc_deployment_id
1324 && capability
1325 .source_usdc_address
1326 .eq_ignore_ascii_case(facts.source_usdc_address)
1327 && capability.source_usdc_standard == facts.source_usdc_standard
1328 && capability.source_usdc_decimals == 6
1329 && capability.swift_contract == facts.swift_contract
1330 && capability.forwarder_address == expected_forwarder
1331 && capability.forwarder_function_selector == expected_forwarder_selector
1332 && capability.jupiter_program_address == expected_jupiter
1333 && capability.builder_endpoint == DEFAULT_BUILDER_ENDPOINT
1334 && capability.explorer_endpoint == DEFAULT_EXPLORER_ENDPOINT
1335 && capability.dependencies == expected_dependencies(facts)
1336 && capability.status == "active";
1337 if !matches {
1338 return Err(bridge_error(BridgeErrorCode::UnsupportedRoute));
1339 }
1340 Ok(capability)
1341}
1342
1343fn normalize_provider_endpoint(source: &str) -> BridgeResult<Url> {
1344 if source.is_empty() || source.trim() != source || !source.contains("://") {
1345 return Err(bridge_error(BridgeErrorCode::InvalidArgument));
1346 }
1347 let endpoint =
1348 Url::parse(source).map_err(|_| bridge_error(BridgeErrorCode::InvalidArgument))?;
1349 if !endpoint.username().is_empty() || endpoint.password().is_some() {
1350 return Err(bridge_error(BridgeErrorCode::InvalidArgument));
1351 }
1352 if endpoint.query().is_some() || endpoint.fragment().is_some() {
1353 return Err(bridge_error(BridgeErrorCode::InvalidArgument));
1354 }
1355 let hostname = endpoint.host_str().unwrap_or_default();
1356 if endpoint.scheme() != "https"
1357 && !(endpoint.scheme() == "http"
1358 && matches!(hostname, "localhost" | "127.0.0.1" | "[::1]" | "::1"))
1359 {
1360 return Err(bridge_error(BridgeErrorCode::InvalidArgument));
1361 }
1362 if hostname.is_empty() || endpoint.port().is_some_and(|port| port == 0) {
1363 return Err(bridge_error(BridgeErrorCode::InvalidArgument));
1364 }
1365 let mut endpoint = endpoint;
1366 let path = endpoint.path().trim_end_matches('/').to_owned();
1367 endpoint.set_path(if path.is_empty() { "/" } else { &path });
1368 Ok(endpoint)
1369}
1370
1371fn endpoint_with_path(base: &Url, path: &str) -> Url {
1372 let mut endpoint = base.clone();
1373 let prefix = endpoint.path().trim_end_matches('/');
1374 endpoint.set_path(&format!("{prefix}/{}", path.trim_start_matches('/')));
1375 endpoint
1376}
1377
1378fn normalize_bridge_config(
1379 config: MayanSwiftV2BridgeConfig,
1380) -> BridgeResult<NormalizedBridgeConfig> {
1381 if config.timeout.is_zero() || config.minimum_quote_validity_seconds > 300 {
1382 return Err(bridge_error(BridgeErrorCode::InvalidArgument));
1383 }
1384 let builder_endpoint = normalize_provider_endpoint(&config.builder_endpoint)?;
1385 let explorer_endpoint = normalize_provider_endpoint(&config.explorer_endpoint)?;
1386 let builder_api_key = config
1387 .builder_api_key
1388 .and_then(|value| if value.is_empty() { None } else { Some(value) });
1389 if let Some(key) = &builder_api_key {
1390 HeaderValue::from_str(key).map_err(|_| bridge_error(BridgeErrorCode::InvalidArgument))?;
1391 }
1392 let http_client = Client::builder()
1393 .redirect(Policy::none())
1394 .build()
1395 .map_err(|_| bridge_error(BridgeErrorCode::InvalidArgument))?;
1396 Ok(NormalizedBridgeConfig {
1397 builder_endpoint,
1398 explorer_endpoint,
1399 builder_api_key,
1400 allow_unauthenticated_build: config.allow_unauthenticated_build,
1401 minimum_quote_validity_seconds: config.minimum_quote_validity_seconds,
1402 timeout: config.timeout,
1403 http_client,
1404 local_build: config.local_build,
1405 })
1406}
1407
1408struct NormalizedBridgeConfig {
1409 builder_endpoint: Url,
1410 explorer_endpoint: Url,
1411 builder_api_key: Option<String>,
1412 allow_unauthenticated_build: bool,
1413 minimum_quote_validity_seconds: u64,
1414 timeout: Duration,
1415 http_client: Client,
1416 local_build: Option<MayanSwiftV2LocalBuildConfig>,
1417}
1418
1419#[derive(Clone, Copy)]
1420enum ProviderOperation {
1421 Quote,
1422 Build,
1423 Status,
1424}
1425
1426#[derive(Clone)]
1428pub struct MayanSwiftV2BridgeClient {
1429 config: Arc<NormalizedBridgeConfig>,
1430 #[cfg(test)]
1431 clock: Option<fn() -> u64>,
1432}
1433
1434impl MayanSwiftV2BridgeClient {
1435 pub fn new(config: MayanSwiftV2BridgeConfig) -> BridgeResult<Self> {
1437 Ok(Self {
1438 config: Arc::new(normalize_bridge_config(config)?),
1439 #[cfg(test)]
1440 clock: None,
1441 })
1442 }
1443
1444 pub fn default_client() -> BridgeResult<Self> {
1446 Self::new(MayanSwiftV2BridgeConfig::default())
1447 }
1448
1449 #[must_use]
1451 pub fn builder_endpoint(&self) -> String {
1452 self.config.builder_endpoint.to_string()
1453 }
1454
1455 #[must_use]
1457 pub fn explorer_endpoint(&self) -> String {
1458 self.config.explorer_endpoint.to_string()
1459 }
1460
1461 pub async fn quote_exact_input<R>(&self, request: R) -> BridgeResult<Vec<MayanSwiftV2Quote>>
1463 where
1464 R: Borrow<MayanSwiftV2QuoteRequest>,
1465 {
1466 self.quote_exact_input_with(request.borrow(), None).await
1467 }
1468
1469 pub async fn quote_exact_input_with<R>(
1471 &self,
1472 request: R,
1473 cancellation: Option<&CancellationToken>,
1474 ) -> BridgeResult<Vec<MayanSwiftV2Quote>>
1475 where
1476 R: Borrow<MayanSwiftV2QuoteRequest>,
1477 {
1478 let request = request.borrow().clone();
1479 let (request, facts, capability) = normalize_quote_request(&request, self)?;
1480 let body = quote_request_body(&request, &facts);
1481 let endpoint = endpoint_with_path(&self.config.builder_endpoint, "/quote");
1482 let response = self
1483 .provider_json(
1484 endpoint,
1485 reqwest::Method::POST,
1486 Some(body),
1487 false,
1488 ProviderOperation::Quote,
1489 cancellation,
1490 )
1491 .await?;
1492 quote_from_response(&response, &request, &facts, &capability, self)
1493 }
1494
1495 pub async fn build_unsigned<R>(&self, request: R) -> BridgeResult<MayanSwiftV2Build>
1497 where
1498 R: Borrow<MayanSwiftV2BuildRequest>,
1499 {
1500 self.build_unsigned_with(request.borrow(), None).await
1501 }
1502
1503 pub async fn build_unsigned_with<R>(
1505 &self,
1506 request: R,
1507 cancellation: Option<&CancellationToken>,
1508 ) -> BridgeResult<MayanSwiftV2Build>
1509 where
1510 R: Borrow<MayanSwiftV2BuildRequest>,
1511 {
1512 let request = request.borrow().clone();
1513 let (route_request, facts, _capability) = normalize_quote_request(
1514 &MayanSwiftV2QuoteRequest {
1515 source_chain_id: request.quote.source_chain_id.clone(),
1516 destination_chain_id: request.quote.destination_chain_id.clone(),
1517 source_token_deployment_id: request.quote.source_token_deployment_id.clone(),
1518 destination_token_deployment_id: request
1519 .quote
1520 .destination_token_deployment_id
1521 .clone(),
1522 amount_in: request.quote.amount_in.clone(),
1523 slippage_bps: request.quote.slippage_bps,
1524 },
1525 self,
1526 )
1527 .map_err(|_| bridge_error(BridgeErrorCode::QuoteMismatch))?;
1528 let swapper_address = normalize_chain_address(
1529 &request.swapper_address,
1530 facts.source_chain_id,
1531 BridgeErrorCode::InvalidArgument,
1532 )?;
1533 let destination_address = normalize_chain_address(
1534 &request.destination_address,
1535 facts.destination_chain_id,
1536 BridgeErrorCode::InvalidArgument,
1537 )?;
1538 let refund_address = request
1539 .refund_address
1540 .as_deref()
1541 .map(|address| {
1542 normalize_chain_address(
1543 address,
1544 facts.source_chain_id,
1545 BridgeErrorCode::InvalidArgument,
1546 )
1547 })
1548 .transpose()?;
1549 if self.config.builder_api_key.is_none() && !self.config.allow_unauthenticated_build {
1550 return Err(bridge_error(BridgeErrorCode::ProviderAuthRequired));
1551 }
1552 let quote = validate_raw_quote_for_build(&request.quote, &route_request, &facts, self)?;
1553 let body = build_request_body(
1554 "e,
1555 facts.source_chain_id,
1556 &swapper_address,
1557 &destination_address,
1558 refund_address.as_deref(),
1559 )?;
1560 let endpoint = endpoint_with_path(&self.config.builder_endpoint, "/build");
1561 let response = self
1562 .provider_json(
1563 endpoint,
1564 reqwest::Method::POST,
1565 Some(body),
1566 true,
1567 ProviderOperation::Build,
1568 cancellation,
1569 )
1570 .await?;
1571 ensure_quote_deadline(
1572 "e.deadline,
1573 self.config.minimum_quote_validity_seconds,
1574 self,
1575 )?;
1576 validate_build_response(&response, "e, &facts, &swapper_address).map_err(|error| {
1577 if error.code() == BridgeErrorCode::ProviderInvalidResponse {
1578 bridge_error(BridgeErrorCode::BuildInvalid)
1579 } else {
1580 error
1581 }
1582 })
1583 }
1584
1585 pub async fn get_status<R>(&self, request: R) -> BridgeResult<MayanSwiftV2Status>
1587 where
1588 R: Borrow<MayanSwiftV2StatusRequest>,
1589 {
1590 self.get_status_with(request.borrow(), None).await
1591 }
1592
1593 pub async fn get_status_with<R>(
1595 &self,
1596 request: R,
1597 cancellation: Option<&CancellationToken>,
1598 ) -> BridgeResult<MayanSwiftV2Status>
1599 where
1600 R: Borrow<MayanSwiftV2StatusRequest>,
1601 {
1602 let request = request.borrow().clone();
1603 let normalized = normalize_status_request(&request)?;
1604 let endpoint = endpoint_with_path(
1605 &self.config.explorer_endpoint,
1606 &format!("/swap/trx/{}", percent_encode_path_segment(&normalized.1)),
1607 );
1608 let response = self
1609 .provider_json(
1610 endpoint,
1611 reqwest::Method::GET,
1612 None,
1613 false,
1614 ProviderOperation::Status,
1615 cancellation,
1616 )
1617 .await?;
1618 status_from_response(&response, &normalized)
1619 }
1620
1621 pub async fn prepare_source_swap(
1623 &self,
1624 context: crate::bridge_local::MayanSwiftV2LocalContext,
1625 ) -> BridgeResult<crate::bridge_local::MayanSwiftV2SourceSwapPlan> {
1626 crate::bridge_local::prepare_source_swap(self, context, None).await
1627 }
1628
1629 pub async fn prepare_source_swap_with(
1631 &self,
1632 context: crate::bridge_local::MayanSwiftV2LocalContext,
1633 cancellation: Option<&CancellationToken>,
1634 ) -> BridgeResult<crate::bridge_local::MayanSwiftV2SourceSwapPlan> {
1635 crate::bridge_local::prepare_source_swap(self, context, cancellation).await
1636 }
1637
1638 pub async fn build_local_unsigned(
1640 &self,
1641 request: crate::bridge_local::MayanSwiftV2LocalBuildRequest,
1642 ) -> BridgeResult<crate::bridge_local::MayanSwiftV2LocalBuild> {
1643 crate::bridge_local::build_local_unsigned(self, request, None).await
1644 }
1645
1646 pub async fn build_local_unsigned_with(
1648 &self,
1649 request: crate::bridge_local::MayanSwiftV2LocalBuildRequest,
1650 cancellation: Option<&CancellationToken>,
1651 ) -> BridgeResult<crate::bridge_local::MayanSwiftV2LocalBuild> {
1652 crate::bridge_local::build_local_unsigned(self, request, cancellation).await
1653 }
1654
1655 pub fn close(&self) {}
1657
1658 pub(crate) fn local_build_config(&self) -> Option<&MayanSwiftV2LocalBuildConfig> {
1659 self.config.local_build.as_ref()
1660 }
1661
1662 pub(crate) fn local_timeout(&self) -> Duration {
1663 self.config.timeout
1664 }
1665
1666 pub(crate) fn local_minimum_quote_validity_seconds(&self) -> u64 {
1667 self.config.minimum_quote_validity_seconds
1668 }
1669
1670 #[cfg(test)]
1671 #[allow(dead_code)]
1672 pub(crate) fn with_clock(mut self, clock: fn() -> u64) -> Self {
1673 self.clock = Some(clock);
1674 self
1675 }
1676
1677 #[cfg(test)]
1678 pub(crate) fn now_seconds(&self) -> BridgeResult<u64> {
1679 if let Some(clock) = self.clock {
1680 return Ok(clock());
1681 }
1682 current_wall_clock()
1683 }
1684
1685 #[cfg(not(test))]
1686 #[allow(clippy::unused_self)]
1687 pub(crate) fn now_seconds(&self) -> BridgeResult<u64> {
1688 current_wall_clock()
1689 }
1690
1691 async fn provider_json(
1692 &self,
1693 endpoint: Url,
1694 method: reqwest::Method,
1695 body: Option<String>,
1696 include_builder_key: bool,
1697 operation: ProviderOperation,
1698 cancellation: Option<&CancellationToken>,
1699 ) -> BridgeResult<ProviderResponse> {
1700 if cancellation.is_some_and(CancellationToken::is_cancelled) {
1701 return Err(bridge_error(BridgeErrorCode::Aborted));
1702 }
1703 let mut request = self
1704 .config
1705 .http_client
1706 .request(method, endpoint)
1707 .header(reqwest::header::ACCEPT, "application/json");
1708 if let Some(body) = body {
1709 request = request
1710 .header(reqwest::header::CONTENT_TYPE, "application/json")
1711 .body(body);
1712 }
1713 if include_builder_key {
1714 if let Some(key) = &self.config.builder_api_key {
1715 let key = HeaderValue::from_str(key)
1716 .map_err(|_| bridge_error(BridgeErrorCode::InvalidArgument))?;
1717 request = request.header("x-api-key", key);
1718 }
1719 }
1720 let operation = async {
1721 let response = request
1722 .send()
1723 .await
1724 .map_err(|_| bridge_error(BridgeErrorCode::ProviderTransport))?;
1725 let status = response.status().as_u16();
1726 if matches!(operation, ProviderOperation::Status) && status == 404 {
1727 return Err(bridge_error_status(BridgeErrorCode::StatusNotFound, status));
1728 }
1729 if (300..400).contains(&status) {
1730 return Err(bridge_error_status(
1731 BridgeErrorCode::ProviderTransport,
1732 status,
1733 ));
1734 }
1735 if matches!(operation, ProviderOperation::Build) && (status == 401 || status == 403) {
1736 return Err(bridge_error_status(
1737 BridgeErrorCode::ProviderAuthRequired,
1738 status,
1739 ));
1740 }
1741 if status != 200 && status != 201 {
1742 return Err(bridge_error_status(BridgeErrorCode::ProviderHttp, status));
1743 }
1744 let body = read_response_body(response).await?;
1745 parse_provider_response(body)
1746 };
1747 let timed = tokio::time::timeout(self.config.timeout, operation);
1748 if let Some(cancellation) = cancellation {
1749 tokio::select! {
1750 biased;
1751 () = cancellation.cancelled() => Err(bridge_error(BridgeErrorCode::Aborted)),
1752 result = timed => result.map_err(|_| bridge_error(BridgeErrorCode::Timeout))?,
1753 }
1754 } else {
1755 timed
1756 .await
1757 .map_err(|_| bridge_error(BridgeErrorCode::Timeout))?
1758 }
1759 }
1760}
1761
1762pub fn create_mayan_swift_v2_bridge_client(
1764 config: MayanSwiftV2BridgeConfig,
1765) -> BridgeResult<MayanSwiftV2BridgeClient> {
1766 MayanSwiftV2BridgeClient::new(config)
1767}
1768
1769fn current_wall_clock() -> BridgeResult<u64> {
1770 SystemTime::now()
1771 .duration_since(UNIX_EPOCH)
1772 .map(|duration| duration.as_secs())
1773 .map_err(|_| bridge_error(BridgeErrorCode::InvalidArgument))
1774}
1775
1776async fn read_response_body(mut response: Response) -> BridgeResult<String> {
1777 let mut bytes = Vec::new();
1778 while let Some(chunk) = response
1779 .chunk()
1780 .await
1781 .map_err(|_| bridge_error(BridgeErrorCode::ProviderTransport))?
1782 {
1783 if bytes.len().saturating_add(chunk.len()) > MAX_RESPONSE_BYTES {
1784 return Err(bridge_error(BridgeErrorCode::ProviderInvalidResponse));
1785 }
1786 bytes.extend_from_slice(&chunk);
1787 }
1788 String::from_utf8(bytes).map_err(|_| bridge_error(BridgeErrorCode::ProviderInvalidResponse))
1789}
1790
1791fn percent_encode_path_segment(value: &str) -> String {
1792 let mut encoded = String::with_capacity(value.len());
1793 for byte in value.bytes() {
1794 if byte.is_ascii_alphanumeric() || b"-._~".contains(&byte) {
1795 encoded.push(byte as char);
1796 } else {
1797 encoded.push_str(&format!("%{byte:02X}"));
1798 }
1799 }
1800 encoded
1801}
1802
1803pub(crate) fn is_evm_address(value: &str) -> bool {
1804 let bytes = value.as_bytes();
1805 bytes.len() == 42
1806 && bytes[0] == b'0'
1807 && bytes[1] == b'x'
1808 && bytes[2..].iter().all(u8::is_ascii_hexdigit)
1809}
1810
1811fn is_zero_evm_address(value: &str) -> bool {
1812 is_evm_address(value) && value[2..].bytes().all(|byte| byte == b'0')
1813}
1814
1815pub(crate) fn normalize_evm_address(value: &str, code: BridgeErrorCode) -> BridgeResult<String> {
1816 if !is_evm_address(value) || is_zero_evm_address(value) {
1817 return Err(bridge_error(code));
1818 }
1819 Ok(format!("0x{}", value[2..].to_ascii_lowercase()))
1820}
1821
1822pub(crate) fn normalize_positive_uint64(
1823 value: &str,
1824 code: BridgeErrorCode,
1825) -> BridgeResult<(String, u64)> {
1826 if value.is_empty()
1827 || value.len() > UINT64_DECIMAL_MAX_LENGTH
1828 || !value.bytes().all(|byte| byte.is_ascii_digit())
1829 || (value.len() > 1 && value.as_bytes()[0] == b'0')
1830 {
1831 return Err(bridge_error(code));
1832 }
1833 let parsed = value.parse::<u128>().map_err(|_| bridge_error(code))?;
1834 if parsed == 0 || parsed > UINT64_MAX {
1835 return Err(bridge_error(code));
1836 }
1837 Ok((
1838 value.to_owned(),
1839 u64::try_from(parsed).map_err(|_| bridge_error(code))?,
1840 ))
1841}
1842
1843fn normalize_canonical_uint64(value: &str, code: BridgeErrorCode) -> BridgeResult<(String, u64)> {
1844 if value.is_empty()
1845 || value.len() > UINT64_DECIMAL_MAX_LENGTH
1846 || !value.bytes().all(|byte| byte.is_ascii_digit())
1847 || (value.len() > 1 && value.as_bytes()[0] == b'0')
1848 {
1849 return Err(bridge_error(code));
1850 }
1851 let parsed = value.parse::<u128>().map_err(|_| bridge_error(code))?;
1852 if parsed > UINT64_MAX {
1853 return Err(bridge_error(code));
1854 }
1855 Ok((
1856 value.to_owned(),
1857 u64::try_from(parsed).map_err(|_| bridge_error(code))?,
1858 ))
1859}
1860
1861fn normalize_slippage(value: u64, code: BridgeErrorCode) -> BridgeResult<u64> {
1862 if value > 500 {
1863 return Err(bridge_error(code));
1864 }
1865 Ok(value)
1866}
1867
1868fn normalize_quote_request(
1869 request: &MayanSwiftV2QuoteRequest,
1870 _client: &MayanSwiftV2BridgeClient,
1871) -> BridgeResult<(MayanSwiftV2QuoteRequest, DirectionFacts, BridgeCapability)> {
1872 let (amount_in, _) =
1873 normalize_positive_uint64(&request.amount_in, BridgeErrorCode::InvalidArgument)?;
1874 let slippage_bps = normalize_slippage(request.slippage_bps, BridgeErrorCode::InvalidArgument)?;
1875 let facts = direction_facts(
1876 &request.source_chain_id,
1877 &request.destination_chain_id,
1878 &request.source_token_deployment_id,
1879 &request.destination_token_deployment_id,
1880 )?;
1881 validate_catalog_direction(&facts)?;
1882 let capability = find_capability(&facts)?;
1883 Ok((
1884 MayanSwiftV2QuoteRequest {
1885 source_chain_id: request.source_chain_id.clone(),
1886 destination_chain_id: request.destination_chain_id.clone(),
1887 source_token_deployment_id: request.source_token_deployment_id.clone(),
1888 destination_token_deployment_id: request.destination_token_deployment_id.clone(),
1889 amount_in,
1890 slippage_bps,
1891 },
1892 facts,
1893 capability,
1894 ))
1895}
1896
1897fn normalize_chain_address(
1898 value: &str,
1899 chain_id: &str,
1900 code: BridgeErrorCode,
1901) -> BridgeResult<String> {
1902 if chain_id == ETHEREUM_CHAIN_ID {
1903 return normalize_evm_address(value, code);
1904 }
1905 decode_base58(value, 32).map_err(|()| bridge_error(code))?;
1906 Ok(value.to_owned())
1907}
1908
1909fn normalize_status_request(
1910 request: &MayanSwiftV2StatusRequest,
1911) -> BridgeResult<(MayanSwiftV2StatusRequest, String)> {
1912 if request.source_chain_id == ETHEREUM_CHAIN_ID {
1913 let source_transaction_hash = request.source_transaction_hash.as_str();
1914 if !is_evm_hash(source_transaction_hash) {
1915 return Err(bridge_error(BridgeErrorCode::InvalidArgument));
1916 }
1917 return Ok((
1918 request.clone(),
1919 format!("0x{}", source_transaction_hash[2..].to_ascii_lowercase()),
1920 ));
1921 }
1922 if request.source_chain_id == SOLANA_CHAIN_ID {
1923 decode_base58(&request.source_transaction_hash, 64)
1924 .map_err(|()| bridge_error(BridgeErrorCode::InvalidArgument))?;
1925 return Ok((request.clone(), request.source_transaction_hash.clone()));
1926 }
1927 Err(bridge_error(BridgeErrorCode::UnsupportedRoute))
1928}
1929
1930fn is_evm_hash(value: &str) -> bool {
1931 let bytes = value.as_bytes();
1932 bytes.len() == 66
1933 && bytes[0] == b'0'
1934 && bytes[1] == b'x'
1935 && bytes[2..].iter().all(u8::is_ascii_hexdigit)
1936}
1937
1938fn quote_request_body(request: &MayanSwiftV2QuoteRequest, facts: &DirectionFacts) -> String {
1939 format!(
1940 "{{\"fromToken\":{},\"fromChain\":{},\"toToken\":{},\"toChain\":{},\"amountIn64\":{},\"slippageBps\":{},\"swift\":true,\"mctp\":false,\"fastMctp\":false,\"wormhole\":false,\"monoChain\":false,\"gasless\":false,\"fullList\":true,\"guaranteedOutput\":true,\"gasDrop\":0}}",
1941 serde_json::to_string(facts.source_token_address).expect("address serializes"),
1942 serde_json::to_string(facts.source_provider_chain_name).expect("chain serializes"),
1943 serde_json::to_string(facts.destination_token_address).expect("address serializes"),
1944 serde_json::to_string(facts.destination_provider_chain_name).expect("chain serializes"),
1945 serde_json::to_string(&request.amount_in).expect("amount serializes"),
1946 request.slippage_bps,
1947 )
1948}
1949
1950fn build_request_body(
1951 quote: &MayanSwiftV2Quote,
1952 source_chain_id: &str,
1953 swapper_address: &str,
1954 destination_address: &str,
1955 refund_address: Option<&str>,
1956) -> BridgeResult<String> {
1957 let mut params = format!(
1958 "{{\"swapperAddress\":{},\"destinationAddress\":{}",
1959 serde_json::to_string(swapper_address)
1960 .map_err(|_| bridge_error(BridgeErrorCode::InvalidArgument))?,
1961 serde_json::to_string(destination_address)
1962 .map_err(|_| bridge_error(BridgeErrorCode::InvalidArgument))?,
1963 );
1964 if source_chain_id == ETHEREUM_CHAIN_ID {
1965 params.push_str(",\"signerChainId\":1");
1966 }
1967 if let Some(refund_address) = refund_address {
1968 params.push_str(",\"swiftRefundAddress\":");
1969 params.push_str(
1970 &serde_json::to_string(refund_address)
1971 .map_err(|_| bridge_error(BridgeErrorCode::InvalidArgument))?,
1972 );
1973 }
1974 params.push('}');
1975 Ok(format!(
1976 "{{\"quote\":{},\"params\":{}}}",
1977 quote.raw_signed_quote_json, params
1978 ))
1979}
1980
1981pub(crate) fn encode_base58(bytes: &[u8]) -> String {
1982 let zeroes = bytes.iter().take_while(|byte| **byte == 0).count();
1983 if zeroes == bytes.len() {
1984 return "1".repeat(zeroes);
1985 }
1986 let mut digits = vec![0_u8];
1987 for byte in bytes {
1988 let mut carry = u32::from(*byte);
1989 for digit in &mut digits {
1990 let value = u32::from(*digit) * 256 + carry;
1991 *digit = u8::try_from(value % 58).expect("base58 digit is bounded");
1992 carry = value / 58;
1993 }
1994 while carry > 0 {
1995 digits.push(u8::try_from(carry % 58).expect("base58 digit is bounded"));
1996 carry /= 58;
1997 }
1998 }
1999 let mut result = "1".repeat(zeroes);
2000 for digit in digits.iter().rev() {
2001 result.push(BASE58_ALPHABET[usize::from(*digit)] as char);
2002 }
2003 result
2004}
2005
2006pub(crate) fn decode_base58(value: &str, expected_bytes: usize) -> Result<Vec<u8>, ()> {
2007 if value.is_empty() || value.len() > expected_bytes.saturating_mul(2) {
2008 return Err(());
2009 }
2010 let mut bytes = vec![0_u8];
2011 for character in value.bytes() {
2012 let Some(digit) = BASE58_ALPHABET.iter().position(|entry| *entry == character) else {
2013 return Err(());
2014 };
2015 let mut carry = u32::try_from(digit).expect("base58 digit index is bounded");
2016 for byte in &mut bytes {
2017 let current = u32::from(*byte) * 58 + carry;
2018 *byte = u8::try_from(current % 256).expect("base58 byte is bounded");
2019 carry = current / 256;
2020 }
2021 while carry > 0 {
2022 bytes.push(u8::try_from(carry % 256).expect("base58 byte is bounded"));
2023 carry /= 256;
2024 }
2025 }
2026 let zeroes = value.bytes().take_while(|byte| *byte == b'1').count();
2027 let body_len = usize::from(!(bytes.len() == 1 && bytes[0] == 0)) * bytes.len();
2028 let mut result = vec![0_u8; zeroes + body_len];
2029 if body_len > 0 {
2030 for (index, byte) in bytes.iter().enumerate() {
2031 let destination = result.len() - 1 - index;
2032 result[destination] = *byte;
2033 }
2034 }
2035 if result.len() != expected_bytes || encode_base58(&result) != value {
2036 return Err(());
2037 }
2038 Ok(result)
2039}
2040
2041const BASE64_ALPHABET: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
2042
2043fn base64_digit(value: u8) -> Option<u8> {
2044 BASE64_ALPHABET
2045 .iter()
2046 .position(|entry| *entry == value)
2047 .and_then(|value| u8::try_from(value).ok())
2048}
2049
2050pub(crate) fn decode_base64(value: &str) -> Result<Vec<u8>, ()> {
2051 if value.is_empty() || value.len() % 4 != 0 {
2052 return Err(());
2053 }
2054 let bytes = value.as_bytes();
2055 let mut decoded = Vec::with_capacity(value.len() / 4 * 3);
2056 for (group_index, group) in bytes.chunks_exact(4).enumerate() {
2057 let last = group_index + 1 == bytes.len() / 4;
2058 let first = base64_digit(group[0]).ok_or(())?;
2059 let second = base64_digit(group[1]).ok_or(())?;
2060 let third = if group[2] == b'=' {
2061 if !last || group[3] != b'=' {
2062 return Err(());
2063 }
2064 None
2065 } else {
2066 Some(base64_digit(group[2]).ok_or(())?)
2067 };
2068 let fourth = if group[3] == b'=' {
2069 if !last {
2070 return Err(());
2071 }
2072 None
2073 } else {
2074 Some(base64_digit(group[3]).ok_or(())?)
2075 };
2076 decoded.push((first << 2) | (second >> 4));
2077 if let Some(third) = third {
2078 decoded.push((second << 4) | (third >> 2));
2079 if let Some(fourth) = fourth {
2080 decoded.push((third << 6) | fourth);
2081 } else if third & 0x03 != 0 {
2082 return Err(());
2083 }
2084 } else if second & 0x0f != 0 {
2085 return Err(());
2086 }
2087 }
2088 if encode_base64(&decoded) != value {
2089 return Err(());
2090 }
2091 Ok(decoded)
2092}
2093
2094pub(crate) fn encode_base64(bytes: &[u8]) -> String {
2095 let mut encoded = String::with_capacity(bytes.len().div_ceil(3) * 4);
2096 for chunk in bytes.chunks(3) {
2097 let first = chunk[0];
2098 let second = chunk.get(1).copied().unwrap_or(0);
2099 let third = chunk.get(2).copied().unwrap_or(0);
2100 encoded.push(BASE64_ALPHABET[usize::from(first >> 2)] as char);
2101 encoded.push(BASE64_ALPHABET[usize::from(((first << 4) | (second >> 4)) & 0x3f)] as char);
2102 if chunk.len() > 1 {
2103 encoded
2104 .push(BASE64_ALPHABET[usize::from(((second << 2) | (third >> 6)) & 0x3f)] as char);
2105 } else {
2106 encoded.push('=');
2107 }
2108 if chunk.len() > 2 {
2109 encoded.push(BASE64_ALPHABET[usize::from(third & 0x3f)] as char);
2110 } else {
2111 encoded.push('=');
2112 }
2113 }
2114 encoded
2115}
2116
2117struct ByteCursor<'a> {
2118 bytes: &'a [u8],
2119 index: usize,
2120}
2121
2122impl<'a> ByteCursor<'a> {
2123 fn new(bytes: &'a [u8]) -> Self {
2124 Self { bytes, index: 0 }
2125 }
2126
2127 fn read(&mut self, count: usize) -> Result<&'a [u8], ()> {
2128 let end = self.index.checked_add(count).ok_or(())?;
2129 if end > self.bytes.len() {
2130 return Err(());
2131 }
2132 let value = &self.bytes[self.index..end];
2133 self.index = end;
2134 Ok(value)
2135 }
2136
2137 fn byte(&mut self) -> Result<u8, ()> {
2138 Ok(self.read(1)?[0])
2139 }
2140}
2141
2142fn read_short_vec(cursor: &mut ByteCursor<'_>, maximum: usize) -> Result<usize, ()> {
2143 let mut value = 0_usize;
2144 let mut shift = 0_u32;
2145 for count in 0..5 {
2146 let byte = cursor.byte()?;
2147 let payload = usize::from(byte & 0x7f);
2148 if shift >= usize::BITS || payload > (usize::MAX >> shift) {
2149 return Err(());
2150 }
2151 value |= payload << shift;
2152 if byte & 0x80 == 0 {
2153 if count > 0 && payload == 0 {
2154 return Err(());
2155 }
2156 if value > maximum {
2157 return Err(());
2158 }
2159 return Ok(value);
2160 }
2161 shift += 7;
2162 }
2163 Err(())
2164}
2165
2166fn all_zero(bytes: &[u8]) -> bool {
2167 bytes.iter().all(|byte| *byte == 0)
2168}
2169
2170#[allow(clippy::ignored_unit_patterns, clippy::too_many_lines)]
2171fn validate_solana_transaction(encoded: &str, fee_payer: &str) -> BridgeResult<String> {
2172 let bytes = decode_base64(encoded).map_err(|_| bridge_error(BridgeErrorCode::BuildInvalid))?;
2173 if bytes.is_empty() || bytes.len() > 1_232 {
2174 return Err(bridge_error(BridgeErrorCode::BuildInvalid));
2175 }
2176 let mut cursor = ByteCursor::new(&bytes);
2177 let signature_count =
2178 read_short_vec(&mut cursor, 1).map_err(|_| bridge_error(BridgeErrorCode::BuildInvalid))?;
2179 if signature_count != 1
2180 || !all_zero(
2181 cursor
2182 .read(64)
2183 .map_err(|_| bridge_error(BridgeErrorCode::BuildInvalid))?,
2184 )
2185 {
2186 return Err(bridge_error(BridgeErrorCode::BuildInvalid));
2187 }
2188 if cursor
2189 .byte()
2190 .map_err(|_| bridge_error(BridgeErrorCode::BuildInvalid))?
2191 != 0x80
2192 {
2193 return Err(bridge_error(BridgeErrorCode::BuildInvalid));
2194 }
2195 let required_signatures = cursor
2196 .byte()
2197 .map_err(|_| bridge_error(BridgeErrorCode::BuildInvalid))?;
2198 let readonly_signed = cursor
2199 .byte()
2200 .map_err(|_| bridge_error(BridgeErrorCode::BuildInvalid))?;
2201 let readonly_unsigned = cursor
2202 .byte()
2203 .map_err(|_| bridge_error(BridgeErrorCode::BuildInvalid))?;
2204 if required_signatures != 1 || readonly_signed != 0 {
2205 return Err(bridge_error(BridgeErrorCode::BuildInvalid));
2206 }
2207 let static_key_count =
2208 read_short_vec(&mut cursor, 64).map_err(|_| bridge_error(BridgeErrorCode::BuildInvalid))?;
2209 if static_key_count == 0 || usize::from(readonly_unsigned) >= static_key_count {
2210 return Err(bridge_error(BridgeErrorCode::BuildInvalid));
2211 }
2212 let static_keys = cursor
2213 .read(static_key_count * 32)
2214 .map_err(|_| bridge_error(BridgeErrorCode::BuildInvalid))?;
2215 let payer_bytes =
2216 decode_base58(fee_payer, 32).map_err(|_| bridge_error(BridgeErrorCode::BuildInvalid))?;
2217 if static_keys[..32] != payer_bytes[..] {
2218 return Err(bridge_error(BridgeErrorCode::BuildInvalid));
2219 }
2220 cursor
2221 .read(32)
2222 .map_err(|_| bridge_error(BridgeErrorCode::BuildInvalid))?;
2223 let instruction_count =
2224 read_short_vec(&mut cursor, 64).map_err(|_| bridge_error(BridgeErrorCode::BuildInvalid))?;
2225 let mut largest_account_index = None;
2226 for _ in 0..instruction_count {
2227 let program_index = cursor
2228 .byte()
2229 .map_err(|_| bridge_error(BridgeErrorCode::BuildInvalid))?;
2230 largest_account_index =
2231 Some(largest_account_index.map_or(program_index, |value: u8| value.max(program_index)));
2232 let account_count = read_short_vec(&mut cursor, 64)
2233 .map_err(|_| bridge_error(BridgeErrorCode::BuildInvalid))?;
2234 for account_index in cursor
2235 .read(account_count)
2236 .map_err(|_| bridge_error(BridgeErrorCode::BuildInvalid))?
2237 {
2238 largest_account_index = Some(
2239 largest_account_index.map_or(*account_index, |value| value.max(*account_index)),
2240 );
2241 }
2242 let data_length = read_short_vec(&mut cursor, 1_024)
2243 .map_err(|_| bridge_error(BridgeErrorCode::BuildInvalid))?;
2244 cursor
2245 .read(data_length)
2246 .map_err(|_| bridge_error(BridgeErrorCode::BuildInvalid))?;
2247 }
2248 let lookup_count =
2249 read_short_vec(&mut cursor, 32).map_err(|_| bridge_error(BridgeErrorCode::BuildInvalid))?;
2250 let mut loaded_address_count = 0_usize;
2251 for _ in 0..lookup_count {
2252 cursor
2253 .read(32)
2254 .map_err(|_| bridge_error(BridgeErrorCode::BuildInvalid))?;
2255 let writable_count = read_short_vec(&mut cursor, 64)
2256 .map_err(|_| bridge_error(BridgeErrorCode::BuildInvalid))?;
2257 cursor
2258 .read(writable_count)
2259 .map_err(|_| bridge_error(BridgeErrorCode::BuildInvalid))?;
2260 let readonly_count = read_short_vec(&mut cursor, 64)
2261 .map_err(|_| bridge_error(BridgeErrorCode::BuildInvalid))?;
2262 cursor
2263 .read(readonly_count)
2264 .map_err(|_| bridge_error(BridgeErrorCode::BuildInvalid))?;
2265 loaded_address_count = loaded_address_count
2266 .checked_add(writable_count + readonly_count)
2267 .ok_or_else(|| bridge_error(BridgeErrorCode::BuildInvalid))?;
2268 if loaded_address_count > 256 {
2269 return Err(bridge_error(BridgeErrorCode::BuildInvalid));
2270 }
2271 }
2272 if largest_account_index
2273 .is_some_and(|index| usize::from(index) >= static_key_count + loaded_address_count)
2274 || cursor.index != bytes.len()
2275 {
2276 return Err(bridge_error(BridgeErrorCode::BuildInvalid));
2277 }
2278 Ok(encoded.to_owned())
2279}
2280
2281fn provider_invalid<T>() -> BridgeResult<T> {
2282 Err(bridge_error(BridgeErrorCode::ProviderInvalidResponse))
2283}
2284
2285fn provider_string(node: &JsonNode, key: &str, allow_empty: bool) -> BridgeResult<String> {
2286 let value = object_value(node, key)
2287 .ok_or_else(|| bridge_error(BridgeErrorCode::ProviderInvalidResponse))?;
2288 let Some(value) = value.as_str() else {
2289 return provider_invalid();
2290 };
2291 if !allow_empty && value.is_empty() {
2292 return provider_invalid();
2293 }
2294 Ok(value.to_owned())
2295}
2296
2297fn provider_bool(node: &JsonNode, key: &str) -> BridgeResult<bool> {
2298 let value = object_value(node, key)
2299 .ok_or_else(|| bridge_error(BridgeErrorCode::ProviderInvalidResponse))?;
2300 value
2301 .as_bool()
2302 .ok_or_else(|| bridge_error(BridgeErrorCode::ProviderInvalidResponse))
2303}
2304
2305fn provider_number(node: &JsonNode, key: &str) -> BridgeResult<f64> {
2306 let value = object_value(node, key)
2307 .ok_or_else(|| bridge_error(BridgeErrorCode::ProviderInvalidResponse))?;
2308 let Some(number) = value.as_number() else {
2309 return provider_invalid();
2310 };
2311 let Some(number) = number.as_f64() else {
2312 return provider_invalid();
2313 };
2314 if !number.is_finite() {
2315 return provider_invalid();
2316 }
2317 Ok(number)
2318}
2319
2320fn provider_integer(node: &JsonNode, key: &str) -> BridgeResult<i64> {
2321 let number = provider_number(node, key)?;
2322 if let Some(value) = object_value(node, key)
2323 .and_then(Value::as_number)
2324 .and_then(serde_json::Number::as_i64)
2325 {
2326 return Ok(value);
2327 }
2328 if let Some(value) = object_value(node, key)
2329 .and_then(Value::as_number)
2330 .and_then(serde_json::Number::as_u64)
2331 {
2332 return i64::try_from(value)
2333 .map_err(|_| bridge_error(BridgeErrorCode::ProviderInvalidResponse));
2334 }
2335 #[allow(clippy::cast_precision_loss, clippy::cast_possible_truncation)]
2336 {
2337 if number.fract() != 0.0 || number < i64::MIN as f64 || number > i64::MAX as f64 {
2338 return provider_invalid();
2339 }
2340 Ok(number as i64)
2341 }
2342}
2343
2344fn provider_address(node: &JsonNode, key: &str, expected: &str) -> BridgeResult<String> {
2345 let value = provider_string(node, key, false)?;
2346 let matches = if is_evm_address(expected) {
2347 is_evm_address(&value) && value.eq_ignore_ascii_case(expected)
2348 } else {
2349 value == expected
2350 };
2351 if !matches {
2352 return provider_invalid();
2353 }
2354 if is_evm_address(&value) {
2355 Ok(format!("0x{}", &value[2..].to_ascii_lowercase()))
2356 } else {
2357 Ok(value)
2358 }
2359}
2360
2361fn provider_uint64(node: &JsonNode, key: &str, positive: bool) -> BridgeResult<(String, u64)> {
2362 let value = provider_string(node, key, false)?;
2363 if positive {
2364 normalize_positive_uint64(&value, BridgeErrorCode::ProviderInvalidResponse)
2365 } else {
2366 normalize_canonical_uint64(&value, BridgeErrorCode::ProviderInvalidResponse)
2367 }
2368}
2369
2370fn provider_token(
2371 node: &JsonNode,
2372 expected_address: &str,
2373 expected_standard: &str,
2374 expected_chain_id: i64,
2375 expected_wormhole_chain_id: i64,
2376 expected_mint: &str,
2377 expected_name: &str,
2378) -> BridgeResult<()> {
2379 if !matches!(node.value, Value::Object(_)) {
2380 return provider_invalid();
2381 }
2382 provider_address(node, "contract", expected_address)?;
2383 let mint = provider_string(node, "mint", true)?;
2384 if mint != expected_mint {
2385 return provider_invalid();
2386 }
2387 provider_address(node, "realOriginContractAddress", expected_address)?;
2388 if provider_string(node, "name", false)? != expected_name {
2389 return provider_invalid();
2390 }
2391 if provider_string(node, "standard", false)? != expected_standard {
2392 return provider_invalid();
2393 }
2394 if provider_integer(node, "chainId")? != expected_chain_id
2395 || provider_integer(node, "wChainId")? != expected_wormhole_chain_id
2396 || provider_integer(node, "realOriginChainId")? != expected_wormhole_chain_id
2397 || provider_integer(node, "decimals")? != 6
2398 {
2399 return provider_invalid();
2400 }
2401 Ok(())
2402}
2403
2404fn quote_provider_standard(facts: &DirectionFacts) -> &'static str {
2405 if facts.source_chain_id == ETHEREUM_CHAIN_ID {
2406 "erc20"
2407 } else {
2408 "spl"
2409 }
2410}
2411
2412fn ensure_quote_deadline(
2413 deadline: &str,
2414 margin: u64,
2415 client: &MayanSwiftV2BridgeClient,
2416) -> BridgeResult<()> {
2417 let (_, deadline) = normalize_positive_uint64(deadline, BridgeErrorCode::QuoteExpired)?;
2418 let now = client.now_seconds()?;
2419 let minimum = now
2420 .checked_add(margin)
2421 .ok_or_else(|| bridge_error(BridgeErrorCode::QuoteExpired))?;
2422 if deadline < minimum {
2423 return Err(bridge_error(BridgeErrorCode::QuoteExpired));
2424 }
2425 Ok(())
2426}
2427
2428struct ValidatedProviderQuote {
2429 quote: MayanSwiftV2Quote,
2430}
2431
2432#[allow(clippy::too_many_lines)]
2433fn validate_provider_quote(
2434 node: &JsonNode,
2435 response: &ProviderResponse,
2436 request: &MayanSwiftV2QuoteRequest,
2437 facts: &DirectionFacts,
2438 client: &MayanSwiftV2BridgeClient,
2439) -> BridgeResult<ValidatedProviderQuote> {
2440 if !matches!(node.value, Value::Object(_)) {
2441 return provider_invalid();
2442 }
2443 let raw = response
2444 .text
2445 .get(node.start..node.end)
2446 .ok_or_else(|| bridge_error(BridgeErrorCode::ProviderInvalidResponse))?;
2447 if raw.len() > MAX_RAW_QUOTE_BYTES {
2448 return provider_invalid();
2449 }
2450 if provider_string(node, "type", false)? != "SWIFT"
2451 || provider_string(node, "swiftVersion", false)? != "V2"
2452 || provider_bool(node, "gasless")?
2453 {
2454 return provider_invalid();
2455 }
2456 if provider_string(node, "fromChain", false)? != facts.source_provider_chain_name
2457 || provider_string(node, "toChain", false)? != facts.destination_provider_chain_name
2458 || provider_integer(node, "slippageBps")?
2459 != i64::try_from(request.slippage_bps).expect("bridge slippage is bounded")
2460 || provider_bool(node, "onlyBridging")?
2461 {
2462 return provider_invalid();
2463 }
2464 let effective_amount = provider_uint64(node, "effectiveAmountIn64", true)?;
2465 if effective_amount.0 != request.amount_in {
2466 return provider_invalid();
2467 }
2468 let expected_amount_out = provider_uint64(node, "expectedAmountOutBaseUnits", true)?;
2469 let minimum_amount_out = provider_uint64(node, "minAmountOutBaseUnits", true)?;
2470 let minimum_received = provider_uint64(node, "minReceivedBaseUnits", true)?;
2471 if minimum_amount_out.1 > expected_amount_out.1 || minimum_received.1 > minimum_amount_out.1 {
2472 return provider_invalid();
2473 }
2474 let deadline = provider_uint64(node, "deadline64", true)?;
2475 ensure_quote_deadline(
2476 &deadline.0,
2477 client.config.minimum_quote_validity_seconds,
2478 client,
2479 )?;
2480
2481 let source_token = required_node(node, "fromToken")?;
2482 let destination_token = required_node(node, "toToken")?;
2483 provider_token(
2484 source_token,
2485 facts.source_token_address,
2486 if facts.source_chain_id == ETHEREUM_CHAIN_ID {
2487 "erc20"
2488 } else {
2489 "spl"
2490 },
2491 i64::from(facts.source_provider_chain_id),
2492 i64::from(facts.source_wormhole_chain_id),
2493 facts.source_token_mint,
2494 facts.source_token_name,
2495 )?;
2496 provider_token(
2497 destination_token,
2498 facts.destination_token_address,
2499 if facts.destination_chain_id == ETHEREUM_CHAIN_ID {
2500 "erc20"
2501 } else {
2502 "spl"
2503 },
2504 i64::from(facts.destination_provider_chain_id),
2505 i64::from(facts.destination_wormhole_chain_id),
2506 facts.destination_token_mint,
2507 facts.destination_token_name,
2508 )?;
2509
2510 let provider_standard = quote_provider_standard(facts);
2511 provider_address(node, "swiftInputContract", facts.source_usdc_address)?;
2512 if provider_string(node, "swiftInputContractStandard", false)? != provider_standard
2513 || provider_integer(node, "swiftInputDecimals")? != 6
2514 {
2515 return provider_invalid();
2516 }
2517 provider_address(node, "swiftMayanContract", facts.swift_contract)?;
2518
2519 let middle_node = required_node(node, "minMiddleAmount")?;
2520 if middle_node.raw_number.is_none()
2521 || !middle_node
2522 .value
2523 .as_number()
2524 .and_then(serde_json::Number::as_f64)
2525 .is_some_and(|value| value.is_finite() && value > 0.0)
2526 {
2527 return provider_invalid();
2528 }
2529 let provider_minimum_amount = middle_node
2530 .raw_number
2531 .clone()
2532 .ok_or_else(|| bridge_error(BridgeErrorCode::ProviderInvalidResponse))?;
2533
2534 let (router_kind, router_address) = if !facts.source_swap_required {
2535 if let Some(value) = object_value(node, "evmSwapRouterAddress") {
2536 if !value.is_null() {
2537 return provider_invalid();
2538 }
2539 }
2540 (None, None)
2541 } else if facts.source_chain_id == ETHEREUM_CHAIN_ID {
2542 (
2543 Some("provider-selected-evm".to_owned()),
2544 Some(normalize_evm_address(
2545 &provider_string(node, "evmSwapRouterAddress", false)?,
2546 BridgeErrorCode::ProviderInvalidResponse,
2547 )?),
2548 )
2549 } else {
2550 if let Some(value) = object_value(node, "evmSwapRouterAddress") {
2551 if !value.is_null() {
2552 return provider_invalid();
2553 }
2554 }
2555 (
2556 Some("jupiter-v6".to_owned()),
2557 Some(SOLANA_JUPITER_V6.to_owned()),
2558 )
2559 };
2560 let quote_id = provider_string(node, "quoteId", false)?;
2561 if !is_hex_text("e_id, 32) {
2562 return provider_invalid();
2563 }
2564 let signature = provider_string(node, "signature", false)?;
2565 if !is_hex_text(&signature, 130) {
2566 return provider_invalid();
2567 }
2568 Ok(ValidatedProviderQuote {
2569 quote: MayanSwiftV2Quote {
2570 quote_kind: "mayan-swift-v2".to_owned(),
2571 provider_id: "mayan-swift-v2".to_owned(),
2572 source_chain_id: request.source_chain_id.clone(),
2573 destination_chain_id: request.destination_chain_id.clone(),
2574 source_token_deployment_id: facts.source_token_deployment_id.to_owned(),
2575 destination_token_deployment_id: facts.destination_token_deployment_id.to_owned(),
2576 amount_in: effective_amount.0,
2577 expected_amount_out: expected_amount_out.0,
2578 minimum_amount_out: minimum_amount_out.0,
2579 minimum_received: minimum_received.0,
2580 deadline: deadline.0,
2581 slippage_bps: request.slippage_bps,
2582 quote_id: quote_id.to_ascii_lowercase(),
2583 provider_signature: signature.to_ascii_lowercase(),
2584 source_swap: MayanSwiftV2SourceSwap {
2585 required: facts.source_swap_required,
2586 input_token_deployment_id: if facts.source_swap_required {
2587 facts.source_token_deployment_id.to_owned()
2588 } else {
2589 facts.source_usdc_deployment_id.to_owned()
2590 },
2591 intermediate_token_deployment_id: facts.source_usdc_deployment_id.to_owned(),
2592 intermediate_token_address: facts.source_usdc_address.to_owned(),
2593 intermediate_token_standard: provider_standard.to_owned(),
2594 intermediate_token_decimals: 6,
2595 provider_minimum_amount,
2596 router_kind,
2597 router_address,
2598 },
2599 dependencies: expected_dependencies(facts),
2600 quote_verification: "provider-signed-not-locally-verified".to_owned(),
2601 raw_signed_quote_json: raw.to_owned(),
2602 },
2603 })
2604}
2605
2606fn is_hex_text(value: &str, digits: usize) -> bool {
2607 value.len() == digits + 2
2608 && value.as_bytes().first() == Some(&b'0')
2609 && value.as_bytes().get(1) == Some(&b'x')
2610 && value.as_bytes()[2..].iter().all(u8::is_ascii_hexdigit)
2611}
2612
2613fn quote_from_response(
2614 response: &ProviderResponse,
2615 request: &MayanSwiftV2QuoteRequest,
2616 facts: &DirectionFacts,
2617 capability: &BridgeCapability,
2618 client: &MayanSwiftV2BridgeClient,
2619) -> BridgeResult<Vec<MayanSwiftV2Quote>> {
2620 if !matches!(response.root.value, Value::Object(_))
2621 || object_value(&response.root, "success") != Some(&Value::Bool(true))
2622 {
2623 return provider_invalid();
2624 }
2625 let quotes = required_node(&response.root, "quotes")?;
2626 let Some(quote_nodes) = quotes.array_items.as_ref() else {
2627 return provider_invalid();
2628 };
2629 if quote_nodes.len() > MAX_QUOTES {
2630 return provider_invalid();
2631 }
2632 let mut selected = Vec::new();
2633 for quote_node in quote_nodes {
2634 if !matches!(quote_node.value, Value::Object(_)) {
2635 continue;
2636 }
2637 if object_value(quote_node, "type").and_then(Value::as_str) != Some("SWIFT")
2638 || object_value(quote_node, "swiftVersion").and_then(Value::as_str) != Some("V2")
2639 || object_value(quote_node, "gasless") != Some(&Value::Bool(false))
2640 {
2641 continue;
2642 }
2643 selected.push(validate_provider_quote(quote_node, response, request, facts, client)?.quote);
2644 }
2645 if selected.is_empty() {
2646 return Err(bridge_error(BridgeErrorCode::QuoteUnavailable));
2647 }
2648 let _ = capability;
2649 Ok(selected)
2650}
2651
2652#[allow(clippy::too_many_lines)]
2653pub(crate) fn validate_normalized_quote_shape(
2654 quote: &MayanSwiftV2Quote,
2655) -> BridgeResult<(MayanSwiftV2Quote, DirectionFacts)> {
2656 if quote.quote_kind != "mayan-swift-v2"
2657 || quote.provider_id != "mayan-swift-v2"
2658 || quote.quote_verification != "provider-signed-not-locally-verified"
2659 {
2660 return Err(bridge_error(BridgeErrorCode::QuoteMismatch));
2661 }
2662 let facts = direction_facts(
2663 "e.source_chain_id,
2664 "e.destination_chain_id,
2665 "e.source_token_deployment_id,
2666 "e.destination_token_deployment_id,
2667 )
2668 .map_err(|_| bridge_error(BridgeErrorCode::QuoteMismatch))?;
2669 let (amount_in, _) =
2670 normalize_positive_uint64("e.amount_in, BridgeErrorCode::QuoteMismatch)?;
2671 let (expected_amount_out, expected_amount_out_value) =
2672 normalize_positive_uint64("e.expected_amount_out, BridgeErrorCode::QuoteMismatch)?;
2673 let (minimum_amount_out, minimum_amount_out_value) =
2674 normalize_positive_uint64("e.minimum_amount_out, BridgeErrorCode::QuoteMismatch)?;
2675 let (minimum_received, minimum_received_value) =
2676 normalize_positive_uint64("e.minimum_received, BridgeErrorCode::QuoteMismatch)?;
2677 if minimum_amount_out_value > expected_amount_out_value
2678 || minimum_received_value > minimum_amount_out_value
2679 {
2680 return Err(bridge_error(BridgeErrorCode::QuoteMismatch));
2681 }
2682 let (deadline, _) = normalize_positive_uint64("e.deadline, BridgeErrorCode::QuoteMismatch)?;
2683 normalize_slippage(quote.slippage_bps, BridgeErrorCode::QuoteMismatch)?;
2684 if !is_hex_text("e.quote_id, 32) || !is_hex_text("e.provider_signature, 130) {
2685 return Err(bridge_error(BridgeErrorCode::QuoteMismatch));
2686 }
2687 let source_swap = "e.source_swap;
2688 if source_swap.required != facts.source_swap_required
2689 || source_swap.input_token_deployment_id
2690 != if facts.source_swap_required {
2691 facts.source_token_deployment_id
2692 } else {
2693 facts.source_usdc_deployment_id
2694 }
2695 || source_swap.intermediate_token_deployment_id != facts.source_usdc_deployment_id
2696 || source_swap.intermediate_token_address != facts.source_usdc_address
2697 || source_swap.intermediate_token_standard != quote_provider_standard(&facts)
2698 || source_swap.intermediate_token_decimals != 6
2699 || source_swap.provider_minimum_amount.is_empty()
2700 {
2701 return Err(bridge_error(BridgeErrorCode::QuoteMismatch));
2702 }
2703 let (router_kind, router_address) = if !facts.source_swap_required {
2704 if source_swap.router_kind.is_some() || source_swap.router_address.is_some() {
2705 return Err(bridge_error(BridgeErrorCode::QuoteMismatch));
2706 }
2707 (None, None)
2708 } else if facts.source_chain_id == ETHEREUM_CHAIN_ID {
2709 if source_swap.router_kind.as_deref() != Some("provider-selected-evm") {
2710 return Err(bridge_error(BridgeErrorCode::QuoteMismatch));
2711 }
2712 (
2713 Some("provider-selected-evm".to_owned()),
2714 Some(normalize_evm_address(
2715 source_swap.router_address.as_deref().unwrap_or_default(),
2716 BridgeErrorCode::QuoteMismatch,
2717 )?),
2718 )
2719 } else {
2720 if source_swap.router_kind.as_deref() != Some("jupiter-v6")
2721 || source_swap.router_address.as_deref() != Some(SOLANA_JUPITER_V6)
2722 {
2723 return Err(bridge_error(BridgeErrorCode::QuoteMismatch));
2724 }
2725 (
2726 Some("jupiter-v6".to_owned()),
2727 Some(SOLANA_JUPITER_V6.to_owned()),
2728 )
2729 };
2730 if quote.dependencies != expected_dependencies(&facts) {
2731 return Err(bridge_error(BridgeErrorCode::QuoteMismatch));
2732 }
2733 if quote.raw_signed_quote_json.is_empty()
2734 || quote.raw_signed_quote_json.len() > MAX_RAW_QUOTE_BYTES
2735 {
2736 return Err(bridge_error(BridgeErrorCode::QuoteMismatch));
2737 }
2738 let normalized = MayanSwiftV2Quote {
2739 quote_kind: "mayan-swift-v2".to_owned(),
2740 provider_id: "mayan-swift-v2".to_owned(),
2741 source_chain_id: quote.source_chain_id.clone(),
2742 destination_chain_id: quote.destination_chain_id.clone(),
2743 source_token_deployment_id: facts.source_token_deployment_id.to_owned(),
2744 destination_token_deployment_id: facts.destination_token_deployment_id.to_owned(),
2745 amount_in,
2746 expected_amount_out,
2747 minimum_amount_out,
2748 minimum_received,
2749 deadline,
2750 slippage_bps: quote.slippage_bps,
2751 quote_id: quote.quote_id.to_ascii_lowercase(),
2752 provider_signature: quote.provider_signature.to_ascii_lowercase(),
2753 source_swap: MayanSwiftV2SourceSwap {
2754 required: facts.source_swap_required,
2755 input_token_deployment_id: if facts.source_swap_required {
2756 facts.source_token_deployment_id.to_owned()
2757 } else {
2758 facts.source_usdc_deployment_id.to_owned()
2759 },
2760 intermediate_token_deployment_id: facts.source_usdc_deployment_id.to_owned(),
2761 intermediate_token_address: facts.source_usdc_address.to_owned(),
2762 intermediate_token_standard: quote_provider_standard(&facts).to_owned(),
2763 intermediate_token_decimals: 6,
2764 provider_minimum_amount: quote.source_swap.provider_minimum_amount.clone(),
2765 router_kind,
2766 router_address,
2767 },
2768 dependencies: expected_dependencies(&facts),
2769 quote_verification: "provider-signed-not-locally-verified".to_owned(),
2770 raw_signed_quote_json: quote.raw_signed_quote_json.clone(),
2771 };
2772 Ok((normalized, facts))
2773}
2774
2775pub(crate) fn validate_raw_quote_for_build(
2776 quote: &MayanSwiftV2Quote,
2777 request: &MayanSwiftV2QuoteRequest,
2778 facts: &DirectionFacts,
2779 client: &MayanSwiftV2BridgeClient,
2780) -> BridgeResult<MayanSwiftV2Quote> {
2781 let (normalized, _) = validate_normalized_quote_shape(quote)?;
2782 if normalized.source_chain_id != request.source_chain_id
2783 || normalized.destination_chain_id != request.destination_chain_id
2784 || normalized.amount_in != request.amount_in
2785 || normalized.slippage_bps != request.slippage_bps
2786 {
2787 return Err(bridge_error(BridgeErrorCode::QuoteMismatch));
2788 }
2789 let response = parse_provider_response(quote.raw_signed_quote_json.clone())
2790 .map_err(|_| bridge_error(BridgeErrorCode::QuoteMismatch))?;
2791 if response.root.start != 0 || response.root.end != response.text.len() {
2792 return Err(bridge_error(BridgeErrorCode::QuoteMismatch));
2793 }
2794 let validated = match validate_provider_quote(&response.root, &response, request, facts, client)
2795 {
2796 Ok(value) => value.quote,
2797 Err(error) if error.code() == BridgeErrorCode::QuoteExpired => return Err(error),
2798 Err(_) => return Err(bridge_error(BridgeErrorCode::QuoteMismatch)),
2799 };
2800 if validated != normalized {
2801 return Err(bridge_error(BridgeErrorCode::QuoteMismatch));
2802 }
2803 Ok(normalized)
2804}
2805
2806fn numeric_zero(value: Option<&Value>) -> bool {
2807 match value {
2808 Some(Value::Number(value)) => value.as_f64().is_some_and(|number| number == 0.0),
2809 Some(Value::String(value)) if value == "0" => true,
2810 Some(Value::String(value)) => {
2811 let bytes = value.as_bytes();
2812 bytes.len() >= 3
2813 && bytes[0] == b'0'
2814 && bytes[1] == b'x'
2815 && bytes[2..].iter().all(|byte| *byte == b'0')
2816 }
2817 _ => false,
2818 }
2819}
2820
2821fn hex_bytes(value: &str) -> bool {
2822 value.len() >= 2
2823 && value.as_bytes()[0] == b'0'
2824 && value.as_bytes()[1] == b'x'
2825 && (value.len() - 2) % 2 == 0
2826 && value.as_bytes()[2..].iter().all(u8::is_ascii_hexdigit)
2827}
2828
2829fn validate_evm_build_result(
2830 wrapper: &JsonNode,
2831 swapper_address: &str,
2832 facts: &DirectionFacts,
2833) -> BridgeResult<MayanSwiftV2UnsignedTransaction> {
2834 if provider_string(wrapper, "chainCategory", false)? != "evm"
2835 || provider_string(wrapper, "quoteType", false)? != "SWIFT"
2836 || provider_bool(wrapper, "gasless")?
2837 {
2838 return Err(bridge_error(BridgeErrorCode::BuildInvalid));
2839 }
2840 let transaction = required_node(wrapper, "transaction")?;
2841 if !matches!(transaction.value, Value::Object(_)) {
2842 return Err(bridge_error(BridgeErrorCode::BuildInvalid));
2843 }
2844 let to = provider_address(transaction, "to", ETHEREUM_FORWARDER)
2845 .map_err(|_| bridge_error(BridgeErrorCode::BuildInvalid))?;
2846 if provider_integer(transaction, "chainId")? != 1
2847 || !numeric_zero(object_value(transaction, "value"))
2848 {
2849 return Err(bridge_error(BridgeErrorCode::BuildInvalid));
2850 }
2851 let data = provider_string(transaction, "data", false)?.to_ascii_lowercase();
2852 let selector = expected_forwarder_selector(facts)
2853 .ok_or_else(|| bridge_error(BridgeErrorCode::BuildInvalid))?;
2854 let minimum_words = if facts.asset == BridgeAsset::Usdc {
2855 10
2856 } else {
2857 13
2858 };
2859 if !hex_bytes(&data) || !data.starts_with(selector) || data.len() < 2 + 8 + minimum_words * 64 {
2860 return Err(bridge_error(BridgeErrorCode::BuildInvalid));
2861 }
2862 Ok(MayanSwiftV2UnsignedTransaction::Evm(
2863 MayanEvmUnsignedTransaction {
2864 kind: "evm-unsigned-transaction".to_owned(),
2865 chain_id: ETHEREUM_CHAIN_ID.to_owned(),
2866 from: swapper_address.to_owned(),
2867 to,
2868 data,
2869 value: "0".to_owned(),
2870 },
2871 ))
2872}
2873
2874fn validate_solana_build_result(
2875 wrapper: &JsonNode,
2876 swapper_address: &str,
2877) -> BridgeResult<MayanSwiftV2UnsignedTransaction> {
2878 if provider_string(wrapper, "chainCategory", false)? != "svm"
2879 || provider_string(wrapper, "quoteType", false)? != "SWIFT"
2880 {
2881 return Err(bridge_error(BridgeErrorCode::BuildInvalid));
2882 }
2883 if let Some(gasless) = object_value(wrapper, "gasless") {
2884 if !gasless.is_null() && gasless != &Value::Bool(false) {
2885 return Err(bridge_error(BridgeErrorCode::BuildInvalid));
2886 }
2887 }
2888 let encoded = provider_string(wrapper, "transaction", false)?;
2889 let encoded = validate_solana_transaction(&encoded, swapper_address)?;
2890 Ok(MayanSwiftV2UnsignedTransaction::Solana(
2891 MayanSolanaUnsignedTransaction {
2892 kind: "solana-v0-unsigned-transaction".to_owned(),
2893 chain_id: SOLANA_CHAIN_ID.to_owned(),
2894 fee_payer: swapper_address.to_owned(),
2895 transaction_base64: encoded,
2896 },
2897 ))
2898}
2899
2900fn validate_build_response(
2901 response: &ProviderResponse,
2902 quote: &MayanSwiftV2Quote,
2903 facts: &DirectionFacts,
2904 swapper_address: &str,
2905) -> BridgeResult<MayanSwiftV2Build> {
2906 if object_value(&response.root, "success") != Some(&Value::Bool(true)) {
2907 return Err(bridge_error(BridgeErrorCode::BuildInvalid));
2908 }
2909 let wrapper = required_node(&response.root, "transaction")?;
2910 if !matches!(wrapper.value, Value::Object(_)) {
2911 return Err(bridge_error(BridgeErrorCode::BuildInvalid));
2912 }
2913 if let Some(signers) = object_value(wrapper, "signers") {
2914 if !signers.is_null() && (!signers.as_array().is_some_and(Vec::is_empty)) {
2915 return Err(bridge_error(BridgeErrorCode::BuildInvalid));
2916 }
2917 }
2918 if let Some(swap_message) = object_value(wrapper, "swapMessageV0Params") {
2919 if !swap_message.is_null() {
2920 return Err(bridge_error(BridgeErrorCode::BuildInvalid));
2921 }
2922 }
2923 let transaction = if facts.source_chain_id == ETHEREUM_CHAIN_ID {
2924 validate_evm_build_result(wrapper, swapper_address, facts)?
2925 } else {
2926 validate_solana_build_result(wrapper, swapper_address)?
2927 };
2928 let allowance = if facts.source_chain_id == ETHEREUM_CHAIN_ID {
2929 Some(MayanSwiftV2Allowance {
2930 token_deployment_id: facts.source_token_deployment_id.to_owned(),
2931 token_address: facts.source_token_address.to_owned(),
2932 owner: swapper_address.to_owned(),
2933 spender: ETHEREUM_FORWARDER.to_owned(),
2934 required_amount: quote.amount_in.clone(),
2935 })
2936 } else {
2937 None
2938 };
2939 Ok(MayanSwiftV2Build {
2940 build_kind: "mayan-swift-v2-unsigned".to_owned(),
2941 provider_id: "mayan-swift-v2".to_owned(),
2942 quote: quote.clone(),
2943 source_chain_id: quote.source_chain_id.clone(),
2944 destination_chain_id: quote.destination_chain_id.clone(),
2945 transaction,
2946 allowance,
2947 validation: MayanSwiftV2BuildValidation {
2948 level: "structural".to_owned(),
2949 quote_signature_locally_verified: false,
2950 transaction_semantics_locally_verified: false,
2951 settlement_locally_verified: false,
2952 },
2953 raw_provider_build_json: response.text.clone(),
2954 })
2955}
2956
2957fn status_from_response(
2958 response: &ProviderResponse,
2959 request: &(MayanSwiftV2StatusRequest, String),
2960) -> BridgeResult<MayanSwiftV2Status> {
2961 if !matches!(response.root.value, Value::Object(_)) {
2962 return provider_invalid();
2963 }
2964 let provider_client_status = provider_string(&response.root, "clientStatus", false)?;
2965 if provider_client_status.len() > 128 {
2966 return provider_invalid();
2967 }
2968 let provider_status = match object_value(&response.root, "status") {
2969 None | Some(Value::Null) => None,
2970 Some(Value::String(value)) if value.len() <= 1024 => Some(value.clone()),
2971 _ => return provider_invalid(),
2972 };
2973 let state = match provider_client_status.as_str() {
2974 "INPROGRESS" => "in-progress",
2975 "COMPLETED" => "completed",
2976 "REFUNDED" => "refunded",
2977 _ => "unknown",
2978 };
2979 Ok(MayanSwiftV2Status {
2980 status_kind: "mayan-explorer-index".to_owned(),
2981 provider_id: "mayan-swift-v2".to_owned(),
2982 source_chain_id: request.0.source_chain_id.clone(),
2983 source_transaction_hash: request.1.clone(),
2984 state: state.to_owned(),
2985 provider_client_status,
2986 provider_status,
2987 status_verification: "provider-indexed-not-locally-verified".to_owned(),
2988 raw_provider_status_json: response.text.clone(),
2989 })
2990}
2991
2992#[cfg(test)]
2993mod tests {
2994 use super::*;
2995 use std::{env, fs, path::Path};
2996
2997 use serde_json::{Map, json};
2998 use tokio::{
2999 io::{AsyncReadExt, AsyncWriteExt},
3000 net::{TcpListener, TcpStream},
3001 task::JoinHandle,
3002 };
3003
3004 const FIXTURE: &str = include_str!("../../../registry/fixtures/mayan-swift-v2-cases.json");
3005 const LOCAL_FIXTURE: &str =
3006 include_str!("../../../registry/fixtures/mayan-swift-v2-local-build-cases.json");
3007 const FIXED_CLOCK: u64 = 1_789_600_000;
3008 const FROZEN_LEGACY_FIXTURE_CASE_IDS: &[&str] = &[
3009 "quote-eth-sol-synthetic",
3010 "quote-sol-eth-synthetic",
3011 "build-eth-sol-synthetic",
3012 "build-sol-eth-synthetic",
3013 "status-eth-inprogress-synthetic",
3014 "status-eth-completed-synthetic",
3015 "status-sol-refunded-synthetic",
3016 "status-sol-unknown-synthetic",
3017 "status-eth-not-found-synthetic",
3018 "quote-duplicate-key",
3019 "quote-malformed-json",
3020 "quote-expired",
3021 "quote-mismatched-amount",
3022 "quote-bad-signature-shape",
3023 "quote-json-depth-limit",
3024 "quote-body-size-limit",
3025 "quote-unsupported-route",
3026 "build-auth-required-local",
3027 "build-quote-mismatch",
3028 "build-evm-forwarder-violation",
3029 "build-evm-selector-violation",
3030 "build-evm-value-violation",
3031 "build-solana-framing-violation",
3032 "build-solana-fee-payer-violation",
3033 "build-solana-extra-signer-violation",
3034 "build-solana-swap-message-violation",
3035 "build-http-auth-401",
3036 "build-http-rate-limit-429",
3037 "quote-redirect-rejected",
3038 "quote-timeout",
3039 "quote-aborted",
3040 "status-invalid-evm-hash",
3041 "status-invalid-provider-fields",
3042 "build-eth-sol-wrong-evm-destination",
3043 "build-sol-eth-wrong-solana-destination",
3044 "quote-eth-sol-zero-validity-margin",
3045 ];
3046
3047 fn fixture_value() -> Value {
3048 serde_json::from_str(FIXTURE).expect("bridge fixture is valid JSON")
3049 }
3050
3051 fn fixture_case<'a>(fixture: &'a Value, case_id: &str) -> &'a Value {
3052 fixture["cases"]
3053 .as_array()
3054 .expect("bridge fixture cases")
3055 .iter()
3056 .find(|case| case["caseId"].as_str() == Some(case_id))
3057 .expect("bridge fixture case")
3058 }
3059
3060 fn fixed_clock() -> u64 {
3061 FIXED_CLOCK
3062 }
3063
3064 #[allow(
3065 clippy::format_collect,
3066 clippy::many_single_char_names,
3067 clippy::unreadable_literal
3068 )]
3069 fn sha256_hex(input: &[u8]) -> String {
3070 const K: [u32; 64] = [
3071 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4,
3072 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe,
3073 0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f,
3074 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7,
3075 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc,
3076 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b,
3077 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, 0x19a4c116,
3078 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
3079 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7,
3080 0xc67178f2,
3081 ];
3082 let mut message = input.to_vec();
3083 let bit_length = u64::try_from(message.len())
3084 .expect("fixture length fits u64")
3085 .saturating_mul(8);
3086 message.push(0x80);
3087 while message.len() % 64 != 56 {
3088 message.push(0);
3089 }
3090 message.extend_from_slice(&bit_length.to_be_bytes());
3091
3092 let mut hash = [
3093 0x6a09e667_u32,
3094 0xbb67ae85,
3095 0x3c6ef372,
3096 0xa54ff53a,
3097 0x510e527f,
3098 0x9b05688c,
3099 0x1f83d9ab,
3100 0x5be0cd19,
3101 ];
3102 for chunk in message.chunks_exact(64) {
3103 let mut schedule = [0_u32; 64];
3104 for (index, word) in schedule[..16].iter_mut().enumerate() {
3105 let offset = index * 4;
3106 *word = u32::from_be_bytes([
3107 chunk[offset],
3108 chunk[offset + 1],
3109 chunk[offset + 2],
3110 chunk[offset + 3],
3111 ]);
3112 }
3113 for index in 16..64 {
3114 let s0 = schedule[index - 15].rotate_right(7)
3115 ^ schedule[index - 15].rotate_right(18)
3116 ^ (schedule[index - 15] >> 3);
3117 let s1 = schedule[index - 2].rotate_right(17)
3118 ^ schedule[index - 2].rotate_right(19)
3119 ^ (schedule[index - 2] >> 10);
3120 schedule[index] = schedule[index - 16]
3121 .wrapping_add(s0)
3122 .wrapping_add(schedule[index - 7])
3123 .wrapping_add(s1);
3124 }
3125 let [mut a, mut b, mut c, mut d, mut e, mut f, mut g, mut h] = hash;
3126 for index in 0..64 {
3127 let s1 = e.rotate_right(6) ^ e.rotate_right(11) ^ e.rotate_right(25);
3128 let choice = (e & f) ^ ((!e) & g);
3129 let temp1 = h
3130 .wrapping_add(s1)
3131 .wrapping_add(choice)
3132 .wrapping_add(K[index])
3133 .wrapping_add(schedule[index]);
3134 let s0 = a.rotate_right(2) ^ a.rotate_right(13) ^ a.rotate_right(22);
3135 let majority = (a & b) ^ (a & c) ^ (b & c);
3136 let temp2 = s0.wrapping_add(majority);
3137 h = g;
3138 g = f;
3139 f = e;
3140 e = d.wrapping_add(temp1);
3141 d = c;
3142 c = b;
3143 b = a;
3144 a = temp1.wrapping_add(temp2);
3145 }
3146 for (value, addend) in hash.iter_mut().zip([a, b, c, d, e, f, g, h]) {
3147 *value = value.wrapping_add(addend);
3148 }
3149 }
3150 hash.iter().map(|word| format!("{word:08x}")).collect()
3151 }
3152
3153 fn compact_json(source: &str) -> Vec<u8> {
3154 let mut compact = Vec::with_capacity(source.len());
3155 let mut in_string = false;
3156 let mut escaped = false;
3157 for byte in source.bytes() {
3158 if in_string {
3159 compact.push(byte);
3160 if escaped {
3161 escaped = false;
3162 } else if byte == b'\\' {
3163 escaped = true;
3164 } else if byte == b'"' {
3165 in_string = false;
3166 }
3167 } else if byte == b'"' {
3168 in_string = true;
3169 compact.push(byte);
3170 } else if !matches!(byte, b' ' | b'\n' | b'\r' | b'\t') {
3171 compact.push(byte);
3172 }
3173 }
3174 compact
3175 }
3176
3177 fn frozen_cases_json() -> Vec<u8> {
3178 let root = StrictJsonParser::new(FIXTURE)
3179 .parse()
3180 .expect("frozen bridge fixture parses");
3181 let cases = object_entry(&root, "cases")
3182 .and_then(|node| node.array_items.as_ref())
3183 .expect("frozen bridge fixture cases");
3184 let mut selected = Vec::new();
3185 selected.push(b'[');
3186 for (index, case_id) in FROZEN_LEGACY_FIXTURE_CASE_IDS.iter().enumerate() {
3187 let case = cases
3188 .iter()
3189 .find(|case| object_value(case, "caseId").and_then(Value::as_str) == Some(*case_id))
3190 .expect("frozen bridge fixture case");
3191 if index > 0 {
3192 selected.push(b',');
3193 }
3194 selected.extend(compact_json(&FIXTURE[case.start..case.end]));
3195 }
3196 selected.push(b']');
3197 selected
3198 }
3199
3200 fn apply_quote_mutation(
3201 mut quote: MayanSwiftV2Quote,
3202 mutation: Option<&Value>,
3203 ) -> MayanSwiftV2Quote {
3204 let Some(mutation) = mutation else {
3205 return quote;
3206 };
3207 let Some(mutation) = mutation.as_object() else {
3208 panic!("unsupported bridge quote mutation");
3209 };
3210 let kind = mutation
3211 .get("kind")
3212 .and_then(Value::as_str)
3213 .expect("quote mutation kind");
3214 match kind {
3215 "normalized-set" => {
3216 let mut keys = mutation.keys().cloned().collect::<Vec<_>>();
3217 keys.sort();
3218 assert_eq!(keys, vec!["kind", "path", "value"]);
3219 match mutation.get("path").and_then(Value::as_str) {
3220 Some("sourceSwap.required") => {
3221 assert_eq!(mutation.get("value"), Some(&Value::Bool(true)));
3222 quote.source_swap.required = true;
3223 }
3224 Some("sourceTokenDeploymentId") => {
3225 let value = mutation
3226 .get("value")
3227 .and_then(Value::as_str)
3228 .expect("source token deployment mutation value");
3229 assert!(matches!(value, "deployment-0008" | "deployment-0011"));
3230 quote.source_token_deployment_id = value.to_owned();
3231 }
3232 _ => panic!("unsupported normalized quote mutation"),
3233 }
3234 }
3235 "raw-replace" => {
3236 let mut keys = mutation.keys().cloned().collect::<Vec<_>>();
3237 keys.sort();
3238 assert_eq!(keys, vec!["from", "kind", "path", "to"]);
3239 assert_eq!(
3240 mutation.get("path").and_then(Value::as_str),
3241 Some("rawSignedQuoteJson")
3242 );
3243 let from = mutation
3244 .get("from")
3245 .and_then(Value::as_str)
3246 .expect("raw quote mutation source");
3247 let to = mutation
3248 .get("to")
3249 .and_then(Value::as_str)
3250 .expect("raw quote mutation replacement");
3251 assert!(quote.raw_signed_quote_json.contains(from));
3252 quote.raw_signed_quote_json = quote.raw_signed_quote_json.replacen(from, to, 1);
3253 }
3254 _ => panic!("unsupported bridge quote mutation"),
3255 }
3256 quote
3257 }
3258
3259 async fn read_http_request(
3260 stream: &mut TcpStream,
3261 ) -> Option<(String, String, Map<String, Value>)> {
3262 let mut bytes = Vec::new();
3263 let mut chunk = [0_u8; 8192];
3264 loop {
3265 let count = stream.read(&mut chunk).await.ok()?;
3266 if count == 0 {
3267 return None;
3268 }
3269 bytes.extend_from_slice(&chunk[..count]);
3270 let header_end = bytes.windows(4).position(|window| window == b"\r\n\r\n")?;
3271 let header_bytes = &bytes[..header_end];
3272 let header_text = String::from_utf8_lossy(header_bytes);
3273 let request_line = header_text.lines().next()?;
3274 let mut parts = request_line.split_whitespace();
3275 let method = parts.next()?.to_owned();
3276 let path = parts.next()?.to_owned();
3277 let content_length = header_text
3278 .lines()
3279 .find_map(|line| {
3280 let (name, value) = line.split_once(':')?;
3281 name.eq_ignore_ascii_case("content-length")
3282 .then(|| value.trim().parse::<usize>().ok())
3283 .flatten()
3284 })
3285 .unwrap_or(0);
3286 let body_start = header_end + 4;
3287 if bytes.len() < body_start + content_length {
3288 continue;
3289 }
3290 let body = if content_length == 0 {
3291 Value::Null
3292 } else {
3293 String::from_utf8(bytes[body_start..body_start + content_length].to_vec())
3294 .map(Value::String)
3295 .unwrap_or(Value::Null)
3296 };
3297 let mut headers = Map::new();
3298 for line in header_text.lines().skip(1) {
3299 let Some((name, value)) = line.split_once(':') else {
3300 continue;
3301 };
3302 let name = name.to_ascii_lowercase();
3303 if matches!(
3304 name.as_str(),
3305 "accept" | "content-type" | "x-api-key" | "authorization" | "cookie"
3306 ) {
3307 headers.insert(name, Value::String(value.trim().to_owned()));
3308 }
3309 }
3310 headers.insert("body".to_owned(), body);
3311 return Some((method, path, headers));
3312 }
3313 }
3314
3315 async fn write_provider_response(stream: &mut TcpStream, status: u16, body: &str) {
3316 let reason = match status {
3317 200 => "OK",
3318 201 => "Created",
3319 302 => "Found",
3320 401 => "Unauthorized",
3321 403 => "Forbidden",
3322 404 => "Not Found",
3323 429 => "Too Many Requests",
3324 _ => "Error",
3325 };
3326 let body = body.as_bytes();
3327 let headers = format!(
3328 "HTTP/1.1 {status} {reason}\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n\r\n",
3329 body.len()
3330 );
3331 let _ = stream.write_all(headers.as_bytes()).await;
3332 let _ = stream.write_all(body).await;
3333 }
3334
3335 async fn start_provider_server(
3336 case: &Value,
3337 expected_url: String,
3338 ) -> (String, JoinHandle<Vec<Value>>) {
3339 let listener = TcpListener::bind("127.0.0.1:0")
3340 .await
3341 .expect("bridge fixture listener");
3342 let address = listener
3343 .local_addr()
3344 .expect("bridge fixture listener address");
3345 let status = u16::try_from(case["providerStatus"].as_u64().unwrap_or(200))
3346 .expect("synthetic status fits u16");
3347 let body = case["providerBody"].as_str().map(str::to_owned);
3348 let case_id = case["caseId"].as_str().unwrap_or_default().to_owned();
3349 let handle = tokio::spawn(async move {
3350 let (mut stream, _) = listener.accept().await.expect("bridge fixture connection");
3351 let Some((method, path, headers)) = read_http_request(&mut stream).await else {
3352 return Vec::new();
3353 };
3354 let captured = vec![json!({
3355 "method": method,
3356 "url": expected_url,
3357 "headers": headers.iter()
3358 .filter(|(key, _)| !matches!(key.as_str(), "body" | "authorization" | "cookie"))
3359 .map(|(key, value)| (key.clone(), value.clone()))
3360 .collect::<Map<_, _>>(),
3361 "path": path,
3362 "body": headers.get("body").cloned().unwrap_or(Value::Null),
3363 "forbiddenHeaders": headers.iter().filter_map(|(key, value)| {
3364 matches!(key.as_str(), "authorization" | "cookie")
3365 .then(|| (key.clone(), value.clone()))
3366 }).collect::<Map<_, _>>(),
3367 })];
3368 if case_id == "quote-timeout" || case_id == "quote-aborted" {
3369 tokio::time::sleep(Duration::from_millis(250)).await;
3370 return captured;
3371 }
3372 let response_body = if body.as_deref() == Some("__SYNTHETIC_BODY_EXCEEDS_1MIB__") {
3373 "x".repeat(MAX_RESPONSE_BYTES + 1)
3374 } else {
3375 body.unwrap_or_default()
3376 };
3377 write_provider_response(&mut stream, status, &response_body).await;
3378 captured
3379 });
3380 (format!("http://{address}"), handle)
3381 }
3382
3383 fn bridge_config(
3384 builder_endpoint: &str,
3385 explorer_endpoint: &str,
3386 case: &Value,
3387 ) -> MayanSwiftV2BridgeConfig {
3388 let mut config = MayanSwiftV2BridgeConfig::new()
3389 .with_builder_endpoint(builder_endpoint)
3390 .with_explorer_endpoint(explorer_endpoint);
3391 if case["config"]["allowUnauthenticatedBuild"] == Value::Bool(true) {
3392 config = config.with_allow_unauthenticated_build(true);
3393 }
3394 if let Some(key) = case["config"]["builderApiKey"].as_str() {
3395 config = config.with_builder_api_key(key);
3396 }
3397 if let Some(seconds) = case["config"]["minimumQuoteValiditySeconds"].as_u64() {
3398 config = config.with_minimum_quote_validity_seconds(seconds);
3399 }
3400 if case["caseId"] == "quote-timeout" {
3401 config = config.with_timeout(Duration::from_millis(20));
3402 }
3403 config
3404 }
3405
3406 async fn capture_quote_for_build(fixture: &Value, quote_case_id: &str) -> MayanSwiftV2Quote {
3407 let quote_case = fixture_case(fixture, quote_case_id);
3408 let (endpoint, server) = start_provider_server(
3409 quote_case,
3410 quote_case["httpTrace"][0]["url"]
3411 .as_str()
3412 .unwrap_or("https://tx-builder.mayan.finance/quote")
3413 .to_owned(),
3414 )
3415 .await;
3416 let request: MayanSwiftV2QuoteRequest =
3417 serde_json::from_value(quote_case["request"].clone()).expect("quote request");
3418 let client = MayanSwiftV2BridgeClient::new(
3419 bridge_config(&endpoint, &endpoint, quote_case).with_allow_unauthenticated_build(true),
3420 )
3421 .expect("quote client")
3422 .with_clock(fixed_clock);
3423 let quote = client
3424 .quote_exact_input(request)
3425 .await
3426 .expect("quote")
3427 .into_iter()
3428 .next()
3429 .expect("selected quote");
3430 server.await.expect("quote server");
3431 quote
3432 }
3433
3434 #[allow(clippy::manual_let_else, clippy::too_many_lines)]
3435 async fn execute_fixture_case(case: &Value, fixture: &Value) -> (Value, Vec<Value>) {
3436 let method = case["method"].as_str().expect("fixture method");
3437 let case_id = case["caseId"].as_str().expect("fixture case ID");
3438 match method {
3439 "quote" => {
3440 let request = match serde_json::from_value::<MayanSwiftV2QuoteRequest>(
3441 case["request"].clone(),
3442 ) {
3443 Ok(request) => request,
3444 Err(_) => {
3445 return (
3446 json!({
3447 "kind": "sdk-error",
3448 "code": BridgeErrorCode::InvalidArgument.as_str(),
3449 "message": BridgeErrorCode::InvalidArgument.message(),
3450 }),
3451 Vec::new(),
3452 );
3453 }
3454 };
3455 if case["httpTrace"].as_array().is_some_and(Vec::is_empty) {
3456 let error = MayanSwiftV2BridgeClient::new(bridge_config(
3457 "http://127.0.0.1:1",
3458 "http://127.0.0.1:1",
3459 case,
3460 ))
3461 .expect("local quote client")
3462 .with_clock(fixed_clock)
3463 .quote_exact_input(request)
3464 .await
3465 .expect_err("unsupported quote case");
3466 return (
3467 json!({"kind":"sdk-error","code":error.code_string(),"message":error.to_string()}),
3468 Vec::new(),
3469 );
3470 }
3471 let expected_url = case["httpTrace"][0]["url"]
3472 .as_str()
3473 .unwrap_or("https://tx-builder.mayan.finance/quote")
3474 .to_owned();
3475 let (endpoint, server) = start_provider_server(case, expected_url).await;
3476 let client =
3477 MayanSwiftV2BridgeClient::new(bridge_config(&endpoint, &endpoint, case))
3478 .expect("quote client")
3479 .with_clock(fixed_clock);
3480 let result = if case_id == "quote-aborted" {
3481 let cancellation = CancellationToken::new();
3482 let task_cancellation = cancellation.clone();
3483 let task_client = client.clone();
3484 let task = tokio::spawn(async move {
3485 task_client
3486 .quote_exact_input_with(request, Some(&task_cancellation))
3487 .await
3488 });
3489 tokio::time::sleep(Duration::from_millis(20)).await;
3490 cancellation.cancel();
3491 task.await.expect("aborted quote task")
3492 } else {
3493 client.quote_exact_input(request).await
3494 };
3495 let captured = tokio::time::timeout(Duration::from_secs(2), server)
3496 .await
3497 .expect("quote server completed")
3498 .expect("quote server joined");
3499 let trace = normalize_trace(captured);
3500 let outcome = match result {
3501 Ok(value) => json!({
3502 "kind": "success",
3503 "value": serde_json::to_value(value).expect("quotes serialize"),
3504 }),
3505 Err(error) => {
3506 let mut value = json!({
3507 "kind": "sdk-error",
3508 "code": error.code_string(),
3509 "message": error.to_string(),
3510 });
3511 if error.code() == BridgeErrorCode::ProviderHttp {
3512 let status = error.status().expect("HTTP error status");
3513 value["status"] = json!(status);
3514 }
3515 value
3516 }
3517 };
3518 (outcome, trace)
3519 }
3520 "build" => {
3521 let quote_case_id = if case_id == "build-quote-mismatch" {
3522 "quote-eth-sol-synthetic"
3523 } else {
3524 case["quoteCaseId"].as_str().expect("build quote case")
3525 };
3526 let mut quote = capture_quote_for_build(fixture, quote_case_id).await;
3527 if let Some(mutation) = case.get("quoteMutation") {
3528 quote = apply_quote_mutation(quote, Some(mutation));
3529 }
3530 if case_id == "build-quote-mismatch" {
3531 quote.amount_in = "100000001".to_owned();
3532 }
3533 let request = MayanSwiftV2BuildRequest {
3534 quote,
3535 swapper_address: case["request"]["swapperAddress"]
3536 .as_str()
3537 .expect("swapper address")
3538 .to_owned(),
3539 destination_address: case["request"]["destinationAddress"]
3540 .as_str()
3541 .expect("destination address")
3542 .to_owned(),
3543 refund_address: case["request"]["refundAddress"].as_str().map(str::to_owned),
3544 };
3545 if case["httpTrace"].as_array().is_some_and(Vec::is_empty) {
3546 let client = MayanSwiftV2BridgeClient::new(bridge_config(
3547 "http://127.0.0.1:1",
3548 "http://127.0.0.1:1",
3549 case,
3550 ))
3551 .expect("local build client")
3552 .with_clock(fixed_clock);
3553 let result = client.build_unsigned(request).await;
3554 let outcome = result.map_or_else(
3555 |error| {
3556 json!({"kind":"sdk-error","code":error.code_string(),"message":error.to_string()})
3557 },
3558 |value| json!({"kind":"success","value":serde_json::to_value(value).expect("build serialize")}),
3559 );
3560 return (outcome, Vec::new());
3561 }
3562 let expected_url = case["httpTrace"][0]["url"]
3563 .as_str()
3564 .unwrap_or("https://tx-builder.mayan.finance/build")
3565 .to_owned();
3566 let (endpoint, server) = start_provider_server(case, expected_url).await;
3567 let client =
3568 MayanSwiftV2BridgeClient::new(bridge_config(&endpoint, &endpoint, case))
3569 .expect("build client")
3570 .with_clock(fixed_clock);
3571 let result = client.build_unsigned(request).await;
3572 let captured = server.await.expect("build server joined");
3573 let outcome = result.map_or_else(
3574 |error| {
3575 let mut value = json!({
3576 "kind": "sdk-error",
3577 "code": error.code_string(),
3578 "message": error.to_string(),
3579 });
3580 if error.code() == BridgeErrorCode::ProviderHttp {
3581 let status = error.status().expect("HTTP error status");
3582 value["status"] = json!(status);
3583 }
3584 value
3585 },
3586 |value| {
3587 json!({
3588 "kind": "success",
3589 "value": serde_json::to_value(value).expect("build serialize"),
3590 })
3591 },
3592 );
3593 (outcome, normalize_trace(captured))
3594 }
3595 "status" => {
3596 let request: MayanSwiftV2StatusRequest =
3597 serde_json::from_value(case["request"].clone()).expect("status request");
3598 if case["httpTrace"].as_array().is_some_and(Vec::is_empty) {
3599 let error = MayanSwiftV2BridgeClient::new(bridge_config(
3600 "http://127.0.0.1:1",
3601 "http://127.0.0.1:1",
3602 case,
3603 ))
3604 .expect("local status client")
3605 .with_clock(fixed_clock)
3606 .get_status(request)
3607 .await
3608 .expect_err("invalid status case");
3609 return (
3610 json!({"kind":"sdk-error","code":error.code_string(),"message":error.to_string()}),
3611 Vec::new(),
3612 );
3613 }
3614 let expected_url = case["httpTrace"][0]["url"]
3615 .as_str()
3616 .unwrap_or("https://explorer-api.mayan.finance/v3/swap/trx/hash")
3617 .to_owned();
3618 let (endpoint, server) = start_provider_server(case, expected_url).await;
3619 let client =
3620 MayanSwiftV2BridgeClient::new(bridge_config(&endpoint, &endpoint, case))
3621 .expect("status client")
3622 .with_clock(fixed_clock);
3623 let result = client.get_status(request).await;
3624 let captured = server.await.expect("status server joined");
3625 let outcome = result.map_or_else(
3626 |error| {
3627 let mut value = json!({
3628 "kind": "sdk-error",
3629 "code": error.code_string(),
3630 "message": error.to_string(),
3631 });
3632 if error.code() == BridgeErrorCode::ProviderHttp {
3633 let status = error.status().expect("HTTP error status");
3634 value["status"] = json!(status);
3635 }
3636 value
3637 },
3638 |value| {
3639 json!({
3640 "kind": "success",
3641 "value": serde_json::to_value(value).expect("status serialize"),
3642 })
3643 },
3644 );
3645 (outcome, normalize_trace(captured))
3646 }
3647 _ => panic!("unsupported fixture method"),
3648 }
3649 }
3650
3651 fn normalize_trace(captured: Vec<Value>) -> Vec<Value> {
3652 captured
3653 .into_iter()
3654 .map(|entry| {
3655 let mut trace = Map::new();
3656 trace.insert("method".to_owned(), entry["method"].clone());
3657 trace.insert("url".to_owned(), entry["url"].clone());
3658 trace.insert("headers".to_owned(), entry["headers"].clone());
3659 trace.insert("body".to_owned(), entry["body"].clone());
3660 if entry["forbiddenHeaders"] != Value::Object(Map::new()) {
3661 trace.insert(
3662 "forbiddenHeaders".to_owned(),
3663 entry["forbiddenHeaders"].clone(),
3664 );
3665 }
3666 Value::Object(trace)
3667 })
3668 .collect()
3669 }
3670
3671 fn expected_error(value: &Value) -> Value {
3672 value.clone()
3673 }
3674
3675 #[tokio::test]
3676 async fn capture_native_bridge_snapshot_when_requested() {
3677 let Some(output) = env::var_os("ERPC_SDK_BRIDGE_PARITY_OUTPUT") else {
3678 return;
3679 };
3680 let fixture = fixture_value();
3681 let mut behavior = Map::from_iter([
3682 ("quote".to_owned(), Value::Array(Vec::new())),
3683 ("build".to_owned(), Value::Array(Vec::new())),
3684 ("status".to_owned(), Value::Array(Vec::new())),
3685 ("prepareSourceSwap".to_owned(), Value::Array(Vec::new())),
3686 ("buildLocalUnsigned".to_owned(), Value::Array(Vec::new())),
3687 ]);
3688 assert_eq!(
3689 sha256_hex(&frozen_cases_json()),
3690 "dce10a654672921bc4b26d4d14312abe81c0b93ac1de3fce48be3bd5beb7e5ee"
3691 );
3692 for case in fixture["cases"].as_array().expect("fixture cases") {
3693 let case_id = case["caseId"].as_str().expect("case ID");
3694 if FROZEN_LEGACY_FIXTURE_CASE_IDS.contains(&case_id) {
3695 assert!(
3696 case.get("quoteMutation").is_none(),
3697 "legacy case gained mutation descriptor"
3698 );
3699 }
3700 let method = case["method"].as_str().expect("method");
3701 let (outcome, trace) = execute_fixture_case(case, &fixture).await;
3702 assert_eq!(
3703 outcome,
3704 expected_error(&case["expected"]),
3705 "bridge fixture outcome mismatch for {case_id}"
3706 );
3707 let expected_trace = case["httpTrace"]
3708 .as_array()
3709 .cloned()
3710 .expect("fixture trace");
3711 assert_eq!(
3712 trace, expected_trace,
3713 "bridge fixture HTTP trace mismatch for {case_id}"
3714 );
3715 behavior[method]
3716 .as_array_mut()
3717 .expect("behavior array")
3718 .push(json!({"caseId":case_id,"outcome":outcome,"httpTrace":trace}));
3719 }
3720 for value in behavior.values_mut() {
3721 value
3722 .as_array_mut()
3723 .expect("behavior array")
3724 .sort_by(|left, right| left["caseId"].as_str().cmp(&right["caseId"].as_str()));
3725 }
3726 let local_fixture: Value =
3727 serde_json::from_str(LOCAL_FIXTURE).expect("local bridge fixture is valid JSON");
3728 assert_eq!(
3729 local_fixture["localFixtureDigest"],
3730 "4a9960ad4d0fcc0865f4afcd5e5403d81823f57a64bbc48039113e568b050c35"
3731 );
3732 let local_behavior =
3733 crate::bridge_local::native_fixture::replay_local_fixture(&local_fixture).await;
3734 behavior.extend(local_behavior);
3735 let snapshot = json!({
3736 "snapshotVersion": 2,
3737 "snapshotKind": "bridge-native-runtime",
3738 "language": "rust",
3739 "runtime": concat!(
3740 "Rust compiled-library unit tests (erpc-sdk ",
3741 env!("CARGO_PKG_VERSION"),
3742 ")"
3743 ),
3744 "capabilityAsOfDate": BRIDGE_CAPABILITIES_AS_OF_DATE,
3745 "capabilityDigest": BRIDGE_CAPABILITIES_CONTENT_DIGEST,
3746 "hostedFixtureDigest": "3c414e362b518a3845e365c3c7c6f78e43984aae396be19817ddb53bb0da6283",
3747 "localFixtureDigest": local_fixture["localFixtureDigest"],
3748 "behavior": behavior,
3749 });
3750 let output = Path::new(&output);
3751 if let Some(parent) = output.parent() {
3752 fs::create_dir_all(parent).expect("bridge parity output directory");
3753 }
3754 let mut encoded = serde_json::to_vec_pretty(&snapshot).expect("bridge snapshot serializes");
3755 encoded.push(b'\n');
3756 fs::write(output, encoded).expect("bridge parity snapshot write");
3757 }
3758}