1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
//! Rust client for the Termina simulator.
//!
//! A session replays a slot range of Solana mainnet on the server. You step it forward slot by
//! slot, read and change its state through the session's RPC endpoint, and stream what it
//! executes. This crate drives sessions over the session control channel and calls the server's
//! HTTP endpoints. It re-exports the wire types as [`simulator_api`], so you never add that crate
//! yourself.
//!
//! Use [`ManagedBacktestSession`], or [`managed::ManagedParallelSession`] for a parallel run.
//! Both reconnect on their own, so a dropped connection does not end your session.
//! [`BacktestClient`] calls the server's HTTP endpoints: ranges, usage, bundles, depth and
//! dataset credentials.
//!
//! Runnable programs live in 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).
//!
//! # Install
//!
//! ```toml
//! [dependencies]
//! simulator-client = "0.31.0" # x-release-please-version
//! tokio = { version = "1", features = ["macros", "rt-multi-thread"] }
//! rustls = { version = "0.23", default-features = false, features = ["ring"] }
//! tracing-subscriber = { version = "0.3", features = ["env-filter"] }
//! ```
//!
//! Needs Rust 1.97 or newer. Add Solana crates only at these versions, so that their types are
//! the ones this crate uses:
//!
//! | Crate | Version |
//! |---|---|
//! | `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 |
//!
//! Every account address is an [`Address`] (re-exported from `solana-address`). A `Pubkey` from
//! `solana-pubkey` 4 is the same type, so pass it as is. A `Pubkey` from an older Solana crate
//! is a different type; convert it with `Address::new_from_array(pubkey.to_bytes())`.
//!
//! # TLS
//!
//! Install a rustls crypto provider at the top of `main`, before you connect:
//!
//! ```no_run
//! let _ = rustls::crypto::ring::default_provider().install_default();
//! ```
//!
//! This crate builds rustls with the `ring` provider. If anything else in your program enables
//! rustls's `aws-lc-rs` provider (rustls's default features, `reqwest` 0.13, the AWS SDK), rustls
//! cannot pick one and the first connection panics. Installing one up front always works. The
//! call fails only when a provider is already installed, so ignoring its result is safe.
//!
//! # Connecting
//!
//! - **URL.** Pass the server's host, such as `simulator.termina.technology`; it becomes
//! `wss://simulator.termina.technology/backtest`. A full `ws://` or `wss://` URL is kept, and
//! gains `/backtest` if it lacks it.
//! - **API key.** Every request sends it as the `X-API-Key` header. Read it from the
//! `SIMULATOR_API_KEY` environment variable, as `sim` does.
//! - **Slot ranges.** [`BacktestClient::available_ranges`] lists the ranges the server can
//! replay, oldest first. Start a session at a range's `bundle_start_slot` and end it at or
//! before its `max_bundle_end_slot`. [`filter_ranges`] narrows the list by slot or date.
//!
//! # Quickstart
//!
//! Start a session, read an account just before the start slot executes, then run it to the end:
//!
//! ```no_run
//! 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();
//! tracing_subscriber::fmt()
//! .with_env_filter(tracing_subscriber::EnvFilter::from_default_env())
//! .init();
//!
//! 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(())
//! }
//! ```
//!
//! # Session lifecycle
//!
//! 1. [`ManagedBacktestSession::start`] returns once the session is created and ready. Its
//! [`session_info`](ManagedBacktestSession::session_info) holds the session ID and the
//! session's RPC endpoint.
//! 2. Call the `subscribe_*` methods you need, before the first continue.
//! 3. Read events with [`next_event`](ManagedBacktestSession::next_event). `Status` updates come
//! first while the session starts.
//! 4. On [`ManagedEvent::ReadyForContinue`] the session is paused. Read or change state through
//! [`rpc`](ManagedBacktestSession::rpc), then call
//! [`send_continue`](ManagedBacktestSession::send_continue) with a [`Continue`]: how many
//! blocks to execute (skipped slots are not counted), user transactions to run first, account
//! overrides to write. Or call
//! [`send_continue_to`](ManagedBacktestSession::send_continue_to) to stop at a slot: the
//! session sends [`ManagedEvent::Paused`] there, then `ReadyForContinue`. Answer only the
//! `ReadyForContinue`.
//! 5. [`ManagedEvent::Completed`] comes after the last slot and after every subscription's last
//! notification. The session's RPC endpoint stops serving (HTTP 502).
//! 6. [`shutdown`](ManagedBacktestSession::shutdown) closes the session on the server. Dropping
//! the session cancels it without waiting.
//!
//! [`wait_until_ready`](ManagedBacktestSession::wait_until_ready) and
//! [`run_to_completion`](ManagedBacktestSession::run_to_completion) wrap steps 3 to 6. For a run
//! split across concurrent sessions, use [`managed::ManagedParallelSession`].
//!
//! # Subscriptions
//!
//! | | Managed `subscribe_*` methods | Functions in [`subscriptions`] | Your own WebSocket |
//! |---|---|---|---|
//! | Delivery | [`ManagedEvent`]s from `next_event` | Your callback, on a background task | Yours |
//! | Reconnect | Yes. See [Connection drops](managed#connection-drops) for the duplicates | No. The stream ends with [`SubscriptionRuntimeError::Closed`] | Yours |
//! | End of run | Every notification arrives before `Completed` | Call [`SubscriptionHandle::shutdown`] before you close the session | Yours |
//! | Stop | `shutdown` on the session | `handle.shutdown().await?`; dropping the handle does not stop it | Yours |
//! | Covers | Transactions (with program logs) and account changes by program; pre-scheduled action results; reroutes; diagnostics | Also single accounts ([`subscribe_account_diffs`]) and program logs alone ([`subscribe_program_logs`]) | Any subscribe method |
//!
//! Subscribe before the continue you want notifications for. Connect your own WebSocket to the
//! session's RPC endpoint (convert it with [`http_to_ws_url`]) and merge [`SubscribeConfig`]
//! into a subscribe's params with [`SubscribeConfig::apply_to`].
//! [`balances::balance_changes`] reads the SOL and token balance changes from a transaction
//! notification; [`decode_transaction`] decodes the binary transactions in discovery, action and
//! reroute notifications.
//!
//! # Errors and recovery
//!
//! The managed session has already retried what it could. Each [`ManagedSessionError`] says what
//! to do. [`ManagedSessionError::is_retryable`] answers the last column in code:
//!
//! | Error | Cause | What to do | Retry with a new session? |
//! |---|---|---|---|
//! | `ApiKeyRejected` | The server refused the API key (HTTP 401 or 403) | Fix the key | No |
//! | `Create` | The create failed. See [`CreateError`] | Retry later, fix the request, or upgrade this crate | When [`CreateError::is_retryable`] |
//! | `SessionTokenRejected` | The session's endpoint refused the token, at the first attach or later | Start a new session | Yes |
//! | `Remote` | The server reported an error, terminal or not, during `wait_until_ready` or `run_to_completion` | Fix what it names | When [`BacktestError::is_retryable`](simulator_api::BacktestError::is_retryable) |
//! | `ControlFailed` | The control channel used up its reconnect budget, or the session ended | Start a new session | Yes |
//! | `SubscriptionFailed` | A subscription ran out of retries | Start a new session | Yes |
//! | `ControlClosed`, `ContinueSend` | The session is over: it completed, or the server sent a terminal error (that error comes first from `next_event`) | Stop | No |
//! | `Cancelled` | Your cancellation token fired, or the parallel run was shut down | Stop | No |
//! | `CompletedBeforeReady` | The session finished before its first pause | Check the range and the create request | No |
//!
//! [`ManagedEvent::Error`] from `next_event` is terminal when
//! [`BacktestError::is_terminal`](simulator_api::BacktestError::is_terminal) is true: stop. Any
//! other error leaves the session running. A [`BacktestClient`] call fails with a
//! [`BacktestClientError`]; [`BacktestClientError::is_retryable`] says whether to retry it.
//!
//! # Timeouts
//!
//! | What | Default | Change it with |
//! |---|---|---|
//! | Waiting for server capacity at create | None: fails at once when the server is busy | [`CreateSession::capacity_wait_timeout_secs`] |
//! | Server keeps an unattached session | 360 s managed single session ([`managed::DEFAULT_DISCONNECT_TIMEOUT_SECS`]); 900 s for a parallel run. At most 900 s | [`CreateSession::disconnect_timeout_secs`] |
//! | Wait for notifications after `Completed` | 60 s without one | [`ManagedBacktestSession::set_completion_drain_timeout`] |
//!
//! # Logging
//!
//! The crate logs through [`tracing`](https://docs.rs/tracing). Install a subscriber, as in the
//! quickstart (`tracing-subscriber` with its `env-filter` feature), and set `RUST_LOG`:
//!
//! - `RUST_LOG=simulator_client=info` shows session creation, reconnects and retries.
//! - `RUST_LOG=simulator_client=debug` adds each reconnect attempt.
//!
//! # Troubleshooting
//!
//! | Symptom | Cause | Fix |
//! |---|---|---|
//! | `API key rejected: HTTP 401` (or 403); `401 Unauthorized` from a [`BacktestClient`] call | Missing, mistyped or expired key | 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` | The range is not available | Pick a range from `available_ranges`; start at its `bundle_start_slot` |
//! | `session create failed: ... insufficient capacity` | The server is busy | Set `capacity_wait_timeout_secs` (`sim run` uses 900), or retry later |
//! | `clerk error` when creating a session | The server could not load the range's historical data | Retry later |
//! | `ControlFailed` from a managed session | The session ended, or its `disconnect_timeout_secs` passed | Start a new session; raise `disconnect_timeout_secs` |
//! | Panic: `Could not automatically determine the process-level CryptoProvider` | Two rustls providers are linked | Install one: see [TLS](#tls) |
//! | Compile error: expected `Address`, found `Pubkey`, or two versions of `solana_address` | A Solana crate from another major version | 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 |
pub use ;
pub use BacktestClient;
pub use ;
pub use SessionGeyserChannel;
pub use ;
pub use ;
pub use ;
pub use ;
pub use ;
pub use ;
pub use ;
pub use ;
pub use ;