Kanatoko
Test Soroban contracts against real Stellar state without deploying to a public network.
Kanatoko runs your Rust scenario in one mutable Soroban environment. It automatically discovers every network contract, WASM, account, trustline, and storage entry the scenario touches, freezes them at one ledger, and replays the test locally with no RPC fallback.
You can also install the contract you are developing into that fork. Your local WASM and captured network contracts then call each other normally.
[]
= { = "29", = ["capture"] }
Choose the Kanatoko major that matches the ledger protocol being captured. The selected Host executes finalized contract WASM built for that protocol or an older one:
| Ledger protocol | Kanatoko | Contract WASM |
|---|---|---|
| 27 | kanatoko = "27" |
Protocol 27 or older |
| 28 | kanatoko = "28" |
Protocol 28 or older |
| 29 | kanatoko = "29" |
Protocol 29 or older |
| 30 | kanatoko = "=30.0.0-rc.2" (prerelease) |
Protocol 30 or older |
The 29 line uses the stable Soroban Rust SDK and ledger snapshot 29 with the compatible Host 29 runtime. Use the Kanatoko major matching the network protocol being captured; the runner fails closed rather than replaying state under a different Host. Until a matching line exists, a network exactly one protocol ahead can be captured and replayed through an explicit opt-in; see A network one protocol ahead.
Your contract against mainnet
Kanatoko 29 captures and replays Protocol 29 Mainnet state. The committed CLI fixture is a Protocol 29 capture; its historical Protocol 27 and 28 predecessors are retained separately only to test fail-closed cross-protocol loading.
Suppose my_vault.wasm accepts a token address in its constructor and
asset_decimals() calls that token contract:
use mainnet;
// Native XLM Stellar Asset Contract on mainnet.
const XLM: &str = "CAS3J7GYLGXMF6TDJBBYYSE3HQ6BBSMLNUQ34T6TZMYMW2EVH34XOWMA";
New code at a production address
Replace only the executable of an existing captured contract to test a new version against its production storage:
use mainnet;
const VAULT: &str = "C...";
replace_wasm preserves the address, instance/persistent/temporary storage,
and their TTLs. It does not call the constructor. Every captured contract that
calls the same address sees the replacement code.
This is a local code override, not an upgrade transaction: it does not call the production upgrade method or test its authorization, delays, events, fees, or signatures. If the replacement touches ledger keys absent from an older cache, an online run recaptures them; offline mode fails closed until then.
The cache file is generated automatically under .kanatoko/ from the selected
network, test thread name, and runner callsite. The first run discovers the
scenario's network dependencies. Each later online run probes the current
ledger: an exact anchor match replays the cache without ledger-entry reads,
while a changed anchor reloads every known key in coherent batches and then
discovers additions. State values from different ledgers are never mixed.
Use .cache(path) to override the path, .refresh() to force a cold capture
with an empty key inventory, or .offline() in CI to replay the cached ledger
as an explicitly pinned snapshot with zero transport calls.
Offline example
examples/offline_replay.rs replays the committed Soroswap XLM/USDC Mainnet
capture and prints a 1 USDC to XLM quote, using only that bundle and no RPC:
Network and RPC
mainnet() and testnet() expose the same API and default RPC endpoints, but
each validates the selected network's exact live protocol. During a staggered
network upgrade, use the Kanatoko major matching each network independently:
use ;
testnet
.run
.unwrap;
mainnet
.rpc_url
.rpc_rate_limit
.run
.unwrap;
An RPC override changes only the provider, never the selected network
passphrase. Capture fails if that provider reports another network. Automatic
cache paths include the network identity but not the RPC URL, so mainnet and
testnet cannot share a default cache while two providers for the same network
can. Every online run validates the configured RPC and probes its complete
latest-ledger anchor. An exact cache hit therefore performs getNetwork and
getLatestLedger, but no getLedgerEntries. Only .offline() ignores an
invalid RPC URL and makes no network calls. RPC pacing is disabled by default;
.rpc_rate_limit(5) opts into a five-request-per-second limit within each
capture run that also covers retry attempts. Separate capture runs do not
share a quota.
Cold capture retries throttled or transient read-only responses (429, 500,
502, 503, and 504) up to four total attempts with 200/400/800 ms
backoff. A reasonable numeric Retry-After is honored up to five seconds.
Other HTTP failures, transport failures, malformed responses, and JSON-RPC
errors fail immediately.
After retries are exhausted, Kanatoko stops issuing reads and returns a typed
CaptureError::Transport; a failed read is never mistaken for absent ledger
state. Capture discovery suppresses the inner Host panic output so the
transport error remains the actionable diagnostic.
Once ledger keys are known, Kanatoko fetches their coherent state in batches of up to 200. This includes the complete inventory reused from an older ledger; only the keys are reused, never their old Present/Absent values. The first encounter with a newly discovered dynamic key remains a single read because the returned value may determine which key the contract touches next.
Protocol 28 external executable references are closed transitively: Kanatoko captures the owner's persistent executable-tag entry, validates its exact 32-byte WASM hash, and captures the referenced ContractCode. A missing or malformed reference fails closed during capture and bundle loading.
For lower-level capture, use CaptureBuilder::mainnet(url) or
CaptureBuilder::testnet(url) and apply the same .rpc_rate_limit(...)
setting when needed.
Candidate code and its own storage remain local to each pass. Rebuilding it does not invalidate the cache unless it starts touching new external ledger keys. Online mode seeds recapture from the cached key inventory even when the ledger anchor has not changed; offline mode fails closed until the cache is refreshed.
A network one protocol ahead
When a network upgrades before the matching Kanatoko line is available, a Kanatoko line whose Host runs Protocol N can opt into capturing and replaying a ledger exactly one protocol newer, Protocol N+1, and execute it on its own Protocol N Host. This works only while Protocol N+1 keeps the ledger XDR that the Protocol N line decodes.
Protocol 30 networks. Protocol 30 changed the ledger header format, so the
29 line cannot capture from Protocol 30 networks: testnet now, and Mainnet
after its upgrade. Capture fails with UnsupportedProtocol, also with the
opt-in. For those networks, use kanatoko = "=30.0.0-rc.2" until 30.0.0 is
released. Committed bundles still replay offline on the 29 line.
On the 29 line the opt-in still replays a Protocol 30 capture offline, executed as Protocol 29:
use mainnet;
mainnet
.allow_newer_protocol
.cache
.offline
.run
.unwrap;
The same opt-in exists on every API that checks the protocol:
CaptureBuilder::allow_newer_protocol(),
CapturedFixture::from_file_allowing_newer_protocol(...),
FrozenFixture::from_file_allowing_newer_protocol(...) and
FrozenFixture::from_snapshot_allowing_newer_protocol(...), and
--allow-newer-protocol on the CLI's capture and run commands. The flag
also applies to .offline() cache loads. Against a network on the Host's own
protocol the opt-in changes nothing.
- One protocol only. The mode accepts the Host's own protocol
(
SUPPORTED_PROTOCOL_VERSION) or exactly the next one. Older ledgers and ledgers two or more protocols ahead still fail withUnsupportedProtocol. Without the opt-in, behaviour and errors are unchanged. - Captures stay truthful. Bundles, their ledger snapshot, provenance, and the ledger, inventory, and bundle digests keep the real network protocol. A Protocol N+1 bundle written this way has the same format and digests as one written by the Kanatoko N+1 line, and loaders without the opt-in reject it.
- Only execution is downgraded. Every
Envgives the Host its own protocol as the ledger protocol, so a scenario'sEnvreports the executed protocol in its ledger info. Fork digests, receipt digests, and checkpoints keep the network protocol. - Traceable.
network_protocol_version()andexecuted_protocol_version()onScenarioFork,InvocationReport,StrictFork, andFork, plusCaptureProvenance::executed_protocol_version()andFrozenFixture::executed_protocol_version(), expose both protocols. The CLI prints a one-line warning to stderr and addsnetworkProtocolandexecutedProtocolto its report and to every receipt.
Behaviour that changed in the Host without an XDR change follows the older
Host. When Kanatoko 28.1.0 ran Protocol 29 on Host 28.0.2, that was WASM parse
metering (Protocol 29 also counts br_table targets and custom sections), the
removal of a separate WASM pre-validation pass, extend_ttl saturating instead
of failing on an overflowing TTL, and a Stellar Asset Contract error message.
A candidate installed locally recorded different ContractCodeCostInputs than
on a Protocol 29 Host, so ledger digests taken after that install differed,
while the committed Mainnet pool strict workflow returned identical quotes,
results, events, authorization trees, and state changes on both Hosts. Treat
resource estimates and metering-sensitive results as evidence from the older
Host.
Natural guards still fail closed and are never caught or softened: ledger data
the older XDR cannot decode, which capture reports as UnsupportedProtocol for
the network's protocol, and contracts whose WASM declares a newer interface
protocol (contract protocol number is newer than host). Move to the Kanatoko
major matching the network once it is available.
One environment, both kinds of contract
fork.deploy(...) installs your candidate WASM and executes its constructor,
if defined. It returns an address for generated clients or dynamic calls:
let app_id = fork.deploy;
let typed = new;
let value = fork.;
Local IDs are deterministic, network-scoped hashes rather than the SDK's small counter addresses, which can already hold balances on a live network. An existing contract instance at the generated ID is still rejected. Upgrading from counter-based IDs changes the keys touched by a scenario: refresh its capture on a compatible network, or keep the original Kanatoko version pinned for historical replay. Unknown keys remain errors.
For a captured address, a local contractimport! file supplies only Rust
bindings. Calls still execute the instance and WASM loaded from Stellar. A
stale incompatible ABI fails instead of silently replacing network code.
Contracts without local bindings can be invoked dynamically:
let dependency = fork.contract;
let value = fork.;
Use try_invoke when a failure is part of the test rather than a panic:
let result = fork.;
assert!;
Preview executes a mutating call in an isolated child and returns detached evidence without changing the scenario state:
use PreviewAuth;
let report = fork
.preview
.unwrap;
let shares = report..unwrap;
assert!;
PreviewAuth::Record exposes the requested authorization tree.
PreviewAuth::Exact(recorded.authorization().to_vec()) reruns the preview and
requires that exact tree. Exact validation is preview-only.
Typed clients, dynamic calls, local WASM, and captured contracts share the same mutable state and can be mixed freely.
Scenario API
| API | Meaning |
|---|---|
mainnet() |
Selects Stellar mainnet and derives a scenario cache path; it does not privilege one root contract. |
testnet() |
Selects Stellar public testnet with otherwise identical behavior. |
.rpc_url(url) |
Overrides the capture provider without changing network identity or automatic cache identity. |
.rpc_rate_limit(rps) |
Opts into per-capture read-RPC pacing; 0 keeps the default unlimited behavior. |
.cache(path) |
Overrides the automatically derived cache path. |
.offline() |
Replays the cached ledger as a pinned snapshot with zero RPC calls. |
.refresh() |
Discards cached key inventory and performs a cold coherent capture. |
.allow_newer_protocol() |
Accepts a network exactly one protocol ahead and executes it on the Host's own protocol; see above. |
fork.contract("C...") |
Parses a network contract address. |
fork.account("G...") |
Parses a network account; Host access discovers its real account and trustlines. |
fork.muxed_account("M...") |
Parses a muxed address; ledger state belongs to its underlying G-address. |
fork.deploy(wasm, args) |
Locally installs candidate WASM and runs its constructor, if defined. |
fork.replace_wasm(contract, wasm) |
Replaces an existing WASM executable while preserving its address, storage, and TTL. |
fork.invoke(contract, fn, args) |
Invokes any contract without generated bindings. |
fork.try_invoke(contract, fn, args) |
Applies one call and returns a small typed failure instead of unwinding. |
fork.preview(contract, fn, args, auth) |
Simulates one call in an isolated child and returns detached result/auth/events/diff/resources. |
fork.local_account("label") |
Creates a deterministic local G-address with no ledger entry or funds. |
fork.fund_local_account(account, stroops) |
Explicitly creates or funds that local account through ledger injection. |
fork.mock_all_auths() |
Explicitly enables SDK record-and-mock authorization. |
Addresses belong in the scenario rather than mainnet(...) or testnet(...).
Host execution discovers actual dependencies, including contracts reached only
through cross-contract calls.
On an exact online cache hit or offline pinned replay, the closure runs once. During a cold or inventory-seeded refresh it may run several times while Kanatoko discovers the dependency graph and verifies strict replay. Every pass starts from a fresh environment, so contract mutations do not accumulate between passes. Only effects outside the Soroban environment, such as random generation, file writes, HTTP requests, counters, or output, would be repeated.
Generate one-time inputs before .run(...) and capture ordinary Rust values in
the closure. Create environment-bound values, addresses, and generated clients
inside it:
let amount = generate_amount_once;
mainnet
.run
.unwrap;
A test may call .run(...) more than once. Each call creates an independent
fork, and ordinary Rust code between the calls runs once. Use a separate cache
path for a materially different scenario. If calls must observe each other's
contract mutations, keep them inside the same .run(...) closure.
Controlling time
A scenario can move ledger time with the SDK's own Ledger test utility.
Kanatoko re-exports soroban_sdk, so no separate dependency is needed:
use Ledger as _;
let now = fork.env.ledger.timestamp;
fork.env.ledger.set_timestamp;
Limits to keep in mind:
- Timestamp and sequence number are separate.
set_timestampdoes not move the sequence number;set_sequence_numberis the call for that. - Temporary entries can expire as the sequence number advances.
- Persistent entries past their TTL stay readable because state archival is not modeled, so a passing test does not prove behavior around state archival.
Roadmap
Kanatoko is moving toward being the easiest way to test your own Soroban contract on top of real deployed protocols, under conditions that are hard to reproduce on a live network.
Planned improvements, in priority order:
- Scenario controls: documented one-line control of time, balances, storage, and external inputs such as oracle prices.
- Clear failure explanations: which external call failed and why, with a readable cross-contract call tree.
- Network fidelity: capture network settings, apply invocation limits, and verify cost-model compatibility.
- Integrator onboarding: a project template and recipes for building on AMMs, lending pools, and oracles.
These are plans, not shipped features.
Evidence boundary
fork.deploy(...), local account funding, and mocked authorization are explicit
test mechanics. They prove contract behavior in the Soroban Host; they do not
emulate transaction envelopes, deployment authorization, signatures, fees,
Stellar Core consensus, or SDEX execution.
Preview resources are the raw local Host estimate, not fee parity. Kanatoko
keeps typed ScError and raw XDR evidence and does not derive stable behavior
by parsing diagnostic or panic text.
Each stable Kanatoko major selects the same major of the SDK, Host, and
ledger-snapshot crates. Stable lines use broad major ranges so Cargo can
resolve one compatible runtime with the rest of the test harness. Prerelease
lines use exact compatible pins. Use the re-exported
kanatoko::soroban_sdk, kanatoko::soroban_env_host, and
kanatoko::soroban_ledger_snapshot instead of declaring a second runtime
version when possible.
A Kanatoko line can capture and replay a live network only when its selected Host protocol matches the protocol reported by that network. For example, a protocol-27 network requires Kanatoko 27; no other major is a historical network-state fork of it. The only exception is the explicit newer-protocol opt-in, limited to one protocol ahead and executed on the older Host.
Your production contract does not need to upgrade with the harness. A contract
crate may remain on Soroban SDK 25 or 26, produce its normal network-valid
WASM, and let a Kanatoko 27 integration-test crate import that WASM when testing
against a protocol-27 network. The current Host executes the original older
WASM; its SDK generates only the test-side ABI client. Do not pass
environment-bound Env, Address, or Val values from the older contract SDK
into the harness.
Unsupported ledger-entry families and uncaptured keys fail closed.
See MISSION.md for the project principles.