#!/usr/bin/env python3 """x402 Buyer Quickstart — Pay $0.01 for crypto price data Prerequisites: pip install x402 httpx eth-account export PRIVATE_KEY=0x... # your Base mainnet wallet key (must hold USDC) API: https://x402.167-172-95-184.nip.io/price Cost: $0.01 USDC per call (Base mainnet, chain ID 8453) Facilitator: https://api.cdp.coinbase.com/platform/v2/x402 (CDP, x402scan-indexed) Pay to: 0x68614873C5d624c07DCAA3aFF5243DD5027c3910 Asset: USDC on Base (0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913) """ import os, json from eth_account import Account from x402.mechanisms.evm import EthAccountSigner from x402.mechanisms.evm.exact import register_exact_evm_client from x402.client import x402ClientSync from x402.http import x402HTTPClientSync import httpx API_URL = 'https://x402.167-172-95-184.nip.io/price' def main(): pk = os.environ.get('PRIVATE_KEY', '') if not pk: print('ERROR: Set PRIVATE_KEY env var to your EVM private key') return if not pk.startswith('0x'): pk = '0x' + pk account = Account.from_key(pk) print(f'Payer: {account.address}') print(f'Paying $0.01 USDC on Base for crypto prices...') signer = EthAccountSigner(account) client = x402ClientSync() register_exact_evm_client(client, signer) http_client = x402HTTPClientSync(client) # Step 1: Get 402 payment challenge r = httpx.get(API_URL, timeout=15) print(f'Initial request: HTTP {r.status_code}') if r.status_code != 402: print(f'Expected 402, got {r.status_code}: {r.text[:200]}') return # Step 2: Parse payment requirements and sign payment_headers, payload = http_client.handle_402_response(dict(r.headers), r.content) print(f'Payment signed for {payload.amount} {payload.asset}') # Step 3: Retry with payment r2 = httpx.get(API_URL, headers=dict(payment_headers), timeout=30) print(f'Paid request: HTTP {r2.status_code}') if r2.status_code == 200: data = r2.json() print(f'\nāœ… Payment settled! Received:') print(json.dumps(data, indent=2)) else: print(f'Payment failed: {r2.text[:300]}') if __name__ == '__main__': main()