Skip to main content

fogo_paymaster/
api.rs

1use crate::cli::NetworkEnvironment;
2use crate::config_manager::config::Domain;
3use crate::constraint::transaction::TransactionToValidate;
4use crate::constraint::{ContextualDomainKeys, ParsedTransactionVariation};
5use crate::metrics::{obs_actual_transaction_costs, obs_send, obs_swap, obs_validation};
6use crate::pooled_http_sender::PooledHttpSender;
7use crate::rpc::{
8    fetch_swap_balance_changes, fetch_transaction_cost_details, send_and_confirm_transaction,
9    send_and_confirm_transaction_ftl, ChainIndex, ConfirmationResultInternal, RetryConfig,
10    SignedVersionedTransaction,
11};
12use crate::swap::SwapConfirmationResult;
13use arc_swap::ArcSwap;
14use axum::extract::{Query, State};
15use axum::http::StatusCode;
16use axum::response::ErrorResponse;
17use axum::Json;
18use axum::{
19    http::{HeaderName, Method},
20    Router,
21};
22use axum_extra::headers::Origin;
23use axum_extra::TypedHeader;
24use axum_prometheus::metrics_exporter_prometheus::{Matcher, PrometheusBuilder};
25use axum_prometheus::PrometheusMetricLayer;
26use base64::Engine;
27use dashmap::DashMap;
28use fogo_sessions_sdk::domain_registry::get_domain_record_address;
29use futures::future::join_all;
30use nonempty::NonEmpty;
31use reqwest::Client;
32use serde_with::{serde_as, DisplayFromStr};
33use solana_client::nonblocking::rpc_client::RpcClient;
34use solana_client::rpc_config::RpcSendTransactionConfig;
35use solana_commitment_config::{CommitmentConfig, CommitmentLevel};
36use solana_derivation_path::DerivationPath;
37use solana_keypair::Keypair;
38use solana_packet::PACKET_DATA_SIZE;
39use solana_pubkey::Pubkey;
40use solana_pubsub_client::nonblocking::pubsub_client::PubsubClient;
41use solana_rpc_client::rpc_client::RpcClientConfig;
42use solana_seed_derivable::SeedDerivable;
43use solana_signature::Signature;
44use solana_signer::Signer;
45use solana_transaction::versioned::VersionedTransaction;
46use solana_transaction_error::TransactionError;
47use std::collections::HashMap;
48use std::sync::atomic::{AtomicUsize, Ordering};
49use std::sync::Arc;
50use tokio::sync::Mutex;
51use tower_http::cors::{AllowHeaders, AllowMethods, AllowOrigin, CorsLayer};
52use tracing::Instrument;
53use url::Url;
54use utoipa_axum::{router::OpenApiRouter, routes};
55
56pub struct DomainState {
57    pub domain_registry_key: Pubkey,
58    pub sponsors: NonEmpty<Arc<Keypair>>,
59    pub next_autoassigned_sponsor_index: Arc<AtomicUsize>,
60    pub enable_preflight_simulation: bool,
61    pub tx_variations: HashMap<String, ParsedTransactionVariation>,
62}
63
64pub struct PubsubClientWithReconnect {
65    pub client: ArcSwap<PubsubClient>,
66    pub rpc_url_ws: String,
67    /// Mutex to prevent redundant concurrent reconnections
68    pub reconnect_lock: Mutex<()>,
69}
70
71impl PubsubClientWithReconnect {
72    pub fn new(rpc_url_ws: String, client: PubsubClient) -> Self {
73        Self {
74            client: ArcSwap::from_pointee(client),
75            rpc_url_ws,
76            reconnect_lock: Mutex::new(()),
77        }
78    }
79
80    /// Reconnects the PubsubClient after grabbing a lock which prevents concurrent reconnections.
81    pub async fn reconnect_pubsub(&self) -> Result<(), (StatusCode, String)> {
82        let old_client = self.client.load_full();
83
84        let _lock = self.reconnect_lock.lock().await;
85
86        let current_client = self.client.load_full();
87
88        // checks if the client was changed while waiting for the lock
89        // if so, then no need to reconnect
90        if Arc::ptr_eq(&old_client, &current_client) {
91            match PubsubClient::new(&self.rpc_url_ws).await {
92                Ok(new_client) => {
93                    let new_arc = Arc::new(new_client);
94                    self.client.store(new_arc);
95                    tracing::debug!("Reconnected to WebSocket RPC at {}", self.rpc_url_ws);
96                    Ok(())
97                }
98                Err(e) => Err((
99                    StatusCode::SERVICE_UNAVAILABLE,
100                    format!("WebSocket unavailable: {e}"),
101                )),
102            }
103        } else {
104            Ok(())
105        }
106    }
107}
108
109pub struct ValiantClient {
110    pub client: Client,
111    pub base_url: Url,
112}
113
114pub struct ServerState {
115    pub domains: Arc<ArcSwap<HashMap<String, DomainState>>>,
116    pub chain_index: ChainIndex,
117    pub rpc_sub: PubsubClientWithReconnect,
118    pub ftl_rpc: Option<RpcClient>,
119    pub fee_coefficients: HashMap<Pubkey, u64>,
120    pub valiant_client: Option<ValiantClient>,
121}
122
123#[derive(utoipa::ToSchema, serde::Deserialize)]
124pub struct SponsorAndSendPayload {
125    pub transaction: String,
126}
127
128impl DomainState {
129    /// Checks that the transaction meets at least one of the specified variations for this domain.
130    /// If so, returns the variation this transaction matched against.
131    /// Otherwise, returns an error with a message indicating why the transaction is invalid.
132    #[tracing::instrument(skip_all, fields(specified_variation = variation_name.as_deref(), matched_variation))]
133    pub async fn validate_transaction(
134        &self,
135        transaction: &TransactionToValidate<'_>,
136        chain_index: &ChainIndex,
137        sponsor: &Pubkey,
138        variation_name: Option<String>,
139    ) -> Result<&ParsedTransactionVariation, (StatusCode, String)> {
140        let message_bytes = transaction.message.serialize();
141        transaction
142            .signatures
143            .iter()
144            .zip(transaction.message.static_account_keys())
145            .skip(1)
146            .try_for_each(|(signature, pubkey)| {
147                signature
148                    .verify(pubkey.as_ref(), &message_bytes)
149                    .then_some(())
150                    .ok_or_else(|| {
151                        (
152                            StatusCode::BAD_REQUEST,
153                            format!("Missing or invalid signature for account {pubkey}")
154                                .to_string(),
155                        )
156                    })
157            })?;
158
159        let validation_futures: Vec<_> = self
160            .tx_variations
161            .iter()
162            .filter_map(|(name, variation)| {
163                if let Some(ref expected_name) = variation_name {
164                    if name != expected_name {
165                        return None;
166                    }
167                }
168
169                Some(Box::pin(async move {
170                    self.validate_transaction_against_variation(
171                        transaction,
172                        variation,
173                        chain_index,
174                        sponsor,
175                    )
176                    .await
177                    .map(|_| variation)
178                }))
179            })
180            .collect();
181
182        // If no variations were validated and the variation_name was specified, return an error indicating no such variation.
183        // If no variation_name was specified, return an error indicating no variations are configured for this domain.
184        if validation_futures.is_empty() {
185            return Err((
186                StatusCode::BAD_REQUEST,
187                if let Some(name) = variation_name {
188                    format!("No transaction variation named '{name}' for domain")
189                } else {
190                    "No transaction variations configured for domain".to_string()
191                },
192            ));
193        } else if variation_name.is_some() {
194            // If variation_name was specified, only one future will be present, and we can propagate its specific error.
195            let future = validation_futures
196                .into_iter()
197                .next()
198                .expect("validation_futures is not empty, so this must exist");
199            let variation = future.await?;
200            tracing::Span::current().record("matched_variation", variation.name().to_string());
201            Ok(variation)
202        } else {
203            match futures::future::select_ok(validation_futures).await {
204                Ok((variation, _remaining)) => {
205                    tracing::Span::current()
206                        .record("matched_variation", variation.name().to_string());
207                    Ok(variation)
208                }
209                Err(_) => Err((
210                    StatusCode::BAD_REQUEST,
211                    "Transaction does not match any allowed variations".to_string(),
212                )),
213            }
214        }
215    }
216
217    pub async fn validate_transaction_against_variation(
218        &self,
219        transaction: &TransactionToValidate<'_>,
220        tx_variation: &ParsedTransactionVariation,
221        chain_index: &ChainIndex,
222        sponsor: &Pubkey,
223    ) -> Result<(), (StatusCode, String)> {
224        match tx_variation {
225            ParsedTransactionVariation::V0(variation) => {
226                variation.validate_transaction(transaction)
227            }
228            ParsedTransactionVariation::V1(variation) => {
229                variation
230                    .validate_transaction(
231                        transaction,
232                        &ContextualDomainKeys {
233                            domain_registry: self.domain_registry_key,
234                            sponsor: *sponsor,
235                        },
236                        chain_index,
237                    )
238                    .await
239            }
240        }
241    }
242}
243
244#[derive(serde::Deserialize, utoipa::IntoParams)]
245#[serde(deny_unknown_fields)]
246#[into_params(parameter_in = Query)]
247struct SponsorAndSendQuery {
248    #[serde(default, rename = "confirm")]
249    #[deprecated]
250    /// Whether to confirm the transaction
251    _confirm: bool,
252
253    #[serde(default)]
254    /// Domain to request the sponsor pubkey for
255    domain: Option<String>,
256
257    #[serde(default)]
258    /// Variation name to validate against. If not provided, all variations for the domain will be tried.
259    variation: Option<String>,
260}
261
262fn get_domain_name(
263    domain_explicit: Option<String>,
264    origin: Option<TypedHeader<Origin>>,
265) -> Result<String, (StatusCode, String)> {
266    let domain = domain_explicit
267        .or_else(|| origin.map(|origin| origin.to_string()))
268        .ok_or_else(|| {
269            (
270                StatusCode::BAD_REQUEST,
271                "The http origin header or query parameter domain is required".to_string(),
272            )
273        })?;
274
275    Ok(domain)
276}
277
278fn get_domain_state<'a>(
279    domains: &'a HashMap<String, DomainState>,
280    domain_query_parameter: &str,
281) -> Result<&'a DomainState, (StatusCode, String)> {
282    let domain_state = domains
283        .get(domain_query_parameter)
284        .ok_or_else(|| {
285            (
286                StatusCode::BAD_REQUEST,
287                format!(
288                    "The domain {domain_query_parameter} is not registered with the paymaster, please either set the domain property in FogoSessionProvider to match your production domain or reach out to the Fogo team to get a paymaster configuration for your app"
289                ),
290            )
291        })?;
292
293    Ok(domain_state)
294}
295
296async fn readiness_handler() -> StatusCode {
297    StatusCode::OK
298}
299
300#[serde_as]
301#[derive(serde::Serialize)]
302#[serde(tag = "type")]
303pub enum ConfirmationResult {
304    /// Transaction was confirmed and succeeded on chain
305    #[serde(rename = "success")]
306    Success {
307        #[serde_as(as = "DisplayFromStr")]
308        signature: Signature,
309    },
310
311    /// TODO: Disambiguate between confirmed and failed on chain vs failed preflight
312    #[serde(rename = "failed")]
313    Failed {
314        #[serde_as(as = "DisplayFromStr")]
315        signature: Signature,
316        error: TransactionError,
317    },
318}
319
320#[utoipa::path(
321    post,
322    path = "/sponsor_and_send",
323    request_body = SponsorAndSendPayload,
324    params(SponsorAndSendQuery)
325)]
326#[tracing::instrument(
327    skip_all,
328    name = "sponsor_and_send",
329    fields(domain, specified_variation = variation.as_deref(), matched_variation, tx_hash)
330)]
331async fn sponsor_and_send_handler(
332    State(state): State<Arc<ServerState>>,
333    origin: Option<TypedHeader<Origin>>,
334    Query(SponsorAndSendQuery {
335        domain, variation, ..
336    }): Query<SponsorAndSendQuery>,
337    Json(payload): Json<SponsorAndSendPayload>,
338) -> Result<Json<ConfirmationResult>, ErrorResponse> {
339    let domain = get_domain_name(domain, origin)?;
340    tracing::Span::current().record("domain", domain.as_str());
341    let domains_guard = state.domains.load();
342    let domain_state = get_domain_state(&domains_guard, &domain)?;
343
344    let transaction_bytes = base64::engine::general_purpose::STANDARD
345        .decode(&payload.transaction)
346        .map_err(|_| (StatusCode::BAD_REQUEST, "Failed to deserialize transaction"))?;
347
348    if transaction_bytes.len() > PACKET_DATA_SIZE {
349        return Err((
350            StatusCode::BAD_REQUEST,
351            format!(
352                "Transaction is too large: {} > {PACKET_DATA_SIZE}",
353                transaction_bytes.len()
354            ),
355        ))?;
356    }
357
358    let (transaction, _): (VersionedTransaction, _) =
359        bincode::serde::decode_from_slice(&transaction_bytes, bincode::config::standard())
360            .map_err(|_| (StatusCode::BAD_REQUEST, "Failed to deserialize transaction"))?;
361
362    let fee_payer = transaction.message.static_account_keys().first().ok_or({
363        (
364            StatusCode::BAD_REQUEST,
365            "The transaction must have a fee payer",
366        )
367    })?;
368    let transaction_sponsor = domain_state
369        .sponsors
370        .iter()
371        .find(|sponsor| sponsor.pubkey() == *fee_payer)
372        .ok_or_else(|| -> (StatusCode, String) {
373            let status_code = StatusCode::BAD_REQUEST;
374            obs_validation(domain.clone(), None, status_code.to_string());
375            (
376                status_code,
377                format!(
378                    "Transaction fee payer must be one of the sponsors: expected one of {}, got {}",
379                    domain_state
380                        .sponsors
381                        .iter()
382                        .map(|sponsor| sponsor.pubkey().to_string())
383                        .collect::<Vec<_>>()
384                        .join(","),
385                    fee_payer,
386                ),
387            )
388        })?;
389
390    let transaction_to_validate =
391        TransactionToValidate::parse(&transaction, &state.chain_index, &state.fee_coefficients)
392            .await?;
393    let (matched_variation_name, swap_into_fogo) = match domain_state
394        .validate_transaction(
395            &transaction_to_validate,
396            &state.chain_index,
397            &transaction_sponsor.pubkey(),
398            variation,
399        )
400        .await
401    {
402        Ok(variation) => {
403            tracing::Span::current().record("matched_variation", variation.name());
404            obs_validation(
405                domain.clone(),
406                Some(variation.name().to_owned()),
407                "success".to_string(),
408            );
409            (
410                variation.name().to_owned(),
411                variation.swap_into_fogo().to_owned(),
412            )
413        }
414        Err(e) => {
415            obs_validation(domain.clone(), None, "invalid".to_string());
416            return Err(e.into());
417        }
418    };
419    let gas_spend = transaction_to_validate.gas_spend;
420
421    let signature = transaction_sponsor.sign_message(&transaction.message.serialize());
422    let signed_transaction = SignedVersionedTransaction::new(transaction, signature)
423        .map_err(|e| (StatusCode::BAD_REQUEST, e.to_string()))?;
424    tracing::Span::current().record("tx_hash", signed_transaction.signature().to_string());
425
426    let rpc_config = RpcSendTransactionConfig {
427        skip_preflight: !domain_state.enable_preflight_simulation,
428        preflight_commitment: Some(CommitmentLevel::Processed),
429        ..RpcSendTransactionConfig::default()
430    };
431
432    let confirmation_result = if let Some(ref ftl_rpc) = state.ftl_rpc {
433        // Use FTL service for sending and confirmation
434        send_and_confirm_transaction_ftl(ftl_rpc, &signed_transaction, rpc_config).await?
435    } else {
436        // Use standard RPC method
437        send_and_confirm_transaction(
438            &state.chain_index.rpc,
439            &state.rpc_sub,
440            &signed_transaction,
441            rpc_config,
442        )
443        .await?
444    };
445
446    let confirmation_status = confirmation_result.status_string();
447
448    obs_send(
449        domain.clone(),
450        matched_variation_name.clone(),
451        confirmation_status.clone(),
452    );
453
454    // Spawn async task to fetch actual transaction costs from RPC
455    // This happens in the background to avoid blocking the response to the client
456    // Only fetch if the transaction actually succeeded on chain
457    let signature = match &confirmation_result {
458        ConfirmationResultInternal::Success { signature } => Some(*signature),
459        ConfirmationResultInternal::Failed { signature, .. } => Some(*signature),
460        _ => None,
461    };
462
463    if let Some(signature_to_fetch) = signature {
464        // We capture the current span to propagate to the spawned task.
465        // This ensures that any logs/traces from the spawned task are associated with the original request.
466        let span = tracing::Span::current();
467
468        tokio::spawn({
469            let state = Arc::clone(&state);
470            let domain = domain.clone();
471            let matched_variation_name = matched_variation_name.clone();
472            async move {
473                match fetch_transaction_cost_details(
474                    &state.chain_index.rpc,
475                    &signature_to_fetch,
476                    gas_spend,
477                    RetryConfig {
478                        max_tries: 3,
479                        sleep_ms: 2000,
480                    },
481                )
482                .await
483                {
484                    Ok(cost_details) => {
485                        obs_actual_transaction_costs(
486                            domain,
487                            matched_variation_name,
488                            confirmation_status,
489                            cost_details,
490                        );
491                    }
492                    Err(e) => {
493                        tracing::warn!(
494                            "Failed to fetch transaction cost details for {signature_to_fetch}: {e}",
495                        );
496                    }
497                }
498            }
499            .instrument(span)
500        });
501
502        if !swap_into_fogo.is_empty() {
503            tokio::spawn({
504                let transaction_sponsor = Arc::clone(transaction_sponsor);
505                let domain = domain.clone();
506                let matched_variation_name = matched_variation_name.clone();
507                async move {
508                    if let Some(valiant_client) = &state.valiant_client {
509                        let swap_results = valiant_client
510                            .swap_tokens_probabilistic(
511                                &swap_into_fogo,
512                                &transaction_sponsor,
513                                &state.chain_index.rpc,
514                                &state.rpc_sub,
515                            )
516                            .await;
517
518                        let transaction_sponsor_pubkey = transaction_sponsor.pubkey();
519
520                        let swap_balance_changes = join_all(
521                            swap_results.iter().filter_map(|swap_result| {
522                                match swap_result {
523                                    Ok(SwapConfirmationResult { mint, confirmation }) => {
524                                        match confirmation {
525                                            ConfirmationResultInternal::Success { signature } => {
526                                                Some(fetch_swap_balance_changes(
527                                                    &state.chain_index.rpc,
528                                                    signature,
529                                                    &transaction_sponsor_pubkey,
530                                                    mint,
531                                                    RetryConfig {
532                                                        max_tries: 3,
533                                                        sleep_ms: 2000,
534                                                    })
535                                                )
536                                            }
537
538                                            ConfirmationResultInternal::Failed { signature, error, } => {
539                                                tracing::warn!("Failed to fetch swap balance changes due to failure to confirm transaction for {signature}: {:?}", error);
540                                                None
541                                            }
542
543                                            ConfirmationResultInternal::UnconfirmedPreflightFailure { signature, error, } => {
544                                                tracing::warn!("Failed to fetch swap balance changes due to transaction preflight failure for {signature}: {:?}", error);
545                                                None
546                                            }
547                                        }
548                                    }
549                                    Err(e) => {
550                                        tracing::warn!("Failed to send and confirm swap: {:?}", e);
551                                        None
552                                    }
553                                }
554                            })
555                        ).await;
556
557                        swap_balance_changes
558                            .iter()
559                            .for_each(|balance_change_result| match balance_change_result {
560                                Ok(balance_change) => {
561                                    obs_swap(
562                                        domain.clone(),
563                                        matched_variation_name.clone(),
564                                        balance_change,
565                                    );
566                                }
567                                Err(e) => {
568                                    tracing::warn!("Failed to fetch swap balance changes: {:?}", e);
569                                }
570                            });
571                    }
572                }
573            });
574        }
575    }
576
577    Ok(Json(confirmation_result.into()))
578}
579
580#[derive(serde::Deserialize, utoipa::IntoParams)]
581#[serde(deny_unknown_fields)]
582#[into_params(parameter_in = Query)]
583struct SponsorPubkeyQuery {
584    #[serde(default)]
585    /// Domain to request the sponsor pubkey for
586    domain: Option<String>,
587    #[serde(default)]
588    #[param(value_type = String)]
589    /// Index of the sponsor to select. Can be a number or the string "autoassign" which may give you a different sponsor every time
590    index: Option<IndexSelector>,
591}
592
593#[derive(serde::Deserialize)]
594#[serde(try_from = "String")]
595enum IndexSelector {
596    Autoassign,
597    Index(u8),
598}
599
600impl TryFrom<String> for IndexSelector {
601    type Error = String;
602    fn try_from(value: String) -> Result<Self, Self::Error> {
603        if value == "autoassign" {
604            Ok(IndexSelector::Autoassign)
605        } else {
606            let i: u8 = value.parse().map_err(|_| {
607                format!(
608                    "Invalid index value: {value}. Use a number between 0 and 255 or 'autoassign'"
609                )
610            })?;
611            Ok(IndexSelector::Index(i))
612        }
613    }
614}
615
616#[utoipa::path(get, path = "/sponsor_pubkey", params(SponsorPubkeyQuery))]
617async fn sponsor_pubkey_handler(
618    State(state): State<Arc<ServerState>>,
619    origin: Option<TypedHeader<Origin>>,
620    Query(SponsorPubkeyQuery { domain, index }): Query<SponsorPubkeyQuery>,
621) -> Result<String, ErrorResponse> {
622    let domain = get_domain_name(domain, origin)?;
623    let domains_guard = state.domains.load();
624    let domain_state = get_domain_state(&domains_guard, &domain)?;
625    let DomainState {
626        domain_registry_key: _,
627        sponsors,
628        enable_preflight_simulation: _,
629        tx_variations: _,
630        next_autoassigned_sponsor_index,
631    } = domain_state;
632
633    let sponsor_index = if let Some(selector) = index {
634        match selector {
635            IndexSelector::Autoassign => {
636                next_autoassigned_sponsor_index.fetch_add(1, Ordering::Relaxed) % sponsors.len()
637            }
638            IndexSelector::Index(i) => {
639                let index = usize::from(i);
640                if index >= sponsors.len() {
641                    return Err((
642                        StatusCode::BAD_REQUEST,
643                        format!(
644                            "Sponsor index {index} is out of bounds for domain {domain} with {} sponsors",
645                            sponsors.len()
646                        ),
647                    )
648                        .into());
649                }
650                index
651            }
652        }
653    } else {
654        0usize
655    };
656    Ok(sponsors[sponsor_index].pubkey().to_string())
657}
658#[serde_as]
659#[derive(serde::Deserialize, utoipa::IntoParams)]
660#[serde(deny_unknown_fields)]
661#[into_params(parameter_in = Query)]
662struct FeeQuery {
663    #[serde(default)]
664    /// Domain to request the fee for
665    domain: Option<String>,
666
667    /// Variation name to request the fee for
668    variation: String,
669
670    #[serde_as(as = "DisplayFromStr")]
671    #[param(value_type = String)]
672    /// Token mint to pay the fee in
673    mint: Pubkey,
674}
675
676#[utoipa::path(get, path = "/fee", params(FeeQuery))]
677async fn fee_handler(
678    State(state): State<Arc<ServerState>>,
679    origin: Option<TypedHeader<Origin>>,
680    Query(FeeQuery {
681        domain,
682        variation,
683        mint,
684    }): Query<FeeQuery>,
685) -> Result<Json<u64>, ErrorResponse> {
686    let domain = get_domain_name(domain, origin)?;
687    let domains_guard = state.domains.load();
688    let domain_state = get_domain_state(&domains_guard, &domain)?;
689    let DomainState { tx_variations, .. } = domain_state;
690
691    let variation = tx_variations.get(&variation).ok_or_else(|| {
692        (
693            StatusCode::NOT_FOUND,
694            format!("Variation {variation} not found for domain {domain}"),
695        )
696    })?;
697
698    let fee_coefficient = state.fee_coefficients.get(&mint).ok_or_else(|| {
699        (
700            StatusCode::NOT_FOUND,
701            format!("Paying paymaster fees in mint {mint} are not supported"),
702        )
703    })?;
704
705    let paymaster_fee_lamports = match variation {
706        ParsedTransactionVariation::V0(_) => 0,
707        ParsedTransactionVariation::V1(v1_variation) => {
708            v1_variation.paymaster_fee_lamports.unwrap_or(0)
709        }
710    };
711
712    Ok(Json(paymaster_fee_lamports.div_ceil(*fee_coefficient)))
713}
714
715pub fn get_domain_state_map(
716    domains: Vec<Domain>,
717    mnemonic: &str,
718) -> anyhow::Result<HashMap<String, DomainState>> {
719    domains
720        .into_iter()
721        .map(
722            |Domain {
723                 domain,
724                 enable_preflight_simulation,
725                 tx_variations,
726                 number_of_signers,
727                 enable_session_management,
728             }| {
729                let domain_registry_key = get_domain_record_address(&domain);
730                let sponsors = NonEmpty::collect((0u8..number_of_signers.into()).map(|i| {
731                    Arc::new(
732                        Keypair::from_seed_and_derivation_path(
733                            &solana_seed_phrase::generate_seed_from_seed_phrase_and_passphrase(
734                                mnemonic, &domain,
735                            ),
736                            Some(DerivationPath::new_bip44(Some(i.into()), Some(0))),
737                        )
738                        .expect("Failed to derive keypair from mnemonic_file"),
739                    )
740                }))
741                .expect("number_of_signers in NonZero so this should never be empty");
742
743                Ok((
744                    domain,
745                    DomainState {
746                        domain_registry_key,
747                        sponsors,
748                        enable_preflight_simulation,
749                        tx_variations: Domain::into_parsed_transaction_variations(
750                            tx_variations,
751                            enable_session_management,
752                        )?,
753                        next_autoassigned_sponsor_index: Arc::new(AtomicUsize::new(0)),
754                    },
755                ))
756            },
757        )
758        .collect::<Result<HashMap<_, _>, _>>()
759}
760
761/// How many RPC clients to create for both FTL and the regular RPC client for read operations
762const RPC_POOL_SIZE: usize = 6;
763
764#[allow(clippy::unwrap_used, reason = "It's fine to panic at startup")]
765#[allow(clippy::too_many_arguments)]
766pub async fn run_server(
767    rpc_url_http: String,
768    rpc_url_ws: String,
769    ftl_url: Option<String>,
770    listen_address: String,
771    domains_states: Arc<ArcSwap<HashMap<String, DomainState>>>,
772    fee_coefficients: HashMap<Pubkey, u64>,
773    network_environment: NetworkEnvironment,
774    valiant_api_key: Option<String>,
775    valiant_url_override: Option<String>,
776) {
777    let rpc_http_sender = PooledHttpSender::new(rpc_url_http, RPC_POOL_SIZE);
778
779    let rpc = RpcClient::new_sender(
780        rpc_http_sender,
781        RpcClientConfig::with_commitment(CommitmentConfig::processed()),
782    );
783
784    let rpc_sub_client = PubsubClient::new(&rpc_url_ws)
785        .await
786        .expect("Failed to create pubsub client");
787    let rpc_sub = PubsubClientWithReconnect::new(rpc_url_ws, rpc_sub_client);
788
789    // Create FTL RPC client with HTTP/2 prior knowledge if FTL URL is provided
790    let ftl_rpc = ftl_url.map(|url| {
791        let http_sender = PooledHttpSender::new(url, RPC_POOL_SIZE);
792
793        RpcClient::new_sender(
794            http_sender,
795            RpcClientConfig::with_commitment(CommitmentConfig::processed()),
796        )
797    });
798
799    let (router, _) = OpenApiRouter::new()
800        .routes(routes!(sponsor_and_send_handler, sponsor_pubkey_handler))
801        .routes(routes!(fee_handler))
802        .split_for_parts();
803
804    let handle = PrometheusBuilder::new()
805        .set_buckets_for_metric(
806            Matcher::Full(crate::metrics::GAS_SPEND_HISTOGRAM.to_string()),
807            crate::metrics::TRANSACTION_COST_BUCKETS,
808        )
809        .unwrap()
810        .set_buckets_for_metric(
811            Matcher::Full(crate::metrics::TRANSFER_SPEND_HISTOGRAM.to_string()),
812            crate::metrics::TRANSACTION_COST_BUCKETS,
813        )
814        .unwrap()
815        .set_buckets_for_metric(
816            Matcher::Full(crate::metrics::TOTAL_SPEND_HISTOGRAM.to_string()),
817            crate::metrics::TRANSACTION_COST_BUCKETS,
818        )
819        .unwrap()
820        .set_buckets_for_metric(
821            Matcher::Full(crate::metrics::SWAP_SPL_SIZE_HISTOGRAM.to_string()),
822            crate::metrics::SWAP_SPL_SIZE_BUCKETS,
823        )
824        .unwrap()
825        .set_buckets_for_metric(
826            Matcher::Full(crate::metrics::SWAP_FOGO_SIZE_HISTOGRAM.to_string()),
827            crate::metrics::SWAP_FOGO_SIZE_BUCKETS,
828        )
829        .unwrap()
830        .install_recorder()
831        .expect("install metrics recorder");
832
833    let prometheus_layer = PrometheusMetricLayer::new();
834
835    let valiant_client = valiant_api_key.map(|key| {
836        ValiantClient::from_params(&key, network_environment, valiant_url_override)
837            .expect("Should create Valiant client")
838    });
839
840    let app = Router::new()
841        .route("/ready", axum::routing::get(readiness_handler))
842        .route(
843            "/metrics",
844            axum::routing::get(move || async move { handle.render() }),
845        )
846        .nest("/api", router)
847        .layer(
848            CorsLayer::new()
849                .allow_origin(AllowOrigin::any())
850                .allow_methods(AllowMethods::list([Method::POST, Method::GET]))
851                .allow_headers(AllowHeaders::list(vec![HeaderName::from_static(
852                    "content-type",
853                )])),
854        )
855        .layer(prometheus_layer)
856        .with_state(Arc::new(ServerState {
857            domains: domains_states,
858            fee_coefficients,
859            chain_index: ChainIndex {
860                rpc,
861                lookup_table_cache: DashMap::new(),
862            },
863            rpc_sub,
864            ftl_rpc,
865            valiant_client,
866        }));
867    let listener = tokio::net::TcpListener::bind(listen_address).await.unwrap();
868    tracing::info!("Starting paymaster service...");
869    axum::serve(listener, app).await.unwrap();
870}