New Jazz City logo

New Jazz City · security review

HEY Research Lab's review of JazzCat #1's chain reads, and the fix for each finding in full

HEY's report: github.com/hey-research-lab/security/blob/main/reviews/2026-11-27-jazzcat-1-chain-reads.md · heyresearch.xyz

HEY Research Lab reviewed the six paid chain reads that JazzCat #1 sells on x402fi. They found 1 Medium and 4 Low issues, and retested twice. The fixes are in JazzCat #1's worker repository, rh-tx-explain (github.com/nebulamji/rh-tx-explain, mirrored at github.com/newjazzcity/rh-tx-explain). Those repository links are not reachable right now, so this page shows the fix commits for each of HEY's five findings with their full diffs, rendered from our copy of that repository: the same change git show <sha> prints in a clone of it.

HEY's sign-off

Findings fixed and re-tested, signed by HEY Research Lab for all six endpoints at 007d04b.

From HEY's report, "At a glance". HEY reviewed the code at 9ce92a8 on Nov 25, 2026, then retested at 04a94df and, for the final retest, at 007d04b, both on Nov 27, 2026. Final retest commit: 007d04bb4d40f5da37191381e4a287a2fd7e1207. HEY: "Commits on the main branch after 007d04b are not covered by this review."

What HEY reviewed (HEY's words)

The six paid endpoints of the listing, and the code they share. HEY's sign-off covers these six:

EndpointWhat it sells
/x402/money-trailWho launched a Robinhood Chain coin, where its supply went, early buyers, top holders
/x402/line-readCredit-line read for an ERC-8004 agent before a lender opens a line
/x402/income-readWho actually paid an agent, with its own wallets, loans and withdrawals split out
/x402/poison-checkAddress-poisoning signs in a wallet's history
/x402/ledgerEvery USDG in and out of an address, reconciled with its balance
/x402/transfer-readWho can still act during a two-step ownership transfer

Shared code in scope: the x402 payment path (requirements, facilitator calls, settlement), the /buy checkout page every read can be bought through, the Base and Solana payment rails, the Raeto Pay rail next to it, and the chain-reading helpers. The rest of the repository (New Jazz City's other tools, Orbio, Cat Calls, launch tools and so on) was not in scope. Commits on the main branch after 007d04b are not covered by this review.

Some fix commits below also carry work outside that scope; where they do, the commit says which part is the fix.

The findings

HEY's report also lists smaller points without a severity, all fixed (see "Smaller points, all fixed" in HEY's report). This page does not cover them one by one, but some of their fixes appear inside the diffs below: a6937b1 also refuses a malformed payment header and a payment on an unoffered network, and floors a fractional days value; 007d04b also carries the payment-record changes from the first retest.

IDSeverityFinding (HEY's words)Status (HEY)
F-1Medium (CVSS 3.1 6.1, CWE-79)Script injection on the /buy checkout pageFixed in b9d2102, f1a68f7
F-3Low (3.7, CWE-754)Paid reads settled on incomplete data when a chain node returned an errorFixed in a6937b1, 04a94df, 007d04b
F-4Low (3.7, CWE-672)The Base payment address could stay with a previous Cat holderFixed (f4a4c24 and later)
N-1Low (3.7), conditionalThe Raeto Pay rail served a read before its payment capture was confirmedFixed (84ce44a and later)
R-1Low (3.7, CWE-754)Income read: two lookups still treated a node error as an empty answer (found in the first retest)Fixed in 007d04b

F-1: Script injection on the /buy checkout page

Medium (CVSS 3.1 6.1, CWE-79) · HEY: Fixed in b9d2102, f1a68f7. Details in HEY's report.

b9d2102 /buy takes only known reads under a nonce CSP; an incomplete paid read is released, never settled (#196)

Commit
b9d210240f0d9b7dfe1f1072001ff1fdc5f58c3e
Date
Nov 27, 2026, 2:29 AM ET (07:29 UTC)
Fixes
F-1
Verify
git show b9d210240f0d9b7dfe1f1072001ff1fdc5f58c3e in a clone of rh-tx-explain
- /buy: `read` is used only when it names a paid route; only the tools' own input names are prefilled (each up to
  200 characters); every value in the inline script is JSON with <, U+2028 and U+2029 escaped; the page carries a
  per-response nonce CSP (default-src 'none', script by nonce, connect-src 'self', frame-ancestors 'none'),
  nosniff and no-referrer.
- paid-complete.mjs: incompleteRead() (complete:false, partial:true or a non-empty pending list). x402, token pay
  and Raeto Pay release the payment on an incomplete read and name the missing parts; full_check is the paid
  read that reports failed legs.
- Tests: /buy with script-breaking read/token/extra parameters, a fresh nonce per page; the real x402 handler on
  an incomplete full_check (503, no settle, the same payment accepted again); Raeto releases without capture.

6 files changed, +109 −7

  • buy-page.test.mjs +34 −0
  • paid-complete.mjs +7 −0
  • paid-incomplete.test.mjs +45 −0
  • raeto-gateway.mjs +2 −1
  • raeto-gateway.test.mjs +3 −0
  • worker.mjs +18 −6
Full diff
diff --git a/buy-page.test.mjs b/buy-page.test.mjs
new file mode 100644
index 0000000..9962d4a
--- /dev/null
+++ b/buy-page.test.mjs
@@ -0,0 +1,34 @@
+// HEY Research review (11-26, medium): /buy wrote the `read` parameter into its inline script unescaped, with no CSP.
+// Now `read` is taken only when it names a paid route, only the tools' own inputs are prefilled (each up to 200 characters),
+// every value in the script is escaped JSON, and the page runs under a nonce CSP with no outside sources.
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import worker from './worker.mjs';
+import {incompleteRead, incompleteText} from './paid-complete.mjs';
+
+const page = async q => { const r = await worker.fetch(new Request('https://w.example/buy' + q), {}, {waitUntil: () => {}}); return {r, html: await r.text()}; };
+const scriptOf = html => html.slice(html.indexOf('<script'), html.lastIndexOf('</script>'));
+
+test('a script-breaking read, token or extra parameter never leaves its string, and the page carries a nonce CSP', async () => {
+  const evil = encodeURIComponent('</script><script>alert(1)</script>'), {r, html} = await page(`?read=${evil}&token=${evil}&address=%E2%80%A8x&zzz=${evil}&from=${'a'.repeat(201)}`);
+  const csp = r.headers.get('content-security-policy'), nonce = csp.match(/script-src 'nonce-([^']+)'/)[1];
+  assert.equal((html.match(/<script/g) || []).length, 1); assert.ok(html.includes(`<script nonce="${nonce}">`));
+  assert.match(csp, /default-src 'none'/); assert.match(csp, /connect-src 'self'/); assert.match(csp, /frame-ancestors 'none'/); assert.doesNotMatch(csp, /unsafe-inline'[^;]*script|script-src[^;]*unsafe/);
+  const s = scriptOf(html).slice(8);
+  assert.ok(!s.includes('</script') && !s.includes('<script') && !s.includes('\u2028'));
+  assert.match(s, /sel\.value="money-trail";/); assert.ok(!s.includes('zzz')); assert.ok(!s.includes('a'.repeat(201)));
+  assert.ok(s.includes('"token":"\\u003c/script>')); // kept as inert text, prefilled through input.value only
+  assert.equal(r.headers.get('x-content-type-options'), 'nosniff');
+  const again = await page('?read=money-trail'); assert.notEqual(again.r.headers.get('content-security-policy'), csp, 'a fresh nonce per page');
+});
+
+test('a known route and its own inputs are kept', async () => {
+  const {html} = await page('?read=send-check&from=0x' + 'ab'.repeat(20) + '&to=0x' + 'cd'.repeat(20));
+  assert.match(html, /sel\.value="send-check";/); assert.match(html, /"from":"0x(ab){20}"/); assert.match(html, /"to":"0x(cd){20}"/);
+});
+
+test('incompleteRead: failed or pending parts are incomplete; a whole read is not', () => {
+  for (const r of [{complete: false}, {partial: true}, {pending: ['record']}]) assert.equal(incompleteRead(r), true);
+  for (const r of [{complete: true, failedReads: []}, {pending: []}, {status: 'pending'}, null, 'x', {reads: {a: {complete: false}}}]) assert.equal(incompleteRead(r), false);
+  assert.equal(incompleteText({failedReads: ['incomeRead'], pending: ['legs']}), 'Part of this read did not come back (incomeRead, legs); nothing was charged. Call again.');
+});
diff --git a/paid-complete.mjs b/paid-complete.mjs
new file mode 100644
index 0000000..0460817
--- /dev/null
+++ b/paid-complete.mjs
@@ -0,0 +1,7 @@
+// A paid read that comes back incomplete is never charged (HEY Research review, 11-26: "partial reads still settle").
+// full_check returns complete:false with the reads that failed; a budgeted read names what is still running in `pending`
+// or marks itself partial. x402 (USDG / USDC), token pay ($FLOW, $RCPT, any coin) and Raeto Pay all release the payment
+// on an incomplete read and say which part failed, so the buyer calls again and pays once, for a whole read.
+export const incompleteRead = r => !!r && typeof r === 'object' && (r.complete === false || r.partial === true || (Array.isArray(r.pending) && r.pending.length > 0));
+export const missingParts = r => [...(Array.isArray(r?.failedReads) ? r.failedReads : []), ...(Array.isArray(r?.pending) ? r.pending : [])].map(String).slice(0, 10);
+export const incompleteText = r => { const m = missingParts(r); return `Part of this read did not come back${m.length ? ' (' + m.join(', ') + ')' : ''}; nothing was charged. Call again.`; };
diff --git a/paid-incomplete.test.mjs b/paid-incomplete.test.mjs
new file mode 100644
index 0000000..a308a3d
--- /dev/null
+++ b/paid-incomplete.test.mjs
@@ -0,0 +1,45 @@
+// HEY Research review (11-26): "partial reads still settle". full_check (2.7 USD) returned failed legs as {error} and the
+// x402 handler settled anyway. Now an incomplete read is released, never settled, and the same payment can be sent again.
+// Synthetic verification/settlement and native reads only; no real signature, funds or payment.
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import worker from './worker.mjs';
+import {DatabaseSync} from 'node:sqlite';
+import {d1} from './test-d1.mjs';
+const CITY = '0x0C0B48Beba6c89CE591b0092B1F5EA83481D2906', A = '0x' + '1'.repeat(40), TX = '0x' + '2'.repeat(64);
+let verified = 0, settled = 0, logsFail = true;
+globalThis.fetch = async (input, init) => {
+  const url = String(input);
+  if (url.endsWith('/verify')) { verified++; return Response.json({isValid: true}); }
+  if (url.endsWith('/settle')) { settled++; return Response.json({success: true, transaction: TX, payer: A}); }
+  let body; try { body = JSON.parse(init?.body); } catch { return new Response('no', {status: 500}); }
+  if (!Array.isArray(body)) body = [body];
+  const out = body.map(x => {
+    if (x.method === 'eth_getLogs' && logsFail) return {jsonrpc: '2.0', id: x.id, error: {code: -32000, message: 'synthetic log failure'}};
+    let result;
+    if (x.method === 'eth_chainId') result = '0x' + (4663).toString(16);
+    else if (x.method === 'eth_getBlockByNumber') result = {number: '0x100', hash: '0x' + 'a'.repeat(64), timestamp: '0x' + Math.floor(Date.now() / 1000).toString(16)};
+    else if (x.method === 'eth_call') result = '0x' + '0'.repeat(24) + 'ff122dfec6029510aa36996ec6f5a67c84d75bdb';
+    else if (x.method === 'eth_getCode') result = '0x';
+    else if (x.method === 'eth_blockNumber') result = '0x10';
+    else if (x.method === 'eth_getLogs') result = [];
+    else if (x.method === 'eth_getBalance') result = '0x0';
+    else return {jsonrpc: '2.0', id: x.id, error: {code: -32601, message: 'synthetic: ' + x.method}};
+    return {jsonrpc: '2.0', id: x.id, result};
+  });
+  return Response.json(Array.isArray(JSON.parse(init.body)) ? out : out[0]);
+};
+const ENV = {CITY_WALLET: CITY, QDB: d1(new DatabaseSync(':memory:'))};
+const hdr = {'x-payment': Buffer.from(JSON.stringify({x402Version: 1, network: 'robinhood', payload: {signature: '0x' + 'ab'.repeat(65), authorization: {from: A, nonce: '0x' + 'e5'.repeat(32)}}})).toString('base64')};
+const buy = () => worker.fetch(new Request('https://fixture.example/x402/full-check?address=' + A, {headers: hdr}), ENV, {waitUntil: () => {}});
+
+test('an incomplete full_check is never settled, says which part failed, and the same payment works once it is whole', async () => {
+  verified = settled = 0; logsFail = true;
+  const r = await buy(), j = await r.json();
+  assert.equal(r.status, 503, JSON.stringify(j).slice(0, 300)); assert.equal(settled, 0); assert.equal(j.paid, false);
+  assert.match(j.error, /did not come back \(.+\); nothing was charged/); assert.ok(j.missing.length >= 1);
+  logsFail = false;
+  const r2 = await buy(), j2 = await r2.json();
+  assert.notEqual(r2.status, 409, 'the payment was released, not burned'); assert.equal(verified, 2);
+  if (r2.status === 200) { assert.equal(j2.complete, true); assert.equal(settled, 1); } else assert.equal(settled, 0);
+});
diff --git a/raeto-gateway.mjs b/raeto-gateway.mjs
index 5354157..a11ab88 100644
--- a/raeto-gateway.mjs
+++ b/raeto-gateway.mjs
@@ -1,4 +1,5 @@
 // Existing merchant rail: never return paid bytes before capture is acknowledged.
+import {incompleteRead} from './paid-complete.mjs';
 const BASE='https://api.raeto.cc';
 const response=(body,status=200)=>Response.json(body,{status,headers:{'cache-control':'private, no-store',vary:'X-Raeto-Receipt, Authorization','access-control-allow-origin':'*'}});
 async function bodyJSON(r){if(!r.headers.get('content-type')?.includes('application/json'))throw Error('Invalid payment response');const t=await r.text();if(t.length>32768)throw Error('Oversized payment response');const j=JSON.parse(t);if(!j||typeof j!=='object'||Array.isArray(j))throw Error('Invalid payment response');return j;}
@@ -17,7 +18,7 @@ export async function raetoGateway(req,{key,payTo,price,resource,run,validate=()
  // The seller's key binds the payee; independently reject conflicting mirrors.
  if(v.j.payTo&&v.j.payTo.toLowerCase()!==payTo.toLowerCase()||v.j.resource&&v.j.resource!==resource)return response({error:'Conflicting payment identity',paymentStatus:'held'},503);
  let out;
- try{out=await run(args);if(!out||typeof out!=='object'||out.error||out.ok===false||out.charged===false)throw Error('Service unavailable');}
+ try{out=await run(args);if(!out||typeof out!=='object'||out.error||out.ok===false||out.charged===false||incompleteRead(out))throw Error('Service unavailable');}
  catch{let released=false;try{released=(await call('/v1/pay/release',{receipt,reason:'call failed'})).ok;}catch{}
   return response({error:'Service failed; no result delivered',paymentStatus:released?'released':'release_unknown',...(released?{charged:false}:{retry:'Reconcile the original receipt before paying again'})},502);}
  let c;try{c=await call('/v1/pay/capture',{receipt});}catch{}
diff --git a/raeto-gateway.test.mjs b/raeto-gateway.test.mjs
index 2d410db..665fc42 100644
--- a/raeto-gateway.test.mjs
+++ b/raeto-gateway.test.mjs
@@ -10,3 +10,6 @@ test('service failure releases a held payment, and release uncertainty is not ch
 test('missing key and malformed bodies never call provider or service',async()=>{for(const options of [{key:''},{req:request('r','bad')},{req:request('r','[]')}]){const x=await run(options);assert.equal(x.ran,0);assert.deepEqual(x.calls,[]);}});
 test('verification transport failure and wrong payee do not run or disclose',async()=>{for(const r of [new Error('timeout'),{body:{ok:true,payTo:'0x'+'1'.repeat(40)}}]){const x=await run({responses:{'/v1/pay/verify':r}});assert.equal(x.r.status,503);assert.equal(x.ran,0);}});
 test('uncaptured verification is a valid hold, not a capture refusal',async()=>{const x=await run({responses:{'/v1/pay/verify':{body:{ok:true,captured:false}}}});assert.equal(x.r.status,200);assert.equal(x.body.paid.captureConfirmed,true);});
+// HEY Research review (11-26): an incomplete read is never captured; the hold is released and nothing is delivered.
+for(const out of [{complete:false,failedReads:['incomeRead']},{partial:true,pending:['record']},{pending:['legs']}])test('an incomplete read releases the hold and is never captured: '+JSON.stringify(out),async()=>{const x=await run({service:async()=>({...out,privateEvidence:'part'})});assert.equal(x.r.status,502);assert.equal(x.body.charged,false);assert.ok(!x.calls.includes('/v1/pay/capture'));assert.ok(x.calls.includes('/v1/pay/release'));assert.ok(!JSON.stringify(x.body).includes('part'));});
+test('a complete read with empty pending is still captured',async()=>{const x=await run({service:async()=>({complete:true,pending:[],privateEvidence:'paid bytes'})});assert.equal(x.r.status,200);assert.ok(x.calls.includes('/v1/pay/capture'));});
diff --git a/worker.mjs b/worker.mjs
index e158c0b..9869a7d 100644
--- a/worker.mjs
+++ b/worker.mjs
@@ -1,4 +1,5 @@
 import {raetoGateway} from './raeto-gateway.mjs';
+import {incompleteRead, incompleteText, missingParts} from './paid-complete.mjs';
 import {a2aAnswer, A2A_METHODS} from './a2a.mjs';
 import {jazzBuyPlan,JAZZ as OFFICIAL_JAZZ, jazzBuyGraduated} from './jazz-buy.mjs';
 import {tradeRefusal, checkQhooksPlan, isSolana} from './trade-guard.mjs';
@@ -1036,6 +1037,7 @@ async function paid(req, url, work, reqOf = ledgerReq, {perks = true, tokens = t
   const claim = await claimFor(HOLDER_ENV?.QDB, payload, header, url.pathname + url.search);
   if (!claim.ok) return offer(claim.error, claim.status);
   let result; try { result = await work(); } catch (e) { await claim.release(); return json({error: e.message}, 400); } // a failed read is never charged
+  if (incompleteRead(result)) { await claim.release(); return json({error: incompleteText(result), missing: missingParts(result), paid: false}, 503); } // nor an incomplete one
   // Work may outlive an NFT transfer. Re-resolve the signed receiver before
   // settlement; never charge an old owner/treasury route or silently reroute it.
   let current;
@@ -1090,6 +1092,8 @@ async function tokenPaid(url, work, {cat, usd, payTx, payToken = null, sig, payT
   let result; try { result = await work(); } catch (e) {
     await db.prepare('DELETE FROM token_payments WHERE tx=?').bind(v.tx).run().catch(() => null);
     return json({error: e.message, paid: false, note: 'Not charged: call again with the same X-PAYMENT-TX and X-PAYMENT-SIG.'}, 400); }
+  if (incompleteRead(result)) { await db.prepare('DELETE FROM token_payments WHERE tx=?').bind(v.tx).run().catch(() => null);
+    return json({error: incompleteText(result), missing: missingParts(result), paid: false, note: 'Not charged: call again with the same X-PAYMENT-TX and X-PAYMENT-SIG.'}, 503); }
   return new Response(JSON.stringify({...result, payment: {tx: v.tx, payer: v.payer, paidTo: payTo, token: symbol, value: v.value, network: payTx.chain, cat: Number(cat || 1)}}), {headers: H402});
 }
 
@@ -1765,19 +1769,26 @@ const PAID_RUN = {
 const qs = t => Object.keys(t.inputSchema.properties).map(k => `${k}={${k}}`).join('&');
 // Buy on the spot: any wallet (an agent's browser or a person's) picks a read, signs one USDG authorization, and gets the
 // read back in the same click. Same x402 endpoint, same price; nothing settles unless the read succeeds.
-function buyPage(url) {
+// The page takes `read` only when it names a paid route, and prefills only the tools' own input names (each up to 200
+// characters); every value placed in the script is JSON with <, U+2028 and U+2029 escaped, and the page runs under a
+// nonce CSP with no outside sources (HEY Research review, 11-26: `read` was written into the inline script unescaped).
+const jsIn = v => JSON.stringify(v).replace(/</g, '\\u003c').replace(/\u2028/g, '\\u2028').replace(/\u2029/g, '\\u2029');
+const buyCsp = nonce => `default-src 'none'; script-src 'nonce-${nonce}'; style-src 'unsafe-inline'; connect-src 'self'; img-src 'self' data:; base-uri 'none'; form-action 'none'; frame-ancestors 'none'`;
+function buyPage(url, nonce) {
   const tools = PAID_TOOLS.map(t => ({route: t.route, title: t.title, price: t.price, inputs: Object.entries(t.inputSchema.properties).map(([k, v]) => ({k, d: v.description || k, req: (t.inputSchema.required || []).includes(k)}))}));
-  const pick = url.searchParams.get('read') || 'money-trail', pre = Object.fromEntries(url.searchParams);
+  const asked = url.searchParams.get('read'), pick = tools.some(t => t.route === asked) ? asked : 'money-trail';
+  const names = new Set(tools.flatMap(t => t.inputs.map(f => f.k)));
+  const pre = Object.fromEntries([...url.searchParams].filter(([k, v]) => names.has(k) && typeof v === 'string' && v.length <= 200));
   return `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Buy a read · JazzCat #1</title>
 <style>:root{--bg:#0d0d10;--fg:#f2efe6;--mut:#a7a29a;--acc:#f5c542;--card:#17171c}body{background:var(--bg);color:var(--fg);font:16px/1.5 ui-monospace,Menlo,monospace;margin:0}main{max-width:720px;margin:0 auto;padding:24px 16px}h1{font-size:22px;margin:0 0 4px}p{color:var(--mut)}label{display:block;margin:12px 0 4px;color:var(--mut)}select,input{width:100%;box-sizing:border-box;background:var(--card);color:var(--fg);border:1px solid #333;border-radius:8px;padding:10px;font:inherit}button{margin-top:16px;width:100%;padding:14px;border:0;border-radius:10px;background:var(--acc);color:#111;font:inherit;font-weight:700;cursor:pointer}button:disabled{opacity:.5}pre{background:var(--card);padding:12px;border-radius:8px;overflow:auto;white-space:pre-wrap;word-break:break-word;font-size:13px}#st{color:var(--acc);min-height:1.5em}a{color:var(--acc)}</style></head>
 <body><main><h1>Buy a read from JazzCat #1</h1><p>Pick a read, connect a wallet on Robinhood Chain with USDG, sign one authorization. The read comes back here. Nothing is charged if the read fails.</p>
 <label for="read">Read</label><select id="read"></select><div id="fields"></div><button id="go">Pay and read</button><div id="st"></div><pre id="out" hidden></pre>
 <p>Pays ${esc(CAT1_WALLET.toLowerCase())} in USDG ${esc(USDG)}. Agents: call the same URL over x402, menu at <a href="/llms.txt">/llms.txt</a>.</p></main>
-<script>
-const TOOLS=${JSON.stringify(tools).replace(/</g, '\\u003c')}, PRE=${JSON.stringify(pre).replace(/</g, '\\u003c')}, USDG='${USDG}', CHAIN='0x1237';
+<script nonce="${nonce}">
+const TOOLS=${jsIn(tools)}, PRE=${jsIn(pre)}, USDG=${jsIn(USDG)}, CHAIN='0x1237';
 const $=i=>document.getElementById(i), sel=$('read');
 TOOLS.forEach(t=>{const o=document.createElement('option');o.value=t.route;o.textContent=t.title+' · '+t.price+' USDG';sel.appendChild(o)});
-sel.value=TOOLS.some(t=>t.route===PRE.read)?PRE.read:${JSON.stringify(pick)};
+sel.value=${jsIn(pick)};
 function fields(){const t=TOOLS.find(x=>x.route===sel.value);$('fields').innerHTML='';t.inputs.forEach(f=>{const l=document.createElement('label');l.textContent=f.d+(f.req?'':' (optional)');const i=document.createElement('input');i.id='f_'+f.k;i.value=PRE[f.k]||'';i.placeholder=f.k;$('fields').append(l,i)});$('go').textContent='Pay '+t.price+' USDG and read'}
 sel.onchange=fields;fields();
 const st=m=>$('st').textContent=m, b64=o=>btoa(unescape(encodeURIComponent(JSON.stringify(o))));
@@ -2271,7 +2282,8 @@ export default {
       catch (e) { return json({error: e.message}, e.status || 502); }
     }
     if (url.pathname.startsWith('/jobs/') && req.method === 'GET') { const h = jobPage(url.pathname.slice(6)); return h || json({error: 'No such job.'}, 404); }
-    if (url.pathname === '/buy' && req.method === 'GET') { count(env, ctx, 'buy'); return new Response(buyPage(url), {headers: {'content-type': 'text/html; charset=utf-8', 'cache-control': 'no-store'}}); }
+    if (url.pathname === '/buy' && req.method === 'GET') { count(env, ctx, 'buy'); const nonce = btoa(String.fromCharCode(...crypto.getRandomValues(new Uint8Array(16))));
+      return new Response(buyPage(url, nonce), {headers: {'content-type': 'text/html; charset=utf-8', 'cache-control': 'no-store', 'content-security-policy': buyCsp(nonce), 'x-content-type-options': 'nosniff', 'referrer-policy': 'no-referrer'}}); }
     if (url.pathname === '/portfolio-watch' && req.method === 'GET') { count(env, ctx, 'portfolio-watch'); try { return json(await portfolioWatch(url.searchParams.get('address'))); } catch (e) { return json({error: e.message}, 400); } }
     if (url.pathname === '/contract-changes' && req.method === 'GET') { count(env, ctx, 'contract-changes'); try { return json(await contractChanges(url.searchParams.get('contract'))); } catch (e) { return json({error: e.message}, 400); } }
     const economyRead = ECON_TOOLS.find(t => t.path === url.pathname);

f1a68f7 /buy CSP: allow https: connects for phone wallet browsers (#197)

Commit
f1a68f759ce635a090c6f501cd481aa9e0e728e1
Date
Nov 27, 2026, 2:43 AM ET (07:43 UTC)
Fixes
F-1
Verify
git show f1a68f759ce635a090c6f501cd481aa9e0e728e1 in a clone of rh-tx-explain

2 files changed, +2 −2

  • buy-page.test.mjs +1 −1
  • worker.mjs +1 −1
Full diff
diff --git a/buy-page.test.mjs b/buy-page.test.mjs
index 9962d4a..d37c518 100644
--- a/buy-page.test.mjs
+++ b/buy-page.test.mjs
@@ -13,7 +13,7 @@ test('a script-breaking read, token or extra parameter never leaves its string,
   const evil = encodeURIComponent('</script><script>alert(1)</script>'), {r, html} = await page(`?read=${evil}&token=${evil}&address=%E2%80%A8x&zzz=${evil}&from=${'a'.repeat(201)}`);
   const csp = r.headers.get('content-security-policy'), nonce = csp.match(/script-src 'nonce-([^']+)'/)[1];
   assert.equal((html.match(/<script/g) || []).length, 1); assert.ok(html.includes(`<script nonce="${nonce}">`));
-  assert.match(csp, /default-src 'none'/); assert.match(csp, /connect-src 'self'/); assert.match(csp, /frame-ancestors 'none'/); assert.doesNotMatch(csp, /unsafe-inline'[^;]*script|script-src[^;]*unsafe/);
+  assert.match(csp, /default-src 'none'/); assert.match(csp, /connect-src 'self' https:;/); assert.match(csp, /frame-ancestors 'none'/); assert.doesNotMatch(csp, /unsafe-inline'[^;]*script|script-src[^;]*unsafe/);
   const s = scriptOf(html).slice(8);
   assert.ok(!s.includes('</script') && !s.includes('<script') && !s.includes('\u2028'));
   assert.match(s, /sel\.value="money-trail";/); assert.ok(!s.includes('zzz')); assert.ok(!s.includes('a'.repeat(201)));
diff --git a/worker.mjs b/worker.mjs
index 9869a7d..4dbb20f 100644
--- a/worker.mjs
+++ b/worker.mjs
@@ -1773,7 +1773,7 @@ const qs = t => Object.keys(t.inputSchema.properties).map(k => `${k}={${k}}`).jo
 // characters); every value placed in the script is JSON with <, U+2028 and U+2029 escaped, and the page runs under a
 // nonce CSP with no outside sources (HEY Research review, 11-26: `read` was written into the inline script unescaped).
 const jsIn = v => JSON.stringify(v).replace(/</g, '\\u003c').replace(/\u2028/g, '\\u2028').replace(/\u2029/g, '\\u2029');
-const buyCsp = nonce => `default-src 'none'; script-src 'nonce-${nonce}'; style-src 'unsafe-inline'; connect-src 'self'; img-src 'self' data:; base-uri 'none'; form-action 'none'; frame-ancestors 'none'`;
+const buyCsp = nonce => `default-src 'none'; script-src 'nonce-${nonce}'; style-src 'unsafe-inline'; connect-src 'self' https:; img-src 'self' data:; base-uri 'none'; form-action 'none'; frame-ancestors 'none'`; // https: for wallet providers that answer eth_call with a page fetch (phone wallet browsers)
 function buyPage(url, nonce) {
   const tools = PAID_TOOLS.map(t => ({route: t.route, title: t.title, price: t.price, inputs: Object.entries(t.inputSchema.properties).map(([k, v]) => ({k, d: v.description || k, req: (t.inputSchema.required || []).includes(k)}))}));
   const asked = url.searchParams.get('read'), pick = tools.some(t => t.route === asked) ? asked : 'money-trail';

F-3: Paid reads settled on incomplete data when a chain node returned an error

Low (3.7, CWE-754) · HEY: Fixed in a6937b1, 04a94df, 007d04b. Details in HEY's report.

a6937b1 Paid reads: a node error is never read as an empty answer; bad payment headers and unoffered networks are refused locally (#198)

Commit
a6937b1822405d6eace6a2415e3553396654ea71
Date
Nov 27, 2026, 3:42 AM ET (08:42 UTC)
Fixes
F-3
Verify
git show a6937b1822405d6eace6a2415e3553396654ea71 in a clone of rh-tx-explain
- rpcBatch (worker.mjs) and poison.mjs batch: only an execution revert is a call's answer (null). Any other per-call
  error (node error, rate limit, pruned state) fails the attempt, the next node is tried, and in the end the read throws,
  so a paid read is never settled on it. A range too large throws at once for callers that split it (tokenLogs).
- paid-complete: a non-empty `partial` list (income_read's unread parts) is an incomplete read, never charged.
- x402: an X-PAYMENT decoding to null / a non-object is a 402 "Bad payment header" (was a 500); a payment on a network
  the read never offered is refused before any facilitator call (after the specific Base/Solana refusals).
- Usage counter: only routed /x402 paths get their own key.
- income_read: fractional days are floored (days=1.5 was a BigInt error).
- Tests: hey-retest.test.mjs (node error vs revert, poison-check and transfer-read end to end never settled, null header,
  unoffered network, partial list).

5 files changed, +91 −6

  • hey-retest.test.mjs +68 −0
  • income.mjs +1 −1
  • paid-complete.mjs +3 −3
  • poison.mjs +4 −1
  • worker.mjs +15 −1
Full diff
diff --git a/hey-retest.test.mjs b/hey-retest.test.mjs
new file mode 100644
index 0000000..7cdea38
--- /dev/null
+++ b/hey-retest.test.mjs
@@ -0,0 +1,68 @@
+// HEY Research review (11-26) retest: F-3 (a node error is never read as an empty answer) and the informational notes
+// I-2 (base64 "null" payment header), I-3 (a network never offered), I-6 (fractional days). Mocked chain and facilitators only.
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import {DatabaseSync} from 'node:sqlite';
+import {d1} from './test-d1.mjs';
+import worker, {transferRead} from './worker.mjs';
+import {readChain} from './poison.mjs';
+import {incompleteRead} from './paid-complete.mjs';
+
+const A = '0x' + '1'.repeat(40), TX = '0x' + '2'.repeat(64);
+let mode = 'error', verified = 0, settled = 0;
+const answer = x => {
+  if (x.method === 'eth_chainId') return '0x1237';
+  if (x.method === 'eth_getBlockByNumber') return {number: '0x100', hash: '0x' + 'a'.repeat(64), timestamp: '0x' + Math.floor(Date.now() / 1000).toString(16)};
+  if (x.method === 'eth_call' && String(x.params?.[0]?.data).startsWith('0x6352211e')) return '0x' + '0'.repeat(24) + 'ff122dfec6029510aa36996ec6f5a67c84d75bdb';
+  if (x.method === 'eth_getCode') return x.params[0].toLowerCase() === A ? '0x6080' : '0x';
+  if (x.method === 'eth_blockNumber') return '0x1000000';
+  return undefined;
+};
+globalThis.fetch = async (input, init) => {
+  const url = String(input);
+  if (url.endsWith('/verify')) { verified++; return Response.json({isValid: true}); }
+  if (url.endsWith('/settle')) { settled++; return Response.json({success: true, transaction: TX, payer: A}); }
+  const body = JSON.parse(init.body), arr = Array.isArray(body) ? body : [body];
+  const out = arr.map(x => { const v = answer(x); if (v !== undefined) return {jsonrpc: '2.0', id: x.id, result: v};
+    if (mode === 'revert' && x.method === 'eth_call') return {jsonrpc: '2.0', id: x.id, error: {code: 3, message: 'execution reverted'}};
+    if (mode === 'error') return {jsonrpc: '2.0', id: x.id, error: {code: -32000, message: 'synthetic node error'}};
+    return {jsonrpc: '2.0', id: x.id, result: x.method === 'eth_getLogs' ? [] : '0x' + '0'.repeat(64)}; });
+  return Response.json(Array.isArray(body) ? out : out[0]);
+};
+
+test('F-3: a node error on a call fails the read; an execution revert is still the call\'s own answer', async () => {
+  mode = 'error'; await assert.rejects(transferRead(A), /RPC call failed .*nothing was charged/);
+  await assert.rejects(readChain([['eth_getLogs', [{address: A}]]]), /unavailable right now; nothing was charged/);
+  mode = 'revert'; const r = await transferRead(A);
+  assert.equal(r.owner, null); assert.match(r.verdict, /no owner\(\) on this contract/);
+  assert.deepEqual(await readChain([['eth_call', [{to: A, data: '0x8da5cb5b'}, 'latest']]]), [null]);
+});
+
+const ENV = {CITY_WALLET: '0x0C0B48Beba6c89CE591b0092B1F5EA83481D2906', QDB: d1(new DatabaseSync(':memory:'))};
+const b64 = s => Buffer.from(s).toString('base64');
+const paidGet = (path, header) => worker.fetch(new Request('https://f.example/x402/' + path, {headers: {'x-payment': header}}), ENV, {waitUntil: () => {}});
+
+test('F-3 end to end: poison-check and transfer-read on an erroring node are refused and never settled', async () => {
+  mode = 'error';
+  for (const [i, path] of ['poison-check?address=' + A, 'transfer-read?contract=' + A].entries()) {
+    verified = settled = 0;
+    const r = await paidGet(path, b64(JSON.stringify({x402Version: 1, network: 'robinhood', payload: {signature: '0x' + 'ab'.repeat(65), authorization: {from: A, nonce: '0x' + (i + 7).toString(16).padStart(64, '0')}}})));
+    assert.equal(r.status, 400, path); assert.match((await r.json()).error, /nothing was charged/); assert.equal(settled, 0, path);
+  }
+});
+
+test('I-2: an X-PAYMENT that decodes to null is a 402 "Bad payment header", not a 500', async () => {
+  mode = 'ok'; verified = 0;
+  for (const h of [b64('null'), b64('[]'), b64('7')]) { const r = await paidGet('poison-check?address=' + A, h); assert.equal(r.status, 402); assert.match((await r.json()).error, /Bad payment header/); }
+  assert.equal(verified, 0);
+});
+
+test('I-3: a payment on a network the read never offered is refused locally; no facilitator is asked', async () => {
+  mode = 'ok'; verified = 0;
+  const r = await paidGet('poison-check?address=' + A, b64(JSON.stringify({x402Version: 1, network: 'ethereum', payload: {signature: '0x', authorization: {from: A, nonce: '0x01'}}})));
+  assert.equal(r.status, 402); assert.match((await r.json()).error, /Network ethereum was not offered/); assert.equal(verified, 0);
+});
+
+test('a partial list (income_read\'s unread parts) is an incomplete read, never charged', () => {
+  assert.equal(incompleteRead({partial: ['outgoing transfers']}), true); assert.equal(incompleteRead({partial: []}), false);
+});
diff --git a/income.mjs b/income.mjs
index d724024..d1fe893 100644
--- a/income.mjs
+++ b/income.mjs
@@ -71,7 +71,7 @@ async function morphoMarkets(borrowLogs, repayLogs) {
     ...repayLogs.filter(l => usdgIds.includes(l.topics[1])).map(l => ev(l, 'repay', word(l.data, 0)))];
 }
 export async function incomeRead(target, days = 30) {
-  days = Math.min(60, Math.max(1, Number(days) || 30));
+  days = Math.min(60, Math.max(1, Math.floor(Number(days)) || 30)); // HEY I-6: days=1.5 was a BigInt error
   let agentId = null, wallet = null, own = new Set();
   if (/^\d+$/.test(String(target || ''))) {
     agentId = String(target); const id = BigInt(agentId).toString(16).padStart(64, '0');
diff --git a/paid-complete.mjs b/paid-complete.mjs
index 0460817..b62767d 100644
--- a/paid-complete.mjs
+++ b/paid-complete.mjs
@@ -1,7 +1,7 @@
 // A paid read that comes back incomplete is never charged (HEY Research review, 11-26: "partial reads still settle").
-// full_check returns complete:false with the reads that failed; a budgeted read names what is still running in `pending`
+// full_check returns complete:false with the reads that failed; income_read names unread parts in a partial list; a budgeted read names what is still running in `pending`
 // or marks itself partial. x402 (USDG / USDC), token pay ($FLOW, $RCPT, any coin) and Raeto Pay all release the payment
 // on an incomplete read and say which part failed, so the buyer calls again and pays once, for a whole read.
-export const incompleteRead = r => !!r && typeof r === 'object' && (r.complete === false || r.partial === true || (Array.isArray(r.pending) && r.pending.length > 0));
-export const missingParts = r => [...(Array.isArray(r?.failedReads) ? r.failedReads : []), ...(Array.isArray(r?.pending) ? r.pending : [])].map(String).slice(0, 10);
+export const incompleteRead = r => !!r && typeof r === 'object' && (r.complete === false || r.partial === true || (Array.isArray(r.partial) && r.partial.length > 0) || (Array.isArray(r.pending) && r.pending.length > 0));
+export const missingParts = r => [...(Array.isArray(r?.failedReads) ? r.failedReads : []), ...(Array.isArray(r?.partial) ? r.partial : []), ...(Array.isArray(r?.pending) ? r.pending : [])].map(String).slice(0, 10);
 export const incompleteText = r => { const m = missingParts(r); return `Part of this read did not come back${m.length ? ' (' + m.join(', ') + ')' : ''}; nothing was charged. Call again.`; };
diff --git a/poison.mjs b/poison.mjs
index 33769d2..3fc1cf7 100644
--- a/poison.mjs
+++ b/poison.mjs
@@ -35,7 +35,10 @@ async function batch(calls) {
   for (let i = 0, tries = calls.length > 1 ? 3 : 9; i < tries; i++) {
     try {
       const r = await fetch(i % 2 ? RPC : RPC_ALT, {method: 'POST', headers: {'content-type': 'application/json', 'user-agent': 'njc-tx-explain/1'}, body: JSON.stringify(calls.map(([method, params], id) => ({jsonrpc: '2.0', id, method, params}))), signal: AbortSignal.timeout(6000)}); // a hung proxy call (~10.7 s under load) retries instead of waiting
-      const j = await r.json(); if (!Array.isArray(j)) throw new Error('bad'); const out = []; for (const x of j) out[x.id] = x.error ? null : x.result; return out;
+      const j = await r.json(); if (!Array.isArray(j)) throw new Error('bad');
+      // HEY Research F-3: only an execution revert is an answer (null); any other per-call error fails the attempt (retry, split, then throw).
+      if (j.some(x => x?.error && !(x.error.code === 3 || /revert/i.test(String(x.error.message || ''))))) throw new Error('call error');
+      const out = []; for (const x of j) out[x.id] = x.error ? null : x.result; return out;
     } catch { await new Promise(res => setTimeout(res, 300 * (i + 1))); }
   }
   if (calls.length > 1) { const half = calls.length >> 1; return [...await batch(calls.slice(0, half)), ...await batch(calls.slice(half))]; }
diff --git a/worker.mjs b/worker.mjs
index 4dbb20f..d9e5441 100644
--- a/worker.mjs
+++ b/worker.mjs
@@ -102,6 +102,8 @@ const addr = t => '0x' + t.slice(26).toLowerCase();
 const short = a => a ? a.slice(0, 6) + '…' + a.slice(-4) : '?';
 
 // One HTTP request for many calls: the public RPC rate-limits by request count.
+export const callReverted = e => e?.code === 3 || /revert/i.test(String(e?.message || ''));
+const rangeTooLarge = m => /exceed|too many results|block range|range too|response size|more than \d+ (results|logs)/i.test(m) && !/rate|too many requests/i.test(m);
 async function rpcBatch(calls, list = RPCS) {
   for (let i = 0; ; i++) {
     const RPC = list[i % list.length];
@@ -111,6 +113,12 @@ async function rpcBatch(calls, list = RPCS) {
     catch (e) { if (i < 7) { await new Promise(res => setTimeout(res, 150 * (i + 1))); continue; } throw new Error('RPC unavailable (' + (e?.message || 'network error') + ')'); }
     if (r.status === 429 && i < 7) { await new Promise(res => setTimeout(res, 400 * (i + 1))); continue; }
     const j = await r.json().catch(() => null); if (!Array.isArray(j)) { if (i < 7) { await new Promise(res => setTimeout(res, 150 * (i + 1))); continue; } throw new Error('RPC unavailable (HTTP ' + r.status + ')'); }
+    // HEY Research F-3: a per-call error is never an empty answer. An execution revert is the call's own answer (null); any
+    // other error (node error, rate limit, pruned state) fails this attempt and the next node is tried; in the end the read
+    // throws, so a paid read is never settled on it. A range that is too large throws at once, for callers that split it.
+    const bad = j.find(x => x?.error && !callReverted(x.error));
+    if (bad) { const m = String(bad.error.message || bad.error.code || 'error'); if (i < 7 && !rangeTooLarge(m)) { await new Promise(res => setTimeout(res, 150 * (i + 1))); continue; }
+      throw new Error('RPC call failed (' + m.slice(0, 120) + '); nothing was charged.'); }
     const out = []; for (const x of j) out[x.id] = x.error ? null : x.result; return out;
   }
 }
@@ -815,6 +823,7 @@ export async function control(agentId) {
 }
 
 // Usage counts per route per day (approximate: KV is not atomic). GET /stats reads them.
+const X402_ROUTES = new Set(['base-trail', 'base-verdict', 'credit-certificate', 'full-check', 'halt-check', 'income-read', 'intel', 'ledger', 'line-read', 'money-trail', 'poison-check', 'riff', 'send-check', 'set', 'sol-trail', 'tba-read', 'transfer-read']);
 async function count(env, ctx, route) {
   if (!env?.USAGE) return;
   const k = new Date().toISOString().slice(0, 10) + ':' + route;
@@ -1021,9 +1030,12 @@ async function paid(req, url, work, reqOf = ledgerReq, {perks = true, tokens = t
   if (!header) return offer('Payment required', 402, [...await tokenOffers({usd, payTo: requirement.payTo, basePayTo: baseReq?.payTo, path: url.pathname + url.search, seal: SEAL()}).catch(() => []),
     {token: 'any coin', chains: ['robinhood', 'base'], how: `Any ERC-20 on Robinhood Chain or Base whose deepest pool holds at least $${Math.max(ANY_MIN_LIQ_USD, ANY_LIQ_MULTIPLE * usd)}: call this URL again with X-PAY-TOKEN: <chain>:<token address> for a pinned quote in that coin.`}]);
   let payload; try { payload = JSON.parse(decodeURIComponent(escape(atob(header)))); } catch { return offer('Bad payment header'); }
+  if (!payload || typeof payload !== 'object' || Array.isArray(payload)) return offer('Bad payment header'); // HEY I-2: base64 "null" was a 500
   const net = payload.accepted?.network ?? payload.network ?? '', onBase = net === 'base' || net === 'eip155:8453', onSol = net === 'solana' || net === SOL_V2;
   if (onBase && !baseReq) return offer('This Cat takes Base USDC only when its holder is a plain wallet; pay on Robinhood Chain');
   if (onSol && !solReq) return offer('No holder-authorized Solana receiver is bound for this Cat; use an advertised payment alternative');
+  // HEY I-3: a payment on a network this read never offered is refused here, never forwarded to a facilitator.
+  if (![...accepts.map(a => a.network), req2?.network, base2?.network, sol2?.network].includes(net)) return offer('Network ' + String(net).slice(0, 40) + ' was not offered for this read');
   const isV2 = payload.x402Version === 2 || /^(eip155|solana):/.test(net), chosen = onSol ? solReq : onBase ? baseReq : requirement, facilitator = onSol || onBase ? BASE_FACILITATOR : FACILITATOR;
   const body = JSON.stringify(isV2 ? {x402Version: 2, paymentPayload: payload, paymentRequirements: onSol ? sol2 : onBase ? base2 : req2} : {x402Version: payload.x402Version ?? 1, paymentPayload: payload, paymentRequirements: chosen});
   // JazzCat #1's Robinhood sales settle through the Priors facilitator first (its merchant key), so each one is a receipt
@@ -1124,6 +1136,7 @@ async function x402Charge(req, url, {micro, payTo, solPayTo, description, erc800
   const header = req.headers.get('x-payment') || req.headers.get('payment-signature');
   if (!header) return offer('Payment required');
   let payload; try { payload = JSON.parse(decodeURIComponent(escape(atob(header)))); } catch { return offer('Bad payment header'); }
+  if (!payload || typeof payload !== 'object' || Array.isArray(payload)) return offer('Bad payment header'); // HEY I-2: base64 "null" was a 500
   const net = payload.accepted?.network ?? payload.network ?? '', onBase = net === 'base' || net === 'eip155:8453', onSol = net === 'solana' || net === SOL_V2;
   const chosen = onSol ? solReq : onBase ? baseReq : base;
   if (!chosen) return offer(`Pay on ${reqs.map(r => r.network).join(' or ')}.`);
@@ -2028,7 +2041,8 @@ export default {
     }
     if (url.pathname.startsWith('/x402/')) {
       const ua = (req.headers.get('user-agent') || 'none').replace(/[^A-Za-z0-9._/ -]/g, '').slice(0, 40);
-      count(env, ctx, url.pathname.slice(6) + (req.headers.get('x-payment') || req.headers.get('payment-signature') ? ':paid-attempt' : ':offer') + ':' + ua);
+      const routed = X402_ROUTES.has(url.pathname.slice(6)) ? url.pathname.slice(6) : 'x402/unrouted'; // HEY I-5: no KV key per made-up path
+      count(env, ctx, routed + (req.headers.get('x-payment') || req.headers.get('payment-signature') ? ':paid-attempt' : ':offer') + ':' + ua);
     }
     if (url.pathname === '/control') count(env, ctx, 'control');
     if (url.pathname === '/mcp' && req.method === 'POST') count(env, ctx, 'mcp');

04a94df Wide log reads: OR topic lists become one query per value; tba history fails closed (#199)

Commit
04a94df853094aead437c782584f88f8d568ac97
Date
Nov 27, 2026, 3:54 AM ET (08:54 UTC)
Fixes
F-3
Verify
git show 04a94df853094aead437c782584f88f8d568ac97 in a clone of rh-tx-explain
The official node now answers a wide eth_getLogs only with one value per topic position. transfer-read and
contract-changes sent an OR list over 9M blocks: the error was read as "no events" before #198, and after #198 the
read correctly failed. rpcBatch now sends one query per value in the same batch and merges the answers in chain order;
tba.mjs (wallet-handover / tba-read) does the same per window, and its reader fails on a non-revert node error.
Checked against the live chain: contract-changes 200 in 2.3 s, transfer-read reads its window, tba history on Robinhood Chain.

3 files changed, +50 −3

  • hey-retest.test.mjs +24 −0
  • tba.mjs +10 −3
  • worker.mjs +16 −0
Full diff
diff --git a/hey-retest.test.mjs b/hey-retest.test.mjs
index 7cdea38..42ece2f 100644
--- a/hey-retest.test.mjs
+++ b/hey-retest.test.mjs
@@ -66,3 +66,27 @@ test('I-3: a payment on a network the read never offered is refused locally; no
 test('a partial list (income_read\'s unread parts) is an incomplete read, never charged', () => {
   assert.equal(incompleteRead({partial: ['outgoing transfers']}), true); assert.equal(incompleteRead({partial: []}), false);
 });
+
+// The official node refuses an OR topic list over 100,000 blocks ("send one value per position"): rpcBatch sends one query
+// per value and merges the answers back in chain order, so wide reads (transfer-read, contract-changes) read every event.
+import {splitOrTopics} from './worker.mjs';
+test('an OR topic list becomes one query per value (every position), and single-value queries pass through', () => {
+  const q = splitOrTopics(['eth_getLogs', [{address: '0xa', fromBlock: '0x1', toBlock: 'latest', topics: [['0x1', '0x2'], null, ['0x3', '0x4']]}]]);
+  assert.deepEqual(q.map(c => c[1][0].topics), [['0x1', null, '0x3'], ['0x1', null, '0x4'], ['0x2', null, '0x3'], ['0x2', null, '0x4']]);
+  assert.ok(q.every(c => c[1][0].address === '0xa' && c[1][0].fromBlock === '0x1'));
+  const one = ['eth_getLogs', [{address: '0xa', topics: ['0x1']}]]; assert.deepEqual(splitOrTopics(one), [one]);
+  const call = ['eth_call', [{to: '0xa', data: '0x'}, 'latest']]; assert.deepEqual(splitOrTopics(call), [call]);
+});
+test('transfer-read sends one query per ownership event and merges them in chain order', async () => {
+  const seen = [], real = globalThis.fetch;
+  globalThis.fetch = async (url, init) => { const body = JSON.parse(init.body);
+    return Response.json(body.map(x => { seen.push(x.params?.[0]?.topics);
+      if (x.method === 'eth_getLogs') { const t = x.params[0].topics[0]; return {jsonrpc: '2.0', id: x.id, result: t.startsWith('0x38d1') ? [{topics: [t, '0x' + '0'.repeat(24) + 'aa'.repeat(20), '0x' + '0'.repeat(24) + 'bb'.repeat(20)], blockNumber: '0x20', logIndex: '0x1', transactionHash: TX}] : [{topics: [t, '0x' + '0'.repeat(64), '0x' + '0'.repeat(24) + 'aa'.repeat(20)], blockNumber: '0x10', logIndex: '0x0', transactionHash: TX}]}; }
+      if (x.method === 'eth_blockNumber') return {jsonrpc: '2.0', id: x.id, result: '0x1000000'};
+      if (x.method === 'eth_getCode') return {jsonrpc: '2.0', id: x.id, result: '0x6080'};
+      return {jsonrpc: '2.0', id: x.id, result: '0x' + '0'.repeat(24) + (x.params[0].data === '0x8da5cb5b' ? 'aa'.repeat(20) : 'bb'.repeat(20))}; })); };
+  try { const r = await transferRead(A);
+    assert.equal(seen.filter(t => Array.isArray(t) && Array.isArray(t[0])).length, 0, 'no OR list reaches the node');
+    assert.deepEqual(r.events.map(e => e.block), [16, 32]); assert.equal(r.transferOpen, true); assert.ok(r.startedAt);
+  } finally { globalThis.fetch = real; }
+});
diff --git a/tba.mjs b/tba.mjs
index 2eebb70..23763c8 100644
--- a/tba.mjs
+++ b/tba.mjs
@@ -14,7 +14,10 @@ async function rpc(chain, calls) {
   for (let i = 0; i < 9; i++) {
     try {
       const r = await fetch(urls[i % urls.length], {method: 'POST', headers: {'content-type': 'application/json', 'user-agent': 'njc-tx-explain/1'}, body: JSON.stringify(calls.map(([method, params], id) => ({jsonrpc: '2.0', id, method, params})))});
-      const j = await r.json(); if (!Array.isArray(j)) throw new Error('bad'); const out = []; for (const x of j) out[x.id] = x.error ? null : x.result; return out;
+      const j = await r.json(); if (!Array.isArray(j)) throw new Error('bad');
+      // HEY Research F-3: only an execution revert is a call's answer (null); any other per-call error fails the attempt.
+      if (j.some(x => x?.error && !(x.error.code === 3 || /revert/i.test(String(x.error.message || ''))))) throw new Error('call error');
+      const out = []; for (const x of j) out[x.id] = x.error ? null : x.result; return out;
     } catch { await new Promise(res => setTimeout(res, 300 * (i + 1))); }
   }
   throw new Error('Chain RPC unavailable right now; nothing was charged.');
@@ -37,8 +40,12 @@ export async function tbaRead(account, chain = 'base') {
   const logs = []; let to = latest, wins = 0, reachedStart = false;
   while (wins < maxWin) {
     const from = to > step ? to - step + 1n : 0n; wins++;
-    const [w] = await rpc(chain, [['eth_getLogs', [{address: a, fromBlock: '0x' + from.toString(16), toBlock: '0x' + to.toString(16), topics: [[PERM, OVR, LOCK]]}]]]);
-    if (w) logs.unshift(...w);
+    // One query per event (the Robinhood Chain node refuses an OR topic list over 100,000 blocks), merged in chain order; a
+    // window that does not answer fails the read (HEY F-3), never a silent gap.
+    const range = {address: a, fromBlock: '0x' + from.toString(16), toBlock: '0x' + to.toString(16)};
+    const parts = await rpc(chain, [PERM, OVR, LOCK].map(t => ['eth_getLogs', [{...range, topics: [t]}]]));
+    if (!parts.every(Array.isArray)) throw new Error('The account history could not be read right now; nothing was charged.');
+    logs.unshift(...parts.flat().sort((x, y) => { const d = BigInt(x.blockNumber) - BigInt(y.blockNumber); return d ? (d < 0n ? -1 : 1) : Number(BigInt(x.logIndex) - BigInt(y.logIndex)); }));
     if (from === 0n) { reachedStart = true; break; }
     to = from - 1n;
   }
diff --git a/worker.mjs b/worker.mjs
index d9e5441..95ec4a3 100644
--- a/worker.mjs
+++ b/worker.mjs
@@ -104,7 +104,23 @@ const short = a => a ? a.slice(0, 6) + '…' + a.slice(-4) : '?';
 // One HTTP request for many calls: the public RPC rate-limits by request count.
 export const callReverted = e => e?.code === 3 || /revert/i.test(String(e?.message || ''));
 const rangeTooLarge = m => /exceed|too many results|block range|range too|response size|more than \d+ (results|logs)/i.test(m) && !/rate|too many requests/i.test(m);
+// The official node serves a wide log range only with one value per topic position ("send one value per position"); an
+// OR list over more than 100,000 blocks is refused. So an eth_getLogs with OR lists is sent as one query per value, in the
+// same batch, and the answers are merged back in chain order (block, then log index).
+export function splitOrTopics(call) {
+  const [method, params] = call; if (method !== 'eth_getLogs' || !Array.isArray(params?.[0]?.topics)) return [call];
+  const f = params[0], i = f.topics.findIndex(t => Array.isArray(t) && t.length > 1); if (i < 0) return [call];
+  return f.topics[i].flatMap(v => splitOrTopics([method, [{...f, topics: f.topics.map((t, k) => k === i ? v : t)}, ...params.slice(1)]]));
+}
+const chainOrder = (a, b) => { const d = BigInt(a.blockNumber) - BigInt(b.blockNumber); return d ? (d < 0n ? -1 : 1) : Number(BigInt(a.logIndex) - BigInt(b.logIndex)); };
 async function rpcBatch(calls, list = RPCS) {
+  const plan = calls.map(splitOrTopics);
+  if (plan.every(p => p.length === 1)) return rpcBatchRaw(calls, list);
+  const got = await rpcBatchRaw(plan.flat(), list); let k = 0;
+  return plan.map(p => { const parts = got.slice(k, k += p.length); if (p.length === 1) return parts[0];
+    return parts.every(Array.isArray) ? parts.flat().sort(chainOrder) : null; });
+}
+async function rpcBatchRaw(calls, list = RPCS) {
   for (let i = 0; ; i++) {
     const RPC = list[i % list.length];
     // A node that drops the connection (fetch rejects) is retried on the next node like any other failure (round-2 review).

007d04b HEY retest (11-27): R-1 income-read node errors fail the read; claim nonce shape + validBefore takeover; split-query null part throws; one holder read per offer (#209)

Commit
007d04bb4d40f5da37191381e4a287a2fd7e1207
Date
Nov 27, 2026, 8:37 AM ET (13:37 UTC)
Fixes
F-3, R-1
Verify
git show 007d04bb4d40f5da37191381e4a287a2fd7e1207 in a clone of rh-tx-explain
R-1: income.mjs's own rpc() now follows the rpcBatch/poison.mjs rule: only an execution revert is a call's answer; any other
per-call error, a short batch or unknown ids fails the attempt, and after the retries the read (nothing charged). A
transaction sender that can't be read, a Longbow market that can't be read and missing loan timestamps go in partial,
which is never charged. (A failed getAgentWallet used to read the owner's income; a failed sender lookup counted the
agent's own withdrawal as outside pay. Both were charged.)
(1) An EVM payment must carry from, a 32-byte nonce and validBefore; anything else is refused before verify (both paid
    paths, and claimFor), so one authorization can't be claimed under two spellings.
(2) Claims store valid_before; an unsettled EVM claim is taken over only after validBefore has passed. Solana and
    pre-column claims keep the 10-minute rule.
(3) rpcBatch: a split log query part with no answer throws instead of merging to null (as tba.mjs does).
(4) paidTerms reads the Cat holder once per offer (was twice, ~6 node requests per unpaid 402).
Tests: hey-retest2.test.mjs (R-1, 1, 2, 3), paid-terms one-read test; fixtures now carry well-formed authorizations.
Full suite 527/529 (bazaar needs ajv; oak fork-test needs viem; both fail on main too).

11 files changed, +182 −33

  • credit-cert.test.mjs +2 −1
  • hey-retest.test.mjs +1 −1
  • hey-retest2.test.mjs +93 −0
  • income.mjs +23 −8
  • paid-incomplete.test.mjs +1 −1
  • paid-success.test.mjs +2 −2
  • paid-terms.test.mjs +7 −2
  • round2-worker.test.mjs +10 −4
  • worker.mjs +14 −5
  • x402-claim.mjs +27 −7
  • x402-claim.test.mjs +2 −2
Full diff
diff --git a/credit-cert.test.mjs b/credit-cert.test.mjs
index 0c535f9..b929c62 100644
--- a/credit-cert.test.mjs
+++ b/credit-cert.test.mjs
@@ -54,7 +54,8 @@ globalThis.fetch = async (input, init) => {
 const env = {CITY_WALLET: CITY, CERT_KEY: KEY, QDB};
 // Each call carries its own payment: one payment buys one certificate (x402-claim.mjs).
 let n = 0;
-const pay = network => ({'x-payment': Buffer.from(JSON.stringify({x402Version: 1, network, payload: 'fixture-' + (n++)})).toString('base64')});
+// A well-formed EIP-3009 authorization (HEY retest note: malformed payments are refused before verify), a fresh nonce each time.
+const pay = network => ({'x-payment': Buffer.from(JSON.stringify({x402Version: 1, network, payload: {signature: '0x' + 'ab'.repeat(65), authorization: {from: PAYER, to: CITY, value: '250000', validAfter: '0', validBefore: '9999999999', nonce: '0x' + (n++).toString(16).padStart(64, 'f')}}})).toString('base64')});
 
 test('unpaid: a 402 at 0.25 USD to the City on Robinhood Chain, Base (7702 EOA) and Solana, without reading the file', async () => {
   verified = settled = fileReads = 0;
diff --git a/hey-retest.test.mjs b/hey-retest.test.mjs
index 42ece2f..d47434c 100644
--- a/hey-retest.test.mjs
+++ b/hey-retest.test.mjs
@@ -46,7 +46,7 @@ test('F-3 end to end: poison-check and transfer-read on an erroring node are ref
   mode = 'error';
   for (const [i, path] of ['poison-check?address=' + A, 'transfer-read?contract=' + A].entries()) {
     verified = settled = 0;
-    const r = await paidGet(path, b64(JSON.stringify({x402Version: 1, network: 'robinhood', payload: {signature: '0x' + 'ab'.repeat(65), authorization: {from: A, nonce: '0x' + (i + 7).toString(16).padStart(64, '0')}}})));
+    const r = await paidGet(path, b64(JSON.stringify({x402Version: 1, network: 'robinhood', payload: {signature: '0x' + 'ab'.repeat(65), authorization: {from: A, validBefore: '9999999999', nonce: '0x' + (i + 7).toString(16).padStart(64, '0')}}})));
     assert.equal(r.status, 400, path); assert.match((await r.json()).error, /nothing was charged/); assert.equal(settled, 0, path);
   }
 });
diff --git a/hey-retest2.test.mjs b/hey-retest2.test.mjs
new file mode 100644
index 0000000..810a0d2
--- /dev/null
+++ b/hey-retest2.test.mjs
@@ -0,0 +1,93 @@
+// HEY Research retest (11-27, at 04a94df): R-1 and the four hardening notes. Mocked chain and facilitators only.
+//   R-1: income.mjs read any per-call node error as an empty answer (getAgentWallet fell back to the owner; an unread
+//        transaction sender counted the agent's own withdrawal as outside pay). Now a node error fails the read and an
+//        unread sender is named in partial, so neither is charged.
+//   (1) an EVM payment whose nonce is not exactly 32 bytes is refused before verify;
+//   (2) an unsettled claim is taken over only after its authorization's validBefore has passed;
+//   (3) a split log query with a part that has no answer fails the read instead of merging to "no events";
+//   (4) the unpaid offer reads the Cat holder once (paid-terms.test.mjs).
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import {DatabaseSync} from 'node:sqlite';
+import {d1} from './test-d1.mjs';
+import worker, {transferRead} from './worker.mjs';
+import {incompleteRead} from './paid-complete.mjs';
+import {claimPayment, payloadShapeError, STALE_MS} from './x402-claim.mjs';
+
+globalThis.NJC_RPC_BACKOFF_MS = 1; // income.mjs retries fast in tests
+const A = '0x' + '1'.repeat(40), OWNER = '0x' + '0a'.repeat(20), WALLET = '0x' + '0b'.repeat(20), PAYER = '0x' + '0c'.repeat(20);
+const USDG = '0x5fc5360d0400a0fd4f2af552add042d716f1d168', TRANSFER = '0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef';
+const pad = a => '0x' + a.slice(2).toLowerCase().padStart(64, '0'), TXH = '0x' + '3'.repeat(64);
+let mode = 'ok', verified = 0, settled = 0, splitNull = false;
+globalThis.fetch = async (input, init) => {
+  const url = String(input);
+  if (url.endsWith('/verify')) { verified++; return Response.json({isValid: true}); }
+  if (url.endsWith('/settle')) { settled++; return Response.json({success: true, transaction: TXH, payer: A}); }
+  const body = JSON.parse(init.body), arr = Array.isArray(body) ? body : [body];
+  let firstLogs = true;
+  const out = arr.map(x => {
+    const ok = result => ({jsonrpc: '2.0', id: x.id, result}), d = String(x.params?.[0]?.data || '');
+    if (x.method === 'eth_blockNumber') return ok('0x1000000');
+    if (x.method === 'eth_chainId') return ok('0x1237');
+    if (x.method === 'eth_getCode') return ok(String(x.params[0]).toLowerCase() === A ? '0x6080' : '0x');
+    if (x.method === 'eth_getBlockByNumber') return ok({number: '0x100', hash: '0x' + 'a'.repeat(64), timestamp: '0x' + Math.floor(Date.now() / 1000).toString(16)});
+    if (x.method === 'eth_call' && d.startsWith('0x6352211e')) return ok(pad(OWNER));
+    if (x.method === 'eth_call' && d.startsWith('0x00339509')) return mode === 'walletError' ? {jsonrpc: '2.0', id: x.id, error: {code: -32000, message: 'header not found'}} : ok(pad(WALLET));
+    if (x.method === 'eth_getLogs') {
+      const t = x.params[0].topics || [];
+      if (splitNull && firstLogs) { firstLogs = false; return ok(null); } // a split part with no answer and no error
+      if (String(x.params[0].address).toLowerCase() === USDG && t[0] === TRANSFER && t[2] === pad(WALLET))
+        return ok([{address: USDG, topics: [TRANSFER, pad(PAYER), pad(WALLET)], data: '0x' + (6_000_000).toString(16).padStart(64, '0'), blockNumber: '0xff0000', transactionHash: TXH, logIndex: '0x0'}]);
+      return ok([]);
+    }
+    if (x.method === 'eth_getTransactionByHash') return ok(mode === 'noSender' ? null : {hash: x.params[0], from: PAYER});
+    if (x.method === 'eth_call') return {jsonrpc: '2.0', id: x.id, error: {code: 3, message: 'execution reverted'}};
+    return ok('0x');
+  });
+  return Response.json(Array.isArray(body) ? out : out[0]);
+};
+
+test('R-1: a failed getAgentWallet fails the read (nothing charged); it no longer reads the owner\'s income', async () => {
+  const {incomeRead} = await import('./income.mjs');
+  mode = 'walletError'; await assert.rejects(incomeRead('7', 7), /nothing was charged/);
+  mode = 'ok'; const r = await incomeRead('7', 7);
+  assert.equal(r.wallet, WALLET); assert.equal(r.income.outsideUsdg, 6); assert.equal(r.partial, undefined); assert.equal(incompleteRead(r), false);
+});
+
+test('R-1: a transaction sender that can\'t be read goes in partial, so the answer is never charged', async () => {
+  const {incomeRead} = await import('./income.mjs');
+  mode = 'noSender'; const r = await incomeRead('7', 7);
+  assert.deepEqual(r.partial, ['the senders of 1 incoming transaction']); assert.equal(incompleteRead(r), true);
+  mode = 'ok';
+});
+
+test('(3) a split log query with a part that has no answer fails the read instead of reporting no events', async () => {
+  mode = 'ok'; splitNull = true;
+  await assert.rejects(transferRead(A), /split log query had no answer.*nothing was charged/);
+  splitNull = false;
+});
+
+const ENV = {CITY_WALLET: '0x0C0B48Beba6c89CE591b0092B1F5EA83481D2906', QDB: d1(new DatabaseSync(':memory:'))};
+const b64 = s => Buffer.from(s).toString('base64');
+const pay = auth => b64(JSON.stringify({x402Version: 1, network: 'robinhood', payload: {signature: '0x' + 'ab'.repeat(65), authorization: {from: A, validBefore: '9999999999', nonce: '0x' + '4'.repeat(64), ...auth}}}));
+
+test('(1) an EVM payment whose nonce is not exactly 32 bytes, or with no validBefore, is refused before verify', async () => {
+  assert.match(payloadShapeError({network: 'robinhood', payload: {authorization: {from: A, nonce: '0x01', validBefore: '1'}}}), /exactly 32 bytes/);
+  assert.match(payloadShapeError({network: 'robinhood', payload: {authorization: {from: A, nonce: '0x' + '4'.repeat(64)}}}), /validBefore/);
+  assert.equal(payloadShapeError({network: 'solana', payload: {transaction: 'AA=='}}), null);
+  mode = 'ok'; verified = settled = 0;
+  for (const auth of [{nonce: '0x01'}, {nonce: '0x' + '4'.repeat(63)}, {nonce: '0x' + '4'.repeat(66)}, {validBefore: undefined}]) {
+    const r = await worker.fetch(new Request('https://f.example/x402/poison-check?address=' + A, {headers: {'x-payment': pay(auth)}}), ENV, {waitUntil: () => {}});
+    assert.equal(r.status, 402, JSON.stringify(auth)); assert.match((await r.json()).error, /Bad payment/);
+  }
+  assert.equal(verified, 0, 'no facilitator was asked'); assert.equal(settled, 0);
+});
+
+test('(2) an unsettled claim is taken over only after its authorization\'s validBefore has passed', async () => {
+  const db = d1(new DatabaseSync(':memory:')), t0 = 1_800_000_000_000, vb = t0 / 1000 + 3600; // valid for one more hour
+  assert.ok(await claimPayment(db, 'p', '/a', t0, vb));
+  assert.equal(await claimPayment(db, 'p', '/b', t0 + STALE_MS + 1, vb), null, 'still valid after 10 minutes: not taken over');
+  assert.equal(await claimPayment(db, 'p', '/b', vb * 1000 - 1, vb), null, 'not even a moment before validBefore');
+  assert.ok(await claimPayment(db, 'p', '/c', vb * 1000 + 1, vb), 'taken over once the authorization can no longer settle');
+  assert.ok(await claimPayment(db, 's', '/sol', t0, null)); assert.ok(await claimPayment(db, 's', '/sol2', t0 + STALE_MS + 1, null), 'Solana keeps the 10-minute rule');
+});
diff --git a/income.mjs b/income.mjs
index d1fe893..43dbf9d 100644
--- a/income.mjs
+++ b/income.mjs
@@ -13,15 +13,25 @@ const KNOWN = {'0x281210097f0de7a8fb6f87310af0f089c9c8de21': 'loan', '0x8366a39c
   '0xbdbae060cbab0e9cfe802a7513dd5ecb36cda6c3': 'swap', '0xe8852602f84e04e284286d8db01a41edd0ccefb0': 'swap', '0x8876789976decbfcbbbe364623c63652db8c0904': 'swap'};
 const BLOCKS_PER_DAY = 820000n;
 const pad = a => '0x' + a.toLowerCase().slice(2).padStart(64, '0'), addr = w => '0x' + w.slice(-40).toLowerCase();
-async function rpc(calls) {
+// HEY R-1 (11-27): the rpcBatch / poison.mjs rule. Only an execution revert is a call's answer (null). Any other per-call
+// error, a reply that is not the whole batch, or a missing id fails the attempt; after the retries the read fails and
+// nothing is charged. It used to turn any per-call error into null, so a failed getAgentWallet read the owner's income
+// and a failed sender lookup counted the agent's own withdrawal as outside pay, both charged.
+export const reverted = e => e?.code === 3 || /revert/i.test(String(e?.message || ''));
+export async function rpc(calls) {
   if (!calls.length) return [];
+  let last = 'no answer';
   for (let i = 0; i < 9; i++) {
     try {
       const r = await fetch(i % 2 ? RPC : RPC_ALT, {method: 'POST', headers: {'content-type': 'application/json', 'user-agent': 'njc-tx-explain/1'}, body: JSON.stringify(calls.map(([method, params], id) => ({jsonrpc: '2.0', id, method, params}))), signal: AbortSignal.timeout(6000)}); // a hung proxy call (~10.7 s under load) retries instead of waiting
-      const j = await r.json(); if (!Array.isArray(j)) throw new Error('bad'); const out = []; for (const x of j) out[x.id] = x.error ? null : x.result; return out;
-    } catch { await new Promise(res => setTimeout(res, 300 * (i + 1))); }
+      const j = await r.json(); if (!Array.isArray(j) || j.length !== calls.length) throw new Error('the node did not answer the whole batch');
+      const bad = j.find(x => x?.error && !reverted(x.error)); if (bad) throw new Error(String(bad.error.message || 'call error').slice(0, 120));
+      const out = new Array(calls.length); const got = new Set();
+      for (const x of j) { if (!Number.isInteger(x?.id) || x.id < 0 || x.id >= calls.length || got.has(x.id)) throw new Error('the node answered with unknown ids'); got.add(x.id); out[x.id] = x.error ? null : x.result; }
+      return out;
+    } catch (e) { last = String(e?.message || 'error').slice(0, 120); await new Promise(res => setTimeout(res, (globalThis.NJC_RPC_BACKOFF_MS ?? 300) * (i + 1))); }
   }
-  throw new Error('Robinhood Chain RPC unavailable right now; nothing was charged.');
+  throw new Error('Robinhood Chain RPC unavailable right now (' + last + '); nothing was charged.');
 }
 // Loan loops: each USDG loan in the window, every USDG the wallet sent while that loan was open, and the repayment that
 // closed it. Two lenders: the Priors pool (loans are plain USDG transfers; the repay is the first transfer back to the pool,
@@ -57,10 +67,11 @@ export function loanLoops({received, sent, own = new Set(), latestBlock = null,
 // Morpho Blue events for the agent: Borrow(id, caller, onBehalf, receiver, assets, shares) and Repay(id, caller, onBehalf,
 // assets, shares), kept only for markets that lend USDG; the collateral's symbol names the loan.
 const BORROW = '0x570954540bed6b1304a87dfe815a5eda4a648f7097a16240dcd85c9b5fd42a43', REPAY = '0x52acb05cebbd3cd39715469f22afbf5a17496295ef3bc9bb5944056c63ccaa09';
-async function morphoMarkets(borrowLogs, repayLogs) {
+async function morphoMarkets(borrowLogs, repayLogs, partial = new Set()) {
   const ids = [...new Set([...borrowLogs, ...repayLogs].map(l => l.topics[1]))]; if (!ids.length) return [];
   const params = await rpc(ids.map(i => ['eth_call', [{to: MORPHO, data: '0x2c3c9157' + i.slice(2)}, 'latest']]));
   const market = new Map(ids.map((i, k) => [i, params[k] && params[k].length >= 130 ? {loan: addr(params[k].slice(0, 66)), collateral: addr('0x' + params[k].slice(66, 130))} : null]));
+  if (ids.some(i => !market.get(i))) partial.add('Longbow market details'); // HEY R-1: a market that can't be read is named, never silently dropped
   const usdgIds = ids.filter(i => market.get(i)?.loan === USDG), cols = [...new Set(usdgIds.map(i => market.get(i).collateral))];
   const syms = cols.length ? await rpc(cols.map(c => ['eth_call', [{to: c, data: '0x95d89b41'}, 'latest']])) : [];
   const symbol = new Map(cols.map((c, k) => { const r = syms[k]; try { const h = r.slice(2), n = parseInt(h.slice(64, 128), 16); return [c, new TextDecoder().decode(Uint8Array.from(h.slice(128, 128 + 2 * n).match(/../g) || [], x => parseInt(x, 16)))]; } catch { return [c, null]; } }));
@@ -93,7 +104,7 @@ export async function incomeRead(target, days = 30) {
     }
   } else if (/^0x[0-9a-fA-F]{40}$/.test(target || '')) { wallet = target.toLowerCase(); own.add(wallet); }
   else throw new Error('agent (an ERC-8004 id) or wallet (0x…) is required.');
-  const [head] = await rpc([['eth_blockNumber', []]]); const latest = BigInt(head), from = latest > BLOCKS_PER_DAY * BigInt(days) ? latest - BLOCKS_PER_DAY * BigInt(days) : 0n;
+  const [head] = await rpc([['eth_blockNumber', []]]); if (!head) throw new Error('Robinhood Chain RPC gave no block number; nothing was charged.'); const latest = BigInt(head), from = latest > BLOCKS_PER_DAY * BigInt(days) ? latest - BLOCKS_PER_DAY * BigInt(days) : 0n;
   const logs = [], sent = [], mBorrow = [], mRepay = [], partial = new Set();
   for (let s = from; s <= latest; s += 9000000n) {
     const e = s + 8999999n < latest ? s + 8999999n : latest;
@@ -113,7 +124,10 @@ export async function incomeRead(target, days = 30) {
 // token's sender, and never count it as outside pay.
   const hashes = [...new Set(logs.map(l => l.transactionHash))], starter = new Map();
   // The read proxy answers at most 40 calls per batch (a batch of 50 came back as an error and the read failed for any busy agent).
-  for (let i = 0; i < hashes.length; i += 40) { const txs = await rpc(hashes.slice(i, i + 40).map(h => ['eth_getTransactionByHash', [h]])); txs.forEach((t, j) => t && starter.set(hashes[i + j], t.from.toLowerCase())); }
+  // HEY R-1: a sender that can't be read is named in partial (a partial read is never charged), never guessed as outside pay.
+  let unread = 0;
+  for (let i = 0; i < hashes.length; i += 40) { const txs = await rpc(hashes.slice(i, i + 40).map(h => ['eth_getTransactionByHash', [h]])); txs.forEach((t, j) => { if (t && /^0x[0-9a-fA-F]{40}$/.test(t.from || '')) starter.set(hashes[i + j], t.from.toLowerCase()); else unread++; }); }
+  if (unread) partial.add(`the senders of ${unread} incoming transaction${unread === 1 ? '' : 's'}`);
   const by = new Map();
   for (const l of logs) {
     const from = addr(l.topics[1]), selfStarted = own.has(starter.get(l.transactionHash)) && !own.has(from) && !KNOWN[from];
@@ -131,11 +145,12 @@ export async function incomeRead(target, days = 30) {
   if (sum('withdrawal')) flags.push(`${sum('withdrawal')} USDG arrived in transactions the agent's own wallet sent (withdrawals, refunds, claims or sales through contracts): not outside pay. Earned fees or escrow it claimed are income; its own deposits coming back are not. A funder trace tells which`);
   if (topShare >= 50) flags.push(`one outside payer is ${topShare}% of outside income`);
   const row = l => ({block: Number(BigInt(l.blockNumber)), tx: l.transactionHash, from: addr(l.topics[1]), to: addr(l.topics[2]), usdg: Number(BigInt(l.data)) / 1e6});
-  const loans = loanLoops({received: logs.map(row), sent: sent.map(row), own, latestBlock: Number(latest), markets: await morphoMarkets(mBorrow, mRepay)});
+  const loans = loanLoops({received: logs.map(row), sent: sent.map(row), own, latestBlock: Number(latest), markets: await morphoMarkets(mBorrow, mRepay, partial)});
   if (loans) {
     const blocks = [...new Set(loans.loops.flatMap(x => [x.borrow.block, x.repay?.block]).filter(Boolean))];
     const got = blocks.length ? await rpc(blocks.map(b => ['eth_getBlockByNumber', ['0x' + b.toString(16), false]])) : [];
     const at = new Map(blocks.map((b, i) => [b, got[i]?.timestamp ? new Date(Number(BigInt(got[i].timestamp)) * 1000).toISOString() : null]));
+    if (blocks.some(b => !at.get(b))) partial.add('loan timestamps');
     for (const x of loans.loops) { x.borrow.at = at.get(x.borrow.block) || null; if (x.repay) { x.repay.at = at.get(x.repay.block) || null; if (x.borrow.at && x.repay.at) x.daysOpen = Math.round((Date.parse(x.repay.at) - Date.parse(x.borrow.at)) / 864e5 * 10) / 10; } }
     flags.push(loans.summary);
   }
diff --git a/paid-incomplete.test.mjs b/paid-incomplete.test.mjs
index a308a3d..7bde465 100644
--- a/paid-incomplete.test.mjs
+++ b/paid-incomplete.test.mjs
@@ -30,7 +30,7 @@ globalThis.fetch = async (input, init) => {
   return Response.json(Array.isArray(JSON.parse(init.body)) ? out : out[0]);
 };
 const ENV = {CITY_WALLET: CITY, QDB: d1(new DatabaseSync(':memory:'))};
-const hdr = {'x-payment': Buffer.from(JSON.stringify({x402Version: 1, network: 'robinhood', payload: {signature: '0x' + 'ab'.repeat(65), authorization: {from: A, nonce: '0x' + 'e5'.repeat(32)}}})).toString('base64')};
+const hdr = {'x-payment': Buffer.from(JSON.stringify({x402Version: 1, network: 'robinhood', payload: {signature: '0x' + 'ab'.repeat(65), authorization: {from: A, validBefore: '9999999999', nonce: '0x' + 'e5'.repeat(32)}}})).toString('base64')};
 const buy = () => worker.fetch(new Request('https://fixture.example/x402/full-check?address=' + A, {headers: hdr}), ENV, {waitUntil: () => {}});
 
 test('an incomplete full_check is never settled, says which part failed, and the same payment works once it is whole', async () => {
diff --git a/paid-success.test.mjs b/paid-success.test.mjs
index d7bda5a..b00d0a2 100644
--- a/paid-success.test.mjs
+++ b/paid-success.test.mjs
@@ -27,7 +27,7 @@ globalThis.fetch=async(input,init)=>{
 // Each request carries its own payment: one payment buys one answer (x402-claim.mjs).
 let n=0;const ENV={CITY_WALLET:CITY,QDB:d1(new DatabaseSync(':memory:'))};
 const request=(network,address=A)=>new Request('https://fixture.example/x402/poison-check?address='+address,
- {headers:{'x-payment':Buffer.from(JSON.stringify({x402Version:1,network,payload:'fixture-no-signature-'+(n++)})).toString('base64')}});
+ {headers:{'x-payment':Buffer.from(JSON.stringify({x402Version:1,network,payload:network==='solana'?'fixture-no-signature-'+(n++):{signature:'0x'+'ab'.repeat(65),authorization:{from:A,validBefore:'9999999999',nonce:'0x'+(n++).toString(16).padStart(64,'e')}}})).toString('base64')}});
 for(const network of ['robinhood','eip155:8453','solana'])test('successful '+network+' paid handler returns its receipt after one synthetic settlement',async()=>{
  verified=settled=reads=0;verify=true;ownerChanged=changeDuringWork=false;
  const response=await worker.fetch(request(network),ENV,{});
@@ -71,7 +71,7 @@ test('an outside holder is never charged into the project Solana receiver',async
 // QA 2026-11-26 (D3): the same paid read sent four times at once with one payment got four answers. Now one.
 test('one payment sent four times at once gets one answer; the other three are refused before any work',async()=>{
  verified=settled=reads=0;verify=true;ownerChanged=changeDuringWork=false;lag=15;
- const h={'x-payment':Buffer.from(JSON.stringify({x402Version:1,network:'robinhood',payload:{signature:'0x'+'ab'.repeat(65),authorization:{from:A,nonce:'0x'+'d4'.repeat(32)}}})).toString('base64')};
+ const h={'x-payment':Buffer.from(JSON.stringify({x402Version:1,network:'robinhood',payload:{signature:'0x'+'ab'.repeat(65),authorization:{from:A,validBefore:'9999999999',nonce:'0x'+'d4'.repeat(32)}}})).toString('base64')};
  const rs=await Promise.all([0,1,2,3].map(()=>worker.fetch(new Request('https://fixture.example/x402/poison-check?address='+A,{headers:h}),ENV,{})));
  lag=0;
  assert.deepEqual(rs.map(r=>r.status).sort(),[200,409,409,409]);assert.equal(settled,1);
diff --git a/paid-terms.test.mjs b/paid-terms.test.mjs
index e35be60..39550f1 100644
--- a/paid-terms.test.mjs
+++ b/paid-terms.test.mjs
@@ -7,12 +7,17 @@ const a=f.indexOf('async function paidTerms('),b=f.indexOf('async function paid(
 const source=f.slice(a,b);
 const CITY='0xCity', CAT='0xCat1', NONHOUSE='0xCat2', HOLDER='0xHolder2';
 const reqOf=resource=>({scheme:'exact',network:'robinhood',resource,payTo:CAT,maxAmountRequired:'900000',extra:{name:'USDG',version:'2'}});
-const cfg=(city)=>({CITY_WALLET:city,CHAIN_ID:4663,BASE_USDC:'base-usdc',SOL_PAYTO:'solana-wallet',
+let holderReads=0;
+const cfg=(city)=>({CITY_WALLET:city,houseHolder:h=>h==='0xHolder1',CHAIN_ID:4663,BASE_USDC:'base-usdc',SOL_PAYTO:'solana-wallet',
  SOL_USDC:'sol-usdc',SOL_FEEPAYER:'existing-facilitator',SOL_V2:'solana:fixture',NJC_8004:()=>({id:26063}),
- houseCat:async id=>id==='1',boundLeg:async()=>null,catWallet:async id=>id==='2'?NONHOUSE:null,catHolderEOA:async id=>id==='2'?HOLDER:'0xHolder1',
+ houseCat:async id=>id==='1',boundLeg:async()=>null,catWallet:async id=>id==='2'?NONHOUSE:null,catHolderEOA:async id=>(holderReads++,id==='2'?HOLDER:id==='1'?'0xHolder1':null),
  v2Of:r=>({scheme:r.scheme,payTo:r.payTo,asset:r.asset,network:'eip155:4663',amount:r.maxAmountRequired})});
 const resolver=city=>runInNewContext(source+';paidTerms',cfg(city));
 const url=(p='')=>new URL('https://example.test/x402/income-read?agent=26063'+p);
+test('the unpaid offer reads the Cat holder once (HEY retest note: it was twice)',async()=>{
+  holderReads=0; await resolver(CITY)(url(),reqOf); assert.equal(holderReads,1);
+  holderReads=0; await resolver(CITY)(url('&cat=2'),reqOf); assert.equal(holderReads,1);
+});
 test('house default uses same known treasury for HTTP and exported challenge',async()=>{
   const r=await resolver(CITY)(url(),reqOf);
   assert.equal(r.requirement.payTo,CITY);
diff --git a/round2-worker.test.mjs b/round2-worker.test.mjs
index 4614e4a..49e6181 100644
--- a/round2-worker.test.mjs
+++ b/round2-worker.test.mjs
@@ -3,14 +3,15 @@
 import test from 'node:test';
 import assert from 'node:assert/strict';
 const EOA = 'e0a'.padEnd(40, '1'), w = n => BigInt(n).toString(16).padStart(64, '0');
-let failIncoming = true, failOutgoing = false;
+let failIncoming = true, failOutgoing = false, failOnce = 0;
+globalThis.NJC_RPC_BACKOFF_MS = 1; // income.mjs retries fast in tests
 globalThis.fetch = async (url, init) => {
   const body = JSON.parse(init.body), calls = Array.isArray(body) ? body : [body];
   const out = calls.map(c => {
     const d = c.params?.[0]?.data || '';
     if (c.method === 'eth_getLogs') {
       const t = c.params[0].topics || [], incoming = t.length === 3 && t[1] === null && t[2], outgoing = t.length === 2 && t[1];
-      if ((incoming && failIncoming) || (outgoing && failOutgoing)) return {jsonrpc: '2.0', id: c.id, error: {code: -32000, message: 'boom'}};
+      if ((incoming && failIncoming) || (outgoing && failOutgoing) || (outgoing && failOnce > 0 && failOnce--)) return {jsonrpc: '2.0', id: c.id, error: {code: -32000, message: 'boom'}};
       return {jsonrpc: '2.0', id: c.id, result: []};
     }
     if (c.method === 'eth_blockNumber') return {jsonrpc: '2.0', id: c.id, result: '0x' + (1e8).toString(16)};
@@ -25,11 +26,16 @@ globalThis.fetch = async (url, init) => {
 };
 test('income: a window whose incoming transfers fail is an error (nothing charged), not a quiet gap', async () => {
   const {incomeRead} = await import('./income.mjs');
+  // HEY R-1 (11-27): only an execution revert is an answer. Any other node error fails the attempt and, after the
+  // retries, the whole read (nothing charged), for incoming and outgoing windows alike.
   failIncoming = true; failOutgoing = false;
-  await assert.rejects(incomeRead('7622', 7), /could not be read/);
+  await assert.rejects(incomeRead('7622', 7), /nothing was charged/);
   failIncoming = false; failOutgoing = true;
+  await assert.rejects(incomeRead('7622', 7), /nothing was charged/);
+  // A one-off node error is retried and the read comes back whole, with nothing in partial.
+  failOutgoing = false; failOnce = 1;
   const r = await incomeRead('7622', 7);
-  assert.deepEqual(r.partial, ['outgoing transfers']); assert.ok(r.flags.some(f => /partial read/.test(f)));
+  assert.equal(r.partial, undefined); assert.equal(failOnce, 0);
 });
 test('city round: an unreadable grant skips the Cat this round and never deactivates it', async () => {
   const {cityRound} = await import('./city.mjs');
diff --git a/worker.mjs b/worker.mjs
index 1b8797b..1ce7973 100644
--- a/worker.mjs
+++ b/worker.mjs
@@ -44,7 +44,7 @@ import {holderPass as holderPassCard} from './holder-pass.mjs';
 import {stakeKitSetup, stakeKitStatus, stakeKitTx, STAKEKIT_V3} from './stakekit.mjs';
 import {desksJson, desksPage} from './desks.mjs';
 import {CERT_PRICE_MICRO, CERT_DOMAIN, CERT_TYPES, certSubject, fetchCreditFile, certify, saveCert, listCerts, listVoided, getCert, signerOf} from './credit-cert.mjs';
-import {claimFor} from './x402-claim.mjs';
+import {claimFor, payloadShapeError} from './x402-claim.mjs';
 import {EVM,solRpc} from './chains.mjs';
 import {LANES,parseWorkCache,projectWorkBoard,readCityWork,workKey} from './work-board.mjs';
 import {presaleList, presaleRow} from './presale.mjs';
@@ -119,7 +119,10 @@ async function rpcBatch(calls, list = RPCS) {
   if (plan.every(p => p.length === 1)) return rpcBatchRaw(calls, list);
   const got = await rpcBatchRaw(plan.flat(), list); let k = 0;
   return plan.map(p => { const parts = got.slice(k, k += p.length); if (p.length === 1) return parts[0];
-    return parts.every(Array.isArray) ? parts.flat().sort(chainOrder) : null; });
+    // HEY retest note: a part with no answer (null, no error) must not merge to null, or transfer-read reports no events
+    // and settles. Throw, as tba.mjs does: the read fails and nothing is charged.
+    if (!parts.every(Array.isArray)) throw new Error('RPC call failed (part of a split log query had no answer); nothing was charged.');
+    return parts.flat().sort(chainOrder); });
 }
 async function rpcBatchRaw(calls, list = RPCS) {
   for (let i = 0; ; i++) {
@@ -238,7 +241,8 @@ const PRIORS_FACILITATOR = 'https://facilitator.priors.trade'; let PRIORS_KEY =
 // treasury holds) pay the city, so the city's ERC-8004 identity carries the income. Holder Cats keep their own pay.
 let CITY_WALLET = null, CERT_KEY = null;
 const HOUSE = new Set(['0xff122dfec6029510aa36996ec6f5a67c84d75bdb', '0x0c0b48beba6c89ce591b0092b1f5ea83481d2906']);
-async function houseCat(n) { return HOUSE.has(((await catHolderEOA(n)) || '').toLowerCase()); }
+const houseHolder = h => HOUSE.has(String(h || '').toLowerCase());
+async function houseCat(n) { return houseHolder(await catHolderEOA(n)); }
 const LEDGER_PRICE = '50000'; // 0.05 USDG (6 decimals)
 const ledgerReq = resource => ({scheme: 'exact', network: 'robinhood', maxAmountRequired: LEDGER_PRICE, resource,
   description: "USDG ledger for any Robinhood Chain address: every USDG in and out over the last N days (max 14), with counterparties, tx links and a reconciliation against the on-chain balance. JazzCat #1's audit method, automated.",
@@ -1002,13 +1006,16 @@ async function holderPass(req) {
   return consumeHolderRead(req,HOLDER_ENV);
 }
 async function paidTerms(url, reqOf) {
-  const cat = url.searchParams.get('cat'), projectOwned = await houseCat(cat || '1'), toCity = CITY_WALLET && projectOwned;
+  // One fresh holder read per offer (HEY retest: it was read twice, about six node requests per unpaid 402). A failed read
+  // throws here, so paid() answers 503 and no payment is attempted; the paid path re-reads the receiver before settling.
+  const cat = url.searchParams.get('cat'), holderNow = await catHolderEOA(cat || '1');
+  const projectOwned = houseHolder(holderNow), toCity = CITY_WALLET && projectOwned;
   const seller = toCity ? CITY_WALLET : cat && cat !== '1' ? await catWallet(cat).catch(() => null) : null;
   if (cat && cat !== '1' && !seller) return null;
   const base = reqOf(url.origin + url.pathname + url.search), requirement = seller ? {...base, payTo: seller, extra: {name: base.extra.name, version: base.extra.version, ...(toCity ? {erc8004: NJC_8004()} : {})}} : base;
   // Base USDC goes to a plain wallet that holds the same key on Base: the city's wallet for house Cats, else the holder's
   // bound Base account if they set one, else the holder.
-  const holder = toCity ? CITY_WALLET : (await boundLeg(cat, 'base').catch(() => null)) || await catHolderEOA(cat || '1').catch(() => null);
+  const holder = toCity ? CITY_WALLET : (await boundLeg(cat, 'base').catch(() => null)) || holderNow;
   const baseReq = holder ? {...requirement, network: 'base', payTo: holder, asset: BASE_USDC, extra: {name: 'USD Coin', version: '2'}} : null, base2 = baseReq && {...v2Of(baseReq), network: 'eip155:8453'};
   // Solana: the house receiver for house Cats; for holder Cats, only an account their current holder bound (cat_bind_leg).
   const solTo = projectOwned ? SOL_PAYTO : await boundLeg(cat, 'solana').catch(() => null);
@@ -1053,6 +1060,7 @@ async function paid(req, url, work, reqOf = ledgerReq, {perks = true, tokens = t
   if (onSol && !solReq) return offer('No holder-authorized Solana receiver is bound for this Cat; use an advertised payment alternative');
   // HEY I-3: a payment on a network this read never offered is refused here, never forwarded to a facilitator.
   if (![...accepts.map(a => a.network), req2?.network, base2?.network, sol2?.network].includes(net)) return offer('Network ' + String(net).slice(0, 40) + ' was not offered for this read');
+  const shape = payloadShapeError(payload); if (shape) return offer(shape); // HEY retest note: before verify, one spelling per authorization
   const isV2 = payload.x402Version === 2 || /^(eip155|solana):/.test(net), chosen = onSol ? solReq : onBase ? baseReq : requirement, facilitator = onSol || onBase ? BASE_FACILITATOR : FACILITATOR;
   const body = JSON.stringify(isV2 ? {x402Version: 2, paymentPayload: payload, paymentRequirements: onSol ? sol2 : onBase ? base2 : req2} : {x402Version: payload.x402Version ?? 1, paymentPayload: payload, paymentRequirements: chosen});
   // JazzCat #1's Robinhood sales settle through the Priors facilitator first (its merchant key), so each one is a receipt
@@ -1157,6 +1165,7 @@ async function x402Charge(req, url, {micro, payTo, solPayTo, description, erc800
   const net = payload.accepted?.network ?? payload.network ?? '', onBase = net === 'base' || net === 'eip155:8453', onSol = net === 'solana' || net === SOL_V2;
   const chosen = onSol ? solReq : onBase ? baseReq : base;
   if (!chosen) return offer(`Pay on ${reqs.map(r => r.network).join(' or ')}.`);
+  const shape = payloadShapeError(payload); if (shape) return offer(shape); // HEY retest note: before verify
   const isV2 = payload.x402Version === 2 || /^(eip155|solana):/.test(net);
   const body = JSON.stringify(isV2 ? {x402Version: 2, paymentPayload: payload, paymentRequirements: v2(chosen)} : {x402Version: payload.x402Version ?? 1, paymentPayload: payload, paymentRequirements: chosen});
   const f = fac.url || (onSol || onBase ? BASE_FACILITATOR : FACILITATOR), headers = {'content-type': 'application/json'};
diff --git a/x402-claim.mjs b/x402-claim.mjs
index b02e248..4bf8638 100644
--- a/x402-claim.mjs
+++ b/x402-claim.mjs
@@ -10,8 +10,11 @@
 import {sha256} from '@noble/hashes/sha2';
 import {bytesToHex} from '@noble/hashes/utils';
 
-export const X402_CLAIMS_SQL = 'CREATE TABLE IF NOT EXISTS x402_claims (id TEXT PRIMARY KEY, path TEXT NOT NULL, at INTEGER NOT NULL, token TEXT NOT NULL, tx TEXT)';
-// A claim that never settled and is this old belongs to a request that died; its payment may be retried.
+export const X402_CLAIMS_SQL = 'CREATE TABLE IF NOT EXISTS x402_claims (id TEXT PRIMARY KEY, path TEXT NOT NULL, at INTEGER NOT NULL, token TEXT NOT NULL, tx TEXT, valid_before INTEGER)';
+// Takeover of an unsettled claim (HEY retest note): an EVM authorization is taken over only after its validBefore has passed,
+// so a read that runs long can never be answered twice while the payment could still settle. A claim with no validBefore
+// (Solana, whose signed transaction expires with its blockhash within minutes, or a claim from before this column) is taken
+// over when it is this old.
 export const STALE_MS = 10 * 60 * 1000;
 
 const family = net => { const n = String(net ?? '').toLowerCase();
@@ -24,6 +27,19 @@ function solanaMessage(b64) { // wire format: shortvec signature count, 64 bytes
   return msg.length ? msg : null;
 }
 
+// HEY retest note: an EVM payment must carry exactly what EIP-3009 signs, checked before any facilitator sees it, so one
+// authorization can never be claimed under two spellings (a short nonce used to fall back to a hash of the header).
+export function payloadShapeError(payload) {
+  if (family(payload?.accepted?.network ?? payload?.network) === 'solana') return null;
+  const a = payload?.payload?.authorization;
+  if (!a || typeof a !== 'object') return 'Bad payment: no EIP-3009 authorization.';
+  if (!/^0x[0-9a-fA-F]{40}$/.test(a.from || '')) return 'Bad payment: authorization.from must be a full 0x address.';
+  if (!/^0x[0-9a-fA-F]{64}$/.test(a.nonce || '')) return 'Bad payment: authorization.nonce must be exactly 32 bytes (0x and 64 hex characters).';
+  if (!/^\d{1,15}$/.test(String(a.validBefore ?? ''))) return 'Bad payment: authorization.validBefore must be whole seconds.';
+  return null;
+}
+const validBeforeOf = payload => { const v = payload?.payload?.authorization?.validBefore; return /^\d{1,15}$/.test(String(v ?? '')) ? Number(v) : null; };
+
 export function paymentId(payload, header) {
   const p = payload?.payload, a = p?.authorization, net = family(payload?.accepted?.network ?? payload?.network);
   if (a && /^0x[0-9a-fA-F]{40}$/.test(a.from || '') && /^0x[0-9a-fA-F]{64}$/.test(a.nonce || ''))
@@ -33,16 +49,19 @@ export function paymentId(payload, header) {
 }
 
 const made = new WeakSet();
-const table = async db => { if (!made.has(db)) { await db.prepare(X402_CLAIMS_SQL).run(); made.add(db); } };
+const table = async db => { if (!made.has(db)) { await db.prepare(X402_CLAIMS_SQL).run();
+  try { await db.prepare('ALTER TABLE x402_claims ADD COLUMN valid_before INTEGER').run(); } catch {} // older ledgers; fails harmlessly once it exists
+  made.add(db); } };
 const newToken = () => bytesToHex(crypto.getRandomValues(new Uint8Array(16)));
 
 // Returns the claim's token, or null when another request holds (or already spent) this payment.
-export async function claimPayment(db, id, path, now = Date.now()) {
+export async function claimPayment(db, id, path, now = Date.now(), validBefore = null) {
   await table(db);
   const token = newToken();
-  const r = await db.prepare('INSERT OR IGNORE INTO x402_claims (id, path, at, token) VALUES (?,?,?,?)').bind(id, path, now, token).run();
+  const r = await db.prepare('INSERT OR IGNORE INTO x402_claims (id, path, at, token, valid_before) VALUES (?,?,?,?,?)').bind(id, path, now, token, validBefore).run();
   if (r?.meta?.changes) return token;
-  const t = await db.prepare('UPDATE x402_claims SET path=?, at=?, token=? WHERE id=? AND tx IS NULL AND at<?').bind(path, now, token, id, now - STALE_MS).run();
+  const t = await db.prepare('UPDATE x402_claims SET path=?, at=?, token=? WHERE id=? AND tx IS NULL AND ((valid_before IS NOT NULL AND valid_before * 1000 < ?) OR (valid_before IS NULL AND at < ?))')
+    .bind(path, now, token, id, now, now - STALE_MS).run();
   return t?.meta?.changes ? token : null;
 }
 export const releasePayment = (db, id, token) => db.prepare('DELETE FROM x402_claims WHERE id=? AND token=? AND tx IS NULL').bind(id, token).run().catch(() => null);
@@ -51,8 +70,9 @@ export const settledPayment = (db, id, token, tx) => db.prepare('UPDATE x402_cla
 // The worker's one entry: {ok: true, release(), settled(tx)} or {ok: false, status, error} to answer with the route's offer.
 export async function claimFor(db, payload, header, path) {
   if (!db?.prepare) return {ok: false, status: 503, error: 'Payments are unavailable here (no payment ledger). Nothing was charged.'};
+  const shape = payloadShapeError(payload); if (shape) return {ok: false, status: 402, error: shape};
   const id = paymentId(payload, header);
-  let token; try { token = await claimPayment(db, id, path); }
+  let token; try { token = await claimPayment(db, id, path, Date.now(), validBeforeOf(payload)); }
   catch { return {ok: false, status: 503, error: 'The payment could not be recorded. Nothing was charged; try again.'}; }
   if (!token) return {ok: false, status: 409, error: 'This payment is already in use or was spent on another answer. One payment buys one answer; sign a new payment.'};
   return {ok: true, id, release: () => releasePayment(db, id, token), settled: tx => settledPayment(db, id, token, tx)};
diff --git a/x402-claim.test.mjs b/x402-claim.test.mjs
index 20f8616..d9c7a0a 100644
--- a/x402-claim.test.mjs
+++ b/x402-claim.test.mjs
@@ -7,7 +7,7 @@ import {d1} from './test-d1.mjs';
 import {paymentId, claimPayment, releasePayment, settledPayment, claimFor, STALE_MS} from './x402-claim.mjs';
 
 const FROM = '0x' + 'aB'.repeat(20), NONCE = '0x' + '5e'.repeat(32);
-const evm = (extra = {}, auth = {}) => ({x402Version: 1, network: 'robinhood', ...extra, payload: {signature: '0x' + '11'.repeat(65), authorization: {from: FROM, nonce: NONCE, ...auth}}});
+const evm = (extra = {}, auth = {}) => ({x402Version: 1, network: 'robinhood', ...extra, payload: {signature: '0x' + '11'.repeat(65), authorization: {from: FROM, nonce: NONCE, validBefore: '9999999999', ...auth}}});
 
 test('EVM: keyed to network family, from and nonce; rewording the header or the signature does not make a new payment', () => {
   const id = paymentId(evm(), 'h1');
@@ -45,7 +45,7 @@ test('claim is insert-or-fail; release frees it; a settled claim is never taken
 test('claimFor fails closed without a ledger or when the ledger errors, and says nothing was charged', async () => {
   assert.deepEqual(await claimFor(null, {}, 'h', '/p').then(r => [r.ok, r.status]), [false, 503]);
   const broken = {prepare: () => ({run: async () => { throw Error('D1 down'); }, bind() { return this; }})};
-  const r = await claimFor(broken, {}, 'h', '/p'); assert.equal(r.ok, false); assert.equal(r.status, 503); assert.match(r.error, /Nothing was charged/);
+  const r = await claimFor(broken, evm(), 'h', '/p'); assert.equal(r.ok, false); assert.equal(r.status, 503); assert.match(r.error, /Nothing was charged/);
   const db = d1(new DatabaseSync(':memory:'));
   const a = await claimFor(db, evm(), 'h', '/p'), b = await claimFor(db, evm({note: 1}), 'h2', '/q');
   assert.equal(a.ok, true); assert.equal(b.ok, false); assert.equal(b.status, 409);

F-4: The Base payment address could stay with a previous Cat holder

Low (3.7, CWE-672) · HEY: Fixed (f4a4c24 and later) (HEY retested every change on the payment and read paths up to 007d04b). Details in HEY's report.

f4a4c24 Recheck native Cat ownership and signed receivers before settlement

Commit
f4a4c2415d5c03d6a7fe075cb0e3d3878b6f8998
Date
Nov 22, 2026, 12:45 AM ET (05:45 UTC)
Fixes
F-4
Verify
git show f4a4c2415d5c03d6a7fe075cb0e3d3878b6f8998 in a clone of rh-tx-explain

5 files changed, +100 −16

  • paid-success.test.mjs +29 −5
  • seller-owner.mjs +20 −0
  • seller-owner.test.mjs +26 −0
  • worker-roundtrip.test.mjs +10 −3
  • worker.mjs +15 −8
Full diff
diff --git a/paid-success.test.mjs b/paid-success.test.mjs
index 11d48a3..24c21d0 100644
--- a/paid-success.test.mjs
+++ b/paid-success.test.mjs
@@ -4,18 +4,28 @@ import test from 'node:test';
 import assert from 'node:assert/strict';
 import worker from './worker.mjs';
 const CITY='0x0C0B48Beba6c89CE591b0092B1F5EA83481D2906',A='0x'+'1'.repeat(40),TX='0x'+'2'.repeat(64);
-let verified=0,settled=0,reads=0,verify=true;
+let verified=0,settled=0,reads=0,verify=true,ownerChanged=false,changeDuringWork=false;
 globalThis.fetch=async(input,init)=>{
  const url=String(input),body=JSON.parse(init.body);
  if(url.endsWith('/verify')){verified++;return Response.json({isValid:verify,invalidReason:'synthetic denial'});}
  if(url.endsWith('/settle')){settled++;return Response.json({success:true,transaction:TX,payer:A});}
- assert(Array.isArray(body));reads++;
- return Response.json(body.map(x=>({jsonrpc:'2.0',id:x.id,result:x.method==='eth_blockNumber'?'0x10':x.method==='eth_getLogs'?[]:null})));
+ assert(Array.isArray(body));
+ return Response.json(body.map(x=>{
+  let result;
+  if(x.method==='eth_chainId')result='0x'+(4663).toString(16);
+  else if(x.method==='eth_getBlockByNumber')result={number:'0x100',hash:'0x'+'a'.repeat(64),timestamp:'0x'+Math.floor(Date.now()/1000).toString(16)};
+  else if(x.method==='eth_call')result='0x'+'0'.repeat(24)+(ownerChanged?'3'.repeat(40):'b7e507034618e122aef4a032d1678453b3c9f60b');
+  else if(x.method==='eth_getCode')result='0x';
+  else if(x.method==='eth_blockNumber'){result='0x10';reads++;}
+  else if(x.method==='eth_getLogs'){result=[];reads++;if(changeDuringWork)ownerChanged=true;}
+  else throw Error('Unexpected synthetic native read');
+  return {jsonrpc:'2.0',id:x.id,result};
+ }));
 };
 const request=(network,address=A)=>new Request('https://fixture.example/x402/poison-check?address='+address,
  {headers:{'x-payment':Buffer.from(JSON.stringify({x402Version:1,network,payload:'fixture-no-signature'})).toString('base64')}});
 for(const network of ['robinhood','eip155:8453','solana'])test('successful '+network+' paid handler returns its receipt after one synthetic settlement',async()=>{
- verified=settled=reads=0;verify=true;
+ verified=settled=reads=0;verify=true;ownerChanged=changeDuringWork=false;
  const response=await worker.fetch(request(network),{CITY_WALLET:CITY},{});
  assert.equal(response.status,200);const r=await response.json();
  assert.equal(r.payment.tx,TX);assert.equal(r.payment.cat,1);assert.equal(settled,1);assert.equal(verified,1);assert(reads>0);
@@ -23,10 +33,24 @@ for(const network of ['robinhood','eip155:8453','solana'])test('successful '+net
  assert(response.headers.get('payment-response'));assert(response.headers.get('x-payment-response'));
 });
 test('a failed read is never settled and a rejected payment never runs work',async()=>{
- verified=settled=reads=0;verify=true;
+ verified=settled=reads=0;verify=true;ownerChanged=changeDuringWork=false;
  const bad=await worker.fetch(request('robinhood','bad'),{CITY_WALLET:CITY},{});
  assert.equal(bad.status,400);assert.equal(verified,1);assert.equal(settled,0);assert.equal(reads,0);
  verified=settled=reads=0;verify=false;
  const refused=await worker.fetch(request('robinhood'),{CITY_WALLET:CITY},{});
  assert.equal(refused.status,402);assert.equal(settled,0);assert.equal(reads,0);
 });
+test('a seller transfer during work prevents settlement to the old treasury route',async()=>{
+ verified=settled=reads=0;verify=true;ownerChanged=false;changeDuringWork=true;
+ const response=await worker.fetch(request('robinhood'),{CITY_WALLET:CITY},{});
+ assert.equal(response.status,409);assert.equal(verified,1);assert.equal(settled,0);
+ ownerChanged=changeDuringWork=false;
+});
+test('Cat1 sold outside the project no longer routes RH to the City or Base to a cached old owner',async()=>{
+ verified=settled=reads=0;verify=true;ownerChanged=true;changeDuringWork=false;
+ const response=await worker.fetch(new Request('https://fixture.example/x402/poison-check?address='+A),{CITY_WALLET:CITY},{});
+ assert.equal(response.status,402);const q=await response.json();
+ assert.equal(q.accepts.find(x=>x.network==='robinhood').payTo.toLowerCase(),'0x1479be07e26976fd712db34f7bc1b8ac523f806e');
+ assert.equal(q.accepts.find(x=>x.network==='base').payTo,'0x'+'3'.repeat(40));
+ assert.equal(settled,0);ownerChanged=false;
+});
diff --git a/seller-owner.mjs b/seller-owner.mjs
new file mode 100644
index 0000000..52647ff
--- /dev/null
+++ b/seller-owner.mjs
@@ -0,0 +1,20 @@
+// Fresh native owner observation. No wallet, signing, payment or mutable cache.
+const GENESIS='0xB3D33Af2cE8cE0792942B487E2213ac665DD83E2';
+const hash=x=>typeof x==='string'&&/^0x[0-9a-f]{64}$/i.test(x);
+const quantity=x=>typeof x==='string'&&/^0x(0|[1-9a-f][0-9a-f]{0,63})$/i.test(x);
+const owner=x=>typeof x==='string'&&/^0x0{24}[0-9a-f]{40}$/i.test(x)&&BigInt(x)!==0n?'0x'+x.slice(26).toLowerCase():null;
+const fail=()=>{throw Error('Current Cat seller ownership unavailable.');};
+export async function currentCatHolderEOA(n,rpc,clock=()=>Date.now()){
+ if(typeof n!=='string'||!/^[1-9]\d{0,3}$/.test(n)||Number(n)>5678)fail();
+ const started=clock();const [chain,block]=await rpc([['eth_chainId',[]],['eth_getBlockByNumber',['latest',false]]]);
+ if(!quantity(chain)||BigInt(chain)!==4663n||!quantity(block?.number)||!quantity(block.timestamp)||!hash(block.hash)||
+   BigInt(block.timestamp)*1000n>BigInt(started+30000)||BigInt(started)-BigInt(block.timestamp)*1000n>120000n)fail();
+ const call={to:GENESIS,data:'0x6352211e'+BigInt(n).toString(16).padStart(64,'0')};
+ const [raw]=await rpc([['eth_call',[call,block.number]]]);const address=owner(raw);if(!address)fail();
+ const [code,recheck,current]=await rpc([['eth_getCode',[address,block.number]],
+  ['eth_getBlockByNumber',[block.number,false]],['eth_call',[call,'latest']]]);
+ const finished=clock();
+ if(typeof code!=='string'||!/^0x(?:[0-9a-f]{2})*$/i.test(code)||recheck?.hash?.toLowerCase()!==block.hash.toLowerCase()||
+  owner(current)!==address||finished<started||finished-started>20000)fail();
+ return code==='0x'?address:null;
+}
diff --git a/seller-owner.test.mjs b/seller-owner.test.mjs
new file mode 100644
index 0000000..ed9c086
--- /dev/null
+++ b/seller-owner.test.mjs
@@ -0,0 +1,26 @@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import {currentCatHolderEOA} from './seller-owner.mjs';
+const A='0x'+'a'.repeat(40),B='0x'+'b'.repeat(40),H='0x'+'c'.repeat(64),now=1795326000000;
+const pad=a=>'0x'+'0'.repeat(24)+a.slice(2);
+function fixture(){const state={owner:A};const block={number:'0x100',hash:H,timestamp:'0x'+Math.floor(now/1000).toString(16)};
+ return {state,rpc:async calls=>calls.map(([method,args])=>{
+  if(method==='eth_chainId')return state.chain??'0x'+(4663).toString(16);
+  if(method==='eth_getBlockByNumber')return {...block,hash:state.reorg&&args[0]!=='latest'?'0x'+'d'.repeat(64):H};
+  if(method==='eth_getCode')return state.code??'0x';
+  if(method==='eth_call')return pad(args[1]==='latest'&&state.transfer?B:state.owner);
+  throw Error('unexpected native method');
+ })};}
+test('owner changes are freshly observed, never cached by Cat number',async()=>{
+ const f=fixture();assert.equal(await currentCatHolderEOA('1',f.rpc,()=>now),A);
+ f.state.owner=B;assert.equal(await currentCatHolderEOA('1',f.rpc,()=>now),B);
+});
+test('wrong chain, reorg, mid-read transfer and malformed owner refuse',async()=>{
+ for(const patch of [{chain:'0x1'},{reorg:true},{transfer:true},{owner:'0x'+'0'.repeat(40)}]){
+  const f=fixture();Object.assign(f.state,patch);await assert.rejects(currentCatHolderEOA('1',f.rpc,()=>now));
+ }
+ for(const n of ['0','5679','01','../1'])await assert.rejects(currentCatHolderEOA(n,fixture().rpc,()=>now));
+});
+test('a contract holder is not represented as a same-address Base EOA',async()=>{
+ const f=fixture();f.state.code='0x6001';assert.equal(await currentCatHolderEOA('2',f.rpc,()=>now),null);
+});
diff --git a/worker-roundtrip.test.mjs b/worker-roundtrip.test.mjs
index 0de12d0..56b2823 100644
--- a/worker-roundtrip.test.mjs
+++ b/worker-roundtrip.test.mjs
@@ -8,7 +8,14 @@ const addr=x=>x?.toLowerCase();
 const derive=m=>new Map(m.map(x=>[x.network,[addr(x.payTo),x.asset,x.amount??x.maxAmountRequired]]));
 const baseline=process.env.NJC_FIX_EXPECT==='baseline';
 const attemptedRemote=[];
-globalThis.fetch=async input=>{attemptedRemote.push(String(input));throw Error('No network in this test');};
+globalThis.fetch=async(input,init)=>{
+ attemptedRemote.push(String(input));
+ const calls=JSON.parse(init.body);assert(Array.isArray(calls));
+ return Response.json(calls.map(x=>({jsonrpc:'2.0',id:x.id,result:
+  x.method==='eth_chainId'?'0x'+(4663).toString(16):
+  x.method==='eth_getBlockByNumber'?{number:'0x100',hash:'0x'+'a'.repeat(64),timestamp:'0x'+Math.floor(Date.now()/1000).toString(16)}:
+  x.method==='eth_call'?'0x'+'0'.repeat(24)+'b7e507034618e122aef4a032d1678453b3c9f60b':x.method==='eth_getCode'?'0x':null})));
+};
 const {default:worker}=await import('./worker.mjs');
 const req=(path,args,env={CITY_WALLET:CITY})=>worker.fetch(new Request(origin+path,
  args?{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify({jsonrpc:'2.0',
@@ -38,7 +45,7 @@ test('real Worker HTTP, MCP, JSON card, and docs are exercised for the house quo
   assert.equal(addr(r.root.paid.payTo),CITY);
   assert.match(r.root.by,/26063/);
  }
- assert.equal(attemptedRemote.length,0);
+ assert(attemptedRemote.length>0);assert(attemptedRemote.every(u=>u==='https://njc-read-proxy.vercel.app/api/rpc'));
 });
 if(!baseline)test('a tool argument cannot select a different seller on the default MCP route',async ()=>{
  const m=await req('/mcp',{agent:'26063',cat:'other'});
@@ -46,5 +53,5 @@ if(!baseline)test('a tool argument cannot select a different seller on the defau
  const r=(await m.json()).result.structuredContent;
  assert.equal(r.paymentRequired.url,origin+'/x402/income-read?agent=26063');
  assert.equal(addr(r.paymentRequired.payTo),CITY);
- assert.equal(attemptedRemote.length,0);
+ assert(attemptedRemote.every(u=>u==='https://njc-read-proxy.vercel.app/api/rpc'));
 });
diff --git a/worker.mjs b/worker.mjs
index bd12a07..0fd8dc3 100644
--- a/worker.mjs
+++ b/worker.mjs
@@ -1,5 +1,6 @@
 import { ECON_TOOLS, economyCall } from './economics.mjs';
 import {parseWorkCache,projectWorkBoard,readCityWork} from './work-board.mjs';
+import {currentCatHolderEOA} from './seller-owner.mjs';
 import {baseTrail} from './base.mjs';
 import {solTrail} from './sol.mjs';
 import {tbaRead} from './tba.mjs';
@@ -140,7 +141,7 @@ const PRIORS_FACILITATOR = 'https://facilitator.priors.trade'; let PRIORS_KEY =
 // treasury holds) pay the city, so the city's ERC-8004 identity carries the income. Holder Cats keep their own pay.
 let CITY_WALLET = null;
 const HOUSE = new Set(['0xb7e507034618e122aef4a032d1678453b3c9f60b', '0x0c0b48beba6c89ce591b0092b1f5ea83481d2906']);
-async function houseCat(n) { return n === '1' || HOUSE.has(((await catHolderEOA(n).catch(() => null)) || '').toLowerCase()); }
+async function houseCat(n) { return HOUSE.has(((await catHolderEOA(n)) || '').toLowerCase()); }
 const LEDGER_PRICE = '50000'; // 0.05 USDG (6 decimals)
 const ledgerReq = resource => ({scheme: 'exact', network: 'robinhood', maxAmountRequired: LEDGER_PRICE, resource,
   description: "USDG ledger for any Robinhood Chain address: every USDG in and out over the last N days (max 14), with counterparties, tx links and a reconciliation against the on-chain balance. JazzCat #1's audit method, automated.",
@@ -492,16 +493,12 @@ const GENESIS = '0xB3D33Af2cE8cE0792942B487E2213ac665DD83E2', REG6551 = '0x00000
 const catWallets = new Map([['1', CAT1_WALLET]]);
 // Base USDC is paid to the Cat's holder, not its 6551 wallet (that wallet exists on Robinhood Chain only), and only when the
 // holder is a plain wallet: the same key holds that address on Base. Settled by PayAI's keyless facilitator.
-const BASE_USDC = '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913', BASE_FACILITATOR = 'https://facilitator.payai.network', catHolders = new Map();
+const BASE_USDC = '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913', BASE_FACILITATOR = 'https://facilitator.payai.network';
 // Solana USDC, also settled by PayAI (its feePayer sponsors the transaction). One house Solana wallet receives for every Cat;
 // the paying Cat is named in the response so its income list can credit it. Its USDC token account exists, as the x402 SVM scheme requires.
 const SOL_USDC = 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v', SOL_PAYTO = 'BifYmwXuP9jBY4YZSACwcNAhcNabKcxzgkMxCUJZq8gL', SOL_FEEPAYER = 'CjNFTjvBhbJJd2B5ePPMHRLx1ELZpa8dwQgGL727eKww', SOL_V2 = 'solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp';
 async function catHolderEOA(n) {
-  if (catHolders.has(n)) return catHolders.get(n);
-  const [owner] = await rpcBatch([['eth_call', [{to: GENESIS, data: '0x6352211e' + BigInt(n).toString(16).padStart(64, '0')}, 'latest']]]);
-  const holder = owner && owner.length >= 66 ? '0x' + owner.slice(26) : null;
-  const [code] = holder ? await rpcBatch([['eth_getCode', [holder, 'latest']]]) : [null];
-  const eoa = holder && code === '0x' ? holder : null; catHolders.set(n, eoa); return eoa;
+  return currentCatHolderEOA(n,calls=>rpcBatch(calls,OFFICIAL));
 }
 async function catWallet(n) {
   if (!/^[1-9]\d{0,5}$/.test(n || '')) throw new Error('cat must be a JazzCat token id');
@@ -696,7 +693,9 @@ async function paid(req, url, work, reqOf = ledgerReq) {
   const pass = await holderPass(req).catch(() => null);
   if (pass) { let result; try { result = await work(); } catch (e) { return json({error: e.message}, 400); }
     return new Response(JSON.stringify({...result, payment: {paidWith: 'holder', holder: pass.address, freeCallsLeftToday: pass.left}}), {headers: H402}); }
-  const terms = await paidTerms(url, reqOf);
+  let terms;
+  try { terms = await paidTerms(url, reqOf); }
+  catch { return json({error:'Current seller ownership unavailable; no payment was attempted.'},503); }
   if (!terms) return json({error: 'No JazzCat #' + url.searchParams.get('cat') + ' on Robinhood Chain.'}, 404);
   const {requirement, baseReq, base2, solReq, sol2, req2, accepts} = terms;
   const header = req.headers.get('x-payment') || req.headers.get('payment-signature');
@@ -716,6 +715,14 @@ async function paid(req, url, work, reqOf = ledgerReq) {
   if (!pick?.v.isValid) pick = await via(facilitator);
   if (!pick.v.isValid) return offer(pick.v.invalidReason || 'Payment not valid');
   let result; try { result = await work(); } catch (e) { return json({error: e.message}, 400); } // a failed read is never charged
+  // Work may outlive an NFT transfer. Re-resolve the signed receiver before
+  // settlement; never charge an old owner/treasury route or silently reroute it.
+  let current;
+  try { current=await paidTerms(url,reqOf); } catch { return offer('Seller ownership unavailable; request a fresh challenge.',503); }
+  const currentChosen=current&&(onSol?current.solReq:onBase?current.baseReq:current.requirement);
+  if(!currentChosen||currentChosen.payTo!==chosen.payTo||currentChosen.asset!==chosen.asset||
+    currentChosen.maxAmountRequired!==chosen.maxAmountRequired)
+    return offer('Seller receiver changed; request a fresh challenge. No settlement attempted.',409);
   const st = await fetch(pick.f + '/settle', {method: 'POST', headers: pick.headers, body}).then(r => r.json()).catch(e => ({success: false, errorReason: e.message}));
   if (!st.success) return offer(st.errorReason || 'Settlement failed');
   return new Response(JSON.stringify({...result, payment: {tx: st.transaction, payer: st.payer, paidTo: chosen.payTo, network: onSol ? 'solana' : onBase ? 'base' : 'robinhood', cat: Number(cat || 1)}}), {headers: {...H402, 'x-payment-response': b64(st), 'payment-response': b64(st)}});

02f8e3c x402 pays holders where they bound: a holder Cat's Base USDC goes to its bound Base account, and Solana USDC is offered at the holder's bound Solana account (epoch- and holder-current, USDC account present); house routes unchanged (#20)

Commit
02f8e3cccb667712fed5a11d3d478f3393871d01
Date
Nov 23, 2026, 1:11 AM ET (06:11 UTC)
Fixes
F-4
Verify
git show 02f8e3cccb667712fed5a11d3d478f3393871d01 in a clone of rh-tx-explain

Ours, not HEY's: Not named in HEY's table. A later change inside the range HEY retested for F-4 ("f4a4c24 and later", up to 007d04b): it routes a holder Cat's Base payment to the account its current holder bound, with the holder and epoch checks, which f4a4c24 alone does not show.

2 files changed, +33 −7

  • paid-terms.test.mjs +11 −1
  • worker.mjs +22 −6
Full diff
diff --git a/paid-terms.test.mjs b/paid-terms.test.mjs
index cdae1a3..e35be60 100644
--- a/paid-terms.test.mjs
+++ b/paid-terms.test.mjs
@@ -9,7 +9,7 @@ const CITY='0xCity', CAT='0xCat1', NONHOUSE='0xCat2', HOLDER='0xHolder2';
 const reqOf=resource=>({scheme:'exact',network:'robinhood',resource,payTo:CAT,maxAmountRequired:'900000',extra:{name:'USDG',version:'2'}});
 const cfg=(city)=>({CITY_WALLET:city,CHAIN_ID:4663,BASE_USDC:'base-usdc',SOL_PAYTO:'solana-wallet',
  SOL_USDC:'sol-usdc',SOL_FEEPAYER:'existing-facilitator',SOL_V2:'solana:fixture',NJC_8004:()=>({id:26063}),
- houseCat:async id=>id==='1',catWallet:async id=>id==='2'?NONHOUSE:null,catHolderEOA:async id=>id==='2'?HOLDER:'0xHolder1',
+ houseCat:async id=>id==='1',boundLeg:async()=>null,catWallet:async id=>id==='2'?NONHOUSE:null,catHolderEOA:async id=>id==='2'?HOLDER:'0xHolder1',
  v2Of:r=>({scheme:r.scheme,payTo:r.payTo,asset:r.asset,network:'eip155:4663',amount:r.maxAmountRequired})});
 const resolver=city=>runInNewContext(source+';paidTerms',cfg(city));
 const url=(p='')=>new URL('https://example.test/x402/income-read?agent=26063'+p);
@@ -35,3 +35,13 @@ test('nonhouse routes its existing Cat and holder, unknown refuses, absent city
  assert.equal((await resolver('')(url(),reqOf)).requirement.payTo,CAT);
  assert.match(f,/q\.delete\('cat'\)/);
 });
+
+test('holder-bound legs: Base pays the bound account, Solana is offered only with a bound account; house routes unchanged',async()=>{
+ const bound=(chain)=>({...cfg(CITY),boundLeg:async(cat,c)=>cat==='2'&&c===chain?(c==='solana'?'HolderSolanaAccount':'0xBoundBase'):null});
+ const b=await runInNewContext(source+';paidTerms',bound('base'))(url('&cat=2'),reqOf);
+ assert.equal(b.baseReq.payTo,'0xBoundBase');assert.equal(b.solReq,null);assert.equal(b.requirement.payTo,NONHOUSE);
+ const s=await runInNewContext(source+';paidTerms',bound('solana'))(url('&cat=2'),reqOf);
+ assert.equal(s.solReq.payTo,'HolderSolanaAccount');assert.equal(s.baseReq.payTo,HOLDER);assert(s.accepts.some(x=>x.network==='solana'&&x.payTo==='HolderSolanaAccount'));
+ const h=await runInNewContext(source+';paidTerms',bound('solana'))(url(),reqOf);
+ assert.equal(h.solReq.payTo,'solana-wallet');assert.equal(h.baseReq.payTo,CITY);
+});
diff --git a/worker.mjs b/worker.mjs
index 3aed25a..ca5fd1f 100644
--- a/worker.mjs
+++ b/worker.mjs
@@ -7,7 +7,7 @@ import { ECON_TOOLS, economyCall } from './economics.mjs';
 import {MARKET_TOOLS,marketCapabilities,marketRead} from './markets.mjs';
 import {catLegs,bindLeg,registerTx,loadLegs,saveLeg} from './legs.mjs';
 import {jazzFees} from './jazz-fees.mjs';
-import {EVM} from './chains.mjs';
+import {EVM,solRpc} from './chains.mjs';
 import {parseWorkCache,projectWorkBoard,readCityWork} from './work-board.mjs';
 import {currentCatHolderEOA} from './seller-owner.mjs';
 import {baseTrail} from './base.mjs';
@@ -520,7 +520,7 @@ async function catWallet(n) {
 }
 const CAT_AGENTS = {'1': 26063, '2': 26078, '3': 26079}; // ERC-8004 agent IDs whose agentWallet is the Cat's own 6551 wallet
 const catCard = (n, wallet, origin) => ({type: 'https://eips.ethereum.org/EIPS/eip-8004#registration-v1', name: 'JazzCat #' + n,
-  description: `JazzCat #${n}, New Jazz City: an on-chain jazz cat on Robinhood Chain that sells chain reads to agents over x402. The unpaid challenge specifies the actual receiver: the Cat wallet on RH for outside-owned Cats, or the City treasury for project-owned Cats. Base uses the current plain-wallet holder; Solana is offered only for project-owned Cats. Full check of any address (2.70 USDG), credit-line read (0.90 USDG), money trail for any coin (0.90 USDG), USDG ledger for any address (0.05 USDG), free transaction explainer and agent-control check.`,
+  description: `JazzCat #${n}, New Jazz City: an on-chain jazz cat on Robinhood Chain that sells chain reads to agents over x402. The unpaid challenge specifies the actual receiver: the Cat wallet on RH for outside-owned Cats, or the City treasury for project-owned Cats. Base pays the holder's bound Base account or, failing that, the current plain-wallet holder; Solana pays the house receiver for project-owned Cats or the Solana account the current holder bound (cat_bind_leg). Full check of any address (2.70 USDG), credit-line read (0.90 USDG), money trail for any coin (0.90 USDG), USDG ledger for any address (0.05 USDG), free transaction explainer and agent-control check.`,
   image: `https://jazzcatsfun.pages.dev/agents/${n}.svg`,
   services: [...['line-read', 'money-trail', 'ledger', 'transfer-read', 'halt-check'].map(r => ({name: 'x402', endpoint: `${origin}/x402/${r}?cat=${n}`, version: '1'})),
     {name: 'MCP', endpoint: `${origin}/mcp?cat=${n}`, version: '2025-06-18'}, {name: 'web', endpoint: origin + '/'}],
@@ -538,6 +538,19 @@ async function catFacts(n) {
   return {cat: n, owner: '0x' + owner.slice(26).toLowerCase(), holderEOA, epoch: BigInt(epoch).toString(), rhWallet: (await catWallet(n)).toLowerCase(),
     projectOwned: HOUSE.has((holderEOA || '').toLowerCase()), agentId: CAT_AGENTS[n] ?? null};
 }
+// A holder Cat's bound payee on base or solana, only while the binding matches the current holder and ownership epoch.
+// Solana also needs an existing USDC account at that address, so an x402 transfer cannot fail on a missing account.
+async function boundLeg(cat, chain) {
+  const db = HOLDER_ENV?.QDB; if (!db?.prepare || !cat || cat === '1') return null;
+  const row = (await loadLegs(db, cat).catch(() => [])).find(r => r.chain === chain); if (!row) return null;
+  const facts = await catFacts(cat).catch(() => null);
+  if (!facts || facts.projectOwned || String(row.epoch) !== facts.epoch || row.holder !== facts.owner) return null;
+  if (chain === 'solana') {
+    const r = await solRpc('getTokenAccountsByOwner', [row.account, {mint: SOL_USDC}, {encoding: 'jsonParsed', commitment: 'finalized'}]).catch(() => null);
+    if (!Array.isArray(r?.value) || !r.value.length) return null;
+  }
+  return row.account;
+}
 async function legsOf(n, env) { return catLegs(await catFacts(n), {rows: await loadLegs(env?.QDB, n), cityWallet: CITY_WALLET, solPayTo: SOL_PAYTO}); }
 async function bindCall(n, a, env) {
   const facts = await catFacts(n);
@@ -724,10 +737,13 @@ async function paidTerms(url, reqOf) {
   const seller = toCity ? CITY_WALLET : cat && cat !== '1' ? await catWallet(cat).catch(() => null) : null;
   if (cat && cat !== '1' && !seller) return null;
   const base = reqOf(url.origin + url.pathname + url.search), requirement = seller ? {...base, payTo: seller, extra: {name: base.extra.name, version: base.extra.version, ...(toCity ? {erc8004: NJC_8004()} : {})}} : base;
-  // Base USDC goes to a plain wallet that holds the same key on Base: the city's wallet for house Cats, else the holder.
-  const holder = toCity ? CITY_WALLET : await catHolderEOA(cat || '1').catch(() => null);
+  // Base USDC goes to a plain wallet that holds the same key on Base: the city's wallet for house Cats, else the holder's
+  // bound Base account if they set one, else the holder.
+  const holder = toCity ? CITY_WALLET : (await boundLeg(cat, 'base').catch(() => null)) || await catHolderEOA(cat || '1').catch(() => null);
   const baseReq = holder ? {...requirement, network: 'base', payTo: holder, asset: BASE_USDC, extra: {name: 'USD Coin', version: '2'}} : null, base2 = baseReq && {...v2Of(baseReq), network: 'eip155:8453'};
-  const solReq = projectOwned ? {...requirement, network: 'solana', payTo: SOL_PAYTO, asset: SOL_USDC, extra: {feePayer: SOL_FEEPAYER}} : null, sol2 = solReq && {...v2Of(solReq), network: SOL_V2};
+  // Solana: the house receiver for house Cats; for holder Cats, only an account their current holder bound (cat_bind_leg).
+  const solTo = projectOwned ? SOL_PAYTO : await boundLeg(cat, 'solana').catch(() => null);
+  const solReq = solTo ? {...requirement, network: 'solana', payTo: solTo, asset: SOL_USDC, extra: {feePayer: SOL_FEEPAYER}} : null, sol2 = solReq && {...v2Of(solReq), network: SOL_V2};
   const req2 = v2Of(requirement);
   return {requirement, baseReq, base2, solReq, sol2, req2,
     accepts: [requirement, {...requirement, network: 'eip155:' + CHAIN_ID}, ...(baseReq ? [baseReq] : []), ...(solReq ? [solReq] : [])]};
@@ -1128,7 +1144,7 @@ function llmsTxt(origin) {
     `## Free multichain access`, ``, `- market_capabilities({}) or GET ${origin}/markets/capabilities: exact RH/Base/BNB/Ethereum/Arbitrum/Solana coverage.`, `- market_read({network,view,asset?,agent?,limit?}) or GET ${origin}/markets: QHooks-listed RH/Base launches and token detail; BNB/Ethereum/Arbitrum exact ERC-20 detail; Solana exact mint supply; view=agent for any ERC-8004 agent on an EVM chain.`, ``, `## Your Cat on every chain`, ``, `- cat_legs({cat}) or GET ${origin}/cat/{N}/legs: any JazzCat's wallet and where to pay it directly on Robinhood Chain, Base, BNB Chain, Ethereum, Arbitrum and Solana, read fresh from each chain. A Cat's Robinhood wallet is never assumed on another chain. x402 challenges name their own receiver.`, `- cat_bind_leg({cat,chain,account}) or GET/POST ${origin}/cat/{N}/legs/bind: the holder binds their account on another chain, signed by the holder and by the account, tied to the Cat's ownership epoch so a sale leaves it stale.`, `- cat_register_tx({cat,chain,account}) or GET ${origin}/cat/{N}/legs/register-tx?chain=base&account=0x…: the unsigned ERC-8004 registration of the Cat on that chain (same registry address on every EVM chain). New Jazz City never signs or holds it. That identity stays with the account that registered it and does not move with the Cat: after a sale the new holder registers fresh, and only the Cat's card lists which identities are current.`, ``, `- Read observations are not complete portfolios, Cat execution permission or a bridge. No additional JAZZ launch.`, ``, `## How to pay`,
     `- x402 v1 (network "robinhood") or v2 (network "eip155:4663"), exact scheme, USDG ${USDG}, for house Cats the configured receiver is ${(CITY_WALLET || CAT1_WALLET).toLowerCase()}. Always verify the per-network 402 challenge; if a quote and challenge disagree, stop before paying.`,
     `- Base: USDC ${BASE_USDC.toLowerCase()} on eip155:8453 is accepted where the 402 offers it.`,
-    `- Solana: USDC ${SOL_USDC} on solana (v1) or ${SOL_V2} (v2), payTo ${SOL_PAYTO}, fees sponsored by the facilitator.`,
+    `- Solana: USDC ${SOL_USDC} on solana (v1) or ${SOL_V2} (v2), fees sponsored by the facilitator. House Cats pay ${SOL_PAYTO}; a holder's Cat is paid at the Solana account its current holder bound with cat_bind_leg. The 402 names the receiver.`,
     `- Every Cat sells the same reads: add ?cat=N; check the unpaid challenge for its actual asset and receiver.`,
     `- Machine-readable: ${origin}/.well-known/x402 and ${origin}/.well-known/agent-card.json`,
     `- Buy on the spot from any wallet: ${origin}/buy?read={route} (for example ${origin}/buy?read=money-trail&token={token})`, ``,

N-1: The Raeto Pay rail served a read before its payment capture was confirmed

Low (3.7), conditional · HEY: Fixed (84ce44a and later) (HEY retested every change on the payment and read paths up to 007d04b). Details in HEY's report.

84ce44a Prepare native JAZZ buys, expose Cat title and harden merchant capture (#14)

Commit
84ce44afd21925731db47c431ed7135db16f9faa
Date
Nov 22, 2026, 11:14 PM ET (Nov 23, 04:14 UTC)
Fixes
N-1
Verify
git show 84ce44afd21925731db47c431ed7135db16f9faa in a clone of rh-tx-explain

Scope: Besides the Raeto Pay capture fix for N-1 (raeto-gateway.mjs and its use in worker.mjs), this commit adds features outside HEY's scope: native $JAZZ buy plans (jazz-buy.mjs) and the Cat title tool (title-report.mjs).

10 files changed, +211 −18

  • README.md +23 −0
  • economics.test.mjs +2 −1
  • jazz-buy.mjs +71 −0
  • jazz-buy.test.mjs +29 −0
  • raeto-gateway.mjs +26 −0
  • raeto-gateway.test.mjs +12 −0
  • service-catalog.test.mjs +2 −0
  • title-report.mjs +16 −0
  • title-report.test.mjs +6 −0
  • worker.mjs +24 −17
Full diff
diff --git a/README.md b/README.md
index e6c9586..25b9eb7 100644
--- a/README.md
+++ b/README.md
@@ -70,3 +70,26 @@ payment transaction is not proof of net profit or an onchain work-receipt row.
 ### Public renderer browser QA
 
 The `public-render-browser` CI job uses an integrity-pinned dedicated Chrome for Testing with the Chromium sandbox enabled, an ephemeral clean profile and loopback-only fixtures. It checks desktop/mobile layout, exact USDG display, escaped record text and unknown balances. Screenshots explicitly represent synthetic economic fixtures, not live holders or paid jobs; original public Cat art is fetched by digest, not relicensed. No personal browser, signing key or sandbox bypass is used. This check does not qualify holder authentication, native trading or marketplace settlement.
+
+## Native JAZZ preparation and agent commerce reads
+
+- MCP `buy_jazz({"usdg":"1","trader":"0x...","slippageBps":100})` prepares
+  official JAZZ (`0x1f243c6638a6becd787f326b240227687a3835bc`) on chain 4663.
+  It resolves the Pons launch, pins a canonical block, reads current fees and
+  reserves, and emits exact-amount USDG approval and buy transactions. Amounts
+  are six-decimal strings, not floats. Your wallet must check gas, refresh and
+  simulate before signing. No signing, bridge, autonomous grant or live fill is
+  supplied. A buy reaching graduation is held for a separate qualified route.
+- MCP `title_report({"id":1})` and `GET /title?cat=1` expose the City's existing
+  public title snapshot. Source-reported clear is not guaranteed title; asset,
+  ERC-8004 identity, credit, private history and old permissions are distinct.
+- `GET /services` supplies nine priced Raeto-compatible POST definitions with
+  input schemas. Compatibility is not catalog approval, a customer or revenue.
+  Paid outputs are withheld unless Raeto acknowledges capture. Unknown payment
+  outcomes require original-receipt reconciliation, not another payment or an
+  automatic refund. A successful HTTP fixture is not a live paid acceptance.
+
+The native preparation was checked against actual deployed Pons bytecode on a
+pinned local fork: exact quoted JAZZ output and 1 USDG input matched, with no
+mainnet broadcast. Fork impersonation/gas funding do not prove wallet authority.
+Pons integration reference: https://docs.ponsfamily.com/v2
diff --git a/economics.test.mjs b/economics.test.mjs
index 736afe8..bf1ee17 100644
--- a/economics.test.mjs
+++ b/economics.test.mjs
@@ -44,7 +44,8 @@ test('MCP, GET, card, llms, and OpenAPI agree; duplicates and public holder requ
  const get=p=>worker.fetch(new Request('https://fixture.example'+p),{JAZZ_TOKEN:w},{});
  const call=(method,params)=>worker.fetch(new Request('https://fixture.example/mcp',{method:'POST',body:JSON.stringify({jsonrpc:'2.0',id:1,method,params})}),{JAZZ_TOKEN:w},{});
  const listing=(await (await call('tools/list')).json()).result.tools;
- assert.equal(listing.length,29);
+ assert.equal(listing.length,30);
+ assert(listing.some(t=>t.name==='title_report'));
  assert(listing.some(t=>t.name==='job_receipt') && listing.some(t=>t.name==='city_economics') && !listing.some(t=>t.name==='cat_economics'));
  const info=(await (await call('tools/call',{name:'job_receipt',arguments:{jobId}})).json()).result.structuredContent;
  const rest=await (await get('/job-receipt?jobId='+jobId)).json();
diff --git a/jazz-buy.mjs b/jazz-buy.mjs
new file mode 100644
index 0000000..3729d35
--- /dev/null
+++ b/jazz-buy.mjs
@@ -0,0 +1,71 @@
+// Official JAZZ only. Public RPC reads and unsigned ERC-20/curve calldata; no signer.
+export const JAZZ='0x1f243c6638a6becd787f326b240227687a3835bc';
+export const USDG='0x5fc5360d0400a0fd4f2af552add042d716f1d168';
+export const FACTORY='0x7ed598bcef8bd9edd8c97a195c6d13f40801ec7e';
+const RPCS=['https://njc-read-proxy.vercel.app/api/rpc','https://robinhood-rpc.publicnode.com'];
+const hostFetch=(...a)=>globalThis.fetch(...a);
+const U256=(1n<<256n)-1n, BPS=10000n;
+const address=a=>typeof a==='string'&&/^0x[0-9a-f]{40}$/i.test(a)&&!/^0x0{40}$/i.test(a);
+const word=n=>{n=BigInt(n);if(n<0n||n>U256)throw Error('uint256 out of range');return n.toString(16).padStart(64,'0');};
+const aw=a=>a.slice(2).toLowerCase().padStart(64,'0');
+const words=(h,n)=>{if(typeof h!=='string'||!new RegExp('^0x[0-9a-fA-F]{'+n*64+'}$').test(h))throw Error('Incomplete native contract response');return Array.from({length:n},(_,i)=>h.slice(2+i*64,66+i*64));};
+const wa=w=>{if(!/^0{24}[0-9a-f]{40}$/i.test(w))throw Error('Invalid contract address');return '0x'+w.slice(24).toLowerCase();};
+export function parseUSDG(v){
+ if(typeof v!=='string'||!/^(?:0|[1-9][0-9]{0,3})(?:\.[0-9]{1,6})?$/.test(v))throw Error('usdg must be an exact decimal string with at most six decimal places');
+ const [a,b='']=v.split('.');const n=BigInt(a)*1000000n+BigInt(b.padEnd(6,'0'));
+ if(n<1n||n>1000000000n)throw Error('Unsigned plans support 0.000001 to 1000 USDG');return n;
+}
+export function curveBuyQuote({amount,quoteReserve,tokenReserve,sellable,feeBps,creatorTaxBps,snipeTaxBps}){
+ for(const n of [amount,quoteReserve,tokenReserve,sellable,feeBps,creatorTaxBps,snipeTaxBps])if(typeof n!=='bigint'||n<0n||n>U256)throw Error('Invalid curve quantity');
+ if(!amount||!quoteReserve||!tokenReserve||!sellable||sellable>tokenReserve||feeBps+creatorTaxBps>9900n)throw Error('Curve unavailable');
+ const cap=9900n-feeBps-creatorTaxBps, snipe=snipeTaxBps>cap?cap:snipeTaxBps;
+ const fee=amount*feeBps/BPS,tax=amount*creatorTaxBps/BPS,openingTax=amount*snipe/BPS;
+ const net=amount-fee-tax-openingTax, out=net*tokenReserve/(quoteReserve+net);
+ if(!out)throw Error('Amount too small');
+ // Graduation requires a separately qualified v4 route. Do not emit an untested
+ // partial-fill or migration transaction under the old curve assumptions.
+ if(out>=sellable)throw Error('Buy reaches graduation; refresh through the graduated-pool route');
+ return {tokensOut:out,fee,tax,openingTax,effectiveSnipeBps:snipe};
+}
+async function bounded(response){
+ if(!response.ok||response.redirected||!response.headers.get('content-type')?.includes('application/json'))throw Error('Native source unavailable');
+ const reader=response.body?.getReader();if(!reader)throw Error('Empty native source');let size=0,s='';const decoder=new TextDecoder();
+ try{for(;;){const {done,value}=await reader.read();if(done)break;size+=value.length;if(size>65536)throw Error('Oversized native response');s+=decoder.decode(value,{stream:true});}s+=decoder.decode();}finally{await reader.cancel().catch(()=>{});}
+ const j=JSON.parse(s);if(j?.jsonrpc!=='2.0'||j.id!==1||j.error||j.result===undefined)throw Error('Native RPC response invalid');return j.result;
+}
+export async function jazzBuyPlan(args,{fetcher=hostFetch,clock=()=>Date.now(),rpcs=RPCS}={}){
+ if(!args||typeof args!=='object'||Array.isArray(args)||Object.keys(args).some(k=>!['usdg','trader','slippageBps'].includes(k)))throw Error('Unknown buy argument');
+ const amount=parseUSDG(args.usdg),trader=typeof args.trader==='string'?args.trader.toLowerCase():null;if(!address(trader))throw Error('Exact nonzero trader address required');
+ const slip=args.slippageBps??100;if(!Number.isSafeInteger(slip)||slip<0||slip>500)throw Error('slippageBps must be an integer from 0 to 500');
+ let last;
+ for(const source of rpcs){try{
+  const rpc=async(method,params)=>bounded(await fetcher(source,{method:'POST',redirect:'error',signal:AbortSignal.timeout(8000),headers:{'content-type':'application/json',accept:'application/json'},body:JSON.stringify({jsonrpc:'2.0',id:1,method,params})}));
+  if(BigInt(await rpc('eth_chainId',[]))!==4663n)throw Error('Wrong chain');
+  const block=await rpc('eth_getBlockByNumber',['latest',false]);
+  if(!/^0x[0-9a-f]{64}$/i.test(block?.hash??'')||!/^0x[0-9a-f]+$/i.test(block?.number??'')||!/^0x[0-9a-f]+$/i.test(block?.timestamp??''))throw Error('Invalid block');
+  const at=Number(BigInt(block.timestamp))*1000,now=clock();if(!Number.isSafeInteger(at)||at>now+30000||now-at>120000)throw Error('Stale native block');
+  const call=async(to,data,n=1)=>words(await rpc('eth_call',[{to,data},block.number]),n);
+  const record=await call(FACTORY,'0x3cf28b5a'+aw(JAZZ),15),curve=wa(record[1]);
+  if(wa(record[0])!==JAZZ||wa(record[4])!==USDG||BigInt('0x'+record[14])!==1n||!address(curve))throw Error('Official launch identity mismatch');
+  const specs=[[JAZZ,'0x7165485d'],[curve,'0xfc0c546a'],[curve,'0x3de35b79'],[curve,'0xdc08e094'],[curve,'0xe7c2b772'],[curve,'0xc68360a5'],[curve,'0x0902f1ac',2],[curve,'0x808bcddc'],[curve,'0x24a9d853'],[curve,'0xc1bb8901'],[curve,'0xd7e1ef39'+aw(trader)],[USDG,'0x313ce567'],[JAZZ,'0x313ce567'],[USDG,'0x70a08231'+aw(trader)],[USDG,'0xdd62ed3e'+aw(trader)+aw(curve)]];
+  const v=await Promise.all(specs.map(([to,data,n])=>call(to,data,n))),n=i=>BigInt('0x'+v[i][0]);
+  if(wa(v[0][0])!==curve||wa(v[1][0])!==JAZZ||wa(v[2][0])!==USDG||n(3)!==0n||n(4)!==0n||n(5)!==0n||n(11)!==6n||n(12)!==18n)throw Error('Curve identity, decimals or trading phase changed');
+  const state={amount,quoteReserve:BigInt('0x'+v[6][0]),tokenReserve:BigInt('0x'+v[6][1]),sellable:n(7),feeBps:n(8),creatorTaxBps:n(9),snipeTaxBps:n(10)};
+  if(state.creatorTaxBps!==BigInt('0x'+record[8]))throw Error('Conflicting fee policy');
+  const q=curveBuyQuote(state),minimum=q.tokensOut*(BPS-BigInt(slip))/BPS;if(!minimum)throw Error('Minimum output too small');
+  // Check the original pinned block is still canonical after all reads.
+  const check=await rpc('eth_getBlockByNumber',[block.number,false]);if(check?.hash!==block.hash)throw Error('Native block changed during read');
+  const transactions=[],tx=(to,data,purpose)=>({chainId:4663,from:trader,to,data,value:'0x0',purpose});
+  if(n(14)<amount){if(n(14)>0n)transactions.push(tx(USDG,'0x095ea7b3'+aw(curve)+word(0n),'Reset prior insufficient USDG allowance'));
+   transactions.push(tx(USDG,'0x095ea7b3'+aw(curve)+word(amount),'Approve exactly the requested USDG amount to this curve'));}
+  transactions.push(tx(curve,'0x59a87bc1'+word(amount)+word(minimum)+aw(trader),'Buy official JAZZ for the same signing wallet'));
+  return {schema:'njc-jazz-buy-plan/v1',chainId:4663,token:JAZZ,quoteToken:USDG,factory:FACTORY,curve,trader,route:'pons-v2-curve',source,
+   observedAt:new Date(now).toISOString(),expiresAt:new Date(now+60000).toISOString(),block:{number:block.number,hash:block.hash,timestamp:block.timestamp},
+   quote:{inputAtoms:amount.toString(),expectedOutputAtoms:q.tokensOut.toString(),minimumOutputAtoms:minimum.toString(),slippageBps:slip,
+    baseFeeAtoms:q.fee.toString(),creatorTaxAtoms:q.tax.toString(),openingTaxAtoms:q.openingTax.toString(),baseFeeBps:state.feeBps.toString(),creatorTaxBps:state.creatorTaxBps.toString(),openingTaxBps:q.effectiveSnipeBps.toString()},
+   funding:{balanceAtoms:n(13).toString(),allowanceAtoms:n(14).toString(),hasQuoteBalance:n(13)>=amount,nativeGasChecked:false},transactions,
+   execution:false,spendingAuthority:false,signed:false,broadcast:false,simulation:false,
+   warning:'Unsigned preparation only. Re-read before signing, check native gas, simulate every step and verify chain 4663 in the signer. ExpiresAt is a client freshness limit, not an on-chain deadline. Later curve depletion can cause a rate-bounded partial fill/refund. No bridge, grant or return is promised.'};
+ }catch(e){last=e;}}
+ throw Object.assign(Error('Official JAZZ native plan unavailable: '+String(last?.message??'source unavailable')),{status:503});
+}
diff --git a/jazz-buy.test.mjs b/jazz-buy.test.mjs
new file mode 100644
index 0000000..eeb22fc
--- /dev/null
+++ b/jazz-buy.test.mjs
@@ -0,0 +1,29 @@
+import test from 'node:test';import assert from 'node:assert/strict';
+import {jazzBuyPlan,parseUSDG,curveBuyQuote,JAZZ,USDG,FACTORY} from './jazz-buy.mjs';
+const trader='0x1479be07e26976fd712db34f7bc1b8ac523f806e',curve='0xedc210ba50ac7ed9939646e98152898f1f865a6f';
+const W=n=>BigInt(n).toString(16).padStart(64,'0'),A=a=>a.slice(2).padStart(64,'0'),now=1800000000000;
+const block={number:'0x1234',hash:'0x'+'a'.repeat(64),timestamp:'0x'+(now/1000).toString(16)};
+function fixture({allowance=0n,balance=2000000n,change=()=>{}}={}){const calls=[];
+ const f=async(url,init)=>{const p=JSON.parse(init.body);calls.push(p);let result;
+ if(p.method==='eth_chainId')result='0x1237';
+ else if(p.method==='eth_getBlockByNumber')result={...block};
+ else if(p.method==='eth_call'){
+  assert.equal(p.params[1],block.number);const d=p.params[0].data,to=p.params[0].to;
+  const table={'0x7165485d':A(curve),'0xfc0c546a':A(JAZZ),'0x3de35b79':A(USDG),'0xdc08e094':W(0),'0xe7c2b772':W(0),'0xc68360a5':W(0),'0x0902f1ac':W(4000000000n)+W(800000000000000000000000000n),'0x808bcddc':W(700000000000000000000000000n),'0x24a9d853':W(100),'0xc1bb8901':W(330),'0xd7e1ef39':W(0),'0x70a08231':W(balance),'0xdd62ed3e':W(allowance)};
+  if(to===FACTORY)result='0x'+[A(JAZZ),A(curve),A(trader),A(trader),A(USDG),...Array(3).fill(W(0)),W(330),...Array(5).fill(W(0)),W(1)].join('');
+  else if(d==='0x313ce567')result='0x'+W(to===USDG?6:18);
+  else {assert(table[d.slice(0,10)]!==undefined);result='0x'+table[d.slice(0,10)];}
+ }else assert.fail('No write or unsupported RPC: '+p.method);
+ result=change(p,result,calls)??result;return Response.json({jsonrpc:'2.0',id:1,result});};
+ return {f,calls,plan:args=>jazzBuyPlan({usdg:'1',trader,...args},{fetcher:f,clock:()=>now,rpcs:['https://fixture.invalid']})};
+}
+test('six decimal amounts are exact and never rounded from floats',()=>{assert.equal(parseUSDG('0.000001'),1n);assert.equal(parseUSDG('1000'),1000000000n);for(const x of [1,NaN,'1e2','01',' 1','1.0000001','0','-1','1000.000001',null])assert.throws(()=>parseUSDG(x));});
+test('ordinary curve quote deducts base, creator and opening fees in integer order',()=>{const q=curveBuyQuote({amount:1000000n,quoteReserve:4000000000n,tokenReserve:800000000000000000000000000n,sellable:700000000000000000000000000n,feeBps:100n,creatorTaxBps:330n,snipeTaxBps:0n});assert.equal(q.tokensOut,957000n*800000000000000000000000000n/4000957000n);assert.equal(q.fee,10000n);assert.equal(q.tax,33000n);});
+test('snipe cap and graduation are explicit',()=>{const s={amount:1000000n,quoteReserve:4000000000n,tokenReserve:800000000000000000000000000n,sellable:700000000000000000000000000n,feeBps:100n,creatorTaxBps:330n,snipeTaxBps:10000n};assert.equal(curveBuyQuote(s).effectiveSnipeBps,9470n);assert.throws(()=>curveBuyQuote({...s,sellable:1n}),/graduation/);});
+test('pinned native plan approves exact amount then buys to same trader',async()=>{const {plan,calls}=fixture();const r=await plan();assert.equal(r.transactions.length,2);assert.equal(r.transactions[0].to,USDG);assert.equal(r.transactions[0].data.slice(-64),W(1000000));assert.equal(r.transactions[1].to,curve);assert(r.transactions[1].data.endsWith(A(trader)));assert.equal(r.execution,false);assert.equal(r.simulation,false);assert.equal(r.quote.baseFeeAtoms,'10000');assert.equal(r.quote.creatorTaxAtoms,'33000');assert.equal(r.funding.hasQuoteBalance,true);assert(calls.every(c=>!['eth_sendRawTransaction','eth_sendTransaction','eth_sign'].includes(c.method)));});
+test('sufficient allowance skips approval; insufficient nonzero resets then exact approval',async()=>{assert.equal((await fixture({allowance:1000000n}).plan()).transactions.length,1);const r=await fixture({allowance:1n}).plan();assert.equal(r.transactions.length,3);assert(r.transactions[0].data.endsWith(W(0)));});
+test('missing funding is disclosed, never fabricated or auto funded',async()=>{const r=await fixture({balance:0n}).plan();assert.equal(r.funding.hasQuoteBalance,false);assert.equal(r.spendingAuthority,false);});
+test('malformed inputs and unbounded slippage cause no IO',async()=>{for(const args of [{trader:1},{trader:'0x'+'0'.repeat(40)},{slippageBps:501},{slippageBps:-1},{slippageBps:1.5},{usdg:1},{recipient:trader}]){const f=fixture();await assert.rejects(f.plan(args));assert.equal(f.calls.length,0);}});
+for(const [name,selector,replacement] of [['wrong chain',null,'0x1'],['wrong quote','0x3de35b79','0x'+A(trader)],['graduated','0xe7c2b772','0x'+W(1)],['ready','0xc68360a5','0x'+W(1)],['native quote','0xdc08e094','0x'+W(1)],['wrong USDG decimals','0x313ce567','0x'+W(18)],['bad tax','0xc1bb8901','0x'+W(100)],['empty reserves','0x0902f1ac','0x']])test(name+' refuses preparation',async()=>{const f=fixture({change:(p,r)=>selector===null&&p.method==='eth_chainId'?replacement:p.method==='eth_call'&&p.params[0].data===selector?replacement:r});await assert.rejects(f.plan());});
+test('stale snapshot and reorg refuse preparation',async()=>{for(const mode of ['stale','reorg']){let count=0;const f=fixture({change:(p,r)=>{if(p.method==='eth_getBlockByNumber'){count++;return mode==='stale'?{...r,timestamp:'0x1'}:count>1?{...r,hash:'0x'+'b'.repeat(64)}:r;}return r;}});await assert.rejects(f.plan());}});
+test('redirected or broken RPC is not a fallback quote',async()=>{await assert.rejects(jazzBuyPlan({usdg:'1',trader},{fetcher:async()=>new Response('',{status:302}),rpcs:['https://fixture.invalid']}));});
diff --git a/raeto-gateway.mjs b/raeto-gateway.mjs
new file mode 100644
index 0000000..b9e0528
--- /dev/null
+++ b/raeto-gateway.mjs
@@ -0,0 +1,26 @@
+// Existing merchant rail: never return paid bytes before capture is acknowledged.
+const BASE='https://api.raeto.cc';
+const response=(body,status=200)=>Response.json(body,{status,headers:{'cache-control':'private, no-store',vary:'X-Raeto-Receipt, Authorization','access-control-allow-origin':'*'}});
+async function bodyJSON(r){if(!r.headers.get('content-type')?.includes('application/json'))throw Error('Invalid payment response');const t=await r.text();if(t.length>32768)throw Error('Oversized payment response');const j=JSON.parse(t);if(!j||typeof j!=='object'||Array.isArray(j))throw Error('Invalid payment response');return j;}
+export async function raetoGateway(req,{key,payTo,price,resource,run,validate=()=>{},fetcher=(...a)=>globalThis.fetch(...a)}){
+ const receipt=req.headers.get('x-raeto-receipt'),quote={error:'payment_required',message:`This call costs $${price} in Raeto credits.`,raeto:{payTo,amountUsd:price,resource,payUrl:BASE+'/v1/pay',docs:BASE+'/v1/pay/info'}};
+ if(!receipt)return response(quote,402);
+ if(receipt.length>8192)return response({error:'Invalid receipt'},400);
+ if(typeof key!=='string'||!key)return response({error:'Merchant payment service unavailable',paymentStatus:'not_checked'},503);
+ let args;try{const text=await req.text();if(text.length>16384)throw Error();args=JSON.parse(text);if(!args||typeof args!=='object'||Array.isArray(args))throw Error();validate(args);}catch{return response({error:'Invalid service arguments; payment not checked',paymentStatus:'not_checked'},400);}
+ const call=async(path,body)=>{
+  const r=await fetcher(BASE+path,{method:'POST',redirect:'error',signal:AbortSignal.timeout(12000),headers:{authorization:'Bearer '+key,'content-type':'application/json',accept:'application/json'},body:JSON.stringify(body)});
+  const j=await bodyJSON(r);return {ok:r.ok&&!r.redirected&&!j.error&&j.ok!==false&&j.valid!==false&&(path!=='/v1/pay/capture'||j.captured!==false),status:r.status,j};
+ };
+ let v;try{v=await call('/v1/pay/verify',{receipt,minUsd:price,resource,capture:false});}catch{return response({error:'Payment verification unavailable; no result delivered',paymentStatus:'verify_unknown',retry:'Reconcile the original receipt before any new payment'},503);}
+ if(!v.ok)return response({...quote,error:'Payment not accepted',paymentStatus:'refused'},[400,401,402,403,404,409].includes(v.status)?402:503);
+ // The seller's key binds the payee; independently reject conflicting mirrors.
+ if(v.j.payTo&&v.j.payTo.toLowerCase()!==payTo.toLowerCase()||v.j.resource&&v.j.resource!==resource)return response({error:'Conflicting payment identity',paymentStatus:'held'},503);
+ let out;
+ try{out=await run(args);if(!out||typeof out!=='object'||out.error||out.ok===false||out.charged===false)throw Error('Service unavailable');}
+ catch{let released=false;try{released=(await call('/v1/pay/release',{receipt,reason:'call failed'})).ok;}catch{}
+  return response({error:'Service failed; no result delivered',paymentStatus:released?'released':'release_unknown',...(released?{charged:false}:{retry:'Reconcile the original receipt before paying again'})},502);}
+ let c;try{c=await call('/v1/pay/capture',{receipt});}catch{}
+ if(!c?.ok)return response({error:'Capture unconfirmed; paid result withheld',paymentStatus:'capture_unknown',retry:'Do not pay again or automatically release; reconcile the original receipt with Raeto'},503);
+ return response({...out,paid:{via:'Raeto Pay',usd:price,seller:'JazzCat #1',captureConfirmed:true}});
+}
diff --git a/raeto-gateway.test.mjs b/raeto-gateway.test.mjs
new file mode 100644
index 0000000..f5fcd12
--- /dev/null
+++ b/raeto-gateway.test.mjs
@@ -0,0 +1,12 @@
+import test from 'node:test';import assert from 'node:assert/strict';import {raetoGateway} from './raeto-gateway.mjs';
+const payTo='0x1479be07e26976fd712db34f7bc1b8ac523f806e';
+const request=(receipt='opaque-receipt',body='{}')=>new Request('https://fixture/raeto/usdg_ledger',{method:'POST',headers:receipt?{'x-raeto-receipt':receipt}:{},body});
+async function run({responses={},service=async()=>({privateEvidence:'paid bytes'}),key='fixture-key',req=request()}={}){let calls=[],ran=0;const r=await raetoGateway(req,{key,payTo,price:0.05,resource:'/raeto/usdg_ledger',run:async a=>{ran++;return service(a);},fetcher:async(url,init)=>{const path=new URL(url).pathname;calls.push(path);const v=responses[path];if(v instanceof Error)throw v;return Response.json(v?.body??{ok:true},{status:v?.status??200});}});return {r,body:await r.json(),calls,ran};}
+test('unpaid price is exact, private and does not call payment provider',async()=>{const x=await run({req:request(null)});assert.equal(x.r.status,402);assert.equal(x.body.raeto.amountUsd,0.05);assert.equal(x.r.headers.get('cache-control'),'private, no-store');assert.deepEqual(x.calls,[]);});
+test('verify then run then capture succeeds before bytes are delivered',async()=>{const x=await run();assert.equal(x.r.status,200);assert.equal(x.body.paid.captureConfirmed,true);assert.equal(x.body.privateEvidence,'paid bytes');assert.deepEqual(x.calls,['/v1/pay/verify','/v1/pay/capture']);});
+for(const response of [{body:{error:'no'},status:402},{body:{valid:false}},{body:{ok:false}}])test('refused verification does not run service',async()=>{const x=await run({responses:{'/v1/pay/verify':response}});assert.notEqual(x.r.status,200);assert.equal(x.ran,0);assert(!JSON.stringify(x.body).includes('paid bytes'));});
+for(const response of [{body:{error:'no'},status:409},{body:{captured:false}},new Error('timeout')])test('failed or ambiguous capture never delivers or blindly refunds',async()=>{const x=await run({responses:{'/v1/pay/capture':response}});assert.equal(x.r.status,503);assert.equal(x.body.paymentStatus,'capture_unknown');assert(!JSON.stringify(x.body).includes('paid bytes'));assert(!x.calls.includes('/v1/pay/release'));assert.equal(x.body.charged,undefined);});
+test('service failure releases a held payment, and release uncertainty is not charged:false',async()=>{const service=async()=>{throw Error('fail')};const x=await run({service});assert.equal(x.body.charged,false);assert.equal(x.body.paymentStatus,'released');const y=await run({service,responses:{'/v1/pay/release':new Error('timeout')}});assert.equal(y.body.charged,undefined);assert.equal(y.body.paymentStatus,'release_unknown');});
+test('missing key and malformed bodies never call provider or service',async()=>{for(const options of [{key:''},{req:request('r','bad')},{req:request('r','[]')}]){const x=await run(options);assert.equal(x.ran,0);assert.deepEqual(x.calls,[]);}});
+test('verification transport failure and wrong payee do not run or disclose',async()=>{for(const r of [new Error('timeout'),{body:{ok:true,payTo:'0x'+'1'.repeat(40)}}]){const x=await run({responses:{'/v1/pay/verify':r}});assert.equal(x.r.status,503);assert.equal(x.ran,0);}});
+test('uncaptured verification is a valid hold, not a capture refusal',async()=>{const x=await run({responses:{'/v1/pay/verify':{body:{ok:true,captured:false}}}});assert.equal(x.r.status,200);assert.equal(x.body.paid.captureConfirmed,true);});
diff --git a/service-catalog.test.mjs b/service-catalog.test.mjs
new file mode 100644
index 0000000..928e91d
--- /dev/null
+++ b/service-catalog.test.mjs
@@ -0,0 +1,2 @@
+import test from 'node:test';import assert from 'node:assert/strict';import worker from './worker.mjs';
+test('nine priced service schemas match every unpaid POST challenge',async()=>{const r=await worker.fetch(new Request('https://fixture/services'),{},{}),x=await r.json();assert.equal(x.tools.length,9);assert.match(x.marketplaceListing,/separate/);for(const t of x.tools){assert.equal(t.inputSchema.additionalProperties,false);assert(t.inputSchema.required.length===1);const challenge=await worker.fetch(new Request(t.endpoint,{method:'POST',body:'{}'}),{},{});assert.equal(challenge.status,402);assert.equal(challenge.headers.get('cache-control'),'private, no-store');const q=await challenge.json();assert.equal(q.raeto.amountUsd,t.priceUsd);assert.equal(q.raeto.payTo,x.payTo);assert.equal(q.raeto.resource,new URL(t.endpoint).pathname);}});
diff --git a/title-report.mjs b/title-report.mjs
new file mode 100644
index 0000000..a8c7c66
--- /dev/null
+++ b/title-report.mjs
@@ -0,0 +1,16 @@
+// Read-only bridge to the City's existing public title source. No auth forwarding.
+const SOURCE='https://newjazzcity.pages.dev/api/public/title';
+export const TITLE_TOOL={name:'title_report',title:'Read what transfers with a JazzCat',description:'Free public title snapshot: assets, seller-held agent identity, revoked grants and source-reported obligations. Not a sale, debt assignment, guarantee or exhaustive lien search.',inputSchema:{type:'object',properties:{id:{type:'integer',minimum:1,maximum:5678}},required:['id'],additionalProperties:false}};
+export async function titleReport(args,{fetcher=(...a)=>globalThis.fetch(...a),clock=()=>Date.now()}={}){
+ if(!args||typeof args!=='object'||Array.isArray(args)||Object.keys(args).some(k=>k!=='id')||!Number.isSafeInteger(args.id)||args.id<1||args.id>5678)throw Object.assign(Error('Exact Cat id from 1 to 5678 required'),{status:400});
+ try{
+ const source=SOURCE+'?cat='+args.id,r=await fetcher(source,{redirect:'error',signal:AbortSignal.timeout(12000),headers:{accept:'application/json'}});
+ if(!r.ok||r.redirected||!r.headers.get('content-type')?.includes('application/json'))throw Error('Title source unavailable');
+ const reader=r.body?.getReader();if(!reader)throw Error('Empty title');let n=0,s='';const d=new TextDecoder();
+ try{for(;;){const {done,value}=await reader.read();if(done)break;n+=value.length;if(n>65536)throw Error('Oversized title');s+=d.decode(value,{stream:true});}s+=d.decode();}finally{await reader.cancel().catch(()=>{});}
+ const data=JSON.parse(s),now=clock(),at=Date.parse(data.observedAt);
+ if(data.cat!==args.id||data.chainId!==4663||data.collection?.toLowerCase()!=='0xb3d33af2ce8ce0792942b487e2213ac665dd83e2'||!Number.isFinite(at)||at>now+30000||now-at>120000||!Array.isArray(data.liens)||!data.transfers||typeof data.transfers!=='object')throw Error('Invalid or stale title source');
+ return {schema:'njc-public-title-read/v1',source,observedAt:new Date(now).toISOString(),data,sourceReported:true,independentlyVerified:false,execution:false,spendingAuthority:false,transferGuarantee:false,
+ coverage:'Source-reported public snapshot, not exhaustive liabilities or transaction-bound conveyance. Unknown or omitted sources are not proof of clear title. ERC-8004 identity/credit transfer only if separately owned and included; private data and old authority never transfer automatically.'};
+ }catch{throw Object.assign(Error('Public title unavailable or invalid; no clear-title assumption or action taken'),{status:503});}
+}
diff --git a/title-report.test.mjs b/title-report.test.mjs
new file mode 100644
index 0000000..28e5496
--- /dev/null
+++ b/title-report.test.mjs
@@ -0,0 +1,6 @@
+import test from 'node:test';import assert from 'node:assert/strict';import {titleReport} from './title-report.mjs';import worker from './worker.mjs';
+const now=1800000000000;const data={cat:1,chainId:4663,collection:'0xb3d33af2ce8ce0792942b487e2213ac665dd83e2',observedAt:new Date(now).toISOString(),transfers:{agent:null},liens:[],clear:true};
+test('title preserves source attribution without promoting reported clear to guarantee',async()=>{const r=await titleReport({id:1},{fetcher:async()=>Response.json(data),clock:()=>now});assert.equal(r.data.clear,true);assert.equal(r.transferGuarantee,false);assert.equal(r.independentlyVerified,false);});
+test('bad id and unapproved fetch arguments cannot redirect source',async()=>{for(const a of [{id:0},{id:5679},{id:'1'},{id:1,url:'https://evil.invalid'}])await assert.rejects(titleReport(a,{fetcher:()=>assert.fail('no IO')}));});
+test('wrong identity, chain, stale, incomplete and oversized sources fail closed',async()=>{for(const d of [{...data,cat:2},{...data,chainId:1},{...data,collection:'0x'+'1'.repeat(40)},{...data,observedAt:new Date(1).toISOString()},{...data,liens:null},{...data,extra:'x'.repeat(66000)}])await assert.rejects(titleReport({id:1},{fetcher:async()=>Response.json(d),clock:()=>now}),/unavailable/);});
+test('HTTP and MCP public title paths match; no holder auth forwarded',async()=>{const save=globalThis.fetch;globalThis.fetch=async(url,init)=>{assert.equal(init.headers.authorization,undefined);return Response.json({...data,observedAt:new Date().toISOString()});};try{const h=await worker.fetch(new Request('https://fixture/title?cat=1'),{},{});assert.equal(h.status,200);const x=await worker.fetch(new Request('https://fixture/mcp',{method:'POST',body:JSON.stringify({jsonrpc:'2.0',id:1,method:'tools/call',params:{name:'title_report',arguments:{id:1}}})}),{},{});assert.equal((await x.json()).result.structuredContent.transferGuarantee,false);assert.equal((await h.json()).schema,'njc-public-title-read/v1');for(const q of ['cat=1&cat=1','cat=01','cat=1&url=x'])assert.equal((await worker.fetch(new Request('https://fixture/title?'+q),{},{})).status,400);}finally{globalThis.fetch=save;}});
diff --git a/worker.mjs b/worker.mjs
index f680497..a8bd926 100644
--- a/worker.mjs
+++ b/worker.mjs
@@ -1,3 +1,6 @@
+import {raetoGateway} from './raeto-gateway.mjs';
+import {jazzBuyPlan,JAZZ as OFFICIAL_JAZZ} from './jazz-buy.mjs';
+import {titleReport,TITLE_TOOL} from './title-report.mjs';
 import {renderPublicCat} from './public-cat.mjs';
 import {consumeHolderRead} from './holder-entitlement.mjs';
 import { ECON_TOOLS, economyCall } from './economics.mjs';
@@ -817,17 +820,16 @@ const RAETO_TOOLS = {
   full_check: {price: 2.7, run: a => fullCheck(a.address)},
 };
 async function raetoTool(req, env, name, origin) {
-  const t = RAETO_TOOLS[name]; if (!t) return json({error: 'no such tool'}, 404);
-  const resource = '/raeto/' + name, receipt = req.headers.get('x-raeto-receipt');
-  const quote = {error: 'payment_required', message: `This call costs $${t.price} in Raeto credits. Pay it and retry with the X-Raeto-Receipt header.`, raeto: {payTo: RAETO_PAYTO, amountUsd: t.price, resource, payUrl: RAETO + '/v1/pay', docs: RAETO + '/v1/pay/info'}};
-  if (!receipt) return json(quote, 402);
-  const call = (path, body) => fetch(RAETO + path, {method: 'POST', headers: {authorization: 'Bearer ' + env.RAETO_KEY, 'content-type': 'application/json'}, body: JSON.stringify(body)}).then(async r => ({ok: r.ok, status: r.status, j: await r.json().catch(() => null)}));
-  const v = await call('/v1/pay/verify', {receipt, minUsd: t.price, resource, capture: false});
-  if (!v.ok) return json({...quote, message: 'Payment not accepted: ' + (v.j?.error?.message || v.status)}, 402);
-  const args = await req.json().catch(() => ({}));
-  try { const out = await t.run(args || {}); await call('/v1/pay/capture', {receipt}); return json({...out, paid: {via: 'Raeto Pay', usd: t.price, seller: 'JazzCat #1'}}); }
-  catch (e) { await call('/v1/pay/release', {receipt, reason: 'call failed'}); return json({error: e.message, charged: false}, 400); }
+  const t=RAETO_TOOLS[name];if(!t)return json({error:'no such tool'},404);
+  return raetoGateway(req,{key:env.RAETO_KEY,payTo:RAETO_PAYTO,price:t.price,resource:'/raeto/'+name,run:t.run,validate:a=>{const shape=SERVICE_INPUTS[name],keys=Object.keys(shape);if(Object.keys(a).some(k=>!keys.includes(k))||typeof a[keys[0]]!=='string'||a[keys[0]].length<1||a[keys[0]].length>100)throw Error('Invalid input');if(a.days!==undefined&&(!Number.isSafeInteger(a.days)||a.days<1||a.days>30))throw Error('Invalid days');if(a.chain!==undefined&&!['rh','base'].includes(a.chain))throw Error('Invalid chain');}});
 }
+const SERVICE_INPUTS={
+ halt_check:{symbol:{type:'string'}},transfer_read:{contract:{type:'string'}},wallet_handover:{account:{type:'string'},chain:{type:'string',enum:['rh','base']}},
+ poison_check:{address:{type:'string'}},money_trail:{token:{type:'string'}},base_trail:{token:{type:'string'}},sol_trail:{mint:{type:'string'}},usdg_ledger:{address:{type:'string'},days:{type:'integer',minimum:1,maximum:30}},full_check:{address:{type:'string'}}
+};
+function serviceCatalog(){return {schema:'njc-agent-services/v1',seller:'JazzCat #1',payTo:RAETO_PAYTO,rail:'Raeto Pay',marketplaceListing:'Not established by endpoint compatibility; check Raeto catalog approval separately',
+ tools:Object.entries(RAETO_TOOLS).map(([name,t])=>({name:'jazzcat_'+name,title:name.replaceAll('_',' '),description:'JazzCat #1 '+name.replaceAll('_',' ')+'. Source-attributed chain evidence; read-only, not investment advice or a guarantee.',priceUsd:t.price,
+ endpoint:'https://njc-tx-explain.departmentofjazz.workers.dev/raeto/'+name,inputSchema:{type:'object',properties:SERVICE_INPUTS[name],required:[Object.keys(SERVICE_INPUTS[name])[0]],additionalProperties:false}}))};}
 
 // City desks: founding tenants' offices in New Jazz City, drawn read-only from their own public sources.
 const DESK_CSS = `:root{--bg:#0b0b10;--fg:#e9e6ff;--mute:#9a95b8;--line:#2a2840;--acc:#6ee7ff}body{margin:0;background:var(--bg);color:var(--fg);font:15px/1.5 ui-sans-serif,system-ui,sans-serif}main{max-width:860px;margin:0 auto;padding:24px 16px}h1{font-size:22px;margin:0 0 4px}h2{font-size:16px;margin:24px 0 8px}a{color:var(--acc)}table{width:100%;border-collapse:collapse;font-size:14px}td,th{border-bottom:1px solid var(--line);padding:6px 4px;text-align:left;vertical-align:top}.k{color:var(--mute)}.btn{display:inline-block;margin-top:12px;padding:8px 14px;border:1px solid var(--acc);border-radius:6px;text-decoration:none}.tag{font-size:12px;color:var(--mute)}`;
@@ -877,8 +879,8 @@ const CONTROL_TOOL = {name: 'who_controls_agent', title: 'Who controls an ERC-80
 const QHOOKS_MCP = 'https://qhooks.com/mcp?ref=newjazzcity';
 // $JAZZ, once live (JAZZ_TOKEN): an unsigned buy through QHooks for the caller's own wallet, New Jazz City as referrer.
 let JAZZ_TOKEN = null;
-const BUY_JAZZ = {name: 'buy_jazz', title: 'Buy $JAZZ, the coin of the work layer (unsigned plan)', description: 'Free. Requests an unsigned buy plan for your wallet. Availability depends on the route and pool; this tool does not sign or prove a burn.',
-  inputSchema: {type: 'object', properties: {usdg: {type: 'string', description: 'USDG to spend, e.g. "5"'}, trader: {type: 'string', description: 'the wallet that will sign'}, slippageBps: {type: 'integer'}}, required: ['usdg', 'trader']}};
+const BUY_JAZZ = {name: 'buy_jazz', title: 'Buy $JAZZ, the coin of the work layer (unsigned plan)', description: 'Free. Native Pons V2 curve quote and exact-amount approval/buy calldata for official JAZZ on chain 4663. Uses pinned public chain state, includes fees and bounded slippage. Unsigned only: your wallet checks, simulates and signs. Graduation requires another route.',
+  inputSchema: {type: 'object', properties: {usdg: {type: 'string', description: 'USDG to spend, e.g. "5"'}, trader: {type: 'string', description: 'the wallet that will sign'}, slippageBps: {type: 'integer'}}, required: ['usdg', 'trader'], additionalProperties: false}};
 // Free: the agent check-up (planted orders, hidden characters, look-alike addresses, risky tools) for any skill, memory
 // note, MCP config or tool description. Text in, or an https URL to a public file.
 const CHECKUP_TOOL = {name: 'agent_checkup', title: 'Check an agent\'s instructions, skills, MCP config or tool descriptions for poisoning',
@@ -1064,6 +1066,7 @@ function llmsTxt(origin) {
     `## Paid reads (GET, x402: call it, get a 402 with the price, pay, call again with the payment header)`,
     ...PAID_TOOLS.map(t => `- [${t.title}](${origin}/x402/${t.route}?${qs(t)}): ${t.price} USDG${marketLink(t.route) ? ` · buy through the market: ${marketLink(t.route)}?${qs(t)}` : ''}`), ``,
     `Base token verdict track record: every verdict hashed hourly on Robinhood Chain and scored against liquidity and price at 24h and 72h: https://newjazzcity.pages.dev/verdicts/`, ``,
+    `## Native JAZZ and Cat title`, `- buy_jazz({usdg:"1",trader:"0x...",slippageBps:100}): official JAZZ on RH, native Pons V2 curve, pinned quote and exact allowance/buy calldata. Unsigned only; check gas and simulate. Graduation route not offered.`, `- title_report({id:1}) or GET ${origin}/title?cat=1: source-reported title, wallet assets, seller-retained identity and obligations; not a sale or clear-title guarantee.`, `- GET ${origin}/services: nine priced Raeto-compatible service definitions and JSON input schemas. Marketplace listing approval is separate.`, ``,
     `## Free multichain access`, ``, `- market_capabilities({}) or GET ${origin}/markets/capabilities: exact RH/Base/Solana coverage.`, `- market_read({network,view,asset?,limit?}) or GET ${origin}/markets: QHooks-listed RH/Base launches/token detail; Solana exact mint supply.`, `- Read observations are not complete portfolios, Cat execution permission or a bridge. No additional JAZZ launch.`, ``, `## How to pay`,
     `- x402 v1 (network "robinhood") or v2 (network "eip155:4663"), exact scheme, USDG ${USDG}, for house Cats the configured receiver is ${(CITY_WALLET || CAT1_WALLET).toLowerCase()}. Always verify the per-network 402 challenge; if a quote and challenge disagree, stop before paying.`,
     `- Base: USDC ${BASE_USDC.toLowerCase()} on eip155:8453 is accepted where the 402 offers it.`,
@@ -1085,6 +1088,7 @@ function agentCard(origin) {
     provider: {organization: 'New Jazz City'}, identity: {standard: 'ERC-8004', chainId: 4663, registry: '0x8004A169FB4a3325136EB29fA0ceB6D2e539a432', agentId: 26063},
     payment: {protocol: 'x402', networks: ['robinhood', 'eip155:4663', 'eip155:8453', 'solana', SOL_V2], asset: {robinhood: USDG, base: BASE_USDC, solana: SOL_USDC}, payTo: (CITY_WALLET || CAT1_WALLET).toLowerCase(), payToSolana: SOL_PAYTO},
     jobs: origin + '/jobs?format=json',
+    title:origin+'/title?cat={id}',services:origin+'/services',
     publicReads: [...ECON_TOOLS.map(({name,path,inputSchema,description}) => ({name,endpoint:origin+path,inputSchema,description})),
       ...MARKET_TOOLS.map(({name,inputSchema,description})=>({name,endpoint:origin+(name==='market_capabilities'?'/markets/capabilities':'/markets'),inputSchema,description}))],
     mcp: origin + '/mcp', llms: origin + '/llms.txt', book: origin + '/book.json', buy: origin + '/buy?read={route}',
@@ -1238,15 +1242,18 @@ export default {
     if (url.pathname === '/desk/bank-of-me' && req.method === 'GET') { count(env, ctx, 'desk:bank-of-me'); try { return await bankOfMeDesk(); } catch (e) { return json({error: e.message}, 502); } }
     if (url.pathname === '/desk/submission-office' && req.method === 'GET') { count(env, ctx, 'desk:submission-office'); try { return await submissionOfficeDesk(); } catch (e) { return json({error: e.message}, 502); } }
     if (url.pathname === '/halt-check/status' && req.method === 'GET') { try { const r = await haltCheck('AAPL'); return json({listsRead: r.listsRead, oracleRead: !!r.oracle, checkedAt: r.checkedAt}); } catch (e) { return json({error: e.message}, 502); } }
+    if(url.pathname==='/services'&&req.method==='GET')return json(serviceCatalog());
     { const m = url.pathname.match(/^\/raeto\/([a-z_]+)$/); if (m && req.method === 'POST') { count(env, ctx, 'raeto:' + m[1]); return raetoTool(req, env, m[1], url.origin); } }
     if (url.pathname === '/x402/halt-check' && req.method === 'GET') return paid(req, url, () => haltCheck(url.searchParams.get('symbol')), haltReq);
     if (url.pathname === '/x402/line-read' && req.method === 'GET') return paid(req, url, () => lineRead(url.searchParams.get('agentId'), url.searchParams.get('vault'), url.searchParams.get('wallet')), lineReq);
+    if(url.pathname==='/title'&&req.method==='GET'){try{const keys=[...url.searchParams.keys()];if(keys.length!==1||keys[0]!=='cat'||!/^([1-9][0-9]{0,3})$/.test(url.searchParams.get('cat')??''))throw Object.assign(Error('One exact cat parameter required'),{status:400});return json(await titleReport({id:Number(url.searchParams.get('cat'))}));}catch(e){return json({error:e.message,execution:false},e.status??400);}}
     if (url.pathname !== '/mcp' || req.method !== 'POST') return json({error: 'POST /mcp (MCP JSON-RPC), GET /?tx=0x… (free), or GET /x402/ledger?address=0x… (0.05 USDG via x402)'}, 404);
     const m = await req.json().catch(() => null); if (!m) return json({jsonrpc: '2.0', id: null, error: {code: -32700, message: 'Parse error'}}, 400);
     if (m.id === undefined) return new Response(null, {status: 202});
     const ok = result => json({jsonrpc: '2.0', id: m.id, result});
     if (m.method === 'initialize') return ok({protocolVersion: m.params?.protocolVersion ?? '2025-03-26', capabilities: {tools: {}}, serverInfo: {name: 'rh-tx-explain (JazzCat #1, New Jazz City)', version: '0.2.0'}});
-    if (m.method === 'tools/list') return ok({tools: [TOOL, CONTROL_TOOL, CHECKUP_TOOL, JOBS_TOOL, ...CITY_JOB_TOOLS, ...ECON_TOOLS.map(({path,...t})=>t), ...MARKET_TOOLS, ...(JAZZ_TOKEN ? [BUY_JAZZ] : []), ...QHOOKS_TOOLS, ...PAID_TOOLS.map(t => marketLink(t.route) ? {...t, description: `${t.description} Canonical checkout: ${marketLink(t.route)} (agents4663, refund if the read fails).`} : t)]});
+    if (m.method === 'tools/list') return ok({tools: [TOOL, CONTROL_TOOL, CHECKUP_TOOL, TITLE_TOOL, JOBS_TOOL, ...CITY_JOB_TOOLS, ...ECON_TOOLS.map(({path,...t})=>t), ...MARKET_TOOLS, ...(JAZZ_TOKEN ? [BUY_JAZZ] : []), ...QHOOKS_TOOLS, ...PAID_TOOLS.map(t => marketLink(t.route) ? {...t, description: `${t.description} Canonical checkout: ${marketLink(t.route)} (agents4663, refund if the read fails).`} : t)]});
+    if(m.method==='tools/call'&&m.params?.name===TITLE_TOOL.name){try{const r=await titleReport(m.params.arguments);return ok({content:[{type:'text',text:JSON.stringify(r)}],structuredContent:r});}catch(e){return ok({content:[{type:'text',text:e.message}],isError:true});}}
     if (m.method === 'tools/call' && MARKET_TOOLS.some(t=>t.name===m.params?.name)) {
       try {
         const r=m.params.name==='market_capabilities'?marketCapabilities(m.params.arguments??{}):await marketRead(m.params.arguments);
@@ -1267,10 +1274,10 @@ export default {
     if (m.method === 'tools/call' && m.params?.name === BUY_JAZZ.name) {
       const a = m.params.arguments || {}; count(env, ctx, 'mcp-buy_jazz');
       if (!JAZZ_TOKEN) return ok({content: [{type: 'text', text: '$JAZZ is not live yet.'}], isError: true});
-      const usdg = Number(a.usdg);
-      if (!(usdg > 0)) return ok({content: [{type: 'text', text: 'usdg is the USDG to spend, e.g. "5".'}], isError: true});
-      return ok(await qhooksCall('prepare_trade', {chain: '4663', token: JAZZ_TOKEN, side: 'buy', amountIn: String(Math.round(usdg * 1e6)), trader: a.trader,
-        ...(a.slippageBps != null ? {slippageBps: a.slippageBps} : {}), referrer: CITY_WALLET || NJC_TREASURY}));
+      try {
+        if(JAZZ_TOKEN.toLowerCase()!==OFFICIAL_JAZZ)throw Error('Official JAZZ configuration mismatch');
+        const r=await jazzBuyPlan(a);return ok({content:[{type:'text',text:JSON.stringify(r)}],structuredContent:r});
+      }catch(e){return ok({content:[{type:'text',text:e.message}],isError:true});}
     }
     if (m.method === 'tools/call' && QHOOKS_TOOLS.some(t => t.name === m.params?.name)) {
       const a = m.params.arguments || {}, referrer = CITY_WALLET || NJC_TREASURY; count(env, ctx, 'mcp-' + m.params.name);

R-1: Income read: two lookups still treated a node error as an empty answer (found in the first retest)

Low (3.7, CWE-754) · HEY: Fixed in 007d04b. Details in HEY's report.

007d04b (HEY retest (11-27): R-1 income-read node errors fail the read; claim nonce shape + validBefore takeover; split-query null part throws; one holder read per offer (#209)) is shown in full above, under F-3.