|
| 1 | +""" |
| 2 | +Test /acp-budget with dynamic pricing via X-Budget header. |
| 3 | +
|
| 4 | +Usage: |
| 5 | + uv run python test_budget.py |
| 6 | +""" |
| 7 | + |
| 8 | +import os |
| 9 | +import asyncio |
| 10 | +from dotenv import load_dotenv |
| 11 | +from eth_account import Account |
| 12 | +from x402.clients.httpx import x402HttpxClient |
| 13 | +from x402.clients.base import decode_x_payment_response |
| 14 | + |
| 15 | +load_dotenv() |
| 16 | + |
| 17 | +private_key = os.getenv("PRIVATE_KEY") |
| 18 | +base_url = os.getenv("RESOURCE_SERVER_URL", "http://localhost:4021") |
| 19 | + |
| 20 | +if not private_key: |
| 21 | + print("Error: PRIVATE_KEY not set") |
| 22 | + exit(1) |
| 23 | + |
| 24 | +account = Account.from_key(private_key) |
| 25 | +print(f"Account: {account.address}\n") |
| 26 | + |
| 27 | + |
| 28 | +async def test_with_budget(budget: str): |
| 29 | + """Test endpoint with specific budget.""" |
| 30 | + print(f"{'='*60}") |
| 31 | + print(f"Testing with budget: {budget}") |
| 32 | + print(f"{'='*60}") |
| 33 | + |
| 34 | + # x402HttpxClient automatically handles payment flow |
| 35 | + async with x402HttpxClient( |
| 36 | + account=account, |
| 37 | + base_url=base_url, |
| 38 | + ) as client: |
| 39 | + # Add X-Budget header to the request |
| 40 | + response = await client.get( |
| 41 | + "/acp-budget", |
| 42 | + headers={"X-Budget": budget} # ⭐ Dynamic pricing |
| 43 | + ) |
| 44 | + |
| 45 | + content = await response.aread() |
| 46 | + print(f"✅ Response: {content.decode()}") |
| 47 | + |
| 48 | + if "X-PAYMENT-RESPONSE" in response.headers: |
| 49 | + payment_resp = decode_x_payment_response( |
| 50 | + response.headers["X-PAYMENT-RESPONSE"] |
| 51 | + ) |
| 52 | + print(f"🧾 TX: {payment_resp.get('transaction', 'N/A')}\n") |
| 53 | + |
| 54 | + |
| 55 | +async def main(): |
| 56 | + """Run tests with different budgets.""" |
| 57 | + # await test_with_budget("$0.001") |
| 58 | + await test_with_budget("$0.01") |
| 59 | + # await test_with_budget("$0.05") |
| 60 | + |
| 61 | + |
| 62 | +if __name__ == "__main__": |
| 63 | + asyncio.run(main()) |
| 64 | + |
0 commit comments