usesolana_sdk::signature::{read_keypair_file,Keypair};usestd::error::Error;fnload_keypair()->Result<Keypair,Box<dynError>>{// Load from fileletkeypair=read_keypair_file(std::env::var("SOLANA_KEYPAIR").unwrap_or_else(|_|{format!("{}/.config/solana/id.json",std::env::var("HOME").unwrap())}))?;Ok(keypair)}
useopenlibx402_client::{X402AutoClient,AutoClientOptions};#[tokio::main]asyncfnmain()->Result<(),Box<dynstd::error::Error>>{// Load your Solana keypairletkeypair=load_keypair()?;// Configure auto clientletoptions=AutoClientOptions{max_payment_amount:"5.0".to_string(),// Max $5 per requestauto_retry:true,max_retries:3,};// Create clientletclient=X402AutoClient::new(keypair,None,Some(options));// Make request - payment handled automatically!letresponse=client.get("http://localhost:8000/premium").await?;letbody=response.text().await?;println!("Response: {}",body);Ok(())}
The client will automatically:
1. Make initial request
2. Detect 402 response
3. Create and send payment
4. Retry with payment authorization
5. Return the data
letoptions=AutoClientOptions{max_payment_amount:"10.0".to_string(),// Maximum amount to payauto_retry:true,// Automatically retry after paymentmax_retries:3,// Maximum retry attempts};
usestd::env;fnload_keypair()->Result<Keypair,Box<dynError>>{letpath=env::var("SOLANA_KEYPAIR").or_else(|_|env::var("HOME").map(|h|format!("{}/.config/solana/id.json",h)))?;read_keypair_file(path).map_err(|e|format!("Failed to load keypair: {}",e).into())}
asyncfnfetch_premium_data(client:&X402AutoClient)->Result<String,Box<dynError>>{matchclient.get("http://localhost:8000/premium").await{Ok(response)=>{ifresponse.status().is_success(){Ok(response.text().await?)}else{Err(format!("HTTP error: {}",response.status()).into())}}Err(X402Error::InsufficientFunds(_))=>{Err("Not enough USDC in wallet".into())}Err(X402Error::PaymentExpired(_))=>{// Retry with new payment requestclient.get("http://localhost:8000/premium").await?.text().await.map_err(Into::into)}Err(e)=>Err(e.into()),}}
#[cfg(test)]modtests{usesuper::*;#[tokio::test]asyncfntest_client(){// Use test server without payment requirementsletclient=X402AutoClient::new(Keypair::new(),None,None);letresponse=client.get("http://localhost:8000/free-endpoint").await.unwrap();assert!(response.status().is_success());}}