Skip to main content

ton_connect_core/
capability.rs

1//! Runtime capability checks for requests sent to a connected wallet.
2
3use thiserror::Error;
4
5use crate::{
6    DeviceInfo, EmbeddedRequest, Feature, KnownAppRequest, SignDataType, StructuredItemType,
7    TransactionPayload,
8};
9
10impl DeviceInfo {
11    /// Checks that this runtime `DeviceInfo` advertises every capability needed
12    /// by an ordinary RPC request.
13    ///
14    /// The connected wallet's `DeviceInfo.features` is authoritative. Calling
15    /// this before `send()` prevents an SDK from presenting an operation that
16    /// the wallet has already declared it cannot process.
17    pub fn validate_request(&self, request: &KnownAppRequest) -> Result<(), CapabilityError> {
18        match request {
19            KnownAppRequest::SendTransaction(request) => {
20                self.validate_transaction("sendTransaction", &request.payload, false)
21            }
22            KnownAppRequest::SignMessage(request) => {
23                self.validate_transaction("signMessage", &request.payload, true)
24            }
25            KnownAppRequest::SignData(request) => {
26                let required = request.payload.data_type();
27                let supported = self.features.iter().find_map(|feature| match feature {
28                    Feature::SignData(feature) => Some(feature.types()),
29                    Feature::LegacySendTransaction
30                    | Feature::SendTransaction(_)
31                    | Feature::SignMessage(_)
32                    | Feature::EmbeddedRequest => None,
33                });
34                let Some(supported) = supported else {
35                    return Err(CapabilityError::MethodNotSupported("signData"));
36                };
37                if !supported.contains(&required) {
38                    return Err(CapabilityError::SignDataTypeNotSupported(required));
39                }
40                Ok(())
41            }
42            // Disconnect is part of the session lifecycle and has no feature
43            // entry of its own in DeviceInfo.
44            KnownAppRequest::Disconnect(_) => Ok(()),
45        }
46    }
47
48    /// Checks both the `EmbeddedRequest` feature and the underlying method's
49    /// runtime capability.
50    pub fn validate_embedded_request(
51        &self,
52        request: &EmbeddedRequest,
53    ) -> Result<(), CapabilityError> {
54        if !self
55            .features
56            .iter()
57            .any(|feature| matches!(feature, Feature::EmbeddedRequest))
58        {
59            return Err(CapabilityError::EmbeddedRequestNotSupported);
60        }
61
62        match request {
63            EmbeddedRequest::SendTransaction(payload) => {
64                self.validate_transaction("sendTransaction", payload, false)
65            }
66            EmbeddedRequest::SignMessage(payload) => {
67                self.validate_transaction("signMessage", payload, true)
68            }
69            EmbeddedRequest::SignData(payload) => {
70                let required = payload.data_type();
71                let supported = self.features.iter().find_map(|feature| match feature {
72                    Feature::SignData(feature) => Some(feature.types()),
73                    Feature::LegacySendTransaction
74                    | Feature::SendTransaction(_)
75                    | Feature::SignMessage(_)
76                    | Feature::EmbeddedRequest => None,
77                });
78                let Some(supported) = supported else {
79                    return Err(CapabilityError::MethodNotSupported("signData"));
80                };
81                if !supported.contains(&required) {
82                    return Err(CapabilityError::SignDataTypeNotSupported(required));
83                }
84                Ok(())
85            }
86        }
87    }
88
89    fn validate_transaction(
90        &self,
91        method: &'static str,
92        payload: &TransactionPayload,
93        sign_only: bool,
94    ) -> Result<(), CapabilityError> {
95        let detailed = self.features.iter().find_map(|feature| match feature {
96            Feature::SendTransaction(feature) if !sign_only => Some((
97                feature.max_messages(),
98                feature.extra_currency_supported(),
99                feature.item_types(),
100            )),
101            Feature::SignMessage(feature) if sign_only => Some((
102                feature.max_messages(),
103                feature.extra_currency_supported(),
104                feature.item_types(),
105            )),
106            Feature::LegacySendTransaction
107            | Feature::SendTransaction(_)
108            | Feature::SignData(_)
109            | Feature::SignMessage(_)
110            | Feature::EmbeddedRequest => None,
111        });
112
113        let Some((max_messages, extra_currency_supported, item_types)) = detailed else {
114            // The deprecated string form predates explicit limits. It remains
115            // usable only for a basic raw sendTransaction, matching the
116            // compatibility behaviour of the reference SDK. Structured items
117            // and extra currencies require an explicit modern capability.
118            let legacy_send = !sign_only
119                && self
120                    .features
121                    .iter()
122                    .any(|feature| matches!(feature, Feature::LegacySendTransaction));
123            if !legacy_send {
124                return Err(CapabilityError::MethodNotSupported(method));
125            }
126            if payload.structured_item_types().is_some() {
127                return Err(CapabilityError::StructuredItemsNotSupported);
128            }
129            if payload.uses_extra_currency() {
130                return Err(CapabilityError::ExtraCurrencyNotSupported);
131            }
132            return Ok(());
133        };
134
135        if u64::try_from(payload.message_count())
136            .is_ok_and(|actual| actual > u64::from(max_messages))
137        {
138            return Err(CapabilityError::MessageLimitExceeded {
139                max_messages,
140                actual: payload.message_count(),
141            });
142        }
143        if payload.uses_extra_currency() && extra_currency_supported != Some(true) {
144            return Err(CapabilityError::ExtraCurrencyNotSupported);
145        }
146        if let Some(required_types) = payload.structured_item_types() {
147            let Some(supported_types) = item_types else {
148                return Err(CapabilityError::StructuredItemsNotSupported);
149            };
150            if let Some(unsupported) = required_types
151                .into_iter()
152                .find(|required| !supported_types.contains(required))
153            {
154                return Err(CapabilityError::StructuredItemTypeNotSupported(unsupported));
155            }
156        }
157        Ok(())
158    }
159}
160
161/// A request exceeds the capabilities advertised by the connected wallet.
162#[derive(Clone, Copy, Debug, Eq, Error, PartialEq)]
163pub enum CapabilityError {
164    /// The wallet did not advertise the requested RPC method.
165    #[error("wallet does not advertise TON Connect method {0}")]
166    MethodNotSupported(&'static str),
167    /// The batch is larger than the runtime-advertised limit.
168    #[error("request has {actual} messages, but wallet advertises at most {max_messages}")]
169    MessageLimitExceeded {
170        /// Runtime-advertised maximum.
171        max_messages: u32,
172        /// Number of messages or items in the request.
173        actual: usize,
174    },
175    /// The request carries extra currencies without explicit wallet support.
176    #[error("wallet does not advertise extra-currency support")]
177    ExtraCurrencyNotSupported,
178    /// The wallet only advertises raw message input for this method.
179    #[error("wallet does not advertise structured transaction items")]
180    StructuredItemsNotSupported,
181    /// A structured item kind is absent from the runtime capability.
182    #[error("wallet does not advertise structured item type {0:?}")]
183    StructuredItemTypeNotSupported(StructuredItemType),
184    /// A `signData` payload kind is absent from the runtime capability.
185    #[error("wallet does not advertise signData type {0:?}")]
186    SignDataTypeNotSupported(SignDataType),
187    /// The wallet does not advertise one-tap embedded requests.
188    #[error("wallet does not advertise embedded TON Connect requests")]
189    EmbeddedRequestNotSupported,
190}
191
192#[cfg(test)]
193mod tests {
194    use super::*;
195    use crate::{AppRequest, DevicePlatform};
196
197    const FRIENDLY: &str = "Ef8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADAU";
198
199    fn request(method: &str, payload: &serde_json::Value) -> KnownAppRequest {
200        AppRequest {
201            method: method.to_owned(),
202            params: vec![payload.to_string()],
203            id: "1".to_owned(),
204        }
205        .decode()
206        .expect("capability fixture is a valid request")
207    }
208
209    fn device(features: &serde_json::Value) -> DeviceInfo {
210        serde_json::from_value(serde_json::json!({
211            "platform": "browser",
212            "appName": "example",
213            "appVersion": "1.0.0",
214            "maxProtocolVersion": 2,
215            "features": features,
216        }))
217        .expect("capability fixture is valid DeviceInfo")
218    }
219
220    #[test]
221    fn enforces_message_limit_and_extra_currency_support() {
222        let wallet = device(&serde_json::json!([{
223            "name": "SendTransaction",
224            "maxMessages": 1
225        }]));
226        let two_messages = request(
227            "sendTransaction",
228            &serde_json::json!({
229                "messages": [
230                    { "address": FRIENDLY, "amount": "1" },
231                    { "address": FRIENDLY, "amount": "2" }
232                ]
233            }),
234        );
235        assert!(matches!(
236            wallet.validate_request(&two_messages),
237            Err(CapabilityError::MessageLimitExceeded {
238                max_messages: 1,
239                actual: 2
240            })
241        ));
242
243        let extra_payload = serde_json::json!({
244            "messages": [{
245                "address": FRIENDLY,
246                "amount": "1",
247                "extra_currency": { "1": "5" }
248            }]
249        });
250        let _: crate::RawTransactionPayload = serde_json::from_value(extra_payload.clone())
251            .expect("raw extra-currency fixture is valid");
252        let extra_currency = request("sendTransaction", &extra_payload);
253        assert_eq!(
254            wallet.validate_request(&extra_currency),
255            Err(CapabilityError::ExtraCurrencyNotSupported)
256        );
257    }
258
259    #[test]
260    fn enforces_structured_and_sign_data_types() {
261        let wallet = device(&serde_json::json!([
262            { "name": "SendTransaction", "maxMessages": 4, "itemTypes": ["ton"] },
263            { "name": "SignData", "types": ["text"] }
264        ]));
265        let jetton = request(
266            "sendTransaction",
267            &serde_json::json!({
268                "items": [{
269                    "type": "jetton",
270                    "master": FRIENDLY,
271                    "destination": FRIENDLY,
272                    "amount": "1"
273                }]
274            }),
275        );
276        assert_eq!(
277            wallet.validate_request(&jetton),
278            Err(CapabilityError::StructuredItemTypeNotSupported(
279                StructuredItemType::Jetton
280            ))
281        );
282
283        let binary = request(
284            "signData",
285            &serde_json::json!({ "type": "binary", "bytes": "AA==" }),
286        );
287        assert_eq!(
288            wallet.validate_request(&binary),
289            Err(CapabilityError::SignDataTypeNotSupported(
290                SignDataType::Binary
291            ))
292        );
293    }
294
295    #[test]
296    fn embedded_requests_require_both_capabilities() {
297        let wallet = DeviceInfo {
298            platform: DevicePlatform::Browser,
299            app_name: "example".to_owned(),
300            app_version: "1.0.0".to_owned(),
301            max_protocol_version: 2,
302            features: vec![Feature::SignData(
303                crate::SignDataFeature::new(vec![SignDataType::Text]).expect("feature is valid"),
304            )],
305        };
306        let request = EmbeddedRequest::SignData(crate::SignDataPayload::Text {
307            text: "hello".to_owned(),
308            network: None,
309            from: None,
310        });
311        assert_eq!(
312            wallet.validate_embedded_request(&request),
313            Err(CapabilityError::EmbeddedRequestNotSupported)
314        );
315    }
316
317    #[test]
318    fn every_rpc_and_embedded_capability_branch_is_enforced() {
319        let raw = serde_json::json!({
320            "messages": [{ "address": FRIENDLY, "amount": "1" }]
321        });
322        let two = serde_json::json!({
323            "messages": [
324                { "address": FRIENDLY, "amount": "1" },
325                { "address": FRIENDLY, "amount": "2" }
326            ]
327        });
328        let sign_text = serde_json::json!({ "type": "text", "text": "hello" });
329        let full = device(&serde_json::json!([
330            { "name": "SendTransaction", "maxMessages": 2, "extraCurrencySupported": true, "itemTypes": ["ton", "jetton", "nft"] },
331            { "name": "SignMessage", "maxMessages": 1 },
332            { "name": "SignData", "types": ["text", "binary", "cell"] },
333            { "name": "EmbeddedRequest" }
334        ]));
335
336        assert_eq!(
337            full.validate_request(&request("sendTransaction", &two)),
338            Ok(())
339        );
340        assert_eq!(full.validate_request(&request("signMessage", &raw)), Ok(()));
341        assert_eq!(
342            full.validate_request(&request("signData", &sign_text)),
343            Ok(())
344        );
345        assert_eq!(
346            full.validate_request(&KnownAppRequest::Disconnect(crate::DisconnectRequest {
347                id: "4".to_owned(),
348            })),
349            Ok(())
350        );
351        assert!(matches!(
352            full.validate_request(&request("signMessage", &two)),
353            Err(CapabilityError::MessageLimitExceeded { .. })
354        ));
355
356        let transaction_payload = serde_json::from_value::<TransactionPayload>(raw.clone())
357            .expect("raw transaction fixture is valid");
358        let embedded_send = EmbeddedRequest::SendTransaction(transaction_payload.clone());
359        let embedded_sign = EmbeddedRequest::SignMessage(transaction_payload);
360        let embedded_data = EmbeddedRequest::SignData(crate::SignDataPayload::Text {
361            text: "hello".to_owned(),
362            network: None,
363            from: None,
364        });
365        assert_eq!(full.validate_embedded_request(&embedded_send), Ok(()));
366        assert_eq!(full.validate_embedded_request(&embedded_sign), Ok(()));
367        assert_eq!(full.validate_embedded_request(&embedded_data), Ok(()));
368
369        let embedded_only = device(&serde_json::json!([{ "name": "EmbeddedRequest" }]));
370        assert_eq!(
371            embedded_only.validate_embedded_request(&embedded_send),
372            Err(CapabilityError::MethodNotSupported("sendTransaction"))
373        );
374        assert_eq!(
375            embedded_only.validate_embedded_request(&embedded_data),
376            Err(CapabilityError::MethodNotSupported("signData"))
377        );
378
379        let legacy = device(&serde_json::json!(["SendTransaction"]));
380        assert_eq!(
381            legacy.validate_request(&request("sendTransaction", &raw)),
382            Ok(())
383        );
384        assert_eq!(
385            legacy.validate_request(&request(
386                "sendTransaction",
387                &serde_json::json!({
388                    "items": [{ "type": "ton", "address": FRIENDLY, "amount": "1" }]
389                })
390            )),
391            Err(CapabilityError::StructuredItemsNotSupported)
392        );
393        assert_eq!(
394            legacy.validate_request(&request(
395                "sendTransaction",
396                &serde_json::json!({
397                    "messages": [{ "address": FRIENDLY, "amount": "1", "extra_currency": { "1": "1" } }]
398                })
399            )),
400            Err(CapabilityError::ExtraCurrencyNotSupported)
401        );
402        assert_eq!(
403            legacy.validate_request(&request("signMessage", &raw)),
404            Err(CapabilityError::MethodNotSupported("signMessage"))
405        );
406
407        let no_sign_data = device(&serde_json::json!([{
408            "name": "SendTransaction", "maxMessages": 1
409        }]));
410        assert_eq!(
411            no_sign_data.validate_request(&request("signData", &sign_text)),
412            Err(CapabilityError::MethodNotSupported("signData"))
413        );
414    }
415}