Instalar com Codex ou Claude Copie este prompt, cole no Codex, Claude ou outro assistente e deixe que ele revise a página da skill e instale para você.
Um comando direto ignora o prompt de revisão. Verifique a origem antes de executá-lo.
Instruções da origem · Visualização somente leitura
name
subsystem-summary-of-soroban-env
description
read this skill for a token-efficient summary of the soroban-env subsystem
Soroban Env Subsystem (p26) — Technical Summary
Overview
The Soroban environment subsystem is split into two crates: soroban-env-common and soroban-env-host. Together they define the host-guest interface for Soroban smart contracts. soroban-env-common defines the ABI types and trait interfaces shared between guest (Wasm) and host code. soroban-env-host provides the concrete Host implementation that executes contracts, manages storage, budgets, authorization, events, and the Wasm VM.
The p26 host only supports protocol version 26 and later (MIN_LEDGER_PROTOCOL_VERSION = 26).
soroban-env-common
Val — The Universal 64-bit Value Type
Val (val.rs) is a 64-bit (u64) union type that is the fundamental ABI type crossing the host-guest boundary. It uses bit-packing:
Low 8 bits: Tag enum indicating the type.
Upper 56 bits: body, optionally subdivided into a 32-bit major and 24-bit minor.
Tag categories:
Small tags (0–14): Values packed entirely within the 56-bit body — False, True, Void, Error, U32Val, I32Val, U64Small, I64Small, TimepointSmall, DurationSmall, , , , , .
U128Small
I128Small
U256Small
I256Small
SymbolSmall
Object tags (64–78): Reference host-side objects via a 32-bit handle in the major field — U64Object, I64Object, TimepointObject, DurationObject, U128Object, I128Object, U256Object, I256Object, BytesObject, StringObject, SymbolObject, VecObject, MapObject, AddressObject, MuxedAddressObject.
Tag::Bad (0x7f): Sentinel for mis-tagged values.
Small values (numbers that fit in 56 bits, symbols ≤9 chars) avoid host object allocation. Larger values overflow to host objects transparently.
Wrapper Types
Type-safe wrappers around Val that statically guarantee the tag:
Object — any object-tagged Val; carries a 32-bit handle.
Symbol / SymbolSmall / SymbolObject — identifiers restricted to [a-zA-Z0-9_]. SymbolSmall packs up to 9 chars into 54 bits using 6-bit codes. SymbolStr is a fixed-size buffer for extracting symbol bytes.
EnvBase (env.rs) — base trait with associated Error type, integrity checks, tracing hooks, and slice-passing helper methods (bytes_copy_from_slice, bytes_new_from_slice, map_new_from_slices, vec_new_from_slice, etc.). These bypass the Wasm ABI for trusted callers.
Env — generated via the call_macro_with_all_host_functions! x-macro from env.json. Declares all host functions that guest contracts can call. Each method takes and returns only 64-bit values (Val and wrappers). The x-macro allows the same function list to be reflected in multiple contexts (trait declaration, dispatch, function info tables).
VmCallerEnv (vmcaller_env.rs) — variant of Env where each method takes an additional &mut VmCaller<Self::VmUserState> parameter, allowing host function implementations to access the Wasm Caller context (e.g., for linear memory access). A blanket impl Env for T where T: VmCallerEnv passes VmCaller::none() automatically, so native callers don't need to deal with VmCaller.
Convert and Compare Traits
Convert<F, T> — generic fallible conversion trait. TryFromVal<E, V> / TryIntoVal<E, V> — Env-aware conversion traits used to convert between Rust types and Val (e.g., i64 <-> Val goes through small-or-object path via the Env). Compare<T> — Env-aware ordering trait (needed because comparing objects requires host access).
ConversionError
Minimal uninformative error for ubiquitous tag/number conversions in Wasm, converting to Error(ScErrorType::Value, ScErrorCode::UnexpectedType).
ScValObject / ScValObjRef
Helper types that classify which ScVal variants require host-side object storage vs. fitting into a small Val.
soroban-env-host
Host — The Core Runtime
Host (host.rs) is a newtype around Rc<HostImpl> implementing VmCallerEnv (and thus Env). It is the concrete environment that executes Soroban contracts. HostImpl is a #[derive(Clone, Default)] struct containing all mutable state behind RefCells:
objects: Vec<HostObject> — the host object table (indexed by absolute handles).
storage: Storage — ledger entry access.
context_stack: Vec<Context> — call stack of frames.
budget: Budget — CPU/memory metering (Rc-shared, not deep-cloned).
events: InternalEventsBuffer — contract and diagnostic events.
Context wraps a Frame with optional per-frame Prng and InstanceStorageMap.
RollbackPoint captures (StorageMap, events_len, AuthorizationManagerSnapshot) for sub-transaction rollback.
Host::with_frame(frame, f) — the central frame lifecycle method. Pushes a context (capturing rollback point), runs closure, pops context. On error, rolls back storage and events. Handles Ok(Error) returns from contracts (converts to Err), distinguishing contract errors from spoofed system errors. Enforces depth limit (DEFAULT_HOST_DEPTH_LIMIT).
Key operations: get, try_get, put, del, has, get_with_live_until_ledger. Each checks footprint first and delegates to the underlying map. TTL extension methods handle extend_ttl and restore.
Budget (budget.rs) is an Rc<RefCell<BudgetImpl>> tracking CPU instructions and memory bytes consumption. It uses a cost model based on ContractCostType enum variants.
BudgetImpl contains:
cpu_insns: BudgetDimension — CPU budget with per-cost-type linear models (const_term + lin_term * input).
is_in_shadow_mode: bool — when true, charges are tracked but don't fail on exceeding limits (used for debug/diagnostic work).
fuel_costs: wasmi::FuelCosts — calibrated Wasm fuel costs for wasmi.
depth_limit: u32 — recursion depth limit.
Budget::charge(ty, input) is the core metering call, invoked pervasively. It updates tracking, charges both CPU and memory dimensions, and checks limits. In shadow mode, limits aren't enforced.
AsBudget trait allows both Budget and Host to be used as budget references.
Fuel bridge: get_wasmi_fuel_remaining() converts remaining CPU budget to wasmi fuel units. Fuel is transferred to/from wasmi at host function call boundaries.
Metered Data Structures
MeteredOrdMap<K, V, Ctx> (host/metered_map.rs) — sorted Vec<(K, V)> with binary search. All operations (insert, get, delete) charge budget based on DeclaredSizeForMetering. Used for HostMap, FootprintMap, StorageMap.
MeteredVector<A> (host/metered_vector.rs) — Vec<A> wrapper with metered insert/append/remove. Used for HostVec.
MeteredClone trait (host/metered_clone.rs) — charges MemCpy budget for cloning, with DeclaredSizeForMetering providing stable size constants (not size_of which may vary). charge_shallow_copy and charge_heap_alloc are the underlying charging functions.
Vm (vm.rs) wraps a wasmi::Instance for a single Wasm module:
contract_id: ContractId
module: Arc<ParsedModule>
wasmi_store: RefCell<wasmi::Store<Host>>
wasmi_instance: wasmi::Instance
wasmi_memory: Option<wasmi::Memory>
Rejects modules with floating point or start functions.
ParsedModule (vm/parsed_module.rs) — pre-parsed, validated Wasm module. Stores wasmi::Module, VersionedContractCodeCostInputs (V0 = just byte length, V1 = detailed instruction/function/global counts), and imported symbol set. Charges parsing and instantiation costs separately.
ModuleCache (vm/module_cache.rs) — caches Arc<ParsedModule> keyed by code hash, shared across invocations within a host. Can be installed externally or built from host storage.
Dispatch — Host Function Routing
dispatch.rs uses the call_macro_with_all_host_functions! x-macro to generate one dispatch function per host function. Each dispatch function:
Transfers wasmi fuel to host CPU budget (FuelRefillable).
Charges DispatchHostFunction cost.
Converts wasmi i64 args to Val/wrappers (with relative-to-absolute object translation via RelativeObjectConversion).
Calls the VmCallerEnv method on Host.
Converts result back (absolute-to-relative).
Transfers residual CPU budget back to wasmi fuel.
func_info.rs — static HOST_FUNCTIONS array of HostFuncInfo structs (mod name, fn name, arity, wrap function, protocol bounds). Used by linker setup and introspection.
Protocol gating: each host function can have optional min_proto/max_proto bounds checked at dispatch time.
Events
events/mod.rs — HostEvent wraps ContractEvent XDR with failed_call flag. InternalEventsBuffer (events/internal.rs) stores events during execution. Events are rolled back on frame failure. system_events.rs emits system events for contract lifecycle operations.
Event types: Contract (user-emitted), System (host-emitted lifecycle), Diagnostic (debug-only, guarded by DiagnosticLevel::Debug and shadow budget).
Authorization
AuthorizationManager (auth.rs) handles both authorization (is action allowed?) and authentication (is credential authentic?). Operates in two modes:
Enforcing: validates SorobanAuthorizationEntry trees against actual invocation patterns.
Recording: captures auth requirements during preflight.
Address types for auth:
Invoker contract — implicit auth from call chain.
Stellar account with credentials — classic multisig to medium threshold.
Transaction source account — pre-authenticated by transaction signatures.
Custom account contract — delegates to __check_auth export.
require_auth(Address) is the main entrypoint. Matches AuthorizedInvocation trees against execution context. Each pattern node matches at most once per transaction.
Call __constructor (protocol ≥22; missing constructor OK if 0 args).
Conversion
host/conversion.rs — methods on Host for converting between ScVal/XDR types and Val/host objects. Includes to_valid_host_val, from_host_val, address/hash extraction helpers, and ScMap↔HostMap conversions. All operations are metered.
Error Handling
HostError (host/error.rs) wraps an Error (the 64-bit Val-encoded error) plus optional DebugInfo (event log + backtrace). ErrorHandler trait provides map_err for wasmi error conversion. Errors are augmented with context via augment_err_result.
Recoverable vs non-recoverable: ScErrorType::Contract errors are recoverable (can be caught by try_call). All others (Budget, Internal, etc.) are non-recoverable and propagate up.
e2e_invoke — Embedder Integration
e2e_invoke.rs provides the top-level entry point for executing Soroban host functions from embedders (stellar-core, RPC). Key types:
host/prng.rs — Prng wraps ChaCha20Rng with metered byte-drawing. Base PRNG seeds per-frame sub-PRNGs deterministically. Separate unmetered PRNGs exist for recording-auth nonces and test data.
Tracing
host/trace.rs — TraceHook, TraceEvent, TraceRecord, TraceState for lifecycle observation. Events include PushCtx, PopCtx, EnvCall, EnvRet. Used for debugging and testing only; disabled during debug-mode operations to avoid observation leaks.
Key Control Flows
Contract Invocation
Embedder calls e2e_invoke with HostFunction, footprint, auth entries.
Host is constructed with Storage and Budget from network config.
For InvokeContract: resolves contract instance, loads Wasm, instantiates Vm.
Host::with_frame(Frame::ContractVM, ..) pushes contract frame with rollback point.
VM calls exported function. Wasm instructions consume wasmi fuel.
Host functions called from Wasm go through dispatch: fuel→budget, args relative→absolute, call VmCallerEnv method, result absolute→relative, budget→fuel.
On return, frame pops. On error, storage/events roll back to rollback point.
Host::try_finish() extracts final (Storage, Events).