// Node.js 20+. Install: npm install @x402/core@2.21.0 @x402/evm@2.21.0 viem // Inspect for free: node pdf-client.mjs https://example.com // Buy once: set EVM_PRIVATE_KEY in your environment, then add --pay. import { x402Client } from '@x402/core/client'; import { x402HTTPClient } from '@x402/core/http'; import { ExactEvmScheme } from '@x402/evm/exact/client'; import { privateKeyToAccount } from 'viem/accounts'; const endpoint = 'https://api.agentwork.run/v1/pdf/read'; const merchant = '0x1cfc6489bc9703a2a49715b8a746d8c6075f3a80'; const usdc = '0x833589fcd6edb6e08f4c7c32d4f71b54bda02913'; const target = process.argv.slice(2).find(arg => arg !== '--pay') || 'https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf'; const body = JSON.stringify({ url: target}); const headers = { 'Content-Type': 'application/json', 'User-Agent': 'AgentWorkExampleClient/1.0' }; const request = extra => fetch(endpoint, { method: 'POST', redirect: 'error', headers: { ...headers, ...extra }, body, signal: AbortSignal.timeout(60000) }); const allowed = terms => terms.scheme === 'exact' && terms.network === 'eip155:8453' && terms.amount === '10000' && terms.payTo.toLowerCase() === merchant && terms.asset.toLowerCase() === usdc; async function main() { const challenge = await request({}); if (challenge.status !== 402) throw Error('Expected a payment challenge; HTTP ' + challenge.status); const required = JSON.parse(Buffer.from(challenge.headers.get('payment-required'), 'base64')); if (required.x402Version !== 2 || required.resource?.url !== endpoint || !required.accepts.some(allowed)) throw Error('Unexpected payment terms; stopped without signing.'); console.error('One successful read costs 0.01 USDC on Base.'); if (!process.argv.includes('--pay')) { console.log(JSON.stringify(required, null, 2)); return; } const key = process.env.EVM_PRIVATE_KEY; if (!/^0x[0-9a-fA-F]{64}$/.test(key || '')) throw Error('Set EVM_PRIVATE_KEY locally to a 0x-prefixed key. Never send it to the API.'); const client = new x402Client(); client.register('eip155:8453', new ExactEvmScheme(privateKeyToAccount(key))); client.registerPolicy((_version, terms) => terms.filter(allowed)); const http = new x402HTTPClient(client); const payment = await http.createPaymentPayload(required); if (payment.resource?.url !== endpoint) throw Error('Payment resource missing; stopped before sending.'); // Exactly one signed request. No automatic retries after an uncertain result. const response = await request(http.encodePaymentSignatureHeader(payment)); let receipt; try { receipt = http.getPaymentSettleResponse(name => response.headers.get(name)); } catch {} if (receipt) console.error(JSON.stringify({ settlement: receipt })); console.log(await response.text()); if (response.status !== 200 || receipt?.success !== true) throw Error('No confirmed successful result. Inspect the response before retrying.'); } main().catch(error => { console.error(error.message); process.exitCode = 1; });