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): sync an escrowed knock from the chain so a refunded row stops looking like money on the table
nirholasffdb8be0c69f
diff --git a/api/knock/escrow-sync.js b/api/knock/escrow-sync.jsnew file mode 100644index 000000000..9879695a6--- /dev/null+++ b/api/knock/escrow-sync.js@@ -0,0 +1,82 @@+// POST /api/knock/escrow-sync+//+// Copy one escrowed knock's on-chain state into the row that caches it.+//+// The escrow_* columns on knock_messages are a cache and nothing more: the+// chain decides whether a knock was answered, refused or refunded, and it does+// so through transactions signed by wallets we do not hold. So there is no+// moment where this server "knows" a settlement happened. It has to look.+//+// This is that look, and it is deliberately open to anybody. It cannot be used+// to claim anything: it reads the account the row already names, and writes+// back only what the program itself recorded. A caller who lies about a+// settlement gets the truth written instead. That is also why it is safe for+// the sender's own page to call it, which is what keeps a refunded knock from+// sitting in the recipient's inbox looking like money still on the table.++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 { rpcFallbackFromEnv } from '../_lib/solana/rpc-fallback.js';+import { KNOCK_ESCROW_PROGRAM_ID, KNOCK_STATE_NAME, decodeKnock } from '../_lib/knock/escrow.js';+import { findByEscrowKnock, updateEscrowState } from '../_lib/knock/store.js';+import { PublicKey } from '@solana/web3.js';++const body = z.object({+ knock: z.string().trim().min(32).max(44),+});++export default wrap(async (req, res) => {+ if (cors(req, res, { origins: '*', methods: 'POST,OPTIONS' })) return;+ if (!method(req, res, ['POST'])) return;++ 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));++ // Only a knock this platform actually delivered can be synced. Anything else+ // is somebody else's escrow and none of our cache's business.+ const row = await findByEscrowKnock(input.knock);+ if (!row) return error(res, 404, 'unknown_escrow', 'no delivered knock is recorded against that escrow');++ let record;+ try {+ const rpc = rpcFallbackFromEnv({ network: 'mainnet' });+ record = await rpc.withFallback(async (connection) => {+ const info = await connection.getAccountInfo(new PublicKey(input.knock));+ if (!info) return null;+ if (info.owner?.toBase58?.() !== KNOCK_ESCROW_PROGRAM_ID) return null;+ return decodeKnock(info.data);+ });+ } catch {+ // An RPC that will not answer is not evidence about a settlement, so the+ // cache is left exactly as it was rather than guessed at.+ return error(res, 503, 'chain_unreachable', 'could not read the chain just now; the cached state is unchanged');+ }++ if (!record) {+ return json(res, 200, {+ ok: true,+ knock: input.knock,+ state: row.escrow_state || 'pending',+ changed: false,+ note: 'that escrow account is not readable, so nothing was changed',+ });+ }++ const state = KNOCK_STATE_NAME[record.state] || 'pending';+ const changed = state !== row.escrow_state;+ if (changed) await updateEscrowState(input.knock, state);++ return json(res, 200, {+ ok: true,+ knock: input.knock,+ state,+ changed,+ amount_atomics: String(record.amount),+ expires_at: record.expiresAt,+ expired: Math.floor(Date.now() / 1000) > record.expiresAt,+ });+});diff --git a/src/knock/page.js b/src/knock/page.jsindex 90faccc64..6c1b2ec9c 100644--- a/src/knock/page.js+++ b/src/knock/page.js@@ -529,9 +529,8 @@ async function onRefuse(knock) {*/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) });+ await knockApi.syncEscrow(escrowKnock);+ const data = await knockApi.inbox({ limit: Math.max(20, state.knocks.length || 20) });state.knocks = data.knocks;renderInbox();if (data.totals) renderTotals(data.totals);@@ -572,21 +571,48 @@ function openReply(li, knock) {if (!reply) return;send.disabled = true;send.textContent = 'Sending…';- await act(knock.id, { status: 'replied', reply });+ // The reply lands first, unconditionally. Only then is the payout+ // collected, so a wallet the owner dismisses costs them the money and+ // never the answer they already wrote.+ const escrowed = knock.escrow?.state === 'pending' && !knock.escrow.expired;+ const saved = await act(knock.id, { status: 'replied', reply }, { quiet: escrowed });+ if (!escrowed || !saved) return;+ try {+ await collectEscrow({ ...knock, pendingReply: reply }, (status) => {+ send.textContent = `${status}…`;+ });+ } catch (err) {+ showSettingsError(+ `Your reply was sent. The payout was not collected: ${err?.message || 'the wallet did not sign'} You can still collect it until the window closes.`,+ );+ } finally {+ send.disabled = false;+ send.textContent = 'Send reply';+ renderInbox();+ }});li.appendChild(form);area.focus();}-async function act(id, patch) {+/**+ * Apply one inbox action.+ *+ * `quiet` keeps the list on screen exactly as it is. The escrowed reply flow+ * needs it: the reply is saved before the wallet opens, and re-rendering there+ * would tear out the open form the payout status is being written into.+ */+async function act(id, patch, { quiet = false } = {}) {try {const { knock } = await knockApi.actOn(id, patch);state.knocks = state.knocks.map((k) => (k.id === id ? { ...k, ...knock } : k));- renderInbox();+ if (!quiet) renderInbox();if (patch.block) applyOwner(await knockApi.settings());else refreshTotals();+ return true;} catch (err) {showSettingsError(err.message);+ return false;}}