soroban_sdk/env.rs
1use core::convert::Infallible;
2
3#[cfg(target_family = "wasm")]
4pub mod internal {
5 use core::convert::Infallible;
6
7 pub use soroban_env_guest::*;
8 pub type EnvImpl = Guest;
9 pub type MaybeEnvImpl = Guest;
10
11 // In the Guest case, Env::Error is already Infallible so there is no work
12 // to do to "reject an error": if an error occurs in the environment, the
13 // host will trap our VM and we'll never get here at all.
14 pub(crate) fn reject_err<T>(_env: &Guest, r: Result<T, Infallible>) -> Result<T, Infallible> {
15 r
16 }
17}
18
19#[cfg(not(target_family = "wasm"))]
20pub mod internal {
21 use core::convert::Infallible;
22
23 pub use soroban_env_host::*;
24 pub type EnvImpl = Host;
25 pub type MaybeEnvImpl = Option<Host>;
26
27 // When we have `feature="testutils"` (or are in cfg(test)) we enable feature
28 // `soroban-env-{common,host}/testutils` which in turn adds the helper method
29 // `Env::escalate_error_to_panic` to the Env trait.
30 //
31 // When this is available we want to use it, because it works in concert
32 // with a _different_ part of the host that's also `testutils`-gated: the
33 // mechanism for emulating the WASM VM error-handling semantics with native
34 // contracts. In particular when a WASM contract calls a host function that
35 // fails with some error E, the host traps the VM (not returning to it at
36 // all) and propagates E to the caller of the contract. This is simulated in
37 // the native case by returning a (nontrivial) error E to us here, which we
38 // then "reject" back to the host, which stores E in a temporary cell inside
39 // any `TestContract` frame in progress and then _panics_, unwinding back to
40 // a panic-catcher it installed when invoking the `TestContract` frame, and
41 // then extracting E from the frame and returning it to its caller. This
42 // simulates the "crash, but catching the error" behaviour of the WASM case.
43 // This only works if we panic via `escalate_error_to_panic`.
44 //
45 // (The reason we don't just panic_any() here and let the panic-catcher do a
46 // type-based catch is that there might _be_ no panic-catcher around us, and
47 // we want to print out a nice error message in that case too, which
48 // panic_any() does not do us the favor of producing. This is all very
49 // subtle. See also soroban_env_host::Host::escalate_error_to_panic.)
50 #[cfg(any(test, feature = "testutils"))]
51 pub(crate) fn reject_err<T>(env: &Host, r: Result<T, HostError>) -> Result<T, Infallible> {
52 r.map_err(|e| env.escalate_error_to_panic(e))
53 }
54
55 // When we're _not_ in a cfg enabling `soroban-env-{common,host}/testutils`,
56 // there is no `Env::escalate_error_to_panic` to call, so we just panic
57 // here. But this is ok because in that case there is also no multi-contract
58 // calling machinery set up, nor probably any panic-catcher installed that
59 // we need to hide error values for the benefit of. Any panic in this case
60 // is probably going to unwind completely anyways. No special case needed.
61 #[cfg(not(any(test, feature = "testutils")))]
62 pub(crate) fn reject_err<T>(_env: &Host, r: Result<T, HostError>) -> Result<T, Infallible> {
63 r.map_err(|e| panic!("{:?}", e))
64 }
65
66 #[doc(hidden)]
67 impl<F, T> Convert<F, T> for super::Env
68 where
69 EnvImpl: Convert<F, T>,
70 {
71 type Error = <EnvImpl as Convert<F, T>>::Error;
72 fn convert(&self, f: F) -> Result<T, Self::Error> {
73 self.env_impl.convert(f)
74 }
75 }
76}
77
78pub use internal::xdr;
79pub use internal::ConversionError;
80pub use internal::EnvBase;
81pub use internal::Error;
82pub use internal::MapObject;
83pub use internal::SymbolStr;
84pub use internal::TryFromVal;
85pub use internal::TryIntoVal;
86pub use internal::Val;
87pub use internal::VecObject;
88
89pub trait IntoVal<E: internal::Env, T> {
90 fn into_val(&self, e: &E) -> T;
91}
92
93pub trait FromVal<E: internal::Env, T> {
94 fn from_val(e: &E, v: &T) -> Self;
95}
96
97impl<E: internal::Env, T, U> FromVal<E, T> for U
98where
99 U: TryFromVal<E, T>,
100{
101 fn from_val(e: &E, v: &T) -> Self {
102 U::try_from_val(e, v).unwrap_optimized()
103 }
104}
105
106impl<E: internal::Env, T, U> IntoVal<E, T> for U
107where
108 T: FromVal<E, Self>,
109{
110 fn into_val(&self, e: &E) -> T {
111 T::from_val(e, self)
112 }
113}
114
115use crate::auth::InvokerContractAuthEntry;
116use crate::unwrap::UnwrapInfallible;
117use crate::unwrap::UnwrapOptimized;
118use crate::InvokeError;
119use crate::{
120 crypto::Crypto, deploy::Deployer, events::Events, ledger::Ledger, logs::Logs, prng::Prng,
121 storage::Storage, Address, Vec,
122};
123use internal::{
124 AddressObject, Bool, BytesObject, DurationObject, I128Object, I256Object, I256Val, I64Object,
125 MuxedAddressObject, StorageType, StringObject, Symbol, SymbolObject, TimepointObject,
126 U128Object, U256Object, U256Val, U32Val, U64Object, U64Val, Void,
127};
128
129#[doc(hidden)]
130#[derive(Clone)]
131pub struct MaybeEnv {
132 maybe_env_impl: internal::MaybeEnvImpl,
133 #[cfg(any(test, feature = "testutils"))]
134 test_state: Option<EnvTestState>,
135}
136
137#[cfg(target_family = "wasm")]
138impl TryFrom<MaybeEnv> for Env {
139 type Error = Infallible;
140
141 fn try_from(_value: MaybeEnv) -> Result<Self, Self::Error> {
142 Ok(Env {
143 env_impl: internal::EnvImpl {},
144 })
145 }
146}
147
148impl Default for MaybeEnv {
149 fn default() -> Self {
150 Self::none()
151 }
152}
153
154#[cfg(target_family = "wasm")]
155impl MaybeEnv {
156 // separate function to be const
157 pub const fn none() -> Self {
158 Self {
159 maybe_env_impl: internal::EnvImpl {},
160 }
161 }
162}
163
164#[cfg(not(target_family = "wasm"))]
165impl MaybeEnv {
166 // separate function to be const
167 pub const fn none() -> Self {
168 Self {
169 maybe_env_impl: None,
170 #[cfg(any(test, feature = "testutils"))]
171 test_state: None,
172 }
173 }
174}
175
176#[cfg(target_family = "wasm")]
177impl From<Env> for MaybeEnv {
178 fn from(value: Env) -> Self {
179 MaybeEnv {
180 maybe_env_impl: value.env_impl,
181 }
182 }
183}
184
185#[cfg(not(target_family = "wasm"))]
186impl TryFrom<MaybeEnv> for Env {
187 type Error = ConversionError;
188
189 fn try_from(value: MaybeEnv) -> Result<Self, Self::Error> {
190 if let Some(env_impl) = value.maybe_env_impl {
191 Ok(Env {
192 env_impl,
193 #[cfg(any(test, feature = "testutils"))]
194 test_state: value.test_state.unwrap_or_default(),
195 })
196 } else {
197 Err(ConversionError)
198 }
199 }
200}
201
202#[cfg(not(target_family = "wasm"))]
203impl From<Env> for MaybeEnv {
204 fn from(value: Env) -> Self {
205 MaybeEnv {
206 maybe_env_impl: Some(value.env_impl.clone()),
207 #[cfg(any(test, feature = "testutils"))]
208 test_state: Some(value.test_state.clone()),
209 }
210 }
211}
212
213/// The [Env] type provides access to the environment the contract is executing
214/// within.
215///
216/// The [Env] provides access to information about the currently executing
217/// contract, who invoked it, contract data, functions for signing, hashing,
218/// etc.
219///
220/// Most types require access to an [Env] to be constructed or converted.
221#[derive(Clone)]
222pub struct Env {
223 env_impl: internal::EnvImpl,
224 #[cfg(any(test, feature = "testutils"))]
225 test_state: EnvTestState,
226}
227
228impl Default for Env {
229 #[cfg(not(any(test, feature = "testutils")))]
230 fn default() -> Self {
231 Self {
232 env_impl: Default::default(),
233 }
234 }
235
236 #[cfg(any(test, feature = "testutils"))]
237 fn default() -> Self {
238 Self::new_with_config(EnvTestConfig::default())
239 }
240}
241
242#[cfg(any(test, feature = "testutils"))]
243#[derive(Default, Clone)]
244struct LastEnv {
245 test_name: String,
246 number: usize,
247}
248
249#[cfg(any(test, feature = "testutils"))]
250thread_local! {
251 static LAST_ENV: RefCell<Option<LastEnv>> = RefCell::new(None);
252}
253
254#[cfg(any(test, feature = "testutils"))]
255#[derive(Clone, Default)]
256struct EnvTestState {
257 test_name: Option<String>,
258 number: usize,
259 config: EnvTestConfig,
260 generators: Rc<RefCell<Generators>>,
261 auth_snapshot: Rc<RefCell<AuthSnapshot>>,
262 snapshot: Option<Rc<LedgerSnapshot>>,
263}
264
265/// Config for changing the default behavior of the Env when used in tests.
266#[cfg(any(test, feature = "testutils"))]
267#[derive(Clone)]
268pub struct EnvTestConfig {
269 /// Capture a test snapshot when the Env is dropped, causing a test snapshot
270 /// JSON file to be written to disk when the Env is no longer referenced.
271 /// Defaults to true.
272 pub capture_snapshot_at_drop: bool,
273}
274
275#[cfg(any(test, feature = "testutils"))]
276impl Default for EnvTestConfig {
277 fn default() -> Self {
278 Self {
279 capture_snapshot_at_drop: true,
280 }
281 }
282}
283
284impl Env {
285 /// Panic with the given error.
286 ///
287 /// Equivalent to `panic!`, but with an error value instead of a string.
288 #[doc(hidden)]
289 #[inline(always)]
290 pub fn panic_with_error(&self, error: impl Into<internal::Error>) -> ! {
291 _ = internal::Env::fail_with_error(self, error.into());
292 #[cfg(target_family = "wasm")]
293 core::arch::wasm32::unreachable();
294 #[cfg(not(target_family = "wasm"))]
295 unreachable!();
296 }
297
298 /// Get a [Storage] for accessing and updating persistent data owned by the
299 /// currently executing contract.
300 #[inline(always)]
301 pub fn storage(&self) -> Storage {
302 Storage::new(self)
303 }
304
305 /// Get [Events] for publishing events associated with the
306 /// currently executing contract.
307 #[inline(always)]
308 pub fn events(&self) -> Events {
309 Events::new(self)
310 }
311
312 /// Get a [Ledger] for accessing the current ledger.
313 #[inline(always)]
314 pub fn ledger(&self) -> Ledger {
315 Ledger::new(self)
316 }
317
318 /// Get a deployer for deploying contracts.
319 #[inline(always)]
320 pub fn deployer(&self) -> Deployer {
321 Deployer::new(self)
322 }
323
324 /// Get a [Crypto] for accessing the current cryptographic functions.
325 #[inline(always)]
326 pub fn crypto(&self) -> Crypto {
327 Crypto::new(self)
328 }
329
330 /// # ⚠️ Hazardous Materials
331 ///
332 /// Get a [CryptoHazmat][crate::crypto::CryptoHazmat] for accessing the
333 /// cryptographic functions that are not generally recommended. Using them
334 /// incorrectly can introduce security vulnerabilities. Use [Crypto] if
335 /// possible.
336 #[cfg_attr(any(test, feature = "hazmat-crypto"), visibility::make(pub))]
337 #[cfg_attr(
338 feature = "docs",
339 doc(cfg(any(feature = "hazmat", feature = "hazmat-crypto")))
340 )]
341 #[inline(always)]
342 pub(crate) fn crypto_hazmat(&self) -> crate::crypto::CryptoHazmat {
343 crate::crypto::CryptoHazmat::new(self)
344 }
345
346 /// Get a [Prng] for accessing the current functions which provide pseudo-randomness.
347 ///
348 /// # Warning
349 ///
350 /// **The pseudo-random generator returned is not suitable for
351 /// security-sensitive work.**
352 #[inline(always)]
353 pub fn prng(&self) -> Prng {
354 Prng::new(self)
355 }
356
357 /// Get the Address object corresponding to the current executing contract.
358 pub fn current_contract_address(&self) -> Address {
359 let address = internal::Env::get_current_contract_address(self).unwrap_infallible();
360 unsafe { Address::unchecked_new(self.clone(), address) }
361 }
362
363 #[doc(hidden)]
364 pub(crate) fn require_auth_for_args(&self, address: &Address, args: Vec<Val>) {
365 internal::Env::require_auth_for_args(self, address.to_object(), args.to_object())
366 .unwrap_infallible();
367 }
368
369 #[doc(hidden)]
370 pub(crate) fn require_auth(&self, address: &Address) {
371 internal::Env::require_auth(self, address.to_object()).unwrap_infallible();
372 }
373
374 /// Invokes a function of a contract that is registered in the [Env].
375 ///
376 /// # Panics
377 ///
378 /// Will panic if the `contract_id` does not match a registered contract,
379 /// `func` does not match a function of the referenced contract, or the
380 /// number of `args` do not match the argument count of the referenced
381 /// contract function.
382 ///
383 /// Will panic if the contract that is invoked fails or aborts in anyway.
384 ///
385 /// Will panic if the value returned from the contract cannot be converted
386 /// into the type `T`.
387 pub fn invoke_contract<T>(
388 &self,
389 contract_address: &Address,
390 func: &crate::Symbol,
391 args: Vec<Val>,
392 ) -> T
393 where
394 T: TryFromVal<Env, Val>,
395 {
396 let rv = internal::Env::call(
397 self,
398 contract_address.to_object(),
399 func.to_symbol_val(),
400 args.to_object(),
401 )
402 .unwrap_infallible();
403 T::try_from_val(self, &rv)
404 .map_err(|_| ConversionError)
405 .unwrap()
406 }
407
408 /// Invokes a function of a contract that is registered in the [Env],
409 /// returns an error if the invocation fails for any reason.
410 pub fn try_invoke_contract<T, E>(
411 &self,
412 contract_address: &Address,
413 func: &crate::Symbol,
414 args: Vec<Val>,
415 ) -> Result<Result<T, T::Error>, Result<E, InvokeError>>
416 where
417 T: TryFromVal<Env, Val>,
418 E: TryFrom<Error>,
419 E::Error: Into<InvokeError>,
420 {
421 let rv = internal::Env::try_call(
422 self,
423 contract_address.to_object(),
424 func.to_symbol_val(),
425 args.to_object(),
426 )
427 .unwrap_infallible();
428 match internal::Error::try_from_val(self, &rv) {
429 Ok(err) => Err(E::try_from(err).map_err(Into::into)),
430 Err(ConversionError) => Ok(T::try_from_val(self, &rv)),
431 }
432 }
433
434 /// Authorizes sub-contract calls on behalf of the current contract.
435 ///
436 /// All the direct calls that the current contract performs are always
437 /// considered to have been authorized. This is only needed to authorize
438 /// deeper calls that originate from the next contract call from the current
439 /// contract.
440 ///
441 /// For example, if the contract A calls contract B, contract
442 /// B calls contract C and contract C calls `A.require_auth()`, then an
443 /// entry corresponding to C call has to be passed in `auth_entries`. It
444 /// doesn't matter if contract B called `require_auth` or not. If contract A
445 /// calls contract B again, then `authorize_as_current_contract` has to be
446 /// called again with the respective entries.
447 ///
448 ///
449 pub fn authorize_as_current_contract(&self, auth_entries: Vec<InvokerContractAuthEntry>) {
450 internal::Env::authorize_as_curr_contract(self, auth_entries.to_object())
451 .unwrap_infallible();
452 }
453
454 /// Get the [Logs] for logging debug events.
455 #[inline(always)]
456 #[deprecated(note = "use [Env::logs]")]
457 #[doc(hidden)]
458 pub fn logger(&self) -> Logs {
459 self.logs()
460 }
461
462 /// Get the [Logs] for logging debug events.
463 #[inline(always)]
464 pub fn logs(&self) -> Logs {
465 Logs::new(self)
466 }
467}
468
469#[doc(hidden)]
470#[cfg(not(target_family = "wasm"))]
471impl Env {
472 pub(crate) fn is_same_env(&self, other: &Self) -> bool {
473 self.env_impl.is_same(&other.env_impl)
474 }
475}
476
477#[cfg(any(test, feature = "testutils"))]
478use crate::testutils::cost_estimate::CostEstimate;
479#[cfg(any(test, feature = "testutils"))]
480use crate::{
481 auth,
482 testutils::{
483 budget::Budget, default_ledger_info, Address as _, AuthSnapshot, AuthorizedInvocation,
484 ContractFunctionSet, EventsSnapshot, Generators, Ledger as _, MockAuth, MockAuthContract,
485 Register, Snapshot, StellarAssetContract, StellarAssetIssuer,
486 },
487 Bytes, BytesN, ConstructorArgs,
488};
489#[cfg(any(test, feature = "testutils"))]
490use core::{cell::RefCell, cell::RefMut};
491#[cfg(any(test, feature = "testutils"))]
492use internal::ContractInvocationEvent;
493#[cfg(any(test, feature = "testutils"))]
494use soroban_ledger_snapshot::LedgerSnapshot;
495#[cfg(any(test, feature = "testutils"))]
496use std::{path::Path, rc::Rc};
497#[cfg(any(test, feature = "testutils"))]
498use xdr::{LedgerEntry, LedgerKey, LedgerKeyContractData, SorobanAuthorizationEntry};
499
500#[cfg(any(test, feature = "testutils"))]
501#[cfg_attr(feature = "docs", doc(cfg(feature = "testutils")))]
502impl Env {
503 #[doc(hidden)]
504 pub fn in_contract(&self) -> bool {
505 self.env_impl.has_frame().unwrap()
506 }
507
508 #[doc(hidden)]
509 pub fn host(&self) -> &internal::Host {
510 &self.env_impl
511 }
512
513 #[doc(hidden)]
514 pub(crate) fn with_generator<T>(&self, f: impl FnOnce(RefMut<'_, Generators>) -> T) -> T {
515 f((*self.test_state.generators).borrow_mut())
516 }
517
518 /// Create an Env with the test config.
519 pub fn new_with_config(config: EnvTestConfig) -> Env {
520 struct EmptySnapshotSource();
521
522 impl internal::storage::SnapshotSource for EmptySnapshotSource {
523 fn get(
524 &self,
525 _key: &Rc<xdr::LedgerKey>,
526 ) -> Result<Option<(Rc<xdr::LedgerEntry>, Option<u32>)>, soroban_env_host::HostError>
527 {
528 Ok(None)
529 }
530 }
531
532 let rf = Rc::new(EmptySnapshotSource());
533
534 Env::new_for_testutils(config, rf, None, None, None)
535 }
536
537 /// Change the test config of an Env.
538 pub fn set_config(&mut self, config: EnvTestConfig) {
539 self.test_state.config = config;
540 }
541
542 /// Used by multiple constructors to configure test environments consistently.
543 fn new_for_testutils(
544 config: EnvTestConfig,
545 recording_footprint: Rc<dyn internal::storage::SnapshotSource>,
546 generators: Option<Rc<RefCell<Generators>>>,
547 ledger_info: Option<internal::LedgerInfo>,
548 snapshot: Option<Rc<LedgerSnapshot>>,
549 ) -> Env {
550 // Store in the Env the name of the test it is for, and a number so that within a test
551 // where one or more Env's have been created they can be uniquely identified relative to
552 // each other.
553 let test_name = match std::thread::current().name() {
554 // When doc tests are running they're all run with the thread name main. There's no way
555 // to detect which doc test is being run.
556 Some(name) if name != "main" => Some(name.to_owned()),
557 _ => None,
558 };
559 let number = if let Some(ref test_name) = test_name {
560 LAST_ENV.with_borrow_mut(|l| {
561 if let Some(last_env) = l.as_mut() {
562 if test_name != &last_env.test_name {
563 last_env.test_name = test_name.clone();
564 last_env.number = 1;
565 1
566 } else {
567 let next_number = last_env.number + 1;
568 last_env.number = next_number;
569 next_number
570 }
571 } else {
572 *l = Some(LastEnv {
573 test_name: test_name.clone(),
574 number: 1,
575 });
576 1
577 }
578 })
579 } else {
580 1
581 };
582
583 let storage = internal::storage::Storage::with_recording_footprint(recording_footprint);
584 let budget = internal::budget::Budget::default();
585 let env_impl = internal::EnvImpl::with_storage_and_budget(storage, budget.clone());
586 env_impl
587 .set_source_account(xdr::AccountId(xdr::PublicKey::PublicKeyTypeEd25519(
588 xdr::Uint256([0; 32]),
589 )))
590 .unwrap();
591 env_impl
592 .set_diagnostic_level(internal::DiagnosticLevel::Debug)
593 .unwrap();
594 env_impl.set_base_prng_seed([0; 32]).unwrap();
595
596 let auth_snapshot = Rc::new(RefCell::new(AuthSnapshot::default()));
597 let auth_snapshot_in_hook = auth_snapshot.clone();
598 env_impl
599 .set_top_contract_invocation_hook(Some(Rc::new(move |host, event| {
600 match event {
601 ContractInvocationEvent::Start => {}
602 ContractInvocationEvent::Finish => {
603 let new_auths = host
604 .get_authenticated_authorizations()
605 // If an error occurs getting the authenticated authorizations
606 // it means that no auth has occurred.
607 .unwrap();
608 (*auth_snapshot_in_hook).borrow_mut().0.push(new_auths);
609 }
610 }
611 })))
612 .unwrap();
613 env_impl.enable_invocation_metering();
614
615 let env = Env {
616 env_impl,
617 test_state: EnvTestState {
618 test_name,
619 number,
620 config,
621 generators: generators.unwrap_or_default(),
622 snapshot,
623 auth_snapshot,
624 },
625 };
626
627 let ledger_info = ledger_info.unwrap_or_else(default_ledger_info);
628 env.ledger().set(ledger_info);
629
630 env
631 }
632
633 /// Returns the resources metered during the last top level contract
634 /// invocation.
635 ///
636 /// In order to get non-`None` results, `enable_invocation_metering` has to
637 /// be called and at least one invocation has to happen after that.
638 ///
639 /// Take the return value with a grain of salt. The returned resources mostly
640 /// correspond only to the operations that have happened during the host
641 /// invocation, i.e. this won't try to simulate the work that happens in
642 /// production scenarios (e.g. certain XDR rountrips). This also doesn't try
643 /// to model resources related to the transaction size.
644 ///
645 /// The returned value is as useful as the preceding setup, e.g. if a test
646 /// contract is used instead of a Wasm contract, all the costs related to
647 /// VM instantiation and execution, as well as Wasm reads/rent bumps will be
648 /// missed.
649 ///
650 /// While the resource metering may be useful for contract optimization,
651 /// keep in mind that resource and fee estimation may be imprecise. Use
652 /// simulation with RPC in order to get the exact resources for submitting
653 /// the transactions to the network.
654 pub fn cost_estimate(&self) -> CostEstimate {
655 CostEstimate::new(self.clone())
656 }
657
658 /// Register a contract with the [Env] for testing.
659 ///
660 /// Pass the contract type when the contract is defined in the current crate
661 /// and is being registered natively. Pass the contract wasm bytes when the
662 /// contract has been loaded as wasm.
663 ///
664 /// Pass the arguments for the contract's constructor, or `()` if none. For
665 /// contracts with a constructor, use the contract's generated `Args` type
666 /// to construct the arguments with the appropropriate types for invoking
667 /// the constructor during registration.
668 ///
669 /// Returns the address of the registered contract that is the same as the
670 /// contract id passed in.
671 ///
672 /// If you need to specify the address the contract should be registered at,
673 /// use [`Env::register_at`].
674 ///
675 /// ### Examples
676 /// Register a contract defined in the current crate, by specifying the type
677 /// name:
678 /// ```
679 /// use soroban_sdk::{contract, contractimpl, testutils::Address as _, Address, BytesN, Env, Symbol};
680 ///
681 /// #[contract]
682 /// pub struct Contract;
683 ///
684 /// #[contractimpl]
685 /// impl Contract {
686 /// pub fn __constructor(_env: Env, _input: u32) {
687 /// }
688 /// }
689 ///
690 /// #[test]
691 /// fn test() {
692 /// # }
693 /// # fn main() {
694 /// let env = Env::default();
695 /// let contract_id = env.register(Contract, ContractArgs::__constructor(&123,));
696 /// }
697 /// ```
698 /// Register a contract wasm, by specifying the wasm bytes:
699 /// ```
700 /// use soroban_sdk::{testutils::Address as _, Address, BytesN, Env};
701 ///
702 /// const WASM: &[u8] = include_bytes!("../doctest_fixtures/contract.wasm");
703 ///
704 /// #[test]
705 /// fn test() {
706 /// # }
707 /// # fn main() {
708 /// let env = Env::default();
709 /// let contract_id = env.register(WASM, ());
710 /// }
711 /// ```
712 pub fn register<'a, C, A>(&self, contract: C, constructor_args: A) -> Address
713 where
714 C: Register,
715 A: ConstructorArgs,
716 {
717 contract.register(self, None, constructor_args)
718 }
719
720 /// Register a contract with the [Env] for testing.
721 ///
722 /// Passing a contract ID for the first arguments registers the contract
723 /// with that contract ID.
724 ///
725 /// Registering a contract that is already registered replaces it.
726 /// Use re-registration with caution as it does not exist in the real
727 /// (on-chain) environment. Specifically, the new contract's constructor
728 /// will be called again during re-registration. That behavior only exists
729 /// for this test utility and is not reproducible on-chain, where contract
730 /// Wasm updates don't cause constructor to be called.
731 ///
732 /// Pass the contract type when the contract is defined in the current crate
733 /// and is being registered natively. Pass the contract wasm bytes when the
734 /// contract has been loaded as wasm.
735 ///
736 /// Returns the address of the registered contract that is the same as the
737 /// contract id passed in.
738 ///
739 /// ### Examples
740 /// Register a contract defined in the current crate, by specifying the type
741 /// name:
742 /// ```
743 /// use soroban_sdk::{contract, contractimpl, testutils::Address as _, Address, BytesN, Env, Symbol};
744 ///
745 /// #[contract]
746 /// pub struct Contract;
747 ///
748 /// #[contractimpl]
749 /// impl Contract {
750 /// pub fn __constructor(_env: Env, _input: u32) {
751 /// }
752 /// }
753 ///
754 /// #[test]
755 /// fn test() {
756 /// # }
757 /// # fn main() {
758 /// let env = Env::default();
759 /// let contract_id = Address::generate(&env);
760 /// env.register_at(&contract_id, Contract, (123_u32,));
761 /// }
762 /// ```
763 /// Register a contract wasm, by specifying the wasm bytes:
764 /// ```
765 /// use soroban_sdk::{testutils::Address as _, Address, BytesN, Env};
766 ///
767 /// const WASM: &[u8] = include_bytes!("../doctest_fixtures/contract.wasm");
768 ///
769 /// #[test]
770 /// fn test() {
771 /// # }
772 /// # fn main() {
773 /// let env = Env::default();
774 /// let contract_id = Address::generate(&env);
775 /// env.register_at(&contract_id, WASM, ());
776 /// }
777 /// ```
778 pub fn register_at<C, A>(
779 &self,
780 contract_id: &Address,
781 contract: C,
782 constructor_args: A,
783 ) -> Address
784 where
785 C: Register,
786 A: ConstructorArgs,
787 {
788 contract.register(self, contract_id, constructor_args)
789 }
790
791 /// Register a contract with the [Env] for testing.
792 ///
793 /// Passing a contract ID for the first arguments registers the contract
794 /// with that contract ID. Providing `None` causes the Env to generate a new
795 /// contract ID that is assigned to the contract.
796 ///
797 /// If a contract has a constructor defined, then it will be called with
798 /// no arguments. If a constructor takes arguments, use `register`.
799 ///
800 /// Registering a contract that is already registered replaces it.
801 /// Use re-registration with caution as it does not exist in the real
802 /// (on-chain) environment. Specifically, the new contract's constructor
803 /// will be called again during re-registration. That behavior only exists
804 /// for this test utility and is not reproducible on-chain, where contract
805 /// Wasm updates don't cause constructor to be called.
806 ///
807 /// Returns the address of the registered contract.
808 ///
809 /// ### Examples
810 /// ```
811 /// use soroban_sdk::{contract, contractimpl, BytesN, Env, Symbol};
812 ///
813 /// #[contract]
814 /// pub struct HelloContract;
815 ///
816 /// #[contractimpl]
817 /// impl HelloContract {
818 /// pub fn hello(env: Env, recipient: Symbol) -> Symbol {
819 /// todo!()
820 /// }
821 /// }
822 ///
823 /// #[test]
824 /// fn test() {
825 /// # }
826 /// # fn main() {
827 /// let env = Env::default();
828 /// let contract_id = env.register_contract(None, HelloContract);
829 /// }
830 /// ```
831 #[deprecated(note = "use `register`")]
832 pub fn register_contract<'a, T: ContractFunctionSet + 'static>(
833 &self,
834 contract_id: impl Into<Option<&'a Address>>,
835 contract: T,
836 ) -> Address {
837 self.register_contract_with_constructor(contract_id, contract, ())
838 }
839
840 /// Register a contract with the [Env] for testing.
841 ///
842 /// This acts the in the same fashion as `register_contract`, but allows
843 /// passing arguments to the contract's constructor.
844 ///
845 /// Passing a contract ID for the first arguments registers the contract
846 /// with that contract ID. Providing `None` causes the Env to generate a new
847 /// contract ID that is assigned to the contract.
848 ///
849 /// Registering a contract that is already registered replaces it.
850 /// Use re-registration with caution as it does not exist in the real
851 /// (on-chain) environment. Specifically, the new contract's constructor
852 /// will be called again during re-registration. That behavior only exists
853 /// for this test utility and is not reproducible on-chain, where contract
854 /// Wasm updates don't cause constructor to be called.
855 ///
856 /// Returns the address of the registered contract.
857 pub(crate) fn register_contract_with_constructor<
858 'a,
859 T: ContractFunctionSet + 'static,
860 A: ConstructorArgs,
861 >(
862 &self,
863 contract_id: impl Into<Option<&'a Address>>,
864 contract: T,
865 constructor_args: A,
866 ) -> Address {
867 struct InternalContractFunctionSet<T: ContractFunctionSet>(pub(crate) T);
868 impl<T: ContractFunctionSet> internal::ContractFunctionSet for InternalContractFunctionSet<T> {
869 fn call(
870 &self,
871 func: &Symbol,
872 env_impl: &internal::EnvImpl,
873 args: &[Val],
874 ) -> Option<Val> {
875 let env = Env {
876 env_impl: env_impl.clone(),
877 test_state: Default::default(),
878 };
879 self.0.call(
880 crate::Symbol::try_from_val(&env, func)
881 .unwrap_infallible()
882 .to_string()
883 .as_str(),
884 env,
885 args,
886 )
887 }
888 }
889
890 let contract_id = if let Some(contract_id) = contract_id.into() {
891 contract_id.clone()
892 } else {
893 Address::generate(self)
894 };
895 self.env_impl
896 .register_test_contract_with_constructor(
897 contract_id.to_object(),
898 Rc::new(InternalContractFunctionSet(contract)),
899 constructor_args.into_val(self).to_object(),
900 )
901 .unwrap();
902 contract_id
903 }
904
905 /// Register a contract in a Wasm file with the [Env] for testing.
906 ///
907 /// Passing a contract ID for the first arguments registers the contract
908 /// with that contract ID. Providing `None` causes the Env to generate a new
909 /// contract ID that is assigned to the contract.
910 ///
911 /// Registering a contract that is already registered replaces it.
912 /// Use re-registration with caution as it does not exist in the real
913 /// (on-chain) environment. Specifically, the new contract's constructor
914 /// will be called again during re-registration. That behavior only exists
915 /// for this test utility and is not reproducible on-chain, where contract
916 /// Wasm updates don't cause constructor to be called.
917 ///
918 /// Returns the address of the registered contract.
919 ///
920 /// ### Examples
921 /// ```
922 /// use soroban_sdk::{BytesN, Env};
923 ///
924 /// const WASM: &[u8] = include_bytes!("../doctest_fixtures/contract.wasm");
925 ///
926 /// #[test]
927 /// fn test() {
928 /// # }
929 /// # fn main() {
930 /// let env = Env::default();
931 /// env.register_contract_wasm(None, WASM);
932 /// }
933 /// ```
934 #[deprecated(note = "use `register`")]
935 pub fn register_contract_wasm<'a>(
936 &self,
937 contract_id: impl Into<Option<&'a Address>>,
938 contract_wasm: impl IntoVal<Env, Bytes>,
939 ) -> Address {
940 let wasm_hash: BytesN<32> = self.deployer().upload_contract_wasm(contract_wasm);
941 self.register_contract_with_optional_contract_id_and_executable(
942 contract_id,
943 xdr::ContractExecutable::Wasm(xdr::Hash(wasm_hash.into())),
944 crate::vec![&self],
945 )
946 }
947
948 /// Register a contract in a Wasm file with the [Env] for testing.
949 ///
950 /// This acts the in the same fashion as `register_contract`, but allows
951 /// passing arguments to the contract's constructor.
952 ///
953 /// Passing a contract ID for the first arguments registers the contract
954 /// with that contract ID. Providing `None` causes the Env to generate a new
955 /// contract ID that is assigned to the contract.
956 ///
957 /// Registering a contract that is already registered replaces it.
958 /// Use re-registration with caution as it does not exist in the real
959 /// (on-chain) environment. Specifically, the new contract's constructor
960 /// will be called again during re-registration. That behavior only exists
961 /// for this test utility and is not reproducible on-chain, where contract
962 /// Wasm updates don't cause constructor to be called.
963 ///
964 /// Returns the address of the registered contract.
965 pub(crate) fn register_contract_wasm_with_constructor<'a>(
966 &self,
967 contract_id: impl Into<Option<&'a Address>>,
968 contract_wasm: impl IntoVal<Env, Bytes>,
969 constructor_args: impl ConstructorArgs,
970 ) -> Address {
971 let wasm_hash: BytesN<32> = self.deployer().upload_contract_wasm(contract_wasm);
972 self.register_contract_with_optional_contract_id_and_executable(
973 contract_id,
974 xdr::ContractExecutable::Wasm(xdr::Hash(wasm_hash.into())),
975 constructor_args.into_val(self),
976 )
977 }
978
979 /// Register the built-in Stellar Asset Contract with provided admin address.
980 ///
981 /// Returns a utility struct that contains the contract ID of the registered
982 /// token contract, as well as methods to read and update issuer flags.
983 ///
984 /// The contract will wrap a randomly-generated Stellar asset. This function
985 /// is useful for using in the tests when an arbitrary token contract
986 /// instance is needed.
987 pub fn register_stellar_asset_contract_v2(&self, admin: Address) -> StellarAssetContract {
988 let issuer_pk = self.with_generator(|mut g| g.address());
989 let issuer_id = xdr::AccountId(xdr::PublicKey::PublicKeyTypeEd25519(xdr::Uint256(
990 issuer_pk.clone(),
991 )));
992
993 let k = Rc::new(xdr::LedgerKey::Account(xdr::LedgerKeyAccount {
994 account_id: issuer_id.clone(),
995 }));
996
997 if self.host().get_ledger_entry(&k).unwrap().is_none() {
998 let v = Rc::new(xdr::LedgerEntry {
999 data: xdr::LedgerEntryData::Account(xdr::AccountEntry {
1000 account_id: issuer_id.clone(),
1001 balance: 0,
1002 flags: 0,
1003 home_domain: Default::default(),
1004 inflation_dest: None,
1005 num_sub_entries: 0,
1006 seq_num: xdr::SequenceNumber(0),
1007 thresholds: xdr::Thresholds([1; 4]),
1008 signers: xdr::VecM::default(),
1009 ext: xdr::AccountEntryExt::V0,
1010 }),
1011 last_modified_ledger_seq: 0,
1012 ext: xdr::LedgerEntryExt::V0,
1013 });
1014 self.host().add_ledger_entry(&k, &v, None).unwrap();
1015 }
1016
1017 let asset = xdr::Asset::CreditAlphanum4(xdr::AlphaNum4 {
1018 asset_code: xdr::AssetCode4([b'a', b'a', b'a', 0]),
1019 issuer: issuer_id.clone(),
1020 });
1021 let create = xdr::HostFunction::CreateContract(xdr::CreateContractArgs {
1022 contract_id_preimage: xdr::ContractIdPreimage::Asset(asset.clone()),
1023 executable: xdr::ContractExecutable::StellarAsset,
1024 });
1025
1026 let token_id: Address = self
1027 .env_impl
1028 .invoke_function(create)
1029 .unwrap()
1030 .try_into_val(self)
1031 .unwrap();
1032
1033 let prev_auth_manager = self.env_impl.snapshot_auth_manager().unwrap();
1034 self.env_impl
1035 .switch_to_recording_auth_inherited_from_snapshot(&prev_auth_manager)
1036 .unwrap();
1037 self.invoke_contract::<()>(
1038 &token_id,
1039 &soroban_sdk_macros::internal_symbol_short!("set_admin"),
1040 (admin,).try_into_val(self).unwrap(),
1041 );
1042 self.env_impl.set_auth_manager(prev_auth_manager).unwrap();
1043
1044 let issuer = StellarAssetIssuer::new(self.clone(), issuer_id);
1045
1046 StellarAssetContract::new(token_id, issuer, asset)
1047 }
1048
1049 /// Register the built-in Stellar Asset Contract with provided admin address.
1050 ///
1051 /// Returns the contract ID of the registered token contract.
1052 ///
1053 /// The contract will wrap a randomly-generated Stellar asset. This function
1054 /// is useful for using in the tests when an arbitrary token contract
1055 /// instance is needed.
1056 #[deprecated(note = "use [Env::register_stellar_asset_contract_v2]")]
1057 pub fn register_stellar_asset_contract(&self, admin: Address) -> Address {
1058 self.register_stellar_asset_contract_v2(admin).address()
1059 }
1060
1061 fn register_contract_with_optional_contract_id_and_executable<'a>(
1062 &self,
1063 contract_id: impl Into<Option<&'a Address>>,
1064 executable: xdr::ContractExecutable,
1065 constructor_args: Vec<Val>,
1066 ) -> Address {
1067 if let Some(contract_id) = contract_id.into() {
1068 self.register_contract_with_contract_id_and_executable(
1069 contract_id,
1070 executable,
1071 constructor_args,
1072 );
1073 contract_id.clone()
1074 } else {
1075 self.register_contract_with_source(executable, constructor_args)
1076 }
1077 }
1078
1079 fn register_contract_with_source(
1080 &self,
1081 executable: xdr::ContractExecutable,
1082 constructor_args: Vec<Val>,
1083 ) -> Address {
1084 let prev_auth_manager = self.env_impl.snapshot_auth_manager().unwrap();
1085 self.env_impl
1086 .switch_to_recording_auth_inherited_from_snapshot(&prev_auth_manager)
1087 .unwrap();
1088 let args_vec: std::vec::Vec<xdr::ScVal> =
1089 constructor_args.iter().map(|v| v.into_val(self)).collect();
1090 let contract_id: Address = self
1091 .env_impl
1092 .invoke_function(xdr::HostFunction::CreateContractV2(
1093 xdr::CreateContractArgsV2 {
1094 contract_id_preimage: xdr::ContractIdPreimage::Address(
1095 xdr::ContractIdPreimageFromAddress {
1096 address: xdr::ScAddress::Contract(xdr::ContractId(xdr::Hash(
1097 self.with_generator(|mut g| g.address()),
1098 ))),
1099 salt: xdr::Uint256([0; 32]),
1100 },
1101 ),
1102 executable,
1103 constructor_args: args_vec.try_into().unwrap(),
1104 },
1105 ))
1106 .unwrap()
1107 .try_into_val(self)
1108 .unwrap();
1109
1110 self.env_impl.set_auth_manager(prev_auth_manager).unwrap();
1111
1112 contract_id
1113 }
1114
1115 /// Set authorizations and signatures in the environment which will be
1116 /// consumed by contracts when they invoke [`Address::require_auth`] or
1117 /// [`Address::require_auth_for_args`] functions.
1118 ///
1119 /// Requires valid signatures for the authorization to be successful.
1120 ///
1121 /// This function can also be called on contract clients.
1122 ///
1123 /// To mock auth for testing, without requiring valid signatures, use
1124 /// [`mock_all_auths`][Self::mock_all_auths] or
1125 /// [`mock_auths`][Self::mock_auths]. If mocking of auths is enabled,
1126 /// calling [`set_auths`][Self::set_auths] disables any mocking.
1127 pub fn set_auths(&self, auths: &[SorobanAuthorizationEntry]) {
1128 self.env_impl
1129 .set_authorization_entries(auths.to_vec())
1130 .unwrap();
1131 }
1132
1133 /// Mock authorizations in the environment which will cause matching invokes
1134 /// of [`Address::require_auth`] and [`Address::require_auth_for_args`] to
1135 /// pass.
1136 ///
1137 /// This function can also be called on contract clients.
1138 ///
1139 /// Authorizations not matching a mocked auth will fail.
1140 ///
1141 /// To mock all auths, use [`mock_all_auths`][Self::mock_all_auths].
1142 ///
1143 /// ### Examples
1144 /// ```
1145 /// use soroban_sdk::{contract, contractimpl, Env, Address, testutils::{Address as _, MockAuth, MockAuthInvoke}, IntoVal};
1146 ///
1147 /// #[contract]
1148 /// pub struct HelloContract;
1149 ///
1150 /// #[contractimpl]
1151 /// impl HelloContract {
1152 /// pub fn hello(env: Env, from: Address) {
1153 /// from.require_auth();
1154 /// // TODO
1155 /// }
1156 /// }
1157 ///
1158 /// #[test]
1159 /// fn test() {
1160 /// # }
1161 /// # fn main() {
1162 /// let env = Env::default();
1163 /// let contract_id = env.register(HelloContract, ());
1164 ///
1165 /// let client = HelloContractClient::new(&env, &contract_id);
1166 /// let addr = Address::generate(&env);
1167 /// client.mock_auths(&[
1168 /// MockAuth {
1169 /// address: &addr,
1170 /// invoke: &MockAuthInvoke {
1171 /// contract: &contract_id,
1172 /// fn_name: "hello",
1173 /// args: (&addr,).into_val(&env),
1174 /// sub_invokes: &[],
1175 /// },
1176 /// },
1177 /// ]).hello(&addr);
1178 /// }
1179 /// ```
1180 pub fn mock_auths(&self, auths: &[MockAuth]) {
1181 for a in auths {
1182 self.register_at(a.address, MockAuthContract, ());
1183 }
1184 let auths = auths
1185 .iter()
1186 .cloned()
1187 .map(Into::into)
1188 .collect::<std::vec::Vec<_>>();
1189 self.env_impl.set_authorization_entries(auths).unwrap();
1190 }
1191
1192 /// Mock all calls to the [`Address::require_auth`] and
1193 /// [`Address::require_auth_for_args`] functions in invoked contracts,
1194 /// having them succeed as if authorization was provided.
1195 ///
1196 /// When mocking is enabled, if the [`Address`] being authorized is the
1197 /// address of a contract, that contract's `__check_auth` function will not
1198 /// be called, and the contract does not need to exist or be registered in
1199 /// the test.
1200 ///
1201 /// When mocking is enabled, if the [`Address`] being authorized is the
1202 /// address of an account, the account does not need to exist.
1203 ///
1204 /// This function can also be called on contract clients.
1205 ///
1206 /// To disable mocking, see [`set_auths`][Self::set_auths].
1207 ///
1208 /// To access a list of auths that have occurred, see [`auths`][Self::auths].
1209 ///
1210 /// It is not currently possible to mock a subset of auths.
1211 ///
1212 /// ### Examples
1213 /// ```
1214 /// use soroban_sdk::{contract, contractimpl, Env, Address, testutils::Address as _};
1215 ///
1216 /// #[contract]
1217 /// pub struct HelloContract;
1218 ///
1219 /// #[contractimpl]
1220 /// impl HelloContract {
1221 /// pub fn hello(env: Env, from: Address) {
1222 /// from.require_auth();
1223 /// // TODO
1224 /// }
1225 /// }
1226 ///
1227 /// #[test]
1228 /// fn test() {
1229 /// # }
1230 /// # fn main() {
1231 /// let env = Env::default();
1232 /// let contract_id = env.register(HelloContract, ());
1233 ///
1234 /// env.mock_all_auths();
1235 ///
1236 /// let client = HelloContractClient::new(&env, &contract_id);
1237 /// let addr = Address::generate(&env);
1238 /// client.hello(&addr);
1239 /// }
1240 /// ```
1241 pub fn mock_all_auths(&self) {
1242 self.env_impl.switch_to_recording_auth(true).unwrap();
1243 }
1244
1245 /// A version of `mock_all_auths` that allows authorizations that are not
1246 /// present in the root invocation.
1247 ///
1248 /// Refer to `mock_all_auths` documentation for general information and
1249 /// prefer using `mock_all_auths` unless non-root authorization is required.
1250 ///
1251 /// The only difference from `mock_all_auths` is that this won't return an
1252 /// error when `require_auth` hasn't been called in the root invocation for
1253 /// any given address. This is useful to test contracts that bundle calls to
1254 /// another contract without atomicity requirements (i.e. any contract call
1255 /// can be frontrun).
1256 ///
1257 /// ### Examples
1258 /// ```
1259 /// use soroban_sdk::{contract, contractimpl, Env, Address, testutils::Address as _};
1260 ///
1261 /// #[contract]
1262 /// pub struct ContractA;
1263 ///
1264 /// #[contractimpl]
1265 /// impl ContractA {
1266 /// pub fn do_auth(env: Env, addr: Address) {
1267 /// addr.require_auth();
1268 /// }
1269 /// }
1270 /// #[contract]
1271 /// pub struct ContractB;
1272 ///
1273 /// #[contractimpl]
1274 /// impl ContractB {
1275 /// pub fn call_a(env: Env, contract_a: Address, addr: Address) {
1276 /// // Notice there is no `require_auth` call here.
1277 /// ContractAClient::new(&env, &contract_a).do_auth(&addr);
1278 /// }
1279 /// }
1280 /// #[test]
1281 /// fn test() {
1282 /// # }
1283 /// # fn main() {
1284 /// let env = Env::default();
1285 /// let contract_a = env.register(ContractA, ());
1286 /// let contract_b = env.register(ContractB, ());
1287 /// // The regular `env.mock_all_auths()` would result in the call
1288 /// // failure.
1289 /// env.mock_all_auths_allowing_non_root_auth();
1290 ///
1291 /// let client = ContractBClient::new(&env, &contract_b);
1292 /// let addr = Address::generate(&env);
1293 /// client.call_a(&contract_a, &addr);
1294 /// }
1295 /// ```
1296 pub fn mock_all_auths_allowing_non_root_auth(&self) {
1297 self.env_impl.switch_to_recording_auth(false).unwrap();
1298 }
1299
1300 /// Returns a list of authorization trees that were seen during the last
1301 /// contract or authorized host function invocation.
1302 ///
1303 /// Use this in tests to verify that the expected authorizations with the
1304 /// expected arguments are required.
1305 ///
1306 /// The return value is a vector of authorizations represented by tuples of
1307 /// `(address, AuthorizedInvocation)`. `AuthorizedInvocation` describes the
1308 /// tree of `require_auth_for_args(address, args)` from the contract
1309 /// functions (or `require_auth` with all the arguments of the function
1310 /// invocation). It also might contain the authorized host functions (
1311 /// currently CreateContract is the only such function) in case if
1312 /// corresponding host functions have been called.
1313 ///
1314 /// Refer to documentation for `AuthorizedInvocation` for detailed
1315 /// information on its contents.
1316 ///
1317 /// The order of the returned vector is defined by the order of
1318 /// [`Address::require_auth`] calls. Repeated calls to
1319 /// [`Address::require_auth`] with the same address and args in the same
1320 /// tree of contract invocations will appear only once in the vector.
1321 ///
1322 /// ### Examples
1323 /// ```
1324 /// use soroban_sdk::{contract, contractimpl, testutils::{Address as _, AuthorizedFunction, AuthorizedInvocation}, symbol_short, Address, Symbol, Env, IntoVal};
1325 ///
1326 /// #[contract]
1327 /// pub struct Contract;
1328 ///
1329 /// #[contractimpl]
1330 /// impl Contract {
1331 /// pub fn transfer(env: Env, address: Address, amount: i128) {
1332 /// address.require_auth();
1333 /// }
1334 /// pub fn transfer2(env: Env, address: Address, amount: i128) {
1335 /// address.require_auth_for_args((amount / 2,).into_val(&env));
1336 /// }
1337 /// }
1338 ///
1339 /// #[test]
1340 /// fn test() {
1341 /// # }
1342 /// # #[cfg(feature = "testutils")]
1343 /// # fn main() {
1344 /// extern crate std;
1345 /// let env = Env::default();
1346 /// let contract_id = env.register(Contract, ());
1347 /// let client = ContractClient::new(&env, &contract_id);
1348 /// env.mock_all_auths();
1349 /// let address = Address::generate(&env);
1350 /// client.transfer(&address, &1000_i128);
1351 /// assert_eq!(
1352 /// env.auths(),
1353 /// std::vec![(
1354 /// address.clone(),
1355 /// AuthorizedInvocation {
1356 /// function: AuthorizedFunction::Contract((
1357 /// client.address.clone(),
1358 /// symbol_short!("transfer"),
1359 /// (&address, 1000_i128,).into_val(&env)
1360 /// )),
1361 /// sub_invocations: std::vec![]
1362 /// }
1363 /// )]
1364 /// );
1365 ///
1366 /// client.transfer2(&address, &1000_i128);
1367 /// assert_eq!(
1368 /// env.auths(),
1369 /// std::vec![(
1370 /// address.clone(),
1371 /// AuthorizedInvocation {
1372 /// function: AuthorizedFunction::Contract((
1373 /// client.address.clone(),
1374 /// symbol_short!("transfer2"),
1375 /// // `transfer2` requires auth for (amount / 2) == (1000 / 2) == 500.
1376 /// (500_i128,).into_val(&env)
1377 /// )),
1378 /// sub_invocations: std::vec![]
1379 /// }
1380 /// )]
1381 /// );
1382 /// }
1383 /// # #[cfg(not(feature = "testutils"))]
1384 /// # fn main() { }
1385 /// ```
1386 pub fn auths(&self) -> std::vec::Vec<(Address, AuthorizedInvocation)> {
1387 (*self.test_state.auth_snapshot)
1388 .borrow()
1389 .0
1390 .last()
1391 .cloned()
1392 .unwrap_or_default()
1393 .into_iter()
1394 .map(|(sc_addr, invocation)| {
1395 (
1396 xdr::ScVal::Address(sc_addr).try_into_val(self).unwrap(),
1397 AuthorizedInvocation::from_xdr(self, &invocation),
1398 )
1399 })
1400 .collect()
1401 }
1402
1403 /// Invokes the special `__check_auth` function of contracts that implement
1404 /// the custom account interface.
1405 ///
1406 /// `__check_auth` can't be called outside of the host-managed `require_auth`
1407 /// calls. This test utility allows testing custom account contracts without
1408 /// the need to setup complex contract call trees and enabling the enforcing
1409 /// auth on the host side.
1410 ///
1411 /// This function requires to provide the template argument for error. Use
1412 /// `soroban_sdk::Error` if `__check_auth` doesn't return a special
1413 /// contract error and use the error with `contracterror` attribute
1414 /// otherwise.
1415 ///
1416 /// ### Examples
1417 /// ```
1418 /// use soroban_sdk::{contract, contracterror, contractimpl, testutils::{Address as _, BytesN as _}, vec, auth::Context, BytesN, Env, Vec, Val};
1419 ///
1420 /// #[contracterror]
1421 /// #[derive(Copy, Clone, Debug, Eq, PartialEq, PartialOrd, Ord)]
1422 /// #[repr(u32)]
1423 /// pub enum NoopAccountError {
1424 /// SomeError = 1,
1425 /// }
1426 /// #[contract]
1427 /// struct NoopAccountContract;
1428 /// #[contractimpl]
1429 /// impl NoopAccountContract {
1430 ///
1431 /// #[allow(non_snake_case)]
1432 /// pub fn __check_auth(
1433 /// _env: Env,
1434 /// _signature_payload: BytesN<32>,
1435 /// signature: Val,
1436 /// _auth_context: Vec<Context>,
1437 /// ) -> Result<(), NoopAccountError> {
1438 /// if signature.is_void() {
1439 /// Err(NoopAccountError::SomeError)
1440 /// } else {
1441 /// Ok(())
1442 /// }
1443 /// }
1444 /// }
1445 /// #[test]
1446 /// fn test() {
1447 /// # }
1448 /// # fn main() {
1449 /// let e: Env = Default::default();
1450 /// let account_contract = NoopAccountContractClient::new(&e, &e.register(NoopAccountContract, ()));
1451 /// // Non-succesful call of `__check_auth` with a `contracterror` error.
1452 /// assert_eq!(
1453 /// e.try_invoke_contract_check_auth::<NoopAccountError>(
1454 /// &account_contract.address,
1455 /// &BytesN::from_array(&e, &[0; 32]),
1456 /// ().into(),
1457 /// &vec![&e],
1458 /// ),
1459 /// // The inner `Result` is for conversion error and will be Ok
1460 /// // as long as a valid error type used.
1461 /// Err(Ok(NoopAccountError::SomeError))
1462 /// );
1463 /// // Successful call of `__check_auth` with a `soroban_sdk::InvokeError`
1464 /// // error - this should be compatible with any error type.
1465 /// assert_eq!(
1466 /// e.try_invoke_contract_check_auth::<soroban_sdk::InvokeError>(
1467 /// &account_contract.address,
1468 /// &BytesN::from_array(&e, &[0; 32]),
1469 /// 0_i32.into(),
1470 /// &vec![&e],
1471 /// ),
1472 /// Ok(())
1473 /// );
1474 /// }
1475 /// ```
1476 pub fn try_invoke_contract_check_auth<E>(
1477 &self,
1478 contract: &Address,
1479 signature_payload: &BytesN<32>,
1480 signature: Val,
1481 auth_context: &Vec<auth::Context>,
1482 ) -> Result<(), Result<E, InvokeError>>
1483 where
1484 E: TryFrom<Error>,
1485 E::Error: Into<InvokeError>,
1486 {
1487 let args = Vec::from_array(
1488 self,
1489 [signature_payload.to_val(), signature, auth_context.to_val()],
1490 );
1491 let res = self
1492 .host()
1493 .call_account_contract_check_auth(contract.to_object(), args.to_object());
1494 match res {
1495 Ok(rv) => Ok(rv.into_val(self)),
1496 Err(e) => Err(e.error.try_into().map_err(Into::into)),
1497 }
1498 }
1499
1500 fn register_contract_with_contract_id_and_executable(
1501 &self,
1502 contract_address: &Address,
1503 executable: xdr::ContractExecutable,
1504 constructor_args: Vec<Val>,
1505 ) {
1506 let contract_id = contract_address.contract_id();
1507 let data_key = xdr::ScVal::LedgerKeyContractInstance;
1508 let key = Rc::new(LedgerKey::ContractData(LedgerKeyContractData {
1509 contract: xdr::ScAddress::Contract(contract_id.clone()),
1510 key: data_key.clone(),
1511 durability: xdr::ContractDataDurability::Persistent,
1512 }));
1513
1514 let instance = xdr::ScContractInstance {
1515 executable,
1516 storage: Default::default(),
1517 };
1518
1519 let entry = Rc::new(LedgerEntry {
1520 ext: xdr::LedgerEntryExt::V0,
1521 last_modified_ledger_seq: 0,
1522 data: xdr::LedgerEntryData::ContractData(xdr::ContractDataEntry {
1523 contract: xdr::ScAddress::Contract(contract_id.clone()),
1524 key: data_key,
1525 val: xdr::ScVal::ContractInstance(instance),
1526 durability: xdr::ContractDataDurability::Persistent,
1527 ext: xdr::ExtensionPoint::V0,
1528 }),
1529 });
1530 let live_until_ledger = self.ledger().sequence() + 1;
1531 self.host()
1532 .add_ledger_entry(&key, &entry, Some(live_until_ledger))
1533 .unwrap();
1534 self.env_impl
1535 .call_constructor_for_stored_contract_unsafe(&contract_id, constructor_args.to_object())
1536 .unwrap();
1537 }
1538
1539 /// Run the function as if executed by the given contract ID.
1540 ///
1541 /// Used to write or read contract data, or take other actions in tests for
1542 /// setting up tests or asserting on internal state.
1543 pub fn as_contract<T>(&self, id: &Address, f: impl FnOnce() -> T) -> T {
1544 let id = id.contract_id();
1545 let func = Symbol::from_small_str("");
1546 let mut t: Option<T> = None;
1547 self.env_impl
1548 .with_test_contract_frame(id, func, || {
1549 t = Some(f());
1550 Ok(().into())
1551 })
1552 .unwrap();
1553 t.unwrap()
1554 }
1555
1556 /// Creates a new Env loaded with the [`Snapshot`].
1557 ///
1558 /// The ledger info and state in the snapshot are loaded into the Env.
1559 ///
1560 /// Events, as an output source only, are not loaded into the Env.
1561 pub fn from_snapshot(s: Snapshot) -> Env {
1562 Env::new_for_testutils(
1563 EnvTestConfig::default(),
1564 Rc::new(s.ledger.clone()),
1565 Some(Rc::new(RefCell::new(s.generators))),
1566 Some(s.ledger.ledger_info()),
1567 Some(Rc::new(s.ledger.clone())),
1568 )
1569 }
1570
1571 /// Creates a new Env loaded with the ledger snapshot loaded from the file.
1572 ///
1573 /// The ledger info and state in the snapshot are loaded into the Env.
1574 ///
1575 /// Events, as an output source only, are not loaded into the Env.
1576 ///
1577 /// ### Panics
1578 ///
1579 /// If there is any error reading the file.
1580 pub fn from_snapshot_file(p: impl AsRef<Path>) -> Env {
1581 Self::from_snapshot(Snapshot::read_file(p).unwrap())
1582 }
1583
1584 /// Create a snapshot from the Env's current state.
1585 pub fn to_snapshot(&self) -> Snapshot {
1586 Snapshot {
1587 generators: (*self.test_state.generators).borrow().clone(),
1588 auth: (*self.test_state.auth_snapshot).borrow().clone(),
1589 ledger: self.to_ledger_snapshot(),
1590 events: self.to_events_snapshot(),
1591 }
1592 }
1593
1594 /// Create a snapshot file from the Env's current state.
1595 ///
1596 /// ### Panics
1597 ///
1598 /// If there is any error writing the file.
1599 pub fn to_snapshot_file(&self, p: impl AsRef<Path>) {
1600 self.to_snapshot().write_file(p).unwrap();
1601 }
1602
1603 /// Creates a new Env loaded with the [`LedgerSnapshot`].
1604 ///
1605 /// The ledger info and state in the snapshot are loaded into the Env.
1606 pub fn from_ledger_snapshot(s: LedgerSnapshot) -> Env {
1607 Env::new_for_testutils(
1608 EnvTestConfig::default(), // TODO: Allow setting the config.
1609 Rc::new(s.clone()),
1610 None,
1611 Some(s.ledger_info()),
1612 Some(Rc::new(s.clone())),
1613 )
1614 }
1615
1616 /// Creates a new Env loaded with the ledger snapshot loaded from the file.
1617 ///
1618 /// ### Panics
1619 ///
1620 /// If there is any error reading the file.
1621 pub fn from_ledger_snapshot_file(p: impl AsRef<Path>) -> Env {
1622 Self::from_ledger_snapshot(LedgerSnapshot::read_file(p).unwrap())
1623 }
1624
1625 /// Create a snapshot from the Env's current state.
1626 pub fn to_ledger_snapshot(&self) -> LedgerSnapshot {
1627 let snapshot = self.test_state.snapshot.clone().unwrap_or_default();
1628 let mut snapshot = (*snapshot).clone();
1629 snapshot.set_ledger_info(self.ledger().get());
1630 snapshot.update_entries(&self.host().get_stored_entries().unwrap());
1631 snapshot
1632 }
1633
1634 /// Create a snapshot file from the Env's current state.
1635 ///
1636 /// ### Panics
1637 ///
1638 /// If there is any error writing the file.
1639 pub fn to_ledger_snapshot_file(&self, p: impl AsRef<Path>) {
1640 self.to_ledger_snapshot().write_file(p).unwrap();
1641 }
1642
1643 /// Create an events snapshot from the Env's current state.
1644 pub(crate) fn to_events_snapshot(&self) -> EventsSnapshot {
1645 EventsSnapshot(
1646 self.host()
1647 .get_events()
1648 .unwrap()
1649 .0
1650 .into_iter()
1651 .filter(|e| match e.event.type_ {
1652 // Keep only system and contract events, because event
1653 // snapshots are used in test snapshots, and intended to be
1654 // stable over time because the goal is to record meaningful
1655 // observable behaviors. Diagnostic events are observable,
1656 // but events have no stability guarantees and are intended
1657 // to be used by developers when debugging, tracing, and
1658 // observing, not by systems that integrate.
1659 xdr::ContractEventType::System | xdr::ContractEventType::Contract => true,
1660 xdr::ContractEventType::Diagnostic => false,
1661 })
1662 .map(Into::into)
1663 .collect(),
1664 )
1665 }
1666
1667 /// Get the budget that tracks the resources consumed for the environment.
1668 #[deprecated(note = "use cost_estimate().budget()")]
1669 pub fn budget(&self) -> Budget {
1670 Budget::new(self.env_impl.budget_cloned())
1671 }
1672}
1673
1674#[cfg(any(test, feature = "testutils"))]
1675impl Drop for Env {
1676 fn drop(&mut self) {
1677 // If the env impl (Host) is finishable, that means this Env is the last
1678 // Env to hold a reference to the Host. The Env should only write a test
1679 // snapshot at that point when no other references to the host exist,
1680 // because it is only when there are no other references that the host
1681 // is being dropped.
1682 if self.env_impl.can_finish() && self.test_state.config.capture_snapshot_at_drop {
1683 self.to_test_snapshot_file();
1684 }
1685 }
1686}
1687
1688#[doc(hidden)]
1689#[cfg(any(test, feature = "testutils"))]
1690impl Env {
1691 /// Create a snapshot file for the currently executing test.
1692 ///
1693 /// Writes the file to the `test_snapshots/{test-name}.N.json` path where
1694 /// `N` is incremented for each unique `Env` in the test.
1695 ///
1696 /// Use to record the observable behavior of a test, and changes to that
1697 /// behavior over time. Commit the test snapshot file to version control and
1698 /// watch for changes in it on contract change, SDK upgrade, protocol
1699 /// upgrade, and other important events.
1700 ///
1701 /// No file will be created if the environment has no meaningful data such
1702 /// as stored entries or events.
1703 ///
1704 /// ### Panics
1705 ///
1706 /// If there is any error writing the file.
1707 pub(crate) fn to_test_snapshot_file(&self) {
1708 let snapshot = self.to_snapshot();
1709
1710 // Don't write a snapshot that has no data in it.
1711 if snapshot.ledger.entries().into_iter().count() == 0
1712 && snapshot.events.0.is_empty()
1713 && snapshot.auth.0.is_empty()
1714 {
1715 return;
1716 }
1717
1718 // Determine path to write test snapshots to.
1719 let Some(test_name) = &self.test_state.test_name else {
1720 // If there's no test name, we're not in a test context, so don't write snapshots.
1721 return;
1722 };
1723 let number = self.test_state.number;
1724 // Break up the test name into directories, using :: as the separator.
1725 // The :: module separator cannot be written into the filename because
1726 // some operating systems (e.g. Windows) do not allow the : character in
1727 // filenames.
1728 let test_name_path = test_name
1729 .split("::")
1730 .map(|p| std::path::Path::new(p).to_path_buf())
1731 .reduce(|p0, p1| p0.join(p1))
1732 .expect("test name to not be empty");
1733 let dir = std::path::Path::new("test_snapshots");
1734 let p = dir
1735 .join(&test_name_path)
1736 .with_extension(format!("{number}.json"));
1737
1738 // Write test snapshots to file.
1739 eprintln!("Writing test snapshot file for test {test_name:?} to {p:?}.");
1740 snapshot.write_file(p).unwrap();
1741 }
1742}
1743
1744#[doc(hidden)]
1745impl internal::EnvBase for Env {
1746 type Error = Infallible;
1747
1748 // This exists to allow code in conversion paths to upgrade an Error to an
1749 // Env::Error with some control granted to the underlying Env (and panic
1750 // paths kept out of the host). We delegate this to our env_impl and then,
1751 // since our own Error type is Infallible, immediately throw it into either
1752 // the env_impl's Error escalation path (if testing), or just plain panic.
1753 #[cfg(not(target_family = "wasm"))]
1754 fn error_from_error_val(&self, e: crate::Error) -> Self::Error {
1755 let host_err = self.env_impl.error_from_error_val(e);
1756 #[cfg(any(test, feature = "testutils"))]
1757 self.env_impl.escalate_error_to_panic(host_err);
1758 #[cfg(not(any(test, feature = "testutils")))]
1759 panic!("{:?}", host_err);
1760 }
1761
1762 // When targeting wasm we don't even need to do that, just delegate to
1763 // the Guest's impl, which calls core::arch::wasm32::unreachable.
1764 #[cfg(target_family = "wasm")]
1765 fn error_from_error_val(&self, e: crate::Error) -> Self::Error {
1766 self.env_impl.error_from_error_val(e)
1767 }
1768
1769 fn check_protocol_version_lower_bound(&self, v: u32) -> Result<(), Self::Error> {
1770 Ok(self
1771 .env_impl
1772 .check_protocol_version_lower_bound(v)
1773 .unwrap_optimized())
1774 }
1775
1776 fn check_protocol_version_upper_bound(&self, v: u32) -> Result<(), Self::Error> {
1777 Ok(self
1778 .env_impl
1779 .check_protocol_version_upper_bound(v)
1780 .unwrap_optimized())
1781 }
1782
1783 // Note: the function `escalate_error_to_panic` only exists _on the `Env`
1784 // trait_ when the feature `soroban-env-common/testutils` is enabled. This
1785 // is because the host wants to never have this function even _compiled in_
1786 // when building for production, as it might be accidentally called (we have
1787 // mistakenly done so with conversion and comparison traits in the past).
1788 //
1789 // As a result, we only implement it here (fairly meaninglessly) when we're
1790 // in `cfg(test)` (which enables `soroban-env-host/testutils` thus
1791 // `soroban-env-common/testutils`) or when we've had our own `testutils`
1792 // feature enabled (which does the same).
1793 //
1794 // See the `internal::reject_err` functions above for more detail about what
1795 // it actually does (when implemented for real, on the host). In this
1796 // not-very-serious impl, since `Self::Error` is `Infallible`, this instance
1797 // can never actually be called and so its body is just a trivial
1798 // transformation from one empty type to another, for Type System Reasons.
1799 #[cfg(any(test, feature = "testutils"))]
1800 fn escalate_error_to_panic(&self, e: Self::Error) -> ! {
1801 match e {}
1802 }
1803
1804 fn bytes_copy_from_slice(
1805 &self,
1806 b: BytesObject,
1807 b_pos: U32Val,
1808 slice: &[u8],
1809 ) -> Result<BytesObject, Self::Error> {
1810 Ok(self
1811 .env_impl
1812 .bytes_copy_from_slice(b, b_pos, slice)
1813 .unwrap_optimized())
1814 }
1815
1816 fn bytes_copy_to_slice(
1817 &self,
1818 b: BytesObject,
1819 b_pos: U32Val,
1820 slice: &mut [u8],
1821 ) -> Result<(), Self::Error> {
1822 Ok(self
1823 .env_impl
1824 .bytes_copy_to_slice(b, b_pos, slice)
1825 .unwrap_optimized())
1826 }
1827
1828 fn bytes_new_from_slice(&self, slice: &[u8]) -> Result<BytesObject, Self::Error> {
1829 Ok(self.env_impl.bytes_new_from_slice(slice).unwrap_optimized())
1830 }
1831
1832 fn log_from_slice(&self, msg: &str, args: &[Val]) -> Result<Void, Self::Error> {
1833 Ok(self.env_impl.log_from_slice(msg, args).unwrap_optimized())
1834 }
1835
1836 fn string_copy_to_slice(
1837 &self,
1838 b: StringObject,
1839 b_pos: U32Val,
1840 slice: &mut [u8],
1841 ) -> Result<(), Self::Error> {
1842 Ok(self
1843 .env_impl
1844 .string_copy_to_slice(b, b_pos, slice)
1845 .unwrap_optimized())
1846 }
1847
1848 fn symbol_copy_to_slice(
1849 &self,
1850 b: SymbolObject,
1851 b_pos: U32Val,
1852 mem: &mut [u8],
1853 ) -> Result<(), Self::Error> {
1854 Ok(self
1855 .env_impl
1856 .symbol_copy_to_slice(b, b_pos, mem)
1857 .unwrap_optimized())
1858 }
1859
1860 fn string_new_from_slice(&self, slice: &[u8]) -> Result<StringObject, Self::Error> {
1861 Ok(self
1862 .env_impl
1863 .string_new_from_slice(slice)
1864 .unwrap_optimized())
1865 }
1866
1867 fn symbol_new_from_slice(&self, slice: &[u8]) -> Result<SymbolObject, Self::Error> {
1868 Ok(self
1869 .env_impl
1870 .symbol_new_from_slice(slice)
1871 .unwrap_optimized())
1872 }
1873
1874 fn map_new_from_slices(&self, keys: &[&str], vals: &[Val]) -> Result<MapObject, Self::Error> {
1875 Ok(self
1876 .env_impl
1877 .map_new_from_slices(keys, vals)
1878 .unwrap_optimized())
1879 }
1880
1881 fn map_unpack_to_slice(
1882 &self,
1883 map: MapObject,
1884 keys: &[&str],
1885 vals: &mut [Val],
1886 ) -> Result<Void, Self::Error> {
1887 Ok(self
1888 .env_impl
1889 .map_unpack_to_slice(map, keys, vals)
1890 .unwrap_optimized())
1891 }
1892
1893 fn vec_new_from_slice(&self, vals: &[Val]) -> Result<VecObject, Self::Error> {
1894 Ok(self.env_impl.vec_new_from_slice(vals).unwrap_optimized())
1895 }
1896
1897 fn vec_unpack_to_slice(&self, vec: VecObject, vals: &mut [Val]) -> Result<Void, Self::Error> {
1898 Ok(self
1899 .env_impl
1900 .vec_unpack_to_slice(vec, vals)
1901 .unwrap_optimized())
1902 }
1903
1904 fn symbol_index_in_strs(&self, key: Symbol, strs: &[&str]) -> Result<U32Val, Self::Error> {
1905 Ok(self
1906 .env_impl
1907 .symbol_index_in_strs(key, strs)
1908 .unwrap_optimized())
1909 }
1910}
1911
1912///////////////////////////////////////////////////////////////////////////////
1913/// X-macro use: impl Env for SDK's Env
1914///////////////////////////////////////////////////////////////////////////////
1915
1916// This is a helper macro used only by impl_env_for_sdk below. It consumes a
1917// token-tree of the form:
1918//
1919// {fn $fn_id:ident $args:tt -> $ret:ty}
1920//
1921// and produces the the corresponding method definition to be used in the
1922// SDK's Env implementation of the Env (calling through to the corresponding
1923// guest or host implementation).
1924macro_rules! sdk_function_helper {
1925 {$mod_id:ident, fn $fn_id:ident($($arg:ident:$type:ty),*) -> $ret:ty}
1926 =>
1927 {
1928 fn $fn_id(&self, $($arg:$type),*) -> Result<$ret, Self::Error> {
1929 internal::reject_err(&self.env_impl, self.env_impl.$fn_id($($arg),*))
1930 }
1931 };
1932}
1933
1934// This is a callback macro that pattern-matches the token-tree passed by the
1935// x-macro (call_macro_with_all_host_functions) and produces a suite of
1936// forwarding-method definitions, which it places in the body of the declaration
1937// of the implementation of Env for the SDK's Env.
1938macro_rules! impl_env_for_sdk {
1939 {
1940 $(
1941 // This outer pattern matches a single 'mod' block of the token-tree
1942 // passed from the x-macro to this macro. It is embedded in a `$()*`
1943 // pattern-repetition matcher so that it will match all provided
1944 // 'mod' blocks provided.
1945 $(#[$mod_attr:meta])*
1946 mod $mod_id:ident $mod_str:literal
1947 {
1948 $(
1949 // This inner pattern matches a single function description
1950 // inside a 'mod' block in the token-tree passed from the
1951 // x-macro to this macro. It is embedded in a `$()*`
1952 // pattern-repetition matcher so that it will match all such
1953 // descriptions.
1954 $(#[$fn_attr:meta])*
1955 { $fn_str:literal, $($min_proto:literal)?, $($max_proto:literal)?, fn $fn_id:ident $args:tt -> $ret:ty }
1956 )*
1957 }
1958 )*
1959 }
1960
1961 => // The part of the macro above this line is a matcher; below is its expansion.
1962
1963 {
1964 // This macro expands to a single item: the implementation of Env for
1965 // the SDK's Env struct used by client contract code running in a WASM VM.
1966 #[doc(hidden)]
1967 impl internal::Env for Env
1968 {
1969 $(
1970 $(
1971 // This invokes the guest_function_helper! macro above
1972 // passing only the relevant parts of the declaration
1973 // matched by the inner pattern above. It is embedded in two
1974 // nested `$()*` pattern-repetition expanders that
1975 // correspond to the pattern-repetition matchers in the
1976 // match section, but we ignore the structure of the 'mod'
1977 // block repetition-level from the outer pattern in the
1978 // expansion, flattening all functions from all 'mod' blocks
1979 // into the implementation of Env for Guest.
1980 sdk_function_helper!{$mod_id, fn $fn_id $args -> $ret}
1981 )*
1982 )*
1983 }
1984 };
1985}
1986
1987// Here we invoke the x-macro passing generate_env_trait as its callback macro.
1988internal::call_macro_with_all_host_functions! { impl_env_for_sdk }