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
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
use core::fmt;
use schemars::JsonSchema;
use serde::{de::DeserializeOwned, Deserialize, Serialize};

use cosmwasm_std::{
    to_binary, Coin, HumanAddr, Querier, QueryRequest, StdError, StdResult, Uint128, WasmQuery,
};

use secret_toolkit_utils::space_pad;

/// TokenInfo response
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)]
pub struct TokenInfo {
    pub name: String,
    pub symbol: String,
    pub decimals: u8,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub total_supply: Option<Uint128>,
}

/// TokenConfig response
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)]
pub struct TokenConfig {
    pub public_total_supply: bool,
    pub deposit_enabled: bool,
    pub redeem_enabled: bool,
    pub mint_enabled: bool,
    pub burn_enabled: bool,
}

/// Contract status
#[derive(Serialize, Deserialize, Clone, PartialEq, JsonSchema, Debug)]
pub enum ContractStatusLevel {
    NormalRun,
    StopAllButRedeems,
    StopAll,
}

/// ContractStatus Response
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)]
pub struct ContractStatus {
    pub status: ContractStatusLevel,
}

/// ExchangeRate response
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)]
pub struct ExchangeRate {
    pub rate: Uint128,
    pub denom: String,
}

/// Allowance response
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)]
pub struct Allowance {
    pub spender: HumanAddr,
    pub owner: HumanAddr,
    pub allowance: Uint128,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub expiration: Option<u64>,
}

/// Balance response
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)]
pub struct Balance {
    pub amount: Uint128,
}

/// Transaction data
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)]
pub struct Tx {
    pub id: u64,
    pub from: HumanAddr,
    pub sender: HumanAddr,
    pub receiver: HumanAddr,
    pub coins: Coin,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub memo: Option<String>,
    // The block time and block height are optional so that the JSON schema
    // reflects that some SNIP-20 contracts may not include this info.
    pub block_time: Option<u64>,
    pub block_height: Option<u64>,
}

/// TransferHistory response
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)]
pub struct TransferHistory {
    pub total: Option<u64>,
    pub txs: Vec<Tx>,
}

/// Types of transactions for RichTx
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum TxAction {
    Transfer {
        from: HumanAddr,
        sender: HumanAddr,
        recipient: HumanAddr,
    },
    Mint {
        minter: HumanAddr,
        recipient: HumanAddr,
    },
    Burn {
        burner: HumanAddr,
        owner: HumanAddr,
    },
    Deposit {},
    Redeem {},
}

/// Rich transaction data used for TransactionHistory
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)]
pub struct RichTx {
    pub id: u64,
    pub action: TxAction,
    pub coins: Coin,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub memo: Option<String>,
    pub block_time: u64,
    pub block_height: u64,
}

/// TransactionHistory response
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)]
pub struct TransactionHistory {
    pub total: Option<u64>,
    pub txs: Vec<RichTx>,
}

/// Minters response
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)]
pub struct Minters {
    pub minters: Vec<HumanAddr>,
}

/// SNIP20 queries
#[derive(Serialize, Clone, Debug, Eq, PartialEq)]
#[serde(rename_all = "snake_case")]
pub enum QueryMsg {
    TokenInfo {},
    TokenConfig {},
    ContractStatus {},
    ExchangeRate {},
    Allowance {
        owner: HumanAddr,
        spender: HumanAddr,
        key: String,
    },
    Balance {
        address: HumanAddr,
        key: String,
    },
    TransferHistory {
        address: HumanAddr,
        key: String,
        page: Option<u32>,
        page_size: u32,
    },
    TransactionHistory {
        address: HumanAddr,
        key: String,
        page: Option<u32>,
        page_size: u32,
    },
    Minters {},
}

impl fmt::Display for QueryMsg {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            QueryMsg::TokenInfo { .. } => write!(f, "TokenInfo"),
            QueryMsg::TokenConfig { .. } => write!(f, "TokenConfig"),
            QueryMsg::ContractStatus { .. } => write!(f, "ContractStatus"),
            QueryMsg::ExchangeRate { .. } => write!(f, "ExchangeRate"),
            QueryMsg::Allowance { .. } => write!(f, "Allowance"),
            QueryMsg::Balance { .. } => write!(f, "Balance"),
            QueryMsg::TransferHistory { .. } => write!(f, "TransferHistory"),
            QueryMsg::TransactionHistory { .. } => write!(f, "TransactionHistory"),
            QueryMsg::Minters { .. } => write!(f, "Minters"),
        }
    }
}

impl QueryMsg {
    /// Returns a StdResult<T>, where T is the "Response" type that wraps the query answer
    ///
    /// # Arguments
    ///
    /// * `querier` - a reference to the Querier dependency of the querying contract
    /// * `block_size` - pad the message to blocks of this size
    /// * `callback_code_hash` - String holding the code hash of the contract being queried
    /// * `contract_addr` - address of the contract being queried
    pub fn query<Q: Querier, T: DeserializeOwned>(
        &self,
        querier: &Q,
        mut block_size: usize,
        callback_code_hash: String,
        contract_addr: HumanAddr,
    ) -> StdResult<T> {
        // can not have block size of 0
        if block_size == 0 {
            block_size = 1;
        }
        let mut msg = to_binary(self)?;
        space_pad(&mut msg.0, block_size);
        querier
            .query(&QueryRequest::Wasm(WasmQuery::Smart {
                contract_addr,
                callback_code_hash,
                msg,
            }))
            .map_err(|err| {
                StdError::generic_err(format!("Error performing {} query: {}", self, err))
            })
    }
}

/// enum used to screen for a ViewingKeyError response from an authenticated query
#[derive(Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum AuthenticatedQueryResponse {
    Allowance {
        spender: HumanAddr,
        owner: HumanAddr,
        allowance: Uint128,
        expiration: Option<u64>,
    },
    Balance {
        amount: Uint128,
    },
    TransferHistory {
        txs: Vec<Tx>,
        total: Option<u64>,
    },
    TransactionHistory {
        txs: Vec<RichTx>,
        total: Option<u64>,
    },
    ViewingKeyError {
        msg: String,
    },
}
/// wrapper to deserialize TokenInfo response
#[derive(Deserialize)]
pub struct TokenInfoResponse {
    pub token_info: TokenInfo,
}

/// wrapper to deserialize TokenConfig response
#[derive(Deserialize)]
pub struct TokenConfigResponse {
    pub token_config: TokenConfig,
}

/// wrapper to deserialize ContractStatus response
#[derive(Deserialize)]
pub struct ContractStatusResponse {
    pub contract_status: ContractStatus,
}

/// wrapper to deserialize ExchangeRate response
#[derive(Deserialize)]
pub struct ExchangeRateResponse {
    pub exchange_rate: ExchangeRate,
}

/// wrapper to deserialize Minters response
#[derive(Deserialize)]
pub struct MintersResponse {
    pub minters: Minters,
}

/// Returns a StdResult<TokenInfo> from performing TokenInfo query
///
/// # Arguments
///
/// * `querier` - a reference to the Querier dependency of the querying contract
/// * `block_size` - pad the message to blocks of this size
/// * `callback_code_hash` - String holding the code hash of the contract being queried
/// * `contract_addr` - address of the contract being queried
pub fn token_info_query<Q: Querier>(
    querier: &Q,
    block_size: usize,
    callback_code_hash: String,
    contract_addr: HumanAddr,
) -> StdResult<TokenInfo> {
    let answer: TokenInfoResponse =
        QueryMsg::TokenInfo {}.query(querier, block_size, callback_code_hash, contract_addr)?;
    Ok(answer.token_info)
}

/// Returns a StdResult<TokenConfig> from performing TokenConfig query
///
/// # Arguments
///
/// * `querier` - a reference to the Querier dependency of the querying contract
/// * `block_size` - pad the message to blocks of this size
/// * `callback_code_hash` - String holding the code hash of the contract being queried
/// * `contract_addr` - address of the contract being queried
pub fn token_config_query<Q: Querier>(
    querier: &Q,
    block_size: usize,
    callback_code_hash: String,
    contract_addr: HumanAddr,
) -> StdResult<TokenConfig> {
    let answer: TokenConfigResponse =
        QueryMsg::TokenConfig {}.query(querier, block_size, callback_code_hash, contract_addr)?;
    Ok(answer.token_config)
}

/// Returns a StdResult<ContractStatus> from performing ContractStatus query
///
/// # Arguments
///
/// * `querier` - a reference to the Querier dependency of the querying contract
/// * `block_size` - pad the message to blocks of this size
/// * `callback_code_hash` - String holding the code hash of the contract being queried
/// * `contract_addr` - address of the contract being queried
pub fn contract_status_query<Q: Querier>(
    querier: &Q,
    block_size: usize,
    callback_code_hash: String,
    contract_addr: HumanAddr,
) -> StdResult<ContractStatus> {
    let answer: ContractStatusResponse = QueryMsg::ContractStatus {}.query(
        querier,
        block_size,
        callback_code_hash,
        contract_addr,
    )?;
    Ok(answer.contract_status)
}

/// Returns a StdResult<ExchangeRate> from performing ExchangeRate query
///
/// # Arguments
///
/// * `querier` - a reference to the Querier dependency of the querying contract
/// * `block_size` - pad the message to blocks of this size
/// * `callback_code_hash` - String holding the code hash of the contract being queried
/// * `contract_addr` - address of the contract being queried
pub fn exchange_rate_query<Q: Querier>(
    querier: &Q,
    block_size: usize,
    callback_code_hash: String,
    contract_addr: HumanAddr,
) -> StdResult<ExchangeRate> {
    let answer: ExchangeRateResponse =
        QueryMsg::ExchangeRate {}.query(querier, block_size, callback_code_hash, contract_addr)?;
    Ok(answer.exchange_rate)
}

/// Returns a StdResult<Allowance> from performing Allowance query
///
/// # Arguments
///
/// * `querier` - a reference to the Querier dependency of the querying contract
/// * `owner` - the address that owns the tokens
/// * `spender` - the address allowed to send/burn tokens
/// * `key` - String holding the authentication key needed to view the allowance
/// * `block_size` - pad the message to blocks of this size
/// * `callback_code_hash` - String holding the code hash of the contract being queried
/// * `contract_addr` - address of the contract being queried
#[allow(clippy::too_many_arguments)]
pub fn allowance_query<Q: Querier>(
    querier: &Q,
    owner: HumanAddr,
    spender: HumanAddr,
    key: String,
    block_size: usize,
    callback_code_hash: String,
    contract_addr: HumanAddr,
) -> StdResult<Allowance> {
    let answer: AuthenticatedQueryResponse = QueryMsg::Allowance {
        owner,
        spender,
        key,
    }
    .query(querier, block_size, callback_code_hash, contract_addr)?;
    match answer {
        AuthenticatedQueryResponse::Allowance {
            spender,
            owner,
            allowance,
            expiration,
        } => Ok(Allowance {
            spender,
            owner,
            allowance,
            expiration,
        }),
        AuthenticatedQueryResponse::ViewingKeyError { .. } => Err(StdError::unauthorized()),
        _ => Err(StdError::generic_err("Invalid Allowance query response")),
    }
}

/// Returns a StdResult<Balance> from performing Balance query
///
/// # Arguments
///
/// * `querier` - a reference to the Querier dependency of the querying contract
/// * `address` - the address whose balance should be displayed
/// * `key` - String holding the authentication key needed to view the balance
/// * `block_size` - pad the message to blocks of this size
/// * `callback_code_hash` - String holding the code hash of the contract being queried
/// * `contract_addr` - address of the contract being queried
pub fn balance_query<Q: Querier>(
    querier: &Q,
    address: HumanAddr,
    key: String,
    block_size: usize,
    callback_code_hash: String,
    contract_addr: HumanAddr,
) -> StdResult<Balance> {
    let answer: AuthenticatedQueryResponse = QueryMsg::Balance { address, key }.query(
        querier,
        block_size,
        callback_code_hash,
        contract_addr,
    )?;
    match answer {
        AuthenticatedQueryResponse::Balance { amount } => Ok(Balance { amount }),
        AuthenticatedQueryResponse::ViewingKeyError { .. } => Err(StdError::unauthorized()),
        _ => Err(StdError::generic_err("Invalid Balance query response")),
    }
}

/// Returns a StdResult<TransferHistory> from performing TransferHistory query
///
/// # Arguments
///
/// * `querier` - a reference to the Querier dependency of the querying contract
/// * `address` - the address whose transaction history should be displayed
/// * `key` - String holding the authentication key needed to view transactions
/// * `page` - Optional u32 representing the page number of transactions to display
/// * `page_size` - u32 number of transactions to return
/// * `block_size` - pad the message to blocks of this size
/// * `callback_code_hash` - String holding the code hash of the contract being queried
/// * `contract_addr` - address of the contract being queried
#[allow(clippy::too_many_arguments)]
pub fn transfer_history_query<Q: Querier>(
    querier: &Q,
    address: HumanAddr,
    key: String,
    page: Option<u32>,
    page_size: u32,
    block_size: usize,
    callback_code_hash: String,
    contract_addr: HumanAddr,
) -> StdResult<TransferHistory> {
    let answer: AuthenticatedQueryResponse = QueryMsg::TransferHistory {
        address,
        key,
        page,
        page_size,
    }
    .query(querier, block_size, callback_code_hash, contract_addr)?;
    match answer {
        AuthenticatedQueryResponse::TransferHistory { txs, total } => {
            Ok(TransferHistory { txs, total })
        }
        AuthenticatedQueryResponse::ViewingKeyError { .. } => Err(StdError::unauthorized()),
        _ => Err(StdError::generic_err(
            "Invalid TransferHistory query response",
        )),
    }
}

/// Returns a StdResult<TransactionHistory> from performing TransactionHistory query
///
/// # Arguments
///
/// * `querier` - a reference to the Querier dependency of the querying contract
/// * `address` - the address whose transaction history should be displayed
/// * `key` - String holding the authentication key needed to view transactions
/// * `page` - Optional u32 representing the page number of transactions to display
/// * `page_size` - u32 number of transactions to return
/// * `block_size` - pad the message to blocks of this size
/// * `callback_code_hash` - String holding the code hash of the contract being queried
/// * `contract_addr` - address of the contract being queried
#[allow(clippy::too_many_arguments)]
pub fn transaction_history_query<Q: Querier>(
    querier: &Q,
    address: HumanAddr,
    key: String,
    page: Option<u32>,
    page_size: u32,
    block_size: usize,
    callback_code_hash: String,
    contract_addr: HumanAddr,
) -> StdResult<TransactionHistory> {
    let answer: AuthenticatedQueryResponse = QueryMsg::TransactionHistory {
        address,
        key,
        page,
        page_size,
    }
    .query(querier, block_size, callback_code_hash, contract_addr)?;
    match answer {
        AuthenticatedQueryResponse::TransactionHistory { txs, total } => {
            Ok(TransactionHistory { txs, total })
        }
        AuthenticatedQueryResponse::ViewingKeyError { .. } => Err(StdError::unauthorized()),
        _ => Err(StdError::generic_err(
            "Invalid TransactionHistory query response",
        )),
    }
}

/// Returns a StdResult<Minters> from performing Minters query
///
/// # Arguments
///
/// * `querier` - a reference to the Querier dependency of the querying contract
/// * `block_size` - pad the message to blocks of this size
/// * `callback_code_hash` - String holding the code hash of the contract being queried
/// * `contract_addr` - address of the contract being queried
pub fn minters_query<Q: Querier>(
    querier: &Q,
    block_size: usize,
    callback_code_hash: String,
    contract_addr: HumanAddr,
) -> StdResult<Minters> {
    let answer: MintersResponse =
        QueryMsg::Minters {}.query(querier, block_size, callback_code_hash, contract_addr)?;
    Ok(answer.minters)
}