r402-tvm 0.17.1

TON (TVM) chain support for the x402 payment protocol.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
//! Wire format types for TON chain interactions.

use std::fmt::{Debug, Display, Formatter};
use std::str::FromStr;

use compact_str::CompactString;
use r402_core::amount::{MoneyAmount, MoneyAmountParseError};
use r402_core::chain::{ChainId, DeployedTokenAmount};
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use tonlib_core::TonAddress;

use crate::{TONCENTER_MAINNET_BASE_URL, TONCENTER_TESTNET_BASE_URL};

/// The CAIP-2 namespace for TON chains.
pub const TVM_NAMESPACE: &str = "tvm";

/// A TON chain reference (`-239` mainnet or `-3` testnet).
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
pub enum TvmChainReference {
    /// TON mainnet (`tvm:-239`).
    Mainnet,
    /// TON testnet (`tvm:-3`).
    Testnet,
}

impl TvmChainReference {
    /// TON mainnet (`tvm:-239`).
    pub const MAINNET: Self = Self::Mainnet;

    /// TON testnet (`tvm:-3`).
    pub const TESTNET: Self = Self::Testnet;

    /// All chain references with built-in support.
    pub const ALL: &'static [Self] = &[Self::Mainnet, Self::Testnet];

    /// Returns the CAIP-2 reference string, including the leading minus.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Mainnet => "-239",
            Self::Testnet => "-3",
        }
    }

    /// TON global id used when deriving W5R1 `walletId`.
    #[must_use]
    pub const fn global_id(self) -> i32 {
        match self {
            Self::Mainnet => -239,
            Self::Testnet => -3,
        }
    }

    /// Returns the default Toncenter REST root for this network.
    #[must_use]
    pub const fn default_rpc_url(self) -> &'static str {
        match self {
            Self::Mainnet => TONCENTER_MAINNET_BASE_URL,
            Self::Testnet => TONCENTER_TESTNET_BASE_URL,
        }
    }
}

impl Debug for TvmChainReference {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        write!(f, "TvmChainReference({})", self.as_str())
    }
}

impl Display for TvmChainReference {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        f.write_str(self.as_str())
    }
}

impl FromStr for TvmChainReference {
    type Err = TvmChainReferenceFormatError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s {
            "-239" => Ok(Self::Mainnet),
            "-3" => Ok(Self::Testnet),
            other => Err(TvmChainReferenceFormatError::InvalidReference(
                other.to_owned(),
            )),
        }
    }
}

impl Serialize for TvmChainReference {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        serializer.serialize_str(self.as_str())
    }
}

impl<'de> Deserialize<'de> for TvmChainReference {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        let s = String::deserialize(deserializer)?;
        s.parse().map_err(serde::de::Error::custom)
    }
}

impl From<TvmChainReference> for ChainId {
    fn from(value: TvmChainReference) -> Self {
        Self::new(TVM_NAMESPACE, value.as_str())
    }
}

impl TryFrom<ChainId> for TvmChainReference {
    type Error = TvmChainReferenceFormatError;

    fn try_from(value: ChainId) -> Result<Self, Self::Error> {
        let (namespace, reference) = value.into_parts();
        if namespace != TVM_NAMESPACE {
            return Err(TvmChainReferenceFormatError::InvalidNamespace(namespace));
        }
        Self::from_str(&reference)
            .map_err(|_| TvmChainReferenceFormatError::InvalidReference(reference))
    }
}

/// Error type for parsing TON chain references.
#[derive(Debug, thiserror::Error)]
pub enum TvmChainReferenceFormatError {
    /// The namespace was not `"tvm"`.
    #[error("Invalid namespace {0}, expected tvm")]
    InvalidNamespace(String),
    /// The reference was not `-239` or `-3`.
    #[error("Invalid tvm chain reference {0}")]
    InvalidReference(String),
}

/// Returns `true` when `network` is a canonical TVM CAIP-2 identifier.
#[must_use]
pub fn is_tvm_network(network: &str) -> bool {
    network == "tvm:-239" || network == "tvm:-3"
}

/// A TON address stored in raw `workchain:hex` form.
///
/// User-friendly bounceable / non-bounceable strings are accepted on parse
/// and normalized to raw form.
#[derive(Clone, Debug, Hash, PartialEq, Eq)]
pub struct TvmAddress(CompactString);

impl TvmAddress {
    /// Returns the raw `workchain:hex` string.
    #[must_use]
    pub fn as_str(&self) -> &str {
        self.0.as_str()
    }

    /// Parses into a `tonlib-core` address.
    ///
    /// # Errors
    ///
    /// Returns [`TvmAddressFormatError`] if the stored raw form is not a TON address.
    pub fn to_ton(&self) -> Result<TonAddress, TvmAddressFormatError> {
        TonAddress::from_str(self.as_str())
            .map_err(|e| TvmAddressFormatError::Invalid(e.to_string()))
    }
}

impl Display for TvmAddress {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        f.write_str(self.as_str())
    }
}

impl FromStr for TvmAddress {
    type Err = TvmAddressFormatError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let parsed =
            TonAddress::from_str(s).map_err(|e| TvmAddressFormatError::Invalid(e.to_string()))?;
        Ok(Self(CompactString::from(parsed.to_hex())))
    }
}

impl TryFrom<&TonAddress> for TvmAddress {
    type Error = TvmAddressFormatError;

    fn try_from(value: &TonAddress) -> Result<Self, Self::Error> {
        Ok(Self(CompactString::from(value.to_hex())))
    }
}

impl Serialize for TvmAddress {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        serializer.serialize_str(self.as_str())
    }
}

impl<'de> Deserialize<'de> for TvmAddress {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        let s = String::deserialize(deserializer)?;
        s.parse().map_err(serde::de::Error::custom)
    }
}

impl AsRef<str> for TvmAddress {
    fn as_ref(&self) -> &str {
        self.as_str()
    }
}

/// Errors that can occur when parsing a TON address.
#[derive(Debug, thiserror::Error)]
pub enum TvmAddressFormatError {
    /// The string is not a valid TON address.
    #[error("invalid tvm address: {0}")]
    Invalid(String),
}

/// Jetton atomic units as a decimal string; parsed as `u128`.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct TvmTokenAmount(CompactString);

impl TvmTokenAmount {
    /// Returns the decimal string.
    #[must_use]
    pub fn as_str(&self) -> &str {
        self.0.as_str()
    }

    /// Parses the amount as `u128`.
    ///
    /// # Errors
    ///
    /// Returns [`TvmTokenAmountFormatError`] if the string is not a decimal `u128`.
    pub fn as_u128(&self) -> Result<u128, TvmTokenAmountFormatError> {
        self.0
            .parse()
            .map_err(|_| TvmTokenAmountFormatError::Invalid(self.0.to_string()))
    }
}

impl Display for TvmTokenAmount {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        f.write_str(self.as_str())
    }
}

impl FromStr for TvmTokenAmount {
    type Err = TvmTokenAmountFormatError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        if s.is_empty() || !s.bytes().all(|b| b.is_ascii_digit()) {
            return Err(TvmTokenAmountFormatError::Invalid(s.to_owned()));
        }
        let _: u128 = s
            .parse()
            .map_err(|_| TvmTokenAmountFormatError::Invalid(s.to_owned()))?;
        Ok(Self(CompactString::from(s)))
    }
}

impl Serialize for TvmTokenAmount {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        serializer.serialize_str(self.as_str())
    }
}

impl<'de> Deserialize<'de> for TvmTokenAmount {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        let s = String::deserialize(deserializer)?;
        s.parse().map_err(serde::de::Error::custom)
    }
}

impl From<u128> for TvmTokenAmount {
    fn from(value: u128) -> Self {
        Self(CompactString::from(value.to_string()))
    }
}

impl TryFrom<TvmTokenAmount> for u128 {
    type Error = TvmTokenAmountFormatError;

    fn try_from(value: TvmTokenAmount) -> Result<Self, Self::Error> {
        value.as_u128()
    }
}

/// Error parsing a jetton token amount.
#[derive(Debug, thiserror::Error)]
pub enum TvmTokenAmountFormatError {
    /// The string is not an unsigned decimal integer.
    #[error("invalid tvm token amount: {0}")]
    Invalid(String),
}

/// Information about a jetton minter deployment on a TON network.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct TvmTokenDeployment {
    /// The TON network where this token is deployed.
    pub chain_reference: TvmChainReference,
    /// The jetton master contract address.
    pub address: TvmAddress,
    /// The number of decimal places for this token.
    pub decimals: u8,
}

impl TvmTokenDeployment {
    /// Creates a new token deployment.
    #[must_use]
    pub const fn new(
        chain_reference: TvmChainReference,
        address: TvmAddress,
        decimals: u8,
    ) -> Self {
        Self {
            chain_reference,
            address,
            decimals,
        }
    }

    /// Creates a deployed token amount with the given raw atomic units.
    #[must_use]
    pub fn amount(&self, v: u128) -> DeployedTokenAmount<u128, Self> {
        DeployedTokenAmount {
            amount: v,
            token: self.clone(),
        }
    }

    /// Parses a human-readable amount into a deployed token amount.
    ///
    /// # Errors
    ///
    /// Returns [`MoneyAmountParseError`] if the value cannot be parsed, exceeds
    /// precision, or overflows `u128`.
    pub fn parse<V>(&self, v: V) -> Result<DeployedTokenAmount<u128, Self>, MoneyAmountParseError>
    where
        V: TryInto<MoneyAmount>,
        MoneyAmountParseError: From<<V as TryInto<MoneyAmount>>::Error>,
    {
        let amount: u128 = v.try_into()?.to_token_amount(self.decimals)?;
        Ok(DeployedTokenAmount {
            amount,
            token: self.clone(),
        })
    }
}

#[cfg(test)]
#[allow(clippy::unwrap_used, reason = "test assertions")]
mod tests {
    use super::*;

    #[test]
    fn chain_id_roundtrips_signed_reference() {
        let mainnet: ChainId = TvmChainReference::MAINNET.into();
        assert_eq!(mainnet.to_string(), "tvm:-239");
        assert_eq!(mainnet.namespace(), "tvm");
        assert_eq!(mainnet.reference(), "-239");
        let back = TvmChainReference::try_from(mainnet).unwrap();
        assert_eq!(back, TvmChainReference::MAINNET);

        let testnet: ChainId = TvmChainReference::TESTNET.into();
        assert_eq!(testnet.to_string(), "tvm:-3");
        assert_eq!(testnet.reference(), "-3");
        assert!(is_tvm_network("tvm:-239"));
        assert!(is_tvm_network("tvm:-3"));
        assert!(!is_tvm_network("eip155:1"));
    }

    #[test]
    fn address_normalizes_raw_and_friendly() {
        let raw = "0:b113a994b5024a16719f69139328eb759596c38a25f59028b146fecdc3621dfe";
        let parsed: TvmAddress = raw.parse().unwrap();
        assert_eq!(parsed.as_str(), raw);
        let friendly = parsed.to_ton().unwrap().to_base64_url();
        let from_friendly: TvmAddress = friendly.parse().unwrap();
        assert_eq!(from_friendly.as_str(), raw);
    }

    #[test]
    fn token_amount_decimal_string() {
        let amount: TvmTokenAmount = "10000".parse().unwrap();
        assert_eq!(amount.as_u128().unwrap(), 10_000);
        assert!("".parse::<TvmTokenAmount>().is_err());
        assert!("1.0".parse::<TvmTokenAmount>().is_err());
        assert!("-1".parse::<TvmTokenAmount>().is_err());
    }
}