1use axum::{http::StatusCode, response::ErrorResponse};
2use base64::prelude::*;
3use dashmap::DashMap;
4use futures::stream::StreamExt;
5use serde_json::json;
6use solana_address_lookup_table_interface::state::AddressLookupTable;
7use solana_client::{
8 nonblocking::rpc_client::RpcClient,
9 rpc_config::{RpcSendTransactionConfig, RpcSignatureSubscribeConfig, RpcTransactionConfig},
10};
11use solana_commitment_config::CommitmentConfig;
12use solana_message::VersionedMessage;
13use solana_program::program_pack::Pack;
14use solana_pubkey::Pubkey;
15use solana_rpc_client_api::client_error::{Error, ErrorKind};
16use solana_rpc_client_api::request::RpcRequest;
17use solana_signature::Signature;
18use solana_transaction::versioned::VersionedTransaction;
19use solana_transaction_error::TransactionError;
20use solana_transaction_status_client_types::{
21 EncodedConfirmedTransactionWithStatusMeta, UiTransactionEncoding, UiTransactionTokenBalance,
22};
23use spl_token::amount_to_ui_amount;
24use std::time::Duration;
25use tokio::time::timeout;
26
27use crate::{
28 api::{ConfirmationResult, PubsubClientWithReconnect},
29 constraint::transaction::InstructionWithIndex,
30};
31
32pub struct ChainIndex {
33 pub rpc: RpcClient,
34 pub lookup_table_cache: DashMap<Pubkey, Vec<Pubkey>>,
35}
36
37pub enum ConfirmationResultInternal {
38 Success { signature: Signature },
40
41 Failed {
43 signature: Signature,
44 error: TransactionError,
45 },
46
47 UnconfirmedPreflightFailure {
49 signature: Signature,
50 error: TransactionError,
51 },
52}
53
54impl ConfirmationResultInternal {
55 pub fn status_string(&self) -> String {
56 match self {
57 ConfirmationResultInternal::Success { .. } => "success".to_string(),
58 ConfirmationResultInternal::Failed { .. } => "failed".to_string(),
59 ConfirmationResultInternal::UnconfirmedPreflightFailure { .. } => {
60 "unconfirmed_preflight_failure".to_string()
61 }
62 }
63 }
64}
65
66impl From<ConfirmationResultInternal> for ConfirmationResult {
67 fn from(internal: ConfirmationResultInternal) -> Self {
68 match internal {
69 ConfirmationResultInternal::Success { signature } => {
70 ConfirmationResult::Success { signature }
71 }
72 ConfirmationResultInternal::Failed { signature, error } => {
73 ConfirmationResult::Failed { signature, error }
74 }
75 ConfirmationResultInternal::UnconfirmedPreflightFailure { signature, error } => {
76 ConfirmationResult::Failed { signature, error }
77 }
78 }
79 }
80}
81
82pub struct SignedVersionedTransaction(VersionedTransaction);
84
85impl SignedVersionedTransaction {
86 pub fn new(
89 mut transaction: VersionedTransaction,
90 signature: Signature,
91 ) -> anyhow::Result<Self> {
92 *transaction.signatures.get_mut(0).ok_or_else(|| {
93 anyhow::anyhow!("Transaction must have at least one signature slot")
94 })? = signature;
95 Ok(Self(transaction))
96 }
97
98 pub fn signature(&self) -> &Signature {
100 self.0
101 .signatures
102 .first()
103 .expect("SignedVersionedTransaction is guaranteed to have at least one signature slot")
104 }
105}
106
107impl AsRef<VersionedTransaction> for SignedVersionedTransaction {
108 fn as_ref(&self) -> &VersionedTransaction {
109 &self.0
110 }
111}
112
113fn to_error_response(err: Error) -> ErrorResponse {
114 (
115 StatusCode::BAD_GATEWAY,
116 format!("Failed SVM RPC call: {err}"),
117 )
118 .into()
119}
120
121impl ChainIndex {
122 pub async fn resolve_instruction_account_pubkey(
124 &self,
125 message: &VersionedMessage,
126 InstructionWithIndex {
127 index: instruction_index,
128 instruction,
129 }: &InstructionWithIndex<'_>,
130 account_index_within_instruction: usize,
131 ) -> Result<Pubkey, (StatusCode, String)> {
132 let account_index_within_transaction = usize::from(*instruction
133 .accounts
134 .get(account_index_within_instruction)
135 .ok_or_else(|| {
136 (
137 StatusCode::BAD_REQUEST,
138 format!(
139 "Account index {account_index_within_instruction} out of bounds for instruction {instruction_index}",
140 ),
141 )
142 })?);
143 if let Some(pubkey) = message
144 .static_account_keys()
145 .get(account_index_within_transaction)
146 {
147 Ok(*pubkey)
148 } else if let Some(lookup_tables) = message.address_table_lookups() {
149 let lookup_accounts: Vec<(Pubkey, u8)> = lookup_tables
150 .iter()
151 .flat_map(|x| {
152 x.writable_indexes
153 .clone()
154 .into_iter()
155 .map(|y| (x.account_key, y))
156 })
157 .chain(lookup_tables.iter().flat_map(|x| {
158 x.readonly_indexes
159 .clone()
160 .into_iter()
161 .map(|y| (x.account_key, y))
162 }))
163 .collect();
164 let account_index_within_lookup_tables =
165 account_index_within_transaction - message.static_account_keys().len();
166 return self
167 .find_and_query_lookup_table(lookup_accounts, account_index_within_lookup_tables)
168 .await;
169 } else {
170 Err((
171 StatusCode::BAD_REQUEST,
172 format!(
173 "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",
174 ),
175 ))
176 }
177 }
178
179 async fn find_and_query_lookup_table(
181 &self,
182 lookup_accounts: Vec<(Pubkey, u8)>,
183 account_position_lookups: usize,
184 ) -> Result<Pubkey, (StatusCode, String)> {
185 let (table_to_query, index_to_query) =
186 lookup_accounts.get(account_position_lookups).ok_or_else(|| {
187 (
188 StatusCode::BAD_REQUEST,
189 format!("Account position {account_position_lookups} out of bounds for lookup table invoked accounts"),
190 )
191 })?;
192 self.query_lookup_table_with_retry(table_to_query, usize::from(*index_to_query))
193 .await
194 }
195
196 async fn query_lookup_table_with_retry(
199 &self,
200 table: &Pubkey,
201 index: usize,
202 ) -> Result<Pubkey, (StatusCode, String)> {
203 if let Some(pubkey) = self.query_lookup_table(table, index) {
204 return Ok(pubkey);
205 }
206
207 let addresses = self.update_lookup_table(table).await?;
208 addresses.get(index).copied().ok_or_else(|| {
210 (
211 StatusCode::BAD_REQUEST,
212 format!("Lookup table {table} does not contain index {index}"),
213 )
214 })
215 }
216
217 fn query_lookup_table(&self, table: &Pubkey, index: usize) -> Option<Pubkey> {
220 self.lookup_table_cache
221 .get(table)
222 .and_then(|entry| entry.get(index).copied())
223 }
224
225 async fn update_lookup_table(
227 &self,
228 table: &Pubkey,
229 ) -> Result<Vec<Pubkey>, (StatusCode, String)> {
230 let table_data = self.rpc.get_account(table).await.map_err(|err| {
231 (
232 StatusCode::INTERNAL_SERVER_ERROR,
233 format!("Failed to fetch lookup table account {table} from RPC: {err}"),
234 )
235 })?;
236 let table_data_deserialized =
237 AddressLookupTable::deserialize(&table_data.data).map_err(|e| {
238 (
239 StatusCode::INTERNAL_SERVER_ERROR,
240 format!("Failed to deserialize lookup table account {table}: {e}"),
241 )
242 })?;
243
244 self.lookup_table_cache
245 .insert(*table, table_data_deserialized.addresses.to_vec());
246
247 Ok(table_data_deserialized.addresses.to_vec())
248 }
249}
250
251#[tracing::instrument(
253 skip_all,
254 fields(
255 tx_hash = %transaction.signature(),
256 result
257 )
258)]
259pub async fn send_and_confirm_transaction(
260 rpc: &RpcClient,
261 pubsub: &PubsubClientWithReconnect,
262 transaction: &SignedVersionedTransaction,
263 config: RpcSendTransactionConfig,
264) -> Result<ConfirmationResultInternal, ErrorResponse> {
265 let signature = match rpc
266 .send_transaction_with_config(transaction.as_ref(), config)
267 .await
268 {
269 Ok(sig) => {
270 tracing::Span::current().record("result", "sent");
271 sig
272 }
273 Err(err) => {
274 if let Some(error) = err.get_transaction_error() {
275 tracing::Span::current().record("result", "preflight_failure");
276 tracing::warn!(
277 "Transaction {} failed preflight: {error}",
278 transaction.signature()
279 );
280 return Ok(ConfirmationResultInternal::UnconfirmedPreflightFailure {
281 signature: *transaction.signature(),
282 error,
283 });
284 }
285 tracing::Span::current().record("result", "send_failed");
286 tracing::error!(
287 "Failed to send transaction {}: {err}",
288 transaction.signature()
289 );
290 return Err(to_error_response(err));
291 }
292 };
293
294 confirm_transaction(pubsub, signature, Some(rpc.commitment())).await
295}
296
297#[tracing::instrument(
300 skip_all,
301 fields(
302 tx_hash = %transaction.signature(),
303 result
304 )
305)]
306pub async fn send_and_confirm_transaction_ftl(
307 ftl_rpc: &RpcClient,
308 transaction: &SignedVersionedTransaction,
309 config: RpcSendTransactionConfig,
310) -> Result<ConfirmationResultInternal, ErrorResponse> {
311 let tx_bytes = bincode::serde::encode_to_vec(transaction.as_ref(), bincode::config::standard())
312 .map_err(|e| {
313 tracing::error!("Failed to serialize transaction: {e}");
314 ErrorResponse::from((
315 StatusCode::INTERNAL_SERVER_ERROR,
316 "Failed to serialize transaction",
317 ))
318 })?;
319 let tx_base64 = BASE64_STANDARD.encode(&tx_bytes);
320
321 let mut config_value = serde_json::to_value(RpcSendTransactionConfig {
322 encoding: Some(config.encoding.unwrap_or(UiTransactionEncoding::Base64)),
323 preflight_commitment: Some(config.preflight_commitment.unwrap_or_default()),
324 ..config
325 })
326 .map_err(|e| {
327 tracing::error!("Failed to serialize config: {e}");
328 ErrorResponse::from((
329 StatusCode::INTERNAL_SERVER_ERROR,
330 "Failed to serialize config",
331 ))
332 })?;
333
334 if let Some(obj) = config_value.as_object_mut() {
336 obj.insert("confirm".to_string(), json!(true));
337 }
338
339 let signature: String = match ftl_rpc
341 .send(
342 RpcRequest::SendTransaction,
343 json!([tx_base64, config_value]),
344 )
345 .await
346 {
347 Ok(sig) => {
348 tracing::Span::current().record("result", "sent");
349 sig
350 }
351 Err(err) => {
352 let preflight = matches!(&err.kind, &ErrorKind::RpcError(_));
353 if let Some(error) = err.get_transaction_error() {
354 if preflight {
355 tracing::Span::current().record("result", "preflight_failure");
356 tracing::warn!(
357 "Transaction {} failed preflight: {error}",
358 transaction.signature()
359 );
360 return Ok(ConfirmationResultInternal::UnconfirmedPreflightFailure {
361 signature: *transaction.signature(),
362 error,
363 });
364 } else {
365 tracing::Span::current().record("result", "failed");
367 return Ok(ConfirmationResultInternal::Failed {
368 signature: *transaction.signature(),
369 error,
370 });
371 }
372 }
373
374 tracing::Span::current().record("result", "send_failed");
375 tracing::error!(
376 "Failed to send transaction {}: {err}",
377 transaction.signature()
378 );
379 return Err(to_error_response(err));
380 }
381 };
382
383 let signature = signature.parse::<Signature>().map_err(|e| {
384 tracing::Span::current().record("result", "send_failed");
385 tracing::error!("Failed to parse signature from FTL response: {e}");
386 ErrorResponse::from((
387 StatusCode::BAD_GATEWAY,
388 format!("Failed to parse signature: {e}"),
389 ))
390 })?;
391
392 tracing::Span::current().record("result", "success");
393 Ok(ConfirmationResultInternal::Success { signature })
395}
396
397const CONFIRMATION_TIMEOUT: Duration = Duration::from_secs(60);
398
399#[tracing::instrument(
400 skip_all,
401 fields(
402 tx_hash = %signature,
403 result
404 )
405)]
406async fn confirm_transaction(
407 pubsub: &PubsubClientWithReconnect,
408 signature: Signature,
409 commitment: Option<CommitmentConfig>,
410) -> Result<ConfirmationResultInternal, ErrorResponse> {
411 let signature_result = subscribe_and_wait_for_signature(pubsub, signature, commitment, true)
412 .await
413 .map_err(|(status, err_string)| {
414 tracing::Span::current().record("result", "unconfirmed");
415 (
416 status,
417 format!("Failed to confirm transaction {signature}: {err_string}"),
418 )
419 })?;
420
421 if let Some(err) = signature_result.err {
422 tracing::Span::current().record("result", "failed");
423 return Ok(ConfirmationResultInternal::Failed {
424 signature,
425 error: err,
426 });
427 } else {
428 tracing::Span::current().record("result", "success");
429 return Ok(ConfirmationResultInternal::Success { signature });
430 }
431}
432
433#[async_recursion::async_recursion]
434async fn subscribe_and_wait_for_signature(
435 pubsub: &PubsubClientWithReconnect,
436 signature: Signature,
437 commitment: Option<CommitmentConfig>,
438 reconnect: bool,
439) -> Result<solana_client::rpc_response::ProcessedSignatureResult, (StatusCode, String)> {
440 let pubsub_client = pubsub.client.load();
441 let subscribe_result = pubsub_client
442 .signature_subscribe(
443 &signature,
444 Some(RpcSignatureSubscribeConfig {
445 commitment,
446 ..RpcSignatureSubscribeConfig::default()
447 }),
448 )
449 .await;
450
451 let (mut stream, unsubscribe) = match subscribe_result {
452 Ok(sub) => sub,
453 Err(_) => {
454 if reconnect {
455 tracing::warn!("WebSocket subscription failed, attempting reconnection and retry");
456 pubsub.reconnect_pubsub().await?;
457 return subscribe_and_wait_for_signature(pubsub, signature, commitment, false)
458 .await;
459 }
460
461 tracing::error!("WebSocket subscription failed");
462
463 return Err((
464 StatusCode::BAD_GATEWAY,
465 "Failed to subscribe to signature".to_string(),
466 ));
467 }
468 };
469
470 let result = timeout(CONFIRMATION_TIMEOUT, async {
475 while let Some(response) = stream.next().await {
476 if let solana_client::rpc_response::RpcSignatureResult::ProcessedSignature(
477 processed_signature_result,
478 ) = response.value
479 {
480 return Ok(processed_signature_result);
481 }
482 }
483
484 tracing::error!("Signature subscription stream ended unexpectedly for {signature}");
485 Err((
486 StatusCode::BAD_GATEWAY,
487 "Signature subscription stream ended unexpectedly".to_string(),
488 ))
489 })
490 .await;
491
492 unsubscribe().await;
493
494 result
495 .map_err(|_| {
496 tracing::error!("Timeout while waiting for transaction confirmation for {signature}");
497 (
498 StatusCode::GATEWAY_TIMEOUT,
499 "Unable to confirm transaction".to_string(),
500 )
501 })
502 .and_then(|r| r)
503}
504
505#[derive(Debug, Clone)]
506pub struct TransactionCostDetails {
507 pub fee: u64,
508 pub balance_spend: Option<i64>,
509}
510
511#[derive(Debug, Clone)]
512pub struct RetryConfig {
513 pub max_tries: u32,
514 pub sleep_ms: u64,
515}
516
517async fn fetch_transaction_with_retry<T, F>(
521 rpc: &RpcClient,
522 signature: &Signature,
523 retry_config: &RetryConfig,
524 process: F,
525) -> anyhow::Result<T>
526where
527 F: Fn(EncodedConfirmedTransactionWithStatusMeta) -> anyhow::Result<T>,
528{
529 let config = RpcTransactionConfig {
530 encoding: Some(UiTransactionEncoding::Base64),
531 max_supported_transaction_version: Some(0),
532 commitment: Some(CommitmentConfig::confirmed()),
534 };
535
536 let mut last_error = None;
537
538 for attempt in 0..retry_config.max_tries {
539 if attempt > 0 {
540 tokio::time::sleep(Duration::from_millis(retry_config.sleep_ms)).await;
541 }
542
543 match rpc.get_transaction_with_config(signature, config).await {
544 Ok(tx_response) => {
545 return process(tx_response);
546 }
547 Err(e) => {
548 last_error = Some(e);
549 }
550 }
551 }
552
553 Err(anyhow::anyhow!(
554 "Failed to fetch transaction from RPC after {} attempts: {:?}",
555 retry_config.max_tries,
556 last_error
557 ))
558}
559
560#[tracing::instrument(skip_all, fields(tx_hash = %signature))]
563pub async fn fetch_transaction_cost_details(
564 rpc: &RpcClient,
565 signature: &Signature,
566 gas_spent: u64,
567 retry_config: RetryConfig,
568) -> anyhow::Result<TransactionCostDetails> {
569 fetch_transaction_with_retry(rpc, signature, &retry_config, |tx_response| {
570 let (fee, balance_spend) = tx_response
572 .transaction
573 .meta
574 .map(|meta| {
575 let balance_spend = meta
576 .pre_balances
577 .first()
578 .and_then(|&before| meta.post_balances.first().map(|&after| (before, after)))
579 .and_then(|(before, after)| {
580 i64::try_from(after)
581 .ok()
582 .zip(i64::try_from(before).ok())
583 .map(|(after_i64, before_i64)| before_i64.saturating_sub(after_i64))
584 });
585 (meta.fee, balance_spend)
586 })
587 .unwrap_or_else(|| (gas_spent, None));
588
589 Ok(TransactionCostDetails { fee, balance_spend })
590 })
591 .await
592}
593
594pub async fn get_spl_ata_balance(
595 rpc: &RpcClient,
596 owner: &Pubkey,
597 mint: &Pubkey,
598) -> anyhow::Result<u64> {
599 let ata = spl_associated_token_account::get_associated_token_address(owner, mint);
600 let account = rpc.get_account(&ata).await?;
601 spl_token::state::Account::unpack(&account.data)
602 .map(|token_account| token_account.amount)
603 .map_err(|e| anyhow::anyhow!("Failed to unpack token account: {}", e))
604}
605
606pub struct SwapBalanceChange {
607 pub mint: Pubkey,
608 pub token_spent: f64,
609 pub fogo_received: f64,
610}
611
612#[tracing::instrument(skip_all, fields(mint = %mint_in, tx_hash = %signature))]
614pub async fn fetch_swap_balance_changes(
615 rpc: &RpcClient,
616 signature: &Signature,
617 owner: &Pubkey,
618 mint_in: &Pubkey,
619 retry_config: RetryConfig,
620) -> anyhow::Result<SwapBalanceChange> {
621 fetch_transaction_with_retry(rpc, signature, &retry_config, |tx_response| {
622 let meta = tx_response
623 .transaction
624 .meta
625 .as_ref()
626 .ok_or_else(|| anyhow::anyhow!("Transaction metadata not available"))?;
627
628 let pre_token_balances: Option<&Vec<_>> = meta.pre_token_balances.as_ref().into();
629 let post_token_balances: Option<&Vec<_>> = meta.post_token_balances.as_ref().into();
630
631 let (token_spent, fogo_received) = pre_token_balances
632 .zip(post_token_balances)
633 .and_then(|(pre_balances, post_balances)| {
634 let token_spent =
635 compute_balance_change(pre_balances, post_balances, owner, mint_in, true)?;
636 let fogo_received = compute_balance_change(
637 pre_balances,
638 post_balances,
639 owner,
640 &spl_token::native_mint::id(),
641 false,
642 )?;
643 Some((token_spent, fogo_received))
644 })
645 .ok_or_else(|| {
646 anyhow::anyhow!("Failed to compute swap balance changes from transaction metadata")
647 })?;
648
649 Ok(SwapBalanceChange {
650 mint: *mint_in,
651 token_spent,
652 fogo_received,
653 })
654 })
655 .await
656}
657
658fn compute_balance_change(
661 pre_balances: &[UiTransactionTokenBalance],
662 post_balances: &[UiTransactionTokenBalance],
663 owner: &Pubkey,
664 mint: &Pubkey,
665 token_spent: bool,
666) -> Option<f64> {
667 pre_balances.iter().find_map(|pre| {
668 if pre.mint == mint.to_string()
669 && pre
670 .owner
671 .as_ref()
672 .map_or(false, |o| *o == owner.to_string())
673 {
674 let post = post_balances
675 .iter()
676 .find(|p| p.account_index == pre.account_index)?;
677 let pre_amount = pre.ui_token_amount.amount.parse::<u64>().ok()?;
678 let post_amount = post.ui_token_amount.amount.parse::<u64>().ok()?;
679 Some(amount_to_ui_amount(
680 if token_spent {
681 pre_amount.saturating_sub(post_amount)
682 } else {
683 post_amount.saturating_sub(pre_amount)
684 },
685 post.ui_token_amount.decimals,
686 ))
687 } else {
688 None
689 }
690 })
691}