importorg.p2p.solanaj.core.Accountimportjava.util.Base64// For development: generate a new accountvalaccount=Account()println("Public Key: ${account.publicKey}")println("Secret Key (save this!): ${Base64.getEncoder().encodeToString(account.secretKey)}")
// Load from environment variablevalkeyString=System.getenv("SOLANA_SECRET_KEY")valsecretKey=Base64.getDecoder().decode(keyString)valaccount=Account(secretKey)
importkotlinx.coroutines.runBlockingimportorg.openlibx402.client.X402AutoClientsuspendfunmain(){// Create client with DSL buildervalclient=X402AutoClient(account){rpcUrl="https://api.devnet.solana.com"maxPaymentAmount="1.0"// Max 1 USDC per requestmaxRetries=2// Retry up to 2 timesallowLocal=true// Development only}client.use{// Automatically handles 402 and retries with paymentvalresponse=it.get("https://api.example.com/premium-data")println(response.body?.string())}}// For gradle run compatibilityfunmain()=runBlocking{main()}
packagecom.exampleimportkotlinx.coroutines.runBlockingimportorg.openlibx402.client.X402AutoClientimportorg.openlibx402.core.errors.X402Errorimportorg.p2p.solanaj.core.Accountimportjava.util.Base64suspendfunmain(){// Load or create accountvalaccount=getAccount()// Create auto client with DSLvalclient=X402AutoClient(account){rpcUrl="https://api.devnet.solana.com"maxPaymentAmount="1.0"maxRetries=2allowLocal=true// Development only}client.use{try{// Make payment-enabled request (suspend function)valurl="https://api.example.com/premium-data"valresponse=it.get(url)// Process responsevaldata=response.body?.string()println("Success! Data: $data")}catch(e:X402Error){when(e){isX402Error.InsufficientFunds->{println("Insufficient funds!")println("Please add funds to: ${account.publicKey}")}isX402Error.PaymentRequired->{println("Payment required but max retries exceeded")}else->{println("Error: ${e.message}")}}}catch(e:Exception){e.printStackTrace()}}}privatefungetAccount():Account{// Try loading from environmentvalkeyEnv=System.getenv("SOLANA_SECRET_KEY")if(keyEnv!=null){valsecretKey=Base64.getDecoder().decode(keyEnv)returnAccount(secretKey)}// Development: generate new accountprintln("Warning: Using random account for demo")returnAccount()}// For gradle run compatibilityfunmain()=runBlocking{main()}
importkotlinx.coroutines.*classPaymentService{privatevalscope=CoroutineScope(Dispatchers.IO+SupervisorJob())funmakeRequest(url:String){scope.launch{client.use{valresponse=it.get(url)// Process response}}}funshutdown(){scope.cancel()}}
Explore Basic Usage Examples for:
- Advanced error handling with when expressions
- Concurrent requests with coroutines
- Custom HTTP configuration
- Flow-based streaming
- Data class features
Read the Client Library Reference for:
- Complete API documentation
- All available methods with suspend functions
- DSL builder options
- Coroutine best practices
See Error Handling Guide for:
- Comprehensive sealed class error handling
- Production deployment with coroutines
- Security considerations
- Monitoring and logging
// Main functionfunmain()=runBlocking{client.get(url)// Now works}// Or use CoroutineScopevalscope=CoroutineScope(Dispatchers.IO)scope.launch{client.get(url)}