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
use serde::{de::DeserializeOwned, Serialize};
use std::marker::PhantomData;
use std::ops::Deref;
use crate::addresses::{Addr, CanonicalAddr};
use crate::binary::Binary;
use crate::coins::Coin;
use crate::errors::{RecoverPubkeyError, StdError, StdResult, VerificationError};
#[cfg(feature = "iterator")]
use crate::iterator::{Order, Record};
#[cfg(feature = "cosmwasm_1_1")]
use crate::query::SupplyResponse;
use crate::query::{
AllBalanceResponse, BalanceResponse, BankQuery, CustomQuery, QueryRequest, WasmQuery,
};
#[cfg(feature = "staking")]
use crate::query::{
AllDelegationsResponse, AllValidatorsResponse, BondedDenomResponse, Delegation,
DelegationResponse, FullDelegation, StakingQuery, Validator, ValidatorResponse,
};
use crate::results::{ContractResult, Empty, SystemResult};
use crate::serde::{from_binary, to_binary, to_vec};
use crate::ContractInfoResponse;
pub trait Storage {
fn get(&self, key: &[u8]) -> Option<Vec<u8>>;
#[cfg(feature = "iterator")]
fn range<'a>(
&'a self,
start: Option<&[u8]>,
end: Option<&[u8]>,
order: Order,
) -> Box<dyn Iterator<Item = Record> + 'a>;
fn set(&mut self, key: &[u8], value: &[u8]);
fn remove(&mut self, key: &[u8]);
}
pub trait Api {
fn addr_validate(&self, human: &str) -> StdResult<Addr>;
fn addr_canonicalize(&self, human: &str) -> StdResult<CanonicalAddr>;
fn addr_humanize(&self, canonical: &CanonicalAddr) -> StdResult<Addr>;
fn secp256k1_verify(
&self,
message_hash: &[u8],
signature: &[u8],
public_key: &[u8],
) -> Result<bool, VerificationError>;
fn secp256k1_recover_pubkey(
&self,
message_hash: &[u8],
signature: &[u8],
recovery_param: u8,
) -> Result<Vec<u8>, RecoverPubkeyError>;
fn ed25519_verify(
&self,
message: &[u8],
signature: &[u8],
public_key: &[u8],
) -> Result<bool, VerificationError>;
fn ed25519_batch_verify(
&self,
messages: &[&[u8]],
signatures: &[&[u8]],
public_keys: &[&[u8]],
) -> Result<bool, VerificationError>;
fn debug(&self, message: &str);
}
pub type QuerierResult = SystemResult<ContractResult<Binary>>;
pub trait Querier {
fn raw_query(&self, bin_request: &[u8]) -> QuerierResult;
}
#[derive(Clone)]
pub struct QuerierWrapper<'a, C: CustomQuery = Empty> {
querier: &'a dyn Querier,
custom_query_type: PhantomData<C>,
}
impl<'a, C: CustomQuery> Copy for QuerierWrapper<'a, C> {}
impl<'a, C: CustomQuery> Deref for QuerierWrapper<'a, C> {
type Target = dyn Querier + 'a;
fn deref(&self) -> &Self::Target {
self.querier
}
}
impl<'a, C: CustomQuery> QuerierWrapper<'a, C> {
pub fn new(querier: &'a dyn Querier) -> Self {
QuerierWrapper {
querier,
custom_query_type: PhantomData,
}
}
pub fn query<U: DeserializeOwned>(&self, request: &QueryRequest<C>) -> StdResult<U> {
let raw = to_vec(request).map_err(|serialize_err| {
StdError::generic_err(format!("Serializing QueryRequest: {}", serialize_err))
})?;
match self.raw_query(&raw) {
SystemResult::Err(system_err) => Err(StdError::generic_err(format!(
"Querier system error: {}",
system_err
))),
SystemResult::Ok(ContractResult::Err(contract_err)) => Err(StdError::generic_err(
format!("Querier contract error: {}", contract_err),
)),
SystemResult::Ok(ContractResult::Ok(value)) => from_binary(&value),
}
}
#[cfg(feature = "cosmwasm_1_1")]
pub fn query_supply(&self, denom: impl Into<String>) -> StdResult<Coin> {
let request = BankQuery::Supply {
denom: denom.into(),
}
.into();
let res: SupplyResponse = self.query(&request)?;
Ok(res.amount)
}
pub fn query_balance(
&self,
address: impl Into<String>,
denom: impl Into<String>,
) -> StdResult<Coin> {
let request = BankQuery::Balance {
address: address.into(),
denom: denom.into(),
}
.into();
let res: BalanceResponse = self.query(&request)?;
Ok(res.amount)
}
pub fn query_all_balances(&self, address: impl Into<String>) -> StdResult<Vec<Coin>> {
let request = BankQuery::AllBalances {
address: address.into(),
}
.into();
let res: AllBalanceResponse = self.query(&request)?;
Ok(res.amount)
}
pub fn query_wasm_smart<T: DeserializeOwned>(
&self,
contract_addr: impl Into<String>,
msg: &impl Serialize,
) -> StdResult<T> {
let request = WasmQuery::Smart {
contract_addr: contract_addr.into(),
msg: to_binary(msg)?,
}
.into();
self.query(&request)
}
pub fn query_wasm_raw(
&self,
contract_addr: impl Into<String>,
key: impl Into<Binary>,
) -> StdResult<Option<Vec<u8>>> {
let request: QueryRequest<Empty> = WasmQuery::Raw {
contract_addr: contract_addr.into(),
key: key.into(),
}
.into();
let raw = to_vec(&request).map_err(|serialize_err| {
StdError::generic_err(format!("Serializing QueryRequest: {}", serialize_err))
})?;
match self.raw_query(&raw) {
SystemResult::Err(system_err) => Err(StdError::generic_err(format!(
"Querier system error: {}",
system_err
))),
SystemResult::Ok(ContractResult::Err(contract_err)) => Err(StdError::generic_err(
format!("Querier contract error: {}", contract_err),
)),
SystemResult::Ok(ContractResult::Ok(value)) => {
if value.is_empty() {
Ok(None)
} else {
Ok(Some(value.into()))
}
}
}
}
pub fn query_wasm_contract_info(
&self,
contract_addr: impl Into<String>,
) -> StdResult<ContractInfoResponse> {
let request = WasmQuery::ContractInfo {
contract_addr: contract_addr.into(),
}
.into();
self.query(&request)
}
#[cfg(feature = "staking")]
pub fn query_all_validators(&self) -> StdResult<Vec<Validator>> {
let request = StakingQuery::AllValidators {}.into();
let res: AllValidatorsResponse = self.query(&request)?;
Ok(res.validators)
}
#[cfg(feature = "staking")]
pub fn query_validator(&self, address: impl Into<String>) -> StdResult<Option<Validator>> {
let request = StakingQuery::Validator {
address: address.into(),
}
.into();
let res: ValidatorResponse = self.query(&request)?;
Ok(res.validator)
}
#[cfg(feature = "staking")]
pub fn query_bonded_denom(&self) -> StdResult<String> {
let request = StakingQuery::BondedDenom {}.into();
let res: BondedDenomResponse = self.query(&request)?;
Ok(res.denom)
}
#[cfg(feature = "staking")]
pub fn query_all_delegations(
&self,
delegator: impl Into<String>,
) -> StdResult<Vec<Delegation>> {
let request = StakingQuery::AllDelegations {
delegator: delegator.into(),
}
.into();
let res: AllDelegationsResponse = self.query(&request)?;
Ok(res.delegations)
}
#[cfg(feature = "staking")]
pub fn query_delegation(
&self,
delegator: impl Into<String>,
validator: impl Into<String>,
) -> StdResult<Option<FullDelegation>> {
let request = StakingQuery::Delegation {
delegator: delegator.into(),
validator: validator.into(),
}
.into();
let res: DelegationResponse = self.query(&request)?;
Ok(res.delegation)
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::testing::MockQuerier;
use crate::{coins, from_slice, Uint128};
fn demo_helper(_querier: &dyn Querier) -> u64 {
2
}
#[test]
fn use_querier_wrapper_as_querier() {
let querier: MockQuerier<Empty> = MockQuerier::new(&[]);
let wrapper = QuerierWrapper::<Empty>::new(&querier);
let res = demo_helper(&*wrapper);
assert_eq!(2, res);
let res = demo_helper(wrapper.deref());
assert_eq!(2, res);
}
#[test]
fn auto_deref_raw_query() {
let acct = String::from("foobar");
let querier: MockQuerier<Empty> = MockQuerier::new(&[(&acct, &coins(5, "BTC"))]);
let wrapper = QuerierWrapper::<Empty>::new(&querier);
let query = QueryRequest::<Empty>::Bank(BankQuery::Balance {
address: acct,
denom: "BTC".to_string(),
});
let raw = wrapper
.raw_query(&to_vec(&query).unwrap())
.unwrap()
.unwrap();
let balance: BalanceResponse = from_slice(&raw).unwrap();
assert_eq!(balance.amount.amount, Uint128::new(5));
}
#[cfg(feature = "cosmwasm_1_1")]
#[test]
fn bank_query_helpers_work() {
use crate::coin;
let querier: MockQuerier<Empty> = MockQuerier::new(&[
("foo", &[coin(123, "ELF"), coin(777, "FLY")]),
("bar", &[coin(321, "ELF")]),
]);
let wrapper = QuerierWrapper::<Empty>::new(&querier);
let supply = wrapper.query_supply("ELF").unwrap();
assert_eq!(supply, coin(444, "ELF"));
let balance = wrapper.query_balance("foo", "ELF").unwrap();
assert_eq!(balance, coin(123, "ELF"));
let all_balances = wrapper.query_all_balances("foo").unwrap();
assert_eq!(all_balances, vec![coin(123, "ELF"), coin(777, "FLY")]);
}
#[test]
fn contract_info() {
const ACCT: &str = "foobar";
fn mock_resp() -> ContractInfoResponse {
ContractInfoResponse {
code_id: 0,
creator: "creator".to_string(),
admin: None,
pinned: false,
ibc_port: None,
}
}
let mut querier: MockQuerier<Empty> = MockQuerier::new(&[(ACCT, &coins(5, "BTC"))]);
querier.update_wasm(|q| -> QuerierResult {
if q == &(WasmQuery::ContractInfo {
contract_addr: ACCT.to_string(),
}) {
SystemResult::Ok(ContractResult::Ok(to_binary(&mock_resp()).unwrap()))
} else {
SystemResult::Err(crate::SystemError::NoSuchContract {
addr: ACCT.to_string(),
})
}
});
let wrapper = QuerierWrapper::<Empty>::new(&querier);
let contract_info = wrapper.query_wasm_contract_info(ACCT).unwrap();
assert_eq!(contract_info, mock_resp());
}
#[test]
fn contract_info_err() {
const ACCT: &str = "foobar";
fn mock_resp() -> ContractInfoResponse {
ContractInfoResponse {
code_id: 0,
creator: "creator".to_string(),
admin: None,
pinned: false,
ibc_port: None,
}
}
let mut querier: MockQuerier<Empty> = MockQuerier::new(&[(ACCT, &coins(5, "BTC"))]);
querier.update_wasm(|q| -> QuerierResult {
if q == &(WasmQuery::ContractInfo {
contract_addr: ACCT.to_string(),
}) {
SystemResult::Ok(ContractResult::Ok(to_binary(&mock_resp()).unwrap()))
} else {
SystemResult::Err(crate::SystemError::NoSuchContract {
addr: ACCT.to_string(),
})
}
});
let wrapper = QuerierWrapper::<Empty>::new(&querier);
let err = wrapper.query_wasm_contract_info("unknown").unwrap_err();
assert!(matches!(
err,
StdError::GenericErr {
msg,
..
} if msg == "Querier system error: No such contract: foobar"
));
}
}