### Usage example: Budgeted comparison between two Vals Source: https://github.com/stellar/rs-soroban-env/blob/main/_autodocs/api-reference/convert-compare.md Uses `host.compare` on two `Val` instances to get an `Ordering`, which fails on invalid object handles or a depleted budget. Asserts the result is `Ordering::Less`. ```rust use soroban_env_common::{Compare, Val, TryFromVal}; use soroban_env_host::Host; use std::cmp::Ordering; let host = Host::default(); let a: Val = 10u32.into(); let b: Val = 20u32.into(); let ordering = host.compare(&a, &b)?; assert_eq!(ordering, Ordering::Less); # Ok::<(), soroban_env_host::HostError>(()) ``` -------------------------------- ### Building LedgerInfo for preflight Source: https://github.com/stellar/rs-soroban-env/blob/main/_autodocs/api-reference/ledger-info.md Constructs a LedgerInfo instance with example values for a preflight, then calls min_live_until_ledger_checked to verify the minimum live-until ledger. The assertion confirms the calculation using the min_temp_entry_ttl value. ```rust use soroban_env_host::LedgerInfo; let mut ledger_info = LedgerInfo { protocol_version: 29, sequence_number: 1234, timestamp: 1_700_000_000, network_id: [0u8; 32], base_reserve: 500_000_00, min_temp_entry_ttl: 4_095, min_persistent_entry_ttl: 4_095, max_entry_ttl: 6_312_000, }; let min = ledger_info.min_live_until_ledger_checked( soroban_env_host::xdr::ContractDataDurability::Persistent ).expect("well-formed ledger info"); assert_eq!(min, 1234 + 4_095 - 1); ``` -------------------------------- ### Usage example: TryFromVal / TryIntoVal with a host Source: https://github.com/stellar/rs-soroban-env/blob/main/_autodocs/api-reference/convert-compare.md Demonstrates converting between Rust types and `Val` using `TryFromVal` and `TryIntoVal`. Shows converting a small `u64` to a `Val`, back to `i64`, and a `Symbol` from a string. ```rust use soroban_env_common::{Env, TryFromVal, TryIntoVal, Val, Symbol}; use soroban_env_host::Host; let host = Host::default(); let v = Val::try_from_val(&host, &123u64)?; // small u64 let n: i64 = v.try_into_val(&host)?; // back out let s: Symbol = Symbol::try_from_val(&host, &"hello")?; # Ok::<(), soroban_env_host::HostError>(()) ``` -------------------------------- ### Usage examples Source: https://github.com/stellar/rs-soroban-env/blob/main/_autodocs/api-reference/object.md Examples of handle manipulation and classification of XDR values. ```APIDOC ## Usage examples ### Handle manipulation ```rust use soroban_env_common::{Object, Tag, ConversionError, VecObject}; // Construct an object handle directly (unsafe: must be a live handle in the env). let obj = unsafe { VecObject::from_handle(5) }; assert_eq!(obj.get_handle(), 5); let o: Object = obj.into(); assert_eq!(o.get_handle(), 5); assert_eq!(o.to_val().get_tag(), Tag::VecObject); let bad: Result = Object::from_handle_and_tag(1, Tag::MapObject).try_into(); assert!(bad.is_err()); // tag mismatch ``` ### Classifying XDR values ```rust use soroban_env_common::{ScValObjRef, ScValObject}; use soroban_env_common::xdr::ScVal; let small = ScVal::U32(5); assert!(ScValObjRef::classify(&small).is_none()); // stays inline let big_bytes = ScVal::Bytes(vec![0u8; 64].try_into().unwrap()); assert!(ScValObjRef::classify(&big_bytes).is_some()); // must be a host object let classified = ScValObject::classify(ScVal::Vec(None).unwrap_or(ScVal::Void)).is_ok(); ``` ``` -------------------------------- ### Tracing on the host side using EnvBase Source: https://github.com/stellar/rs-soroban-env/blob/main/_autodocs/api-reference/env.md Demonstrates how to use the trace_env_call and trace_env_ret methods on a generic EnvBase implementation to trace a host function call. The example checks value integrity and returns a result. ```rust use soroban_env_common::{EnvBase, Val}; fn trace_once(env: &E, v: Val) -> Result<(), E::Error> { env.trace_env_call("my_op", &[&v])?; let r = env.check_val_integrity(v)?; env.trace_env_ret("my_op", &Ok(&r))?; Ok(()) } ``` -------------------------------- ### Calling the interface from SDK/native code using Env Source: https://github.com/stellar/rs-soroban-env/blob/main/_autodocs/api-reference/env.md Shows how to use the blanket Env impl to create a Host, build a VecObject of arguments, and convert a string to a Symbol. Note that invoking a contract requires a deployed contract; this example only illustrates the interface shape. ```rust use soroban_env_common::{Env, Val, U32Val, Symbol, VecObject, TryFromVal}; use soroban_env_host::Host; let host = Host::default(); let arg: Val = 1u32.into(); let args: VecObject = host.vec_new_from_slice(&[arg])?; let sym: Symbol = Symbol::try_from_val(&host, &"balance")?; // (invoking a contract requires a deployed contract; this shows the interface shape) # Ok::<(), soroban_env_host::HostError>(()) ``` -------------------------------- ### Default host with uninitialized ledger access Source: https://github.com/stellar/rs-soroban-env/blob/main/_autodocs/api-reference/host.md Creates a default Host and attempts to get the ledger protocol version, which fails because the ledger is not set. The error is printed with its code. ```rust use soroban_env_host::{Host, HostError}; let host = Host::default(); match host.get_ledger_protocol_version() { Err(e) => println!("ledger not set yet: {} (type={:?})", e.error, e.error.get_code()), Ok(v) => println!("protocol {}", v), } ``` -------------------------------- ### Env implementation for Guest Source: https://github.com/stellar/rs-soroban-env/blob/main/_autodocs/api-reference/guest.md Implements the `Env` trait for `Guest`, showing `log_from_linear_memory` as an example. All 199 host functions are wrapped in `Ok(...)` and call the corresponding extern function. ```rust impl Env for Guest { fn log_from_linear_memory(&self, msg_pos: U32Val, msg_len: U32Val, vals_pos: U32Val, vals_len: U32Val) -> Result { unsafe { Ok(context::log_from_linear_memory(msg_pos, msg_len, vals_pos, vals_len)) } } // ... all 199 host functions, each wrapped in Ok(...) ... } ``` -------------------------------- ### Create custom Budget from network configuration Source: https://github.com/stellar/rs-soroban-env/blob/main/_autodocs/api-reference/budget.md Constructs a Budget using ContractCostParams for CPU and memory, then charges a WasmInsnExec operation and prints the consumed CPU instructions. Requires the full network params from the ledger in production; the example uses placeholder values for illustration. ```rust use soroban_env_host::{Budget, HostError}; use soroban_env_host::xdr::{ContractCostParamEntry, ContractCostParams, ExtensionPoint}; // One entry per ContractCostType; here just the first two for illustration — // production code loads the full network params from the ledger. let cpu_cost_params = ContractCostParams( vec![ ContractCostParamEntry { ext: ExtensionPoint::V0, const_term: 35, linear_term: 36 }, ContractCostParamEntry { ext: ExtensionPoint::V0, const_term: 37, linear_term: 38 }, ].try_into().unwrap(), ); let mem_cost_params = ContractCostParams( vec![ ContractCostParamEntry { ext: ExtensionPoint::V0, const_term: 39, linear_term: 40 }, ContractCostParamEntry { ext: ExtensionPoint::V0, const_term: 41, linear_term: 42 }, ContractCostParamEntry { ext: ExtensionPoint::V0, const_term: 43, linear_term: 44 }, ].try_into().unwrap(), ); let budget = Budget::try_from_configs(100_000_000, 40_000_000, cpu_cost_params, mem_cost_params)?; budget.charge(soroban_env_host::xdr::ContractCostType::WasmInsnExec, None)?; println!("cpu consumed: {}", budget.get_cpu_insns_consumed()?); # Ok::<(), HostError>(()) ``` -------------------------------- ### Recording-mode storage with custom snapshot Source: https://github.com/stellar/rs-soroban-env/blob/main/_autodocs/api-reference/storage.md Example of creating a recording-mode storage backed by a custom snapshot that returns no data. Used for SDK-style preflight. The comment indicates to run preflight contract calls and then switch to enforcing mode. ```rust use std::rc::Rc; use soroban_env_host::storage::{SnapshotSource, Storage, EntryWithLiveUntil}; use soroban_env_host::xdr::LedgerKey; use soroban_env_host::HostError; struct EmptySnapshot; impl SnapshotSource for EmptySnapshot { fn get(&self, _key: &Rc) -> Result, HostError> { Ok(None) // no data on disk } } let storage = Storage::with_recording_footprint(Rc::new(EmptySnapshot)); let host = soroban_env_host::Host::with_storage_and_budget(storage, Default::default()); // run preflight contract calls here, then switch to enforcing: // (testutils/recording_mode builds) ``` -------------------------------- ### Recording invocation with invoke_host_function_in_recording_mode Source: https://github.com/stellar/rs-soroban-env/blob/main/_autodocs/api-reference/e2e-invoke.md Shows how to call invoke_host_function_in_recording_mode with a snapshot source and recording auth mode. The result's instructions and recorded auth entries are printed. The example ends with an Ok::<(), HostError>(()) expression. ```rust use std::rc::Rc; use soroban_env_host::{Budget, HostError, LedgerInfo}; use soroban_env_host::e2e_invoke::{ invoke_host_function_in_recording_mode, RecordingInvocationAuthMode, }; use soroban_env_host::storage::SnapshotSource; use soroban_env_host::xdr::HostFunction; let snapshot: Rc = /* ... */; let budget = Budget::default(); let mut diagnostics = vec![]; let result = invoke_host_function_in_recording_mode( &budget, true, &host_fn, // &HostFunction &source_account, // &AccountId RecordingInvocationAuthMode::recording(true, false), ledger_info, snapshot, [0u8; 32], &mut diagnostics, )?; println!("instructions: {}", result.resources.instructions); println!("recorded auth entries: {}", result.auth.len()); # Ok::<(), HostError>(()) ``` -------------------------------- ### Enforcing storage with default footprint Source: https://github.com/stellar/rs-soroban-env/blob/main/_autodocs/api-reference/storage.md Example of creating an enforcing-mode storage with an empty footprint. Any transaction touching a LedgerKey not declared in the footprint will fail with `(Storage, ExceededLimit)`. ```rust use soroban_env_host::storage::Storage; let storage = Storage::default(); // Enforcing with empty footprint // A transaction that touches any LedgerKey without declaring it in the // footprint will now fail with (Storage, ExceededLimit). ``` -------------------------------- ### Using MeteredVector and MeteredOrdMap with Host Source: https://github.com/stellar/rs-soroban-env/blob/main/_autodocs/api-reference/metered-collections.md Demonstrates basic usage of `MeteredVector` and `MeteredOrdMap` from `soroban_env_host`. It creates a vector, pushes a value, creates a map, inserts, gets, and removes a key, and asserts results. The final line is a hidden test marker that returns `Ok` on success. ```rust use soroban_env_host::{Host, MeteredOrdMap, MeteredVector}; let host = Host::default(); let mut v = MeteredVector::from_vec(vec![1u32, 2, 3])?; v = v.push_back(4u32, host.budget_ref())?; assert_eq!(v.len(), 4); let m = MeteredOrdMap::from_map(vec![(1u32, "a"), (2, "b")], &host)?; let m = m.insert(3, "c", &host)?; assert_eq!(m.get(&2, &host)?, Some(&"b")); let (m, removed) = m.remove(&2, &host)?.expect("key present"); assert_eq!(removed, "b"); # Ok::<(), soroban_env_host::HostError>(()) ``` -------------------------------- ### Handle manipulation example Source: https://github.com/stellar/rs-soroban-env/blob/main/_autodocs/api-reference/object.md Constructs an object handle directly using VecObject::from_handle, converts it to Object, and verifies the handle and tag. Also demonstrates a tag mismatch conversion error. ```rust use soroban_env_common::{Object, Tag, ConversionError, VecObject}; // Construct an object handle directly (unsafe: must be a live handle in the env). let obj = unsafe { VecObject::from_handle(5) }; assert_eq!(obj.get_handle(), 5); let o: Object = obj.into(); assert_eq!(o.get_handle(), 5); assert_eq!(o.to_val().get_tag(), Tag::VecObject); let bad: Result = Object::from_handle_and_tag(1, Tag::MapObject).try_into(); assert!(bad.is_err()); // tag mismatch ``` -------------------------------- ### Object methods Source: https://github.com/stellar/rs-soroban-env/blob/main/_autodocs/api-reference/object.md Methods on the Object type to get the handle and construct from handle and tag. ```APIDOC ## Object::get_handle ### Description Returns the 32-bit major field (handle) of the Object. ### Method const fn ### Signature pub const fn get_handle(&self) -> u32 ### Parameters - self (Object) - The Object instance. ### Returns u32 - The 32-bit handle. ## Object::from_handle_and_tag ### Description Constructs an Object from a handle and a tag, asserting at debug time that the tag is an object tag. ### Method const fn ### Signature pub const fn from_handle_and_tag(handle: u32, tag: Tag) -> Self ### Parameters - handle (u32) - The 32-bit handle. - tag (Tag) - The object tag. ### Returns Object - The constructed Object. ### Errors Panics in debug mode if tag.is_object() is false. ``` -------------------------------- ### Estimate fees from metered resources with FeeConfiguration Source: https://github.com/stellar/rs-soroban-env/blob/main/_autodocs/api-reference/invocation-metering.md Use this snippet to estimate fees after invoking contracts with metering enabled. It creates a default Host, enables invocation metering, and after contract invocations retrieves the last invocation resources to estimate fees using a default FeeConfiguration. The example prints the estimated total fee. ```rust use soroban_env_host::Host; use soroban_env_host::fees::FeeConfiguration; let host = Host::default(); host.enable_invocation_metering(); // ... invoke contract(s) ... if let Some(res) = host.get_last_invocation_resources() { let fee_config = FeeConfiguration::default(); // load real network config in practice let estimate = res.estimate_fees(&fee_config, 100, 10, 10); println!("estimated fee: {}", estimate.total); } ``` -------------------------------- ### Loading TTL config fields from network configuration Source: https://github.com/stellar/rs-soroban-env/blob/main/_autodocs/api-reference/ledger-info.md Loads TTL configuration fields into a LedgerInfo instance from a NetworkConfig loaded from a snapshot. The example asserts that the min_persistent_entry_ttl field is set correctly. ```rust use soroban_env_host::LedgerInfo; use soroban_simulation::NetworkConfig; let snapshot = /* impl SnapshotSource */; let network_config = NetworkConfig::load_from_snapshot(&snapshot)?; let mut ledger_info = LedgerInfo { protocol_version: 29, sequence_number: 100, ..Default::default() }; network_config.fill_config_fields_in_ledger_info(&mut ledger_info); assert_eq!(ledger_info.min_persistent_entry_ttl, network_config.min_persistent_entry_ttl); # Ok::<(), anyhow::Error>(()) ``` -------------------------------- ### Compute rent fee with compute_rent_fee Source: https://github.com/stellar/rs-soroban-env/blob/main/_autodocs/api-reference/fees.md Computes the rent fee for a set of ledger entry rent changes using the provided RentFeeConfiguration and current ledger sequence number. The example uses a single change with old and new sizes and live-until ledgers, then prints the resulting fee. ```rust use soroban_env_host::fees::{compute_rent_fee, RentFeeConfiguration, LedgerEntryRentChange}; let changes = vec![LedgerEntryRentChange { is_persistent: true, is_code_entry: false, old_size_bytes: 100, new_size_bytes: 100, old_live_until_ledger: 1000, new_live_until_ledger: 3000, }]; let config = RentFeeConfiguration { fee_per_write_1kb: 1000, fee_per_rent_1kb: 100, fee_per_write_entry: 500, persistent_rent_rate_denominator: 10, temporary_rent_rate_denominator: 10, }; let fee = compute_rent_fee(&changes, &config, 999); println!("rent fee: {fee}"); ``` -------------------------------- ### Transparent small-or-object representation with U64Val, U128Val, I256Val Source: https://github.com/stellar/rs-soroban-env/blob/main/_autodocs/api-reference/num.md Shows how small values (fits in 56 bits) are stored as small variants, while larger values become object-backed. The example uses `u64::try_from` to extract values and demonstrates the behavior with `U64Val`, `U128Val`, and `I256Val`. The `Ok::<(), ConversionError>(())` line indicates the expected success type. ```rust use soroban_env_common::{U64Val, U128Val, I256Val, ConversionError}; let small: U64Val = 123u64.into(); // U64Small form let big: U64Val = (1u64 << 60).into(); // exceeds 56 bits -> U64Object assert_eq!(u64::try_from(small).unwrap_or(0), 123); assert_eq!(u64::try_from(big), Ok(1 << 60)); let u: U128Val = (u128::MAX >> 1).into(); // object-backed u128 let v: U128Val = 7u128.into(); // small-backed # Ok::<(), ConversionError>(()) ``` -------------------------------- ### Compute transaction resource fee with compute_transaction_resource_fee Source: https://github.com/stellar/rs-soroban-env/blob/main/_autodocs/api-reference/fees.md Computes the non-refundable and refundable resource fees for a transaction using the provided TransactionResources and FeeConfiguration. The example sets up a sample transaction with 2 million instructions, 3 disk reads, 1 write, and various byte sizes, then prints the resulting fees. ```rust use soroban_env_host::fees::{TransactionResources, FeeConfiguration, compute_transaction_resource_fee}; let tx_resources = TransactionResources { instructions: 2_000_000, disk_read_entries: 3, write_entries: 1, disk_read_bytes: 500, write_bytes: 300, contract_events_size_bytes: 64, transaction_size_bytes: 1_024, }; let fee_config = FeeConfiguration { fee_per_instruction_increment: 100, fee_per_disk_read_entry: 500, fee_per_write_entry: 500, fee_per_disk_read_1kb: 1000, fee_per_write_1kb: 1000, fee_per_historical_1kb: 1000, fee_per_contract_event_1kb: 1000, fee_per_transaction_size_1kb: 1000, }; let (non_refundable, refundable) = compute_transaction_resource_fee(&tx_resources, &fee_config); println!("non-refundable={non_refundable} refundable={refundable}"); ``` -------------------------------- ### pub fn with_storage_and_budget(storage: Storage, budget: Budget) -> Self Source: https://github.com/stellar/rs-soroban-env/blob/main/_autodocs/api-reference/host.md Constructs a Host using the provided Storage for contract-data access and the provided Budget for metering. ```APIDOC ## pub fn with_storage_and_budget(storage: Storage, budget: Budget) -> Self ### Description Constructs a Host using the provided Storage for contract-data access and the provided Budget for metering. ### Method Constructor ### Signature `pub fn with_storage_and_budget(storage: Storage, budget: Budget) -> Self` ### Parameters - **storage** (Storage) - Required - The storage to use for contract-data access. - **budget** (Budget) - Required - The budget to use for metering. ### Returns A new `Host` instance with the given storage and budget. ``` -------------------------------- ### try_from_configs Source: https://github.com/stellar/rs-soroban-env/blob/main/_autodocs/api-reference/budget.md Creates a new Budget instance with specified CPU and memory limits and cost parameters. Returns a Result indicating success or a HostError. ```APIDOC ## try_from_configs ### Description Constructs a new Budget with the given CPU and memory limits and cost parameters. ### Method Constructor ### Signature ```rust pub fn try_from_configs( cpu_limit: u64, mem_limit: u64, cpu_cost_params: ContractCostParams, mem_cost_params: ContractCostParams, ) -> Result; ``` ### Parameters - **cpu_limit** (u64) - Required - Max modelled CPU instructions (ns) for the invocation. - **mem_limit** (u64) - Required - Max modelled memory bytes. - **cpu_cost_params** (ContractCostParams) - Required - XDR `ContractCostParamEntry` list per `ContractCostType` for CPU. - **mem_cost_params** (ContractCostParams) - Required - Same for memory. ### Returns - **Result** - Ok(Budget) on success, Err(HostError) on failure. ``` -------------------------------- ### Host lifecycle with explicit storage and budget Source: https://github.com/stellar/rs-soroban-env/blob/main/_autodocs/api-reference/host.md Creates a Host with default storage and budget, similar to test configurations. Verifies the host can finish and then finishes it to retrieve storage and events. ```rust use soroban_env_host::{Host, Budget, Storage, LedgerInfo}; use soroban_env_host::xdr::{ContractCostParams, Limits, ScErrorCode, ScErrorType}; use soroban_env_host::budget::DEFAULT_XDR_RW_LIMITS; // Similar to what soroban-env-host tests do (budget defaults for tests): let storage = Storage::default(); let budget = Budget::default(); let host = Host::with_storage_and_budget(storage, budget); assert!(host.can_finish()); let (storage, events) = host.try_finish().expect("unique ref, nothing borrowed"); ``` -------------------------------- ### Preserve auth state across test setup Source: https://github.com/stellar/rs-soroban-env/blob/main/_autodocs/api-reference/auth.md Snapshots the auth manager before performing authorized test setup that mutates it, then restores the snapshot to roll back changes. ```rust use soroban_env_host::{Host, HostError}; let host = Host::default(); let snapshot = host.snapshot_auth_manager()?; // ... authorized test setup that mutates the auth manager ... host.set_auth_manager(snapshot)?; // roll back # Ok::<(), HostError>(()) ``` -------------------------------- ### try_from_configs_with_shadow_limits Source: https://github.com/stellar/rs-soroban-env/blob/main/_autodocs/api-reference/budget.md Creates a new Budget instance with additional shadow limits for CPU and memory. Useful for tracking without affecting actual limits. ```APIDOC ## try_from_configs_with_shadow_limits ### Description Constructs a new Budget with CPU/memory limits and shadow limits, plus cost parameters. ### Method Constructor ### Signature ```rust pub fn try_from_configs_with_shadow_limits( cpu_limit: u64, mem_limit: u64, cpu_shadow_limit: u64, mem_shadow_limit: u64, cpu_cost_params: ContractCostParams, mem_cost_params: ContractCostParams, ) -> Result; ``` ### Parameters - **cpu_limit** (u64) - Required - Max modelled CPU instructions (ns) for the invocation. - **mem_limit** (u64) - Required - Max modelled memory bytes. - **cpu_shadow_limit** (u64) - Required - Shadow CPU budget limit. - **mem_shadow_limit** (u64) - Required - Shadow memory budget limit. - **cpu_cost_params** (ContractCostParams) - Required - XDR `ContractCostParamEntry` list per `ContractCostType` for CPU. - **mem_cost_params** (ContractCostParams) - Required - Same for memory. ### Returns - **Result** - Ok(Budget) on success, Err(HostError) on failure. ``` -------------------------------- ### set_auth_manager Source: https://github.com/stellar/rs-soroban-env/blob/main/_autodocs/api-reference/auth.md Restores a snapshot to preserve auth state across test setup. ```APIDOC ## set_auth_manager ### Description Restores a snapshot to preserve auth state across test setup. ### Method `pub fn set_auth_manager(&self, auth_manager: AuthorizationManager) -> Result<(), HostError>` ### Rust Signature ```rust pub fn set_auth_manager(&self, auth_manager: AuthorizationManager) -> Result<(), HostError> ``` ### Parameters - **auth_manager** (AuthorizationManager) - Required - The authorization manager snapshot to restore. ### Returns - `Result<(), HostError>` - `Ok(())` on success, or a `HostError`. ### Notes - Visibility/feature: `#[cfg(any(test, feature = "testutils"))] pub fn` - This is part of the `Host` implementation in `auth.rs`. ``` -------------------------------- ### Vm::from_parsed_module_and_wasmi_linker Source: https://github.com/stellar/rs-soroban-env/blob/main/_autodocs/api-reference/vm.md Instantiates a Vm from pre-parsed module and linker inputs, also checking that the ledger protocol is supported by the host. ```APIDOC ## Vm::from_parsed_module_and_wasmi_linker ### Description Instantiates a Vm from pre-parsed module and linker inputs, also checking that the ledger protocol is supported by the host. ### Method Constructor ### Signature ```rust pub fn from_parsed_module_and_wasmi_linker(host: &Host, contract_id: ContractId, parsed_module: Arc, wasmi_linker: &wasmi::Linker) -> Result, HostError> ``` ### Parameters - **host** (`&Host`) - Required - The host environment. - **contract_id** (`ContractId`) - Required - The contract identifier. - **parsed_module** (`Arc`) - Required - The pre-parsed module. - **wasmi_linker** (`&wasmi::Linker`) - Required - The wasmi linker. ### Returns - **Result, HostError>** - A reference-counted Vm instance on success, or a HostError on failure. ### Errors - Returns `HostError` if the ledger protocol is not supported. ``` -------------------------------- ### Reading events from a host Source: https://github.com/stellar/rs-soroban-env/blob/main/_autodocs/api-reference/events.md Shows how to retrieve and iterate over events from a Host after invoking a contract. Uses get_events() to get all events and get_contract_events() to filter out diagnostics. ```rust use soroban_env_host::{Host, HostError}; let host = Host::default(); // ... invoke a contract via e2e_invoke::invoke_host_function or Host::invoke_function ... let events = host.get_events()?; for e in events.0 { println!("event: {e} failed_call={}", e.failed_call); } let contract_only = host.get_contract_events()?; // filters diagnostics out # Ok::<(), HostError>(()) ``` -------------------------------- ### Instantiate a VM directly Source: https://github.com/stellar/rs-soroban-env/blob/main/_autodocs/api-reference/vm.md Creates a default Host, constructs a Vm from WASM bytes, and reads the 'contractenvmetav0' custom section, printing its byte length. Uses ContractId::default() for illustration and returns Ok::<(), HostError>(()). ```rust use std::rc::Rc; use soroban_env_host::{Host, Vm, HostError}; let host = Host::default(); let wasm: &[u8] = &[/* contract wasm bytes */]; let vm: Rc = Vm::new(&host, Default::default(), wasm)?; // ContractId::default() for illustration let section = vm.custom_section("contractenvmetav0"); if let Some(bytes) = section { println!("interface-version section: {} bytes", bytes.len()); } # Ok::<(), HostError>(()) ``` -------------------------------- ### impl Default for Host Source: https://github.com/stellar/rs-soroban-env/blob/main/_autodocs/api-reference/host.md Creates a fresh default host with empty storage, default budget, enforcing auth without authorizations, and no ledger info. ```APIDOC ## impl Default for Host ### Description Creates a fresh default host with empty storage, default budget, enforcing auth without authorizations, and no ledger info. ### Method Default constructor ### Signature `impl Default for Host` ### Parameters None ### Returns A new `Host` instance with default configuration. ``` -------------------------------- ### SnapshotSource trait definition Source: https://github.com/stellar/rs-soroban-env/blob/main/_autodocs/api-reference/storage.md Trait implemented by embedders and `AutoRestoringSnapshotSource` to provide access to ledger entries. The `get` method returns the entry and its live-until ledger if it exists, or `None`. ```rust pub trait SnapshotSource { /// Returns the ledger entry for the key and its live_until ledger if entry /// exists, or `None` otherwise. fn get(&self, key: &Rc) -> Result, HostError>; } ``` -------------------------------- ### Budget constructors: try_from_configs and try_from_configs_with_shadow_limits Source: https://github.com/stellar/rs-soroban-env/blob/main/_autodocs/api-reference/budget.md Defines the two public constructors for the Budget type. try_from_configs creates a budget with CPU and memory limits and cost parameters. try_from_configs_with_shadow_limits additionally accepts shadow limits for CPU and memory. Both return Result. ```rust impl Budget { pub fn try_from_configs( cpu_limit: u64, mem_limit: u64, cpu_cost_params: ContractCostParams, mem_cost_params: ContractCostParams, ) -> Result; pub fn try_from_configs_with_shadow_limits( cpu_limit: u64, mem_limit: u64, cpu_shadow_limit: u64, mem_shadow_limit: u64, cpu_cost_params: ContractCostParams, mem_cost_params: ContractCostParams, ) -> Result; } ``` -------------------------------- ### Simulate InvokeHostFunctionOp with soroban_simulation Source: https://github.com/stellar/rs-soroban-env/blob/main/_autodocs/api-reference/simulation.md Use this to simulate an InvokeHostFunctionOp with the SDK. It loads network config from a snapshot, fills ledger info, and calls simulate_invoke_host_function_op with recording auth mode. The result includes invoke_result, transaction_data, and auth entries; diagnostics can be enabled via the last argument. ```rust use std::rc::Rc; use soroban_env_host::storage::SnapshotSource; use soroban_env_host::e2e_invoke::RecordingInvocationAuthMode; use soroban_env_host::xdr::HostFunction; use soroban_env_host::LedgerInfo; use soroban_simulation::{ NetworkConfig, AutoRestoringSnapshotSource, SimulationAdjustmentConfig, simulate_invoke_host_function_op, }; let snapshot: Rc = /* your ledger snapshot */; let network_config = NetworkConfig::load_from_snapshot(snapshot.as_ref())?; let mut ledger_info = LedgerInfo::default(); // protocol_version, sequence_number, timestamp, network_id, base_reserve... network_config.fill_config_fields_in_ledger_info(&mut ledger_info); let host_fn: HostFunction = /* invoke-contract XDR */; let result = simulate_invoke_host_function_op( snapshot.clone(), &network_config, &SimulationAdjustmentConfig::default_adjustment(), &ledger_info, host_fn, RecordingInvocationAuthMode::recording(true, false), &source_account, [0u8; 32], true, // enable_diagnostics )?; match result.invoke_result { Ok(scval) => println!("success: {:?}", scval), Err(e) => println!("failed: {}", e.error), } if let Some(tx_data) = result.transaction_data { println!("resource fee: {}", tx_data.resource_fee); println!("recorded auth entries to sign: {}", result.auth.len()); } # Ok::<(), anyhow::Error>(()) ``` -------------------------------- ### Basic construction and inspection of Val Source: https://github.com/stellar/rs-soroban-env/blob/main/_autodocs/api-reference/val.md Shows how to create Val from u32 and bool, check tags, and use Val::VOID. Uses soroban_env_common types. ```rust use soroban_env_common::{Val, Tag, Bool, U32Val, ConversionError}; let v: Val = Val::from_u32(42); assert_eq!(v.get_tag(), Tag::U32Val); assert_eq!(v, Val::from(42u32)); let b: Bool = Val::from_bool(true); assert!(b.to_val().is_true()); assert_eq!(Val::VOID.to_val().get_tag(), Tag::Void); ``` -------------------------------- ### Convert symbols using the environment Source: https://github.com/stellar/rs-soroban-env/blob/main/_autodocs/api-reference/symbol.md Shows how to create symbols using an environment host, which supports both small symbols and longer symbols that require allocation as SymbolObjects. ```rust use soroban_env_common::{Env, TryFromVal, Symbol, Host /* from soroban_env_host */}; let host = Host::default(); // "transfer" fits the small form; a longer valid name allocates a SymbolObject. let sym: Symbol = Symbol::try_from_val(&host, &"transfer")?; let long: Symbol = Symbol::try_from_val(&host, &"very_long_function_name")?; // SymbolStr works for both forms: let text = SymbolStr::try_from_val(&host, &sym)?; # Ok::<(), soroban_env_host::HostError>(()) ``` -------------------------------- ### Catch budget-exceeded error Source: https://github.com/stellar/rs-soroban-env/blob/main/_autodocs/api-reference/budget.md Attempts to charge a huge memory allocation and checks that the returned HostError has the Budget type and ExceededLimit code. The example uses u64::MAX to force the limit and asserts on the error's type and code. ```rust use soroban_env_host::xdr::{ContractCostType, ScErrorCode, ScErrorType}; use soroban_env_host::{Budget, HostError}; let budget = Budget::default(); let result = budget.charge(ContractCostType::MemAlloc, Some(u64::MAX)); if let Err(e) = result { // HostError wraps Error; the code is (Budget, ExceededLimit) let err: soroban_env_common::Error = e.error; assert!(err.is_type(ScErrorType::Budget) && err.is_code(ScErrorCode::ExceededLimit)); } ``` -------------------------------- ### Map a foreign error with context Source: https://github.com/stellar/rs-soroban-env/blob/main/_autodocs/api-reference/host-error.md Use this snippet to map a foreign error into a HostError using the host's map_err method. The example shows mapping a ParseIntError and an xdr::Error, with a comment that the pattern works for types with a From impl. ```rust use soroban_env_host::{Host, HostError, ErrorHandler}; use soroban_env_common::Error; let host = Host::default(); let fallible: Result = "not-a-number".parse(); let mapped: Result = host.map_err(fallible); // ParseIntError: From<...> for Error is not defined, so the code above shows // the pattern; in the host codebase this is done for types with a From // impl (e.g. xdr errors), e.g.: let xdr_res: Result = /* ... */; let mapped: Result = host.map_err(xdr_res); # Ok::<(), HostError>(mapped.map(|_| ())?) ``` -------------------------------- ### Auto-restoring simulator with AutoRestoringSnapshotSource Source: https://github.com/stellar/rs-soroban-env/blob/main/_autodocs/api-reference/simulation.md Use this to simulate with automatic restoration of archived entries. It creates an AutoRestoringSnapshotSource from a base snapshot, loads network config, and simulates a restore operation. The restore operation's resources are printed if available. ```rust use std::rc::Rc; use soroban_env_host::storage::SnapshotSource; use soroban_env_host::LedgerInfo; use soroban_simulation::{AutoRestoringSnapshotSource, NetworkConfig, SimulationAdjustmentConfig}; let base: Rc = /* snapshot incl. archived entries */; let ledger_info = LedgerInfo::default(); let auto_restoring = AutoRestoringSnapshotSource::new(base, &ledger_info)?; // ... run simulation with `Rc::new(auto_restoring)` as the snapshot ... let network_config = NetworkConfig::load_from_snapshot(&*auto_restoring)?; let restore_op = auto_restoring.simulate_restore_keys_op( &network_config, &SimulationAdjustmentConfig::no_adjustments(), &ledger_info, )?; if let Some(res) = restore_op { println!("restore op resources: {:?}", res.transaction_data.resources); } # Ok::<(), anyhow::Error>(()) ``` -------------------------------- ### Classifying XDR values example Source: https://github.com/stellar/rs-soroban-env/blob/main/_autodocs/api-reference/object.md Shows how to use ScValObjRef::classify and ScValObject::classify to determine whether an ScVal should be represented as an object. Small values stay inline, large byte arrays become objects, and Vec(None) classification is checked. ```rust use soroban_env_common::{ScValObjRef, ScValObject}; use soroban_env_common::xdr::ScVal; let small = ScVal::U32(5); assert!(ScValObjRef::classify(&small).is_none()); // stays inline let big_bytes = ScVal::Bytes(vec![0u8; 64].try_into().unwrap()); assert!(ScValObjRef::classify(&big_bytes).is_some()); // must be a host object let classified = ScValObject::classify(ScVal::Vec(None).unwrap_or(ScVal::Void)).is_ok(); ``` -------------------------------- ### Match errors from an env call Source: https://github.com/stellar/rs-soroban-env/blob/main/_autodocs/api-reference/host-error.md Use this snippet to match errors returned by a Host method, checking the error type and code. The example calls get_ledger_protocol_version() and asserts the error is of type Context and code InternalError, printing diagnostics via Debug. ```rust use soroban_env_common::xdr::{ScErrorCode, ScErrorType}; use soroban_env_host::{Host, HostError}; let host = Host::default(); // A call that fails because, e.g., ledger info is unset: match host.get_ledger_protocol_version() { Ok(v) => println!("protocol {v}"), Err(he) => { // he.error is the common Error code; diagnostics in he via Debug assert!(he.error.is_type(ScErrorType::Context)); assert!(he.error.is_code(ScErrorCode::InternalError)); eprintln!("{he:?}"); // includes event log + backtrace in debug builds } } ``` -------------------------------- ### Converting U256Val to XDR with ScVal::try_from_val Source: https://github.com/stellar/rs-soroban-env/blob/main/_autodocs/api-reference/num.md Converts a `U256Val` to an `ScVal` using `ScVal::try_from_val` with a `Host` instance. The example creates a `U256Val` from `U256::from(42u8)` and expects `ScVal::U256`. The `Ok::<(), soroban_env_host::HostError>(())` line indicates the success type. ```rust use soroban_env_common::{U256Val, U256, xdr::ScVal, TryFromVal, Env, Host}; let host = Host::default(); let val: U256Val = U256::from(42u8).into(); let scval = ScVal::try_from_val(&host, &val)?; // ScVal::U256 # Ok::<(), soroban_env_host::HostError>(()) ``` -------------------------------- ### Enabling debug diagnostics Source: https://github.com/stellar/rs-soroban-env/blob/main/_autodocs/api-reference/events.md Shows how to enable debug diagnostics on a Host for preflight simulation. Uses set_diagnostic_level(DiagnosticLevel::Debug) or enable_debug(). Diagnostic work is metered against the shadow budget and does not affect replicated outputs. ```rust use soroban_env_host::{Host, HostError}; use soroban_env_host::events::DiagnosticLevel; let host = Host::default(); host.set_diagnostic_level(DiagnosticLevel::Debug)?; // or host.enable_debug() // Diagnostic work is metered against the shadow budget and never affects // replicated outputs; contract/system events are unchanged. # Ok::<(), HostError>(()) ``` -------------------------------- ### Vm::get_all_host_functions_with_supported_protocol_range Source: https://github.com/stellar/rs-soroban-env/blob/main/_autodocs/api-reference/vm.md Returns a list of all host functions with their module name, function name, arity, and supported protocol range. This is only available with the testutils feature. ```APIDOC ## Vm::get_all_host_functions_with_supported_protocol_range ### Description Returns a list of all host functions with their module name, function name, arity, and supported protocol range. This is only available with the testutils feature. ### Method Static Method ### Signature ```rust #[cfg(feature = "testutils")] pub fn get_all_host_functions_with_supported_protocol_range() -> Vec<(&'static str, &'static str, u32, Option, Option)> ``` ### Returns - **Vec<(&'static str, &'static str, u32, Option, Option)>** - A vector of tuples containing (module_str, fn_str, arity, min_proto, max_proto). ``` -------------------------------- ### Enforce invocation resource limits during tests with InvocationResourceLimits Source: https://github.com/stellar/rs-soroban-env/blob/main/_autodocs/api-reference/invocation-metering.md Use this snippet to enforce transaction-like limits during tests. It creates a Host, enables metering, defines an InvocationResourceLimits struct with specific thresholds, and sets them on the host. Invocations exceeding these limits will panic with diagnostics. The example returns Ok(()) using the HostError type. ```rust use soroban_env_host::{Host, HostError}; use soroban_env_host::InvocationResourceLimits; let host = Host::default(); host.enable_invocation_metering(); let limits = InvocationResourceLimits { instructions: 100_000_000, mem_bytes: 40_000_000, disk_read_entries: 64, write_entries: 16, ledger_entries: 128, disk_read_bytes: 512_000, write_bytes: 128_000, contract_events_size_bytes: 64_000, max_contract_data_key_size_bytes: 200, max_contract_data_entry_size_bytes: 64 * 1024, max_contract_code_entry_size_bytes: 256 * 1024, }; host.set_invocation_resource_limits(Some(limits))?; // Invocations exceeding these limits now panic with diagnostics. # Ok::<(), HostError>(()) ``` -------------------------------- ### Host invocation metering methods Source: https://github.com/stellar/rs-soroban-env/blob/main/_autodocs/api-reference/invocation-metering.md Shows the Host methods for enabling invocation metering and setting resource limits. enable_invocation_metering forces debug mode on and flips the meter's enabled flag; it requires the testutils/test feature-gated field. set_invocation_resource_limits(Some(limits)) also resets budget limits to the resource limits' caps, while None disables resource checks and budget limit checks via Budget::reset_unlimited. Panics if metering is disabled. ```rust impl Host { /// Enables invocation metering (it's disabled by default). pub fn enable_invocation_metering(&self); #[cfg(any(test, feature = "testutils"))] pub fn set_invocation_resource_limits( &self, limits: Option, ) -> Result<(), HostError>; } ``` -------------------------------- ### Contract function using Guest environment Source: https://github.com/stellar/rs-soroban-env/blob/main/_autodocs/api-reference/guest.md Shows a contract function that uses the `Guest` environment to call `Env` methods. It creates a `Guest` instance, converts a symbol, creates a vector, and calls a contract function. Errors are `Infallible`, so `unwrap()` is used. ```rust use soroban_env_guest::{ Env, Guest, Symbol, TryFromVal, U32Val, Val, VecObject, }; #[no_mangle] pub extern "C" fn my_contract_fn() -> Val { let env = Guest; // zero-sized; Copy // Any env method call compiles to a direct wasm import call. // Errors are Infallible, so ?-free code treats them as impossible: let sym = Symbol::try_from_val(&env, &"increment").unwrap(); let args: VecObject = env.vec_new_from_slice(&[Val::from(1u32)]).unwrap(); let _v: Val = env.call(env.get_current_contract_address().unwrap(), sym, args).unwrap(); Val::VOID.into() } ``` -------------------------------- ### switch_to_recording_auth_inherited_from_snapshot Source: https://github.com/stellar/rs-soroban-env/blob/main/_autodocs/api-reference/auth.md Switches to recording auth inheriting state from a snapshot. ```APIDOC ## switch_to_recording_auth_inherited_from_snapshot ### Description Switches to recording auth inheriting state from a snapshot. ### Method `pub fn switch_to_recording_auth_inherited_from_snapshot(&self) -> Result<(), HostError>` ### Rust Signature ```rust pub fn switch_to_recording_auth_inherited_from_snapshot(&self) -> Result<(), HostError> ``` ### Returns - `Result<(), HostError>` - `Ok(())` on success, or a `HostError`. ### Notes - Visibility/feature: `#[cfg(any(test, feature = "testutils"))] pub fn` - This is part of the `Host` implementation in `auth.rs`. ``` -------------------------------- ### obj_from_u256_pieces(hi_hi: u64, hi_lo: u64, lo_hi: u64, lo_lo: u64) -> U256Object Source: https://github.com/stellar/rs-soroban-env/blob/main/_autodocs/api-reference/env-functions.md Constructs a 256-bit unsigned integer object from four 64-bit pieces. ```APIDOC ## obj_from_u256_pieces ### Description Create a U256Object from four u64 pieces. ### Parameters - **hi_hi** (u64) - Highest 64 bits. - **hi_lo** (u64) - Second 64 bits. - **lo_hi** (u64) - Third 64 bits. - **lo_lo** (u64) - Lowest 64 bits. ### Returns - U256Object ``` -------------------------------- ### set_shadow_budget_limits Source: https://github.com/stellar/rs-soroban-env/blob/main/_autodocs/api-reference/host.md Sets shadow budget limits for CPU and memory. ```APIDOC ## set_shadow_budget_limits ### Description Sets shadow budget limits for CPU and memory. ### Method `pub fn set_shadow_budget_limits(&self, cpu: u64, mem: u64) -> Result<(), HostError>` ### Parameters - `cpu` (u64) - Required - CPU limit. - `mem` (u64) - Required - Memory limit. ### Returns - `Result<(), HostError>` - Ok if the limits were set successfully, otherwise a HostError. ```