Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

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.

Packagesoroban-testkit-core
Modulesbudget · error · storage · dependency · footprint · wasm · profiler · reentrancy · conservation
Budget tracking, error decoding, storage inspection and contract dependency graphs — the primitives the rest of Testkit is built on.
Packagesoroban-testkit-core
Modulesbudget · diagnostic_event · instruction_profiler · error · storage · dependency · footprint · reentrancy · conservation
Dependenciessoroban-sdk · soroban-env-host · serde · serde_json

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

TypePurpose
BudgetSnapshotCPU instructions and memory bytes — last_invocation() for the call that just ran
BudgetReadTrait implemented by any source capture() can read: invocation resources, the SDK budget, the host Budget
BudgetGuardCeilings and a baseline tolerance for one named operation
BudgetViolation, ViolationKindThe limit a cost broke, rendered as one parseable line
BudgetMetricWhich resource a violation was measured against — Cpu or Memory, and the cpu_insns / mem_bytes word as_str() prints for it
BudgetBaselineRecorded costs per case, loaded from and saved to a JSON file
budget_guard!Macro form of the guard around a single invocation
InstructionProfilerCPU instruction deltas across labeled checkpoints, with text and Markdown reports
InstructionStepOne labeled segment and its consumed CPU instructions
MemoryPressureAuditorMeasures what each invocation allocated, copied and kept live; measure() returns the call’s value
AllocationProfileOne invocation’s allocations, allocated bytes, peak live bytes, copied bytes, churn ratio and efficiency score
AllocationReportEvery measured profile, the hotspot filter and the Markdown report
DecodedErrorA Soroban error code split into category, meaning and context
ErrorRegistryYour #[contracterror] codes mapped to the words they mean
ClientOutcome, unwrap_decodedUnwrap a v28 try_* client call, panicking with the decoded error
StorageEntry, StorageTierA live storage key, its rendered value, tier and expiry ledger
StorageSnapshotEvery live entry of one contract, captured at a point in time
StorageDiff, StorageChangeKeys added, removed and rewritten between two snapshots
FootprintSnapshotXDR byte size of every live storage key of one contract, by tier
RentParameters, RentEstimateProtocol fee parameters and the Stroop cost of keeping a footprint alive for N ledgers
StorageFootprintFootprints for several contracts, loaded from and saved to a JSON artifact
StorageFootprintDiffBase vs head footprints: growing keys, a Markdown report, a growth threshold
DependencyGraphDirected graph of inter-contract calls, built from an invocation’s fn_call diagnostics
DependencyEdgeOne caller → callee edge with its call count and functions
DependencyCycleA closed call chain such as A -> B -> C -> A, with self-recursion as A -> A
storage-footprint-diffBinary wrapping StorageFootprintDiff for CI
BudgetDiff, BudgetCaseDiffBase vs head baselines: signed deltas, growth percent, a Markdown report and the cases past a threshold
budget-diffBinary wrapping BudgetDiff for CI
HostExecutionProfiler, HostExecutionSummaryRepeated call latency and explicit host-operation measurements
WasmSectionAnalyzer, WasmAnalysisWASM section sizes, deployment limits and debug/bloat warnings
StorageFragmentationAnalyzerAnalyzes key-to-value serialization overhead, detects fragmentation, and estimates Stroop savings
FragmentationReportComprehensive metrics across tiers, high-overhead alerts, and Markdown recommendations
StackDepthAuditorReconstructs a contract call chain from host diagnostic events and checks it against a depth cap
CallFrameOne invocation in that chain: depth, contract id, function
StackDepthBreachA trace deeper than its cap, rendered with every frame
CompatibilityAuditorEvaluates contracts against upcoming SDK v29 / Protocol 22+ changes and flags deprecated host calls
CompatibilityScorecardActionable readiness scorecard with grades, remediation advice, and Markdown output
ReentrancyGuardAuditorStatically and dynamically analyzes lock flag state across multi-frame calls and external callbacks
LockStateUninitialized, Locked, or Unlocked reentrancy guard states
ReentrancyReportComprehensive violation diagnostics and visual ASCII state access ordering timelines
ReentrancyViolationFlagged uninitialized, unlocked, premature release, dangling, or indirect reentrant calls
ReentrancyDetectorWatches one invocation for CEI ordering flaws and re-entry attempts, scoped by monitor(label, closure)
DetectorViolation, DetectorViolationKindOne detector finding: CeiViolation or ReentrancyAttempt
MockReentrantAttackerTest contract that publishes a re-entry attempt against a target contract
emit_storage_read, emit_storage_write, emit_external_call, emit_reentry_attemptEmit the detector’s instrumentation contract events
CoverageAuditorDetects uninvoked functions and dead code across contract WASM, spec XDR, and client definitions
CoverageReportAggregates execution metrics, coverage percentages, Markdown tables, and plaintext summaries
ClientDefinitionTyped representation of contract client entry points for coverage auditing
client_definition!Macro for concise client entry point declaration
CallTracerRecovers 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, CallOutcomeOne traced contract frame, and whether it returned, failed (with the host error) or is unknown
TtlInspectorLive TTL of a storage entry in any tier, read without triggering eviction or auto-restore, with the ledger’s rent thresholds
TtlStatus, RentThresholdsLive / Expired (temporary) / Archived (persistent, instance), and the ledger’s min/max TTL parameters
TtlExtensionAn entry’s TTL before and after a call, checked against the host’s extend_ttl rules
DiagnosticEventAuditorInspects host diagnostic events, categorizes them, enforces count limits, and flags suspicious payloads
DiagnosticEventReportStructured audit result with counts, categories, events, and findings; renders text logs
InstanceBloatDetectorInstance-storage footprint and dynamically growing collection diagnostics
InstanceBloatWarningA 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.

SDK v28 note

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)
});
}
Every breach, not just the first

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.

Recording a baseline

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.

Only new, non-instance keys are leaks

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, &registry);
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);
}
Scope

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(&params, 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.

A warning is not a failure

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.

What the trace cannot show

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:

  1. Reentrancy locks are set (LockState::Locked) before any external invocation is performed.
  2. Locks are initialized and never accessed while uninitialized.
  3. Locks are not prematurely released before external calls finish.
  4. 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:

TopicValue
0Symbol("tk_reentry") — protocol marker
1Symbol("storage_read"), "storage_write", "external_call", or "reentry_attempt"
2Symbol(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.