Stellar · Soroban · Test tooling
Soroban Testkit
Soroban Testkit is an open-source testing and debugging framework for Soroban smart contracts. It layers ergonomic fixtures, assertions, budget introspection and property-testing strategies on top of the official SDK, so contract tests are shorter, faster to write, and far closer to how they behave on-chain.
Why Testkit
The Soroban SDK ships solid primitives — Env::default(), testutils, event inspection — but day-to-day contract testing still has rough edges that every team re-solves on its own.
setUp context builder.
proptest strategies for SDK types.
The Crates
Each crate is independent — adopt one, or combine all four for a complete testing stack.
Inspect & measure
Budget snapshots with call-level diffs, on-chain error decoding, per-invocation memory pressure profiles, and storage inspection across instance, persistent and temporary tiers.
Assert fluently
Readable matchers for contract events and authorizations, filterable by contract id and topic.
Set up once
A reusable test context plus a builder for environments, admin accounts and generated users, with ledger control and simulated archival sweeps.
Generate wildly
Property-testing strategies for token amounts, ledger sequences, timestamps and 32-byte account or contract addresses that respect Soroban limits.
Architecture
soroban-testkit/ Cargo workspace, resolver 2
├── crates/soroban-testkit-core budget snapshots · error decoding · storage
├── crates/soroban-testkit-assert event matchers · authorization matchers
├── crates/soroban-testkit-fixtures test context · context builder
└── crates/soroban-testkit-generators proptest strategies · address generators
A First Look
Build a context, register the contract, invoke a call, then assert on events and budget in the same breath.
#![allow(unused)]
fn main() {
use soroban_testkit_assert::events::EventMatcher;
use soroban_testkit_fixtures::TestContext;
#[test]
fn transfer_emits_event() {
let ctx = TestContext::new();
// arrange: register your contract against ctx.env
// act: invoke the contract client
EventMatcher::new(&ctx.env).assert_emitted();
}
}
Full walkthroughs live in Quick Start, Testing Patterns and Budget-Aware Testing.
Stellar Wave
This project is funded through the Stellar Wave program on Drips Network. Every issue carries a complexity label — Trivial 100 pts Medium 150 pts High 200 pts — and rewards land once your PR is merged.
Pick up an issueBuilt and maintained by Stellar Crucible · Apache-2.0 licensed · contributions welcome.
Installation
Add only the crates your test suite needs. All four are published on crates.io as soroban-testkit-core, soroban-testkit-assert, soroban-testkit-fixtures and soroban-testkit-generators. If you would rather pin the source, every release is also tagged — a tag points at a commit whose CI (tests, clippy and the cargo deny supply-chain gate) is green.
Add the dev-dependencies
[dev-dependencies]
soroban-testkit-core = "0.4.1"
soroban-testkit-assert = "0.4.1"
soroban-testkit-fixtures = "0.4.1"
soroban-testkit-generators = { version = "0.4.1", features = ["proptest"] }
The same set pinned to the release tag:
[dev-dependencies]
soroban-testkit-core = { git = "https://github.com/stellar-crucible/soroban-testkit", tag = "v0.4.1" }
soroban-testkit-assert = { git = "https://github.com/stellar-crucible/soroban-testkit", tag = "v0.4.1" }
soroban-testkit-fixtures = { git = "https://github.com/stellar-crucible/soroban-testkit", tag = "v0.4.1" }
soroban-testkit-generators = { git = "https://github.com/stellar-crucible/soroban-testkit", tag = "v0.4.1", features = ["proptest"] }
Install steps
-
Check your toolchain
Soroban SDK v28 needs a recent Cargo. Run
rustc --versionand upgrade withrustup update stableif it reports anything below 1.91. -
Pin the SDK your contract already uses
Testkit is built against SDK v28. Match the
soroban-sdkversion in your contract crate so thetestutilsfeatures resolve to one copy. -
Enable
testutilsin testsAddress generation, event inspection and auth recording are gated behind the SDK's
testutilsfeature — the dev-dependency above turns it on for the test profile only. -
Verify the wiring
Run
cargo test. A green compile means the crates are linked; the Quick Start gives you a first test to paste in.
Feature flags
soroban-testkit-generators
| Feature | Description |
|---|---|
proptest (default) | Enable proptest strategies — the strategies and xdr modules are gated on it |
arbitrary | Arbitrary implementations for cargo-fuzz and afl harnesses — see Fuzzing with arbitrary. Builds without proptest |
For a fuzz-only crate, turn proptest off: soroban-testkit-generators = { version = "0.4.1", default-features = false, features = ["arbitrary"] }.
#[mock_contract] lives in its own crate, soroban-testkit-mock; add it as a dev-dependency to generate mock dependency contracts — see Mocking Dependency Contracts.
Testkit is pre-1.0. A 0.x release may break the API, so pin an exact version or a release tag once your suite is green — cargo update can otherwise pull breaking changes from a newer 0.x.
Quick Start
Write a complete Soroban test in about a minute: build a context, register the contract, invoke it, then assert on events and resource cost in the same test.
Imports
#![allow(unused)]
fn main() {
use soroban_sdk::{Env, Address};
use soroban_testkit_fixtures::builder::TestContextBuilder;
use soroban_testkit_assert::events::EventMatcher;
use soroban_testkit_core::budget::BudgetSnapshot;
}
Write a test
-
Build the context
TestContextBuilderhands you a mockedEnvplus ready-made addresses. -
Register the contract
Bind your contract to the context environment and create its client.
-
Invoke the contract
Call the function under test, then read the metering that call left behind.
-
Assert on events and cost
Match the events the call emitted and check its instruction count against a ceiling.
#![allow(unused)]
fn main() {
#[test]
fn test_token_transfer() {
// 1. Create a test context with pre-generated users
let ctx = TestContextBuilder::new()
.with_users(2)
.build();
let sender = &ctx.users[0];
let receiver = &ctx.users[1];
// 2. Register your contract
let contract_id = ctx.env.register(MyContract, ());
let client = MyContractClient::new(&ctx.env, &contract_id);
// 3. Invoke the function under test
client.transfer(sender, receiver, &1000);
// 4. Read the metering that invocation left behind
let cost = BudgetSnapshot::last_invocation(&ctx.env);
// 5. Assert events were emitted, and what they carried
EventMatcher::new(&ctx.env)
.from_contract(&contract_id)
.with_topic("Transfer")
.assert_emitted();
EventMatcher::new(&ctx.env)
.with_topic("Transfer")
.assert_data_matches(|data| data.deserialize::<i128>() == Some(1_000));
// 6. Check resource consumption
assert!(cost.cpu_insns < 500_000);
}
}
The test passes with no extra scaffolding — no manual Env construction, no tuple destructuring over env.events().all(), no separate budget harness.
What’s happening
Setup, once
Eliminates manual Env creation, address generation and auth mocking. Opt out of mocked auth when a test needs explicit authorization.
Readable assertions
Replaces raw tuple iteration over emitted events with a chainable filter by contract and topic.
Costs made visible
Surfaces the per-call CPU-instruction and memory costs that standard Soroban tests never show.
Adopt piecemeal
Each crate stands alone. Start with fixtures, add assertions when your tests grow, keep budget checks for CI.
Next steps
Testing patterns
Layouts for unit, integration and contract-interaction tests.
Budget-aware testing
Turn resource regressions into ordinary failing assertions.
Property testing
Generate Soroban-aware inputs with proptest strategies.
Troubleshooting
Common issues encountered when testing Soroban smart contracts, how to identify them, and how to resolve them.
1. Duplicate soroban-sdk versions in dependency tree
Symptom
The compiler produces a mismatched types error between two identical-looking types:
error[E0308]: mismatched types
--> tests/contract.rs:12:35
|
12 | let client = ContractClient::new(&env, &contract_id);
| ------------------- ^^^^ expected `&soroban_sdk::Env`, found `&soroban_sdk::Env`
|
= note: `soroban_sdk::Env` and `soroban_sdk::Env` have similar names, but are considered distinct types
= note: perhaps two different versions of a crate are being used?
Cause
Cargo resolved two distinct versions of soroban-sdk in your dependency graph. Because Rust treats types from different crate versions as incompatible, an Env from one version cannot be passed to a contract client built against another.
Run cargo tree -d soroban-sdk to inspect duplicates:
soroban-sdk v28.0.0
└── my-tests v0.1.0
soroban-sdk v22.0.0
└── other-dependency v0.2.0
Fix
Align all crates and workspace members to the same soroban-sdk version:
[dependencies]
soroban-sdk = "28.0.0"
Then update your lockfile:
cargo update -p soroban-sdk
2. testutils feature not enabled on soroban-sdk
Symptom
Calling Address::generate or budget inspection methods fails to compile:
error[E0599]: no function or associated item named `generate` found for struct `soroban_sdk::Address` in the current scope
--> tests/test.rs:8:26
|
8 | let addr = Address::generate(&env);
| ^^^^^^^^ function or associated item not found in `Address`
Cause
Test helpers like Address::generate(&env) and ledger controls are guarded behind the SDK’s testutils feature flag.
Fix
Enable the testutils feature in your Cargo.toml under [dev-dependencies]:
[dev-dependencies]
soroban-sdk = { version = "28.0.0", features = ["testutils"] }
And bring the test trait into scope in your test file:
#![allow(unused)]
fn main() {
use soroban_sdk::testutils::Address as _;
}
Alternatively, use TestContextBuilder from soroban-testkit-fixtures, which pre-generates addresses without manual setup.
3. Address used across different Env instances
Symptom
A test panics with a context error:
thread 'test' panicked at 'Context error: BadContext'
Cause
In the Soroban SDK, an Address instance is a host handle bound to the specific Env that created it. Passing an Address created in one Env into a contract invocation on a second Env produces a context mismatch.
Fix
When resetting or creating a fresh environment, migrate addresses across environment boundaries using TestContext::reset():
#![allow(unused)]
fn main() {
use soroban_testkit_fixtures::builder::TestContextBuilder;
let mut ctx = TestContextBuilder::new().with_users(2).build();
// ... test phase 1 ...
// Safely resets the chain while preserving addresses in the new env
ctx.reset();
// ... test phase 2 with same ctx.admin and ctx.user(0) ...
}
4. Events missing from previous contract invocations
Symptom
An event that was emitted earlier in a test is not found by EventMatcher:
thread 'test' panicked at 'Expected an event whose data matches, but no event was emitted'
Cause
By design, EventMatcher::new(&env) scopes event inspection to the most recent contract invocation. If your test calls multiple contract methods sequentially, matching against EventMatcher::new(&env) only inspects the last call.
Fix
To aggregate and assert events across multiple calls, use EventLog:
#![allow(unused)]
fn main() {
use soroban_testkit_assert::events::EventLog;
let mut log = EventLog::new();
// Collect events from each call
log.collect(&env, || client.mint(&user, &100));
log.collect(&env, || client.transfer(&user, &recipient, &50));
// Assert over the full history
log.matcher(&env).with_topic("mint").assert_emitted();
log.matcher(&env).with_topic("transfer").assert_emitted();
}
For single invocations, EventMatcher::new(&env) is all you need. For sequences where early events matter, wrap the sequence in EventLog.
soroban-testkit-core
Budget tracking, error decoding, storage inspection, contract dependency graphs, WASM analysis and host execution profiling — the primitives the rest of Testkit is built on.
Instance storage bloat
InstanceBloatDetector measures the XDR byte footprint of instance keys after
test invocations and reports oversized values or growing vectors/maps:
#![allow(unused)]
fn main() {
use soroban_testkit_core::InstanceBloatDetector;
let mut detector = InstanceBloatDetector::start(&env, &contract);
// Run one or more contract calls...
detector.checkpoint(&env, &contract, "after workflow");
detector.assert_no_bloat(&env, &contract);
println!("{}", detector.report(&env, &contract));
}
The default threshold is 64 KiB. Use
InstanceBloatDetector::with_threshold(bytes) for a project-specific limit.
Warnings include the exact key name and distinguish a threshold breach from a
dynamically growing vector or map.
API at a glance
| Type | Purpose |
|---|---|
BudgetSnapshot | CPU instructions and memory bytes — last_invocation() for the call that just ran |
BudgetRead | Trait implemented by any source capture() can read: invocation resources, the SDK budget, the host Budget |
BudgetGuard | Ceilings and a baseline tolerance for one named operation |
BudgetViolation, ViolationKind | The limit a cost broke, rendered as one parseable line |
BudgetMetric | Which resource a violation was measured against — Cpu or Memory, and the cpu_insns / mem_bytes word as_str() prints for it |
BudgetBaseline | Recorded costs per case, loaded from and saved to a JSON file |
budget_guard! | Macro form of the guard around a single invocation |
InstructionProfiler | CPU instruction deltas across labeled checkpoints, with text and Markdown reports |
InstructionStep | One labeled segment and its consumed CPU instructions |
MemoryPressureAuditor | Measures what each invocation allocated, copied and kept live; measure() returns the call’s value |
AllocationProfile | One invocation’s allocations, allocated bytes, peak live bytes, copied bytes, churn ratio and efficiency score |
AllocationReport | Every measured profile, the hotspot filter and the Markdown report |
DecodedError | A Soroban error code split into category, meaning and context |
ErrorRegistry | Your #[contracterror] codes mapped to the words they mean |
ClientOutcome, unwrap_decoded | Unwrap a v28 try_* client call, panicking with the decoded error |
StorageEntry, StorageTier | A live storage key, its rendered value, tier and expiry ledger |
StorageSnapshot | Every live entry of one contract, captured at a point in time |
StorageDiff, StorageChange | Keys added, removed and rewritten between two snapshots |
FootprintSnapshot | XDR byte size of every live storage key of one contract, by tier |
RentParameters, RentEstimate | Protocol fee parameters and the Stroop cost of keeping a footprint alive for N ledgers |
StorageFootprint | Footprints for several contracts, loaded from and saved to a JSON artifact |
StorageFootprintDiff | Base vs head footprints: growing keys, a Markdown report, a growth threshold |
DependencyGraph | Directed graph of inter-contract calls, built from an invocation’s fn_call diagnostics |
DependencyEdge | One caller → callee edge with its call count and functions |
DependencyCycle | A closed call chain such as A -> B -> C -> A, with self-recursion as A -> A |
storage-footprint-diff | Binary wrapping StorageFootprintDiff for CI |
BudgetDiff, BudgetCaseDiff | Base vs head baselines: signed deltas, growth percent, a Markdown report and the cases past a threshold |
budget-diff | Binary wrapping BudgetDiff for CI |
HostExecutionProfiler, HostExecutionSummary | Repeated call latency and explicit host-operation measurements |
WasmSectionAnalyzer, WasmAnalysis | WASM section sizes, deployment limits and debug/bloat warnings |
StorageFragmentationAnalyzer | Analyzes key-to-value serialization overhead, detects fragmentation, and estimates Stroop savings |
FragmentationReport | Comprehensive metrics across tiers, high-overhead alerts, and Markdown recommendations |
StackDepthAuditor | Reconstructs a contract call chain from host diagnostic events and checks it against a depth cap |
CallFrame | One invocation in that chain: depth, contract id, function |
StackDepthBreach | A trace deeper than its cap, rendered with every frame |
CompatibilityAuditor | Evaluates contracts against upcoming SDK v29 / Protocol 22+ changes and flags deprecated host calls |
CompatibilityScorecard | Actionable readiness scorecard with grades, remediation advice, and Markdown output |
ReentrancyGuardAuditor | Statically and dynamically analyzes lock flag state across multi-frame calls and external callbacks |
LockState | Uninitialized, Locked, or Unlocked reentrancy guard states |
ReentrancyReport | Comprehensive violation diagnostics and visual ASCII state access ordering timelines |
ReentrancyViolation | Flagged uninitialized, unlocked, premature release, dangling, or indirect reentrant calls |
ReentrancyDetector | Watches one invocation for CEI ordering flaws and re-entry attempts, scoped by monitor(label, closure) |
DetectorViolation, DetectorViolationKind | One detector finding: CeiViolation or ReentrancyAttempt |
MockReentrantAttacker | Test contract that publishes a re-entry attempt against a target contract |
emit_storage_read, emit_storage_write, emit_external_call, emit_reentry_attempt | Emit the detector’s instrumentation contract events |
CoverageAuditor | Detects uninvoked functions and dead code across contract WASM, spec XDR, and client definitions |
CoverageReport | Aggregates execution metrics, coverage percentages, Markdown tables, and plaintext summaries |
ClientDefinition | Typed representation of contract client entry points for coverage auditing |
client_definition! | Macro for concise client entry point declaration |
CallTracer | Recovers the cross-contract call tree of an invocation: depth, contract, function, metered CPU/memory and outcome per frame; renders ASCII trees and Mermaid sequence diagrams |
TraceFrame, CallOutcome | One traced contract frame, and whether it returned, failed (with the host error) or is unknown |
TtlInspector | Live TTL of a storage entry in any tier, read without triggering eviction or auto-restore, with the ledger’s rent thresholds |
TtlStatus, RentThresholds | Live / Expired (temporary) / Archived (persistent, instance), and the ledger’s min/max TTL parameters |
TtlExtension | An entry’s TTL before and after a call, checked against the host’s extend_ttl rules |
DiagnosticEventAuditor | Inspects host diagnostic events, categorizes them, enforces count limits, and flags suspicious payloads |
DiagnosticEventReport | Structured audit result with counts, categories, events, and findings; renders text logs |
InstanceBloatDetector | Instance-storage footprint and dynamically growing collection diagnostics |
InstanceBloatWarning | A threshold or collection-growth diagnostic naming the exact storage key |
Budget snapshots
The SDK meters one top-level invocation at a time, and the reading a test wants is usually the call that just finished:
#![allow(unused)]
fn main() {
use soroban_testkit_core::budget::BudgetSnapshot;
client.increment(&caller, &1);
let cost = BudgetSnapshot::last_invocation(&env);
println!("CPU instructions: {}", cost.cpu_insns);
println!("Memory bytes: {}", cost.mem_bytes);
}
capture() takes anything implementing BudgetRead — those invocation
resources, the cumulative env.cost_estimate().budget(), and a
soroban_env_host::budget::Budget you charge by hand. diff() saturates at
zero, so a later snapshot that reads smaller never underflows an assertion.
env.budget() is deprecated; go through env.cost_estimate(). And read the numbers as a comparison between builds rather than as a fee quote: a contract registered as a native test contract is never metered through the VM, so wasm instantiation, execution and rent reads are absent from the reading.
Profiling labeled instruction steps
InstructionProfiler samples the environment’s cumulative CPU instruction
meter. Each checkpoint attributes the work since the previous checkpoint to
its label, so place checkpoints around the operations you want to compare:
#![allow(unused)]
fn main() {
use soroban_testkit_core::InstructionProfiler;
let mut profiler = InstructionProfiler::new(&env);
client.prepare();
profiler.checkpoint("prepare");
client.execute();
profiler.checkpoint("execute");
println!("{}", profiler.format_text(25));
println!("{}", profiler.format_markdown(25));
}
Both reports show each segment’s instruction count and share of the measured
total; segments consuming strictly more than the chosen percentage are marked
HOT. hot_paths_over(25) returns those segments directly. The profiler
measures work charged to Soroban’s host budget; ordinary Rust code executed
outside a host call is not metered by the SDK.
Guards: turning a measurement into a limit
A number on its own passes whatever it is. BudgetGuard states the two things a
test can actually act on — an absolute ceiling, and how far the cost may have
grown relative to the last time it was recorded.
#![allow(unused)]
fn main() {
use soroban_testkit_core::budget::{BudgetGuard, BudgetSnapshot};
let cost = BudgetSnapshot { cpu_insns: 1_500_000, mem_bytes: 200_000 };
BudgetGuard::new("transfer") // the name every failure line carries
.cpu_ceiling(2_000_000)
.mem_ceiling(500_000)
.baseline(Some(previous_cost)) // `None` for a case not recorded yet
.tolerance_percent(10) // 0 means "not one instruction more"
.assert_within(&cost);
}
run() makes the call, reads the metering that call left behind, and returns
whatever the invocation returned:
#![allow(unused)]
fn main() {
let total = BudgetGuard::new("increment")
.cpu_ceiling(20_000_000)
.run(&env, || client.increment(&caller, &1));
}
The budget_guard! macro is the same call written around the invocation, with
the limits in a block:
#![allow(unused)]
fn main() {
use soroban_testkit_core::budget_guard;
budget_guard!(&env, "increment", { cpu_max: 20_000_000, mem_max: 20_000_000 }, || {
client.increment(&caller, &1)
});
}
violations() returns all limits one cost breaks — ceilings first, then growth — and assert_within() panics with one line per breach. A change that costs both CPU and memory is found in one run, and the lines are key=value pairs, so CI can grep them.
BUDGET kind=growth case=transfer metric=cpu_insns actual=1500000 limit=1100000 baseline=1000000 tolerance_percent=10
Baselines: recording cost so a regression is visible
BudgetBaseline is a map of case name to recorded cost that reads and writes a
JSON file, so the numbers a suite enforces live in the repository rather than in
a test’s memory.
#![allow(unused)]
fn main() {
use soroban_testkit_core::budget::BudgetBaseline;
let baseline = BudgetBaseline::load(std::path::Path::new("tests/budget.json"))?;
for (case, cost) in baseline.cases() {
baseline.guard(case).tolerance_percent(5).run(&env, || invoke(case));
}
}
load and save are the file-shaped ends; parse and to_json_string do the same work on a &str and a String, which is what a CI job that reads the baseline from an artifact needs. get(case) reads one recorded cost, record(case, cost) adds or replaces one and returns &mut Self so calls chain, and len / is_empty describe the map.
The file format is one version field and one map of costs:
{
"version": 1,
"cases": {
"increment": { "cpu_insns": 32669, "mem_bytes": 5252 }
}
}
Cases are keyed by name and iterated in name order, so a rewritten file stays a
readable diff. A file whose version is newer than the loader is refused with
BaselineError::UnsupportedVersion rather than silently read with missing cases.
record() and save() write the file; what refreshes it is a policy choice. Committing the file and failing on drift keeps the numbers honest, so most projects regenerate it in one deliberate commit rather than on every test run — Budget-Aware Testing walks through both. The pattern is applied in this repository: examples/counter/budget.json holds the counter's two hot paths, two #[ignore]d tests record and check it, and the Budget baseline workflow runs the check on one pinned runner and reports the numbers on the pull request.
Storage leaks
A contract that opens an order, escrow or position allocates keys for it and is
supposed to remove them when the entity closes. A forgotten remove does not
fail the call that forgot it — it quietly keeps paying rent. StorageLeakDetector
captures the contract’s storage before a lifecycle and reports the persistent and
temporary keys that are still live at teardown.
#![allow(unused)]
fn main() {
use soroban_testkit_core::leak_detector::StorageLeakDetector;
let mut detector = StorageLeakDetector::start(&ctx.env, &contract_id);
// ... open escrow, fund, cancel ...
detector.checkpoint("cancel");
let leaks = detector.detect_orphaned_keys();
assert!(leaks.is_empty(), "Storage leak detected: {leaks:?}");
}
detect_orphaned_keys() returns a Vec<StorageLeak>, each carrying the key,
the storage tier, an estimated byte size (the rendered key and value) and the
label of the first checkpoint that saw the key. A leak renders as one readable
diagnostic:
storage leak: temporary:quote (12 bytes, allocated at open escrow)
assert_no_orphaned_keys() fails with every leak on its own line, and
report(&leaks) returns the same text for a custom assertion message.
Keys present in the baseline snapshot are never reported: the detector judges what the lifecycle allocated, not what the contract already owned. Instance storage is the contract's singleton configuration and is always exempt. A key whose value was rewritten is not a leak either — the comparison is key identity.
Permanent records a contract is supposed to keep — a config record, a factory registry, a fee cache — are exempted by name or wildcard:
#![allow(unused)]
fn main() {
use soroban_testkit_core::StorageLeakDetector;
let detector = StorageLeakDetector::start(&env, &contract)
.ignoring_key("config") // exact key, any tier
.ignoring_key("persistent:fees") // tier-qualified exact key
.ignoring_pattern("order:*") // a family of keys
.ignoring_pattern("*:cache"); // a suffix on the qualified name
assert!(detector.detect_orphaned_keys().is_empty());
}
checkpoint(label) records the current storage as a phase of the lifecycle. The
first checkpoint containing a leaked key becomes its allocation site, so a
failure points at the step that should have released it instead of only naming
the key. Without a checkpoint a leak is still detected; its site reads as
unobserved. detect_orphaned_keys_in(&snapshot) runs the same analysis against
a snapshot the test captured itself.
Error decoding
Soroban reports failures as a packed integer. DecodedError::from_error splits it into the category the host raised it in and the code’s known meaning:
#![allow(unused)]
fn main() {
use soroban_testkit_core::error::DecodedError;
// A v28 client's `try_*` method reports the contract's own error as `Err(Ok(error))`.
let error = client.try_withdraw(&amount).unwrap_err().unwrap();
println!("{}", DecodedError::from_error(&error));
// Soroban Error [storage/3]: MissingValue — a required value was not provided (errors accessing host storage)
}
The ten categories the protocol defines (contract, wasm_vm, context, storage, object, crypto, events, budget, value, auth) and the ten standard codes (ArithDomain, IndexBounds, InvalidInput, MissingValue, ExistingValue, ExceededLimit, InvalidAction, InternalError, UnexpectedType, UnexpectedSize) are all described. An unrecognised number falls back to a sentence naming it rather than a panic.
Your own error codes
A #[contracterror] enum hands the host an integer with no words attached, so the vocabulary is yours to supply. ErrorRegistry is that mapping:
#![allow(unused)]
fn main() {
use soroban_testkit_core::error::{ErrorRegistry, DecodedError};
let registry = ErrorRegistry::new()
.register(101, "Insufficient balance")
.register(102, "Contract is paused");
let decoded = DecodedError::from_error_with(&error, ®istry);
assert_eq!(decoded.to_string(), "Soroban Error [101]: Insufficient balance");
}
Without a registry a contract code still decodes — it just says the code is unregistered, which beats reading Error(3) and going hunting.
In test output
unwrap_decoded unwraps a v28 try_* client call and panics with the decoded sentence, so a failing call reads as a diagnosis in the test log rather than as nested Result debug output:
#![allow(unused)]
fn main() {
use soroban_testkit_core::error::unwrap_decoded;
let total: u32 = unwrap_decoded(client.try_withdraw(&amount));
// panicked at 'Soroban Error [budget/5]: ExceededLimit — a gas or size limit was hit (errors relating to budget limits)'
}
The nesting you see at that call site — Err(Ok(error)) — is the SDK’s own shape for a client method whose contract function returns Result; ClientOutcome<T> is the alias Testkit names it with. unwrap_decoded_with is the same call against an ErrorRegistry, so your own codes come out as words.
DecodedError implements Display, so it also reads well inside assert! messages:
#![allow(unused)]
fn main() {
use soroban_testkit_core::error::DecodedError;
let err = DecodedError {
code: 12,
category: "contract",
message: "Insufficient balance".to_string(),
context: Some("transfer".to_string()),
};
assert!(format!("{}", err).contains("Insufficient balance"));
}
The rest of the module is small. DecodedError::from_contract_code(code) decodes a bare #[contracterror] integer as read from Error::get_code(), with no error value to unpack, and label() renders a code the way the host does — category/code for a host error, the bare number for a contract one, which is why the output above reads [12] rather than [contract/12]. On the registry side, lookup(code) reads back a name you registered, decoded_contract(code) builds a DecodedError from it and says so plainly when the code is not registered, and len / is_empty describe the map. CATEGORY_CONTRACT is the exported constant for the "contract" category those compare against.
Storage snapshots and diffs
Capture everything a contract holds, then compare two captures around an
operation. Keys and values are rendered to stable strings (u32 becomes "42",
a map becomes "{a: 1, b: 2}"), so a diff reports what changed rather than two
opaque blobs. Instance storage is unfolded entry by entry, and each entry
carries the ledger sequence it expires at.
#![allow(unused)]
fn main() {
use soroban_testkit_core::storage::{inspect_storage, StorageSnapshot, StorageTier};
let entries = inspect_storage(&env, &contract);
for entry in &entries {
println!("{} = {} ({})", entry.qualified(), entry.value, entry.key);
}
let before = StorageSnapshot::capture(&env, &contract);
client.bump();
let after = StorageSnapshot::capture(&env, &contract);
let diff = before.diff(&after);
assert!(diff.added().is_empty() && diff.removed().is_empty());
assert_eq!(diff.modified()[0].after, "43");
// Or assert directly; failures list what actually happened.
before.assert_entry_removed(&after, "pending");
after.assert_unchanged(&StorageSnapshot::capture(&env, &contract));
assert_eq!(after.in_tier(StorageTier::Temporary).len(), 1);
}
Storage tier assertions
Use assert_storage_tier! to assert that a key or pattern belongs to the expected [StorageTier]:
#![allow(unused)]
fn main() {
use soroban_testkit_core::assert_storage_tier;
use soroban_testkit_core::storage::StorageTier;
// Assert an exact key
assert_storage_tier!(&env, &contract, "admin", StorageTier::Instance);
// Assert all keys matching a wildcard pattern
assert_storage_tier!(&env, &contract, "balances:*", StorageTier::Persistent);
}
A snapshot covers one contract only: other contracts' data, the WASM ContractCode entry and ledger entries the contract does not own are never included. Account addresses own no contract data, so they capture as empty instead of failing.
WASM section analysis
WasmSectionAnalyzer validates the WebAssembly 1.0 header, walks standard
binary sections and reports each section’s payload size:
#![allow(unused)]
fn main() {
use soroban_testkit_core::wasm::WasmSectionAnalyzer;
let wasm = std::fs::read("target/wasm32v1-none/release/contract.wasm")?;
let report = WasmSectionAnalyzer::new(64 * 1024).analyze(&wasm)?;
println!("{}", report.to_markdown());
for warning in &report.warnings {
eprintln!("warning: {warning}");
}
}
The report includes Code, Type, Function, Table, Memory, Data and Custom sections. It warns when the binary reaches 90% of the configured deployment limit, exceeds it, contains a debug/name custom section, or has oversized string or data sections.
Use to_json() when section footprints feed a continuous performance artifact;
the JSON shape is stable and contains the configured limit, total bytecode size,
section list and warnings.
Host execution profiling
HostExecutionProfiler repeatedly times an invocation and summarizes mean,
p50, p95 and p99 wall-clock latency. Because stable Soroban host APIs do not
expose per-call map/object counters, explicit counters are recorded in the
invocation closure:
#![allow(unused)]
fn main() {
use soroban_testkit_core::profiler::HostExecutionProfiler;
let summary = HostExecutionProfiler::new(100).run(|metrics| {
contract_client.increment(&caller, &1);
metrics.record_map_lookup();
metrics.record_object_created();
metrics.record_memory_copy(4_096);
})?;
println!("{}", summary.to_markdown());
std::fs::write("host-profile.json", summary.to_json()?)?;
}
The return value contains every timing sample plus mean map lookup, object creation and memory-copy totals. A percentile uses nearest-rank ordering, so small benchmark sets are deterministic. JSON exports use the same complete sample and summary shape for continuous benchmarking.
Storage Namespace Auditing
When contracts compose multiple modules or traits, bare symbol keys such as
"admin" can collide and silently overwrite another module’s state.
NamespaceAuditor records keys per module and reports collisions and
un-namespaced keys.
#![allow(unused)]
fn main() {
use soroban_testkit_core::namespace_auditor::NamespaceAuditor;
let mut auditor = NamespaceAuditor::new(&env, &contract);
auditor
.record("ownable", "ownable::admin")
.record("pausable", "pausable::paused");
let report = auditor.audit();
assert!(!report.has_collisions(), "Storage collision: {:?}", report.collisions());
println!("{report}");
}
Keys are considered namespaced when they contain a namespace separator
(::, :, ., /) such as DataKey::Admin or ownable:admin. Bare keys
like admin are flagged as collision risks. A collision is reported when the
same key is written by two independent modules. report.modules() returns the
full key map, while NamespaceAuditor::from_entries infers module ownership
from a StorageEntry snapshot.
Storage footprint diffs in CI
A refactor that widens a struct or adds a key silently grows what a contract
keeps on the ledger, and with it state rent and every read/write fee. The
footprint module measures that growth in the unit those fees are charged in —
XDR-encoded bytes — and diffs it between two Git revisions.
A test records the footprint of each contract into a JSON artifact that the repository commits:
#![allow(unused)]
fn main() {
use soroban_testkit_core::footprint::StorageFootprint;
#[test]
#[ignore = "run with --ignored to refresh storage-footprint.json"]
fn record_storage_footprint() {
let (env, token) = deploy_and_exercise_token();
let (_, vault) = deploy_and_exercise_vault(&env);
let mut footprint = StorageFootprint::new();
footprint.capture("token", &env, &token);
footprint.capture("vault", &env, &vault);
footprint.save(std::path::Path::new("storage-footprint.json")).unwrap();
}
}
{
"version": 1,
"contracts": {
"token": {
"entries": { "instance:admin": 84, "persistent:balances": 200 }
}
}
}
Persistent and temporary keys are measured as their whole ledger entry; each
key inside instance storage is measured as its key-plus-value map entry. Keys
are tier:key, iterated in order, so the committed file diffs cleanly.
StorageFootprintDiff::compare(&base, &head) lines two artifacts up key by
key. changed_keys() lists every key whose size moved, largest growth first,
growing_keys() only the new or larger ones, and exceeding(pct) the
contracts whose total grew by more than pct percent. A contract that is new
in the head artifact is reported but not counted against the threshold, since
there is no base to grow from. to_markdown(Some(pct)) renders the report:
## Storage footprint
**Fail** — storage grew by more than 10% in `token` (+35.21%).
| Contract | Instance | Persistent | Temporary | Total | Change |
|----------|---------:|-----------:|----------:|------:|-------:|
| `token` | 84 | 200 → 260 | 0 → 40 | 284 → 384 | +35.21% |
| `vault` | 0 | 100 | 0 | 100 | 0% |
### Changed keys
| Contract | Key | Base | Head | Change |
|----------|-----|-----:|-----:|-------:|
| `token` | `persistent:balances` | 200 | 260 | **+60 B** |
| `token` | `temporary:nonce` | – | 40 | **+40 B** (new) |
The storage-footprint-diff binary
storage-footprint-diff BASE.json HEAD.json [--threshold PCT] [--output FILE] [--allow-missing-base]
It prints the Markdown report, also writes it to --output for a comment
step, and exits 0 within the threshold, 1 when a contract grew past it, and
2 on a usage or file error. --allow-missing-base treats an absent base file
as empty, for the pull request that introduces the artifact. The binary reads
files and never runs Git itself, so the base revision is whatever the job
extracts:
- run: cargo test --workspace -- --ignored record_storage_footprint
- run: git show "origin/${BASE_REF}:storage-footprint.json" > base-footprint.json || true
env:
BASE_REF: ${{ github.base_ref }}
- run: >
cargo run -p soroban-testkit-core --bin storage-footprint-diff --
base-footprint.json storage-footprint.json
--threshold 10 --output footprint.md --allow-missing-base
Post footprint.md as the pull-request comment the same way the Budget baseline workflow posts its numbers. run_diff_cli(args) is the same binary
as a function, for embedding it in an xtask without spawning a process.
Rent projection and the summary table
Byte counts answer “how much state is there”. The question a deployer actually
asks is “what does keeping it cost”, and the two differ by the entry writes and
the rent term the network charges per TTL bump. FootprintSnapshot projects
forward, and renders itself as a table.
StorageFootprint::measure captures one contract without going through an
artifact, which is what you want inside a test that just deployed something:
#![allow(unused)]
fn main() {
use soroban_testkit_core::{DEFAULT_PROJECTION_LEDGERS, StorageFootprint};
let snapshot = StorageFootprint::measure(&ctx.env, &contract_id);
// Bytes, and the Stroops to hold them for another 518,400 ledgers.
let bytes = snapshot.total_bytes();
let stroops = snapshot.projected_rent(DEFAULT_PROJECTION_LEDGERS);
}
The arithmetic is the network’s own: each entry is priced through
soroban_env_host::fees::compute_rent_fee, the function core calls, so a
projection agrees with what the protocol charges rather than with a restatement
of the formula here. A projection is the cost of one TTL bump from zero, which
means it is rent plus the per-entry write plus the 48-byte TtlEntry the
bump itself writes. Doubling the horizon therefore adds rent without adding a
second entry write.
rent_estimate breaks the same number up per tier, and RentParameters is
where you override the fee set:
#![allow(unused)]
fn main() {
use soroban_testkit_core::{RentParameters, StorageFootprint};
let params = RentParameters::default()
// Re-price rent per KB for a network holding more state than the target,
// following core's own curve instead of the floor.
.with_soroban_state_size(6_000_000_000);
let estimate = StorageFootprint::measure(&ctx.env, &contract_id)
.rent_estimate(¶ms, 518_400);
let persistent = estimate.persistent_stroops;
assert!(estimate.total_stroops() >= persistent);
}
to_markdown renders the entries and the projection as one table, for a PR
comment or a docs page:
#![allow(unused)]
fn main() {
print!("{}", snapshot.to_markdown());
}
### Entries
| Key | Bytes |
|-----|--------:|
| `instance:admin` | 24 |
| `instance:paused` | 24 |
| `persistent:count` | 80 |
| `persistent:owner` | 80 |
| `temporary:nonce` | 80 |
| Tier | Entries | Bytes | Rent for 518400 ledgers |
|------|--------:|------:|----------------------:|
| instance | 2 | 48 | 40047 |
| persistent | 2 | 160 | 106762 |
| temporary | 1 | 80 | 36714 |
| **Total** | **5** | **288** | **183523** |
<sub>Sizes are XDR-encoded bytes. Rent is priced by `soroban-env-host`'s
`compute_rent_fee` at the protocol 23 fee parameters, entry write and
`TtlEntry` included.</sub>
Two things about those numbers are worth reading carefully. The tier rows are
not three copies of the same arithmetic: persistent and temporary keys are each
their own ledger entry, so each pays its own entry write, while every key in
instance storage lives inside one ContractData entry and is priced as that
single map. That is why two 24-byte instance keys rent for less than one 80-byte
persistent key. And because the snapshot records the key-plus-value map entries
of instance storage rather than the envelope around them, the instance column is
a floor. StorageFootprint::to_markdown does the same for every contract in the
artifact, one section each, under a ## \label`` heading.
Storage fragmentation analyzer
Storing data across dozens of small scalar entries inflates the ledger footprint due to repeated LedgerKey overhead and redundant key serialization. StorageFragmentationAnalyzer inspects contract storage across instance, persistent, and temporary tiers to measure key-to-value byte ratios, identify fragmented entries sharing common prefixes, and calculate projected byte and Stroop rent savings:
#![allow(unused)]
fn main() {
use soroban_testkit_core::{StorageFragmentationAnalyzer, StorageTier};
let analyzer = StorageFragmentationAnalyzer::new()
.with_overhead_threshold(0.40) // Flag entries where key bytes >= 40% of total
.with_stroop_rate_per_byte(100); // Rent rate assumption for Stroop savings
let report = analyzer.analyze(&env, &contract_id);
println!("Overall overhead ratio: {:.1}%", report.overall_overhead_ratio * 100.0);
println!("Potential byte savings: {} B", report.total_projected_byte_savings());
println!("Projected Stroop savings: {} Stroops", report.total_projected_stroop_savings());
// Render an optimization report as Markdown:
let markdown = report.to_markdown();
}
Call-stack depth auditing
Deep contract composition has a hard ceiling: the host refuses one more nested
call once the stack is full. StackDepthAuditor reconstructs the chain that
ran, reports its high-water depth, and checks it against a cap a test controls.
#![allow(unused)]
fn main() {
use soroban_testkit_core::StackDepthAuditor;
client.deposit(&user, &1_000); // proxy -> vault -> token
let auditor = StackDepthAuditor::from_env(&env);
println!("{}", auditor.trace());
// call trace: 3 frame(s), max depth 3, cap 100, warning threshold 90
// depth=1 contract=CDEPOSIT... function=deposit
// depth=2 contract=CVAULT... function=transfer_in
// depth=3 contract=CTOKEN... function=transfer
assert_eq!(auditor.max_depth(), 3);
assert!(!auditor.warning_triggered());
auditor.assert_within(); // panics with the full trace if the cap was passed
}
Where the depth comes from
The pinned host does not expose a public per-frame hook. Host::set_trace_hook
is crate-private, and the public Host::set_invocation_hook fires only when a
top-level invocation starts and finishes, not for each nested call. What the
host does expose is its diagnostic event stream: fn_call is emitted before a
frame opens and carries the called contract id and function name, and
fn_return is emitted when that call returns. StackDepthAuditor reads those
events through Env::host().get_diagnostic_events() and nests them in order,
which makes the reconstruction exact for successful cross-contract chains.
For a harness or an instrumented test contract, enter(contract, function)
and exit() record the same frames by hand:
#![allow(unused)]
fn main() {
use soroban_testkit_core::StackDepthAuditor;
let mut auditor = StackDepthAuditor::new();
auditor.enter("CPROXY", "forward").enter("CIMPL", "credit");
assert_eq!(auditor.max_depth(), 2);
auditor.exit();
}
The host limit
The cap defaults to the host’s own limit, not a number Testkit guessed.
soroban-env-host 28.0.2 defines DEFAULT_HOST_DEPTH_LIMIT = 100 in
src/budget/limits.rs, and Host::with_frame in src/host/frame.rs returns
Context/ExceededLimit when the context stack has already reached it. A test
environment’s top-level client call starts with an empty context stack, so
contract frames 1 through 100 are accepted and the 101st nested call is the one
that fails. An entry point reached through Host::invoke_function pushes a
host-function frame first, which leaves room for 99 contract frames. The
constant is re-exported as HOST_CALL_STACK_LIMIT.
warning_triggered() and warnings() report frames at or beyond the warning threshold — 90% of the cap by default, set with with_warning_threshold. Only breach() and assert_within() treat a depth as a failure.
Lowering the cap to test recovery
Running 100 nested calls to reach the real limit is slow and awkward. A test can check the same contract against a shallower ceiling instead:
#![allow(unused)]
fn main() {
use soroban_testkit_core::StackDepthAuditor;
let auditor = StackDepthAuditor::from_env(&env).with_lowered_cap(4);
if auditor.breach().is_some() {
// The contract's fallback path: split the call, or return a partial result.
}
// Or check a recorded trace against a hypothetical cap without changing it.
let would_breach = auditor.simulate_lowered_cap(2);
assert!(would_breach.is_some());
}
with_lowered_cap reduces the auditor’s cap and simulate_lowered_cap
answers what a different cap would have said about the same trace; neither
changes the host. StackDepthBreach carries max_depth, cap and the
rendered trace, so a panic message lists every frame rather than only the
number that was too large.
Env::default() enables diagnostics, which is what makes the reconstruction possible. A call that traps emits no fn_return, so its frame is recorded but never paired with a return; the high-water depth is still correct. The host also refuses contract re-entry before it emits a nested fn_call, so a refused recursive call leaves no extra frame. Where diagnostics are unavailable, use enter/exit from an instrumented harness.
SDK v29 compatibility auditor
As protocol standards move from Protocol 21/22 toward Protocol 23 and SDK v29, legacy host functions and untyped APIs are deprecated. CompatibilityAuditor monitors contract invocations, events, and host errors to identify deprecated calls early, outputting a compatibility scorecard with concrete remediation instructions:
#![allow(unused)]
fn main() {
use soroban_testkit_core::{CompatibilityAuditor, CompatibilityGrade};
let mut auditor = CompatibilityAuditor::new()
.with_target_protocol(22); // Target Protocol 22 / SDK v29
// Audit contract interactions:
let scorecard = auditor.audit_contract(&env, &contract_id);
println!("Readiness grade: {}", scorecard.grade.as_str());
assert!(scorecard.is_ready_for_upgrade, "Contract contains critical obsolete calls!");
// Render a CI-ready Markdown report:
let markdown_report = scorecard.to_markdown();
}
Reentrancy guard and state access ordering auditor
DeFi contracts using external callbacks, token transfers, or multi-contract routing must guarantee that reentrancy guard flags cannot be bypassed via indirect re-entry paths. Static and dynamic verification of state access order ensures protocol safety under Check-Effects-Interactions (CEI) patterns.
[ReentrancyGuardAuditor] monitors lock flag states and cross-contract invocations,
verifying that:
- Reentrancy locks are set (
LockState::Locked) before any external invocation is performed. - Locks are initialized and never accessed while uninitialized.
- Locks are not prematurely released before external calls finish.
- Locks are properly reset (
LockState::Unlocked) upon frame exit.
Static trace verification
Harnesses and unit tests can verify execution sequences directly:
#![allow(unused)]
fn main() {
use soroban_testkit_core::{LockState, ReentrancyGuardAuditor};
let mut auditor = ReentrancyGuardAuditor::new();
auditor
.enter_frame("CVAULT", "withdraw")
.set_lock("CVAULT", LockState::Locked)
.external_call("CVAULT", "CTOKEN", "transfer")
.enter_frame("CTOKEN", "transfer")
.exit_frame("CTOKEN", "transfer")
.set_lock("CVAULT", LockState::Unlocked)
.exit_frame("CVAULT", "withdraw");
let report = auditor.audit();
assert!(report.is_safe());
}
Detecting flawed reentrancy guard implementations
When a contract fails to initialize its lock before calling an external callback or releases its guard prematurely, assert_reentrancy_safe() flags the vulnerability and renders a state access ordering timeline:
#![allow(unused)]
fn main() {
use soroban_testkit_core::ReentrancyGuardAuditor;
let mut auditor = ReentrancyGuardAuditor::new();
auditor
.enter_frame("CVAULT", "withdraw")
// Flaw: External call performed while lock is uninitialized!
.external_call("CVAULT", "CTOKEN", "transfer")
.exit_frame("CVAULT", "withdraw");
// Panics with visual state access ordering timeline:
auditor.assert_reentrancy_safe();
}
Visual state access ordering timeline
On assertion failure or via report.render_timeline(), the auditor outputs an ASCII execution timeline detailing every step, depth, contract, action, lock state, and violation diagnostic:
STATE ACCESS ORDERING & REENTRANCY TIMELINE
Step | Depth | Contract | Action | Lock State | Status / Notes
-----+-------+------------+---------------------------------------+---------------+-----------------
1 | 1 | CVAULT | Enter: withdraw | Uninitialized | OK
2 | 1 | CVAULT | ExternalCall -> CTOKEN::transfer | Uninitialized | [VIOLATION] External call made while lock flag is Uninitialized on 'CVAULT'
3 | 1 | CVAULT | Exit: withdraw | Uninitialized | OK
----------------------------------------------------------------------------------------------------
Result: FAILED — 1 reentrancy violation(s) detected:
1. [Step 2] External call from 'CVAULT' to 'CTOKEN::transfer' while lock is Uninitialized
Dynamic environment observation
The auditor can also observe contract invocations dynamically from the test environment:
#![allow(unused)]
fn main() {
use soroban_testkit_core::ReentrancyGuardAuditor;
use soroban_sdk::Env;
fn audit_env(env: &Env) {
let auditor = ReentrancyGuardAuditor::from_env(env);
let report = auditor.audit();
if report.has_violations() {
println!("{}", report.render_timeline());
}
}
}
Per-invocation reentrancy detection
ReentrancyDetector answers a narrower question than the guard auditor: did one
invocation perform an external call before finalizing state, and did any contract
reappear on the active call stack? It owns a clone of the test Env, so
monitor(label, closure) observes only the diagnostic events the closure
produces and tags every finding with that label.
#![allow(unused)]
fn main() {
use soroban_testkit_core::ReentrancyDetector;
use soroban_sdk::Env;
fn withdraw(_env: &Env) {}
let mut detector = ReentrancyDetector::new(&env);
detector.monitor("vault_withdraw", || {
withdraw(&env);
});
assert!(!detector.has_cei_violations());
assert!(!detector.has_reentrancy_attempts());
assert!(!detector.has_violations());
println!("{}", detector.report());
detector.assert_safe();
}
A CEI violation is recorded when a frame makes an external call while it has no
storage write yet. A re-entry attempt is recorded when enter_frame sees a
contract that is already active, or when an instrumented re-entry event names a
contract on the active stack. violations() returns the findings,
report() renders the ordered trace with each violation, and assert_safe()
panics with that report when any finding exists.
Frames and instrumentation events
Call frames come from the host diagnostic stream: fn_call opens a frame and
fn_return closes it. Storage reads and writes and explicit call/re-entry events
come from contract events using this topic protocol:
| Topic | Value |
|---|---|
0 | Symbol("tk_reentry") — protocol marker |
1 | Symbol("storage_read"), "storage_write", "external_call", or "reentry_attempt" |
2 | Symbol(key) for storage, or Symbol(function) for calls |
| data | () for storage events; the other contract as Address for calls |
The emit_* helpers publish exactly this shape:
#![allow(unused)]
fn main() {
use soroban_sdk::{Address, Env, Symbol};
use soroban_testkit_core::{
emit_external_call, emit_reentry_attempt, emit_storage_read, emit_storage_write,
};
#[allow(deprecated)]
fn finalize_then_call(env: &Env, token: &Address, self_address: &Address) {
emit_storage_read(env, Symbol::new(env, "balance"));
emit_storage_write(env, Symbol::new(env, "balance"));
emit_external_call(env, token, Symbol::new(env, "transfer"));
emit_reentry_attempt(env, self_address, Symbol::new(env, "withdraw"));
}
}
MockReentrantAttacker is a ready-made contract whose attempt_reentry,
attack, and callback methods publish a re-entry event. The host refuses a
real recursive invocation before it opens a nested frame, so the mock simulates
the attempt as a protocol event; the detector still reports it when the target
contract is active.
Harnesses that cannot publish contract events can record the same actions
directly with record_storage_read, record_storage_write,
record_external_call, enter_frame, exit_frame, and
record_reentry_attempt. observe() ingests any new events from the detector’s
environment; observe_env(&env) switches the environment first.
Contract function coverage auditing (CoverageAuditor)
Integration test suites can pass with 100% green checks while failing to invoke critical administrative, recovery, or emergency functions defined in contract bytecode, leaving potential vulnerabilities unexercised.
[CoverageAuditor] extracts all public function entry points from contract WASM bytecode, contract spec XDR, or client definitions, tracks invocations observed via Soroban host diagnostic events across test executions, and produces comprehensive coverage reports in both Markdown and text formats.
Extracting entry points
You can extract functions from contract WASM bytecode, spec XDR, or typed client definitions:
#![allow(unused)]
fn main() {
use soroban_testkit_core::{CoverageAuditor, client_definition};
use soroban_sdk::{contract, contractimpl, Env, Address};
#[contract] pub struct Vault;
#[contractimpl] impl Vault {
pub fn initialize(_e: Env) {}
pub fn deposit(_e: Env) {}
pub fn withdraw(_e: Env) {}
pub fn emergency_stop(_e: Env) {}
pub fn admin_recover(_e: Env) {}
}
fn example(env: &Env, contract_id: &Address) -> Result<(), soroban_testkit_core::CoverageError> {
let client = VaultClient::new(env, contract_id);
let mut auditor = CoverageAuditor::new();
// 1. From client definitions:
auditor.register_client_definition(
&client.address,
&client_definition!("Vault", [initialize, deposit, withdraw, emergency_stop, admin_recover]),
);
// 2. Or directly from function names:
auditor.register_contract(&client.address, ["initialize", "deposit", "withdraw"]);
// 3. Or from WASM bytecode / Spec XDR:
let wasm_bytes = b"\0asm\x01\0\0\0";
// auditor.register_contract_wasm(&contract_id, wasm_bytes)?;
Ok(())
}
}
Configurable ignore lists
One-time setup functions (like init or initialize) or internal callbacks (like __check_auth) can be intentionally excluded from required coverage calculations:
#![allow(unused)]
fn main() {
use soroban_testkit_core::CoverageAuditor;
use soroban_sdk::Address;
fn example(auditor: &mut CoverageAuditor, contract_id: &Address) {
// Ignore per-contract:
auditor.ignore_function(contract_id, "initialize");
// Ignore common setup defaults ("init", "initialize", "__check_auth"):
auditor.ignore_default_setup_functions(contract_id);
// Ignore globally across all monitored contracts:
auditor.ignore_globally("initialize");
}
}
Observing invocations and generating reports
Call auditor.observe(&env) during or after test execution to ingest host diagnostic events. The auditor automatically aggregates invocations and computes coverage percentages:
#![allow(unused)]
fn main() {
use soroban_testkit_core::{CoverageAuditor, client_definition};
use soroban_sdk::{contract, contractimpl, Env, Address};
#[contract] pub struct Vault;
#[contractimpl] impl Vault {
pub fn initialize(_e: Env) {}
pub fn deposit(_e: Env) {}
pub fn withdraw(_e: Env) {}
pub fn emergency_stop(_e: Env) {}
}
fn test_flow(env: &Env, contract_id: &Address) {
let client = VaultClient::new(env, contract_id);
let mut auditor = CoverageAuditor::new();
auditor.register_client_definition(&client.address, &client_definition!("Vault", [initialize, deposit, withdraw, emergency_stop]));
auditor.ignore_function(&client.address, "initialize");
client.deposit();
client.withdraw();
// Ingest diagnostic events from the host:
auditor.observe(env);
let report = auditor.report();
// Print Markdown report for PR comments or CI artifacts:
println!("{}", report.to_markdown());
// Print concise plaintext table:
println!("{}", report.to_text());
// Assert full coverage of all non-ignored public functions:
// report.assert_full_coverage();
// Or enforce a minimum threshold:
report.assert_min_coverage(50.0);
}
}
Report outputs
When uninvoked functions are detected, report.to_markdown() renders detailed status tables and alerts:
# Contract Function Coverage Report
| Contract | Total Functions | Invoked | Uninvoked | Ignored | Coverage |
| :--- | :---: | :---: | :---: | :---: | :---: |
| `Vault` (`CAAA...`) | 5 | 2 | 2 | 1 | 50.0% |
| **Total** | **5** | **2** | **2** | **1** | **50.0%** |
## Contract: `Vault` (`CAAA...`)
| Function | Status | Invocations | Notes |
| :--- | :--- | :---: | :--- |
| `initialize` | ⊘ Ignored | 1 | Configured ignore list (setup/initialization) |
| `deposit` | ✓ Invoked | 1 | - |
| `withdraw` | ✓ Invoked | 1 | - |
| `emergency_stop` | ✗ **Uninvoked** | 0 | **Dead code or unexercised entry point** |
| `admin_recover` | ✗ **Uninvoked** | 0 | **Dead code or unexercised entry point** |
> [!WARNING]
> **2 uninvoked contract entry point(s) detected.** Unexercised administrative, emergency, or recovery functions leave critical code paths untested.
Memory Allocation and Footprint Profiler
The Soroban host enforces strict memory limits alongside CPU limits. Contracts with nested collections or recursive data structures frequently exhaust host memory on-chain despite passing CPU metering locally.
[MemoryProfiler] captures memory allocation deltas, measures memory bytes metered per execution step via env.budget().memory_bytes_cost(), tracks host object allocations, identifies peak allocation spikes, and generates structured reports with configurable threshold warnings:
#![allow(unused)]
fn main() {
use soroban_testkit_core::memory_profiler::MemoryProfiler;
let mut profiler = MemoryProfiler::new(&ctx.env)
.with_warning_threshold(500_000);
profiler.profile_call("batch_mint", || {
token_client.batch_mint(&recipients, &amounts);
});
assert!(profiler.peak_memory_bytes() < 500_000);
println!("{}", profiler.report());
}
Structured output formats:
- Parseable text summary:
println!("{}", profiler.report()) - JSON profile report:
profiler.report().to_json()
Comparative Budget Benchmarking and Diff Reporting
While budget_guard! and BudgetBaseline check costs against fixed ceilings, protocol upgrades require comparative reports across versions or PRs to detect subtle gas regressions across multiple functions before merging.
[BudgetComparison] diffs two budget.json baseline files, calculates delta CPU instructions, memory bytes, and percentage shifts per contract function, and flags regressions exceeding configurable thresholds (e.g. > 5%):
#![allow(unused)]
fn main() {
use soroban_testkit_core::budget_report::BudgetComparison;
let report = BudgetComparison::diff_files("budget_base.json", "budget_head.json")?;
println!("{}", report.to_markdown_table());
if report.has_regressions_above(0.05) {
panic!("Gas regression detected: {}", report.summary());
}
}
GitHub PR Comment Markdown Table
report.to_markdown_table() generates clean Markdown tables formatted for automated CI pull request comment injection:
### 📊 Soroban Budget Comparison Report
| Function | Status | CPU (Base → Head) | CPU Shift | Mem (Base → Head) | Mem Shift |
|:---|:---:|:---:|:---:|:---:|:---:|
| `batch_mint` | 🔴 Regressed | 1,000,000 → 1,120,000 | +12.0% | 50,000 → 55,000 | +10.0% |
| `transfer` | 🟢 Improved | 500,000 → 450,000 | -10.0% | 20,000 → 18,000 | -10.0% |
| `balance` | ⚪ Unchanged | 100,000 → 100,000 | 0.0% | 5,000 → 5,000 | 0.0% |
Standalone Responsive HTML Reports
report.to_html_report() generates a standalone HTML document with KPI summary cards, responsive tables, and visual diff bars:
#![allow(unused)]
fn main() {
let html = report.to_html_report();
std::fs::write("target/budget_report.html", html).unwrap();
}
Next: soroban-testkit-assert — turn these measurements into readable assertions.
Liquidity conservation (ConservationVerifier)
The core invariant of anything that moves tokens: across the holders you track (users, pools, vaults, fee collectors), the total balance changes by exactly what was minted minus what was burned. ConservationVerifier reads every tracked balance from the token contract before and after a workflow and checks that equation exactly, so a leak of a single stroop fails.
#![allow(unused)]
fn main() {
use soroban_testkit_core::ConservationVerifier;
let verifier = ConservationVerifier::new(&env, &token_id);
verifier.track_accounts(&[user1.clone(), user2.clone(), pool.clone()]);
// ... a multi-step workflow: swaps, deposits, fee splits ...
verifier.record_mint(500); // supply the workflow is meant to create
verifier.record_burn(40); // supply it is meant to destroy
verifier.assert_conserved();
}
The SEP-41 token interface has no total-supply query, so mints and burns are declared with record_mint / record_burn. Anything the contract mints or burns that the test did not declare is reported as a discrepancy. Negative means a leak (value left the tracked set or was destroyed, such as rounding dust burned or kept by an untracked contract). Positive means phantom minting.
On a violation, assert_conserved panics with a reconciliation table: opening and closing balance, credit and debit per account, the totals, and the verdict. This one is from the crate’s own test, where a splitter pays 100 out to three recipients in shares of 33 and burns the 1-stroop rounding remainder:
account | opening | closing | credit | debit
---------------------------------------------------------------------------------------------------------
CAAAAA…HK3M | 1000 | 900 | | 100
CAAAAA…OLZM | 0 | 0 | |
CAAAAA…ITA4 | 0 | 33 | 33 |
CAAAAA…K3IM | 0 | 33 | 33 |
CAAAAA…MDR4 | 0 | 33 | 33 |
---------------------------------------------------------------------------------------------------------
total | 1000 | 999 | 99 | 100
net balance delta : -1
expected delta : 0 (minted 0 - burned 0)
discrepancy : -1 — LEAK: 1 stroop(s) left the tracked set
check() returns the same ConservationReport as Ok/Err instead of panicking, and checkpoint() makes the current balances the new opening position so each step of a long workflow can be checked on its own.
Diagnostic event auditing
DiagnosticEventAuditor inspects Soroban host diagnostic events emitted during
contract execution. It categorizes events (function call/return, error, contract,
system diagnostic), enforces configurable count thresholds, and flags suspicious
payload patterns or watched addresses that may indicate credential leakage.
#![allow(unused)]
fn main() {
use soroban_sdk::Env;
use soroban_testkit_core::DiagnosticEventAuditor;
let env = Env::default();
// ... invoke contract ...
let mut auditor = DiagnosticEventAuditor::new()
.with_max_total_events(200)
.with_max_diagnostic_events(150)
.watch_sensitive_address("admin", &admin);
auditor.observe(&env);
auditor.assert_within_limits();
println!("{}", auditor.report().to_text());
}
Use assert_diagnostic_count_lte for a focused count check, and diagnostic_log(&env)
for a quick formatted dump on test failure.
soroban-testkit-assert
Fluent matchers for contract events, authorizations and storage, so assertions read like the behaviour you expect.
API at a glance
| Method | Asserts |
|---|---|
EventMatcher::assert_emitted() | At least one matching event exists |
EventMatcher::assert_not_emitted() | No matching event exists |
EventMatcher::assert_none_match(pred) | No matching event satisfies a predicate |
EventMatcher::assert_count(n) | Exactly n events were emitted |
EventMatcher::assert_count_within(bound) | The number of matching events falls within a range (or equals a count) |
EventMatcher::assert_topic_count(topic, bound) | The number of events carrying topic falls within a range (or equals a count) |
assert_event_count_range!(env, 3..=5) | Macro form of assert_count_within, over an Env or an EventLog |
assert_event_topic_count!(env, "Transfer", 2) | Macro form of assert_topic_count, over an Env or an EventLog |
EventMatcher::assert_data_matches(pred) | One event’s payload satisfies a predicate |
EventMatcher::from_contract(addr) | Restricts matches to one contract address |
EventMatcher::with_topic(t) | Restricts matches to events carrying that topic symbol |
EventLog::collect() | Gathers one invocation’s events into a set spanning calls |
EventLog::matcher() | A matcher over everything that log collected |
assert_event_emitted!(env, contract, topic, { field: value, .. }) | Asserts at least one matching event was emitted with expected contract, topic(s), and data fields |
assert_event_data_schema!(env, topic, { field: Type, .. }) | Checks matching event maps for required fields, exact keys, and deserializable types |
assert_emitted_matches!(env, { .. }) | Asserts emitted events matching glob wildcards (*, ?) or regex topic patterns and data fields |
assert_no_contract_error!(client.try_call(..)) | Unwraps a successful client call or reports its decoded Soroban error |
assert_call_success_with_value!(client.try_call(..), expected) | Checks decoded call success and return-value equality |
assert_contract_error!(client.try_call(..), MyError::Variant) | The call failed with exactly that #[contracterror] variant |
assert_host_error!(client.try_call(..), ScErrorType::Auth) | The call failed with a host error of that category, category and code, or exact Error |
assert_panic_msg!(expr, "text") / contains: / glob: / regex: | The expression panicked with a message matching a substring, glob (*, ?) or regular expression, including a contract panic surfaced through a host error |
AuthMatcher::assert_no_auth_required() | The call needed no authorizations |
AuthMatcher::assert_auth_count(n) | Exactly n authorizations were recorded |
AuthMatcher::assert_matches() | One recorded authorization fits the configured invoker, function, and arguments |
assert_auth_matches!(env, { .. }) | The same, with the invoker, function, and argument pattern inline |
assert_auth_strict!(env, [ .. ]) | Every expected authorization matches exactly one record, with no records left over |
assert_auth_invoker_distinct!(expected, auths) | Verifies that an invocation was authorized exclusively by the declared authorized address |
AuthSubTreeMatcher::assert_matches() | A matching authorization sub-tree appears at any depth in recorded auths |
assert_auth_sub_tree_matches!(env, { .. }) | Inline sub-tree matcher with argument and child wildcards and side-by-side failure trees |
assert_auth_tree!(env, { .. }) | Validates hierarchical authorization call-trees down to arbitrary depth with visual tree diffs |
AuthTreeMockBuilder::new(..) | Programmatic builder for mock authorization call-trees |
assert_storage_key_deleted!(env, contract, key) | A key is gone from instance, persistent and temporary storage |
assert_storage_key_deleted!(env, contract, key, tier) | A key is gone from one named tier |
assert_storage_empty!(env, contract) | No live storage entry survives in any tier |
assert_storage_empty!(env, contract, tier) | A named tier holds no live entry |
AuthSubInvocationMatcher::assert_matches() | An authorized sub-call matching contract, function, and arguments appears at any depth |
assert_auth_sub_invocation!(env, { .. }) | Inline sub-invocation matcher isolating intermediate contract calls at any depth |
StorageQuotaMatcher::assert_matches() | Asserts storage tier counts satisfy exact quotas or upper bounds |
assert_storage_tier_count!(env, contract, { .. }) | Macro enforcing allocation quotas across instance, persistent, and temporary tiers |
assert_balance_conserved!(..) | Asserts total token balance conservation across accounts, fee pools, and reserves |
assert_budget_diff_within!(..) | Asserts relative gas savings between baseline and optimized closures with side-by-side failure diff table |
assert_snapshot_matches!(name, value, env) | Serializes contract state, events or return values to canonical JSON and compares with a committed snapshot |
SnapshotOptions::new() | Exact comparison by default; opt into address normalization and recursive field removal |
Event matching
Replace raw tuple iteration with a fluent API:
#![allow(unused)]
fn main() {
use soroban_testkit_assert::events::EventMatcher;
// Assert at least one event was emitted
EventMatcher::new(&env).assert_emitted();
// Assert exact count
EventMatcher::new(&env).assert_count(3);
// Filter by contract and topic
EventMatcher::new(&env)
.from_contract(&contract_id)
.with_topic("Transfer")
.assert_emitted();
}
EventMatcher::new(&env) reads env.events().all(), and in SDK v28 that returns the events of the most recent contract invocation. Assert right after each call, as the examples here do. To judge several calls as one set, collect them into an EventLog — same filters, same assertions, wider scope.
env.events().all() now returns ContractEvents. Call .events() on it to get the slice, and import soroban_sdk::testutils::Events as _ — the method is feature-gated behind testutils. Testkit applies the contract and topic filters for you.
Asserting across several invocations
A multi-step test usually wants a sentence about a whole sequence: “these three calls emitted exactly two Transfer events, and nothing was ever refunded”. EventLog gathers the events of each call the test means to judge, and hands the set to the same matcher:
#![allow(unused)]
fn main() {
use soroban_testkit_assert::events::{EventLog, EventMatcher};
let mut log = EventLog::new(&env);
client.transfer(&from, &to, &100);
log.collect();
client.close_offer(&from);
log.collect();
// Every filter and assertion reads the sequence as one set.
log.matcher().assert_count(2);
log.matcher().with_topic("Transfer").assert_count(1);
log.matcher().from_contract(&contract_id).assert_emitted();
log.matcher().with_topic("Refund").assert_not_emitted();
// The latest call alone still works, unchanged.
EventMatcher::new(&env).with_topic("CloseOffer").assert_count(1);
}
Collection is explicit because the SDK gives a test no per-invocation hook: a call nobody collected from adds nothing to the log, and a call that published nothing adds nothing either. That is what lets an assertion over a log mean “not anywhere in this test” rather than “not in the last call”.
| Method | Gives |
|---|---|
EventLog::new(&env) | An empty log |
log.collect() | Appends the events of the invocation that just ran |
log.matcher() | An EventMatcher over everything collected so far |
log.topics() | Vec<Vec<String>> — one entry per event, its topic symbols |
log.events() | The collected ContractEvent values |
log.len() / log.is_empty() | How much has been gathered |
Events stay in call order — one contiguous run per collected invocation, in the order the contract published them — so topics() is what a sequence assertion reads:
#![allow(unused)]
fn main() {
let sequence = log
.topics()
.iter()
.map(|topics| topics.join("."))
.collect::<Vec<_>>()
.join("|");
assert_eq!(sequence, "Transfer|CloseOffer");
}
A failure over a log reports the aggregate, which is the count of calls the assertion actually saw:
assertion `left == right` failed: Expected 3 events, found 2
panicked at 'Expected an event whose data matches, checked 2 event(s) with data [1, 2]'
Negative assertions
Proving something did not happen is the other half of event testing — a rejected transfer should emit no Transfer event, a closed offer should publish nothing at all:
#![allow(unused)]
fn main() {
use soroban_testkit_assert::events::EventMatcher;
// Nothing in scope was published
EventMatcher::new(&env).assert_not_emitted();
// A specific topic stayed silent
EventMatcher::new(&env)
.from_contract(&contract_id)
.with_topic("Transfer")
.assert_not_emitted();
// Anything the topic filter cannot express
EventMatcher::new(&env).assert_none_match(|event| {
matches!(event.type_, soroban_sdk::xdr::ContractEventType::Diagnostic)
});
}
assert_none_match hands you the raw ContractEvent, so a predicate can inspect the event type or the data payload rather than only the topics.
Both failures quote the event they were not supposed to find:
panicked at 'Expected no events to be emitted, found 1 — unexpected event: topics [Transfer], type Contract'
EventMatcher::new(&env).assert_not_emitted() proves the most recent invocation published nothing matching. Proving a topic never appeared across a test is the EventLog case: collect each call, then log.matcher().with_topic("Refund").assert_not_emitted().
Event count ranges and topic frequencies
An exact assert_count(n) breaks the day a batch call starts emitting one extra fee or audit event, even though the behaviour under test did not change. Two macros state what the test actually depends on instead: that the total falls in a range, and that a given topic appeared a given number of times.
#![allow(unused)]
fn main() {
use soroban_testkit_assert::{assert_event_count_range, assert_event_topic_count};
client.batch_transfer(&from, &recipients); // 2 transfers + auxiliary events
// Total events within a range: any standard range works.
assert_event_count_range!(env, 3..=5);
assert_event_count_range!(env, 2..);
assert_event_count_range!(env, ..=10);
// An exact topic frequency, or a range of them.
assert_event_topic_count!(env, "transfer", 2);
assert_event_topic_count!(env, "fee", 0..=1);
assert_event_topic_count!(env, "refund", 0);
// Restrict either one to the events of one contract.
assert_event_count_range!(env, from = token_id, 3..);
assert_event_topic_count!(env, from = token_id, "transfer", 2);
}
The bound is an exact count (2) or any range over integers: a..b, a..=b, a.., ..b, ..=b, or ... Integer literals need no suffix. A topic counts the same way with_topic matches: an event counts once when any of its topics is that symbol, and symbols are case sensitive.
The first argument is anything that implements EventSource: an Env (the most recent invocation) or an EventLog (every call it collected), by value or by reference. That makes the macros the natural way to bound a whole multi-step test:
#![allow(unused)]
fn main() {
let mut log = EventLog::new(&env);
for batch in batches {
client.batch_transfer(&from, &batch);
log.collect();
}
assert_event_count_range!(log, 6..=12);
assert_event_topic_count!(log, "transfer", 6);
}
Both checks also exist as matcher methods, which compose with the existing filters:
#![allow(unused)]
fn main() {
EventMatcher::new(&env)
.from_contract(&token_id)
.with_topic("transfer")
.assert_count_within(2..=3);
EventMatcher::new(&env).assert_topic_count("fee", 1);
}
Failure diagnostics
A failure prints the bound, the observed count, the scope that was read, and a table of every topic signature in scope with how many events carried it, so you see what was emitted instead. Symbol topics are spelled out. Every other topic shows as its type (<address>, <i128>, …), so transfers to different recipients share one row:
Event topic count mismatch: expected topic "Transfer" exactly 2 time(s), observed 0 (topic "Transfer" was not observed)
Scope: most recent invocation
| Observed topics | Count |
|---------------------|-------|
| transfer, <address> | 2 |
| fee | 1 |
| audit | 1 |
| total | 4 |
The table lists signatures in the order they first appeared. It honours from = … / from_contract but deliberately ignores the topic being counted, because the useful question on failure is “what did come out of the call?”.
Asserting on payload data
Topics say which event fired; the data says what happened. assert_data_matches hands the predicate one EventData per event in scope, after the contract and topic filters:
#![allow(unused)]
fn main() {
use soroban_testkit_assert::events::EventMatcher;
// A single-value payload, read as the type it is
EventMatcher::new(&env)
.with_topic("transfer")
.assert_data_matches(|data| data.deserialize::<i128>() == Some(1_000));
// A struct published with `contractevent` arrives as a map keyed by field name
EventMatcher::new(&env)
.from_contract(&contract_id)
.with_topic("incremented")
.assert_data_matches(|data| {
data.field("new_count")
.and_then(|value| value.deserialize::<u32>())
== Some(12)
});
// A `contracttype` struct deserializes whole, when a test wants all of it
EventMatcher::new(&env)
.with_topic("moved")
.assert_data_matches(|data| data.deserialize::<Moved>() == Some(expected));
// Anything the typed views cannot express: the payload as the ledger stored it
EventMatcher::new(&env)
.with_topic("flag")
.assert_data_matches(|data| matches!(data.raw(), soroban_sdk::xdr::ScVal::Bool(true)));
}
| View | Returns | Use it when |
|---|---|---|
deserialize::<T>() | Option<T> | the payload is one value of a known type — a number, Address, Vec/Map, or a contracttype struct |
field("name") | Option<EventData> | the payload is a map, which is what a contractevent struct becomes, and one field is the point |
fields() | Vec<String> | the payload is a map and you want to enumerate the field names in ledger order |
raw() | &ScVal | neither fits, or the test is about the shape itself |
deserialize yields None rather than panicking, so one predicate can probe a payload without assuming it. field composes with it: data.field("amount").and_then(|value| value.deserialize::<i128>()).
fields() returns the field names actually present on the ledger in order:
#![allow(unused)]
fn main() {
EventMatcher::new(&env)
.with_topic("moved")
.assert_data_matches(|data| data.fields() == ["amount", "to"]);
}
contractevent struct is not a contracttype struct
The struct declared with contractevent gets an Event implementation, not ledger conversions, so deserialize::<Incremented>() will not compile against it. Read its fields with field. Note too that the SDK publishes event maps sparse by default: a field whose value is None is absent from the map rather than stored as void, so field returning None covers both "no such field" and "field left empty".
A failed data assertion prints the payloads it was handed, which is the difference between a message you can read and a re-run:
panicked at 'Expected an event whose data matches, checked 4 event(s) with data [7, 9000, true, "widget"]'
panicked at 'Expected an event whose data matches, checked 1 event(s) with data [{"amount": 500, "to": Contract(CAAAAAA...FCT4)}]'
Scalars print their values, maps and vectors print their entries, an address prints as its strkey (abbreviated above, printed whole in a real message), and a shape too rare to spell out falls back to its XDR debug form, so the message never hides the value it rejected. When no event is in scope the message says so instead of claiming the data was wrong.
Checking an event payload schema
assert_event_data_schema! validates the complete map payload of every event
matching the topic. It reports missing or mistyped fields individually and
rejects extra keys, which helps catch accidental indexer schema changes:
#![allow(unused)]
fn main() {
use soroban_testkit_assert::assert_event_data_schema;
use soroban_sdk::Address;
client.transfer(&from, &to, &100);
assert_event_data_schema!(&env, "transfer", {
amount: i128,
from: Address,
to: Address,
});
}
Types are checked by Soroban value deserialization, including i128, u64,
Address, Symbol, and bool. A failure names each offending field and shows
the expected type and observed type/value. The assertion requires at least one
event matching the topic.
Declarative event assertion with assert_event_emitted!
assert_event_emitted! provides ergonomic declarative assertions for contract events. It filters by contract ID, topic name(s), and data payload fields, asserting that at least one matching event was published:
#![allow(unused)]
fn main() {
use soroban_testkit_assert::assert_event_emitted;
client.increment(&caller, &5);
// Assert by contract, topic, and struct/map fields:
assert_event_emitted!(&env, &contract_id, "incremented", {
caller: caller,
new_count: 5u32,
});
// Assert with multiple topics:
assert_event_emitted!(&env, &contract_id, ["counter", "incremented"], {
new_count: 5u32,
});
// Assert by contract and topic only:
assert_event_emitted!(&env, &contract_id, "incremented");
}
Like EventMatcher::new(&env), assert_event_emitted! inspects env.events().all(), which in Soroban SDK v28 returns events from the most recent contract invocation only. Invoke the assertion immediately after the contract call that should emit the event.
When multiple events match the filters, the assertion succeeds (at least one match). If no event matches, it panics with a detailed diagnostic message displaying what was expected versus all events emitted during the invocation:
panicked at 'assert_event_emitted! failed: no matching event found.
Expected event:
contract: Contract(CAAAAA...)
topic(s): ["incremented"]
data: { new_count: 5u32 }
Emitted events (1 in scope):
[1] contract: Contract(CAAAAA...), topics: [counter, incremented], data: {"caller": Contract(...), "new_count": 10}'
Regex and wildcard topic matching (assert_emitted_matches!)
When contract events contain prefixes, variable identifiers, or structured multi-part topics (e.g. Transfer:XLM, Order:Created:104), exact string topic matching can be brittle. assert_emitted_matches! allows matching topics using wildcard glob patterns (*, ?) and regular expressions, while validating data payload fields in the same assertion:
#![allow(unused)]
fn main() {
use soroban_testkit_assert::assert_emitted_matches;
// Match with wildcard globs across single or multi-part topics
assert_emitted_matches!(env, {
contract: dex_id,
topic: "Trade:*",
data: { amount: 500u64 },
});
// Match with regular expression pattern
assert_emitted_matches!(env, {
contract: dex_id,
topic: r"^Order:(Filled|Cancelled)$",
});
// Works across EventLog collections spanning multiple invocations
assert_emitted_matches!(event_log, {
topic: "Trade:XLM",
});
}
On assertion failure, assert_emitted_matches! reports every recorded event with its emitting contract, formatted topics, and raw payload data.
Successful contract calls
Use the generated client’s try_* call with these macros instead of a bare
unwrap(). A host failure is decoded into its category, code, and known name
(for example storage/3: MissingValue); contract-specific errors retain their
code and are identified as unregistered unless decoded separately:
#![allow(unused)]
fn main() {
use soroban_testkit_assert::{
assert_call_success_with_value, assert_no_contract_error,
};
// Assert success and keep the returned value for further checks.
let balance = assert_no_contract_error!(client.try_balance(&account));
assert!(balance > 0);
// Assert that a successful invocation returned exactly the expected value.
assert_call_success_with_value!(client.try_transfer(&from, &to, &100), ());
}
Both macros evaluate the call once and distinguish a returned contract/host
error from an invocation failure. assert_no_contract_error! returns the
successful value; assert_call_success_with_value! compares it with the
expected value.
Asserting exact contract and host errors
#[should_panic] passes for any panic, so a test written to prove
“unauthorized callers are refused” keeps passing when the call starts failing
on a budget overflow instead. assert_contract_error! takes the result of a
try_* client call and fails unless it carries exactly the expected variant:
#![allow(unused)]
fn main() {
use soroban_testkit_assert::assert_contract_error;
assert_contract_error!(
client.try_transfer(&sender, &receiver, &1000),
TokenError::InsufficientBalance
);
}
It handles every arm of the SDK v28 try_* shape,
Result<Result<T, ConversionError>, Result<E, InvokeError>>:
| The call returned | The macro |
|---|---|
Err(Ok(e)) with e == expected | passes |
Err(Ok(e)) with another variant | fails, naming both variants with code and category |
Err(Err(InvokeError::Contract(code))) | fails: a code the client’s error enum has no variant for |
Err(Err(InvokeError::Abort)) | fails: a panic or host failure |
Ok(..) | fails: the call unexpectedly succeeded, printing the returned value |
assert_contract_error! failed: the call failed with a different error
expected: InsufficientBalance (code 1, category contract)
received: Unauthorized (code 2, category contract)
decoded: Soroban Error [2]: unregistered contract error — add it to an ErrorRegistry to read it as text
The expected value can be the contract’s error enum or a raw
soroban_sdk::Error::from_contract_error(code); codes and categories come
from DecodedError in soroban-testkit-core.
Host errors
assert_host_error! matches a host error at the precision you need:
#![allow(unused)]
fn main() {
use soroban_sdk::xdr::{ScErrorCode, ScErrorType};
use soroban_testkit_assert::assert_host_error;
assert_host_error!(outcome, ScErrorType::Storage); // any storage error
assert_host_error!(outcome, ScErrorType::Storage, ScErrorCode::MissingValue); // exact category and code
assert_host_error!(outcome, Error::from_contract_error(101)); // an exact Error value
}
The last form is how to assert an error code that propagated from a
different contract — a token’s InsufficientBalance surfacing through a
pool whose client only knows AmmError.
Three things the host decides, not the macro:
- A
#[contracterror]client can only carry contract codes; a host failure arrives asInvokeError::Abortwith its category lost. The diagnostic says so — callenv.try_invoke_contract::<_, soroban_sdk::Error>(..)to keep it. - A host failure inside a native (non-Wasm) test contract surfaces as
context/InvalidAction: the host catches it as a failed contract frame. - Budget exhaustion is unrecoverable and escalates to a panic even through
try_*; catch it with#[should_panic(expected = "Error(Budget, ExceededLimit)")].
check_contract_error and check_host_error return the diagnostic as a
Result<(), String> instead of panicking.
Asserting the error code behind a panic
A client method that is not a try_* call panics when the invocation fails, and
the host renders the failure inside the panic text:
HostError: Error(Contract, #101)
HostError: Error(Auth, InvalidAction)
#[should_panic(expected = "...")] only checks that the text contains a
substring. assert_contract_call_panics_with_error_code! catches the panic,
parses the packed Error(..), and compares the decoded error with an exact
expectation:
#![allow(unused)]
fn main() {
use soroban_sdk::xdr::{ScErrorCode, ScErrorType};
use soroban_testkit_assert::assert_contract_call_panics_with_error_code;
// A numeric #[contracterror] code.
assert_contract_call_panics_with_error_code!(client.withdraw(&1_000), VaultError::Locked as u32);
// An exact host error category and code.
assert_contract_call_panics_with_error_code!(
client.withdraw(&1_000),
ScErrorType::Auth,
ScErrorCode::InvalidAction
);
}
The call is evaluated once, inside catch_unwind. The assertion fails cleanly
when the call returns normally, when the panic carries no Soroban error (the
diagnostic quotes the panic), and when the code or category differs. A mismatch
prints both errors with their decoded category, numeric code and variant name:
assert_contract_call_panics_with_error_code! failed: the call panicked with a different error
expected: Error(Contract, #101) — decoded: code 101, category contract
received: Error(Contract, #2) — decoded: code 2, category contract, variant contract code 2
panic: HostError: Error(Contract, #2)
check_panic_error_code returns the diagnostic as a Result<(), String>
without panicking, for tests that assert on the message itself.
Matching a panic message (assert_panic_msg!)
#[should_panic(expected = "...")] applies to the whole test, passes for a
panic raised anywhere in it, and only does a substring match.
assert_panic_msg! scopes the expectation to a single expression, runs that
expression exactly once inside catch_unwind, and matches the message it
panicked with by substring, glob, or regular expression. On a match it
evaluates to a CapturedPanic you can inspect further.
Matching modes
The mode is chosen by a keyword. The macro never guesses it from what the
pattern contains, so "a*b" with no keyword is a literal substring:
| Form | Mode | Rule |
|---|---|---|
assert_panic_msg!(expr, "text") | substring | The message contains text (same rule as #[should_panic(expected)]) |
assert_panic_msg!(expr, contains: "text") | substring | The same rule, written out |
assert_panic_msg!(expr, glob: "pat") | glob | The whole message matches; * is any run of characters (newlines included), ? exactly one character |
assert_panic_msg!(expr, regex: r"pat") | regex | regex crate syntax; unanchored unless the pattern uses ^/$ |
The pattern can be any expression that gives a &str or String, so
format! with runtime values works. A closure written in place (|| expr or
move || expr) is called once, not just constructed.
#![allow(unused)]
fn main() {
use soroban_testkit_assert::assert_panic_msg;
fn withdraw(amount: u64) {
assert!(amount <= 100, "withdrawal of {amount} exceeds the limit of 100");
}
// Substring
assert_panic_msg!(withdraw(250), "exceeds the limit");
assert_panic_msg!(withdraw(250), contains: "exceeds the limit");
// Glob: the whole message, with * and ?
assert_panic_msg!(withdraw(250), glob: "withdrawal of * exceeds the limit of ???");
// Regex
assert_panic_msg!(withdraw(250), regex: r"^withdrawal of \d+ exceeds the limit of \d+$");
// Dynamic values in the pattern, and inspecting what was caught
let amount = 250;
let captured = assert_panic_msg!(withdraw(amount), contains: format!("withdrawal of {amount}"));
assert_eq!(captured.message(), "withdrawal of 250 exceeds the limit of 100");
}
Panics from panic! and from failed assert!, assert_eq! and
unwrap all work. A bare assert!(ready) or panic!("literal") carries a
&'static str payload and a formatted message a String; both are read.
Contract panics and host diagnostics
A contract called through its generated client does not unwind with the
contract’s own payload. The test host catches the contract’s panic, turns it
into a host error, and re-panics with a String like this:
HostError: Error(WasmVm, InvalidAction)
Event log (newest first):
...
3: [Failed Diagnostic Event (not emitted)] contract:CA..., topics:[log], data:["caught panic 'withdrawal of 250 exceeds the limit of 100' from contract function 'Symbol(withdraw)'", 250]
...
CapturedPanic splits that text into parts. host_error holds the
Error(..) from the first line, and contract_panics holds the message
from each caught panic '..' entry. A pattern passes if it matches any
of the candidates below, tried in this order:
- each contract panic message;
- the host error (
Error(WasmVm, InvalidAction),Error(Contract, #7), …); - the
HostError: ...header line; - the full raw panic text.
That is how a whole-message glob or anchored regex can match the contract’s own words even though the raw payload also carries the event log:
#![allow(unused)]
fn main() {
let captured = assert_panic_msg!(
client.withdraw(&250),
glob: "withdrawal of * exceeds the limit of 100"
);
assert_eq!(captured.host_error.as_deref(), Some("Error(WasmVm, InvalidAction)"));
// An error raised with panic_with_error! carries a code, not text:
assert_panic_msg!(client.locked(), glob: "Error(Contract, #7)");
}
For a Rust panic raised by test-side code, the raw message is the only candidate.
Failure diagnostics
A failure says which of four things went wrong.
The invocation did not panic:
assert_panic_msg! failed: the invocation completed without panicking
expected a panic matching (contains): "exceeds"
No candidate matched. The failure prints the expected pattern, its mode, and the actual message. For a host panic it also prints the host error and each contract panic message:
assert_panic_msg! failed: the panic message did not match
expected (glob): "deposit of *"
origin: Soroban host error
host error: Error(WasmVm, InvalidAction)
contract panic message: "withdrawal of 250 exceeds the limit of 100"
actual (full host panic):
| HostError: Error(WasmVm, InvalidAction)
| ...
The payload has no text. This happens with std::panic::panic_any(42u32)
and similar. The failure reports the payload as having no message instead of
matching the pattern against an empty string.
The regex pattern is invalid. The failure prints the compile error, and the invocation is never run.
check_panic_msg(capture_panic(|| ...), &PanicPattern::glob("...")) gives
you the same result as a Result<CapturedPanic, PanicMsgFailure> without
panicking. PanicPattern::matches_text and panic_msg::glob_match let you test the
matching on its own.
Limitations
- The contract’s own panic text is only available from the host’s
diagnostic event log.
Env::default()in testutils records that log. If diagnostics are off, only the host error is available, and a mismatch reportscontract panic message: unavailableinstead of matching against empty text. The crate’s tests cover this case. panic_with_error!and#[contracterror]returns carry a numeric code, not text. Match them by theirError(Contract, #N)rendering, or useassert_contract_call_panics_with_error_code!to compare the decoded code.- The text is matched exactly as the host renders it in the event log. A contract message containing quotes or control characters may appear escaped.
- Only the native test host has been exercised. A Wasm contract built with
panic = "abort"traps without a message, so all you get there is the host error. - The default panic hook still prints the caught panic to stderr. The macro does not replace the process-wide hook, because doing that is not safe while tests run in parallel.
Authorization matching
Verify who had to sign for a call, and for what. A recorded authorization carries
the invoker, the contract function, and the arguments require_auth demanded, and
the macro names all three:
#![allow(unused)]
fn main() {
use soroban_testkit_assert::assert_auth_matches;
client.increment(&caller, &1);
// The invoker and the function are enough when the arguments are not the point.
assert_auth_matches!(env, {
invoker: caller,
function: "increment",
});
// Arguments are matched position by position; `_` accepts any value.
assert_auth_matches!(env, {
invoker: caller,
function: "increment",
args: [_, 1u32],
});
}
assert_auth_matches! reads env.auths(), which in SDK v28 reports the authorizations of the most recent contract invocation — the same scope as EventMatcher::new. Assert right after the call, or provide the expected auth with env.mock_auths(..) / env.set_auths(..) and let the call run with real requirements instead of mock_all_auths().
The matcher behind the macro is available directly when a test builds the filter in steps:
#![allow(unused)]
fn main() {
use soroban_testkit_assert::auth::{AuthArgs, AuthMatcher};
AuthMatcher::new(&env)
.invoker(&admin)
.function("set_admin")
.assert_matches();
AuthMatcher::new(&env)
.args(AuthArgs::new().any().value(&env, 7u32))
.assert_matches();
}
And the coarser questions still have their own assertions:
#![allow(unused)]
fn main() {
use soroban_testkit_assert::auth::AuthMatcher;
// Assert no auth was required
AuthMatcher::new(&env).assert_no_auth_required();
// Assert specific auth count
AuthMatcher::new(&env).assert_auth_count(2);
}
A failed match prints the expectation next to every authorization the invocation recorded, so the wrong invoker, function, or argument is visible without a re-run:
panicked at 'Expected an authorization matching { invoker Contract(C…FCT4), function "set_admin", args [_, 7] }, found 1 recorded authorization(s):
[0] invoker Contract(C…FCT4) contract Contract(C…D2KM) function "increment" args [Contract(C…FCT4), 1]'
Strict authorization matching
Use assert_auth_strict! when a test must prove that a call authorized only
the expected invokers and functions. Every listed pattern must match a distinct
recorded authorization, and every record must match one listed pattern. The
macro also accepts argument patterns, where _ matches any value in that
position:
#![allow(unused)]
fn main() {
use soroban_testkit_assert::assert_auth_strict;
client.set_admin(&admin, &new_admin);
assert_auth_strict!(env, [
{
invoker: admin,
function: "set_admin",
args: [new_admin],
},
]);
}
Declare multiple authorizations as separate entries. An empty list asserts that the invocation recorded no authorizations:
#![allow(unused)]
fn main() {
assert_auth_strict!(env, [
{ invoker: first, function: "joint", args: [_, second] },
{ invoker: second, function: "joint", args: [first, _] },
]);
assert_auth_strict!(env, []);
}
If a pattern is missing or any unlisted authorization was recorded, the failure shows expected and observed authorizations side by side, then identifies missing patterns and extra records.
Exact multiset matching
assert_auth_exact_multiset! is the order-insensitive form of the same
assertion. A contract that triggers several independent require_auth demands
can record them in any order, and the order is not part of the SDK’s contract:
#![allow(unused)]
fn main() {
use soroban_testkit_assert::assert_auth_exact_multiset;
client.settle(&first, &second);
assert_auth_exact_multiset!(env, [
{ invoker: second, function: "settle", args: [first, _] },
{ invoker: first, function: "settle", args: [_, second] },
]);
}
Matching is one-to-one, so this is a multiset rather than a subset rule:
- every expected pattern must match a distinct recorded authorization;
- every recorded authorization must be consumed by an expected pattern;
- two identical patterns require two identical records, and an empty list asserts that nothing was authorized.
Missing and surplus authorizations both fail, with the side-by-side table followed by the unmatched expectations and the extra records.
Sub-tree authorization matching
Multi-hop routing protocols (such as aggregator -> pool -> vault) record nested
AuthorizedInvocation trees in env.auths(). assert_auth_sub_tree_matches!
locates and validates a sub-tree starting at any depth, so a modular test can
verify an intermediate contract hop without repeating the entire outer call stack:
#![allow(unused)]
fn main() {
use soroban_testkit_assert::assert_auth_sub_tree_matches;
aggregator.swap(&user, &pool_id, &vault_id, &500i128);
// Matches Pool -> Vault inside Aggregator -> Pool -> Vault without naming Aggregator.
assert_auth_sub_tree_matches!(env, {
invoker: user,
contract: pool_id,
function: "route",
args: [_, vault_id.clone(), 500i128],
sub_invocations: [
{
contract: vault_id,
function: "deposit",
args: [user.clone(), 500i128],
sub_invocations: [],
},
],
});
}
Every field (invoker, contract, function, args, sub_invocations) is
optional and accepts _ as a wildcard. Inside sub_invocations: [..]:
| Pattern | Matches |
|---|---|
Omitted or sub_invocations: _ | Any child invocations (zero or more) |
sub_invocations: [] | Exactly zero child invocations (leaf node) |
_ | Any single child invocation at that position |
.. | Zero or more child invocations at that position |
{ ... } | A nested sub-tree node with its own filters and sub_invocations |
The same matching is available through the chainable builder types
AuthSubTree, SubInvocations, and AuthSubTreeMatcher:
#![allow(unused)]
fn main() {
use soroban_testkit_assert::auth::{AuthArgs, AuthSubTree, AuthSubTreeMatcher, SubInvocations};
let expected = AuthSubTree::new()
.contract(&pool_id)
.function("route_with_fee")
.sub_invocations(
SubInvocations::new()
.node(
AuthSubTree::new()
.contract(&vault_id)
.function("deposit")
.args(AuthArgs::new().any().value(&env, 1_000i128)),
)
.any_many(),
);
AuthSubTreeMatcher::new(&env)
.invoker(&user)
.sub_tree(expected)
.assert_matches();
}
When a sub-tree fails to match, the assertion renders a side-by-side tree
comparison highlighting missing branches with [MISSING]:
Expected authorization sub-tree did not match any recorded authorization (1 recorded):
Expected sub-tree | Recorded authorization tree(s)
-------------------------------------------------------------+-------------------------------------------------------------
invoker Contract(C…1234) | [0] invoker Contract(C…1234)
contract Contract(C…BBBB) function "route" | contract Contract(C…AAAA) function "swap" args [...]
├── contract Contract(C…CCCC) function "deposit" | └── contract Contract(C…BBBB) function "route" args [...]
└── contract Contract(C…DDDD) function "collect" [MISSING] | └── contract Contract(C…CCCC) function "deposit" args [...]
Hierarchical call-tree validation and mock builder (assert_auth_tree!)
In nested multi-contract calls (e.g. Router -> Pool -> Vault -> Token), authorizations form recursive trees of AuthorizedInvocation structures. assert_auth_tree! validates an entire nested delegation hierarchy to arbitrary depth using concise sub_invokes lists:
#![allow(unused)]
fn main() {
use soroban_testkit_assert::assert_auth_tree;
assert_auth_tree!(env, {
invoker: user,
function: "deposit_and_stake",
sub_invokes: [
{
invoker: router,
function: "transfer",
args: [user, pool, 1000],
sub_invokes: [
{ invoker: pool, function: "mint_receipt", args: [user, 1000] }
]
}
]
});
}
To construct mock authorization trees programmatically in tests or mocks, use AuthTreeMockBuilder:
#![allow(unused)]
fn main() {
use soroban_testkit_assert::{auth_tree::tree_depth, AuthTreeMockBuilder};
let mock_invocation = AuthTreeMockBuilder::new(router, "transfer")
.arg(&user, &env)
.arg(&pool, &env)
.arg(&1000i128, &env)
.sub_invoke(
AuthTreeMockBuilder::new(pool, "mint_receipt")
.arg(&user, &env)
.arg(&1000i128, &env)
.build(&env)
)
.build(&env);
assert_eq!(tree_depth(&mock_invocation), 2);
}
Isolating intermediate sub-invocations
When inspecting authorization trees from complex multi-contract calls, developers often only care about asserting that a specific intermediate contract properly authorized a sub-call, regardless of top-level invoker details.
assert_auth_sub_invocation! searches recursively across all recorded authorization trees and matches any sub-invocation matching { contract, function, args } at any depth:
#![allow(unused)]
fn main() {
use soroban_testkit_assert::assert_auth_sub_invocation;
aggregator.swap(&user, &pool_id, &vault_id, &500i128);
// Matches Vault deposit at depth 2 without naming Aggregator or Pool:
assert_auth_sub_invocation!(env, {
contract: vault_id,
function: "deposit",
args: [user.clone(), 500i128],
});
// Matches intermediate Pool route without top-level wrapper details:
assert_auth_sub_invocation!(env, {
contract: pool_id,
function: "route",
args: [_, vault_id, 500i128],
});
}
All fields are optional and accept _ as a wildcard:
contract: addr(or_/ omitted): filters calls targetingaddr.function: "name"(or_/ omitted): filters calls named"name".args: [_, val](or_/ omitted): matches arguments positionally with_wildcards.invoker: addr(or_/ omitted): restricts matches to authorization trees originating fromaddr.
The same matching is available via the chainable builder AuthSubInvocationMatcher:
#![allow(unused)]
fn main() {
use soroban_testkit_assert::auth::{AuthArgs, AuthSubInvocationMatcher};
AuthSubInvocationMatcher::new(&env)
.contract(&vault_id)
.function("deposit")
.args(AuthArgs::new().any().value(&env, 500i128))
.assert_matches();
}
When no matching sub-invocation is found, the assertion formats the full recorded authorization tree displaying all sub-invocations:
panicked at 'Expected authorization sub-invocation matching { contract Contract(C…), function "deposit", args [_, 999] }, found no match in 1 recorded authorization tree(s):
[0] invoker Contract(C…1234)
contract Contract(C…AAAA) function "swap" args [...]
└── contract Contract(C…BBBB) function "route" args [...]
└── contract Contract(C…CCCC) function "deposit" args [...]'
Storage assertions
Closing an account, burning a balance or cancelling an escrow should leave no storage behind. assert_storage_key_deleted! and assert_storage_empty! prove entries are gone from the ledger rather than merely rewritten:
#![allow(unused)]
fn main() {
use soroban_testkit_assert::{assert_storage_empty, assert_storage_key_deleted};
use soroban_testkit_assert::storage::StorageTier;
// The key no longer exists in any tier.
assert_storage_key_deleted!(&env, &token, "balance");
// Only the named tier is inspected; another tier may still hold the key.
assert_storage_key_deleted!(&env, &token, "allowance", StorageTier::Persistent);
// The contract's whole storage is empty, or one tier of it is.
assert_storage_empty!(&env, &token);
assert_storage_empty!(&env, &token, StorageTier::Temporary);
}
Both assertions inspect instance, persistent and temporary storage through StorageSnapshot, with instance storage unfolded per key exactly as assert_storage_tier! reports it. The key is the snapshot’s rendered form: a symbol’s text for the usual case, but also [a, b] for a vector or {k: v} for a map, so composite keys can be named too.
These assertions are about the entry, not its value. A key rewritten to 0, set to Option::None (stored as void), or holding an empty map is still a live ledger entry and fails both assertions. Delete the key with storage().remove(&key); overwriting it with a tombstone is not enough.
A failure lists every surviving entry with the tier it lives in, its rendered value, and the XDR bytes the ledger holds:
panicked at 'Expected contract storage to be empty, but 2 entries survived:
persistent:balance = 0 [8 bytes: 0000000300000000]
temporary:allowance = void [4 bytes: 00000000]'
Naming a key narrows the message to that key’s survivors:
panicked at 'Expected storage key "balance" to be deleted from all tiers, but it still exists:
persistent:balance = 0 [8 bytes: 0000000300000000]'
A contract that never wrote storage passes assert_storage_empty!, and an address that is not a contract owns no contract data, so it passes too.
Failure messages
Assertions fail with the counts they observed, which is what makes them worth using over hand-rolled loops:
assertion `left == right` failed: Expected 3 events, found 1
Storage tier quota assertions
Protocols must keep storage tier entry counts within bounded budgets: instance storage is reserved for small singleton configuration, persistent storage holds durable state, and temporary storage manages short-lived queues. assert_storage_tier_count! validates entry count quotas per tier:
#![allow(unused)]
fn main() {
use soroban_testkit_assert::assert_storage_tier_count;
// Enforce quotas using block syntax:
assert_storage_tier_count!(env, contract_id, {
instance: 1, // Exactly 1 instance entry
max_persistent: 10, // At most 10 persistent entries
temporary: 0, // No temporary storage entries
});
// Or concise assignment syntax:
assert_storage_tier_count!(env, contract_id, max_instance = 3, max_persistent = 10);
}
When a quota is breached, the assertion prints an informative breakdown table listing all stored keys per tier:
Storage allocation quota exceeded for contract:
Breached tiers: persistent (found 12, expected max 10)
| Tier | Count | Quota | Status | Keys |
|-------------|-------|----------------|--------|--------------------------------------------|
| instance | 1 | max 5 | PASS | "cfg" |
| persistent | 12 | max 10 | BREACH | "u_1", "u_2", "u_3", ... (total 12) |
| temporary | 0 | exact 0 | PASS | (none) |
| assert_budget_consumed!(..) | Bounds the most recent invocation’s CPU and memory consumption |
Storage diff assertions
The assert_storage_diff! macro provides a declarative way to assert contract storage changes between two points in time. It captures a storage snapshot before operations, executes the test logic, and then verifies the expected changes against the actual storage diff.
#![allow(unused)]
fn main() {
use soroban_testkit_assert::assert_storage_diff;
use soroban_testkit_core::storage::{StorageSnapshot, StorageTier};
// Capture storage state before operations
let before = StorageSnapshot::capture(&env, &contract_id);
// ... perform contract operations ...
client.transfer(&from, &to, &100);
// Assert storage changes declaratively
assert_storage_diff!(before, env, contract_id, {
added: [
{ key: "new_key" },
{ key: "allowance:*", tier: StorageTier::Temporary },
],
modified: [
{ key: "balances", from: 1000u64, to: 900u64 },
],
removed: [
{ key: "old_key" },
],
unchanged: [
{ key: "admin", tier: StorageTier::Instance },
],
});
}
Clauses
The macro supports four declarative clauses:
| Clause | Purpose | Example |
|---|---|---|
added | Keys that should be newly present | { key: "new_key" } |
modified | Keys whose values should change | { key: "balances", from: 1000u64, to: 900u64 } |
removed | Keys that should be deleted | { key: "old_key" } |
unchanged | Keys that should remain exactly the same | { key: "admin", tier: StorageTier::Instance } |
Key matching
Keys can be exact strings or glob patterns:
- Exact:
{ key: "exact_key" } - Prefix wildcard:
{ key: "prefix_*" } - Suffix wildcard:
{ key: "*_suffix" } - Match all:
{ key: "*" }
Each entry can optionally specify a storage tier: tier: StorageTier::Instance, StorageTier::Persistent, or StorageTier::Temporary.
Value matching
Values can be specified in multiple ways:
- Exact value:
{ key: "count", from: 42u32, to: 43u32 } - Typed value (with type annotation):
{ key: "count", from: u32 => 42, to: u32 => 43 } - Wildcard (match any value):
{ key: "count", from: _, to: _ }(usingsoroban_testkit_assert::__storage_diff_value!)
Failure diagnostics
When an assertion fails, the macro prints a detailed side-by-side diff table showing expected vs actual changes:
Storage diff assertion failed:
Expected modified key 'balances' (tier: persistent): from: expected '1000', found '999'
═══════════════════════════════════════════════════════════════════════════════
STORAGE DIFF REPORT
═══════════════════════════════════════════════════════════════════════════════
Summary: 1 added, 1 modified, 0 removed | Failures: 1
┌──────────────────────────────────────────────────────────────────────────────┐
│ MODIFIED │
├────────┬──────────────────────┬──────────────────────┬──────────────────────┤
│ Tier │ Key │ Before │ After │
├────────┼──────────────────────┼──────────────────────┼──────────────────────┤
│ persis │ balances │ 1000 │ 999 │ ✗ UNEXPECTED
└────────┴──────────────────────┴──────────────────────┴──────────────────────┘
Using without pre-captured snapshot
The macro can also capture the “before” snapshot automatically when called without a pre-captured snapshot:
#![allow(unused)]
fn main() {
// Captures current state as "before", then asserts after operations
assert_storage_diff!(env, contract_id, {
added: [{ key: "new_key" }],
modified: [{ key: "count", from: 0u32, to: 1u32 }],
});
}
Note: This form captures the current state as the “before” snapshot when the macro is invoked, so any operations before the macro call are included in the baseline.
Multi-party balance conservation
Asserting balance conservation across multi-user operations (e.g., swaps, multi-hop routes, fee splits, or batch transfers) commonly leads to repetitive boilerplate when querying balances before and after calls. The assert_balance_conserved! macro captures pre-invocation balances, runs the operation, verifies that total tokens across all tracked participants plus reserves are conserved, and accounts for explicit external mints or burns:
#![allow(unused)]
fn main() {
use soroban_testkit_assert::assert_balance_conserved;
// Standard 2-party transfer:
assert_balance_conserved!(
accounts: [&alice, &bob],
balance: |addr| token_client.balance(addr),
call: {
token_client.transfer(&alice, &bob, &100);
}
);
// Multi-party swap with fees, liquidity pool reserve, and custom labels:
assert_balance_conserved!(
accounts: [
(&alice, "Alice (Trader)"),
(&bob, "Bob (Recipient)"),
(&pool, "AMM Liquidity Pool"),
(&treasury, "Protocol Fee Vault")
],
balance: |addr| token_client.balance(addr),
call: {
router.swap(&alice, &bob, &1000);
}
);
// Invocations involving external mints or burns:
assert_balance_conserved!(
accounts: [&alice, &vault],
balance: |addr| token_client.balance(addr),
mint: 500,
burn: 100,
call: {
token_client.mint(&alice, &500);
token_client.burn(&vault, &100);
}
);
}
When an invariant is violated (for example, if a fee calculation suffers from fractional token loss or round-off leakage), assert_balance_conserved! panics with a formatted debit/credit reconciliation table:
Balance Conservation Breach: Discrepancy = -1 (LEAK DETECTED)
Expected net delta: 0 (mints: +0, burns: -0) | Actual net delta: -1
------------------------------------------------------------------------------------------------------
| Account / Reserve | Pre-Balance | Post-Balance | Delta (Debit/Credit) |
------------------------------------------------------------------------------------------------------
| Alice | 1000 | 900 | -100 |
| Bob | 0 | 97 | +97 |
| Fee Collector | 0 | 2 | +2 |
------------------------------------------------------------------------------------------------------
| Total Tracked | 1000 | 999 | -1 |
| External Mints (+) | | | +0 |
| External Burns (-) | | | -0 |
------------------------------------------------------------------------------------------------------
| Discrepancy | | | -1 (LEAK DETECTED) |
------------------------------------------------------------------------------------------------------
Cross-invocation token conservation (assert_token_conservation_across_invocations!)
When a protocol moves tokens across several invocations — swaps, fee splits,
batch settlements — the total supply must be conserved. The
assert_token_conservation_across_invocations! macro records balances before and
after each invocation, credits declared protocol fees to their treasury accounts,
and panics with a debit/credit reconciliation table when an invocation leaks
value:
#![allow(unused)]
fn main() {
use soroban_testkit_assert::assert_token_conservation_across_invocations;
let report = assert_token_conservation_across_invocations!(
accounts: [(&alice, "Alice"), (&bob, "Bob")],
balance: |address| token_client.balance(address),
fees: [(&treasury, "Treasury", 10i128)],
invocations: [
{ router.swap(&alice, &bob, &1000); },
{ router.settle_fees(&treasury); },
],
);
assert!(report.is_conserved());
}
Declared fees are internal transfers to treasury accounts and are auto-added
to the tracked set. A fee that never reaches its treasury is reported as a
missing credit. TokenConservationReport exposes is_conserved,
invocations, and fees for further assertions.
Comparative budget differential and relative gas savings
When refactoring code paths or evaluating alternative algorithm implementations (such as linear scan vs binary search, or unindexed vs indexed storage queries), smart contract engineers need to assert that an optimized branch achieves relative gas savings without regressing on CPU instruction or memory consumption.
The assert_budget_diff_within! macro executes baseline and optimized closures, measures the differential CPU instructions and memory bytes consumed, and asserts that relative savings targets are met.
Basic comparison
In default mode, the optimized branch must consume strictly fewer instructions or memory bytes than baseline and cannot regress in either dimension:
#![allow(unused)]
fn main() {
use soroban_testkit_assert::assert_budget_diff_within;
assert_budget_diff_within!(
&env,
baseline: {
client.linear_search(&items, &target);
},
optimized: {
client.binary_search(&items, &target);
},
);
}
Enforcing relative and absolute savings
Specify target percentage reductions (min_cpu_savings_percent, min_mem_savings_percent, min_savings_percent) or absolute thresholds (min_cpu_savings, min_mem_savings):
#![allow(unused)]
fn main() {
assert_budget_diff_within!(
env: &env,
baseline: || client.unindexed_scan(&key),
optimized: || client.indexed_lookup(&key),
min_cpu_savings_percent: 25.0, // At least 25% CPU instruction reduction
min_mem_savings_percent: 10.0, // At least 10% memory byte reduction
);
}
Space-time tradeoffs and dual environments
For operations that modify contract state or trade slight memory increases for massive CPU reductions:
#![allow(unused)]
fn main() {
// Separate environments ensure identical initial state:
assert_budget_diff_within!(
baseline: (&env1, { client1.bubble_sort(&data) }),
optimized: (&env2, { client2.radix_sort(&data) }),
min_cpu_savings_percent: 50.0,
allow_mem_regression: true, // Permit memory increase for large CPU reduction
);
}
Side-by-side consumption table on failure
When an optimized branch regresses or fails to reach the required savings target, assert_budget_diff_within! panics with a formatted side-by-side consumption table:
Budget Differential Assertion Failed!
Optimized branch failed to achieve required gas savings or exceeded baseline limits.
======================================================================================================================================
| Metric | Baseline | Optimized | Delta (Opt-Base) | Savings (%) | Target | Status |
======================================================================================================================================
| CPU Instructions | 100,000 | 85,000 | -15,000 | +15.00% savings | >= 25.00% | FAIL |
--------------------------------------------------------------------------------------------------------------------------------------
| Memory (Bytes) | 4,096 | 3,840 | -256 | +6.25% savings | <= baseline | PASS |
======================================================================================================================================
Failure Summary:
• Failed to achieve target CPU savings: achieved 15.00%, expected at least 25.00%
Event Sequence Assertions
While EventLog collects events across multiple invocations, verifying that events occurred in an exact sequence—or that a specific sequence occurred with allowed interleaving—is streamlined by assert_event_sequence!.
Strict and Relaxed Sequence Modes
assert_event_sequence! supports two modes:
Strict(exact_sequence): Every expected event must match consecutively 1:1 in length and order without unexpected or interleaved intermediate events.Relaxed(ordered_subsequence): Expected events must appear in order, allowing intermediate unrelated events between them.
#![allow(unused)]
fn main() {
use soroban_testkit_assert::assert_event_sequence;
use soroban_testkit_assert::sequence::{Relaxed, Strict};
// Relaxed mode: allows intermediate noise/transfer events
assert_event_sequence!(event_log, [
{ topic: "Deposit", contract: vault_id },
{ topic: "Mint", contract: token_id },
{ topic: "Transfer", contract: token_id },
], mode = Relaxed);
// Strict mode: exact 1:1 sequence match
assert_event_sequence!(event_log, [
{ topic: "Deposit", contract: vault_id },
{ topic: "Mint", contract: token_id },
], mode = Strict);
}
Matching Payload Data Predicates
You can match topics, contract IDs, and payload data predicates:
#![allow(unused)]
fn main() {
assert_event_sequence!(event_log, [
{
topic: "Deposit",
contract: vault_id,
data: |data| data.deserialize::<u64>() == Some(500)
},
{ topic: "Transfer", contract: token_id },
], mode = Relaxed);
}
Detailed Failure Diagnostics
When an event sequence fails, assert_event_sequence! outputs detailed diagnostics showing matched events, divergence points, and missing expectations:
Event sequence diverged at index 1 (mode = Strict / exact_sequence):
Expected event: { topic: "Mint", contract: CAAA... }
Observed event: topics: [Noise], contract: CAAA...
Full sequence breakdown:
[ 0] ✓ MATCHED | Expected: { topic: "Deposit" } | Observed: topics: [Deposit]
[ 1] ✗ DIVERGED | Expected: { topic: "Mint" } | Observed: topics: [Noise]
[ 2] PENDING | Expected: { topic: "Transfer" }| Observed: topics: [Transfer]
Filtering by contract
from_contract narrows a matcher to one contract id — essential once a test wires several contracts together.
Budget ranges and ceilings (assert_budget_consumed!)
assert_budget_consumed! bounds what the most recent top-level invocation cost (BudgetSnapshot::last_invocation), without manual snapshot arithmetic. Each metric takes either a range or an inclusive ceiling:
#![allow(unused)]
fn main() {
use soroban_testkit_assert::assert_budget_consumed;
client.swap(&user, &100);
assert_budget_consumed!(env, {
max_cpu: 150_000,
max_mem: 50_000,
});
assert_budget_consumed!(env, {
cpu: 10_000..=15_000, // any range: a..b, a..=b, a.., ..b, ..=b
mem: 1_000..,
});
}
| Key | Value | Meaning |
|---|---|---|
cpu | u64 range | CPU instructions must fall inside the range |
max_cpu | u64 | CPU instructions must not exceed it (inclusive) |
mem | u64 range | memory bytes must fall inside the range |
max_mem | u64 | memory bytes must not exceed it (inclusive) |
An unknown key is a compile error. On failure every breached metric is reported at once, with the observed value, the expected bound, the miss, and the miss as a percentage of the crossed bound:
assert_budget_consumed! failed:
cpu_insns: observed 1_650, expected ..=1_500 — over the upper bound by 150 (+10.00%)
observed totals: cpu_insns=1_650 mem_bytes=812
The same check is available without the macro: build a BudgetBounds (.cpu(..), .max_cpu(..), .mem(..), .max_mem(..)) and call check(&snapshot) or assert_within(&snapshot) on any BudgetSnapshot.
Distinct Invoker Authorization
To enforce least-privilege delegation across addresses:
#![allow(unused)]
fn main() {
use soroban_testkit_assert::assert_auth_invoker_distinct;
// Asserts that only admin_address authorized the operation
assert_auth_invoker_distinct!(&admin_address, &[admin_address.clone()]);
}
Golden snapshots (assert_snapshot_matches!)
assert_snapshot_matches! serializes a value into canonical JSON and compares it with a
committed snapshot stored at tests/snapshots/<name>.snap.json (relative to the test crate’s
CARGO_MANIFEST_DIR). The first run creates the file. Later runs fail with a colored unified
diff, so an added, renamed or omitted field is visible as a removed and added line with exact
line numbers:
#![allow(unused)]
fn main() {
use soroban_sdk::testutils::Address as _;
use soroban_testkit_assert::{assert_snapshot_matches, SnapshotOptions};
let state = ContractState { owner: addr, total: 100 };
// Uses an explicit `Env` (works for `Val`, `ScVal`, `Map`, and `#[contracttype]` values):
assert_snapshot_matches!("state after init", state, env);
// Two-argument form uses a fresh `Env`, so pass `env` explicitly for host objects:
assert_snapshot_matches!("answer", 42u32);
// Volatile fields and generated addresses can be normalized:
let options = SnapshotOptions::new()
.normalize_addresses(true)
.ignore_field("updated_at");
assert_snapshot_matches!("state after init", state, env, options);
}
Because macro_rules! cannot capture an implicit caller-local identifier, the two-argument arm
uses a default Env and is meant for values that do not reference host objects; use the
three-argument arm with your test’s env otherwise.
The conversion is also available directly:
#![allow(unused)]
fn main() {
use soroban_testkit_assert::{assert_snapshot_matches, snapshot_json};
let json = snapshot_json(&env, &state);
assert_snapshot_matches("state after init", &json);
}
snapshot_json accepts Val, ScVal, primitives and user #[contracttype] structs through
TryIntoVal. The renderer sorts map keys, escapes strings consistently, writes integers as
decimal text and covers Void, Bool, the unsigned and signed integer variants (including
128-bit), Symbol, String, Bytes (lowercase hex with a 0x prefix), Address,
Timepoint, Duration, Vec and Map. Other ScVal variants get a readable debug fallback.
Map insertion order therefore never changes a snapshot.
normalize_addresses(true) replaces addresses with ~address0, ~address1, … in order of
first appearance, so regenerated addresses do not cause drift. ignore_field("...") drops a
field at every depth from both the stored and current value; timestamps and nonces are typical
candidates. Note that a missing snapshot is created with normalization applied.
Two environment variables control persistence:
SNAPSHOT_DIRoverrides the compile-timetests/snapshotslocation at runtime.UPDATE_SNAPSHOTS=1rewrites the snapshot on drift instead of failing, which is convenient when an intentional state change needs to be accepted.
A mismatch looks like this (red for stored lines, green for current lines, cyan for headers):
snapshot assertion failed for "state after init": stored snapshot does not match the current value
--- expected (stored): tests/snapshots/state after init.snap.json
+++ actual (current): state after init
@@ -1,4 +1,4 @@
{
- "owner": "alice",
+ "owner": "bob",
"total": 100
}
set UPDATE_SNAPSHOTS=1 to accept the new snapshot
soroban-testkit-fixtures
A reusable test context inspired by Foundry’s setUp(): one place to build the environment, admin and user addresses every test needs.
What TestContext gives you
| Field | Value |
|---|---|
ctx.env | A fresh Env, auth mocked unless you opt out |
ctx.admin | A generated Address to act as deployer / owner |
ctx.users | A Vec<Address> you extend with add_user() |
ctx.mock_auths | The auth policy the context was built with, re-applied by reset() |
Basic usage
#![allow(unused)]
fn main() {
use soroban_testkit_fixtures::TestContext;
let ctx = TestContext::new();
// ctx.env — pre-configured Env with mock_all_auths
// ctx.admin — generated admin address
// ctx.users — empty vec, add users as needed
// ctx.user(i) — safe accessor with diagnostic panic message
}
Accessing users
Retrieve generated user addresses with ctx.user(index):
#![allow(unused)]
fn main() {
let ctx = TestContextBuilder::new().with_users(3).build();
let alice = ctx.user(0);
let bob = ctx.user(1);
}
When called with an index out of bounds, ctx.user(i) panics with a descriptive diagnostic pointing directly at TestContextBuilder::with_users:
user index out of bounds: index is 2 but context holds 2 users (did you call TestContextBuilder::with_users(3)?)
Builder pattern
Describe the context you want instead of assembling it:
#![allow(unused)]
fn main() {
use soroban_testkit_fixtures::builder::TestContextBuilder;
let ctx = TestContextBuilder::new()
.with_users(5) // Pre-generate 5 user addresses
.without_mock_auths() // Disable automatic auth mocking
.build();
}
Keep mock_all_auths for behaviour tests. Call without_mock_auths() as soon as a test asserts who had to sign — that is AuthMatcher territory.
Moving the ledger clock
Time-dependent contracts — vesting, auctions, lockups — need the ledger to
advance between two calls. TestContext exposes the four operations that cover
almost all of that without building a LedgerInfo by hand:
| Method | Effect |
|---|---|
ctx.timestamp() | The unix timestamp the ledger reports |
ctx.sequence() | The ledger sequence number the ledger reports |
ctx.set_timestamp(t) | Jump to absolute time t |
ctx.advance_time(s) | Add s seconds, return the new timestamp |
ctx.advance_ledger(n) | Add n to the sequence, return the new height |
ctx.archive_expired(n) | Advance n ledgers, archive everything past its TTL, return the ArchivalSweepSimulator holding it |
#![allow(unused)]
fn main() {
use soroban_testkit_fixtures::TestContext;
let mut ctx = TestContext::new();
ctx.set_timestamp(1_700_000_000);
// ... assert the position is locked
let unlocked_at = ctx.advance_time(86_400 * 30); // 30 days later
assert_eq!(unlocked_at, 1_702_592_000);
// ... assert the position is claimable
}
Advance only what you assert
advance_time leaves the sequence alone and advance_ledger leaves the clock alone. A real ledger close moves both, so a test that wants the full picture calls each — and a test that only cares about TTL expiry does not silently move the clock.
Reentrancy guard verification
ReentrancyGuardHarness deploys a target contract and a malicious receiver,
then executes a cross-contract callback back into the target:
#![allow(unused)]
fn main() {
use soroban_testkit_fixtures::reentrancy::ReentrancyGuardHarness;
let harness = ReentrancyGuardHarness::new();
assert!(harness.execute(false));
assert!(!harness.lock_is_set());
assert!(!harness.execute(true)); // receiver panics after the callback
assert!(!harness.lock_is_set()); // caught panic rolls the lock back
}
The harness proves that a second invocation is rejected while the guard is held, and that both successful calls and caught receiver panics leave the target lock in its restored unlocked state.
Set before you advance
The SDK test env starts at timestamp 0 and sequence 0, so advance_time(3_600) lands on 3_600 rather than on wall-clock time. Pin an absolute moment with set_timestamp first when the test reads better as a date.
Both helpers saturate instead of wrapping: advancing past u64::MAX or
u32::MAX returns the maximum rather than panicking or rolling the clock back
to a date in 1970.
Pruning expired contract storage
After advancing the ledger, call prune_expired_storage to compact all
contract-data entries whose live-until ledger has been reached. Temporary
entries become absent; persistent entries are removed from the mock host to
simulate archival. Entries whose TTL is still active are preserved. The
returned report separates temporary pruning from persistent archival:
#![allow(unused)]
fn main() {
let mut ctx = TestContext::new();
// ... store temporary and persistent contract data
ctx.advance_ledger(100);
let report = ctx.prune_expired_storage().unwrap();
assert_eq!(report.ledger, ctx.sequence());
}
TestContext::prune_expired_storage and StorageCompactor::prune_expired
return a host error if the mock storage update fails. This helper changes
in-memory test-host state; it does not perform an on-chain transaction or
restore archived entries.
Scripting multi-block scenarios
Time-dependent contract logic — vesting, streams, bridge relays — fails under
ledger movement a single call cannot reproduce: a missed block, a stalled
network, a rollback that makes the clock run backwards. ScenarioBuilder
scripts that movement as a chain over one TestContext:
#![allow(unused)]
fn main() {
use soroban_testkit_fixtures::ScenarioBuilder;
let mut scenario = ScenarioBuilder::new(&ctx);
scenario
.step("Open stream", |ctx| stream_client.open(&1_000))
.advance_blocks(100)
.step("Claim partial", |ctx| stream_client.claim())
.halt(3_600)
.advance_blocks(500)
.step("Final claim", |ctx| stream_client.claim());
scenario.assert_all_passed();
}
| Method | Effect |
|---|---|
step(label, f) | Runs a contract invocation and records it |
check(label, f) | Runs a bool state-consistency check |
probe(label, f) | Reads a contract clock/state and rejects a backwards move |
advance_blocks(n) | Closes n ledgers, leaving the clock alone |
advance_time(s) | Moves the clock s seconds, leaving the sequence alone |
advance(blocks, seconds) | Moves both |
halt(s) | A network halt: time passes, no block closes |
rollback_blocks(n) | A reorg that rewinds the sequence |
set_clock(seq, t) | Jump to an explicit ledger position |
step and check run through catch_unwind, so a contract panic does not stop
the script: later steps still run, and assert_all_passed fails with the whole
timeline, marking the step that panicked. format_timeline() returns the same
text when a test wants to assert on it:
SCENARIO FAILED (1 failure(s))
#00 seq=0 t=1700000000 start: seq=0 t=1700000000 (start)
#01 seq=0 t=1700000000 Open stream: seq 0->0, t 1700000000->1700000000 (passed)
#02 seq=100 t=1700000000 advance 100 block(s): seq 0->100 (passed)
#03 seq=100 t=1700000100 Claim partial: ... (FAILED: attempt to subtract with overflow)
-> scenario step #3 "Claim partial": attempt to subtract with overflow
probe is the automated clock-inversion check. A contract reports the time it
believes it is at, and a reading below the previous one is recorded as a
failure naming both values and the subtraction that would underflow — which is
what catches a streaming contract that computes now - last_claim after a
reorg.
#![allow(unused)]
fn main() {
scenario
.step("Open", |_| stream.open(&1_700_000_000, &10))
.advance_time(100)
.probe("before reorg", |_| stream.clock())
.set_clock(0, 1_699_999_900)
.probe("after reorg", |_| stream.clock());
// one failure: clock inversion in "after reorg": 1699999900 after …
}
Block production is not uniform. A scenario can close 1 then 100 then 500 blocks, or stop closing them while seconds still pass. A contract that measures progress in timestamp() reaches the same state either way; one that confuses heights with time does not — and the timeline shows which steps saw which heights.
blocks_elapsed() and seconds_elapsed() saturate at zero, so a rollback below
the starting height reports zero rather than wrapping into a huge number.
Resetting the chain underneath a test
Some scenarios are the same actors on a clean chain twice: a phase-one
initialize, then a phase-two that must not see phase-one’s storage. reset
gives you that without rebuilding the fixture:
| Method | Effect |
|---|---|
ctx.reset() | Fresh env — ledger, events, auths and contract storage all cleared — with the same admin and users |
ctx.reset_full() | Fresh env and new identities: a new admin and a new users list of the same length |
#![allow(unused)]
fn main() {
let mut ctx = TestContextBuilder::new().with_users(2).build();
let env = ctx.env.clone();
let (vault, client) = register_vault(&env);
client.deposit(&ctx.users[0], &1_000);
ctx.reset();
// ctx.admin and ctx.users are the same actors; the chain remembers nothing.
// `vault` named a contract in the env that is gone, so register again:
let env = ctx.env.clone();
let (vault, client) = register_vault(&env);
assert_eq!(client.balance(&vault, &ctx.users[0]), 0);
}
Re-register after resetting
An Address is a handle into the env that made it, so reset rebuilds each one from its ScAddress form and the strkey survives intact. A registered contract cannot travel that way — its code and storage live in the old env — so the id you held before the reset points at nothing. Reach for a second TestContext instead whenever the two phases want different fixtures, user counts or auth policies.
Reset keeps the policy, not by magic
TestContext remembers whether it mocks authorizations, so an unmocked context stays unmocked through a reset. An Env does not report its own policy, which means with_env has to assume the mocked default — set ctx.mock_auths = false when it is not what you configured.
reset_full exists because SDK v28 mints test addresses from a counter that
restarts at 1 in every Env. Generating straight away would hand back exactly
the addresses you replaced, so it first walks the new env’s counter past the
range the old identities occupied.
Named branches and speculative paths
reset is destructive: it throws the chain away. When several paths start from
the same protocol state — five trade routes from one liquidity pool, three
liquidation scenarios from one debt position — build the state once and take a
named checkpoint instead:
#![allow(unused)]
fn main() {
use soroban_testkit_fixtures::branching::BranchingContext;
use soroban_testkit_fixtures::builder::TestContextBuilder;
let mut ctx = BranchingContext::new(TestContextBuilder::new().with_users(2).build());
let pool_id = ctx.env.register(Pool, ());
let pool = PoolClient::new(&ctx.env, &pool_id);
pool.deposit(&1_000); // setup, executed once
ctx.create_branch("initial_pool");
for route in routes {
ctx.switch_branch("initial_pool").create_branch(route.name);
// ... run the route against the pool's original 1,000 ...
}
}
BranchingContext derefs to TestContext, so ctx.env, ctx.users,
advance_time and the rest keep working. Its branch API is:
| Method | Effect |
|---|---|
create_branch(name) | Snapshot the ledger under name and make it current |
switch_branch(name) | Rewrite the live ledger to the checkpoint |
current_branch() | The last created or switched-to name |
branch_names() | Every checkpoint, in sorted order |
has_branch(name) | Whether a checkpoint exists |
delete_branch(name) | Drop one checkpoint, returning whether it existed |
A switch restores every captured ledger entry with its value and live_until
TTL, removes contract data keys written after the checkpoint (including entries
the contract deleted, which come back), and resets the full ledger clock:
sequence, timestamp, protocol version, network id, base reserve and the TTL
thresholds.
The environment itself is kept rather than rebuilt, which is what makes the rest of the fixture keep working:
- native test contracts stay registered, so no setup is re-executed;
ctx.admin,ctx.users, contract addresses and clients remain valid;- the auth policy (
mock_all_auths) and the network profile still apply.
A contract registered after a checkpoint keeps its code and instance entries — its storage is cleared, but it remains callable, because the SDK exposes no API to delete those entries. Register every contract before the checkpoint. Recorded authorizations (env.auths()) belong to the most recent invocation rather than to the ledger, so assert them immediately after the call that produced them.
Persistent storage eviction
StateEvictionSimulator creates a short-lived persistent entry, advances its
ledger past the TTL, and exposes the archived read error before exercising
restoration. It uses protocol 22 to observe the legacy Storage failure, then
protocol 23 automatic restoration to model an invocation carrying the entry
in its restore list. The restored value is read back and its TTL extended.
#![allow(unused)]
fn main() {
let env = Env::default();
let contract = env.register(MyContract, ());
let mut state = StateEvictionSimulator::new(&env, &contract, key.into_val(&env), value.into_val(&env));
state.store();
state.advance_past_ttl();
assert!(state.try_read().unwrap_err().is_type(ScErrorType::Storage));
state.restore(20_000);
assert_eq!(state.read(), Some(state.original()));
assert!(state.ttl() >= 20_000);
}
The simulator keeps archived state in the host so restoration must recover the original data; it does not substitute a new value during the test.
TTL and expiration simulation
Testing a restore path or an archival boundary used to mean arithmetic on
sequence numbers that silently goes stale when the network’s rent parameters
change. TestContext reads the boundary from the entry itself:
#![allow(unused)]
fn main() {
use soroban_sdk::{symbol_short, Val};
use soroban_testkit_fixtures::{TestContext, TtlInspector};
let ctx = TestContext::new();
let contract_id = ctx.env.register(Nonces, ());
NoncesClient::new(&ctx.env, &contract_id).put(); // writes a temporary entry
let key = symbol_short!("nonce");
let ttl = TtlInspector::for_key(&ctx.env, &contract_id, &key);
assert!(ttl.live_until_ledger > ctx.ledger_sequence());
ctx.fast_forward_to_expiration(&contract_id, &key);
let value = ctx.env.as_contract(&contract_id, || {
ctx.env.storage().temporary().get::<_, Val>(&key)
});
assert!(value.is_none());
}
Storage has to be read from inside a contract frame, hence as_contract;
ctx.assert_temporary_expired(&contract_id, &key) does exactly that read and
also checks the TTL.
| Method | Does |
|---|---|
ttl(contract, key) | TtlInspector for the entry, in whichever tier holds it |
ledger_sequence() | The current sequence, as used in TTL arithmetic |
fast_forward_to_expiration(contract, key) | Sets the sequence to live_until + 1, the first ledger the entry is not live |
fast_forward_to_last_live_ledger(contract, key) | Sets the sequence to live_until, the last ledger the entry still reads |
observe_ttl_extension(contract, key, call) | Runs call and returns a TtlExtension (before/after readings) |
assert_temporary_expired(contract, key) | The temporary entry is past its TTL and reads as empty from the contract |
assert_persistent_archived(contract, key) | The persistent entry is past its TTL, checked without restoring it |
How each tier behaves
- Temporary — past its TTL the entry is gone: the next read returns
Noneandhasreturnsfalse, and nothing can bring it back. - Persistent — past its TTL the entry is archived. The SDK test host
restores an archived entry the moment a contract reads it, so check the
archival with
assert_persistent_archived(which does not read through the contract) or take archived entries off the ledger witharchive_expiredand test the restore path withArchivalSweepSimulator. - Instance — every instance key shares the contract instance’s TTL;
ttl()on an instance key reports it, and expiry archives the instance.
Validating extend_ttl
#![allow(unused)]
fn main() {
let extension = ctx.observe_ttl_extension(&contract_id, &key, || {
client.extend(&threshold, &extend_to)
});
extension.assert_matches_extend_ttl(threshold, extend_to);
extension.assert_extended_to(extend_to);
}
assert_matches_extend_ttl judges the call against the host’s rules from the
before reading (extend only when the TTL is at or below threshold, clamp
to the network ceiling, never shorten), so the same assertion covers both
sides of the threshold. assert_not_extended pins the no-op case.
Testing schema migrations
Contracts bump their storage schema — v1 to v2 to v3 — and migrate the data
they already hold. MigrationRunner drives those migrations from a test and
reads the schema version out of the contract’s instance storage before and
after every step:
#![allow(unused)]
fn main() {
use soroban_testkit_fixtures::{MigrationRunner, TestContext};
let ctx = TestContext::new();
let id = ctx.env.register(Vault, ());
let mut runner = MigrationRunner::with_client(&ctx.env, &id, VaultClient::new(&ctx.env, &id));
assert_eq!(runner.current_version(), 1);
let step = runner.execute_migration(2, |client| client.migrate_v1_to_v2());
step.assert_renamed("balance", "ledger");
step.assert_schema_after(&["ledger", "version"]);
assert_eq!(runner.current_version(), 2);
runner.execute_migration(3, |client| client.migrate_v2_to_v3());
runner.assert_schema(&["fee_bps", "ledger", "version"]);
}
MigrationRunner::new(&env, &id) is the same runner with the contract’s
Address passed to each closure instead of a client.
The version lives under the instance-storage symbol version by default;
with_version_key(DataKey::Version) points the runner at whatever key the
contract uses, stored_version() reads it raw, and a contract that stores no
version yet counts as v1 unless assuming_unversioned_is(n) says otherwise.
The contract’s migration writes the new version itself — the runner checks it,
it never writes it.
| A step is refused or fails when… | MigrationError |
|---|---|
| it already ran through this runner | AlreadyApplied — names the step it ran as |
| the target is at or below the current version | NotForward |
the target skips a version (v1 → v3) | SkipsVersion |
| it finished without recording the target version | VersionNotRecorded |
| it panicked and storage is unchanged | Failed |
| it panicked and left storage changed | NotAtomic — lists the leftover keys |
The first three are checked before the closure runs, so a double migration
never reaches the contract. execute_migration panics with the error’s message;
try_execute_migration returns it, which is what a test that expects a
refusal wants.
Each successful step returns a MigrationRecord holding the StorageSnapshot
on either side of it. diff(), assert_added, assert_removed,
assert_renamed, assert_schema_before and assert_schema_after are the
before-and-after schema assertions, and runner.history() lists every step in
order.
A single contract call that panics is rolled back by the host, so a broken one-call migration reports Failed with storage untouched. A migration spread over several calls has no such transaction around it: if the second call fails, the first call's writes stay — and the runner reports that as NotAtomic, naming what was left behind.
Testing in-place contract upgrades (ContractUpgradeHarness)
A contract upgrades itself with
env.deployer().update_current_contract(ContractExecutable::Wasm(new_wasm_hash)): it keeps its
address and storage, and only the code changes. ContractUpgradeHarness
drives that upgrade from a test and checks the four things a production
upgrade can get wrong:
| Check | API |
|---|---|
| Instance and persistent entries written by V1 survive byte for byte | verify_state_preserved() / verify_state_preserved_except(&["config"]) |
| A migration converts legacy data, and a failed one rolls back | migrate(..) / try_migrate(..) |
| Entry points V2 dropped stop answering | assert_function_removed("legacy_ping", args) |
| An upgrade without the required signature is refused and V1 stays | try_upgrade_to_wasm(..) returning UpgradeError::Rejected |
No compiled Wasm is needed. upload(Version) registers a contract type from
the current crate under a Wasm hash (Env::upload), and deploy_uploaded
deploys V1 the same way, so the upgrade runs through the real
update_current_contract_wasm host path and later calls go to V2:
use soroban_testkit_fixtures::{deploy_uploaded, ContractUpgradeHarness, TestContext};
let ctx = TestContext::new();
let id = deploy_uploaded(&ctx.env, VaultV1);
let v1 = VaultV1Client::new(&ctx.env, &id);
let mut harness = ContractUpgradeHarness::new(&ctx.env, &id);
harness.populate_v1_state(|_| {
v1.init(&ctx.admin);
v1.set_config(&30); // legacy layout: a bare u32 fee
v1.deposit(&user, &500);
});
let v2_wasm_hash = harness.upload(VaultV2);
harness.upgrade_to_wasm(&v2_wasm_hash);
harness.verify_state_preserved();
let v2 = VaultV2Client::new(&ctx.env, &id);
let step = harness.migrate(|_| v2.migrate());
step.assert_removed("config");
step.assert_added("config2");
harness.verify_state_preserved_except(&["config", "version"]);
harness.assert_function_removed("legacy_ping", soroban_sdk::vec![&ctx.env]);
The contract under test must expose an upgrade entry point that takes the new
Wasm hash as its only argument (upgrade by default; change it with
with_upgrade_function("name")). The harness calls it with whatever
authorization the environment provides, so withholding authorization tests
the refusal path:
ctx.env.set_auths(&[]);
let error = harness.try_upgrade_to_wasm(&v2_wasm_hash).unwrap_err();
assert!(matches!(error, UpgradeError::Rejected { .. }));
try_migrate catches a panicking migration and compares storage before and
after it. A single contract call that panics is rolled back by the host, so it
reports MigrationFailed { atomic: true, .. }. A migration spread over several
calls whose later call fails reports atomic: false and lists the leftover
changes. populate_v1_state (or mark_baseline) records the baseline that the
preservation checks compare against. Temporary entries are left out of that
comparison because they can expire independently of any upgrade. Each upgrade
is kept in history() as an UpgradeRecord holding the storage on either side
of it.
EventIndexerEmulator
EventIndexerEmulator is an in-memory index that belongs to a test scenario:
keep one instance for as long as the test needs its history, and drop it when
the scenario ends. SDK v28’s env.events().all() exposes the events from the
most recent invocation, not an automatic stream of all ledgers. Ingest the
events after each invocation and provide the ledger sequence explicitly:
#![allow(unused)]
fn main() {
use soroban_sdk::testutils::{Events as _, Ledger as _};
use soroban_testkit_fixtures::EventIndexerEmulator;
let mut indexer = EventIndexerEmulator::new();
let sequence = ctx.sequence();
client.transfer(&from, &to, &100);
indexer
.ingest_ledger(sequence, ctx.env.events().all().events())
.unwrap();
ctx.advance_ledger(1);
let sequence = ctx.sequence();
client.transfer(&from, &to, &200);
indexer
.ingest_ledger(sequence, ctx.env.events().all().events())
.unwrap();
}
Ingestion copies the original ContractEvent, including only metadata the SDK
actually exposes. The ledger sequence is fixture-level metadata supplied by
the caller; it is not present in the event itself. Soroban also does not give
these events a unique event id, so the fixture identity is the supplied ledger
sequence plus a monotonically increasing ingestion ordinal. Re-ingesting the
same XDR event records a second occurrence rather than guessing that it is a
duplicate.
The index has inverted indexes for symbol topics and emitting contract ids, plus an ordered ledger-sequence index. Results are ordered by ascending ledger sequence and then by ingestion order within a ledger, even if the test ingests ledgers out of order. A query combines topic, contract and ledger filters with AND; an event matching multiple of its own topics appears only once.
Topic, contract and ledger queries
An exact topic pattern matches a ScVal::Symbol topic exactly. * matches
zero or more bytes and can be used anywhere in the pattern: "transfer" is
exact, "trans*" matches a prefix, "*fer" matches a suffix, and "*" matches
any symbol topic. Non-symbol topic values are not interpreted as strings and
do not match a topic query.
query_by_contract accepts a Soroban contract Address; account addresses
match no events. query_by_contract_id accepts an XDR ContractId directly.
query_range treats both ledger endpoints as inclusive and returns an error
when the start is greater than the end.
#![allow(unused)]
fn main() {
use soroban_testkit_fixtures::{EventIndexerEmulator, EventQuery};
let transfers = indexer.query_by_topic("transfer");
let matching_contract = indexer.query_by_contract(&contract_id);
let ledgers = indexer.query_range(100, 110)?;
let query = EventQuery::new()
.topic("trans*")
.contract_address(&contract_id)
.ledger_range(100, 110);
let first_page = indexer.query(&query)?;
}
Each query returns an EventPage. Its total is the count before pagination,
and offset identifies the first requested match. The default maximum page
size is 100; configure a positive cap with set_page_limit. Explicit page
requests use query_by_topic_page, query_by_contract_page,
query_range_page, or query_page; a requested size above the cap is reduced
to the configured maximum. Use next_offset() to fetch the next page:
#![allow(unused)]
fn main() {
indexer.set_page_limit(25)?;
let first = indexer.query_by_topic("transfer");
if let Some(offset) = first.next_offset() {
let next = indexer.query_by_topic_page("transfer", offset, 25)?;
// `next.events` continues in the same deterministic order.
}
}
Empty queries return an empty page. Zero page sizes and reversed ledger ranges
are reported as EventIndexerError, not silently accepted.
GasExhaustionHarness
GasExhaustionHarness executes a real Soroban host invocation after applying
the configured CPU and memory limits through SDK v28’s test budget. It does
not synthesize budget errors. Its default configuration is 250,000 CPU
instructions and unlimited test-host memory; cpu_50k() and cpu_100k()
provide the other common CPU ceilings. Use with_limits(cpu, memory) for a
custom pair.
The function name and arguments are passed to Env::try_invoke_contract, so
arguments must be Soroban Vals. The report distinguishes successful results,
contract errors, other host errors, invocation aborts, conversion failures and
host-reported budget exhaustion:
#![allow(unused)]
fn main() {
use soroban_sdk::{Env, Val, Vec};
use soroban_testkit_fixtures::{
ExecutionStatus, GasExhaustionHarness,
};
let env = Env::default();
let contract_id = env.register(MyContract, ());
let report = GasExhaustionHarness::cpu_250k().invoke(
&env,
&contract_id,
"process_batch",
Vec::<Val>::new(&env),
);
match &report.status {
ExecutionStatus::Succeeded(_) => {}
ExecutionStatus::BudgetExhausted { resource, .. } => {
eprintln!("execution exhausted {resource:?}");
}
other => panic!("unexpected invocation result: {other:?}"),
}
println!("{}", report.diagnostic());
}
The report includes the configured limits, actual CPU and memory costs, and
diagnostic events returned by env.logs().all(). It classifies exhaustion by
comparing the measured resource totals with those limits; if both dimensions
cross the boundary or the counters do not identify one, the report says so
instead of guessing. The harness resets the test budget to SDK defaults after
recording the report, so later assertions and storage inspection can proceed.
Failed invocations use the host’s transactional semantics. To test rollback, capture state before the call, invoke a contract method that writes persistent state and then performs enough metered host work to exhaust its budget, and compare the state snapshot after the harness returns:
#![allow(unused)]
fn main() {
use soroban_testkit_core::storage::StorageSnapshot;
use soroban_sdk::{Env, IntoVal, Val};
use soroban_testkit_fixtures::{ExecutionStatus, GasExhaustionHarness};
let before = StorageSnapshot::capture(&env, &contract_id);
let report = GasExhaustionHarness::with_limits(100_000, u64::MAX).invoke(
&env,
&contract_id,
"write_then_process_large_batch",
soroban_sdk::vec![&env, 10_000u32.into_val(&env)],
);
assert!(matches!(
&report.status,
ExecutionStatus::BudgetExhausted { .. }
));
assert_eq!(StorageSnapshot::capture(&env, &contract_id), before);
}
For memory-specific tests, use a custom CPU limit with a deliberately tight memory limit. The host can report resource exhaustion and the metered totals, but it does not expose an exact Rust source statement or loop iteration. Native test contracts also omit VM instruction and Wasm execution costs, so their measurements are not representative of the deployed Wasm contract; register or upload Wasm when those costs are part of the test.
Congestion and queue delay simulator
Under network congestion on Stellar, transaction base fees fluctuate and transactions can be delayed across multiple ledgers in validator queues before execution. Contracts enforcing deadlines (such as slippage parameters or auction bidding windows) must reject delayed transactions gracefully. CongestionSimulator emulates variable base fees, surge spikes, and ledger delays:
#![allow(unused)]
fn main() {
use soroban_testkit_fixtures::CongestionSimulator;
let mut sim = CongestionSimulator::new()
.with_base_fee(100) // Base fee in Stroops
.with_base_fee_range(100, 1_000) // Fluctuation bounds
.with_surge_multiplier(5) // Surge pricing multiplier
.with_delay_range(1, 10) // Simulated ledger queue arrival delay
.with_seconds_per_ledger(5);
// Check fee requirements under fluctuating conditions:
let required_fee = sim.calculate_fee(1);
assert!(sim.is_fee_sufficient(offered_fee, 1));
// Advance ledger height and timestamp to simulate arrival queue latency:
let report = sim.advance_delay(&env);
println!("Delayed by {} ledgers ({}s)", report.ledgers_delayed, report.seconds_delayed);
// Execute invocation closure with simulated congestion delay:
let (report, result) = sim.execute_with_delay(&env, || {
client.try_swap(&100, &90, &deadline)
});
}
Multi-validator consensus and ledger close jitter
Stellar’s SCP does not close a ledger on a fixed cadence: intervals drift between roughly three and eight seconds, and a validator only backs a close whose interval sits close to the one it nominated. Protocols that average over time — TWAP oracles, streaming rates, funding accrual, timelocks — behave differently under that jitter than they do against a metronome, and a test that closes every ledger by exactly five seconds cannot tell the two apart. ConsensusSimulator closes ledgers with a Gaussian-jittered interval, advances the ledger header, and counts validator votes for each round:
#![allow(unused)]
fn main() {
use soroban_sdk::Env;
use soroban_testkit_fixtures::ConsensusSimulator;
let env = Env::default();
let mut sim = ConsensusSimulator::new()
.with_validators(5)
.with_quorum(3)
.with_close_interval(3_000, 8_000)
.with_jitter_std_ms(1_200.0)
.with_seed(7); // replay the same close sequence
let round = sim.run_round(&env);
println!(
"ledger {} at t={} ({} ms, {} votes for, quorum {})",
round.close.sequence,
round.close.timestamp,
round.close.close_interval_ms,
round.votes_for,
round.quorum,
);
// Or advance the chain and run the invocation in the block it produced:
let (round, result) = sim.execute_with_consensus(&env, || client.try_swap(&100, &90, &deadline));
}
| Method | Effect |
|---|---|
close_ledger(&env) | Close one ledger; returns a LedgerClose with the header values, the sampled interval and its jitter |
advance_ledgers(&env, n) | Close n ledgers, returning each close in order |
run_round(&env) | Close a ledger and collect every validator’s vote on the interval |
execute_with_consensus(&env, f) | Run a round, then invoke f against the new head |
next_close_interval_ms() | Sample the next interval without touching the env |
| Builder | Effect |
|---|---|
with_validators(n) | Validators that vote each round (at least one) |
with_quorum(n) | Agreeing votes a round needs, clamped to 1..=validators |
with_close_interval(min, max) | Allowed close interval range in milliseconds |
with_jitter_std_ms(std) | Standard deviation of the Gaussian jitter; zero closes on the midpoint |
with_seed(seed) | Reproducible interval and vote sequence |
The range is a promise
Samples are drawn Gaussian around the range midpoint and then clamped, so a close never leaves the interval the test declared even when the tail of the distribution would. A zero standard deviation makes every close take the midpoint.
Headers store whole seconds
The sampled interval is reported in milliseconds, but a ledger header stores seconds, so the timestamp advances by the interval rounded up. Both numbers are on LedgerClose, which is why a test can assert on the millisecond sample and on env.ledger().timestamp() independently.
Votes and quorum
A round closes a ledger regardless of the vote outcome, which is what makes it useful for testing protocols that react to a ledger rather than to consensus itself. Each validator nominates its own interval and votes for the close when that nomination is within acceptance_band_ms — 1.96 standard deviations — of the closed interval:
#![allow(unused)]
fn main() {
let round = sim.run_round(&env);
assert_eq!(round.votes_for + round.votes_against, round.validators);
assert_eq!(round.quorum_reached, round.votes_for >= round.quorum);
}
A band that covers the jitter (the default) keeps rounds agreed. Tightening the band, or raising the quorum to every validator, produces rounds that close a ledger yet miss quorum — the shape a test needs when the contract under test is supposed to wait for agreement.
Time-weighted averages under jitter
An oracle that weights a price by the time it was live must use the ledger timestamp, not the block height. ConsensusSimulator is what makes the difference visible:
#![allow(unused)]
fn main() {
let mut sim = ConsensusSimulator::new().with_seed(3);
client.record(&100);
for _ in 0..20 {
sim.close_ledger(&env);
client.record(&100);
}
for _ in 0..20 {
sim.close_ledger(&env);
client.record(&200);
}
// Twenty irregular closes at each price: the TWAP sits between the prices,
// near their midpoint, instead of snapping to one of them.
let twap = client.twap();
assert!((100..=200).contains(&twap));
}
The fixture’s own tests run that shape across a range of seeds and assert that irregular intervals never push the average outside the price range or far from the duration-weighted result.
Mock price oracle (OracleHarness)
Price-dependent contracts need feeds with their own decimals, a round that
moves when an update arrives, a timestamp that ages, and a way to fail in the
same ways a real oracle fails. OracleHarness registers a MockPriceOracle
contract on an Env and drives both its stored data and its failure states.
It is re-exported at the crate root together with AssetPrice, OracleError,
MockPriceOracle, MockPriceOracleClient, Sep40Asset and Sep40PriceData.
The contract exposes both the harness-friendly get_price API and the SEP-40
consumer interface.
Registering and seeding feeds
OracleHarness::new(&env) registers the contract, generates an admin address,
and installs a 3,600-second heartbeat. It does not create a new Env or
change the caller’s auth policy: the admin address is a configuration key, and
admin-gated calls compare the supplied address with the stored one rather than
calling require_auth. Use with_admin to replace that key without losing
seeded prices, and with_heartbeat to change the freshness window before
seeding.
#![allow(unused)]
fn main() {
use soroban_sdk::{testutils::Ledger as _, Env, Symbol};
use soroban_testkit_fixtures::OracleHarness;
let env = Env::default();
env.ledger().set_timestamp(1_700_000_000);
let mut oracle = OracleHarness::new(&env).with_heartbeat(3_600);
oracle.set_price("BTC", 6_400_000, 2); // round 1, current ledger time
oracle.set_price("USD", 1_000_000, 6); // round 1, independent scale
assert_eq!(oracle.price("BTC").price, 6_400_000);
assert_eq!(oracle.price("BTC").decimals, 2);
assert_eq!(oracle.price("USD").decimals, 6);
let btc = Symbol::new(&env, "BTC");
assert!(oracle.client().try_get_price(&btc).is_ok());
}
An AssetPrice holds four fields: price, decimals, round and
last_updated. Asset names are Soroban Symbols, so the harness converts the
&str you pass through Symbol::new; names may be up to 32 characters. Each
asset keeps its own scale, sequence and clock.
Validation and error precedence
get_price is the validated read. It checks in a fixed order, which matters
when more than one thing is wrong with a feed:
| Check | Error |
|---|---|
| Oracle is offline | OracleError::OracleOffline |
| No stored record for the asset | OracleError::AssetNotFound |
| Price is zero or negative | OracleError::InvalidPrice |
| Feed is older than the heartbeat | OracleError::StalePrice |
Staleness is measured against env.ledger().timestamp():
stale when now.saturating_sub(last_updated) > heartbeat
The boundary is inclusive: a quote exactly heartbeat seconds old is still
fresh. A timestamp in the future ages as zero, so moving the ledger clock
backwards does not make a feed stale.
peek_price deliberately skips the offline, sign and freshness checks. It
still reports AssetNotFound for an unknown asset. The harness exposes it as
price(asset), which is what assertions use to inspect the bad state that
get_price is about to reject.
After oracle.simulate_stale("BTC"):
#![allow(unused)]
fn main() {
assert_eq!(
oracle.client().try_get_price(&btc),
Err(Ok(OracleError::StalePrice))
);
assert_eq!(oracle.price("BTC").price, 6_400_000); // raw record still there
}
The generated client’s try_get_price returns the SDK’s nested result:
Ok(Ok(quote)) on success, Err(Ok(OracleError)) for a contract error and
Err(Err(invoke_error)) for a host-level failure. The plain get_price client
method unwraps that result and panics on an error.
Rounds, timestamps and explicit updates
set_price publishes at the current ledger timestamp and the next round,
starting at 1 for a new asset. The harness keeps the round counter per asset,
so set_price_with_round can pin a round and timestamp, after which the next
plain set_price continues from that round plus one.
| Method | Effect |
|---|---|
set_price(asset, price, decimals) | Publish now at the next round |
set_price_with_round(asset, price, decimals, round, timestamp) | Publish an explicit record |
advance_round(asset, rounds) | Add to the round, preserving price and time |
set_round(asset, round) | Set the round absolutely |
set_last_updated(asset, timestamp) | Set the feed timestamp absolutely |
advance_last_updated_time(asset, delta: i64) | Shift the timestamp; negative deltas move it backwards and both ends saturate |
#![allow(unused)]
fn main() {
oracle.set_price_with_round("ETH", 2_000, 2, 40, 1_700_000_000);
oracle.advance_round("ETH", 3); // round 43
oracle.set_round("ETH", 50); // round 50
oracle.advance_last_updated_time("ETH", -120); // only this feed's clock moves
assert_eq!(oracle.price("ETH").last_updated, 1_699_999_880);
}
Round arithmetic and timestamp shifting saturate at u64::MAX and 0 rather
than wrapping.
Simulating stale, invalid, deviating and offline feeds
The simulation helpers publish real updates through the contract API at the next round and the current ledger time, so a consumer sees the same error it would see on a live feed.
| Helper | Produced state |
|---|---|
simulate_stale(asset) | Backdates the quote to now - (heartbeat + 1), clamped at zero |
simulate_negative_price(asset) | Publishes the negated current price, or -1 when it was zero |
simulate_deviation(asset, percent) | Publishes price * (100 + percent) / 100 |
set_offline(bool) | Takes the whole oracle offline or back online |
simulate_stale reads the heartbeat from the contract, so it follows
with_heartbeat. simulate_deviation takes a signed percentage: -30 is a
30% drop and 50 is a 50% rise. Integer division truncates toward zero;
-100 produces a zero price, which get_price reports as InvalidPrice, and
a value below -100 flips the sign.
#![allow(unused)]
fn main() {
oracle.set_price("ETH", 2_000, 2);
oracle.simulate_deviation("ETH", -30);
assert_eq!(oracle.price("ETH").price, 1_400);
assert_eq!(oracle.price("ETH").round, 2);
oracle.simulate_stale("ETH");
assert!(matches!(
oracle.client().try_get_price(&Symbol::new(&env, "ETH")),
Err(Ok(OracleError::StalePrice))
));
oracle.set_price("ETH", 2_000, 2);
oracle.simulate_negative_price("ETH");
assert_eq!(oracle.price("ETH").price, -2_000);
oracle.set_offline(true);
assert!(matches!(
oracle.client().try_get_price(&Symbol::new(&env, "ETH")),
Err(Ok(OracleError::OracleOffline))
));
assert_eq!(oracle.price("ETH").price, -2_000); // peek ignores offline
}
Dependent consumer contracts
A consumer that wants to react to an oracle failure must call try_get_price,
not get_price: the plain client method panics on a contract error, which
aborts the whole invocation and leaves the caller no error to map. The fixture’s
tests register a consumer that forwards OracleError, then assert its try_*
result for every failure state:
#![allow(unused)]
fn main() {
use soroban_sdk::{contract, contractimpl, Address, Env, Symbol};
use soroban_testkit_fixtures::{
AssetPrice, MockPriceOracleClient, OracleError,
};
#[contract]
pub struct FundingCheck;
#[contractimpl]
impl FundingCheck {
pub fn price(
env: Env,
oracle: Address,
asset: Symbol,
) -> Result<AssetPrice, OracleError> {
match MockPriceOracleClient::new(&env, &oracle).try_get_price(&asset) {
Ok(Ok(quote)) => Ok(quote),
Err(Ok(error)) => Err(error),
_ => panic!("unexpected oracle failure"),
}
}
}
// After registering FundingCheck:
// assert!(matches!(
// check.try_price(oracle.address(), &asset),
// Err(Ok(OracleError::StalePrice))
// ));
}
Because the consumer returns Result<AssetPrice, OracleError>, its own
generated try_price has the same nested shape as the oracle’s. That is what
makes the assertions read consistently for StalePrice, InvalidPrice and
OracleOffline.
Use harness.price(asset) and peek_price to arrange or assert a broken feed. Use get_price only in the code path whose reaction to that broken feed is under test.
client() returns a typed MockPriceOracleClient bound to the harness’s
environment and address; address() and env() expose the same pair for
registering consumers or advancing the ledger directly.
SEP-40 compatibility view
The same contract also exposes the SEP-40 oracle consumer shape: base,
assets, decimals, resolution, price, prices, and lastprice. The mock
quotes everything in Sep40Asset::Other(Symbol("USD")); Sep40Asset::Stellar
is accepted by the interface but has no seeded feed. resolution reports the
configured heartbeat, and decimals reports a quote-wide precision that starts
at 7 and can be changed with set_decimals. Feed-specific scales remain on
AssetPrice.decimals.
Every set_price appends a Sep40PriceData { price, timestamp } record to a
bounded per-asset history, so prices(asset, n) returns the last n records
and price(asset, timestamp) finds a record published at that exact timestamp.
SEP-40 methods never enforce offline, staleness, or sign checks; use
get_price when the consumer’s reaction to a broken feed is what you are
testing.
#![allow(unused)]
fn main() {
use soroban_testkit_fixtures::{OracleHarness, Sep40Asset, Sep40PriceData};
let asset = Sep40Asset::Other(Symbol::new(&env, "BTC"));
let latest: Option<Sep40PriceData> = oracle.client().lastprice(&asset);
assert_eq!(latest.unwrap().price, 6_400_000);
assert_eq!(oracle.client().resolution(), 3_600);
}
Extending fixtures
Compose TestContext into project-specific fixtures so setup is written once per repo:
#![allow(unused)]
fn main() {
struct TokenTestEnv {
ctx: TestContext,
token_id: BytesN<32>,
}
impl TokenTestEnv {
fn setup() -> Self {
let ctx = TestContextBuilder::new().with_users(3).build();
let token_id = ctx.env.register(TokenContract, ());
Self { ctx, token_id }
}
}
}
Behind testutils
Address::generate is a test-only SDK API. SDK v28 requires use soroban_sdk::testutils::Address as _; plus the testutils feature.
Seeded state
Registering contracts and seeding their state from the builder would turn the setup above into one line.
Multi-contract protocol registry and upgrade proxy pattern (ProtocolRegistryHarness)
Production DeFi protocols typically use an address registry contract (service locator pattern) and upgradeable proxy contracts to route calls to active implementation contracts. Testing dynamic service discovery, protocol-wide dependency injection, and live address swaps requires orchestrating multiple interconnected contracts.
[ProtocolRegistryHarness] maintains a directory of registered service contracts (Router, Treasury, Oracle, Vault, and custom roles), deploys on-chain registry contracts, simulates protocol upgrades by swapping service addresses, and validates that consumer contracts seamlessly resolve updated implementations.
Coordinating multi-contract protocol topologies
Initialize a harness around an [Env], register protocol services, and attach dependent consumer contracts:
#![allow(unused)]
fn main() {
use soroban_sdk::{testutils::Address as _, Address, Env};
use soroban_testkit_fixtures::{ProtocolRegistryHarness, ServiceRole};
let env = Env::default();
env.mock_all_auths();
let mut harness = ProtocolRegistryHarness::new(&env);
// Deploy and register core protocol services
let router_addr = Address::generate(&env);
let treasury_addr = Address::generate(&env);
let oracle_v1 = Address::generate(&env);
let vault_addr = Address::generate(&env);
harness.register_service(ServiceRole::Router, &router_addr).unwrap();
harness.register_service(ServiceRole::Treasury, &treasury_addr).unwrap();
harness.register_service(ServiceRole::Oracle, &oracle_v1).unwrap();
harness.register_service(ServiceRole::Vault, &vault_addr).unwrap();
// Register a consumer contract with its declared dependencies
let pool_addr = Address::generate(&env);
harness.register_consumer("LiquidityPool", &pool_addr, [ServiceRole::Oracle, ServiceRole::Vault]).unwrap();
}
Simulating protocol upgrades
Simulate a protocol upgrade by swapping a service address in the registry. The harness validates monotonic version increments, records before-and-after audit logs, and updates the on-chain registry contract:
#![allow(unused)]
fn main() {
let oracle_v2 = Address::generate(&env);
// Upgrade Oracle from v1 to v2:
let upgrade_record = harness.upgrade_service(ServiceRole::Oracle, &oracle_v2).unwrap();
assert_eq!(upgrade_record.from_version, 1);
assert_eq!(upgrade_record.to_version, 2);
// Consumers querying the registry dynamically resolve the new implementation
assert_eq!(harness.resolve(&ServiceRole::Oracle).unwrap(), oracle_v2);
// Verify all dependent consumer contracts resolve updated services
harness.verify_consumer_resolution("LiquidityPool", &ServiceRole::Oracle, &oracle_v2).unwrap();
}
Upgrade proxy pattern
Deploy an UpgradeProxyContract bound to a specific service role. The proxy dynamically resolves its implementation address via the on-chain registry, allowing calls to route to the latest implementation without consumer reconfiguration:
#![allow(unused)]
fn main() {
// Deploy an upgrade proxy pointing to the Treasury service role
let proxy_address = harness.deploy_proxy(ServiceRole::Treasury);
// Proxy dynamically resolves Treasury v1
let active_impl = harness.resolve_from_proxy(&proxy_address);
assert_eq!(active_impl, treasury_addr);
// Upgrade treasury address in registry:
let treasury_v2 = Address::generate(&env);
harness.upgrade_service(ServiceRole::Treasury, &treasury_v2).unwrap();
// Proxy immediately and seamlessly resolves Treasury v2
assert_eq!(harness.resolve_from_proxy(&proxy_address), treasury_v2);
}
Topology diagram generation
Visualizing interconnected multi-contract topologies helps verify protocol dependencies and architecture in tests and documentation:
#![allow(unused)]
fn main() {
// Generate Mermaid diagram for PRs or Markdown documentation:
println!("{}", harness.to_mermaid());
// Or format a clean ASCII topology summary:
println!("{}", harness.render_topology());
}
flowchart TD
Registry["Registry"]
subgraph Services["Protocol Services"]
ROUTER["Router (v1)"]
TREASURY["Treasury (v2)"]
ORACLE["Oracle (v2)"]
VAULT["Vault (v1)"]
end
Registry --> ROUTER
Registry --> TREASURY
Registry --> ORACLE
Registry --> VAULT
subgraph Consumers["Dependent Consumers"]
C_0["LiquidityPool"]
end
C_0 -. resolves .-> ORACLE
C_0 -. resolves .-> VAULT
Declared dependency topology validation (TopologyValidator)
For multi-contract protocols, TopologyValidator lets a test declare the
expected dependency graph and then scan each deployed contract’s instance
storage for Address references. It flags three failure modes:
- Uninitialized link — a declared dependency that no contract stores yet.
- Dangling reference — a stored address that points at a contract that was never registered.
- Inactive contract — a registered contract whose address is not deployed.
#![allow(unused)]
fn main() {
use soroban_sdk::{testutils::Address as _, Address, Env};
use soroban_testkit_fixtures::TopologyValidator;
let env = Env::default();
env.mock_all_auths();
let mut topology = TopologyValidator::new(&env);
let token = Address::generate(&env);
let oracle = env.register_contract(None, ...); // deployed contract id
let pool = env.register_contract(None, ...);
topology.register_contract("token", &token);
topology.register_contract("oracle", &oracle);
topology.register_contract("pool", &pool);
topology.require_link("pool", "token");
topology.require_link("pool", "oracle");
topology.assert_valid(); // panics with the full report on any violation
}
TopologyValidator::validate returns a TopologyReport whose is_valid,
violations, to_mermaid, and render_topology helpers support non-fatal
assertions and diagram generation for documentation.
Deterministic deployer and address prediction (DeterministicDeployer)
Factory contracts deploy children with env.deployer().with_address(..., salt)
or with_current_contract(salt). DeterministicDeployer computes the
predicted contract address before deployment and can deploy+assert the address
matches.
#![allow(unused)]
fn main() {
use soroban_sdk::{BytesN, Env};
use soroban_testkit_fixtures::{DeterministicDeployer, SaltHierarchy};
let env = Env::default();
let wasm_hash = env.upload(MyContract);
let deployer = env.current_contract_address();
let salt = BytesN::from_array(&env, &[1u8; 32]);
let predicted = DeterministicDeployer::predicted_address(&env, &deployer, &salt);
let deployed = DeterministicDeployer::deploy_checked(&env, &deployer, &salt, &wasm_hash);
assert_eq!(predicted, deployed);
let salts = SaltHierarchy::from_namespace(7);
let child_salt = salts.derive_bytesn(&env, &[0, 1]);
let child = DeterministicDeployer::deploy(&env, &deployer, &child_salt, &wasm_hash);
}
SaltHierarchy provides deterministic, path-sensitive salt derivation for test
suites that deploy multiple related contracts.
Failure injection for mock dependencies (FailureInjector)
A resilient contract has to survive a dependency that fails: an oracle out of budget, a vault whose storage expired, a token that traps. FailureInjector decides, per contract and per function, when a mock dependency fails and with which error, without writing a separate crashing contract for each case.
The injection point is one call at the top of each mock function:
#![allow(unused)]
fn main() {
use soroban_testkit_fixtures::{failure_point, FailureInjector, InjectedFailure};
#[contractimpl]
impl MockOracle {
pub fn get_price(env: Env) -> i128 {
failure_point(&env, "get_price");
100
}
}
let injector = FailureInjector::attach(&env);
injector.fail_function(&oracle_id, "get_price", InjectedFailure::BudgetExceeded); // permanent crash
assert_eq!(dex.try_quote(&oracle_id, &2), Err(Ok(DexError::OracleUnavailable)));
injector.fail_times(&oracle_id, "get_price", InjectedFailure::StorageNotFound, 2); // temporary outage
injector.fail_on_call(&oracle_id, "get_price", InjectedFailure::InternalError, 3); // only call 3 fails
injector.clear(); // normal execution again (also happens on drop)
}
| Failure | Raised as |
|---|---|
OutOfMemory | Error(WasmVm, ExceededLimit) |
BudgetExceeded | Error(Budget, ExceededLimit) (the out-of-gas case) |
StorageNotFound | a genuine host trap: a TTL extension on a missing entry, as an archived or never-written entry would cause |
InternalError | Error(Context, InternalError) |
Contract(code) | a contract error with that code |
What the caller sees. A Contract(code) failure reaches a try_* caller unchanged. Every host-level failure reaches it as Error(Context, InvalidAction), because the host never forwards a callee’s host error verbatim. That is also exactly what a caller sees when a real dependency traps. Without a try_* call, the failure aborts the caller.
One difference from a live network. On a network, exhausting the CPU or memory budget aborts the whole transaction and no caller can catch it. The injected BudgetExceeded and OutOfMemory fail only the dependency’s invocation, modelling a dependency that runs out and reports it, so the caller’s fallback path is testable. To test transaction-wide exhaustion, run the call under real limits (NetworkProfile, or env.cost_estimate().budget().reset_limits).
Rules are scoped to the test thread and to the injector that installed them, so one test cannot leak a failure into the next. injector.calls(&id, "fn") reports how many calls the injection point has seen.
Declarative mock contracts
Unit tests rarely want to hand-write a stand-in for every dependency. Declare the interface once with #[mock_contract], then give each test its own behaviour:
#![allow(unused)]
fn main() {
use soroban_sdk::{contract, contractimpl, Address, Env};
use soroban_testkit_fixtures::{mock_contract, MockContractBuilder};
#[contract]
pub struct RateOracle;
#[mock_contract]
#[contractimpl]
impl RateOracle {
pub fn get_rate(_env: Env, _asset: Address) -> i128 { unimplemented!() }
}
let oracle = MockContractBuilder::<RateOracle>::new(&env)
.expect_call("get_rate", |_env, _args| 1_500i128)
.times(2)
.build();
// the contract under test sees a normal contract address
consumer_client.trade(&oracle.address(), &usdc);
oracle.assert_expectations();
}
#[mock_contract] replaces every function body with a dispatcher, so the placeholder bodies are never compiled; the attribute must sit directly above #[contractimpl].
| Builder call | Meaning |
|---|---|
expect_call(name, handler) | return whatever handler(env, args) produces |
expect_panic(name, message) | fail the invocation with message |
.times(n) | exactly n calls (the default is exactly once) |
.at_least(n) | n or more calls |
.never() | the function must not be called |
Arguments arrive encoded as Vals in declaration order; mock::arg::<T>(env, args, i) decodes one and panics with a diagnostic if it is missing or has the wrong type. Expectations are verified by assert_expectations() and again when the mock is dropped, so a forgotten assertion still fails the test.
Why the interface is declared. A Soroban host resolves an invocation to an exported function symbol before any contract code runs, and no entry point receives the function name as a value. The SDK therefore cannot expose a contract whose exported functions are decided at runtime. #[mock_contract] generates a real contract at compile time and dispatches inside it, which keeps the address usable by typed clients, including from the contract under test.
Mocks live in a thread-local registry keyed by contract address, which suits #[test] functions; they are not shared between threads.
soroban-testkit-generators
Soroban-aware property-testing strategies for proptest, so generated inputs respect the ranges real contracts accept.
Available strategies
| Strategy | Type | Range |
|---|---|---|
token_amount() | i128 | 0 to 1e15 |
stroop_amount() | i128 | 0 to MAX_TOKEN_SUPPLY (1e9 units), weighted towards decimal boundaries |
extreme_stroop_amount() | i128 | stroops plus i64::MAX, u64::MAX and i128::MAX |
stroop_boundaries() | Vec<i128> | the amounts a fee rounds wrongly around: 0, 1 stroop, a unit ± 1, ten units ± 1, the cap |
basis_points() | u32 | 0 to 10,000, weighted towards 0, 1, 30, 50, 100, 9,999 and 10,000 |
exchange_rate_ratio() | (i128, i128) | numerator and denominator in 1 to 1e6, so the supply cap times either leg fits in i128 |
priced_stroop_amount() | (i128, i128, i128) | (amount, numerator, denominator) — an amount with the rate that prices it |
split_fee(amount, bps) | (i128, i128) | reference (net, fee) split, rounding the fee up |
ledger_sequence() | u32 | 1 to 10,000,000 |
timestamp() | u64 | Sep 2020 to May 2033 |
address() | AddressBytes | an account or contract address |
account_address() | AddressBytes | an ed25519 account (G...) |
contract_address() | AddressBytes | a contract id (C...) |
address_of_type(kind) | AddressBytes | the format you ask for |
sc_address() | ScAddress | a ScAddress::Account, ScAddress::Contract, or ScAddress::MuxedAccount |
sc_address_account() | ScAddress | a ScAddress::Account (G...) address |
sc_address_contract() | ScAddress | a ScAddress::Contract (C...) address |
sc_address_muxed() | ScAddress | a ScAddress::MuxedAccount (M...) address |
sc_address_collection() | Vec<ScAddress> | a mixed vector holding both account and contract addresses |
fuzzed_invocation_args(env, typed, max_rogue) | Vec<Val> | valid arguments mixed with integers, booleans, symbols, errors, and address objects |
contract_error_code() | u32 | any application-defined contract error code, shrinking towards zero |
host_error() | Error | an SDK error from every standard category, including arbitrary contract codes |
error_with_type(kind) | Error | an SDK error restricted to the requested ScErrorType |
host_error_code_coverage() | HostError | all 10 categories × all 10 codes |
host_error_type() | ScErrorType | every host category |
host_error_code() | ScErrorCode | every host code |
host_error_of_type(kind) | HostError | the codes of one category |
soroban_tuple_2(a, b) | (A, B) | one component from each strategy |
soroban_tuple_3(a, b, c) | (A, B, C) | one component from each strategy |
byte_array_32() | [u8; 32] | any 32 bytes — hashes, keys, seeds |
byte_array_64() | [u8; 64] | any 64 bytes — ed25519 signatures |
byte_array::<N>() | [u8; N] | any N bytes |
ed25519_signature_pair() | Ed25519SignaturePair | valid ed25519 public key, message digest, and signature |
secp256k1_signature_pair() | Secp256k1SignaturePair | valid secp256k1 public key, hash, signature, and recovery id |
malleated_signature(sig) | [u8; 64] | corrupted signature payload guaranteed to differ |
contract_executable_wasm_hash() | [u8; 32] | any 32-byte WASM bytecode hash |
contract_executable() | ContractExecutable | Wasm, StellarAsset, or ExternalRef variants |
deployer_salt() | [u8; 32] | 32-byte salt for deterministic deployment |
storage_tier() | StorageTier | Instance, Persistent, or Temporary (shrinks to Temporary) |
storage_tier_with_ttl(current, min, max) | StorageTierWithTtl | a tier paired with durability and live/expired TTL properties |
mixed_tier_allocations(keys, size) | MixedTierAllocation<K> | mixed key allocations across instance, persistent, and temporary tiers |
mixed_tier_allocations_with_ttl(keys, current, min, max, size) | MixedTierTtlAllocation<K> | mixed key allocations paired with TTLs per tier |
entry_ttl(current, min_threshold, max_ttl) | EntryTtl | a live entry whose TTL is in min_threshold..=max_ttl |
expired_ttl(current) | EntryTtl | an entry that expired before current |
ttl_extension_delta() | u32 | 1 to MAINNET_MAX_ENTRY_TTL (3,110,400) ledgers |
ttl_extension_delta_up_to(max) | u32 | 1 to max ledgers |
soroban_duration(env, min_secs, max_secs) | Duration | a host duration in min_secs..=max_secs seconds |
soroban_timepoint(env, min_timestamp, max_timestamp) | Timepoint | a host timepoint in min_timestamp..=max_timestamp unix seconds |
ledger_sequence_interval() | (u32, u32) | (start, end) with start <= end, both in 1..=10,000,000 |
contract_cost_model() | ContractCostModel | valid host cost schedule covering all ContractCostType variants, shrinking to baseline |
contract_cost_model_with_multipliers(cpu, mem) | ContractCostModel | cost schedule with custom CPU and Memory fee multipliers (percentage) |
contract_cost_model_with_config(config) | ContractCostModel | cost schedule with per-dimension and per-cost-type multiplier overrides |
soroban_symbol(env) | Symbol | valid alphanumeric and underscore symbol (1 to 32 chars) |
sorobans_symbol_strategy(env, min, max) | Symbol | valid symbol constrained to custom length range min..=max |
soroban_identifier_symbol(env) | Symbol | standard naming convention identifier starting with letter |
invalid_symbol_strategy() | String | strings with rejected/invalid characters (spaces, special symbols, etc.) |
xdr_symbol(env, max_len) | Symbol | [a-zA-Z0-9_], at most max_len (≤ 32) characters |
xdr_string(env, max_len) | String | printable ASCII, at most max_len bytes |
xdr_bytes(env, max_len) | Bytes | at most max_len bytes |
xdr_vec(env, element, max_len) | Vec<T> | at most max_len elements drawn from any XDR strategy |
xdr_map(env, key, value, max_len) | Map<K, V> | at most max_len entries; duplicate keys collapse |
xdr_value(bounds) | XdrValue | an env-free value tree inside an XdrBounds |
xdr_val(env, bounds) | Val | a host value built from an xdr_value tree |
Money: stroops, basis points and rates
financial spends its cases where integer money goes wrong instead of spreading
them evenly over i128. Two thirds of the amounts come from
stroop_boundaries() — zero, one stroop, one stroop either side of a whole unit,
a unit either side of ten, and the supply cap — and the rest is spread over
0..=MAX_TOKEN_SUPPLY (1e9 units at seven decimals). Rate ratios stay in
1..=1e6 on both legs, so MAX_TOKEN_SUPPLY * numerator is always representable:
a failed case means the contract overflowed, not the strategy.
#![allow(unused)]
fn main() {
use proptest::prelude::*;
use soroban_testkit_generators::financial::{basis_points, stroop_amount};
use soroban_testkit_generators::{assert_balances_never_negative, assert_fee_rounding_favors_protocol};
proptest! {
#[test]
fn a_swap_keeps_every_stroop(amount in stroop_amount(), fee_bps in basis_points()) {
let (net, fee) = split(amount, fee_bps);
assert_fee_rounding_favors_protocol!(gross = amount, fee_bps = fee_bps, net = net, fee = fee);
assert_balances_never_negative!(net = net, fee = fee);
}
}
}
assert_fee_rounding_favors_protocol! holds a split to the three things a fee
bug breaks: the legs add back up to the gross, neither is negative, and the fee
is no more than one stroop away from gross * bps / 10_000 in either direction —
the loosest two honest divisions can be. assert_balances_never_negative! takes
as many name = value pairs as you have legs and names the one that went below
zero.
Usage with proptest
#![allow(unused)]
fn main() {
use proptest::prelude::*;
use soroban_testkit_generators::strategies;
proptest! {
#[test]
fn transfer_preserves_total_supply(
amount in strategies::token_amount(),
seq in strategies::ledger_sequence(),
) {
// amount is always a valid token balance
// seq is always a realistic ledger sequence number
}
}
}
Addresses
Both Soroban address formats are 32 opaque bytes, so every address strategy
returns an AddressBytes that carries those bytes and the format they were
generated as. as_bytes() borrows the raw value, into_bytes() hands over
ownership of the [u8; 32], address_type() reads the format tag back, and
to_address(&env) turns it into the Address a contract call expects.
ScAddress::from(address_bytes) gives the XDR form instead, which is what you
want when comparing against a ledger value rather than calling a contract.
#![allow(unused)]
fn main() {
use proptest::prelude::*;
use soroban_sdk::{Address, Env};
use soroban_testkit_generators::strategies::{self, AddressType};
proptest! {
#[test]
fn transfer_reaches_the_recipient(recipient in strategies::account_address()) {
let env = Env::default();
let recipient: Address = recipient.to_address(&env);
// recipient is always a valid ed25519 account address
}
}
}
Filter by format with address_of_type, or use the two named shortcuts when a
test only cares about one side of a transfer:
#![allow(unused)]
fn main() {
use proptest::prelude::*;
use soroban_testkit_generators::strategies::{self, AddressType};
proptest! {
#[test]
fn a_contract_never_receives_a_signature(
contract in strategies::address_of_type(AddressType::Contract),
) {
assert_eq!(contract.address_type(), AddressType::Contract);
assert_eq!(contract.as_bytes().len(), 32);
}
}
}
Each generated address carries a process-wide nonce, so two calls to address() in the same test run never produce the same bytes — even if their random prefixes collide. The trade-off is that values depend on generation order, so a failing case should be judged by the bytes proptest prints rather than by replaying a random seed alone.
Strkeys (account, contract, corrupted)
Soroban strkeys are 56-character base32 strings carrying a version byte and a
CRC-16 checksum. The generators module provides strategies that produce valid
account (G...) and contract (C...) strkeys, plus corrupted variants that
flip a checksum bit:
#![allow(unused)]
fn main() {
use proptest::prelude::*;
use soroban_testkit_generators::strategies::{
account_strkey, contract_strkey, corrupted_strkey, Strkey,
};
proptest! {
#[test]
fn round_trips(s in account_strkey()) {
let decoded = Strkey::decode(&s).unwrap();
assert_eq!(decoded.encoded(), s);
}
#[test]
fn corrupted_is_rejected(s in corrupted_strkey()) {
assert!(Strkey::decode(&s).is_err());
}
}
}
Strkey exposes new, zero, encoded, decode, to_address, and
StrkeyKind/StrkeyError for direct parsing tests. Valid inputs shrink toward
the canonical all-zero strkey; corrupted inputs shrink toward a single-bit
checksum flip.
ScAddress (account, contract, and muxed addresses)
address() and friends produce host AddressBytes, which is convenient for
contract calls but hides the XDR shape. When a test compares against ledger
values, decodes strkeys, or checks low-level conversion code, generate the raw
ScAddress instead:
sc_address_account()—ScAddress::Account, an Ed25519 account id (G...).sc_address_contract()—ScAddress::Contract, a 32-byte contract id hash (C...).sc_address_muxed()—ScAddress::MuxedAccount, an Ed25519 key plus au64id, the strkeyM...form.sc_address()— one of the three variants.sc_address_collection()— aVec<ScAddress>that always holds at least one account and one contract address, plus up to six more entries of either variant.
#![allow(unused)]
fn main() {
use proptest::prelude::*;
use soroban_sdk::xdr::ScAddress;
use soroban_testkit_generators::strategies::{sc_address, sc_address_collection};
proptest! {
#[test]
fn every_variant_round_trips_through_its_strkey(address in sc_address()) {
let encoded = address.to_string();
let decoded: ScAddress = encoded.parse().expect("generated strkey must decode");
assert_eq!(decoded, address);
}
#[test]
fn mixed_collections_cover_both_xdr_formats(addresses in sc_address_collection()) {
assert!(addresses.iter().any(|a| matches!(a, ScAddress::Account(_))));
assert!(addresses.iter().any(|a| matches!(a, ScAddress::Contract(_))));
}
}
}
Account and contract values convert both ways with the host type, which is how you move from generated XDR to a call argument:
#![allow(unused)]
fn main() {
use soroban_sdk::{Address, Env, TryFromVal};
use soroban_sdk::xdr::ScAddress;
use soroban_testkit_generators::sc_address_account;
let env = Env::default();
// ...inside a property, with `sc: ScAddress` from `sc_address_account()`...
let address = Address::try_from_val(&env, &sc).unwrap();
assert_eq!(ScAddress::from(&address), sc);
}
Muxed accounts have no host Address counterpart, so encode them to their
strkey when a test needs to pass them through a textual interface.
All of these strategies shrink toward zeroed payloads: the account key and the
contract hash become [0u8; 32], and the muxed id becomes 0. There is no
uniqueness nonce here (unlike address()), so the shrink target really is the
canonical all-zero value.
Generating strategies for nested contract structs
The prop_contract_struct! macro synthesises a proptest strategy plus a
builder function for a user #[contracttype] struct. You provide one strategy
per field; the macro maps the tuple of field values into the struct, so each
field keeps its own shrink tree and shrinking recurses through nested members.
#![allow(unused)]
fn main() {
use proptest::prelude::*;
use soroban_sdk::{contracttype, Env};
use soroban_testkit_generators::{prop_contract_struct, strategies};
#[contracttype]
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Limit {
pub amount: i128,
pub enabled: bool,
}
#[contracttype]
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Order {
pub limit: Limit,
pub backup: Option<i128>,
pub tags: soroban_sdk::Vec<u32>,
}
prop_contract_struct! {
pub fn limit_strategy() -> Limit {
amount: strategies::token_amount(),
enabled: any::<bool>(),
}
}
prop_contract_struct! {
pub fn order_strategy(env: Env) -> Order {
limit: limit_strategy(),
backup: prop::option::of(strategies::token_amount()),
tags: strategies::soroban_vec(0u32..=100, 4, env),
}
}
}
The generated function accepts whatever parameters the invocation declares and
forwards them into the field strategy expressions, which is how
strategies::soroban_vec receives its Env. Attributes, doc comments, and
visibility are copied onto the generated function.
Child structs are ordinary strategies, so they compose with prop::option::of,
prop::collection::vec, or prop::collection::hash_map. Contract enums work
the same way: build a prop_oneof! strategy for the enum and use it as the
field strategy.
The macro builds a proptest tuple, which supports up to 12 fields per struct.
Group wider structs into a child #[contracttype] struct to stay inside that
limit.
Fuzzing invocation argument types
fuzzed_invocation_args takes the host environment, a vector of valid
arguments for the target function, and a maximum number of rogue values. It
returns actual host Vals, so object handles belong to the same environment
as the contract client. Primitive values shrink toward zero and false, while
the argument list shrinks toward the original typed arguments.
#![allow(unused)]
fn main() {
use soroban_sdk::{Env, IntoVal};
use soroban_testkit_generators::fuzzed_invocation_args;
let env = Env::default();
let valid = vec![7u32.into_val(&env)];
let args = fuzzed_invocation_args(&env, valid, 4);
}
Use the generated values with a contract entry point that accepts Val (or
through the host’s dynamic invocation API) to ensure dispatch and validation
reject unexpected types before business logic runs. Generated rogue values
cover signed/unsigned integers, booleans, symbols, contract errors, and
address object handles.
Host error discriminants
Testkit also generates the failures themselves. Soroban reports a host error as
a category (ScErrorType)
paired with a code (ScErrorCode),
ten of each, so the whole domain is one hundred pairs. host_error_code_coverage()
draws from all of them, which is what lets a property test drive an
error-recovery block with failures nobody typed by hand:
#![allow(unused)]
fn main() {
use proptest::prelude::*;
use soroban_sdk::xdr::ScErrorType;
use soroban_testkit_generators::errors::host_error_code_coverage;
enum Recovery {
Retry,
Stop,
}
fn recover(error: &soroban_sdk::Error) -> Recovery {
// A total classification: every category answers, none panics.
if error.is_type(ScErrorType::Budget) || error.is_type(ScErrorType::Storage) {
Recovery::Retry
} else {
Recovery::Stop
}
}
proptest! {
#[test]
fn recovery_handles_every_host_failure(error in host_error_code_coverage()) {
let decision = recover(&error.as_error());
if matches!(error.error_type(), ScErrorType::Budget | ScErrorType::Storage) {
assert!(matches!(decision, Recovery::Retry));
} else {
assert!(matches!(decision, Recovery::Stop));
}
}
}
}
HostError carries the pair and answers what a test usually needs to name it:
error_type() and code() return the discriminants, category() and
code_name() return "storage" and "MissingValue", label() renders
storage/3, is_contract_error() separates an application code from a host
failure, and as_error() produces the Error
a contract call returns. host_error_of_type(kind) narrows a run to one branch
when a category needs its own treatment, and all_host_errors() is the full
hundred in table order for a deterministic sweep.
Use host_error() when the code under test consumes the SDK error directly;
error_with_type(kind) keeps generated errors within one category, including
application-defined contract codes when kind is ScErrorType::Contract.
contract_error_code() produces the entire valid u32 range and shrinks
failing values towards zero. Generated SDK errors convert to the corresponding
XDR ScVal::Error
without losing their category or code:
#![allow(unused)]
fn main() {
use proptest::prelude::*;
use soroban_sdk::xdr::{ScErrorType, ScVal};
use soroban_testkit_core::error::DecodedError;
use soroban_testkit_generators::{error_with_type, host_error};
proptest! {
#[test]
fn error_handler_never_panics(error in host_error()) {
let decoded = DecodedError::from_error(&error);
assert!(!decoded.category.is_empty());
let xdr_error = ScVal::try_from(error).expect("generated errors are valid XDR");
assert!(matches!(xdr_error, ScVal::Error(_)));
}
#[test]
fn storage_error_handler_never_panics(
error in error_with_type(ScErrorType::Storage),
) {
// The strategy only emits Storage errors.
assert!(error.is_type(ScErrorType::Storage));
}
}
}
host_error_code_coverage() uses two bounded integers — one position in the category table, one in the code table — rather than a prop_oneof! over the pairs. proptest shrinks integers towards zero, and both tables are in XDR discriminant order, so a failing case simplifies to Contract/ArithDomain (contract/0). host_error() follows that category order and contract codes shrink towards zero too.
Tuples and fixed-size arrays
Contract functions often take a composite argument — an (Address, i128)
allowance grant, a BytesN<32> hash, a BytesN<64> signature. The tuples
module names those shapes so a test does not rebuild them by hand, and every
strategy is re-exported from the crate root:
#![allow(unused)]
fn main() {
use proptest::prelude::*;
use soroban_sdk::{BytesN, Env};
use soroban_testkit_generators::strategies::{account_address, token_amount};
use soroban_testkit_generators::{byte_array_32, byte_array_64, soroban_tuple_2};
proptest! {
#[test]
fn test_allowance_pair(
(owner, spender) in soroban_tuple_2(account_address(), account_address()),
amount in token_amount(),
) {
let env = Env::default();
let (owner, spender) = (owner.to_address(&env), spender.to_address(&env));
client.approve(&owner, &spender, &amount);
}
#[test]
fn verify_rejects_a_forged_signature(
digest in byte_array_32(),
signature in byte_array_64(),
) {
let env = Env::default();
let digest = BytesN::from_array(&env, &digest);
let signature = BytesN::from_array(&env, &signature);
# Host-allocated collection generators
Soroban contracts work with host-allocated collection types (`Map`, `Vec`, `Bytes`, `String`) that live in the contract's environment. The `strategies` module provides generators that construct these types directly in the test's `Env`, with configurable size bounds and proper shrinking.
## Map generator
```rust
use proptest::prelude::*;
use soroban_sdk::{Env, Map};
use soroban_testkit_generators::{soroban_map, token_amount};
proptest! {
#[test]
fn test_batch_process(
ref map in soroban_map(token_amount(), token_amount(), 20, Env::default())
) {
// map is a soroban_sdk::Map<i128, i128> with at most 20 entries
prop_assert!(map.len() <= 20);
}
}
}
Signature:
#![allow(unused)]
fn main() {
soroban_map<K, V, KS, VS>(key_strategy: KS, value_strategy: VS, max_entries: u32, env: Env)
}
key_strategy/value_strategy: proptest strategies for keys and valuesmax_entries: maximum number of entries (shrinking reduces entry count)env: the Soroban environment to allocate the map in
Vec generator
#![allow(unused)]
fn main() {
use proptest::prelude::*;
use soroban_sdk::{Env, Vec};
use soroban_testkit_generators::{soroban_vec, token_amount};
proptest! {
#[test]
fn test_batch_process(
ref vec in soroban_vec(token_amount(), 50, Env::default())
) {
// vec is a soroban_sdk::Vec<i128> with at most 50 elements
prop_assert!(vec.len() <= 50);
}
}
}
Signature:
#![allow(unused)]
fn main() {
soroban_vec<T, S>(elem_strategy: S, max_entries: u32, env: Env)
}
Bytes generator
#![allow(unused)]
fn main() {
use proptest::prelude::*;
use soroban_sdk::{Bytes, Env};
use soroban_testkit_generators::soroban_bytes;
proptest! {
#[test]
fn test_bytes_processing(
ref bytes in soroban_bytes(256, Env::default())
) {
// bytes is a soroban_sdk::Bytes with at most 256 bytes
prop_assert!(bytes.len() <= 256);
}
}
}
Signature:
#![allow(unused)]
fn main() {
soroban_bytes(max_len: u32, env: Env)
}
String generator
#![allow(unused)]
fn main() {
use proptest::prelude::*;
use soroban_sdk::{String, Env};
use soroban_testkit_generators::{soroban_string, soroban_ascii_string};
proptest! {
#[test]
fn test_string_processing(
ref s in soroban_string(128, Env::default())
) {
// s is a soroban_sdk::String with at most 128 bytes
prop_assert!(s.len() <= 128);
}
#[test]
fn test_ascii_string(
ref s in soroban_ascii_string(64, Env::default())
) {
// s is a soroban_sdk::String with only printable ASCII, up to 64 bytes
prop_assert!(s.len() <= 64);
}
}
}
Signatures:
#![allow(unused)]
fn main() {
soroban_string(max_len: u32, env: Env) -> Strategy<Value = soroban_sdk::String>
soroban_ascii_string(max_len: u32, env: Env) -> Strategy<Value = soroban_sdk::String>
}
soroban_string: generates printable ASCII strings (valid UTF-8)soroban_ascii_string: generates only printable ASCII characters (subset ofsoroban_string)
All collection generators:
- Respect the configured size bounds
- Shrink towards empty collections (reducing entries/elements/bytes)
- Construct the collection directly in the provided
Env - Work with any key/value/element types that implement
IntoVal<Env, Val>andTryFromVal<Env, Val>
Stateful property-based testing with state machines
The state_machine module provides a Soroban-aware state machine harness built on proptest::state_machine. It enables testing contracts with sequences of transactions, verifying invariants after each step, and automatically shrinking failing sequences to the minimal reproducible call sequence.
Defining a state machine
#![allow(unused)]
fn main() {
use soroban_testkit_generators::state_machine::{SorobanStateMachine, SorobanStateMachineRunner, prop_state_machine_test};
use soroban_sdk::{Env, Address, testutils::Address as _};
#[derive(Clone, Debug, Default, PartialEq, Eq)]
struct TokenModel {
balances: std::collections::HashMap<Address, i128>,
total_supply: i128,
}
#[derive(Clone, Debug, PartialEq, Eq)]
enum TokenAction {
Mint { to: Address, amount: i128 },
Transfer { from: Address, to: Address, amount: i128 },
Burn { from: Address, amount: i128 },
}
struct TokenStateMachine {
env: Env,
}
impl SorobanStateMachine for TokenStateMachine {
type Action = TokenAction;
type Model = TokenModel;
type Context = TokenTestContext;
fn generate_action(&self, model: &Self::Model) -> BoxedStrategy<Self::Action> {
// Generate actions based on current model state
}
fn check_precondition(&self, model: &Self::Model, action: &Self::Action) -> bool {
// Validate action against model state
}
fn execute(&self, context: &mut Self::Context, action: &Self::Action) -> Result<(), String> {
// Execute action against real contract
}
fn apply_to_model(&self, model: &mut Self::Model, action: &Self::Action) {
// Update expected model state
}
fn check_invariant(&self, model: &Self::Model, context: &Self::Context) -> TestCaseResult {
// Verify invariant (e.g., total supply conservation)
}
fn initial_model(&self) -> Self::Model {
TokenModel::default()
}
fn create_context(&self) -> Self::Context {
TokenTestContext { ... }
}
}
}
Running the state machine
#![allow(unused)]
fn main() {
let machine = TokenStateMachine::new();
let runner = SorobanStateMachineRunner::new(machine).cases(100);
runner.run().unwrap();
}
Or use the simpler prop_state_machine_test function:
#![allow(unused)]
fn main() {
prop_state_machine_test(machine, 20, 100).unwrap();
}
Key features
- Automated invariant verification after each transition
- Precondition checking to filter invalid actions
- Automated shrinking of failing action sequences to the minimal failing sequence
- Sequence length ≥ 50 actions supported
- Integration example: Token balance conservation invariant verification
State machine for property testing
Every contract data entry has a live-until ledger — the last ledger it can
be read on — and rent bugs sit at the edges of that interval. The ttl module
generates the intervals themselves, in the SDK’s units: an entry’s TTL is
live_until_ledger - current_ledger, the number get_ttl(&key) reports and
extend_ttl(&key, threshold, extend_to) takes, so a TTL of 0 means
“readable this ledger, gone the next”.
#![allow(unused)]
fn main() {
use proptest::prelude::*;
use soroban_sdk::testutils::Ledger as _;
use soroban_testkit_generators::{entry_ttl, expired_ttl, ttl_extension_delta_up_to};
const RENEW_THRESHOLD: u32 = 17_280; // ~1 day
const RENEW_TO: u32 = 518_400; // ~30 days
proptest! {
#[test]
fn renewal_keeps_the_balance_alive(
entry in entry_ttl(1_000, 0, RENEW_TO),
gap in ttl_extension_delta_up_to(RENEW_THRESHOLD),
) {
// Put the entry on the ledger with exactly entry.ttl() remaining,
// then call the contract's renewal function.
client.renew();
let ttl = env.as_contract(&id, || env.storage().persistent().get_ttl(&KEY));
prop_assert!(ttl >= RENEW_THRESHOLD);
env.ledger().set_sequence_number(env.ledger().sequence() + gap);
prop_assert!(client.has_balance());
}
#[test]
fn an_expired_entry_is_never_read(entry in expired_ttl(50_000)) {
prop_assert!(!entry.is_live());
// ...
}
}
}
The values are plain Rust tuples and arrays, so once each component is a host
type the whole value converts with soroban_sdk::IntoVal — (Address, i128),
(Address, Address, i128) and BytesN<N> all cross a contract boundary
unchanged, which is what the module’s own tests check against a live contract.
soroban_tuple_3(a, b, c) is the three-component form, and byte_array::<N>()
covers any other length.
A failing tuple shrinks one component at a time while the others stay put, and a failing byte array shrinks every byte towards 0x00 independently. A signature check that only trips on the last byte therefore minimises to sixty-three zeros and the one byte that matters, rather than to an arbitrary-looking blob.
EntryTtl carries current_ledger and live_until_ledger, and answers the
questions a rent test asks of them: is_live(), ttl() (None once expired),
ledgers_since_expiry(), expires_at() (the first unreadable ledger) and
advanced_by(n) for the same entry observed n ledgers later.
max_ttl is the network ceiling — MAINNET_MAX_ENTRY_TTL on Mainnet, or the
value a test passed to env.ledger().set_max_entry_ttl(..) — and an interval
that would run past u32::MAX is clamped. entry_ttl refuses a
min_threshold above max_ttl, and expired_ttl refuses ledger 0, because
neither has a value to generate.
entry_ttl shrinks the TTL towards min_threshold, expired_ttl shrinks towards the entry that expired exactly one ledger ago, and ttl_extension_delta shrinks towards a single ledger. A renewal bug therefore minimises to the entry closest to dying, which is where off-by-one liveness checks fail. The module's own tests check these intervals against the host: what entry_ttl generates is what get_ttl reports, and a temporary entry is readable on live_until_ledger and gone on expires_at().
Durations, timepoints and ledger intervals
Vesting schedules, timelocks and renewal windows are all expressed in the
SDK’s two time types. Both are 64-bit unsigned second counts, but they are
environment-backed wrappers rather than u64: build one with
Duration::from_seconds(&env, ..) or Timepoint::from_unix(&env, ..) and read
it back with to_seconds() or to_unix(). The strategies therefore take an
Env, the same way fuzzed_invocation_args does, so the generated value
belongs to the environment under test.
#![allow(unused)]
fn main() {
use proptest::prelude::*;
use soroban_sdk::Env;
use soroban_testkit_generators::{ledger_sequence_interval, soroban_duration, soroban_timepoint};
proptest! {
#[test]
fn a_timelock_unlocks_after_its_start(
(start, duration) in {
let env = Env::default();
(
soroban_timepoint(&env, 1_600_000_000, 2_000_000_000),
soroban_duration(&env, 0, 100_000_000),
)
},
(first, last) in ledger_sequence_interval(),
) {
let unlock = start.to_unix() + duration.to_seconds(); // bounded ranges
prop_assert!(unlock >= start.to_unix());
prop_assert!(first <= last);
}
}
}
ledger_sequence_interval() returns the interval itself rather than a
Duration or Timepoint: both ends are ordinary u32 ledger numbers in the
same range ledger_sequence() draws from, ordered so start <= end always
holds.
soroban_duration and soroban_timepoint panic when the minimum is above the maximum, matching the crate's existing range strategies. The whole u64 range is accepted, including u64::MAX; the range strategy itself cannot overflow because it never adds to the generated value.
A failing duration minimises to min_secs, a failing timepoint to min_timestamp, and a failing interval to (1, 1) — or to (1, 2) when the bug needs a non-empty span. A vesting calculation that is wrong at the end of its schedule is therefore reported at the earliest boundary that reproduces it rather than at a random year.
Realistic ledger windows
A time-locked contract sees both env.ledger().sequence() and
env.ledger().timestamp(), and the two move together: Stellar closes a ledger
about every five seconds. realistic_ledger_window() generates a sequence span
and the timestamps at its two ends, correlated at that cadence with a bounded
clock skew:
#![allow(unused)]
fn main() {
use proptest::prelude::*;
use soroban_testkit_generators::{realistic_ledger_window, LedgerWindow};
proptest! {
#[test]
fn a_timelock_unlocks_inside_its_window(
window in realistic_ledger_window(),
lock_secs in 0u64..=600,
) {
let unlock_at = window.start_timestamp + lock_secs;
let unlock_ledger = window.sequence_at(unlock_at);
prop_assert!(window.timestamp_at(unlock_ledger) <= unlock_at);
}
}
}
LedgerWindow carries start_sequence, end_sequence, start_timestamp,
end_timestamp and the skew_secs beyond the nominal cadence, with helpers:
| Method | Meaning |
|---|---|
ledger_count() | Ledgers spanned; zero for an immediate window |
elapsed_secs() | Network time spanned, skew included |
is_immediate() | The window opens and closes on the same ledger |
timestamp_at(seq) | Clock at a ledger, interpolated across the window |
sequence_at(ts) | The ledger at or immediately before a timestamp |
Both ends are inclusive, so timestamp_at(start_sequence) is
start_timestamp and timestamp_at(end_sequence) is end_timestamp. Set them
on a test environment with
env.ledger().set_sequence_number(window.end_sequence) and
env.ledger().set_timestamp(window.end_timestamp) to run a contract at the far
end of the window.
skew_secs lies in 0..=ledger_count(), so the generated window averages
between five and six seconds per ledger; the end timestamp is never behind the
start. Start sequences come from the same range as ledger_sequence(), and the
span reaches MAX_LEDGER_WINDOW_LEDGERS (about six days of network time).
A failing window minimises to a zero-ledger, zero-second span with no skew, at the lowest start sequence and MIN_LEDGER_TIMESTAMP. A boundary check that is wrong only for a long lock therefore reports the smallest window that still reproduces it, rather than a random week of ledgers.
Event Fuzzing
EventFuzzHarness produces valid SDK v28 ContractEvent values and mutates
them to verify that event parsers reject malformed payloads cleanly.
#![allow(unused)]
fn main() {
use soroban_testkit_generators::event_fuzz::{
fuzzed_event, valid_transfer_event, EventFuzzHarness, MutationOperator,
};
// Start from a well-formed event and apply a single mutation.
let harness = EventFuzzHarness::new(valid_transfer_event());
let malformed = harness.mutate(MutationOperator::DropField, 42);
// Or drive a property test across every mutation operator.
proptest! {
#[test]
fn parser_never_panics(event in fuzzed_event(valid_transfer_event())) {
// Downstream decoding must return an error, never panic.
let _ = TransferEvent::try_from_event(&event);
}
}
}
Supported mutation operators:
| Operator | Effect |
|---|---|
DropField | Removes a topic, or clears the data when no topics remain |
TypeShift | Replaces a value with a different ScVal variant |
ByteTruncate | Halves the length of bytes, strings, symbols, or vectors |
SignFlip | Flips the sign of a number or toggles a boolean |
EventFuzzHarness::shrink deterministically reduces a malformed payload after
a failure, mirroring proptest’s shrinking so failures are reported with the
smallest event that still reproduces the bug. shrink_candidates returns each
intermediate step for debugging.
Contract executables and deployer salts
Factory contracts and deployment utilities dynamically deploy child contracts using WASM hashes or contract executable descriptors. contract_executable_wasm_hash(), contract_executable(), and deployer_salt() test factory patterns and verify deterministic contract address calculation:
#![allow(unused)]
fn main() {
use proptest::prelude::*;
use soroban_sdk::{Address, BytesN, Env};
use soroban_testkit_generators::strategies;
proptest! {
#[test]
fn deterministic_factory_address(
salt in strategies::deployer_salt(),
wasm_hash in strategies::contract_executable_wasm_hash(),
) {
let env = Env::default();
let deployer = Address::generate(&env);
let salt_n = BytesN::from_array(&env, &salt);
// Precompute deterministic deployment address
let predicted = env
.deployer()
.with_address(deployer.clone(), salt_n.clone())
.deployed_address();
// Repeated address calculations with identical inputs match
let predicted_repeat = env
.deployer()
.with_address(deployer, salt_n)
.deployed_address();
assert_eq!(predicted, predicted_repeat);
}
}
}
contract_executable() generates variants across ContractExecutable::Wasm, ContractExecutable::StellarAsset, and ContractExecutable::ExternalRef, allowing comprehensive fuzzing of contract installation and factory routines.
Cryptographic signatures and malleation
Contracts verifying external cryptographic signatures with env.crypto().ed25519_verify or secp256k1_recover require testing both valid signatures and corrupted variants.
ed25519_signature_pair() generates cryptographically valid Ed25519 keypairs, message digests, and signatures. secp256k1_signature_pair() produces valid Secp256k1 SEC-1 uncompressed 65-byte public keys, message hashes, 64-byte compact ECDSA signatures, and recovery IDs:
#![allow(unused)]
fn main() {
use proptest::prelude::*;
use soroban_sdk::{Bytes, BytesN, Env};
use soroban_testkit_generators::strategies;
proptest! {
#[test]
fn verify_ed25519_signatures(pair in strategies::ed25519_signature_pair()) {
let env = Env::default();
let pk = BytesN::from_array(&env, pair.public_key());
let msg = Bytes::from_slice(&env, pair.message_digest());
let sig = BytesN::from_array(&env, pair.signature());
// Verifies cleanly without panic
env.crypto().ed25519_verify(&pk, &msg, &sig);
}
#[test]
fn recover_secp256k1_public_keys(pair in strategies::secp256k1_signature_pair()) {
let env = Env::default();
let hash_bytes = Bytes::from_slice(&env, pair.message_hash());
let hash = env.crypto().sha256(&hash_bytes);
let sig = BytesN::from_array(&env, pair.signature());
let recovered = env.crypto().secp256k1_recover(&hash, &sig, pair.recovery_id());
assert_eq!(recovered.to_array(), *pair.public_key());
}
}
}
malleated_signature(valid_sig) introduces single-bit or byte perturbations into valid signatures to verify that corrupted or tampered signatures fail verification cleanly.
Storage tiers and allocations
Property-testing generalized storage adapters, multi-tier caches, or state partitioning layers requires generating random storage tier allocations (Instance, Persistent, Temporary) to test that functions handle all three tiers correctly.
storage_tier() produces all standard StorageTier enum variants compatible with soroban-testkit-core. It shrinks towards StorageTier::Temporary so that failing test cases simplify to the most ephemeral storage tier:
#![allow(unused)]
fn main() {
use proptest::prelude::*;
use soroban_testkit_core::storage::StorageTier;
use soroban_testkit_generators::strategies;
proptest! {
#[test]
fn cache_adapter_handles_all_tiers(tier in strategies::storage_tier()) {
match tier {
StorageTier::Temporary => { /* ephemeral storage handling */ }
StorageTier::Persistent => { /* restorable long-lived storage */ }
StorageTier::Instance => { /* contract instance storage */ }
}
}
}
}
Storage tiers with TTL properties
storage_tier_with_ttl(current_ledger, min_threshold, max_ttl) pairs each generated tier with its protocol durability (ContractDataDurability) and entry TTL properties (EntryTtl):
#![allow(unused)]
fn main() {
use proptest::prelude::*;
use soroban_testkit_generators::strategies;
proptest! {
#[test]
fn storage_renewal_respects_durability(
alloc in strategies::storage_tier_with_ttl(1_000, 100, 10_000),
) {
assert!(alloc.is_live());
if alloc.is_temporary() {
assert!(!alloc.is_restorable());
} else if alloc.is_persistent() {
assert!(alloc.is_restorable());
}
}
}
}
Mixed-tier key allocations
mixed_tier_allocations(key_strategy, count_range) generates partitioned plans allocating a dynamic set of keys across instance, persistent, and temporary storage tiers:
#![allow(unused)]
fn main() {
use proptest::prelude::*;
use soroban_testkit_generators::strategies;
proptest! {
#[test]
fn storage_manager_partitions_keys_properly(
plan in strategies::mixed_tier_allocations("[a-z0-9_]{3,12}", 10..=30),
) {
let (inst_count, pers_count, temp_count) = plan.counts();
assert_eq!(inst_count + pers_count + temp_count, plan.len());
for key in plan.temporary_keys() {
// Test temporary key eviction / purging logic
}
for key in plan.persistent_keys() {
// Test archive and restoration logic
}
}
}
}
Host cost models and budget threshold fuzzing
Soroban meters contract execution across granular ContractCostType
categories — including WasmInsnExec, MemAlloc, MemCpy, MemCmp, ValSer,
ValDeser, ComputeSha256Hash, VerifyEd25519Sig, VmInstantiation, and elliptic curve arithmetic.
Simulating resource cost fluctuations allows contracts to be stress-tested against
future protocol parameter adjustments and network fee shifts.
contract_cost_model() generates a realistic [ContractCostModel] covering all standard
ContractCostType enumerations. It generates valid host cost schedules (ContractCostParams)
directly compatible with soroban-env-host, supports configuring custom fee multipliers
for individual cost dimensions (CostDimension::Cpu and CostDimension::Memory), and
shrinks towards the baseline protocol fee schedule.
#![allow(unused)]
fn main() {
use proptest::prelude::*;
use soroban_env_host::xdr::ContractCostType;
use soroban_testkit_generators::strategies;
proptest! {
#[test]
fn contract_execution_fits_under_fee_shifts(
model in strategies::contract_cost_model(),
) {
// Construct a soroban-env-host Budget loaded with the generated schedule
let budget = model.try_into_budget(10_000_000, 10_000_000).unwrap();
// Meter operations or invoke contract functions
budget.charge(ContractCostType::WasmInsnExec, None).unwrap();
budget.charge(ContractCostType::MemAlloc, Some(1024)).unwrap();
assert!(budget.get_cpu_insns_remaining().unwrap() > 0);
}
}
}
Configuring fee multipliers
Use contract_cost_model_with_multipliers to supply percentage ranges for CPU and Memory
fee multipliers (where 100 represents 100% / 1.0x baseline):
#![allow(unused)]
fn main() {
use proptest::prelude::*;
use soroban_testkit_generators::strategies;
proptest! {
#[test]
fn test_tight_cpu_headroom(
// Stress-test 1.5x - 4.0x CPU shifts and 1.0x - 2.0x Memory shifts
model in strategies::contract_cost_model_with_multipliers(150..=400, 100..=200),
) {
let (cpu_cost, mem_cost) = model.evaluate_cost(
soroban_env_host::xdr::ContractCostType::ComputeSha256Hash,
1,
Some(256),
);
assert!(cpu_cost > 0);
assert_eq!(mem_cost, 0);
}
}
}
For fine-grained control, configure individual cost dimensions or specific ContractCostType
discriminants using ContractCostModelConfig:
#![allow(unused)]
fn main() {
use proptest::prelude::*;
use soroban_env_host::xdr::ContractCostType;
use soroban_testkit_generators::cost_model::{
ContractCostModelConfig, CostDimension,
};
use soroban_testkit_generators::strategies;
let config = ContractCostModelConfig::new()
.with_cpu_multiplier_range(100..=200)
.with_mem_multiplier_range(100..=150)
// Target a specific crypto primitive for severe cost surge
.with_cost_type_multiplier_range(
ContractCostType::VerifyEd25519Sig,
CostDimension::Cpu,
300..=1000,
);
proptest! {
#[test]
fn ed25519_heavy_contract_tolerates_signature_cost_spike(
model in strategies::contract_cost_model_with_config(config.clone()),
) {
let budget = model.try_into_budget(5_000_000, 5_000_000).unwrap();
budget.charge(ContractCostType::VerifyEd25519Sig, Some(64)).unwrap();
}
}
}
proptest shrinks integer offsets towards zero. contract_cost_model() generates fee shifts as offsets relative to 100% baseline, so failing runs simplify towards the standard on-chain protocol fee schedule (100% / 1.0x) rather than stopping at an arbitrary random multiplier.
XDR values: symbols, strings, bytes, vectors and maps
The xdr module generates the complex argument types contract interfaces
take, with configurable size bounds, and composes them into nested shapes.
#![allow(unused)]
fn main() {
use proptest::prelude::*;
use soroban_sdk::Env;
use soroban_testkit_generators::xdr::{xdr_bytes, xdr_map, xdr_string, xdr_symbol, xdr_vec};
let env = Env::default();
// Map<Symbol, Vec<Symbol>>: at most 5 keys, each with at most 4 symbols.
let tags = xdr_map(&env, xdr_symbol(&env, 10), xdr_vec(&env, xdr_symbol(&env, 10), 4), 5);
// A full argument tuple for `index(label: String, tags: Map<..>, payload: Bytes)`.
let args = (xdr_string(&env, 24), tags, xdr_bytes(&env, 32));
}
Each typed strategy returns a host value owned by env, so it can be passed
straight to a generated client. Element strategies can be any other strategy
whose value converts to and from Val, so xdr_vec(&env, xdr_vec(&env, xdr_symbol(&env, 8), 2), 3) is a Vec<Vec<Symbol>>.
Recursive values and depth limits
When a contract accepts a bare Val — or you want to fuzz any shape at all —
use xdr_value / xdr_val with an XdrBounds:
#![allow(unused)]
fn main() {
use soroban_testkit_generators::xdr::{xdr_val, xdr_value, XdrBounds};
let bounds = XdrBounds::default() // symbol ≤ 32, string ≤ 64, bytes ≤ 64,
.with_max_collection_len(4) // vectors / maps ≤ 4 entries
.with_max_depth(3); // at most 3 levels of nesting
proptest! {
#[test]
fn echo_round_trips(value in xdr_val(&env, bounds)) {
let echoed = client.echo(&value);
// compare via ScVal::try_from_val(&env, &value)
}
}
}
XdrBounds field | Default | Meaning |
|---|---|---|
max_symbol_len | 32 | longest symbol, clamped to the host’s 32-character limit |
max_string_len | 64 | longest string, in bytes |
max_bytes_len | 64 | longest byte array |
max_collection_len | 8 | most elements per vector / entries per map |
max_depth | 3 | container nesting: 0 = scalars only, 1 = a vector or map of scalars, … |
xdr_value produces an XdrValue — an environment-free description covering
Void, Bool, U32, I32, U64, I64, U128, I128, Symbol, String,
Bytes, Vec and Map — that prints readably when a case fails and is turned
into a Val with to_val(&env). Generation uses prop_recursive, so the
depth bound is a hard cap rather than a probability: a tree can never recurse
past max_depth, which keeps generation off the stack-overflow path and inside
the host’s object limits. XdrValue::depth() and max_collection_len() let a
test assert the bounds held. Map keys are scalars and are de-duplicated, and
every generated value converts to a valid ScVal.
tests/xdr_contract.rs drives a sample contract that takes String,
Map<Symbol, Vec<Symbol>>, Bytes, Val and Vec<Val> arguments with these
strategies and checks every value round-trips through storage and across the
contract boundary.
Fuzzing with arbitrary (cargo-fuzz, afl)
Coverage-guided fuzzers such as cargo-fuzz
and afl.rs build typed inputs with the
arbitrary crate rather than proptest. The
arbitrary feature implements Arbitrary for the same value ranges the
proptest strategies use. It compiles on its own — proptest is not required:
[dependencies]
soroban-testkit-generators = { version = "0.4", default-features = false, features = ["arbitrary"] }
| Type | Generated value |
|---|---|
AddressBytes | an account (G...) or contract (C...) address, 32 arbitrary bytes |
AddressType | Account or Contract |
TokenAmount | i128 in 0..=TOKEN_AMOUNT_MAX (10^15) |
LedgerSequence | u32 in 1..=10_000_000 |
Timestamp | u64 in 1_600_000_000..=2_000_000_000 |
ArbitraryLedgerInfo | a LedgerInfo the test host accepts (see below) |
The range constants (TOKEN_AMOUNT_MAX, LEDGER_SEQUENCE_MIN/MAX,
TIMESTAMP_MIN/MAX) live in the always-compiled types module and back both
the proptest strategies and the Arbitrary implementations, so the two
ecosystems can never disagree on what is valid. The bounded newtypes expose
get(), MIN, MAX and a checked new(value).
ArbitraryLedgerInfo always reports protocol version 28, a valid sequence and
timestamp, minimum temporary and persistent TTLs of at least one ledger, a
max_entry_ttl no smaller than either minimum, and a sequence that cannot
overflow when the maximum TTL is added. Install it with info.apply(&env).
Generation never panics. Every implementation draws with
Unstructured::int_in_range or fixed-size byte copies, which fall back to the
low end of the range when the fuzzer’s input runs out. An empty, truncated or
all-0xFF input still produces a valid value.
A cargo-fuzz harness
#![allow(unused)]
#![no_main]
fn main() {
use arbitrary::{Arbitrary, Unstructured};
use libfuzzer_sys::fuzz_target;
use soroban_sdk::Env;
use soroban_testkit_generators::arbitrary::{AddressBytes, ArbitraryLedgerInfo, TokenAmount};
fuzz_target!(|data: &[u8]| {
let mut u = Unstructured::new(data);
let ledger = ArbitraryLedgerInfo::arbitrary(&mut u).unwrap();
let payer = AddressBytes::arbitrary(&mut u).unwrap();
let amount = TokenAmount::arbitrary(&mut u).unwrap();
let env = Env::default();
ledger.apply(&env);
let payer = payer.to_address(&env);
// ... call the contract under test with `payer` and `amount.get()` ...
});
}
The crate ships this as a ready-made project in
crates/soroban-testkit-generators/fuzz/, kept outside the workspace because
libFuzzer needs nightly:
cargo install cargo-fuzz
cd crates/soroban-testkit-generators
cargo +nightly fuzz run arbitrary_values
The target’s body lives in fuzz/fuzz_targets/harness.rs, and the stable
integration test tests/arbitrary_fuzz_harness.rs runs the same harness over
empty, short, saturated and pseudo-random inputs, so cargo test --workspace
checks the “never panics, always valid” guarantee on every CI run.
Custom strategies
Compose the built-ins with proptest combinators:
#![allow(unused)]
fn main() {
use proptest::prelude::*;
use soroban_testkit_generators::strategies;
fn transfer_args() -> impl Strategy<Value = (i128, i128)> {
(strategies::token_amount(), strategies::token_amount())
.prop_filter("sender must have sufficient balance", |(a, b)| a >= b)
}
}
Soroban tests run on the host and pay for every instruction. Start proptest! cases at the default 256, and shrink ranges before raising the count — Property Testing covers the trade-offs.
One backend today
proptest is the default and currently the only backend, and it gates the whole strategies module — turn off default features and the crate compiles to nothing rather than to a second generator family.
An arbitrary backend
#16 adds Arbitrary implementations behind an arbitrary flag, for the fuzzers that drive inputs through that crate instead of proptest — Medium 150 pts. Until it lands there is no such flag.
Testing Patterns
Common patterns for testing Soroban contracts with Testkit: a shared setup(), multi-contract interactions, and deterministic ledger time.
Unit test structure
#![allow(unused)]
fn main() {
#[cfg(test)]
mod tests {
use super::*;
use soroban_testkit_fixtures::builder::TestContextBuilder;
fn setup() -> TestContext {
TestContextBuilder::new()
.with_users(3)
.build()
}
#[test]
fn test_happy_path() {
let ctx = setup();
// ...
}
#[test]
#[should_panic(expected = "InsufficientBalance")]
fn test_insufficient_balance() {
let ctx = setup();
// ...
}
}
}
Cross-contract testing
Register multiple contracts and test interactions:
#![allow(unused)]
fn main() {
#[test]
fn test_contract_interaction() {
let ctx = TestContextBuilder::new().with_users(2).build();
let token_id = ctx.env.register(TokenContract, ());
let vault_id = ctx.env.register(VaultContract, (&token_id,));
let vault_client = VaultClient::new(&ctx.env, &vault_id);
vault_client.deposit(&ctx.users[0], &1000);
// Assert both contracts behaved correctly
}
}
Time-dependent tests
Manipulate ledger state for time-sensitive logic:
#![allow(unused)]
fn main() {
#[test]
fn test_vesting_unlock() {
let ctx = TestContextBuilder::new().with_users(1).build();
ctx.env.ledger().set(LedgerInfo {
timestamp: 1_700_000_000,
..Default::default()
});
// ... assert locked
ctx.env.ledger().set(LedgerInfo {
timestamp: 1_800_000_000,
..Default::default()
});
// ... assert unlocked
}
}
Each TestContext owns its own Env, so ledger writes and storage never leak between tests. Share a setup() helper instead of a mutable global fixture.
Where to go next
Budget-aware testing
Pin these patterns down with CPU and memory regression assertions.
Property testing
Replace hand-picked inputs with Soroban-aware generators.
soroban-testkit-assert
The full matcher API for events and authorizations.
Worked Example: Counter
A complete contract and its test suite, line by line. Everything here is the real code in examples/counter, which is a workspace member you can run.
The contract
A counter that stores one u32 in instance storage, charges an authorisation, and emits one event per increment.
#![allow(unused)]
fn main() {
#[contract]
pub struct CounterContract;
#[contractevent(topics = ["counter", "incremented"])]
#[derive(Clone)]
pub struct Incremented {
pub caller: Address,
pub new_count: u32,
}
#[contractimpl]
impl CounterContract {
pub fn get(env: Env) -> u32 {
let key = Symbol::new(&env, "count");
env.storage().instance().get(&key).unwrap_or(0)
}
pub fn increment(env: Env, caller: Address, by: u32) -> u32 {
caller.require_auth();
let key = Symbol::new(&env, "count");
let current: u32 = env.storage().instance().get(&key).unwrap_or(0);
let next = current.checked_add(by).expect("counter overflow");
env.storage().instance().set(&key, &next);
Incremented { caller, new_count: next }.publish(&env);
next
}
}
}
Step 1 — build the environment
TestContextBuilder hands back an Env, an admin and pre-generated user addresses. Nothing else is set up by hand in this suite.
#![allow(unused)]
fn main() {
use soroban_testkit_fixtures::builder::TestContextBuilder;
use soroban_testkit_fixtures::TestContext;
fn context(users: usize) -> TestContext {
TestContextBuilder::new().with_users(users).build()
}
}
Auth is mocked by default, so caller.require_auth() passes without wiring a signature per test.
Step 2 — register and call
Registering returns the contract’s Address; the generated client borrows the environment. Two helpers keep the borrow checker happy, because a client cannot hold a reference to the context it is stored next to.
#![allow(unused)]
fn main() {
use soroban_sdk::Address;
fn client_for(ctx: &TestContext) -> (Address, CounterContractClient<'_>) {
let contract_id = ctx.env.register(CounterContract, ());
(
contract_id.clone(),
CounterContractClient::new(&ctx.env, &contract_id),
)
}
#[test]
fn increment_accumulates_and_returns_the_new_value() {
let ctx = context(1);
let (_id, client) = client_for(&ctx);
let caller: Address = ctx.users[0].clone();
assert_eq!(client.increment(&caller, &5), 5);
assert_eq!(client.increment(&caller, &7), 12);
assert_eq!(client.get(), 12);
}
}
Step 3 — assert on events
EventMatcher reads the events of the most recent invocation, which is what env.events().all() exposes in SDK v28 — so a per-call assertion goes right after that call. Judging several calls together is EventLog’s job, shown at the end of this step.
#![allow(unused)]
fn main() {
use soroban_testkit_assert::events::EventMatcher;
#[test]
fn events_can_be_filtered_to_the_contract_that_emitted_them() {
let ctx = context(1);
let (contract_id, client) = client_for(&ctx);
let caller = ctx.users[0].clone();
client.increment(&caller, &1);
EventMatcher::new(&ctx.env)
.from_contract(&contract_id)
.with_topic("counter")
.assert_emitted();
}
}
A read-only call emits nothing, which is worth its own test:
#![allow(unused)]
fn main() {
#[test]
fn read_only_calls_emit_nothing() {
let ctx = context(1);
let (_id, client) = client_for(&ctx);
client.get();
EventMatcher::new(&ctx.env).assert_not_emitted();
}
}
assert_not_emitted is the negative half of the matcher and respects the same filters, so a topic the contract never publishes is provable too:
#![allow(unused)]
fn main() {
EventMatcher::new(&ctx.env)
.from_contract(&contract_id)
.with_topic("decremented")
.assert_not_emitted();
}
It reads the latest invocation, so the topic is proven absent from the call under test; EventLog below widens that to a whole sequence of calls.
The counter publishes its event with #[contractevent], so the payload arrives as a map keyed by field name and assert_data_matches reads the field the test is about:
#![allow(unused)]
fn main() {
#[test]
fn the_increment_event_carries_the_caller_and_the_new_count() {
let ctx = context(1);
let (contract_id, client) = client_for(&ctx);
let caller = ctx.users[0].clone();
client.increment(&caller, &12);
EventMatcher::new(&ctx.env)
.from_contract(&contract_id)
.with_topic("incremented")
.assert_data_matches(|data| {
data.field("new_count")
.and_then(|value| value.deserialize::<u32>())
== Some(12)
});
}
}
A failed assertion reports the payload it was handed instead of only saying the predicate was wrong — this is the counter’s event after an increment the predicate did not expect:
Expected an event whose data matches, checked 1 event(s) with data [{"caller": Contract(CAAAAAA...FCT4), "new_count": 7}]
The account key is abbreviated here; a real message prints the whole strkey, because a hash of the public key is not what a test author compares against.
See soroban-testkit-assert for deserialize, field and raw.
Several calls as one set
Counting the events of a whole run is the one thing a single-call matcher cannot say: “these increments emitted two events, and the first carried 5”. EventLog collects after each call the test means to judge, and its matcher takes the same filters and assertions:
#![allow(unused)]
fn main() {
use soroban_testkit_assert::events::EventLog;
#[test]
fn a_sequence_of_calls_can_be_asserted_over_as_one_set() {
let ctx = context(1);
let (contract_id, client) = client_for(&ctx);
let caller = ctx.users[0].clone();
let mut log = EventLog::new(&ctx.env);
client.increment(&caller, &5);
log.collect();
client.get();
log.collect();
client.increment(&caller, &7);
log.collect();
log.matcher()
.from_contract(&contract_id)
.with_topic("incremented")
.assert_count(2);
log.matcher()
.with_topic("incremented")
.assert_data_matches(|data| {
data.field("new_count")
.and_then(|value| value.deserialize::<u32>())
== Some(5)
});
}
}
client.get() publishes nothing, so it adds nothing to the log — that is what makes a log-wide assert_not_emitted() mean “never in these calls”. Collection stays explicit because SDK v28 gives a test no per-invocation hook to drain: a call nobody collected from is simply not in scope. Events keep their call order, and log.topics() reads that order back.
Step 4 — bound the cost
Wrap the call in a guard instead of reading the meter by hand. The guard runs the closure and judges the metering that call left behind, so there is no warm-up call and no delta to compute.
#![allow(unused)]
fn main() {
use soroban_testkit_core::budget_guard;
#[test]
fn increment_stays_inside_its_cpu_ceiling() {
let ctx = context(1);
let (_id, client) = client_for(&ctx);
let caller = ctx.users[0].clone();
budget_guard!(&ctx.env, "increment", { cpu_max: 20_000_000, mem_max: 20_000_000 }, || {
client.increment(&caller, &1)
});
}
}
A ceiling is transaction headroom, not the measured cost. A contract registered with register() runs as native host code, so the VM’s own instantiation and execution costs never appear in the reading — the call above meters at tens of thousands of instructions here while a network would bill more.
The macro expands to the builder, so a test that loops over several calls can hold its own guard:
#![allow(unused)]
fn main() {
use soroban_testkit_core::budget::BudgetGuard;
BudgetGuard::new("increment").cpu_ceiling(20_000_000).run(&ctx.env, || client.increment(&caller, &1));
}
The other half is a baseline. Record the cost of a call once, and the next run of the same call is judged against the build that produced it:
#![allow(unused)]
fn main() {
use soroban_testkit_core::budget::{BudgetBaseline, BudgetSnapshot};
client.increment(&caller, &1);
let measured = BudgetSnapshot::last_invocation(&ctx.env);
let mut baseline = BudgetBaseline::new();
baseline.record("increment", measured);
baseline.guard("increment").tolerance_percent(25).run(&ctx.env, || {
client.increment(&caller, &1);
});
}
A ceiling says the call is still affordable; a baseline says it is still the call you measured. The first catches a rewrite that got loose, the second catches a drift no reviewer noticed. One guard checks both, prints every breach as a key=value line, and leaves the numbers in the pull request diff instead of in a deploy log.
This crate carries its own baseline — examples/counter/budget.json — and two #[ignore]d tests that record and enforce it. They are ignored because an SDK bump moves every number at once and the recording test rewrites a file, neither of which belongs in cargo test; the Budget baseline workflow runs them on a pinned runner instead, so the numbers are still judged somewhere. See Budget-aware testing for the commands and the failure output.
Step 5 — prove the authorisation is real
Everything above mocks auth. The last test turns mocking off and expects the call to panic, which is the only proof that require_auth() was not decorative.
#![allow(unused)]
fn main() {
#[test]
#[should_panic]
fn increment_requires_authorization_when_auths_are_not_mocked() {
let ctx = TestContextBuilder::new()
.with_users(1)
.without_mock_auths()
.build();
let (_id, client) = client_for(&ctx);
let caller = ctx.users[0].clone();
client.increment(&caller, &1);
}
}
Running it
cargo test -p soroban-testkit-example-counter
running 9 tests
test test::counter_starts_at_zero ... ok
test test::a_topic_the_contract_never_publishes_stays_silent ... ok
test test::each_invocation_is_asserted_on_its_own ... ok
test test::events_can_be_filtered_to_the_contract_that_emitted_them ... ok
test test::increment_accumulates_and_returns_the_new_value ... ok
test test::increment_emits_exactly_one_event ... ok
test test::increment_consumes_a_predictable_amount_of_cpu ... ok
test test::read_only_calls_emit_nothing ... ok
test test::increment_requires_authorization_when_auths_are_not_mocked - should panic ... ok
One assertion per invocation
Assert right after the call you care about. The matcher cannot see events from earlier invocations, so an end-of-test count is always wrong.
Construct per test
Each test builds its own context. Sharing one environment across tests would leak budget counters and auth records between them.
Warm up before measuring
The first cost estimate on a fresh Env can read zero. A throwaway call makes the snapshot meaningful.
Test the failure path
A #[should_panic] test with without_mock_auths() is what turns an auth check from a line of code into a guarantee.
Where to go next
Worked Example: Token
A second contract and its suite, written to show the parts Worked Example: Counter cannot: an event payload with three fields in it, two contracts registered in one environment, an allowance one holder grants another, and generated inputs. Everything here is real code in examples/token, a workspace member you can run.
The contract
An ERC-20 shaped token: a supply that only moves through mint, burn and
transfer, balances in persistent storage, allowances a spender draws down, and
one event per state change carrying the values that changed.
#![allow(unused)]
fn main() {
#[contractevent(topics = ["token", "transfer"])]
#[derive(Clone)]
pub struct Transfer {
pub from: Address,
pub to: Address,
pub amount: i128,
}
pub fn transfer(env: Env, from: Address, to: Address, amount: i128) {
from.require_auth();
move_balance(&env, &from, &to, amount);
Transfer { from, to, amount }.publish(&env);
}
}
The three fields are the reason this example exists. The counter’s event carries
one number, so its suite asserts on that number and nothing else; a token test
has to say which of from, to and amount it means.
Why four files
The package splits its suite by crate, one file each, so a reader can open the file for the crate they are learning and find nothing else in it.
| File | Crate | What it covers |
|---|---|---|
src/test.rs | soroban-testkit-fixtures | TestContextBuilder, user(index), add_user, the ledger clock, reset |
tests/assert_events.rs | soroban-testkit-assert | EventMatcher, EventData, EventLog, assert_auth_matches!, AuthMatcher |
tests/budget_and_storage.rs | soroban-testkit-core | budget_guard!, BudgetSnapshot, BudgetBaseline, StorageSnapshot, assert_storage_tier! |
tests/property.rs | soroban-testkit-generators | proptest! over token_amount(), account_address(), contract_address() |
src/test.rs is a module of the no_std crate, so it reaches the contract
directly with use crate::{TokenContract, TokenContractClient}. The three files
under tests/ are separate binaries and name the package instead:
#![allow(unused)]
fn main() {
use soroban_testkit_example_token::{TokenContract, TokenContractClient};
}
Fixtures — the environment
#![allow(unused)]
fn main() {
fn context(users: usize) -> TestContext {
TestContextBuilder::new().with_users(users).build()
}
fn token(ctx: &TestContext) -> (Address, TokenContractClient<'_>) {
let contract_id = ctx.env.register(TokenContract, ());
let client = TokenContractClient::new(&ctx.env, &contract_id);
client.initialize(&ctx.admin);
(contract_id, client)
}
}
Two things the counter never needed. A token has holders, so the builder is
asked for them up front and ctx.user(index) is the accessor — with a panic
message that names the with_users call to fix when the index is out of range.
And a token has an admin: initialize records ctx.admin, which is what makes
the fixture’s admin a contract concept rather than a test variable.
reset() is the other fixture idea worth a test of its own:
#![allow(unused)]
fn main() {
ctx.reset();
let (_id, client) = token(&ctx);
assert_eq!(client.balance_of(&holder), 0);
assert_eq!(client.total_supply(), 0);
}
The same holders, a brand-new chain. Registration belongs to the environment that created it, so the contract is re-registered and every byte of its storage is gone — which is exactly the second-phase state a multi-phase test wants without tearing the whole fixture down.
Assert — events, then authorisations
EventMatcher reads the data payload as a map keyed by field name, so a test
asserts the value that moved:
#![allow(unused)]
fn main() {
EventMatcher::new(&ctx.env)
.from_contract(&contract_id)
.with_topic("transfer")
.assert_data_matches(|data| {
data.field("amount")
.and_then(|value| value.deserialize::<i128>())
== Some(250)
});
}
Three behaviours of that API the counter’s suite has no room to show.
A field that has no value is absent, not void. The SDK publishes event maps
sparse, so Minted — which has no from — reads data.field("from").is_none(),
while Transfer reads Some. fields() enumerates what is really in the map,
which pins an event’s shape as well as its values.
from_contract matters once two contracts share an environment. The token
example registers two of them in one test and asserts that one matcher answers
while the other stays silent. Nothing about the fixture changed between them.
The scope is the most recent invocation. This is the trap in both suites, and
the example walks into it on purpose in prose rather than in code: reading state
back after the assertion is one more invocation, and the invocation the matcher
was looking at is gone with it. So the event assertions come first and the
balance_of checks after. EventLog is how a test opts out of that scope — it
keeps every call it collects, so a sequence of mint, transfer and approve
can be judged as one set:
#![allow(unused)]
fn main() {
let mut log = EventLog::new(&ctx.env);
client.mint(sender, &1_000);
log.collect();
client.transfer(sender, recipient, &250);
log.collect();
client.approve(sender, spender, &100);
log.collect();
log.matcher().with_topic("transfer").assert_count(1);
assert_eq!(log.len(), 3);
}
Auth works the same way. assert_auth_matches! reads env.auths() for the
latest invocation, and under the builder’s default policy the requirement is
recorded rather than enforced:
#![allow(unused)]
fn main() {
assert_auth_matches!(ctx.env, {
invoker: sender,
function: "transfer",
args: [_, recipient, 250i128],
});
}
AuthMatcher answers the questions the macro does not ask — assert_auth_count(1)
after a transfer, assert_no_auth_required() after a balance_of — and one
test drops the mocked policy entirely and supplies the MockAuth itself, which
is how you prove the contract really asked.
Core — cost and storage tier
budget_and_storage.rs builds a bare Env instead of a TestContext, so the
file contains no other crate.
#![allow(unused)]
fn main() {
soroban_testkit_core::budget_guard!(
&env,
"mint",
{ cpu_max: 20_000_000, mem_max: 20_000_000 },
|| client(&env, &contract).mint(&holder, &1_000)
);
}
A ceiling is transaction headroom, not the measured cost — a contract registered
natively is metered without the VM’s own costs. Crossing one fails with one
parseable line, which a #[should_panic(expected = "...")] test pins:
BUDGET kind=ceiling case=mint metric=cpu_insns actual=… limit=1
BudgetSnapshot::last_invocation is per call, so a read and a mint in the same
test are two readings, and diff is the gap between them. BudgetBaseline
turns a reading into a number CI can commit; one test round-trips a baseline
through to_json_string and parse to show the recorded cases survive it.
The storage half is what a token has and a counter does not: three tiers in one contract.
#![allow(unused)]
fn main() {
soroban_testkit_core::assert_storage_tier!(&env, &contract, "admin", StorageTier::Instance);
soroban_testkit_core::assert_storage_tier!(&env, &contract, "balances", StorageTier::Persistent);
let snapshot = StorageSnapshot::capture(&env, &contract);
assert_eq!(snapshot.in_tier(StorageTier::Persistent).len(), 2);
}
The pattern argument takes prefix* and *suffix as well as an exact key, so
"*es" asserts the pair balances and allowances in one line. A key in the
tier nobody meant is a failure with the key, the expected tier and the found one
in the message, and StorageDiff says which entry a call added — the first
mint adds persistent:balances and rewrites instance:supply, which is a
storage read nobody intended made visible.
Generators — properties over the whole contract
#![allow(unused)]
fn main() {
proptest! {
#![proptest_config(ProptestConfig::with_cases(64))]
#[test]
fn a_transfer_moves_exactly_what_it_reports(
held in token_amount(),
moved in token_amount(),
sender in account_address(),
recipient in contract_address(),
) {
prop_assume!(moved <= held);
let env = Env::default();
let client = deploy(&env);
let sender = sender.to_address(&env);
let recipient = recipient.to_address(&env);
client.mint(&sender, &held);
client.transfer(&sender, &recipient, &moved);
prop_assert_eq!(client.balance_of(&recipient), moved);
prop_assert_eq!(client.balance_of(&sender), held - moved);
prop_assert_eq!(client.total_supply(), held);
}
}
}
Each case makes its own Env, so no case inherits another’s storage, and
prop_assume! is how a case asks for a relation between two generated values —
here that the transfer fits inside the balance. The allowance test asks for two:
the spend has to fit the allowance and the balance.
The recipient is generated with contract_address() and the sender with
account_address(), which is the point of the two strategies: both formats are
opaque 32 bytes on the wire, so a contract that silently assumed a G... account
fails here rather than on mainnet. Two more cases judge the strategies
themselves — that generated addresses never collide, and that the requested
format is the XDR shape that arrives.
Every case registers a contract and runs several calls on the host. The file keeps its cases low enough that cargo test --workspace stays quick; the strategy-only block in the same file runs 256, because a case over plain numbers costs nothing.
Running it
cargo test -p soroban-testkit-example-token
test test::initialize_records_the_admin_and_starts_the_supply_at_zero ... ok
test test::the_builder_hands_out_as_many_distinct_holders_as_the_test_asks_for ... ok
test test::asking_for_a_holder_that_was_never_built_points_at_with_users - should panic ... ok
test test::reset_keeps_the_holders_and_empties_the_chain ... ok
# src/test.rs — 7 tests, fixtures
test a_transfer_event_carries_the_amount_and_both_parties_in_its_data ... ok
test a_mint_payload_omits_the_field_that_has_no_value ... ok
test two_tokens_in_one_environment_keep_their_events_apart ... ok
test the_matcher_counts_one_calls_requirement_and_a_reads_none ... ok
# tests/assert_events.rs — 11 tests
test mint_stays_inside_its_transaction_ceiling ... ok
test a_call_past_its_ceiling_fails_the_test_with_a_parseable_line - should panic ... ok
test initialize_writes_only_instance_storage ... ok
test every_key_a_token_holds_reads_back_qualified ... ok
# tests/budget_and_storage.rs — 11 tests
test a_transfer_moves_exactly_what_it_reports ... ok
test an_allowance_is_drawn_down_by_what_was_spent ... ok
test generated_addresses_never_collide ... ok
# tests/property.rs — 8 tests
37 tests in the package, and all of them inside cargo test --workspace --locked.
Where to go next
soroban-testkit-core
StorageSnapshot and BudgetBaseline, the two APIs tests/budget_and_storage.rs uses.
Worked Example: Bounty Escrow
A task bounty with a multi-signature release: a creator locks funds, a
contributor submits work, named reviewers approve, and the escrow pays out only
when enough of them have signed — or refunds the creator once the deadline has
passed without a release. Everything here is real code in
examples/bounty_escrow,
a workspace member you can run.
The contract
One #![no_std] contract
holds every bounty in a persistent map and the next id in instance storage. A
bounty moves through four states, and exactly one of the last two is reachable:
Open ──submit──▶ Submitted ──threshold approvals──▶ Released
│ │
└──────refund───────┴─────(deadline passed)────▶ Refunded
#![allow(unused)]
fn main() {
#[contracttype]
pub enum BountyStatus {
Open,
Submitted,
Released,
Refunded,
}
pub fn create(
env: Env,
creator: Address,
token: Address,
amount: i128,
reviewers: Vec<Address>,
threshold: u32,
deadline: u64,
) -> u64 {
creator.require_auth();
assert!(amount > 0, "amount must be positive");
assert!(!reviewers.is_empty(), "at least one reviewer is required");
assert!(
threshold > 0 && threshold <= reviewers.len(),
"threshold must be between 1 and the reviewer count"
);
// ... store the bounty, then move the creator's tokens into the contract
token::Client::new(&env, &token).transfer(
&creator,
&env.current_contract_address(),
&amount,
);
id
}
}
The escrow is the contract’s own token balance. create moves the money in, so
a bounty that is never claimed still has funds the creator can reclaim; approve
moves it out on the signature that reaches the threshold; refund moves it back
after the deadline. submit and approve both reject a clock at or past the
deadline, which leaves refund as the only way the funds can move once the window
closes.
Why four files
The package splits its suite by crate, one file each, so a reader can open the file for the crate they are learning and find nothing else in it.
| File | Crate | What it covers |
|---|---|---|
src/test.rs | soroban-testkit-fixtures | TestContextBuilder, user(index), add_user, the ledger clock, reset, and the contract’s own validation rules |
tests/assert_events.rs | soroban-testkit-assert | EventMatcher, EventData, EventLog, assert_auth_matches!, AuthMatcher |
tests/budget_and_storage.rs | soroban-testkit-core | budget_guard!, BudgetSnapshot, BudgetBaseline, StorageSnapshot, assert_storage_tier!, and the payout benchmark |
tests/property.rs | soroban-testkit-generators | proptest! over token_amount(), contract_address(), and host_error_code_coverage() |
src/test.rs is a module of the no_std crate, so it reaches the contract
directly with use crate::{BountyEscrowContract, BountyEscrowContractClient}.
The three files under tests/ are separate binaries and name the package
instead:
#![allow(unused)]
fn main() {
use soroban_testkit_example_bounty_escrow::{
BountyEscrowContract, BountyEscrowContractClient, BountyStatus,
};
}
Fixtures — three roles and a clock
#![allow(unused)]
fn main() {
fn context(users: usize) -> TestContext {
TestContextBuilder::new().with_users(users).build()
}
fn deploy(ctx: &TestContext, funding: i128) -> (Address, Address, BountyEscrowContractClient<'_>) {
let contract_id = ctx.env.register(BountyEscrowContract, ());
let client = BountyEscrowContractClient::new(&ctx.env, &contract_id);
let token = ctx
.env
.register_stellar_asset_contract_v2(ctx.admin.clone())
.address();
StellarAssetClient::new(&ctx.env, &token).mint(ctx.user(0), &funding);
(contract_id, token, client)
}
}
The suite assigns the fixture’s identities to roles rather than inventing them
per test: index 0 is the creator and the funded holder, index 1 is the
contributor, and every index from 2 is a reviewer. reviewers(ctx, 3) builds
that list, which is the value create takes.
The clock is a fixture concept too. ctx.timestamp() is what open adds a day
to, and ctx.env.ledger().set_timestamp(...) is how a test moves past the
deadline without waiting:
#![allow(unused)]
fn main() {
let deadline = ctx.timestamp() + 86_400;
// ... later, in the refund test
ctx.env.ledger().set_timestamp(deadline);
}
reset() clears the chain without clearing the identities, so the multi-phase
test re-registers the contract and proves the next bounty starts from id 1 with
an empty balance. add_user grows the context after the fact, which is the
reviewer that arrives late.
Assert — five event kinds, then the authorisations
Every transition publishes an event, and the payload is what the assertions read as a map keyed by field name:
#![allow(unused)]
fn main() {
EventMatcher::new(&ctx.env)
.from_contract(&contract_id)
.with_topic("created")
.assert_data_matches(|data| {
data.field("amount")
.and_then(|value| value.deserialize::<i128>())
== Some(1_000)
});
}
The suite asserts five shapes: bounty/created with its terms, bounty/submitted
with the contributor, bounty/approved with the running count and the threshold,
bounty/released with the amount paid, and bounty/refunded with the amount
returned. Two of those are the interesting ones.
The approval event carries its progress. approvals and threshold travel
in the data, so a test proves the count grew rather than only that a signature
was recorded:
#![allow(unused)]
fn main() {
for expected in 1..=2u32 {
client.approve(&id, &ctx.user(1 + expected as usize));
EventMatcher::new(&ctx.env)
.from_contract(&contract_id)
.with_topic("approved")
.assert_data_matches(|data| {
data.field("approvals")
.and_then(|value| value.deserialize::<u32>())
== Some(expected)
});
}
}
no_release_before_the_threshold_is_reached is the negative half: after one
of two signatures the released topic is silent, and the balance has not moved.
Together with the positive release test it pins the multi-signature rule from
both sides.
Auth is the other half of this file. assert_auth_matches! names the invoker,
function and arguments of the latest invocation:
#![allow(unused)]
fn main() {
assert_auth_matches!(ctx.env, {
invoker: contributor,
function: "submit",
args: [id, contributor],
});
}
AuthMatcher answers what the macro does not ask: assert_auth_count(1) after
create, submit, approve and refund, and assert_no_auth_required() after
a read. The file also proves the refusals: an address that is not a reviewer
cannot approve, and a reviewer cannot sign twice.
Core — ceilings, a payout benchmark, and two storage tiers
budget_and_storage.rs builds a bare Env instead of a TestContext, so the
file contains no other testkit crate.
#![allow(unused)]
fn main() {
soroban_testkit_core::budget_guard!(&fixture.env, "create", {
cpu_max: 50_000_000,
mem_max: 50_000_000,
}, || fixture.open(1_000));
}
A ceiling is transaction headroom, not a measured cost. Crossing one fails with
one parseable line, which a #[should_panic(expected = "...")] test pins:
BUDGET kind=ceiling case=create metric=cpu_insns actual=… limit=1
The payout benchmark is the reason this file is more than a guard. A release
costs whatever the signatures before it cost, so payout_cost(reviewer_count)
sums BudgetSnapshot::last_invocation across the approvals:
#![allow(unused)]
fn main() {
fn payout_cost(reviewer_count: usize) -> BudgetSnapshot {
let fixture = setup(reviewer_count);
let client = fixture.client();
let id = fixture.open(1_000);
client.submit(&id, &fixture.contributor);
let mut total = BudgetSnapshot { cpu_insns: 0, mem_bytes: 0 };
for reviewer in fixture.reviewers.iter() {
client.approve(&id, &reviewer);
let step = BudgetSnapshot::last_invocation(&fixture.env);
total.cpu_insns += step.cpu_insns;
total.mem_bytes += step.mem_bytes;
}
total
}
}
payout_cost_grows_with_the_reviewer_count measures 1, 2, 3, 5 and 7 reviewers,
prints the table for a reviewer to read, and asserts the shape rather than a
machine-specific number: each larger quorum costs more instructions, and seven
signatures write more memory than one. a_baseline_records_one_payout_case_per_reviewer_count
turns those readings into BudgetBaseline cases (payout/1, payout/3,
payout/5) and round-trips them through to_json_string and parse, which is
what lets a pull request compare its costs against a file recorded on main.
The storage half shows the two tiers the contract uses:
#![allow(unused)]
fn main() {
soroban_testkit_core::assert_storage_tier!(
&fixture.env, &fixture.contract, "next_id", StorageTier::Instance
);
soroban_testkit_core::assert_storage_tier!(
&fixture.env, &fixture.contract, "bounties", StorageTier::Persistent
);
}
StorageDiff says what a transition really wrote. The first create adds both
keys; a later approve modifies persistent:bounties and leaves
instance:next_id alone; a refund rewrites exactly one entry; and a set of reads
leaves the snapshot unchanged. The deliberately wrong tier test pins the failure
message:
Storage tier mismatch for key 'next_id': expected persistent, found instance
Generators — the threshold, the clock, and host errors
#![allow(unused)]
fn main() {
proptest! {
#![proptest_config(ProptestConfig::with_cases(48))]
#[test]
fn funds_are_released_only_at_the_reviewer_threshold(
threshold in 1u32..=4u32,
signatures in 0u32..=5u32,
) {
let fixture = setup(1_000, 4);
let client = fixture.client();
let id = fixture.open(500, threshold);
client.submit(&id, &fixture.contributor);
let applied = signatures.min(threshold);
for index in 0..applied {
fixture.approve(id, index);
}
let bounty = client.get(&id);
if signatures >= threshold {
prop_assert_eq!(bounty.status, BountyStatus::Released);
prop_assert_eq!(fixture.paid_out(), 500);
} else {
prop_assert_eq!(bounty.status, BountyStatus::Submitted);
prop_assert_eq!(fixture.escrow(), 500);
}
}
}
}
That is the acceptance criterion in code: across every generated threshold and
signature count, the escrow pays the contributor only once the threshold is
reached, and otherwise holds the full amount. any_threshold_inside_the_reviewer_set_always_releases
complements it over generated reviewer sets from 1 to 6, so the rule is proven
for every legal threshold rather than only the fixed one the unit tests use.
Amounts come from token_amount(), which can generate zero; the escrow
properties prop_assume!(amount > 0) because a zero bounty is refused at
creation, a different property from the one each case is about. Wherever the
money sits, the_escrow_holds_exactly_the_bounty asserts the invariant:
escrow + paid_out == amount, and the creator’s balance is zero.
The clock is generated too: a_submission_after_the_deadline_is_refused and
an_approval_after_the_deadline_is_refused add 0..=10_000 seconds past the
deadline — zero included, so the exact boundary is covered — and assert the call
fails while the escrow stays put. a_settled_bounty_refuses_further_moves proves
a released bounty cannot be paid twice: a late signature and a refund both fail.
The host-error case is the new generator in action. host_error_code_coverage()
draws from all ten ScErrorType categories and all ten ScErrorCode values, and
the suite fuzzes an error-recovery block over the whole domain:
#![allow(unused)]
fn main() {
enum Recovery {
Retry,
Stop,
}
fn recover(error: &Error) -> Recovery {
if error.is_type(ScErrorType::Budget) || error.is_type(ScErrorType::Storage) {
Recovery::Retry
} else {
Recovery::Stop
}
}
#[test]
fn every_generated_host_error_is_recoverable_around_a_rejected_action(
error in host_error_code_coverage(),
) {
// ... a non-reviewer's approval is refused and the state is intact
let decision = recover(&error.as_error());
// every category gets a decision; only transient ones ask for a retry
}
}
Each case also proves the rejected action left storage untouched, so a contract
that handled an error by half-writing state would fail here. See
crate docs for generators for the strategy’s tables,
HostError accessors, and the shrink-to-contract/0 behaviour.
Every property case registers two contracts — the escrow and a Stellar asset contract — and runs several calls on the host. The file keeps its case count at 48 so cargo test --workspace stays quick; each case builds its own Env, so no case inherits another's storage or balances.
Running it
cargo test -p soroban-testkit-example-bounty-escrow
test test::creating_a_bounty_locks_the_creators_funds_in_the_contract ... ok
test test::the_fixture_clock_is_what_the_deadline_is_measured_against ... ok
test test::reset_keeps_the_identities_and_empties_the_chain ... ok
# src/test.rs — 13 tests, fixtures
# plus the contract's validation rules
test a_created_event_carries_the_bounty_terms ... ok
test every_approval_reports_the_running_count ... ok
test no_release_before_the_threshold_is_reached ... ok
test a_reviewer_cannot_approve_twice ... ok
# tests/assert_events.rs — 14 tests
test a_multi_signature_release_stays_inside_its_ceiling ... ok
test payout_cost_grows_with_the_reviewer_count ... ok
test a_baseline_records_one_payout_case_per_reviewer_count ... ok
test a_key_in_the_wrong_tier_is_a_failure - should panic ... ok
# tests/budget_and_storage.rs — 12 tests
test funds_are_released_only_at_the_reviewer_threshold ... ok
test any_threshold_inside_the_reviewer_set_always_releases ... ok
test every_generated_host_error_is_recoverable_around_a_rejected_action ... ok
# tests/property.rs — 9 tests
48 tests in the package, and all of them inside cargo test --workspace --locked.
The payout benchmark prints its table with --nocapture:
cargo test -p soroban-testkit-example-bounty-escrow payout_cost_grows_with_the_reviewer_count -- --nocapture
reviewers= 1 cpu_insns=… mem_bytes=…
reviewers= 2 cpu_insns=… mem_bytes=…
reviewers= 3 cpu_insns=… mem_bytes=…
reviewers= 5 cpu_insns=… mem_bytes=…
reviewers= 7 cpu_insns=… mem_bytes=…
Where to go next
Budget-Aware Testing
Ceilings, baselines and the parseable failure line this suite's guards use.
soroban-testkit-generators
host_error_code_coverage() and every other strategy this package draws from.
Worked Example: Vesting Escrow
A token vesting escrow with a cliff and linear unlock: an admin locks a grant, a
beneficiary claims vested tokens over time, and the admin may revoke the
unvested portion at any moment. Everything here is real code in
examples/vesting_escrow,
a workspace member you can run.
The contract
One #![no_std] contract holds every schedule in a persistent map and the next
id in instance storage. A schedule is Active until it is either fully claimed
(Completed) or revoked (Revoked):
Active ──claim──▶ Active (until fully claimed) ──▶ Completed
│
└──revoke──▶ Revoked (vested remainder stays claimable)
#![allow(unused)]
fn main() {
#[contracttype]
pub enum ScheduleStatus { Active, Revoked, Completed }
pub fn create_schedule(
env: Env, admin: Address, beneficiary: Address, token: Address,
total_amount: i128, start: u64, cliff_duration: u64, duration: u64,
revocable: bool,
) -> u64;
pub fn claim(env: Env, id: u64) -> i128;
pub fn revoke(env: Env, id: u64) -> i128;
}
Vesting is zero until the cliff, then linear over the full duration:
#![allow(unused)]
fn main() {
fn vested_at(schedule: &VestingSchedule, now: u64) -> i128 {
if now < schedule.start { return 0; }
let elapsed = now - schedule.start;
if elapsed < schedule.cliff_duration { return 0; }
if elapsed >= schedule.duration { return schedule.total_amount; }
schedule.total_amount * elapsed as i128 / schedule.duration as i128
}
}
Revocation freezes the vested cap at the revocation timestamp and returns only the unvested portion to the admin; the beneficiary keeps claiming what had already vested.
Tests
tests/fixtures.rs— 10 tests: creation locks tokens, sequential ids, cliff boundary, linear quarters, claim payout, accrual, revocation freeze, and non-revocable / fully-vested rejection.tests/assert_events.rs— 8 tests: event payloads,EventLogordering, and authorization matching forcreate_schedule,claim, andrevoke.tests/budget_and_storage.rs— 10 tests: ceilings, tier placement, and the committedbudget.jsonbaseline.tests/property.rs— 3 proptests: the conservation invariantclaimed + claimable + unvested + returned == total, monotonic vesting, and claims never exceeding the vested amount.
Worked Example: Decentralized Escrow with Arbiter Dispute Resolution
A milestone-based escrow contract with third-party arbiter dispute resolution: a buyer funds the escrow for a seller across multiple milestones, the buyer (or designated arbiter) approves milestone releases upon satisfactory delivery, either party can raise a formal dispute to freeze payouts, and the arbiter can resolve the dispute with arbitrary split payouts or the buyer can claim a timeout refund.
Everything here is real code in examples/escrow, a workspace member you can run.
Architecture and State Machine
The contract is #![no_std] and manages an escrow agreement between three parties: Buyer, Seller, and Arbiter.
┌───────────┐
│ Active │◀──────────────────┐
└─────┬─────┘ │
│ │
┌──────┴──────┐ │
▼ ▼ │
┌───────────┐ ┌───────────┐ │
│ Completed │ │ Disputed ├────────────┘
└───────────┘ └─────┬─────┘ (milestone approval)
│
┌───────┴───────┐
▼ ▼
┌───────────┐ ┌───────────┐
│ Resolved │ │ Refunded │
└───────────┘ └───────────┘
Storage Model
- Instance Storage:
DataKey::Config: The immutable parties, total allocation, deposited amount, released amount, timeout ledger, and status.DataKey::MilestoneIds: Vector of registered milestone IDs.
- Persistent Storage:
DataKey::Milestone(u32): Independent milestone record with description, amount, andMilestoneStatus(Pending,Approved,Released).
Testing Across All Four Testkit Crates
The test suite in examples/escrow demonstrates how each Testkit crate provides dedicated superpowers:
1. soroban-testkit-fixtures (tests/fixtures_tests.rs)
Manages multi-identity fixtures (buyer, seller, arbiter, attacker), deploys mock Stellar asset tokens, and controls ledger progression:
#![allow(unused)]
fn main() {
let mut fix = EscrowFixture::new(10_000, 500);
fix.client.deposit(&fix.buyer, &10_000);
// Advance mock ledger past expiration sequence
fix.ctx.advance_ledger(501);
let refunded = fix.client.claim_refund(&fix.buyer);
assert_eq!(refunded, 10_000);
assert_eq!(fix.client.get_status(), EscrowStatus::Refunded);
}
2. soroban-testkit-assert (tests/assert_tests.rs)
Asserts emitted contract events and verifies strict mathematical token conservation across all parties:
#![allow(unused)]
fn main() {
// Initial total tokens must strictly equal final total tokens
assert_eq!(
initial_buyer + initial_seller,
final_buyer + final_seller + contract_balance
);
assert_eq!(contract_balance, 0);
}
3. soroban-testkit-core (tests/budget_and_storage.rs)
Meters CPU instructions, memory bytes, and verifies storage tier isolation (Instance vs Persistent):
#![allow(unused)]
fn main() {
client.initialize(&buyer, &seller, &arbiter, &token, &10_000, &500);
client.add_milestone(&buyer, &1, &Symbol::new(&env, "m1"), &5_000);
let budget = BudgetSnapshot::last_invocation(&env);
assert!(budget.cpu_insns > 0);
let storage = StorageSnapshot::capture(&env, &contract);
let persistent_entries = storage.entries_in(StorageTier::Persistent);
assert_eq!(persistent_entries.len(), 1);
}
4. soroban-testkit-generators (tests/property_tests.rs)
Property-based invariants running hundreds of generated scenarios with proptest!:
#![allow(unused)]
fn main() {
proptest! {
#[test]
fn prop_unauthorized_parties_cannot_claim_or_release(
total in 1_000i128..=100_000,
milestone_amt in 100i128..=500,
) {
// Invariant: Attackers can never approve milestones, resolve disputes, or claim refunds
let res_approve = client.try_approve_milestone(&attacker, &1);
prop_assert_eq!(res_approve, Err(Ok(EscrowError::Unauthorized)));
}
}
}
Running the Suite
cargo test -p soroban-testkit-example-escrow
Multisig Vault Worked Example
This guide walks through examples/multisig_vault, a time-delayed M-of-N
treasury vault that demonstrates every crate in the Testkit workspace.
What the Vault Does
The vault holds a balance and requires two independent conditions before any withdrawal can be executed:
- Threshold — at least
thresholdof the configuredsignersmust approve the proposal. - Timelock — once the threshold is reached the proposal is queued, and it
cannot execute until
timelockseconds have elapsed. During the delay any signer can cancel the request.
#![allow(unused)]
fn main() {
use multisig_vault::{MultisigVault, MultisigVaultClient};
let vault_id = env.register(MultisigVault, ());
let client = MultisigVaultClient::new(&env, &vault_id);
client.initialize(&admin, &signers, &2, &3_600);
client.deposit(&depositor, &10_000);
let proposal_id = client.propose_withdrawal(&signer_a, &recipient, &2_500);
client.approve(&signer_a, &proposal_id);
client.approve(&signer_b, &proposal_id); // threshold reached, proposal queued
env.ledger().set_timestamp(env.ledger().timestamp() + 3_600);
client.execute(&signer_a, &proposal_id);
}
Contract Surface
| Function | Purpose |
|---|---|
initialize | Stores signers, threshold, timelock and starts the balance at zero |
deposit | Requires the depositor’s auth and credits the vault |
propose_withdrawal | Signer-only; validates amount against the balance |
approve | Records a unique signer approval; queues the proposal at threshold |
execute | Requires threshold + timelock + sufficient balance |
cancel | Any signer may veto a proposal until it executes |
balance, threshold, timelock, signers, proposal, next_proposal_id | Read-only getters |
Failures are returned as typed VaultError values, so tests can assert exact
error causes rather than matching panic strings. State changes emit typed
contract events (WithdrawalProposed, WithdrawalApproved,
WithdrawalExecuted, WithdrawalCancelled).
Storage uses the typed DataKey enum (DataKey::Signers,
DataKey::Proposal(u64), and so on) so that the vault’s keys are namespaced and
auditable.
Test Layout
The suite is split across four files under examples/multisig_vault/tests and
contains more than 30 tests:
| File | Focus |
|---|---|
fixtures.rs | Initialization, deposits, proposal creation, approvals and validation errors |
assert.rs | Event and authorization assertions, timelock rejection, execution and cancellation |
budget_storage.rs | Budget snapshots, network profiles, namespace auditing and fee estimates |
proptest.rs | Property tests proving funds cannot leave without threshold + delay |
A shared tests/common/mod.rs builds a Fixture that registers the contract,
generates signers and exposes helpers for funding, proposing, approving and
advancing ledger time.
Fixtures and Setup
#![allow(unused)]
fn main() {
use soroban_testkit_fixtures::builder::TestContextBuilder;
use soroban_testkit_fixtures::NetworkProfile;
let ctx = TestContextBuilder::new()
.with_network_profile(NetworkProfile::Local)
.with_users(2)
.build();
}
Local keeps the host unmetered for fast iteration. Swap in
NetworkProfile::Testnet or NetworkProfile::Mainnet to enforce real resource
ceilings and ledger parameters without changing the test body.
Authorization and Event Assertions
#![allow(unused)]
fn main() {
use soroban_testkit_assert::auth::AuthMatcher;
use soroban_testkit_assert::events::EventMatcher;
fixture.fund(1_000);
EventMatcher::new(&fixture.ctx.env).assert_count(1);
AuthMatcher::new(&fixture.ctx.env).assert_auth_count(1);
}
Budget and Storage Inspection
#![allow(unused)]
fn main() {
use soroban_testkit_core::budget::BudgetSnapshot;
use soroban_testkit_core::namespace_auditor::NamespaceAuditor;
let before = BudgetSnapshot::capture(&ctx.env.host().budget_cloned());
client.execute(&signer, &proposal_id);
let after = BudgetSnapshot::capture(&ctx.env.host().budget_cloned());
let cost = before.diff(&after);
let mut auditor = NamespaceAuditor::default();
auditor.record("multisig_vault", "DataKey::Signers");
assert!(!auditor.audit().has_collisions());
}
Property Tests
#![allow(unused)]
fn main() {
proptest! {
#[test]
fn funds_never_leave_without_threshold(amount in withdrawal_amount()) {
let fixture = Fixture::funded();
let proposal_id = fixture.propose(amount);
fixture.advance_time(TIMELOCK);
let result = fixture.client().try_execute(&fixture.signers[0], &proposal_id);
prop_assert_eq!(result.unwrap_err().unwrap(), VaultError::ThresholdNotMet);
prop_assert_eq!(fixture.client().balance(), INITIAL_BALANCE);
}
}
}
The property suite also covers premature execution, exact balance accounting,
cancelled proposals, duplicate approvals, ready_at computation, and monotonic
proposal IDs. Amounts are produced with
soroban_testkit_generators::strategies::token_amount().
Running the Example
From the repository root:
cargo test -p multisig-vault
cargo clippy -p multisig-vault --all-targets -- -D warnings
Because examples/multisig_vault is a workspace member, the top-level commands
exercise it too:
cargo test --workspace
cargo clippy --workspace --all-targets --locked -- -D warnings
Guardian-Protected Multisig Treasury
examples/guardian_treasury is a #![no_std] treasury demonstrating M-of-N
withdrawal approvals with a separate Guardian veto role. The proposal’s
timelock begins when the approval threshold is reached. Only the configured
Guardian may veto, and only before the deadline; once vetoed, the proposal
cannot be executed. A signer still needs to satisfy the threshold and wait for
the delay before execution.
The example tracks treasury funds as an internal balance so the authorization, proposal, veto and accounting workflow can be tested independently. It does not implement a production token custody or recovery mechanism.
Workflow
#![allow(unused)]
fn main() {
let treasury_id = env.register(GuardianTreasury, ());
let treasury = GuardianTreasuryClient::new(&env, &treasury_id);
treasury.initialize(&admin, &signers, &2, &3_600, &guardian);
treasury.deposit(&depositor, &10_000);
let id = treasury.propose(&signer_a, &recipient, &2_500);
treasury.approve(&signer_a, &id);
treasury.approve(&signer_b, &id); // starts the delay window
treasury.veto(&guardian, &id); // optional, only before ready_at
}
If the Guardian does not veto, a signer can execute after the deadline. The contract emits typed events for initialization, deposits, proposals, approvals, vetoes and execution. All proposals are persistent entries and the active configuration and balance are instance data.
Test layout
The four dedicated suites provide over 30 tests:
fixtures.rs: initialization validation, deposits, proposals and IDs.assert.rs: guardian authority, veto timing, threshold enforcement, timelock execution, events and auth assertions.budget_storage.rs: instruction baselines, storage tiers and budget checks.proptest.rs: properties proving vetoed proposals never execute and never debit funds, and that execution respects threshold and time.
The example uses Testkit fixtures for isolated environments, Testkit assert helpers for contract/auth/event assertions, Testkit core for instruction and storage accounting, and Testkit generators for randomized amounts.
Budget baselines
examples/guardian_treasury/budget.json records guardian-veto and execution
costs. Verify them with:
cargo test -p guardian-treasury --test budget_storage
Regenerate the measurements deliberately with:
cargo test -p guardian-treasury --test budget_storage -- --ignored record_budget_baseline
Flash Mint & Token Burn Worked Example
This guide walks through examples/flash_mint, an ERC-3156 / SEP-style Flash Mint token contract that demonstrates cross-contract callback handling, atomic token burning, and comprehensive testing across all four crates in the Testkit workspace.
What Flash Minting Does
Flash minting allows a borrower contract to temporarily mint unbacked tokens within a single transaction, under the strict mathematical condition that the exact borrowed principal plus an optional protocol fee is returned and burned before invocation completion.
If the borrower fails to execute the callback successfully, returns the wrong magic symbol, or lacks sufficient funds to cover the principal and fee, the entire transaction rolls back atomically.
#![allow(unused)]
fn main() {
use soroban_testkit_example_flash_mint::{FlashMintToken, FlashMintTokenClient};
let token_id = env.register(FlashMintToken, ());
let client = FlashMintTokenClient::new(&env, &token_id);
client.initialize(&admin, &treasury, &10, &1_000_000); // 10 bps fee, 1M max borrow
// Executes callback on receiver, verifies repayment, burns principal, and collects fee
client.flash_loan(&receiver_contract_id, &token_id, &250_000, &Bytes::new(&env));
}
Protocol Architecture
The protocol adheres to standard flash lending conventions:
- Borrow Limit Check: Asserts
0 < amount <= max_flash_loanand checks that the contract is not paused. - Reentrancy Protection: Employs a reentrancy lock in temporary storage to prevent recursive reentrant calls during the borrower callback.
- Optimistic Minting: Mints
amounttokens toreceiver. - Cross-Contract Callback: Calls
receiver.on_flash_loan(initiator, token, amount, fee, data). The borrower must returnsymbol_short!("success"). - Atomic Repayment & Burn: The contract verifies that
receiverhas at leastamount + feetokens, burns the borrowedamount, and transfersfeeto the treasury. - Supply Invariance: Asserts that
total_supplyafter repayment is identical to initial supply before the flash mint.
Error Conditions
| Error | Cause |
|---|---|
Paused | Contract is paused by admin |
ZeroAmount | Requested borrow amount is zero or negative |
ExceedsMaxFlashLoan | Amount exceeds configured ceiling |
InvalidToken | Token parameter does not match the Flash Mint contract address |
CallbackFailed | Borrower callback reverted or returned unexpected symbol |
DeficitAfterFlashMint | Borrower spent the borrowed funds without returning them |
ReentrancyGuard | Recursive flash loan invocation attempted during callback |
Test Suite Structure
The test suite in examples/flash_mint/tests is organized into 4 dedicated test files exercising all 4 Testkit crates:
examples/flash_mint/tests/
├── fixtures.rs # soroban-testkit-fixtures: TestContext, limits, fees, congestion
├── assert_events_and_auth.rs # soroban-testkit-assert: EventMatcher, EventLog, failure rollbacks
├── budget_and_storage.rs # soroban-testkit-core: BudgetGuard, StorageSnapshot, quotas & fragmentation
└── property.rs # proptest & generators: Total supply invariants and fee scaling
1. Fixtures (tests/fixtures.rs)
Exercises soroban-testkit-fixtures:
- Sets up test environments with
TestContextandTestContextBuilder. - Configures fee basis points and verifies fee calculations across various amounts.
- Tests borrow limit enforcement and pause/unpause toggles.
- Emulates network queue latency using
CongestionSimulator.
2. Event and Auth Assertions (tests/assert_events_and_auth.rs)
Exercises soroban-testkit-assert:
EventMatcherasserts emission offlash_mnt,mint,burn, andfee_paidevents.EventLogtracks event sequences across multiple sequential flash loans.- Tests transaction rollback on
CallbackFailedandDeficitAfterFlashMint. - Validates reentrancy protection against recursive borrowers.
3. Budget and Storage Verification (tests/budget_and_storage.rs)
Exercises soroban-testkit-core:
BudgetGuardandBudgetSnapshotmeasure CPU instruction and memory consumption.StorageSnapshotvalidates atomic storage invariance before and after a flash loan.assert_storage_tier_count!verifies entry quotas across instance, persistent, and temporary tiers.StorageFragmentationAnalyzerinspects storage layout for serialization efficiency.
4. Property Testing (tests/property.rs)
Uses proptest to test protocol invariants:
- Total Supply Invariant: Verifies that for any arbitrary borrow amount,
total_supplybefore and after the flash mint is strictly identical. - Fee Scaling Invariant: Verifies that fee computation matches mathematical expectations across all inputs.
- Bound Enforcing: Proves that requested amounts exceeding
max_flash_loanare consistently rejected.
Worked Example: Flash Loan Provider and Receiver
The examples/flash_loan
crate is a flash loan market in two #![no_std] contracts:
FlashLoanProviderholds liquidity in any number of Stellar Asset Contract tokens. It lends to a receiver contract, calls it back, and then checks its own balance. If the balance has not grown by at least the fee, it returns an error and the host reverts the whole invocation, including the principal transfer. Fees are attributed per token and per borrower.FlashLoanReceiveris a configurable borrower. ItsRepayMode(Full,ShortBy(n),PrincipalOnly,Reject) drives every failure path the tests need.
The suite spreads 33 tests over four files, one per testkit crate.
The loan, step by step
borrower ──flash_loan──▶ provider ──transfer(amount)──▶ receiver
│ │
│◀── on_flash_loan(fee) ───────┤
│◀── transfer(amount + fee) ───┘
└─ balance ≥ before + fee ? record fee : Err(RepaymentShort)
compute_fee(amount, bps)rounds up, so a positive loan is free only when the rate is zero. The rate is capped atMAX_FEE_BPS(10%).flash_loan_multilends several tokens at once, with one callback and a repayment check per token. Duplicate tokens and mismatched lists are refused.- No reentrancy lock is needed, because the Soroban host never lets a contract re-enter itself.
tests/fixtures.rs: soroban-testkit-fixtures
The market is built on a TestContext, and TestContextBuilder::with_users(2)
supplies two borrowers. That makes it possible to check that fees land on the
right borrower and token:
let ctx = TestContextBuilder::new().with_users(2).build();
let market = Market::on(ctx.env.clone());
let a1 = lender.flash_loan(ctx.user(0), &market.receiver, &market.tokens[0], &100_000, &data);
let b1 = lender.flash_loan(ctx.user(1), &market.receiver, &market.tokens[0], &300_000, &data);
assert_eq!(lender.fees_collected(&market.tokens[0]), a1 + b1);
This file also covers fee rounding (flash_fee(10_001) == 10 at 9 bps), deposits,
multi-token fees, invalid amounts, unlisted tokens, insufficient liquidity, and
admin configuration.
tests/assert.rs: soroban-testkit-assert
Rollback. Repaying one stroop short, returning only the principal, refusing the callback, or coming up short on one leg of a multi-token loan all fail with an exact error, and every balance, fee counter, and loan counter is back where it started:
market.set_mode(RepayMode::ShortBy(1));
assert_contract_error!(try_borrow(&market, 1_000_000), FlashLoanError::RepaymentShort);
assert_rolled_back(&market);
Propagated errors. A receiver that does not trust the lender panics with
ReceiverError::UnknownLender. The error reaches the test with the
receiver’s code, so it is checked with assert_host_error!.
Events. EventMatcher finds the provider’s flash event, and
assert_event_topic_count! counts the two token transfers (principal out,
repayment in).
Sub-invocation authorization. The borrower signs only the root call:
market.lender().mock_auths(&[MockAuth {
address: &market.borrower,
invoke: &MockAuthInvoke {
contract: &market.provider,
fn_name: "flash_loan",
args: (borrower, receiver, token, amount, data).into_val(env),
sub_invokes: &[],
},
}]).flash_loan(/* ... */);
No nested entries are needed:
- the principal leaves the provider’s own balance
- the receiver authenticates the provider as its direct caller (
provider.require_auth()) - the repayment leaves the receiver’s own balance
Without the borrower’s signature, the loan is refused.
tests/budget_and_storage.rs: soroban-testkit-core
Single-token and two-token loans are measured with
BudgetSnapshot::last_invocation. The measurements are compared against the
committed examples/flash_loan/budget.json
with a 10% tolerance, and the single loan also runs under a BudgetGuard
ceiling. After an SDK bump, re-record the baseline with:
cargo test -p soroban-testkit-example-flash-loan -- --ignored budget_baseline_records_current_costs
StorageSnapshot diffs show the storage footprint:
- a first loan adds exactly two persistent entries (
FeesCollected,BorrowerFees) and one instance entry (LoanCount) - a returning borrower rewrites those entries in place
- a failed loan leaves provider storage untouched
assert_storage_tier_count! keeps the provider free of temporary state.
tests/property.rs: soroban-testkit-generators
token_amount() and basis_points() drive proptest over the fee function:
- the fee is the exact ceiling of
amount × bps / 10_000 - it is monotonic in the amount, never exceeds the principal, and is zero only at a zero rate
- negative amounts and overflowing products return
Noneinstead of wrapping
End to end, every affordable loan grows the pool by exactly its fee, any shortfall rolls back, and per-borrower fees always add up to the token total.
Running it
cargo test -p soroban-testkit-example-flash-loan
cargo clippy --workspace --all-targets --locked -- -D warnings
Worked Example: Crowdfunding and Milestone Escrow
The examples/crowdfunding workspace member models a campaign funded with a
SEP-41 asset. A creator sets a funding goal and deadline, backers contribute
before the deadline, and the creator can release the raised funds in milestone
tranches after the goal is reached. If the deadline passes below goal, the
campaign is finalized as failed and each backer can claim their recorded
contribution once.
Invariants covered
- Contributions move tokens into escrow and update both the campaign total and the backer’s recorded amount.
- The creator release method rejects a campaign whose goal was not met.
- A failed campaign only returns the caller’s recorded contribution; claiming zeroes that record, preventing a second withdrawal.
- Proptest varies amounts and goals to check that a creator cannot release funds from a failed campaign.
The integration suite is split into fixture, behavior assertions, budget/storage, and property-test files. The batch refund benchmark builds a multi-backer campaign and bounds host CPU cost for the batch setup; actual refund claims remain individually authorized calls.
Run the example with cargo test -p soroban-testkit-example-crowdfunding.
Worked Example: Yield-Bearing Liquid Staking
The examples/liquid_staking workspace member keeps shares fixed while
staking yield raises the amount of underlying asset represented by each share.
Depositors receive shares at the current exchange rate; redemption burns shares
and transfers the corresponding pro-rata underlying amount. Integer division
uses checked multiplication before division so intermediate overflow is
reported instead of silently wrapping.
Invariants covered
- Initial deposits mint shares one-to-one with underlying units.
- Yield increases total assets without minting shares, so the exchange rate rises over time.
- A redemption removes the proportional share of assets and updates both supply and the holder’s balance.
- Proptest accrues a positive random yield and verifies redemption value never decreases as yield accumulates.
The integration tests are split into fixtures, behavior assertions, budget/storage checks, and property tests. The exchange-rate gas check uses a committed CPU ceiling to catch accidental growth in this simple calculation.
Run the example with cargo test -p soroban-testkit-example-liquid-staking.
Worked Example: Staking and Yield Farming
examples/staking is a staking pool with a reward stream funded separately from
the principal: stakers deposit a token, the distributor pays a fixed number of
reward stroops per second for the whole pool, and each staker’s share accrues in
proportion to their stake. It exists to show the two things a staking contract
gets wrong — the reward accumulator and the exit — under test.
The contract keeps one accumulator, reward stroops per staked stroop scaled by
SCALE (1e12), and each position remembers the accumulator value it was last
paid against. A claim is therefore
amount * (pool.reward_per_token - position.reward_per_token_paid) / SCALE
which is why every stake, unstake and claim settles the accumulator before
it touches a position: a deposit that skipped that step would retroactively earn
the rewards that accrued while it was not in the pool.
What the contract does
| Call | Behaviour |
|---|---|
initialize(admin, stake_token, reward_token, reward_rate) | One pool, one admin, no second initialization |
stake(owner, amount) | Settles, transfers in, records the position, restarts the lock |
unstake(owner, amount) | Settles, pays the principal (minus a penalty inside the lock) |
claim(owner) | Pays the settled reward and resets it |
emergency_withdraw(owner) | Paused-only full exit; forfeits unsettled rewards |
set_reward_rate(rate) | Settles at the old rate, then changes it |
set_paused(bool) | Refuses new stakes; never blocks exits |
earned(owner) | A view: settled rewards plus what has accrued since |
- Rewards accrue from the ledger timestamp, so
advance_timein the fixture moves the clock the contract reads. - A withdrawal before
MIN_LOCK_SECONDS(seven days) paysEARLY_EXIT_PENALTY_BPS(10%) of the withdrawn amount to the admin, taken from principal. - An empty pool advances its timestamp without paying anybody, so an idle window is not handed to the next staker.
- Rewards live in the contract, minted by the distributor: a claim larger than the balance is a configuration bug and the transfer fails rather than minting.
The five test files
| File | What it covers |
|---|---|
tests/common/mod.rs | The fixture: two funded stakers, a funded reward pool, advance_time |
tests/fixtures.rs | Deposits, top-ups, partial and full exits, penalties, claims, reward splits, rate changes |
tests/assert.rs | The explicit MockAuth tree, refusals, paused behaviour, emergency exit, the idle window |
tests/budget_storage.rs | Budget ceilings for stake and claim, a view measuring less than a write, instance vs persistent storage, storage diffs, a baseline round trip |
tests/proptest.rs | Principal survival, penalty exactness, reward conservation across two stakers, monotonic views |
cargo test -p soroban-testkit-example-staking
The properties that matter
#![allow(unused)]
fn main() {
proptest! {
#[test]
fn two_stakers_share_the_stream_without_creating_value(
alice in 1i128..=1_000 * ONE,
bob in 1i128..=1_000 * ONE,
seconds in 1u64..=1_000,
) {
let fixture = Fixture::new();
fixture.client().stake(&fixture.alice, &alice);
fixture.client().stake(&fixture.bob, &bob);
fixture.advance_time(seconds);
let total = fixture.client().earned(&fixture.alice)
+ fixture.client().earned(&fixture.bob);
let stream = 1_000 * seconds as i128;
prop_assert!(total <= stream);
prop_assert!(stream - total <= 2); // one stroop lost per floor division
}
}
}
The <= 2 is the point of the example: two integer divisions round down, so the
pool can keep at most one stroop per staker, and a test that allowed more would
hide a real leak. The same style of property pins the early exit
(returned + penalty == amount) and a full round trip (staked == 0,
total_staked == 0, principal returned exactly).
Storage and cost
The pool lives in one instance entry and each staker in one persistent entry, so a first stake adds exactly one key and a top-up rewrites two values without adding any:
#![allow(unused)]
fn main() {
let diff = before.diff(&after);
assert_eq!(diff.added().len(), 0);
assert_eq!(diff.modified().len(), 2);
}
budget_guard! holds stake and claim under a transaction ceiling, and a view
is measured against a write to show that earned costs less than the claim
that pays the same number — the difference is the transfer and the two storage
writes, not the arithmetic.
Synthetic Asset & CDP Worked Example
This guide walks through examples/cdp, a protocol that mints a synthetic US dollar (sUSD) against XLM collateral. A user locks collateral in a collateralized debt position (CDP), borrows sUSD against it while staying above a minimum collateralization ratio (MCR), pays a stability fee on outstanding debt, and is liquidated if a price drop pushes them below the MCR.
The protocol needs several contracts working together, which makes it a good test of everything Testkit offers. The suite has 47 tests across 4 files and uses all four workspace crates.
The contracts
| Contract | Module | Role |
|---|---|---|
| Collateral token | Stellar Asset Contract (tests) | XLM, locked into and released from the engine |
PriceOracle | oracle.rs | Admin-fed USD price of the collateral, stamped with the ledger time |
SyntheticToken | synth.rs | sUSD. Only its minter, the engine, can mint or burn |
CdpEngine | engine.rs | Holds collateral, issues and tracks debt, accrues fees, liquidates |
All three are #![no_std]. Each lives in its own module so the generated clients and contract specs never collide. A deployment builds each one as a separate WASM.
#![allow(unused)]
fn main() {
use soroban_testkit_example_cdp::*;
let collateral = env.register_stellar_asset_contract_v2(admin.clone()).address();
let oracle_id = env.register(PriceOracle, ());
let synth_id = env.register(SyntheticToken, ());
let engine_id = env.register(CdpEngine, ());
PriceOracleClient::new(&env, &oracle_id).initialize(&admin);
SyntheticTokenClient::new(&env, &synth_id).initialize(&engine_id); // engine is the minter
CdpEngineClient::new(&env, &engine_id).initialize(&CdpConfig {
admin: admin.clone(),
collateral_token: collateral.clone(),
synth_token: synth_id.clone(),
oracle: oracle_id.clone(),
mcr_bps: 15_000, // 150% minimum collateralization ratio
liquidation_penalty_bps: 1_000, // 10% bonus to the liquidator
stability_fee_bps: 200, // 2% a year on outstanding debt
max_price_age: 3_600, // refuse prices older than an hour
});
}
Protocol mechanics
Prices are USD per collateral unit, scaled by PRICE_SCALE = 10_000_000 (7 decimals, like Stellar assets). Ratios and rates are in basis points.
| Operation | Who signs | What happens |
|---|---|---|
deposit(owner, amount) | owner | XLM moves owner → engine. The position’s collateral grows |
borrow(owner, amount) | owner | Fails with BelowMinCollateralRatio unless collateral × price ≥ (debt + amount) × MCR. Otherwise the engine has sUSD mint amount to the owner |
repay(owner, amount) | owner | The engine burns amount of the owner’s sUSD and reduces the debt |
withdraw(owner, amount) | owner | XLM moves engine → owner, provided an indebted position stays at or above the MCR |
liquidate(liquidator, owner) | liquidator | Only below the MCR. The liquidator burns the whole debt and receives collateral worth debt × (1 + penalty), capped at what the position holds |
accrue(owner) | anyone | Adds the stability fee accrued so far to the debt |
MCR checks never round in the borrower’s favour. is_healthy compares collateral × price × 10_000 ≥ debt × MCR × PRICE_SCALE by cross-multiplying, so a position a hair below 150% is never truncated up to exactly 150%.
Stability fee. Debt grows by simple interest, debt × fee_bps × elapsed / (10_000 × 31_536_000), and the fee is folded in whenever the position is touched. The accrual clock only moves when at least one whole unit of fee was added, so a small position touched often still pays. Fees are owed but never minted, so total_debt − sUSD total_supply is exactly the fee revenue accrued so far.
Liquidation. At a $0.08 price, 10,000 XLM ($800) backing 600 sUSD sits at 133%, below the MCR. A liquidator burns 600 sUSD and receives $660 of XLM (8,250 XLM). The owner keeps the 600 sUSD they borrowed and can withdraw the remaining 1,750 XLM. If the collateral is worth less than the debt, the liquidator takes all of it and the position is closed.
Error conditions
| Error | Cause |
|---|---|
AlreadyInitialized / NotInitialized | Engine initialized twice / used before initialization |
InvalidParameter | MCR ≤ 100%, penalty or fee > 100%, or a zero max_price_age |
InvalidAmount | Zero or negative amount |
NoPosition | Borrow, repay, withdraw or liquidate against an owner with no position |
InsufficientCollateral | Withdrawing more than the position holds |
BelowMinCollateralRatio | A borrow or withdrawal would leave the position below the MCR |
ExceedsDebt | Repaying more than is owed |
NotLiquidatable | Liquidating a position at or above the MCR, or with no debt |
PriceUnavailable / StalePrice | Oracle has no price / price is older than max_price_age |
InsufficientSynth | Repayer or liquidator lacks the sUSD to burn |
Test suite structure
examples/cdp/tests/
├── common/mod.rs # the `Cdp` fixture: deploys and wires all four contracts
├── fixtures.rs # soroban-testkit-fixtures — lifecycle, MCR, fees, oracle, liquidation (22 tests)
├── assert.rs # soroban-testkit-assert — events, auth, balance conservation (11 tests)
├── budget_storage.rs # soroban-testkit-core — liquidation gas benchmark, budgets, storage (8 tests)
└── proptest.rs # soroban-testkit-generators + proptest — MCR invariants (6 properties)
The Cdp fixture (tests/common/mod.rs)
Built on TestContextBuilder::new().with_users(3): the owner, a liquidator, and a second independent borrower. Cdp::new() deploys everything, publishes a $0.10 price, and funds each user with 1,000,000 XLM. Helpers keep the tests readable:
#![allow(unused)]
fn main() {
let mut cdp = Cdp::new();
cdp.open(&cdp.owner, 10_000 * ONE, 600 * ONE); // deposit + borrow
cdp.arm_liquidator(600 * ONE); // liquidator opens a safe CDP for sUSD
cdp.crash_price(20); // oracle drops 20%
cdp.advance_time(YEAR); // TestContext::advance_time + oracle refresh
cdp.advance_time_without_oracle(3_601); // let the price go stale
}
1. Fixtures (tests/fixtures.rs)
Drives the whole lifecycle and pins exact numbers: a 600 sUSD borrow against $1,000 is a 16,666 bps ratio. max_borrow is exactly 666.6666666 sUSD, and one more stroop fails. A year at 2% turns 600 sUSD of debt into 612. Half a year leaves 6 sUSD of fees after repaying the principal. A 10% fee pushes a max-borrowed position below the MCR within a month. A stale or missing price blocks borrowing. A liquidator without enough sUSD is rejected, and nothing about the position changes.
2. Assertions (tests/assert.rs)
This is where the new event count range macros are useful. Once time has passed, a borrow emits an extra fee event, so the same call publishes two events at t = 0 and three a year later. An exact assert_count(2) would break. A range states what the test really depends on:
#![allow(unused)]
fn main() {
cdp.engine().borrow(&cdp.owner, &(100 * ONE));
assert_event_count_range!(env, 2..=3);
assert_event_topic_count!(env, "fee", 0);
cdp.advance_time(YEAR);
cdp.engine().borrow(&cdp.owner, &(100 * ONE));
assert_event_count_range!(env, 2..=3); // still holds
assert_event_topic_count!(env, "fee", 1); // the auxiliary event appeared
}
from = … restricts a count to one contract, which matters when several contracts emit a transfer topic:
#![allow(unused)]
fn main() {
cdp.engine().liquidate(&cdp.liquidator, &cdp.owner);
assert_event_topic_count!(env, from = cdp.engine_id, "liquidate", 1);
assert_event_topic_count!(env, from = cdp.synth_id, "burn", 1);
assert_event_topic_count!(env, from = cdp.collateral, "transfer", 1);
}
The macros also accept an EventLog, so one assertion can cover a whole deposit → borrow → borrow → repay → withdraw lifecycle (assert_event_topic_count!(log, from = cdp.synth_id, "mint", 2)). Other tests in this file read the liquidate payload with assert_data_matches, check signers with assert_auth_matches! (including argument patterns like args: [_, 100 * ONE]), and use assert_balance_conserved! to show that a liquidation only moves XLM between engine and liquidator and that a borrow mints exactly the requested sUSD.
3. Budget & storage (tests/budget_storage.rs)
Liquidation gas benchmark. A position opened at 160% is liquidated after price drops of 10%, 30%, 45%, 60%, and 90%, each under a BudgetGuard with CPU and memory ceilings. The test prints a table (cargo test -p soroban-testkit-example-cdp --test budget_storage -- --nocapture):
| Price drop | Underwater | Seized (XLM) | Remaining (XLM) | CPU insns | Mem bytes |
|-----------:|:----------:|-------------:|----------------:|----------:|----------:|
| 10% | no | 7638 | 2361 | 387849 | 73771 |
| 30% | no | 9821 | 178 | 387849 | 73771 |
| 45% | yes | 10000 | 0 | 373723 | 71493 |
| 60% | yes | 10000 | 0 | 373723 | 71493 |
| 90% | yes | 10000 | 0 | 373723 | 71493 |
The test asserts that seizures grow with severity, that mild drops leave collateral behind and severe ones exhaust it, and that cost stays within 2× across all severities. Severity changes which branch runs, not how much work is done. An underwater liquidation is slightly cheaper because it deletes the position entry instead of rewriting it. (Exact numbers depend on the SDK version. The assertions do not.)
Storage. StorageSnapshot diffs show that opening a position adds exactly one persistent entry, borrowing rewrites it in place, and closing it (repay + withdraw) removes it. assert_storage_tier_count! pins one persistent entry per owner on the engine and one per holder on sUSD, and a zero balance is deleted rather than stored. StorageFragmentationAnalyzer produces a report over the engine’s storage.
4. Properties (tests/proptest.rs)
Collateral and borrow sizes come from soroban_testkit_generators::strategies::token_amount(), and prices span $0.0001 to $10.
| Property | Invariant |
|---|---|
prop_synthetic_is_never_minted_below_the_mcr | A borrow succeeds if and only if the resulting position is at or above the MCR. A refused borrow mints nothing and records no debt |
prop_borrow_sequences_respect_the_mcr_at_every_step | Across interleaved price moves and borrows, each accepted borrow leaves the position healthy, and supply = debt = sum of accepted borrows |
prop_max_borrow_is_always_mintable | Borrowing exactly max_borrow always succeeds and stays at or above the MCR |
prop_withdraw_never_leaves_a_position_below_the_mcr | A withdrawal succeeds exactly when the position stays healthy |
prop_liquidation_only_below_the_mcr_and_conserves_collateral | Liquidation succeeds exactly below the MCR. Seized + remaining = original collateral, and the liquidator’s gain equals the engine’s loss |
prop_stability_fee_follows_simple_interest | Accrued debt matches the simple-interest formula for any rate (0–20%) and elapsed time (0–5 years) |
Running it
cargo test -p soroban-testkit-example-cdp
cargo test -p soroban-testkit-example-cdp --test budget_storage -- --nocapture # benchmark table
Lending Worked Example
This guide walks through examples/lending, a money market built from four #![no_std] contracts: a collateral vault, a borrowing pool, a simple price oracle, and an internal debt token. A depositor locks a Stellar Asset Contract token, borrows debt tokens within a maximum loan-to-value ratio, watches the position’s health factor move with the oracle price and ledger time, and can be liquidated by a third party.
The suite has 46 running tests across four files and uses all four workspace crates. The contracts are registered natively, which meters the host work without Wasm instantiation; the budget numbers are regression baselines rather than network fee estimates.
The contracts
| Contract | Module | Role |
|---|---|---|
| Collateral token | Stellar Asset Contract (tests) | The asset users deposit and liquidators receive |
LendingOracle | oracle.rs | Admin-fed price with the ledger timestamp it was published at |
DebtToken | debt_token.rs | Internal token minted and burned only by the pool |
CollateralVault | vault.rs | Holds collateral, enforces reserved collateral on withdrawal, allows the pool to seize |
BorrowingPool | pool.rs | Tracks debt, checks LTV, accrues interest, and runs liquidation |
All four live in separate modules so the generated clients and contract specs do not collide. A deployment builds each one as its own Wasm.
#![allow(unused)]
fn main() {
use soroban_testkit_example_lending::*;
let collateral = env.register_stellar_asset_contract_v2(admin.clone()).address();
let oracle_id = env.register(LendingOracle, ());
let debt_id = env.register(DebtToken, ());
let vault_id = env.register(CollateralVault, ());
let pool_id = env.register(BorrowingPool, ());
LendingOracleClient::new(&env, &oracle_id).initialize(&admin);
DebtTokenClient::new(&env, &debt_id).initialize(&pool_id);
CollateralVaultClient::new(&env, &vault_id).initialize(&VaultConfig {
pool: pool_id.clone(),
collateral_token: collateral.clone(),
});
BorrowingPoolClient::new(&env, &pool_id).initialize(&PoolConfig {
admin: admin.clone(),
vault: vault_id,
oracle: oracle_id,
debt_token: debt_id,
max_ltv_bps: 8_000, // borrow up to 80% of collateral value
liquidation_threshold_bps: 11_000, // liquidate below 110% health
liquidation_penalty_bps: 500, // 5% bonus to the liquidator
interest_rate_bps: 500, // 5% simple annual interest
max_price_age: 63_072_000, // roughly two years in this fixture
});
}
Protocol mechanics
Prices are USD per collateral unit scaled by PRICE_SCALE = 10_000_000 (seven decimals, like Stellar assets). Rates and ratios are basis points.
| Operation | Who signs | What happens |
|---|---|---|
deposit(owner, amount) | owner | Collateral moves owner → vault and the position grows |
borrow(owner, amount) | owner | Fails with AboveMaxLtv if debt + amount would exceed 80% of collateral value; otherwise the debt token mints amount to the owner |
withdraw(owner, amount) | owner | Collateral moves vault → owner, provided what remains covers the outstanding debt at the current price |
repay(owner, amount) | owner | Debt tokens are burned and the position’s debt falls |
liquidate(liquidator, owner) | liquidator | Only below the liquidation threshold. The liquidator burns the debt and receives collateral worth debt × 1.05, capped at what the position holds |
accrue(owner) | anyone | Folds accrued interest into the stored debt position |
LTV and health. max_borrow computes collateral × price / PRICE_SCALE × 8_000 / 10_000 − debt. health_factor_bps computes collateral × price × 10_000 / (PRICE_SCALE × debt); a debt-free position reports i128::MAX. With 10,000 collateral at $1 and 6,000 of debt the health factor is 16,666 bps. When the price drops to $0.65 it becomes 10,833 bps, below the 11,000 bps liquidation threshold.
Interest. Debt grows by simple interest, debt × rate_bps × elapsed / (10_000 × 31_536_000). Queries such as debt_of and health_factor include the pending interest without writing it; accrue, borrow, repay, and liquidate fold it into storage and emit an interest event. A year at 5% turns 6,000 of debt into 6,300. Interest is owed but not minted, so debt-token supply still tracks principal.
Liquidation. The pool accrues interest, checks the threshold with a cross-multiplication that never rounds in the borrower’s favour, burns the liquidator’s debt tokens, and asks the vault to seize collateral. The vault only accepts a seize from the pool, so a caller cannot take another user’s collateral directly. If collateral is worth less than the debt plus penalty, the liquidator takes all of it and the position is removed.
Error conditions
| Error | Cause |
|---|---|
NotInitialized / AlreadyInitialized | Contract used before setup / initialized twice |
InvalidAmount | Zero or negative deposit, borrow, repay, withdraw, or seize |
InvalidParameter | LTV at or above 100%, a threshold not above the LTV, or a zero parameter |
NoCollateral / NoPosition | Borrowing without a deposit / mutating a position that does not exist |
AboveMaxLtv | A borrow would exceed the ceiling |
InsufficientCollateral / ReservedCollateral | Withdrawing too much / taking collateral needed for debt |
ExceedsDebt | Repaying more than the position owes |
NotLiquidatable | Liquidating a healthy or debt-free position |
PriceUnavailable / StalePrice | Oracle has no price / its timestamp is older than max_price_age |
InsufficientDebtToken | Liquidator or repayer lacks enough debt tokens to burn |
Test suite structure
examples/lending/tests/
├── common/mod.rs # the `Lending` fixture: deploys and wires all four contracts
├── fixtures.rs # soroban-testkit-fixtures — lifecycle, LTV, interest, oracle, liquidation (19 tests)
├── assert.rs # soroban-testkit-assert — events, auth, balance conservation (10 tests)
├── budget_storage.rs # soroban-testkit-core — baselines, ceilings, storage footprint (10 tests + 1 ignored recorder)
└── proptest.rs # soroban-testkit-generators + proptest — seven properties at 64 cases
The Lending fixture (tests/common/mod.rs)
Built on TestContextBuilder::new().with_users(3): the owner, a keeper who can liquidate, and a second borrower. Lending::new() registers the four contracts, wires them, publishes a $1 price, and funds each actor with 1,000,000 units of collateral.
#![allow(unused)]
fn main() {
let mut lending = Lending::new();
lending.open(&lending.owner, 10_000 * ONE, 6_000 * ONE); // deposit + borrow
lending.arm_liquidator(6_000 * ONE); // keeper opens a safe position
lending.crash_price(35); // oracle publishes a lower price
lending.advance_time(YEAR); // ledger clock + refreshed price
}
advance_time_without_oracle deliberately skips the refresh so staleness can be tested.
1. Fixtures (tests/fixtures.rs)
Drives the whole lifecycle and pins exact numbers. A 10,000-unit deposit supports 8,000 of borrowing at 80% LTV; one stroop more fails. Repayment frees collateral, but until then withdrawal is limited to what the debt does not reserve. A year at 5% makes 6,000 become 6,300, and a fall to $0.65 takes the health factor below the threshold. A third party then repays the debt and receives collateral plus the 5% penalty. Two borrowers keep isolated positions while the vault and pool totals add up.
2. Assertions (tests/assert.rs)
Event counts are scoped to the emitting contract, which matters when a borrow spans the pool’s borrow, the debt token’s mint, and the collateral token’s transfer:
#![allow(unused)]
fn main() {
assert_event_topic_count!(env, from = lending.pool_id, "borrow", 1);
assert_event_topic_count!(env, from = lending.debt_id, "mint", 1);
assert_event_count_range!(env, 2);
}
EventMatcher::assert_data_matches reads what an event carried, including the (debt, seized) pair on liquidate and the interest amount. EventLog collects deposit, two borrows, repayment and withdrawal into one scope. assert_auth_matches! pins the owner on deposit and repay and the liquidator on liquidate. Two assert_balance_conserved! checks show that a liquidation only moves collateral between the vault and the keeper, and that a borrow mints exactly the requested debt-token supply.
3. Budget and storage (tests/budget_storage.rs)
Three hot paths are measured in fresh environments and compared with examples/lending/budget.json:
| Case | CPU instructions | Memory bytes |
|---|---|---|
deposit | 253,201 | 47,248 |
borrow | 222,231 | 50,383 |
liquidate | 481,056 | 97,552 |
The baseline test allows 10% growth and enforces absolute ceilings as well. BudgetGuard::run bounds each user-facing call, BudgetSnapshot::diff compares two invocations, and a read is shown to cost less than a write. Refresh the committed numbers deliberately with:
cargo test -p soroban-testkit-example-lending --test budget_storage -- --ignored budget_baseline_records_current_costs
On the storage side, StorageSnapshot diffs show that a deposit adds one persistent vault entry, a second borrow rewrites the existing pool entry, repayment and withdrawal remove their entries, and an underwater liquidation leaves only the keeper’s positions. assert_storage_tier!, assert_storage_tier_count!, and StorageFragmentationAnalyzer pin where those entries live.
4. Properties (tests/proptest.rs)
Collateral and interest rates come from soroban_testkit_generators::financial, borrow requests from strategies::token_amount(), and prices span $0.0001 to $10. Every property runs 64 cases.
| Property | Invariant |
|---|---|
prop_a_borrow_never_exceeds_the_ltv_ceiling | A borrow succeeds only up to max_borrow; a refused borrow mints nothing |
prop_a_lower_price_never_raises_the_health_factor | A lower oracle price cannot increase health, and the query matches the pure helper |
prop_max_borrow_is_always_safe_to_take | Borrowing exactly the ceiling succeeds and leaves no further capacity |
prop_withdrawal_never_releases_reserved_collateral | A withdrawal succeeds exactly when the remaining collateral still covers the debt |
prop_interest_follows_simple_interest_at_any_rate | Accrued debt matches the simple-interest formula for rates from 0 to 100% and up to five years |
prop_liquidation_only_below_threshold_and_conserves_collateral | Liquidation happens only below the threshold, and the liquidator’s collateral gain equals the vault’s loss |
prop_two_borrowers_have_additive_totals | Two borrowers’ debt, supply, and collateral sum to the protocol totals |
Running it
cargo test -p soroban-testkit-example-lending
cargo clippy -p soroban-testkit-example-lending --all-targets --locked -- -D warnings
Worked Example: Dynamic AMM with Volatility Fees
An Automated Market Maker (AMM) with volatility-adjusted dynamic fees: liquidity providers deposit token pairs, a time-weighted average price (TWAP) accumulator tracks price movement across ledger blocks, and swap fees automatically scale up during periods of high price volatility to protect LPs against impermanent loss and toxic order flow. Everything here is real code in examples/dynamic_amm, a workspace member you can run.
The contract
One #![no_std] contract manages pool reserves, LP shares, TWAP accumulators, and dynamic swap fee calculations.
Deposit A + B ──▶ Mint LP Shares ──▶ Swaps adjust Spot Price ──▶ TWAP accumulates over time ──▶ Dynamic Fee Scales
Constant product & spot price
The pool maintains reserves of two tokens, token_a and token_b. The instantaneous spot price expresses the ratio of reserves scaled to 7 decimals (PRICE_PRECISION = 10_000_000):
#![allow(unused)]
fn main() {
pub fn calculate_spot_price(reserve_a: i128, reserve_b: i128) -> Option<i128> {
if reserve_a <= 0 || reserve_b <= 0 {
return None;
}
reserve_b
.checked_mul(PRICE_PRECISION)?
.checked_div(reserve_a)
}
}
Time-Weighted Average Price (TWAP)
To measure genuine pool trends without being fooled by transient flash loans or single-block manipulation, the pool records a cumulative price accumulator across ledger blocks:
$$\text{price_cumulative} \mathrel{+}= \text{spot_price} \times \Delta t$$
When the elapsed time reaches the configured observation window (twap_window, e.g. 300 seconds), the TWAP is updated:
$$\text{TWAP} = \frac{\Delta \text{price_cumulative}}{\Delta t_{\text{window}}}$$
#![allow(unused)]
fn main() {
let time_elapsed = now.saturating_sub(twap.last_timestamp);
if time_elapsed > 0 && twap.last_spot_price > 0 {
let incremental = twap.last_spot_price * (time_elapsed as i128);
twap.price_cumulative += incremental;
twap.last_timestamp = now;
let window_elapsed = now.saturating_sub(twap.window_start_timestamp);
if window_elapsed >= config.twap_window {
twap.twap_price = (twap.price_cumulative - twap.window_start_price_cumulative)
/ (window_elapsed as i128);
twap.window_start_timestamp = now;
twap.window_start_price_cumulative = twap.price_cumulative;
}
}
}
Volatility-adjusted dynamic fee
When large swaps cause the current spot price to diverge significantly from the historical TWAP, the pool experiences high volatility. The fee scales up with deviation in basis points, strictly clamped between min_fee_bps and max_fee_bps:
#![allow(unused)]
fn main() {
pub fn calculate_dynamic_fee_bps(
spot_price: i128,
twap_price: i128,
base_fee_bps: u32,
min_fee_bps: u32,
max_fee_bps: u32,
volatility_factor: u32,
) -> u32 {
if spot_price <= 0 || twap_price <= 0 {
return base_fee_bps.clamp(min_fee_bps, max_fee_bps);
}
let diff = if spot_price >= twap_price {
spot_price - twap_price
} else {
twap_price - spot_price
};
let deviation_bps = (diff * BPS_DENOMINATOR / twap_price) as u32;
let extra_fee = deviation_bps.saturating_mul(volatility_factor);
let raw_fee = base_fee_bps.saturating_add(extra_fee);
raw_fee.clamp(min_fee_bps, max_fee_bps)
}
}
During quiet periods ($\text{spot} \approx \text{TWAP}$), trades enjoy standard fees (e.g. 30 bps = 0.30%). During sharp movements, fees rise up to max_fee_bps (e.g. 500 bps = 5.00%), capturing arbitrageur rent for liquidity providers.
Why four files
The test suite divides its coverage cleanly across four dedicated files, exercising all four workspace testkit crates:
| File | Crate | What it covers |
|---|---|---|
tests/fixtures.rs | soroban-testkit-fixtures | TestContextBuilder, user funding, pool initialization, LP share minting/burning, multi-block TWAP updates, and fee cooling |
tests/assert_events.rs | soroban-testkit-assert | EventMatcher, EventLog, assert_event_topic_count!, assert_auth_matches!, and intermediate token transfer isolation with assert_auth_sub_invocation! |
tests/budget_and_storage.rs | soroban-testkit-core & assert | Benchmarking dynamic fee overhead against constant product AMM, budget_guard!, BudgetSnapshot, assert_storage_tier_count! |
tests/property.rs | soroban-testkit-generators | proptest! proving fee clamping within $[min, max]$, constant-product invariant $k_{\text{after}} \ge k_{\text{before}}$, and monotonic fee scaling |
Fixtures — pool lifecycle and multi-block TWAP updates
tests/fixtures.rs uses TestContextBuilder to set up funded accounts and test pool operations:
#![allow(unused)]
fn main() {
use soroban_testkit_fixtures::builder::TestContextBuilder;
let ctx = TestContextBuilder::new().with_users(3).build();
let pool = ctx.env.register(DynamicAmmContract, ());
}
Key lifecycle tests:
- Initial liquidity: mints $S = \sqrt{A \times B}$ LP shares.
- Proportional provisioning: second depositor receives shares exactly proportional to current reserves.
- Partial and complete withdrawals: burns shares and returns underlying assets.
- TWAP across ledger blocks: uses
ctx.env.ledger().set_timestamp(...)to simulate time passage across blocks, proving price accumulation and window calculation. - Dynamic fee scaling and cooling: demonstrates that fees rise during large swaps and cool down as time passes and the pool stabilizes.
Event and authorization assertions
tests/assert_events.rs uses soroban-testkit-assert to verify the public observability and authorization requirements of AMM operations:
#![allow(unused)]
fn main() {
use soroban_testkit_assert::events::{EventLog, EventMatcher};
use soroban_testkit_assert::{assert_auth_matches, assert_auth_sub_invocation, assert_event_topic_count};
// Verify swap event emission
EventMatcher::new(&fx.ctx.env)
.from_contract(&fx.pool)
.with_topic("swap")
.assert_emitted();
// Assert direct swapper authorization
assert_auth_matches!(fx.ctx.env, {
invoker: fx.trader,
function: "swap",
args: [fx.trader.clone(), fx.token_a.clone(), 5_000 * ONE, 1i128],
});
// Isolate intermediate token transfer sub-invocation using assert_auth_sub_invocation!
assert_auth_sub_invocation!(fx.ctx.env, {
contract: fx.token_a,
function: "transfer",
args: [fx.trader.clone(), fx.pool.clone(), 5_000 * ONE],
});
}
Using assert_auth_sub_invocation!, tests isolate the intermediate token contract transfer without needing to assert on top-level invoker wrappers or entire sub-trees.
Budget benchmarking & storage quotas
tests/budget_and_storage.rs evaluates the performance and gas overhead of the dynamic fee mechanism compared to standard constant-product AMMs:
#![allow(unused)]
fn main() {
use soroban_testkit_core::budget::BudgetSnapshot;
// Constant-fee baseline swap
client1.swap_constant_fee(&fx1.trader, &fx1.token_a, &(5_000 * ONE), &1, &30);
let constant_cost = BudgetSnapshot::last_invocation(&fx1.env);
// Dynamic-fee swap with TWAP calculation
client2.swap(&fx2.trader, &fx2.token_a, &(5_000 * ONE), &1);
let dynamic_cost = BudgetSnapshot::last_invocation(&fx2.env);
// The dynamic fee calculation overhead is strictly bounded (< 30%)
let cpu_overhead_pct = ((dynamic_cost.cpu_insns as f64 - constant_cost.cpu_insns as f64)
/ constant_cost.cpu_insns as f64) * 100.0;
assert!(cpu_overhead_pct < 30.0);
}
Storage tier allocations are enforced using assert_storage_tier_count!:
#![allow(unused)]
fn main() {
use soroban_testkit_assert::assert_storage_tier_count;
// Instance storage holds Config, Reserves, TotalShares, and Twap
// Persistent storage holds user LP shares
assert_storage_tier_count!(fx.env, fx.pool, {
instance: 4,
persistent: 1,
temporary: 0,
});
}
Property testing
tests/property.rs uses soroban-testkit-generators and proptest! to prove critical DeFi invariants across arbitrary values:
- Strict fee bounds: Proves that for all generated spot prices, TWAP values, and volatility multipliers, $\text{fee} \in [\text{min_fee_bps}, \text{max_fee_bps}]$.
- Monotonic fee scaling: Proves that greater price deviation from TWAP always yields equal or higher fees.
- Zero deviation base fee: When $\text{spot} = \text{TWAP}$, fee strictly equals
base_fee_bps. - Constant product invariant: Across arbitrary reserve ratios and swap amounts, $k_{\text{after}} \ge k_{\text{before}}$ holds with zero precision loss.
- Solvency bound: Output amount is strictly less than reserve out ($\text{amount_out} < \text{reserve_out}$).
- Babylonian square root accuracy: $\lfloor\sqrt{y}\rfloor^2 \le y < (\lfloor\sqrt{y}\rfloor + 1)^2$.
#![allow(unused)]
fn main() {
proptest! {
#[test]
fn proptest_dynamic_fee_strictly_within_min_and_max_bounds(
spot_price in 1i128..=10_000_000_000_000i128,
twap_price in 1i128..=10_000_000_000_000i128,
min_fee in 1u32..=100u32,
base_fee_offset in 0u32..=200u32,
max_fee_offset in 0u32..=2000u32,
volatility_factor in 0u32..=20u32,
) {
let base_fee = min_fee + base_fee_offset;
let max_fee = base_fee + max_fee_offset;
let fee = calculate_dynamic_fee_bps(
spot_price,
twap_price,
base_fee,
min_fee,
max_fee,
volatility_factor,
);
prop_assert!(fee >= min_fee);
prop_assert!(fee <= max_fee);
}
}
}
Worked Example: Constant Product AMM
A multi-contract DeFi protocol: two ERC-20 style tokens, a constant-product (x * y = k) pool that mints LP share tokens, and a router that forwards swaps to the pool. It is the reference for testing several contracts that call each other — registration in one environment, authorization trees three levels deep, slippage guards, LP fee accrual, and the invariant proved with property tests. Everything here is real code in examples/amm, a workspace member you can run.
The contracts
Three #![no_std] contract types, deployed five times:
| Contract | Deployed as | Role |
|---|---|---|
AmmToken | token_a, token_b | The pool’s two assets: balances and allowances in persistent storage, metadata and supply in instance storage |
AmmToken | share | The LP share token. Its admin is the pool, so only the pool can mint shares |
ConstantProductPool | pool | Holds the reserves, mints and burns shares, swaps along x * y = k |
Router | router | User-facing entry point that forwards a swap to a pool |
user signs once
│
▼
router.swap_exact_in ──▶ pool.swap ──▶ token_in.transfer(user → pool)
└──▶ token_out.transfer(pool → user)
The pool is deployed first, so the share token can name it as admin, and then initialized with all three token addresses:
#![allow(unused)]
fn main() {
let token_a = env.register(AmmToken, (admin.clone(), 7u32, String::from_str(&env, "Token A"), String::from_str(&env, "TKA")));
let token_b = env.register(AmmToken, (admin.clone(), 7u32, String::from_str(&env, "Token B"), String::from_str(&env, "TKB")));
let pool = env.register(ConstantProductPool, ());
let share = env.register(AmmToken, (pool.clone(), 7u32, String::from_str(&env, "Pool Share"), String::from_str(&env, "LP")));
let router = env.register(Router, ());
ConstantProductPoolClient::new(&env, &pool).initialize(&token_a, &token_b, &share, &30);
}
The math
The arithmetic is in free functions so property tests can exercise it without a contract in the loop.
A swap of amount_in with a fee of fee_bps pays out
$$\text{out} = \left\lfloor \frac{\text{in} \cdot (10000 - \text{fee}) \cdot R_{out}}{R_{in} \cdot 10000 + \text{in} \cdot (10000 - \text{fee})} \right\rfloor$$
which always leaves $(R_{in} + \text{in})(R_{out} - \text{out}) \ge R_{in} R_{out}$.
The fee stays in the pool, so k grows with every trade — that growth is what
liquidity providers earn. The pool re-checks the invariant after computing the
output and refuses with AmmError::InvariantViolated if it ever fails.
The first deposit mints $\lfloor\sqrt{a \cdot b}\rfloor$ shares, of which
MINIMUM_LIQUIDITY (1,000) are locked so a dust-sized first deposit cannot set
an absurd share price. Later deposits are first trimmed to the pool ratio
(optimal_deposit) and mint the smaller of the two proportional claims
(shares_for_deposit), so a lopsided deposit cannot dilute existing holders.
Errors
#![allow(unused)]
fn main() {
#[contracterror]
pub enum AmmError {
AlreadyInitialized = 1, NotInitialized = 2, InvalidAmount = 3,
SlippageExceeded = 4, InsufficientLiquidity = 5, InvalidFee = 6, InvariantViolated = 7,
}
#[contracterror]
pub enum TokenError { NegativeAmount = 100, InsufficientBalance = 101, InsufficientAllowance = 102 }
}
Token codes start at 100 on purpose. A token failure inside pool.swap
propagates out of the pool with its own code; if the ranges overlapped, a
token’s InsufficientBalance = 2 would read as the pool’s NotInitialized.
The test suite
One file per testkit crate, sharing a deployment helper in tests/common:
| File | Crate | Tests |
|---|---|---|
tests/fixtures.rs | soroban-testkit-fixtures | 12 |
tests/assert.rs | soroban-testkit-assert | 17 |
tests/budget_and_storage.rs | soroban-testkit-core | 11 (+1 ignored recorder) |
tests/property.rs | soroban-testkit-generators + proptest | 8 |
Fixtures: multi-contract context registration
TestContextBuilder::with_users(3) gives an LP, a trader and a second LP in
the same environment as all five contracts:
#![allow(unused)]
fn main() {
let ctx = TestContextBuilder::new().with_users(3).build();
let amm = Amm::deploy(&ctx.env, &ctx.admin, DEFAULT_FEE_BPS);
for user in &ctx.users {
amm.fund(user, 1_000_000 * ONE);
}
}
The suite checks share minting (sqrt(a * b) - MINIMUM_LIQUIDITY first,
proportional after), that a lopsided deposit only takes the pool ratio, that a
swap pays exactly the quote and moves both reserves, that the router swaps
exactly like a direct call, pro-rata withdrawals, and LP fee accrual: after ten
round-trip trades k has grown and the LP withdraws more than it deposited.
It also uses the TTL helpers on LP balances. A share balance is a persistent entry; left untouched past its TTL it is archived, and once swept off the ledger it reads as zero until restored:
#![allow(unused)]
fn main() {
let key = TokenKey::Balance(lp.clone());
assert_eq!(ctx.ttl(&amm.share, &key).tier, StorageTier::Persistent);
ctx.fast_forward_to_expiration(&amm.share, &key);
ctx.assert_persistent_archived(&amm.share, &key);
ctx.archive_expired(0);
assert_eq!(amm.share().balance(&lp), 0);
}
Assert: events, sub-invocation auth and exact errors
Events are asserted per contract, which matters with five contracts emitting:
#![allow(unused)]
fn main() {
amm.pool().deposit(&lp, &(1_000 * ONE), &(1_000 * ONE), &0, &0);
EventMatcher::new(&env).from_contract(&amm.pool).with_topic("deposit").assert_emitted();
assert_event_topic_count!(env, "transfer", 2);
assert_event_topic_count!(env, from = amm.share, "mint", 1);
}
A routed swap needs one signature from the trader that covers three levels.
assert_auth_sub_invocation! finds the token transfer at any depth of the
recorded tree:
#![allow(unused)]
fn main() {
amm.router().swap_exact_in(&amm.pool, &trader, &false, &(3_000 * ONE), &0);
assert_auth_matches!(env, { invoker: trader, function: "swap_exact_in" });
assert_auth_sub_invocation!(env, {
contract: amm.token_a,
function: "transfer",
args: [trader.clone(), amm.pool.clone(), 3_000 * ONE],
});
}
The same tree written out as a MockAuth is enough for the swap to succeed
without mock_all_auths; dropping the nested pool.swap and
token.transfer entries makes the call fail.
Slippage guards and configuration errors are asserted by variant with
assert_contract_error!, so a test cannot pass by failing for the wrong reason:
#![allow(unused)]
fn main() {
let quoted = amm.pool().quote(&true, &(1_000 * ONE));
assert_contract_error!(
amm.pool().try_swap(&trader, &true, &(1_000 * ONE), &(quoted + 1)),
AmmError::SlippageExceeded
);
}
A token failure beneath the pool carries a TokenError code the pool’s
client cannot name, so it is asserted as a raw contract error:
#![allow(unused)]
fn main() {
assert_host_error!(
amm.pool().try_swap(&broke, &true, &ONE, &0),
Error::from_contract_error(TokenError::InsufficientBalance as u32)
);
}
assert_balance_conserved! closes the file: a swap moves token A between the
trader and the pool and creates none.
Core: budget baseline, storage diffs and the call tracer
examples/amm/budget.json tracks the four hot paths — swap, router_swap,
deposit, withdraw. The enforcing test measures each with
BudgetSnapshot::last_invocation and fails when one grows more than 20% past
the committed reading:
#![allow(unused)]
fn main() {
let baseline = BudgetBaseline::load(&baseline_path()).unwrap();
for (case, cost) in measure_hot_paths() {
baseline.guard(case).tolerance(TOLERANCE_PERCENT).assert_within(&cost);
}
}
Refresh it deliberately, then commit the file:
cargo test -p soroban-testkit-example-amm --test budget_and_storage -- --ignored record_budget_baseline
Storage snapshots prove a swap rewrites exactly the two reserves and nothing else in the pool:
#![allow(unused)]
fn main() {
let before = StorageSnapshot::capture(&env, &amm.pool);
amm.pool().swap(&trader, &true, &(1_000 * ONE), &0);
let diff = before.diff(&StorageSnapshot::capture(&env, &amm.pool));
// modified keys: [ReserveA], [ReserveB]
}
CallTracer shows the routed swap’s call tree with the cost of every frame,
and on failure points at the frame that refused:
#![allow(unused)]
fn main() {
let trace = CallTracer::capture(&env, || {
amm.router().swap_exact_in(&amm.pool, &broke, &true, &ONE, &0)
})
.with_label(&amm.router, "router")
.with_label(&amm.pool, "pool")
.with_label(&amm.token_b, "token_b");
assert_eq!(
trace.render_failure_path().unwrap(),
"router::swap_exact_in -> pool::swap -> token_b::transfer (error: Contract(101))"
);
}
For a successful swap, render_ascii() prints:
router::swap_exact_in [ok] cpu=271623 mem=51987
└── pool::swap [ok] cpu=242342 mem=42756
├── token_b::transfer [ok] cpu=74519 mem=13436
└── token_a::transfer [ok] cpu=75818 mem=13131
And render_mermaid():
sequenceDiagram
participant Test
participant C0 as router
participant C1 as pool
participant C2 as token_b
participant C3 as token_a
Test->>C0: swap_exact_in (cpu=271623, mem=51987)
C0->>C1: swap (cpu=242342, mem=42756)
C1->>C2: transfer (cpu=74519, mem=13436)
C2-->>C1: ok
C1->>C3: transfer (cpu=75818, mem=13131)
C3-->>C1: ok
C1-->>C0: ok
C0-->>Test: ok
Generators: the invariant under arbitrary trade sizes
Strategies are built from token_amount() and bounded so reserve * reserve
cannot overflow an i128:
#![allow(unused)]
fn main() {
fn reserve() -> impl Strategy<Value = i128> {
token_amount().prop_map(|amount| amount % 1_000_000_000_000_000 + 1)
}
}
The pure-math properties run 256 cases each: a quoted swap never decreases
k and never drains the output side, a higher fee never pays out more,
integer_sqrt is the exact floor, an optimal deposit never exceeds what was
offered, and minted shares never claim more of the pool than was deposited.
Against a live pool (32 cases each), a random sequence of swaps in both
directions keeps k non-decreasing and pays exactly the quote, and a deposit
followed by an immediate withdrawal never returns more than went in. A
generated account_address() is funded and trades, to show generator
addresses are usable in a multi-contract flow.
Running it
cargo test -p soroban-testkit-example-amm
cargo clippy -p soroban-testkit-example-amm --all-targets -- -D warnings
Concentrated Liquidity AMM
examples/concentrated_amm demonstrates tick-ranged liquidity, swap execution
across active tick bands, fee compounding and testkit budget/storage checks.
Run the example suite:
cargo test -p soroban-testkit-example-concentrated-amm
The contract is #![no_std] and exposes mint_position, burn_position, and
swap entry points. Positions carry owner, tick bounds and liquidity. Minting
requires aligned tick spacing; swapping moves the active tick and updates virtual
reserves while fee-bearing output is deducted.
Test layout
fixtures.rscovers setup, initialization and position lifecycle.assert.rscovers swaps, tick crossings and authorization failures.budget_storage.rscaptures metering and persistent position behavior.proptest.rsproves swap reserve invariants and bounded tick math.
The suite uses every workspace testkit crate:
soroban-testkit-fixturesbuilds isolated environments.soroban-testkit-generatorssupplies property-test strategy patterns.soroban-testkit-corerecords budget baselines.soroban-testkit-assertvalidates wallet and contract behavior.
Worked Example: Order Book DEX with Price-Time Priority
A Central Limit Order Book (CLOB) decentralized exchange on Soroban: makers place resting limit orders with escrowed collateral, bids and asks maintain strict price-time priority ordering, and market orders execute with deterministic partial and full fill settlements. Everything here is real code in examples/orderbook, a workspace member you can run.
The contract
One #![no_std] contract manages resting order queues, price-time sorting, collateral escrow, and market execution matching:
Maker Limit Order ──▶ Escrow Collateral ──▶ Sorted Queue (Bids/Asks) ──▶ Market Match ──▶ Settlement & Deletion
Price-time priority queues
The order book maintains two queues of resting orders:
- Bids (Buy Orders): Sorted by price descending (highest buy price first). For equal prices, orders are sorted by timestamp and ID ascending (earliest first).
- Asks (Sell Orders): Sorted by price ascending (lowest sell price first). For equal prices, orders are sorted by timestamp and ID ascending.
#![allow(unused)]
fn main() {
// Bids sorted descending: highest price first
if !inserted && price > existing_order.price {
new_bids.push_back(order_id);
inserted = true;
}
}
Maker collateral escrow & cancellations
When a maker places an order:
- A
Buyorder escrows(amount * price) / PRICE_PRECISIONquote tokens in the contract. - A
Sellorder escrowsamountbase tokens in the contract.
When an order is cancelled or partially filled:
- Unfilled collateral is refunded to the maker immediately.
- The order entry is completely removed from storage upon cancellation or 100% execution, reclaiming contract footprint and preventing state bloat.
Partial fill execution
When a taker executes a market order:
- The contract walks through the resting book up to the requested volume.
- Matched volume is executed at the resting maker’s price.
- If an order is partially filled, its
filledtally updates and the order remains in the book. - If an order is fully filled (
filled == amount), it is pruned from the queue and deleted from persistent storage.
Why four files
The test suite divides its coverage cleanly across four dedicated files, exercising all four workspace testkit crates:
| File | Crate | What it covers |
|---|---|---|
tests/fixtures.rs | soroban-testkit-fixtures | TestContextBuilder, user funding, token setup, order placement, order cancellation, refunds, full matching, and partial matching |
tests/assert_events.rs | soroban-testkit-assert | EventLog, assert_auth_matches!, assert_event_count_range!, assert_event_topic_count!, and negative event assertions |
tests/budget_and_storage.rs | soroban-testkit-core | BudgetSnapshot, StorageSnapshot, instruction cost scaling across matching depths (1, 5, 10), and storage diff proving order deletion |
tests/property.rs | soroban-testkit-generators | Proptest strategies for price and amounts, verifying that buyer received tokens and seller received payment matching the price |
Key test patterns
Price-time priority verification
tests/fixtures.rs asserts that orders placed out of order automatically sort into their correct priority slots:
#![allow(unused)]
fn main() {
#[test]
fn place_orders_maintains_bid_price_priority_descending() {
let fx = setup();
let client = OrderBookContractClient::new(&fx.ctx.env, &fx.book);
let id1 = client.place_order(&fx.maker_1, &Side::Buy, &(2 * PRICE_PRECISION), &(10 * ONE));
let id2 = client.place_order(&fx.maker_1, &Side::Buy, &(3 * PRICE_PRECISION), &(10 * ONE));
let id3 = client.place_order(&fx.maker_2, &Side::Buy, &(25 * PRICE_PRECISION / 10), &(10 * ONE));
let bids = client.get_bids();
assert_eq!(bids.get(0).unwrap(), id2); // 3.0
assert_eq!(bids.get(1).unwrap(), id3); // 2.5
assert_eq!(bids.get(2).unwrap(), id1); // 2.0
}
}
Storage deletion proof
tests/budget_and_storage.rs captures contract storage before order creation, during resting state, and after full execution, proving with StorageSnapshot that filled entries leave zero lingering storage footprint:
#![allow(unused)]
fn main() {
#[test]
fn storage_diff_proves_order_deletion_upon_full_fill() {
let fx = setup();
let client = OrderBookContractClient::new(&fx.env, &fx.book);
let initial_storage = StorageSnapshot::capture(&fx.env, &fx.book);
let order_id = client.place_order(&fx.maker, &Side::Sell, &(2 * PRICE_PRECISION), &(10 * ONE));
// Storage increases while order is resting
assert!(StorageSnapshot::capture(&fx.env, &fx.book).len() > initial_storage.len());
// 100% filled market order
client.execute_market_order(&fx.taker, &Side::Buy, &(10 * ONE));
let filled_storage = StorageSnapshot::capture(&fx.env, &fx.book);
// Order entry is fully erased from persistent storage
assert_eq!(filled_storage.len(), initial_storage.len());
assert!(client.get_order(&order_id).is_none());
}
}
Matching depth CPU instruction benchmarking
tests/budget_and_storage.rs compares CPU instruction consumption across execution depths of 1, 5, and 10 matched orders, verifying predictable linear budget growth:
#![allow(unused)]
fn main() {
assert!(depth_1_cost.cpu_insns < depth_5_cost.cpu_insns);
assert!(depth_5_cost.cpu_insns < depth_10_cost.cpu_insns);
}
Worked Example: Non-Fungible Token (NFT) with Royalties and Approvals
A standard-compliant Non-Fungible Token (NFT) contract on Soroban: unique token IDs, single and batch minting, operator approvals with expiration, safe transfers, metadata URIs, and secondary sale royalty splits. Everything here is real code in examples/nft, a workspace member you can run.
The contract
One #![no_std] contract implements token ownership, operator authorizations, and marketplace royalty settlements:
Mint Token ──▶ Set Approvals (Single/All) ──▶ Transfer / Safe Transfer ──▶ Secondary Sale with Royalty Split
Unique token IDs and owner tracking
Each token has a unique u32 ID, an owner address, and a metadata URI:
- Minting verifies the token ID does not already exist, records the owner, assigns the URI, and increments supply and balances.
- Burning cleans up ownership and URI mappings and decrements total supply.
Approvals and operator delegation
Two levels of authorization allow contracts and marketplaces to operate on behalf of users:
- Single Token Approval: An owner approves an operator for a specific
token_idvalid until a ledger sequence (live_until_ledger). - Operator Approval for All: An owner authorizes an operator to manage all tokens they own until expiration.
- Revocation & Expiration: Approvals can be explicitly revoked or expire automatically as the ledger sequence advances.
Secondary sale royalty splits
When an NFT is sold on a secondary market:
- The contract computes the creator royalty based on
royalty_bps(e.g., 500 bps = 5%). - Royalty proceeds are delivered directly to
royalty_recipient. - Remaining proceeds are transferred to the seller.
- Token ownership transfers to the buyer in the same atomic invocation.
Why four files
The test suite divides its coverage cleanly across four dedicated files, exercising all four workspace testkit crates:
| File | Crate | What it covers |
|---|---|---|
tests/fixtures.rs | soroban-testkit-fixtures | TestContextBuilder, user roles, minting, batch minting, transfers, approval expiration, burning, and secondary sales |
tests/assert_events.rs | soroban-testkit-assert | EventMatcher, assert_auth_matches!, assert_event_topic_count!, and events for mint, transfer, approval, and royalties |
tests/budget_and_storage.rs | soroban-testkit-core | Storage inspection verifying persistent entries per token ID, and storage growth benchmarking across 1, 10, and 100 minted tokens |
tests/property.rs | soroban-testkit-generators | Proptest suite proving token uniqueness, single-owner invariant, batch balance conservation, and bounded royalty math |
Key test patterns
Single-owner invariant property test
tests/property.rs asserts that each token ID has exactly one owner at any time, that duplicates are rejected, and that transfers preserve total supply and balance invariants:
#![allow(unused)]
fn main() {
#[test]
fn proptest_token_uniqueness_and_single_owner_invariant(token_id in 1u32..=1000u32) {
// Mint token to user_a
client.mint(&user_a, &token_id, &uri);
prop_assert_eq!(client.owner_of(&token_id), Some(user_a.clone()));
// Uniqueness invariant: duplicate mint is rejected
let duplicate = client.try_mint(&user_b, &token_id, &uri);
prop_assert!(duplicate.is_err());
// Transfer preserves single-owner invariant
client.transfer(&user_a, &user_b, &token_id);
prop_assert_eq!(client.owner_of(&token_id), Some(user_b.clone()));
prop_assert_eq!(client.balance_of(&user_a), 0);
prop_assert_eq!(client.balance_of(&user_b), 1);
}
}
Storage growth benchmarking
tests/budget_and_storage.rs measures persistent storage expansion across 1, 10, and 100 minted tokens using StorageSnapshot:
#![allow(unused)]
fn main() {
assert_eq!(storage_1.len(), 4); // Config + Balance + Owner + URI
assert_eq!(storage_10.len(), 22); // Config + Balance + 10 Owners + 10 URIs
assert_eq!(storage_100.len(), 202);// Config + Balance + 100 Owners + 100 URIs
}
Worked Example: Portfolio Rebalancing Vault
This guide walks through examples/portfolio_vault, a multi-asset index vault
that mints portfolio shares, tracks oracle prices, and executes simplified
oracle-priced rebalancing swaps.
Contract model
PortfolioVault stores target asset weights (basis points), oracle prices, and
user share balances. Deposits mint shares proportional to contributed value;
withdrawals burn shares pro-rata across vault assets; rebalance executes an
oracle-priced swap between two vault assets with slippage protection.
Four-file test split
| File | Crate | Focus |
|---|---|---|
tests/fixtures.rs | soroban-testkit-fixtures | Deployment, deposits, withdrawals, oracle updates, rebalance setup |
tests/assert.rs | soroban-testkit-assert | Auth/errors and invalid-input rejection |
tests/budget_storage.rs | soroban-testkit-core | Budget snapshots, storage snapshots, value preservation checks |
tests/proptest.rs | soroban-testkit-generators + proptest | Property invariants for deposits, withdrawals, rebalance value/tolerance |
Fixtures
tests/common/mod.rs deploys three Stellar asset contracts, registers the
vault, initializes 50/30/20 target weights, and sets initial oracle prices.
Assert
Auth and error tests verify admin-only price updates/rebalance, invalid inputs, and insufficient share withdrawals.
Core budget/storage
Budget tests capture BudgetSnapshot::last_invocation for deposit/withdraw/
rebalance. Storage tests inspect vault snapshots and verify share balance cleanup
and value preservation across oracle-priced rebalance.
Property tests
Proptest cases verify minted shares are positive, withdrawals cannot exceed shares, oracle-priced rebalance preserves total value, and single-depositor share accounting is consistent.
Running it
cargo test -p soroban-testkit-example-portfolio-vault
cargo clippy -p soroban-testkit-example-portfolio-vault --all-targets -- -D warnings
Dutch and Batch Auction Worked Example
This guide walks through examples/auction, a single #![no_std] contract, AuctionHouse, that runs two kinds of auction:
- Dutch auction. One lot is offered at a price that falls over ledger time. The first bidder willing to pay the current asking price buys the whole lot.
- Batch auction. A supply of units is offered for a bidding window. Bids are collected and then evaluated together: they are ranked, filled from the supply, and every winner pays the same uniform clearing price.
Both kinds sell units of an asset token for a payment token, and both escrow everything in advance, so settlement only ever pays out of funds the contract already holds. The suite has 55 tests (plus one deliberately ignored baseline recorder) in four files, and all four workspace crates are used in the clearing scenarios.
Dutch vs batch, in one table
| Dutch | Batch | |
|---|---|---|
| What is sold | One lot of lot_size units, as a whole | supply units, split across bidders |
| Price | Asking price for the lot falls from start_price to floor_price | Discovered at settlement: the uniform clearing price per unit |
| Who wins | The first bid at or above the asking price | The highest-priced bids, until supply runs out |
| What a winner pays | The asking price when they bid (not their maximum) | allocation × clearing_price, never above their own maximum |
| Bidding window | start_time ≤ now ≤ start_time + duration | start_time ≤ now < end_time |
| Escrow per bid | The asking price | quantity × max_price |
| Payout | settle pays the buyer and the seller | settle pays the seller, then each bidder claims units and refund |
Architecture and entry points
examples/auction/
├── src/lib.rs # AuctionHouse contract, types, errors, events
├── budget.json # committed budget baseline for the benchmark
└── tests/
├── common/mod.rs # the `House` fixture, built on soroban-testkit-fixtures
├── fixtures.rs # soroban-testkit-fixtures — lifecycle and clearing (19 tests)
├── assert.rs # soroban-testkit-assert — errors, events, auth, conservation (22 tests)
├── budget_storage.rs # soroban-testkit-core — benchmark, budgets, limits, storage (8 + 1 ignored)
└── proptest.rs # soroban-testkit-generators + proptest — invariants (6 properties)
| Entry point | Signs | What it does |
|---|---|---|
create_dutch(seller, DutchConfig) -> u64 | seller | Checks the schedule, escrows lot_size asset units, returns the auction id |
create_batch(seller, BatchConfig) -> u64 | seller | Checks supply, reserve and window, escrows supply asset units |
bid_dutch(id, bidder, max_price) -> i128 | bidder | Buys the lot if max_price ≥ the current asking price, escrowing that price |
bid_batch(id, bidder, quantity, max_price) | bidder | Places the bidder’s one bid, escrowing quantity × max_price |
settle(id) -> Auction | anyone | Settles once: Dutch delivers lot and proceeds; batch discovers the clearing price and pays the seller |
claim(id, bidder) -> Bid | anyone | After batch settlement, sends the bidder their allocation and refund, once |
auction(id), current_price(id), get_bid(id, bidder), book(id) | — | Read-only views. get_bid shows a bid’s allocation, payment and refund as soon as the auction is settled |
Storage: the id counter lives in instance storage. Each auction ([Auction, id]), its ranked order book ([Book, id]) and each batch bid ([Bid, id, bidder]) are persistent entries.
Configuring and initializing an auction
#![allow(unused)]
fn main() {
use soroban_testkit_example_auction::{AuctionHouse, AuctionHouseClient, BatchConfig, DutchConfig};
let client = AuctionHouseClient::new(&env, &env.register(AuctionHouse, ()));
// A 100-unit lot asking 10_000, falling to 4_000 over 600 s in 1 s steps.
let dutch = client.create_dutch(&seller, &DutchConfig {
asset: asset.clone(),
payment: payment.clone(),
lot_size: 100,
start_price: 10_000,
floor_price: 4_000,
start_time: now,
duration: 600,
step_seconds: 1,
});
// 1_000 units, at least 10 per unit, bids accepted for an hour.
let batch = client.create_batch(&seller, &BatchConfig {
asset: asset.clone(),
payment: payment.clone(),
supply: 1_000,
reserve_price: 10,
start_time: now,
end_time: now + 3_600,
});
}
create_dutch rejects with InvalidConfig a non-positive lot or floor, a floor above the start price, a zero duration or step, a step longer than the duration, or a duration that is not a multiple of the step (so the floor is always reached exactly at the end). If (start_price − floor_price) × duration would overflow an i128, it rejects with ArithmeticOverflow. That check is what guarantees the price calculation can never overflow later. create_batch rejects a non-positive supply or reserve, and an empty window.
Bidding and escrow
Every bid needs the bidder’s authorization, and the payment is moved into the contract in the same call through the payment token’s transfer. If the bidder cannot cover it, the token contract fails the call and the whole invocation rolls back: no bid is recorded, no order book entry is added, and no funds move.
A failure inside the token contract propagates through the escrow call unchanged. An insufficient balance arrives at the caller as the Stellar Asset Contract's own Error(Contract, #10). If AuctionError were numbered from 1, a client would decode that as auction error 10. Starting at 101 keeps the two apart, and tests/assert.rs asserts the token error explicitly with assert_host_error!(…, Error::from_contract_error(10)).
Batch bids also enforce these rules:
- one bid per bidder (
DuplicateBid); quantity > 0(InvalidQuantity);max_price ≥ reserve_price(BidBelowPrice);- the seller cannot bid (
SellerCannotBid); - at most
MAX_BATCH_BIDS = 64bids per auction (TooManyBids); - the escrow
quantity × max_pricemust fit in ani128, checked before any transfer (ArithmeticOverflow).
Dutch price decay
elapsed = clamp(now − start_time, 0, duration)
stepped = elapsed − elapsed mod step_seconds
drop = (start_price − floor_price) × stepped / duration (integer division, rounds down)
asking = start_price − drop (so the price rounds up)
With the defaults above the price falls 10 per second: 10,000 at the start, 8,500 after 150 s, 7,000 after 300 s, and 4,000 from 600 s on. With step_seconds = 60 it holds at 10,000 for the first minute and then drops 600 at once. Rounding the drop down means the asking price never undercuts the published schedule and never goes below the floor. A 999-unit spread over 7 s asks 858 after one second, not 857.
bid_dutch accepts the first bid with max_price ≥ asking while the window is open. It escrows the asking price, not the bidder’s maximum, records the winner, and refuses every later bid with LotAlreadySold. The tests use TestContext::advance_time to step the ledger clock:
#![allow(unused)]
fn main() {
let id = house.dutch();
assert!(house.client().try_bid_dutch(&id, &bidder, &8_000).is_err()); // asking 10_000
house.advance(200); // asking 8_000
assert_eq!(house.client().bid_dutch(&id, &bidder, &8_000), 8_000);
}
settle delivers the lot to the buyer and the escrowed price to the seller. If the window closes with no buyer, settle returns the lot to the seller. Settling before then fails with BiddingOpen, and settling twice fails with AlreadySettled.
Batch clearing-price discovery
The order book is kept ranked as bids arrive: by max_price descending, then by submission order (earlier first). Settlement works through it greedily:
- Undersubscribed (total demand ≤ supply). Every bid is filled in full, and the clearing price is the reserve price. Demand exactly equal to supply counts as undersubscribed.
- Oversubscribed (total demand > supply). Bids are filled in rank order until the supply is gone. The clearing price is the
max_priceof the marginal bid, the last bid to receive any units, which may be filled only in part. Bids ranked after it receive nothing. - No bids. There is no clearing price (
None), and the whole supply goes back to the seller.
Tie-breaking. Bids at the same price are filled in submission order. With 500 units and three 300-unit bids at 20, the first gets 300, the second 200, and the third nothing. A later bid at a higher price still outranks an earlier, lower one.
Worked example. With 1,000 units, a reserve of 10, and bids A 400@30, B 500@25, C 300@20, D 200@15:
| Bid | Rank | Escrow | Allocation | Pays (×20) | Refund |
|---|---|---|---|---|---|
| A 400@30 | 1 | 12,000 | 400 | 8,000 | 4,000 |
| B 500@25 | 2 | 12,500 | 500 | 10,000 | 2,500 |
| C 300@20 | 3 | 6,000 | 100 (marginal) | 2,000 | 4,000 |
| D 200@15 | 4 | 3,000 | 0 | 0 | 3,000 |
Cumulative demand reaches 1,000 inside C, so C is the marginal bid and the clearing price is 20. The seller receives 20,000.
Why no winner overpays. Every filled bid ranks at or above the marginal bid, so clearing_price ≤ max_price for every winner. Allocations never exceed quantities, so payment = allocation × clearing ≤ quantity × max_price = escrow and no refund is negative. The contract also checks this and refuses with EscrowMismatch rather than over-charging.
Settlement and refunds
Batch payouts are pull-based:
settle(id)(afterend_time, once) works out the clearing price, sends the sellerunits_sold × clearing_priceand any unsold units, and records the result. It reads the order book but writes only the auction entry.claim(id, bidder)(after settlement, once per bid) works out that bid’s fill again from the ranked book (min(quantity, supply − units ranked ahead)). It then sends the allocation in asset units and the refundescrow − allocation × clearing_pricein payment tokens, and marks the bidclaimed. Anyone may call it, because the funds can only go to the bidder.
The accounting holds as an invariant. After settlement, total_escrow equals the sum of all refunds still owed. Each claim reduces it by exactly that bid’s refund, so once every bid has been claimed the contract holds zero of both tokens for the auction.
settle?
An earlier version of this example did exactly that. Measuring it against the SDK's Mainnet invocation limits showed the problem. Each payout is a token transfer, and each transfer emits an event. At 50 bidders, settlement produced about 17.9 KB of contract events, more than the 16 KiB a Mainnet transaction may carry. Pull-based claims keep settle nearly constant in cost and every claim bounded, and tests/budget_storage.rs checks a full 64-bid book against both the Testnet and Mainnet limits.
Error conditions
| Error (code) | Cause |
|---|---|
AuctionNotFound (101) | Unknown auction id |
InvalidConfig (102) | A schedule, supply, reserve or window that cannot work (see above) |
NotStarted (103) | Bid before start_time |
BiddingClosed (104) | Dutch bid after start_time + duration; batch bid at or after end_time |
BiddingOpen (105) | Settle before the window closes (a Dutch lot that has already sold can be settled at once) |
AlreadySettled (106) | Settle, or bid, after settlement |
BidBelowPrice (107) | Dutch maximum below the asking price; batch price below the reserve |
InvalidQuantity (108) | Batch quantity ≤ 0 |
DuplicateBid (109) | A second batch bid from the same bidder |
LotAlreadySold (110) | A Dutch bid after the lot was taken |
TooManyBids (111) | More than MAX_BATCH_BIDS bids |
ArithmeticOverflow (112) | An escrow, demand total, or price calculation would overflow |
WrongAuctionKind (113) | A Dutch call on a batch auction, or the reverse |
SellerCannotBid (114) | The seller bidding on their own auction |
EscrowMismatch (115) | Settlement accounting would not return every escrowed token. Never raised by a correct build |
BidNotFound (116) | get_bid or claim for an address that did not bid |
NotSettled (117) | claim before settlement |
AlreadyClaimed (118) | A second claim for the same bid |
The test suite
The House fixture (tests/common/mod.rs)
House::new(n) builds a TestContext with TestContextBuilder::new().with_users(n) (House::with_profile adds a NetworkProfile). It sets the clock, registers the contract and two Stellar Asset Contracts, mints the seller 1,000,000 asset units, and gives each bidder 1,000,000,000 payment tokens. Helpers keep the tests short: dutch(), dutch_with(start, floor, duration, step), batch(), batch_with(supply, reserve), place_bids(id, &[(qty, price), …]), close_window(), claim_all(id, n), advance(secs) (which calls TestContext::advance_time), and balance readers.
1. Fixtures (tests/fixtures.rs)
The full lifecycle, with exact numbers:
- Dutch. Escrow on creation. Linear and stepped decay. Rounding. A bid refused at 10,000 and accepted 200 s later at 8,000. The winner pays the asking price, not their maximum. A bid at the last second pays the floor, and one second later bidding is refused. Settlement delivers the lot, and an unsold lot goes back to the seller.
- Batch. Escrow per bid. Undersubscribed clears at the reserve. Oversubscribed clears at the marginal bid (the table above). Ties fill in submission order, and a later higher bid outranks an earlier one. Demand equal to supply clears at the reserve. Settlement and claims are run with 1, 3, 10 and 25 bidders. With no bids, the supply comes back to the seller.
- Insufficient balance. A bid the bidder cannot cover fails and leaves no trace (Dutch and batch).
2. Assertions (tests/assert.rs)
assert_contract_error!pins the exact error for every rejection above: invalid configs, an overflowing schedule, unknown ids, wrong kind, a bid below the price, the lot already sold, out-of-window bids, duplicate bids, bad quantities, an overflowing escrow, the seller bidding, the book cap, settlement and claims at the wrong time or repeated.assert_host_error!checks that an under-funded bid surfaces the token’sError(Contract, #10).EventMatcherreads thebatch_bid,dutch_bid,claimedandsettledpayloads, including the clearing price.assert_auth_matches!confirms that bids need the bidder’s signature and creation needs the seller’s.assert_balance_conserved!shows that settlement and claims conserve both tokens across the contract, the seller and every bidder.
3. Budget and storage (tests/budget_storage.rs)
Benchmark: 5, 20 and 50 bidders. The scenario is fixed so runs are comparable. Bidder i asks for 10 units at 10 + i, and supply is 5 × bidders, so the auction is exactly 2× oversubscribed. The test measures each invocation with BudgetSnapshot::last_invocation and reports:
- the single
settlecall; - the sum of all
claimcalls; - the most expensive single claim;
- the sum of all bids.
It asserts the clearing price, a BudgetGuard ceiling of 100M instructions / 40 MiB for settle and for the worst claim, and that costs grow with bidder count. These are the numbers measured for this PR (cargo test -p soroban-testkit-example-auction --test budget_storage -- --nocapture):
bidders | settle cpu | settle mem | all claims cpu | all claims mem | worst claim cpu | worst claim mem | all bids cpu | all bids mem
5 | 311333 | 58675 | 2266140 | 423819 | 527607 | 98329 | 1854181 | 384612
20 | 417835 | 98575 | 11294312 | 2555823 | 703495 | 164613 | 10248708 | 2640297
50 | 611710 | 178375 | 40453546 | 11321808 | 1002916 | 293441 | 38407643 | 12132492
These are host-metered costs for a native test contract. VM instantiation and Wasm execution are not included, so a deployed Wasm build costs more. The figures are deterministic for a given Cargo.lock. The per-claim cost rises with the bidder count because each claim scans the ranked book up to its own position.
Baseline. budget.json commits settle_{5,20,50}_bidders and claims_{5,20,50}_bidders. settlement_costs_stay_within_the_committed_baseline fails if any of them grows more than 10%. To re-record after an intended change, run the ignored recorder:
cargo test -p soroban-testkit-example-auction --test budget_storage -- --ignored budget_baseline_records_current_costs
Network limits. a_full_order_book_fits_the_network_resource_limits settles and claims a full 64-bid book twice, once under NetworkProfile::Testnet and once under NetworkProfile::Mainnet. With a profile installed, the host enforces that network’s per-invocation limits, so any call that broke one would fail. The test also compares the measured cost_estimate().resources() of settle and of the worst-case claim with the profile’s invocation_limits(), covering instructions, memory, read and write entries, footprint, bytes and event size. If a check fails, it names the resource that went over.
Storage. StorageSnapshot shows:
- creation adds
[Auction, 0](persistent) and[NextId](instance), and nothing temporary; - each bid adds exactly one persistent
[Bid, 0, …]entry and rewrites[Book, 0]and[Auction, 0]; - settlement modifies only
[Auction, 0]; - a claim modifies only the auction and that bidder’s record.
4. Properties (tests/proptest.rs)
The bid books are random: 1–12 bids, quantities 1–200, prices from the reserve to 200, and supply 1–1,000. Dutch schedules draw their start time from soroban_testkit_generators::strategies::timestamp() and their prices from token_amount().
| Property | Invariant |
|---|---|
a_winning_bidder_never_pays_more_than_their_maximum_bid | Every filled bid has clearing ≤ max_price, and what each bidder lost equals their recorded payment, which is at most allocation × max_price |
allocations_never_exceed_supply_and_follow_the_documented_rule | Total allocation = min(supply, demand) ≤ supply, and the clearing price and every allocation match an independent model of the documented rule |
escrow_accounting_conserves_both_tokens | payment + refund = escrow for every bid, proceeds = units_sold × clearing, both token totals are unchanged, and the contract ends holding zero |
with_distinct_prices_submission_order_does_not_matter | Rotating the submission order of distinct-price bids changes neither the clearing price nor anyone’s allocation |
dutch_price_is_non_increasing_and_bounded | The asking price never rises, stays within [floor, start], matches the published formula, and ends at the floor |
dutch_bid_is_accepted_exactly_when_it_covers_the_asking_price | A Dutch bid succeeds if and only if max_price ≥ asking, and then pays exactly asking |
Running it
cargo test -p soroban-testkit-example-auction
cargo test -p soroban-testkit-example-auction --test budget_storage -- --nocapture
Assumptions and limitations
- Escrow. A Dutch bidder escrows the asking price at the moment they bid. A batch bidder escrows their full
quantity × max_priceuntil they claim. Funds are never pulled from a bidder at settlement. - One bid per bidder in a batch auction. Bids cannot be amended or withdrawn.
- Allocation is by price, then time priority. There is no pro-rata split at the clearing price, so the earlier of two tied bids is filled first.
- Undersubscribed batch auctions clear at the reserve. Without competition for the supply, every bidder pays the seller’s minimum rather than the lowest bid.
- The book is capped at 64 bids so that settlement and the worst-case claim stay well inside a transaction’s limits.
- Unclaimed refunds stay in escrow until someone calls
claim. There is no expiry or sweep. - Cost figures are native-contract measurements. They are not network fees. With soroban-sdk 28, a Wasm build needs
stellar contract build(stellar-cli v25.2.0+); a plaincargo build --target wasm32v1-noneis refused by the SDK’s build script.
Worked Example: vAMM Perpetual Futures
examples/vamm demonstrates synthetic perpetual positions backed by virtual
AMM reserves instead of a spot asset pool. It exercises Testkit fixtures,
assertions, budget/storage inspection and property testing.
Position model
A position stores the trader, signed size, collateral, entry mark, and leverage. Positive size is a long and negative size is a short. The mark is the virtual quote reserve divided by the virtual base reserve.
#![allow(unused)]
fn main() {
let position = client.open_position(&trader, &1, &1_000, &5);
assert_eq!(position.collateral, 1_000);
assert_eq!(position.leverage, 5);
}
Use move_mark in tests to simulate an exchange mark change, unrealized_pnl
to calculate the live result, and close_position to settle and remove the
position.
Margin and liquidation
The maintenance threshold is 10% of the absolute position notional. A position is liquidatable when collateral plus unrealized PnL is at or below that threshold.
#![allow(unused)]
fn main() {
if client.is_liquidatable(trader.clone()) {
client.liquidate(trader);
}
}
The suite verifies that margin additions increase collateral, long and short PnL have opposite signs around the same mark move, and underwater property cases always remain eligible for liquidation.
Funding
set_funding and funding_index provide a testable funding checkpoint without
introducing a token transfer model. Applications can extend the worked example
with funding accrual and settlement against the index.
Validation layout
tests/fixtures.rsbuilds traders and exercises lifecycle inputs.tests/assert.rschecks authorization, PnL and position removal.tests/budget_storage.rsmeasures budgets and storage tiers.tests/property.rsuses proptest for leverage, liquidation, margin and settlement invariants.
Budget-Aware Testing
Soroban contracts execute within strict CPU and memory budgets. Tests that pass locally can fail on-chain once resource consumption exceeds the transaction limits — Testkit makes those costs visible in ordinary assertions.
Why budget matters
The Soroban runtime enforces resource budgets per transaction. The SDK’s test environment does not enforce those limits by default, so a contract can pass every unit test and still fail during deployment or execution on testnet and mainnet.
Basic budget tracking
The SDK meters one call at a time, and the metering of the call that just finished is what a test should read:
#![allow(unused)]
fn main() {
use soroban_testkit_core::budget::BudgetSnapshot;
#[test]
fn test_budget_regression() {
let env = Env::default();
env.mock_all_auths();
// ... invoke function
client.increment(&caller, &1);
let cost = BudgetSnapshot::last_invocation(&env);
assert!(cost.cpu_insns < 1_000_000, "CPU: {}", cost.cpu_insns);
assert!(cost.mem_bytes < 100_000, "Memory: {}", cost.mem_bytes);
}
}
SDK v28 meters each top-level invocation separately: env.cost_estimate().resources() returns what the call that just ran consumed, and env.cost_estimate().budget() returns the same metering as a running total for that call. The older env.budget() accessor is deprecated and should not appear in new tests.
A contract registered with env.register(...) runs as host code, so VM instantiation, wasm execution and rent reads are never metered — the reading is the storage and host-work half of the real cost, not all of it. Treat these numbers as a comparison between builds of the same contract rather than as a fee quote, and use a deployed wasm contract when you need the full figure.
Reading a snapshot
| Field | Meaning | Suggested use |
|---|---|---|
cpu_insns | Instructions metered for one invocation | Regression guard in CI |
mem_bytes | Memory metered for one invocation | Keeps entries under ledger limits |
last_invocation() | Snapshot of the call that just ran | The reading a test asserts on |
diff() | Saturating delta of two snapshots | Comparing two readings of one running budget |
Asserting a limit instead of a number
BudgetGuard carries the two limits a reviewer can argue about: a ceiling this
call may not cross, and a growth allowance against the cost recorded the last
time the case was measured.
-
Name the case
BudgetGuard::new("transfer"). The name is what every failure line carries, so a CI log points at an operation rather than at a test file. -
Set the ceilings
.cpu_ceiling(2_000_000).mem_ceiling(500_000)— absolute limits, independent of history. -
Add the baseline
.baseline(Some(recorded)).tolerance_percent(10)rejects a call that grew more than 10% past the recorded cost. A tolerance of0means not one instruction more. -
Measure the call
.run(&env, || client.transfer(&from, &to, &1000))makes the call, reads the metering that call left behind, asserts against it, and returns the invocation's value.
#![allow(unused)]
fn main() {
use soroban_testkit_core::budget::BudgetGuard;
#[test]
fn increment_stays_inside_its_budget() {
let ctx = TestContextBuilder::new().with_users(1).build();
let (id, client) = register(&ctx);
let caller = ctx.users[0].clone();
BudgetGuard::new("increment")
.cpu_ceiling(20_000_000)
.mem_ceiling(20_000_000)
.run(&ctx.env, || client.increment(&caller, &1));
}
}
The budget_guard! macro is the same assertion written around the call:
#![allow(unused)]
fn main() {
use soroban_testkit_core::budget_guard;
budget_guard!(&env, "transfer", {
cpu_max: 2_000_000,
mem_max: 500_000,
baseline: recorded, // Option<BudgetSnapshot>
tolerance: 10, // percent
}, || client.transfer(&sender, &receiver, &1000));
}
A guard reports every limit a cost breaks — ceilings first, then growth — instead of stopping at the first. One run tells you whether a change moved CPU, memory, or both.
Committing the numbers: baseline files
A baseline is a JSON file mapping case names to the cost recorded for them, so the limits live in the repository and a pull request shows a cost change as a diff.
{
"version": 1,
"cases": {
"get": { "cpu_insns": 7861, "mem_bytes": 1510 },
"increment": { "cpu_insns": 32669, "mem_bytes": 5252 }
}
}
#![allow(unused)]
fn main() {
use soroban_testkit_core::budget::BudgetBaseline;
let mut baseline = BudgetBaseline::load(std::path::Path::new("tests/budget.json")).unwrap();
baseline
.guard("increment") // carries the recorded cost for the case
.tolerance_percent(5)
.run(&env, || client.increment(&caller, &1));
// Re-record and commit the file when a cost change is intended:
baseline.record("increment", measured_cost);
baseline.save(std::path::Path::new("tests/budget.json")).unwrap();
}
guard() on a case the file does not know returns a guard with no baseline, so
a new operation is only bounded by whatever ceilings the test adds — the missing
case never fails a suite by itself. A file written by a newer Testkit is refused
rather than half-read.
Machine-readable output
Every breach renders as one line of key=value pairs, which is what lets a CI
step grep, annotate, or trend them:
BUDGET kind=ceiling case=transfer metric=cpu_insns actual=2500000 limit=2000000
BUDGET kind=growth case=transfer metric=mem_bytes actual=610000 limit=550000 baseline=500000 tolerance_percent=10
| Field | Meaning |
|---|---|
kind | ceiling (absolute limit) or growth (past a baseline) |
case | The name the guard was built with |
metric | cpu_insns or mem_bytes |
actual / limit | Measured cost and the largest value still accepted |
baseline / tolerance_percent | Only on growth, so the ratio is recoverable from the line |
Running the check in CI
The counter example ships the whole loop: examples/counter/budget.json records
the cost of its two hot paths, and two #[ignore]d tests in
examples/counter/src/test.rs drive it.
# record the costs where they will be enforced
cargo test -p soroban-testkit-example-counter -- --ignored --nocapture \
budget_baseline_records_current_costs
# compare a run against the committed file
TESTKIT_BUDGET_TOLERANCE=5 cargo test -p soroban-testkit-example-counter -- --ignored --nocapture \
budget_baseline_rejects_drifted_costs
Both are ignored on purpose. Soroban metering is deterministic, so the reading is a property of the contract and the pinned SDK rather than of the machine that ran it — the file recorded on Windows measured identical on ubuntu-latest, drift=+0.00% on every metric. What that means is that an SDK or env-host bump moves every number at once, and the recording test rewrites a file in the repository, so neither belongs in cargo test --workspace. The Budget baseline workflow runs them where Cargo.lock and the runner are fixed: one pinned ubuntu-latest, the numbers printed in the job summary, a comment on the pull request, and a failure when a case grows past the tolerance — 10% by default, tolerance on a manual run, fail_on_drift off when you want the report without the verdict.
BUDGET_SUMMARY case=get metric=cpu_insns actual=7861 baseline=7861 drift=+0.00%
BUDGET_SUMMARY case=increment metric=cpu_insns actual=32669 baseline=32669 drift=+0.00%
| Field | Meaning |
|---|---|
case | The key in the committed budget.json |
actual | What the call cost on this runner |
baseline | What the committed file says it cost |
drift | actual against baseline, signed percent |
A breach then follows as the usual BUDGET kind=growth … line, so the same grep
covers both the check and an in-test guard.
-
An unintended rise
The job fails and the comment says which case, which metric and by how much. Nothing to record — the code is what has to change.
-
An intended rise
Run the workflow with Record checked: it rewrites
budget.jsonon the same runner that enforces it and uploads the file as an artifact. Commit that file on the branch, and the pull request diff reads as a reviewable statement —increment: 32669 → 41000— rather than a red check someone retried.
The metering the SDK reports belongs to the top-level invocation that has just finished, so a closure that makes two calls is judged on the second one. Give each call its own guard, and name the case after the call you care about.
Diffing two baselines
The counter example records one file; a pull request has two — the baseline on
the base branch and the one the branch records. budget-diff compares them,
prints a table, and exits non-zero when a case grew past a percentage.
cargo run -p soroban-testkit-core --bin budget-diff -- \
budget-main.json budget-pr.json \
--threshold 5 \
--output-markdown budget-comment.md
### Soroban budget diff
Threshold: `5%`. 2 case(s) compared, 1 regression(s).
| Case | CPU instructions | Δ CPU | Memory bytes | Δ memory | |
|------|------------------|-------|--------------|----------|---|
| `get` | 7861 | 0 | 1320 | 0 | 🟢 |
| `increment` | 32669 → 35000 | +2331 (+7.14%) | 5252 | 0 | 🔴 |
**1** case(s) grew past the 5% threshold.
| Option | Meaning |
|---|---|
BASE.json / HEAD.json | The two baseline files, or --base / --head by name |
--threshold PCT | How far a case may grow; --fail-on-regression is the same flag |
--output-markdown FILE | Also write the table to a file for a PR comment (--output is an alias) |
--allow-missing-base | Treat a base branch that has no baseline yet as empty |
Exit codes are the contract: 0 no case grew past the threshold, 1 at least
one did, 2 a usage error. A case that only exists in one of the two files is
reported as new or removed and never fails the run — there was nothing to grow
from. Growth is measured per metric against its own base, so a case that costs
more CPU and the same memory is one regression, not two.
A reusable workflow
.github/workflows/templates/budget-check.yml is a workflow_call template: it
takes the baseline path and the command that records it, lifts the base branch’s
copy with git show, runs the comparison, writes the table into the job summary,
and posts it as a sticky comment keyed on a marker so reruns replace the previous
one rather than stacking.
jobs:
budget:
uses: ./.github/workflows/budget-check.yml
with:
baseline: tests/budget.json
test-command: cargo test -p my-contract -- --ignored --nocapture record_baseline
threshold: "5"
The job needs contents: read and pull-requests: write; a run from a fork
cannot comment, so that step is allowed to fail while the comparison step is the
one that decides the build. Set allow-missing-base on the first pull request
that introduces a baseline.
Related: Property testing for inputs, soroban-testkit-core for the full budget API.
Property Testing
Property-based testing checks invariants across hundreds of generated inputs, catching the edge cases example-based tests miss. Testkit’s generators keep those inputs inside ranges Soroban actually accepts.
Setup
Enable the proptest feature:
[dev-dependencies]
soroban-testkit-generators = { version = "0.4.1", features = ["proptest"] }
proptest = "1"
Basic property test
#![allow(unused)]
fn main() {
use proptest::prelude::*;
use soroban_testkit_generators::strategies;
proptest! {
#[test]
fn balance_never_negative(amount in strategies::token_amount()) {
// All generated amounts are >= 0 and within realistic bounds
assert!(amount >= 0);
}
}
}
Combining with fixtures
#![allow(unused)]
fn main() {
proptest! {
#[test]
fn transfer_preserves_supply(
amount_a in strategies::token_amount(),
amount_b in strategies::token_amount(),
) {
let ctx = TestContextBuilder::new().with_users(2).build();
// ... initialize balances, perform transfers
// ... assert total supply unchanged
}
}
}
Every generated case builds a real Env and executes on the host. If the suite slows down, reduce cases with #![proptest_config(ProptestConfig::with_cases(64))] before you narrow the strategy ranges.
examples/token/tests/property.rs is a suite that follows every rule on this page: five cases over a live contract at 64 iterations, three strategy-only cases at 256, prop_assume! for the relations between generated amounts, and both address formats on the same call. Worked Example: Token walks through it.
Generating principals
Access-control properties need callers, and a caller in Soroban is an address rather than a string. address() generates a valid 32-byte principal in either format, account_address() and contract_address() pin one, and address_of_type(AddressType::Account) takes the format as an argument. Each yields an AddressBytes, which becomes a host value through to_address(&env).
#![allow(unused)]
fn main() {
use soroban_testkit_fixtures::builder::TestContextBuilder;
use soroban_testkit_generators::strategies;
proptest! {
#[test]
fn only_the_caller_moves_their_balance(
caller in strategies::account_address(),
amount in strategies::token_amount(),
) {
let ctx = TestContextBuilder::new().build();
let caller = caller.to_address(&ctx.env);
// ... register the contract, fund `caller`, then assert that the same
// call from a different address fails or records no authorization
}
}
}
Generating the contract form is what catches an address-format assumption — a C... id where the code only ever saw a G... account. The full list with return types is in the strategy reference.
Every generated address carries a process-wide nonce, so two calls in one test run never collide even when their random prefixes do. The trade-off is that a value depends on generation order: judge a failing case by the bytes proptest prints rather than by replaying a seed alone.
Differential testing against a reference model
A property test asserts something you can state without computing it — supply is conserved, a balance never goes negative. When you can compute the answer, compare against it: write the rule once as a contract and once as plain Rust, and check that every generated input makes the two agree. DifferentialHarness runs both sides and shrinks the first disagreement down to a small input you can paste into a regression test.
#![allow(unused)]
fn main() {
use soroban_testkit_generators::differential::DifferentialHarness;
use soroban_testkit_generators::strategies::token_amount;
let harness = DifferentialHarness::new();
harness.compare(
token_amount(),
|amount| client.calculate_fee(&amount),
|amount| reference_fee_calculator(amount),
);
}
The first closure is the contract, the second the model. Both take the generated input by value, so the contract call borrows it (&amount) while the model consumes it. compare panics on the shrunk input, naming what each side did with it:
contract diverged from its reference model
smallest failing input: 1
return value: contract 1, model 0 (contract is 1 from the model)
tolerance: 0
That line is what diff reports without panicking, which is the form you want when the comparison is one of several checks in a test:
#![allow(unused)]
fn main() {
let report = DifferentialHarness::new()
.cases(64)
.tolerance(1)
.diff(token_amount(), |amount| client.calculate_fee(&amount), reference_fee_calculator);
assert!(report.is_match(), "{}", report.failure().unwrap().render(1));
}
tolerance is how far apart two numbers may be and still count as equal — absolute units, not a percentage. A fee the contract rounds half-up and the model truncates is one unit out on every odd amount, and .tolerance(1) says so without also forgiving a fee computed off the wrong basis. Non-numeric results ignore the tolerance: false is never one unit from true, and a u128 above i128::MAX has no signed form to diff.
Shrinking is proptest's, and it walks down from a failing case to a smaller one that still fails, stopping at the first dead end. For a bug that only shows on odd amounts, that dead end can be a large odd number rather than 1. Take the printed payload as the reproducer — paste it into an example-based test — or pin generation with .seed(7), which replays the same inputs in the same order.
Comparing state as well as the return value
A call on a ledger can return the right number and write the wrong state, which is why a side may return an ExecutionTrace instead of a bare value. with_state names a storage key the call leaves behind, and the harness compares keys the same way it compares return values:
#![allow(unused)]
fn main() {
use soroban_testkit_generators::differential::{DifferentialHarness, ExecutionTrace};
let report = DifferentialHarness::new().diff(
token_amount(),
|amount| {
let fee = client.calculate_fee(&amount);
ExecutionTrace::new(fee).with_state("fee_total", client.fee_total())
},
|amount| {
let fee = reference_fee_calculator(amount);
ExecutionTrace::new(fee).with_state("fee_total", fee)
},
);
}
Keys are strings you choose rather than symbols read off the ledger, which is what lets the model side record state without building an Env. Two consequences follow from that. A key only one side records is itself a divergence, reported against <unset>, so both sides have to name the same keys for the comparison to mean anything. And a contract that writes four keys needs four with_state calls: a trace that names one of them proves one of them.
Differential tests belong next to the arithmetic rather than the access control: bonding curves, fee splits, AMM invariants, interest accrual. Anywhere a second, simpler implementation is cheaper to write than the bug is to find. Every case builds a real Env for the contract side, so narrow the strategy with a generator before you raise the case count.
Stateful property-based testing with state machines
Stateful property testing generates sequences of contract calls and verifies invariants after each step. This catches bugs that only appear across multiple interacting transactions (e.g., deposit → lock → vote → withdraw → claim). Testkit provides a state machine harness built on proptest::state_machine.
Defining a state machine
#![allow(unused)]
fn main() {
use soroban_testkit_generators::state_machine::{SorobanStateMachine, SorobanStateMachineRunner};
use soroban_sdk::{Env, Address, testutils::Address as _};
#[derive(Clone, Debug, Default, PartialEq, Eq)]
struct TokenModel {
balances: std::collections::HashMap<Address, i128>,
total_supply: i128,
}
#[derive(Clone, Debug, PartialEq, Eq)]
enum TokenAction {
Mint { to: Address, amount: i128 },
Transfer { from: Address, to: Address, amount: i128 },
Burn { from: Address, amount: i128 },
}
struct TokenStateMachine {
env: Env,
}
impl SorobanStateMachine for TokenStateMachine {
type Action = TokenAction;
type Model = TokenModel;
type Context = TokenTestContext;
fn generate_action(&self, model: &Self::Model) -> BoxedStrategy<Self::Action> {
// Generate actions based on current model state
}
fn check_precondition(&self, model: &Self::Model, action: &Self::Action) -> bool {
// Validate action against model state
}
fn execute(&self, context: &mut Self::Context, action: &Self::Action) -> Result<(), String> {
// Execute action against real contract
}
fn apply_to_model(&self, model: &mut Self::Model, action: &Self::Action) {
// Update expected model state
}
fn check_invariant(&self, model: &Self::Model, context: &Self::Context) -> TestCaseResult {
// Verify invariant (e.g., total supply conservation)
}
fn initial_model(&self) -> Self::Model {
TokenModel::default()
}
fn create_context(&self) -> Self::Context {
TokenTestContext { ... }
}
}
}
Running the state machine
#![allow(unused)]
fn main() {
let machine = TokenStateMachine::new();
let runner = SorobanStateMachineRunner::new(machine).cases(100);
runner.run().unwrap();
}
Or use the simpler prop_state_machine_test function:
#![allow(unused)]
fn main() {
use soroban_testkit_generators::state_machine::prop_state_machine_test;
prop_state_machine_test(machine, 20, 100).unwrap();
}
Key features
- Automated invariant verification after each transition
- Precondition checking to filter invalid actions
- Automated shrinking of failing action sequences to the minimal failing sequence
- Sequences of length ≥ 50 supported
- Integration example: Token balance conservation invariant verification
When to use property testing
Arithmetic
Supply conservation, no overflow, and rounding that stays consistent across amounts.
State machines
A valid state remains reachable after any sequence of operations, not just the one you scripted.
Access control
Unauthorized callers fail regardless of the parameters they present.
Boundaries
Zero amounts, maximum values and empty collections are generated rather than remembered.
Strategy reference: soroban-testkit-generators.
Contributing
Contributions of every size are welcome. The repository guide — CONTRIBUTING.md — is the authoritative version; this page summarises the flow and the rewards.
Contribution flow
-
Fork and clone
Create your fork of
stellar-crucible/soroban-testkit, thencargo test --workspace --lockedto confirm a green baseline (470 tests run locally; two more are#[ignore]d and belong to CI). -
Claim an issue
Every funded task carries both
Stellar Waveand acomplexity:*label. Comment on the issue before starting so two contributors do not collide — Wave issues are first-come, first-served. If this is your first pull request here, start from thecomplexity:triviallist: those are scoped to one accessor, one method or one page, and each states the acceptance criteria it will be merged against. -
Branch, commit, check
Run
cargo fmt --all --checkandcargo clippy --workspace --all-targets --locked -- -D warningslocally.mainis protected:Malware guard,Secret scan,CI integrity,check,Docs buildandSupply chain auditmust all be green before a pull request can merge.Malware guardis a dependency of the last three, so nothing compiles your Rust until it has passed —cargo testexecutes abuild.rsin your diff whether or not anyone has read it yet. Another job,Budget baseline, runs on any pull request that touches the counter example or the budget code — it re-measures the hot paths and comments the numbers on the pull request. -
Open a pull request
Reference the issue, describe what changed and why, and include the test evidence for behaviour changes. If
Malware guardgoes red, read what it printed: it names the file, the line and the rule. An issue off the tracker will not come near it, and a deliberate change that does — a build script, an edit to CI — is allowed once you have explained it and a maintainer has applied thesecurity-overridelabel. Do not reword the line it caught to slip past; the label leaves a record and a worked-around check leaves nothing.
Stellar Wave rewards
This project participates in the Stellar Wave program on Drips Network. Every issue carries a complexity label, and rewards land when the pull request merges.
100 points
Docs, small type fixes, one-line helpers. Expected within a day or two.
150 points
A new matcher, a generator family, or an API that touches one crate.
200 points
Cross-crate features, storage enumeration, or anything needing design discussion first.
If an issue is not merged inside the monthly cycle it carries over with its label intact — picking it up late still pays.
Unsure whether an issue is the right size, or stuck on a host behaviour that looks wrong? The Telegram channel is where the maintainer reads questions — asking there costs a minute and saves a pull request that has to be rescoped.
Ready to start? The tracker lists every open task with its complexity label and acceptance criteria.
Browse issuesRoadmap
Where Soroban Testkit is going, and which parts are open for contributors. Anything listed here is a proposal until an issue exists for it — the tracker is the source of truth.
Shipped in v0.1.0
Test context + builder
One call to get a mocked Env, an admin address and pre-generated users.
Event and auth matchers
Chainable assert_emitted, assert_count, assert_no_auth_required, with contract and topic filtering.
Budget snapshots
Read the CPU and memory one call metered, and diff two readings of a running budget.
proptest strategies
Token amounts, ledger sequences and timestamps bounded to realistic ranges.
Test suite for the toolkit
Unit tests in all four crates, plus cargo fmt, clippy -D warnings, docs build and a cargo deny supply-chain gate in CI. Every pull request is also inspected before anything compiles it: a malware guard over the diff, a secret scan, and an audit of the pipeline itself.
Worked integration example
A real Soroban contract tested with fixtures, event matchers, budget assertions and authorization failures.
Landed since v0.1.0
Storage snapshots and diffs
StorageSnapshot::capture enumerates a contract's live instance, persistent and temporary entries from the ledger snapshot, and diff() reports added, removed and rewritten keys — #4, closed.
Negative event assertions
assert_not_emitted() and assert_none_match() prove a topic stayed silent, quoting the unexpected event when they fail — #11, closed.
Event payload assertions
assert_data_matches() reads what an event carried — a typed deserialize, one field of the map a #[contractevent] struct publishes, or the raw ScVal — and a failure prints every payload it rejected — #18, closed.
Events aggregated across calls
EventLog gathers each invocation's events as a test runs, and matcher() hands the sequence to the same filters and assertions — so assert_count, with_topic and assert_not_emitted speak about several calls at once, and topics() reads the order back — #19, closed.
Error code decoder
DecodedError::from_error names the host category and meaning behind a packed error code, and ErrorRegistry adds words for your own #[contracterror] codes — #5, closed.
Ledger time helpers
advance_time(), set_timestamp() and advance_ledger() move the clock or the height on their own, so a vesting or TTL test reads as a span instead of as a hand-built LedgerInfo — #12, closed.
Context reset
reset() swaps in a fresh env — ledger, events, auths and storage gone — and carries every address across, so a two-phase test keeps its actors instead of rebuilding its fixture — #17, closed.
Budget regression detection
BudgetGuard and budget_guard! hold a call to a CPU and memory ceiling plus a growth allowance against a recorded cost, and BudgetBaseline keeps those costs in a committed JSON file — every breach printed as one parseable line — #3, closed.
Budgets diffed in CI
examples/counter/budget.json commits the counter's hot-path costs, one ignored test records them and another enforces them, and the Budget baseline workflow runs the check on a pinned runner and reports every case on the pull request — #14, closed.
Address strategies
address(), account_address(), contract_address() and address_of_type() generate valid 32-byte Soroban principals as an AddressBytes that carries its format tag and converts straight to a host Address, with a process-wide nonce keeping every address in a run unique — #7, closed.
A second worked example
An ERC-20 shaped token whose suite is split one file per crate, so the parts the counter cannot reach are demonstrated rather than described: a three-field event payload, two contracts registered in one environment, storage tiers behind a pattern, and a proptest over generated amounts and both address formats — #9, closed.
Published on crates.io
All four crates are live on the registry as soroban-testkit-core, -assert, -fixtures and -generators, with 0.4.1 as the current stable release, so a consumer adds a version requirement instead of a Git pin. The release tag stays available for anyone who wants to pin the source commit its CI went green on.
Next cycle
Never contributed here before? The three complexity:trivial rows are the intended first pull request — each is one API or one page, scoped tightly enough to finish in an evening, and each lists the acceptance criteria it will be judged against.
| Area | Work | Complexity |
|---|---|---|
| Assertions | Enumerate a struct event’s field names (#50) | complexity:trivial |
| Fixtures | A user(index) accessor that explains its own panic (#51) | complexity:trivial |
| Docs | A troubleshooting page for the four failures that cost newcomers the most time (#52) | complexity:trivial |
| Assertions | assert_event_emitted! macro with topic and data matching (#1) | complexity:high |
| Assertions | assert_auth_matches! macro (#2) | complexity:medium |
| Assertions | assert_storage_tier! — prove a key landed in instance, persistent or temporary storage (#13) | complexity:medium |
| Generators | XDR-compatible value generation (#8) | complexity:high |
| Generators | Arbitrary implementations for Soroban types (#16) | complexity:medium |
Later
Non-goals
It will not replace the official SDK's testing primitives, will not become a network simulator or transaction builder, and will not fork soroban-env-host. Testkit stays a thin, composable layer on top of the SDK.
Shaping the roadmap
Roadmap items start life as issues. If you want a feature that is not here, open a discussion in the issue tracker; if it is accepted and labelled with a complexity tag, it enters the next Wave cycle.
Everything above is claimable once labelled. Pick something that matches the time you have.
Open the tracker