#!/usr/bin/env python3 """Quote or buy one report service request, and install solders to sign a payment.""" import argparse from decimal import Decimal, InvalidOperation from pathlib import Path import base64 import json import os import struct import sys import urllib.error import urllib.request PAY_TO = '9HkwyUhDMyjbpSpnyu5xuZ9vRaFQeajnJsavhie7XcsT' # the address the service is paid at; a run is never paid to another one unless you say so USDC = 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v' SOLANA_MAINNET = 'solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp' RPC = 'https://api.mainnet-beta.solana.com' class NoRedirect(urllib.request.HTTPRedirectHandler): def redirect_request(self, req, fp, code, msg, headers, newurl): return None def spending_limit(value): try: amount = Decimal(value) if amount.is_finite() and amount >= 0: return amount except InvalidOperation: pass raise argparse.ArgumentTypeError("Give a finite spending limit of zero or more USDC.") def post(url, body, headers=None, timeout=30): req = urllib.request.Request(url, data=body, headers=dict({'Content-Type': 'application/json', 'Accept': 'application/json', 'User-Agent': 'x402-buy/1'}, **(headers or {}))) try: with urllib.request.build_opener(NoRedirect()).open(req, timeout=timeout) as r: return r.status, dict(r.headers), r.read() except urllib.error.HTTPError as e: return e.code, dict(e.headers), e.read() def header(headers, name): return next((v for k, v in headers.items() if k.lower() == name), None) def keypair(path): from solders.keypair import Keypair return Keypair.from_bytes(bytes(json.loads(Path(path).expanduser().read_bytes()))) def recent_blockhash(rpc): body = json.dumps({'jsonrpc': '2.0', 'id': 1, 'method': 'getLatestBlockhash', 'params': [{'commitment': 'confirmed'}]}).encode() status, _, raw = post(rpc, body, timeout=25) if status != 200: sys.exit(f"The blockhash request returned HTTP {status}, so the purchase could not be signed.") return json.loads(raw)['result']['value']['blockhash'] def signed_payment(kp, terms, accept, blockhash): """The header PAYMENT-SIGNATURE: one USDC transfer of exactly the named amount, signed by the wallet and left for the service's fee payer to sign and send.""" from solders.hash import Hash from solders.instruction import AccountMeta, Instruction from solders.message import MessageV0, to_bytes_versioned from solders.pubkey import Pubkey from solders.signature import Signature from solders.transaction import VersionedTransaction token = Pubkey.from_string('TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA') ata_program = Pubkey.from_string('ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL') budget = Pubkey.from_string('ComputeBudget111111111111111111111111111111') memo = Pubkey.from_string('MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr') mint, pay_to, fee_payer = Pubkey.from_string(accept['asset']), Pubkey.from_string(accept['payTo']), Pubkey.from_string(accept['extra']['feePayer']) payer = kp.pubkey() def account(owner): return Pubkey.find_program_address([bytes(owner), bytes(token), bytes(mint)], ata_program)[0] instructions = [ Instruction(budget, bytes([2]) + struct.pack(' args.max_usdc: sys.exit('The payee or amount exceeds the permission you gave for this purchase.') if not args.keypair: parser.error('Supply --keypair to sign or use --quote to inspect the terms.') headers['PAYMENT-SIGNATURE'] = signed_payment(keypair(args.keypair), terms, accepted, recent_blockhash(args.rpc)) try: status, response, raw = post(args.url, body, headers) except OSError: sys.exit('The signed request lost its reply, so check the transfer before attempting another purchase.') receipt = header(response, 'payment-response') print(raw.decode(errors='replace')) settlement = json.loads(base64.b64decode(receipt)) if receipt else {} print(json.dumps(settlement, indent=2)) if status != 200 or settlement.get('success') is not True: sys.exit(f'The service returned HTTP {status}, so check your order before paying again.') if __name__ == '__main__': main()