1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072
use core::convert::Infallible;
#[cfg(target_family = "wasm")]
pub mod internal {
use core::convert::Infallible;
pub use soroban_env_guest::*;
pub type EnvImpl = 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;
// 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)
}
}
}
// Testutils from the environment are pub here, and then pub re-exported out of
// the SDK in the crate::testutils mod.
#[cfg(any(test, feature = "testutils"))]
pub mod testutils {
pub use super::internal::budget::Budget;
pub use super::internal::budget::CostType;
pub use super::internal::LedgerInfo;
}
pub use internal::meta;
pub use internal::xdr;
pub use internal::BitSet;
pub use internal::Compare;
pub use internal::ConversionError;
pub use internal::EnvBase;
pub use internal::Object;
pub use internal::RawVal;
pub use internal::RawValConvertible;
pub use internal::Status;
pub use internal::Symbol;
pub use internal::TryFromVal;
pub use internal::TryIntoVal;
pub use internal::Val;
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::unwrap::UnwrapInfallible;
use crate::unwrap::UnwrapOptimized;
use crate::{
crypto::Crypto, deploy::Deployer, events::Events, ledger::Ledger, logging::Logger,
storage::Storage, Address, Bytes, BytesN, Vec,
};
/// 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"))]
snapshot: Option<Rc<LedgerSnapshot>>,
}
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::default_with_testutils()
}
}
impl Env {
/// Panic with the given error.
///
/// Equivalent to `panic!`, but with an error value instead of a string.
#[doc(hidden)]
pub fn panic_with_error(&self, error: impl Into<Status>) {
_ = internal::Env::fail_with_status(self, error.into());
unreachable!()
}
/// Get a [Storage] for accessing and update contract data that has been stored
/// by the currently executing contract.
#[inline(always)]
#[deprecated(note = "use env.storage()")]
pub fn data(&self) -> Storage {
self.storage()
}
/// Get a [Storage] for accessing and update contract data that has been stored
/// 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)
}
/// 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) }
}
/// Get the 32-byte hash identifier of the current executing contract.
///
/// Prefer `current_contract_address` for the most cases, unless dealing
/// with contract-specific functions (like the call stacks).
pub fn current_contract_id(&self) -> BytesN<32> {
let id = internal::Env::get_current_contract_id(self).unwrap_infallible();
unsafe { BytesN::<32>::unchecked_new(self.clone(), id) }
}
#[doc(hidden)]
pub(crate) fn require_auth_for_args(&self, address: &Address, args: Vec<RawVal>) {
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();
}
/// Returns the contract call stack as a [`Vec`]
/// of `(contract_id, function_name)`.
///
/// ### Examples
/// ```
/// use soroban_sdk::{contractimpl, BytesN, Env, Symbol, symbol};
///
/// pub struct Contract;
///
/// #[contractimpl]
/// impl Contract {
/// pub fn hello(env: Env) {
/// let stack = env.call_stack();
/// assert_eq!(stack.len(), 1);
///
/// let outer = stack.get(0).unwrap().unwrap();
/// assert_eq!(outer.0, BytesN::from_array(&env, &[0; 32]));
/// assert_eq!(outer.1, symbol!("hello"));
/// }
/// }
/// #[test]
/// fn test() {
/// # }
/// # #[cfg(feature = "testutils")]
/// # fn main() {
/// let env = Env::default();
/// let contract_id = BytesN::from_array(&env, &[0; 32]);
/// env.register_contract(&contract_id, Contract);
/// let client = ContractClient::new(&env, &contract_id);
/// client.hello();
/// }
/// # #[cfg(not(feature = "testutils"))]
/// # fn main() { }
/// ```
pub fn call_stack(&self) -> Vec<(BytesN<32>, Symbol)> {
let stack = internal::Env::get_current_call_stack(self).unwrap_infallible();
unsafe { Vec::unchecked_new(self.clone(), stack) }
}
#[doc(hidden)]
#[deprecated(note = "use env.crypto().sha256(msg)")]
pub fn compute_hash_sha256(&self, msg: &Bytes) -> BytesN<32> {
self.crypto().sha256(msg)
}
#[doc(hidden)]
#[deprecated(note = "use env.crypto().ed25519_verify(pk, msg, sig)")]
pub fn verify_sig_ed25519(&self, pk: &BytesN<32>, msg: &Bytes, sig: &BytesN<64>) {
self.crypto().ed25519_verify(pk, msg, sig);
}
/// 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_id: &BytesN<32>,
func: &Symbol,
args: Vec<RawVal>,
) -> T
where
T: TryFromVal<Env, RawVal>,
{
let rv = internal::Env::call(self, contract_id.to_object(), *func, 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_id: &BytesN<32>,
func: &Symbol,
args: Vec<RawVal>,
) -> Result<Result<T, T::Error>, Result<E, E::Error>>
where
T: TryFromVal<Env, RawVal>,
E: TryFrom<Status>,
{
let rv = internal::Env::try_call(self, contract_id.to_object(), *func, args.to_object())
.unwrap_infallible();
match Status::try_from_val(self, &rv) {
Ok(status) => Err(E::try_from(status)),
Err(ConversionError) => Ok(T::try_from_val(self, &rv)),
}
}
/// Get the [Logger] for logging debug events.
#[inline(always)]
pub fn logger(&self) -> Logger {
Logger::new(self)
}
#[doc(hidden)]
pub fn log_value<V: IntoVal<Env, RawVal>>(&self, v: V) {
internal::Env::log_value(self, v.into_val(self)).unwrap_infallible();
}
}
#[cfg(any(test, feature = "testutils"))]
use crate::testutils::{budget::Budget, random, BytesN as _, ContractFunctionSet, Ledger as _};
#[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::{Hash, LedgerEntry, LedgerKey, LedgerKeyContractData};
#[cfg(any(test, feature = "testutils"))]
#[cfg_attr(feature = "docs", doc(cfg(feature = "testutils")))]
impl Env {
pub(crate) fn host(&self) -> &internal::Host {
&self.env_impl
}
fn default_with_testutils() -> Env {
struct EmptySnapshotSource();
impl internal::storage::SnapshotSource for EmptySnapshotSource {
fn get(
&self,
_key: &xdr::LedgerKey,
) -> Result<xdr::LedgerEntry, soroban_env_host::HostError> {
use xdr::{ScHostStorageErrorCode, ScStatus};
let status: internal::Status =
ScStatus::HostStorageError(ScHostStorageErrorCode::MissingKeyInGet).into();
Err(status.into())
}
fn has(&self, _key: &xdr::LedgerKey) -> Result<bool, soroban_env_host::HostError> {
Ok(false)
}
}
let rf = Rc::new(EmptySnapshotSource());
let storage = internal::storage::Storage::with_recording_footprint(rf);
let budget = internal::budget::Budget::default();
let env_impl = internal::EnvImpl::with_storage_and_budget(storage, budget.clone());
env_impl.switch_to_recording_auth();
let env = Env {
env_impl,
snapshot: None,
};
env.ledger().set(internal::LedgerInfo {
protocol_version: 0,
sequence_number: 0,
timestamp: 0,
network_id: [0; 32],
base_reserve: 0,
});
env
}
/// 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 a random ID to be
/// assigned to the contract.
///
/// Registering a contract that is already registered replaces it.
///
/// Returns the contract ID of the registered contract.
///
/// ### Examples
/// ```
/// use soroban_sdk::{contractimpl, BytesN, Env, Symbol};
///
/// pub struct HelloContract;
///
/// #[contractimpl]
/// impl HelloContract {
/// pub fn hello(env: Env, recipient: soroban_sdk::Symbol) -> soroban_sdk::Symbol {
/// todo!()
/// }
/// }
///
/// #[test]
/// fn test() {
/// # }
/// # fn main() {
/// let env = Env::default();
/// let contract_id = BytesN::from_array(&env, &[0; 32]);
/// env.register_contract(&contract_id, HelloContract);
/// }
/// ```
pub fn register_contract<'a, T: ContractFunctionSet + 'static>(
&self,
contract_id: impl Into<Option<&'a BytesN<32>>>,
contract: T,
) -> BytesN<32> {
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: &[RawVal],
) -> Option<RawVal> {
self.0.call(func, Env::with_impl(env_impl.clone()), args)
}
}
let contract_id = if let Some(contract_id) = contract_id.into() {
contract_id.clone()
} else {
BytesN::random(self)
};
self.env_impl
.register_test_contract(
contract_id.to_object(),
Rc::new(InternalContractFunctionSet(contract)),
)
.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 a random ID to be
/// assigned to the contract.
///
/// Registering a contract that is already registered replaces it.
///
/// Returns the contract ID 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);
/// }
/// ```
pub fn register_contract_wasm<'a>(
&self,
contract_id: impl Into<Option<&'a BytesN<32>>>,
contract_wasm: &[u8],
) -> BytesN<32> {
let wasm_hash: BytesN<32> = self.install_contract_wasm(contract_wasm);
self.register_contract_with_optional_contract_id_and_source(
contract_id,
xdr::ScContractCode::WasmRef(xdr::Hash(wasm_hash.into())),
)
}
/// Register the built-in Stellar Asset Contract with provided admin address.
///
/// Returns the contract ID of the registered token contract.
///
/// 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(&self, admin: Address) -> BytesN<32> {
let issuer_id =
xdr::AccountId(xdr::PublicKey::PublicKeyTypeEd25519(xdr::Uint256(random())));
self.host()
.with_mut_storage(|storage| {
let k = xdr::LedgerKey::Account(xdr::LedgerKeyAccount {
account_id: issuer_id.clone(),
});
if !storage.has(
&k,
soroban_env_host::budget::AsBudget::as_budget(self.host()),
)? {
let v = xdr::LedgerEntry {
data: xdr::LedgerEntryData::Account(xdr::AccountEntry {
account_id: issuer_id.clone(),
balance: 0,
flags: 0,
home_domain: xdr::StringM::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,
};
storage.put(
&k,
&v,
soroban_env_host::budget::AsBudget::as_budget(self.host()),
)?
}
Ok(())
})
.unwrap();
let asset = xdr::Asset::CreditAlphanum4(xdr::AlphaNum4 {
asset_code: xdr::AssetCode4(random()),
issuer: issuer_id.clone(),
});
let create = xdr::HostFunction::CreateContract(xdr::CreateContractArgs {
contract_id: xdr::ContractId::Asset(asset.clone()),
source: xdr::ScContractCode::Token,
});
let token_id = self
.env_impl
.invoke_function(create)
.unwrap()
.try_into_val(self)
.unwrap();
let issuer_address = Address::try_from_val(
self,
&xdr::ScVal::Object(Some(xdr::ScObject::Address(xdr::ScAddress::Account(
issuer_id.clone(),
)))),
)
.unwrap();
let _: () = self.invoke_contract(
&token_id,
&Symbol::from_str("set_admin"),
(issuer_address, admin).try_into_val(self).unwrap(),
);
token_id
}
fn register_contract_with_optional_contract_id_and_source<'a>(
&self,
contract_id: impl Into<Option<&'a BytesN<32>>>,
source: xdr::ScContractCode,
) -> BytesN<32> {
if let Some(contract_id) = contract_id.into() {
self.register_contract_with_contract_id_and_source(contract_id, source);
contract_id.clone()
} else {
self.register_contract_with_source(source)
}
}
fn register_contract_with_source(&self, source: xdr::ScContractCode) -> BytesN<32> {
let prev_source_account = if let Ok(prev_acc) = self.env_impl.source_account() {
Some(prev_acc)
} else {
None
};
self.env_impl
.set_source_account(xdr::AccountId(xdr::PublicKey::PublicKeyTypeEd25519(
xdr::Uint256(random()),
)));
let contract_id: BytesN<32> = self
.env_impl
.invoke_function(xdr::HostFunction::CreateContract(xdr::CreateContractArgs {
contract_id: xdr::ContractId::SourceAccount(xdr::Uint256(random())),
source,
}))
.unwrap()
.try_into_val(self)
.unwrap();
if let Some(prev_acc) = prev_source_account {
self.env_impl.set_source_account(prev_acc);
} else {
self.env_impl.remove_source_account();
}
contract_id
}
/// Returns the recorded top-level `require_auth` or `require_auth_for_args`
/// calls that have happened during the last contract invocation.
///
/// Use this in tests to verify that the expected authorizations with the
/// expected arguments are required.
///
/// The return value is a vector of authorizations represented by tuples of
/// `(address, contract_id, function_name, args)` corresponding to the calls
/// of `require_auth_for_args(address, args)` from the contract function
/// `(contract_id, function_name)` (or `require_auth` with all the arguments
/// of the function invocation).
///
/// The order of the returned vector is defined by the order of
/// `require_auth` calls. It is recommended though to do unordered
/// comparison in case if multiple entries are returned.
///
/// 'Top-level call' here means that this is the first call of
/// `require_auth` for a given address in the call stack; it doesn't have
/// to coincide with the actual top-level contract invocation. For example,
/// if contract A doesn't use `require_auth` and then it calls contract B
/// that uses `require_auth`, then `verify_top_authorization` will return
/// `true` when verifying the contract B's `require_auth` call, but it will
/// return `false` if contract A makes a `require_auth` call.
///
/// It is possible for a single address to be present multiple times in the
/// output, as long as there are multiple disjoint call trees for that
/// address.
///
/// ### Examples
/// ```
/// use soroban_sdk::{contractimpl, testutils::Address as _, Address, Env, IntoVal, symbol};
///
/// pub struct Contract;
///
/// #[contractimpl]
/// impl Contract {
/// pub fn transfer(env: Env, address: Address, amount: i128) {
/// address.require_auth();
/// }
/// pub fn transfer2(env: Env, address: Address, amount: i128) {
/// address.require_auth_for_args((amount / 2,).into_val(&env));
/// }
/// }
///
/// #[test]
/// fn test() {
/// # }
/// # #[cfg(feature = "testutils")]
/// # fn main() {
/// extern crate std;
/// let env = Env::default();
/// let contract_id = env.register_contract(None, Contract);
/// let client = ContractClient::new(&env, &contract_id);
/// let address = Address::random(&env);
/// client.transfer(&address, &1000_i128);
/// assert_eq!(
/// env.recorded_top_authorizations(),
/// std::vec![(
/// address.clone(),
/// client.contract_id.clone(),
/// symbol!("transfer"),
/// (&address, 1000_i128,).into_val(&env)
/// )]
/// );
///
/// client.transfer2(&address, &1000_i128);
/// assert_eq!(
/// env.recorded_top_authorizations(),
/// std::vec![(
/// address.clone(),
/// client.contract_id.clone(),
/// symbol!("transfer2"),
/// // `transfer2` requires auth for (amount / 2) == (1000 / 2) == 500.
/// (500_i128,).into_val(&env)
/// )]
/// );
/// }
/// # #[cfg(not(feature = "testutils"))]
/// # fn main() { }
/// ```
pub fn recorded_top_authorizations(
&self,
) -> std::vec::Vec<(Address, BytesN<32>, Symbol, Vec<RawVal>)> {
use xdr::{ScObject, ScVal};
let authorizations = self.env_impl.get_recorded_top_authorizations().unwrap();
authorizations
.iter()
.map(|a| {
let mut args = Vec::new(self);
for v in a.3.iter() {
args.push_back(RawVal::try_from_val(self, v).unwrap());
}
(
Address::try_from_val(
self,
&ScVal::Object(Some(ScObject::Address(a.0.clone()))),
)
.unwrap(),
BytesN::<32>::try_from_val(
self,
&ScVal::Object(Some(ScObject::Bytes(
a.1.as_slice().to_vec().try_into().unwrap(),
))),
)
.unwrap(),
a.2.clone(),
args,
)
})
.collect()
}
fn register_contract_with_contract_id_and_source(
&self,
contract_id: &BytesN<32>,
source: xdr::ScContractCode,
) {
let contract_id_hash = Hash(contract_id.into());
let data_key = xdr::ScVal::Static(xdr::ScStatic::LedgerKeyContractCode);
let key = LedgerKey::ContractData(LedgerKeyContractData {
contract_id: contract_id_hash.clone(),
key: data_key.clone(),
});
self.env_impl
.with_mut_storage(|storage| {
storage.put(
&key,
&LedgerEntry {
ext: xdr::LedgerEntryExt::V0,
last_modified_ledger_seq: 0,
data: xdr::LedgerEntryData::ContractData(xdr::ContractDataEntry {
contract_id: contract_id_hash.clone(),
key: data_key,
val: xdr::ScVal::Object(Some(xdr::ScObject::ContractCode(source))),
}),
},
&self.env_impl.budget_cloned(),
)
})
.unwrap();
}
/// Install the contract WASM code to the [Env] for testing.
///
/// Returns the hash of the installed code that can be then used for
/// the contract deployment.
///
/// Useful for contract factory testing, otherwise use
/// `register_contract_wasm` function that installs and deploys the contract
/// in a single call.
///
/// ### 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.install_contract_wasm(WASM);
/// }
/// ```
pub fn install_contract_wasm(&self, contract_wasm: &[u8]) -> BytesN<32> {
self.env_impl
.invoke_function(xdr::HostFunction::InstallContractCode(
xdr::InstallContractCodeArgs {
code: contract_wasm.clone().try_into().unwrap(),
},
))
.unwrap()
.try_into_val(self)
.unwrap()
}
/// Run the function as if executed by the given contract ID.
///
/// Used to write or read contract data, or take other actions in tests for
/// setting up tests or asserting on internal state.
pub fn as_contract<T>(&self, id: &BytesN<32>, f: impl FnOnce() -> T) -> T {
let id: [u8; 32] = id.into();
let func = Symbol::from_str("");
let mut t: Option<T> = None;
self.env_impl
.with_test_contract_frame(id.into(), func, || {
t = Some(f());
Ok(().into())
})
.unwrap();
t.unwrap()
}
/// Creates a new Env loaded with the [`LedgerSnapshot`].
///
/// The ledger info and state in the snapshot are loaded into the Env.
pub fn from_snapshot(s: LedgerSnapshot) -> Env {
let info = s.ledger_info();
let rs = Rc::new(s.clone());
let storage = internal::storage::Storage::with_recording_footprint(rs.clone());
let budget = internal::budget::Budget::default();
let env_impl = internal::EnvImpl::with_storage_and_budget(storage, budget.clone());
env_impl.switch_to_recording_auth();
let env = Env {
env_impl,
snapshot: Some(rs.clone()),
};
env.ledger().set(info);
env
}
/// Creates a new Env loaded with the ledger snapshot loaded from the file.
///
/// ### Panics
///
/// If there is any error reading the file.
pub fn from_snapshot_file(p: impl AsRef<Path>) -> Env {
Self::from_snapshot(LedgerSnapshot::read_file(p).unwrap())
}
/// Create a snapshot from the Env's current state.
pub fn to_snapshot(&self) -> LedgerSnapshot {
let snapshot = self.snapshot.clone().unwrap_or_default();
let mut snapshot = (*snapshot).clone();
snapshot.set_ledger_info(self.ledger().get());
let budget = soroban_env_host::budget::AsBudget::as_budget(&self.env_impl);
let storage = self
.env_impl
.with_mut_storage(|s| Ok(s.map.clone()))
.unwrap();
snapshot.update_entries(storage.iter(budget).unwrap());
snapshot
}
/// Create a snapshot file from the Env's current state.
///
/// ### Panics
///
/// If there is any error writing the file.
pub fn to_snapshot_file(&self, p: impl AsRef<Path>) {
self.to_snapshot().write_file(p).unwrap();
}
/// Get the budget that tracks the resources consumed for the environment.
pub fn budget(&self) -> Budget {
self.env_impl.with_budget(|b| Budget::new(b))
}
}
#[doc(hidden)]
impl Env {
pub fn with_impl(env_impl: internal::EnvImpl) -> Env {
Env {
env_impl,
#[cfg(any(test, feature = "testutils"))]
snapshot: None,
}
}
}
#[doc(hidden)]
impl internal::EnvBase for Env {
type Error = Infallible;
// Note: the function `escalate_error_to_panic` only exists _on the `Env`
// trait_ when the feature `soroban-env-common/testutils` is enabled. This
// is because the host wants to never have this function even _compiled in_
// when building for production, as it might be accidentally called (we have
// mistakenly done so with conversion and comparison traits in the past).
//
// As a result, we only implement it here (fairly meaninglessly) when we're
// in `cfg(test)` (which enables `soroban-env-host/testutils` thus
// `soroban-env-common/testutils`) or when we've had our own `testutils`
// feature enabled (which does the same).
//
// See the `internal::reject_err` functions above for more detail about what
// it actually does (when implemented for real, on the host). In this
// not-very-serious impl, since `Self::Error` is `Infallible`, this instance
// can never actually be called and so its body is just a trivial
// transformation from one empty type to another, for Type System Reasons.
#[cfg(any(test, feature = "testutils"))]
fn escalate_error_to_panic(&self, e: Self::Error) -> ! {
match e {}
}
fn as_mut_any(&mut self) -> &mut dyn core::any::Any {
self
}
fn check_same_env(&self, other: &Self) {
self.env_impl.check_same_env(&other.env_impl);
}
fn deep_clone(&self) -> Self {
Env {
env_impl: self.env_impl.deep_clone(),
#[cfg(any(test, feature = "testutils"))]
snapshot: self.snapshot.clone(),
}
}
fn bytes_copy_from_slice(
&self,
b: Object,
b_pos: RawVal,
mem: &[u8],
) -> Result<Object, Self::Error> {
Ok(self
.env_impl
.bytes_copy_from_slice(b, b_pos, mem)
.unwrap_optimized())
}
fn bytes_copy_to_slice(
&self,
b: Object,
b_pos: RawVal,
mem: &mut [u8],
) -> Result<(), Self::Error> {
Ok(self
.env_impl
.bytes_copy_to_slice(b, b_pos, mem)
.unwrap_optimized())
}
fn bytes_new_from_slice(&self, mem: &[u8]) -> Result<Object, Self::Error> {
Ok(self.env_impl.bytes_new_from_slice(mem).unwrap_optimized())
}
fn log_static_fmt_val(&self, fmt: &'static str, v: RawVal) -> Result<(), Self::Error> {
Ok(self.env_impl.log_static_fmt_val(fmt, v).unwrap_optimized())
}
fn log_static_fmt_static_str(
&self,
fmt: &'static str,
s: &'static str,
) -> Result<(), Self::Error> {
Ok(self
.env_impl
.log_static_fmt_static_str(fmt, s)
.unwrap_optimized())
}
fn log_static_fmt_val_static_str(
&self,
fmt: &'static str,
v: RawVal,
s: &'static str,
) -> Result<(), Self::Error> {
Ok(self
.env_impl
.log_static_fmt_val_static_str(fmt, v, s)
.unwrap_optimized())
}
fn log_static_fmt_general(
&self,
fmt: &'static str,
v: &[RawVal],
s: &[&'static str],
) -> Result<(), Self::Error> {
Ok(self
.env_impl
.log_static_fmt_general(fmt, v, s)
.unwrap_optimized())
}
}
///////////////////////////////////////////////////////////////////////////////
/// X-macro use: impl Env for SDK's Env
///////////////////////////////////////////////////////////////////////////////
// This is a helper macro used only by impl_env_for_sdk below. It consumes a
// token-tree of the form:
//
// {fn $fn_id:ident $args:tt -> $ret:ty}
//
// and produces the the corresponding method definition to be used in the
// SDK's Env implementation of the Env (calling through to the corresponding
// guest or host implementation).
macro_rules! sdk_function_helper {
{$mod_id:ident, fn $fn_id:ident($($arg:ident:$type:ty),*) -> $ret:ty}
=>
{
fn $fn_id(&self, $($arg:$type),*) -> Result<$ret, Self::Error> {
internal::reject_err(&self.env_impl, self.env_impl.$fn_id($($arg),*))
}
};
}
// This is a callback macro that pattern-matches the token-tree passed by the
// x-macro (call_macro_with_all_host_functions) and produces a suite of
// forwarding-method definitions, which it places in the body of the declaration
// of the implementation of Env for the SDK's Env.
macro_rules! impl_env_for_sdk {
{
$(
// This outer pattern matches a single 'mod' block of the token-tree
// passed from the x-macro to this macro. It is embedded in a `$()*`
// pattern-repetition matcher so that it will match all provided
// 'mod' blocks provided.
$(#[$mod_attr:meta])*
mod $mod_id:ident $mod_str:literal
{
$(
// This inner pattern matches a single function description
// inside a 'mod' block in the token-tree passed from the
// x-macro to this macro. It is embedded in a `$()*`
// pattern-repetition matcher so that it will match all such
// descriptions.
$(#[$fn_attr:meta])*
{ $fn_str:literal, fn $fn_id:ident $args:tt -> $ret:ty }
)*
}
)*
}
=> // The part of the macro above this line is a matcher; below is its expansion.
{
// This macro expands to a single item: the implementation of Env for
// the SDK's Env struct used by client contract code running in a WASM VM.
#[doc(hidden)]
impl internal::Env for Env
{
$(
$(
// This invokes the guest_function_helper! macro above
// passing only the relevant parts of the declaration
// matched by the inner pattern above. It is embedded in two
// nested `$()*` pattern-repetition expanders that
// correspond to the pattern-repetition matchers in the
// match section, but we ignore the structure of the 'mod'
// block repetition-level from the outer pattern in the
// expansion, flattening all functions from all 'mod' blocks
// into the implementation of Env for Guest.
sdk_function_helper!{$mod_id, fn $fn_id $args -> $ret}
)*
)*
}
};
}
// Here we invoke the x-macro passing generate_env_trait as its callback macro.
internal::call_macro_with_all_host_functions! { impl_env_for_sdk }