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
use crate::types::{
  CreateTransactionResponse, DestinationTransferPeerPath, EstimateFee, OneTimeAddress, PeerType, Transaction,
  TransactionArguments, TransactionOperation, TransactionStatus, TransferPeerPath,
};
use crate::Client;
use bigdecimal::BigDecimal;
use std::borrow::Borrow;
use std::fmt::{Debug, Display};
use std::ops::Add;
use tokio::time;
use tracing::debug;

impl Client {
  /// Query transactions
  ///
  /// See
  /// * [getTransactions](https://docs.fireblocks.com/api/swagger-ui/#/Transactions/getTransactions)
  /// * [`crate::types::transaction::TransactionListBuilder`]
  #[tracing::instrument(level = "debug", skip(self, options))]
  pub async fn transactions<I, K, V>(&self, options: I) -> crate::Result<Vec<Transaction>>
  where
    I: IntoIterator,
    I::Item: Borrow<(K, V)>,
    K: AsRef<str>,
    V: AsRef<str>,
  {
    let u = self.build_url_params("transactions", Some(options))?.0;
    self.get(u).await
  }

  /// Create a transaction
  ///
  /// [createTransaction](https://docs.fireblocks.com/api/swagger-ui/#/Transactions/createTransaction)
  #[tracing::instrument(level = "debug", skip(self))]
  pub async fn create_transaction(&self, args: &TransactionArguments) -> crate::Result<CreateTransactionResponse> {
    let u = self.build_url("transactions")?.0;
    self.post(u, Some(args)).await
  }

  /// Create a vault-to-vault transaction
  ///
  /// [createTransaction](https://docs.fireblocks.com/api/swagger-ui/#/Transactions/createTransaction)
  #[tracing::instrument(level = "debug", skip(self))]
  pub async fn create_transaction_vault<T>(
    &self,
    source_vault: i32,
    destination_vault: i32,
    asset_id: T,
    amount: BigDecimal,
    note: Option<&str>,
  ) -> crate::Result<CreateTransactionResponse>
  where
    T: AsRef<str> + Debug + Display,
  {
    let args = &TransactionArguments {
      asset_id: format!("{asset_id}"),
      operation: TransactionOperation::TRANSFER,
      source: TransferPeerPath { id: Some(source_vault.to_string()), ..Default::default() },
      destination: Some(DestinationTransferPeerPath { id: destination_vault.to_string(), ..Default::default() }),
      amount: amount.to_string(),
      gas_price: None,
      gas_limit: None,
      note: note.unwrap_or("created by fireblocks-sdk for rust").to_string(),
    };
    self.create_transaction(args).await
  }

  /// Create a transaction to external wallet
  ///
  /// [createTransaction](https://docs.fireblocks.com/api/swagger-ui/#/Transactions/createTransaction)
  #[tracing::instrument(level = "debug", skip(self))]
  pub async fn create_transaction_external<A, D>(
    &self,
    source_vault: i32,
    destination: D,
    asset_id: A,
    amount: BigDecimal,
    note: Option<&str>,
  ) -> crate::Result<CreateTransactionResponse>
  where
    A: AsRef<str> + Debug + Display,
    D: AsRef<str> + Debug + Display,
  {
    let args = &TransactionArguments {
      asset_id: format!("{asset_id}"),
      operation: TransactionOperation::TRANSFER,
      source: TransferPeerPath {
        id: Some(source_vault.to_string()),
        peer_type: PeerType::VAULT_ACCOUNT,
        ..Default::default()
      },
      destination: Some(DestinationTransferPeerPath {
        peer_type: PeerType::ONE_TIME_ADDRESS,
        one_time_address: Some(OneTimeAddress { address: destination.to_string(), tag: None }),
        ..Default::default()
      }),
      amount: amount.to_string(),
      gas_price: None,
      gas_limit: None,
      note: note.unwrap_or("created by fireblocks-sdk for rust").to_string(),
    };
    self.create_transaction(args).await
  }

  /// Get a transaction by id
  ///
  /// [getTransaction](https://docs.fireblocks.com/api/swagger-ui/#/Transactions/getTransaction)
  #[tracing::instrument(level = "debug", skip(self))]
  pub async fn get_transaction(&self, id: &str) -> crate::Result<Transaction> {
    let u = self.build_url(&format!("transactions/{id}"))?.0;
    self.get(u).await
  }

  /// Pool transaction until
  /// * [`TransactionStatus::FAILED`]
  /// * [`TransactionStatus::COMPLETED`]
  /// * [`TransactionStatus::BROADCASTING`]
  /// * [`TransactionStatus::BLOCKED`]
  /// * [`TransactionStatus::TIMEOUT`]
  /// * [`TransactionStatus::CANCELLED`]
  /// * [`TransactionStatus::CANCELLING`]
  /// * [`TransactionStatus::CONFIRMING`]
  ///
  /// [getTransaction](https://docs.fireblocks.com/api/swagger-ui/#/Transactions/getTransaction)
  #[tracing::instrument(level = "debug", skip(self))]
  pub async fn poll_transaction(
    &self,
    id: &str,
    timeout: time::Duration,
    interval: time::Duration,
  ) -> crate::Result<Transaction> {
    let u = self.build_url(&format!("transactions/{id}"))?.0;
    let mut total_time = time::Duration::from_millis(0);
    loop {
      if let Ok(result) = self.get::<Transaction>(u.clone()).await {
        let status = result.0.status;
        debug!("status {:#?}", status);
        #[allow(clippy::match_same_arms)]
        match status {
          TransactionStatus::BLOCKED => break,
          TransactionStatus::CANCELLING => break,
          TransactionStatus::CANCELLED => break,
          TransactionStatus::COMPLETED => break,
          TransactionStatus::CONFIRMING => break,
          TransactionStatus::FAILED => break,
          TransactionStatus::REJECTED => break,
          TransactionStatus::TIMEOUT => break,
          _ => {},
        }
      }
      time::sleep(interval).await;
      total_time = total_time.add(interval);
      if total_time > timeout {
        break;
      }
    }
    self.get(u.clone()).await
  }

  #[tracing::instrument(level = "debug", skip(self))]
  pub async fn estimate_fee(&self, asset: &str) -> crate::Result<EstimateFee> {
    let u = self.build_url(&format!("estimate_network_fee?assetId={asset}"))?.0;
    self.get(u).await
  }
}