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)]
224mod tests {
225    use rstest::rstest;
226    use serde_json::{Value, json};
227
228    use super::*;
229
230    const PAYER: &str = "11111111111111111111111111111112";
231    const STATIC_1: &str = "11111111111111111111111111111113";
232    const LOADED_W: &str = "11111111111111111111111111111114";
233    const LOADED_R: &str = "11111111111111111111111111111115";
234    const TOKEN_ACCT: &str = "11111111111111111111111111111116";
235    const MINT_A: &str = "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v";
236    const MINT_B: &str = "Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB";
237    const OWNER_1: &str = "So11111111111111111111111111111111111111112";
238    const SIG: &str = "1111111111111111111111111111111111111111111111111111111111111111";
239
240    fn address(s: &str) -> Address {
241        s.parse().expect("valid address")
242    }
243
244    /// Deserializing the wire JSON is sturdier than building the many `OptionSerializer` fields.
245    fn decode(transaction: Value, meta: Value) -> Result<BalanceChanges, BalanceChangesError> {
246        let tx: EncodedTransactionWithStatusMeta =
247            serde_json::from_value(json!({ "transaction": transaction, "meta": meta }))
248                .expect("valid encoded transaction");
249        balance_changes(&tx)
250    }
251
252    fn raw_transaction(account_keys: &[&str]) -> Value {
253        json!({
254            "signatures": [SIG],
255            "message": {
256                "header": {
257                    "numRequiredSignatures": 1,
258                    "numReadonlySignedAccounts": 0,
259                    "numReadonlyUnsignedAccounts": 0,
260                },
261                "accountKeys": account_keys,
262                "recentBlockhash": "hash",
263                "instructions": [],
264            },
265        })
266    }
267
268    /// A jsonParsed message: `transaction` keys first, then `lookupTable` ones, as the RPC lists them.
269    fn parsed_transaction(static_keys: &[&str], loaded_keys: &[&str]) -> Value {
270        let account = |pubkey: &&str, source| json!({ "pubkey": pubkey, "writable": true, "signer": false, "source": source });
271        let account_keys: Vec<Value> = static_keys
272            .iter()
273            .map(|k| account(k, "transaction"))
274            .chain(loaded_keys.iter().map(|k| account(k, "lookupTable")))
275            .collect();
276        json!({
277            "signatures": [SIG],
278            "message": {
279                "accountKeys": account_keys,
280                "recentBlockhash": "hash",
281                "instructions": [],
282            },
283        })
284    }
285
286    fn meta(pre: &[u64], post: &[u64]) -> Value {
287        json!({
288            "err": null, "status": {"Ok": null}, "fee": 0,
289            "preBalances": pre, "postBalances": post,
290        })
291    }
292
293    fn token_balance(account_index: u8, mint: &str, amount: &str) -> Value {
294        json!({
295            "accountIndex": account_index,
296            "mint": mint,
297            "owner": OWNER_1,
298            "uiTokenAmount": {
299                "uiAmount": null,
300                "decimals": 6,
301                "amount": amount,
302                "uiAmountString": amount,
303            },
304        })
305    }
306
307    fn token_meta(pre: Vec<Value>, post: Vec<Value>) -> Value {
308        let mut meta = meta(&[100, 10], &[100, 10]);
309        meta["preTokenBalances"] = pre.into();
310        meta["postTokenBalances"] = post.into();
311        meta
312    }
313
314    #[test]
315    fn missing_meta_is_an_error() {
316        let result = decode(raw_transaction(&[PAYER]), Value::Null);
317        assert!(matches!(result, Err(BalanceChangesError::MissingMeta)));
318    }
319
320    #[rstest]
321    #[case::binary(json!(["AQ==", "base64"]))]
322    #[case::legacy_binary(json!("3qd"))]
323    #[case::accounts(json!({
324        "signatures": [SIG],
325        "accountKeys": [{ "pubkey": PAYER, "writable": true, "signer": true, "source": "transaction" }],
326    }))]
327    fn binary_and_accounts_encodings_are_unsupported(#[case] transaction: Value) {
328        let result = decode(transaction, meta(&[100], &[100]));
329        assert!(matches!(
330            result,
331            Err(BalanceChangesError::UnsupportedEncoding)
332        ));
333    }
334
335    #[test]
336    fn loaded_addresses_extend_static_keys_and_equal_balances_are_skipped() {
337        let mut meta = meta(&[100, 50, 10, 7], &[90, 50, 25, 7]);
338        meta["loadedAddresses"] = json!({"writable": [LOADED_W], "readonly": [LOADED_R]});
339        let changes = decode(raw_transaction(&[PAYER, STATIC_1]), meta).unwrap();
340
341        // Index 2 must resolve to the loaded key, not a static one.
342        assert_eq!(
343            changes.sol,
344            [
345                SolChange {
346                    pubkey: address(PAYER),
347                    pre_lamports: 100,
348                    post_lamports: 90,
349                },
350                SolChange {
351                    pubkey: address(LOADED_W),
352                    pre_lamports: 10,
353                    post_lamports: 25,
354                },
355            ]
356        );
357        assert_eq!(changes.sol[0].delta(), -10);
358    }
359
360    #[test]
361    fn parsed_v0_message_does_not_double_count_loaded_keys() {
362        let mut meta = meta(&[100, 50, 10, 7], &[90, 50, 25, 7]);
363        meta["loadedAddresses"] = json!({"writable": [LOADED_W], "readonly": [LOADED_R]});
364        let changes = decode(
365            parsed_transaction(&[PAYER, STATIC_1], &[LOADED_W, LOADED_R]),
366            meta,
367        )
368        .unwrap();
369
370        let moved: Vec<Address> = changes.sol.iter().map(|c| c.pubkey).collect();
371        assert_eq!(moved, [address(PAYER), address(LOADED_W)]);
372    }
373
374    #[test]
375    fn post_only_token_balance_gets_zero_pre_amount() {
376        let changes = decode(
377            raw_transaction(&[PAYER, TOKEN_ACCT]),
378            token_meta(vec![], vec![token_balance(1, MINT_A, "500")]),
379        )
380        .unwrap();
381
382        assert_eq!(
383            changes.token,
384            [TokenChange {
385                pubkey: address(TOKEN_ACCT),
386                mint: address(MINT_A),
387                owner: Some(address(OWNER_1)),
388                pre_amount: 0,
389                post_amount: 500,
390                decimals: 6,
391            }]
392        );
393    }
394
395    #[test]
396    fn equal_token_amounts_are_skipped() {
397        let changes = decode(
398            raw_transaction(&[PAYER, TOKEN_ACCT]),
399            token_meta(
400                vec![token_balance(1, MINT_A, "500")],
401                vec![token_balance(1, MINT_A, "500")],
402            ),
403        )
404        .unwrap();
405        assert!(changes.token.is_empty());
406    }
407
408    #[test]
409    fn token_delta_above_i64_max_is_exact() {
410        let changes = decode(
411            raw_transaction(&[PAYER, TOKEN_ACCT]),
412            token_meta(
413                vec![token_balance(1, MINT_A, "0")],
414                vec![token_balance(1, MINT_A, &u64::MAX.to_string())],
415            ),
416        )
417        .unwrap();
418        assert_eq!(changes.token[0].delta(), i128::from(u64::MAX));
419    }
420
421    #[test]
422    fn unparseable_token_amount_is_an_error() {
423        let result = decode(
424            raw_transaction(&[PAYER, TOKEN_ACCT]),
425            token_meta(vec![token_balance(1, MINT_A, "1.5")], vec![]),
426        );
427        assert!(matches!(result, Err(BalanceChangesError::TokenAmount(_))));
428    }
429
430    #[rstest]
431    #[case::short_pre(&[100], &[100, 10])]
432    #[case::short_post(&[100, 10], &[100])]
433    #[case::extra_post(&[100, 10], &[100, 10, 1])]
434    fn balance_count_mismatch_is_an_error(#[case] pre: &[u64], #[case] post: &[u64]) {
435        let result = decode(raw_transaction(&[PAYER, TOKEN_ACCT]), meta(pre, post));
436        assert!(matches!(
437            result,
438            Err(BalanceChangesError::BalanceCount { keys: 2, .. })
439        ));
440    }
441
442    #[test]
443    fn token_index_outside_keys_is_an_error() {
444        let result = decode(
445            raw_transaction(&[PAYER, TOKEN_ACCT]),
446            token_meta(vec![], vec![token_balance(2, MINT_A, "500")]),
447        );
448        assert!(matches!(
449            result,
450            Err(BalanceChangesError::TokenIndex { index: 2, keys: 2 })
451        ));
452    }
453
454    #[test]
455    fn mint_change_at_same_index_yields_two_changes() {
456        // The account was closed and reopened for another mint within the transaction.
457        let changes = decode(
458            raw_transaction(&[PAYER, TOKEN_ACCT]),
459            token_meta(
460                vec![token_balance(1, MINT_A, "500")],
461                vec![token_balance(1, MINT_B, "700")],
462            ),
463        )
464        .unwrap();
465
466        let moved: Vec<(Address, u64, u64)> = changes
467            .token
468            .iter()
469            .map(|c| (c.mint, c.pre_amount, c.post_amount))
470            .collect();
471        let mut expected = [(address(MINT_A), 500, 0), (address(MINT_B), 0, 700)];
472        expected.sort();
473        assert_eq!(moved, expected);
474    }
475}