-
Notifications
You must be signed in to change notification settings - Fork 372
/
Copy pathcalls.rs
856 lines (802 loc) · 27.8 KB
/
calls.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
use serde::de::DeserializeOwned;
use wasmer::Value;
use cosmwasm_std::{ContractResult, CustomMsg, Env, MessageInfo, QueryResponse, Reply, Response};
#[cfg(feature = "stargate")]
use cosmwasm_std::{
Ibc3ChannelOpenResponse, IbcBasicResponse, IbcChannelCloseMsg, IbcChannelConnectMsg,
IbcChannelOpenMsg, IbcPacketAckMsg, IbcPacketReceiveMsg, IbcPacketTimeoutMsg,
IbcReceiveResponse,
};
use crate::backend::{BackendApi, Querier, Storage};
use crate::conversion::ref_to_u32;
use crate::errors::{VmError, VmResult};
use crate::instance::Instance;
use crate::serde::{from_slice, to_vec};
/// The limits in here protect the host from allocating an unreasonable amount of memory
/// and copying an unreasonable amount of data.
///
/// A JSON deserializer would want to set the limit to a much smaller value because
/// deserializing JSON is more expensive. As a consequence, any sane contract should hit
/// the deserializer limit before the read limit.
mod read_limits {
/// A mibi (mega binary)
const MI: usize = 1024 * 1024;
/// Max length (in bytes) of the result data from an instantiate call.
pub const RESULT_INSTANTIATE: usize = 64 * MI;
/// Max length (in bytes) of the result data from an execute call.
pub const RESULT_EXECUTE: usize = 64 * MI;
/// Max length (in bytes) of the result data from a migrate call.
pub const RESULT_MIGRATE: usize = 64 * MI;
/// Max length (in bytes) of the result data from a sudo call.
pub const RESULT_SUDO: usize = 64 * MI;
/// Max length (in bytes) of the result data from a reply call.
pub const RESULT_REPLY: usize = 64 * MI;
/// Max length (in bytes) of the result data from a query call.
pub const RESULT_QUERY: usize = 64 * MI;
/// Max length (in bytes) of the result data from a ibc_channel_open call.
#[cfg(feature = "stargate")]
pub const RESULT_IBC_CHANNEL_OPEN: usize = 64 * MI;
/// Max length (in bytes) of the result data from a ibc_channel_connect call.
#[cfg(feature = "stargate")]
pub const RESULT_IBC_CHANNEL_CONNECT: usize = 64 * MI;
/// Max length (in bytes) of the result data from a ibc_channel_close call.
#[cfg(feature = "stargate")]
pub const RESULT_IBC_CHANNEL_CLOSE: usize = 64 * MI;
/// Max length (in bytes) of the result data from a ibc_packet_receive call.
#[cfg(feature = "stargate")]
pub const RESULT_IBC_PACKET_RECEIVE: usize = 64 * MI;
/// Max length (in bytes) of the result data from a ibc_packet_ack call.
#[cfg(feature = "stargate")]
pub const RESULT_IBC_PACKET_ACK: usize = 64 * MI;
/// Max length (in bytes) of the result data from a ibc_packet_timeout call.
#[cfg(feature = "stargate")]
pub const RESULT_IBC_PACKET_TIMEOUT: usize = 64 * MI;
}
/// The limits for the JSON deserialization.
///
/// Those limits are not used when the Rust JSON deserializer is bypassed by using the
/// public `call_*_raw` functions directly.
mod deserialization_limits {
/// A kibi (kilo binary)
const KI: usize = 1024;
/// Max length (in bytes) of the result data from an instantiate call.
pub const RESULT_INSTANTIATE: usize = 256 * KI;
/// Max length (in bytes) of the result data from an execute call.
pub const RESULT_EXECUTE: usize = 256 * KI;
/// Max length (in bytes) of the result data from a migrate call.
pub const RESULT_MIGRATE: usize = 256 * KI;
/// Max length (in bytes) of the result data from a sudo call.
pub const RESULT_SUDO: usize = 256 * KI;
/// Max length (in bytes) of the result data from a reply call.
pub const RESULT_REPLY: usize = 256 * KI;
/// Max length (in bytes) of the result data from a query call.
pub const RESULT_QUERY: usize = 256 * KI;
/// Max length (in bytes) of the result data from a ibc_channel_open call.
#[cfg(feature = "stargate")]
pub const RESULT_IBC_CHANNEL_OPEN: usize = 256 * KI;
/// Max length (in bytes) of the result data from a ibc_channel_connect call.
#[cfg(feature = "stargate")]
pub const RESULT_IBC_CHANNEL_CONNECT: usize = 256 * KI;
/// Max length (in bytes) of the result data from a ibc_channel_close call.
#[cfg(feature = "stargate")]
pub const RESULT_IBC_CHANNEL_CLOSE: usize = 256 * KI;
/// Max length (in bytes) of the result data from a ibc_packet_receive call.
#[cfg(feature = "stargate")]
pub const RESULT_IBC_PACKET_RECEIVE: usize = 256 * KI;
/// Max length (in bytes) of the result data from a ibc_packet_ack call.
#[cfg(feature = "stargate")]
pub const RESULT_IBC_PACKET_ACK: usize = 256 * KI;
/// Max length (in bytes) of the result data from a ibc_packet_timeout call.
#[cfg(feature = "stargate")]
pub const RESULT_IBC_PACKET_TIMEOUT: usize = 256 * KI;
}
pub fn call_instantiate<A, S, Q, U>(
instance: &mut Instance<A, S, Q>,
env: &Env,
info: &MessageInfo,
msg: &[u8],
) -> VmResult<ContractResult<Response<U>>>
where
A: BackendApi + 'static,
S: Storage + 'static,
Q: Querier + 'static,
U: DeserializeOwned + CustomMsg,
{
let env = to_vec(env)?;
let info = to_vec(info)?;
let data = call_instantiate_raw(instance, &env, &info, msg)?;
let result: ContractResult<Response<U>> =
from_slice(&data, deserialization_limits::RESULT_INSTANTIATE)?;
Ok(result)
}
pub fn call_execute<A, S, Q, U>(
instance: &mut Instance<A, S, Q>,
env: &Env,
info: &MessageInfo,
msg: &[u8],
) -> VmResult<ContractResult<Response<U>>>
where
A: BackendApi + 'static,
S: Storage + 'static,
Q: Querier + 'static,
U: DeserializeOwned + CustomMsg,
{
let env = to_vec(env)?;
let info = to_vec(info)?;
let data = call_execute_raw(instance, &env, &info, msg)?;
let result: ContractResult<Response<U>> =
from_slice(&data, deserialization_limits::RESULT_EXECUTE)?;
Ok(result)
}
pub fn call_migrate<A, S, Q, U>(
instance: &mut Instance<A, S, Q>,
env: &Env,
msg: &[u8],
) -> VmResult<ContractResult<Response<U>>>
where
A: BackendApi + 'static,
S: Storage + 'static,
Q: Querier + 'static,
U: DeserializeOwned + CustomMsg,
{
let env = to_vec(env)?;
let data = call_migrate_raw(instance, &env, msg)?;
let result: ContractResult<Response<U>> =
from_slice(&data, deserialization_limits::RESULT_MIGRATE)?;
Ok(result)
}
pub fn call_sudo<A, S, Q, U>(
instance: &mut Instance<A, S, Q>,
env: &Env,
msg: &[u8],
) -> VmResult<ContractResult<Response<U>>>
where
A: BackendApi + 'static,
S: Storage + 'static,
Q: Querier + 'static,
U: DeserializeOwned + CustomMsg,
{
let env = to_vec(env)?;
let data = call_sudo_raw(instance, &env, msg)?;
let result: ContractResult<Response<U>> =
from_slice(&data, deserialization_limits::RESULT_SUDO)?;
Ok(result)
}
pub fn call_reply<A, S, Q, U>(
instance: &mut Instance<A, S, Q>,
env: &Env,
msg: &Reply,
) -> VmResult<ContractResult<Response<U>>>
where
A: BackendApi + 'static,
S: Storage + 'static,
Q: Querier + 'static,
U: DeserializeOwned + CustomMsg,
{
let env = to_vec(env)?;
let msg = to_vec(msg)?;
let data = call_reply_raw(instance, &env, &msg)?;
let result: ContractResult<Response<U>> =
from_slice(&data, deserialization_limits::RESULT_REPLY)?;
Ok(result)
}
pub fn call_query<A, S, Q>(
instance: &mut Instance<A, S, Q>,
env: &Env,
msg: &[u8],
) -> VmResult<ContractResult<QueryResponse>>
where
A: BackendApi + 'static,
S: Storage + 'static,
Q: Querier + 'static,
{
let env = to_vec(env)?;
let data = call_query_raw(instance, &env, msg)?;
let result: ContractResult<QueryResponse> =
from_slice(&data, deserialization_limits::RESULT_QUERY)?;
// Ensure query response is valid JSON
if let ContractResult::Ok(binary_response) = &result {
serde_json::from_slice::<serde_json::Value>(binary_response.as_slice())
.map_err(|e| VmError::generic_err(format!("Query response must be valid JSON. {e}")))?;
}
Ok(result)
}
#[cfg(feature = "stargate")]
pub fn call_ibc_channel_open<A, S, Q>(
instance: &mut Instance<A, S, Q>,
env: &Env,
msg: &IbcChannelOpenMsg,
) -> VmResult<ContractResult<Option<Ibc3ChannelOpenResponse>>>
where
A: BackendApi + 'static,
S: Storage + 'static,
Q: Querier + 'static,
{
let env = to_vec(env)?;
let msg = to_vec(msg)?;
let data = call_ibc_channel_open_raw(instance, &env, &msg)?;
let result: ContractResult<Option<Ibc3ChannelOpenResponse>> =
from_slice(&data, deserialization_limits::RESULT_IBC_CHANNEL_OPEN)?;
Ok(result)
}
#[cfg(feature = "stargate")]
pub fn call_ibc_channel_connect<A, S, Q, U>(
instance: &mut Instance<A, S, Q>,
env: &Env,
msg: &IbcChannelConnectMsg,
) -> VmResult<ContractResult<IbcBasicResponse<U>>>
where
A: BackendApi + 'static,
S: Storage + 'static,
Q: Querier + 'static,
U: DeserializeOwned + CustomMsg,
{
let env = to_vec(env)?;
let msg = to_vec(msg)?;
let data = call_ibc_channel_connect_raw(instance, &env, &msg)?;
let result = from_slice(&data, deserialization_limits::RESULT_IBC_CHANNEL_CONNECT)?;
Ok(result)
}
#[cfg(feature = "stargate")]
pub fn call_ibc_channel_close<A, S, Q, U>(
instance: &mut Instance<A, S, Q>,
env: &Env,
msg: &IbcChannelCloseMsg,
) -> VmResult<ContractResult<IbcBasicResponse<U>>>
where
A: BackendApi + 'static,
S: Storage + 'static,
Q: Querier + 'static,
U: DeserializeOwned + CustomMsg,
{
let env = to_vec(env)?;
let msg = to_vec(msg)?;
let data = call_ibc_channel_close_raw(instance, &env, &msg)?;
let result = from_slice(&data, deserialization_limits::RESULT_IBC_CHANNEL_CLOSE)?;
Ok(result)
}
#[cfg(feature = "stargate")]
pub fn call_ibc_packet_receive<A, S, Q, U>(
instance: &mut Instance<A, S, Q>,
env: &Env,
msg: &IbcPacketReceiveMsg,
) -> VmResult<ContractResult<IbcReceiveResponse<U>>>
where
A: BackendApi + 'static,
S: Storage + 'static,
Q: Querier + 'static,
U: DeserializeOwned + CustomMsg,
{
let env = to_vec(env)?;
let msg = to_vec(msg)?;
let data = call_ibc_packet_receive_raw(instance, &env, &msg)?;
let result = from_slice(&data, deserialization_limits::RESULT_IBC_PACKET_RECEIVE)?;
Ok(result)
}
#[cfg(feature = "stargate")]
pub fn call_ibc_packet_ack<A, S, Q, U>(
instance: &mut Instance<A, S, Q>,
env: &Env,
msg: &IbcPacketAckMsg,
) -> VmResult<ContractResult<IbcBasicResponse<U>>>
where
A: BackendApi + 'static,
S: Storage + 'static,
Q: Querier + 'static,
U: DeserializeOwned + CustomMsg,
{
let env = to_vec(env)?;
let msg = to_vec(msg)?;
let data = call_ibc_packet_ack_raw(instance, &env, &msg)?;
let result = from_slice(&data, deserialization_limits::RESULT_IBC_PACKET_ACK)?;
Ok(result)
}
#[cfg(feature = "stargate")]
pub fn call_ibc_packet_timeout<A, S, Q, U>(
instance: &mut Instance<A, S, Q>,
env: &Env,
msg: &IbcPacketTimeoutMsg,
) -> VmResult<ContractResult<IbcBasicResponse<U>>>
where
A: BackendApi + 'static,
S: Storage + 'static,
Q: Querier + 'static,
U: DeserializeOwned + CustomMsg,
{
let env = to_vec(env)?;
let msg = to_vec(msg)?;
let data = call_ibc_packet_timeout_raw(instance, &env, &msg)?;
let result = from_slice(&data, deserialization_limits::RESULT_IBC_PACKET_TIMEOUT)?;
Ok(result)
}
/// Calls Wasm export "instantiate" and returns raw data from the contract.
/// The result is length limited to prevent abuse but otherwise unchecked.
pub fn call_instantiate_raw<A, S, Q>(
instance: &mut Instance<A, S, Q>,
env: &[u8],
info: &[u8],
msg: &[u8],
) -> VmResult<Vec<u8>>
where
A: BackendApi + 'static,
S: Storage + 'static,
Q: Querier + 'static,
{
instance.set_storage_readonly(false);
call_raw(
instance,
"instantiate",
&[env, info, msg],
read_limits::RESULT_INSTANTIATE,
)
}
/// Calls Wasm export "execute" and returns raw data from the contract.
/// The result is length limited to prevent abuse but otherwise unchecked.
pub fn call_execute_raw<A, S, Q>(
instance: &mut Instance<A, S, Q>,
env: &[u8],
info: &[u8],
msg: &[u8],
) -> VmResult<Vec<u8>>
where
A: BackendApi + 'static,
S: Storage + 'static,
Q: Querier + 'static,
{
instance.set_storage_readonly(false);
call_raw(
instance,
"execute",
&[env, info, msg],
read_limits::RESULT_EXECUTE,
)
}
/// Calls Wasm export "migrate" and returns raw data from the contract.
/// The result is length limited to prevent abuse but otherwise unchecked.
pub fn call_migrate_raw<A, S, Q>(
instance: &mut Instance<A, S, Q>,
env: &[u8],
msg: &[u8],
) -> VmResult<Vec<u8>>
where
A: BackendApi + 'static,
S: Storage + 'static,
Q: Querier + 'static,
{
instance.set_storage_readonly(false);
call_raw(
instance,
"migrate",
&[env, msg],
read_limits::RESULT_MIGRATE,
)
}
/// Calls Wasm export "sudo" and returns raw data from the contract.
/// The result is length limited to prevent abuse but otherwise unchecked.
pub fn call_sudo_raw<A, S, Q>(
instance: &mut Instance<A, S, Q>,
env: &[u8],
msg: &[u8],
) -> VmResult<Vec<u8>>
where
A: BackendApi + 'static,
S: Storage + 'static,
Q: Querier + 'static,
{
instance.set_storage_readonly(false);
call_raw(instance, "sudo", &[env, msg], read_limits::RESULT_SUDO)
}
/// Calls Wasm export "reply" and returns raw data from the contract.
/// The result is length limited to prevent abuse but otherwise unchecked.
pub fn call_reply_raw<A, S, Q>(
instance: &mut Instance<A, S, Q>,
env: &[u8],
msg: &[u8],
) -> VmResult<Vec<u8>>
where
A: BackendApi + 'static,
S: Storage + 'static,
Q: Querier + 'static,
{
instance.set_storage_readonly(false);
call_raw(instance, "reply", &[env, msg], read_limits::RESULT_REPLY)
}
/// Calls Wasm export "query" and returns raw data from the contract.
/// The result is length limited to prevent abuse but otherwise unchecked.
pub fn call_query_raw<A, S, Q>(
instance: &mut Instance<A, S, Q>,
env: &[u8],
msg: &[u8],
) -> VmResult<Vec<u8>>
where
A: BackendApi + 'static,
S: Storage + 'static,
Q: Querier + 'static,
{
instance.set_storage_readonly(true);
call_raw(instance, "query", &[env, msg], read_limits::RESULT_QUERY)
}
#[cfg(feature = "stargate")]
pub fn call_ibc_channel_open_raw<A, S, Q>(
instance: &mut Instance<A, S, Q>,
env: &[u8],
msg: &[u8],
) -> VmResult<Vec<u8>>
where
A: BackendApi + 'static,
S: Storage + 'static,
Q: Querier + 'static,
{
instance.set_storage_readonly(false);
call_raw(
instance,
"ibc_channel_open",
&[env, msg],
read_limits::RESULT_IBC_CHANNEL_OPEN,
)
}
#[cfg(feature = "stargate")]
pub fn call_ibc_channel_connect_raw<A, S, Q>(
instance: &mut Instance<A, S, Q>,
env: &[u8],
msg: &[u8],
) -> VmResult<Vec<u8>>
where
A: BackendApi + 'static,
S: Storage + 'static,
Q: Querier + 'static,
{
instance.set_storage_readonly(false);
call_raw(
instance,
"ibc_channel_connect",
&[env, msg],
read_limits::RESULT_IBC_CHANNEL_CONNECT,
)
}
#[cfg(feature = "stargate")]
pub fn call_ibc_channel_close_raw<A, S, Q>(
instance: &mut Instance<A, S, Q>,
env: &[u8],
msg: &[u8],
) -> VmResult<Vec<u8>>
where
A: BackendApi + 'static,
S: Storage + 'static,
Q: Querier + 'static,
{
instance.set_storage_readonly(false);
call_raw(
instance,
"ibc_channel_close",
&[env, msg],
read_limits::RESULT_IBC_CHANNEL_CLOSE,
)
}
#[cfg(feature = "stargate")]
pub fn call_ibc_packet_receive_raw<A, S, Q>(
instance: &mut Instance<A, S, Q>,
env: &[u8],
msg: &[u8],
) -> VmResult<Vec<u8>>
where
A: BackendApi + 'static,
S: Storage + 'static,
Q: Querier + 'static,
{
instance.set_storage_readonly(false);
call_raw(
instance,
"ibc_packet_receive",
&[env, msg],
read_limits::RESULT_IBC_PACKET_RECEIVE,
)
}
#[cfg(feature = "stargate")]
pub fn call_ibc_packet_ack_raw<A, S, Q>(
instance: &mut Instance<A, S, Q>,
env: &[u8],
msg: &[u8],
) -> VmResult<Vec<u8>>
where
A: BackendApi + 'static,
S: Storage + 'static,
Q: Querier + 'static,
{
instance.set_storage_readonly(false);
call_raw(
instance,
"ibc_packet_ack",
&[env, msg],
read_limits::RESULT_IBC_PACKET_ACK,
)
}
#[cfg(feature = "stargate")]
pub fn call_ibc_packet_timeout_raw<A, S, Q>(
instance: &mut Instance<A, S, Q>,
env: &[u8],
msg: &[u8],
) -> VmResult<Vec<u8>>
where
A: BackendApi + 'static,
S: Storage + 'static,
Q: Querier + 'static,
{
instance.set_storage_readonly(false);
call_raw(
instance,
"ibc_packet_timeout",
&[env, msg],
read_limits::RESULT_IBC_PACKET_TIMEOUT,
)
}
/// Calls a function with the given arguments.
/// The exported function must return exactly one result (an offset to the result Region).
pub(crate) fn call_raw<A, S, Q>(
instance: &mut Instance<A, S, Q>,
name: &str,
args: &[&[u8]],
result_max_length: usize,
) -> VmResult<Vec<u8>>
where
A: BackendApi + 'static,
S: Storage + 'static,
Q: Querier + 'static,
{
let mut arg_region_ptrs = Vec::<Value>::with_capacity(args.len());
for arg in args {
let region_ptr = instance.allocate(arg.len())?;
instance.write_memory(region_ptr, arg)?;
arg_region_ptrs.push(region_ptr.into());
}
let result = instance.call_function1(name, &arg_region_ptrs)?;
let res_region_ptr = ref_to_u32(&result)?;
let data = instance.read_memory(res_region_ptr, result_max_length)?;
// free return value in wasm (arguments were freed in wasm code)
instance.deallocate(res_region_ptr)?;
Ok(data)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::testing::{mock_env, mock_info, mock_instance};
use cosmwasm_std::{coins, Empty};
static CONTRACT: &[u8] = include_bytes!("../testdata/hackatom.wasm");
static CYBERPUNK: &[u8] = include_bytes!("../testdata/cyberpunk.wasm");
#[test]
fn call_instantiate_works() {
let mut instance = mock_instance(CONTRACT, &[]);
// init
let info = mock_info("creator", &coins(1000, "earth"));
let msg = br#"{"verifier": "verifies", "beneficiary": "benefits"}"#;
call_instantiate::<_, _, _, Empty>(&mut instance, &mock_env(), &info, msg)
.unwrap()
.unwrap();
assert_eq!(instance.get_gas_left(), 494235049729);
}
#[test]
fn call_execute_works() {
let mut instance = mock_instance(CONTRACT, &[]);
// init
let info = mock_info("creator", &coins(1000, "earth"));
let msg = br#"{"verifier": "verifies", "beneficiary": "benefits"}"#;
call_instantiate::<_, _, _, Empty>(&mut instance, &mock_env(), &info, msg)
.unwrap()
.unwrap();
// execute
let info = mock_info("verifies", &coins(15, "earth"));
let msg = br#"{"release":{}}"#;
call_execute::<_, _, _, Empty>(&mut instance, &mock_env(), &info, msg)
.unwrap()
.unwrap();
assert_eq!(instance.get_gas_left(), 485686146123);
}
#[test]
fn call_execute_runs_out_of_gas() {
let mut instance = mock_instance(CYBERPUNK, &[]);
// init
let info = mock_info("creator", &[]);
call_instantiate::<_, _, _, Empty>(&mut instance, &mock_env(), &info, br#"{}"#)
.unwrap()
.unwrap();
// execute
let info = mock_info("looper", &[]);
let msg = br#"{"cpu_loop":{}}"#;
let err =
call_execute::<_, _, _, Empty>(&mut instance, &mock_env(), &info, msg).unwrap_err();
assert!(matches!(err, VmError::GasDepletion {}));
assert_eq!(instance.get_gas_left(), 0);
}
#[test]
fn call_execute_handles_panic() {
let mut instance = mock_instance(CYBERPUNK, &[]);
let info = mock_info("creator", &[]);
call_instantiate::<_, _, _, Empty>(&mut instance, &mock_env(), &info, br#"{}"#)
.unwrap()
.unwrap();
// execute
let info = mock_info("troll", &[]);
let msg = br#"{"panic":{}}"#;
let err =
call_execute::<_, _, _, Empty>(&mut instance, &mock_env(), &info, msg).unwrap_err();
match err {
VmError::RuntimeErr { msg } => {
assert!(msg.contains(
"RuntimeError: Aborted: panicked at 'This page intentionally faulted'"
))
}
err => panic!("Unexpected error: {err:?}"),
}
assert_eq!(instance.get_gas_left(), 493100600000);
}
#[test]
fn call_execute_handles_unreachable() {
let mut instance = mock_instance(CYBERPUNK, &[]);
let info = mock_info("creator", &[]);
call_instantiate::<_, _, _, Empty>(&mut instance, &mock_env(), &info, br#"{}"#)
.unwrap()
.unwrap();
// execute
let info = mock_info("troll", &[]);
let msg = br#"{"unreachable":{}}"#;
let err =
call_execute::<_, _, _, Empty>(&mut instance, &mock_env(), &info, msg).unwrap_err();
match err {
VmError::RuntimeErr { msg } => {
assert!(msg.contains("RuntimeError: unreachable"))
}
err => panic!("Unexpected error: {err:?}"),
}
assert_eq!(instance.get_gas_left(), 493655750000);
}
#[test]
fn call_migrate_works() {
let mut instance = mock_instance(CONTRACT, &[]);
// init
let info = mock_info("creator", &coins(1000, "earth"));
let msg = br#"{"verifier": "verifies", "beneficiary": "benefits"}"#;
call_instantiate::<_, _, _, Empty>(&mut instance, &mock_env(), &info, msg)
.unwrap()
.unwrap();
// change the verifier via migrate
let msg = br#"{"verifier": "someone else"}"#;
let _res = call_migrate::<_, _, _, Empty>(&mut instance, &mock_env(), msg);
// query the new_verifier with verifier
let msg = br#"{"verifier":{}}"#;
let contract_result = call_query(&mut instance, &mock_env(), msg).unwrap();
let query_response = contract_result.unwrap();
assert_eq!(
query_response.as_slice(),
b"{\"verifier\":\"someone else\"}"
);
assert_eq!(instance.get_gas_left(), 485028949541);
}
#[test]
fn call_query_works() {
let mut instance = mock_instance(CONTRACT, &[]);
// init
let info = mock_info("creator", &coins(1000, "earth"));
let msg = br#"{"verifier": "verifies", "beneficiary": "benefits"}"#;
call_instantiate::<_, _, _, Empty>(&mut instance, &mock_env(), &info, msg)
.unwrap()
.unwrap();
// query
let msg = br#"{"verifier":{}}"#;
let contract_result = call_query(&mut instance, &mock_env(), msg).unwrap();
let query_response = contract_result.unwrap();
assert_eq!(query_response.as_slice(), b"{\"verifier\":\"verifies\"}");
assert_eq!(instance.get_gas_left(), 489741349723);
}
#[cfg(feature = "stargate")]
mod ibc {
use super::*;
use crate::calls::{call_instantiate, call_reply};
use crate::testing::{
mock_env, mock_info, mock_instance, MockApi, MockQuerier, MockStorage,
};
use cosmwasm_std::testing::{
mock_ibc_channel_close_init, mock_ibc_channel_connect_ack, mock_ibc_channel_open_init,
mock_ibc_packet_ack, mock_ibc_packet_recv, mock_ibc_packet_timeout, mock_wasmd_attr,
};
use cosmwasm_std::{
Empty, Event, IbcAcknowledgement, IbcOrder, Reply, ReplyOn, SubMsgResponse,
SubMsgResult,
};
static CONTRACT: &[u8] = include_bytes!("../testdata/ibc_reflect.wasm");
const IBC_VERSION: &str = "ibc-reflect-v1";
fn setup(
instance: &mut Instance<MockApi, MockStorage, MockQuerier>,
channel_id: &str,
account: &str,
) {
// init
let info = mock_info("creator", &[]);
let msg = br#"{"reflect_code_id":77}"#;
call_instantiate::<_, _, _, Empty>(instance, &mock_env(), &info, msg)
.unwrap()
.unwrap();
// first we try to open with a valid handshake
let handshake_open =
mock_ibc_channel_open_init(channel_id, IbcOrder::Ordered, IBC_VERSION);
call_ibc_channel_open(instance, &mock_env(), &handshake_open)
.unwrap()
.unwrap();
// then we connect (with counter-party version set)
let handshake_connect =
mock_ibc_channel_connect_ack(channel_id, IbcOrder::Ordered, IBC_VERSION);
let res: IbcBasicResponse = call_ibc_channel_connect::<_, _, _, Empty>(
instance,
&mock_env(),
&handshake_connect,
)
.unwrap()
.unwrap();
assert_eq!(1, res.messages.len());
assert_eq!(
res.events,
[Event::new("ibc").add_attribute("channel", "connect")]
);
assert_eq!(ReplyOn::Success, res.messages[0].reply_on);
let id = res.messages[0].id;
let event = Event::new("instantiate").add_attributes(vec![
// We have to force this one to avoid the debug assertion against _
mock_wasmd_attr("_contract_address", account),
]);
// which creates a reflect account. here we get the callback
let response = Reply {
id,
result: SubMsgResult::Ok(SubMsgResponse {
events: vec![event],
data: None,
}),
};
call_reply::<_, _, _, Empty>(instance, &mock_env(), &response).unwrap();
}
const CHANNEL_ID: &str = "channel-123";
const ACCOUNT: &str = "account-456";
#[test]
fn call_ibc_channel_open_and_connect_works() {
let mut instance = mock_instance(CONTRACT, &[]);
setup(&mut instance, CHANNEL_ID, ACCOUNT);
}
#[test]
fn call_ibc_channel_close_works() {
let mut instance = mock_instance(CONTRACT, &[]);
setup(&mut instance, CHANNEL_ID, ACCOUNT);
let handshake_close =
mock_ibc_channel_close_init(CHANNEL_ID, IbcOrder::Ordered, IBC_VERSION);
call_ibc_channel_close::<_, _, _, Empty>(&mut instance, &mock_env(), &handshake_close)
.unwrap()
.unwrap();
}
#[test]
fn call_ibc_packet_ack_works() {
let mut instance = mock_instance(CONTRACT, &[]);
setup(&mut instance, CHANNEL_ID, ACCOUNT);
let ack = IbcAcknowledgement::new(br#"{}"#);
let msg = mock_ibc_packet_ack(CHANNEL_ID, br#"{}"#, ack).unwrap();
call_ibc_packet_ack::<_, _, _, Empty>(&mut instance, &mock_env(), &msg)
.unwrap()
.unwrap();
}
#[test]
fn call_ibc_packet_timeout_works() {
let mut instance = mock_instance(CONTRACT, &[]);
setup(&mut instance, CHANNEL_ID, ACCOUNT);
let msg = mock_ibc_packet_timeout(CHANNEL_ID, br#"{}"#).unwrap();
call_ibc_packet_timeout::<_, _, _, Empty>(&mut instance, &mock_env(), &msg)
.unwrap()
.unwrap();
}
#[test]
fn call_ibc_packet_receive_works() {
let mut instance = mock_instance(CONTRACT, &[]);
setup(&mut instance, CHANNEL_ID, ACCOUNT);
let who_am_i = br#"{"who_am_i":{}}"#;
let msg = mock_ibc_packet_recv(CHANNEL_ID, who_am_i).unwrap();
call_ibc_packet_receive::<_, _, _, Empty>(&mut instance, &mock_env(), &msg)
.unwrap()
.unwrap();
}
}
}