Skip to main content

simulator_client/
balances.rs

1//! Lamport and token balance changes read from an encoded transaction's metadata.
2
3use std::{
4    collections::{BTreeMap, BTreeSet},
5    num::ParseIntError,
6};
7
8use solana_address::{Address, error::ParseAddressError};
9use solana_transaction_status::{
10    EncodedTransaction, EncodedTransactionWithStatusMeta, UiMessage, UiTransactionTokenBalance,
11    option_serializer::OptionSerializer,
12};
13use thiserror::Error;
14
15/// Accounts whose balance moved in one transaction; unchanged accounts are omitted.
16#[derive(Debug, Clone, PartialEq, Eq)]
17pub struct BalanceChanges {
18    /// Lamport changes, in account-key order.
19    pub sol: Vec<SolChange>,
20    /// Token changes, ordered by account index then mint.
21    pub token: Vec<TokenChange>,
22}
23
24/// One account's lamport balance before and after the transaction.
25#[derive(Debug, Clone, PartialEq, Eq)]
26pub struct SolChange {
27    /// The account.
28    pub pubkey: Address,
29    /// Lamports before execution.
30    pub pre_lamports: u64,
31    /// Lamports after execution.
32    pub post_lamports: u64,
33}
34
35impl SolChange {
36    /// Signed lamport change, `post - pre`.
37    pub fn delta(&self) -> i128 {
38        i128::from(self.post_lamports) - i128::from(self.pre_lamports)
39    }
40}
41
42/// One token account's balance of one mint before and after the transaction.
43#[derive(Debug, Clone, PartialEq, Eq)]
44pub struct TokenChange {
45    /// The token account.
46    pub pubkey: Address,
47    /// The token's mint.
48    pub mint: Address,
49    /// The token account's owner. Absent when the meta omits it.
50    pub owner: Option<Address>,
51    /// Base units before execution; 0 when the account held none of `mint`.
52    pub pre_amount: u64,
53    /// Base units after execution; 0 when the account holds none of `mint`.
54    pub post_amount: u64,
55    /// The mint's decimal places.
56    pub decimals: u8,
57}
58
59impl TokenChange {
60    /// Signed change in base units, `post - pre`.
61    pub fn delta(&self) -> i128 {
62        i128::from(self.post_amount) - i128::from(self.pre_amount)
63    }
64}
65
66/// Why [`balance_changes`] could not read a transaction.
67#[derive(Debug, Error)]
68pub enum BalanceChangesError {
69    /// The transaction carries no status meta.
70    #[error("transaction has no status meta")]
71    MissingMeta,
72    /// Only JSON and jsonParsed encodings carry the account keys.
73    #[error("transaction encoding carries no account keys; request json or jsonParsed")]
74    UnsupportedEncoding,
75    /// An account key, mint or owner is not a valid address.
76    #[error("invalid address: {0}")]
77    Address(#[from] ParseAddressError),
78    /// A token balance's raw amount is not a `u64`.
79    #[error("invalid token amount: {0}")]
80    TokenAmount(#[from] ParseIntError),
81    /// The lamport balance lists do not match the account keys one to one.
82    #[error("{keys} account keys but {pre} pre and {post} post balances")]
83    BalanceCount {
84        /// Account keys, including lookup-table loads.
85        keys: usize,
86        /// Entries in `pre_balances`.
87        pre: usize,
88        /// Entries in `post_balances`.
89        post: usize,
90    },
91    /// A token balance points past the account keys.
92    #[error("token balance account index {index} is out of range for {keys} account keys")]
93    TokenIndex {
94        /// The token balance's `account_index`.
95        index: u8,
96        /// Account keys, including lookup-table loads.
97        keys: usize,
98    },
99}
100
101/// One token balance's fields other than its `(account_index, mint)` key.
102struct TokenBalance {
103    amount: u64,
104    owner: Option<Address>,
105    decimals: u8,
106}
107
108/// Full key list (static + lookup-loaded) joined with the meta's balances.
109///
110/// # Errors
111/// See [`BalanceChangesError`]; a malformed payload fails rather than yielding partial changes.
112pub fn balance_changes(
113    tx: &EncodedTransactionWithStatusMeta,
114) -> Result<BalanceChanges, BalanceChangesError> {
115    let meta = tx.meta.as_ref().ok_or(BalanceChangesError::MissingMeta)?;
116    let EncodedTransaction::Json(ui_tx) = &tx.transaction else {
117        return Err(BalanceChangesError::UnsupportedEncoding);
118    };
119    let keys = match &ui_tx.message {
120        // A raw v0 message lists only its static keys; the meta carries the lookup-loaded ones.
121        UiMessage::Raw(raw) => {
122            let loaded = match &meta.loaded_addresses {
123                OptionSerializer::Some(loaded) => Some(loaded),
124                _ => None,
125            };
126            raw.account_keys
127                .iter()
128                .chain(
129                    loaded
130                        .into_iter()
131                        .flat_map(|l| l.writable.iter().chain(&l.readonly)),
132                )
133                .map(|key| key.parse())
134                .collect::<Result<Vec<Address>, _>>()?
135        }
136        // jsonParsed already includes the lookup-loaded keys.
137        UiMessage::Parsed(parsed) => parsed
138            .account_keys
139            .iter()
140            .map(|key| key.pubkey.parse())
141            .collect::<Result<Vec<Address>, _>>()?,
142    };
143
144    if meta.pre_balances.len() != keys.len() || meta.post_balances.len() != keys.len() {
145        return Err(BalanceChangesError::BalanceCount {
146            keys: keys.len(),
147            pre: meta.pre_balances.len(),
148            post: meta.post_balances.len(),
149        });
150    }
151    let sol = keys
152        .iter()
153        .zip(meta.pre_balances.iter().zip(&meta.post_balances))
154        .filter(|(_, (pre, post))| pre != post)
155        .map(|(pubkey, (&pre_lamports, &post_lamports))| SolChange {
156            pubkey: *pubkey,
157            pre_lamports,
158            post_lamports,
159        })
160        .collect();
161
162    let pre = token_balances(&meta.pre_token_balances, keys.len())?;
163    let post = token_balances(&meta.post_token_balances, keys.len())?;
164    let token = pre
165        .keys()
166        .chain(post.keys())
167        .copied()
168        .collect::<BTreeSet<_>>()
169        .into_iter()
170        .filter_map(|key @ (index, mint)| {
171            let (pre, post) = (pre.get(&key), post.get(&key));
172            let pre_amount = pre.map_or(0, |b| b.amount);
173            let post_amount = post.map_or(0, |b| b.amount);
174            if pre_amount == post_amount {
175                return None;
176            }
177            let balance = pre.or(post)?;
178            Some(TokenChange {
179                pubkey: *keys.get(usize::from(index))?,
180                mint,
181                owner: balance.owner,
182                pre_amount,
183                post_amount,
184                decimals: balance.decimals,
185            })
186        })
187        .collect();
188
189    Ok(BalanceChanges { sol, token })
190}
191
192/// Index token balances by `(account_index, mint)`, checking each index against `keys`.
193fn token_balances(
194    balances: &OptionSerializer<Vec<UiTransactionTokenBalance>>,
195    keys: usize,
196) -> Result<BTreeMap<(u8, Address), TokenBalance>, BalanceChangesError> {
197    let OptionSerializer::Some(balances) = balances else {
198        return Ok(BTreeMap::new());
199    };
200    balances
201        .iter()
202        .map(|balance| {
203            let index = balance.account_index;
204            if usize::from(index) >= keys {
205                return Err(BalanceChangesError::TokenIndex { index, keys });
206            }
207            let owner = match &balance.owner {
208                OptionSerializer::Some(owner) => Some(owner.parse()?),
209                _ => None,
210            };
211            Ok((
212                (index, balance.mint.parse()?),
213                TokenBalance {
214                    amount: balance.ui_token_amount.amount.parse()?,
215                    owner,
216                    decimals: balance.ui_token_amount.decimals,
217                },
218            ))
219        })
220        .collect()
221}
222
223#[cfg(test)]
224#[expect(clippy::unwrap_in_result, reason = "tests")]
225mod tests {
226    use rstest::rstest;
227    use serde_json::{Value, json};
228
229    use super::*;
230
231    const PAYER: &str = "11111111111111111111111111111112";
232    const STATIC_1: &str = "11111111111111111111111111111113";
233    const LOADED_W: &str = "11111111111111111111111111111114";
234    const LOADED_R: &str = "11111111111111111111111111111115";
235    const TOKEN_ACCT: &str = "11111111111111111111111111111116";
236    const MINT_A: &str = "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v";
237    const MINT_B: &str = "Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB";
238    const OWNER_1: &str = "So11111111111111111111111111111111111111112";
239    const SIG: &str = "1111111111111111111111111111111111111111111111111111111111111111";
240
241    fn address(s: &str) -> Address {
242        s.parse().expect("valid address")
243    }
244
245    /// Deserializing the wire JSON is sturdier than building the many `OptionSerializer` fields.
246    fn decode(transaction: &Value, meta: &Value) -> Result<BalanceChanges, BalanceChangesError> {
247        let tx: EncodedTransactionWithStatusMeta =
248            serde_json::from_value(json!({ "transaction": transaction, "meta": meta }))
249                .expect("valid encoded transaction");
250        balance_changes(&tx)
251    }
252
253    fn raw_transaction(account_keys: &[&str]) -> Value {
254        json!({
255            "signatures": [SIG],
256            "message": {
257                "header": {
258                    "numRequiredSignatures": 1,
259                    "numReadonlySignedAccounts": 0,
260                    "numReadonlyUnsignedAccounts": 0,
261                },
262                "accountKeys": account_keys,
263                "recentBlockhash": "hash",
264                "instructions": [],
265            },
266        })
267    }
268
269    /// A jsonParsed message: `transaction` keys first, then `lookupTable` ones, as the RPC lists them.
270    fn parsed_transaction(static_keys: &[&str], loaded_keys: &[&str]) -> Value {
271        let account = |pubkey: &&str, source| json!({ "pubkey": pubkey, "writable": true, "signer": false, "source": source });
272        let account_keys: Vec<Value> = static_keys
273            .iter()
274            .map(|k| account(k, "transaction"))
275            .chain(loaded_keys.iter().map(|k| account(k, "lookupTable")))
276            .collect();
277        json!({
278            "signatures": [SIG],
279            "message": {
280                "accountKeys": account_keys,
281                "recentBlockhash": "hash",
282                "instructions": [],
283            },
284        })
285    }
286
287    fn meta(pre: &[u64], post: &[u64]) -> Value {
288        json!({
289            "err": null, "status": {"Ok": null}, "fee": 0,
290            "preBalances": pre, "postBalances": post,
291        })
292    }
293
294    fn token_balance(account_index: u8, mint: &str, amount: &str) -> Value {
295        json!({
296            "accountIndex": account_index,
297            "mint": mint,
298            "owner": OWNER_1,
299            "uiTokenAmount": {
300                "uiAmount": null,
301                "decimals": 6,
302                "amount": amount,
303                "uiAmountString": amount,
304            },
305        })
306    }
307
308    fn token_meta(pre: Vec<Value>, post: Vec<Value>) -> Value {
309        let mut meta = meta(&[100, 10], &[100, 10]);
310        meta["preTokenBalances"] = pre.into();
311        meta["postTokenBalances"] = post.into();
312        meta
313    }
314
315    #[test]
316    fn missing_meta_is_an_error() {
317        let result = decode(&raw_transaction(&[PAYER]), &Value::Null);
318        assert!(matches!(result, Err(BalanceChangesError::MissingMeta)));
319    }
320
321    #[rstest]
322    #[case::binary(json!(["AQ==", "base64"]))]
323    #[case::legacy_binary(json!("3qd"))]
324    #[case::accounts(json!({
325        "signatures": [SIG],
326        "accountKeys": [{ "pubkey": PAYER, "writable": true, "signer": true, "source": "transaction" }],
327    }))]
328    fn binary_and_accounts_encodings_are_unsupported(#[case] transaction: Value) {
329        let result = decode(&transaction, &meta(&[100], &[100]));
330        assert!(matches!(
331            result,
332            Err(BalanceChangesError::UnsupportedEncoding)
333        ));
334    }
335
336    #[test]
337    fn loaded_addresses_extend_static_keys_and_equal_balances_are_skipped() {
338        let mut meta = meta(&[100, 50, 10, 7], &[90, 50, 25, 7]);
339        meta["loadedAddresses"] = json!({"writable": [LOADED_W], "readonly": [LOADED_R]});
340        let changes = decode(&raw_transaction(&[PAYER, STATIC_1]), &meta).unwrap();
341
342        // Index 2 must resolve to the loaded key, not a static one.
343        assert_eq!(
344            changes.sol,
345            [
346                SolChange {
347                    pubkey: address(PAYER),
348                    pre_lamports: 100,
349                    post_lamports: 90,
350                },
351                SolChange {
352                    pubkey: address(LOADED_W),
353                    pre_lamports: 10,
354                    post_lamports: 25,
355                },
356            ]
357        );
358        assert_eq!(changes.sol[0].delta(), -10);
359    }
360
361    #[test]
362    fn parsed_v0_message_does_not_double_count_loaded_keys() {
363        let mut meta = meta(&[100, 50, 10, 7], &[90, 50, 25, 7]);
364        meta["loadedAddresses"] = json!({"writable": [LOADED_W], "readonly": [LOADED_R]});
365        let changes = decode(
366            &parsed_transaction(&[PAYER, STATIC_1], &[LOADED_W, LOADED_R]),
367            &meta,
368        )
369        .unwrap();
370
371        let moved: Vec<Address> = changes.sol.iter().map(|c| c.pubkey).collect();
372        assert_eq!(moved, [address(PAYER), address(LOADED_W)]);
373    }
374
375    #[test]
376    fn post_only_token_balance_gets_zero_pre_amount() {
377        let changes = decode(
378            &raw_transaction(&[PAYER, TOKEN_ACCT]),
379            &token_meta(vec![], vec![token_balance(1, MINT_A, "500")]),
380        )
381        .unwrap();
382
383        assert_eq!(
384            changes.token,
385            [TokenChange {
386                pubkey: address(TOKEN_ACCT),
387                mint: address(MINT_A),
388                owner: Some(address(OWNER_1)),
389                pre_amount: 0,
390                post_amount: 500,
391                decimals: 6,
392            }]
393        );
394    }
395
396    #[test]
397    fn equal_token_amounts_are_skipped() {
398        let changes = decode(
399            &raw_transaction(&[PAYER, TOKEN_ACCT]),
400            &token_meta(
401                vec![token_balance(1, MINT_A, "500")],
402                vec![token_balance(1, MINT_A, "500")],
403            ),
404        )
405        .unwrap();
406        assert!(changes.token.is_empty());
407    }
408
409    #[test]
410    fn token_delta_above_i64_max_is_exact() {
411        let changes = decode(
412            &raw_transaction(&[PAYER, TOKEN_ACCT]),
413            &token_meta(
414                vec![token_balance(1, MINT_A, "0")],
415                vec![token_balance(1, MINT_A, &u64::MAX.to_string())],
416            ),
417        )
418        .unwrap();
419        assert_eq!(changes.token[0].delta(), i128::from(u64::MAX));
420    }
421
422    #[test]
423    fn unparseable_token_amount_is_an_error() {
424        let result = decode(
425            &raw_transaction(&[PAYER, TOKEN_ACCT]),
426            &token_meta(vec![token_balance(1, MINT_A, "1.5")], vec![]),
427        );
428        assert!(matches!(result, Err(BalanceChangesError::TokenAmount(_))));
429    }
430
431    #[rstest]
432    #[case::short_pre(&[100], &[100, 10])]
433    #[case::short_post(&[100, 10], &[100])]
434    #[case::extra_post(&[100, 10], &[100, 10, 1])]
435    fn balance_count_mismatch_is_an_error(#[case] pre: &[u64], #[case] post: &[u64]) {
436        let result = decode(&raw_transaction(&[PAYER, TOKEN_ACCT]), &meta(pre, post));
437        assert!(matches!(
438            result,
439            Err(BalanceChangesError::BalanceCount { keys: 2, .. })
440        ));
441    }
442
443    #[test]
444    fn token_index_outside_keys_is_an_error() {
445        let result = decode(
446            &raw_transaction(&[PAYER, TOKEN_ACCT]),
447            &token_meta(vec![], vec![token_balance(2, MINT_A, "500")]),
448        );
449        assert!(matches!(
450            result,
451            Err(BalanceChangesError::TokenIndex { index: 2, keys: 2 })
452        ));
453    }
454
455    #[test]
456    fn mint_change_at_same_index_yields_two_changes() {
457        // The account was closed and reopened for another mint within the transaction.
458        let changes = decode(
459            &raw_transaction(&[PAYER, TOKEN_ACCT]),
460            &token_meta(
461                vec![token_balance(1, MINT_A, "500")],
462                vec![token_balance(1, MINT_B, "700")],
463            ),
464        )
465        .unwrap();
466
467        let moved: Vec<(Address, u64, u64)> = changes
468            .token
469            .iter()
470            .map(|c| (c.mint, c.pre_amount, c.post_amount))
471            .collect();
472        let mut expected = [(address(MINT_A), 500, 0), (address(MINT_B), 0, 700)];
473        expected.sort();
474        assert_eq!(moved, expected);
475    }
476}