everscale_types/models/account/
mod.rs

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
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
//! Account state models.

use crate::cell::*;
use crate::dict::*;
use crate::error::*;
use crate::num::*;

use crate::models::currency::CurrencyCollection;
use crate::models::message::IntAddr;
use crate::models::Lazy;

/// Amount of unique cells and bits for shard states.
#[derive(Debug, Default, Clone, Eq, PartialEq, Store, Load)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct StorageUsed {
    /// Amount of unique cells.
    pub cells: VarUint56,
    /// The total number of bits in unique cells.
    pub bits: VarUint56,
    /// The number of public libraries in the state.
    pub public_cells: VarUint56,
}

impl StorageUsed {
    /// The additive identity for this type, i.e. `0`.
    pub const ZERO: Self = Self {
        cells: VarUint56::ZERO,
        bits: VarUint56::ZERO,
        public_cells: VarUint56::ZERO,
    };

    /// Computes a total storage usage stats.
    ///
    /// `cell_limit` is the maximum number of unique cells to visit.
    /// If the limit is reached, the function will return [`Error::Cancelled`].
    pub fn compute(account: &Account, cell_limit: usize) -> Result<Self, Error> {
        let cell = {
            let cx = &mut Cell::empty_context();
            let mut storage = CellBuilder::new();
            storage.store_u64(account.last_trans_lt)?;
            account.balance.store_into(&mut storage, cx)?;
            account.state.store_into(&mut storage, cx)?;
            if account.init_code_hash.is_some() {
                account.init_code_hash.store_into(&mut storage, cx)?;
            }
            storage.build_ext(cx)?
        };

        let Some(res) = cell.compute_unique_stats(cell_limit) else {
            return Err(Error::Cancelled);
        };

        let res = Self {
            cells: VarUint56::new(res.cell_count),
            bits: VarUint56::new(res.bit_count),
            public_cells: Default::default(),
        };

        if res.cells.is_valid() || !res.bits.is_valid() {
            return Err(Error::IntOverflow);
        }

        Ok(res)
    }
}

/// Amount of unique cells and bits.
#[derive(Debug, Default, Clone, Copy, Eq, PartialEq, Store, Load)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct StorageUsedShort {
    /// Amount of unique cells.
    pub cells: VarUint56,
    /// The total number of bits in unique cells.
    pub bits: VarUint56,
}

impl StorageUsedShort {
    /// The additive identity for this type, i.e. `0`.
    pub const ZERO: Self = Self {
        cells: VarUint56::ZERO,
        bits: VarUint56::ZERO,
    };
}

/// Storage profile of an account.
#[derive(Debug, Default, Clone, Eq, PartialEq, Store, Load)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct StorageInfo {
    /// Amount of unique cells and bits which account state occupies.
    pub used: StorageUsed,
    /// Unix timestamp of the last storage phase.
    pub last_paid: u32,
    /// Account debt for storing its state.
    pub due_payment: Option<Tokens>,
}

/// Brief account status.
#[derive(Debug, Clone, Copy, Eq, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum AccountStatus {
    /// Account exists but has not yet been deployed.
    Uninit = 0b00,
    /// Account exists but has been frozen.
    Frozen = 0b01,
    /// Account exists and has been deployed.
    Active = 0b10,
    /// Account does not exist.
    NotExists = 0b11,
}

impl AccountStatus {
    /// The number of data bits that this struct occupies.
    pub const BITS: u16 = 2;
}

impl Store for AccountStatus {
    #[inline]
    fn store_into(&self, builder: &mut CellBuilder, _: &mut dyn CellContext) -> Result<(), Error> {
        builder.store_small_uint(*self as u8, 2)
    }
}

impl<'a> Load<'a> for AccountStatus {
    #[inline]
    fn load_from(slice: &mut CellSlice<'a>) -> Result<Self, Error> {
        match slice.load_small_uint(2) {
            Ok(ty) => Ok(match ty {
                0b00 => Self::Uninit,
                0b01 => Self::Frozen,
                0b10 => Self::Active,
                0b11 => Self::NotExists,
                _ => {
                    debug_assert!(false, "unexpected small uint");
                    // SAFETY: `load_small_uint` must return 2 bits
                    unsafe { std::hint::unreachable_unchecked() }
                }
            }),
            Err(e) => Err(e),
        }
    }
}

/// Shard accounts entry.
#[derive(Debug, Clone, Eq, PartialEq, Store, Load)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct ShardAccount {
    /// Optional reference to account state.
    pub account: Lazy<OptionalAccount>,
    /// The exact hash of the last transaction.
    pub last_trans_hash: HashBytes,
    /// The exact logical time of the last transaction.
    pub last_trans_lt: u64,
}

impl ShardAccount {
    /// Tries to load account data.
    pub fn load_account(&self) -> Result<Option<Account>, Error> {
        let OptionalAccount(account) = ok!(self.account.load());
        Ok(account)
    }
}

/// A wrapper for `Option<Account>` with customized representation.
#[derive(Default, Debug, Clone, Eq, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct OptionalAccount(pub Option<Account>);

impl OptionalAccount {
    /// Non-existing account.
    pub const EMPTY: Self = Self(None);

    /// Returns an optional account status.
    pub fn status(&self) -> AccountStatus {
        match &self.0 {
            None => AccountStatus::NotExists,
            Some(account) => account.state.status(),
        }
    }

    /// Logical time after the last transaction execution if account exists
    /// or zero otherwise.
    pub fn last_trans_lt(&self) -> u64 {
        match &self.0 {
            None => 0,
            Some(account) => account.last_trans_lt,
        }
    }

    /// Account balance for all currencies.
    #[cfg(feature = "sync")]
    pub fn balance(&self) -> &CurrencyCollection {
        static DEFAULT_VALANCE: CurrencyCollection = CurrencyCollection::ZERO;

        match &self.0 {
            None => &DEFAULT_VALANCE,
            Some(account) => &account.balance,
        }
    }

    /// Returns an account state if it exists.
    pub fn state(&self) -> Option<&AccountState> {
        Some(&self.0.as_ref()?.state)
    }
}

impl AsRef<Option<Account>> for OptionalAccount {
    #[inline]
    fn as_ref(&self) -> &Option<Account> {
        &self.0
    }
}

impl AsMut<Option<Account>> for OptionalAccount {
    #[inline]
    fn as_mut(&mut self) -> &mut Option<Account> {
        &mut self.0
    }
}

impl Store for OptionalAccount {
    fn store_into(
        &self,
        builder: &mut CellBuilder,
        context: &mut dyn CellContext,
    ) -> Result<(), Error> {
        match &self.0 {
            None => builder.store_bit_zero(),
            Some(account) => {
                let with_init_code_hash = account.init_code_hash.is_some();
                ok!(if with_init_code_hash {
                    builder.store_small_uint(0b0001, 4)
                } else {
                    builder.store_bit_one()
                });

                ok!(account.address.store_into(builder, context));
                ok!(account.storage_stat.store_into(builder, context));
                ok!(builder.store_u64(account.last_trans_lt));
                ok!(account.balance.store_into(builder, context));
                ok!(account.state.store_into(builder, context));
                if let Some(init_code_hash) = &account.init_code_hash {
                    ok!(builder.store_bit_one());
                    builder.store_u256(init_code_hash)
                } else {
                    Ok(())
                }
            }
        }
    }
}

impl<'a> Load<'a> for OptionalAccount {
    fn load_from(slice: &mut CellSlice<'a>) -> Result<Self, Error> {
        let with_init_code_hash = if ok!(slice.load_bit()) {
            false // old version
        } else if slice.is_data_empty() {
            return Ok(Self::EMPTY);
        } else {
            let tag = ok!(slice.load_small_uint(3));
            match tag {
                0 => false, // old version
                1 => true,  // new version
                _ => return Err(Error::InvalidData),
            }
        };

        Ok(Self(Some(Account {
            address: ok!(IntAddr::load_from(slice)),
            storage_stat: ok!(StorageInfo::load_from(slice)),
            last_trans_lt: ok!(slice.load_u64()),
            balance: ok!(CurrencyCollection::load_from(slice)),
            state: ok!(AccountState::load_from(slice)),
            init_code_hash: if with_init_code_hash {
                ok!(Option::<HashBytes>::load_from(slice))
            } else {
                None
            },
        })))
    }
}

impl From<Account> for OptionalAccount {
    #[inline]
    fn from(value: Account) -> Self {
        Self(Some(value))
    }
}

/// Existing account data.
#[derive(Debug, Clone, Eq, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Account {
    /// Account address.
    pub address: IntAddr,
    /// Storage statistics.
    pub storage_stat: StorageInfo,
    /// Logical time after the last transaction execution.
    pub last_trans_lt: u64,
    /// Account balance for all currencies.
    pub balance: CurrencyCollection,
    /// Account state.
    pub state: AccountState,
    /// Optional initial code hash.
    pub init_code_hash: Option<HashBytes>,
}

/// State of an existing account.
#[derive(Debug, Clone, Eq, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(tag = "status"))]
pub enum AccountState {
    /// Account exists but has not yet been deployed.
    Uninit,
    /// Account exists and has been deployed.
    Active(StateInit),
    /// Account exists but has been frozen. Contains a hash of the last known [`StateInit`].
    Frozen(HashBytes),
}

impl AccountState {
    /// Returns an account status.
    pub fn status(&self) -> AccountStatus {
        match self {
            Self::Uninit => AccountStatus::Uninit,
            Self::Active(_) => AccountStatus::Active,
            Self::Frozen(_) => AccountStatus::Frozen,
        }
    }
}

impl Store for AccountState {
    fn store_into(
        &self,
        builder: &mut CellBuilder,
        context: &mut dyn CellContext,
    ) -> Result<(), Error> {
        match self {
            Self::Uninit => builder.store_small_uint(0b00, 2),
            Self::Active(state) => {
                ok!(builder.store_bit_one());
                state.store_into(builder, context)
            }
            Self::Frozen(hash) => {
                ok!(builder.store_small_uint(0b01, 2));
                builder.store_u256(hash)
            }
        }
    }
}

impl<'a> Load<'a> for AccountState {
    fn load_from(slice: &mut CellSlice<'a>) -> Result<Self, Error> {
        Ok(if ok!(slice.load_bit()) {
            match StateInit::load_from(slice) {
                Ok(state) => Self::Active(state),
                Err(e) => return Err(e),
            }
        } else if ok!(slice.load_bit()) {
            match slice.load_u256() {
                Ok(state) => Self::Frozen(state),
                Err(e) => return Err(e),
            }
        } else {
            Self::Uninit
        })
    }
}

/// Deployed account state.
#[derive(Debug, Clone, Eq, PartialEq, Store, Load)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct StateInit {
    /// Optional split depth for large smart contracts.
    pub split_depth: Option<SplitDepth>,
    /// Optional special contract flags.
    pub special: Option<SpecialFlags>,
    /// Optional contract code.
    #[cfg_attr(feature = "serde", serde(with = "crate::boc::Boc"))]
    pub code: Option<Cell>,
    /// Optional contract data.
    #[cfg_attr(feature = "serde", serde(with = "crate::boc::Boc"))]
    pub data: Option<Cell>,
    /// Libraries used in smart-contract.
    pub libraries: Dict<HashBytes, SimpleLib>,
}

impl Default for StateInit {
    fn default() -> Self {
        Self {
            split_depth: None,
            special: None,
            code: None,
            data: None,
            libraries: Dict::new(),
        }
    }
}

impl StateInit {
    /// Exact size of this value when it is stored in slice.
    pub const fn exact_size_const(&self) -> Size {
        Size {
            bits: self.bit_len(),
            refs: self.reference_count(),
        }
    }

    /// Returns the number of data bits that this struct occupies.
    const fn bit_len(&self) -> u16 {
        (1 + self.split_depth.is_some() as u16 * SplitDepth::BITS)
            + (1 + self.special.is_some() as u16 * SpecialFlags::BITS)
            + 3
    }

    /// Returns the number of references that this struct occupies.
    const fn reference_count(&self) -> u8 {
        self.code.is_some() as u8 + self.data.is_some() as u8 + !self.libraries.is_empty() as u8
    }
}

impl ExactSize for StateInit {
    #[inline]
    fn exact_size(&self) -> Size {
        self.exact_size_const()
    }
}

/// Special transactions execution flags.
#[derive(Debug, Default, Clone, Copy, Eq, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct SpecialFlags {
    /// Account will be called at the beginning of each block.
    pub tick: bool,
    /// Account will be called at the end of each block.
    pub tock: bool,
}

impl SpecialFlags {
    /// The number of data bits that this struct occupies.
    pub const BITS: u16 = 2;
}

impl Store for SpecialFlags {
    fn store_into(&self, builder: &mut CellBuilder, _: &mut dyn CellContext) -> Result<(), Error> {
        builder.store_small_uint(((self.tick as u8) << 1) | self.tock as u8, 2)
    }
}

impl<'a> Load<'a> for SpecialFlags {
    fn load_from(slice: &mut CellSlice<'a>) -> Result<Self, Error> {
        match slice.load_small_uint(2) {
            Ok(data) => Ok(Self {
                tick: data & 0b10 != 0,
                tock: data & 0b01 != 0,
            }),
            Err(e) => Err(e),
        }
    }
}

/// Simple TVM library.
#[derive(Debug, Clone, Eq, PartialEq, Store, Load)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct SimpleLib {
    /// Whether this library is accessible from other accounts.
    pub public: bool,
    /// Library code.
    #[cfg_attr(feature = "serde", serde(with = "crate::boc::Boc"))]
    pub root: Cell,
}