importorg.p2p.solanaj.core.Account;// For development: generate a new accountAccountaccount=newAccount();System.out.println("Public Key: "+account.getPublicKey());System.out.println("Secret Key (save this!): "+java.util.Base64.getEncoder().encodeToString(account.getSecretKey()));
// Load from environment variableStringkeyEnv=System.getenv("SOLANA_SECRET_KEY");byte[]secretKey=java.util.Base64.getDecoder().decode(keyEnv);Accountaccount=newAccount(secretKey);
importorg.openlibx402.client.X402AutoClient;importokhttp3.Response;// Create client with automatic payment handlingX402AutoClientclient=newX402AutoClient.Builder(account).rpcUrl("https://api.devnet.solana.com").maxPaymentAmount("1.0")// Max 1 USDC per request.maxRetries(3)// Retry up to 3 times.allowLocal(true)// Development only.build();try{// Automatically handles 402 and retries with paymentResponseresponse=client.get("https://api.example.com/premium-data");System.out.println(response.body().string());}finally{client.close();}
packagecom.example;importorg.openlibx402.client.X402AutoClient;importorg.openlibx402.core.errors.*;importorg.p2p.solanaj.core.Account;importokhttp3.Response;publicclassQuickStart{publicstaticvoidmain(String[]args){// Load or create accountAccountaccount=getAccount();// Create auto clienttry(X402AutoClientclient=newX402AutoClient.Builder(account).rpcUrl("https://api.devnet.solana.com").maxPaymentAmount("1.0").maxRetries(3).allowLocal(true)// Development only.build()){// Make payment-enabled requestStringurl="https://api.example.com/premium-data";Responseresponse=client.get(url);// Process responseStringdata=response.body().string();System.out.println("Success! Data: "+data);}catch(InsufficientFundsErrore){System.err.println("Insufficient funds!");System.err.println("Please add funds to: "+account.getPublicKey());}catch(PaymentRequiredErrore){System.err.println("Payment required but max retries exceeded");}catch(X402Errore){System.err.println("X402 Error: "+e.getMessage());}catch(Exceptione){e.printStackTrace();}}privatestaticAccountgetAccount(){// Try loading from environmentStringkeyEnv=System.getenv("SOLANA_SECRET_KEY");if(keyEnv!=null){byte[]secretKey=java.util.Base64.getDecoder().decode(keyEnv);returnnewAccount(secretKey);}// Development: generate new accountSystem.out.println("⚠️ Using random account for demo");returnnewAccount();}}