spark_rust/spark_test_utils/
polling.rs

1#![cfg(feature = "integration-tests")]
2
3use std::time::Duration;
4
5use crate::error::{SparkSdkError, ValidationError};
6use crate::SparkSdk;
7use tokio::time::sleep;
8
9use super::DEPOSIT_CONFIRMATION_WAIT;
10
11/// Helper function to poll for deposit claim
12pub async fn poll_for_claim_deposit(sdk: &SparkSdk, txid: String) -> Result<(), SparkSdkError> {
13    // Initial 30-second wait
14    sleep(Duration::from_secs(DEPOSIT_CONFIRMATION_WAIT)).await;
15
16    // Poll for deposit claim up to 3 times, waiting 5 seconds between attempts
17    for attempt in 1..=3 {
18        let tree_nodes = sdk.claim_deposit(txid.clone()).await?;
19        match tree_nodes.len() {
20            0 => {
21                if attempt == 3 {
22                    return Err(SparkSdkError::from(
23                        ValidationError::DepositTransactionNotFoundInNetwork { txid: txid.clone() },
24                    ));
25                }
26                sleep(Duration::from_secs(5)).await;
27            }
28            _ => {
29                return Ok(());
30            }
31        }
32    }
33
34    Ok(())
35}
36
37/// Helper function to poll for transfer claim
38pub async fn poll_for_claim_transfers(
39    sdk: &SparkSdk,
40    initial_wait_time: u64,
41) -> Result<(), SparkSdkError> {
42    let initial_balance = sdk.get_bitcoin_balance();
43
44    sleep(Duration::from_secs(initial_wait_time)).await;
45
46    // Poll for transfer claim up to 3 times, waiting 5 seconds between attempts
47    for attempt in 1..=3 {
48        sdk.claim_transfers().await?;
49        let new_balance = sdk.get_bitcoin_balance();
50        if new_balance == initial_balance {
51            if attempt == 3 {
52                return Err(SparkSdkError::from(
53                    ValidationError::TransferClaimDidNotUpdateBalance,
54                ));
55            }
56            sleep(Duration::from_secs(5)).await;
57        } else {
58            return Ok(());
59        }
60    }
61
62    Ok(())
63}