forked from stellar/rs-soroban-sdk
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathenv.rs
More file actions
1974 lines (1840 loc) · 70.3 KB
/
env.rs
File metadata and controls
1974 lines (1840 loc) · 70.3 KB
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 core::convert::Infallible;
#[cfg(target_family = "wasm")]
pub mod internal {
use core::convert::Infallible;
pub use soroban_env_guest::*;
pub type EnvImpl = Guest;
pub type MaybeEnvImpl = Guest;
// In the Guest case, Env::Error is already Infallible so there is no work
// to do to "reject an error": if an error occurs in the environment, the
// host will trap our VM and we'll never get here at all.
pub(crate) fn reject_err<T>(_env: &Guest, r: Result<T, Infallible>) -> Result<T, Infallible> {
r
}
}
#[cfg(not(target_family = "wasm"))]
pub mod internal {
use core::convert::Infallible;
pub use soroban_env_host::*;
pub type EnvImpl = Host;
pub type MaybeEnvImpl = Option<Host>;
// When we have `feature="testutils"` (or are in cfg(test)) we enable feature
// `soroban-env-{common,host}/testutils` which in turn adds the helper method
// `Env::escalate_error_to_panic` to the Env trait.
//
// When this is available we want to use it, because it works in concert
// with a _different_ part of the host that's also `testutils`-gated: the
// mechanism for emulating the WASM VM error-handling semantics with native
// contracts. In particular when a WASM contract calls a host function that
// fails with some error E, the host traps the VM (not returning to it at
// all) and propagates E to the caller of the contract. This is simulated in
// the native case by returning a (nontrivial) error E to us here, which we
// then "reject" back to the host, which stores E in a temporary cell inside
// any `TestContract` frame in progress and then _panics_, unwinding back to
// a panic-catcher it installed when invoking the `TestContract` frame, and
// then extracting E from the frame and returning it to its caller. This
// simulates the "crash, but catching the error" behaviour of the WASM case.
// This only works if we panic via `escalate_error_to_panic`.
//
// (The reason we don't just panic_any() here and let the panic-catcher do a
// type-based catch is that there might _be_ no panic-catcher around us, and
// we want to print out a nice error message in that case too, which
// panic_any() does not do us the favor of producing. This is all very
// subtle. See also soroban_env_host::Host::escalate_error_to_panic.)
#[cfg(any(test, feature = "testutils"))]
pub(crate) fn reject_err<T>(env: &Host, r: Result<T, HostError>) -> Result<T, Infallible> {
r.map_err(|e| env.escalate_error_to_panic(e))
}
// When we're _not_ in a cfg enabling `soroban-env-{common,host}/testutils`,
// there is no `Env::escalate_error_to_panic` to call, so we just panic
// here. But this is ok because in that case there is also no multi-contract
// calling machinery set up, nor probably any panic-catcher installed that
// we need to hide error values for the benefit of. Any panic in this case
// is probably going to unwind completely anyways. No special case needed.
#[cfg(not(any(test, feature = "testutils")))]
pub(crate) fn reject_err<T>(_env: &Host, r: Result<T, HostError>) -> Result<T, Infallible> {
r.map_err(|e| panic!("{:?}", e))
}
#[doc(hidden)]
impl<F, T> Convert<F, T> for super::Env
where
EnvImpl: Convert<F, T>,
{
type Error = <EnvImpl as Convert<F, T>>::Error;
fn convert(&self, f: F) -> Result<T, Self::Error> {
self.env_impl.convert(f)
}
}
}
pub use internal::xdr;
pub use internal::ConversionError;
pub use internal::EnvBase;
pub use internal::Error;
pub use internal::MapObject;
pub use internal::SymbolStr;
pub use internal::TryFromVal;
pub use internal::TryIntoVal;
pub use internal::Val;
pub use internal::VecObject;
pub trait IntoVal<E: internal::Env, T> {
fn into_val(&self, e: &E) -> T;
}
pub trait FromVal<E: internal::Env, T> {
fn from_val(e: &E, v: &T) -> Self;
}
impl<E: internal::Env, T, U> FromVal<E, T> for U
where
U: TryFromVal<E, T>,
{
fn from_val(e: &E, v: &T) -> Self {
U::try_from_val(e, v).unwrap_optimized()
}
}
impl<E: internal::Env, T, U> IntoVal<E, T> for U
where
T: FromVal<E, Self>,
{
fn into_val(&self, e: &E) -> T {
T::from_val(e, self)
}
}
use crate::auth::InvokerContractAuthEntry;
use crate::unwrap::UnwrapInfallible;
use crate::unwrap::UnwrapOptimized;
use crate::InvokeError;
use crate::{
crypto::Crypto, deploy::Deployer, events::Events, ledger::Ledger, logs::Logs, prng::Prng,
storage::Storage, Address, Vec,
};
use internal::{
AddressObject, Bool, BytesObject, DurationObject, I128Object, I256Object, I256Val, I64Object,
MuxedAddressObject, StorageType, StringObject, Symbol, SymbolObject, TimepointObject,
U128Object, U256Object, U256Val, U32Val, U64Object, U64Val, Void,
};
#[doc(hidden)]
#[derive(Clone)]
pub struct MaybeEnv {
maybe_env_impl: internal::MaybeEnvImpl,
#[cfg(any(test, feature = "testutils"))]
test_state: Option<EnvTestState>,
}
#[cfg(target_family = "wasm")]
impl TryFrom<MaybeEnv> for Env {
type Error = Infallible;
fn try_from(_value: MaybeEnv) -> Result<Self, Self::Error> {
Ok(Env {
env_impl: internal::EnvImpl {},
})
}
}
impl Default for MaybeEnv {
fn default() -> Self {
Self::none()
}
}
#[cfg(target_family = "wasm")]
impl MaybeEnv {
// separate function to be const
pub const fn none() -> Self {
Self {
maybe_env_impl: internal::EnvImpl {},
}
}
}
#[cfg(not(target_family = "wasm"))]
impl MaybeEnv {
// separate function to be const
pub const fn none() -> Self {
Self {
maybe_env_impl: None,
#[cfg(any(test, feature = "testutils"))]
test_state: None,
}
}
}
#[cfg(target_family = "wasm")]
impl From<Env> for MaybeEnv {
fn from(value: Env) -> Self {
MaybeEnv {
maybe_env_impl: value.env_impl,
}
}
}
#[cfg(not(target_family = "wasm"))]
impl TryFrom<MaybeEnv> for Env {
type Error = ConversionError;
fn try_from(value: MaybeEnv) -> Result<Self, Self::Error> {
if let Some(env_impl) = value.maybe_env_impl {
Ok(Env {
env_impl,
#[cfg(any(test, feature = "testutils"))]
test_state: value.test_state.unwrap_or_default(),
})
} else {
Err(ConversionError)
}
}
}
#[cfg(not(target_family = "wasm"))]
impl From<Env> for MaybeEnv {
fn from(value: Env) -> Self {
MaybeEnv {
maybe_env_impl: Some(value.env_impl.clone()),
#[cfg(any(test, feature = "testutils"))]
test_state: Some(value.test_state.clone()),
}
}
}
/// The [Env] type provides access to the environment the contract is executing
/// within.
///
/// The [Env] provides access to information about the currently executing
/// contract, who invoked it, contract data, functions for signing, hashing,
/// etc.
///
/// Most types require access to an [Env] to be constructed or converted.
#[derive(Clone)]
pub struct Env {
env_impl: internal::EnvImpl,
#[cfg(any(test, feature = "testutils"))]
test_state: EnvTestState,
}
impl Default for Env {
#[cfg(not(any(test, feature = "testutils")))]
fn default() -> Self {
Self {
env_impl: Default::default(),
}
}
#[cfg(any(test, feature = "testutils"))]
fn default() -> Self {
Self::new_with_config(EnvTestConfig::default())
}
}
#[cfg(any(test, feature = "testutils"))]
#[derive(Clone, Default)]
struct EnvTestState {
config: EnvTestConfig,
generators: Rc<RefCell<Generators>>,
auth_snapshot: Rc<RefCell<AuthSnapshot>>,
snapshot: Option<Rc<LedgerSnapshot>>,
}
/// Config for changing the default behavior of the Env when used in tests.
#[cfg(any(test, feature = "testutils"))]
#[derive(Clone)]
pub struct EnvTestConfig {
/// Capture a test snapshot when the Env is dropped, causing a test snapshot
/// JSON file to be written to disk when the Env is no longer referenced.
/// Defaults to true.
pub capture_snapshot_at_drop: bool,
}
#[cfg(any(test, feature = "testutils"))]
impl Default for EnvTestConfig {
fn default() -> Self {
Self {
capture_snapshot_at_drop: true,
}
}
}
impl Env {
/// Panic with the given error.
///
/// Equivalent to `panic!`, but with an error value instead of a string.
#[doc(hidden)]
#[inline(always)]
pub fn panic_with_error(&self, error: impl Into<internal::Error>) -> ! {
_ = internal::Env::fail_with_error(self, error.into());
#[cfg(target_family = "wasm")]
core::arch::wasm32::unreachable();
#[cfg(not(target_family = "wasm"))]
unreachable!();
}
/// Get a [Storage] for accessing and updating persistent data owned by the
/// currently executing contract.
#[inline(always)]
pub fn storage(&self) -> Storage {
Storage::new(self)
}
/// Get [Events] for publishing events associated with the
/// currently executing contract.
#[inline(always)]
pub fn events(&self) -> Events {
Events::new(self)
}
/// Get a [Ledger] for accessing the current ledger.
#[inline(always)]
pub fn ledger(&self) -> Ledger {
Ledger::new(self)
}
/// Get a deployer for deploying contracts.
#[inline(always)]
pub fn deployer(&self) -> Deployer {
Deployer::new(self)
}
/// Get a [Crypto] for accessing the current cryptographic functions.
#[inline(always)]
pub fn crypto(&self) -> Crypto {
Crypto::new(self)
}
/// # ⚠️ Hazardous Materials
///
/// Get a [CryptoHazmat][crate::crypto::CryptoHazmat] for accessing the
/// cryptographic functions that are not generally recommended. Using them
/// incorrectly can introduce security vulnerabilities. Use [Crypto] if
/// possible.
#[cfg(any(test, feature = "hazmat"))]
#[cfg_attr(feature = "docs", doc(cfg(feature = "hazmat")))]
#[inline(always)]
pub fn crypto_hazmat(&self) -> crate::crypto::CryptoHazmat {
crate::crypto::CryptoHazmat::new(self)
}
/// Get a [Prng] for accessing the current functions which provide pseudo-randomness.
///
/// # Warning
///
/// **The pseudo-random generator returned is not suitable for
/// security-sensitive work.**
#[inline(always)]
pub fn prng(&self) -> Prng {
Prng::new(self)
}
/// Get the Address object corresponding to the current executing contract.
pub fn current_contract_address(&self) -> Address {
let address = internal::Env::get_current_contract_address(self).unwrap_infallible();
unsafe { Address::unchecked_new(self.clone(), address) }
}
#[doc(hidden)]
pub(crate) fn require_auth_for_args(&self, address: &Address, args: Vec<Val>) {
internal::Env::require_auth_for_args(self, address.to_object(), args.to_object())
.unwrap_infallible();
}
#[doc(hidden)]
pub(crate) fn require_auth(&self, address: &Address) {
internal::Env::require_auth(self, address.to_object()).unwrap_infallible();
}
/// Invokes a function of a contract that is registered in the [Env].
///
/// # Panics
///
/// Will panic if the `contract_id` does not match a registered contract,
/// `func` does not match a function of the referenced contract, or the
/// number of `args` do not match the argument count of the referenced
/// contract function.
///
/// Will panic if the contract that is invoked fails or aborts in anyway.
///
/// Will panic if the value returned from the contract cannot be converted
/// into the type `T`.
pub fn invoke_contract<T>(
&self,
contract_address: &Address,
func: &crate::Symbol,
args: Vec<Val>,
) -> T
where
T: TryFromVal<Env, Val>,
{
let rv = internal::Env::call(
self,
contract_address.to_object(),
func.to_symbol_val(),
args.to_object(),
)
.unwrap_infallible();
T::try_from_val(self, &rv)
.map_err(|_| ConversionError)
.unwrap()
}
/// Invokes a function of a contract that is registered in the [Env],
/// returns an error if the invocation fails for any reason.
pub fn try_invoke_contract<T, E>(
&self,
contract_address: &Address,
func: &crate::Symbol,
args: Vec<Val>,
) -> Result<Result<T, T::Error>, Result<E, InvokeError>>
where
T: TryFromVal<Env, Val>,
E: TryFrom<Error>,
E::Error: Into<InvokeError>,
{
let rv = internal::Env::try_call(
self,
contract_address.to_object(),
func.to_symbol_val(),
args.to_object(),
)
.unwrap_infallible();
match internal::Error::try_from_val(self, &rv) {
Ok(err) => Err(E::try_from(err).map_err(Into::into)),
Err(ConversionError) => Ok(T::try_from_val(self, &rv)),
}
}
/// Authorizes sub-contract calls on behalf of the current contract.
///
/// All the direct calls that the current contract performs are always
/// considered to have been authorized. This is only needed to authorize
/// deeper calls that originate from the next contract call from the current
/// contract.
///
/// For example, if the contract A calls contract B, contract
/// B calls contract C and contract C calls `A.require_auth()`, then an
/// entry corresponding to C call has to be passed in `auth_entries`. It
/// doesn't matter if contract B called `require_auth` or not. If contract A
/// calls contract B again, then `authorize_as_current_contract` has to be
/// called again with the respective entries.
///
///
pub fn authorize_as_current_contract(&self, auth_entries: Vec<InvokerContractAuthEntry>) {
internal::Env::authorize_as_curr_contract(self, auth_entries.to_object())
.unwrap_infallible();
}
/// Get the [Logs] for logging debug events.
#[inline(always)]
#[deprecated(note = "use [Env::logs]")]
#[doc(hidden)]
pub fn logger(&self) -> Logs {
self.logs()
}
/// Get the [Logs] for logging debug events.
#[inline(always)]
pub fn logs(&self) -> Logs {
Logs::new(self)
}
}
#[doc(hidden)]
#[cfg(not(target_family = "wasm"))]
impl Env {
pub(crate) fn is_same_env(&self, other: &Self) -> bool {
self.env_impl.is_same(&other.env_impl)
}
}
#[cfg(any(test, feature = "testutils"))]
use crate::testutils::cost_estimate::CostEstimate;
#[cfg(any(test, feature = "testutils"))]
use crate::{
auth,
testutils::{
budget::Budget, Address as _, AuthSnapshot, AuthorizedInvocation, ContractFunctionSet,
EventsSnapshot, Generators, Ledger as _, MockAuth, MockAuthContract, Register, Snapshot,
StellarAssetContract, StellarAssetIssuer,
},
Bytes, BytesN, ConstructorArgs,
};
#[cfg(any(test, feature = "testutils"))]
use core::{cell::RefCell, cell::RefMut};
#[cfg(any(test, feature = "testutils"))]
use internal::ContractInvocationEvent;
#[cfg(any(test, feature = "testutils"))]
use soroban_ledger_snapshot::LedgerSnapshot;
#[cfg(any(test, feature = "testutils"))]
use std::{path::Path, rc::Rc};
#[cfg(any(test, feature = "testutils"))]
use xdr::{LedgerEntry, LedgerKey, LedgerKeyContractData, SorobanAuthorizationEntry};
#[cfg(any(test, feature = "testutils"))]
#[cfg_attr(feature = "docs", doc(cfg(feature = "testutils")))]
impl Env {
#[doc(hidden)]
pub fn in_contract(&self) -> bool {
self.env_impl.has_frame().unwrap()
}
#[doc(hidden)]
pub fn host(&self) -> &internal::Host {
&self.env_impl
}
#[doc(hidden)]
pub(crate) fn with_generator<T>(&self, f: impl FnOnce(RefMut<'_, Generators>) -> T) -> T {
f((*self.test_state.generators).borrow_mut())
}
/// Create an Env with the test config.
pub fn new_with_config(config: EnvTestConfig) -> Env {
struct EmptySnapshotSource();
impl internal::storage::SnapshotSource for EmptySnapshotSource {
fn get(
&self,
_key: &Rc<xdr::LedgerKey>,
) -> Result<Option<(Rc<xdr::LedgerEntry>, Option<u32>)>, soroban_env_host::HostError>
{
Ok(None)
}
}
let rf = Rc::new(EmptySnapshotSource());
let info = internal::LedgerInfo {
protocol_version: 25,
sequence_number: 0,
timestamp: 0,
network_id: [0; 32],
base_reserve: 0,
min_persistent_entry_ttl: 4096,
min_temp_entry_ttl: 16,
max_entry_ttl: 6_312_000,
};
Env::new_for_testutils(config, rf, None, info, None)
}
/// Change the test config of an Env.
pub fn set_config(&mut self, config: EnvTestConfig) {
self.test_state.config = config;
}
/// Used by multiple constructors to configure test environments consistently.
fn new_for_testutils(
config: EnvTestConfig,
recording_footprint: Rc<dyn internal::storage::SnapshotSource>,
generators: Option<Rc<RefCell<Generators>>>,
ledger_info: internal::LedgerInfo,
snapshot: Option<Rc<LedgerSnapshot>>,
) -> Env {
let storage = internal::storage::Storage::with_recording_footprint(recording_footprint);
let budget = internal::budget::Budget::default();
let env_impl = internal::EnvImpl::with_storage_and_budget(storage, budget.clone());
env_impl
.set_source_account(xdr::AccountId(xdr::PublicKey::PublicKeyTypeEd25519(
xdr::Uint256([0; 32]),
)))
.unwrap();
env_impl
.set_diagnostic_level(internal::DiagnosticLevel::Debug)
.unwrap();
env_impl.set_base_prng_seed([0; 32]).unwrap();
let auth_snapshot = Rc::new(RefCell::new(AuthSnapshot::default()));
let auth_snapshot_in_hook = auth_snapshot.clone();
env_impl
.set_top_contract_invocation_hook(Some(Rc::new(move |host, event| {
match event {
ContractInvocationEvent::Start => {}
ContractInvocationEvent::Finish => {
let new_auths = host
.get_authenticated_authorizations()
// If an error occurs getting the authenticated authorizations
// it means that no auth has occurred.
.unwrap();
(*auth_snapshot_in_hook).borrow_mut().0.push(new_auths);
}
}
})))
.unwrap();
env_impl.enable_invocation_metering();
let env = Env {
env_impl,
test_state: EnvTestState {
config,
generators: generators.unwrap_or_default(),
snapshot,
auth_snapshot,
},
};
env.ledger().set(ledger_info);
env
}
/// Returns the resources metered during the last top level contract
/// invocation.
///
/// In order to get non-`None` results, `enable_invocation_metering` has to
/// be called and at least one invocation has to happen after that.
///
/// Take the return value with a grain of salt. The returned resources mostly
/// correspond only to the operations that have happened during the host
/// invocation, i.e. this won't try to simulate the work that happens in
/// production scenarios (e.g. certain XDR rountrips). This also doesn't try
/// to model resources related to the transaction size.
///
/// The returned value is as useful as the preceding setup, e.g. if a test
/// contract is used instead of a Wasm contract, all the costs related to
/// VM instantiation and execution, as well as Wasm reads/rent bumps will be
/// missed.
///
/// While the resource metering may be useful for contract optimization,
/// keep in mind that resource and fee estimation may be imprecise. Use
/// simulation with RPC in order to get the exact resources for submitting
/// the transactions to the network.
pub fn cost_estimate(&self) -> CostEstimate {
CostEstimate::new(self.clone())
}
/// Register a contract with the [Env] for testing.
///
/// Pass the contract type when the contract is defined in the current crate
/// and is being registered natively. Pass the contract wasm bytes when the
/// contract has been loaded as wasm.
///
/// Pass the arguments for the contract's constructor, or `()` if none. For
/// contracts with a constructor, use the contract's generated `Args` type
/// to construct the arguments with the appropropriate types for invoking
/// the constructor during registration.
///
/// Returns the address of the registered contract that is the same as the
/// contract id passed in.
///
/// If you need to specify the address the contract should be registered at,
/// use [`Env::register_at`].
///
/// ### Examples
/// Register a contract defined in the current crate, by specifying the type
/// name:
/// ```
/// use soroban_sdk::{contract, contractimpl, testutils::Address as _, Address, BytesN, Env, Symbol};
///
/// #[contract]
/// pub struct Contract;
///
/// #[contractimpl]
/// impl Contract {
/// pub fn __constructor(_env: Env, _input: u32) {
/// }
/// }
///
/// #[test]
/// fn test() {
/// # }
/// # fn main() {
/// let env = Env::default();
/// let contract_id = env.register(Contract, ContractArgs::__constructor(&123,));
/// }
/// ```
/// Register a contract wasm, by specifying the wasm bytes:
/// ```
/// use soroban_sdk::{testutils::Address as _, Address, BytesN, Env};
///
/// const WASM: &[u8] = include_bytes!("../doctest_fixtures/contract.wasm");
///
/// #[test]
/// fn test() {
/// # }
/// # fn main() {
/// let env = Env::default();
/// let contract_id = env.register(WASM, ());
/// }
/// ```
pub fn register<'a, C, A>(&self, contract: C, constructor_args: A) -> Address
where
C: Register,
A: ConstructorArgs,
{
contract.register(self, None, constructor_args)
}
/// Register a contract with the [Env] for testing.
///
/// Passing a contract ID for the first arguments registers the contract
/// with that contract ID.
///
/// Registering a contract that is already registered replaces it.
/// Use re-registration with caution as it does not exist in the real
/// (on-chain) environment. Specifically, the new contract's constructor
/// will be called again during re-registration. That behavior only exists
/// for this test utility and is not reproducible on-chain, where contract
/// Wasm updates don't cause constructor to be called.
///
/// Pass the contract type when the contract is defined in the current crate
/// and is being registered natively. Pass the contract wasm bytes when the
/// contract has been loaded as wasm.
///
/// Returns the address of the registered contract that is the same as the
/// contract id passed in.
///
/// ### Examples
/// Register a contract defined in the current crate, by specifying the type
/// name:
/// ```
/// use soroban_sdk::{contract, contractimpl, testutils::Address as _, Address, BytesN, Env, Symbol};
///
/// #[contract]
/// pub struct Contract;
///
/// #[contractimpl]
/// impl Contract {
/// pub fn __constructor(_env: Env, _input: u32) {
/// }
/// }
///
/// #[test]
/// fn test() {
/// # }
/// # fn main() {
/// let env = Env::default();
/// let contract_id = Address::generate(&env);
/// env.register_at(&contract_id, Contract, (123_u32,));
/// }
/// ```
/// Register a contract wasm, by specifying the wasm bytes:
/// ```
/// use soroban_sdk::{testutils::Address as _, Address, BytesN, Env};
///
/// const WASM: &[u8] = include_bytes!("../doctest_fixtures/contract.wasm");
///
/// #[test]
/// fn test() {
/// # }
/// # fn main() {
/// let env = Env::default();
/// let contract_id = Address::generate(&env);
/// env.register_at(&contract_id, WASM, ());
/// }
/// ```
pub fn register_at<C, A>(
&self,
contract_id: &Address,
contract: C,
constructor_args: A,
) -> Address
where
C: Register,
A: ConstructorArgs,
{
contract.register(self, contract_id, constructor_args)
}
/// Register a contract with the [Env] for testing.
///
/// Passing a contract ID for the first arguments registers the contract
/// with that contract ID. Providing `None` causes the Env to generate a new
/// contract ID that is assigned to the contract.
///
/// If a contract has a constructor defined, then it will be called with
/// no arguments. If a constructor takes arguments, use `register`.
///
/// Registering a contract that is already registered replaces it.
/// Use re-registration with caution as it does not exist in the real
/// (on-chain) environment. Specifically, the new contract's constructor
/// will be called again during re-registration. That behavior only exists
/// for this test utility and is not reproducible on-chain, where contract
/// Wasm updates don't cause constructor to be called.
///
/// Returns the address of the registered contract.
///
/// ### Examples
/// ```
/// use soroban_sdk::{contract, contractimpl, BytesN, Env, Symbol};
///
/// #[contract]
/// pub struct HelloContract;
///
/// #[contractimpl]
/// impl HelloContract {
/// pub fn hello(env: Env, recipient: Symbol) -> Symbol {
/// todo!()
/// }
/// }
///
/// #[test]
/// fn test() {
/// # }
/// # fn main() {
/// let env = Env::default();
/// let contract_id = env.register_contract(None, HelloContract);
/// }
/// ```
#[deprecated(note = "use `register`")]
pub fn register_contract<'a, T: ContractFunctionSet + 'static>(
&self,
contract_id: impl Into<Option<&'a Address>>,
contract: T,
) -> Address {
self.register_contract_with_constructor(contract_id, contract, ())
}
/// Register a contract with the [Env] for testing.
///
/// This acts the in the same fashion as `register_contract`, but allows
/// passing arguments to the contract's constructor.
///
/// Passing a contract ID for the first arguments registers the contract
/// with that contract ID. Providing `None` causes the Env to generate a new
/// contract ID that is assigned to the contract.
///
/// Registering a contract that is already registered replaces it.
/// Use re-registration with caution as it does not exist in the real
/// (on-chain) environment. Specifically, the new contract's constructor
/// will be called again during re-registration. That behavior only exists
/// for this test utility and is not reproducible on-chain, where contract
/// Wasm updates don't cause constructor to be called.
///
/// Returns the address of the registered contract.
pub(crate) fn register_contract_with_constructor<
'a,
T: ContractFunctionSet + 'static,
A: ConstructorArgs,
>(
&self,
contract_id: impl Into<Option<&'a Address>>,
contract: T,
constructor_args: A,
) -> Address {
struct InternalContractFunctionSet<T: ContractFunctionSet>(pub(crate) T);
impl<T: ContractFunctionSet> internal::ContractFunctionSet for InternalContractFunctionSet<T> {
fn call(
&self,
func: &Symbol,
env_impl: &internal::EnvImpl,
args: &[Val],
) -> Option<Val> {
let env = Env {
env_impl: env_impl.clone(),
test_state: Default::default(),
};
self.0.call(
crate::Symbol::try_from_val(&env, func)
.unwrap_infallible()
.to_string()
.as_str(),
env,
args,
)
}
}
let contract_id = if let Some(contract_id) = contract_id.into() {
contract_id.clone()
} else {
Address::generate(self)
};
self.env_impl
.register_test_contract_with_constructor(
contract_id.to_object(),
Rc::new(InternalContractFunctionSet(contract)),
constructor_args.into_val(self).to_object(),
)
.unwrap();
contract_id
}
/// Register a contract in a Wasm file with the [Env] for testing.
///
/// Passing a contract ID for the first arguments registers the contract
/// with that contract ID. Providing `None` causes the Env to generate a new
/// contract ID that is assigned to the contract.
///
/// Registering a contract that is already registered replaces it.
/// Use re-registration with caution as it does not exist in the real
/// (on-chain) environment. Specifically, the new contract's constructor
/// will be called again during re-registration. That behavior only exists
/// for this test utility and is not reproducible on-chain, where contract
/// Wasm updates don't cause constructor to be called.
///
/// Returns the address of the registered contract.
///
/// ### Examples
/// ```
/// use soroban_sdk::{BytesN, Env};
///
/// const WASM: &[u8] = include_bytes!("../doctest_fixtures/contract.wasm");
///
/// #[test]
/// fn test() {
/// # }
/// # fn main() {
/// let env = Env::default();
/// env.register_contract_wasm(None, WASM);
/// }
/// ```
#[deprecated(note = "use `register`")]
pub fn register_contract_wasm<'a>(
&self,
contract_id: impl Into<Option<&'a Address>>,
contract_wasm: impl IntoVal<Env, Bytes>,
) -> Address {
let wasm_hash: BytesN<32> = self.deployer().upload_contract_wasm(contract_wasm);
self.register_contract_with_optional_contract_id_and_executable(
contract_id,
xdr::ContractExecutable::Wasm(xdr::Hash(wasm_hash.into())),
crate::vec![&self],
)
}
/// Register a contract in a Wasm file with the [Env] for testing.
///
/// This acts the in the same fashion as `register_contract`, but allows
/// passing arguments to the contract's constructor.
///
/// Passing a contract ID for the first arguments registers the contract
/// with that contract ID. Providing `None` causes the Env to generate a new
/// contract ID that is assigned to the contract.
///
/// Registering a contract that is already registered replaces it.
/// Use re-registration with caution as it does not exist in the real
/// (on-chain) environment. Specifically, the new contract's constructor
/// will be called again during re-registration. That behavior only exists
/// for this test utility and is not reproducible on-chain, where contract
/// Wasm updates don't cause constructor to be called.
///
/// Returns the address of the registered contract.
pub(crate) fn register_contract_wasm_with_constructor<'a>(
&self,
contract_id: impl Into<Option<&'a Address>>,
contract_wasm: impl IntoVal<Env, Bytes>,
constructor_args: impl ConstructorArgs,
) -> Address {
let wasm_hash: BytesN<32> = self.deployer().upload_contract_wasm(contract_wasm);
self.register_contract_with_optional_contract_id_and_executable(
contract_id,
xdr::ContractExecutable::Wasm(xdr::Hash(wasm_hash.into())),
constructor_args.into_val(self),
)
}
/// Register the built-in Stellar Asset Contract with provided admin address.
///
/// Returns a utility struct that contains the contract ID of the registered
/// token contract, as well as methods to read and update issuer flags.
///
/// The contract will wrap a randomly-generated Stellar asset. This function
/// is useful for using in the tests when an arbitrary token contract
/// instance is needed.
pub fn register_stellar_asset_contract_v2(&self, admin: Address) -> StellarAssetContract {
let issuer_pk = self.with_generator(|mut g| g.address());
let issuer_id = xdr::AccountId(xdr::PublicKey::PublicKeyTypeEd25519(xdr::Uint256(
issuer_pk.clone(),
)));
let k = Rc::new(xdr::LedgerKey::Account(xdr::LedgerKeyAccount {
account_id: issuer_id.clone(),
}));
if self.host().get_ledger_entry(&k).unwrap().is_none() {
let v = Rc::new(xdr::LedgerEntry {
data: xdr::LedgerEntryData::Account(xdr::AccountEntry {
account_id: issuer_id.clone(),
balance: 0,
flags: 0,
home_domain: Default::default(),
inflation_dest: None,
num_sub_entries: 0,
seq_num: xdr::SequenceNumber(0),
thresholds: xdr::Thresholds([1; 4]),
signers: xdr::VecM::default(),
ext: xdr::AccountEntryExt::V0,
}),
last_modified_ledger_seq: 0,
ext: xdr::LedgerEntryExt::V0,
});
self.host().add_ledger_entry(&k, &v, None).unwrap();
}
let asset = xdr::Asset::CreditAlphanum4(xdr::AlphaNum4 {
asset_code: xdr::AssetCode4([b'a', b'a', b'a', 0]),
issuer: issuer_id.clone(),
});
let create = xdr::HostFunction::CreateContract(xdr::CreateContractArgs {
contract_id_preimage: xdr::ContractIdPreimage::Asset(asset.clone()),
executable: xdr::ContractExecutable::StellarAsset,
});
let token_id: Address = self
.env_impl
.invoke_function(create)
.unwrap()
.try_into_val(self)
.unwrap();
let prev_auth_manager = self.env_impl.snapshot_auth_manager().unwrap();
self.env_impl
.switch_to_recording_auth_inherited_from_snapshot(&prev_auth_manager)
.unwrap();
self.invoke_contract::<()>(
&token_id,
&soroban_sdk_macros::internal_symbol_short!("set_admin"),
(admin,).try_into_val(self).unwrap(),
);
self.env_impl.set_auth_manager(prev_auth_manager).unwrap();