Skip to content

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.

feat(knock): a lane where the money only moves if the person actually answers

nirholasb467d2fa1708
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 90c40c1a7..cb5a74850 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr
## 2026-09-04
- **A knock now holds the money until you actually get a reply**: Paying to reach someone used to send your money the instant the payment cleared, which meant an owner could take every knock and answer none, and you had no way to get it back. A new Solana program makes the payment conditional: it sits in a vault that only the knock itself controls, and exactly three things can happen to it. The owner answers inside the reply window and gets paid, the owner declines and you are refunded in full with no fee taken, or the window closes and anyone at all can trigger your refund. There is no admin key that can move a knock that is parked, the fee is capped at 10% in the program itself, and the fee you agreed to when you knocked cannot be raised on money that is already in escrow. Your message never touches the chain: only a fingerprint of it is stored, so either side can later prove what was sent without publishing it. Ten invariants covering every one of those promises run against the real compiled program on every test run. `[feature, security]`
+- **Knock somebody's door and get your money back if they never answer**: Paying to reach a stranger has meant paying first and hoping. The money left your wallet the moment the payment cleared, and if the person never replied, that was that. Doors can now take escrowed knocks instead: your payment sits in a vault on Solana that the recipient cannot touch until they actually answer you. If they answer, they are paid. If they decline, you get everything back and are charged nothing, because reading something and passing on it is not a service. And if they simply never respond before the window they set, anyone at all can trigger the refund and every cent comes back to you, so it does not depend on you remembering to chase it. three.ws holds no key that can move that money, and neither does anyone else. Door owners can turn the lane on in their knock settings and choose how long they get to reply, from an hour to a month. (`/docs/knock`) `[feature, security]`
- **The 3D services we sell to other agents quote one clear price, however they are asked**: Our four paid 3D generation services on the OKX.AI agent marketplace answer every caller with a price quote before any work happens. Two flaws in that quote are fixed. A request that arrived with no body and no content type was turned away with a formatting complaint instead of a price, and that is exactly how the marketplace's own compatibility check asks, so the check saw four services that looked like they had no payment set up at all. Separately, a request that named no specific tool got a quote listing the same payment network twice at two different prices, one of them wrong. Every unpaid request now receives a single unambiguous quote at the service's listed price, on each payment network it accepts. `[fix]`
- **The IBM partnership demos arm wherever the page is opened**: The live demo pages loaded their own payment script across the network by full address, so on any address other than the main site (a preview, a local run, a copy published on a partner domain) the browser refused it and the paid demos never armed. Each page now loads the copy it ships with. The publish-once page IBM hosts got the opposite fix: every file it pulls now carries our full address, so its language switcher no longer looks for a file on the host's own domain and comes back empty. (`/ibm/hello`) `[fix]`
diff --git a/api/_lib/knock/deliver.js b/api/_lib/knock/deliver.js
index f7a6c6269..cda8c46bf 100644
--- a/api/_lib/knock/deliver.js
+++ b/api/_lib/knock/deliver.js
@@ -61,6 +61,9 @@ export async function checkDoor(userId, input) {
* @param {string} args.userId recipient
* @param {object} args.clean the output of validateKnock()
* @param {object} [args.payment] { payerWallet, network, txHash, amountAtomics, asset }
+ * plus { escrowKnock, escrowExpiresAt, escrowState } on
+ * the escrowed lane, where the money is parked on-chain
+ * rather than already in the recipient's wallet.
* @returns {Promise<{knock: object, duplicate: boolean, importance: number}>}
*/
export async function deliverKnock({ userId, clean, payment = {} }) {
@@ -106,6 +109,10 @@ export async function deliverKnock({ userId, clean, payment = {} }) {
amountAtomics,
asset: payment.asset ?? null,
companionEventId: event?.id ?? null,
+ // Only the escrowed lane sets these; both other lanes leave them null.
+ escrowKnock: payment.escrowKnock ?? null,
+ escrowExpiresAt: payment.escrowExpiresAt ?? null,
+ escrowState: payment.escrowState ?? null,
});
// recordKnock returns null only on the request-id conflict, which the check
diff --git a/api/_lib/knock/store.js b/api/_lib/knock/store.js
index 7b9ae1e48..c11039ab0 100644
--- a/api/_lib/knock/store.js
+++ b/api/_lib/knock/store.js
@@ -10,6 +10,7 @@ import { DEFAULT_PRICE_ATOMICS, KNOCK_STATUSES, normalizeHandle } from './policy
const DOOR_COLUMNS = sql`
user_id, open, price_atomics::text as price_atomics, pay_to_solana, pay_to_base,
+ escrow_enabled, escrow_window_hours,
headline, greeting, max_chars, daily_cap, listed, created_at, updated_at
`;
@@ -42,6 +43,8 @@ export async function updateDoor(userId, patch) {
max_chars = coalesce(${patch.max_chars ?? null}, max_chars),
daily_cap = coalesce(${patch.daily_cap ?? null}, daily_cap),
listed = coalesce(${patch.listed ?? null}, listed),
+ escrow_enabled = coalesce(${patch.escrow_enabled ?? null}, escrow_enabled),
+ escrow_window_hours = coalesce(${patch.escrow_window_hours ?? null}, escrow_window_hours),
updated_at = now()
where user_id = ${userId}
returning ${DOOR_COLUMNS}
@@ -62,6 +65,7 @@ export async function publicDoorByHandle(handle) {
select u.id as user_id, u.username, u.display_name, u.avatar_url, u.verified_type,
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,
d.pay_to_solana is not null as has_solana_payout,
d.pay_to_base is not null as has_base_payout
from users u
@@ -120,18 +124,62 @@ export async function isBlocked(userId, keys) {
* knock instead of two.
*/
export async function recordKnock(userId, knock) {
+ // escrow_* is a cache of what the chain says (api/_lib/knock/escrow.js), so
+ // the inbox can show a countdown without an RPC read per row. Null on both
+ // non-escrow lanes, which is how a reader tells the three apart.
const [row] = await sql`
insert into knock_messages
(recipient_user_id, sender_name, sender_url, sender_kind, payer_wallet, network,
- tx_hash, amount_atomics, asset, subject, message, companion_event_id, request_id)
+ tx_hash, amount_atomics, asset, subject, message, companion_event_id, request_id,
+ escrow_knock, escrow_expires_at, escrow_state)
values (${userId}, ${knock.senderName}, ${knock.senderUrl ?? null}, ${knock.senderKind ?? 'unknown'},
${knock.payerWallet ?? null}, ${knock.network ?? null}, ${knock.txHash ?? null},
${String(knock.amountAtomics ?? 0)}, ${knock.asset ?? null}, ${knock.subject ?? null},
- ${knock.message}, ${knock.companionEventId ?? null}, ${knock.requestId ?? null})
+ ${knock.message}, ${knock.companionEventId ?? null}, ${knock.requestId ?? null},
+ ${knock.escrowKnock ?? null},
+ ${knock.escrowExpiresAt ? new Date(knock.escrowExpiresAt * 1000) : null},
+ ${knock.escrowState ?? null})
on conflict (recipient_user_id, request_id) where request_id is not null do nothing
returning id, sender_name, sender_url, sender_kind, payer_wallet, network, tx_hash,
amount_atomics::text as amount_atomics, asset, subject, message, status,
- companion_event_id, created_at
+ companion_event_id, created_at, escrow_knock, escrow_expires_at, escrow_state
+ `;
+ return row || null;
+}
+
+/**
+ * Has this exact on-chain knock already bought a message?
+ *
+ * One escrowed knock buys exactly one delivery. The unique index on
+ * escrow_knock is what actually enforces it; this read is so a replay gets a
+ * clean "already delivered" with the original row instead of a constraint
+ * violation surfacing as a 500.
+ */
+export async function findByEscrowKnock(escrowKnock) {
+ if (!escrowKnock) return null;
+ const [row] = await sql`
+ select id, recipient_user_id, sender_name, subject, message, status, created_at,
+ escrow_knock, escrow_expires_at, escrow_state
+ from knock_messages
+ where escrow_knock = ${escrowKnock}
+ limit 1
+ `;
+ return row || null;
+}
+
+/**
+ * Write back what the chain now says about an escrowed knock.
+ *
+ * Called after re-reading the account, so a row that says `pending` in the
+ * inbox cannot keep saying it after the money has already gone back.
+ */
+export async function updateEscrowState(escrowKnock, state) {
+ if (!escrowKnock) return null;
+ const [row] = await sql`
+ update knock_messages
+ set escrow_state = ${state}
+ where escrow_knock = ${escrowKnock}
+ returning id, escrow_knock, escrow_state
`;
return row || null;
}
diff --git a/api/_lib/migrations/20260904010000_knock_escrow.sql b/api/_lib/migrations/20260904010000_knock_escrow.sql
new file mode 100644
index 000000000..edc8262ca
--- /dev/null
+++ b/api/_lib/migrations/20260904010000_knock_escrow.sql
@@ -0,0 +1,80 @@
+-- Migration: the escrowed knock lane on knock_doors and knock_messages.
+-- Apply: psql "$DATABASE_URL" -f api/_lib/migrations/20260904010000_knock_escrow.sql
+-- Idempotent.
+--
+-- The two existing lanes both settle before the recipient has done anything:
+-- the free lane charges nothing, and the x402 lane sends the sender's USDC
+-- straight to the recipient's wallet the moment it clears. The knock_doors
+-- comment says it plainly, "Nothing here holds funds", and for a door you were
+-- introduced to that is right. For a stranger it is the whole risk: a door can
+-- bank every knock and answer none, and there is no recourse, so at volume
+-- paying a stranger stops being rational and the price signal dies with it.
+--
+-- The escrowed lane parks the payment in a vault owned by the knock's own PDA
+-- on the knock_escrow program (contracts/knock-escrow). The recipient is paid
+-- by answering inside the reply window; if they refuse, or the window lapses,
+-- every unit goes back to the sender and anybody at all can crank that refund.
+--
+-- Nothing below holds funds either, and that is deliberate: three.ws never has
+-- custody, never signs for either side, and cannot release an escrow. These
+-- columns are a CACHE of what the chain already says, so the inbox can show a
+-- countdown and rank by it without an RPC round trip per row. The chain stays
+-- authoritative: api/_lib/knock/escrow.js re-reads the account before it
+-- believes anything here.
+
+begin;
+
+alter table knock_doors
+ -- Off by default. Turning it on changes what a stranger is agreeing to, so
+ -- it is the owner's explicit choice, never a silent upgrade of a live door.
+ add column if not exists escrow_enabled boolean not null default false,
+ -- How long the owner has to answer before the sender can take the money
+ -- back. Mirrors the program's 1-hour..30-day band; the program is the one
+ -- that enforces it, this is what the door advertises.
+ add column if not exists escrow_window_hours integer not null default 24;
+
+do $$
+begin
+ if not exists (
+ select 1 from pg_constraint where conname = 'knock_doors_escrow_window_chk'
+ ) then
+ alter table knock_doors
+ add constraint knock_doors_escrow_window_chk
+ check (escrow_window_hours between 1 and 720);
+ end if;
+end $$;
+
+alter table knock_messages
+ -- The knock's PDA: the address of the on-chain record this message was paid
+ -- through. Unique because one escrowed knock buys exactly one message, and
+ -- a second row against the same PDA would mean a delivered message the
+ -- sender never paid for.
+ add column if not exists escrow_knock text,
+ -- The deadline, copied from the chain so the inbox can sort by "answer this
+ -- before the money goes back" without reading 30 accounts to render a page.
+ add column if not exists escrow_expires_at timestamptz,
+ -- Last known on-chain state: pending, answered, refunded, refused.
+ add column if not exists escrow_state text;
+
+do $$
+begin
+ if not exists (
+ select 1 from pg_constraint where conname = 'knock_messages_escrow_state_chk'
+ ) then
+ alter table knock_messages
+ add constraint knock_messages_escrow_state_chk
+ check (escrow_state is null
+ or escrow_state in ('pending', 'answered', 'refunded', 'refused'));
+ end if;
+end $$;
+
+create unique index if not exists knock_messages_escrow_knock_key
+ on knock_messages (escrow_knock)
+ where escrow_knock is not null;
+
+-- The inbox's escrow view: what is still owed an answer, soonest deadline first.
+create index if not exists knock_messages_escrow_pending_idx
+ on knock_messages (recipient_user_id, escrow_expires_at)
+ where escrow_state = 'pending';
+
+commit;
diff --git a/api/knock/escrowed.js b/api/knock/escrowed.js
new file mode 100644
index 000000000..6d1fd8551
--- /dev/null
+++ b/api/knock/escrowed.js
@@ -0,0 +1,169 @@
+// POST /api/knock/escrowed
+//
+// The escrowed lane. A stranger pays a door's price into an on-chain vault the
+// recipient cannot touch until they answer, and this endpoint delivers the
+// message against that escrow.
+//
+// The other two lanes both settle before the recipient has done anything: the
+// free lane charges nothing, and the x402 lane sends the USDC straight to the
+// recipient's wallet the instant it clears. Between people who already know
+// each other that is right. Between strangers it is the whole risk, because a
+// door can bank every knock and answer none, and the sender has no recourse.
+//
+// Here the sender signs the `knock` instruction themselves on the knock_escrow
+// program (contracts/knock-escrow) BEFORE calling this, which parks their
+// payment in a vault owned by the knock's own PDA. Then exactly three things
+// can happen to that money, and three.ws is not one of them:
+//
+// - the owner answers inside the window and is paid;
+// - the owner refuses and the sender is refunded in full, with no fee;
+// - the window lapses and anyone at all can crank the refund.
+//
+// So this handler has no custody and no signing key in the path. All it does is
+// read the chain, refuse anything the chain does not back, and deliver. The
+// sender is told the escrow's deadline in the response, because the one thing
+// they need to know afterwards is when to stop waiting.
+//
+// The order of operations is the same as the paid lane's and for the same
+// reason: the door's own limits are checked BEFORE the escrow is read, so a
+// message that was going to be rejected for being too long, or aimed at a door
+// that is shut or full for the day, is refused without the sender ever being
+// told their escrow was accepted.
+
+import { z } from 'zod';
+import { cors, json, method, wrap, error, readJson, rateLimited } from '../_lib/http.js';
+import { clientIp, limits } from '../_lib/rate-limit.js';
+import { parse } from '../_lib/validate.js';
+import { normalizeHandle } from '../_lib/knock/policy.js';
+import { publicDoorByHandle, payoutFor, findByEscrowKnock } from '../_lib/knock/store.js';
+import { checkDoor, deliverKnock } from '../_lib/knock/deliver.js';
+import { receiptUrl } from '../_lib/knock/receipt.js';
+import { rpcFallbackFromEnv } from '../_lib/solana/rpc-fallback.js';
+import { verifyEscrowedKnock, EscrowRejected, KNOCK_ESCROW_PROGRAM_ID } from '../_lib/knock/escrow.js';
+
+const body = z.object({
+ to: z.string().trim().min(1).max(40),
+ from: z.string().trim().min(1).max(64),
+ message: z.string().min(1).max(2000),
+ subject: z.string().trim().max(120).optional(),
+ url: z.string().trim().max(400).optional(),
+ sender_kind: z.enum(['agent', 'human', 'unknown']).optional(),
+ request_id: z.string().trim().max(80).optional(),
+ // The wallet that signed the on-chain knock. Together with the door and the
+ // nonce this is what derives the knock's address; it is not trusted for
+ // anything else, because the account it points at either exists with the
+ // right contents or the request is refused.
+ sender_wallet: z.string().trim().min(32).max(44),
+ nonce: z.union([z.number().int().min(0), z.string().regex(/^\d{1,20}$/)]),
+});
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { origins: '*', methods: 'POST,OPTIONS' })) return;
+ if (!method(req, res, ['POST'])) return;
+
+ // Same bucket as the free lane. An escrowed knock costs the sender real
+ // money, but deriving and reading an account costs US an RPC round trip, and
+ // a caller can make that call with no escrow at all.
+ const rl = await limits.knockSendIp(clientIp(req));
+ if (!rl.success) return rateLimited(res, rl, 'too many escrow checks from one address');
+
+ const input = parse(body, await readJson(req));
+ const handle = normalizeHandle(input.to);
+ const door = await publicDoorByHandle(handle);
+ if (!door) return error(res, 404, 'no_door', 'no open door for that handle');
+ if (!door.escrow_enabled) {
+ return error(res, 409, 'escrow_not_enabled', `${door.display_name || handle} does not take escrowed knocks`, {
+ lane: String(door.price_atomics) === '0' ? 'free' : 'x402',
+ endpoint:
+ String(door.price_atomics) === '0'
+ ? '/api/knock/send'
+ : `/api/x402/knock?to=${encodeURIComponent(handle)}`,
+ });
+ }
+
+ // The recipient's Solana address is both where an answer pays out and the
+ // owner half of the door's PDA, so a door with no address has no on-chain
+ // door to knock at.
+ const payout = await payoutFor(door.user_id);
+ if (!payout?.pay_to_solana) {
+ return error(res, 409, 'no_payout_wallet', 'that door has no Solana address, so it has no on-chain door');
+ }
+
+ // Door limits first: never tell a sender their escrow was accepted for a
+ // message this door was always going to refuse.
+ const { clean } = await checkDoor(door.user_id, { ...input, payer_wallet: input.sender_wallet });
+
+ let escrow;
+ try {
+ const rpc = rpcFallbackFromEnv({ network: 'mainnet' });
+ escrow = await rpc.withFallback((connection) =>
+ verifyEscrowedKnock(connection, {
+ ownerWallet: payout.pay_to_solana,
+ handle,
+ sender: input.sender_wallet,
+ nonce: input.nonce,
+ message: clean.message,
+ minPriceAtomics: BigInt(door.price_atomics),
+ }),
+ );
+ } catch (err) {
+ if (err instanceof EscrowRejected) {
+ // 402 for "there is no payment here", 409 for "there is one and it is
+ // not usable". The difference tells a client whether to go and knock
+ // on-chain or to stop retrying.
+ const status = err.code === 'knock_not_found' ? 402 : 409;
+ return error(res, status, err.code, err.message, {
+ ...err.detail,
+ program: KNOCK_ESCROW_PROGRAM_ID,
+ });
+ }
+ throw err;
+ }
+
+ // One escrowed knock buys exactly one message. The unique index enforces it;
+ // this returns the original delivery rather than a constraint violation.
+ const already = await findByEscrowKnock(escrow.knock);
+ if (already) {
+ return json(res, 200, {
+ ok: true,
+ duplicate: true,
+ knock_id: already.id,
+ escrow: { knock: escrow.knock, state: escrow.stateName, expires_at: escrow.expiresAt },
+ receipt: receiptUrl(already.id),
+ });
+ }
+
+ const { knock, duplicate } = await deliverKnock({
+ userId: door.user_id,
+ clean,
+ payment: {
+ payerWallet: input.sender_wallet,
+ network: 'solana',
+ amountAtomics: String(escrow.amount),
+ asset: escrow.mint,
+ escrowKnock: escrow.knock,
+ escrowExpiresAt: escrow.expiresAt,
+ escrowState: escrow.stateName,
+ },
+ });
+
+ return json(res, duplicate ? 200 : 201, {
+ ok: true,
+ duplicate,
+ knock_id: knock.id,
+ delivered_to: door.display_name || handle,
+ escrow: {
+ knock: escrow.knock,
+ vault: escrow.vault,
+ program: KNOCK_ESCROW_PROGRAM_ID,
+ amount_atomics: String(escrow.amount),
+ state: escrow.stateName,
+ expires_at: escrow.expiresAt,
+ expires_in_seconds: escrow.expiresInSeconds,
+ // Said plainly, because it is the reason to use this lane at all.
+ guarantee:
+ 'If this is not answered before the window closes, anyone can crank the refund and every unit returns to you.',
+ },
+ receipt: receiptUrl(knock.id),
+ });
+});
diff --git a/api/knock/settings.js b/api/knock/settings.js
index 3af9ac870..78add8e58 100644
--- a/api/knock/settings.js
+++ b/api/knock/settings.js
@@ -28,6 +28,12 @@ const patchBody = z.object({
max_chars: z.number().int().min(40).max(2000).optional(),
daily_cap: z.number().int().min(1).max(1000).optional(),
listed: z.boolean().optional(),
+ // The escrowed lane. Off by default on every door, because turning it on
+ // changes what a stranger is agreeing to when they pay.
+ escrow_enabled: z.boolean().optional(),
+ // Bounded to the same 1-hour..30-day band the program enforces, so a door
+ // cannot advertise a window the chain would refuse.
+ escrow_window_hours: z.number().int().min(1).max(720).optional(),
block: z.string().trim().min(1).max(120).optional(),
unblock: z.string().uuid().optional(),
});
@@ -69,6 +75,8 @@ export default wrap(async (req, res) => {
if (body.max_chars !== undefined) patch.max_chars = body.max_chars;
if (body.daily_cap !== undefined) patch.daily_cap = body.daily_cap;
if (body.listed !== undefined) patch.listed = body.listed;
+ if (body.escrow_enabled !== undefined) patch.escrow_enabled = body.escrow_enabled;
+ if (body.escrow_window_hours !== undefined) patch.escrow_window_hours = body.escrow_window_hours;
// Opening a door with a price and nowhere to send the money would take
// payments into the platform's own wallet. Refuse instead of quietly
@@ -83,6 +91,18 @@ export default wrap(async (req, res) => {
);
}
+ // An escrowed door's PDA is derived from the owner's Solana address, and an
+ // answer pays out to it. Without one there is no on-chain door to knock at,
+ // so enabling the lane would advertise something that cannot work.
+ if (merged.escrow_enabled && !merged.pay_to_solana) {
+ return error(
+ res,
+ 400,
+ 'missing_solana_payout',
+ 'the escrowed lane needs a Solana address: it is where an answer pays out, and half of the door\'s on-chain address',
+ );
+ }
+
if (Object.keys(patch).length) await updateDoor(user.id, patch);
return json(res, 200, await ownerView(user));
});
diff --git a/data/changelog.json b/data/changelog.json
index 3d1c9fbbb..356841fa8 100644
--- a/data/changelog.json
+++ b/data/changelog.json
@@ -1,6 +1,16 @@
{
"$comment": "Curated changelog entries for three.ws, the editorial layer of the public changelog. New PAGE launches are tracked automatically via the `added` field in data/pages.json; this file is for everything else holders care about: improvements, fixes, SDK releases, trading/payments capabilities, security work. scripts/build-page-index.mjs merges both sources into CHANGELOG.md, public/changelog.json, and public/changelog.xml. Newest first. Allowed tags: feature, improvement, fix, sdk, infra, docs, security. `link` is optional and must be a live three.ws path.",
"entries": [
+ {
+ "date": "2026-09-04",
+ "title": "Knock somebody's door and get your money back if they never answer",
+ "summary": "Paying to reach a stranger has meant paying first and hoping. The money left your wallet the moment the payment cleared, and if the person never replied, that was that. Doors can now take escrowed knocks instead: your payment sits in a vault on Solana that the recipient cannot touch until they actually answer you. If they answer, they are paid. If they decline, you get everything back and are charged nothing, because reading something and passing on it is not a service. And if they simply never respond before the window they set, anyone at all can trigger the refund and every cent comes back to you, so it does not depend on you remembering to chase it. three.ws holds no key that can move that money, and neither does anyone else. Door owners can turn the lane on in their knock settings and choose how long they get to reply, from an hour to a month.",
+ "link": "/docs/knock",
+ "tags": [
+ "feature",
+ "security"
+ ]
+ },
{
"date": "2026-09-04",
"title": "The 3D services we sell to other agents quote one clear price, however they are asked",
diff --git a/docs/knock.md b/docs/knock.md
index 9fecb0a3d..ba1e9e3a2 100644
--- a/docs/knock.md
+++ b/docs/knock.md
@@ -251,6 +251,7 @@ a 404, not a 403: an id on its own should not confirm that a knock exists.
| `GET /api/knock/directory` | none | Every open, listed door, cheapest first. |
| `POST /api/knock/send` | none | Knock on a free door. |
| `POST /api/x402/knock?to=` | x402 payment | Knock on a priced door. |
+| `POST /api/knock/escrowed` | on-chain escrow | Knock on a door that takes escrowed knocks, where the money only moves if you get an answer. |
| `GET /api/knock/reply?id=&token=` | receipt token | What became of a knock you sent. |
| `GET /api/knock/settings` | session | Your door, your totals, your block list. |
| `PATCH /api/knock/settings` | session | Change any of it. |
@@ -261,6 +262,91 @@ Error codes are stable and mean what they say: `no_door`, `door_closed`,
`door_full` (429, retryable tomorrow), `message_too_long`, `message_too_short`,
`bad_url`, `missing_sender`, `free_door`, `payment_required`.
+The escrowed lane adds `escrow_not_enabled` (409, and the body names the lane
+to use instead), `no_payout_wallet` (409), `knock_not_found` (402, nothing is
+escrowed at the address the request derives), and four 409s for an escrow that
+exists but cannot be used: `already_settled`, `message_mismatch`,
+`window_closed`, `underpaid`.
+
+---
+
+## The escrowed lane
+
+The x402 lane sends your USDC to the recipient the instant the payment clears.
+Between people who already know each other that is the right shape, and it is
+why the lane exists. Between strangers it is the whole risk: a door can bank
+every knock and answer none, and you have no recourse. Nobody is going to keep
+paying strangers under those terms, and when they stop, the price stops meaning
+anything, which was the entire point of pricing a door.
+
+An escrowed door fixes that without giving three.ws your money either. You sign
+a `knock` instruction on the [knock_escrow](https://github.com/nirholas/three.ws/tree/main/contracts/knock-escrow)
+Solana program, which parks your payment in a vault owned by that knock's own
+program address. From there exactly three things can happen to it:
+
+| Outcome | Who can trigger it | Where your money goes |
+| --- | --- | --- |
+| Answered inside the window | the door's owner, and nobody else | to them, minus the protocol fee |
+| Refused | the door's owner | **all of it back to you**, no fee taken |
+| The window closes | **anyone at all** | **all of it back to you** |
+
+There is no fourth path. three.ws holds no key that can move a parked knock,
+and neither can the protocol authority: the vault's only authority is the
+knock's own address. The worst case for a sender is that their money is
+unavailable until the window they agreed to runs out.
+
+Two details worth knowing:
+
+**The refund is permissionless.** If only you could claim it back, the guarantee
+would be worth exactly as much as your diligence, and an agent that knocked and
+went away would leave the money stranded. Anybody can crank an expired refund,
+and it can only ever pay the original sender.
+
+**Refusing costs you nothing.** An owner who will not engage is better off
+refusing than letting the clock run out: you get your money back immediately
+rather than a day later. Reading something and declining to answer is not a
+service, so it is not charged for.
+
+### Sending an escrowed knock
+
+```bash
+# 1. Check the door takes escrowed knocks and read its price.
+curl -s 'https://three.ws/api/knock/door?handle=nirholas'
+
+# 2. Sign the on-chain `knock` instruction yourself, parking the price in escrow.
+# The knock's address derives from (door, your wallet, a nonce you choose).
+
+# 3. Deliver the message against it.
+curl -sX POST https://three.ws/api/knock/escrowed \
+ -H 'content-type: application/json' \
+ -d '{
+ "to": "nirholas",
+ "from": "Ada (research agent)",
+ "message": "two questions about the facilitator, happy to pay for the time",
+ "sender_wallet": "<the wallet that signed the knock>",
+ "nonce": 7
+ }'
+```
+
+The response carries the knock's address, its vault, the deadline, and the
+seconds remaining. The message body itself never touches the chain: the escrow
+commits to its SHA-256, so both sides can prove later what was actually sent
+without publishing a stranger's private message to a public ledger. That hash is
+also what stops a paid escrow being reused to deliver a different message.
+
+### Opening an escrowed door
+
+```bash
+curl -sX PATCH https://three.ws/api/knock/settings \
+ -H 'content-type: application/json' \
+ -d '{ "escrow_enabled": true, "escrow_window_hours": 24 }'
+```
+
+Off by default on every door, because turning it on changes what a stranger is
+agreeing to when they pay. It needs a Solana address on the door: that address
+is where an answer pays out, and it is half of the door's on-chain identity.
+The window can be 1 hour to 30 days, the same band the program enforces.
+
---
## Why it is built this way
@@ -283,7 +369,10 @@ avatar as a speaker.
**No custody, no cut.** `payTo` on the 402 challenge is the recipient's own
address. There is no platform wallet in the path to be drained, reconciled, or
-argued about.
+argued about. The escrowed lane keeps that property while removing the trust it
+used to require: the money sits in a vault whose only authority is the knock's
+own program address, so three.ws cannot release it, refund it, or redirect it,
+and neither can anyone else outside the three outcomes above.
---
diff --git a/public/changelog.json b/public/changelog.json
index a6b15ed3a..2542128c1 100644
--- a/public/changelog.json
+++ b/public/changelog.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-09-04T01:50:19.386Z",
+ "generated_at": "2026-09-04T01:54:47.940Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json",
"site": {
"name": "three.ws",
@@ -17,6 +17,17 @@
"security"
]
},
+ {
+ "date": "2026-09-04",
+ "type": "update",
+ "title": "Knock somebody's door and get your money back if they never answer",
+ "summary": "Paying to reach a stranger has meant paying first and hoping. The money left your wallet the moment the payment cleared, and if the person never replied, that was that. Doors can now take escrowed knocks instead: your payment sits in a vault on Solana that the recipient cannot touch until they actually answer you. If they answer, they are paid. If they decline, you get everything back and are charged nothing, because reading something and passing on it is not a service. And if they simply never respond before the window they set, anyone at all can trigger the refund and every cent comes back to you, so it does not depend on you remembering to chase it. three.ws holds no key that can move that money, and neither does anyone else. Door owners can turn the lane on in their knock settings and choose how long they get to reply, from an hour to a month.",
+ "link": "/docs/knock",
+ "tags": [
+ "feature",
+ "security"
+ ]
+ },
{
"date": "2026-09-04",
"type": "update",
diff --git a/public/changelog.xml b/public/changelog.xml
index e89034ef9..1e7350f46 100644
--- a/public/changelog.xml
+++ b/public/changelog.xml
@@ -14,6 +14,14 @@
<category>feature</category>
<description>Paying to reach someone used to send your money the instant the payment cleared, which meant an owner could take every knock and answer none, and you had no way to get it back. A new Solana program makes the payment conditional: it sits in a vault that only the knock itself controls, and exactly three things can happen to it. The owner answers inside the reply window and gets paid, the owner declines and you are refunded in full with no fee taken, or the window closes and anyone at all can trigger your refund. There is no admin key that can move a knock that is parked, the fee is capped at 10% in the program itself, and the fee you agreed to when you knocked cannot be raised on money that is already in escrow. Your message never touches the chain: only a fingerprint of it is stored, so either side can later prove what was sent without publishing it. Ten invariants covering every one of those promises run against the real compiled program on every test run.</description>
</item>
+ <item>
+ <title>Knock somebody's door and get your money back if they never answer</title>
+ <link>https://three.ws/docs/knock</link>
+ <guid isPermaLink="false">2026-09-04:Knock somebody's door and get your money back if they never answer</guid>
+ <pubDate>Fri, 04 Sep 2026 12:00:00 GMT</pubDate>
+ <category>feature</category>
+ <description>Paying to reach a stranger has meant paying first and hoping. The money left your wallet the moment the payment cleared, and if the person never replied, that was that. Doors can now take escrowed knocks instead: your payment sits in a vault on Solana that the recipient cannot touch until they actually answer you. If they answer, they are paid. If they decline, you get everything back and are charged nothing, because reading something and passing on it is not a service. And if they simply never respond before the window they set, anyone at all can trigger the refund and every cent comes back to you, so it does not depend on you remembering to chase it. three.ws holds no key that can move that money, and neither does anyone else. Door owners can turn the lane on in their knock settings and choose how long they get to reply, from an hour to a month.</description>
+ </item>
<item>
<title>The 3D services we sell to other agents quote one clear price, however they are asked</title>
<link>https://three.ws/changelog</link>
diff --git a/public/features.json b/public/features.json
index 0ee5ce831..f12077105 100644
--- a/public/features.json
+++ b/public/features.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-09-04T01:50:19.365Z",
+ "generated_at": "2026-09-04T01:54:47.914Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json",
"site": {
"name": "three.ws",
diff --git a/tests/api-knock-escrowed.test.js b/tests/api-knock-escrowed.test.js
new file mode 100644
index 000000000..e522ca35b
--- /dev/null
+++ b/tests/api-knock-escrowed.test.js
@@ -0,0 +1,296 @@
+// POST /api/knock/escrowed: the escrowed lane's refusal surface.
+//
+// The handler's whole job is to refuse anything the chain does not back, so the
+// cases that matter are the refusals. Each one below is something a caller can
+// really do, and getting any of them wrong means either delivering a message
+// nobody paid for or telling somebody who did pay that they did not.
+//
+// Everything downstream of the seams is the real handler: the real zod schema,
+// the real ordering of checks, the real escrow verifier decoding real
+// program-layout bytes. Only the two boundaries are stubbed, the database and
+// the Solana RPC, because this suite is about the handler's decisions rather
+// than about Postgres or a live cluster. The PDA derivation those bytes are
+// keyed by is pinned against the compiled program in tests/knock-escrow-pda.test.js.
+
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { PublicKey } from '@solana/web3.js';
+
+const OWNER_WALLET = '11111111111111111111111111111111';
+const SENDER = 'TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA';
+const USDC = 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v';
+const HANDLE = 'nirholas';
+const NONCE = 7;
+const PRICE = '50000';
+// From tests/knock-escrow-pda.test.js, which pins these against the program.
+const KNOCK_PDA = '8WvZ64SL6JNss232BC78aapB2M6MjE95f9LtWfYYRn5t';
+const DOOR_PDA = 'DMDKj3mSoM5rjsftGAhSbLbrAWMwmFxEkHDLsx997vk8';
+const DISC_KNOCK = 'f9c621b06c558191';
+const PROGRAM = 'uVX46U6sGUs6PD3339ZXbTpMyhZwkQhBLPxnvRX9ps7';
+
+const state = {
+ door: null,
+ payout: null,
+ account: null,
+ accountOwner: PROGRAM,
+ existingByEscrow: null,
+ delivered: [],
+ checkDoorThrows: null,
+};
+
+vi.mock('../api/_lib/knock/store.js', () => ({
+ publicDoorByHandle: async () => state.door,
+ payoutFor: async () => state.payout,
+ findByEscrowKnock: async () => state.existingByEscrow,
+}));
+
+vi.mock('../api/_lib/knock/deliver.js', () => ({
+ checkDoor: async (userId, input) => {
+ if (state.checkDoorThrows) throw state.checkDoorThrows;
+ return { clean: { message: input.message, senderName: input.from, subject: input.subject ?? null } };
+ },
+ deliverKnock: async (args) => {
+ state.delivered.push(args);
+ return { knock: { id: 'knock-row-1' }, duplicate: false };
+ },
+}));
+
+vi.mock('../api/_lib/knock/receipt.js', () => ({ receiptUrl: (id) => `/knock/receipt/${id}` }));
+
+vi.mock('../api/_lib/rate-limit.js', () => ({
+ clientIp: () => '203.0.113.9',
+ limits: { knockSendIp: async () => ({ success: true }) },
+}));
+
+vi.mock('../api/_lib/solana/rpc-fallback.js', () => ({
+ rpcFallbackFromEnv: () => ({
+ withFallback: (fn) =>
+ fn({
+ async getAccountInfo() {
+ if (!state.account) return null;
+ return { data: state.account, owner: { toBase58: () => state.accountOwner } };
+ },
+ }),
+ }),
+}));
+
+const { default: handler } = await import('../api/knock/escrowed.js');
+const { sha256 } = await import('../api/_lib/knock/escrow.js');
+
+/** A KnockRecord laid out exactly as the program writes one. */
+function knockAccount({
+ messageHash,
+ amount = 50_000n,
+ state: knockState = 0,
+ expiresAt = Math.floor(Date.now() / 1000) + 3600,
+} = {}) {
+ const buf = Buffer.alloc(205);
+ Buffer.from(DISC_KNOCK, 'hex').copy(buf, 0);
+ new PublicKey(DOOR_PDA).toBuffer().copy(buf, 8);
+ new PublicKey(SENDER).toBuffer().copy(buf, 40);
+ new PublicKey(USDC).toBuffer().copy(buf, 72);
+ buf.writeBigUInt64LE(amount, 104);
+ buf.writeUInt16LE(250, 112);
+ buf.writeBigUInt64LE(BigInt(NONCE), 114);
+ Buffer.from(messageHash).copy(buf, 122);
+ buf.writeBigInt64LE(BigInt(expiresAt - 3600), 186);
+ buf.writeBigInt64LE(BigInt(expiresAt), 194);
+ buf[202] = knockState;
+ return buf;
+}
+
+function call(body) {
+ const req = {
+ method: 'POST',
+ url: '/api/knock/escrowed',
+ headers: { 'content-type': 'application/json', origin: 'https://three.ws' },
+ body,
+ socket: { remoteAddress: '203.0.113.9' },
+ };
+ const res = {
+ statusCode: 0,
+ payload: null,
+ headers: {},
+ setHeader(k, v) {
+ this.headers[String(k).toLowerCase()] = v;
+ },
+ getHeader(k) {
+ return this.headers[String(k).toLowerCase()];
+ },
+ removeHeader(k) {
+ delete this.headers[String(k).toLowerCase()];
+ },
+ writeHead(code) {
+ this.statusCode = code;
+ return this;
+ },
+ get headersSent() {
+ return false;
+ },
+ get writableEnded() {
+ return false;
+ },
+ end(chunk) {
+ if (chunk) {
+ try {
+ this.payload = JSON.parse(String(chunk));
+ } catch {
+ this.payload = String(chunk);
+ }
+ }
+ return this;
+ },
+ };
+ return handler(req, res).then(() => ({ status: res.statusCode, body: res.payload }));
+}
+
+const MESSAGE = 'two questions about the facilitator, happy to pay for the time';
+const goodBody = {
+ to: HANDLE,
+ from: 'Ada (research agent)',
+ message: MESSAGE,
+ sender_wallet: SENDER,
+ nonce: NONCE,
+};
+
+beforeEach(() => {
+ state.door = {
+ user_id: 'user-1',
+ username: HANDLE,
+ display_name: 'nirholas',
+ price_atomics: PRICE,
+ escrow_enabled: true,
+ escrow_window_hours: 24,
+ };
+ state.payout = { pay_to_solana: OWNER_WALLET };
+ state.account = knockAccount({ messageHash: sha256(MESSAGE) });
+ state.accountOwner = PROGRAM;
+ state.existingByEscrow = null;
+ state.delivered = [];
+ state.checkDoorThrows = null;
+});
+
+describe('POST /api/knock/escrowed', () => {
+ it('delivers a message backed by a live escrow, and says when it expires', async () => {
+ const out = await call(goodBody);
+ expect(out.status).toBe(201);
+ expect(out.body.ok).toBe(true);
+ expect(out.body.escrow.knock).toBe(KNOCK_PDA);
+ expect(out.body.escrow.program).toBe(PROGRAM);
+ expect(out.body.escrow.amount_atomics).toBe('50000');
+ expect(out.body.escrow.state).toBe('pending');
+ expect(out.body.escrow.expires_in_seconds).toBeGreaterThan(0);
+ expect(out.body.receipt).toBe('/knock/receipt/knock-row-1');
+
+ // The delivery carries the escrow through, so the inbox can show a
+ // countdown and the row can be reconciled against the chain later.
+ expect(state.delivered).toHaveLength(1);
+ expect(state.delivered[0].payment).toMatchObject({
+ escrowKnock: KNOCK_PDA,
+ escrowState: 'pending',
+ network: 'solana',
+ asset: USDC,
+ });
+ });
+
+ it('answers 402, not 500, when no escrow exists', async () => {
+ state.account = null;
+ const out = await call(goodBody);
+ expect(out.status).toBe(402);
+ expect(out.body.error).toBe('knock_not_found');
+ // The caller is told which account to go and fund.
+ expect(out.body.knock).toBe(KNOCK_PDA);
+ expect(state.delivered).toHaveLength(0);
+ });
+
+ it('refuses a message the sender did not escrow, so a payment cannot be reused', async () => {
+ state.account = knockAccount({ messageHash: sha256('a much smaller favour') });
+ const out = await call(goodBody);
+ expect(out.status).toBe(409);
+ expect(out.body.error).toBe('message_mismatch');
+ expect(state.delivered).toHaveLength(0);
+ });
+
+ it('refuses an escrow that already settled', async () => {
+ state.account = knockAccount({ messageHash: sha256(MESSAGE), state: 1 });
+ const out = await call(goodBody);
+ expect(out.status).toBe(409);
+ expect(out.body.error).toBe('already_settled');
+ });
+
+ it('refuses an expired escrow, because that money is owed back', async () => {
+ state.account = knockAccount({
+ messageHash: sha256(MESSAGE),
+ expiresAt: Math.floor(Date.now() / 1000) - 5,
+ });
+ const out = await call(goodBody);
+ expect(out.status).toBe(409);
+ expect(out.body.error).toBe('window_closed');
+ });
+
+ it('refuses an escrow below the door price', async () => {
+ state.account = knockAccount({ messageHash: sha256(MESSAGE), amount: 10_000n });
+ const out = await call(goodBody);
+ expect(out.status).toBe(409);
+ expect(out.body.error).toBe('underpaid');
+ });
+
+ it('refuses an account owned by another program', async () => {
+ state.accountOwner = '11111111111111111111111111111111';
+ const out = await call(goodBody);
+ expect(out.status).toBe(409);
+ expect(out.body.error).toBe('wrong_program');
+ });
+
+ it('checks the door BEFORE the chain, so a doomed message never reports a good escrow', async () => {
+ const refusal = Object.assign(new Error('this door is full for today'), {
+ code: 'door_full',
+ status: 429,
+ });
+ state.checkDoorThrows = refusal;
+ state.account = null; // would be a 402 if the chain were consulted first
+ const out = await call(goodBody);
+ // The door's own refusal wins, and it is the door's status the caller
+ // sees, not a payment error about an escrow that was never the problem.
+ expect(out.status).toBe(429);
+ expect(out.body.error).toBe('door_full');
+ expect(state.delivered).toHaveLength(0);
+ });
+
+ it('points a caller at the right lane when the door does not take escrow', async () => {
+ state.door.escrow_enabled = false;
+ const out = await call(goodBody);
+ expect(out.status).toBe(409);
+ expect(out.body.error).toBe('escrow_not_enabled');
+ expect(out.body.endpoint).toContain('/api/x402/knock');
+ });
+
+ it('refuses a door with no Solana address, which has no on-chain door at all', async () => {
+ state.payout = { pay_to_solana: null };
+ const out = await call(goodBody);
+ expect(out.status).toBe(409);
+ expect(out.body.error).toBe('no_payout_wallet');
+ });
+
+ it('404s an unknown handle', async () => {
+ state.door = null;
+ const out = await call(goodBody);
+ expect(out.status).toBe(404);
+ expect(out.body.error).toBe('no_door');
+ });
+
+ it('returns the original delivery when one escrow is replayed', async () => {
+ state.existingByEscrow = { id: 'knock-row-1' };
+ const out = await call(goodBody);
+ expect(out.status).toBe(200);
+ expect(out.body.duplicate).toBe(true);
+ expect(out.body.knock_id).toBe('knock-row-1');
+ // One escrow buys one message: no second delivery is staged.
+ expect(state.delivered).toHaveLength(0);
+ });
+
+ it('accepts a nonce sent as a string, which is how a JSON client avoids u64 loss', async () => {
+ const out = await call({ ...goodBody, nonce: String(NONCE) });
+ expect(out.status).toBe(201);
+ expect(out.body.escrow.knock).toBe(KNOCK_PDA);
+ });
+});