import os, json, requests
from eth_account import Account
from x402.clients.requests import x402_requests
from anchorbrowser import Anchorbrowser
ENDPOINT = "https://api.anchorbrowser.io/v1/sessions"
BODY = {}
key = os.getenv("PRIVATE_KEY") or exit("Set PRIVATE_KEY=0x...")
# Try to create session normally first
try:
anchor_client = Anchorbrowser(api_key=os.getenv("ANCHOR_API_KEY"))
session = anchor_client.sessions.create()
print(json.dumps(session.data, indent=2))
except Exception as e:
# If we get a 402 error, handle payment
if "402" in str(e):
# Get payment details and process with x402
pre = requests.post(ENDPOINT, json=BODY, timeout=30)
price = int(pre.json()["accepts"][0]["maxAmountRequired"])
res = x402_requests(Account.from_key(key)).post(ENDPOINT, json=BODY, timeout=60)
print(json.dumps(res.json(), indent=2))
else:
raise e