# For an authorized purchase: pip install "x402[httpx,svm]>=2.29,<2.30" # Run without --pay-to for an unpaid quote using only Python. # Run --help for available options. The SDK is needed for an authorized purchase. import argparse import asyncio import base64 import json import sys from collections.abc import Callable from pathlib import Path from urllib.error import HTTPError from urllib.request import HTTPRedirectHandler, Request, build_opener ENDPOINT = 'https://apiacre.com/v1/research/crossref-work-search' SOLANA = 'solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp' USDC = 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v' PRICE_USDC = '0.008' ATOMIC_AMOUNT = '8000' USER_AGENT = 'APIAcre-x402-Python/1' REQUEST_LOCKED = False REQUEST = {'query': 'agentic commerce payment protocols', 'max_results': 5, 'work_type': 'journal-article', 'sort_by': 'relevance'} def read_request(path: str) -> bytes: try: if path == "-": body = sys.stdin.buffer.read() if hasattr(sys.stdin, "buffer") else sys.stdin.read().encode("utf-8") else: body = Path(path).read_bytes() data = json.loads(body.decode("utf-8")) 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 body class NoRedirect(HTTPRedirectHandler): def redirect_request(self, request, fp, code, message, headers, new_url): return None def quote_recipient( body: bytes, *, network: str, amount: str, label: str, valid_recipient: Callable[[object], bool], case_insensitive_asset: bool = False, ) -> str: request = Request( ENDPOINT, data=body, headers={"Content-Type": "application/json", "User-Agent": USER_AGENT}, method="POST", ) try: with build_opener(NoRedirect()).open(request, timeout=20) as response: raise RuntimeError(f"Expected an unpaid quote, got HTTP {response.status}") except HTTPError as response: with response: if response.code != 402: raise RuntimeError(f"Expected an unpaid quote, got HTTP {response.code}") from response if "PAYMENT-RESPONSE" in response.headers: raise RuntimeError("The unpaid response unexpectedly included a settlement receipt") required = response.headers.get_all("PAYMENT-REQUIRED", []) if len(required) != 1: raise RuntimeError("Expected one PAYMENT-REQUIRED header") try: quote = json.loads(base64.b64decode(required[0], validate=True)) except ValueError as error: raise RuntimeError("The payment challenge did not contain a valid quote") from error if not isinstance(quote, dict) or type(quote.get("x402Version")) is not int or quote["x402Version"] != 2: raise RuntimeError("Expected an x402 v2 quote") resource = quote.get("resource") if not isinstance(resource, dict) or resource.get("url") != ENDPOINT: raise RuntimeError("The quote identifies a different resource") offers = quote.get("accepts") if not isinstance(offers, list) or any(not isinstance(offer, dict) for offer in offers): raise RuntimeError("The quote is missing its payment terms") matches = [] for offer in offers: asset = offer.get("asset") if case_insensitive_asset and isinstance(asset, str): asset = asset.lower() if ( offer.get("network") == network and offer.get("scheme") == "exact" and asset == USDC and offer.get("amount") == amount ): matches.append(offer) if len(matches) != 1: raise RuntimeError(f"Expected one {label} quote for {PRICE_USDC} USDC") offer = matches[0] recipient = offer.get("payTo") timeout = offer.get("maxTimeoutSeconds") if not isinstance(recipient, str) or not valid_recipient(recipient): raise RuntimeError(f"The quote identifies an invalid {label} recipient") if type(timeout) is not int or timeout <= 0: raise RuntimeError("The quote has an invalid payment timeout") return recipient BASE58_DIGITS = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz" def is_solana_recipient(value: object) -> bool: if not isinstance(value, str) or not 32 <= len(value) <= 44: return False integer = 0 try: for digit in value: integer = integer * 58 + BASE58_DIGITS.index(digit) except ValueError: return False leading_zeroes = len(value) - len(value.lstrip("1")) return leading_zeroes + (integer.bit_length() + 7) // 8 == 32 async def main(pay_to: str | None, request: bytes | None = None) -> None: body = json.dumps(REQUEST, allow_nan=False).encode("utf-8") if request is None else request if pay_to is None: recipient = await asyncio.to_thread( quote_recipient, body, network=SOLANA, amount=ATOMIC_AMOUNT, label="Solana", valid_recipient=is_solana_recipient, ) print(json.dumps({ "endpoint": ENDPOINT, "network": SOLANA, "asset": USDC, "recipient": recipient, "priceUsdc": PRICE_USDC, }, indent=2)) return import os 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 client = x402Client() protocol = x402HTTPClient(client) async with httpx.AsyncClient( follow_redirects=False, timeout=20, headers={"Content-Type": "application/json", "User-Agent": USER_AGENT}, ) as http: response = await http.post(ENDPOINT, content=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 != 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, content=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") response_text = response.content.decode("utf-8") json.loads(response_text) print(response_text) print(receipt) if __name__ == "__main__": parser = argparse.ArgumentParser(description="Try an API Acre service on Solana", allow_abbrev=False) if not REQUEST_LOCKED: parser.add_argument( "--input", metavar="FILE", type=read_request, help="Read a JSON request object from FILE or - for stdin" ) parser.set_defaults(input=None) 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))