# simulator-client
Rust client for the Termina simulator. A session replays a slot range of Solana mainnet on the
server: step it forward, read and change its state through the session's RPC endpoint, and
stream what it executes.
- Full guide and API reference: <https://docs.rs/simulator-client/latest/simulator_client/>
- Runnable programs: the [examples repository](https://github.com/nitro-svm/examples). Start with
[`hello_session`](https://github.com/nitro-svm/examples/tree/main/src/bin/hello_session).
- Concepts: the [Termina docs](https://docs.termina.technology/documentation)
## Install
```toml
[dependencies]
simulator-client = "0.30.0" # x-release-please-version
tokio = { version = "1", features = ["macros", "rt-multi-thread"] }
rustls = { version = "0.23", default-features = false, features = ["ring"] }
```
Needs Rust 1.97 or newer. Add Solana crates only at these versions:
| `solana-address` | 2.6 or newer, below 3 |
| `solana-pubkey` | 4.x |
| `solana-account`, `solana-client`, `solana-rpc-client`, `solana-rpc-client-api`, `solana-transaction`, `solana-transaction-status` | 4.3 or newer, below 5 |
| `solana-hash`, `solana-message` | 4.x |
| `solana-commitment-config`, `solana-system-interface` | 3.x |
| `solana-keypair`, `solana-signature` | 3.1 or newer, below 4 |
| `solana-loader-v3-interface` | 7.x |
| `solana-signer` | 3.0.1 or newer, below 4 |
Addresses are `simulator_client::Address`. A `Pubkey` from `solana-pubkey` 4 is the same type.
Convert a `Pubkey` from an older Solana crate with `Address::new_from_array(pubkey.to_bytes())`.
## TLS
Install a rustls crypto provider at the top of `main`, before you connect:
```rust
let _ = rustls::crypto::ring::default_provider().install_default();
```
Without it, the first connection panics whenever your program also enables rustls's `aws-lc-rs`
provider (rustls's default features, `reqwest` 0.13, the AWS SDK).
## Quickstart
Set `SIMULATOR_API_KEY`, then:
```rust
use simulator_client::{
Address, BacktestClient, Continue, CreateSession, ManagedBacktestSession, ManagedEvent,
};
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let _ = rustls::crypto::ring::default_provider().install_default();
let host = "simulator.termina.technology";
let api_key = std::env::var("SIMULATOR_API_KEY")?;
// 1. Pick the newest slot range the server can replay.
let client = BacktestClient::builder().url(host).api_key(&api_key).build();
let ranges = client.available_ranges().await?;
let range = ranges
.iter()
.max_by_key(|range| range.bundle_start_slot)
.ok_or("the server lists no slot ranges")?;
// 2. Start a session at the range's first slot. `slot_count` counts the slots after it.
let create = CreateSession::builder()
.start_slot(range.bundle_start_slot)
.slot_count(10)
.capacity_wait_timeout_secs(300)
.build()
.into_request()?;
let mut session = ManagedBacktestSession::start(host.to_string(), api_key, create).await?;
// 3. Read state just before the start slot executes (the end of the slot before it)
// through the session's RPC endpoint.
session.wait_until_ready().await?;
let usdc: Address = "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v".parse()?;
let mint = session.rpc().get_account(&usdc).await?;
println!("USDC mint: {} bytes, owned by {}", mint.data.len(), mint.owner);
// 4. Step one block at a time until the session completes, then close it.
let step = Continue::builder().advance_count(1).build().into_params();
session.send_continue(step.clone()).await?;
let summary = session
.run_to_completion(step, |event| {
if let ManagedEvent::Slot(slot) = event {
println!("executed slot {slot}");
}
})
.await?;
println!("{summary:?}");
Ok(())
}
```
`ManagedBacktestSession`, or `managed::ManagedParallelSession` for a parallel run, reconnects on
its own, so a dropped connection does not end your session. `BacktestClient` calls
the server's HTTP endpoints: ranges, usage, bundles, depth and dataset credentials.
## Logging
The client logs through `tracing`. Install a subscriber (`tracing-subscriber` with its
`env-filter` feature) and set `RUST_LOG=simulator_client=info`:
```rust
tracing_subscriber::fmt()
.with_env_filter(tracing_subscriber::EnvFilter::from_default_env())
.init();
```
## Troubleshooting
| `API key rejected: HTTP 401` (or 403), or `401 Unauthorized` from `available_ranges` | Check `SIMULATOR_API_KEY`; `sim usage` confirms a key works |
| `session create failed: ... block bundle not found`, `invalid request` or `no produced blocks in requested range` | Pick a range from `available_ranges`; start at its `bundle_start_slot` |
| `session create failed: ... insufficient capacity` | Set `capacity_wait_timeout_secs`, or retry later |
| `session not found` after a reconnect | The session ended. Start a new one; raise `disconnect_timeout_secs` |
| Panic: `Could not automatically determine the process-level CryptoProvider` | Install a provider: see [TLS](#tls) |
| Expected `Address`, found `Pubkey`, or two versions of `solana_address` | Use the versions in [Install](#install); `cargo tree -i solana-address@2 -e normal` shows which crates use the 2.x copy. Other major versions, pulled in by `spl-*` crates, are harmless |
## Datasets
`BacktestClient` also calls the dataset endpoints:
- `dataset_credentials`: temporary, read-only S3 credentials for the prebuilt datasets and your
custom ones.
- `create_dataset_job`, `get_dataset_job`, `list_dataset_jobs`, `cancel_dataset_job`: dataset
jobs, including depth datasets.
- `depth_universe`: the markets, venues and size rungs a depth job samples. From onchain
revision 5 rung `n` spends `$1 * 2^n` of the input token at the range's price, so rung 0 is a
dollar in both directions of a market. The three rungs after rung 17 ($131,072) are $500,000,
$1,000,000 and $10,000,000. A pool's ladder ends at its liquidity limit: the first rung that the
pool refuses above its last priced rung. That rung is kept as declined and the rungs above it are
dropped, so a pool can have fewer than 21 rungs. A refused rung with a priced rung above it (a
venue quoting from a stamp refuses sizes at random) is kept as declined and does not end the
ladder, and neither does a pool refused at every rung.
- `build_bundle`, `get_bundle_status`, `list_bundle_builds`, `delete_bundle`: custom bundles.
The [crate docs](https://docs.rs/simulator-client/latest/simulator_client/) cover session
lifecycle, subscriptions, errors and timeouts.