import base64, json, os, time
import httpx
from eth_account import Account
from eth_account.messages import encode_typed_data
URL = ("https://zcjbtpxuhdekpwcxmepn.supabase.co/functions/v1/silo-api/v2/prices"
"?id=PETR4&from=2026-01-01&to=2026-06-30")
acct = Account.from_key(os.environ["BUYER_PRIVATE_KEY"])
first = httpx.get(URL)
assert first.status_code == 402, first.text
req = json.loads(base64.b64decode(first.headers["payment-required"]))
a = req["accepts"][0]
now = int(time.time())
auth = {"from": acct.address, "to": a["payTo"], "value": a["amount"],
"validAfter": str(now - 600), "validBefore": str(now + a["maxTimeoutSeconds"]),
"nonce": "0x" + os.urandom(32).hex()}
typed = {
"types": {
"EIP712Domain": [{"name": "name", "type": "string"}, {"name": "version", "type": "string"},
{"name": "chainId", "type": "uint256"}, {"name": "verifyingContract", "type": "address"}],
"TransferWithAuthorization": [{"name": "from", "type": "address"}, {"name": "to", "type": "address"},
{"name": "value", "type": "uint256"}, {"name": "validAfter", "type": "uint256"},
{"name": "validBefore", "type": "uint256"}, {"name": "nonce", "type": "bytes32"}],
},
"primaryType": "TransferWithAuthorization",
"domain": {"name": a["extra"]["name"], "version": a["extra"]["version"],
"chainId": int(a["network"].split(":")[1]), "verifyingContract": a["asset"]},
"message": {**auth, "value": int(auth["value"]), "validAfter": int(auth["validAfter"]),
"validBefore": int(auth["validBefore"]), "nonce": bytes.fromhex(auth["nonce"][2:])},
}
sig = "0x" + acct.sign_message(encode_typed_data(full_message=typed)).signature.hex().removeprefix("0x")
payment = {"x402Version": 2, "accepted": a, "payload": {"signature": sig, "authorization": auth}}
paid = httpx.get(URL, headers={"PAYMENT-SIGNATURE": base64.b64encode(json.dumps(payment).encode()).decode()},
timeout=90)
body = paid.json()
print(paid.status_code, body["meta"]["tier"], body["meta"]["payment"], len(body["data"]))
print(json.loads(base64.b64decode(paid.headers["payment-response"])))