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
use std::{
    sync::{Arc, Mutex},
    time::SystemTime,
};

use casper_engine_test_support::{InMemoryWasmTestBuilder, DEFAULT_RUN_GENESIS_REQUEST};
use casper_types::{
    account::AccountHash, bytesrepr::FromBytes, CLTyped, Key, PublicKey, RuntimeArgs, SecretKey,
};

use crate::utils::{deploy, fund_account, query, query_dictionary_item, DeploySource};

pub fn now() -> u64 {
    SystemTime::now()
        .duration_since(SystemTime::UNIX_EPOCH)
        .unwrap()
        .as_millis() as u64
}

#[derive(Clone)]
pub struct TestEnv {
    state: Arc<Mutex<TestEnvState>>,
}

impl TestEnv {
    pub fn new() -> TestEnv {
        TestEnv {
            state: Arc::new(Mutex::new(TestEnvState::new())),
        }
    }

    pub fn run(
        &self,
        sender: AccountHash,
        session_code: DeploySource,
        session_args: RuntimeArgs,
        time: u64,
    ) {
        deploy(
            &mut self.state.lock().unwrap().builder,
            &sender,
            &session_code,
            session_args,
            true,
            Some(time),
        )
    }

    pub fn next_user(&self) -> AccountHash {
        self.state.lock().unwrap().next_user()
    }

    pub fn query<T: CLTyped + FromBytes>(
        &self,
        contract_hash: [u8; 32],
        dict_name: &str,
        key: String,
    ) -> T {
        self.state
            .lock()
            .unwrap()
            .query(contract_hash, dict_name.to_string(), key)
    }

    pub fn query_dictionary<T: CLTyped + FromBytes>(
        &self,
        contract_hash: [u8; 32],
        dict_name: &str,
        key: String,
    ) -> Option<T> {
        self.state
            .lock()
            .unwrap()
            .query_dictionary(contract_hash, dict_name.to_string(), key)
    }

    pub fn query_account_named_key<T: CLTyped + FromBytes>(
        &self,
        account: AccountHash,
        path: &[String],
    ) -> T {
        self.state
            .lock()
            .unwrap()
            .query_account_named_key(account, path)
    }
}

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

struct TestEnvState {
    builder: InMemoryWasmTestBuilder,
    accounts: Vec<AccountHash>,
}

impl TestEnvState {
    pub fn new() -> TestEnvState {
        let mut builder = InMemoryWasmTestBuilder::default();
        builder.run_genesis(&DEFAULT_RUN_GENESIS_REQUEST).commit();
        let mut accounts = Vec::new();
        for i in 0..10u8 {
            let secret_key: SecretKey = SecretKey::ed25519_from_bytes([i; 32]).unwrap();
            let public_key: PublicKey = (&secret_key).into();
            let account_hash = AccountHash::from(&public_key);
            accounts.push(account_hash);
            builder
                .exec(fund_account(&account_hash))
                .expect_success()
                .commit();
        }

        TestEnvState { builder, accounts }
    }

    pub fn _new_with_users(user_secrets: &[[u8; 32]]) -> TestEnvState {
        let mut builder = InMemoryWasmTestBuilder::default();
        builder.run_genesis(&DEFAULT_RUN_GENESIS_REQUEST).commit();

        let mut accounts = Vec::new();
        for user_secret in user_secrets {
            let secret_key: SecretKey = SecretKey::ed25519_from_bytes(user_secret).unwrap();
            let public_key: PublicKey = (&secret_key).into();
            let account_hash = AccountHash::from(&public_key);
            accounts.push(account_hash);
            builder
                .exec(fund_account(&account_hash))
                .expect_success()
                .commit();
        }

        TestEnvState { builder, accounts }
    }

    pub fn next_user(&mut self) -> AccountHash {
        self.accounts.pop().unwrap()
    }

    pub fn _run(
        &mut self,
        sender: AccountHash,
        session_code: DeploySource,
        session_args: RuntimeArgs,
    ) {
        deploy(
            &mut self.builder,
            &sender,
            &session_code,
            session_args,
            true,
            None,
        )
    }

    pub fn query<T: CLTyped + FromBytes>(
        &self,
        contract_hash: [u8; 32],
        dict_name: String,
        dictionary_item_key: String,
    ) -> T {
        match query_dictionary_item(
            &self.builder,
            Key::Hash(contract_hash),
            Some(dict_name),
            dictionary_item_key,
        ) {
            Ok(value) => value
                .as_cl_value()
                .expect("should be cl value.")
                .clone()
                .into_t()
                .expect("Wrong type in query result."),
            Err(e) => {
                panic!("{}", e);
            }
        }
    }

    pub fn query_dictionary<T: CLTyped + FromBytes>(
        &self,
        contract_hash: [u8; 32],
        dict_name: String,
        dictionary_item_key: String,
    ) -> Option<T> {
        match query_dictionary_item(
            &self.builder,
            Key::Hash(contract_hash),
            Some(dict_name),
            dictionary_item_key,
        ) {
            Ok(value) => value
                .as_cl_value()
                .expect("should be cl value.")
                .clone()
                .into_t()
                .expect("Wrong type in query result."),
            Err(e) => {
                println!("{}", e);
                None
            }
        }
    }

    pub fn query_account_named_key<T: CLTyped + FromBytes>(
        &self,
        account: AccountHash,
        path: &[String],
    ) -> T {
        query(&self.builder, Key::Account(account), path)
    }
}