// npm install @x402/core @x402/evm viem // node reconcile-agent.mjs # fetch the quote // node reconcile-agent.mjs --pay # requires an authorized Base wallet in FIELDWORK_BUYER_KEY import {createHash} from 'node:crypto'; import {x402Client} from '@x402/core/client'; import { decodePaymentRequiredHeader, decodePaymentResponseHeader, encodePaymentSignatureHeader, } from '@x402/core/http'; import {ExactEvmScheme} from '@x402/evm/exact/client'; import {privateKeyToAccount} from 'viem/accounts'; const url = 'https://workflowfieldwork.com/api/x402/reconcile-exports'; const network = 'eip155:8453'; const asset = '0x833589fcd6edb6e08f4c7c32d4f71b54bda02913'; const recipient = '0x8f11f891ed8e9aac9a194a9ebb2451752082a4da'; const amount = '1000000'; const body = JSON.stringify({ before:[{id:'example',quantity:1}], after:[{id:'example',quantity:2}], }); async function post(payment) { const headers = {'Content-Type':'application/json'}; if (payment) headers['PAYMENT-SIGNATURE'] = payment; return fetch(url,{method:'POST',headers,body,redirect:'error',signal:AbortSignal.timeout(75000)}); } async function run() { const reply = await post(); const header = reply.headers.get('PAYMENT-REQUIRED'); if (reply.status !== 402 || !header) throw new Error('Checkout did not return an x402 quote.'); const quote = decodePaymentRequiredHeader(header); const offer = quote.accepts.find(item => item.scheme === 'exact' && item.network === network && item.amount === amount && item.asset.toLowerCase() === asset && item.payTo.toLowerCase() === recipient); if (quote.x402Version !== 2 || quote.resource?.url !== url || !offer || offer.extra?.name !== 'USD Coin' || offer.extra?.version !== '2' || offer.maxTimeoutSeconds !== 60) { throw new Error('The quote does not match the approved 1 USDC Base payment.'); } console.log('Quote: 1 USDC on Base. Recipient: ' + offer.payTo); if (!process.argv.includes('--pay')) return; const key = process.env.FIELDWORK_BUYER_KEY; if (!/^0x[a-f0-9]{64}$/i.test(key ?? '')) throw new Error('Set an authorized buyer wallet key using your runtime secret store.'); const signer = privateKeyToAccount(key); const client = new x402Client().register(network,new ExactEvmScheme(signer)); const payload = await client.createPaymentPayload({...quote,accepts:[offer]}); const auth = payload.payload.authorization; const reference = createHash('sha256').update(auth.from.toLowerCase()+':'+auth.nonce.toLowerCase()) .digest('base64url').slice(0,24); const signed = encodePaymentSignatureHeader(payload); for (let attempt = 0; attempt < 3; attempt++) { let response; try { response = await post(signed); } catch { throw new Error('Payment could not be confirmed. Contact support with reference '+reference+' before paying again.'); } if (response.status === 429) { const wait = Number(response.headers.get('Retry-After')); if (attempt < 2 && wait >= 1 && wait <= 60 && Date.now()/1000 + wait + 2 < Number(auth.validBefore)) { await new Promise(resolve=>setTimeout(resolve,wait*1000)); continue; } throw new Error('Checkout is at capacity. This request was not submitted for settlement.'); } if (response.status === 402) throw new Error('The authorization was rejected. No settlement was requested.'); if (!response.ok) throw new Error('Check settlement with support before retrying. Reference: '+reference); try { const receipt = decodePaymentResponseHeader(response.headers.get('PAYMENT-RESPONSE') ?? ''); if (!receipt.success || receipt.network !== network || !/^0x[0-9a-f]{64}$/i.test(receipt.transaction ?? '')) { throw new Error('Invalid receipt'); } console.log(JSON.stringify({reference,transaction:receipt.transaction,result:await response.json()},null,2)); return; } catch { throw new Error('Payment receipt could not be confirmed. Contact support with reference '+reference+' before paying again.'); } } } run().catch(error=>{ console.error(error.message); process.exitCode=1; });