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
extern crate ellipticoin;
extern crate wasm_rpc;
extern crate wasm_rpc_macros;

use std::cell::RefCell;
use std::collections::BTreeMap;
pub use wasm_rpc::{Bytes, FromBytes, ToBytes, Value};
pub use wasm_rpc_macros::export;

thread_local!(static SENDER: RefCell<Vec<u8>> = RefCell::new(Vec::new()));
thread_local!(static BLOCK_WINNER: RefCell<Vec<u8>> = RefCell::new(Vec::new()));
thread_local!(static BLOCK_NUMBER: RefCell<u64> = RefCell::new(0));
thread_local!(static MEMORY: RefCell<BTreeMap<Vec<u8>, Vec<u8>>> = RefCell::new(BTreeMap::new()));
thread_local!(static STORAGE: RefCell<BTreeMap<Vec<u8>, Vec<u8>>> = RefCell::new(BTreeMap::new()));

pub mod error;

pub fn set_sender(sender: Vec<u8>) {
    SENDER.with(|sender_cell| sender_cell.replace(sender));
}

pub fn set_block_winner(block_winner: Vec<u8>) {
    BLOCK_WINNER.with(|block_winner_cell| block_winner_cell.replace(block_winner));
}

pub fn set_block_number(block_number: u64) {
    BLOCK_NUMBER.with(|block_number_cell| block_number_cell.replace(block_number));
}

pub fn get_memory<K: ToBytes, V: FromBytes>(key: K) -> V {
    let v: Vec<u8> = MEMORY.with(|state_cell| {
        let state = state_cell.borrow_mut();
        match state.get::<Vec<u8>>(&key.to_bytes()) {
            Some(value) => value.to_vec(),
            None => vec![],
        }
    });
    FromBytes::from_bytes(v)
}

pub fn set_memory<K: ToBytes, V: ToBytes>(key: K, value: V) {
    MEMORY.with(|state_cell| {
        let mut state = state_cell.borrow_mut();
        state.insert(key.to_bytes(), value.to_bytes());
    })
}

pub fn get_storage<K: ToBytes, V: FromBytes>(key: K) -> V {
    let v: Vec<u8> = STORAGE.with(|state_cell| {
        let state = state_cell.borrow_mut();
        match state.get::<Vec<u8>>(&key.to_bytes()) {
            Some(value) => value.to_vec(),
            None => vec![],
        }
    });
    FromBytes::from_bytes(v)
}

pub fn set_storage<K: ToBytes, V: ToBytes>(key: K, value: V) {
    STORAGE.with(|state_cell| {
        let mut state = state_cell.borrow_mut();
        state.insert(key.to_bytes(), value.to_bytes());
    })
}

pub fn sender() -> Vec<u8> {
    SENDER.with(|sender_cell| sender_cell.borrow().to_vec())
}

pub fn block_winner() -> Vec<u8> {
    BLOCK_WINNER.with(|block_winner_cell| block_winner_cell.borrow().to_vec())
}

pub fn block_number() -> u64 {
    BLOCK_NUMBER.with(|block_number_cell| *block_number_cell.borrow())
}

pub fn call(
    _code: Vec<u8>,
    _method: String,
    _params: Vec<u8>,
    _storage_context: Vec<u8>,
) -> Vec<u8> {
    unreachable!();
}