Skip to main content

ton_connect_core/
rpc.rs

1use std::collections::BTreeMap;
2
3use serde::{Deserialize, Deserializer, Serialize, Serializer, de};
4use serde_json::{Map, Value};
5use thiserror::Error;
6
7use crate::{
8    AccountAddress, AccountVerificationError, Base64Value, CellBoc, DecimalString,
9    Ed25519PublicKey, Ed25519Signature, FriendlyAddress, NetworkId, NonEmptyVec, RawAccountAddress,
10    SignDataSigningPayload, SignDataType, SignatureDomain, SigningError, StructuredItemType,
11    TonAddressItemReply, sign_data_signing_hash, verify_signature,
12};
13
14/// Extra-currency identifier to non-negative elementary-unit amount.
15#[derive(Clone, Debug, Default, Eq, PartialEq)]
16pub struct ExtraCurrencies(BTreeMap<u32, DecimalString>);
17
18impl ExtraCurrencies {
19    /// Creates a map from already typed currency identifiers.
20    #[must_use]
21    pub fn new(values: BTreeMap<u32, DecimalString>) -> Self {
22        Self(values)
23    }
24
25    /// Returns the typed currency map.
26    #[must_use]
27    pub const fn as_map(&self) -> &BTreeMap<u32, DecimalString> {
28        &self.0
29    }
30
31    /// Reports whether the map contains no extra currencies.
32    #[must_use]
33    pub fn is_empty(&self) -> bool {
34        self.0.is_empty()
35    }
36}
37
38impl Serialize for ExtraCurrencies {
39    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
40    where
41        S: Serializer,
42    {
43        use serde::ser::SerializeMap as _;
44
45        let mut map = serializer.serialize_map(Some(self.0.len()))?;
46        for (currency_id, amount) in &self.0 {
47            map.serialize_entry(&currency_id.to_string(), amount)?;
48        }
49        map.end()
50    }
51}
52
53impl<'de> Deserialize<'de> for ExtraCurrencies {
54    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
55    where
56        D: Deserializer<'de>,
57    {
58        let wire = BTreeMap::<String, DecimalString>::deserialize(deserializer)?;
59        let mut values = BTreeMap::new();
60        for (currency_id, amount) in wire {
61            let parsed = currency_id
62                .parse::<u32>()
63                .map_err(|_| de::Error::custom("extra-currency id must be an unsigned integer"))?;
64            if parsed.to_string() != currency_id || values.insert(parsed, amount).is_some() {
65                return Err(de::Error::custom(
66                    "extra-currency id must use canonical decimal form",
67                ));
68            }
69        }
70        Ok(Self(values))
71    }
72}
73
74/// A raw outgoing message in `sendTransaction` or `signMessage`.
75#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)]
76#[serde(deny_unknown_fields)]
77pub struct RawMessage {
78    /// Destination in TEP-2 user-friendly form.
79    pub address: FriendlyAddress,
80    /// Nanocoins represented as a non-negative decimal string.
81    pub amount: DecimalString,
82    /// Optional base64 one-cell body `BoC`.
83    #[serde(
84        default,
85        deserialize_with = "crate::value::deserialize_optional_non_null",
86        skip_serializing_if = "Option::is_none"
87    )]
88    pub payload: Option<CellBoc>,
89    /// Optional base64 one-cell `StateInit` `BoC`.
90    #[serde(
91        rename = "stateInit",
92        default,
93        deserialize_with = "crate::value::deserialize_optional_non_null",
94        skip_serializing_if = "Option::is_none"
95    )]
96    pub state_init: Option<CellBoc>,
97    /// Optional TEP-92 extra currencies.
98    #[serde(
99        default,
100        deserialize_with = "crate::value::deserialize_optional_non_null",
101        skip_serializing_if = "Option::is_none"
102    )]
103    pub extra_currency: Option<ExtraCurrencies>,
104}
105
106/// A wallet-built structured transfer item.
107#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)]
108#[serde(tag = "type", rename_all = "lowercase", deny_unknown_fields)]
109pub enum StructuredItem {
110    /// Native TON transfer.
111    Ton {
112        /// Destination address.
113        address: FriendlyAddress,
114        /// Nanocoins to transfer.
115        amount: DecimalString,
116        /// Optional base64 one-cell body `BoC`.
117        #[serde(
118            default,
119            deserialize_with = "crate::value::deserialize_optional_non_null",
120            skip_serializing_if = "Option::is_none"
121        )]
122        payload: Option<CellBoc>,
123        /// Optional base64 one-cell `StateInit` `BoC`.
124        #[serde(
125            rename = "stateInit",
126            default,
127            deserialize_with = "crate::value::deserialize_optional_non_null",
128            skip_serializing_if = "Option::is_none"
129        )]
130        state_init: Option<CellBoc>,
131        /// Optional TEP-92 extra currencies.
132        #[serde(
133            default,
134            deserialize_with = "crate::value::deserialize_optional_non_null",
135            skip_serializing_if = "Option::is_none"
136        )]
137        extra_currency: Option<ExtraCurrencies>,
138    },
139    /// TEP-74 jetton transfer.
140    Jetton {
141        /// Jetton master contract address.
142        master: AccountAddress,
143        /// Recipient address.
144        destination: AccountAddress,
145        /// Jetton elementary-unit amount.
146        amount: DecimalString,
147        /// Optional attached TON amount in nanocoins.
148        #[serde(
149            rename = "attachAmount",
150            default,
151            deserialize_with = "crate::value::deserialize_optional_non_null",
152            skip_serializing_if = "Option::is_none"
153        )]
154        attach_amount: Option<DecimalString>,
155        /// Optional application query identifier.
156        #[serde(
157            rename = "queryId",
158            default,
159            deserialize_with = "crate::value::deserialize_optional_non_null",
160            skip_serializing_if = "Option::is_none"
161        )]
162        query_id: Option<String>,
163        /// Optional excess-TON refund address.
164        #[serde(
165            rename = "responseDestination",
166            default,
167            deserialize_with = "crate::value::deserialize_optional_non_null",
168            skip_serializing_if = "Option::is_none"
169        )]
170        response_destination: Option<AccountAddress>,
171        /// Optional base64 `custom_payload` cell `BoC`.
172        #[serde(
173            rename = "customPayload",
174            default,
175            deserialize_with = "crate::value::deserialize_optional_non_null",
176            skip_serializing_if = "Option::is_none"
177        )]
178        custom_payload: Option<CellBoc>,
179        /// Optional forwarded TON amount in nanocoins.
180        #[serde(
181            rename = "forwardAmount",
182            default,
183            deserialize_with = "crate::value::deserialize_optional_non_null",
184            skip_serializing_if = "Option::is_none"
185        )]
186        forward_amount: Option<DecimalString>,
187        /// Optional base64 `forward_payload` cell `BoC`.
188        #[serde(
189            rename = "forwardPayload",
190            default,
191            deserialize_with = "crate::value::deserialize_optional_non_null",
192            skip_serializing_if = "Option::is_none"
193        )]
194        forward_payload: Option<CellBoc>,
195    },
196    /// TEP-62 NFT transfer.
197    Nft {
198        /// NFT item contract address.
199        #[serde(rename = "nftAddress")]
200        nft_address: AccountAddress,
201        /// New owner address.
202        #[serde(rename = "newOwner")]
203        new_owner: AccountAddress,
204        /// Optional attached TON amount in nanocoins.
205        #[serde(
206            rename = "attachAmount",
207            default,
208            deserialize_with = "crate::value::deserialize_optional_non_null",
209            skip_serializing_if = "Option::is_none"
210        )]
211        attach_amount: Option<DecimalString>,
212        /// Optional application query identifier.
213        #[serde(
214            rename = "queryId",
215            default,
216            deserialize_with = "crate::value::deserialize_optional_non_null",
217            skip_serializing_if = "Option::is_none"
218        )]
219        query_id: Option<String>,
220        /// Optional excess-TON refund address.
221        #[serde(
222            rename = "responseDestination",
223            default,
224            deserialize_with = "crate::value::deserialize_optional_non_null",
225            skip_serializing_if = "Option::is_none"
226        )]
227        response_destination: Option<AccountAddress>,
228        /// Optional base64 `custom_payload` cell `BoC`.
229        #[serde(
230            rename = "customPayload",
231            default,
232            deserialize_with = "crate::value::deserialize_optional_non_null",
233            skip_serializing_if = "Option::is_none"
234        )]
235        custom_payload: Option<CellBoc>,
236        /// Optional forwarded TON amount in nanocoins.
237        #[serde(
238            rename = "forwardAmount",
239            default,
240            deserialize_with = "crate::value::deserialize_optional_non_null",
241            skip_serializing_if = "Option::is_none"
242        )]
243        forward_amount: Option<DecimalString>,
244        /// Optional base64 `forward_payload` cell `BoC`.
245        #[serde(
246            rename = "forwardPayload",
247            default,
248            deserialize_with = "crate::value::deserialize_optional_non_null",
249            skip_serializing_if = "Option::is_none"
250        )]
251        forward_payload: Option<CellBoc>,
252    },
253}
254
255/// A transaction payload containing caller-built raw messages.
256#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)]
257#[serde(deny_unknown_fields)]
258pub struct RawTransactionPayload {
259    /// Optional Unix expiration time in seconds.
260    #[serde(
261        default,
262        deserialize_with = "crate::value::deserialize_optional_non_null",
263        skip_serializing_if = "Option::is_none"
264    )]
265    pub valid_until: Option<u64>,
266    /// Optional target network global ID.
267    #[serde(
268        default,
269        deserialize_with = "crate::value::deserialize_optional_non_null",
270        skip_serializing_if = "Option::is_none"
271    )]
272    pub network: Option<NetworkId>,
273    /// Optional fixed sender address.
274    #[serde(
275        default,
276        deserialize_with = "crate::value::deserialize_optional_non_null",
277        skip_serializing_if = "Option::is_none"
278    )]
279    pub from: Option<AccountAddress>,
280    /// One or more raw outgoing messages.
281    pub messages: NonEmptyVec<RawMessage>,
282}
283
284/// A transaction payload containing wallet-built structured items.
285#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)]
286#[serde(deny_unknown_fields)]
287pub struct StructuredTransactionPayload {
288    /// Optional Unix expiration time in seconds.
289    #[serde(
290        default,
291        deserialize_with = "crate::value::deserialize_optional_non_null",
292        skip_serializing_if = "Option::is_none"
293    )]
294    pub valid_until: Option<u64>,
295    /// Optional target network global ID.
296    #[serde(
297        default,
298        deserialize_with = "crate::value::deserialize_optional_non_null",
299        skip_serializing_if = "Option::is_none"
300    )]
301    pub network: Option<NetworkId>,
302    /// Optional fixed sender address.
303    #[serde(
304        default,
305        deserialize_with = "crate::value::deserialize_optional_non_null",
306        skip_serializing_if = "Option::is_none"
307    )]
308    pub from: Option<AccountAddress>,
309    /// One or more structured transfer items.
310    pub items: NonEmptyVec<StructuredItem>,
311}
312
313/// Payload shared by `sendTransaction` and `signMessage`.
314///
315/// The untagged representation enforces the protocol's exclusive choice:
316/// exactly one of `messages` or `items` must be present.
317#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
318#[serde(untagged)]
319pub enum TransactionPayload {
320    /// Raw caller-built messages.
321    Raw(RawTransactionPayload),
322    /// Wallet-built structured items.
323    Structured(StructuredTransactionPayload),
324}
325
326impl<'de> Deserialize<'de> for TransactionPayload {
327    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
328    where
329        D: Deserializer<'de>,
330    {
331        let value = Value::deserialize(deserializer)?;
332        let Value::Object(object) = &value else {
333            return Err(de::Error::custom("transaction payload must be an object"));
334        };
335        match (
336            object.contains_key("messages"),
337            object.contains_key("items"),
338        ) {
339            (true, false) => serde_json::from_value::<RawTransactionPayload>(value)
340                .map(Self::Raw)
341                .map_err(de::Error::custom),
342            (false, true) => serde_json::from_value::<StructuredTransactionPayload>(value)
343                .map(Self::Structured)
344                .map_err(de::Error::custom),
345            (true, true) | (false, false) => Err(de::Error::custom(
346                "transaction payload requires exactly one of messages or items",
347            )),
348        }
349    }
350}
351
352impl TransactionPayload {
353    /// Returns the number of raw messages or structured items in the request.
354    #[must_use]
355    pub fn message_count(&self) -> usize {
356        match self {
357            Self::Raw(payload) => payload.messages.as_slice().len(),
358            Self::Structured(payload) => payload.items.as_slice().len(),
359        }
360    }
361
362    /// Reports whether the request transfers any TEP-92 extra currency.
363    #[must_use]
364    pub fn uses_extra_currency(&self) -> bool {
365        match self {
366            Self::Raw(payload) => payload.messages.as_slice().iter().any(|message| {
367                message
368                    .extra_currency
369                    .as_ref()
370                    .is_some_and(|currencies| !currencies.is_empty())
371            }),
372            Self::Structured(payload) => payload.items.as_slice().iter().any(|item| {
373                matches!(
374                    item,
375                    StructuredItem::Ton {
376                        extra_currency: Some(currencies),
377                        ..
378                    } if !currencies.is_empty()
379                )
380            }),
381        }
382    }
383
384    /// Returns the structured item kinds used by this request.
385    ///
386    /// `None` identifies the raw `messages` form. A non-empty slice identifies
387    /// the `items` form and retains duplicates because each item still counts
388    /// towards the wallet's advertised `maxMessages` limit.
389    #[must_use]
390    pub fn structured_item_types(&self) -> Option<Vec<StructuredItemType>> {
391        let Self::Structured(payload) = self else {
392            return None;
393        };
394        Some(
395            payload
396                .items
397                .as_slice()
398                .iter()
399                .map(|item| match item {
400                    StructuredItem::Ton { .. } => StructuredItemType::Ton,
401                    StructuredItem::Jetton { .. } => StructuredItemType::Jetton,
402                    StructuredItem::Nft { .. } => StructuredItemType::Nft,
403                })
404                .collect(),
405        )
406    }
407
408    /// Validates time, network, and fixed-sender constraints common to
409    /// `sendTransaction` and `signMessage`.
410    pub fn validate_context(
411        &self,
412        now: u64,
413        active_network: &NetworkId,
414        active_account: &RawAccountAddress,
415    ) -> Result<(), RequestContextError> {
416        let (valid_until, network, from) = match self {
417            Self::Raw(payload) => (
418                payload.valid_until,
419                payload.network.as_ref(),
420                payload.from.as_ref(),
421            ),
422            Self::Structured(payload) => (
423                payload.valid_until,
424                payload.network.as_ref(),
425                payload.from.as_ref(),
426            ),
427        };
428        if valid_until.is_some_and(|valid_until| now > valid_until) {
429            return Err(RequestContextError::Expired);
430        }
431        validate_network_and_account(network, from, active_network, active_account)
432    }
433}
434
435/// Discriminated `signData` payload.
436#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)]
437#[serde(tag = "type", rename_all = "lowercase", deny_unknown_fields)]
438pub enum SignDataPayload {
439    /// UTF-8 text shown and signed verbatim.
440    Text {
441        /// Text to sign.
442        text: String,
443        /// Optional target network global ID.
444        #[serde(
445            default,
446            deserialize_with = "crate::value::deserialize_optional_non_null",
447            skip_serializing_if = "Option::is_none"
448        )]
449        network: Option<NetworkId>,
450        /// Optional fixed signer address.
451        #[serde(
452            default,
453            deserialize_with = "crate::value::deserialize_optional_non_null",
454            skip_serializing_if = "Option::is_none"
455        )]
456        from: Option<AccountAddress>,
457    },
458    /// Opaque binary bytes.
459    Binary {
460        /// Base64-encoded bytes to sign.
461        bytes: Base64Value,
462        /// Optional target network global ID.
463        #[serde(
464            default,
465            deserialize_with = "crate::value::deserialize_optional_non_null",
466            skip_serializing_if = "Option::is_none"
467        )]
468        network: Option<NetworkId>,
469        /// Optional fixed signer address.
470        #[serde(
471            default,
472            deserialize_with = "crate::value::deserialize_optional_non_null",
473            skip_serializing_if = "Option::is_none"
474        )]
475        from: Option<AccountAddress>,
476    },
477    /// A TVM cell interpreted with a TL-B schema.
478    Cell {
479        /// TL-B schema whose final declaration is the root.
480        schema: String,
481        /// Base64 cell `BoC`.
482        cell: CellBoc,
483        /// Optional target network global ID.
484        #[serde(
485            default,
486            deserialize_with = "crate::value::deserialize_optional_non_null",
487            skip_serializing_if = "Option::is_none"
488        )]
489        network: Option<NetworkId>,
490        /// Optional fixed signer address.
491        #[serde(
492            default,
493            deserialize_with = "crate::value::deserialize_optional_non_null",
494            skip_serializing_if = "Option::is_none"
495        )]
496        from: Option<AccountAddress>,
497    },
498}
499
500impl SignDataPayload {
501    /// Returns the capability discriminator required to process this payload.
502    #[must_use]
503    pub const fn data_type(&self) -> SignDataType {
504        match self {
505            Self::Text { .. } => SignDataType::Text,
506            Self::Binary { .. } => SignDataType::Binary,
507            Self::Cell { .. } => SignDataType::Cell,
508        }
509    }
510
511    /// Validates optional network and signer constraints for `signData`.
512    pub fn validate_context(
513        &self,
514        active_network: &NetworkId,
515        active_account: &RawAccountAddress,
516    ) -> Result<(), RequestContextError> {
517        let (network, from) = match self {
518            Self::Text { network, from, .. }
519            | Self::Binary { network, from, .. }
520            | Self::Cell { network, from, .. } => (network.as_ref(), from.as_ref()),
521        };
522        validate_network_and_account(network, from, active_network, active_account)
523    }
524}
525
526/// Request constraints conflict with the wallet's active session context.
527#[derive(Clone, Copy, Debug, Eq, Error, PartialEq)]
528pub enum RequestContextError {
529    /// Transaction `valid_until` is before the observed clock.
530    #[error("TON Connect request has expired")]
531    Expired,
532    /// Explicit request network differs from the active wallet network.
533    #[error("TON Connect request network differs from the active network")]
534    NetworkMismatch,
535    /// Explicit `from` address differs from the session account.
536    #[error("TON Connect request signer differs from the connected account")]
537    AccountMismatch,
538}
539
540fn validate_network_and_account(
541    network: Option<&NetworkId>,
542    from: Option<&AccountAddress>,
543    active_network: &NetworkId,
544    active_account: &RawAccountAddress,
545) -> Result<(), RequestContextError> {
546    if network.is_some_and(|network| network != active_network) {
547        return Err(RequestContextError::NetworkMismatch);
548    }
549    if from.is_some_and(|from| from.raw_address() != *active_account) {
550        return Err(RequestContextError::AccountMismatch);
551    }
552    Ok(())
553}
554
555/// Raw `{ method, params, id }` request envelope received from a dApp.
556///
557/// `method` remains a string so a wallet can parse an unknown method and
558/// return protocol error 400 instead of dropping an otherwise valid request.
559#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)]
560#[serde(deny_unknown_fields)]
561pub struct AppRequest {
562    /// RPC method name.
563    pub method: String,
564    /// Method parameters. Complex payloads are JSON strings inside this array.
565    pub params: Vec<String>,
566    /// dApp-assigned request identifier.
567    pub id: String,
568}
569
570/// A validated `sendTransaction` request.
571#[derive(Clone, Debug, Eq, PartialEq)]
572pub struct SendTransactionRequest {
573    /// dApp request identifier.
574    pub id: String,
575    /// Transaction to sign and broadcast.
576    pub payload: TransactionPayload,
577}
578
579/// A validated `signMessage` request.
580#[derive(Clone, Debug, Eq, PartialEq)]
581pub struct SignMessageRequest {
582    /// dApp request identifier.
583    pub id: String,
584    /// Transaction-shaped message to sign without broadcasting.
585    pub payload: TransactionPayload,
586}
587
588/// A validated `signData` request.
589#[derive(Clone, Debug, Eq, PartialEq)]
590pub struct SignDataRequest {
591    /// dApp request identifier.
592    pub id: String,
593    /// Data and signer constraints.
594    pub payload: SignDataPayload,
595}
596
597/// A validated `disconnect` request.
598#[derive(Clone, Debug, Eq, PartialEq)]
599pub struct DisconnectRequest {
600    /// dApp request identifier.
601    pub id: String,
602}
603
604/// A known request with its nested JSON parameter parsed and validated.
605#[derive(Clone, Debug, Eq, PartialEq)]
606pub enum KnownAppRequest {
607    /// Sign and broadcast a transaction.
608    SendTransaction(SendTransactionRequest),
609    /// Sign an internal message without broadcasting.
610    SignMessage(SignMessageRequest),
611    /// Sign application data.
612    SignData(SignDataRequest),
613    /// End the session.
614    Disconnect(DisconnectRequest),
615}
616
617impl KnownAppRequest {
618    /// Returns the protocol method discriminator for this request.
619    #[must_use]
620    pub fn method(&self) -> crate::RpcMethod {
621        self.into()
622    }
623
624    /// Returns the exact dApp request identifier.
625    #[must_use]
626    pub fn id(&self) -> &str {
627        match self {
628            Self::SendTransaction(request) => &request.id,
629            Self::SignMessage(request) => &request.id,
630            Self::SignData(request) => &request.id,
631            Self::Disconnect(request) => &request.id,
632        }
633    }
634}
635
636/// Failure while decoding or encoding an RPC request.
637#[derive(Debug, Error)]
638pub enum RpcError {
639    /// The method is not implemented by this protocol version.
640    #[error("unsupported TON Connect RPC method: {0}")]
641    UnsupportedMethod(String),
642    /// The method carried an incorrect number of parameters.
643    #[error("TON Connect RPC method {method} requires {expected} parameter(s), got {actual}")]
644    InvalidParameterCount {
645        /// Method being parsed.
646        method: &'static str,
647        /// Required parameter count.
648        expected: usize,
649        /// Received parameter count.
650        actual: usize,
651    },
652    /// A nested JSON payload violates the method schema.
653    #[error("invalid TON Connect RPC payload: {0}")]
654    InvalidPayload(#[from] serde_json::Error),
655}
656
657impl AppRequest {
658    /// Parses the method-specific parameter and enforces its exact schema.
659    pub fn decode(self) -> Result<KnownAppRequest, RpcError> {
660        match self.method.as_str() {
661            "sendTransaction" => Ok(KnownAppRequest::SendTransaction(SendTransactionRequest {
662                id: self.id,
663                payload: parse_single_parameter("sendTransaction", self.params)?,
664            })),
665            "signMessage" => Ok(KnownAppRequest::SignMessage(SignMessageRequest {
666                id: self.id,
667                payload: parse_single_parameter("signMessage", self.params)?,
668            })),
669            "signData" => Ok(KnownAppRequest::SignData(SignDataRequest {
670                id: self.id,
671                payload: parse_single_parameter("signData", self.params)?,
672            })),
673            "disconnect" => {
674                if self.params.is_empty() {
675                    Ok(KnownAppRequest::Disconnect(DisconnectRequest {
676                        id: self.id,
677                    }))
678                } else {
679                    Err(RpcError::InvalidParameterCount {
680                        method: "disconnect",
681                        expected: 0,
682                        actual: self.params.len(),
683                    })
684                }
685            }
686            _ => Err(RpcError::UnsupportedMethod(self.method)),
687        }
688    }
689
690    /// Encodes a validated request into the exact bridge envelope shape.
691    pub fn encode(request: KnownAppRequest) -> Result<Self, RpcError> {
692        match request {
693            KnownAppRequest::SendTransaction(request) => Ok(Self {
694                method: "sendTransaction".to_owned(),
695                params: vec![serde_json::to_string(&request.payload)?],
696                id: request.id,
697            }),
698            KnownAppRequest::SignMessage(request) => Ok(Self {
699                method: "signMessage".to_owned(),
700                params: vec![serde_json::to_string(&request.payload)?],
701                id: request.id,
702            }),
703            KnownAppRequest::SignData(request) => Ok(Self {
704                method: "signData".to_owned(),
705                params: vec![serde_json::to_string(&request.payload)?],
706                id: request.id,
707            }),
708            KnownAppRequest::Disconnect(request) => Ok(Self {
709                method: "disconnect".to_owned(),
710                params: Vec::new(),
711                id: request.id,
712            }),
713        }
714    }
715}
716
717fn parse_single_parameter<T>(method: &'static str, params: Vec<String>) -> Result<T, RpcError>
718where
719    T: for<'de> Deserialize<'de>,
720{
721    if params.len() != 1 {
722        return Err(RpcError::InvalidParameterCount {
723            method,
724            expected: 1,
725            actual: params.len(),
726        });
727    }
728    let Some(payload) = params.into_iter().next() else {
729        return Err(RpcError::InvalidParameterCount {
730            method,
731            expected: 1,
732            actual: 0,
733        });
734    };
735    serde_json::from_str(&payload).map_err(RpcError::from)
736}
737
738macro_rules! numeric_enum_serde {
739    ($name:ident { $($variant:ident = $value:literal),+ $(,)? }) => {
740        impl Serialize for $name {
741            fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
742            where
743                S: Serializer,
744            {
745                let value = match self {
746                    $(Self::$variant => $value,)+
747                };
748                serializer.serialize_u16(value)
749            }
750        }
751
752        impl<'de> Deserialize<'de> for $name {
753            fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
754            where
755                D: Deserializer<'de>,
756            {
757                match u16::deserialize(deserializer)? {
758                    $($value => Ok(Self::$variant),)+
759                    value => Err(de::Error::custom(format_args!(
760                        "unsupported TON Connect error code {value}"
761                    ))),
762                }
763            }
764        }
765    };
766}
767
768pub(crate) use numeric_enum_serde;
769
770/// Central TON Connect RPC error catalogue.
771#[derive(Clone, Copy, Debug, Eq, PartialEq)]
772#[repr(u16)]
773pub enum RpcErrorCode {
774    /// Unexpected wallet-side failure.
775    Unknown = 0,
776    /// Malformed request or violated method constraint.
777    BadRequest = 1,
778    /// Unknown or revoked app session.
779    UnknownApp = 100,
780    /// User declined the operation.
781    UserDeclined = 300,
782    /// Wallet does not implement the method.
783    MethodNotSupported = 400,
784}
785
786numeric_enum_serde!(RpcErrorCode {
787    Unknown = 0,
788    BadRequest = 1,
789    UnknownApp = 100,
790    UserDeclined = 300,
791    MethodNotSupported = 400,
792});
793
794/// Success result permitted by the generic wallet-response schema.
795#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)]
796#[serde(untagged)]
797pub enum WalletResult {
798    /// String result, such as a signed external-message `BoC`.
799    String(String),
800    /// Object result, such as `signData` or `signMessage` output.
801    Object(Map<String, Value>),
802}
803
804/// Successful wallet RPC response.
805#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)]
806#[serde(deny_unknown_fields)]
807pub struct WalletResponseSuccess {
808    /// Method-specific result.
809    pub result: WalletResult,
810    /// Exact request ID being answered.
811    pub id: String,
812}
813
814/// Protocol RPC error body.
815#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)]
816#[serde(deny_unknown_fields)]
817pub struct WalletResponseError {
818    /// Protocol error code.
819    pub code: RpcErrorCode,
820    /// Human-readable diagnostic.
821    pub message: String,
822    /// Optional method-specific details.
823    #[serde(skip_serializing_if = "Option::is_none")]
824    pub data: Option<Value>,
825}
826
827/// Wallet response correlated to one dApp request ID.
828#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)]
829#[serde(untagged, deny_unknown_fields)]
830pub enum WalletResponse {
831    /// Successful response.
832    Success(WalletResponseSuccess),
833    /// Error response.
834    Error {
835        /// Protocol error body.
836        error: WalletResponseError,
837        /// Exact request ID being answered.
838        id: String,
839    },
840}
841
842/// Typed success body returned by `signMessage`.
843#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)]
844#[serde(rename_all = "camelCase", deny_unknown_fields)]
845pub struct SignMessageResult {
846    /// Base64 `BoC` of the signed internal message.
847    pub internal_boc: CellBoc,
848}
849
850/// Typed success body returned by `signData`.
851#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)]
852#[serde(deny_unknown_fields)]
853pub struct SignDataResult {
854    /// Base64 Ed25519 signature.
855    pub signature: Ed25519Signature,
856    /// Raw wallet address.
857    pub address: RawAccountAddress,
858    /// Unix signing time in seconds.
859    pub timestamp: u64,
860    /// Application domain bound into the signature.
861    pub domain: String,
862    /// Exact payload echoed from the request.
863    pub payload: SignDataPayload,
864}
865
866impl SignDataResult {
867    /// Reconstructs the exact digest represented by this response.
868    pub fn signing_hash(&self) -> Result<[u8; 32], SigningError> {
869        match &self.payload {
870            SignDataPayload::Text { text, .. } => sign_data_signing_hash(
871                &self.address,
872                &self.domain,
873                self.timestamp,
874                SignDataSigningPayload::Text(text),
875            ),
876            SignDataPayload::Binary { bytes, .. } => {
877                let decoded = bytes
878                    .decode()
879                    .map_err(|_| SigningError::InvalidBase64Payload)?;
880                sign_data_signing_hash(
881                    &self.address,
882                    &self.domain,
883                    self.timestamp,
884                    SignDataSigningPayload::Binary(&decoded),
885                )
886            }
887            SignDataPayload::Cell { schema, cell, .. } => sign_data_signing_hash(
888                &self.address,
889                &self.domain,
890                self.timestamp,
891                SignDataSigningPayload::Cell {
892                    schema,
893                    boc: cell.as_bytes(),
894                },
895            ),
896        }
897    }
898
899    /// Verifies this `signData` response with the trusted account public key.
900    pub fn verify(&self, public_key: &Ed25519PublicKey) -> Result<bool, SigningError> {
901        verify_signature(
902            &self.signing_hash()?,
903            &self.signature,
904            public_key,
905            SignatureDomain::Empty,
906        )
907    }
908
909    /// Verifies this result with the address-bound key from the connected
910    /// standard wallet rather than trusting a wallet-advertised key.
911    pub fn verify_with_account(
912        &self,
913        account: &TonAddressItemReply,
914    ) -> Result<bool, AccountVerificationError> {
915        if self.address != account.address {
916            return Err(AccountVerificationError::ResponseAddressMismatch);
917        }
918        let wallet = account.verify_standard_wallet()?;
919        self.verify(wallet.public_key()).map_err(Into::into)
920    }
921}
922
923/// Method-specific response after correlation and payload validation.
924#[derive(Clone, Debug, Eq, PartialEq)]
925pub enum KnownWalletResponse {
926    /// Signed and broadcast external-message `BoC`.
927    SendTransaction(CellBoc),
928    /// Signed internal message.
929    SignMessage(SignMessageResult),
930    /// Application data signature.
931    SignData(Box<SignDataResult>),
932    /// Successful disconnect acknowledgement.
933    Disconnect,
934    /// Protocol error valid for the requested method.
935    Error(WalletResponseError),
936}
937
938/// Failure to correlate or validate a wallet response for a known request.
939#[derive(Clone, Debug, Eq, Error, PartialEq)]
940pub enum ResponseValidationError {
941    /// Response and request IDs differ.
942    #[error("wallet response id does not match request id")]
943    RequestIdMismatch,
944    /// The success result has the wrong JSON kind or fields for the method.
945    #[error("wallet response result does not match the requested method")]
946    InvalidResult,
947    /// A result that must contain bytes decoded to an empty value.
948    #[error("wallet response result must not be empty")]
949    EmptyResult,
950    /// `signData` did not echo the exact request payload.
951    #[error("signData response payload does not match request payload")]
952    SignDataPayloadMismatch,
953    /// The method does not permit the returned protocol error code.
954    #[error("wallet response error code is not valid for the requested method")]
955    InvalidErrorCode,
956}
957
958impl WalletResponse {
959    /// Correlates this response and validates its method-specific result.
960    pub fn validate_for(
961        &self,
962        request: &KnownAppRequest,
963    ) -> Result<KnownWalletResponse, ResponseValidationError> {
964        let response_id = match self {
965            Self::Success(response) => &response.id,
966            Self::Error { id, .. } => id,
967        };
968        if response_id != request.id() {
969            return Err(ResponseValidationError::RequestIdMismatch);
970        }
971
972        match self {
973            Self::Error { error, .. } => {
974                if matches!(request, KnownAppRequest::Disconnect(_))
975                    && error.code == RpcErrorCode::UserDeclined
976                {
977                    return Err(ResponseValidationError::InvalidErrorCode);
978                }
979                Ok(KnownWalletResponse::Error(error.clone()))
980            }
981            Self::Success(response) => validate_success_result(&response.result, request),
982        }
983    }
984}
985
986fn validate_success_result(
987    result: &WalletResult,
988    request: &KnownAppRequest,
989) -> Result<KnownWalletResponse, ResponseValidationError> {
990    match (request, result) {
991        (KnownAppRequest::SendTransaction(_), WalletResult::String(result)) => {
992            let boc = CellBoc::try_from(result.clone())
993                .map_err(|_| ResponseValidationError::InvalidResult)?;
994            if boc.as_str().is_empty() {
995                return Err(ResponseValidationError::EmptyResult);
996            }
997            Ok(KnownWalletResponse::SendTransaction(boc))
998        }
999        (KnownAppRequest::SignMessage(_), WalletResult::Object(result)) => {
1000            let parsed = serde_json::from_value::<SignMessageResult>(Value::Object(result.clone()))
1001                .map_err(|_| ResponseValidationError::InvalidResult)?;
1002            if parsed.internal_boc.as_str().is_empty() {
1003                return Err(ResponseValidationError::EmptyResult);
1004            }
1005            Ok(KnownWalletResponse::SignMessage(parsed))
1006        }
1007        (KnownAppRequest::SignData(request), WalletResult::Object(result)) => {
1008            let parsed = serde_json::from_value::<SignDataResult>(Value::Object(result.clone()))
1009                .map_err(|_| ResponseValidationError::InvalidResult)?;
1010            if parsed.payload != request.payload {
1011                return Err(ResponseValidationError::SignDataPayloadMismatch);
1012            }
1013            Ok(KnownWalletResponse::SignData(Box::new(parsed)))
1014        }
1015        (KnownAppRequest::Disconnect(_), WalletResult::Object(result)) if result.is_empty() => {
1016            Ok(KnownWalletResponse::Disconnect)
1017        }
1018        (
1019            KnownAppRequest::SendTransaction(_)
1020            | KnownAppRequest::SignMessage(_)
1021            | KnownAppRequest::SignData(_)
1022            | KnownAppRequest::Disconnect(_),
1023            WalletResult::String(_) | WalletResult::Object(_),
1024        ) => Err(ResponseValidationError::InvalidResult),
1025    }
1026}
1027
1028#[cfg(test)]
1029mod tests {
1030    use base64::{Engine as _, engine::general_purpose::STANDARD};
1031    use ed25519_dalek::{Signer as _, SigningKey};
1032
1033    use super::*;
1034
1035    const FRIENDLY_ADDRESS: &str = "Ef8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADAU";
1036
1037    #[test]
1038    fn transaction_requires_exactly_one_non_empty_body_kind() {
1039        let neither = r#"{"network":"-239"}"#;
1040        let both = r#"{"messages":[{"address":"EQ","amount":"1"}],"items":[{"type":"ton","address":"EQ","amount":"1"}]}"#;
1041        let empty = r#"{"messages":[]}"#;
1042        assert!(serde_json::from_str::<TransactionPayload>(neither).is_err());
1043        assert!(serde_json::from_str::<TransactionPayload>(both).is_err());
1044        assert!(serde_json::from_str::<TransactionPayload>(empty).is_err());
1045    }
1046
1047    #[test]
1048    fn app_request_decodes_json_string_parameter() {
1049        let json = r#"{
1050            "method":"sendTransaction",
1051            "params":["{\"valid_until\":1764424242,\"network\":\"-239\",\"messages\":[{\"address\":\"Ef8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADAU\",\"amount\":\"100000000\"}]}"],
1052            "id":"42"
1053        }"#;
1054        let request = serde_json::from_str::<AppRequest>(json).expect("valid request envelope");
1055        assert!(matches!(
1056            request.decode(),
1057            Ok(KnownAppRequest::SendTransaction(_))
1058        ));
1059    }
1060
1061    #[test]
1062    fn known_request_rejects_extra_nested_fields() {
1063        let request = AppRequest {
1064            method: "signData".to_owned(),
1065            params: vec![r#"{"type":"text","text":"hello","extra":true}"#.to_owned()],
1066            id: "1".to_owned(),
1067        };
1068        assert!(matches!(request.decode(), Err(RpcError::InvalidPayload(_))));
1069    }
1070
1071    #[test]
1072    fn unknown_method_remains_answerable() {
1073        let request = AppRequest {
1074            method: "futureMethod".to_owned(),
1075            params: Vec::new(),
1076            id: "7".to_owned(),
1077        };
1078        assert!(matches!(
1079            request.decode(),
1080            Err(RpcError::UnsupportedMethod(method)) if method == "futureMethod"
1081        ));
1082    }
1083
1084    #[test]
1085    fn error_catalogue_rejects_unknown_numeric_codes() {
1086        assert!(serde_json::from_str::<RpcErrorCode>("400").is_ok());
1087        assert!(serde_json::from_str::<RpcErrorCode>("401").is_err());
1088    }
1089
1090    #[test]
1091    fn response_must_match_request_id_and_method_shape() -> Result<(), Box<dyn std::error::Error>> {
1092        let request = KnownAppRequest::SendTransaction(SendTransactionRequest {
1093            id: "42".to_owned(),
1094            payload: serde_json::from_str(&format!(
1095                r#"{{"messages":[{{"address":"{FRIENDLY_ADDRESS}","amount":"0"}}]}}"#
1096            ))?,
1097        });
1098        let wrong_id = WalletResponse::Success(WalletResponseSuccess {
1099            result: WalletResult::String("AA==".to_owned()),
1100            id: "43".to_owned(),
1101        });
1102        let wrong_shape = WalletResponse::Success(WalletResponseSuccess {
1103            result: WalletResult::Object(Map::new()),
1104            id: "42".to_owned(),
1105        });
1106        assert_eq!(
1107            wrong_id.validate_for(&request),
1108            Err(ResponseValidationError::RequestIdMismatch)
1109        );
1110        assert_eq!(
1111            wrong_shape.validate_for(&request),
1112            Err(ResponseValidationError::InvalidResult)
1113        );
1114        Ok(())
1115    }
1116
1117    #[test]
1118    fn sign_data_result_verifies_the_exact_echoed_payload() -> Result<(), SigningError> {
1119        let signing_key = SigningKey::from_bytes(&[0x55; 32]);
1120        let public_key = Ed25519PublicKey::from_bytes(signing_key.verifying_key().to_bytes());
1121        let mut result = SignDataResult {
1122            signature: Ed25519Signature::from_bytes([0_u8; 64]),
1123            address: RawAccountAddress::new(0, [0x44; 32]),
1124            timestamp: 1_700_000_000,
1125            domain: "example.com".to_owned(),
1126            payload: SignDataPayload::Text {
1127                text: "Approve login".to_owned(),
1128                network: None,
1129                from: None,
1130            },
1131        };
1132        result.signature =
1133            Ed25519Signature::from_bytes(signing_key.sign(&result.signing_hash()?).to_bytes());
1134
1135        assert!(result.verify(&public_key)?);
1136        result.payload = SignDataPayload::Text {
1137            text: "Approve transfer".to_owned(),
1138            network: None,
1139            from: None,
1140        };
1141        assert!(!result.verify(&public_key)?);
1142        Ok(())
1143    }
1144
1145    #[test]
1146    fn every_normative_rpc_request_variant_decodes() -> Result<(), Box<dyn std::error::Error>> {
1147        let boc = "te6ccgEBAQEAAgAAAA==";
1148        let raw = serde_json::json!({
1149            "valid_until": 1_900_000_000_u64,
1150            "network": "-239",
1151            "from": "-1:0000000000000000000000000000000000000000000000000000000000000000",
1152            "messages": [{
1153                "address": FRIENDLY_ADDRESS,
1154                "amount": "1",
1155                "payload": boc,
1156                "stateInit": boc
1157            }]
1158        });
1159        let structured = serde_json::json!({
1160            "items": [
1161                {"type":"ton","address":FRIENDLY_ADDRESS,"amount":"1"},
1162                {"type":"jetton","master":FRIENDLY_ADDRESS,"destination":FRIENDLY_ADDRESS,"amount":"2"},
1163                {"type":"nft","nftAddress":FRIENDLY_ADDRESS,"newOwner":FRIENDLY_ADDRESS}
1164            ]
1165        });
1166        let requests = [
1167            app_request("sendTransaction", Some(raw.clone()), "1")?,
1168            app_request("sendTransaction", Some(structured), "2")?,
1169            app_request("signMessage", Some(raw), "3")?,
1170            app_request(
1171                "signData",
1172                Some(serde_json::json!({"type":"text","text":"hello"})),
1173                "4",
1174            )?,
1175            app_request(
1176                "signData",
1177                Some(serde_json::json!({"type":"binary","bytes":"AA=="})),
1178                "5",
1179            )?,
1180            app_request(
1181                "signData",
1182                Some(serde_json::json!({
1183                    "type":"cell",
1184                    "schema":"value:uint32 = Value",
1185                    "cell":boc
1186                })),
1187                "6",
1188            )?,
1189            app_request("disconnect", None, "7")?,
1190        ];
1191
1192        for request in requests {
1193            let decoded = request.clone().decode()?;
1194            let encoded = AppRequest::encode(decoded.clone())?;
1195            assert_eq!(encoded.method, request.method);
1196            assert_eq!(encoded.id, request.id);
1197            assert_eq!(encoded.decode()?, decoded);
1198        }
1199        Ok(())
1200    }
1201
1202    #[test]
1203    fn every_rpc_method_rejects_the_wrong_parameter_count() {
1204        for method in ["sendTransaction", "signMessage", "signData"] {
1205            for params in [Vec::new(), vec!["{}".to_owned(), "{}".to_owned()]] {
1206                let actual = params.len();
1207                assert!(matches!(
1208                    AppRequest {
1209                        method: method.to_owned(),
1210                        params,
1211                        id: "1".to_owned(),
1212                    }
1213                    .decode(),
1214                    Err(RpcError::InvalidParameterCount {
1215                        method: actual_method,
1216                        expected: 1,
1217                        actual: actual_count,
1218                    }) if actual_method == method && actual_count == actual
1219                ));
1220            }
1221        }
1222
1223        assert!(matches!(
1224            AppRequest {
1225                method: "disconnect".to_owned(),
1226                params: vec!["{}".to_owned()],
1227                id: "2".to_owned(),
1228            }
1229            .decode(),
1230            Err(RpcError::InvalidParameterCount {
1231                method: "disconnect",
1232                expected: 0,
1233                actual: 1,
1234            })
1235        ));
1236    }
1237
1238    #[test]
1239    fn every_normative_success_response_matches_its_request()
1240    -> Result<(), Box<dyn std::error::Error>> {
1241        let boc = "te6ccgEBAQEAAgAAAA==";
1242        let transaction = app_request(
1243            "sendTransaction",
1244            Some(serde_json::json!({
1245                "messages":[{"address":FRIENDLY_ADDRESS,"amount":"1"}]
1246            })),
1247            "1",
1248        )?
1249        .decode()?;
1250        let sign_message = app_request(
1251            "signMessage",
1252            Some(serde_json::json!({
1253                "messages":[{"address":FRIENDLY_ADDRESS,"amount":"1"}]
1254            })),
1255            "2",
1256        )?
1257        .decode()?;
1258        let sign_data = app_request(
1259            "signData",
1260            Some(serde_json::json!({"type":"text","text":"hello"})),
1261            "3",
1262        )?
1263        .decode()?;
1264        let disconnect = app_request("disconnect", None, "4")?.decode()?;
1265        let signature = STANDARD.encode([0_u8; 64]);
1266        let responses = [
1267            (transaction, serde_json::json!({"result":boc,"id":"1"})),
1268            (
1269                sign_message,
1270                serde_json::json!({"result":{"internalBoc":boc},"id":"2"}),
1271            ),
1272            (
1273                sign_data,
1274                serde_json::json!({
1275                    "result":{
1276                        "signature":signature,
1277                        "address":"0:1111111111111111111111111111111111111111111111111111111111111111",
1278                        "timestamp":1_800_000_000_u64,
1279                        "domain":"example.com",
1280                        "payload":{"type":"text","text":"hello"}
1281                    },
1282                    "id":"3"
1283                }),
1284            ),
1285            (disconnect, serde_json::json!({"result":{},"id":"4"})),
1286        ];
1287
1288        for (request, response) in responses {
1289            let response = serde_json::from_value::<WalletResponse>(response)?;
1290            assert!(response.validate_for(&request).is_ok());
1291        }
1292        Ok(())
1293    }
1294
1295    #[test]
1296    fn request_context_enforces_expiry_network_and_fixed_account()
1297    -> Result<(), Box<dyn std::error::Error>> {
1298        let active_network = NetworkId::try_from("-239")?;
1299        let active_account = RawAccountAddress::new(-1, [0_u8; 32]);
1300        let request = app_request(
1301            "sendTransaction",
1302            Some(serde_json::json!({
1303                "valid_until":100,
1304                "network":"-239",
1305                "from":FRIENDLY_ADDRESS,
1306                "messages":[{"address":FRIENDLY_ADDRESS,"amount":"1"}]
1307            })),
1308            "1",
1309        )?
1310        .decode()?;
1311        let KnownAppRequest::SendTransaction(request) = request else {
1312            return Err("expected sendTransaction".into());
1313        };
1314        assert_eq!(
1315            request
1316                .payload
1317                .validate_context(101, &active_network, &active_account),
1318            Err(RequestContextError::Expired)
1319        );
1320        assert!(
1321            request
1322                .payload
1323                .validate_context(100, &active_network, &active_account)
1324                .is_ok()
1325        );
1326
1327        let wrong_network = NetworkId::try_from("-3")?;
1328        assert_eq!(
1329            request
1330                .payload
1331                .validate_context(99, &wrong_network, &active_account),
1332            Err(RequestContextError::NetworkMismatch)
1333        );
1334        let wrong_account = RawAccountAddress::new(0, [0_u8; 32]);
1335        assert_eq!(
1336            request
1337                .payload
1338                .validate_context(99, &active_network, &wrong_account),
1339            Err(RequestContextError::AccountMismatch)
1340        );
1341
1342        let sign_data = serde_json::from_value::<SignDataPayload>(serde_json::json!({
1343            "type": "text",
1344            "text": "authorize",
1345            "network": "-239",
1346            "from": FRIENDLY_ADDRESS,
1347        }))?;
1348        assert_eq!(sign_data.data_type(), SignDataType::Text);
1349        assert_eq!(
1350            sign_data.validate_context(&active_network, &active_account),
1351            Ok(())
1352        );
1353        assert_eq!(
1354            sign_data.validate_context(&wrong_network, &active_account),
1355            Err(RequestContextError::NetworkMismatch)
1356        );
1357        assert_eq!(
1358            sign_data.validate_context(&active_network, &wrong_account),
1359            Err(RequestContextError::AccountMismatch)
1360        );
1361        Ok(())
1362    }
1363
1364    #[test]
1365    fn extra_currencies_preserve_typed_identifiers_and_amounts()
1366    -> Result<(), Box<dyn std::error::Error>> {
1367        let values = BTreeMap::from([
1368            (7, DecimalString::try_from("11")?),
1369            (u32::MAX, DecimalString::try_from("0")?),
1370        ]);
1371        let currencies = ExtraCurrencies::new(values.clone());
1372        assert_eq!(currencies.as_map(), &values);
1373        assert!(!currencies.is_empty());
1374        assert_eq!(
1375            serde_json::from_str::<ExtraCurrencies>(&serde_json::to_string(&currencies)?)?,
1376            currencies
1377        );
1378        Ok(())
1379    }
1380
1381    fn app_request(
1382        method: &str,
1383        payload: Option<Value>,
1384        id: &str,
1385    ) -> Result<AppRequest, serde_json::Error> {
1386        Ok(AppRequest {
1387            method: method.to_owned(),
1388            params: payload
1389                .map(|payload| serde_json::to_string(&payload))
1390                .transpose()?
1391                .into_iter()
1392                .collect(),
1393            id: id.to_owned(),
1394        })
1395    }
1396}