ton-contracts 0.7.2

Bindings for common smart-contracts on TON blockchain
Documentation
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
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
use std::sync::Arc;

use chrono::{DateTime, Utc};
use lazy_static::lazy_static;
use nacl::sign::PUBLIC_KEY_LENGTH;
use tlb_ton::{
    BagOfCells, Cell, Context, Data, Error, List, MsgAddress, Same, UnixTimestamp,
    action::{OutAction, SendMsgAction},
    bits::{de::BitReaderExt, ser::BitWriterExt},
    de::{CellDeserialize, CellParser, CellParserError},
    hashmap::HashmapE,
    ser::{CellBuilder, CellBuilderError, CellSerialize},
};

use super::WalletVersion;

lazy_static! {
    static ref WALLET_V5R1_CODE_CELL: Arc<Cell> = {
        BagOfCells::parse_base64(include_str!("./wallet_v5r1.code"))
            .unwrap()
            .into_single_root()
            .expect("code BoC must be single root")
    };
}

/// Wallet [v5r1](https://github.com/ton-blockchain/wallet-contract-v5/blob/main/Specification.md).
pub struct V5R1;

impl WalletVersion for V5R1 {
    type Data = WalletV5R1Data;
    type SignBody = WalletV5RSignBody;
    type ExternalMsgBody = WalletV5R1MsgBody;

    const DEFAULT_WALLET_ID: u32 = 0x7FFFFF11;

    #[inline]
    fn code() -> Arc<Cell> {
        WALLET_V5R1_CODE_CELL.clone()
    }

    #[inline]
    fn init_data(wallet_id: u32, pubkey: [u8; nacl::sign::PUBLIC_KEY_LENGTH]) -> Self::Data {
        WalletV5R1Data {
            is_signature_allowed: true,
            seqno: 0,
            wallet_id,
            pubkey,
            extensions: HashmapE::Empty,
        }
    }

    #[inline]
    fn create_sign_body(
        wallet_id: u32,
        valid_until: DateTime<Utc>,
        msg_seqno: u32,
        msgs: impl IntoIterator<Item = SendMsgAction>,
    ) -> Self::SignBody {
        WalletV5RSignBody {
            wallet_id,
            valid_until,
            msg_seqno,
            inner: WalletV5R1InnerRequest {
                out_actions: msgs.into_iter().map(OutAction::SendMsg).collect(),
                extended: [].into(),
            },
        }
    }

    #[inline]
    fn wrap_signed_external(body: Self::SignBody, signature: [u8; 64]) -> Self::ExternalMsgBody {
        WalletV5R1MsgBody::ExternalSigned(WalletV5R1SignedRequest { body, signature })
    }
}

#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct WalletV5R1Data {
    pub is_signature_allowed: bool,
    pub seqno: u32,
    pub wallet_id: u32,
    pub pubkey: [u8; PUBLIC_KEY_LENGTH],
    #[cfg_attr(feature = "arbitrary", arbitrary(default))]
    pub extensions: HashmapE<bool>,
}

impl CellSerialize for WalletV5R1Data {
    type Args = ();

    #[inline]
    fn store(&self, builder: &mut CellBuilder, _: Self::Args) -> Result<(), CellBuilderError> {
        builder
            .pack(self.is_signature_allowed, ())?
            .pack(self.seqno, ())?
            .pack(self.wallet_id, ())?
            .pack(self.pubkey, ())?
            .store_as::<_, &HashmapE<Data, Same>>(&self.extensions, (256, (), ()))?;
        Ok(())
    }
}

impl<'de> CellDeserialize<'de> for WalletV5R1Data {
    type Args = ();

    #[inline]
    fn parse(parser: &mut CellParser<'de>, _: Self::Args) -> Result<Self, CellParserError<'de>> {
        Ok(Self {
            is_signature_allowed: parser.unpack(())?,
            seqno: parser.unpack(())?,
            wallet_id: parser.unpack(())?,
            pubkey: parser.unpack(())?,
            extensions: parser.parse_as::<_, HashmapE<Data, Same>>((256, (), ()))?,
        })
    }
}

/// ```tlb
/// actions$_ out_actions:(Maybe OutList) has_other_actions:(## 1) {m:#} {n:#} other_actions:(ActionList n m) = InnerRequest;
/// ```
#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct WalletV5R1InnerRequest {
    pub out_actions: Vec<OutAction>,
    pub extended: Vec<ExtendedAction>,
}

impl CellSerialize for WalletV5R1InnerRequest {
    type Args = ();

    fn store(&self, builder: &mut CellBuilder, _: Self::Args) -> Result<(), CellBuilderError> {
        builder
            .store_as::<_, Option<&List>>(
                Some(&self.out_actions).filter(|actions| !actions.is_empty()),
                (),
            )?
            .store_as::<_, Option<&List>>(
                Some(&self.extended).filter(|other| !other.is_empty()),
                (),
            )?;
        Ok(())
    }
}

impl<'de> CellDeserialize<'de> for WalletV5R1InnerRequest {
    type Args = ();

    fn parse(parser: &mut CellParser<'de>, _: Self::Args) -> Result<Self, CellParserError<'de>> {
        Ok(Self {
            out_actions: parser
                .parse_as::<_, Option<List>>(())
                .context("out_actions")?
                .unwrap_or_default(),
            extended: parser
                .parse_as::<_, Option<List>>(())
                .context("extended")?
                .unwrap_or_default(),
        })
    }
}

/// ```tlb
/// action_add_ext#02 addr:MsgAddressInt = ExtendedAction;
/// action_delete_ext#03 addr:MsgAddressInt = ExtendedAction;
/// action_set_signature_auth_allowed#04 allowed:(## 1) = ExtendedAction;
/// ```
#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ExtendedAction {
    /// ```tlb
    /// action_add_ext#02 addr:MsgAddressInt = ExtendedAction;
    /// ```
    AddExtension(MsgAddress),

    /// ```tlb
    /// action_delete_ext#03 addr:MsgAddressInt = ExtendedAction;
    /// ```
    DeleteExtension(MsgAddress),

    /// ```tlb
    /// action_set_signature_auth_allowed#04 allowed:(## 1) = ExtendedAction;
    /// ```
    SetSignatureAuthAllowed(bool),
}

impl ExtendedAction {
    const ADD_EXTENSION_PREFIX: u8 = 0x02;
    const DELETE_EXTENSION_PREFIX: u8 = 0x03;
    const SET_SIGNATURE_AUTH_ALLOWED_PREFIX: u8 = 0x04;
}

impl CellSerialize for ExtendedAction {
    type Args = ();

    fn store(&self, builder: &mut CellBuilder, _: Self::Args) -> Result<(), CellBuilderError> {
        match self {
            Self::AddExtension(addr) => builder
                .pack(Self::ADD_EXTENSION_PREFIX, ())?
                .pack(addr, ())?,
            Self::DeleteExtension(addr) => builder
                .pack(Self::DELETE_EXTENSION_PREFIX, ())?
                .pack(addr, ())?,
            Self::SetSignatureAuthAllowed(allowed) => builder
                .pack(Self::SET_SIGNATURE_AUTH_ALLOWED_PREFIX, ())?
                .pack(allowed, ())?,
        };
        Ok(())
    }
}

impl<'de> CellDeserialize<'de> for ExtendedAction {
    type Args = ();

    fn parse(parser: &mut CellParser<'de>, _: Self::Args) -> Result<Self, CellParserError<'de>> {
        Ok(match parser.unpack(())? {
            Self::ADD_EXTENSION_PREFIX => Self::AddExtension(parser.unpack(())?),
            Self::DELETE_EXTENSION_PREFIX => Self::DeleteExtension(parser.unpack(())?),
            Self::SET_SIGNATURE_AUTH_ALLOWED_PREFIX => {
                Self::SetSignatureAuthAllowed(parser.unpack(())?)
            }
            prefix => return Err(Error::custom(format!("unknown prefix: {prefix:#0x}"))),
        })
    }
}

/// ```tlb
/// signed_request$_             // 32 (opcode from outer)
///  wallet_id:    #            // 32
///  valid_until:  #            // 32
///  msg_seqno:    #            // 32
///  inner:        InnerRequest //
///  signature:    bits512      // 512
///= SignedRequest;             // Total: 688 .. 976 + ^Cell
/// ```
#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct WalletV5RSignBody {
    pub wallet_id: u32,
    #[cfg_attr(
        feature = "arbitrary",
        arbitrary(with = UnixTimestamp::arbitrary)
    )]
    pub valid_until: DateTime<Utc>,
    pub msg_seqno: u32,
    pub inner: WalletV5R1InnerRequest,
}

impl CellSerialize for WalletV5RSignBody {
    type Args = ();

    fn store(&self, builder: &mut CellBuilder, _: Self::Args) -> Result<(), CellBuilderError> {
        builder
            .pack(self.wallet_id, ())?
            .pack_as::<_, UnixTimestamp>(self.valid_until, ())?
            .pack(self.msg_seqno, ())?
            .store(&self.inner, ())?;
        Ok(())
    }
}

impl<'de> CellDeserialize<'de> for WalletV5RSignBody {
    type Args = ();

    fn parse(parser: &mut CellParser<'de>, _: Self::Args) -> Result<Self, CellParserError<'de>> {
        Ok(Self {
            wallet_id: parser.unpack(())?,
            valid_until: parser.unpack_as::<_, UnixTimestamp>(())?,
            msg_seqno: parser.unpack(())?,
            inner: parser.parse(())?,
        })
    }
}

/// ```tlb
/// signed_request$_             // 32 (opcode from outer)
///  wallet_id:    #            // 32
///  valid_until:  #            // 32
///  msg_seqno:    #            // 32
///  inner:        InnerRequest //
///  signature:    bits512      // 512
///= SignedRequest;             // Total: 688 .. 976 + ^Cell
/// ```
#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct WalletV5R1SignedRequest {
    pub body: WalletV5RSignBody,
    pub signature: [u8; 64],
}

impl CellSerialize for WalletV5R1SignedRequest {
    type Args = ();

    fn store(&self, builder: &mut CellBuilder, _: Self::Args) -> Result<(), CellBuilderError> {
        builder.store(&self.body, ())?.pack(self.signature, ())?;
        Ok(())
    }
}

impl<'de> CellDeserialize<'de> for WalletV5R1SignedRequest {
    type Args = ();

    fn parse(parser: &mut CellParser<'de>, _: Self::Args) -> Result<Self, CellParserError<'de>> {
        Ok(Self {
            body: parser.parse(())?,
            signature: parser.unpack(())?,
        })
    }
}

#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum WalletV5R1MsgBody {
    /// ```tlb
    /// internal_signed#73696e74 signed:SignedRequest = InternalMsgBody;
    /// ```
    InternalSigned(WalletV5R1SignedRequest),

    /// ```tlb
    /// internal_extension#6578746e query_id:(## 64) inner:InnerRequest = InternalMsgBody;
    /// ```
    InternalExtension(InternalExtensionWalletV5R1MsgBody),

    /// ```tlb
    /// external_signed#7369676e signed:SignedRequest = ExternalMsgBody;
    /// ```
    ExternalSigned(WalletV5R1SignedRequest),
}

impl WalletV5R1MsgBody {
    const INTERNAL_SIGNED_PREFIX: u32 = 0x73696e74;
    const INTERNAL_EXTENSION_PREFIX: u32 = 0x6578746e;
    const EXTERNAL_SIGNED_PREFIX: u32 = 0x7369676e;
}

impl CellSerialize for WalletV5R1MsgBody {
    type Args = ();

    fn store(&self, builder: &mut CellBuilder, _: Self::Args) -> Result<(), CellBuilderError> {
        match self {
            Self::InternalSigned(msg) => builder
                .pack(Self::INTERNAL_SIGNED_PREFIX, ())?
                .store(msg, ())?,
            Self::InternalExtension(msg) => builder
                .pack(Self::INTERNAL_EXTENSION_PREFIX, ())?
                .store(msg, ())?,
            Self::ExternalSigned(msg) => builder
                .pack(Self::EXTERNAL_SIGNED_PREFIX, ())?
                .store(msg, ())?,
        };
        Ok(())
    }
}

impl<'de> CellDeserialize<'de> for WalletV5R1MsgBody {
    type Args = ();

    fn parse(parser: &mut CellParser<'de>, _: Self::Args) -> Result<Self, CellParserError<'de>> {
        Ok(match parser.unpack(())? {
            Self::INTERNAL_SIGNED_PREFIX => {
                Self::InternalSigned(parser.parse(()).context("internal_signed")?)
            }
            Self::INTERNAL_EXTENSION_PREFIX => {
                Self::InternalExtension(parser.parse(()).context("internal_extension")?)
            }
            Self::EXTERNAL_SIGNED_PREFIX => {
                Self::ExternalSigned(parser.parse(()).context("external_signed")?)
            }
            prefix => return Err(Error::custom(format!("unknown prefix: {prefix:#0x}"))),
        })
    }
}

#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct InternalExtensionWalletV5R1MsgBody {
    query_id: u64,
    inner: WalletV5R1InnerRequest,
}

impl CellSerialize for InternalExtensionWalletV5R1MsgBody {
    type Args = ();

    fn store(&self, builder: &mut CellBuilder, _: Self::Args) -> Result<(), CellBuilderError> {
        builder.pack(self.query_id, ())?.store(&self.inner, ())?;
        Ok(())
    }
}

impl<'de> CellDeserialize<'de> for InternalExtensionWalletV5R1MsgBody {
    type Args = ();

    fn parse(parser: &mut CellParser<'de>, _: Self::Args) -> Result<Self, CellParserError<'de>> {
        Ok(Self {
            query_id: parser.unpack(())?,
            inner: parser.parse(())?,
        })
    }
}

#[cfg(test)]
mod tests {
    use tlb_ton::{
        BagOfCellsArgs, BoC,
        bits::{de::unpack_fully, ser::pack},
    };

    use super::*;

    #[test]
    fn check_code() {
        let packed = pack(
            BoC::from_root(WALLET_V5R1_CODE_CELL.clone()),
            BagOfCellsArgs {
                has_idx: false,
                has_crc32c: true,
            },
        )
        .unwrap();

        let unpacked: BoC = unpack_fully(&packed, ()).unwrap();

        let got: Cell = unpacked.single_root().unwrap().parse_fully(()).unwrap();
        assert_eq!(&got, WALLET_V5R1_CODE_CELL.as_ref());
    }
}