Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
feat(knock): give the escrowed lane a door, a countdown and a refund the sender signs themselves
nirholas8ee4060ff534
diff --git a/api/_lib/knock/store.js b/api/_lib/knock/store.jsindex c11039ab0..f00a84506 100644--- a/api/_lib/knock/store.js+++ b/api/_lib/knock/store.js@@ -66,6 +66,14 @@ export async function publicDoorByHandle(handle) {d.open, d.price_atomics::text as price_atomics, d.headline, d.greeting,d.max_chars, d.daily_cap, d.listed,d.escrow_enabled, d.escrow_window_hours,+ -- The owner's Solana address, and ONLY when they turned the+ -- escrowed lane on. It is half of their on-chain door address,+ -- which a stranger has to derive before they can escrow+ -- anything. api/knock/door.js ships the derived address rather+ -- than this one, so a payout address still never appears in a+ -- public body; the account it points at is public because the+ -- owner opted into publishing it.+ case when d.escrow_enabled then d.pay_to_solana end as escrow_owner,d.pay_to_solana is not null as has_solana_payout,d.pay_to_base is not null as has_base_payoutfrom users u@@ -200,7 +208,8 @@ export async function listInbox(userId, { limit = 30, before = null, status = nureturn sql`select id, sender_name, sender_url, sender_kind, payer_wallet, network, tx_hash,amount_atomics::text as amount_atomics, asset, subject, message, status,- reply_text, read_at, replied_at, created_at+ reply_text, read_at, replied_at, created_at,+ escrow_knock, escrow_expires_at, escrow_statefrom knock_messageswhere recipient_user_id = ${userId}${statusClause}@@ -214,10 +223,20 @@ export async function inboxTotals(userId) {const [row] = await sql`select count(*) filter (where status = 'pending')::int as pending,count(*)::int as total,- coalesce(sum(amount_atomics), 0)::text as earned_atomics+ -- An escrowed knock is not earned until it is answered. Counting+ -- one that is still pending would show the owner money they+ -- cannot spend and might never be paid, and counting a refunded+ -- one would show them money that went back to the sender.+ coalesce(sum(amount_atomics) filter (+ where escrow_state is null or escrow_state = 'answered'+ ), 0)::text as earned_atomics,+ coalesce(sum(amount_atomics) filter (+ where escrow_state = 'pending'+ ), 0)::text as escrowed_atomics,+ count(*) filter (where escrow_state = 'pending')::int as escrowed_pendingfrom knock_messages where recipient_user_id = ${userId}`;- return row || { pending: 0, total: 0, earned_atomics: '0' };+ return row || { pending: 0, total: 0, earned_atomics: '0', escrowed_atomics: '0', escrowed_pending: 0 };}export async function updateKnock(userId, id, { status = null, reply = null }) {diff --git a/api/knock/door.js b/api/knock/door.jsindex 8942ea986..2cc2be93f 100644--- a/api/knock/door.js+++ b/api/knock/door.js@@ -12,7 +12,7 @@import { cors, json, method, wrap, error, rateLimited } from '../_lib/http.js';import { clientIp, limits } from '../_lib/rate-limit.js';import { env } from '../_lib/env.js';-import { KNOCK_ESCROW_PROGRAM_ID } from '../_lib/knock/escrow.js';+import { KNOCK_ESCROW_PROGRAM_ID, doorId, doorPda } from '../_lib/knock/escrow.js';import { formatUsdc, normalizeHandle } from '../_lib/knock/policy.js';import { publicDoorByHandle } from '../_lib/knock/store.js';@@ -77,11 +77,18 @@ export function publicShape(row) {* entire reason to pick this lane over paying up front.*/function escrowShape(row) {- if (!row.escrow_enabled) return null;+ if (!row.escrow_enabled || !row.escrow_owner) return null;return {endpoint: `${env.APP_ORIGIN}/api/knock/escrowed`,program: KNOCK_ESCROW_PROGRAM_ID,network: 'solana',+ // The door's on-chain address. A sender needs it to escrow, and reading+ // the account at it tells them the price, the mint and the window the+ // PROGRAM will enforce, which is the only version of those numbers that+ // can take their money. The owner's own address is not shipped here;+ // this is derived from it, and the account it names carries whatever+ // the owner chose to publish on-chain.+ door: doorPda(row.escrow_owner, doorId(row.username)).toBase58(),window_hours: Number(row.escrow_window_hours ?? 24),guarantee:'Your payment is held on-chain and pays out only if this door answers you. If it refuses, or the window closes, every unit comes back to you and anyone can trigger that refund.',diff --git a/api/knock/inbox/index.js b/api/knock/inbox/index.jsindex a5fc3e739..158f1b50a 100644--- a/api/knock/inbox/index.js+++ b/api/knock/inbox/index.js@@ -9,6 +9,7 @@ import { cors, json, method, wrap, error, rateLimited } from '../../_lib/http.jsimport { limits } from '../../_lib/rate-limit.js';import { formatUsdc, KNOCK_STATUSES } from '../../_lib/knock/policy.js';import { listInbox, inboxTotals } from '../../_lib/knock/store.js';+import { KNOCK_ESCROW_PROGRAM_ID } from '../../_lib/knock/escrow.js';export default wrap(async (req, res) => {if (cors(req, res, { methods: 'GET,OPTIONS', credentials: true })) return;@@ -33,14 +34,42 @@ export default wrap(async (req, res) => {inboxTotals(user.id),]);+ const now = Date.now();return json(res, 200, {- knocks: rows.map((row) => ({ ...row, amount: formatUsdc(row.amount_atomics) })),+ knocks: rows.map((row) => ({+ ...row,+ amount: formatUsdc(row.amount_atomics),+ // On an escrowed knock the money is parked on-chain and is owed back+ // unless this owner answers in time, so the row carries the deadline+ // and whether it has passed. Without it the inbox would show a knock+ // worth answering that is in fact already refundable.+ escrow: escrowShape(row, now),+ })),has_more: rows.length === limit,totals: {pending: totals.pending,total: totals.total,earned_atomics: totals.earned_atomics,earned: formatUsdc(totals.earned_atomics),+ // Escrowed but unanswered: real money at this door that is not the+ // owner's yet, and stops being reachable when the window closes.+ escrowed_atomics: totals.escrowed_atomics ?? '0',+ escrowed: formatUsdc(totals.escrowed_atomics ?? '0'),+ escrowed_pending: totals.escrowed_pending ?? 0,},});});++/** The on-chain half of one inbox row, or null on the two off-chain lanes. */+function escrowShape(row, now) {+ if (!row.escrow_knock) return null;+ const expiresAt = row.escrow_expires_at ? new Date(row.escrow_expires_at).getTime() : null;+ return {+ knock: row.escrow_knock,+ program: KNOCK_ESCROW_PROGRAM_ID,+ state: row.escrow_state || 'pending',+ expires_at: row.escrow_expires_at,+ expires_in_seconds: expiresAt === null ? null : Math.round((expiresAt - now) / 1000),+ expired: expiresAt !== null && expiresAt <= now,+ };+}diff --git a/api/knock/settings.js b/api/knock/settings.jsindex 78add8e58..48debcd12 100644--- a/api/knock/settings.js+++ b/api/knock/settings.js@@ -15,6 +15,7 @@ import { parse } from '../_lib/validate.js';import { env } from '../_lib/env.js';import { formatUsdc, parsePrice } from '../_lib/knock/policy.js';import { getDoor, updateDoor, inboxTotals, listBlocks, addBlock, removeBlock } from '../_lib/knock/store.js';+import { KNOCK_ESCROW_PROGRAM_ID, doorId, doorPda } from '../_lib/knock/escrow.js';import { sql } from '../_lib/db.js';const patchBody = z.object({@@ -126,12 +127,45 @@ async function ownerView(user) {// what the settings page tells them to do first.url: handle ? `${env.APP_ORIGIN}/knock/${handle}` : null,endpoint: handle ? `${env.APP_ORIGIN}/api/x402/knock?to=${handle}` : null,+ // Everything the owner needs to run the escrowed lane from their own+ // wallet. The door address is derived, not stored, so it is correct the+ // instant they set a Solana address and cannot drift from what a+ // stranger's client derives for the same handle.+ escrow: escrowView(door, handle),totals: {pending: totals.pending,total: totals.total,earned_atomics: totals.earned_atomics,earned: formatUsdc(totals.earned_atomics),+ escrowed_atomics: totals.escrowed_atomics ?? '0',+ escrowed: formatUsdc(totals.escrowed_atomics ?? '0'),+ escrowed_pending: totals.escrowed_pending ?? 0,},blocks,};}++/**+ * The owner's view of their on-chain door.+ *+ * `door` is the address they open, reprice and shut through their own wallet;+ * three.ws cannot do any of it for them, which is the point. It is null until+ * they set a Solana address, because the address is half of what derives it.+ *+ * The window band mirrors the program's own constants, so the settings UI can+ * refuse an out-of-range value before a wallet is ever opened.+ */+function escrowView(door, handle) {+ const owner = door.pay_to_solana || null;+ return {+ enabled: Boolean(door.escrow_enabled),+ window_hours: Number(door.escrow_window_hours ?? 24),+ min_window_hours: 1,+ max_window_hours: 720,+ program: KNOCK_ESCROW_PROGRAM_ID,+ network: 'solana',+ owner,+ door: owner && handle ? doorPda(owner, doorId(handle)).toBase58() : null,+ endpoint: handle ? `${env.APP_ORIGIN}/api/knock/escrowed` : null,+ };+}diff --git a/pages/knock-door.html b/pages/knock-door.htmlindex e8241e9c0..0bb1db5b1 100644--- a/pages/knock-door.html+++ b/pages/knock-door.html@@ -90,7 +90,35 @@.foot-note{color:var(--dim);font-size:12px;text-align:center;margin-top:26px;line-height:1.6;}.foot-note a{color:var(--muted);text-decoration:underline;text-underline-offset:2px;}.foot-note a:hover{color:var(--blue);}- @media(max-width:560px){.row{grid-template-columns:1fr;}.who{flex-wrap:wrap;}.price{margin-left:0;width:100%;text-align:left;}}+ .lanes{display:grid;grid-template-columns:1fr 1fr;gap:10px;margin-top:16px;}+ .lane{position:relative;display:grid;gap:3px;padding:12px 13px;border:1px solid var(--line-2);border-radius:11px;background:var(--bg-2);cursor:pointer;transition:border-color .15s,background .15s;font-weight:400;color:var(--text);}+ .lane:hover{border-color:var(--blue);}+ .lane:has(input:checked){border-color:var(--blue);background:rgba(59,130,246,.08);}+ .lane:has(input:focus-visible){outline:2px solid var(--blue);outline-offset:2px;}+ .lane input{position:absolute;opacity:0;pointer-events:none;}+ .lane-title{font-size:13.5px;font-weight:650;letter-spacing:-0.01em;}+ .lane-note{font-size:11.5px;color:var(--muted);line-height:1.45;}+ .lane-tag{font-size:10px;font-weight:700;text-transform:uppercase;letter-spacing:.06em;color:var(--green);}+ .guarantee{margin-top:12px;padding:11px 13px;border:1px solid rgba(34,197,94,.3);background:rgba(34,197,94,.07);border-radius:10px;font-size:12.5px;line-height:1.6;color:var(--muted);}+ .guarantee strong{color:var(--text);font-weight:650;}+ .escrow-status{margin-top:14px;padding-top:14px;border-top:1px solid var(--line);display:grid;gap:9px;}+ .escrow-row{display:flex;align-items:baseline;justify-content:space-between;gap:12px;font-size:13px;color:var(--muted);}+ .escrow-row strong{color:var(--text);font-variant-numeric:tabular-nums;font-weight:650;}+ .escrow-bar{height:5px;border-radius:999px;background:var(--bg-2);border:1px solid var(--line);overflow:hidden;}+ .escrow-bar span{display:block;height:100%;background:var(--green);width:100%;transition:width 1s linear;}+ .escrow-bar.is-late span{background:var(--amber);}+ .escrow-note{font-size:12px;color:var(--dim);line-height:1.55;}+ dialog.confirm{border:1px solid var(--line-2);background:var(--card);color:var(--text);border-radius:var(--radius);padding:0;max-width:420px;width:calc(100% - 32px);}+ dialog.confirm::backdrop{background:rgba(0,0,0,.6);}+ dialog.confirm form{padding:20px;display:grid;gap:14px;}+ dialog.confirm h2{font-size:16px;font-weight:700;}+ dialog.confirm dl{display:grid;grid-template-columns:auto 1fr;gap:7px 14px;font-size:13px;margin:0;}+ dialog.confirm dt{color:var(--muted);}+ dialog.confirm dd{margin:0;text-align:right;font-weight:600;word-break:break-all;}+ dialog.confirm dd.mono{font-family:ui-monospace,SFMono-Regular,Menlo,monospace;font-size:11px;font-weight:400;color:var(--muted);}+ .confirm-note{font-size:12px;color:var(--muted);line-height:1.6;border-top:1px solid var(--line);padding-top:12px;}+ .confirm-actions{display:flex;gap:8px;justify-content:flex-end;}+ @media(max-width:560px){.row{grid-template-columns:1fr;}.who{flex-wrap:wrap;}.price{margin-left:0;width:100%;text-align:left;}.lanes{grid-template-columns:1fr;}}@media(prefers-reduced-motion:reduce){.skeleton{animation:none;}}</style></head>@@ -126,6 +154,20 @@<p class="greeting" id="greeting" hidden></p><p class="price-note" id="price-note"></p>+ <div class="lanes" id="lanes" role="radiogroup" aria-label="How to pay" hidden>+ <label class="lane">+ <input type="radio" name="lane" value="pay" checked />+ <span class="lane-title">Pay now</span>+ <span class="lane-note" id="lane-pay-note"></span>+ </label>+ <label class="lane">+ <input type="radio" name="lane" value="escrow" />+ <span class="lane-title">Escrow <span class="lane-tag">refundable</span></span>+ <span class="lane-note" id="lane-escrow-note"></span>+ </label>+ </div>+ <p class="guarantee" id="guarantee" hidden></p>+<form id="form" novalidate><div class="row"><label>Who are you@@ -151,6 +193,18 @@<p id="sent-line"></p><code class="receipt" id="receipt-url" hidden></code><div class="reply-box" id="reply-box" hidden></div>++ <div class="escrow-status" id="escrow-status" hidden>+ <div class="escrow-row"><span>Held in escrow</span><strong id="escrow-amount"></strong></div>+ <div class="escrow-row"><span id="escrow-clock-label">Answer due in</span><strong id="escrow-clock"></strong></div>+ <div class="escrow-bar" id="escrow-bar"><span id="escrow-bar-fill"></span></div>+ <p class="escrow-note" id="escrow-note"></p>+ <div class="sent-actions">+ <a class="btn btn-sm" id="escrow-explorer" target="_blank" rel="noopener noreferrer">View the escrow</a>+ <button type="button" class="btn btn-sm" id="reclaim" hidden>Take my payment back</button>+ </div>+ </div>+<div class="sent-actions"><button type="button" class="btn btn-sm" id="copy-receipt" hidden>Copy receipt link</button><button type="button" class="btn btn-sm" id="check-reply" hidden>Check for a reply</button>@@ -176,6 +230,13 @@</div><pre id="curl-snippet"></pre></div>+ <div id="escrow-block" hidden>+ <div class="snip-head">+ <h3>Escrowed lane (refunded if unanswered)</h3>+ <button type="button" class="btn btn-sm" data-copy-target="escrow-snippet">Copy</button>+ </div>+ <pre id="escrow-snippet"></pre>+ </div><div><div class="snip-head"><h3>SDK</h3>@@ -199,6 +260,18 @@</p></main>+ <dialog class="confirm" id="confirm-escrow" aria-labelledby="confirm-title">+ <form method="dialog">+ <h2 id="confirm-title">Confirm what you are signing</h2>+ <dl id="confirm-terms"></dl>+ <p class="confirm-note" id="confirm-note"></p>+ <div class="confirm-actions">+ <button class="btn" value="cancel">Cancel</button>+ <button class="btn btn-primary" value="ok" id="confirm-ok">Escrow and knock</button>+ </div>+ </form>+ </dialog>+<div id="footer-container"></div><script src="/footer.js"></script><script type="module" src="/x402.js"></script>diff --git a/pages/knock.html b/pages/knock.htmlindex e85a718a5..4c230c416 100644--- a/pages/knock.html+++ b/pages/knock.html@@ -117,7 +117,18 @@.how div{background:var(--card);border:1px solid var(--line);border-radius:var(--radius);padding:16px;}.how b{display:block;font-size:13.5px;margin-bottom:5px;}.how p{color:var(--muted);font-size:12.5px;line-height:1.6;}- @media(max-width:700px){.fields{grid-template-columns:1fr;}.stats{grid-template-columns:1fr;}.hero h1{font-size:26px;}}+ .escrow-panel{margin-top:18px;padding:16px;border:1px solid var(--line-2);border-radius:12px;background:var(--bg-2);display:grid;gap:12px;}+ .escrow-head{display:flex;align-items:flex-start;justify-content:space-between;gap:14px;flex-wrap:wrap;}+ .escrow-head h3{font-size:14px;font-weight:700;letter-spacing:-0.01em;}+ .escrow-head p{font-size:12.5px;color:var(--muted);line-height:1.6;margin-top:4px;max-width:52ch;}+ .escrow-grid{display:grid;grid-template-columns:1fr 1fr;gap:14px;}+ .chain-state{display:flex;align-items:center;gap:9px;font-size:12.5px;color:var(--muted);padding:11px 13px;border:1px solid var(--line);border-radius:10px;background:var(--card);line-height:1.55;}+ .dot{width:8px;height:8px;border-radius:50%;background:var(--dim);flex-shrink:0;}+ .dot.is-live{background:var(--green);}+ .dot.is-warn{background:var(--amber);}+ .chain-actions{display:flex;gap:8px;flex-wrap:wrap;}+ .escrow-address{font-family:ui-monospace,SFMono-Regular,Menlo,monospace;font-size:11px;color:var(--dim);word-break:break-all;}+ @media(max-width:700px){.fields{grid-template-columns:1fr;}.stats{grid-template-columns:1fr;}.hero h1{font-size:26px;}.escrow-grid{grid-template-columns:1fr;}}@media(prefers-reduced-motion:reduce){.skeleton{animation:none;}.door-card:hover{transform:none;}}</style></head>@@ -170,6 +181,7 @@<div class="stat"><b id="stat-pending">0</b><span>Waiting</span></div><div class="stat"><b id="stat-total">0</b><span>All time</span></div><div class="stat"><b id="stat-earned">$0.00</b><span>Earned</span></div>+ <div class="stat" id="stat-escrowed-card" hidden><b id="stat-escrowed">$0.00</b><span>In escrow</span></div></div><div class="fields">@@ -205,6 +217,31 @@</label></div>+ <div class="escrow-panel" id="escrow-panel">+ <div class="escrow-head">+ <div>+ <h3>Escrowed knocks</h3>+ <p id="escrow-pitch">Let a stranger pay into an on-chain vault instead of paying you directly. You are paid by answering; if you decline, or the window closes, every unit goes back to them. Nobody can move it, including us.</p>+ </div>+ <label class="toggle"><input type="checkbox" id="escrow-enabled" /> Take escrowed knocks</label>+ </div>+ <div class="escrow-grid" id="escrow-fields" hidden>+ <label>Answer within+ <input type="number" id="escrow-window" min="1" max="720" />+ <span class="hint">Hours. After this the sender can take their payment back, and anybody can trigger it for them.</span>+ </label>+ <div class="chain-state" id="chain-state">+ <span class="dot" id="chain-dot"></span>+ <span id="chain-text">Checking your on-chain door</span>+ </div>+ </div>+ <div class="chain-actions" id="chain-actions" hidden>+ <button type="button" class="btn btn-sm btn-primary" id="open-chain-door">Open my door on-chain</button>+ <a class="btn btn-sm" id="chain-explorer" target="_blank" rel="noopener noreferrer" hidden>View it</a>+ </div>+ <code class="escrow-address" id="escrow-address" hidden></code>+ </div>+<div class="error" id="settings-error" hidden></div><div class="save-row">diff --git a/src/knock/api.js b/src/knock/api.jsindex 8d22d38d3..77a8b6d2e 100644--- a/src/knock/api.js+++ b/src/knock/api.js@@ -59,7 +59,14 @@ export const knockApi = {door: (handle) => open(`/api/knock/door?handle=${encodeURIComponent(handle)}`),directory: (limit = 60) => open(`/api/knock/directory?limit=${limit}`),send: (body) => open('/api/knock/send', { method: 'POST', body }),+ // The escrowed lane. Called only AFTER the sender's own wallet has parked+ // the payment on-chain: this endpoint reads that escrow and delivers, it+ // never takes money, so calling it without one simply answers 402.+ escrowed: (body) => open('/api/knock/escrowed', { method: 'POST', body }),receipt: (url) => open(url.replace(/^https?:\/\/[^/]+/, '')),+ // Copy one escrow's on-chain state into the row that caches it. Open to+ // anybody because it can only ever write what the program already recorded.+ syncEscrow: (knock) => open('/api/knock/escrow-sync', { method: 'POST', body: { knock } }),// Ownersettings: () => authed('/api/knock/settings', { allowAnonymous: true }),diff --git a/src/knock/door.js b/src/knock/door.jsindex ec400ee8c..2d5a33039 100644--- a/src/knock/door.js+++ b/src/knock/door.js@@ -18,6 +18,10 @@ import { knockApi } from './api.js';const els = {};let door = null;let lastReceiptUrl = null;+// The escrow this visitor just paid, while the page is still open: what the+// countdown counts down to, and what the refund button acts on.+let escrow = null;+let clockTimer = null;document.addEventListener('DOMContentLoaded', () => {for (const id of [@@ -26,6 +30,11 @@ document.addEventListener('DOMContentLoaded', () => {'message', 'url', 'counter', 'submit', 'form-error', 'sent', 'sent-line', 'receipt-url','copy-receipt', 'check-reply', 'reply-box', 'knock-again', 'agent-panel', 'agent-endpoint','curl-snippet', 'sdk-snippet', 'mcp-snippet', 'copy-endpoint',+ 'lanes', 'lane-pay-note', 'lane-escrow-note', 'guarantee',+ 'escrow-status', 'escrow-amount', 'escrow-clock', 'escrow-clock-label', 'escrow-bar',+ 'escrow-bar-fill', 'escrow-note', 'escrow-explorer', 'reclaim',+ 'confirm-escrow', 'confirm-terms', 'confirm-note', 'confirm-ok',+ 'escrow-block', 'escrow-snippet',]) {els[id] = document.getElementById(id);}@@ -97,11 +106,57 @@ function render() {els.message.maxLength = door.max_chars;updateCounter();- els.submit.textContent = door.free ? 'Knock' : `Pay ${door.price} and knock`;+ renderLanes();+ updateSubmitLabel();renderAgentPanel();}+/**+ * The lane picker, shown only when this door takes escrow.+ *+ * A door with one lane does not get a chooser: a single option presented as a+ * choice is noise. When there are two, the difference between them is the only+ * thing worth saying, so each option says what happens to the money rather+ * than naming a protocol.+ */+function renderLanes() {+ if (!door.escrow || door.free) {+ els.lanes.hidden = true;+ els.guarantee.hidden = true;+ return;+ }+ els.lanes.hidden = false;+ els['lane-pay-note'].textContent = `${door.price} goes straight to ${door.display_name} when you send.`;+ els['lane-escrow-note'].textContent = `${door.price} is held on-chain and only pays out if they answer.`;+ els.guarantee.hidden = false;+ const strong = document.createElement('strong');+ strong.textContent = `They have ${windowLabel(door.escrow.window_hours)} to answer. `;+ els.guarantee.replaceChildren(strong, document.createTextNode(door.escrow.guarantee));+}++function windowLabel(hours) {+ const n = Number(hours) || 24;+ if (n < 24) return `${n} hour${n === 1 ? '' : 's'}`;+ const days = Math.round(n / 24);+ return `${days} day${days === 1 ? '' : 's'}`;+}++function selectedLane() {+ if (door?.free || !door?.escrow) return door?.free ? 'free' : 'pay';+ const picked = document.querySelector('input[name="lane"]:checked');+ return picked?.value === 'escrow' ? 'escrow' : 'pay';+}++function updateSubmitLabel() {+ if (door.free) {+ els.submit.textContent = 'Knock';+ return;+ }+ els.submit.textContent =+ selectedLane() === 'escrow' ? `Escrow ${door.price} and knock` : `Pay ${door.price} and knock`;+}+function renderAgentPanel() {const endpoint = door.endpoint;els['agent-endpoint'].textContent = endpoint;@@ -131,6 +186,27 @@ function renderAgentPanel() {'console.log(receipt.receipt_url); // poll this for a reply',].join('\n');+ // The escrowed lane, for a caller who can sign Solana. Written out rather+ // than hidden behind an SDK call, because the one step that cannot be+ // delegated is the one the agent has to get exactly right: the message hash+ // on-chain must be the SHA-256 of the trimmed body sent here, or this+ // endpoint refuses to deliver a message the escrow did not pay for.+ els['escrow-block'].hidden = !door.escrow;+ if (door.escrow) {+ els['escrow-snippet'].textContent = [+ `# 1. Sign \`knock\` on ${door.escrow.program}`,+ `# door: ${door.escrow.door}`,+ '# args: nonce (u64), message_hash (sha256 of the trimmed message)',+ `# the program takes this door's on-chain price and holds it in a vault`,+ `# that pays out only if @${door.handle} answers within ${windowLabel(door.escrow.window_hours)}.`,+ '',+ '# 2. Deliver the message against that escrow.',+ `curl -X POST ${door.escrow.endpoint} \\`,+ " -H 'content-type: application/json' \\",+ ` -d '${JSON.stringify({ to: door.handle, ...example, sender_wallet: '<your pubkey>', nonce: '<the nonce you signed>' })}'`,+ ].join('\n');+ }+els['mcp-snippet'].textContent = ['{',' "mcpServers": {',@@ -154,6 +230,8 @@ function bind() {els.message?.addEventListener('input', updateCounter);els.form?.addEventListener('submit', onSubmit);els['knock-again']?.addEventListener('click', () => {+ stopClock();+ els['escrow-status'].hidden = true;els.sent.hidden = true;els.form.hidden = false;els.message.value = '';@@ -162,6 +240,10 @@ function bind() {els.from.focus();});els['check-reply']?.addEventListener('click', checkReply);+ els.reclaim?.addEventListener('click', onReclaim);+ for (const radio of document.querySelectorAll('input[name="lane"]')) {+ radio.addEventListener('change', updateSubmitLabel);+ }for (const btn of document.querySelectorAll('[data-copy-target], [data-copy]')) {btn.addEventListener('click', () => copy(btn));}@@ -210,14 +292,18 @@ async function onSubmit(e) {if (body.message.length < 8) return setError('Say at least 8 characters.');if (!body.from) return setError('Tell them who you are.');+ const lane = selectedLane();els.submit.disabled = true;const label = els.submit.textContent;els.submit.textContent = door.free ? 'Knocking…' : 'Opening wallet…';try {- const result = door.free- ? await knockApi.send({ to: door.handle, ...body })- : await payAndKnock(body);+ const result =+ lane === 'free'+ ? await knockApi.send({ to: door.handle, ...body })+ : lane === 'escrow'+ ? await escrowAndKnock(body, (status) => { els.submit.textContent = `${status}…`; })+ : await payAndKnock(body);showSent(result);} catch (err) {setError(friendlyError(err));@@ -245,6 +331,177 @@ async function payAndKnock(body) {return result;}+/**+ * The escrowed lane, end to end.+ *+ * Two steps, in this order and never the other way round. The visitor's own+ * wallet parks the payment on-chain first, and only then does the API get+ * asked to deliver the message, because the API's entire job on this lane is to+ * refuse anything the chain does not already back. If the delivery call fails+ * after the escrow is paid, the money is not lost and this says so: it is sitting+ * in a vault that pays nobody but the sender once the window closes.+ */+async function escrowAndKnock(body, onStatus) {+ const { escrowKnock, EscrowError } = await import('./escrow-checkout.js');+ const paid = await escrowKnock({+ doorAddress: door.escrow.door,+ message: body.message,+ onStatus,+ confirm: confirmEscrow,+ });++ onStatus('Delivering');+ try {+ const result = await knockApi.escrowed({+ to: door.handle,+ ...body,+ sender_wallet: paid.sender,+ nonce: String(paid.nonce),+ });+ return { ...result, paid };+ } catch (err) {+ // The escrow exists whatever happened here, so the visitor is told what+ // they are holding and how to get it back rather than just that+ // something failed.+ const reason = err instanceof EscrowError ? err.message : friendlyError(err);+ throw Object.assign(+ new Error(+ `Your ${paid.amount} is escrowed and safe, but the message did not go through: ${reason} Nobody can spend it, and you can take it back after the window closes.`,+ ),+ { code: 'delivery_failed', escrow: paid },+ );+ }+}++/**+ * The spend confirmation. Nothing is signed until this resolves true.+ *+ * It states the amount, who it goes to and the deadline in the same words the+ * page used to sell the lane, because a confirmation that says something+ * different from the pitch is how people end up agreeing to what they did not+ * read.+ */+function confirmEscrow(terms) {+ const dialog = els['confirm-escrow'];+ if (typeof dialog?.showModal !== 'function') {+ // No dialog support: fall back to the browser's own confirm rather than+ // silently signing. Spending money always asks.+ return Promise.resolve(+ window.confirm(+ `Escrow ${terms.amount} to knock on ${door.display_name}? It pays out only if they answer within ${windowLabel(door.escrow.window_hours)}, and comes back to you otherwise.`,+ ),+ );+ }++ const rows = [+ ['You escrow', terms.amount, false],+ ['Goes to', `${door.display_name} (@${door.handle})`, false],+ ['Only if they answer by', new Date(terms.expiresAt * 1000).toLocaleString(), false],+ ['Held at', terms.knock, true],+ ];+ els['confirm-terms'].replaceChildren(+ ...rows.flatMap(([label, value, mono]) => {+ const dt = document.createElement('dt');+ dt.textContent = label;+ const dd = document.createElement('dd');+ dd.textContent = value;+ if (mono) dd.className = 'mono';+ return [dt, dd];+ }),+ );+ els['confirm-note'].textContent =+ 'Your wallet signs this, not three.ws. Once it is escrowed nobody can spend it except by answering you, and if the deadline passes anyone can send it back to you.';+ els['confirm-ok'].textContent = `Escrow ${terms.amount}`;++ return new Promise((resolve) => {+ dialog.addEventListener('close', () => resolve(dialog.returnValue === 'ok'), { once: true });+ dialog.showModal();+ });+}++/** The live state of the escrow this visitor is holding open on the page. */+function showEscrow(paid, escrowState) {+ // The API returns the deadline the CHAIN recorded, in unix seconds. Prefer+ // it over the one derived locally before signing: the program stamps+ // expires_at from the cluster's clock, not this browser's.+ escrow = {+ knock: escrowState?.knock || paid.knock,+ amount: paid.amount,+ createdAt: Math.floor(Date.now() / 1000),+ expiresAt: Number(escrowState?.expires_at) || paid.expiresAt,+ };+ els['escrow-status'].hidden = false;+ els['escrow-amount'].textContent = `${escrow.amount} USDC`;+ els['escrow-explorer'].href = `https://solscan.io/account/${escrow.knock}`;+ els['escrow-note'].textContent =+ `Nobody can spend this but ${door.display_name}, and only by answering you.`;+ tickClock();+ stopClock();+ clockTimer = window.setInterval(tickClock, 1000);+}++function stopClock() {+ if (clockTimer) window.clearInterval(clockTimer);+ clockTimer = null;+}++function tickClock() {+ if (!escrow) return;+ const now = Math.floor(Date.now() / 1000);+ const left = escrow.expiresAt - now;+ const total = Math.max(1, escrow.expiresAt - escrow.createdAt);++ if (left > 0) {+ els['escrow-clock-label'].textContent = 'Answer due in';+ els['escrow-clock'].textContent = countdown(left);+ els['escrow-bar-fill'].style.width = `${Math.max(0, Math.min(100, (left / total) * 100))}%`;+ els['escrow-bar'].classList.toggle('is-late', left < total * 0.25);+ els.reclaim.hidden = true;+ return;+ }++ els['escrow-clock-label'].textContent = 'Window closed';+ els['escrow-clock'].textContent = 'Refundable now';+ els['escrow-bar-fill'].style.width = '0%';+ els['escrow-bar'].classList.add('is-late');+ els['escrow-note'].textContent =+ `${door.display_name} did not answer in time, so this is yours again. Anyone can send it back to you; the button below does it from this wallet.`;+ els.reclaim.hidden = false;+ stopClock();+}++function countdown(seconds) {+ const d = Math.floor(seconds / 86400);+ const h = Math.floor((seconds % 86400) / 3600);+ const m = Math.floor((seconds % 3600) / 60);+ const s = seconds % 60;+ if (d) return `${d}d ${h}h`;+ if (h) return `${h}h ${String(m).padStart(2, '0')}m`;+ return `${m}m ${String(s).padStart(2, '0')}s`;+}++async function onReclaim() {+ if (!escrow) return;+ els.reclaim.disabled = true;+ const label = els.reclaim.textContent;+ els.reclaim.textContent = 'Opening wallet…';+ try {+ const { reclaimKnock } = await import('./escrow-checkout.js');+ await reclaimKnock({+ knockAddress: escrow.knock,+ onStatus: (status) => { els.reclaim.textContent = `${status}…`; },+ });+ els['escrow-clock-label'].textContent = 'Refunded';+ els['escrow-clock'].textContent = escrow.amount;+ els['escrow-note'].textContent = 'Every unit went back to your wallet, and the escrow is closed.';+ els.reclaim.hidden = true;+ } catch (err) {+ els['escrow-note'].textContent = err?.message || 'That refund did not go through. Try again shortly.';+ els.reclaim.disabled = false;+ els.reclaim.textContent = label;+ }+}+function friendlyError(err) {const map = {door_closed: 'This door just closed.',@@ -253,6 +510,15 @@ function friendlyError(err) {message_too_short: 'Say at least 8 characters.',bad_url: 'That link needs to be a plain http(s) URL.',payment_required: 'This door charges now. Reload the page to see the price.',+ // Escrowed lane. Each of these is the chain disagreeing with the+ // request, so each says what the sender still holds and what to do.+ knock_not_found: 'The escrow has not landed yet. Give it a few seconds and knock again.',+ escrow_not_enabled: 'This door stopped taking escrowed knocks. Reload the page to pay the normal way.',+ message_mismatch: 'That escrow was paid against a different message. Escrow again for this one.',+ already_settled: 'That escrow was already settled and cannot buy a second message.',+ window_closed: 'That escrow expired. Take it back below and knock again.',+ underpaid: 'This door raised its price after the escrow was paid. Take it back below and knock again.',+ no_payout_wallet: 'This door has no Solana address, so it has no on-chain door to knock at.',};if (err.status === 429) return 'Too many knocks from here for now. Try again a bit later.';return map[err.code] || err.message || 'That did not go through.';@@ -266,7 +532,8 @@ function setError(message) {function showSent(result) {els.form.hidden = true;els.sent.hidden = false;- lastReceiptUrl = result.receipt_url || null;+ lastReceiptUrl = result.receipt_url || result.receipt || null;+ if (result.paid) showEscrow(result.paid, result.escrow);els['sent-line'].textContent = result.duplicate? `Already delivered. ${door.display_name} has this one.`: `Delivered. ${door.display_name}'s companion will walk on and say who you are.`;diff --git a/src/knock/escrow-checkout.js b/src/knock/escrow-checkout.jsnew file mode 100644index 000000000..f528d0b65--- /dev/null+++ b/src/knock/escrow-checkout.js@@ -0,0 +1,439 @@+// The escrowed knock, from the visitor's side of the glass.+//+// A door with the escrowed lane on takes payment the same way every other door+// does, and then does something none of them do: it cannot spend the money+// until it answers. This module is what makes that true in a browser. The+// sender's own wallet signs the escrow, and the same wallet (or anybody else's)+// signs the refund if the answer never comes. Nothing here asks a server for+// permission, because a server that could grant it could also refuse it.+//+// The chain is read for every number shown. The off-chain door row says what+// the owner intends to charge; the on-chain Door account says what the program+// will actually take, and only the second one can move a stranger's USDC. Where+// they disagree, this shows the on-chain number, because that is the one being+// agreed to.+//+// Instruction encoding lives in ./escrow-program.js and is pinned against the+// compiled program. This file is the flow around it: wallet, RPC, the checks+// worth making before a wallet ever opens, and errors a person can act on.++import {+ KNOCK_STATE_NAME,+ answerIx,+ ataFor,+ configPda,+ createAtaIfMissingIx,+ decodeConfig,+ decodeDoor,+ decodeKnock,+ doorPda,+ doorId,+ hex,+ knockIx,+ knockPda,+ openDoorIx,+ reclaimIx,+ refuseIx,+ setDoorIx,+ sha256,+ tokenProgramForOwner,+} from './escrow-program.js';++/** A refusal a person can act on, rather than a chain error nobody can read. */+export class EscrowError extends Error {+ constructor(code, message) {+ super(message);+ this.name = 'EscrowError';+ this.code = code;+ }+}++let _web3 = null;+async function web3() {+ if (!_web3) _web3 = await import('@solana/web3.js');+ return _web3;+}++function rpcEndpoint() {+ return (+ (typeof window !== 'undefined' && window.__solanaRpc) ||+ `${window.location.origin}/api/solana-rpc`+ );+}++export async function connection() {+ const { Connection } = await web3();+ return new Connection(rpcEndpoint(), 'confirmed');+}++/** The connected wallet, connecting it first if the visitor has not yet. */+export async function wallet() {+ const provider = typeof window !== 'undefined' ? window.solana : null;+ if (!provider) {+ throw new EscrowError('no_wallet', 'No Solana wallet in this browser. Install Phantom, or use an agent client.');+ }+ if (!provider.isConnected) {+ if (typeof provider.connect !== 'function') {+ throw new EscrowError('not_connected', 'Connect your wallet and try again.');+ }+ await provider.connect();+ }+ if (!provider.publicKey) throw new EscrowError('not_connected', 'Connect your wallet and try again.');+ return provider;+}++/**+ * Read a door's on-chain half.+ *+ * Returns null when the owner has turned the lane on but never opened the door+ * on-chain, which is a real and recoverable state: the page says so rather than+ * offering a lane that would fail in the wallet.+ */+export async function readDoor(conn, doorAddress) {+ const { PublicKey } = await web3();+ const info = await conn.getAccountInfo(new PublicKey(doorAddress));+ if (!info) return null;+ const door = decodeDoor(info.data);+ const mintInfo = await conn.getAccountInfo(new PublicKey(door.mint));+ if (!mintInfo) throw new EscrowError('bad_mint', 'This door is priced in a token that no longer exists.');+ return {+ ...door,+ address: String(doorAddress),+ tokenProgram: tokenProgramForOwner(mintInfo.owner.toBase58()),+ // Mint layout puts decimals at byte 44 in both Token and Token-2022.+ decimals: mintInfo.data[44],+ };+}++/** Human amount from atomic units, without floating point in the middle. */+export function formatAmount(atomics, decimals) {+ const negative = BigInt(atomics) < 0n;+ const value = negative ? -BigInt(atomics) : BigInt(atomics);+ const base = 10n ** BigInt(decimals);+ const whole = value / base;+ const fraction = (value % base).toString().padStart(decimals, '0').replace(/0+$/, '');+ return `${negative ? '-' : ''}${whole}${fraction ? `.${fraction}` : ''}`;+}++/**+ * Escrow a door's price and return the knock the API needs to see.+ *+ * `confirm` is handed the exact terms being signed (amount, token, door,+ * deadline) and must resolve truthy for the wallet to open. Nothing is signed+ * before it does, because this spends real money on a promise from a stranger.+ */+export async function escrowKnock({ doorAddress, message, onStatus = () => {}, confirm }) {+ const { Transaction } = await web3();+ const conn = await connection();++ onStatus('Reading this door on-chain');+ const door = await readDoor(conn, doorAddress);+ if (!door) {+ throw new EscrowError(+ 'door_not_open',+ 'This person has turned on the escrowed lane but has not opened their door on-chain yet. Use the normal lane, or come back shortly.',+ );+ }+ if (!door.open) throw new EscrowError('door_closed', 'This door is shut on-chain and is not taking knocks.');++ const provider = await wallet();+ const sender = provider.publicKey.toBase58();+ const senderTokens = ataFor(door.mint, sender, door.tokenProgram);++ onStatus('Checking your balance');+ const balance = await tokenBalance(conn, senderTokens);+ if (balance === null) {+ throw new EscrowError(+ 'no_token_account',+ 'This wallet holds none of the token this door is priced in. Fund it and try again.',+ );+ }+ if (balance < door.price) {+ throw new EscrowError(+ 'insufficient_funds',+ `This door costs ${formatAmount(door.price, door.decimals)} and this wallet holds ${formatAmount(balance, door.decimals)}.`,+ );+ }++ const messageHash = sha256(String(message).trim());+ const nonce = await freeNonce(conn, door.address, sender);+ const knock = knockPda(door.address, sender, nonce);+ const expiresAt = Math.floor(Date.now() / 1000) + door.replyWindow;++ const agreed = await confirm({+ amount: formatAmount(door.price, door.decimals),+ amountAtomics: door.price.toString(),+ mint: door.mint,+ decimals: door.decimals,+ door: door.address,+ owner: door.owner,+ knock: knock.toBase58(),+ nonce,+ replyWindowSeconds: door.replyWindow,+ expiresAt,+ });+ if (!agreed) throw new EscrowError('cancelled', 'Nothing was signed and nothing was spent.');++ onStatus('Waiting for your wallet');+ const tx = new Transaction().add(+ knockIx({+ sender,+ door: door.address,+ mint: door.mint,+ senderTokens,+ nonce,+ messageHash,+ tokenProgram: door.tokenProgram,+ }),+ );+ const signature = await sendTx(conn, provider, tx, sender);++ onStatus('Escrow confirmed');+ return {+ signature,+ nonce,+ knock: knock.toBase58(),+ sender,+ amountAtomics: door.price.toString(),+ amount: formatAmount(door.price, door.decimals),+ mint: door.mint,+ decimals: door.decimals,+ expiresAt,+ messageHash: hex(messageHash),+ };+}++/**+ * Crank an expired knock's refund.+ *+ * Anyone can send this, including the sender themselves, and every token and+ * lamport in it goes to the sender's own accounts. It is offered on the page+ * because a guarantee nobody can act on is not a guarantee.+ */+export async function reclaimKnock({ knockAddress, onStatus = () => {} }) {+ const { PublicKey, Transaction } = await web3();+ const conn = await connection();++ onStatus('Reading the escrow');+ const info = await conn.getAccountInfo(new PublicKey(knockAddress));+ if (!info) throw new EscrowError('already_settled', 'This escrow is already closed. Nothing is being held.');+ const record = decodeKnock(info.data);+ if (record.state !== 0) {+ throw new EscrowError('already_settled', `This escrow was already ${KNOCK_STATE_NAME[record.state]}.`);+ }+ if (Math.floor(Date.now() / 1000) <= record.expiresAt) {+ throw new EscrowError(+ 'not_expired',+ 'The reply window is still open. The refund can be taken the moment it closes.',+ );+ }++ const provider = await wallet();+ const mintInfo = await conn.getAccountInfo(new PublicKey(record.mint));+ const tokenProgram = tokenProgramForOwner(mintInfo.owner.toBase58());++ onStatus('Waiting for your wallet');+ const tx = new Transaction().add(+ reclaimIx({+ cranker: provider.publicKey.toBase58(),+ door: record.door,+ knock: knockAddress,+ mint: record.mint,+ sender: record.sender,+ senderTokens: ataFor(record.mint, record.sender, tokenProgram),+ tokenProgram,+ }),+ );+ const signature = await sendTx(conn, provider, tx, provider.publicKey.toBase58());+ onStatus('Refunded');+ return { signature, amountAtomics: record.amount.toString(), sender: record.sender };+}++/**+ * Answer an escrowed knock and take the payment. Owner-signed.+ *+ * The reply text is hashed, not stored on-chain: the reply itself belongs to+ * the two people, and what the chain needs is only proof that an answer of+ * exactly this content was what released the money.+ */+export async function answerKnock({ knockAddress, reply, onStatus = () => {} }) {+ const { PublicKey, Transaction } = await web3();+ const conn = await connection();++ onStatus('Reading the escrow');+ const info = await conn.getAccountInfo(new PublicKey(knockAddress));+ if (!info) throw new EscrowError('already_settled', 'This escrow is already closed.');+ const record = decodeKnock(info.data);+ if (record.state !== 0) {+ throw new EscrowError('already_settled', `This escrow was already ${KNOCK_STATE_NAME[record.state]}.`);+ }+ if (Math.floor(Date.now() / 1000) > record.expiresAt) {+ throw new EscrowError(+ 'window_closed',+ 'The reply window closed, so this payment is owed back to the sender. Your reply still sends; the money does not.',+ );+ }++ const provider = await wallet();+ const owner = provider.publicKey.toBase58();+ const { tokenProgram, treasury } = await settlementContext(conn, record.mint);++ onStatus('Waiting for your wallet');+ const tx = new Transaction()+ .add(createAtaIfMissingIx({ payer: owner, owner, mint: record.mint, tokenProgram }))+ .add(createAtaIfMissingIx({ payer: owner, owner: treasury, mint: record.mint, tokenProgram }))+ .add(+ answerIx({+ owner,+ door: record.door,+ knock: knockAddress,+ mint: record.mint,+ sender: record.sender,+ ownerTokens: ataFor(record.mint, owner, tokenProgram),+ treasuryTokens: ataFor(record.mint, treasury, tokenProgram),+ replyHash: sha256(String(reply).trim()),+ tokenProgram,+ }),+ );+ const signature = await sendTx(conn, provider, tx, owner);+ onStatus('Paid out');+ return { signature, amountAtomics: record.amount.toString(), feeBps: record.feeBps };+}++/**+ * Decline an escrowed knock and hand it all back. Owner-signed, and no fee is+ * taken, because refusing to engage is not a service anybody should pay for.+ */+export async function refuseKnock({ knockAddress, onStatus = () => {} }) {+ const { PublicKey, Transaction } = await web3();+ const conn = await connection();++ const info = await conn.getAccountInfo(new PublicKey(knockAddress));+ if (!info) throw new EscrowError('already_settled', 'This escrow is already closed.');+ const record = decodeKnock(info.data);+ if (record.state !== 0) {+ throw new EscrowError('already_settled', `This escrow was already ${KNOCK_STATE_NAME[record.state]}.`);+ }++ const provider = await wallet();+ const mintInfo = await conn.getAccountInfo(new PublicKey(record.mint));+ const tokenProgram = tokenProgramForOwner(mintInfo.owner.toBase58());++ onStatus('Waiting for your wallet');+ const tx = new Transaction().add(+ refuseIx({+ owner: provider.publicKey.toBase58(),+ door: record.door,+ knock: knockAddress,+ mint: record.mint,+ sender: record.sender,+ senderTokens: ataFor(record.mint, record.sender, tokenProgram),+ tokenProgram,+ }),+ );+ const signature = await sendTx(conn, provider, tx, provider.publicKey.toBase58());+ onStatus('Refunded in full');+ return { signature, amountAtomics: record.amount.toString() };+}++/**+ * Open, reprice or shut the owner's own on-chain door.+ *+ * `handle` is hashed into the door id, so the address a stranger derives from+ * the same handle is the one this opens. There is no server step: the owner's+ * wallet is the only thing that can create this account.+ */+export async function openDoorOnChain({ handle, priceAtomics, replyWindowSeconds, mint, onStatus = () => {} }) {+ const { Transaction } = await web3();+ const conn = await connection();+ const provider = await wallet();+ const owner = provider.publicKey.toBase58();++ const address = doorPda(owner, doorId(handle));+ const existing = await readDoor(conn, address);++ onStatus('Waiting for your wallet');+ const tx = new Transaction().add(+ existing+ ? setDoorIx({ owner, handle, priceAtomics, replyWindowSeconds, open: true })+ : openDoorIx({ owner, mint, priceAtomics, replyWindowSeconds, handle }),+ );+ const signature = await sendTx(conn, provider, tx, owner);+ onStatus(existing ? 'Door updated on-chain' : 'Door opened on-chain');+ return { signature, door: address.toBase58(), created: !existing };+}++// ── plumbing ────────────────────────────────────────────────────────────────++/** Sign, send and confirm one transaction through the connected wallet. */+async function sendTx(conn, provider, tx, feePayer) {+ const { PublicKey } = await web3();+ const { blockhash, lastValidBlockHeight } = await conn.getLatestBlockhash('confirmed');+ tx.feePayer = new PublicKey(feePayer);+ tx.recentBlockhash = blockhash;++ let signature;+ try {+ if (typeof provider.signAndSendTransaction === 'function') {+ ({ signature } = await provider.signAndSendTransaction(tx));+ } else {+ const signed = await provider.signTransaction(tx);+ signature = await conn.sendRawTransaction(signed.serialize(), { maxRetries: 3 });+ }+ } catch (err) {+ // A wallet rejection is a decision, not a failure, and should not be+ // dressed up as one.+ if (/reject|denied|cancell?ed/i.test(err?.message || '')) {+ throw new EscrowError('cancelled', 'Nothing was signed and nothing was spent.');+ }+ throw err;+ }++ const result = await conn.confirmTransaction({ signature, blockhash, lastValidBlockHeight }, 'confirmed');+ if (result?.value?.err) {+ throw new EscrowError('tx_failed', 'The transaction did not go through. Nothing was taken from your wallet.');+ }+ return signature;+}++/** A token account's balance, or null when the account does not exist. */+async function tokenBalance(conn, address) {+ const { PublicKey } = await web3();+ const info = await conn.getAccountInfo(new PublicKey(address));+ if (!info) return null;+ // SPL token accounts hold the amount as a u64 at byte 64 in both programs.+ return new DataView(info.data.buffer, info.data.byteOffset, info.data.byteLength).getBigUint64(64, true);+}++/**+ * A nonce with no knock account at it yet.+ *+ * Seconds since the epoch is unique per sender and door in every realistic+ * case; the loop covers the one that is not, two knocks inside one second,+ * because colliding would fail in the wallet with an error about an account+ * already in use.+ */+async function freeNonce(conn, door, sender) {+ const { PublicKey } = await web3();+ let nonce = Math.floor(Date.now() / 1000);+ for (let attempt = 0; attempt < 8; attempt += 1) {+ const info = await conn.getAccountInfo(new PublicKey(knockPda(door, sender, nonce)));+ if (!info) return nonce;+ nonce += 1;+ }+ throw new EscrowError('nonce_exhausted', 'Too many knocks from this wallet at once. Try again in a moment.');+}++/** The token program and the protocol treasury an answer has to pay. */+async function settlementContext(conn, mint) {+ const { PublicKey } = await web3();+ const [mintInfo, configInfo] = await Promise.all([+ conn.getAccountInfo(new PublicKey(mint)),+ conn.getAccountInfo(configPda()),+ ]);+ if (!configInfo) throw new EscrowError('not_initialized', 'The escrow program is not initialized on this cluster.');+ return {+ tokenProgram: tokenProgramForOwner(mintInfo.owner.toBase58()),+ treasury: decodeConfig(configInfo.data).treasury,+ };+}diff --git a/src/knock/page.js b/src/knock/page.jsindex 8a78f7a2a..90faccc64 100644--- a/src/knock/page.js+++ b/src/knock/page.js@@ -11,7 +11,12 @@import { knockApi } from './api.js';const els = {};-let state = { door: null, handle: null, url: null, totals: null, blocks: [], knocks: [], loadingMore: false };+let state = {+ door: null, handle: null, url: null, totals: null, blocks: [], knocks: [], loadingMore: false,+ // The escrowed lane's two halves: what we store (escrow) and what the chain+ // says (chainDoor). They can disagree, and the panel exists to say so.+ escrow: null, chainDoor: null,+};document.addEventListener('DOMContentLoaded', () => {for (const id of [@@ -21,6 +26,9 @@ document.addEventListener('DOMContentLoaded', () => {'share-url', 'copy-share', 'share-block', 'endpoint-url', 'copy-endpoint','stat-pending', 'stat-total', 'stat-earned', 'inbox', 'inbox-empty', 'inbox-loading','load-more', 'blocks', 'blocks-empty', 'no-handle', 'inbox-section', 'blocks-section',+ 'stat-escrowed', 'stat-escrowed-card', 'escrow-panel', 'escrow-enabled', 'escrow-window',+ 'escrow-fields', 'escrow-address', 'chain-state', 'chain-dot', 'chain-text',+ 'chain-actions', 'open-chain-door', 'chain-explorer',]) {els[id] = document.getElementById(id);}@@ -135,13 +143,147 @@ function applyOwner(data) {els['copy-endpoint'].dataset.copy = data.endpoint;}- els['stat-pending'].textContent = String(data.totals.pending);- els['stat-total'].textContent = String(data.totals.total);- els['stat-earned'].textContent = data.totals.earned;-+ renderTotals(data.totals);+ renderEscrow(data.escrow, door);renderBlocks(data.blocks || []);}+function renderTotals(totals) {+ els['stat-pending'].textContent = String(totals.pending);+ els['stat-total'].textContent = String(totals.total);+ els['stat-earned'].textContent = totals.earned;+ // Only shown once there is escrowed money to show. A permanent $0.00 tile+ // for a lane this owner does not use is furniture, not information.+ const escrowed = Number(totals.escrowed_pending || 0) > 0;+ els['stat-escrowed-card'].hidden = !escrowed;+ els['stat-escrowed'].textContent = totals.escrowed || '$0.00';+}++/**+ * The escrowed lane's own panel.+ *+ * Two things live here that nothing else in these settings does. The toggle is+ * an ordinary saved field, but the on-chain door beside it is not ours to+ * write: only this owner's wallet can open, reprice or shut it, so the panel+ * reads the chain and tells them what is actually true rather than what they+ * asked for.+ */+function renderEscrow(escrow, door) {+ state.escrow = escrow || null;+ if (!escrow) {+ els['escrow-panel'].hidden = true;+ return;+ }+ els['escrow-panel'].hidden = false;+ els['escrow-enabled'].checked = Boolean(escrow.enabled);+ els['escrow-window'].value = String(escrow.window_hours);+ els['escrow-window'].min = String(escrow.min_window_hours);+ els['escrow-window'].max = String(escrow.max_window_hours);+ els['escrow-fields'].hidden = !escrow.enabled;+ els['escrow-address'].hidden = !escrow.door || !escrow.enabled;+ els['escrow-address'].textContent = escrow.door ? `Your on-chain door: ${escrow.door}` : '';+ if (escrow.enabled) refreshChainState(door);+ else els['chain-actions'].hidden = true;+}++/** What the chain says about this owner's door, in their own words. */+async function refreshChainState(door) {+ const escrow = state.escrow;+ if (!escrow) return;+ if (!escrow.door) {+ return setChainState('warn', 'Add your Solana wallet above and save. It is half of your door\'s on-chain address.');+ }++ setChainState(null, 'Checking your on-chain door');+ els['chain-explorer'].hidden = false;+ els['chain-explorer'].href = `https://solscan.io/account/${escrow.door}`;++ try {+ const { connection, readDoor } = await import('./escrow-checkout.js');+ const onChain = await readDoor(await connection(), escrow.door);+ state.chainDoor = onChain;++ if (!onChain) {+ els['chain-actions'].hidden = false;+ els['open-chain-door'].textContent = 'Open my door on-chain';+ return setChainState(+ 'warn',+ 'Not opened yet. Until you open it, an escrowed knock has nowhere to land and senders see the normal lane.',+ );+ }++ const wanted = String(door.price_atomics);+ const wantedWindow = Number(escrow.window_hours) * 3600;+ const drifted = String(onChain.price) !== wanted || onChain.replyWindow !== wantedWindow || !onChain.open;+ els['chain-actions'].hidden = !drifted;+ els['open-chain-door'].textContent = 'Update it on-chain';++ if (!onChain.open) {+ return setChainState('warn', 'Shut on-chain. Escrowed knocks are refused until you reopen it.');+ }+ if (drifted) {+ return setChainState(+ 'warn',+ `On-chain it charges ${formatAtomics(onChain.price)} and answers within ${Math.round(onChain.replyWindow / 3600)}h. That is what a sender agrees to, so bring it in line with the settings above.`,+ );+ }+ return setChainState(+ 'live',+ `Open on-chain: ${formatAtomics(onChain.price)} per knock, ${Math.round(onChain.replyWindow / 3600)}h to answer. ${onChain.knocks} knock(s), ${onChain.answered} answered.`,+ );+ } catch (err) {+ setChainState('warn', `Could not read your on-chain door just now: ${err.message}`);+ }+}++function setChainState(tone, text) {+ els['chain-dot'].className = `dot${tone ? ` is-${tone}` : ''}`;+ els['chain-text'].textContent = text;+}++/** USDC atomics as a human amount, matching what the API formats elsewhere. */+function formatAtomics(atomics) {+ const value = Number(BigInt(atomics)) / 1e6;+ return `$${value.toFixed(value < 0.01 ? 4 : 2)}`;+}++/**+ * Open or update the on-chain door from the owner's own wallet.+ *+ * three.ws cannot do this for them and should not be able to: the account is+ * derived from their wallet, and only their signature can create or change it.+ */+async function openChainDoor() {+ const escrow = state.escrow;+ if (!escrow) return;+ const btn = els['open-chain-door'];+ const label = btn.textContent;+ btn.disabled = true;+ try {+ const { openDoorOnChain } = await import('./escrow-checkout.js');+ const { USDC_MINT } = await import('./escrow-program.js');+ const price = BigInt(state.door.price_atomics);+ if (price <= 0n) {+ showSettingsError('Set a price above zero before opening an escrowed door: the program will not hold nothing.');+ return;+ }+ await openDoorOnChain({+ handle: state.handle,+ priceAtomics: price,+ replyWindowSeconds: Number(els['escrow-window'].value || 24) * 3600,+ mint: USDC_MINT,+ onStatus: (status) => { btn.textContent = `${status}…`; },+ });+ showSettingsError('');+ await refreshChainState(state.door);+ } catch (err) {+ showSettingsError(err?.message || 'That did not go through.');+ } finally {+ btn.disabled = false;+ btn.textContent = label;+ }+}+function renderBlocks(blocks) {state.blocks = blocks;if (!blocks.length) {@@ -188,6 +330,8 @@ async function saveSettings() {max_chars: Number(els['door-max'].value) || 600,daily_cap: Number(els['door-cap'].value) || 25,listed: els['door-listed'].checked,+ escrow_enabled: els['escrow-enabled'].checked,+ escrow_window_hours: Number(els['escrow-window'].value) || 24,};els.save.disabled = true;els.save.textContent = 'Saving…';@@ -221,11 +365,7 @@ async function loadInbox({ append = false } = {}) {els['inbox-loading'].hidden = true;els['load-more'].hidden = !data.has_more;renderInbox();- if (data.totals) {- els['stat-pending'].textContent = String(data.totals.pending);- els['stat-total'].textContent = String(data.totals.total);- els['stat-earned'].textContent = data.totals.earned;- }+ if (data.totals) renderTotals(data.totals);} catch (err) {els['inbox-loading'].hidden = true;els['inbox-empty'].hidden = false;@@ -291,11 +431,20 @@ function knockRow(knock) {body.appendChild(reply);}+ if (knock.escrow) body.appendChild(escrowLine(knock.escrow));+const actions = document.createElement('div');actions.className = 'knock-actions';if (knock.status !== 'replied') {- const replyBtn = button('Reply', () => openReply(li, knock));- actions.appendChild(replyBtn);+ const payable = knock.escrow?.state === 'pending' && !knock.escrow.expired;+ actions.appendChild(button(payable ? 'Reply and get paid' : 'Reply', () => openReply(li, knock)));+ }+ if (knock.escrow?.state === 'pending' && !knock.escrow.expired) {+ // Declining is a real answer, and the one the sender is owed a refund+ // for. It is offered next to the reply rather than buried, because a+ // door that will not answer should say so while the money can still go+ // back cleanly instead of waiting out the clock.+ actions.appendChild(button('Refuse and refund', () => onRefuse(knock), 'danger'));}if (knock.status === 'pending') {actions.appendChild(button('Mark read', () => act(knock.id, { status: 'read' })));@@ -309,6 +458,88 @@ function knockRow(knock) {return li;}+/**+ * The on-chain half of one knock, said plainly.+ *+ * An escrowed knock is not money in the owner's pocket, and the inbox has to+ * stop implying that it is. Pending says what answering is worth and by when;+ * expired says the money is already owed back, which is the single most+ * important thing an owner can know before spending time on a reply.+ */+function escrowLine(escrow) {+ const el = document.createElement('div');+ el.className = `knock-escrow is-${escrow.state}${escrow.expired && escrow.state === 'pending' ? ' is-expired' : ''}`;+ if (escrow.state !== 'pending') {+ el.textContent =+ escrow.state === 'answered'+ ? 'Escrow released to you.'+ : escrow.state === 'refused'+ ? 'You declined this. The sender was refunded in full.'+ : 'The window closed and the sender took their payment back.';+ return el;+ }+ el.textContent = escrow.expired+ ? 'Escrowed, but the window has closed. This is owed back to the sender now; a reply is still welcome, it just will not pay.'+ : `Escrowed on-chain. Answer within ${remaining(escrow.expires_in_seconds)} to be paid.`;+ return el;+}++function remaining(seconds) {+ const s = Math.max(0, Number(seconds) || 0);+ if (s >= 86400) return `${Math.floor(s / 86400)}d ${Math.floor((s % 86400) / 3600)}h`;+ if (s >= 3600) return `${Math.floor(s / 3600)}h ${Math.floor((s % 3600) / 60)}m`;+ return `${Math.max(1, Math.floor(s / 60))}m`;+}++/**+ * Release an escrowed knock's payment by answering it on-chain.+ *+ * The reply is already saved by the time this runs, so a wallet the owner+ * cancels costs them the payout and nothing else: the sender still gets their+ * answer, and the escrow refunds itself when the window closes. That ordering+ * is deliberate. The alternative loses a written reply to a wallet prompt.+ */+async function collectEscrow(knock, setStatus) {+ const { answerKnock } = await import('./escrow-checkout.js');+ await answerKnock({+ knockAddress: knock.escrow.knock,+ reply: knock.pendingReply,+ onStatus: setStatus,+ });+ await syncEscrowRow(knock.escrow.knock);+}++/** Decline an escrowed knock and hand every unit back. Owner-signed, no fee. */+async function onRefuse(knock) {+ try {+ const { refuseKnock } = await import('./escrow-checkout.js');+ await refuseKnock({ knockAddress: knock.escrow.knock });+ await act(knock.id, { status: 'dismissed' });+ await syncEscrowRow(knock.escrow.knock);+ } catch (err) {+ showSettingsError(err?.message || 'That refusal did not go through.');+ }+}++/**+ * Ask the server to re-read one escrow and update its cached state.+ *+ * Best effort on purpose: the chain is authoritative either way, and a failed+ * sync means a stale label on a row, not a lost settlement.+ */+async function syncEscrowRow(escrowKnock) {+ try {+ const { state } = await knockApi.syncEscrow(escrowKnock);+ state.escrowSyncedAt = Date.now();+ const data = await knockApi.inbox({ limit: Math.max(20, state.knocks?.length || 20) });+ state.knocks = data.knocks;+ renderInbox();+ if (data.totals) renderTotals(data.totals);+ } catch {+ // The row's label stays as it was. Nothing on-chain depends on it.+ }+}+function button(label, onClick, tone = null) {const b = document.createElement('button');b.type = 'button';@@ -362,9 +593,7 @@ async function act(id, patch) {async function refreshTotals() {try {const data = await knockApi.inbox({ limit: 1 });- els['stat-pending'].textContent = String(data.totals.pending);- els['stat-total'].textContent = String(data.totals.total);- els['stat-earned'].textContent = data.totals.earned;+ renderTotals(data.totals);} catch {// The list on screen is already correct; a stale counter is not worth// an error banner.@@ -394,12 +623,26 @@ function bind() {els['door-open']?.addEventListener('change', hintPayout);els['door-price']?.addEventListener('input', hintPayout);els['door-solana']?.addEventListener('input', hintPayout);+ els['escrow-enabled']?.addEventListener('change', () => {+ els['escrow-fields'].hidden = !els['escrow-enabled'].checked;+ els['chain-actions'].hidden = !els['escrow-enabled'].checked;+ hintPayout();+ });+ els['open-chain-door']?.addEventListener('click', openChainDoor);}function hintPayout() {const priced = (els['door-price'].value.trim() || '0') !== '0';- const needsWallet = els['door-open'].checked && priced && !els['door-solana'].value.trim() && !els['door-base'].value.trim();- showSettingsError(needsWallet ? 'A priced door needs the wallet that should receive the USDC.' : '');+ const solana = els['door-solana'].value.trim();+ const needsWallet = els['door-open'].checked && priced && !solana && !els['door-base'].value.trim();+ if (needsWallet) return showSettingsError('A priced door needs the wallet that should receive the USDC.');+ // The escrowed lane needs Solana specifically: it is where an answer pays+ // out AND half of what derives the door's on-chain address, so a Base-only+ // door cannot run it. Saying so here beats a rejected save.+ if (els['escrow-enabled']?.checked && !solana) {+ return showSettingsError('Escrowed knocks need your Solana address: it is where an answer pays out, and half of your on-chain door address.');+ }+ showSettingsError('');}async function copy(btn) {