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
#[macro_use]
extern crate lazy_static;

use core::convert::TryInto;
use serde::{Serialize, Deserialize};
use serde::de::DeserializeOwned;
use std::collections::HashMap;
use std::sync::Mutex;

#[derive(Deserialize)]
pub struct CallParams {
    pub address: [u8; 20],
    pub balance: f64,
    pub caller: [u8; 20],
    pub origin: [u8; 20],
    pub spice_limit: f64,
    pub spice_remaining: f64,
    pub args: HashMap<String, Vec<u8>>
}

extern "C" {
    pub fn revert() -> !;
}

lazy_static! {
    pub static ref MSG: CallParams = unsafe {
        let env_len = 128 as *const u32;
        let env_serd = std::slice::from_raw_parts(132 as *const u8, *env_len as usize);
        let env_de: CallParams = serde_cbor::from_reader(&env_serd[..]).unwrap();
        env_de
    };
    static ref STORAGE_MAP: Mutex<HashMap<String, Vec<u8>>> = Mutex::new(HashMap::new());
    pub static ref STORAGE: Mutex<Vec<u8>> = Mutex::new(Vec::new());
}

/*#[panic_handler]
  fn panic(info: &core::panic::PanicInfo) -> ! {
  unsafe { revert(); }
  }*/
pub fn get_arg<T: DeserializeOwned>(name: &str) -> T {
    let arg_ser = MSG.args.get(name).unwrap();
    serde_cbor::from_slice(&arg_ser).unwrap()
}

pub fn sstore<T: Serialize>(key: &str, val: T) {
    let serialized = serde_cbor::ser::to_vec_packed(&val).unwrap();
    STORAGE_MAP.lock().unwrap().insert(key.to_string(), serialized);
}

pub fn sload<T: DeserializeOwned>(key: String) -> T {
    serde_cbor::from_slice(STORAGE_MAP.lock().unwrap().get(&key).unwrap()).unwrap()
}

#[no_mangle]
pub unsafe fn _get_storage_ptr() -> *const u8 {
    let mut locked_storage = STORAGE.lock().unwrap();
    let mut serialized_storage = serde_cbor::ser::to_vec_packed(
        &(*STORAGE_MAP)).unwrap();
    locked_storage.append(&mut serialized_storage);
    &*locked_storage.as_ptr()
}

#[no_mangle]
pub unsafe fn _get_storage_len() -> i32 {
    let ret: usize = STORAGE.lock().unwrap().len();
    ret.try_into().unwrap()
}

pub type Address = [u8; 20];