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
use std::cell::UnsafeCell;

use crate::{
    ext,
    types::{Address, H256, U256},
};

/// A type that can be stored in blockchain storage.
pub trait Storage = serde::Serialize + serde::de::DeserializeOwned;

pub trait Service {
    /// Builds a service struct from items in Storage.
    fn coalesce() -> Self;

    /// Stores a service struct to Storage.
    fn sunder(c: Self);
}

pub trait Event {
    /// A struct implementing the builder pattern for setting topics.
    ///
    /// For example,
    /// ```
    /// #[derive(Event)]
    /// struct MyEvent {
    ///    #[indexed]
    ///    my_topic: U256
    ///    #[indexed]
    ///    my_other_topic: U256,
    /// }
    ///
    /// let topics: Vec<H256> = MyTopics::Topics::default()
    ///    .set_my_other_topic(&U256::from(42))
    ///    .hash();
    /// // topics = vec![0, keccak256(abi_encode(my_other_topic))]
    /// ```
    type Topics;

    /// Emits an event tagged with the (keccak) hashed function name and topics.
    fn emit(&self);
}

/// The context of the current RPC.
// `Option` values are set by the user. `None` when populated by runting (during call/deploy).
#[derive(Default, Copy, Clone, Debug)]
pub struct Context {
    #[doc(hidden)]
    pub sender: Option<Address>,

    #[doc(hidden)]
    pub value: Option<U256>,

    #[doc(hidden)]
    pub gas: Option<U256>,

    #[doc(hidden)]
    pub call_type: CallType,
}

#[derive(Copy, Clone, Debug)]
pub enum CallType {
    Default,
    Delegated,
    Constant,
}

impl Default for CallType {
    fn default() -> Self {
        CallType::Default
    }
}

impl Context {
    pub fn delegated() -> Self {
        Self {
            call_type: CallType::Delegated,
            ..Default::default()
        }
    }

    /// Sets the sender of the RPC receiving this `Context` as an argument.
    /// Has no effect when called inside of a service.
    pub fn with_sender(mut self, sender: Address) -> Self {
        self.sender = Some(sender);
        self
    }

    /// Amends a Context with the value that should be transferred to the callee.
    pub fn with_value<V: Into<U256>>(mut self, value: V) -> Self {
        self.value = Some(value.into());
        self
    }

    /// Sets the amount of computation resources available to the callee.
    /// Payed for by the `payer` of the `Context`.
    pub fn with_gas<V: Into<U256>>(mut self, gas: V) -> Self {
        self.gas = Some(gas.into());
        self
    }

    /// Returns the `Address` of the sender of the current RPC.
    pub fn sender(&self) -> Address {
        self.sender.unwrap_or_else(ext::sender)
    }

    /// Returns the `Address` of the currently executing service.
    /// Panics if not currently in a service.
    pub fn address(&self) -> Address {
        ext::address()
    }

    /// Returns the value with which this `Context` was created.
    pub fn value(&self) -> U256 {
        self.value.unwrap_or_else(ext::value)
    }

    /// Returns the remaining gas allocated to this transaction.
    pub fn gas_left(&self) -> U256 {
        ext::gas_left()
    }
}

/// Container for service state that is lazily loaded from storage.
/// Currently can only be used as a top-level type (e.g., `Lazy<Vec<T>>`, not `Vec<Lazy<T>>`).
/// where the entire Vec will be lazily instantiated (as opposed to each individual element).
///
/// ## Example
///
/// ```
/// mantle::service! {
/// #[derive(Service)]
/// pub struct SinglePlayerRPG {
///     player_name: String,
///     inventory: Vec<InventoryItem>,
///     bank: Lazy<HashMap<InventoryItem, u64>>,
/// }
///
/// impl SinglePlayerRPG {
///    pub fn new(_ctx: &Context, player_name: String) -> Self {
///        Self {
///           player_name,
///           inventory: Vec::new(),
///           bank: lazy!(HashMap::new()),
///        }
///    }
///
///    pub fn get_inventory(&self, _ctx: &Context) -> Vec<InventoryItem> {
///        self.inventory.clone()
///    }
///
///    pub fn get_bank(&self, _ctx: &Context) -> Vec<InventoryItem> {
///        self.bank.get().clone()
///    }
///
///    pub fn move_item_to_inventory(&mut self, _ctx: &Context, item: InventoryItem) {
///        self.bank.get_mut().entry(&item).and_modify(|count| {
///            if count > 0 {
///                 self.inventory.push(item);
///                 *count -= 1
///            }
///        });
///    }
/// }
/// }
/// ```
#[derive(Debug)]
pub struct Lazy<T: Storage> {
    key: H256,
    val: UnsafeCell<Option<T>>,
}

impl<T: Storage> Lazy<T> {
    /// Creates a Lazy value with initial contents.
    /// This function is for internal use. Clients should use the `lazy!` macro.
    #[doc(hidden)]
    pub fn _new(key: H256, val: T) -> Self {
        Self {
            key,
            val: UnsafeCell::new(Some(val)),
        }
    }

    /// Creates an empty Lazy. This function is for internal use.
    #[doc(hidden)]
    pub fn _uninitialized(key: H256) -> Self {
        Self {
            key,
            val: UnsafeCell::new(None),
        }
    }

    fn ensure_val(&self) -> &mut T {
        let val = unsafe { &mut *self.val.get() };
        if val.is_none() {
            val.replace(serde_cbor::from_slice(&ext::get_bytes(&self.key).unwrap()).unwrap());
        }
        val.as_mut().unwrap()
    }

    /// Returns a reference to the value loaded from Storage.
    pub fn get(&self) -> &T {
        self.ensure_val()
    }

    /// Returns a mutable reference to the value loaded from Storage.
    pub fn get_mut(&mut self) -> &mut T {
        self.ensure_val()
    }

    pub fn is_initialized(&self) -> bool {
        unsafe { &*self.val.get() }.is_some()
    }
}

/// A marker for inserting a `Lazy::new`.
/// Works in tandem with `mantle_macros::LazyInserter`.
///
/// ```
/// fn new(ctx: &Context) -> Self {
///    Self { the_field: lazy!(the_val) }
/// }
/// ```
/// expands to
/// ```
/// fn new(ctx: &Context) -> Self {
///    Self {
///        the_field: Lazy::new(H256::from(keccak256("the_field".as_bytes())), the_val)
///    }
/// }
/// ```
#[macro_export]
macro_rules! lazy {
    ($val:expr) => {
        compile_error!("`lazy!` used outside of struct expr.")
    };
}