fogo-paymaster 0.7.2

Fogo paymaster service and transaction validator CLI
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
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
use axum::{http::StatusCode, response::ErrorResponse};
use base64::prelude::*;
use dashmap::DashMap;
use futures::stream::StreamExt;
use serde_json::json;
use solana_address_lookup_table_interface::state::AddressLookupTable;
use solana_client::{
    nonblocking::rpc_client::RpcClient,
    rpc_config::{RpcSendTransactionConfig, RpcSignatureSubscribeConfig, RpcTransactionConfig},
};
use solana_commitment_config::CommitmentConfig;
use solana_message::VersionedMessage;
use solana_program::program_pack::Pack;
use solana_pubkey::Pubkey;
use solana_rpc_client_api::client_error::{Error, ErrorKind};
use solana_rpc_client_api::request::RpcRequest;
use solana_signature::Signature;
use solana_transaction::versioned::VersionedTransaction;
use solana_transaction_error::TransactionError;
use solana_transaction_status_client_types::{
    EncodedConfirmedTransactionWithStatusMeta, UiTransactionEncoding, UiTransactionTokenBalance,
};
use spl_token::amount_to_ui_amount;
use std::time::Duration;
use tokio::time::timeout;

use crate::{
    api::{ConfirmationResult, PubsubClientWithReconnect},
    constraint::transaction::InstructionWithIndex,
};

pub struct ChainIndex {
    pub rpc: RpcClient,
    pub lookup_table_cache: DashMap<Pubkey, Vec<Pubkey>>,
}

pub enum ConfirmationResultInternal {
    /// Transaction was confirmed and succeeded on chain
    Success { signature: Signature },

    /// Transaction was confirmed but failed on chain
    Failed {
        signature: Signature,
        error: TransactionError,
    },

    /// Transaction was not confirmed due to preflight failure
    UnconfirmedPreflightFailure {
        signature: Signature,
        error: TransactionError,
    },
}

impl ConfirmationResultInternal {
    pub fn status_string(&self) -> String {
        match self {
            ConfirmationResultInternal::Success { .. } => "success".to_string(),
            ConfirmationResultInternal::Failed { .. } => "failed".to_string(),
            ConfirmationResultInternal::UnconfirmedPreflightFailure { .. } => {
                "unconfirmed_preflight_failure".to_string()
            }
        }
    }
}

impl From<ConfirmationResultInternal> for ConfirmationResult {
    fn from(internal: ConfirmationResultInternal) -> Self {
        match internal {
            ConfirmationResultInternal::Success { signature } => {
                ConfirmationResult::Success { signature }
            }
            ConfirmationResultInternal::Failed { signature, error } => {
                ConfirmationResult::Failed { signature, error }
            }
            ConfirmationResultInternal::UnconfirmedPreflightFailure { signature, error } => {
                ConfirmationResult::Failed { signature, error }
            }
        }
    }
}

/// A wrapper around `VersionedTransaction` that guarantees the transaction has been signed by its fee payer (first signature slot).
pub struct SignedVersionedTransaction(VersionedTransaction);

impl SignedVersionedTransaction {
    /// Creates a new SignedVersionedTransaction by adding the signature to the transaction.
    /// Returns an error if the transaction has no signature slots.
    pub fn new(
        mut transaction: VersionedTransaction,
        signature: Signature,
    ) -> anyhow::Result<Self> {
        *transaction.signatures.get_mut(0).ok_or_else(|| {
            anyhow::anyhow!("Transaction must have at least one signature slot")
        })? = signature;
        Ok(Self(transaction))
    }

    /// Returns the fee-payer signature of the transaction.
    pub fn signature(&self) -> &Signature {
        self.0
            .signatures
            .first()
            .expect("SignedVersionedTransaction is guaranteed to have at least one signature slot")
    }
}

impl AsRef<VersionedTransaction> for SignedVersionedTransaction {
    fn as_ref(&self) -> &VersionedTransaction {
        &self.0
    }
}

fn to_error_response(err: Error) -> ErrorResponse {
    (
        StatusCode::BAD_GATEWAY,
        format!("Failed SVM RPC call: {err}"),
    )
        .into()
}

impl ChainIndex {
    /// Find the pubkey for the account at index `account_index_within_instruction` within the `instruction_with_index` in the given `transaction`.
    pub async fn resolve_instruction_account_pubkey(
        &self,
        message: &VersionedMessage,
        InstructionWithIndex {
            index: instruction_index,
            instruction,
        }: &InstructionWithIndex<'_>,
        account_index_within_instruction: usize,
    ) -> Result<Pubkey, (StatusCode, String)> {
        let account_index_within_transaction = usize::from(*instruction
            .accounts
            .get(account_index_within_instruction)
            .ok_or_else(|| {
                (
                    StatusCode::BAD_REQUEST,
                    format!(
                        "Account index {account_index_within_instruction} out of bounds for instruction {instruction_index}",
                    ),
                )
            })?);
        if let Some(pubkey) = message
            .static_account_keys()
            .get(account_index_within_transaction)
        {
            Ok(*pubkey)
        } else if let Some(lookup_tables) = message.address_table_lookups() {
            let lookup_accounts: Vec<(Pubkey, u8)> = lookup_tables
                .iter()
                .flat_map(|x| {
                    x.writable_indexes
                        .clone()
                        .into_iter()
                        .map(|y| (x.account_key, y))
                })
                .chain(lookup_tables.iter().flat_map(|x| {
                    x.readonly_indexes
                        .clone()
                        .into_iter()
                        .map(|y| (x.account_key, y))
                }))
                .collect();
            let account_index_within_lookup_tables =
                account_index_within_transaction - message.static_account_keys().len();
            return self
                .find_and_query_lookup_table(lookup_accounts, account_index_within_lookup_tables)
                .await;
        } else {
            Err((
                StatusCode::BAD_REQUEST,
                format!(
                    "Account index {account_index_within_instruction} for instruction {instruction_index} expected to be in the address table lookup but the transaction does not reference any address table lookups",
                ),
            ))
        }
    }

    /// Finds the lookup table and the index within that table that correspond to the given relative account position within the list of lookup invoked accounts.
    async fn find_and_query_lookup_table(
        &self,
        lookup_accounts: Vec<(Pubkey, u8)>,
        account_position_lookups: usize,
    ) -> Result<Pubkey, (StatusCode, String)> {
        let (table_to_query, index_to_query) =
            lookup_accounts.get(account_position_lookups).ok_or_else(|| {
                (
                    StatusCode::BAD_REQUEST,
                    format!("Account position {account_position_lookups} out of bounds for lookup table invoked accounts"),
                )
            })?;
        self.query_lookup_table_with_retry(table_to_query, usize::from(*index_to_query))
            .await
    }

    /// Queries the lookup table for the pubkey at the given index.
    /// If the table is not cached or the index is out of bounds, it fetches and updates the table from the RPC before requerying.
    async fn query_lookup_table_with_retry(
        &self,
        table: &Pubkey,
        index: usize,
    ) -> Result<Pubkey, (StatusCode, String)> {
        if let Some(pubkey) = self.query_lookup_table(table, index) {
            return Ok(pubkey);
        }

        let addresses = self.update_lookup_table(table).await?;
        // get the key from the returned addresses instead of re-querying and re-locking the map
        addresses.get(index).copied().ok_or_else(|| {
            (
                StatusCode::BAD_REQUEST,
                format!("Lookup table {table} does not contain index {index}"),
            )
        })
    }

    /// Queries the lookup table for the pubkey at the given index.
    /// Returns None if the table is not cached or the index is out of bounds.
    fn query_lookup_table(&self, table: &Pubkey, index: usize) -> Option<Pubkey> {
        self.lookup_table_cache
            .get(table)
            .and_then(|entry| entry.get(index).copied())
    }

    // Updates the lookup table entry in the dashmap based on pulling from RPC. Returns the updated table data.
    async fn update_lookup_table(
        &self,
        table: &Pubkey,
    ) -> Result<Vec<Pubkey>, (StatusCode, String)> {
        let table_data = self.rpc.get_account(table).await.map_err(|err| {
            (
                StatusCode::INTERNAL_SERVER_ERROR,
                format!("Failed to fetch lookup table account {table} from RPC: {err}"),
            )
        })?;
        let table_data_deserialized =
            AddressLookupTable::deserialize(&table_data.data).map_err(|e| {
                (
                    StatusCode::INTERNAL_SERVER_ERROR,
                    format!("Failed to deserialize lookup table account {table}: {e}"),
                )
            })?;

        self.lookup_table_cache
            .insert(*table, table_data_deserialized.addresses.to_vec());

        Ok(table_data_deserialized.addresses.to_vec())
    }
}

/// Sends a transaction and waits for confirmation via WebSocket subscription.
#[tracing::instrument(
    skip_all,
    fields(
        tx_hash = %transaction.signature(),
        result
    )
)]
pub async fn send_and_confirm_transaction(
    rpc: &RpcClient,
    pubsub: &PubsubClientWithReconnect,
    transaction: &SignedVersionedTransaction,
    config: RpcSendTransactionConfig,
) -> Result<ConfirmationResultInternal, ErrorResponse> {
    let signature = match rpc
        .send_transaction_with_config(transaction.as_ref(), config)
        .await
    {
        Ok(sig) => {
            tracing::Span::current().record("result", "sent");
            sig
        }
        Err(err) => {
            if let Some(error) = err.get_transaction_error() {
                tracing::Span::current().record("result", "preflight_failure");
                tracing::warn!(
                    "Transaction {} failed preflight: {error}",
                    transaction.signature()
                );
                return Ok(ConfirmationResultInternal::UnconfirmedPreflightFailure {
                    signature: *transaction.signature(),
                    error,
                });
            }
            tracing::Span::current().record("result", "send_failed");
            tracing::error!(
                "Failed to send transaction {}: {err}",
                transaction.signature()
            );
            return Err(to_error_response(err));
        }
    };

    confirm_transaction(pubsub, signature, Some(rpc.commitment())).await
}

/// Sends a transaction using the FTL service which handles both sending and confirmation.
/// The FTL service requires a "confirm" parameter set to true in the RPC config.
#[tracing::instrument(
    skip_all,
    fields(
        tx_hash = %transaction.signature(),
        result
    )
)]
pub async fn send_and_confirm_transaction_ftl(
    ftl_rpc: &RpcClient,
    transaction: &SignedVersionedTransaction,
    config: RpcSendTransactionConfig,
) -> Result<ConfirmationResultInternal, ErrorResponse> {
    let tx_bytes = bincode::serde::encode_to_vec(transaction.as_ref(), bincode::config::standard())
        .map_err(|e| {
            tracing::error!("Failed to serialize transaction: {e}");
            ErrorResponse::from((
                StatusCode::INTERNAL_SERVER_ERROR,
                "Failed to serialize transaction",
            ))
        })?;
    let tx_base64 = BASE64_STANDARD.encode(&tx_bytes);

    let mut config_value = serde_json::to_value(RpcSendTransactionConfig {
        encoding: Some(config.encoding.unwrap_or(UiTransactionEncoding::Base64)),
        preflight_commitment: Some(config.preflight_commitment.unwrap_or_default()),
        ..config
    })
    .map_err(|e| {
        tracing::error!("Failed to serialize config: {e}");
        ErrorResponse::from((
            StatusCode::INTERNAL_SERVER_ERROR,
            "Failed to serialize config",
        ))
    })?;

    // Add the "confirm" parameter to the config
    if let Some(obj) = config_value.as_object_mut() {
        obj.insert("confirm".to_string(), json!(true));
    }

    // Use the RPC client's send method to make the request
    let signature: String = match ftl_rpc
        .send(
            RpcRequest::SendTransaction,
            json!([tx_base64, config_value]),
        )
        .await
    {
        Ok(sig) => {
            tracing::Span::current().record("result", "sent");
            sig
        }
        Err(err) => {
            let preflight = matches!(&err.kind, &ErrorKind::RpcError(_));
            if let Some(error) = err.get_transaction_error() {
                if preflight {
                    tracing::Span::current().record("result", "preflight_failure");
                    tracing::warn!(
                        "Transaction {} failed preflight: {error}",
                        transaction.signature()
                    );
                    return Ok(ConfirmationResultInternal::UnconfirmedPreflightFailure {
                        signature: *transaction.signature(),
                        error,
                    });
                } else {
                    // confirmed failed
                    tracing::Span::current().record("result", "failed");
                    return Ok(ConfirmationResultInternal::Failed {
                        signature: *transaction.signature(),
                        error,
                    });
                }
            }

            tracing::Span::current().record("result", "send_failed");
            tracing::error!(
                "Failed to send transaction {}: {err}",
                transaction.signature()
            );
            return Err(to_error_response(err));
        }
    };

    let signature = signature.parse::<Signature>().map_err(|e| {
        tracing::Span::current().record("result", "send_failed");
        tracing::error!("Failed to parse signature from FTL response: {e}");
        ErrorResponse::from((
            StatusCode::BAD_GATEWAY,
            format!("Failed to parse signature: {e}"),
        ))
    })?;

    tracing::Span::current().record("result", "success");
    // Since FTL handles confirmation, we return success immediately
    Ok(ConfirmationResultInternal::Success { signature })
}

const CONFIRMATION_TIMEOUT: Duration = Duration::from_secs(60);

#[tracing::instrument(
    skip_all,
    fields(
        tx_hash = %signature,
        result
    )
)]
async fn confirm_transaction(
    pubsub: &PubsubClientWithReconnect,
    signature: Signature,
    commitment: Option<CommitmentConfig>,
) -> Result<ConfirmationResultInternal, ErrorResponse> {
    let signature_result = subscribe_and_wait_for_signature(pubsub, signature, commitment, true)
        .await
        .map_err(|(status, err_string)| {
            tracing::Span::current().record("result", "unconfirmed");
            (
                status,
                format!("Failed to confirm transaction {signature}: {err_string}"),
            )
        })?;

    if let Some(err) = signature_result.err {
        tracing::Span::current().record("result", "failed");
        return Ok(ConfirmationResultInternal::Failed {
            signature,
            error: err,
        });
    } else {
        tracing::Span::current().record("result", "success");
        return Ok(ConfirmationResultInternal::Success { signature });
    }
}

#[async_recursion::async_recursion]
async fn subscribe_and_wait_for_signature(
    pubsub: &PubsubClientWithReconnect,
    signature: Signature,
    commitment: Option<CommitmentConfig>,
    reconnect: bool,
) -> Result<solana_client::rpc_response::ProcessedSignatureResult, (StatusCode, String)> {
    let pubsub_client = pubsub.client.load();
    let subscribe_result = pubsub_client
        .signature_subscribe(
            &signature,
            Some(RpcSignatureSubscribeConfig {
                commitment,
                ..RpcSignatureSubscribeConfig::default()
            }),
        )
        .await;

    let (mut stream, unsubscribe) = match subscribe_result {
        Ok(sub) => sub,
        Err(_) => {
            if reconnect {
                tracing::warn!("WebSocket subscription failed, attempting reconnection and retry");
                pubsub.reconnect_pubsub().await?;
                return subscribe_and_wait_for_signature(pubsub, signature, commitment, false)
                    .await;
            }

            tracing::error!("WebSocket subscription failed");

            return Err((
                StatusCode::BAD_GATEWAY,
                "Failed to subscribe to signature".to_string(),
            ));
        }
    };

    // two levels of results here:
    // 1. timeout error (outer)
    // 2. RpcError from the stream failing (inner)
    // innermost contains actual transaction error if transaction failed or success info if it succeeded
    let result = timeout(CONFIRMATION_TIMEOUT, async {
        while let Some(response) = stream.next().await {
            if let solana_client::rpc_response::RpcSignatureResult::ProcessedSignature(
                processed_signature_result,
            ) = response.value
            {
                return Ok(processed_signature_result);
            }
        }

        tracing::error!("Signature subscription stream ended unexpectedly for {signature}");
        Err((
            StatusCode::BAD_GATEWAY,
            "Signature subscription stream ended unexpectedly".to_string(),
        ))
    })
    .await;

    unsubscribe().await;

    result
        .map_err(|_| {
            tracing::error!("Timeout while waiting for transaction confirmation for {signature}");
            (
                StatusCode::GATEWAY_TIMEOUT,
                "Unable to confirm transaction".to_string(),
            )
        })
        .and_then(|r| r)
}

#[derive(Debug, Clone)]
pub struct TransactionCostDetails {
    pub fee: u64,
    pub balance_spend: Option<i64>,
}

#[derive(Debug, Clone)]
pub struct RetryConfig {
    pub max_tries: u32,
    pub sleep_ms: u64,
}

/// Fetches a transaction from RPC with retry logic, then applies a processing function to the response.
/// retry_config configures the retries of the RPC call with sleep on failure. This is useful in cases where the
/// transaction was sent with a lower commitment level, so it may not be confirmed yet.
async fn fetch_transaction_with_retry<T, F>(
    rpc: &RpcClient,
    signature: &Signature,
    retry_config: &RetryConfig,
    process: F,
) -> anyhow::Result<T>
where
    F: Fn(EncodedConfirmedTransactionWithStatusMeta) -> anyhow::Result<T>,
{
    let config = RpcTransactionConfig {
        encoding: Some(UiTransactionEncoding::Base64),
        max_supported_transaction_version: Some(0),
        // this method does not support any commitment below confirmed
        commitment: Some(CommitmentConfig::confirmed()),
    };

    let mut last_error = None;

    for attempt in 0..retry_config.max_tries {
        if attempt > 0 {
            tokio::time::sleep(Duration::from_millis(retry_config.sleep_ms)).await;
        }

        match rpc.get_transaction_with_config(signature, config).await {
            Ok(tx_response) => {
                return process(tx_response);
            }
            Err(e) => {
                last_error = Some(e);
            }
        }
    }

    Err(anyhow::anyhow!(
        "Failed to fetch transaction from RPC after {} attempts: {:?}",
        retry_config.max_tries,
        last_error
    ))
}

/// Fetches transaction details from RPC and extracts cost information (fee and balance changes) for the tx fee payer.
/// If metadata is not available from RPC, falls back to computing gas spend from the transaction.
#[tracing::instrument(skip_all, fields(tx_hash = %signature))]
pub async fn fetch_transaction_cost_details(
    rpc: &RpcClient,
    signature: &Signature,
    gas_spent: u64,
    retry_config: RetryConfig,
) -> anyhow::Result<TransactionCostDetails> {
    fetch_transaction_with_retry(rpc, signature, &retry_config, |tx_response| {
        // balance_spend is positive if balance decreased
        let (fee, balance_spend) = tx_response
            .transaction
            .meta
            .map(|meta| {
                let balance_spend = meta
                    .pre_balances
                    .first()
                    .and_then(|&before| meta.post_balances.first().map(|&after| (before, after)))
                    .and_then(|(before, after)| {
                        i64::try_from(after)
                            .ok()
                            .zip(i64::try_from(before).ok())
                            .map(|(after_i64, before_i64)| before_i64.saturating_sub(after_i64))
                    });
                (meta.fee, balance_spend)
            })
            .unwrap_or_else(|| (gas_spent, None));

        Ok(TransactionCostDetails { fee, balance_spend })
    })
    .await
}

pub async fn get_spl_ata_balance(
    rpc: &RpcClient,
    owner: &Pubkey,
    mint: &Pubkey,
) -> anyhow::Result<u64> {
    let ata = spl_associated_token_account::get_associated_token_address(owner, mint);
    let account = rpc.get_account(&ata).await?;
    spl_token::state::Account::unpack(&account.data)
        .map(|token_account| token_account.amount)
        .map_err(|e| anyhow::anyhow!("Failed to unpack token account: {}", e))
}

pub struct SwapBalanceChange {
    pub mint: Pubkey,
    pub token_spent: f64,
    pub fogo_received: f64,
}

/// Fetches transaction details from RPC and extracts balance changes for the specified mint and WFOGO due to the swap.
#[tracing::instrument(skip_all, fields(mint = %mint_in, tx_hash = %signature))]
pub async fn fetch_swap_balance_changes(
    rpc: &RpcClient,
    signature: &Signature,
    owner: &Pubkey,
    mint_in: &Pubkey,
    retry_config: RetryConfig,
) -> anyhow::Result<SwapBalanceChange> {
    fetch_transaction_with_retry(rpc, signature, &retry_config, |tx_response| {
        let meta = tx_response
            .transaction
            .meta
            .as_ref()
            .ok_or_else(|| anyhow::anyhow!("Transaction metadata not available"))?;

        let pre_token_balances: Option<&Vec<_>> = meta.pre_token_balances.as_ref().into();
        let post_token_balances: Option<&Vec<_>> = meta.post_token_balances.as_ref().into();

        let (token_spent, fogo_received) = pre_token_balances
            .zip(post_token_balances)
            .and_then(|(pre_balances, post_balances)| {
                let token_spent =
                    compute_balance_change(pre_balances, post_balances, owner, mint_in, true)?;
                let fogo_received = compute_balance_change(
                    pre_balances,
                    post_balances,
                    owner,
                    &spl_token::native_mint::id(),
                    false,
                )?;
                Some((token_spent, fogo_received))
            })
            .ok_or_else(|| {
                anyhow::anyhow!("Failed to compute swap balance changes from transaction metadata")
            })?;

        Ok(SwapBalanceChange {
            mint: *mint_in,
            token_spent,
            fogo_received,
        })
    })
    .await
}

/// Computes the balance change for a particular owner and mint combination.
/// token_spent indicates whether to compute the amount spent (true) or received (false).
fn compute_balance_change(
    pre_balances: &[UiTransactionTokenBalance],
    post_balances: &[UiTransactionTokenBalance],
    owner: &Pubkey,
    mint: &Pubkey,
    token_spent: bool,
) -> Option<f64> {
    pre_balances.iter().find_map(|pre| {
        if pre.mint == mint.to_string()
            && pre
                .owner
                .as_ref()
                .map_or(false, |o| *o == owner.to_string())
        {
            let post = post_balances
                .iter()
                .find(|p| p.account_index == pre.account_index)?;
            let pre_amount = pre.ui_token_amount.amount.parse::<u64>().ok()?;
            let post_amount = post.ui_token_amount.amount.parse::<u64>().ok()?;
            Some(amount_to_ui_amount(
                if token_spent {
                    pre_amount.saturating_sub(post_amount)
                } else {
                    post_amount.saturating_sub(pre_amount)
                },
                post.ui_token_amount.decimals,
            ))
        } else {
            None
        }
    })
}