Skip to main content

ton_connect_core/
connect.rs

1use std::collections::BTreeMap;
2
3use serde::{Deserialize, Deserializer, Serialize, Serializer, de};
4use serde_json::Value;
5
6use crate::{
7    AccountVerificationError, Ed25519PublicKey, Ed25519Signature, EmbeddedResponse, EmptyObject,
8    HttpsUrl, NetworkId, NonEmptyVec, RawAccountAddress, ResponseValidationError, SignatureDomain,
9    SigningError, StandardWalletState, Uint64String, WalletStateError, WalletStateInit,
10    rpc::numeric_enum_serde, ton_proof_signing_hash, verify_signature,
11};
12
13/// Request for the connected wallet address and optional target network hint.
14#[derive(Clone, Debug, Eq, PartialEq)]
15pub struct TonAddressItem {
16    /// Optional desired network global ID.
17    pub network: Option<NetworkId>,
18}
19
20/// Request for a wallet ownership proof bound to a dApp payload.
21#[derive(Clone, Debug, Eq, PartialEq)]
22pub struct TonProofItem {
23    /// Opaque application-provided challenge.
24    pub payload: String,
25}
26
27/// Data item requested during the initial connect handshake.
28///
29/// Unknown item names are preserved so a wallet can return the mandatory
30/// per-item error `400` instead of rejecting the complete connect request.
31#[derive(Clone, Debug, Eq, PartialEq)]
32pub enum ConnectItem {
33    /// Connected account address information.
34    TonAddr {
35        /// Optional desired network global ID.
36        network: Option<NetworkId>,
37    },
38    /// Wallet ownership proof.
39    TonProof {
40        /// Opaque application-provided challenge.
41        payload: String,
42    },
43    /// A forward-compatible item unsupported by this protocol revision.
44    Unsupported {
45        /// Exact requested item name echoed in the error reply.
46        name: String,
47        /// Unknown item fields retained without interpretation.
48        fields: BTreeMap<String, Value>,
49    },
50}
51
52impl ConnectItem {
53    /// Returns the exact connect-item discriminator.
54    #[must_use]
55    pub fn name(&self) -> &str {
56        match self {
57            Self::TonAddr { .. } => "ton_addr",
58            Self::TonProof { .. } => "ton_proof",
59            Self::Unsupported { name, .. } => name,
60        }
61    }
62
63    /// Creates a forward-compatible item unknown to this crate revision.
64    pub fn unsupported(
65        name: String,
66        fields: BTreeMap<String, Value>,
67    ) -> Result<Self, UnsupportedConnectItemError> {
68        if name.is_empty() || fields.contains_key("name") {
69            return Err(UnsupportedConnectItemError);
70        }
71        Ok(Self::Unsupported { name, fields })
72    }
73}
74
75/// Invalid construction of a forward-compatible connect item.
76#[derive(Clone, Copy, Debug, Eq, thiserror::Error, PartialEq)]
77#[error("unsupported connect item requires a non-empty name outside its fields")]
78pub struct UnsupportedConnectItemError;
79
80#[derive(Deserialize)]
81#[serde(deny_unknown_fields)]
82struct TonAddressItemWire {
83    #[serde(
84        default,
85        deserialize_with = "crate::value::deserialize_optional_non_null"
86    )]
87    network: Option<NetworkId>,
88}
89
90#[derive(Deserialize)]
91#[serde(deny_unknown_fields)]
92struct TonProofItemWire {
93    payload: String,
94}
95
96impl Serialize for ConnectItem {
97    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
98    where
99        S: Serializer,
100    {
101        let mut object = serde_json::Map::new();
102        let _ = object.insert("name".to_owned(), Value::String(self.name().to_owned()));
103        match self {
104            Self::TonAddr { network } => {
105                if let Some(network) = network {
106                    let _ = object.insert(
107                        "network".to_owned(),
108                        serde_json::to_value(network).map_err(serde::ser::Error::custom)?,
109                    );
110                }
111            }
112            Self::TonProof { payload } => {
113                let _ = object.insert("payload".to_owned(), Value::String(payload.clone()));
114            }
115            Self::Unsupported { fields, .. } => {
116                object.extend(fields.clone());
117            }
118        }
119        Value::Object(object).serialize(serializer)
120    }
121}
122
123impl<'de> Deserialize<'de> for ConnectItem {
124    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
125    where
126        D: Deserializer<'de>,
127    {
128        let Value::Object(mut object) = Value::deserialize(deserializer)? else {
129            return Err(de::Error::custom("connect item must be an object"));
130        };
131        let name = object
132            .remove("name")
133            .and_then(|value| value.as_str().map(str::to_owned))
134            .filter(|name| !name.is_empty())
135            .ok_or_else(|| de::Error::custom("connect item name must be a non-empty string"))?;
136        let fields = object.into_iter().collect::<BTreeMap<_, _>>();
137        match name.as_str() {
138            "ton_addr" => serde_json::from_value::<TonAddressItemWire>(
139                serde_json::to_value(fields).map_err(de::Error::custom)?,
140            )
141            .map(|wire| Self::TonAddr {
142                network: wire.network,
143            })
144            .map_err(de::Error::custom),
145            "ton_proof" => serde_json::from_value::<TonProofItemWire>(
146                serde_json::to_value(fields).map_err(de::Error::custom)?,
147            )
148            .map(|wire| Self::TonProof {
149                payload: wire.payload,
150            })
151            .map_err(de::Error::custom),
152            _ => Ok(Self::Unsupported { name, fields }),
153        }
154    }
155}
156
157impl From<TonAddressItem> for ConnectItem {
158    fn from(item: TonAddressItem) -> Self {
159        Self::TonAddr {
160            network: item.network,
161        }
162    }
163}
164
165impl From<TonProofItem> for ConnectItem {
166    fn from(item: TonProofItem) -> Self {
167        Self::TonProof {
168            payload: item.payload,
169        }
170    }
171}
172
173/// Initial plaintext request carried by a TON Connect deep link.
174#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)]
175#[serde(rename_all = "camelCase", deny_unknown_fields)]
176pub struct ConnectRequest {
177    /// URL of the dApp's `tonconnect-manifest.json`.
178    pub manifest_url: HttpsUrl,
179    /// One or more requested account data items.
180    pub items: NonEmptyVec<ConnectItem>,
181}
182
183/// Wallet runtime reported in `DeviceInfo`.
184#[derive(Clone, Copy, Debug, Eq, PartialEq, Deserialize, Serialize)]
185#[serde(rename_all = "lowercase")]
186pub enum DevicePlatform {
187    /// iPhone wallet.
188    Iphone,
189    /// iPad wallet.
190    Ipad,
191    /// Android wallet.
192    Android,
193    /// Windows wallet.
194    Windows,
195    /// macOS wallet.
196    Mac,
197    /// Linux wallet.
198    Linux,
199    /// Browser wallet or extension.
200    Browser,
201}
202
203/// Structured transfer kinds accepted by a wallet.
204#[derive(Clone, Copy, Debug, Eq, PartialEq, Deserialize, Serialize)]
205#[serde(rename_all = "lowercase")]
206pub enum StructuredItemType {
207    /// Native TON transfer.
208    Ton,
209    /// Jetton transfer.
210    Jetton,
211    /// NFT transfer.
212    Nft,
213}
214
215/// Data variants accepted by the `signData` method.
216#[derive(Clone, Copy, Debug, Eq, PartialEq, Deserialize, Serialize)]
217#[serde(rename_all = "lowercase")]
218pub enum SignDataType {
219    /// UTF-8 text.
220    Text,
221    /// Opaque bytes.
222    Binary,
223    /// TL-B-described cell.
224    Cell,
225}
226
227/// Advertised `SendTransaction` limits.
228#[derive(Clone, Debug, Eq, PartialEq)]
229pub struct SendTransactionFeature {
230    /// Maximum number of outgoing messages accepted in one request.
231    max_messages: u32,
232    /// Whether TEP-92 extra currencies are supported.
233    extra_currency_supported: Option<bool>,
234    /// Structured item kinds accepted by the wallet.
235    item_types: Option<Vec<StructuredItemType>>,
236}
237
238impl SendTransactionFeature {
239    /// Creates validated transaction capability limits.
240    pub fn new(
241        max_messages: u32,
242        extra_currency_supported: Option<bool>,
243        item_types: Option<Vec<StructuredItemType>>,
244    ) -> Result<Self, FeatureValidationError> {
245        validate_message_feature(max_messages, item_types.as_deref())?;
246        Ok(Self {
247            max_messages,
248            extra_currency_supported,
249            item_types,
250        })
251    }
252
253    /// Returns the maximum accepted outgoing message count.
254    #[must_use]
255    pub const fn max_messages(&self) -> u32 {
256        self.max_messages
257    }
258
259    /// Returns whether extra currencies are supported when explicitly declared.
260    #[must_use]
261    pub const fn extra_currency_supported(&self) -> Option<bool> {
262        self.extra_currency_supported
263    }
264
265    /// Returns the supported structured item kinds.
266    #[must_use]
267    pub fn item_types(&self) -> Option<&[StructuredItemType]> {
268        self.item_types.as_deref()
269    }
270}
271
272/// Advertised `SignMessage` limits.
273#[derive(Clone, Debug, Eq, PartialEq)]
274pub struct SignMessageFeature {
275    /// Maximum number of outgoing messages accepted in one request.
276    max_messages: u32,
277    /// Whether TEP-92 extra currencies are supported.
278    extra_currency_supported: Option<bool>,
279    /// Structured item kinds accepted by the wallet.
280    item_types: Option<Vec<StructuredItemType>>,
281}
282
283impl SignMessageFeature {
284    /// Creates validated message-signing capability limits.
285    pub fn new(
286        max_messages: u32,
287        extra_currency_supported: Option<bool>,
288        item_types: Option<Vec<StructuredItemType>>,
289    ) -> Result<Self, FeatureValidationError> {
290        validate_message_feature(max_messages, item_types.as_deref())?;
291        Ok(Self {
292            max_messages,
293            extra_currency_supported,
294            item_types,
295        })
296    }
297
298    /// Returns the maximum accepted outgoing message count.
299    #[must_use]
300    pub const fn max_messages(&self) -> u32 {
301        self.max_messages
302    }
303
304    /// Returns whether extra currencies are supported when explicitly declared.
305    #[must_use]
306    pub const fn extra_currency_supported(&self) -> Option<bool> {
307        self.extra_currency_supported
308    }
309
310    /// Returns the supported structured item kinds.
311    #[must_use]
312    pub fn item_types(&self) -> Option<&[StructuredItemType]> {
313        self.item_types.as_deref()
314    }
315}
316
317/// Advertised `SignData` variants.
318#[derive(Clone, Debug, Eq, PartialEq)]
319pub struct SignDataFeature {
320    /// Payload variants accepted by the wallet.
321    types: Vec<SignDataType>,
322}
323
324impl SignDataFeature {
325    /// Creates a non-empty feature with unique payload variants.
326    pub fn new(types: Vec<SignDataType>) -> Result<Self, FeatureValidationError> {
327        if types.is_empty() || !all_unique(&types) {
328            return Err(FeatureValidationError);
329        }
330        Ok(Self { types })
331    }
332
333    /// Returns the supported payload variants.
334    #[must_use]
335    pub fn types(&self) -> &[SignDataType] {
336        &self.types
337    }
338}
339
340/// Feature capability violates the normative schema constraints.
341#[derive(Clone, Copy, Debug, Eq, thiserror::Error, PartialEq)]
342#[error("feature arrays must be non-empty and unique, and maxMessages must be positive")]
343pub struct FeatureValidationError;
344
345/// Wallet capability advertised in `DeviceInfo.features`.
346#[derive(Clone, Debug, Eq, PartialEq)]
347pub enum Feature {
348    /// Deprecated protocol-v2 string form retained for compatibility.
349    LegacySendTransaction,
350    /// Transaction signing and broadcasting.
351    SendTransaction(SendTransactionFeature),
352    /// Arbitrary data signing.
353    SignData(SignDataFeature),
354    /// Message signing without broadcasting.
355    SignMessage(SignMessageFeature),
356    /// Connect-link embedded requests.
357    EmbeddedRequest,
358}
359
360#[derive(Deserialize, Serialize)]
361#[serde(tag = "name", deny_unknown_fields)]
362enum DetailedFeature {
363    #[serde(rename = "SendTransaction")]
364    SendTransaction {
365        #[serde(rename = "maxMessages")]
366        max_messages: u32,
367        #[serde(
368            rename = "extraCurrencySupported",
369            default,
370            deserialize_with = "crate::value::deserialize_optional_non_null",
371            skip_serializing_if = "Option::is_none"
372        )]
373        extra_currency_supported: Option<bool>,
374        #[serde(
375            rename = "itemTypes",
376            default,
377            deserialize_with = "crate::value::deserialize_optional_non_null",
378            skip_serializing_if = "Option::is_none"
379        )]
380        item_types: Option<Vec<StructuredItemType>>,
381    },
382    #[serde(rename = "SignData")]
383    SignData { types: Vec<SignDataType> },
384    #[serde(rename = "SignMessage")]
385    SignMessage {
386        #[serde(rename = "maxMessages")]
387        max_messages: u32,
388        #[serde(
389            rename = "extraCurrencySupported",
390            default,
391            deserialize_with = "crate::value::deserialize_optional_non_null",
392            skip_serializing_if = "Option::is_none"
393        )]
394        extra_currency_supported: Option<bool>,
395        #[serde(
396            rename = "itemTypes",
397            default,
398            deserialize_with = "crate::value::deserialize_optional_non_null",
399            skip_serializing_if = "Option::is_none"
400        )]
401        item_types: Option<Vec<StructuredItemType>>,
402    },
403    #[serde(rename = "EmbeddedRequest")]
404    EmbeddedRequest,
405}
406
407impl Serialize for Feature {
408    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
409    where
410        S: Serializer,
411    {
412        match self {
413            Self::LegacySendTransaction => serializer.serialize_str("SendTransaction"),
414            Self::SendTransaction(feature) => DetailedFeature::SendTransaction {
415                max_messages: feature.max_messages,
416                extra_currency_supported: feature.extra_currency_supported,
417                item_types: feature.item_types.clone(),
418            }
419            .serialize(serializer),
420            Self::SignData(feature) => DetailedFeature::SignData {
421                types: feature.types.clone(),
422            }
423            .serialize(serializer),
424            Self::SignMessage(feature) => DetailedFeature::SignMessage {
425                max_messages: feature.max_messages,
426                extra_currency_supported: feature.extra_currency_supported,
427                item_types: feature.item_types.clone(),
428            }
429            .serialize(serializer),
430            Self::EmbeddedRequest => DetailedFeature::EmbeddedRequest.serialize(serializer),
431        }
432    }
433}
434
435impl<'de> Deserialize<'de> for Feature {
436    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
437    where
438        D: Deserializer<'de>,
439    {
440        let value = Value::deserialize(deserializer)?;
441        if let Value::String(name) = &value {
442            return if name == "SendTransaction" {
443                Ok(Self::LegacySendTransaction)
444            } else {
445                Err(de::Error::custom("unsupported legacy TON Connect feature"))
446            };
447        }
448
449        match serde_json::from_value::<DetailedFeature>(value).map_err(de::Error::custom)? {
450            DetailedFeature::SendTransaction {
451                max_messages,
452                extra_currency_supported,
453                item_types,
454            } => SendTransactionFeature::new(max_messages, extra_currency_supported, item_types)
455                .map(Self::SendTransaction)
456                .map_err(de::Error::custom),
457            DetailedFeature::SignData { types } => SignDataFeature::new(types)
458                .map(Self::SignData)
459                .map_err(de::Error::custom),
460            DetailedFeature::SignMessage {
461                max_messages,
462                extra_currency_supported,
463                item_types,
464            } => SignMessageFeature::new(max_messages, extra_currency_supported, item_types)
465                .map(Self::SignMessage)
466                .map_err(de::Error::custom),
467            DetailedFeature::EmbeddedRequest => Ok(Self::EmbeddedRequest),
468        }
469    }
470}
471
472fn validate_message_feature(
473    max_messages: u32,
474    item_types: Option<&[StructuredItemType]>,
475) -> Result<(), FeatureValidationError> {
476    if max_messages == 0
477        || item_types.is_some_and(|values| values.is_empty() || !all_unique(values))
478    {
479        Err(FeatureValidationError)
480    } else {
481        Ok(())
482    }
483}
484
485fn all_unique<T: Eq>(values: &[T]) -> bool {
486    values.iter().enumerate().all(|(index, value)| {
487        values
488            .iter()
489            .skip(index.saturating_add(1))
490            .all(|other| other != value)
491    })
492}
493
494/// Wallet self-description returned in a successful connect event.
495#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
496#[serde(rename_all = "camelCase", deny_unknown_fields)]
497pub struct DeviceInfo {
498    /// Wallet runtime platform.
499    pub platform: DevicePlatform,
500    /// Wallet identifier matching its wallets-list `app_name`.
501    pub app_name: String,
502    /// Wallet application version.
503    pub app_version: String,
504    /// Highest supported TON Connect protocol version.
505    pub max_protocol_version: u32,
506    /// Runtime-authoritative capability list.
507    pub features: Vec<Feature>,
508}
509
510#[derive(Deserialize)]
511#[serde(rename_all = "camelCase", deny_unknown_fields)]
512struct DeviceInfoWire {
513    platform: DevicePlatform,
514    app_name: String,
515    app_version: String,
516    max_protocol_version: u32,
517    features: Vec<Feature>,
518}
519
520impl DeviceInfo {
521    /// Creates a validated runtime wallet descriptor.
522    pub fn new(
523        platform: DevicePlatform,
524        app_name: String,
525        app_version: String,
526        max_protocol_version: u32,
527        features: Vec<Feature>,
528    ) -> Result<Self, DeviceInfoValidationError> {
529        let value = Self {
530            platform,
531            app_name,
532            app_version,
533            max_protocol_version,
534            features,
535        };
536        value.validate()?;
537        Ok(value)
538    }
539
540    /// Validates identity, protocol-version, and feature-set invariants.
541    pub fn validate(&self) -> Result<(), DeviceInfoValidationError> {
542        if self.app_name.is_empty() || self.app_version.is_empty() {
543            return Err(DeviceInfoValidationError::EmptyIdentity);
544        }
545        if self.max_protocol_version < u32::from(crate::PROTOCOL_VERSION) {
546            return Err(DeviceInfoValidationError::UnsupportedProtocolVersion);
547        }
548
549        let mut names = Vec::new();
550        for feature in &self.features {
551            let name = match feature {
552                Feature::LegacySendTransaction | Feature::SendTransaction(_) => "SendTransaction",
553                Feature::SignData(_) => "SignData",
554                Feature::SignMessage(_) => "SignMessage",
555                Feature::EmbeddedRequest => "EmbeddedRequest",
556            };
557            if names.contains(&name) {
558                return Err(DeviceInfoValidationError::DuplicateFeature);
559            }
560            names.push(name);
561        }
562        Ok(())
563    }
564}
565
566impl<'de> Deserialize<'de> for DeviceInfo {
567    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
568    where
569        D: Deserializer<'de>,
570    {
571        let wire = DeviceInfoWire::deserialize(deserializer)?;
572        Self::new(
573            wire.platform,
574            wire.app_name,
575            wire.app_version,
576            wire.max_protocol_version,
577            wire.features,
578        )
579        .map_err(de::Error::custom)
580    }
581}
582
583/// Runtime wallet metadata is not a valid protocol-v2 `DeviceInfo` value.
584#[derive(Clone, Copy, Debug, Eq, thiserror::Error, PartialEq)]
585pub enum DeviceInfoValidationError {
586    /// Wallet registry identity or application version is empty.
587    #[error("DeviceInfo appName and appVersion must be non-empty")]
588    EmptyIdentity,
589    /// The wallet does not report support for the current protocol revision.
590    #[error("DeviceInfo maxProtocolVersion does not support TON Connect v2")]
591    UnsupportedProtocolVersion,
592    /// More than one entry advertises the same runtime feature.
593    #[error("DeviceInfo contains a duplicate feature")]
594    DuplicateFeature,
595}
596
597/// Connected account information returned for `ton_addr`.
598#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)]
599#[serde(deny_unknown_fields)]
600pub struct TonAddressItemReply {
601    #[serde(rename = "name")]
602    name: TonAddressReplyName,
603    /// Raw TON address (`workchain:hex`).
604    pub address: RawAccountAddress,
605    /// Connected network global ID.
606    pub network: NetworkId,
607    /// Canonical standard-base64 wallet `StateInit` `BoC`.
608    #[serde(rename = "walletStateInit")]
609    pub wallet_state_init: WalletStateInit,
610    /// Untrusted wallet public key as hex without `0x`.
611    #[serde(rename = "publicKey")]
612    pub public_key: Ed25519PublicKey,
613}
614
615#[derive(Clone, Copy, Debug, Eq, PartialEq, Deserialize, Serialize)]
616enum TonAddressReplyName {
617    #[serde(rename = "ton_addr")]
618    TonAddr,
619}
620
621impl TonAddressItemReply {
622    /// Creates a canonical `ton_addr` reply.
623    #[must_use]
624    pub fn new(
625        address: RawAccountAddress,
626        network: NetworkId,
627        wallet_state_init: WalletStateInit,
628        public_key: Ed25519PublicKey,
629    ) -> Self {
630        Self {
631            name: TonAddressReplyName::TonAddr,
632            address,
633            network,
634            wallet_state_init,
635            public_key,
636        }
637    }
638
639    /// Verifies that `walletStateInit` derives this address and stores the
640    /// advertised key under a recognized standard wallet data layout.
641    pub fn verify_standard_wallet(&self) -> Result<StandardWalletState, WalletStateError> {
642        self.wallet_state_init
643            .verify_standard_wallet(&self.address, &self.public_key)
644    }
645}
646
647/// dApp domain bound into a `ton_proof` signature.
648#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
649#[serde(rename_all = "camelCase")]
650pub struct TonProofDomain {
651    /// UTF-8 byte length of `value`.
652    length_bytes: u32,
653    /// Domain name without scheme or encoding.
654    value: String,
655}
656
657#[derive(Deserialize)]
658#[serde(rename_all = "camelCase", deny_unknown_fields)]
659struct RawTonProofDomain {
660    length_bytes: u32,
661    value: String,
662}
663
664impl TonProofDomain {
665    /// Creates a domain whose declared wire length matches its UTF-8 bytes.
666    pub fn new(value: String) -> Result<Self, SigningError> {
667        let length_bytes = u32::try_from(value.len()).map_err(|_| SigningError::LengthOverflow)?;
668        Ok(Self {
669            length_bytes,
670            value,
671        })
672    }
673
674    /// Returns the validated UTF-8 byte length carried on the wire.
675    #[must_use]
676    pub const fn length_bytes(&self) -> u32 {
677        self.length_bytes
678    }
679
680    /// Returns the exact domain name bound into the signature.
681    #[must_use]
682    pub fn value(&self) -> &str {
683        &self.value
684    }
685}
686
687impl<'de> Deserialize<'de> for TonProofDomain {
688    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
689    where
690        D: Deserializer<'de>,
691    {
692        let raw = RawTonProofDomain::deserialize(deserializer)?;
693        let Ok(actual) = u32::try_from(raw.value.len()) else {
694            return Err(de::Error::custom("ton_proof domain exceeds uint32 length"));
695        };
696        if actual != raw.length_bytes {
697            return Err(de::Error::custom(
698                "ton_proof domain lengthBytes does not match UTF-8 byte length",
699            ));
700        }
701        Ok(Self {
702            length_bytes: raw.length_bytes,
703            value: raw.value,
704        })
705    }
706}
707
708/// Wallet ownership proof returned during connect.
709#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)]
710#[serde(deny_unknown_fields)]
711pub struct TonProof {
712    /// Unix signing time in seconds.
713    pub timestamp: Uint64String,
714    /// Bound application domain.
715    pub domain: TonProofDomain,
716    /// Original dApp challenge.
717    pub payload: String,
718    /// Base64 Ed25519 signature.
719    pub signature: Ed25519Signature,
720}
721
722impl TonProof {
723    /// Reconstructs the digest bound by this proof.
724    pub fn signing_hash(&self, address: &RawAccountAddress) -> Result<[u8; 32], SigningError> {
725        ton_proof_signing_hash(
726            address,
727            self.domain.value(),
728            self.timestamp.get(),
729            &self.payload,
730        )
731    }
732
733    /// Verifies the proof signature with the connected account's trusted key.
734    pub fn verify(
735        &self,
736        address: &RawAccountAddress,
737        public_key: &Ed25519PublicKey,
738    ) -> Result<bool, SigningError> {
739        verify_signature(
740            &self.signing_hash(address)?,
741            &self.signature,
742            public_key,
743            SignatureDomain::Empty,
744        )
745    }
746
747    /// Verifies this proof using the address-bound key from a standard wallet
748    /// `StateInit`, never trusting the advertised key by itself.
749    pub fn verify_with_account(
750        &self,
751        account: &TonAddressItemReply,
752    ) -> Result<bool, AccountVerificationError> {
753        let wallet = account.verify_standard_wallet()?;
754        self.verify(&account.address, wallet.public_key())
755            .map_err(Into::into)
756    }
757}
758
759/// Successful `ton_proof` item reply.
760#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)]
761#[serde(deny_unknown_fields)]
762pub struct TonProofItemReply {
763    #[serde(rename = "name")]
764    name: TonProofReplyName,
765    /// Signed proof.
766    pub proof: TonProof,
767}
768
769#[derive(Clone, Copy, Debug, Eq, PartialEq, Deserialize, Serialize)]
770enum TonProofReplyName {
771    #[serde(rename = "ton_proof")]
772    TonProof,
773}
774
775impl TonProofItemReply {
776    /// Creates a canonical successful `ton_proof` reply.
777    #[must_use]
778    pub const fn new(proof: TonProof) -> Self {
779        Self {
780            name: TonProofReplyName::TonProof,
781            proof,
782        }
783    }
784}
785
786/// Per-connect-item protocol error catalogue.
787#[derive(Clone, Copy, Debug, Eq, PartialEq)]
788#[repr(u16)]
789pub enum ConnectItemErrorCode {
790    /// Unexpected wallet-side failure.
791    Unknown = 0,
792    /// Wallet does not implement the requested item.
793    MethodNotSupported = 400,
794}
795
796numeric_enum_serde!(ConnectItemErrorCode {
797    Unknown = 0,
798    MethodNotSupported = 400,
799});
800
801#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)]
802#[serde(deny_unknown_fields)]
803struct ConnectItemErrorBody {
804    code: ConnectItemErrorCode,
805    #[serde(
806        default,
807        deserialize_with = "crate::value::deserialize_optional_non_null",
808        skip_serializing_if = "Option::is_none"
809    )]
810    message: Option<String>,
811}
812
813/// Error reply for a specific requested connect item.
814#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)]
815#[serde(deny_unknown_fields)]
816pub struct ConnectItemError {
817    name: String,
818    error: ConnectItemErrorBody,
819}
820
821impl ConnectItemError {
822    /// Creates a per-item failure preserving the requested item name.
823    #[must_use]
824    pub fn new(name: String, code: ConnectItemErrorCode, message: Option<String>) -> Self {
825        Self {
826            name,
827            error: ConnectItemErrorBody { code, message },
828        }
829    }
830
831    /// Returns the requested item name.
832    #[must_use]
833    pub fn name(&self) -> &str {
834        &self.name
835    }
836
837    /// Returns the protocol error code.
838    #[must_use]
839    pub const fn code(&self) -> ConnectItemErrorCode {
840        self.error.code
841    }
842
843    /// Returns the optional wallet diagnostic.
844    #[must_use]
845    pub fn message(&self) -> Option<&str> {
846        self.error.message.as_deref()
847    }
848}
849
850/// Reply corresponding to one requested connect item.
851#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)]
852#[serde(untagged)]
853pub enum ConnectItemReply {
854    /// Connected account information.
855    TonAddress(TonAddressItemReply),
856    /// Successful ownership proof.
857    TonProof(TonProofItemReply),
858    /// Per-item failure, including unsupported future item names.
859    Error(ConnectItemError),
860}
861
862impl ConnectItemReply {
863    /// Returns the connect-item discriminator echoed by this reply.
864    #[must_use]
865    pub fn name(&self) -> &str {
866        match self {
867            Self::TonAddress(_) => "ton_addr",
868            Self::TonProof(_) => "ton_proof",
869            Self::Error(error) => error.name(),
870        }
871    }
872
873    /// Creates the protocol-required error for an unsupported requested item.
874    #[must_use]
875    pub fn unsupported(item: &ConnectItem, message: Option<String>) -> Self {
876        Self::Error(ConnectItemError::new(
877            item.name().to_owned(),
878            ConnectItemErrorCode::MethodNotSupported,
879            message,
880        ))
881    }
882}
883
884/// Payload of a successful connect event.
885#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)]
886#[serde(deny_unknown_fields)]
887pub struct ConnectEventPayload {
888    /// Replies to the requested connect items.
889    pub items: Vec<ConnectItemReply>,
890    /// Wallet runtime and capabilities.
891    pub device: DeviceInfo,
892}
893
894/// Connect-event error catalogue.
895#[derive(Clone, Copy, Debug, Eq, PartialEq)]
896#[repr(u16)]
897pub enum ConnectEventErrorCode {
898    /// Unexpected wallet-side failure.
899    Unknown = 0,
900    /// Malformed connect request.
901    BadRequest = 1,
902    /// Manifest could not be fetched.
903    ManifestNotFound = 2,
904    /// Manifest JSON or schema is invalid.
905    ManifestContent = 3,
906    /// Unknown or revoked app session.
907    UnknownApp = 100,
908    /// User declined the connection.
909    UserDeclined = 300,
910    /// Requested method is unsupported.
911    MethodNotSupported = 400,
912}
913
914numeric_enum_serde!(ConnectEventErrorCode {
915    Unknown = 0,
916    BadRequest = 1,
917    ManifestNotFound = 2,
918    ManifestContent = 3,
919    UnknownApp = 100,
920    UserDeclined = 300,
921    MethodNotSupported = 400,
922});
923
924/// Error details carried by a `connect_error` event.
925#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)]
926#[serde(deny_unknown_fields)]
927pub struct ConnectEventError {
928    /// Protocol error code.
929    pub code: ConnectEventErrorCode,
930    /// Human-readable wallet diagnostic.
931    pub message: String,
932}
933
934/// Wallet-initiated event sent to the dApp.
935#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)]
936#[serde(tag = "event", rename_all = "snake_case", deny_unknown_fields)]
937pub enum ConnectEvent {
938    /// Successful connection.
939    Connect {
940        /// Monotonic wallet event identifier.
941        id: u64,
942        /// Requested item replies and wallet capabilities.
943        payload: ConnectEventPayload,
944        /// Optional response to an embedded request.
945        #[serde(
946            default,
947            deserialize_with = "crate::value::deserialize_optional_non_null",
948            skip_serializing_if = "Option::is_none"
949        )]
950        response: Option<EmbeddedResponse>,
951    },
952    /// Failed connection.
953    ConnectError {
954        /// Monotonic wallet event identifier.
955        id: u64,
956        /// Protocol error details.
957        payload: ConnectEventError,
958    },
959    /// Wallet-initiated session termination.
960    Disconnect {
961        /// Monotonic wallet event identifier.
962        id: u64,
963        /// Reserved object; currently empty.
964        payload: EmptyObject,
965    },
966}
967
968impl ConnectEvent {
969    /// Returns the monotonic wallet event identifier.
970    #[must_use]
971    pub const fn id(&self) -> u64 {
972        match self {
973            Self::Connect { id, .. }
974            | Self::ConnectError { id, .. }
975            | Self::Disconnect { id, .. } => *id,
976        }
977    }
978
979    /// Reports whether this event ends or rejects the session.
980    #[must_use]
981    pub const fn terminates_session(&self) -> bool {
982        matches!(self, Self::ConnectError { .. } | Self::Disconnect { .. })
983    }
984
985    /// Validates a connect response against the exact request and optional
986    /// embedded action carried by the link.
987    ///
988    /// Replies may be reordered, but their names and multiplicities must match
989    /// the requested items. A successful connect always needs exactly one
990    /// successful `ton_addr` reply because that address becomes the immutable
991    /// session identity.
992    pub fn validate_for_connect(
993        &self,
994        request: &ConnectRequest,
995        embedded_request: Option<&crate::EmbeddedRequest>,
996    ) -> Result<(), ConnectValidationError> {
997        let Self::Connect {
998            payload, response, ..
999        } = self
1000        else {
1001            return if matches!(self, Self::ConnectError { .. }) {
1002                Ok(())
1003            } else {
1004                Err(ConnectValidationError::NotAConnectResponse)
1005            };
1006        };
1007
1008        payload.device.validate()?;
1009        let requested = request.items.as_slice();
1010        if requested
1011            .iter()
1012            .filter(|item| matches!(item, ConnectItem::TonAddr { .. }))
1013            .count()
1014            != 1
1015        {
1016            return Err(ConnectValidationError::InvalidTonAddressRequest);
1017        }
1018        if requested.len() != payload.items.len()
1019            || requested.iter().any(|item| {
1020                let requested_count = requested
1021                    .iter()
1022                    .filter(|candidate| candidate.name() == item.name())
1023                    .count();
1024                let reply_count = payload
1025                    .items
1026                    .iter()
1027                    .filter(|reply| reply.name() == item.name())
1028                    .count();
1029                requested_count != reply_count
1030            })
1031        {
1032            return Err(ConnectValidationError::ItemReplyMismatch);
1033        }
1034
1035        let mut accounts = payload.items.iter().filter_map(|reply| match reply {
1036            ConnectItemReply::TonAddress(account) => Some(account),
1037            ConnectItemReply::TonProof(_) | ConnectItemReply::Error(_) => None,
1038        });
1039        let Some(account) = accounts.next() else {
1040            return Err(ConnectValidationError::MissingTonAddressReply);
1041        };
1042        if accounts.next().is_some() {
1043            return Err(ConnectValidationError::MultipleTonAddressReplies);
1044        }
1045        let requested_network = requested.iter().find_map(|item| match item {
1046            ConnectItem::TonAddr { network } => network.as_ref(),
1047            ConnectItem::TonProof { .. } | ConnectItem::Unsupported { .. } => None,
1048        });
1049        if requested_network.is_some_and(|network| network != &account.network) {
1050            return Err(ConnectValidationError::NetworkMismatch);
1051        }
1052
1053        for proof in payload.items.iter().filter_map(|reply| match reply {
1054            ConnectItemReply::TonProof(reply) => Some(&reply.proof),
1055            ConnectItemReply::TonAddress(_) | ConnectItemReply::Error(_) => None,
1056        }) {
1057            if !requested.iter().any(|item| {
1058                matches!(item, ConnectItem::TonProof { payload } if payload == &proof.payload)
1059            }) {
1060                return Err(ConnectValidationError::ProofPayloadMismatch);
1061            }
1062        }
1063
1064        let supports_embedded = payload
1065            .device
1066            .features
1067            .iter()
1068            .any(|feature| matches!(feature, Feature::EmbeddedRequest));
1069        match (embedded_request, response, supports_embedded) {
1070            (None, None, false | true) | (Some(_), None, false) => Ok(()),
1071            (None, Some(_), false | true) | (Some(_), Some(_), false) => {
1072                Err(ConnectValidationError::UnexpectedEmbeddedResponse)
1073            }
1074            (Some(_), None, true) => Err(ConnectValidationError::MissingEmbeddedResponse),
1075            (Some(request), Some(response), true) => {
1076                let _ = response.validate_for(request)?;
1077                Ok(())
1078            }
1079        }
1080    }
1081}
1082
1083/// A connect event cannot be correlated safely with its initiating request.
1084#[derive(Clone, Debug, Eq, thiserror::Error, PartialEq)]
1085pub enum ConnectValidationError {
1086    /// A disconnect event was passed where a connect response was expected.
1087    #[error("disconnect event is not a response to a connect request")]
1088    NotAConnectResponse,
1089    /// A successful connection requires exactly one requested `ton_addr` item.
1090    #[error("connect request must contain exactly one ton_addr item")]
1091    InvalidTonAddressRequest,
1092    /// Reply names or counts do not match the requested items.
1093    #[error("connect item replies do not match the request")]
1094    ItemReplyMismatch,
1095    /// The wallet did not return the account required to establish a session.
1096    #[error("successful connect event has no ton_addr reply")]
1097    MissingTonAddressReply,
1098    /// More than one account identity was returned for one session.
1099    #[error("successful connect event has multiple ton_addr replies")]
1100    MultipleTonAddressReplies,
1101    /// The returned account network differs from the explicit request network.
1102    #[error("connected account network differs from the requested network")]
1103    NetworkMismatch,
1104    /// A proof does not echo any challenge from the connect request.
1105    #[error("ton_proof reply payload does not match the requested challenge")]
1106    ProofPayloadMismatch,
1107    /// A response appeared without a supported embedded request.
1108    #[error("connect event contains an unexpected embedded response")]
1109    UnexpectedEmbeddedResponse,
1110    /// The wallet advertised embedded support but omitted the action response.
1111    #[error("connect event omitted the embedded request response")]
1112    MissingEmbeddedResponse,
1113    /// Runtime wallet metadata violates protocol invariants.
1114    #[error(transparent)]
1115    InvalidDeviceInfo(#[from] DeviceInfoValidationError),
1116    /// Embedded action result does not match its method.
1117    #[error(transparent)]
1118    InvalidEmbeddedResponse(#[from] ResponseValidationError),
1119}
1120
1121#[cfg(test)]
1122mod tests {
1123    use base64::Engine as _;
1124    use ed25519_dalek::{Signer as _, SigningKey};
1125    use ton_core::{cell::TonCell, traits::tlb::TLB as _};
1126
1127    use super::*;
1128    use crate::{EmbeddedResponseSuccess, ValueError};
1129
1130    fn connect_account(network: &str) -> Result<TonAddressItemReply, Box<dyn std::error::Error>> {
1131        let mut state = TonCell::builder();
1132        state.write_bit(false)?;
1133        state.write_bit(false)?;
1134        state.write_bit(true)?;
1135        state.write_ref(TonCell::empty().to_owned())?;
1136        state.write_bit(true)?;
1137        state.write_ref(TonCell::empty().to_owned())?;
1138        state.write_bit(false)?;
1139        let state = WalletStateInit::from_boc(state.build()?.to_boc()?)?;
1140        let address = state.derive_address(0)?;
1141        Ok(TonAddressItemReply::new(
1142            address,
1143            NetworkId::try_from(network)?,
1144            state,
1145            Ed25519PublicKey::from_bytes([0_u8; 32]),
1146        ))
1147    }
1148
1149    fn device(embedded: bool) -> Result<DeviceInfo, DeviceInfoValidationError> {
1150        let mut features = vec![Feature::SendTransaction(SendTransactionFeature {
1151            max_messages: 1,
1152            extra_currency_supported: Some(false),
1153            item_types: None,
1154        })];
1155        if embedded {
1156            features.push(Feature::EmbeddedRequest);
1157        }
1158        DeviceInfo::new(
1159            DevicePlatform::Browser,
1160            "wallet".to_owned(),
1161            "1".to_owned(),
1162            2,
1163            features,
1164        )
1165    }
1166
1167    fn connect_request(items: Vec<ConnectItem>) -> Result<ConnectRequest, ValueError> {
1168        Ok(ConnectRequest {
1169            manifest_url: HttpsUrl::try_from("https://app.example/manifest.json")?,
1170            items: NonEmptyVec::try_from(items)?,
1171        })
1172    }
1173
1174    fn connect_success(
1175        items: Vec<ConnectItemReply>,
1176        embedded: bool,
1177        response: Option<EmbeddedResponse>,
1178    ) -> Result<ConnectEvent, DeviceInfoValidationError> {
1179        Ok(ConnectEvent::Connect {
1180            id: 1,
1181            payload: ConnectEventPayload {
1182                items,
1183                device: device(embedded)?,
1184            },
1185            response,
1186        })
1187    }
1188
1189    #[test]
1190    fn connect_request_uses_canonical_item_discriminators() {
1191        let request = r#"{
1192            "manifestUrl":"https://example.com/tonconnect-manifest.json",
1193            "items":[{"name":"ton_addr","network":"-239"},{"name":"ton_proof","payload":"nonce"}]
1194        }"#;
1195        let decoded = serde_json::from_str::<ConnectRequest>(request);
1196        assert!(decoded.is_ok());
1197        assert!(
1198            decoded
1199                .and_then(|value| serde_json::to_string(&value))
1200                .is_ok()
1201        );
1202        assert!(matches!(
1203            ConnectItem::from(TonAddressItem { network: None }),
1204            ConnectItem::TonAddr { network: None }
1205        ));
1206        assert!(matches!(
1207            ConnectItem::from(TonProofItem {
1208                payload: "nonce".to_owned(),
1209            }),
1210            ConnectItem::TonProof { payload } if payload == "nonce"
1211        ));
1212    }
1213
1214    #[test]
1215    fn unknown_connect_item_round_trips_and_can_receive_error_400()
1216    -> Result<(), Box<dyn std::error::Error>> {
1217        let json = r#"{"name":"future_identity","scope":"read","revision":3}"#;
1218        let item = serde_json::from_str::<ConnectItem>(json)?;
1219        assert_eq!(item.name(), "future_identity");
1220        assert!(matches!(item, ConnectItem::Unsupported { .. }));
1221        assert_eq!(
1222            serde_json::from_str::<serde_json::Value>(&serde_json::to_string(&item)?)?,
1223            serde_json::from_str::<serde_json::Value>(json)?
1224        );
1225
1226        let reply = ConnectItemReply::unsupported(&item, Some("not supported".to_owned()));
1227        assert!(matches!(
1228            reply,
1229            ConnectItemReply::Error(error)
1230                if error.name() == "future_identity"
1231                    && error.code() == ConnectItemErrorCode::MethodNotSupported
1232                    && error.message() == Some("not supported")
1233        ));
1234        assert!(ConnectItem::unsupported("future_identity".to_owned(), BTreeMap::new()).is_ok());
1235        assert!(ConnectItem::unsupported(String::new(), BTreeMap::new()).is_err());
1236        assert!(
1237            ConnectItem::unsupported(
1238                "future_identity".to_owned(),
1239                BTreeMap::from([("name".to_owned(), Value::String("shadow".to_owned()))]),
1240            )
1241            .is_err()
1242        );
1243        Ok(())
1244    }
1245
1246    #[test]
1247    fn known_connect_items_still_reject_unknown_fields() {
1248        assert!(serde_json::from_str::<ConnectItem>(r#"{"network":"-239"}"#).is_err());
1249        assert!(serde_json::from_str::<ConnectItem>(r#"{"name":""}"#).is_err());
1250        assert!(
1251            serde_json::from_str::<ConnectItem>(
1252                r#"{"name":"ton_addr","network":"-239","future":true}"#
1253            )
1254            .is_err()
1255        );
1256        assert!(
1257            serde_json::from_str::<ConnectItem>(
1258                r#"{"name":"ton_proof","payload":"nonce","future":true}"#
1259            )
1260            .is_err()
1261        );
1262    }
1263
1264    #[test]
1265    fn feature_supports_legacy_and_current_wire_forms() {
1266        assert!(matches!(
1267            serde_json::from_str::<Feature>(r#""SendTransaction""#),
1268            Ok(Feature::LegacySendTransaction)
1269        ));
1270        let current = r#"{"name":"SendTransaction","maxMessages":4,"extraCurrencySupported":false,"itemTypes":["ton"]}"#;
1271        assert!(matches!(
1272            serde_json::from_str::<Feature>(current),
1273            Ok(Feature::SendTransaction(SendTransactionFeature {
1274                max_messages: 4,
1275                ..
1276            }))
1277        ));
1278    }
1279
1280    #[test]
1281    fn feature_rejects_zero_limits_and_empty_or_duplicate_arrays() {
1282        let invalid = [
1283            r#"{"name":"SendTransaction","maxMessages":0}"#,
1284            r#"{"name":"SendTransaction","maxMessages":1,"itemTypes":[]}"#,
1285            r#"{"name":"SendTransaction","maxMessages":1,"itemTypes":["ton","ton"]}"#,
1286            r#"{"name":"SignMessage","maxMessages":0}"#,
1287            r#"{"name":"SignData","types":[]}"#,
1288            r#"{"name":"SignData","types":["text","text"]}"#,
1289        ];
1290        for value in invalid {
1291            assert!(
1292                serde_json::from_str::<Feature>(value).is_err(),
1293                "accepted {value}"
1294            );
1295        }
1296    }
1297
1298    #[test]
1299    fn device_info_rejects_invalid_identity_version_and_duplicate_features() {
1300        let invalid = [
1301            r#"{"platform":"browser","appName":"","appVersion":"1","maxProtocolVersion":2,"features":[]}"#,
1302            r#"{"platform":"browser","appName":"wallet","appVersion":"","maxProtocolVersion":2,"features":[]}"#,
1303            r#"{"platform":"browser","appName":"wallet","appVersion":"1","maxProtocolVersion":1,"features":[]}"#,
1304            r#"{"platform":"browser","appName":"wallet","appVersion":"1","maxProtocolVersion":2,"features":["SendTransaction",{"name":"SendTransaction","maxMessages":4}]}"#,
1305        ];
1306        for value in invalid {
1307            assert!(
1308                serde_json::from_str::<DeviceInfo>(value).is_err(),
1309                "accepted {value}"
1310            );
1311        }
1312    }
1313
1314    #[test]
1315    fn event_ids_are_non_negative_in_rust_and_unknown_fields_are_rejected() {
1316        let negative = r#"{"event":"disconnect","id":-1,"payload":{}}"#;
1317        let extra =
1318            r#"{"event":"connect_error","id":1,"payload":{"code":1,"message":"bad"},"extra":true}"#;
1319        assert!(serde_json::from_str::<ConnectEvent>(negative).is_err());
1320        assert!(serde_json::from_str::<ConnectEvent>(extra).is_err());
1321    }
1322
1323    #[test]
1324    fn ton_proof_uses_string_timestamp_and_checks_domain_byte_length() -> Result<(), SigningError> {
1325        let proof = TonProof {
1326            timestamp: Uint64String::from(1_700_000_000),
1327            domain: TonProofDomain::new("пример.рф".to_owned())?,
1328            payload: "nonce".to_owned(),
1329            signature: Ed25519Signature::from_bytes([0_u8; 64]),
1330        };
1331        assert_eq!(proof.domain.length_bytes(), 17);
1332        let encoded = serde_json::to_string(&proof);
1333        assert!(
1334            encoded
1335                .as_ref()
1336                .is_ok_and(|json| json.contains(r#""timestamp":"1700000000""#))
1337        );
1338
1339        let numeric_timestamp = r#"{
1340            "timestamp":1700000000,
1341            "domain":{"lengthBytes":11,"value":"example.com"},
1342            "payload":"nonce",
1343            "signature":"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=="
1344        }"#;
1345        let wrong_utf8_length = r#"{
1346            "timestamp":"1700000000",
1347            "domain":{"lengthBytes":9,"value":"пример.рф"},
1348            "payload":"nonce",
1349            "signature":"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=="
1350        }"#;
1351        assert!(serde_json::from_str::<TonProof>(numeric_timestamp).is_err());
1352        assert!(serde_json::from_str::<TonProof>(wrong_utf8_length).is_err());
1353        Ok(())
1354    }
1355
1356    #[test]
1357    fn ton_proof_wrapper_reconstructs_and_verifies_the_signed_fields()
1358    -> Result<(), Box<dyn std::error::Error>> {
1359        let address = RawAccountAddress::new(0, [0x22; 32]);
1360        let signing_key = SigningKey::from_bytes(&[0x33; 32]);
1361        let public_key = Ed25519PublicKey::from_bytes(signing_key.verifying_key().to_bytes());
1362        let mut proof = TonProof {
1363            timestamp: Uint64String::from(1_700_000_000),
1364            domain: TonProofDomain::new("example.com".to_owned())?,
1365            payload: "single-use-nonce".to_owned(),
1366            signature: Ed25519Signature::from_bytes([0_u8; 64]),
1367        };
1368        proof.signature = Ed25519Signature::from_bytes(
1369            signing_key.sign(&proof.signing_hash(&address)?).to_bytes(),
1370        );
1371        assert!(proof.verify(&address, &public_key)?);
1372        proof.payload.push_str("-changed");
1373        assert!(!proof.verify(&address, &public_key)?);
1374        Ok(())
1375    }
1376
1377    #[test]
1378    #[allow(
1379        clippy::too_many_lines,
1380        reason = "keeps every connect correlation outcome in one state matrix"
1381    )]
1382    fn connect_response_correlation_covers_every_terminal_branch()
1383    -> Result<(), Box<dyn std::error::Error>> {
1384        let account = connect_account("-239")?;
1385        let request = connect_request(vec![ConnectItem::TonAddr {
1386            network: Some(NetworkId::try_from("-239")?),
1387        }])?;
1388        let success = connect_success(
1389            vec![ConnectItemReply::TonAddress(account.clone())],
1390            false,
1391            None,
1392        )?;
1393        assert_eq!(success.validate_for_connect(&request, None), Ok(()));
1394
1395        let connect_error = ConnectEvent::ConnectError {
1396            id: 2,
1397            payload: ConnectEventError {
1398                code: ConnectEventErrorCode::UserDeclined,
1399                message: "declined".to_owned(),
1400            },
1401        };
1402        assert_eq!(connect_error.validate_for_connect(&request, None), Ok(()));
1403        assert_eq!(
1404            ConnectEvent::Disconnect {
1405                id: 3,
1406                payload: EmptyObject,
1407            }
1408            .validate_for_connect(&request, None),
1409            Err(ConnectValidationError::NotAConnectResponse)
1410        );
1411
1412        let no_address = connect_request(vec![ConnectItem::TonProof {
1413            payload: "nonce".to_owned(),
1414        }])?;
1415        assert_eq!(
1416            success.validate_for_connect(&no_address, None),
1417            Err(ConnectValidationError::InvalidTonAddressRequest)
1418        );
1419        let duplicate_address = connect_request(vec![
1420            ConnectItem::TonAddr { network: None },
1421            ConnectItem::TonAddr { network: None },
1422        ])?;
1423        assert_eq!(
1424            success.validate_for_connect(&duplicate_address, None),
1425            Err(ConnectValidationError::InvalidTonAddressRequest)
1426        );
1427
1428        let no_replies = connect_success(Vec::new(), false, None)?;
1429        assert_eq!(
1430            no_replies.validate_for_connect(&request, None),
1431            Err(ConnectValidationError::ItemReplyMismatch)
1432        );
1433        let account_error = connect_success(
1434            vec![ConnectItemReply::unsupported(
1435                request.items.as_slice().first().ok_or("ton_addr item")?,
1436                None,
1437            )],
1438            false,
1439            None,
1440        )?;
1441        assert_eq!(
1442            account_error.validate_for_connect(&request, None),
1443            Err(ConnectValidationError::MissingTonAddressReply)
1444        );
1445
1446        let wrong_network = connect_success(
1447            vec![ConnectItemReply::TonAddress(connect_account("-3")?)],
1448            false,
1449            None,
1450        )?;
1451        assert_eq!(
1452            wrong_network.validate_for_connect(&request, None),
1453            Err(ConnectValidationError::NetworkMismatch)
1454        );
1455
1456        let proof_request = connect_request(vec![
1457            ConnectItem::TonAddr { network: None },
1458            ConnectItem::TonProof {
1459                payload: "expected".to_owned(),
1460            },
1461        ])?;
1462        let proof = TonProof {
1463            timestamp: Uint64String::from(1),
1464            domain: TonProofDomain::new("app.example".to_owned())?,
1465            payload: "wrong".to_owned(),
1466            signature: Ed25519Signature::from_bytes([0_u8; 64]),
1467        };
1468        let proof_mismatch = connect_success(
1469            vec![
1470                ConnectItemReply::TonAddress(account.clone()),
1471                ConnectItemReply::TonProof(TonProofItemReply::new(proof)),
1472            ],
1473            false,
1474            None,
1475        )?;
1476        assert_eq!(
1477            proof_mismatch.validate_for_connect(&proof_request, None),
1478            Err(ConnectValidationError::ProofPayloadMismatch)
1479        );
1480
1481        let embedded_request = crate::decode_embedded_request_param(
1482            &base64::engine::general_purpose::URL_SAFE_NO_PAD
1483                .encode(r#"{"m":"st","ms":[{"a":"Ef8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADAU","am":"1"}]}"#),
1484        )?;
1485        let embedded_response = EmbeddedResponse::Success(EmbeddedResponseSuccess {
1486            result: crate::WalletResult::String(
1487                base64::engine::general_purpose::STANDARD.encode(TonCell::EMPTY_BOC),
1488            ),
1489        });
1490        let unexpected = connect_success(
1491            vec![ConnectItemReply::TonAddress(account.clone())],
1492            false,
1493            Some(embedded_response.clone()),
1494        )?;
1495        assert_eq!(
1496            unexpected.validate_for_connect(&request, None),
1497            Err(ConnectValidationError::UnexpectedEmbeddedResponse)
1498        );
1499        let missing = connect_success(
1500            vec![ConnectItemReply::TonAddress(account.clone())],
1501            true,
1502            None,
1503        )?;
1504        assert_eq!(
1505            missing.validate_for_connect(&request, Some(&embedded_request)),
1506            Err(ConnectValidationError::MissingEmbeddedResponse)
1507        );
1508        let embedded_success = connect_success(
1509            vec![ConnectItemReply::TonAddress(account)],
1510            true,
1511            Some(embedded_response),
1512        )?;
1513        assert_eq!(
1514            embedded_success.validate_for_connect(&request, Some(&embedded_request)),
1515            Ok(())
1516        );
1517        Ok(())
1518    }
1519}