Skip to main content

ton_connect_core/
session_state.rs

1use std::{cmp::Ordering, fmt, str::FromStr};
2
3use serde::{Deserialize, Deserializer, Serialize, Serializer, de};
4use thiserror::Error;
5
6use crate::{AppRequest, ConnectEvent};
7
8/// A dApp RPC request ID ordered as an arbitrary-precision unsigned integer.
9///
10/// The protocol transports this counter as a string and does not specify a
11/// machine-width limit. Canonicalization removes leading zeroes so `"01"` and
12/// `"1"` cannot bypass replay protection while the original request envelope
13/// remains available for an exact response-ID echo.
14#[derive(Clone, Eq, Hash, PartialEq)]
15pub struct RpcRequestId(String);
16
17impl RpcRequestId {
18    /// Returns the canonical decimal representation used for ordering.
19    #[must_use]
20    pub fn as_str(&self) -> &str {
21        &self.0
22    }
23}
24
25impl fmt::Debug for RpcRequestId {
26    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
27        fmt::Display::fmt(self, formatter)
28    }
29}
30
31impl fmt::Display for RpcRequestId {
32    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
33        formatter.write_str(self.as_str())
34    }
35}
36
37impl FromStr for RpcRequestId {
38    type Err = SessionStateError;
39
40    fn from_str(value: &str) -> Result<Self, Self::Err> {
41        if value.is_empty() || !value.as_bytes().iter().all(u8::is_ascii_digit) {
42            return Err(SessionStateError::InvalidRequestId);
43        }
44        let without_zeroes = value.trim_start_matches('0');
45        let canonical = if without_zeroes.is_empty() {
46            "0"
47        } else {
48            without_zeroes
49        };
50        Ok(Self(canonical.to_owned()))
51    }
52}
53
54impl Ord for RpcRequestId {
55    fn cmp(&self, other: &Self) -> Ordering {
56        self.0
57            .len()
58            .cmp(&other.0.len())
59            .then_with(|| self.0.cmp(&other.0))
60    }
61}
62
63impl PartialOrd for RpcRequestId {
64    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
65        Some(self.cmp(other))
66    }
67}
68
69impl Serialize for RpcRequestId {
70    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
71    where
72        S: Serializer,
73    {
74        serializer.serialize_str(self.as_str())
75    }
76}
77
78impl<'de> Deserialize<'de> for RpcRequestId {
79    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
80    where
81        D: Deserializer<'de>,
82    {
83        let value = String::deserialize(deserializer)?;
84        Self::from_str(&value).map_err(de::Error::custom)
85    }
86}
87
88/// Durable lifecycle phase of one wallet-side TON Connect session.
89#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
90#[serde(rename_all = "snake_case")]
91pub enum WalletSessionPhase {
92    /// A deep-link request exists but no connect event has completed it.
93    PendingConnect,
94    /// The connect event succeeded and dApp RPC requests are accepted.
95    Connected,
96    /// A connect error or either side's disconnect permanently ended the session.
97    Disconnected,
98}
99
100/// Wallet event transition whose identifier is allocated by the session reducer.
101#[derive(Clone, Copy, Debug, Eq, PartialEq)]
102pub enum WalletEventKind {
103    /// Successful initial connection.
104    Connect,
105    /// Failed initial connection.
106    ConnectError,
107    /// Wallet-initiated termination of an established session.
108    Disconnect,
109}
110
111/// Persistable state required for monotonic IDs, replay rejection, and disconnect.
112///
113/// Transition methods are deliberately non-mutating. Atomically persist the
114/// returned next state together with the accepted request or outgoing event
115/// before running the wallet action or publishing. After a crash, restore that
116/// durable work item and retry it directly; a replay from the bridge is then
117/// rejected instead of signing the same request twice.
118#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
119#[serde(deny_unknown_fields)]
120pub struct WalletSessionState {
121    phase: WalletSessionPhase,
122    last_request_id: Option<RpcRequestId>,
123    last_event_id: Option<u64>,
124}
125
126#[derive(Deserialize)]
127#[serde(deny_unknown_fields)]
128struct RawWalletSessionState {
129    phase: WalletSessionPhase,
130    last_request_id: Option<RpcRequestId>,
131    last_event_id: Option<u64>,
132}
133
134impl<'de> Deserialize<'de> for WalletSessionState {
135    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
136    where
137        D: Deserializer<'de>,
138    {
139        let raw = RawWalletSessionState::deserialize(deserializer)?;
140        let valid = match raw.phase {
141            WalletSessionPhase::PendingConnect => {
142                raw.last_request_id.is_none() && raw.last_event_id.is_none()
143            }
144            WalletSessionPhase::Connected | WalletSessionPhase::Disconnected => {
145                raw.last_event_id.is_some()
146            }
147        };
148        if !valid {
149            return Err(de::Error::custom(
150                "persisted TON Connect session state violates lifecycle invariants",
151            ));
152        }
153        Ok(Self {
154            phase: raw.phase,
155            last_request_id: raw.last_request_id,
156            last_event_id: raw.last_event_id,
157        })
158    }
159}
160
161impl WalletSessionState {
162    /// Creates state for a newly received connect request.
163    #[must_use]
164    pub const fn pending_connect() -> Self {
165        Self {
166            phase: WalletSessionPhase::PendingConnect,
167            last_request_id: None,
168            last_event_id: None,
169        }
170    }
171
172    /// Returns the durable lifecycle phase.
173    #[must_use]
174    pub const fn phase(&self) -> WalletSessionPhase {
175        self.phase
176    }
177
178    /// Returns the highest accepted dApp request ID, if any.
179    #[must_use]
180    pub fn last_request_id(&self) -> Option<&RpcRequestId> {
181        self.last_request_id.as_ref()
182    }
183
184    /// Returns the last allocated wallet event ID, if any.
185    #[must_use]
186    pub const fn last_event_id(&self) -> Option<u64> {
187        self.last_event_id
188    }
189
190    /// Prepares a wallet event and its durable next state.
191    ///
192    /// The first event ID is zero, matching the reference TypeScript SDK. A
193    /// connect result may only finish a pending session, and a disconnect event
194    /// may only finish a connected session.
195    pub fn prepare_event(
196        &self,
197        kind: WalletEventKind,
198    ) -> Result<PreparedWalletEvent, SessionStateError> {
199        let next_phase = match (self.phase, kind) {
200            (WalletSessionPhase::PendingConnect, WalletEventKind::Connect) => {
201                WalletSessionPhase::Connected
202            }
203            (WalletSessionPhase::PendingConnect, WalletEventKind::ConnectError)
204            | (WalletSessionPhase::Connected, WalletEventKind::Disconnect) => {
205                WalletSessionPhase::Disconnected
206            }
207            (
208                WalletSessionPhase::PendingConnect
209                | WalletSessionPhase::Connected
210                | WalletSessionPhase::Disconnected,
211                WalletEventKind::Connect
212                | WalletEventKind::ConnectError
213                | WalletEventKind::Disconnect,
214            ) => return Err(SessionStateError::InvalidEventTransition),
215        };
216
217        let id = match self.last_event_id {
218            Some(previous) => previous
219                .checked_add(1)
220                .ok_or(SessionStateError::EventIdExhausted)?,
221            None => 0,
222        };
223        let mut next_state = self.clone();
224        next_state.phase = next_phase;
225        next_state.last_event_id = Some(id);
226        Ok(PreparedWalletEvent { id, next_state })
227    }
228
229    /// Accepts a strictly newer dApp request and prepares its durable next state.
230    ///
231    /// The raw envelope is used intentionally: unsupported or malformed methods
232    /// still consume a fresh ID once processed, so replaying the same packet
233    /// cannot repeatedly exercise parsing and approval code. A syntactically
234    /// exact `disconnect` request closes the session in the same atomic state
235    /// transition that consumes its ID.
236    pub fn prepare_request(
237        &self,
238        request: &AppRequest,
239    ) -> Result<PreparedAppRequest, SessionStateError> {
240        if self.phase != WalletSessionPhase::Connected {
241            return Err(SessionStateError::SessionNotConnected);
242        }
243
244        let request_id = RpcRequestId::from_str(&request.id)?;
245        if self
246            .last_request_id
247            .as_ref()
248            .is_some_and(|last| request_id <= *last)
249        {
250            return Err(SessionStateError::RequestIdNotIncreasing);
251        }
252
253        let closes_session = request.method == "disconnect" && request.params.is_empty();
254        let mut next_state = self.clone();
255        next_state.last_request_id = Some(request_id.clone());
256        if closes_session {
257            next_state.phase = WalletSessionPhase::Disconnected;
258        }
259        Ok(PreparedAppRequest {
260            request_id,
261            closes_session,
262            next_state,
263        })
264    }
265}
266
267impl Default for WalletSessionState {
268    fn default() -> Self {
269        Self::pending_connect()
270    }
271}
272
273/// Prepared event ID plus the state that must be persisted before publication.
274#[derive(Clone, Debug, Eq, PartialEq)]
275pub struct PreparedWalletEvent {
276    id: u64,
277    next_state: WalletSessionState,
278}
279
280impl PreparedWalletEvent {
281    /// Returns the event ID to place in the wallet event envelope.
282    #[must_use]
283    pub const fn id(&self) -> u64 {
284        self.id
285    }
286
287    /// Borrows the state that must be persisted before event publication.
288    #[must_use]
289    pub const fn next_state(&self) -> &WalletSessionState {
290        &self.next_state
291    }
292
293    /// Consumes the transition and returns its durable state.
294    #[must_use]
295    pub fn into_state(self) -> WalletSessionState {
296        self.next_state
297    }
298}
299
300/// Accepted request plus the state that must be persisted before processing.
301#[derive(Clone, Debug, Eq, PartialEq)]
302pub struct PreparedAppRequest {
303    request_id: RpcRequestId,
304    closes_session: bool,
305    next_state: WalletSessionState,
306}
307
308impl PreparedAppRequest {
309    /// Returns the canonical numeric request ID used by replay protection.
310    #[must_use]
311    pub const fn request_id(&self) -> &RpcRequestId {
312        &self.request_id
313    }
314
315    /// Reports whether this exact request atomically ends the session.
316    #[must_use]
317    pub const fn closes_session(&self) -> bool {
318        self.closes_session
319    }
320
321    /// Borrows the state that must be persisted before request processing.
322    #[must_use]
323    pub const fn next_state(&self) -> &WalletSessionState {
324        &self.next_state
325    }
326
327    /// Consumes the transition and returns its durable state.
328    #[must_use]
329    pub fn into_state(self) -> WalletSessionState {
330        self.next_state
331    }
332}
333
334/// A rejected session-state transition.
335#[derive(Clone, Copy, Debug, Eq, Error, PartialEq)]
336pub enum SessionStateError {
337    /// Request ID is not a non-empty unsigned decimal string.
338    #[error("TON Connect request id must be a non-empty unsigned decimal string")]
339    InvalidRequestId,
340    /// Request ID is equal to or below the durable session baseline.
341    #[error("TON Connect request id is not strictly greater than the last processed id")]
342    RequestIdNotIncreasing,
343    /// RPC requests are only valid after a successful connect and before disconnect.
344    #[error("TON Connect session is not connected")]
345    SessionNotConnected,
346    /// The requested event does not follow the session lifecycle.
347    #[error("wallet event is invalid for the current TON Connect session phase")]
348    InvalidEventTransition,
349    /// No larger `u64` wallet event ID can be allocated.
350    #[error("TON Connect wallet event id is exhausted")]
351    EventIdExhausted,
352}
353
354/// Durable dApp-side cursor for monotonic wallet events.
355#[derive(Clone, Debug, Default, Eq, PartialEq, Serialize)]
356#[serde(rename_all = "camelCase", deny_unknown_fields)]
357pub struct WalletEventCursor {
358    last_event_id: Option<u64>,
359    terminated: bool,
360}
361
362#[derive(Deserialize)]
363#[serde(rename_all = "camelCase", deny_unknown_fields)]
364struct WalletEventCursorWire {
365    last_event_id: Option<u64>,
366    terminated: bool,
367}
368
369impl<'de> Deserialize<'de> for WalletEventCursor {
370    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
371    where
372        D: serde::Deserializer<'de>,
373    {
374        let wire = WalletEventCursorWire::deserialize(deserializer)?;
375        if wire.terminated && wire.last_event_id.is_none() {
376            return Err(serde::de::Error::custom(
377                "terminated wallet event cursor requires an accepted event id",
378            ));
379        }
380        Ok(Self {
381            last_event_id: wire.last_event_id,
382            terminated: wire.terminated,
383        })
384    }
385}
386
387impl WalletEventCursor {
388    /// Returns the last accepted wallet event ID.
389    #[must_use]
390    pub const fn last_event_id(&self) -> Option<u64> {
391        self.last_event_id
392    }
393
394    /// Reports whether connect failed or either side disconnected.
395    #[must_use]
396    pub const fn is_terminated(&self) -> bool {
397        self.terminated
398    }
399
400    /// Validates one event and prepares state to persist before publication.
401    pub fn prepare_event(
402        &self,
403        event: &ConnectEvent,
404    ) -> Result<PreparedWalletEventReceipt, WalletEventCursorError> {
405        if self.terminated {
406            return Err(WalletEventCursorError::SessionTerminated);
407        }
408        let id = event.id();
409        if self.last_event_id.is_some_and(|last| id <= last) {
410            return Err(WalletEventCursorError::EventIdNotIncreasing);
411        }
412        Ok(PreparedWalletEventReceipt {
413            event_id: id,
414            next_cursor: Self {
415                last_event_id: Some(id),
416                terminated: event.terminates_session(),
417            },
418        })
419    }
420}
421
422/// Accepted wallet event and cursor that must be persisted first.
423#[derive(Clone, Debug, Eq, PartialEq)]
424pub struct PreparedWalletEventReceipt {
425    event_id: u64,
426    next_cursor: WalletEventCursor,
427}
428
429impl PreparedWalletEventReceipt {
430    /// Returns the accepted protocol event ID.
431    #[must_use]
432    pub const fn event_id(&self) -> u64 {
433        self.event_id
434    }
435
436    /// Returns the cursor to persist before publishing the event.
437    #[must_use]
438    pub const fn next_cursor(&self) -> &WalletEventCursor {
439        &self.next_cursor
440    }
441
442    /// Consumes the prepared receipt into its durable cursor.
443    #[must_use]
444    pub fn into_cursor(self) -> WalletEventCursor {
445        self.next_cursor
446    }
447}
448
449/// Wallet event is replayed, reordered, or belongs to a terminated session.
450#[derive(Clone, Copy, Debug, Eq, Error, PartialEq)]
451pub enum WalletEventCursorError {
452    /// Event ID is equal to or below the accepted baseline.
453    #[error("wallet event id is not strictly increasing")]
454    EventIdNotIncreasing,
455    /// No event is accepted after a terminal event.
456    #[error("wallet event session is already terminated")]
457    SessionTerminated,
458}
459
460#[cfg(test)]
461mod tests {
462    use proptest::prelude::*;
463
464    use super::*;
465    use crate::{ConnectEventError, ConnectEventErrorCode, EmptyObject};
466
467    fn connected() -> Result<WalletSessionState, SessionStateError> {
468        WalletSessionState::pending_connect()
469            .prepare_event(WalletEventKind::Connect)
470            .map(PreparedWalletEvent::into_state)
471    }
472
473    fn disconnect_event(id: u64) -> ConnectEvent {
474        ConnectEvent::Disconnect {
475            id,
476            payload: EmptyObject,
477        }
478    }
479
480    fn request(id: &str, method: &str, params: Vec<String>) -> AppRequest {
481        AppRequest {
482            method: method.to_owned(),
483            params,
484            id: id.to_owned(),
485        }
486    }
487
488    #[test]
489    fn numeric_order_is_not_lexicographic_or_machine_width_limited() {
490        let nine = RpcRequestId::from_str("9");
491        let ten = RpcRequestId::from_str("10");
492        let huge = RpcRequestId::from_str("18446744073709551616000000000000000000");
493        assert!(
494            matches!((nine, ten, huge), (Ok(nine), Ok(ten), Ok(huge)) if nine < ten && ten < huge)
495        );
496        let canonical = RpcRequestId::from_str("00042").expect("decimal request id");
497        assert_eq!(canonical.as_str(), "42");
498        assert_eq!(canonical.to_string(), "42");
499        assert_eq!(format!("{canonical:?}"), "42");
500    }
501
502    #[test]
503    fn request_ids_reject_every_non_decimal_shape() -> Result<(), SessionStateError> {
504        let state = connected()?;
505        for invalid in ["", "-1", "+1", "1.0", " 1", "1 ", "١"] {
506            assert_eq!(
507                state.prepare_request(&request(invalid, "unknown", Vec::new())),
508                Err(SessionStateError::InvalidRequestId)
509            );
510        }
511        Ok(())
512    }
513
514    #[test]
515    fn leading_zeroes_cannot_bypass_replay_rejection() -> Result<(), SessionStateError> {
516        let state = connected()?;
517        let persisted = state
518            .prepare_request(&request("001", "unknown", Vec::new()))?
519            .into_state();
520        assert_eq!(
521            persisted.prepare_request(&request("1", "unknown", Vec::new())),
522            Err(SessionStateError::RequestIdNotIncreasing)
523        );
524        Ok(())
525    }
526
527    #[test]
528    fn restored_state_rejects_replay_before_wallet_action_runs_again()
529    -> Result<(), Box<dyn std::error::Error>> {
530        let original = connected()?;
531        let accepted =
532            original.prepare_request(&request("7", "signData", vec!["{}".to_owned()]))?;
533        assert_eq!(original.last_request_id(), None);
534
535        let stored = serde_json::to_string(accepted.next_state())?;
536        let restored = serde_json::from_str::<WalletSessionState>(&stored)?;
537        assert_eq!(
538            restored.prepare_request(&request("7", "signData", vec!["{}".to_owned()])),
539            Err(SessionStateError::RequestIdNotIncreasing)
540        );
541        Ok(())
542    }
543
544    #[test]
545    fn valid_disconnect_consumes_id_and_closes_in_one_transition() -> Result<(), SessionStateError>
546    {
547        let accepted = connected()?.prepare_request(&request("3", "disconnect", Vec::new()))?;
548        assert!(accepted.closes_session());
549        assert_eq!(accepted.request_id().as_str(), "3");
550        assert_eq!(
551            accepted.next_state().phase(),
552            WalletSessionPhase::Disconnected
553        );
554        let closed = accepted.into_state();
555        assert_eq!(closed.phase(), WalletSessionPhase::Disconnected);
556        assert_eq!(
557            closed.prepare_request(&request("4", "sendTransaction", vec!["{}".to_owned()])),
558            Err(SessionStateError::SessionNotConnected)
559        );
560        Ok(())
561    }
562
563    #[test]
564    fn malformed_disconnect_consumes_id_without_closing() -> Result<(), SessionStateError> {
565        let accepted = connected()?.prepare_request(&request(
566            "3",
567            "disconnect",
568            vec!["unexpected".to_owned()],
569        ))?;
570        assert!(!accepted.closes_session());
571        assert_eq!(accepted.next_state().phase(), WalletSessionPhase::Connected);
572        Ok(())
573    }
574
575    #[test]
576    fn event_lifecycle_is_monotonic_and_terminal() -> Result<(), SessionStateError> {
577        let pending = WalletSessionState::pending_connect();
578        let connect = pending.prepare_event(WalletEventKind::Connect)?;
579        assert_eq!(connect.id(), 0);
580        let disconnect = connect
581            .into_state()
582            .prepare_event(WalletEventKind::Disconnect)?;
583        assert_eq!(disconnect.id(), 1);
584        assert_eq!(
585            disconnect.next_state().phase(),
586            WalletSessionPhase::Disconnected
587        );
588        assert_eq!(
589            disconnect
590                .next_state()
591                .prepare_event(WalletEventKind::Disconnect),
592            Err(SessionStateError::InvalidEventTransition)
593        );
594        Ok(())
595    }
596
597    #[test]
598    fn wallet_event_id_exhaustion_never_wraps_to_zero() -> Result<(), Box<dyn std::error::Error>> {
599        let state = serde_json::from_value::<WalletSessionState>(serde_json::json!({
600            "phase": "connected",
601            "last_request_id": null,
602            "last_event_id": u64::MAX,
603        }))?;
604        assert_eq!(
605            state.prepare_event(WalletEventKind::Disconnect),
606            Err(SessionStateError::EventIdExhausted)
607        );
608        assert_eq!(state.last_event_id(), Some(u64::MAX));
609        assert_eq!(state.phase(), WalletSessionPhase::Connected);
610        Ok(())
611    }
612
613    #[test]
614    fn persisted_state_rejects_impossible_lifecycle_combinations() {
615        assert_eq!(
616            WalletSessionState::default(),
617            WalletSessionState::pending_connect()
618        );
619        let pending_with_request =
620            r#"{"phase":"pending_connect","last_request_id":"1","last_event_id":null}"#;
621        let connected_without_event =
622            r#"{"phase":"connected","last_request_id":null,"last_event_id":null}"#;
623        assert!(serde_json::from_str::<WalletSessionState>(pending_with_request).is_err());
624        assert!(serde_json::from_str::<WalletSessionState>(connected_without_event).is_err());
625    }
626
627    proptest! {
628        #[test]
629    fn every_strictly_increasing_u128_sequence_is_accepted(
630            mut values in proptest::collection::vec(any::<u128>(), 1..64)
631        ) {
632            values.sort_unstable();
633            values.dedup();
634            let mut state = connected().expect("connect transition is valid");
635            for value in values {
636                let transition = state.prepare_request(&request(
637                    &value.to_string(),
638                    "unknown",
639                    Vec::new(),
640                ));
641                prop_assert!(transition.is_ok());
642                if let Ok(accepted) = transition {
643                    state = accepted.into_state();
644                }
645            }
646        }
647    }
648
649    #[test]
650    fn dapp_event_cursor_rejects_replay_and_stops_after_disconnect()
651    -> Result<(), Box<dyn std::error::Error>> {
652        let cursor = WalletEventCursor::default();
653        let first = cursor.prepare_event(&disconnect_event(7))?;
654        assert_eq!(first.event_id(), 7);
655        assert_eq!(first.next_cursor().last_event_id(), Some(7));
656        let terminated = first.into_cursor();
657        assert!(terminated.is_terminated());
658        let restored =
659            serde_json::from_str::<WalletEventCursor>(&serde_json::to_string(&terminated)?)?;
660        assert_eq!(restored, terminated);
661        assert_eq!(
662            terminated.prepare_event(&disconnect_event(8)),
663            Err(WalletEventCursorError::SessionTerminated)
664        );
665
666        let active = WalletEventCursor::default()
667            .prepare_event(&ConnectEvent::ConnectError {
668                id: 10,
669                payload: ConnectEventError {
670                    code: ConnectEventErrorCode::Unknown,
671                    message: "failed".to_owned(),
672                },
673            })?
674            .into_cursor();
675        assert_eq!(active.last_event_id(), Some(10));
676        assert!(active.is_terminated());
677        Ok(())
678    }
679
680    #[test]
681    fn dapp_event_cursor_accepts_first_baseline_then_requires_strict_growth() {
682        let first = WalletEventCursor::default()
683            .prepare_event(&disconnect_event(0))
684            .map(PreparedWalletEventReceipt::into_cursor);
685        assert!(first.is_ok());
686
687        let active = WalletEventCursor {
688            last_event_id: Some(5),
689            terminated: false,
690        };
691        assert_eq!(
692            active.prepare_event(&disconnect_event(5)),
693            Err(WalletEventCursorError::EventIdNotIncreasing)
694        );
695        assert_eq!(
696            active.prepare_event(&disconnect_event(4)),
697            Err(WalletEventCursorError::EventIdNotIncreasing)
698        );
699    }
700}