simulator-client 0.29.0

Async WebSocket client for the Solana simulator backtest API
Documentation
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
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
//! Lamport and token balance changes read from an encoded transaction's metadata.

use std::{
    collections::{BTreeMap, BTreeSet},
    num::ParseIntError,
};

use solana_address::{Address, error::ParseAddressError};
use solana_transaction_status::{
    EncodedTransaction, EncodedTransactionWithStatusMeta, UiMessage, UiTransactionTokenBalance,
    option_serializer::OptionSerializer,
};
use thiserror::Error;

/// Accounts whose balance moved in one transaction; unchanged accounts are omitted.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct BalanceChanges {
    /// Lamport changes, in account-key order.
    pub sol: Vec<SolChange>,
    /// Token changes, ordered by account index then mint.
    pub token: Vec<TokenChange>,
}

/// One account's lamport balance before and after the transaction.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SolChange {
    /// The account.
    pub pubkey: Address,
    /// Lamports before execution.
    pub pre_lamports: u64,
    /// Lamports after execution.
    pub post_lamports: u64,
}

impl SolChange {
    /// Signed lamport change, `post - pre`.
    pub fn delta(&self) -> i128 {
        i128::from(self.post_lamports) - i128::from(self.pre_lamports)
    }
}

/// One token account's balance of one mint before and after the transaction.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TokenChange {
    /// The token account.
    pub pubkey: Address,
    /// The token's mint.
    pub mint: Address,
    /// The token account's owner. Absent when the meta omits it.
    pub owner: Option<Address>,
    /// Base units before execution; 0 when the account held none of `mint`.
    pub pre_amount: u64,
    /// Base units after execution; 0 when the account holds none of `mint`.
    pub post_amount: u64,
    /// The mint's decimal places.
    pub decimals: u8,
}

impl TokenChange {
    /// Signed change in base units, `post - pre`.
    pub fn delta(&self) -> i128 {
        i128::from(self.post_amount) - i128::from(self.pre_amount)
    }
}

/// Why [`balance_changes`] could not read a transaction.
#[derive(Debug, Error)]
pub enum BalanceChangesError {
    /// The transaction carries no status meta.
    #[error("transaction has no status meta")]
    MissingMeta,
    /// Only JSON and jsonParsed encodings carry the account keys.
    #[error("transaction encoding carries no account keys; request json or jsonParsed")]
    UnsupportedEncoding,
    /// An account key, mint or owner is not a valid address.
    #[error("invalid address: {0}")]
    Address(#[from] ParseAddressError),
    /// A token balance's raw amount is not a `u64`.
    #[error("invalid token amount: {0}")]
    TokenAmount(#[from] ParseIntError),
    /// The lamport balance lists do not match the account keys one to one.
    #[error("{keys} account keys but {pre} pre and {post} post balances")]
    BalanceCount {
        /// Account keys, including lookup-table loads.
        keys: usize,
        /// Entries in `pre_balances`.
        pre: usize,
        /// Entries in `post_balances`.
        post: usize,
    },
    /// A token balance points past the account keys.
    #[error("token balance account index {index} is out of range for {keys} account keys")]
    TokenIndex {
        /// The token balance's `account_index`.
        index: u8,
        /// Account keys, including lookup-table loads.
        keys: usize,
    },
}

/// One token balance's fields other than its `(account_index, mint)` key.
struct TokenBalance {
    amount: u64,
    owner: Option<Address>,
    decimals: u8,
}

/// Full key list (static + lookup-loaded) joined with the meta's balances.
///
/// # Errors
/// See [`BalanceChangesError`]; a malformed payload fails rather than yielding partial changes.
pub fn balance_changes(
    tx: &EncodedTransactionWithStatusMeta,
) -> Result<BalanceChanges, BalanceChangesError> {
    let meta = tx.meta.as_ref().ok_or(BalanceChangesError::MissingMeta)?;
    let EncodedTransaction::Json(ui_tx) = &tx.transaction else {
        return Err(BalanceChangesError::UnsupportedEncoding);
    };
    let keys = match &ui_tx.message {
        // A raw v0 message lists only its static keys; the meta carries the lookup-loaded ones.
        UiMessage::Raw(raw) => {
            let loaded = match &meta.loaded_addresses {
                OptionSerializer::Some(loaded) => Some(loaded),
                _ => None,
            };
            raw.account_keys
                .iter()
                .chain(
                    loaded
                        .into_iter()
                        .flat_map(|l| l.writable.iter().chain(&l.readonly)),
                )
                .map(|key| key.parse())
                .collect::<Result<Vec<Address>, _>>()?
        }
        // jsonParsed already includes the lookup-loaded keys.
        UiMessage::Parsed(parsed) => parsed
            .account_keys
            .iter()
            .map(|key| key.pubkey.parse())
            .collect::<Result<Vec<Address>, _>>()?,
    };

    if meta.pre_balances.len() != keys.len() || meta.post_balances.len() != keys.len() {
        return Err(BalanceChangesError::BalanceCount {
            keys: keys.len(),
            pre: meta.pre_balances.len(),
            post: meta.post_balances.len(),
        });
    }
    let sol = keys
        .iter()
        .zip(meta.pre_balances.iter().zip(&meta.post_balances))
        .filter(|(_, (pre, post))| pre != post)
        .map(|(pubkey, (&pre_lamports, &post_lamports))| SolChange {
            pubkey: *pubkey,
            pre_lamports,
            post_lamports,
        })
        .collect();

    let pre = token_balances(&meta.pre_token_balances, keys.len())?;
    let post = token_balances(&meta.post_token_balances, keys.len())?;
    let token = pre
        .keys()
        .chain(post.keys())
        .copied()
        .collect::<BTreeSet<_>>()
        .into_iter()
        .filter_map(|key @ (index, mint)| {
            let (pre, post) = (pre.get(&key), post.get(&key));
            let pre_amount = pre.map_or(0, |b| b.amount);
            let post_amount = post.map_or(0, |b| b.amount);
            if pre_amount == post_amount {
                return None;
            }
            let balance = pre.or(post)?;
            Some(TokenChange {
                pubkey: *keys.get(usize::from(index))?,
                mint,
                owner: balance.owner,
                pre_amount,
                post_amount,
                decimals: balance.decimals,
            })
        })
        .collect();

    Ok(BalanceChanges { sol, token })
}

/// Index token balances by `(account_index, mint)`, checking each index against `keys`.
fn token_balances(
    balances: &OptionSerializer<Vec<UiTransactionTokenBalance>>,
    keys: usize,
) -> Result<BTreeMap<(u8, Address), TokenBalance>, BalanceChangesError> {
    let OptionSerializer::Some(balances) = balances else {
        return Ok(BTreeMap::new());
    };
    balances
        .iter()
        .map(|balance| {
            let index = balance.account_index;
            if usize::from(index) >= keys {
                return Err(BalanceChangesError::TokenIndex { index, keys });
            }
            let owner = match &balance.owner {
                OptionSerializer::Some(owner) => Some(owner.parse()?),
                _ => None,
            };
            Ok((
                (index, balance.mint.parse()?),
                TokenBalance {
                    amount: balance.ui_token_amount.amount.parse()?,
                    owner,
                    decimals: balance.ui_token_amount.decimals,
                },
            ))
        })
        .collect()
}

#[cfg(test)]
mod tests {
    use rstest::rstest;
    use serde_json::{Value, json};

    use super::*;

    const PAYER: &str = "11111111111111111111111111111112";
    const STATIC_1: &str = "11111111111111111111111111111113";
    const LOADED_W: &str = "11111111111111111111111111111114";
    const LOADED_R: &str = "11111111111111111111111111111115";
    const TOKEN_ACCT: &str = "11111111111111111111111111111116";
    const MINT_A: &str = "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v";
    const MINT_B: &str = "Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB";
    const OWNER_1: &str = "So11111111111111111111111111111111111111112";
    const SIG: &str = "1111111111111111111111111111111111111111111111111111111111111111";

    fn address(s: &str) -> Address {
        s.parse().expect("valid address")
    }

    /// Deserializing the wire JSON is sturdier than building the many `OptionSerializer` fields.
    fn decode(transaction: Value, meta: Value) -> Result<BalanceChanges, BalanceChangesError> {
        let tx: EncodedTransactionWithStatusMeta =
            serde_json::from_value(json!({ "transaction": transaction, "meta": meta }))
                .expect("valid encoded transaction");
        balance_changes(&tx)
    }

    fn raw_transaction(account_keys: &[&str]) -> Value {
        json!({
            "signatures": [SIG],
            "message": {
                "header": {
                    "numRequiredSignatures": 1,
                    "numReadonlySignedAccounts": 0,
                    "numReadonlyUnsignedAccounts": 0,
                },
                "accountKeys": account_keys,
                "recentBlockhash": "hash",
                "instructions": [],
            },
        })
    }

    /// A jsonParsed message: `transaction` keys first, then `lookupTable` ones, as the RPC lists them.
    fn parsed_transaction(static_keys: &[&str], loaded_keys: &[&str]) -> Value {
        let account = |pubkey: &&str, source| json!({ "pubkey": pubkey, "writable": true, "signer": false, "source": source });
        let account_keys: Vec<Value> = static_keys
            .iter()
            .map(|k| account(k, "transaction"))
            .chain(loaded_keys.iter().map(|k| account(k, "lookupTable")))
            .collect();
        json!({
            "signatures": [SIG],
            "message": {
                "accountKeys": account_keys,
                "recentBlockhash": "hash",
                "instructions": [],
            },
        })
    }

    fn meta(pre: &[u64], post: &[u64]) -> Value {
        json!({
            "err": null, "status": {"Ok": null}, "fee": 0,
            "preBalances": pre, "postBalances": post,
        })
    }

    fn token_balance(account_index: u8, mint: &str, amount: &str) -> Value {
        json!({
            "accountIndex": account_index,
            "mint": mint,
            "owner": OWNER_1,
            "uiTokenAmount": {
                "uiAmount": null,
                "decimals": 6,
                "amount": amount,
                "uiAmountString": amount,
            },
        })
    }

    fn token_meta(pre: Vec<Value>, post: Vec<Value>) -> Value {
        let mut meta = meta(&[100, 10], &[100, 10]);
        meta["preTokenBalances"] = pre.into();
        meta["postTokenBalances"] = post.into();
        meta
    }

    #[test]
    fn missing_meta_is_an_error() {
        let result = decode(raw_transaction(&[PAYER]), Value::Null);
        assert!(matches!(result, Err(BalanceChangesError::MissingMeta)));
    }

    #[rstest]
    #[case::binary(json!(["AQ==", "base64"]))]
    #[case::legacy_binary(json!("3qd"))]
    #[case::accounts(json!({
        "signatures": [SIG],
        "accountKeys": [{ "pubkey": PAYER, "writable": true, "signer": true, "source": "transaction" }],
    }))]
    fn binary_and_accounts_encodings_are_unsupported(#[case] transaction: Value) {
        let result = decode(transaction, meta(&[100], &[100]));
        assert!(matches!(
            result,
            Err(BalanceChangesError::UnsupportedEncoding)
        ));
    }

    #[test]
    fn loaded_addresses_extend_static_keys_and_equal_balances_are_skipped() {
        let mut meta = meta(&[100, 50, 10, 7], &[90, 50, 25, 7]);
        meta["loadedAddresses"] = json!({"writable": [LOADED_W], "readonly": [LOADED_R]});
        let changes = decode(raw_transaction(&[PAYER, STATIC_1]), meta).unwrap();

        // Index 2 must resolve to the loaded key, not a static one.
        assert_eq!(
            changes.sol,
            [
                SolChange {
                    pubkey: address(PAYER),
                    pre_lamports: 100,
                    post_lamports: 90,
                },
                SolChange {
                    pubkey: address(LOADED_W),
                    pre_lamports: 10,
                    post_lamports: 25,
                },
            ]
        );
        assert_eq!(changes.sol[0].delta(), -10);
    }

    #[test]
    fn parsed_v0_message_does_not_double_count_loaded_keys() {
        let mut meta = meta(&[100, 50, 10, 7], &[90, 50, 25, 7]);
        meta["loadedAddresses"] = json!({"writable": [LOADED_W], "readonly": [LOADED_R]});
        let changes = decode(
            parsed_transaction(&[PAYER, STATIC_1], &[LOADED_W, LOADED_R]),
            meta,
        )
        .unwrap();

        let moved: Vec<Address> = changes.sol.iter().map(|c| c.pubkey).collect();
        assert_eq!(moved, [address(PAYER), address(LOADED_W)]);
    }

    #[test]
    fn post_only_token_balance_gets_zero_pre_amount() {
        let changes = decode(
            raw_transaction(&[PAYER, TOKEN_ACCT]),
            token_meta(vec![], vec![token_balance(1, MINT_A, "500")]),
        )
        .unwrap();

        assert_eq!(
            changes.token,
            [TokenChange {
                pubkey: address(TOKEN_ACCT),
                mint: address(MINT_A),
                owner: Some(address(OWNER_1)),
                pre_amount: 0,
                post_amount: 500,
                decimals: 6,
            }]
        );
    }

    #[test]
    fn equal_token_amounts_are_skipped() {
        let changes = decode(
            raw_transaction(&[PAYER, TOKEN_ACCT]),
            token_meta(
                vec![token_balance(1, MINT_A, "500")],
                vec![token_balance(1, MINT_A, "500")],
            ),
        )
        .unwrap();
        assert!(changes.token.is_empty());
    }

    #[test]
    fn token_delta_above_i64_max_is_exact() {
        let changes = decode(
            raw_transaction(&[PAYER, TOKEN_ACCT]),
            token_meta(
                vec![token_balance(1, MINT_A, "0")],
                vec![token_balance(1, MINT_A, &u64::MAX.to_string())],
            ),
        )
        .unwrap();
        assert_eq!(changes.token[0].delta(), i128::from(u64::MAX));
    }

    #[test]
    fn unparseable_token_amount_is_an_error() {
        let result = decode(
            raw_transaction(&[PAYER, TOKEN_ACCT]),
            token_meta(vec![token_balance(1, MINT_A, "1.5")], vec![]),
        );
        assert!(matches!(result, Err(BalanceChangesError::TokenAmount(_))));
    }

    #[rstest]
    #[case::short_pre(&[100], &[100, 10])]
    #[case::short_post(&[100, 10], &[100])]
    #[case::extra_post(&[100, 10], &[100, 10, 1])]
    fn balance_count_mismatch_is_an_error(#[case] pre: &[u64], #[case] post: &[u64]) {
        let result = decode(raw_transaction(&[PAYER, TOKEN_ACCT]), meta(pre, post));
        assert!(matches!(
            result,
            Err(BalanceChangesError::BalanceCount { keys: 2, .. })
        ));
    }

    #[test]
    fn token_index_outside_keys_is_an_error() {
        let result = decode(
            raw_transaction(&[PAYER, TOKEN_ACCT]),
            token_meta(vec![], vec![token_balance(2, MINT_A, "500")]),
        );
        assert!(matches!(
            result,
            Err(BalanceChangesError::TokenIndex { index: 2, keys: 2 })
        ));
    }

    #[test]
    fn mint_change_at_same_index_yields_two_changes() {
        // The account was closed and reopened for another mint within the transaction.
        let changes = decode(
            raw_transaction(&[PAYER, TOKEN_ACCT]),
            token_meta(
                vec![token_balance(1, MINT_A, "500")],
                vec![token_balance(1, MINT_B, "700")],
            ),
        )
        .unwrap();

        let moved: Vec<(Address, u64, u64)> = changes
            .token
            .iter()
            .map(|c| (c.mint, c.pre_amount, c.post_amount))
            .collect();
        let mut expected = [(address(MINT_A), 500, 0), (address(MINT_B), 0, 700)];
        expected.sort();
        assert_eq!(moved, expected);
    }
}