# For an authorized purchase: pip install "x402[httpx,evm]>=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/wikidata-organization-search" NETWORK = "eip155:8453" USDC = "0x833589fcd6edb6e08f4c7c32d4f71b54bda02913" AMOUNT = "15000" PRICE_USDC = "0.015" USER_AGENT = 'APIAcre-x402-Python/1' REQUEST = {'organization_name': 'OpenAI', 'language': 'en', 'max_results': 5} 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 import re ADDRESS = re.compile(r"0x[0-9a-fA-F]{40}") 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=NETWORK, amount=AMOUNT, label="Base", valid_recipient=lambda value: isinstance(value, str) and ADDRESS.fullmatch(value) is not None, case_insensitive_asset=True, ) result = { "endpoint": ENDPOINT, "network": NETWORK, "asset": USDC, "recipient": recipient, "priceUsdc": PRICE_USDC, } if request is None: result["request"] = REQUEST print(json.dumps(result, indent=2)) return import os import httpx from eth_account import Account from x402 import x402Client from x402.http import x402HTTPClient from x402.mechanisms.evm import EthAccountSigner from x402.mechanisms.evm.exact.client import ExactEvmScheme 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 == NETWORK and option.scheme == "exact" and option.asset.lower() == USDC and option.amount == AMOUNT ] if len(options) != 1 or ADDRESS.fullmatch(options[0].pay_to) is None: raise RuntimeError(f"Expected one Base quote for {PRICE_USDC} USDC and a valid recipient") option = options[0] if pay_to.lower() != option.pay_to.lower(): raise RuntimeError("The live recipient differs from the address you approved") signer = EthAccountSigner(Account.from_key(os.environ["EVM_PRIVATE_KEY"])) client.register(NETWORK, ExactEvmScheme(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 != NETWORK or not receipt.transaction: raise RuntimeError("The response did not confirm settlement on Base") if receipt.amount is not None and receipt.amount != 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 Base", 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 recipients and (len(recipients) != 1 or ADDRESS.fullmatch(recipients[0]) is None): parser.error("Pass --pay-to with one valid EVM address") asyncio.run(main(recipients[0] if recipients else None, args.input))