# Install using pip install "x402[httpx,evm]>=2.29,<2.30" # Run without --pay-to for an unpaid quote. --input FILE supplies your own JSON. import argparse import asyncio import json import os import re import sys from pathlib import Path 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 ENDPOINT = "https://apiacre.com/v1/data/place-geocode" NETWORK = "eip155:8453" USDC = "0x833589fcd6edb6e08f4c7c32d4f71b54bda02913" AMOUNT = "2000" PRICE_USDC = "0.002" USER_AGENT = 'APIAcre-x402-Python/1' REQUEST = {'place': 'London, GB', 'limit': 5} 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 ADDRESS = re.compile(r"0x[0-9a-fA-F]{40}") 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 == 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 is None: result = { "endpoint": ENDPOINT, "network": NETWORK, "asset": USDC, "recipient": option.pay_to, "priceUsdc": PRICE_USDC, } if request is None: result["request"] = REQUEST print(json.dumps(result, indent=2)) return 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, 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 != 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") print(response.json()) 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))