#!/usr/bin/env python3
"""Turn an x402 v2 PAYMENT-REQUIRED header into a PAYMENT-SIGNATURE value (for curl users).

  pip install "x402[evm]" eth-account
  export X402_PRIVATE_KEY=0x...   # Base wallet with USDC
  SIG=$(python3 x402_sign.py "$PAYMENT_REQUIRED_HEADER_VALUE")   # refuses above MAX_USD (default 0.50)

Signs an EIP-3009 USDC authorization for exactly the quoted amount and payTo. Nothing is sent:
the payment only settles when you resend your request with the header.
"""
import os, sys
from eth_account import Account
from x402 import x402ClientSync, max_amount
from x402.http.utils import decode_payment_required_header, encode_payment_signature_header
from x402.mechanisms.evm import EthAccountSigner
from x402.mechanisms.evm.exact import ExactEvmScheme

if len(sys.argv) != 2:
    sys.exit(__doc__)
client = x402ClientSync()
client.register("eip155:8453", ExactEvmScheme(signer=EthAccountSigner(Account.from_key(os.environ["X402_PRIVATE_KEY"]))))
client.register_policy(max_amount(int(float(os.environ.get("MAX_USD", "0.50")) * 1_000_000)))
payload = client.create_payment_payload(decode_payment_required_header(sys.argv[1].strip()))
print(encode_payment_signature_header(payload))
