1use std::future::Future;
4
5use thiserror::Error;
6
7use crate::{
8 AppRequest, ConnectEvent, ConnectRequest, DeviceInfo, DeviceInfoValidationError, HttpsUrl,
9 WalletResponse,
10};
11
12#[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 #[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 #[must_use]
50 pub fn name(&self) -> &str {
51 &self.name
52 }
53
54 #[must_use]
56 pub const fn image(&self) -> &HttpsUrl {
57 &self.image
58 }
59
60 #[must_use]
62 pub fn tondns(&self) -> Option<&str> {
63 self.tondns.as_deref()
64 }
65
66 #[must_use]
68 pub const fn about_url(&self) -> &HttpsUrl {
69 &self.about_url
70 }
71}
72
73#[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 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 #[must_use]
104 pub const fn device_info(&self) -> &DeviceInfo {
105 &self.device_info
106 }
107
108 #[must_use]
110 pub const fn wallet_info(&self) -> Option<&InjectedWalletInfo> {
111 self.wallet_info.as_ref()
112 }
113
114 #[must_use]
116 pub const fn protocol_version(&self) -> u32 {
117 self.protocol_version
118 }
119
120 #[must_use]
122 pub const fn is_wallet_browser(&self) -> bool {
123 self.is_wallet_browser
124 }
125
126 #[must_use]
128 pub const fn supports(&self, requested_version: u32) -> bool {
129 requested_version > 0 && requested_version <= self.protocol_version
130 }
131}
132
133pub type JsBridgeEventListener = Box<dyn Fn(ConnectEvent) + Send + Sync + 'static>;
135
136pub trait JsBridge: Send + Sync {
141 type Error;
143 type Subscription;
145
146 fn descriptor(&self) -> &JsBridgeDescriptor;
148
149 fn connect(
151 &self,
152 protocol_version: u32,
153 request: ConnectRequest,
154 ) -> impl Future<Output = Result<ConnectEvent, Self::Error>> + Send;
155
156 fn restore_connection(&self) -> impl Future<Output = Result<ConnectEvent, Self::Error>> + Send;
158
159 fn send(
161 &self,
162 request: AppRequest,
163 ) -> impl Future<Output = Result<WalletResponse, Self::Error>> + Send;
164
165 fn listen(&self, listener: JsBridgeEventListener) -> Result<Self::Subscription, Self::Error>;
167}
168
169#[derive(Clone, Copy, Debug, Eq, Error, PartialEq)]
171pub enum JsBridgeContractError {
172 #[error("injected wallet metadata is invalid")]
174 InvalidWalletInfo,
175 #[error("injected bridge protocol version does not match DeviceInfo")]
177 ProtocolVersionMismatch,
178 #[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}