inkpad_sandbox/
contract.rs

1//! Contract entry
2use crate::Sandbox;
3use inkpad_std::Vec;
4use parity_scale_codec::{Decode, Encode};
5
6/// Gas Meter
7#[derive(Default, Clone, Decode, Encode)]
8pub struct GasMeter {
9    pub gas_limit: u64,
10    pub gas_left: u64,
11}
12
13impl GasMeter {
14    pub fn new(gas: u64) -> GasMeter {
15        GasMeter {
16            gas_limit: gas,
17            gas_left: gas,
18        }
19    }
20
21    pub fn gas_left_bytes(&self) -> Vec<u8> {
22        self.gas_left.encode()
23    }
24
25    pub fn with_nested<R, F>(&mut self, amount: u64, f: F) -> R
26    where
27        F: FnOnce(Option<&mut GasMeter>) -> R,
28    {
29        // NOTE that it is ok to allocate all available gas since it still ensured
30        // by `charge` that it doesn't reach zero.
31        if self.gas_left < amount {
32            f(None)
33        } else {
34            self.gas_left -= amount;
35
36            let mut nested = GasMeter::new(amount);
37            let r = f(Some(&mut nested));
38
39            self.gas_left += nested.gas_left;
40            r
41        }
42    }
43}
44
45/// Information needed for rent calculations that can be requested by a contract.
46#[derive(Default, Clone, Encode, Decode, PartialEq, Eq)]
47pub struct RentParams {
48    /// The total balance of the contract. Includes the balance transferred from the caller.
49    total_balance: u64,
50    /// The free balance of the contract. Includes the balance transferred from the caller.
51    free_balance: u64,
52    /// See crate [`Contracts::subsistence_threshold()`].
53    subsistence_threshold: u64,
54    /// See crate [`Config::DepositPerContract`].
55    deposit_per_contract: u64,
56    /// See crate [`Config::DepositPerStorageByte`].
57    deposit_per_storage_byte: u64,
58    /// See crate [`Config::DepositPerStorageItem`].
59    deposit_per_storage_item: u64,
60    /// See crate [`Ext::rent_allowance()`].
61    rent_allowance: u64,
62    /// See crate [`Config::RentFraction`].
63    rent_fraction: u16,
64    /// See crate [`AliveContractInfo::storage_size`].
65    storage_size: u32,
66    /// See crate [`Executable::aggregate_code_len()`].
67    code_size: u32,
68    /// See crate [`Executable::refcount()`].
69    code_refcount: u32,
70    /// Reserved for backwards compatible changes to this data structure.
71    _reserved: Option<()>,
72}
73
74impl Sandbox {
75    pub fn tombstone_deposit(&self) -> [u8; 32] {
76        [1; 32]
77    }
78
79    pub fn rent_allowance(&self) -> [u8; 32] {
80        self.ext.rent_allowance
81    }
82
83    pub fn set_rent_allowance(&mut self, rent_allowence: [u8; 32]) {
84        self.ext.rent_allowance = rent_allowence;
85    }
86
87    pub fn rent_params(&self) -> Vec<u8> {
88        self.ext.rent_params.encode()
89    }
90}