# Install using pip install "x402[httpx,svm]>=2.29,<2.30" # Run without --pay-to to review the live quote. --input FILE supplies your own JSON. import argparse import asyncio import json import os import sys from pathlib import Path import httpx from solders.pubkey import Pubkey from x402 import x402Client from x402.http import x402HTTPClient from x402.mechanisms.svm import KeypairSigner from x402.mechanisms.svm.exact import ExactSvmScheme from x402.schemas import PaymentRequired ENDPOINT = 'https://apiacre.com/v1/research/crossref-doi-metadata' SOLANA = 'solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp' USDC = 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v' PRICE_USDC = '0.003' ATOMIC_AMOUNT = '3000' USER_AGENT = 'APIAcre-x402-Python/1' REQUEST = {'doi': '10.1038/s41586-021-03819-2'} def read_request(path: str) -> dict[str, object]: try: text = sys.stdin.read() if path == "-" else Path(path).read_text(encoding="utf-8") data = json.loads(text) if not isinstance(data, dict): raise ValueError("the top-level value must be an object") json.dumps(data, allow_nan=False, ensure_ascii=False).encode("utf-8") except (OSError, ValueError, RecursionError) as error: raise argparse.ArgumentTypeError(f"expected a JSON request object: {error}") from error return data async def main(pay_to: str | None, request: dict[str, object] | None = None) -> None: body = REQUEST if request is None else request client = x402Client() protocol = x402HTTPClient(client) async with httpx.AsyncClient( follow_redirects=False, timeout=20, headers={"User-Agent": USER_AGENT} ) as http: response = await http.post(ENDPOINT, json=body) if response.status_code != 402: raise RuntimeError(f"Expected an unpaid quote, got HTTP {response.status_code}") if "payment-response" in response.headers: raise RuntimeError("The unpaid response unexpectedly included a settlement receipt") quote = protocol.get_payment_required_response(response.headers.get) if not isinstance(quote, PaymentRequired) or quote.x402_version != 2: raise RuntimeError("Expected an x402 v2 quote") if quote.resource is None or quote.resource.url != ENDPOINT: raise RuntimeError("The quote identifies a different resource") options = [ option for option in quote.accepts if option.network == SOLANA and option.scheme == "exact" and option.asset == USDC and option.amount == ATOMIC_AMOUNT ] if len(options) != 1: raise RuntimeError(f"Expected one Solana quote for {PRICE_USDC} USDC") option = options[0] try: Pubkey.from_string(option.pay_to) except ValueError as error: raise RuntimeError("The quote identifies an invalid Solana recipient") from error if pay_to is None: print(json.dumps({ "endpoint": ENDPOINT, "network": SOLANA, "asset": USDC, "recipient": option.pay_to, "priceUsdc": PRICE_USDC, }, indent=2)) return if pay_to != option.pay_to: raise RuntimeError("The live recipient differs from the address you approved") signer = KeypairSigner.from_base58(os.environ["SVM_PRIVATE_KEY"]) client.register(SOLANA, ExactSvmScheme(signer)) client.set_spend_controls({"max_amount_per_payment": f"${PRICE_USDC}"}) selected = quote.model_copy(update={"accepts": [option]}) payload = await client.create_payment_payload(selected) response = await http.post( ENDPOINT, json=body, headers=protocol.encode_payment_signature_header(payload), ) response.raise_for_status() receipt = protocol.get_payment_settle_response(response.headers.get) if not receipt.success or receipt.network != SOLANA or not receipt.transaction: raise RuntimeError("The response did not confirm settlement on Solana") if receipt.amount is not None and receipt.amount != ATOMIC_AMOUNT: raise RuntimeError("The receipt amount differs from the approved quote") print(response.json()) print(receipt) if __name__ == "__main__": parser = argparse.ArgumentParser(description="Try an API Acre service on Solana", allow_abbrev=False) parser.add_argument( "--input", metavar="FILE", type=read_request, help="Read a JSON request object from FILE or - for stdin" ) parser.add_argument( "--pay-to", action="append", metavar="RECIPIENT", help=f"Authorize {PRICE_USDC} USDC to this recipient" ) args = parser.parse_args() recipients = args.pay_to or [] if len(recipients) > 1: parser.error("Pass --pay-to once with the quoted Solana address") asyncio.run(main(recipients[0] if recipients else None, args.input))