Rust SDK and cheatcodes
The Rust SDK lets integration tests run a local, Solana-compatible Surfnet inside the test process. It gives the test a normal RPC client for transactions and reads, plus cheatcodes that can set accounts, tokens, time, streamed state, and deployed programs without using normal transaction flow. It can also preload exported account snapshots and lock state-changing RPC methods before handing the network to other code. For the wider integration map, see Developer integrations; the Node SDK and MCP server expose related ways to work with Surfpool.
System purpose
Surfnet is a short-lived local network for tests. The SDK starts it without an external process, waits until its RPC service and startup funding are visible, and returns a handle that owns the test network. This keeps test setup close to the test while preserving the normal Solana RPC boundary for application code. References: crates/…/lib.rs• L1-31, crates/…/surfnet.rs• L140-241
Surfnet lifecycle
Startup configuration
Surfnet::start() creates a network with fast transaction-based block production, offline account lookup, a fresh payer, and 10 SOL for that payer. Surfnet::builder() changes the parts that matter to a test, such as a remote RPC fallback, block timing, extra funded addresses, blockhash checks, the payer keypair, and SVM feature gates.
The builder can also preload accounts from an exported snapshot or a JSON snapshot file. Later snapshot sources override earlier values for the same account. A restored account takes precedence over its startup airdrop, which lets a test restore an exact balance instead of the default payer funding. The builder can enable instruction profiling and can lock selected cheatcodes before the first client request. A remote RPC URL turns off offline mode so Surfnet can use that source for account data. References: crates/…/surfnet.rs• L87-231, crates/…/snapshot.rs• L22-81, crates/…/cheatcode_lock.rs• L35-93
The builder selects free local ports for HTTP RPC and WebSocket RPC. The returned Surfnet exposes both URLs, but most Rust tests can use rpc_client() and let the standard Solana client API handle reads and transactions. References: crates/…/surfnet.rs• L27-140, crates/…/surfnet.rs• L244-297
Runtime readiness
Startup is complete only after the embedded runtime reports that its core has started and the configured startup balances can be read through RPC. Restored balances are excluded from that airdrop check because the snapshot is the desired source of truth. A startup abort, an unexpected event-channel close, an unreadable snapshot, or balances that do not appear within the startup window returns an error instead of an apparently usable client.
The lifecycle and request path are:
flowchart LR
A[Test calls Surfnet::start] --> B[Builder creates local runtime]
B --> C[Runtime opens HTTP and WebSocket RPC]
C --> D[Startup event reports core ready]
D --> E[RPC confirms payer funding]
E --> F[Surfnet handle]
F --> G[Normal Solana RPC client]
F --> H[Cheatcode RPC helpers]
References: crates/…/surfnet.rs• L199-241 crates/…/surfnet.rs• L335-353 crates/…/surfnet.rs• L535-606
Runtime shutdown
Dropping a Surfnet sends a terminate command as a best-effort cleanup. Tests that need to know that both RPC servers have stopped should call stop() and handle its result. stop() waits for two shutdown events, marks the handle stopped on success, and does nothing on later calls.
Shutdown drains the same event channel used by events(). Code must not read that channel at the same time as stop(), or it can consume a shutdown event and make confirmed shutdown fail. During shutdown, the WebSocket service sends a normal close frame and then gives an unanswered client a short grace period before it releases the connection. References: crates/…/surfnet.rs• L425-494, crates/…/ws_shutdown.rs• L37-83
Client API
Solana RPC access
rpc_client() returns a standard RpcClient connected to the local HTTP endpoint. Use it for the application path under test: submit transactions, read balances and accounts, inspect epoch state, and verify the result of a cheatcode. payer() supplies the funded signing keypair that the default setup gives to the test.
The SDK also exposes the WebSocket URL for clients that need subscriptions. events() provides runtime events, send_command() accepts simnet control commands, and instance_id() identifies the running Surfnet handle. These access points are useful when a test observes network state in addition to account state. References: crates/…/lib.rs• L20-31, crates/…/surfnet.rs• L387-439
Cheatcode access
cheatcodes() creates helpers tied to the same HTTP endpoint. A cheatcode is a test-only RPC action that changes local state directly. It is separate from the transaction path, so a test can create the state needed for a case and then exercise the real application transaction against that state.
The direct helpers cover the common setup path:
| Need | Rust API | Result |
|---|---|---|
| Give a wallet SOL | fund_sol and fund_sol_many | Set one or more lamport balances |
| Set full or partial account state | set_account or SetAccount | Change lamports, owner, raw data, rent epoch, or executable state |
| Give a wallet tokens | fund_token, set_token_balance, and fund_token_many | Create the associated token account when needed and set its amount |
| Find an associated token account | get_ata | Derive the address for a wallet and mint |
| Move test time forward | time_travel_to_slot, time_travel_to_epoch, time_travel_to_timestamp, or time_travel_to_slot_at | Return updated epoch information |
| Load a program | deploy or deploy_program | Write program code and optionally register its IDL |
References: crates/…/mod.rs• L18-58 crates/…/mod.rs• L65-328 crates/…/mod.rs• L330-419
Cheatcode locking
Cheatcode locking turns a configured Surfnet into a safer RPC boundary after test setup. SurfnetBuilder::lock_cheatcodes() applies the lock before startup, while Cheatcodes::lock() applies it after setup. A full filter blocks all Surfnet methods, airdrops, and administrative methods such as stopping the network or loading plugins; a list filter blocks only named methods.
The lock is one-way. Code that receives the RPC endpoint cannot re-enable a locked method, but normal validator RPC methods remain available when only a list is locked. Startup airdrops and Surfnet::stop() still work because they do not use the locked RPC path. References: crates/…/surfnet.rs• L176-205, crates/…/mod.rs• L459-496, crates/…/cheatcode_lock.rs• L35-225
State setup and mutation
Snapshot state
Snapshots preload account state before the local network becomes ready. A snapshot can come from an in-memory account map or from the JSON value exported by surfnet_exportSnapshot, so an offline test can start from state captured in another Surfnet run.
Multiple sources merge in builder order, and the last value for an account wins. Snapshot data restores accounts but does not restore the clock; use the clock cheatcode when a program depends on the slot and Unix time from the source network. References: crates/…/surfnet.rs• L208-231, crates/…/surfnet.rs• L254-269, crates/…/surfnet.rs• L497-521, crates/…/snapshot.rs• L22-117, crates/…/clock.rs• L1-3
Account state
Account cheatcodes support both a simple balance change and a typed account update. The simple form sets SOL in lamports. The typed form can set only the fields a test needs; omitted fields remain unchanged when an account already exists. A complete account description can replace the account state, while a missing account starts from default account values before a partial update is applied.
This distinction lets a test choose between a focused mutation and a complete fixture. Account data is supplied as bytes by the Rust builder and becomes the encoded data expected by the RPC contract. References: crates/…/mod.rs• L65-118, crates/…/set_account.rs• L30-108, crates/…/surfnet_cheatcodes.rs• L40-97, crates/…/surfnet_cheatcodes.rs• L139-186
Token account state
Token setup is expressed by wallet owner and mint rather than by an account address. The helper finds or creates the associated token account and sets its amount. The classic SPL Token program is the default; pass a program ID when the test uses Token-2022. The typed builder also supports token account state, delegate, delegated amount, and close authority so tests can model permission and lifecycle cases.
Use the optional program ID consistently when deriving the associated token address and when changing the token account. Otherwise the default program can point the test at a different account than the application uses. References: crates/…/mod.rs• L120-250, crates/…/set_token_account.rs• L25-145, crates/…/surfnet_cheatcodes.rs• L274-369
Clock state
Time travel moves the local clock forward to an absolute slot, epoch, or Unix timestamp in milliseconds. The RPC returns EpochInfo, which lets the test assert the new position. A target in the past is rejected; use this API for expiry, epoch boundary, and other time-sensitive behavior rather than waiting for wall-clock time.
time_travel_to_slot_at() sets a slot and the Unix timestamp associated with that slot. Use it after restoring a snapshot when program logic compares both values, such as oracle freshness or time-based funding. The clock sysvar then exposes the restored slot and time to programs. References: crates/…/mod.rs• L252-328, crates/…/clock.rs• L8-39
The Rust SDK exposes forward jumps. The underlying Surfnet RPC also has pause and resume controls for tests that need to stop automatic clock progress while they inspect or prepare state. References: crates/…/mod.rs• L252-328, crates/…/surfnet_cheatcodes.rs• L738-852
Program deployment
Program deployment is a compound setup action. The SDK writes program bytes to the local program account and then registers an optional Anchor IDL for later use. DeployProgram accepts either inline bytes or a .so path, and it can take an IDL path. deploy_program(name) is the workspace shortcut: it looks for the program binary and keypair under target/deploy and uses target/idl when an IDL exists.
This path is for making a program available before the application transaction runs. It does not replace the normal transaction and instruction checks performed by that transaction. References: crates/…/mod.rs• L330-401, crates/…/deploy_program.rs• L10-120, crates/…/surfnet_cheatcodes.rs• L1216-1265
Remote account streaming
Streaming cheatcodes control which accounts Surfnet should fetch from its account source and cache locally. A test can register one account or a group of accounts and can include accounts owned by each registered account. This is useful when a scenario depends on data that is not part of the initial local state.
The Rust builder covers one account. The underlying RPC also supports batch registration and a query for the current streamed set. References: crates/…/stream_account.rs• L5-59, crates/…/surfnet_cheatcodes.rs• L1033-1161
Account reset
Reset removes a local account so a test can return to a clean state or test account creation again. The optional include_owned_accounts setting extends the reset to accounts owned by the target. This is a state reset, not a ledger rollback, so use it as an explicit fixture action between test phases.
References: crates/…/reset_account.rs• L5-59 crates/…/surfnet_cheatcodes.rs• L854-893
Cheatcode builders
Builder contract
Typed builders give each cheatcode a Rust-facing input model. A builder starts with required values, adds optional values through fluent setters, and turns into one method name plus a JSON-RPC parameter array when passed to Cheatcodes::execute. This keeps the wire format in one place while allowing a test to express only the state it wants to change.
The public builders are SetAccount, SetTokenAccount, ResetAccount, StreamAccount, and DeployProgram. The first four map to one RPC action. Deployment is different because it can write code and then register an IDL. References: crates/…/mod.rs• L1-45, crates/…/mod.rs• L403-419, crates/…/deploy_program.rs• L10-13
Builder choices
| Builder | Required setup | Main mutation |
|---|---|---|
SetAccount | Account public key | Account balance, owner, data, rent epoch, or executable flag |
SetTokenAccount | Wallet owner and mint | Token amount and token-account authorities or state |
ResetAccount | Account public key | Remove the account, with optional owned-account cascade |
StreamAccount | Account public key | Register account data for remote streaming, with optional owned accounts |
DeployProgram | Program public key or keypair path | Load program bytes and optionally register an IDL |
Use the convenience methods for common SOL, token, clock, and workspace-deploy cases. Use a builder when the test needs optional fields or a clear typed description of a fixture. References: crates/…/set_account.rs• L39-83, crates/…/set_token_account.rs• L36-100, crates/…/reset_account.rs• L29-43, crates/…/stream_account.rs• L29-43, crates/…/deploy_program.rs• L40-85
Error model
The SDK returns SurfnetResult<T>, which is Result<T, SurfnetError>. Startup, runtime control, and cheatcode calls therefore use one error type. The error category tells the caller which boundary failed, while the message preserves the lower-level reason. Snapshot read or parse failures and invalid startup cheatcode locks are reported as startup errors because the network must not be exposed in a partial state.
| Error | Meaning | Typical response |
|---|---|---|
PortAllocation | The SDK could not reserve a local RPC port | Treat startup as unavailable and retry or report the host problem |
Startup | The runtime started but did not become usable or funded in time | Inspect startup conditions and the returned message |
Runtime | A command or shutdown operation failed, or the runtime ended unexpectedly | Stop using the handle and treat the network as unhealthy |
Cheatcode | A custom RPC call or local artifact operation failed | Check the target account, RPC state, program bytes, or IDL |
Aborted | The network stopped or aborted while starting | Treat the Surfnet instance as unusable |
Cheatcode errors include the RPC method name, which helps separate an account or token problem from a general RPC problem. A successful helper call means the RPC accepted the state change; tests should still read the affected state through rpc_client() when the state itself is part of the assertion. References: crates/…/error.rs• L1-31, crates/…/mod.rs• L421-495, crates/…/surfnet.rs• L250-253, crates/…/surfnet.rs• L497-516
Change checklist
When these files or sections are changed, remember to consider these:
- Keep each typed builder's
METHODand JSON parameter shape aligned with the matchingsurfnet_*RPC contract. - When account update fields change, preserve the distinction between a complete account replacement and a partial update.
- When token-account behavior changes, update the default-program and Token-2022 paths together with associated-token derivation.
- When startup readiness or event handling changes, check both the SDK's readiness wait and callers that use
events()orstop(). - When WebSocket shutdown behavior changes, preserve the normal close handshake and the bounded wait for clients that do not reply.
- When deployment artifact names or IDL rules change, update both
deploy_programdiscovery andDeployProgram's explicit-input path. - When snapshot loading changes, check merge order, exported snapshot shape, restored balances, and the rule that snapshots do not restore clock state.
- When cheatcode locking changes, check both startup locks and post-setup locks, including the one-way behavior and the distinction between full and list filters.
- When a cheatcode response shape changes, check the Rust RPC client expectations and the related Node and MCP integrations.
Important failure modes
| Trigger | Consequence | Guard |
|---|---|---|
| A startup balance is not visible through RPC before the startup deadline | Surfnet::start() returns Startup and no usable handle is returned | Keep startup funding and readiness checks on the same endpoint |
stop() and events() read the event channel at the same time | A shutdown acknowledgement can be consumed by the wrong reader and stop() can time out | Let one owner drain the channel during shutdown |
| A WebSocket client does not answer the server close frame | Shutdown waits only for the grace period and then drops the socket | Treat the bounded close wait as expected and do not require a client reply |
| A time-travel target is earlier than the current clock | The cheatcode call is rejected | Compute the target from current epoch or slot information |
| A snapshot file is missing or invalid | Startup returns Startup instead of a partially restored Surfnet | Validate the file before relying on restored accounts |
| A snapshot restores an account that startup also funds | The restored balance wins and the startup wait does not expect the airdrop amount | Treat snapshot state as authoritative for restored addresses |
| A full or list cheatcode lock includes an unknown method | Startup returns Startup and no network handle is returned | Use method names accepted by the cheatcode filter |
| Code receives an RPC endpoint after cheatcodes are locked | Locked methods and, for a full lock, airdrops and admin calls stay unavailable | Perform all setup before the lock and expose only the normal RPC path |
| A Token-2022 account uses the default classic token program | The derived or updated account can be the wrong account | Pass the Token-2022 program ID to both token operations |
DeployProgram has neither program bytes nor a .so path | Deployment returns a Cheatcode error before writing program state | Supply one byte source and verify the optional IDL path |
| A required workspace binary or keypair is absent | deploy_program cannot locate the program artifacts | Build the program into the expected target/deploy location or use explicit builder inputs |
Key files
| File | Why to read it |
|---|---|
| crates/…/lib.rs | Public Rust SDK surface and the basic embedded-test model |
| crates/…/surfnet.rs | Surfnet configuration, snapshot preload, cheatcode locking, readiness, client access, events, commands, and shutdown |
| crates/…/snapshot.rs | Snapshot preload, merge order, exported-state restore, and startup precedence |
| crates/…/clock.rs | Restoring a slot and Unix time together after account snapshot setup |
| crates/…/cheatcode_lock.rs | One-way startup and post-setup cheatcode locks and their RPC boundary |
| crates/…/mod.rs | High-level state setup helpers, time control, deployment, locking, and custom RPC calls |
| crates/…/mod.rs | Builder contract and the public builder set |
| crates/…/set_account.rs | Typed account state updates |
| crates/…/set_token_account.rs | Typed token account updates and token-program selection |
| crates/…/deploy_program.rs | Program byte and IDL deployment inputs |
| crates/…/surfnet_cheatcodes.rs | RPC contracts and the server-side meaning of account, token, clock, reset, stream, and deployment actions |
| crates/…/error.rs | SDK error categories and result type |