#!/usr/bin/env bash
# The x402 cycle by hand: 402 → sign → 200. One step per command; needs curl, jq, node (for signing only).
#   export API=https://api.awesomefee.com EVM_PRIVATE_KEY=0x…   (YOUR wallet with USDC on Base)
set -euo pipefail
DEFAULT_API='https://api.awesomefee.com'
API="${API:-$DEFAULT_API}"
ADDR="${1:?TRON receiver address}"
BODY="{\"address\":\"$ADDR\",\"amount\":65000,\"duration_blocks\":1000}"

# 0. Find the product (free): its url, method, body schema, price
curl -s "$API/v1/search?q=buy+energy&limit=1" | jq '.results[0] | {id, method, url, payment, price}'

# 1. Free price
curl -s "$API/x402/v1/quote?product=energy&amount=65000" | jq .

# 2. Paid call without payment → 402; the terms are in the PAYMENT-REQUIRED header (base64 JSON)
REQ=$(curl -s -o /dev/null -D - -X POST "$API/x402/v1/tron/energy" -H 'Content-Type: application/json' -d "$BODY" | tr -d '\r' | sed -n 's/^payment-required: //Ip')
echo "$REQ" | base64 -d | jq '{amount: .accepts[0].amount, network: .accepts[0].network, payTo: .accepts[0].payTo, extra: .accepts[0].extra}'

# 3. Sign the terms with your wallet (offline, EIP-3009: no gas) → PAYMENT-SIGNATURE
SIG=$(echo "$REQ" | node sign-x402.mjs)

# 4. The same request with the payment → 200 + result; PAYMENT-RESPONSE carries the settlement transaction
HDR=$(mktemp)
curl -s -D "$HDR" -X POST "$API/x402/v1/tron/energy" -H 'Content-Type: application/json' -H "PAYMENT-SIGNATURE: $SIG" -d "$BODY" | jq .
tr -d '\r' < "$HDR" | sed -n 's/^payment-response: //Ip' | base64 -d | jq .
rm -f "$HDR"
