// pay-apex-verdict.mts: pay one APEX tool with x402 on Arc mainnet. Node 20+. Tested 2026-10-09 with the official x402 client.
// First draft by Arc Studio (Circle); rewritten on @x402/fetch + @x402/evm, which build the standard payment header.
// npm install @x402/fetch@2.28.0 @x402/evm@2.28.0 viem      run: PAYER_KEY=0x... node pay-apex-verdict.mts
import { x402Client, wrapFetchWithPayment } from '@x402/fetch'
import { registerExactEvmScheme } from '@x402/evm/exact/client'
import { privateKeyToAccount } from 'viem/accounts'

// 1. Your payer wallet (it needs a little USDC on Arc). The key comes from the environment and is never printed.
const account = privateKeyToAccount(process.env.PAYER_KEY as `0x${string}`)

// 2. A standard x402 client that pays with USDC on Arc mainnet (chain 5042). No gas needed: APEX settles the payment.
const client = new x402Client()
registerExactEvmScheme(client, { signer: account, networks: ['eip155:5042'] })

// 3. A fetch that answers the server's 402 by signing the payment and retrying, all by itself.
const payFetch = wrapFetchWithPayment(fetch, client)

// 4. One call, $0.002: is this Arc token's pool OK to sell into?
const res = await payFetch('https://apexfaucet.xyz/api/x402/arc-verdict?token=0x094e758838e56484cb95af9b18448d32f335564f')
const answer = await res.json()

// 5. The verdict (ok / caution / avoid), its score and reasons, and the on-chain payment.
const receipt = res.headers.get('payment-response')
console.log(res.status, answer.verdict, answer.score, answer.reasons)
const why = res.headers.get('payment-required')   // on a refusal the reason is here, e.g. insufficient_funds
console.log('payment:', res.ok && receipt ? JSON.parse(Buffer.from(receipt, 'base64').toString()).transaction
  : '(not paid: ' + (why ? JSON.parse(Buffer.from(why, 'base64').toString()).error : answer.error) + ')')
