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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
use schemars::JsonSchema;
use serde::de::DeserializeOwned;
use std::collections::HashMap;
use std::fmt;
use std::ops::Deref;
use cosmwasm_std::{
from_slice, Addr, Api, Binary, BlockInfo, ContractInfo, CosmosMsg, Deps, DepsMut, Empty, Env,
MessageInfo, Querier, QuerierWrapper, Reply, Response, Storage, SubMsg, WasmQuery,
};
use crate::transactions::{RepLog, StorageTransaction};
pub trait Contract<T>
where
T: Clone + fmt::Debug + PartialEq + JsonSchema,
{
fn execute(
&self,
deps: DepsMut,
env: Env,
info: MessageInfo,
msg: Vec<u8>,
) -> Result<Response<T>, String>;
fn instantiate(
&self,
deps: DepsMut,
env: Env,
info: MessageInfo,
msg: Vec<u8>,
) -> Result<Response<T>, String>;
fn sudo(&self, deps: DepsMut, env: Env, msg: Vec<u8>) -> Result<Response<T>, String>;
fn reply(&self, deps: DepsMut, env: Env, msg: Reply) -> Result<Response<T>, String>;
fn query(&self, deps: Deps, env: Env, msg: Vec<u8>) -> Result<Binary, String>;
}
type ContractFn<T, C, E> =
fn(deps: DepsMut, env: Env, info: MessageInfo, msg: T) -> Result<Response<C>, E>;
type SudoFn<T, C, E> = fn(deps: DepsMut, env: Env, msg: T) -> Result<Response<C>, E>;
type ReplyFn<C, E> = fn(deps: DepsMut, env: Env, msg: Reply) -> Result<Response<C>, E>;
type QueryFn<T, E> = fn(deps: Deps, env: Env, msg: T) -> Result<Binary, E>;
type ContractClosure<T, C, E> = Box<dyn Fn(DepsMut, Env, MessageInfo, T) -> Result<Response<C>, E>>;
type SudoClosure<T, C, E> = Box<dyn Fn(DepsMut, Env, T) -> Result<Response<C>, E>>;
type ReplyClosure<C, E> = Box<dyn Fn(DepsMut, Env, Reply) -> Result<Response<C>, E>>;
type QueryClosure<T, E> = Box<dyn Fn(Deps, Env, T) -> Result<Binary, E>>;
pub struct ContractWrapper<T1, T2, T3, E1, E2, E3, C = Empty, T4 = Empty, E4 = String, E5 = String>
where
T1: DeserializeOwned,
T2: DeserializeOwned,
T3: DeserializeOwned,
T4: DeserializeOwned,
E1: ToString,
E2: ToString,
E3: ToString,
E4: ToString,
E5: ToString,
C: Clone + fmt::Debug + PartialEq + JsonSchema,
{
execute_fn: ContractClosure<T1, C, E1>,
instantiate_fn: ContractClosure<T2, C, E2>,
query_fn: QueryClosure<T3, E3>,
sudo_fn: Option<SudoClosure<T4, C, E4>>,
reply_fn: Option<ReplyClosure<C, E5>>,
}
impl<T1, T2, T3, E1, E2, E3, C> ContractWrapper<T1, T2, T3, E1, E2, E3, C>
where
T1: DeserializeOwned + 'static,
T2: DeserializeOwned + 'static,
T3: DeserializeOwned + 'static,
E1: ToString + 'static,
E2: ToString + 'static,
E3: ToString + 'static,
C: Clone + fmt::Debug + PartialEq + JsonSchema + 'static,
{
pub fn new(
execute_fn: ContractFn<T1, C, E1>,
instantiate_fn: ContractFn<T2, C, E2>,
query_fn: QueryFn<T3, E3>,
) -> Self {
ContractWrapper {
execute_fn: Box::new(execute_fn),
instantiate_fn: Box::new(instantiate_fn),
query_fn: Box::new(query_fn),
sudo_fn: None,
reply_fn: None,
}
}
pub fn new_with_empty(
execute_fn: ContractFn<T1, Empty, E1>,
instantiate_fn: ContractFn<T2, Empty, E2>,
query_fn: QueryFn<T3, E3>,
) -> Self {
ContractWrapper {
execute_fn: customize_fn(execute_fn),
instantiate_fn: customize_fn(instantiate_fn),
query_fn: Box::new(query_fn),
sudo_fn: None,
reply_fn: None,
}
}
}
impl<T1, T2, T3, E1, E2, E3, C, T4, E4> ContractWrapper<T1, T2, T3, E1, E2, E3, C, T4, E4>
where
T1: DeserializeOwned + 'static,
T2: DeserializeOwned + 'static,
T3: DeserializeOwned + 'static,
T4: DeserializeOwned + 'static,
E1: ToString + 'static,
E2: ToString + 'static,
E3: ToString + 'static,
E4: ToString + 'static,
C: Clone + fmt::Debug + PartialEq + JsonSchema + 'static,
{
pub fn new_with_sudo(
execute_fn: ContractFn<T1, C, E1>,
instantiate_fn: ContractFn<T2, C, E2>,
query_fn: QueryFn<T3, E3>,
sudo_fn: SudoFn<T4, C, E4>,
) -> Self {
ContractWrapper {
execute_fn: Box::new(execute_fn),
instantiate_fn: Box::new(instantiate_fn),
query_fn: Box::new(query_fn),
sudo_fn: Some(Box::new(sudo_fn)),
reply_fn: None,
}
}
}
impl<T1, T2, T3, E1, E2, E3, C, E5> ContractWrapper<T1, T2, T3, E1, E2, E3, C, Empty, String, E5>
where
T1: DeserializeOwned + 'static,
T2: DeserializeOwned + 'static,
T3: DeserializeOwned + 'static,
E1: ToString + 'static,
E2: ToString + 'static,
E3: ToString + 'static,
E5: ToString + 'static,
C: Clone + fmt::Debug + PartialEq + JsonSchema + 'static,
{
pub fn new_with_reply(
execute_fn: ContractFn<T1, C, E1>,
instantiate_fn: ContractFn<T2, C, E2>,
query_fn: QueryFn<T3, E3>,
reply_fn: ReplyFn<C, E5>,
) -> Self {
ContractWrapper {
execute_fn: Box::new(execute_fn),
instantiate_fn: Box::new(instantiate_fn),
query_fn: Box::new(query_fn),
sudo_fn: None,
reply_fn: Some(Box::new(reply_fn)),
}
}
}
fn customize_fn<T, C, E>(raw_fn: ContractFn<T, Empty, E>) -> ContractClosure<T, C, E>
where
T: DeserializeOwned + 'static,
E: ToString + 'static,
C: Clone + fmt::Debug + PartialEq + JsonSchema + 'static,
{
let customized =
move |deps: DepsMut, env: Env, info: MessageInfo, msg: T| -> Result<Response<C>, E> {
raw_fn(deps, env, info, msg).map(customize_response::<C>)
};
Box::new(customized)
}
fn customize_response<C>(resp: Response<Empty>) -> Response<C>
where
C: Clone + fmt::Debug + PartialEq + JsonSchema,
{
Response::<C> {
messages: resp.messages.into_iter().map(customize_msg::<C>).collect(),
events: resp.events,
attributes: resp.attributes,
data: resp.data,
}
}
fn customize_msg<C>(msg: SubMsg<Empty>) -> SubMsg<C>
where
C: Clone + fmt::Debug + PartialEq + JsonSchema,
{
SubMsg {
msg: match msg.msg {
CosmosMsg::Wasm(wasm) => CosmosMsg::Wasm(wasm),
CosmosMsg::Bank(bank) => CosmosMsg::Bank(bank),
CosmosMsg::Staking(staking) => CosmosMsg::Staking(staking),
CosmosMsg::Custom(_) => unreachable!(),
#[cfg(feature = "stargate")]
CosmosMsg::Ibc(ibc) => CosmosMsg::Ibc(ibc),
#[cfg(feature = "stargate")]
CosmosMsg::Stargate { type_url, value } => CosmosMsg::Stargate { type_url, value },
_ => panic!("unknown message variant {:?}", msg),
},
id: msg.id,
gas_limit: msg.gas_limit,
reply_on: msg.reply_on,
}
}
impl<T1, T2, T3, E1, E2, E3, C, T4, E4, E5> Contract<C>
for ContractWrapper<T1, T2, T3, E1, E2, E3, C, T4, E4, E5>
where
T1: DeserializeOwned,
T2: DeserializeOwned,
T3: DeserializeOwned,
T4: DeserializeOwned,
E1: ToString,
E2: ToString,
E3: ToString,
E4: ToString,
E5: ToString,
C: Clone + fmt::Debug + PartialEq + JsonSchema,
{
fn execute(
&self,
deps: DepsMut,
env: Env,
info: MessageInfo,
msg: Vec<u8>,
) -> Result<Response<C>, String> {
let msg: T1 = from_slice(&msg).map_err(|e| e.to_string())?;
let res = (self.execute_fn)(deps, env, info, msg);
res.map_err(|e| e.to_string())
}
fn instantiate(
&self,
deps: DepsMut,
env: Env,
info: MessageInfo,
msg: Vec<u8>,
) -> Result<Response<C>, String> {
let msg: T2 = from_slice(&msg).map_err(|e| e.to_string())?;
let res = (self.instantiate_fn)(deps, env, info, msg);
res.map_err(|e| e.to_string())
}
fn sudo(&self, deps: DepsMut, env: Env, msg: Vec<u8>) -> Result<Response<C>, String> {
let msg: T4 = from_slice(&msg).map_err(|e| e.to_string())?;
let res = match &self.sudo_fn {
Some(sudo) => sudo(deps, env, msg),
None => return Err("sudo not implemented for contract".to_string()),
};
res.map_err(|e| e.to_string())
}
fn reply(&self, deps: DepsMut, env: Env, reply_data: Reply) -> Result<Response<C>, String> {
let res = match &self.reply_fn {
Some(reply) => reply(deps, env, reply_data),
None => return Err("reply not implemented for contract".to_string()),
};
res.map_err(|e| e.to_string())
}
fn query(&self, deps: Deps, env: Env, msg: Vec<u8>) -> Result<Binary, String> {
let msg: T3 = from_slice(&msg).map_err(|e| e.to_string())?;
let res = (self.query_fn)(deps, env, msg);
res.map_err(|e| e.to_string())
}
}
struct ContractData {
code_id: usize,
storage: Box<dyn Storage>,
}
impl ContractData {
fn new(code_id: usize, storage: Box<dyn Storage>) -> Self {
ContractData { code_id, storage }
}
fn as_mut(&mut self) -> ContractMut {
ContractMut {
code_id: self.code_id,
storage: self.storage.as_mut(),
}
}
fn as_ref(&self) -> ContractRef {
ContractRef {
code_id: self.code_id,
storage: self.storage.as_ref(),
}
}
}
struct ContractMut<'a> {
code_id: usize,
storage: &'a mut dyn Storage,
}
impl<'a> ContractMut<'a> {
fn new(code_id: usize, storage: &'a mut dyn Storage) -> Self {
ContractMut { code_id, storage }
}
}
struct ContractRef<'a> {
code_id: usize,
storage: &'a dyn Storage,
}
impl<'a> ContractRef<'a> {
fn new(code_id: usize, storage: &'a dyn Storage) -> Self {
ContractRef { code_id, storage }
}
}
pub fn next_block(block: &mut BlockInfo) {
block.time = block.time.plus_seconds(5);
block.height += 1;
}
pub type StorageFactory = fn() -> Box<dyn Storage>;
pub struct WasmRouter<C>
where
C: Clone + fmt::Debug + PartialEq + JsonSchema,
{
codes: HashMap<usize, Box<dyn Contract<C>>>,
contracts: HashMap<Addr, ContractData>,
block: BlockInfo,
api: Box<dyn Api>,
storage_factory: StorageFactory,
}
impl<C> WasmRouter<C>
where
C: Clone + fmt::Debug + PartialEq + JsonSchema,
{
pub fn new(api: Box<dyn Api>, block: BlockInfo, storage_factory: StorageFactory) -> Self {
WasmRouter {
codes: HashMap::new(),
contracts: HashMap::new(),
block,
api,
storage_factory,
}
}
pub fn set_block(&mut self, block: BlockInfo) {
self.block = block;
}
pub fn update_block<F: Fn(&mut BlockInfo)>(&mut self, action: F) {
action(&mut self.block);
}
pub fn block_info(&self) -> BlockInfo {
self.block.clone()
}
pub fn store_code(&mut self, code: Box<dyn Contract<C>>) -> usize {
let idx = self.codes.len() + 1;
self.codes.insert(idx, code);
idx
}
pub fn cache(&'_ self) -> WasmCache<'_, C> {
WasmCache::new(self)
}
pub fn query(&self, querier: &dyn Querier, request: WasmQuery) -> Result<Binary, String> {
match request {
WasmQuery::Smart { contract_addr, msg } => {
self.query_smart(Addr::unchecked(contract_addr), querier, msg.into())
}
WasmQuery::Raw { contract_addr, key } => {
self.query_raw(Addr::unchecked(contract_addr), &key)
}
q => panic!("Unsupported wasm query: {:?}", q),
}
}
pub fn query_smart(
&self,
address: Addr,
querier: &dyn Querier,
msg: Vec<u8>,
) -> Result<Binary, String> {
self.with_storage(querier, address, |handler, deps, env| {
handler.query(deps, env, msg)
})
}
pub fn query_raw(&self, address: Addr, key: &[u8]) -> Result<Binary, String> {
let contract = self
.contracts
.get(&address)
.ok_or_else(|| "Unregistered contract address".to_string())?;
let data = contract.storage.get(&key).unwrap_or_default();
Ok(data.into())
}
fn get_env<T: Into<Addr>>(&self, address: T) -> Env {
Env {
block: self.block.clone(),
contract: ContractInfo {
address: address.into(),
},
}
}
fn with_storage<F, T>(
&self,
querier: &dyn Querier,
address: Addr,
action: F,
) -> Result<T, String>
where
F: FnOnce(&Box<dyn Contract<C>>, Deps, Env) -> Result<T, String>,
{
let contract = self
.contracts
.get(&address)
.ok_or_else(|| "Unregistered contract address".to_string())?;
let handler = self
.codes
.get(&contract.code_id)
.ok_or_else(|| "Unregistered code id".to_string())?;
let env = self.get_env(address);
let deps = Deps {
storage: contract.storage.as_ref(),
api: self.api.deref(),
querier: QuerierWrapper::new(querier),
};
action(handler, deps, env)
}
}
trait ContractProvider {
fn get_contract<'a>(&'a self, addr: &Addr) -> Option<ContractRef<'a>>;
fn num_contracts(&self) -> usize;
}
impl<C> ContractProvider for WasmRouter<C>
where
C: Clone + fmt::Debug + PartialEq + JsonSchema,
{
fn get_contract<'a>(&'a self, addr: &Addr) -> Option<ContractRef<'a>> {
self.contracts.get(addr).map(|x| x.as_ref())
}
fn num_contracts(&self) -> usize {
self.contracts.len()
}
}
pub struct WasmCache<'a, C>
where
C: Clone + fmt::Debug + PartialEq + JsonSchema,
{
router: &'a WasmRouter<C>,
parent_contracts: &'a dyn ContractProvider,
state: WasmCacheState<'a>,
}
impl<'a, C> ContractProvider for WasmCache<'a, C>
where
C: Clone + fmt::Debug + PartialEq + JsonSchema,
{
fn get_contract<'b>(&'b self, addr: &Addr) -> Option<ContractRef<'b>> {
self.state.get_contract_ref(self.parent_contracts, addr)
}
fn num_contracts(&self) -> usize {
self.parent_contracts.num_contracts() + self.state.contracts.len()
}
}
pub struct WasmCacheState<'a> {
contracts: HashMap<Addr, ContractData>,
contract_diffs: HashMap<Addr, StorageTransaction<'a>>,
}
impl<'a> WasmCacheState<'a> {
pub fn new() -> Self {
WasmCacheState {
contracts: HashMap::new(),
contract_diffs: HashMap::new(),
}
}
}
pub struct WasmOps {
new_contracts: HashMap<Addr, ContractData>,
contract_diffs: Vec<(Addr, RepLog)>,
}
impl WasmOps {
pub fn commit(self, committable: &mut dyn WasmCommittable) {
committable.apply_ops(self)
}
}
pub trait WasmCommittable {
fn apply_ops(&mut self, ops: WasmOps);
}
impl<C> WasmCommittable for WasmRouter<C>
where
C: Clone + fmt::Debug + PartialEq + JsonSchema,
{
fn apply_ops(&mut self, ops: WasmOps) {
ops.new_contracts.into_iter().for_each(|(k, v)| {
self.contracts.insert(k, v);
});
ops.contract_diffs.into_iter().for_each(|(k, ops)| {
let storage = self.contracts.get_mut(&k).unwrap().storage.as_mut();
ops.commit(storage);
});
}
}
impl<'a, C> WasmCommittable for WasmCache<'a, C>
where
C: Clone + fmt::Debug + PartialEq + JsonSchema,
{
fn apply_ops(&mut self, ops: WasmOps) {
ops.new_contracts.into_iter().for_each(|(k, v)| {
self.state.contracts.insert(k, v);
});
ops.contract_diffs.into_iter().for_each(|(k, ops)| {
match self.state.get_contract_mut(self.parent_contracts, &k) {
Some(contract) => ops.commit(contract.storage),
None => panic!("No contract at {}, but applying diff", k),
}
});
}
}
impl<'a, C> WasmCache<'a, C>
where
C: Clone + fmt::Debug + PartialEq + JsonSchema,
{
fn new(router: &'a WasmRouter<C>) -> Self {
WasmCache {
router,
parent_contracts: router,
state: WasmCacheState::new(),
}
}
pub fn cache(&self) -> WasmCache<C> {
WasmCache {
router: self.router,
parent_contracts: self,
state: WasmCacheState::new(),
}
}
pub fn prepare(self) -> WasmOps {
self.state.prepare()
}
pub fn register_contract(&mut self, code_id: usize) -> Result<Addr, String> {
if !self.router.codes.contains_key(&code_id) {
return Err("Cannot init contract with unregistered code id".to_string());
}
let addr = self.next_address();
let info = ContractData::new(code_id, (self.router.storage_factory)());
self.state.contracts.insert(addr.clone(), info);
Ok(addr)
}
fn next_address(&self) -> Addr {
let count = self.parent_contracts.num_contracts() + self.state.contracts.len();
Addr::unchecked("Contract #".to_string() + &count.to_string())
}
pub fn execute(
&mut self,
address: Addr,
querier: &dyn Querier,
info: MessageInfo,
msg: Vec<u8>,
) -> Result<Response<C>, String> {
let parent = &self.router.codes;
let env = self.router.get_env(address.clone());
let api = self.router.api.as_ref();
self.state.with_storage(
querier,
self.parent_contracts,
address,
env,
api,
|code_id, deps, env| {
let handler = parent
.get(&code_id)
.ok_or_else(|| "Unregistered code id".to_string())?;
handler.execute(deps, env, info, msg)
},
)
}
pub fn instantiate(
&mut self,
address: Addr,
querier: &dyn Querier,
info: MessageInfo,
msg: Vec<u8>,
) -> Result<Response<C>, String> {
let parent = &self.router.codes;
let env = self.router.get_env(address.clone());
let api = self.router.api.as_ref();
self.state.with_storage(
querier,
self.parent_contracts,
address,
env,
api,
|code_id, deps, env| {
let handler = parent
.get(&code_id)
.ok_or_else(|| "Unregistered code id".to_string())?;
handler.instantiate(deps, env, info, msg)
},
)
}
pub fn reply(
&mut self,
address: Addr,
querier: &dyn Querier,
reply: Reply,
) -> Result<Response<C>, String> {
let parent = &self.router.codes;
let env = self.router.get_env(address.clone());
let api = self.router.api.as_ref();
self.state.with_storage(
querier,
self.parent_contracts,
address,
env,
api,
|code_id, deps, env| {
let handler = parent
.get(&code_id)
.ok_or_else(|| "Unregistered code id".to_string())?;
handler.reply(deps, env, reply)
},
)
}
pub fn sudo(
&mut self,
address: Addr,
querier: &dyn Querier,
msg: Vec<u8>,
) -> Result<Response<C>, String> {
let parent = &self.router.codes;
let env = self.router.get_env(address.clone());
let api = self.router.api.as_ref();
self.state.with_storage(
querier,
self.parent_contracts,
address,
env,
api,
|code_id, deps, env| {
let handler = parent
.get(&code_id)
.ok_or_else(|| "Unregistered code id".to_string())?;
handler.sudo(deps, env, msg)
},
)
}
}
impl<'a> WasmCacheState<'a> {
pub fn prepare(self) -> WasmOps {
let diffs: Vec<_> = self
.contract_diffs
.into_iter()
.map(|(k, store)| (k, store.prepare()))
.collect();
WasmOps {
new_contracts: self.contracts,
contract_diffs: diffs,
}
}
fn get_contract_mut<'b>(
&'b mut self,
parent: &'a dyn ContractProvider,
addr: &Addr,
) -> Option<ContractMut<'b>> {
if let Some(x) = self.contracts.get_mut(addr) {
return Some(x.as_mut());
}
if let Some(c) = parent.get_contract(addr) {
let code_id = c.code_id;
if self.contract_diffs.contains_key(addr) {
let storage = self.contract_diffs.get_mut(addr).unwrap();
return Some(ContractMut::new(code_id, storage));
}
let wrap = StorageTransaction::new(c.storage);
self.contract_diffs.insert(addr.clone(), wrap);
let storage = self.contract_diffs.get_mut(addr).unwrap();
return Some(ContractMut::new(code_id, storage));
} else {
None
}
}
fn get_contract_ref<'b>(
&'b self,
parent: &'a dyn ContractProvider,
addr: &Addr,
) -> Option<ContractRef<'b>> {
if let Some(x) = self.contracts.get(addr) {
return Some(x.as_ref());
}
if let Some(c) = parent.get_contract(addr) {
let code_id = c.code_id;
if self.contract_diffs.contains_key(addr) {
let storage = self.contract_diffs.get(addr).unwrap();
return Some(ContractRef::new(code_id, storage));
}
Some(c)
} else {
None
}
}
fn with_storage<F, T>(
&mut self,
querier: &dyn Querier,
parent: &'a dyn ContractProvider,
address: Addr,
env: Env,
api: &dyn Api,
action: F,
) -> Result<T, String>
where
F: FnOnce(usize, DepsMut, Env) -> Result<T, String>,
{
let ContractMut { code_id, storage } = self
.get_contract_mut(parent, &address)
.ok_or_else(|| "Unregistered contract address".to_string())?;
let deps = DepsMut {
storage,
api,
querier: QuerierWrapper::new(querier),
};
action(code_id, deps, env)
}
}
#[cfg(test)]
mod test {
use super::*;
use crate::test_helpers::{contract_error, contract_payout, PayoutInitMessage, PayoutQueryMsg};
use cosmwasm_std::testing::{mock_env, mock_info, MockApi, MockQuerier, MockStorage};
use cosmwasm_std::{coin, to_vec, BankMsg, BlockInfo, Coin, CosmosMsg, Empty};
fn mock_router() -> WasmRouter<Empty> {
let env = mock_env();
let api = Box::new(MockApi::default());
WasmRouter::new(api, env.block, || Box::new(MockStorage::new()))
}
#[test]
fn register_contract() {
let mut router = mock_router();
let code_id = router.store_code(contract_error());
let mut cache = router.cache();
cache.register_contract(code_id + 1).unwrap_err();
let contract_addr = cache.register_contract(code_id).unwrap();
let querier: MockQuerier<Empty> = MockQuerier::new(&[]);
let info = mock_info("foobar", &[]);
let err = cache
.instantiate(contract_addr, &querier, info, b"{}".to_vec())
.unwrap_err();
assert_eq!(err, "Generic error: Init failed");
let info = mock_info("foobar", &[]);
let err = cache
.instantiate(
Addr::unchecked("unregistered"),
&querier,
info,
b"{}".to_vec(),
)
.unwrap_err();
assert_eq!(err, "Unregistered contract address");
cache.prepare().commit(&mut router);
}
#[test]
fn update_block() {
let mut router = mock_router();
let BlockInfo { time, height, .. } = router.get_env(Addr::unchecked("foo")).block;
router.update_block(next_block);
let next = router.get_env(Addr::unchecked("foo")).block;
assert_eq!(time.plus_seconds(5), next.time);
assert_eq!(height + 1, next.height);
}
#[test]
fn contract_send_coins() {
let mut router = mock_router();
let code_id = router.store_code(contract_payout());
let mut cache = router.cache();
let contract_addr = cache.register_contract(code_id).unwrap();
let querier: MockQuerier<Empty> = MockQuerier::new(&[]);
let payout = coin(100, "TGD");
let info = mock_info("foobar", &[]);
let init_msg = to_vec(&PayoutInitMessage {
payout: payout.clone(),
})
.unwrap();
let res = cache
.instantiate(contract_addr.clone(), &querier, info, init_msg)
.unwrap();
assert_eq!(0, res.messages.len());
let info = mock_info("foobar", &[]);
let res = cache
.execute(contract_addr.clone(), &querier, info, b"{}".to_vec())
.unwrap();
assert_eq!(1, res.messages.len());
match &res.messages[0].msg {
CosmosMsg::Bank(BankMsg::Send { to_address, amount }) => {
assert_eq!(to_address.as_str(), "foobar");
assert_eq!(amount.as_slice(), &[payout.clone()]);
}
m => panic!("Unexpected message {:?}", m),
}
cache.prepare().commit(&mut router);
let query = to_vec(&PayoutQueryMsg::Payout {}).unwrap();
let data = router.query_smart(contract_addr, &querier, query).unwrap();
let res: PayoutInitMessage = from_slice(&data).unwrap();
assert_eq!(res.payout, payout);
}
fn assert_payout(cache: &mut WasmCache<Empty>, contract_addr: &Addr, payout: &Coin) {
let querier: MockQuerier<Empty> = MockQuerier::new(&[]);
let info = mock_info("silly", &[]);
let res = cache
.execute(contract_addr.clone(), &querier, info, b"{}".to_vec())
.unwrap();
assert_eq!(1, res.messages.len());
match &res.messages[0].msg {
CosmosMsg::Bank(BankMsg::Send { to_address, amount }) => {
assert_eq!(to_address.as_str(), "silly");
assert_eq!(amount.as_slice(), &[payout.clone()]);
}
m => panic!("Unexpected message {:?}", m),
}
}
fn assert_no_contract(cache: &WasmCache<Empty>, contract_addr: &Addr) {
let contract = cache.get_contract(contract_addr);
assert!(contract.is_none(), "{:?}", contract_addr);
}
#[test]
fn multi_level_wasm_cache() {
let mut router = mock_router();
let code_id = router.store_code(contract_payout());
let querier: MockQuerier<Empty> = MockQuerier::new(&[]);
let mut cache = router.cache();
let contract1 = cache.register_contract(code_id).unwrap();
let payout1 = coin(100, "TGD");
let info = mock_info("foobar", &[]);
let init_msg = to_vec(&PayoutInitMessage {
payout: payout1.clone(),
})
.unwrap();
let _res = cache
.instantiate(contract1.clone(), &querier, info, init_msg)
.unwrap();
cache.prepare().commit(&mut router);
let mut cache = router.cache();
assert_payout(&mut cache, &contract1, &payout1);
let contract2 = cache.register_contract(code_id).unwrap();
let payout2 = coin(50, "BTC");
let info = mock_info("foobar", &[]);
let init_msg = to_vec(&PayoutInitMessage {
payout: payout2.clone(),
})
.unwrap();
let _res = cache
.instantiate(contract2.clone(), &querier, info, init_msg)
.unwrap();
assert_payout(&mut cache, &contract2, &payout2);
let mut cache2 = cache.cache();
assert_payout(&mut cache2, &contract1, &payout1);
assert_payout(&mut cache2, &contract2, &payout2);
let contract3 = cache2.register_contract(code_id).unwrap();
let payout3 = coin(1234, "ATOM");
let info = mock_info("johnny", &[]);
let init_msg = to_vec(&PayoutInitMessage {
payout: payout3.clone(),
})
.unwrap();
let _res = cache2
.instantiate(contract3.clone(), &querier, info, init_msg)
.unwrap();
assert_payout(&mut cache2, &contract3, &payout3);
assert_no_contract(&cache, &contract3);
cache2.prepare().commit(&mut cache);
assert_payout(&mut cache, &contract1, &payout1);
assert_payout(&mut cache, &contract2, &payout2);
assert_payout(&mut cache, &contract3, &payout3);
cache.prepare().commit(&mut router);
let mut cache3 = router.cache();
assert_payout(&mut cache3, &contract1, &payout1);
assert_payout(&mut cache3, &contract2, &payout2);
assert_payout(&mut cache3, &contract3, &payout3);
}
}