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
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
use crate::cli::NetworkEnvironment;
use crate::config_manager::config::Domain;
use crate::constraint::transaction::TransactionToValidate;
use crate::constraint::{ContextualDomainKeys, ParsedTransactionVariation};
use crate::metrics::{obs_actual_transaction_costs, obs_send, obs_swap, obs_validation};
use crate::pooled_http_sender::PooledHttpSender;
use crate::rpc::{
    fetch_swap_balance_changes, fetch_transaction_cost_details, send_and_confirm_transaction,
    send_and_confirm_transaction_ftl, ChainIndex, ConfirmationResultInternal, RetryConfig,
    SignedVersionedTransaction,
};
use crate::swap::SwapConfirmationResult;
use crate::unwrap_fogo::unwrap_fogo;
use arc_swap::ArcSwap;
use axum::extract::{Query, State};
use axum::http::StatusCode;
use axum::response::ErrorResponse;
use axum::Json;
use axum::{
    http::{HeaderName, Method},
    Router,
};
use axum_extra::headers::Origin;
use axum_extra::TypedHeader;
use axum_prometheus::metrics_exporter_prometheus::{Matcher, PrometheusBuilder};
use axum_prometheus::PrometheusMetricLayer;
use base64::Engine;
use dashmap::DashMap;
use fogo_sessions_sdk::domain_registry::get_domain_record_address;
use futures::future::join_all;
use nonempty::NonEmpty;
use reqwest::Client;
use serde_with::{serde_as, DisplayFromStr};
use solana_client::nonblocking::rpc_client::RpcClient;
use solana_client::rpc_config::RpcSendTransactionConfig;
use solana_commitment_config::{CommitmentConfig, CommitmentLevel};
use solana_derivation_path::DerivationPath;
use solana_keypair::Keypair;
use solana_packet::PACKET_DATA_SIZE;
use solana_pubkey::Pubkey;
use solana_pubsub_client::nonblocking::pubsub_client::PubsubClient;
use solana_rpc_client::rpc_client::RpcClientConfig;
use solana_seed_derivable::SeedDerivable;
use solana_signature::Signature;
use solana_signer::Signer;
use solana_transaction::versioned::VersionedTransaction;
use solana_transaction_error::TransactionError;
use std::collections::HashMap;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::Arc;
use tokio::sync::Mutex;
use tower_http::cors::{AllowHeaders, AllowMethods, AllowOrigin, CorsLayer};
use tracing::Instrument;
use url::Url;
use utoipa_axum::{router::OpenApiRouter, routes};

pub struct DomainState {
    pub domain_registry_key: Pubkey,
    pub sponsors: NonEmpty<Arc<Keypair>>,
    pub next_autoassigned_sponsor_index: Arc<AtomicUsize>,
    pub enable_preflight_simulation: bool,
    pub tx_variations: HashMap<String, ParsedTransactionVariation>,
}

pub struct PubsubClientWithReconnect {
    pub client: ArcSwap<PubsubClient>,
    pub rpc_url_ws: String,
    /// Mutex to prevent redundant concurrent reconnections
    pub reconnect_lock: Mutex<()>,
}

impl PubsubClientWithReconnect {
    pub fn new(rpc_url_ws: String, client: PubsubClient) -> Self {
        Self {
            client: ArcSwap::from_pointee(client),
            rpc_url_ws,
            reconnect_lock: Mutex::new(()),
        }
    }

    /// Reconnects the PubsubClient after grabbing a lock which prevents concurrent reconnections.
    pub async fn reconnect_pubsub(&self) -> Result<(), (StatusCode, String)> {
        let old_client = self.client.load_full();

        let _lock = self.reconnect_lock.lock().await;

        let current_client = self.client.load_full();

        // checks if the client was changed while waiting for the lock
        // if so, then no need to reconnect
        if Arc::ptr_eq(&old_client, &current_client) {
            match PubsubClient::new(&self.rpc_url_ws).await {
                Ok(new_client) => {
                    let new_arc = Arc::new(new_client);
                    self.client.store(new_arc);
                    tracing::debug!("Reconnected to WebSocket RPC at {}", self.rpc_url_ws);
                    Ok(())
                }
                Err(e) => Err((
                    StatusCode::SERVICE_UNAVAILABLE,
                    format!("WebSocket unavailable: {e}"),
                )),
            }
        } else {
            Ok(())
        }
    }
}

pub struct ValiantClient {
    pub client: Client,
    pub base_url: Url,
}

pub struct ServerState {
    pub domains: Arc<ArcSwap<HashMap<String, DomainState>>>,
    pub chain_index: ChainIndex,
    pub rpc_sub: PubsubClientWithReconnect,
    pub ftl_rpc: Option<RpcClient>,
    pub fee_coefficients: HashMap<Pubkey, u64>,
    pub valiant_client: Option<ValiantClient>,
}

#[derive(utoipa::ToSchema, serde::Deserialize)]
pub struct SponsorAndSendPayload {
    pub transaction: String,
}

impl DomainState {
    /// Checks that the transaction meets at least one of the specified variations for this domain.
    /// If so, returns the variation this transaction matched against.
    /// Otherwise, returns an error with a message indicating why the transaction is invalid.
    #[tracing::instrument(skip_all, fields(specified_variation = variation_name.as_deref(), matched_variation))]
    pub async fn validate_transaction(
        &self,
        transaction: &TransactionToValidate<'_>,
        chain_index: &ChainIndex,
        sponsor: &Pubkey,
        variation_name: Option<String>,
    ) -> Result<&ParsedTransactionVariation, (StatusCode, String)> {
        let message_bytes = transaction.message.serialize();
        transaction
            .signatures
            .iter()
            .zip(transaction.message.static_account_keys())
            .skip(1)
            .try_for_each(|(signature, pubkey)| {
                signature
                    .verify(pubkey.as_ref(), &message_bytes)
                    .then_some(())
                    .ok_or_else(|| {
                        (
                            StatusCode::BAD_REQUEST,
                            format!("Missing or invalid signature for account {pubkey}")
                                .to_string(),
                        )
                    })
            })?;

        let validation_futures: Vec<_> = self
            .tx_variations
            .iter()
            .filter_map(|(name, variation)| {
                if let Some(ref expected_name) = variation_name {
                    if name != expected_name {
                        return None;
                    }
                }

                Some(Box::pin(async move {
                    self.validate_transaction_against_variation(
                        transaction,
                        variation,
                        chain_index,
                        sponsor,
                    )
                    .await
                    .map(|_| variation)
                }))
            })
            .collect();

        // If no variations were validated and the variation_name was specified, return an error indicating no such variation.
        // If no variation_name was specified, return an error indicating no variations are configured for this domain.
        if validation_futures.is_empty() {
            return Err((
                StatusCode::BAD_REQUEST,
                if let Some(name) = variation_name {
                    format!("No transaction variation named '{name}' for domain")
                } else {
                    "No transaction variations configured for domain".to_string()
                },
            ));
        } else if variation_name.is_some() {
            // If variation_name was specified, only one future will be present, and we can propagate its specific error.
            let future = validation_futures
                .into_iter()
                .next()
                .expect("validation_futures is not empty, so this must exist");
            let variation = future.await?;
            tracing::Span::current().record("matched_variation", variation.name().to_string());
            Ok(variation)
        } else {
            match futures::future::select_ok(validation_futures).await {
                Ok((variation, _remaining)) => {
                    tracing::Span::current()
                        .record("matched_variation", variation.name().to_string());
                    Ok(variation)
                }
                Err(_) => Err((
                    StatusCode::BAD_REQUEST,
                    "Transaction does not match any allowed variations".to_string(),
                )),
            }
        }
    }

    pub async fn validate_transaction_against_variation(
        &self,
        transaction: &TransactionToValidate<'_>,
        tx_variation: &ParsedTransactionVariation,
        chain_index: &ChainIndex,
        sponsor: &Pubkey,
    ) -> Result<(), (StatusCode, String)> {
        match tx_variation {
            ParsedTransactionVariation::V0(variation) => {
                variation.validate_transaction(transaction)
            }
            ParsedTransactionVariation::V1(variation) => {
                variation
                    .validate_transaction(
                        transaction,
                        &ContextualDomainKeys {
                            domain_registry: self.domain_registry_key,
                            sponsor: *sponsor,
                        },
                        chain_index,
                    )
                    .await
            }
        }
    }
}

#[derive(serde::Deserialize, utoipa::IntoParams)]
#[serde(deny_unknown_fields)]
#[into_params(parameter_in = Query)]
struct SponsorAndSendQuery {
    #[serde(default, rename = "confirm")]
    #[deprecated]
    /// Whether to confirm the transaction
    _confirm: bool,

    #[serde(default)]
    /// Domain to request the sponsor pubkey for
    domain: Option<String>,

    #[serde(default)]
    /// Variation name to validate against. If not provided, all variations for the domain will be tried.
    variation: Option<String>,
}

fn get_domain_name(
    domain_explicit: Option<String>,
    origin: Option<TypedHeader<Origin>>,
) -> Result<String, (StatusCode, String)> {
    let domain = domain_explicit
        .or_else(|| origin.map(|origin| origin.to_string()))
        .ok_or_else(|| {
            (
                StatusCode::BAD_REQUEST,
                "The http origin header or query parameter domain is required".to_string(),
            )
        })?;

    Ok(domain)
}

fn get_domain_state<'a>(
    domains: &'a HashMap<String, DomainState>,
    domain_query_parameter: &str,
) -> Result<&'a DomainState, (StatusCode, String)> {
    let domain_state = domains
        .get(domain_query_parameter)
        .ok_or_else(|| {
            (
                StatusCode::BAD_REQUEST,
                format!(
                    "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"
                ),
            )
        })?;

    Ok(domain_state)
}

async fn readiness_handler() -> StatusCode {
    StatusCode::OK
}

#[serde_as]
#[derive(serde::Serialize)]
#[serde(tag = "type")]
pub enum ConfirmationResult {
    /// Transaction was confirmed and succeeded on chain
    #[serde(rename = "success")]
    Success {
        #[serde_as(as = "DisplayFromStr")]
        signature: Signature,
    },

    /// TODO: Disambiguate between confirmed and failed on chain vs failed preflight
    #[serde(rename = "failed")]
    Failed {
        #[serde_as(as = "DisplayFromStr")]
        signature: Signature,
        error: TransactionError,
    },
}

#[utoipa::path(
    post,
    path = "/sponsor_and_send",
    request_body = SponsorAndSendPayload,
    params(SponsorAndSendQuery)
)]
#[tracing::instrument(
    skip_all,
    name = "sponsor_and_send",
    fields(domain, specified_variation = variation.as_deref(), matched_variation, tx_hash)
)]
async fn sponsor_and_send_handler(
    State(state): State<Arc<ServerState>>,
    origin: Option<TypedHeader<Origin>>,
    Query(SponsorAndSendQuery {
        domain, variation, ..
    }): Query<SponsorAndSendQuery>,
    Json(payload): Json<SponsorAndSendPayload>,
) -> Result<Json<ConfirmationResult>, ErrorResponse> {
    let domain = get_domain_name(domain, origin)?;
    tracing::Span::current().record("domain", domain.as_str());
    let domains_guard = state.domains.load();
    let domain_state = get_domain_state(&domains_guard, &domain)?;

    let transaction_bytes = base64::engine::general_purpose::STANDARD
        .decode(&payload.transaction)
        .map_err(|_| (StatusCode::BAD_REQUEST, "Failed to deserialize transaction"))?;

    if transaction_bytes.len() > PACKET_DATA_SIZE {
        return Err((
            StatusCode::BAD_REQUEST,
            format!(
                "Transaction is too large: {} > {PACKET_DATA_SIZE}",
                transaction_bytes.len()
            ),
        ))?;
    }

    let (transaction, _): (VersionedTransaction, _) =
        bincode::serde::decode_from_slice(&transaction_bytes, bincode::config::standard())
            .map_err(|_| (StatusCode::BAD_REQUEST, "Failed to deserialize transaction"))?;

    let fee_payer = transaction.message.static_account_keys().first().ok_or({
        (
            StatusCode::BAD_REQUEST,
            "The transaction must have a fee payer",
        )
    })?;
    let transaction_sponsor = domain_state
        .sponsors
        .iter()
        .find(|sponsor| sponsor.pubkey() == *fee_payer)
        .ok_or_else(|| -> (StatusCode, String) {
            let status_code = StatusCode::BAD_REQUEST;
            obs_validation(domain.clone(), None, status_code.to_string());
            (
                status_code,
                format!(
                    "Transaction fee payer must be one of the sponsors: expected one of {}, got {}",
                    domain_state
                        .sponsors
                        .iter()
                        .map(|sponsor| sponsor.pubkey().to_string())
                        .collect::<Vec<_>>()
                        .join(","),
                    fee_payer,
                ),
            )
        })?;

    let transaction_to_validate =
        TransactionToValidate::parse(&transaction, &state.chain_index, &state.fee_coefficients)
            .await?;
    let (matched_variation_name, swap_into_fogo) = match domain_state
        .validate_transaction(
            &transaction_to_validate,
            &state.chain_index,
            &transaction_sponsor.pubkey(),
            variation,
        )
        .await
    {
        Ok(variation) => {
            tracing::Span::current().record("matched_variation", variation.name());
            obs_validation(
                domain.clone(),
                Some(variation.name().to_owned()),
                "success".to_string(),
            );
            (
                variation.name().to_owned(),
                variation.swap_into_fogo().to_owned(),
            )
        }
        Err(e) => {
            obs_validation(domain.clone(), None, "invalid".to_string());
            return Err(e.into());
        }
    };
    let gas_spend = transaction_to_validate.gas_spend;

    let signature = transaction_sponsor.sign_message(&transaction.message.serialize());
    let signed_transaction = SignedVersionedTransaction::new(transaction, signature)
        .map_err(|e| (StatusCode::BAD_REQUEST, e.to_string()))?;
    tracing::Span::current().record("tx_hash", signed_transaction.signature().to_string());

    let rpc_config = RpcSendTransactionConfig {
        skip_preflight: !domain_state.enable_preflight_simulation,
        preflight_commitment: Some(CommitmentLevel::Processed),
        ..RpcSendTransactionConfig::default()
    };

    let confirmation_result = if let Some(ref ftl_rpc) = state.ftl_rpc {
        // Use FTL service for sending and confirmation
        send_and_confirm_transaction_ftl(ftl_rpc, &signed_transaction, rpc_config).await?
    } else {
        // Use standard RPC method
        send_and_confirm_transaction(
            &state.chain_index.rpc,
            &state.rpc_sub,
            &signed_transaction,
            rpc_config,
        )
        .await?
    };

    let confirmation_status = confirmation_result.status_string();

    obs_send(
        domain.clone(),
        matched_variation_name.clone(),
        confirmation_status.clone(),
    );

    // Spawn async task to fetch actual transaction costs from RPC
    // This happens in the background to avoid blocking the response to the client
    // Only fetch if the transaction actually succeeded on chain
    let signature = match &confirmation_result {
        ConfirmationResultInternal::Success { signature } => Some(*signature),
        ConfirmationResultInternal::Failed { signature, .. } => Some(*signature),
        _ => None,
    };

    if let Some(signature_to_fetch) = signature {
        // We capture the current span to propagate to the spawned task.
        // This ensures that any logs/traces from the spawned task are associated with the original request.
        let span = tracing::Span::current();

        tokio::spawn({
            let state = Arc::clone(&state);
            let domain = domain.clone();
            let matched_variation_name = matched_variation_name.clone();
            async move {
                match fetch_transaction_cost_details(
                    &state.chain_index.rpc,
                    &signature_to_fetch,
                    gas_spend,
                    RetryConfig {
                        max_tries: 3,
                        sleep_ms: 2000,
                    },
                )
                .await
                {
                    Ok(cost_details) => {
                        obs_actual_transaction_costs(
                            domain,
                            matched_variation_name,
                            confirmation_status,
                            cost_details,
                        );
                    }
                    Err(e) => {
                        tracing::warn!(
                            "Failed to fetch transaction cost details for {signature_to_fetch}: {e}",
                        );
                    }
                }
            }
            .instrument(span)
        });

        if !swap_into_fogo.is_empty() {
            tokio::spawn({
                let transaction_sponsor = Arc::clone(transaction_sponsor);
                let domain = domain.clone();
                let matched_variation_name = matched_variation_name.clone();
                async move {
                    if let Some(valiant_client) = &state.valiant_client {
                        let swap_results = valiant_client
                            .swap_tokens_probabilistic(
                                &swap_into_fogo,
                                &transaction_sponsor,
                                &state.chain_index.rpc,
                                &state.rpc_sub,
                            )
                            .await;

                        let n_successful_swaps = swap_results
                            .iter()
                            .filter(|result| {
                                if let Ok(SwapConfirmationResult { confirmation, .. }) = result {
                                    matches!(
                                        confirmation,
                                        ConfirmationResultInternal::Success { .. }
                                    )
                                } else {
                                    false
                                }
                            })
                            .count();

                        if n_successful_swaps > 0 {
                            match unwrap_fogo(
                                &transaction_sponsor,
                                &state.chain_index.rpc,
                                &state.rpc_sub,
                            )
                            .await
                            {
                                Ok(confirmation) => match confirmation {
                                    ConfirmationResultInternal::Failed { signature, error } => {
                                        tracing::warn!("Failed to unwrap due to failure to confirm transaction for {signature}: {:?}", error);
                                    }
                                    ConfirmationResultInternal::UnconfirmedPreflightFailure {
                                        signature,
                                        error,
                                    } => {
                                        tracing::warn!("Failed to unwrap due to transaction preflight failure for {signature}: {:?}", error);
                                    }
                                    ConfirmationResultInternal::Success { .. } => {}
                                },

                                Err(e) => {
                                    tracing::warn!(
                                        "Failed to send and confirm unwrap transaction: {:?}",
                                        e
                                    );
                                }
                            }
                        }

                        let transaction_sponsor_pubkey = transaction_sponsor.pubkey();

                        let swap_balance_changes = join_all(
                            swap_results.iter().filter_map(|swap_result| {
                                match swap_result {
                                    Ok(SwapConfirmationResult { mint, confirmation }) => {
                                        match confirmation {
                                            ConfirmationResultInternal::Success { signature } => {
                                                Some(fetch_swap_balance_changes(
                                                    &state.chain_index.rpc,
                                                    signature,
                                                    &transaction_sponsor_pubkey,
                                                    mint,
                                                    RetryConfig {
                                                        max_tries: 3,
                                                        sleep_ms: 2000,
                                                    })
                                                )
                                            }

                                            ConfirmationResultInternal::Failed { signature, error, } => {
                                                tracing::warn!("Failed to fetch swap balance changes due to failure to confirm transaction for {signature}: {:?}", error);
                                                None
                                            }

                                            ConfirmationResultInternal::UnconfirmedPreflightFailure { signature, error, } => {
                                                tracing::warn!("Failed to fetch swap balance changes due to transaction preflight failure for {signature}: {:?}", error);
                                                None
                                            }
                                        }
                                    }
                                    Err(e) => {
                                        tracing::warn!("Failed to send and confirm swap: {:?}", e);
                                        None
                                    }
                                }
                            })
                        ).await;

                        swap_balance_changes
                            .iter()
                            .for_each(|balance_change_result| match balance_change_result {
                                Ok(balance_change) => {
                                    obs_swap(
                                        domain.clone(),
                                        matched_variation_name.clone(),
                                        balance_change,
                                    );
                                }
                                Err(e) => {
                                    tracing::warn!("Failed to fetch swap balance changes: {:?}", e);
                                }
                            });
                    }
                }
            });
        }
    }

    Ok(Json(confirmation_result.into()))
}

#[derive(serde::Deserialize, utoipa::IntoParams)]
#[serde(deny_unknown_fields)]
#[into_params(parameter_in = Query)]
struct SponsorPubkeyQuery {
    #[serde(default)]
    /// Domain to request the sponsor pubkey for
    domain: Option<String>,
    #[serde(default)]
    #[param(value_type = String)]
    /// Index of the sponsor to select. Can be a number or the string "autoassign" which may give you a different sponsor every time
    index: Option<IndexSelector>,
}

#[derive(serde::Deserialize)]
#[serde(try_from = "String")]
enum IndexSelector {
    Autoassign,
    Index(u8),
}

impl TryFrom<String> for IndexSelector {
    type Error = String;
    fn try_from(value: String) -> Result<Self, Self::Error> {
        if value == "autoassign" {
            Ok(IndexSelector::Autoassign)
        } else {
            let i: u8 = value.parse().map_err(|_| {
                format!(
                    "Invalid index value: {value}. Use a number between 0 and 255 or 'autoassign'"
                )
            })?;
            Ok(IndexSelector::Index(i))
        }
    }
}

#[utoipa::path(get, path = "/sponsor_pubkey", params(SponsorPubkeyQuery))]
async fn sponsor_pubkey_handler(
    State(state): State<Arc<ServerState>>,
    origin: Option<TypedHeader<Origin>>,
    Query(SponsorPubkeyQuery { domain, index }): Query<SponsorPubkeyQuery>,
) -> Result<String, ErrorResponse> {
    let domain = get_domain_name(domain, origin)?;
    let domains_guard = state.domains.load();
    let domain_state = get_domain_state(&domains_guard, &domain)?;
    let DomainState {
        domain_registry_key: _,
        sponsors,
        enable_preflight_simulation: _,
        tx_variations: _,
        next_autoassigned_sponsor_index,
    } = domain_state;

    let sponsor_index = if let Some(selector) = index {
        match selector {
            IndexSelector::Autoassign => {
                next_autoassigned_sponsor_index.fetch_add(1, Ordering::Relaxed) % sponsors.len()
            }
            IndexSelector::Index(i) => {
                let index = usize::from(i);
                if index >= sponsors.len() {
                    return Err((
                        StatusCode::BAD_REQUEST,
                        format!(
                            "Sponsor index {index} is out of bounds for domain {domain} with {} sponsors",
                            sponsors.len()
                        ),
                    )
                        .into());
                }
                index
            }
        }
    } else {
        0usize
    };
    Ok(sponsors[sponsor_index].pubkey().to_string())
}
#[serde_as]
#[derive(serde::Deserialize, utoipa::IntoParams)]
#[serde(deny_unknown_fields)]
#[into_params(parameter_in = Query)]
struct FeeQuery {
    #[serde(default)]
    /// Domain to request the fee for
    domain: Option<String>,

    /// Variation name to request the fee for
    variation: String,

    #[serde_as(as = "DisplayFromStr")]
    #[param(value_type = String)]
    /// Token mint to pay the fee in
    mint: Pubkey,
}

#[utoipa::path(get, path = "/fee", params(FeeQuery))]
async fn fee_handler(
    State(state): State<Arc<ServerState>>,
    origin: Option<TypedHeader<Origin>>,
    Query(FeeQuery {
        domain,
        variation,
        mint,
    }): Query<FeeQuery>,
) -> Result<Json<u64>, ErrorResponse> {
    let domain = get_domain_name(domain, origin)?;
    let domains_guard = state.domains.load();
    let domain_state = get_domain_state(&domains_guard, &domain)?;
    let DomainState { tx_variations, .. } = domain_state;

    let variation = tx_variations.get(&variation).ok_or_else(|| {
        (
            StatusCode::NOT_FOUND,
            format!("Variation {variation} not found for domain {domain}"),
        )
    })?;

    let fee_coefficient = state.fee_coefficients.get(&mint).ok_or_else(|| {
        (
            StatusCode::NOT_FOUND,
            format!("Paying paymaster fees in mint {mint} are not supported"),
        )
    })?;

    let paymaster_fee_lamports = match variation {
        ParsedTransactionVariation::V0(_) => 0,
        ParsedTransactionVariation::V1(v1_variation) => {
            v1_variation.paymaster_fee_lamports.unwrap_or(0)
        }
    };

    Ok(Json(paymaster_fee_lamports.div_ceil(*fee_coefficient)))
}

pub fn get_domain_state_map(
    domains: Vec<Domain>,
    mnemonic: &str,
) -> anyhow::Result<HashMap<String, DomainState>> {
    domains
        .into_iter()
        .map(
            |Domain {
                 domain,
                 enable_preflight_simulation,
                 tx_variations,
                 number_of_signers,
                 enable_session_management,
             }| {
                let domain_registry_key = get_domain_record_address(&domain);
                let sponsors = NonEmpty::collect((0u8..number_of_signers.into()).map(|i| {
                    Arc::new(
                        Keypair::from_seed_and_derivation_path(
                            &solana_seed_phrase::generate_seed_from_seed_phrase_and_passphrase(
                                mnemonic, &domain,
                            ),
                            Some(DerivationPath::new_bip44(Some(i.into()), Some(0))),
                        )
                        .expect("Failed to derive keypair from mnemonic_file"),
                    )
                }))
                .expect("number_of_signers in NonZero so this should never be empty");

                Ok((
                    domain,
                    DomainState {
                        domain_registry_key,
                        sponsors,
                        enable_preflight_simulation,
                        tx_variations: Domain::into_parsed_transaction_variations(
                            tx_variations,
                            enable_session_management,
                        )?,
                        next_autoassigned_sponsor_index: Arc::new(AtomicUsize::new(0)),
                    },
                ))
            },
        )
        .collect::<Result<HashMap<_, _>, _>>()
}

/// How many RPC clients to create for both FTL and the regular RPC client for read operations
const RPC_POOL_SIZE: usize = 6;

#[allow(clippy::unwrap_used, reason = "It's fine to panic at startup")]
#[allow(clippy::too_many_arguments)]
pub async fn run_server(
    rpc_url_http: String,
    rpc_url_ws: String,
    ftl_url: Option<String>,
    listen_address: String,
    domains_states: Arc<ArcSwap<HashMap<String, DomainState>>>,
    fee_coefficients: HashMap<Pubkey, u64>,
    network_environment: NetworkEnvironment,
    valiant_api_key: Option<String>,
    valiant_url_override: Option<String>,
) {
    let rpc_http_sender = PooledHttpSender::new(rpc_url_http, RPC_POOL_SIZE);

    let rpc = RpcClient::new_sender(
        rpc_http_sender,
        RpcClientConfig::with_commitment(CommitmentConfig::processed()),
    );

    let rpc_sub_client = PubsubClient::new(&rpc_url_ws)
        .await
        .expect("Failed to create pubsub client");
    let rpc_sub = PubsubClientWithReconnect::new(rpc_url_ws, rpc_sub_client);

    // Create FTL RPC client with HTTP/2 prior knowledge if FTL URL is provided
    let ftl_rpc = ftl_url.map(|url| {
        let http_sender = PooledHttpSender::new(url, RPC_POOL_SIZE);

        RpcClient::new_sender(
            http_sender,
            RpcClientConfig::with_commitment(CommitmentConfig::processed()),
        )
    });

    let (router, _) = OpenApiRouter::new()
        .routes(routes!(sponsor_and_send_handler, sponsor_pubkey_handler))
        .routes(routes!(fee_handler))
        .split_for_parts();

    let handle = PrometheusBuilder::new()
        .set_buckets_for_metric(
            Matcher::Full(crate::metrics::GAS_SPEND_HISTOGRAM.to_string()),
            crate::metrics::TRANSACTION_COST_BUCKETS,
        )
        .unwrap()
        .set_buckets_for_metric(
            Matcher::Full(crate::metrics::TRANSFER_SPEND_HISTOGRAM.to_string()),
            crate::metrics::TRANSACTION_COST_BUCKETS,
        )
        .unwrap()
        .set_buckets_for_metric(
            Matcher::Full(crate::metrics::TOTAL_SPEND_HISTOGRAM.to_string()),
            crate::metrics::TRANSACTION_COST_BUCKETS,
        )
        .unwrap()
        .set_buckets_for_metric(
            Matcher::Full(crate::metrics::SWAP_SPL_SIZE_HISTOGRAM.to_string()),
            crate::metrics::SWAP_SPL_SIZE_BUCKETS,
        )
        .unwrap()
        .set_buckets_for_metric(
            Matcher::Full(crate::metrics::SWAP_FOGO_SIZE_HISTOGRAM.to_string()),
            crate::metrics::SWAP_FOGO_SIZE_BUCKETS,
        )
        .unwrap()
        .install_recorder()
        .expect("install metrics recorder");

    let prometheus_layer = PrometheusMetricLayer::new();

    let valiant_client = valiant_api_key.map(|key| {
        ValiantClient::from_params(&key, network_environment, valiant_url_override)
            .expect("Should create Valiant client")
    });

    let app = Router::new()
        .route("/ready", axum::routing::get(readiness_handler))
        .route(
            "/metrics",
            axum::routing::get(move || async move { handle.render() }),
        )
        .nest("/api", router)
        .layer(
            CorsLayer::new()
                .allow_origin(AllowOrigin::any())
                .allow_methods(AllowMethods::list([Method::POST, Method::GET]))
                .allow_headers(AllowHeaders::list(vec![HeaderName::from_static(
                    "content-type",
                )])),
        )
        .layer(prometheus_layer)
        .with_state(Arc::new(ServerState {
            domains: domains_states,
            fee_coefficients,
            chain_index: ChainIndex {
                rpc,
                lookup_table_cache: DashMap::new(),
            },
            rpc_sub,
            ftl_rpc,
            valiant_client,
        }));
    let listener = tokio::net::TcpListener::bind(listen_address).await.unwrap();
    tracing::info!("Starting paymaster service...");
    axum::serve(listener, app).await.unwrap();
}