Skip to main content

ton_connect_core/
js_bridge.rs

1//! Runtime-neutral contract for an injected TON Connect JavaScript bridge.
2
3use std::future::Future;
4
5use thiserror::Error;
6
7use crate::{
8    AppRequest, ConnectEvent, ConnectRequest, DeviceInfo, DeviceInfoValidationError, HttpsUrl,
9    WalletResponse,
10};
11
12/// Optional wallet metadata exposed directly by an injected bridge.
13#[derive(Clone, Debug, Eq, PartialEq)]
14pub struct InjectedWalletInfo {
15    name: String,
16    image: HttpsUrl,
17    tondns: Option<String>,
18    about_url: HttpsUrl,
19}
20
21impl InjectedWalletInfo {
22    /// Creates metadata that can override a wallets-list entry.
23    #[allow(
24        clippy::case_sensitive_file_extension_comparisons,
25        reason = "the normative wallet metadata field requires lowercase .ton"
26    )]
27    pub fn new(
28        name: String,
29        image: HttpsUrl,
30        tondns: Option<String>,
31        about_url: HttpsUrl,
32    ) -> Result<Self, JsBridgeContractError> {
33        if name.is_empty()
34            || tondns
35                .as_ref()
36                .is_some_and(|value| value == ".ton" || !value.ends_with(".ton"))
37        {
38            return Err(JsBridgeContractError::InvalidWalletInfo);
39        }
40        Ok(Self {
41            name,
42            image,
43            tondns,
44            about_url,
45        })
46    }
47
48    /// Returns the wallet display name.
49    #[must_use]
50    pub fn name(&self) -> &str {
51        &self.name
52    }
53
54    /// Returns the wallet icon URL.
55    #[must_use]
56    pub const fn image(&self) -> &HttpsUrl {
57        &self.image
58    }
59
60    /// Returns the optional TON DNS identity.
61    #[must_use]
62    pub fn tondns(&self) -> Option<&str> {
63        self.tondns.as_deref()
64    }
65
66    /// Returns the wallet information URL.
67    #[must_use]
68    pub const fn about_url(&self) -> &HttpsUrl {
69        &self.about_url
70    }
71}
72
73/// Static properties exposed by `window.<key>.tonconnect`.
74#[derive(Clone, Debug, Eq, PartialEq)]
75pub struct JsBridgeDescriptor {
76    device_info: DeviceInfo,
77    wallet_info: Option<InjectedWalletInfo>,
78    protocol_version: u32,
79    is_wallet_browser: bool,
80}
81
82impl JsBridgeDescriptor {
83    /// Creates a self-consistent injected bridge descriptor.
84    pub fn new(
85        device_info: DeviceInfo,
86        wallet_info: Option<InjectedWalletInfo>,
87        protocol_version: u32,
88        is_wallet_browser: bool,
89    ) -> Result<Self, JsBridgeContractError> {
90        device_info.validate()?;
91        if protocol_version == 0 || protocol_version != device_info.max_protocol_version {
92            return Err(JsBridgeContractError::ProtocolVersionMismatch);
93        }
94        Ok(Self {
95            device_info,
96            wallet_info,
97            protocol_version,
98            is_wallet_browser,
99        })
100    }
101
102    /// Returns runtime-authoritative wallet metadata and features.
103    #[must_use]
104    pub const fn device_info(&self) -> &DeviceInfo {
105        &self.device_info
106    }
107
108    /// Returns optional metadata supplied outside wallets-list.
109    #[must_use]
110    pub const fn wallet_info(&self) -> Option<&InjectedWalletInfo> {
111        self.wallet_info.as_ref()
112    }
113
114    /// Returns the maximum protocol version accepted by `connect()`.
115    #[must_use]
116    pub const fn protocol_version(&self) -> u32 {
117        self.protocol_version
118    }
119
120    /// Reports whether the dApp runs inside the wallet browser.
121    #[must_use]
122    pub const fn is_wallet_browser(&self) -> bool {
123        self.is_wallet_browser
124    }
125
126    /// Reports whether a requested protocol revision is supported.
127    #[must_use]
128    pub const fn supports(&self, requested_version: u32) -> bool {
129        requested_version > 0 && requested_version <= self.protocol_version
130    }
131}
132
133/// Callback receiving wallet-initiated events from an injected bridge.
134pub type JsBridgeEventListener = Box<dyn Fn(ConnectEvent) + Send + Sync + 'static>;
135
136/// Runtime-neutral host contract matching `TonConnectBridge` from `bridge.md`.
137///
138/// Platform adapters implement this trait with JavaScript promises, Swift
139/// continuations, Kotlin coroutines, or another executor. Core owns no runtime.
140pub trait JsBridge: Send + Sync {
141    /// Adapter-specific call failure.
142    type Error;
143    /// Handle whose drop or explicit adapter operation removes a listener.
144    type Subscription;
145
146    /// Returns the injected bridge's static descriptor.
147    fn descriptor(&self) -> &JsBridgeDescriptor;
148
149    /// Starts a user-initiated connection.
150    fn connect(
151        &self,
152        protocol_version: u32,
153        request: ConnectRequest,
154    ) -> impl Future<Output = Result<ConnectEvent, Self::Error>> + Send;
155
156    /// Restores a previously approved session without a new prompt.
157    fn restore_connection(&self) -> impl Future<Output = Result<ConnectEvent, Self::Error>> + Send;
158
159    /// Sends one ordinary dApp RPC request and awaits its correlated response.
160    fn send(
161        &self,
162        request: AppRequest,
163    ) -> impl Future<Output = Result<WalletResponse, Self::Error>> + Send;
164
165    /// Registers a listener for wallet-initiated events.
166    fn listen(&self, listener: JsBridgeEventListener) -> Result<Self::Subscription, Self::Error>;
167}
168
169/// Injected bridge metadata is internally inconsistent.
170#[derive(Clone, Copy, Debug, Eq, Error, PartialEq)]
171pub enum JsBridgeContractError {
172    /// Display metadata is empty or has an invalid TON DNS value.
173    #[error("injected wallet metadata is invalid")]
174    InvalidWalletInfo,
175    /// Bridge and `DeviceInfo` protocol versions differ or are zero.
176    #[error("injected bridge protocol version does not match DeviceInfo")]
177    ProtocolVersionMismatch,
178    /// Injected runtime metadata violates `DeviceInfo` invariants.
179    #[error(transparent)]
180    InvalidDeviceInfo(#[from] DeviceInfoValidationError),
181}
182
183#[cfg(test)]
184mod tests {
185    use super::*;
186    use crate::{DevicePlatform, PROTOCOL_VERSION};
187
188    fn device_info(version: u32) -> DeviceInfo {
189        DeviceInfo {
190            platform: DevicePlatform::Browser,
191            app_name: "examplewallet".to_owned(),
192            app_version: "1.0.0".to_owned(),
193            max_protocol_version: version,
194            features: Vec::new(),
195        }
196    }
197
198    #[test]
199    fn descriptor_requires_one_consistent_nonzero_protocol_version() {
200        let version = u32::from(PROTOCOL_VERSION);
201        let descriptor = JsBridgeDescriptor::new(device_info(version), None, version, true);
202        assert!(
203            descriptor
204                .as_ref()
205                .is_ok_and(|value| value.supports(version))
206        );
207        let descriptor = descriptor.expect("valid descriptor");
208        assert_eq!(descriptor.device_info().app_name, "examplewallet");
209        assert_eq!(descriptor.protocol_version(), version);
210        assert_eq!(descriptor.wallet_info(), None);
211        assert!(!descriptor.supports(0));
212        assert!(!descriptor.supports(version.saturating_add(1)));
213        assert!(descriptor.is_wallet_browser());
214        assert!(matches!(
215            JsBridgeDescriptor::new(device_info(version), None, version.saturating_add(1), false),
216            Err(JsBridgeContractError::ProtocolVersionMismatch)
217        ));
218    }
219
220    #[test]
221    fn injected_wallet_metadata_validates_identity() -> Result<(), Box<dyn std::error::Error>> {
222        let image = HttpsUrl::try_from("https://wallet.example/icon.png")?;
223        let about = HttpsUrl::try_from("https://wallet.example/about")?;
224        let info = InjectedWalletInfo::new(
225            "Example Wallet".to_owned(),
226            image.clone(),
227            Some("example.ton".to_owned()),
228            about.clone(),
229        )?;
230        assert_eq!(info.name(), "Example Wallet");
231        assert_eq!(info.image(), &image);
232        assert_eq!(info.tondns(), Some("example.ton"));
233        assert_eq!(info.about_url(), &about);
234        assert!(matches!(
235            InjectedWalletInfo::new(String::new(), image, None, about),
236            Err(JsBridgeContractError::InvalidWalletInfo)
237        ));
238        Ok(())
239    }
240}