Skip to main content

x402_sdk/verifier/
mod.rs

1use crate::types::{ChainType, PaymentRequest, PaymentVerification};
2use async_trait::async_trait;
3use std::collections::HashMap;
4
5pub mod evm;
6pub mod solana;
7
8#[derive(Debug)]
9pub enum VerificationError {
10    NetworkError(String),
11    InvalidAddress,
12    ChainNotSupported,
13    RpcError(String),
14    TransactionNotFound,
15    InsufficientAmount,
16    InvalidCurrency,
17    Timeout,
18    ParseError(String),
19    Error(String),
20}
21
22impl std::fmt::Display for VerificationError {
23    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
24        match self {
25            Self::NetworkError(msg) => write!(f, "Network error: {}", msg),
26            Self::InvalidAddress => write!(f, "Invalid address"),
27            Self::ChainNotSupported => write!(f, "Chain not supported"),
28            Self::RpcError(msg) => write!(f, "RPC error: {}", msg),
29            Self::TransactionNotFound => write!(f, "Transaction not found"),
30            Self::InsufficientAmount => write!(f, "Insufficient payment amount"),
31            Self::InvalidCurrency => write!(f, "Invalid currency"),
32            Self::Timeout => write!(f, "Verification timeout"),
33            Self::ParseError(msg) => write!(f, "Parse error: {}", msg),
34            Self::Error(msg) => write!(f, "Error: {}", msg),
35        }
36    }
37}
38
39impl std::error::Error for VerificationError {}
40
41#[async_trait]
42pub trait PaymentVerifier: Send + Sync {
43    async fn verify_payment(
44        &self,
45        payment_request: &PaymentRequest,
46        payer_address: &str,
47    ) -> Result<PaymentVerification, VerificationError>;
48
49    fn supports_chain(&self, chain_type: &ChainType) -> bool;
50}
51
52pub struct VerifierRegistry {
53    verifiers: HashMap<ChainType, Box<dyn PaymentVerifier>>,
54}
55
56impl VerifierRegistry {
57    pub fn new() -> Self {
58        Self {
59            verifiers: HashMap::new(),
60        }
61    }
62
63    pub fn register_verifier(&mut self, chain_type: ChainType, verifier: Box<dyn PaymentVerifier>) {
64        self.verifiers.insert(chain_type, verifier);
65    }
66
67    pub fn get_verifier(&self, chain_type: &ChainType) -> Option<&dyn PaymentVerifier> {
68        self.verifiers.get(chain_type).map(|v| v.as_ref())
69    }
70
71    pub fn has_verifier(&self, chain_type: &ChainType) -> bool {
72        self.verifiers.contains_key(chain_type)
73    }
74
75    pub fn supported_chains(&self) -> Vec<ChainType> {
76        self.verifiers.keys().cloned().collect()
77    }
78
79    pub fn remove_verifier(&mut self, chain_type: &ChainType) -> Option<Box<dyn PaymentVerifier>> {
80        self.verifiers.remove(chain_type)
81    }
82}
83
84impl Default for VerifierRegistry {
85    fn default() -> Self {
86        Self::new()
87    }
88}