-
Notifications
You must be signed in to change notification settings - Fork 346
/
mock.rs
2759 lines (2451 loc) · 99.8 KB
/
mock.rs
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
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use crate::prelude::*;
use crate::HashFunction;
use crate::{Addr, CanonicalAddr, Timestamp};
use alloc::collections::BTreeMap;
#[cfg(feature = "cosmwasm_1_3")]
use alloc::collections::BTreeSet;
use bech32::primitives::decode::CheckedHrpstring;
use bech32::{encode, Bech32, Hrp};
use core::marker::PhantomData;
#[cfg(feature = "cosmwasm_1_3")]
use core::ops::Bound;
use rand_core::OsRng;
use serde::de::DeserializeOwned;
#[cfg(feature = "stargate")]
use serde::Serialize;
use sha2::{Digest, Sha256};
use crate::coin::Coin;
use crate::deps::OwnedDeps;
#[cfg(feature = "stargate")]
use crate::ibc::{
IbcAcknowledgement, IbcChannel, IbcChannelCloseMsg, IbcChannelConnectMsg, IbcChannelOpenMsg,
IbcEndpoint, IbcOrder, IbcPacket, IbcPacketAckMsg, IbcPacketReceiveMsg, IbcPacketTimeoutMsg,
IbcTimeoutBlock,
};
#[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, DelegationResponse,
FullDelegation, StakingQuery, Validator, ValidatorResponse,
};
#[cfg(feature = "cosmwasm_1_3")]
use crate::query::{DelegatorWithdrawAddressResponse, DistributionQuery};
use crate::results::{ContractResult, Empty, SystemResult};
use crate::storage::MemoryStorage;
use crate::traits::{Api, Querier, QuerierResult};
use crate::types::{BlockInfo, ContractInfo, Env, MessageInfo, TransactionInfo};
use crate::{from_json, to_json_binary, Binary, Uint128};
#[cfg(feature = "cosmwasm_1_3")]
use crate::{
query::{AllDenomMetadataResponse, DecCoin, DenomMetadataResponse},
PageRequest,
};
use crate::{Attribute, DenomMetadata};
#[cfg(feature = "stargate")]
use crate::{ChannelResponse, IbcQuery, ListChannelsResponse, PortIdResponse};
#[cfg(feature = "cosmwasm_1_4")]
use crate::{Decimal256, DelegationRewardsResponse, DelegatorValidatorsResponse};
use crate::{RecoverPubkeyError, StdError, StdResult, SystemError, VerificationError};
pub const MOCK_CONTRACT_ADDR: &str =
"cosmwasm1jpev2csrppg792t22rn8z8uew8h3sjcpglcd0qv9g8gj8ky922tscp8avs";
/// Creates all external requirements that can be injected for unit tests.
///
/// See also [`mock_dependencies_with_balance`] and [`mock_dependencies_with_balances`]
/// if you want to start with some initial balances.
pub fn mock_dependencies() -> OwnedDeps<MockStorage, MockApi, MockQuerier, Empty> {
OwnedDeps {
storage: MockStorage::default(),
api: MockApi::default(),
querier: MockQuerier::default(),
custom_query_type: PhantomData,
}
}
/// Creates all external requirements that can be injected for unit tests.
///
/// It sets the given balance for the contract itself, nothing else.
pub fn mock_dependencies_with_balance(
contract_balance: &[Coin],
) -> OwnedDeps<MockStorage, MockApi, MockQuerier, Empty> {
mock_dependencies_with_balances(&[(MOCK_CONTRACT_ADDR, contract_balance)])
}
/// Initializes the querier along with the mock_dependencies.
/// Sets all balances provided (you must explicitly set contract balance if desired).
pub fn mock_dependencies_with_balances(
balances: &[(&str, &[Coin])],
) -> OwnedDeps<MockStorage, MockApi, MockQuerier> {
OwnedDeps {
storage: MockStorage::default(),
api: MockApi::default(),
querier: MockQuerier::new(balances),
custom_query_type: PhantomData,
}
}
// Use MemoryStorage implementation (which is valid in non-testcode)
// We can later make simplifications here if needed
pub type MockStorage = MemoryStorage;
/// Default prefix used when creating Bech32 encoded address.
const BECH32_PREFIX: &str = "cosmwasm";
// MockApi zero pads all human addresses to make them fit the canonical_length
// it trims off zeros for the reverse operation.
// not really smart, but allows us to see a difference (and consistent length for canonical addresses)
#[derive(Copy, Clone)]
pub struct MockApi {
/// Prefix used for creating addresses in Bech32 encoding.
bech32_prefix: &'static str,
}
impl Default for MockApi {
fn default() -> Self {
MockApi {
bech32_prefix: BECH32_PREFIX,
}
}
}
impl Api for MockApi {
fn addr_validate(&self, input: &str) -> StdResult<Addr> {
let canonical = self.addr_canonicalize(input)?;
let normalized = self.addr_humanize(&canonical)?;
if input != normalized.as_str() {
return Err(StdError::generic_err(
"Invalid input: address not normalized",
));
}
Ok(Addr::unchecked(input))
}
fn addr_canonicalize(&self, input: &str) -> StdResult<CanonicalAddr> {
let hrp_str = CheckedHrpstring::new::<Bech32>(input)
.map_err(|_| StdError::generic_err("Error decoding bech32"))?;
if !hrp_str
.hrp()
.as_bytes()
.eq_ignore_ascii_case(self.bech32_prefix.as_bytes())
{
return Err(StdError::generic_err("Wrong bech32 prefix"));
}
let bytes: Vec<u8> = hrp_str.byte_iter().collect();
validate_length(&bytes)?;
Ok(bytes.into())
}
fn addr_humanize(&self, canonical: &CanonicalAddr) -> StdResult<Addr> {
validate_length(canonical.as_ref())?;
let prefix = Hrp::parse(self.bech32_prefix)
.map_err(|_| StdError::generic_err("Invalid bech32 prefix"))?;
encode::<Bech32>(prefix, canonical.as_slice())
.map(Addr::unchecked)
.map_err(|_| StdError::generic_err("Bech32 encoding error"))
}
fn bls12_381_aggregate_g1(&self, g1s: &[u8]) -> Result<[u8; 48], VerificationError> {
cosmwasm_crypto::bls12_381_aggregate_g1(g1s).map_err(Into::into)
}
fn bls12_381_aggregate_g2(&self, g2s: &[u8]) -> Result<[u8; 96], VerificationError> {
cosmwasm_crypto::bls12_381_aggregate_g2(g2s).map_err(Into::into)
}
fn bls12_381_pairing_equality(
&self,
ps: &[u8],
qs: &[u8],
r: &[u8],
s: &[u8],
) -> Result<bool, VerificationError> {
cosmwasm_crypto::bls12_381_pairing_equality(ps, qs, r, s).map_err(Into::into)
}
fn bls12_381_hash_to_g1(
&self,
hash_function: HashFunction,
msg: &[u8],
dst: &[u8],
) -> Result<[u8; 48], VerificationError> {
Ok(cosmwasm_crypto::bls12_381_hash_to_g1(
hash_function.into(),
msg,
dst,
))
}
fn bls12_381_hash_to_g2(
&self,
hash_function: HashFunction,
msg: &[u8],
dst: &[u8],
) -> Result<[u8; 96], VerificationError> {
Ok(cosmwasm_crypto::bls12_381_hash_to_g2(
hash_function.into(),
msg,
dst,
))
}
fn secp256k1_verify(
&self,
message_hash: &[u8],
signature: &[u8],
public_key: &[u8],
) -> Result<bool, VerificationError> {
Ok(cosmwasm_crypto::secp256k1_verify(
message_hash,
signature,
public_key,
)?)
}
fn secp256k1_recover_pubkey(
&self,
message_hash: &[u8],
signature: &[u8],
recovery_param: u8,
) -> Result<Vec<u8>, RecoverPubkeyError> {
let pubkey =
cosmwasm_crypto::secp256k1_recover_pubkey(message_hash, signature, recovery_param)?;
Ok(pubkey.to_vec())
}
fn secp256r1_verify(
&self,
message_hash: &[u8],
signature: &[u8],
public_key: &[u8],
) -> Result<bool, VerificationError> {
Ok(cosmwasm_crypto::secp256r1_verify(
message_hash,
signature,
public_key,
)?)
}
fn secp256r1_recover_pubkey(
&self,
message_hash: &[u8],
signature: &[u8],
recovery_param: u8,
) -> Result<Vec<u8>, RecoverPubkeyError> {
let pubkey =
cosmwasm_crypto::secp256r1_recover_pubkey(message_hash, signature, recovery_param)?;
Ok(pubkey.to_vec())
}
fn ed25519_verify(
&self,
message: &[u8],
signature: &[u8],
public_key: &[u8],
) -> Result<bool, VerificationError> {
Ok(cosmwasm_crypto::ed25519_verify(
message, signature, public_key,
)?)
}
fn ed25519_batch_verify(
&self,
messages: &[&[u8]],
signatures: &[&[u8]],
public_keys: &[&[u8]],
) -> Result<bool, VerificationError> {
Ok(cosmwasm_crypto::ed25519_batch_verify(
&mut OsRng,
messages,
signatures,
public_keys,
)?)
}
fn debug(&self, #[allow(unused)] message: &str) {
println!("{message}");
}
}
impl MockApi {
/// Returns [MockApi] with Bech32 prefix set to provided value.
///
/// Bech32 prefix must not be empty.
///
/// # Example
///
/// ```
/// # use cosmwasm_std::Addr;
/// # use cosmwasm_std::testing::MockApi;
/// #
/// let mock_api = MockApi::default().with_prefix("juno");
/// let addr = mock_api.addr_make("creator");
///
/// assert_eq!(addr.to_string(), "juno1h34lmpywh4upnjdg90cjf4j70aee6z8qqfspugamjp42e4q28kqsksmtyp");
/// ```
pub fn with_prefix(mut self, prefix: &'static str) -> Self {
self.bech32_prefix = prefix;
self
}
/// Returns an address built from provided input string.
///
/// # Example
///
/// ```
/// # use cosmwasm_std::Addr;
/// # use cosmwasm_std::testing::MockApi;
/// #
/// let mock_api = MockApi::default();
/// let addr = mock_api.addr_make("creator");
///
/// assert_eq!(addr.to_string(), "cosmwasm1h34lmpywh4upnjdg90cjf4j70aee6z8qqfspugamjp42e4q28kqs8s7vcp");
/// ```
///
/// # Panics
///
/// This function panics when generating a valid address is not possible,
/// especially when Bech32 prefix set in function [with_prefix](Self::with_prefix) is empty.
///
pub fn addr_make(&self, input: &str) -> Addr {
let digest = Sha256::digest(input);
let prefix = match Hrp::parse(self.bech32_prefix) {
Ok(prefix) => prefix,
Err(reason) => panic!("Generating address failed with reason: {reason}"),
};
match encode::<Bech32>(prefix, &digest) {
Ok(address) => Addr::unchecked(address),
Err(reason) => panic!("Generating address failed with reason: {reason}"),
}
}
}
/// Does basic validation of the number of bytes in a canonical address
fn validate_length(bytes: &[u8]) -> StdResult<()> {
match bytes.len() {
1..=255 => Ok(()),
_ => Err(StdError::generic_err("Invalid canonical address length")),
}
}
/// Returns a default environment with height, time, chain_id, and contract address.
/// You can submit as is to most contracts, or modify height/time if you want to
/// test for expiration.
///
/// This is intended for use in test code only.
///
/// The contract address uses the same bech32 prefix as [`MockApi`](crate::testing::MockApi). While
/// this is good for the majority of users, you might need to create your `Env`s
/// differently if you need a valid address using a different prefix.
///
/// ## Examples
///
/// Create an env:
///
/// ```
/// # use cosmwasm_std::{Addr, BlockInfo, ContractInfo, Env, Timestamp, TransactionInfo};
/// use cosmwasm_std::testing::mock_env;
///
/// let env = mock_env();
/// assert_eq!(env, Env {
/// block: BlockInfo {
/// height: 12_345,
/// time: Timestamp::from_nanos(1_571_797_419_879_305_533),
/// chain_id: "cosmos-testnet-14002".to_string(),
/// },
/// transaction: Some(TransactionInfo { index: 3 }),
/// contract: ContractInfo {
/// address: Addr::unchecked("cosmwasm1jpev2csrppg792t22rn8z8uew8h3sjcpglcd0qv9g8gj8ky922tscp8avs"),
/// },
/// });
/// ```
///
/// Mutate and reuse environment:
///
/// ```
/// # use cosmwasm_std::{Addr, BlockInfo, ContractInfo, Env, Timestamp, TransactionInfo};
/// use cosmwasm_std::testing::mock_env;
///
/// let env1 = mock_env();
///
/// // First test with `env1`
///
/// let mut env2 = env1.clone();
/// env2.block.height += 1;
/// env2.block.time = env1.block.time.plus_seconds(6);
///
/// // `env2` is one block and 6 seconds later
///
/// let mut env3 = env2.clone();
/// env3.block.height += 1;
/// env3.block.time = env2.block.time.plus_nanos(5_500_000_000);
///
/// // `env3` is one block and 5.5 seconds later
/// ```
pub fn mock_env() -> Env {
let contract_addr = MockApi::default().addr_make("cosmos2contract");
Env {
block: BlockInfo {
height: 12_345,
time: Timestamp::from_nanos(1_571_797_419_879_305_533),
chain_id: "cosmos-testnet-14002".to_string(),
},
transaction: Some(TransactionInfo { index: 3 }),
contract: ContractInfo {
address: contract_addr,
},
}
}
/// Just set sender and funds for the message.
/// This is intended for use in test code only.
#[deprecated(note = "This is inconvenient and unsafe. Use message_info instead.")]
pub fn mock_info(sender: &str, funds: &[Coin]) -> MessageInfo {
MessageInfo {
sender: Addr::unchecked(sender),
funds: funds.to_vec(),
}
}
/// Creates an IbcChannel for testing. You set a few key parameters for handshaking,
/// If you want to set more, use this as a default and mutate other fields
#[cfg(feature = "stargate")]
pub fn mock_ibc_channel(my_channel_id: &str, order: IbcOrder, version: &str) -> IbcChannel {
IbcChannel {
endpoint: IbcEndpoint {
port_id: "my_port".to_string(),
channel_id: my_channel_id.to_string(),
},
counterparty_endpoint: IbcEndpoint {
port_id: "their_port".to_string(),
channel_id: "channel-7".to_string(),
},
order,
version: version.to_string(),
connection_id: "connection-2".to_string(),
}
}
/// Creates a IbcChannelOpenMsg::OpenInit for testing ibc_channel_open.
#[cfg(feature = "stargate")]
pub fn mock_ibc_channel_open_init(
my_channel_id: &str,
order: IbcOrder,
version: &str,
) -> IbcChannelOpenMsg {
IbcChannelOpenMsg::new_init(mock_ibc_channel(my_channel_id, order, version))
}
/// Creates a IbcChannelOpenMsg::OpenTry for testing ibc_channel_open.
#[cfg(feature = "stargate")]
pub fn mock_ibc_channel_open_try(
my_channel_id: &str,
order: IbcOrder,
version: &str,
) -> IbcChannelOpenMsg {
IbcChannelOpenMsg::new_try(mock_ibc_channel(my_channel_id, order, version), version)
}
/// Creates a IbcChannelConnectMsg::ConnectAck for testing ibc_channel_connect.
#[cfg(feature = "stargate")]
pub fn mock_ibc_channel_connect_ack(
my_channel_id: &str,
order: IbcOrder,
version: &str,
) -> IbcChannelConnectMsg {
IbcChannelConnectMsg::new_ack(mock_ibc_channel(my_channel_id, order, version), version)
}
/// Creates a IbcChannelConnectMsg::ConnectConfirm for testing ibc_channel_connect.
#[cfg(feature = "stargate")]
pub fn mock_ibc_channel_connect_confirm(
my_channel_id: &str,
order: IbcOrder,
version: &str,
) -> IbcChannelConnectMsg {
IbcChannelConnectMsg::new_confirm(mock_ibc_channel(my_channel_id, order, version))
}
/// Creates a IbcChannelCloseMsg::CloseInit for testing ibc_channel_close.
#[cfg(feature = "stargate")]
pub fn mock_ibc_channel_close_init(
my_channel_id: &str,
order: IbcOrder,
version: &str,
) -> IbcChannelCloseMsg {
IbcChannelCloseMsg::new_init(mock_ibc_channel(my_channel_id, order, version))
}
/// Creates a IbcChannelCloseMsg::CloseConfirm for testing ibc_channel_close.
#[cfg(feature = "stargate")]
pub fn mock_ibc_channel_close_confirm(
my_channel_id: &str,
order: IbcOrder,
version: &str,
) -> IbcChannelCloseMsg {
IbcChannelCloseMsg::new_confirm(mock_ibc_channel(my_channel_id, order, version))
}
/// Creates a IbcPacketReceiveMsg for testing ibc_packet_receive. You set a few key parameters that are
/// often parsed. If you want to set more, use this as a default and mutate other fields
#[cfg(feature = "stargate")]
pub fn mock_ibc_packet_recv(
my_channel_id: &str,
data: &impl Serialize,
) -> StdResult<IbcPacketReceiveMsg> {
Ok(IbcPacketReceiveMsg::new(
IbcPacket {
data: to_json_binary(data)?,
src: IbcEndpoint {
port_id: "their-port".to_string(),
channel_id: "channel-1234".to_string(),
},
dest: IbcEndpoint {
port_id: "our-port".to_string(),
channel_id: my_channel_id.into(),
},
sequence: 27,
timeout: IbcTimeoutBlock {
revision: 1,
height: 12345678,
}
.into(),
},
Addr::unchecked("relayer"),
))
}
/// Creates a IbcPacket for testing ibc_packet_{ack,timeout}. You set a few key parameters that are
/// often parsed. If you want to set more, use this as a default and mutate other fields.
/// The difference from mock_ibc_packet_recv is if `my_channel_id` is src or dest.
#[cfg(feature = "stargate")]
fn mock_ibc_packet(my_channel_id: &str, data: &impl Serialize) -> StdResult<IbcPacket> {
Ok(IbcPacket {
data: to_json_binary(data)?,
src: IbcEndpoint {
port_id: "their-port".to_string(),
channel_id: my_channel_id.into(),
},
dest: IbcEndpoint {
port_id: "our-port".to_string(),
channel_id: "channel-1234".to_string(),
},
sequence: 29,
timeout: IbcTimeoutBlock {
revision: 1,
height: 432332552,
}
.into(),
})
}
/// Creates a IbcPacketAckMsg for testing ibc_packet_ack. You set a few key parameters that are
/// often parsed. If you want to set more, use this as a default and mutate other fields.
/// The difference from mock_ibc_packet_recv is if `my_channel_id` is src or dest.
#[cfg(feature = "stargate")]
pub fn mock_ibc_packet_ack(
my_channel_id: &str,
data: &impl Serialize,
ack: IbcAcknowledgement,
) -> StdResult<IbcPacketAckMsg> {
let packet = mock_ibc_packet(my_channel_id, data)?;
Ok(IbcPacketAckMsg::new(
ack,
packet,
Addr::unchecked("relayer"),
))
}
/// Creates a IbcPacketTimeoutMsg for testing ibc_packet_timeout. You set a few key parameters that are
/// often parsed. If you want to set more, use this as a default and mutate other fields.
/// The difference from mock_ibc_packet_recv is if `my_channel_id` is src or dest.
#[cfg(feature = "stargate")]
pub fn mock_ibc_packet_timeout(
my_channel_id: &str,
data: &impl Serialize,
) -> StdResult<IbcPacketTimeoutMsg> {
let packet = mock_ibc_packet(my_channel_id, data)?;
Ok(IbcPacketTimeoutMsg::new(packet, Addr::unchecked("relayer")))
}
/// The same type as cosmwasm-std's QuerierResult, but easier to reuse in
/// cosmwasm-vm. It might diverge from QuerierResult at some point.
pub type MockQuerierCustomHandlerResult = SystemResult<ContractResult<Binary>>;
/// MockQuerier holds an immutable table of bank balances
/// and configurable handlers for Wasm queries and custom queries.
pub struct MockQuerier<C: DeserializeOwned = Empty> {
pub bank: BankQuerier,
#[cfg(feature = "staking")]
pub staking: StakingQuerier,
#[cfg(feature = "cosmwasm_1_3")]
pub distribution: DistributionQuerier,
wasm: WasmQuerier,
#[cfg(feature = "stargate")]
pub ibc: IbcQuerier,
/// A handler to handle custom queries. This is set to a dummy handler that
/// always errors by default. Update it via `with_custom_handler`.
///
/// Use box to avoid the need of another generic type
custom_handler: Box<dyn for<'a> Fn(&'a C) -> MockQuerierCustomHandlerResult>,
}
impl<C: DeserializeOwned> MockQuerier<C> {
pub fn new(balances: &[(&str, &[Coin])]) -> Self {
MockQuerier {
bank: BankQuerier::new(balances),
#[cfg(feature = "cosmwasm_1_3")]
distribution: DistributionQuerier::default(),
#[cfg(feature = "staking")]
staking: StakingQuerier::default(),
wasm: WasmQuerier::default(),
#[cfg(feature = "stargate")]
ibc: IbcQuerier::default(),
// strange argument notation suggested as a workaround here: https://github.com/rust-lang/rust/issues/41078#issuecomment-294296365
custom_handler: Box::from(|_: &_| -> MockQuerierCustomHandlerResult {
SystemResult::Err(SystemError::UnsupportedRequest {
kind: "custom".to_string(),
})
}),
}
}
pub fn update_wasm<WH>(&mut self, handler: WH)
where
WH: Fn(&WasmQuery) -> QuerierResult + 'static,
{
self.wasm.update_handler(handler)
}
pub fn with_custom_handler<CH>(mut self, handler: CH) -> Self
where
CH: Fn(&C) -> MockQuerierCustomHandlerResult + 'static,
{
self.custom_handler = Box::from(handler);
self
}
}
impl Default for MockQuerier {
fn default() -> Self {
MockQuerier::new(&[])
}
}
impl<C: CustomQuery + DeserializeOwned> Querier for MockQuerier<C> {
fn raw_query(&self, bin_request: &[u8]) -> QuerierResult {
let request: QueryRequest<C> = match from_json(bin_request) {
Ok(v) => v,
Err(e) => {
return SystemResult::Err(SystemError::InvalidRequest {
error: format!("Parsing query request: {e}"),
request: bin_request.into(),
})
}
};
self.handle_query(&request)
}
}
impl<C: CustomQuery + DeserializeOwned> MockQuerier<C> {
pub fn handle_query(&self, request: &QueryRequest<C>) -> QuerierResult {
match &request {
QueryRequest::Bank(bank_query) => self.bank.query(bank_query),
QueryRequest::Custom(custom_query) => (*self.custom_handler)(custom_query),
#[cfg(feature = "staking")]
QueryRequest::Staking(staking_query) => self.staking.query(staking_query),
#[cfg(feature = "cosmwasm_1_3")]
QueryRequest::Distribution(distribution_query) => {
self.distribution.query(distribution_query)
}
QueryRequest::Wasm(msg) => self.wasm.query(msg),
#[cfg(feature = "stargate")]
#[allow(deprecated)]
QueryRequest::Stargate { .. } => SystemResult::Err(SystemError::UnsupportedRequest {
kind: "Stargate".to_string(),
}),
#[cfg(feature = "cosmwasm_2_0")]
QueryRequest::Grpc(_) => SystemResult::Err(SystemError::UnsupportedRequest {
kind: "GRPC".to_string(),
}),
#[cfg(feature = "stargate")]
QueryRequest::Ibc(msg) => self.ibc.query(msg),
}
}
}
struct WasmQuerier {
/// A handler to handle Wasm queries. This is set to a dummy handler that
/// always errors by default. Update it via `with_custom_handler`.
///
/// Use box to avoid the need of generic type.
handler: Box<dyn for<'a> Fn(&'a WasmQuery) -> QuerierResult>,
}
impl WasmQuerier {
fn new(handler: Box<dyn for<'a> Fn(&'a WasmQuery) -> QuerierResult>) -> Self {
Self { handler }
}
fn update_handler<WH>(&mut self, handler: WH)
where
WH: Fn(&WasmQuery) -> QuerierResult + 'static,
{
self.handler = Box::from(handler)
}
fn query(&self, request: &WasmQuery) -> QuerierResult {
(*self.handler)(request)
}
}
impl Default for WasmQuerier {
fn default() -> Self {
let handler = Box::from(|request: &WasmQuery| -> QuerierResult {
let err = match request {
WasmQuery::Smart { contract_addr, .. } => SystemError::NoSuchContract {
addr: contract_addr.clone(),
},
WasmQuery::Raw { contract_addr, .. } => SystemError::NoSuchContract {
addr: contract_addr.clone(),
},
WasmQuery::ContractInfo { contract_addr, .. } => SystemError::NoSuchContract {
addr: contract_addr.clone(),
},
#[cfg(feature = "cosmwasm_1_2")]
WasmQuery::CodeInfo { code_id, .. } => {
SystemError::NoSuchCode { code_id: *code_id }
}
};
SystemResult::Err(err)
});
Self::new(handler)
}
}
#[derive(Clone, Default)]
pub struct BankQuerier {
#[allow(dead_code)]
/// BTreeMap<denom, amount>
supplies: BTreeMap<String, Uint128>,
/// A map from address to balance. The address is the String conversion of `Addr`,
/// i.e. the bech32 encoded address.
balances: BTreeMap<String, Vec<Coin>>,
/// Vec<Metadata>
denom_metadata: BTreeMap<Vec<u8>, DenomMetadata>,
}
impl BankQuerier {
pub fn new(balances: &[(&str, &[Coin])]) -> Self {
let balances: BTreeMap<_, _> = balances
.iter()
.map(|(address, balance)| (address.to_string(), balance.to_vec()))
.collect();
BankQuerier {
supplies: Self::calculate_supplies(&balances),
balances,
denom_metadata: BTreeMap::new(),
}
}
/// set a new balance for the given address and return the old balance
pub fn update_balance(
&mut self,
addr: impl Into<String>,
balance: Vec<Coin>,
) -> Option<Vec<Coin>> {
let result = self.balances.insert(addr.into(), balance);
self.supplies = Self::calculate_supplies(&self.balances);
result
}
pub fn set_denom_metadata(&mut self, denom_metadata: &[DenomMetadata]) {
self.denom_metadata = denom_metadata
.iter()
.map(|d| (d.base.as_bytes().to_vec(), d.clone()))
.collect();
}
fn calculate_supplies(balances: &BTreeMap<String, Vec<Coin>>) -> BTreeMap<String, Uint128> {
let mut supplies = BTreeMap::new();
let all_coins = balances.iter().flat_map(|(_, coins)| coins);
for coin in all_coins {
*supplies
.entry(coin.denom.clone())
.or_insert_with(Uint128::zero) += coin.amount;
}
supplies
}
pub fn query(&self, request: &BankQuery) -> QuerierResult {
let contract_result: ContractResult<Binary> = match request {
#[cfg(feature = "cosmwasm_1_1")]
BankQuery::Supply { denom } => {
let amount = self
.supplies
.get(denom)
.cloned()
.unwrap_or_else(Uint128::zero);
let bank_res = SupplyResponse {
amount: Coin {
amount,
denom: denom.to_string(),
},
};
to_json_binary(&bank_res).into()
}
BankQuery::Balance { address, denom } => {
// proper error on not found, serialize result on found
let amount = self
.balances
.get(address)
.and_then(|v| v.iter().find(|c| &c.denom == denom).map(|c| c.amount))
.unwrap_or_default();
let bank_res = BalanceResponse {
amount: Coin {
amount,
denom: denom.to_string(),
},
};
to_json_binary(&bank_res).into()
}
#[allow(deprecated)]
BankQuery::AllBalances { address } => {
// proper error on not found, serialize result on found
let bank_res = AllBalanceResponse {
amount: self.balances.get(address).cloned().unwrap_or_default(),
};
to_json_binary(&bank_res).into()
}
#[cfg(feature = "cosmwasm_1_3")]
BankQuery::DenomMetadata { denom } => {
let denom_metadata = self.denom_metadata.get(denom.as_bytes());
match denom_metadata {
Some(m) => {
let metadata_res = DenomMetadataResponse {
metadata: m.clone(),
};
to_json_binary(&metadata_res).into()
}
None => return SystemResult::Err(SystemError::Unknown {}),
}
}
#[cfg(feature = "cosmwasm_1_3")]
BankQuery::AllDenomMetadata { pagination } => {
let default_pagination = PageRequest {
key: None,
limit: 100,
reverse: false,
};
let pagination = pagination.as_ref().unwrap_or(&default_pagination);
// range of all denoms after the given key (or until the key for reverse)
let range = match (pagination.reverse, &pagination.key) {
(_, None) => (Bound::Unbounded, Bound::Unbounded),
(true, Some(key)) => (Bound::Unbounded, Bound::Included(key.as_slice())),
(false, Some(key)) => (Bound::Included(key.as_slice()), Bound::Unbounded),
};
let iter = self.denom_metadata.range::<[u8], _>(range);
// using dynamic dispatch here to reduce code duplication and since this is only testing code
let iter: Box<dyn Iterator<Item = _>> = if pagination.reverse {
Box::new(iter.rev())
} else {
Box::new(iter)
};
let mut metadata: Vec<_> = iter
// take the requested amount + 1 to get the next key
.take((pagination.limit.saturating_add(1)) as usize)
.map(|(_, m)| m.clone())
.collect();
// if we took more than requested, remove the last element (the next key),
// otherwise this is the last batch
let next_key = if metadata.len() > pagination.limit as usize {
metadata.pop().map(|m| Binary::from(m.base.as_bytes()))
} else {
None
};
let metadata_res = AllDenomMetadataResponse { metadata, next_key };
to_json_binary(&metadata_res).into()
}
};
// system result is always ok in the mock implementation
SystemResult::Ok(contract_result)
}
}
#[cfg(feature = "stargate")]
#[derive(Clone, Default)]
pub struct IbcQuerier {
port_id: String,
channels: Vec<IbcChannel>,
}
#[cfg(feature = "stargate")]
impl IbcQuerier {
/// Create a mock querier where:
/// - port_id is the port the "contract" is bound to
/// - channels are a list of ibc channels
pub fn new(port_id: &str, channels: &[IbcChannel]) -> Self {
IbcQuerier {
port_id: port_id.to_string(),
channels: channels.to_vec(),
}
}
/// Update the querier's configuration
pub fn update(&mut self, port_id: impl Into<String>, channels: &[IbcChannel]) {
self.port_id = port_id.into();
self.channels = channels.to_vec();
}
pub fn query(&self, request: &IbcQuery) -> QuerierResult {
let contract_result: ContractResult<Binary> = match request {
IbcQuery::Channel {
channel_id,
port_id,
} => {
let channel = self
.channels
.iter()
.find(|c| match port_id {
Some(p) => c.endpoint.channel_id.eq(channel_id) && c.endpoint.port_id.eq(p),
None => {
c.endpoint.channel_id.eq(channel_id)
&& c.endpoint.port_id == self.port_id
}
})
.cloned();
let res = ChannelResponse { channel };
to_json_binary(&res).into()
}
#[allow(deprecated)]
IbcQuery::ListChannels { port_id } => {
let channels = self
.channels
.iter()
.filter(|c| match port_id {
Some(p) => c.endpoint.port_id.eq(p),
None => c.endpoint.port_id == self.port_id,
})
.cloned()
.collect();
let res = ListChannelsResponse { channels };
to_json_binary(&res).into()
}
IbcQuery::PortId {} => {
let res = PortIdResponse {
port_id: self.port_id.clone(),
};
to_json_binary(&res).into()
}
#[cfg(feature = "cosmwasm_2_2")]
IbcQuery::FeeEnabledChannel { .. } => {
use crate::query::FeeEnabledChannelResponse;
// for now, we always return true
to_json_binary(&FeeEnabledChannelResponse::new(true)).into()
}
};
// system result is always ok in the mock implementation
SystemResult::Ok(contract_result)
}
}
#[cfg(feature = "staking")]
#[derive(Clone, Default)]
pub struct StakingQuerier {
denom: String,
validators: Vec<Validator>,
delegations: Vec<FullDelegation>,
}
#[cfg(feature = "staking")]
impl StakingQuerier {
pub fn new(denom: &str, validators: &[Validator], delegations: &[FullDelegation]) -> Self {
StakingQuerier {
denom: denom.to_string(),
validators: validators.to_vec(),
delegations: delegations.to_vec(),
}
}
/// Update the querier's configuration
pub fn update(
&mut self,
denom: impl Into<String>,
validators: &[Validator],
delegations: &[FullDelegation],
) {
self.denom = denom.into();
self.validators = validators.to_vec();
self.delegations = delegations.to_vec();
}