x402-listing / tree / test/helpers.js ยท raw (this view has old GitHub links rewritten for the mirror; raw is byte-exact)
import { createApp } from '../src/app.js';
import { RegistryCore } from '../src/registry.js';
import { DEFAULT_ENABLED, supportedKinds } from '../src/networks.js';
export const PAY_TO = '0x3c1A1E01e790Cd326495631B3b38Bd7068F08d6F';
export const SOL_PAY_TO = 'FH73WbbUe2UyNzfy72MJs5nT3NxyDf9GrqE7kzjL2Jte';
export const BASE = 'https://listing.example.com';
export const TOKEN = 'T'.repeat(48);
export const PAYER = '0x' + '22'.repeat(20);
export const TX = '0x' + 'ab'.repeat(32);
export const GOOD = { tool_url: 'https://example.com/tool', name: 'Example Tool', contact_email: 'Founder@Example.COM', category: 'x402 API', description: 'Does things.' };
export const enc = (o) => Buffer.from(JSON.stringify(o)).toString('base64');
export const dec = (h) => JSON.parse(Buffer.from(h, 'base64').toString());

/** Fake DO namespace: one RegistryCore per name over an in-memory storage (get/put/delete/list), calls serialised. */
export function fakeNs() {
  const objs = new Map(); const mems = new Map();
  return {
    mems,
    idFromName: (n) => n,
    get(id) {
      let o = objs.get(id);
      if (!o) {
        const mem = new Map(); mems.set(id, mem);
        const storage = {
          get: async (k) => (mem.has(k) ? structuredClone(mem.get(k)) : undefined),
          put: async (k, v) => { mem.set(k, structuredClone(v)); },
          delete: async (k) => mem.delete(k),
          list: async ({ prefix = '' } = {}) => new Map([...mem.entries()].filter(([k]) => k.startsWith(prefix)).sort(([a], [b]) => (a < b ? -1 : 1)).map(([k, v]) => [k, structuredClone(v)])),
        };
        const core = new RegistryCore(storage);
        let q = Promise.resolve();
        o = new Proxy({}, { get: (_, m) => (m === 'then' ? undefined : (arg) => { const p = q.then(() => core[m](arg || {})); q = p.catch(() => {}); return p; }) });
        objs.set(id, o);
      }
      return o;
    },
  };
}
export function fakeFacilitator({ settleOk = true, cfg = {} } = {}) {
  const f = { verified: [], settled: [], settleOk,
    async getSupported() { return { kinds: supportedKinds(cfg), extensions: ['bazaar'], signers: {} }; },
    async verify(payload, req) { f.verified.push(req); const a = payload?.payload?.authorization; return a && a.to.toLowerCase() === req.payTo.toLowerCase() && String(a.value) === String(req.amount) ? { isValid: true, payer: a.from } : { isValid: false, invalidReason: 'fake_invalid' }; },
    async settle(payload, req) { f.settled.push(req); return f.settleOk ? { success: true, transaction: TX, network: req.network, payer: payload.payload.authorization.from } : { success: false, errorReason: 'fake_settle_failed', transaction: '', network: req.network }; },
  };
  return f;
}
export const memStats = () => { const hits = []; return { hits, hit(e) { hits.push(...[].concat(e)); }, async summary() { return { enabled: false }; }, enabled: false }; };
export function build({ settleOk = true, multichain = true, adminToken = TOKEN, now, v1FetchImpl, publicUrl = BASE } = {}) {
  const cfg = { payTo: PAY_TO, network: 'eip155:8453', ...(multichain ? { enabledNetworks: DEFAULT_ENABLED, solanaPayTo: SOL_PAY_TO } : {}) };
  const facilitator = fakeFacilitator({ settleOk, cfg }); const registry = fakeNs(); const stats = memStats();
  const app = createApp({ ...cfg, facilitatorClient: facilitator, publicUrl, registry, stats, adminToken, now, v1FetchImpl });
  const f = (path, init = {}) => app.fetch(new Request(`${BASE}${path}`, init));
  const store = () => registry.mems.get('registry') || new Map();
  return { app, f, facilitator, registry, stats, store };
}
export const post = (body, headers = {}) => ({ method: 'POST', headers: { 'content-type': 'application/json', ...headers }, body: typeof body === 'string' ? body : JSON.stringify(body) });
/** Pay a route: fetch the 402 for this exact request, then retry with a v2 PAYMENT-SIGNATURE for the chosen accepts entry. */
export async function pay(f, path, init = {}, { network = 'eip155:8453' } = {}) {
  const r0 = await f(path, init);
  if (r0.status !== 402) return { r0 };
  const pr = dec(r0.headers.get('payment-required'));
  const accepted = pr.accepts.find((a) => a.network === network);
  const payload = { x402Version: 2, resource: pr.resource, accepted, payload: { signature: '0x' + '11'.repeat(65), authorization: { from: PAYER, to: accepted.payTo, value: accepted.amount, validAfter: '0', validBefore: String(Math.floor(Date.now() / 1000) + 600), nonce: '0x' + '33'.repeat(32) } } };
  const r = await f(path, { ...init, headers: { ...(init.headers || {}), 'payment-signature': enc(payload) } });
  return { r0, r, pr };
}
export const auth = (t = TOKEN) => ({ authorization: `Bearer ${t}` });

agentgate-source: code mirror on Cloudflare Pages. All repos