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
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
use crate::{prelude::{*, cosmwasm_storage::{PrefixedStorage, ReadonlyPrefixedStorage}}};
use secret_toolkit::storage::{TypedStore, TypedStoreMut};
use std::any::type_name;
use std::convert::TryFrom;
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use serde::de::DeserializeOwned;
use super::msg::{status_level_to_u8, u8_to_status_level, ContractStatusLevel};
pub const PREFIX_TXS: &[u8] = b"YteGsgSZyO";
pub const KEY_CONSTANTS: &[u8] = b"N3QP0mNoPG";
pub const KEY_TOTAL_SUPPLY: &[u8] = b"bx98UUOWYa";
pub const KEY_CONTRACT_STATUS: &[u8] = b"EhYS9rzai1";
pub const KEY_MINTERS: &[u8] = b"wpitCjS7wB";
pub const KEY_TX_COUNT: &[u8] = b"n8BHFWp7eT";
pub const KEY_SELF: &[u8] = b"Qdfh7Fshg2";
pub const PREFIX_CONFIG: &[u8] = b"YywNU6aiTV";
pub const PREFIX_BALANCES: &[u8] = b"DyCKbmlEL8";
pub const PREFIX_ALLOWANCES: &[u8] = b"eXDXajOxRG";
pub const PREFIX_VIEW_KEY: &[u8] = b"MLRCoHCV8x";
pub const PREFIX_RECEIVERS: &[u8] = b"V1SJqXtGju";
#[derive(Serialize, Debug, Deserialize, Clone, PartialEq, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct Constants {
pub name: String,
pub admin: HumanAddr,
pub symbol: String,
pub decimals: u8,
pub prng_seed: Vec<u8>,
pub total_supply_is_public: bool,
pub deposit_is_enabled: bool,
pub redeem_is_enabled: bool,
pub mint_is_enabled: bool,
pub burn_is_enabled: bool,
}
pub struct ReadonlyConfig<'a, S: ReadonlyStorage> {
storage: ReadonlyPrefixedStorage<'a, S>,
}
impl<'a, S: ReadonlyStorage> ReadonlyConfig<'a, S> {
pub fn from_storage(storage: &'a S) -> Self {
Self {
storage: ReadonlyPrefixedStorage::new(PREFIX_CONFIG, storage),
}
}
fn as_readonly(&self) -> ReadonlyConfigImpl<ReadonlyPrefixedStorage<S>> {
ReadonlyConfigImpl(&self.storage)
}
pub fn constants(&self) -> StdResult<Constants> {
self.as_readonly().constants()
}
pub fn self_address(&self) -> StdResult<HumanAddr> {
self.as_readonly().self_address()
}
pub fn total_supply(&self) -> u128 {
self.as_readonly().total_supply()
}
pub fn contract_status(&self) -> ContractStatusLevel {
self.as_readonly().contract_status()
}
pub fn minters(&self) -> Vec<HumanAddr> {
self.as_readonly().minters()
}
pub fn tx_count(&self) -> u64 {
self.as_readonly().tx_count()
}
}
fn ser_bin_data<T: Serialize>(obj: &T) -> StdResult<Vec<u8>> {
bincode2::serialize(&obj).map_err(|e| StdError::serialize_err(type_name::<T>(), e))
}
fn deser_bin_data<T: DeserializeOwned>(data: &[u8]) -> StdResult<T> {
bincode2::deserialize::<T>(&data).map_err(|e| StdError::serialize_err(type_name::<T>(), e))
}
fn set_bin_data<T: Serialize, S: Storage>(storage: &mut S, key: &[u8], data: &T) -> StdResult<()> {
let bin_data = ser_bin_data(data)?;
storage.set(key, &bin_data);
Ok(())
}
fn get_bin_data<T: DeserializeOwned, S: ReadonlyStorage>(storage: &S, key: &[u8]) -> StdResult<T> {
let bin_data = storage.get(key);
match bin_data {
None => Err(StdError::not_found("Key not found in storage")),
Some(bin_data) => Ok(deser_bin_data(&bin_data)?),
}
}
pub struct Config<'a, S: Storage> {
storage: PrefixedStorage<'a, S>,
}
impl<'a, S: Storage> Config<'a, S> {
pub fn from_storage(storage: &'a mut S) -> Self {
Self {
storage: PrefixedStorage::new(PREFIX_CONFIG, storage),
}
}
fn as_readonly(&self) -> ReadonlyConfigImpl<PrefixedStorage<S>> {
ReadonlyConfigImpl(&self.storage)
}
pub fn constants(&self) -> StdResult<Constants> {
self.as_readonly().constants()
}
pub fn set_constants(&mut self, constants: &Constants) -> StdResult<()> {
set_bin_data(&mut self.storage, KEY_CONSTANTS, constants)
}
pub fn set_self_address(&mut self, address: &HumanAddr) -> StdResult<()> {
set_bin_data(&mut self.storage, KEY_SELF, address)
}
pub fn total_supply(&self) -> u128 {
self.as_readonly().total_supply()
}
pub fn set_total_supply(&mut self, supply: u128) {
self.storage.set(KEY_TOTAL_SUPPLY, &supply.to_be_bytes());
}
pub fn contract_status(&self) -> ContractStatusLevel {
self.as_readonly().contract_status()
}
pub fn set_contract_status(&mut self, status: ContractStatusLevel) {
let status_u8 = status_level_to_u8(status);
self.storage
.set(KEY_CONTRACT_STATUS, &status_u8.to_be_bytes());
}
pub fn set_minters(&mut self, minters_to_set: Vec<HumanAddr>) -> StdResult<()> {
set_bin_data(&mut self.storage, KEY_MINTERS, &minters_to_set)
}
pub fn add_minters(&mut self, minters_to_add: Vec<HumanAddr>) -> StdResult<()> {
let mut minters = self.minters();
minters.extend(minters_to_add);
self.set_minters(minters)
}
pub fn remove_minters(&mut self, minters_to_remove: Vec<HumanAddr>) -> StdResult<()> {
let mut minters = self.minters();
for minter in minters_to_remove {
minters.retain(|x| x != &minter);
}
self.set_minters(minters)
}
pub fn minters(&mut self) -> Vec<HumanAddr> {
self.as_readonly().minters()
}
pub fn tx_count(&self) -> u64 {
self.as_readonly().tx_count()
}
pub fn set_tx_count(&mut self, count: u64) -> StdResult<()> {
set_bin_data(&mut self.storage, KEY_TX_COUNT, &count)
}
}
struct ReadonlyConfigImpl<'a, S: ReadonlyStorage>(&'a S);
impl<'a, S: ReadonlyStorage> ReadonlyConfigImpl<'a, S> {
fn constants(&self) -> StdResult<Constants> {
let consts_bytes = self
.0
.get(KEY_CONSTANTS)
.ok_or_else(|| StdError::generic_err("no constants stored in configuration"))?;
bincode2::deserialize::<Constants>(&consts_bytes)
.map_err(|e| StdError::serialize_err(type_name::<Constants>(), e))
}
fn total_supply(&self) -> u128 {
let supply_bytes = self
.0
.get(KEY_TOTAL_SUPPLY)
.expect("no total supply stored in config");
slice_to_u128(&supply_bytes).unwrap()
}
fn self_address(&self) -> StdResult<HumanAddr> {
let bytes = self
.0
.get(KEY_SELF)
.ok_or_else(|| StdError::generic_err("no constants stored in configuration"))?;
bincode2::deserialize::<HumanAddr>(&bytes)
.map_err(|e| StdError::serialize_err(type_name::<HumanAddr>(), e))
}
fn contract_status(&self) -> ContractStatusLevel {
let supply_bytes = self
.0
.get(KEY_CONTRACT_STATUS)
.expect("no contract status stored in config");
let status = slice_to_u8(&supply_bytes).unwrap();
u8_to_status_level(status).unwrap()
}
fn minters(&self) -> Vec<HumanAddr> {
get_bin_data(self.0, KEY_MINTERS).unwrap()
}
pub fn tx_count(&self) -> u64 {
get_bin_data(self.0, KEY_TX_COUNT).unwrap_or_default()
}
}
pub struct ReadonlyBalances<'a, S: ReadonlyStorage> {
storage: ReadonlyPrefixedStorage<'a, S>,
}
impl<'a, S: ReadonlyStorage> ReadonlyBalances<'a, S> {
pub fn from_storage(storage: &'a S) -> Self {
Self {
storage: ReadonlyPrefixedStorage::new(PREFIX_BALANCES, storage),
}
}
fn as_readonly(&self) -> ReadonlyBalancesImpl<ReadonlyPrefixedStorage<S>> {
ReadonlyBalancesImpl(&self.storage)
}
pub fn account_amount(&self, account: &CanonicalAddr) -> u128 {
self.as_readonly().account_amount(account)
}
}
pub struct Balances<'a, S: Storage> {
storage: PrefixedStorage<'a, S>,
}
impl<'a, S: Storage> Balances<'a, S> {
pub fn from_storage(storage: &'a mut S) -> Self {
Self {
storage: PrefixedStorage::new(PREFIX_BALANCES, storage),
}
}
fn as_readonly(&self) -> ReadonlyBalancesImpl<PrefixedStorage<S>> {
ReadonlyBalancesImpl(&self.storage)
}
pub fn balance(&self, account: &CanonicalAddr) -> u128 {
self.as_readonly().account_amount(account)
}
pub fn set_account_balance(&mut self, account: &CanonicalAddr, amount: u128) {
self.storage.set(account.as_slice(), &amount.to_be_bytes())
}
}
struct ReadonlyBalancesImpl<'a, S: ReadonlyStorage>(&'a S);
impl<'a, S: ReadonlyStorage> ReadonlyBalancesImpl<'a, S> {
pub fn account_amount(&self, account: &CanonicalAddr) -> u128 {
let account_bytes = account.as_slice();
let result = self.0.get(account_bytes);
match result {
Some(balance_bytes) => slice_to_u128(&balance_bytes).unwrap(),
None => 0,
}
}
}
#[derive(Serialize, Debug, Deserialize, Clone, PartialEq, Default, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct Allowance {
pub amount: u128,
pub expiration: Option<u64>,
}
impl Allowance {
pub fn is_expired_at(&self, block: &BlockInfo) -> bool {
match self.expiration {
Some(time) => block.time >= time,
None => false,
}
}
}
pub fn read_allowance<S: Storage>(
store: &S,
owner: &CanonicalAddr,
spender: &CanonicalAddr,
) -> StdResult<Allowance> {
let owner_store =
ReadonlyPrefixedStorage::multilevel(&[PREFIX_ALLOWANCES, owner.as_slice()], store);
let owner_store = TypedStore::attach(&owner_store);
let allowance = owner_store.may_load(spender.as_slice());
allowance.map(Option::unwrap_or_default)
}
pub fn write_allowance<S: Storage>(
store: &mut S,
owner: &CanonicalAddr,
spender: &CanonicalAddr,
allowance: &Allowance,
) -> StdResult<()> {
let mut owner_store =
PrefixedStorage::multilevel(&[PREFIX_ALLOWANCES, owner.as_slice()], store);
let mut owner_store = TypedStoreMut::attach(&mut owner_store);
owner_store.store(spender.as_slice(), allowance)
}
pub fn write_viewing_key<S: Storage>(store: &mut S, owner: &CanonicalAddr, key: &ViewingKey) {
let mut balance_store = PrefixedStorage::new(PREFIX_VIEW_KEY, store);
balance_store.set(owner.as_slice(), &key.to_hashed());
}
pub fn read_viewing_key<S: Storage>(store: &S, owner: &CanonicalAddr) -> Option<Vec<u8>> {
let balance_store = ReadonlyPrefixedStorage::new(PREFIX_VIEW_KEY, store);
balance_store.get(owner.as_slice())
}
pub fn get_receiver_hash<S: ReadonlyStorage>(
store: &S,
account: &HumanAddr,
) -> Option<StdResult<String>> {
let store = ReadonlyPrefixedStorage::new(PREFIX_RECEIVERS, store);
store.get(account.as_str().as_bytes()).map(|data| {
String::from_utf8(data)
.map_err(|_err| StdError::invalid_utf8("stored code hash was not a valid String"))
})
}
pub fn set_receiver_hash<S: Storage>(store: &mut S, account: &HumanAddr, code_hash: String) {
let mut store = PrefixedStorage::new(PREFIX_RECEIVERS, store);
store.set(account.as_str().as_bytes(), code_hash.as_bytes());
}
fn slice_to_u128(data: &[u8]) -> StdResult<u128> {
match <[u8; 16]>::try_from(data) {
Ok(bytes) => Ok(u128::from_be_bytes(bytes)),
Err(_) => Err(StdError::generic_err(
"Corrupted data found. 16 byte expected.",
)),
}
}
fn slice_to_u8(data: &[u8]) -> StdResult<u8> {
if data.len() == 1 {
Ok(data[0])
} else {
Err(StdError::generic_err(
"Corrupted data found. 1 byte expected.",
))
}
}