// x402 v2 facilitator for GOAT Network Testnet3 (eip155:48816), exact scheme, EIP-3009 tokens. Testnet only.
// GET / info (JSON)
// GET /supported x402 supported kinds
// POST /verify { x402Version, paymentPayload, paymentRequirements } -> VerifyResponse
// POST /settle same body -> SettleResponse (facilitator wallet pays the GOAT testnet BTC gas)
// Built on the official @x402/core x402Facilitator + @x402/evm ExactEvmScheme. The facilitator only settles
// allowlisted tokens to allowlisted receivers (PAY_TO_ALLOWLIST) with a per-payment cap, so it can't be used to
// drain its testnet gas for third parties. Secret: FACILITATOR_PRIVATE_KEY (wrangler secret, testnet-only key).
import { x402Facilitator } from '@x402/core/facilitator';
import { ExactEvmScheme } from '@x402/evm/exact/facilitator';
import { toFacilitatorEvmSigner } from '@x402/evm';
import { createWalletClient, http, publicActions, getAddress } from 'viem';
import { privateKeyToAccount } from 'viem/accounts';
import { goatTestnet3, GOAT_TESTNET3, GOAT_RPC, GOAT_EXPLORER, GOAT_TOKENS } from './goat.js';
const MAX_ATOMIC = 1_000_000n; // 1 token (6 decimals) per payment
const json = (body, status = 200) => new Response(JSON.stringify(body, null, 1), { status, headers: { 'content-type': 'application/json', 'access-control-allow-origin': '*' } });
let cached;
function facilitatorFor(env) {
if (cached) return cached;
const account = privateKeyToAccount(env.FACILITATOR_PRIVATE_KEY);
const client = createWalletClient({ account, chain: goatTestnet3, transport: http(env.GOAT_RPC || GOAT_RPC, { timeout: 15000 }) }).extend(publicActions);
const signer = toFacilitatorEvmSigner({
address: account.address,
readContract: (a) => client.readContract(a),
verifyTypedData: (a) => client.verifyTypedData(a),
writeContract: (a) => client.writeContract({ ...a, chain: goatTestnet3, account }),
sendTransaction: (a) => client.sendTransaction({ ...a, chain: goatTestnet3, account }),
waitForTransactionReceipt: (a) => client.waitForTransactionReceipt({ pollingInterval: 1000, ...a }),
getCode: (a) => client.getCode(a),
}, { confirmationTimeoutMs: 25000 });
const fac = new x402Facilitator().register(GOAT_TESTNET3, new ExactEvmScheme(signer));
cached = { fac, address: account.address };
return cached;
}
function policy(env, req) {
const r = req?.paymentRequirements;
if (!r || r.network !== GOAT_TESTNET3 || r.scheme !== 'exact') return 'unsupported_network_or_scheme';
const assets = Object.values(GOAT_TOKENS).map((t) => t.address.toLowerCase());
if (!assets.includes(String(r.asset).toLowerCase())) return 'asset_not_allowed';
const payTos = String(env.PAY_TO_ALLOWLIST || '').split(',').map((s) => s.trim().toLowerCase()).filter(Boolean);
if (!payTos.includes(String(r.payTo).toLowerCase())) return 'pay_to_not_allowed';
let amt; try { amt = BigInt(r.amount); } catch { return 'invalid_amount'; }
if (amt <= 0n || amt > MAX_ATOMIC) return 'amount_over_cap';
return null;
}
export default {
async fetch(request, env) {
const url = new URL(request.url);
if (request.method === 'OPTIONS') return new Response(null, { headers: { 'access-control-allow-origin': '*', 'access-control-allow-methods': 'GET, POST', 'access-control-allow-headers': 'content-type' } });
try {
if (request.method === 'GET' && url.pathname === '/') {
return json({
name: 'PayGuard GOAT Testnet3 x402 facilitator', x402Version: 2, scheme: 'exact', network: GOAT_TESTNET3, testnet: true,
rpc: GOAT_RPC, explorer: GOAT_EXPLORER, tokens: GOAT_TOKENS, signer: env.FACILITATOR_ADDRESS,
policy: { payToAllowlist: String(env.PAY_TO_ALLOWLIST || '').split(',').filter(Boolean), maxAtomicPerPayment: String(MAX_ATOMIC) },
endpoints: ['GET /supported', 'POST /verify', 'POST /settle'],
note: 'Self-hosted facilitator for PayGuard\'s GOAT Testnet3 route. Uses @x402/core x402Facilitator + @x402/evm ExactEvmScheme (EIP-3009). Not a GOAT merchant / GoatX402 integration.',
});
}
if (request.method === 'GET' && url.pathname === '/supported') {
return json({ kinds: [{ x402Version: 2, scheme: 'exact', network: GOAT_TESTNET3 }], extensions: [], signers: { 'eip155:*': [env.FACILITATOR_ADDRESS] } });
}
if (request.method === 'POST' && (url.pathname === '/verify' || url.pathname === '/settle')) {
let body; try { body = await request.json(); } catch { return json({ error: 'invalid_json' }, 400); }
const bad = policy(env, body);
const payer = body?.paymentPayload?.payload?.authorization?.from;
if (url.pathname === '/verify') {
if (bad) return json({ isValid: false, invalidReason: bad, payer });
return json(await facilitatorFor(env).fac.verify(body.paymentPayload, body.paymentRequirements));
}
if (bad) return json({ success: false, errorReason: bad, transaction: '', network: GOAT_TESTNET3, payer });
const r = await facilitatorFor(env).fac.settle(body.paymentPayload, body.paymentRequirements);
console.log(`settle ${r.success ? 'ok' : 'fail'} ${r.transaction || ''} ${r.errorReason || ''}`);
return json(r);
}
return json({ error: 'not_found' }, 404);
} catch (e) {
console.error('facilitator error', e?.message);
return json({ error: 'facilitator_error', message: String(e?.message || e).slice(0, 300) }, 500);
}
},
};
agentgate-source: code mirror on Cloudflare Pages. All repos