fogo-paymaster 0.7.4

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
use anyhow::{anyhow, Context, Result};
use clap::{Parser, Subcommand, ValueEnum};
use config::File;
use dashmap::DashMap;
use fogo_paymaster::{
    config_manager::config::{Config, Domain},
    constraint::{
        transaction::TransactionToValidate, ContextualDomainKeys, ParsedTransactionVariation,
    },
    parse::parse_transaction_from_base64,
    rpc::ChainIndex,
};
use fogo_sessions_sdk::domain_registry::get_domain_record_address;
use futures::stream::{FuturesOrdered, StreamExt};
use governor::{
    clock::DefaultClock,
    middleware::NoOpMiddleware,
    state::{InMemoryState, NotKeyed},
    Quota, RateLimiter,
};
use solana_client::{
    nonblocking::rpc_client::RpcClient, rpc_client::GetConfirmedSignaturesForAddress2Config,
    rpc_config::RpcTransactionConfig,
};
use solana_pubkey::Pubkey;
use solana_signature::Signature;
use solana_transaction::versioned::VersionedTransaction;
use solana_transaction_status_client_types::UiTransactionEncoding;
use std::{collections::HashMap, num::NonZeroU32, str::FromStr};

#[derive(Parser)]
#[command(name = "tx-validator")]
#[command(about = "Validates transactions against domain configuration variations")]
struct Cli {
    #[command(subcommand)]
    command: Commands,
}

#[derive(Subcommand)]
enum Commands {
    Validate {
        /// Path to the TOML configuration file
        #[arg(short, long)]
        config: String,

        /// Domain name to check against (if not provided, checks all domains)
        #[arg(short, long)]
        domain: Option<String>,

        /// Transaction variation to check against (if not provided, checks all variations in scope)
        #[arg(short, long, requires = "domain")]
        variation: Option<String>,

        /// Fogo network to target, this determines the paymaster instance and the default RPC endpoint to use.
        #[arg(long, value_enum, default_value_t = Network::Testnet)]
        network: Network,

        /// Sponsor pubkey for the provided domain, if this is provided the sponsor pubkey won't be fetched from the paymaster server. This is useful if your domain is not registered with the paymaster server yet.
        #[arg(long, requires = "domain")]
        sponsor: Option<Pubkey>,

        /// Transaction hash to fetch from RPC
        #[arg(long, conflicts_with_all = ["transaction", "recent_sponsor_txs"])]
        transaction_hash: Option<String>,

        /// Base64 encoded serialized transaction
        #[arg(short, long, conflicts_with_all = ["transaction_hash", "recent_sponsor_txs"])]
        transaction: Option<String>,

        /// Number of recent sponsor transactions to fetch and validate
        #[arg(long, conflicts_with_all = ["transaction", "transaction_hash"])]
        recent_sponsor_txs: Option<usize>,

        /// RPC rate limit (per second)
        #[arg(long, default_value_t = 10)]
        rpc_quota_per_second: u32,

        /// RPC HTTP URL (defaults to the network-specific endpoint)
        #[arg(long)]
        rpc_url_http: Option<String>,
    },
}

type RpcRateLimiter = RateLimiter<NotKeyed, InMemoryState, DefaultClock, NoOpMiddleware>;

#[derive(Copy, Clone, ValueEnum)]
enum Network {
    Mainnet,
    Testnet,
}

impl Network {
    fn paymaster_base_url(self) -> &'static str {
        match self {
            Network::Mainnet => "https://fogo-mainnet.dourolabs-paymaster.xyz",
            Network::Testnet => "https://fogo-testnet.dourolabs-paymaster.xyz",
        }
    }

    fn default_rpc_url_http(self) -> &'static str {
        match self {
            Network::Mainnet => "https://mainnet.fogo.io",
            Network::Testnet => "https://testnet.fogo.io",
        }
    }
}

pub fn load_file_config(config_path: &str) -> Result<Config> {
    let config: Config = config::Config::builder()
        .add_source(File::with_name(config_path))
        .build()?
        .try_deserialize()?;
    Ok(config)
}

#[tokio::main]
async fn main() -> Result<()> {
    let cli = Cli::parse();

    match cli.command {
        Commands::Validate {
            config,
            domain,
            variation,
            network,
            sponsor,
            transaction_hash,
            transaction,
            recent_sponsor_txs,
            rpc_quota_per_second,
            rpc_url_http,
        } => {
            let config = load_file_config(&config)?;
            let domains = get_domains_for_validation(config, &domain, &variation)?;
            let rpc_url_http =
                rpc_url_http.unwrap_or_else(|| network.default_rpc_url_http().to_string());
            let chain_index = ChainIndex {
                rpc: RpcClient::new(rpc_url_http),
                lookup_table_cache: DashMap::new(),
            };

            let rpc_limiter = RateLimiter::direct(Quota::per_second(
                NonZeroU32::new(rpc_quota_per_second)
                    .expect("RPC quota per second must be greater than zero"),
            ));

            let contextual_keys_cache: ContextualKeysCache =
                ContextualKeysCache::new(&domains, network, sponsor).await?;

            let (transactions, is_batch) = fetch_transactions(
                recent_sponsor_txs,
                transaction_hash,
                transaction,
                &domain,
                &domains,
                &chain_index,
                &rpc_limiter,
                &contextual_keys_cache,
            )
            .await?;

            let (validation_counts, failure_count) = validate_transactions(
                &transactions,
                &domains,
                &chain_index,
                &contextual_keys_cache,
                is_batch,
                variation.is_some(),
                true,
            )
            .await;

            if is_batch {
                print_summary(validation_counts, failure_count);
            }
        }
    }

    Ok(())
}

type Domains = HashMap<String, HashMap<String, ParsedTransactionVariation>>;

/// Extracts from the config the domains to use in validation.
/// If `domain` is specified, only returns that domain's variations.
/// If `variation` is specified, filters out all other variations.
fn get_domains_for_validation(
    config: fogo_paymaster::config_manager::config::Config,
    domain: &Option<String>,
    variation: &Option<String>,
) -> Result<Domains> {
    let domains = if let Some(domain_name) = domain {
        vec![config
            .domains
            .into_iter()
            .find(|d| d.domain == *domain_name)
            .expect("Specified domain not found in config")]
    } else {
        config.domains
    };

    domains
        .into_iter()
        .map(
            |Domain {
                 domain,
                 tx_variations,
                 enable_session_management,
                 ..
             }| {
                let parsed_transaction_variations = Domain::into_parsed_transaction_variations(
                    tx_variations,
                    enable_session_management,
                )?
                .into_iter()
                .filter(|(_, v)| variation.as_ref().is_none_or(|name| v.name() == name))
                .collect();
                Ok((domain, parsed_transaction_variations))
            },
        )
        .collect()
}

#[allow(clippy::too_many_arguments)]
async fn fetch_transactions(
    recent_sponsor_txs: Option<usize>,
    transaction_hash: Option<String>,
    transaction: Option<String>,
    domain: &Option<String>,
    domains: &Domains,
    chain_index: &ChainIndex,
    rpc_limiter: &RpcRateLimiter,
    contextual_keys_cache: &ContextualKeysCache,
) -> Result<(Vec<VersionedTransaction>, bool)> {
    if let Some(limit) = recent_sponsor_txs {
        let domain_for_sponsor = if let Some(domain_name) = domain {
            domain_name.as_str()
        } else if domains.len() == 1 {
            domains
                .keys()
                .next()
                .expect("Length is 1, should not panic")
        } else if domains.is_empty() {
            return Err(anyhow!("No domains found in config"));
        } else {
            return Err(anyhow!(
                "When using --recent-sponsor-txs with multiple domains, --domain must be specified"
            ));
        };
        let sponsor = contextual_keys_cache.get(domain_for_sponsor).await?.sponsor;
        let txs = fetch_recent_sponsor_transactions(&sponsor, limit, &chain_index.rpc, rpc_limiter)
            .await?;
        println!(
            "Fetched {} recent transactions from sponsor {}\n",
            txs.len(),
            sponsor
        );
        Ok((txs, true))
    } else if let Some(tx_hash) = transaction_hash {
        let tx_hash = Signature::from_str(&tx_hash)
            .with_context(|| format!("Invalid transaction signature: {tx_hash}"))?;
        let tx = fetch_transaction_from_rpc(tx_hash, &chain_index.rpc, rpc_limiter).await?;
        Ok((vec![tx], false))
    } else if let Some(tx) = transaction {
        let tx = parse_transaction_from_base64(&tx)?;
        Ok((vec![tx], false))
    } else {
        Err(anyhow!(
            "Either --transaction-hash, --transaction, or --recent-sponsor-txs must be provided"
        ))
    }
}

async fn validate_transactions(
    transactions: &[VersionedTransaction],
    domains: &Domains,
    chain_index: &ChainIndex,
    contextual_keys_cache: &ContextualKeysCache,
    is_batch: bool,
    show_validation_details: bool,
    show_validation_outcomes: bool,
) -> (HashMap<(String, String), usize>, usize) {
    let mut validation_stream = transactions
        .iter()
        .enumerate()
        .map(|(idx, tx)| async move {
            let results =
                futures::future::join_all(domains.iter().map(|(domain, tx_variations)| async {
                    let variations = get_matching_variations(
                        tx,
                        domain,
                        tx_variations,
                        chain_index,
                        contextual_keys_cache,
                        show_validation_details,
                    )
                    .await
                    .unwrap_or_default();
                    variations
                        .into_iter()
                        .map(|v| (domain.as_str(), v))
                        .collect::<Vec<_>>()
                }))
                .await
                .into_iter()
                .flatten()
                .collect::<Vec<_>>();

            (idx, tx, results)
        })
        .collect::<FuturesOrdered<_>>();

    let indent = if is_batch { "  " } else { "" };
    let mut validation_counts = HashMap::new();
    let mut failure_count = 0;

    while let Some((idx, tx, validations)) = validation_stream.next().await {
        if validations.is_empty() {
            failure_count += 1;
        } else {
            for (domain_name, variation) in &validations {
                *validation_counts
                    .entry((domain_name.to_string(), variation.name().to_string()))
                    .or_insert(0) += 1;
            }
        }

        if show_validation_outcomes {
            if is_batch {
                println!(
                    "Transaction {} ({})",
                    idx + 1,
                    tx.signatures
                        .first()
                        .expect("Failed to access fee-payer signature")
                );
            }

            if validations.is_empty() {
                println!("{indent}❌ Does not match any variations");
            } else {
                println!("{indent}✅ Matches:");
                for (domain_name, variation) in &validations {
                    println!(
                        "{}  - Domain: {domain_name}, Variation: {}",
                        indent,
                        variation.name()
                    );
                }
            }

            if is_batch {
                println!();
            }
        }
    }

    (validation_counts, failure_count)
}

fn print_summary(validation_counts: HashMap<(String, String), usize>, failure_count: usize) {
    println!("Summary:");
    println!("========");

    let mut sorted_counts: Vec<_> = validation_counts.into_iter().collect();
    sorted_counts.sort_by(|a, b| b.1.cmp(&a.1));

    let max_domain_len = sorted_counts
        .iter()
        .map(|((domain_name, _), _)| domain_name.len())
        .chain(std::iter::once("-".len()))
        .max()
        .unwrap_or(0);

    let max_variation_len = sorted_counts
        .iter()
        .map(|((_, variation_name), _)| variation_name.len())
        .chain(std::iter::once("Failures".len()))
        .max()
        .unwrap_or(0);

    for ((domain_name, variation_name), count) in sorted_counts {
        println!("✅ {domain_name:max_domain_len$}  {variation_name:max_variation_len$}  {count}");
    }

    if failure_count > 0 {
        println!(
            "❌ {:domain_width$}  {:variation_width$}  {}",
            "-",
            "Failures",
            failure_count,
            domain_width = max_domain_len,
            variation_width = max_variation_len
        );
    }
}

async fn fetch_transaction_from_rpc(
    tx_hash: Signature,
    rpc_client: &RpcClient,
    rpc_limiter: &RpcRateLimiter,
) -> Result<VersionedTransaction> {
    let config = RpcTransactionConfig {
        encoding: Some(UiTransactionEncoding::Base64),
        max_supported_transaction_version: Some(0),
        ..Default::default()
    };

    rpc_limiter.until_ready().await;
    let transaction = rpc_client
        .get_transaction_with_config(&tx_hash, config)
        .await
        .with_context(|| format!("Failed to fetch transaction from RPC: {tx_hash}"))?;

    let versioned_transaction = transaction
        .transaction
        .transaction
        .decode()
        .ok_or_else(|| anyhow!("Failed to decode transaction from RPC response"))?;

    Ok(versioned_transaction)
}

async fn fetch_recent_sponsor_signatures(
    sponsor_pubkey: &solana_pubkey::Pubkey,
    mut number: usize,
    rpc_client: &RpcClient,
    rpc_limiter: &RpcRateLimiter,
) -> Result<Vec<Signature>> {
    let mut signatures = Vec::new();
    let mut before = None;
    while number > 0 {
        rpc_limiter.until_ready().await;
        let new_signatures = rpc_client
            .get_signatures_for_address_with_config(
                sponsor_pubkey,
                GetConfirmedSignaturesForAddress2Config {
                    limit: Some(number.min(1000)),
                    before,
                    ..Default::default()
                },
            )
            .await
            .with_context(|| format!("Failed to fetch signatures for sponsor {sponsor_pubkey}"))?;

        number -= new_signatures.len();
        if new_signatures.is_empty() {
            break;
        }
        before = new_signatures
            .last()
            .and_then(|s| Signature::from_str(&s.signature).ok());

        signatures.extend(new_signatures);
    }

    signatures
        .into_iter()
        .map(|s| {
            Signature::from_str(&s.signature)
                .map_err(|e| anyhow!("Invalid signature from RPC: {}", s.signature).context(e))
        })
        .collect::<Result<Vec<_>>>()
}

async fn fetch_recent_sponsor_transactions(
    sponsor_pubkey: &solana_pubkey::Pubkey,
    number: usize,
    rpc_client: &RpcClient,
    rpc_limiter: &RpcRateLimiter,
) -> Result<Vec<VersionedTransaction>> {
    let signatures_to_fetch =
        fetch_recent_sponsor_signatures(sponsor_pubkey, number, rpc_client, rpc_limiter).await?;
    let transaction_futures = signatures_to_fetch
        .into_iter()
        .map(|signature| fetch_transaction_from_rpc(signature, rpc_client, rpc_limiter));
    let results = futures::future::join_all(transaction_futures).await;

    results.into_iter().collect::<Result<Vec<_>, _>>()
}

async fn get_matching_variations<'a>(
    transaction: &VersionedTransaction,
    domain: &str,
    tx_variations: &'a HashMap<String, ParsedTransactionVariation>,
    chain_index: &ChainIndex,
    contextual_keys_cache: &ContextualKeysCache,
    show_validation_details: bool,
) -> Result<Vec<&'a ParsedTransactionVariation>> {
    let mut matching_variations = Vec::new();

    let contextual_keys = contextual_keys_cache.get(domain).await?;
    for variation in tx_variations.values() {
        let matches = if let Ok(paymaster_transaction) =
            TransactionToValidate::parse(transaction, chain_index, &HashMap::new()).await
        {
            match variation {
                ParsedTransactionVariation::V0(v0_variation) => {
                    let validation = v0_variation.validate_transaction(&paymaster_transaction);
                    if show_validation_details {
                        match validation {
                            Ok(()) => println!(
                                "Validation against v0 variation {}: ✅",
                                v0_variation.name
                            ),
                            Err((status_code, ref details)) => println!(
                                "Validation against v0 variation {}: ❌ ({}) {}",
                                v0_variation.name, status_code, details
                            ),
                        }
                    }
                    validation.is_ok()
                }
                ParsedTransactionVariation::V1(v1_variation) => {
                    let validation_compute_units =
                        v1_variation.validate_compute_units(&paymaster_transaction);
                    let validation_instruction_constraints = v1_variation
                        .validate_instruction_constraints(
                            &paymaster_transaction,
                            &contextual_keys,
                            chain_index,
                        )
                        .await;
                    if show_validation_details {
                        match (&validation_compute_units, &validation_instruction_constraints) {
                            (Err((status_code, ref details_cu)), Ok(())) => println!("Validation against v1 variation {}: ❌ (Compute Units: {}) {}", v1_variation.name, status_code, details_cu),
                            (Ok(()), Err((status_code, ref details_ic))) => println!("Validation against v1 variation {}: ❌ (Instruction Constraints: {}) {}", v1_variation.name, status_code, details_ic),
                            (Err((status_code_cu, ref details_cu)), Err((status_code_ic, ref details_ic))) => println!("Validation against v1 variation {}: ❌ \n -(Compute Units: {}) {} \n -(Instruction Constraints: {}) {}", v1_variation.name, status_code_cu, details_cu, status_code_ic, details_ic),
                            _ => println!("Validation against v1 variation {}: ✅", v1_variation.name),
                        }
                    }
                    validation_compute_units.is_ok() && validation_instruction_constraints.is_ok()
                } // TODO: make the tx validator fetch the paymaster fee coefficients so we can use validate_transaction here
            }
        } else {
            false
        };

        if matches {
            matching_variations.push(variation);
        }
    }

    Ok(matching_variations)
}

async fn fetch_sponsor_pubkey(domain: &str, network: Network) -> Result<Pubkey> {
    let url = format!(
        "{}/api/sponsor_pubkey?domain={domain}",
        network.paymaster_base_url()
    );
    let client = reqwest::Client::new();
    let response =
        client.get(&url).send().await.with_context(|| {
            format!("Failed to fetch sponsor pubkey from API for domain: {domain}")
        })?;

    if !response.status().is_success() {
        return Err(anyhow!(
            "API returned error status {} when fetching sponsor pubkey for domain: {domain}",
            response.status()
        ));
    }

    let sponsor_str = response
        .text()
        .await
        .with_context(|| format!("Failed to read response body for domain: {domain}"))?;

    solana_pubkey::Pubkey::from_str(sponsor_str.trim()).with_context(|| {
        format!("Failed to parse sponsor pubkey from API response for domain: {domain}")
    })
}

struct ContextualKeysCache {
    pub cache: DashMap<String, ContextualDomainKeys>,
    pub network: Network,
    /// If this is Some, the sponsor pubkey won't be fetched from the paymaster server and the inner pubkey will be used instead. This is useful for apps whose domain is not registered with the paymaster server, so they don't have a sponsor wallet.
    pub sponsor_override: Option<Pubkey>,
}

impl ContextualKeysCache {
    pub async fn new(
        domains: &Domains,
        network: Network,
        sponsor_override: Option<Pubkey>,
    ) -> Result<Self> {
        Ok(Self {
            cache: futures::future::try_join_all(domains.keys().map(|domain| async {
                let keys = compute_contextual_keys(domain, network, sponsor_override).await?;
                Ok::<_, anyhow::Error>((domain.clone(), keys))
            }))
            .await?
            .into_iter()
            .collect(),
            network,
            sponsor_override,
        })
    }

    pub async fn get(&self, domain: &str) -> Result<ContextualDomainKeys> {
        if let Some(keys) = self.cache.get(domain) {
            Ok(keys.clone())
        } else {
            let keys = compute_contextual_keys(domain, self.network, self.sponsor_override).await?;
            self.cache.insert(domain.to_string(), keys.clone());
            Ok(keys)
        }
    }
}

async fn compute_contextual_keys(
    domain: &str,
    network: Network,
    sponsor_override: Option<Pubkey>,
) -> Result<ContextualDomainKeys> {
    let sponsor = if let Some(sponsor) = sponsor_override {
        sponsor
    } else {
        fetch_sponsor_pubkey(domain, network).await?
    };

    Ok(ContextualDomainKeys {
        domain_registry: get_domain_record_address(domain),
        sponsor,
    })
}