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): let a browser sign every side of an escrowed knock itself
nirholas526d272c611f
diff --git a/contracts/program-tests/tests/knock_escrow_pda.rs b/contracts/program-tests/tests/knock_escrow_pda.rsindex 8d650df1c..adc9d0263 100644--- a/contracts/program-tests/tests/knock_escrow_pda.rs+++ b/contracts/program-tests/tests/knock_escrow_pda.rs@@ -66,3 +66,26 @@ fn account_discriminators_match_the_js_decoder() {assert_eq!(hex(&sha256(b"account:Door")[..8]), EXPECT_DISC_DOOR);assert_eq!(hex(&sha256(b"account:KnockRecord")[..8]), EXPECT_DISC_KNOCK);}++#[test]+fn instruction_discriminators_match_the_browser_client() {+ // Anchor's instruction discriminator is sha256("global:<snake_case_name>")[..8].+ // The browser builds these by hand in src/knock/escrow-program.js, because+ // it signs for the sender and the owner directly rather than going through+ // a server that could move their money. A mismatch here does not fail+ // loudly on-chain; it dispatches to a DIFFERENT instruction or none at all,+ // so both sides pin the same eight bytes.+ for (name, expect) in [+ ("initialize", "afaf6d1f0d989bed"),+ ("set_config", "6c9e9aafd4623442"),+ ("open_door", "0b8c29ba454e37f7"),+ ("set_door", "e3022b8b592a417a"),+ ("knock", "fbd9cc537e9b5da3"),+ ("answer", "48d62c2035de09f4"),+ ("refuse", "c449f3c611fac816"),+ ("reclaim", "2cb1ecf9916da3ba"),+ ] {+ let disc = &ix_data(name, &[])[..8];+ assert_eq!(hex(disc), expect, "discriminator for {name}");+ }+}diff --git a/src/knock/escrow-program.js b/src/knock/escrow-program.jsnew file mode 100644index 000000000..36fc3c7f0--- /dev/null+++ b/src/knock/escrow-program.js@@ -0,0 +1,388 @@+// The knock_escrow program, from the browser.+//+// api/_lib/knock/escrow.js is the READ side: the server derives a knock's+// address and checks what the chain says about it. This is the WRITE side, and+// it lives in the browser on purpose, because three.ws must never be able to+// move an escrowed payment. Every instruction below is signed by the person it+// belongs to: the sender escrows, the owner answers or refuses, and anybody at+// all can crank an expired refund.+//+// The account orders, argument encodings and discriminators here are the ones+// the compiled program accepts. They are pinned against it in+// tests/knock-escrow-program.test.js, which shares fixtures with the Rust suite+// in contracts/program-tests, so a change on either side fails a test instead of+// producing a transaction the program silently rejects at the account layer.+//+// Loaded dynamically (see src/knock/door.js), so the Solana SDKs stay out of the+// bundle for the visitors who only ever read a door.++import { PublicKey, TransactionInstruction, SystemProgram, SYSVAR_RENT_PUBKEY } from '@solana/web3.js';+import { sha256 as nobleSha256 } from '@noble/hashes/sha256';+import {+ getAssociatedTokenAddressSync,+ createAssociatedTokenAccountIdempotentInstruction,+ ASSOCIATED_TOKEN_PROGRAM_ID,+ TOKEN_PROGRAM_ID,+ TOKEN_2022_PROGRAM_ID,+} from '@solana/spl-token';++/** knock_escrow's `declare_id!`. */+export const KNOCK_ESCROW_PROGRAM_ID = 'uVX46U6sGUs6PD3339ZXbTpMyhZwkQhBLPxnvRX9ps7';++/** The mint a door opened from this UI prices itself in. */+export const USDC_MINT = 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v';++/** The program's own reply-window band. A door outside it is refused on-chain. */+export const MIN_REPLY_WINDOW_SECONDS = 60 * 60;+export const MAX_REPLY_WINDOW_SECONDS = 60 * 60 * 24 * 30;++/** The program's price ceiling, in atomic units of the door's mint. */+export const MAX_PRICE_ATOMICS = 1_000_000_000n;++export const KNOCK_STATE_NAME = Object.freeze({ 0: 'pending', 1: 'answered', 2: 'refunded', 3: 'refused' });++const enc = new TextEncoder();+const CONFIG_SEED = enc.encode('config');+const DOOR_SEED = enc.encode('door');+const KNOCK_SEED = enc.encode('knock');+const VAULT_SEED = enc.encode('vault');++const programKey = () => new PublicKey(KNOCK_ESCROW_PROGRAM_ID);+const key = (v) => (v instanceof PublicKey ? v : new PublicKey(v));++/** SHA-256, the digest the program hashes door ids, messages and replies with. */+export function sha256(input) {+ return nobleSha256(typeof input === 'string' ? enc.encode(input) : input);+}++/**+ * A door's 32-byte on-chain id: the SHA-256 of the owner's handle, lowercased.+ *+ * Normalized because the off-chain door is keyed case-insensitively, and+ * hashing the raw string would give `/knock/Ada` and `/knock/ada` two different+ * doors on-chain for one door in the product.+ */+export function doorId(handle) {+ return sha256(String(handle).trim().toLowerCase());+}++export function configPda() {+ return PublicKey.findProgramAddressSync([CONFIG_SEED], programKey())[0];+}++export function doorPda(owner, id) {+ return PublicKey.findProgramAddressSync([DOOR_SEED, key(owner).toBytes(), id], programKey())[0];+}++export function knockPda(door, sender, nonce) {+ return PublicKey.findProgramAddressSync(+ [KNOCK_SEED, key(door).toBytes(), key(sender).toBytes(), u64(nonce)],+ programKey(),+ )[0];+}++export function vaultPda(knock) {+ return PublicKey.findProgramAddressSync([VAULT_SEED, key(knock).toBytes()], programKey())[0];+}++// ── encoding ────────────────────────────────────────────────────────────────++function u64(value) {+ const out = new Uint8Array(8);+ new DataView(out.buffer).setBigUint64(0, BigInt(value), true);+ return out;+}++function i64(value) {+ const out = new Uint8Array(8);+ new DataView(out.buffer).setBigInt64(0, BigInt(value), true);+ return out;+}++function concat(parts) {+ const total = parts.reduce((n, p) => n + p.length, 0);+ const out = new Uint8Array(total);+ let at = 0;+ for (const p of parts) {+ out.set(p, at);+ at += p.length;+ }+ return out;+}++/** Anchor's instruction discriminator: `sha256("global:<name>")[..8]`. */+export function discriminator(name) {+ return sha256(`global:${name}`).slice(0, 8);+}++function data(name, ...args) {+ return Buffer.from(concat([discriminator(name), ...args]));+}++const meta = (pubkey, { signer = false, writable = false } = {}) => ({+ pubkey: key(pubkey),+ isSigner: signer,+ isWritable: writable,+});++// ── instructions ────────────────────────────────────────────────────────────++/**+ * Open a priced door on-chain. The owner signs, and it is their wallet plus the+ * door id that make the door's address, so nobody can open a door in their name.+ */+export function openDoorIx({ owner, mint, priceAtomics, replyWindowSeconds, handle }) {+ const id = doorId(handle);+ return new TransactionInstruction({+ programId: programKey(),+ keys: [+ meta(owner, { signer: true, writable: true }),+ meta(mint),+ meta(doorPda(owner, id), { writable: true }),+ meta(SystemProgram.programId),+ ],+ data: data('open_door', id, u64(priceAtomics), i64(replyWindowSeconds)),+ });+}++/**+ * Reprice a door, change its window, or shut it. Every field is optional, and+ * borsh encodes an `Option<T>` as a 1-byte tag followed by the value.+ *+ * Shutting a door stops new knocks and deliberately leaves the ones already in+ * flight alone: those are owed an answer or a refund either way.+ */+export function setDoorIx({ owner, handle, priceAtomics = null, replyWindowSeconds = null, open = null }) {+ const parts = [];+ parts.push(priceAtomics === null ? Uint8Array.of(0) : concat([Uint8Array.of(1), u64(priceAtomics)]));+ parts.push(replyWindowSeconds === null ? Uint8Array.of(0) : concat([Uint8Array.of(1), i64(replyWindowSeconds)]));+ parts.push(open === null ? Uint8Array.of(0) : Uint8Array.of(1, open ? 1 : 0));+ return new TransactionInstruction({+ programId: programKey(),+ keys: [+ meta(owner, { signer: true }),+ meta(doorPda(owner, doorId(handle)), { writable: true }),+ ],+ data: data('set_door', ...parts),+ });+}++/**+ * Pay a door's price into escrow.+ *+ * `messageHash` is the SHA-256 of the exact message the sender is about to+ * deliver. That hash is what stops a payment being reused for something else:+ * the API refuses to deliver any message whose hash is not the one on-chain.+ */+export function knockIx({ sender, door, mint, senderTokens, nonce, messageHash, tokenProgram = TOKEN_PROGRAM_ID }) {+ const knock = knockPda(door, sender, nonce);+ return new TransactionInstruction({+ programId: programKey(),+ keys: [+ meta(sender, { signer: true, writable: true }),+ meta(configPda()),+ meta(door, { writable: true }),+ meta(mint),+ meta(senderTokens, { writable: true }),+ meta(knock, { writable: true }),+ meta(vaultPda(knock), { writable: true }),+ meta(tokenProgram),+ meta(SystemProgram.programId),+ meta(SYSVAR_RENT_PUBKEY),+ ],+ data: data('knock', u64(nonce), messageHash),+ });+}++/**+ * Answer a knock and take the payment, minus the fee snapshotted when it was+ * made. Only the door's owner can sign this, and only inside the window.+ */+export function answerIx({+ owner,+ door,+ knock,+ mint,+ sender,+ ownerTokens,+ treasuryTokens,+ replyHash,+ tokenProgram = TOKEN_PROGRAM_ID,+}) {+ return new TransactionInstruction({+ programId: programKey(),+ keys: [+ meta(owner, { signer: true }),+ meta(configPda()),+ meta(door, { writable: true }),+ meta(knock, { writable: true }),+ meta(mint),+ meta(vaultPda(knock), { writable: true }),+ meta(ownerTokens, { writable: true }),+ meta(treasuryTokens, { writable: true }),+ meta(sender, { writable: true }),+ meta(tokenProgram),+ ],+ data: data('answer', replyHash),+ });+}++/**+ * Decline a knock outright and hand every unit back. No fee is taken: refusing+ * to engage is not a service anybody should be charged for.+ */+export function refuseIx({ owner, door, knock, mint, sender, senderTokens, tokenProgram = TOKEN_PROGRAM_ID }) {+ return new TransactionInstruction({+ programId: programKey(),+ keys: [+ meta(owner, { signer: true }),+ meta(door, { writable: true }),+ meta(knock, { writable: true }),+ meta(mint),+ meta(vaultPda(knock), { writable: true }),+ meta(senderTokens, { writable: true }),+ meta(sender, { writable: true }),+ meta(tokenProgram),+ ],+ data: data('refuse'),+ });+}++/**+ * Crank an expired knock's refund.+ *+ * The signer is whoever bothers to send it and gets nothing for it: every token+ * goes to the sender's own account and every lamport of rent goes to the+ * sender's own wallet, both address-checked by the program. That is what makes+ * the guarantee real rather than conditional on the sender still being around.+ */+export function reclaimIx({ cranker, door, knock, mint, sender, senderTokens, tokenProgram = TOKEN_PROGRAM_ID }) {+ return new TransactionInstruction({+ programId: programKey(),+ keys: [+ meta(cranker, { signer: true }),+ meta(door, { writable: true }),+ meta(knock, { writable: true }),+ meta(mint),+ meta(vaultPda(knock), { writable: true }),+ meta(senderTokens, { writable: true }),+ meta(sender, { writable: true }),+ meta(tokenProgram),+ ],+ data: data('reclaim'),+ });+}++// ── token accounts ──────────────────────────────────────────────────────────++/** The associated token account, for the token program the mint belongs to. */+export function ataFor(mint, owner, tokenProgram = TOKEN_PROGRAM_ID) {+ return getAssociatedTokenAddressSync(key(mint), key(owner), true, key(tokenProgram), ASSOCIATED_TOKEN_PROGRAM_ID);+}++/**+ * An idempotent create for a token account that must exist before the program+ * can pay into it. Safe to include when it already does, which is why the payout+ * side sends it unconditionally rather than reading the account first.+ */+export function createAtaIfMissingIx({ payer, owner, mint, tokenProgram = TOKEN_PROGRAM_ID }) {+ return createAssociatedTokenAccountIdempotentInstruction(+ key(payer),+ ataFor(mint, owner, tokenProgram),+ key(owner),+ key(mint),+ key(tokenProgram),+ ASSOCIATED_TOKEN_PROGRAM_ID,+ );+}++/** Which token program a mint belongs to, read from the mint account's owner. */+export function tokenProgramForOwner(accountOwner) {+ const owner = String(accountOwner);+ return owner === TOKEN_2022_PROGRAM_ID.toBase58() ? TOKEN_2022_PROGRAM_ID : TOKEN_PROGRAM_ID;+}++// ── account decoding ────────────────────────────────────────────────────────++function accountDiscriminator(name) {+ return sha256(`account:${name}`).slice(0, 8);+}++function sameBytes(a, b) {+ if (a.length !== b.length) return false;+ for (let i = 0; i < a.length; i += 1) if (a[i] !== b[i]) return false;+ return true;+}++function view(data) {+ const bytes = data instanceof Uint8Array ? data : new Uint8Array(data);+ return { bytes, dv: new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength) };+}++const pubkeyAt = (bytes, at) => new PublicKey(bytes.subarray(at, at + 32)).toBase58();+const hexAt = (bytes, at, len) =>+ Array.from(bytes.subarray(at, at + len), (b) => b.toString(16).padStart(2, '0')).join('');++/** Decode a `Config` account: authority 32 | treasury 32 | fee_bps 2 | bump 1. */+export function decodeConfig(data) {+ const { bytes, dv } = view(data);+ if (bytes.length < 75) throw new Error('config account is too small to decode');+ if (!sameBytes(bytes.subarray(0, 8), accountDiscriminator('Config'))) {+ throw new Error('account is not a knock_escrow Config');+ }+ return {+ authority: pubkeyAt(bytes, 8),+ treasury: pubkeyAt(bytes, 40),+ feeBps: dv.getUint16(72, true),+ };+}++/** Decode a `Door` account. Layout mirrors api/_lib/knock/escrow.js. */+export function decodeDoor(data) {+ const { bytes, dv } = view(data);+ if (bytes.length < 154) throw new Error('door account is too small to decode');+ if (!sameBytes(bytes.subarray(0, 8), accountDiscriminator('Door'))) {+ throw new Error('account is not a knock_escrow Door');+ }+ return {+ owner: pubkeyAt(bytes, 8),+ mint: pubkeyAt(bytes, 40),+ doorId: hexAt(bytes, 72, 32),+ price: dv.getBigUint64(104, true),+ replyWindow: Number(dv.getBigInt64(112, true)),+ open: bytes[120] === 1,+ knocks: dv.getBigUint64(121, true),+ answered: dv.getBigUint64(129, true),+ refunded: dv.getBigUint64(137, true),+ earned: dv.getBigUint64(145, true),+ };+}++/** Decode a `KnockRecord` account. Layout mirrors api/_lib/knock/escrow.js. */+export function decodeKnock(data) {+ const { bytes, dv } = view(data);+ if (bytes.length < 205) throw new Error('knock account is too small to decode');+ if (!sameBytes(bytes.subarray(0, 8), accountDiscriminator('KnockRecord'))) {+ throw new Error('account is not a knock_escrow KnockRecord');+ }+ const state = bytes[202];+ return {+ door: pubkeyAt(bytes, 8),+ sender: pubkeyAt(bytes, 40),+ mint: pubkeyAt(bytes, 72),+ amount: dv.getBigUint64(104, true),+ feeBps: dv.getUint16(112, true),+ nonce: dv.getBigUint64(114, true),+ messageHash: hexAt(bytes, 122, 32),+ replyHash: hexAt(bytes, 154, 32),+ createdAt: Number(dv.getBigInt64(186, true)),+ expiresAt: Number(dv.getBigInt64(194, true)),+ state,+ stateName: KNOCK_STATE_NAME[state] || 'unknown',+ };+}++/** Hex, for comparing a message against the hash a knock was paid against. */+export function hex(bytes) {+ return Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join('');+}diff --git a/tests/knock-escrow-program.test.js b/tests/knock-escrow-program.test.jsnew file mode 100644index 000000000..b085c1aa4--- /dev/null+++ b/tests/knock-escrow-program.test.js@@ -0,0 +1,348 @@+// The browser's knock_escrow client, pinned against the program it talks to.+//+// src/knock/escrow-program.js builds transactions the sender and the door owner+// sign with their own wallets, because three.ws holds no key that can move an+// escrowed payment. That design means a wrong byte here is not caught by any+// server: the wallet signs whatever it is handed, and the program either+// dispatches to a different instruction or rejects the transaction at the+// account layer with an error nobody can read.+//+// So everything that has to agree with the program is asserted here against the+// same fixtures the Rust suite pins in contracts/program-tests/tests/+// knock_escrow_pda.rs, and the account orders below are the ones the compiled+// program accepts in contracts/program-tests/tests/knock_escrow.rs, which runs+// them against real bytecode.++import { describe, it, expect } from 'vitest';+import { PublicKey, SystemProgram, SYSVAR_RENT_PUBKEY } from '@solana/web3.js';+import { TOKEN_PROGRAM_ID, TOKEN_2022_PROGRAM_ID } from '@solana/spl-token';+import {+ KNOCK_ESCROW_PROGRAM_ID,+ USDC_MINT,+ ataFor,+ answerIx,+ configPda,+ createAtaIfMissingIx,+ decodeConfig,+ decodeDoor,+ decodeKnock,+ discriminator,+ doorId,+ doorPda,+ hex,+ knockIx,+ knockPda,+ openDoorIx,+ reclaimIx,+ refuseIx,+ setDoorIx,+ sha256,+ tokenProgramForOwner,+ vaultPda,+} from '../src/knock/escrow-program.js';++const OWNER = '11111111111111111111111111111111';+const SENDER = 'TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA';+const HANDLE = 'nirholas';+const NONCE = 7;++// Produced by the program's own find_program_address calls.+const EXPECT = {+ doorIdHex: 'b3d92abfa95658f0d35e6b20752e8ca9ba4fad9e9bbc62352c999c75853fb53d',+ config: '7jAKSyTgRC8aGAjdYkMjQMPv7uh3uJX869GRXkBTUPkZ',+ door: 'DMDKj3mSoM5rjsftGAhSbLbrAWMwmFxEkHDLsx997vk8',+ knock: '8WvZ64SL6JNss232BC78aapB2M6MjE95f9LtWfYYRn5t',+ vault: '8LLgeTjcL4ZiU1MwoFWR4DkTkYnXruBsorMG7MKWbSwv',+};++const doorKey = () => doorPda(OWNER, doorId(HANDLE));+const knockKey = () => knockPda(doorKey(), SENDER, NONCE);++/** [address, isSigner, isWritable] for every account, in order. */+const shape = (ix) => ix.keys.map((k) => [k.pubkey.toBase58(), k.isSigner, k.isWritable]);++describe('addresses', () => {+ it('derives the same PDAs the program does', () => {+ expect(hex(doorId(HANDLE))).toBe(EXPECT.doorIdHex);+ expect(configPda().toBase58()).toBe(EXPECT.config);+ expect(doorKey().toBase58()).toBe(EXPECT.door);+ expect(knockKey().toBase58()).toBe(EXPECT.knock);+ expect(vaultPda(knockKey()).toBase58()).toBe(EXPECT.vault);+ });++ it('normalizes the handle, so one door is never two doors on-chain', () => {+ expect(hex(doorId('NirHolas'))).toBe(EXPECT.doorIdHex);+ expect(hex(doorId(' nirholas '))).toBe(EXPECT.doorIdHex);+ });++ it('agrees with the server-side read client', async () => {+ const server = await import('../api/_lib/knock/escrow.js');+ expect(server.KNOCK_ESCROW_PROGRAM_ID).toBe(KNOCK_ESCROW_PROGRAM_ID);+ expect(server.doorId(HANDLE).toString('hex')).toBe(hex(doorId(HANDLE)));+ expect(server.doorPda(OWNER, server.doorId(HANDLE)).toBase58()).toBe(doorKey().toBase58());+ expect(server.knockPda(doorKey(), SENDER, NONCE).toBase58()).toBe(knockKey().toBase58());+ expect(server.vaultPda(knockKey()).toBase58()).toBe(vaultPda(knockKey()).toBase58());+ });+});++describe('instruction discriminators', () => {+ // Same eight bytes the Rust suite pins. A wrong one dispatches somewhere else.+ it.each([+ ['open_door', '0b8c29ba454e37f7'],+ ['set_door', 'e3022b8b592a417a'],+ ['knock', 'fbd9cc537e9b5da3'],+ ['answer', '48d62c2035de09f4'],+ ['refuse', 'c449f3c611fac816'],+ ['reclaim', '2cb1ecf9916da3ba'],+ ])('%s', (name, expected) => {+ expect(hex(discriminator(name))).toBe(expected);+ });+});++describe('knock', () => {+ const senderTokens = ataFor(USDC_MINT, SENDER);+ const messageHash = sha256('two questions about the facilitator');++ it('lists the accounts the program expects, in order', () => {+ const ix = knockIx({+ sender: SENDER,+ door: doorKey(),+ mint: USDC_MINT,+ senderTokens,+ nonce: NONCE,+ messageHash,+ });+ expect(ix.programId.toBase58()).toBe(KNOCK_ESCROW_PROGRAM_ID);+ expect(shape(ix)).toEqual([+ [SENDER, true, true],+ [EXPECT.config, false, false],+ [EXPECT.door, false, true],+ [USDC_MINT, false, false],+ [senderTokens.toBase58(), false, true],+ [EXPECT.knock, false, true],+ [EXPECT.vault, false, true],+ [TOKEN_PROGRAM_ID.toBase58(), false, false],+ [SystemProgram.programId.toBase58(), false, false],+ [SYSVAR_RENT_PUBKEY.toBase58(), false, false],+ ]);+ });++ it('carries the nonce and the message hash, and nothing else', () => {+ const ix = knockIx({+ sender: SENDER,+ door: doorKey(),+ mint: USDC_MINT,+ senderTokens,+ nonce: NONCE,+ messageHash,+ });+ expect(ix.data).toHaveLength(8 + 8 + 32);+ expect(hex(ix.data.subarray(0, 8))).toBe('fbd9cc537e9b5da3');+ expect(ix.data.readBigUInt64LE(8)).toBe(7n);+ expect(hex(ix.data.subarray(16))).toBe(hex(messageHash));+ });++ it('is a different knock for a different nonce, so one sender can knock twice', () => {+ const first = knockIx({ sender: SENDER, door: doorKey(), mint: USDC_MINT, senderTokens, nonce: 7, messageHash });+ const second = knockIx({ sender: SENDER, door: doorKey(), mint: USDC_MINT, senderTokens, nonce: 8, messageHash });+ expect(shape(first)[5][0]).not.toBe(shape(second)[5][0]);+ });++ it('signs with the token program the door mint belongs to, for Token-2022', () => {+ const ix = knockIx({+ sender: SENDER,+ door: doorKey(),+ mint: USDC_MINT,+ senderTokens,+ nonce: NONCE,+ messageHash,+ tokenProgram: TOKEN_2022_PROGRAM_ID,+ });+ expect(shape(ix)[7][0]).toBe(TOKEN_2022_PROGRAM_ID.toBase58());+ });+});++describe('open_door', () => {+ it('lists the accounts the program expects, in order', () => {+ const ix = openDoorIx({+ owner: OWNER,+ mint: USDC_MINT,+ priceAtomics: 50_000n,+ replyWindowSeconds: 86_400,+ handle: HANDLE,+ });+ expect(shape(ix)).toEqual([+ [OWNER, true, true],+ [USDC_MINT, false, false],+ [EXPECT.door, false, true],+ [SystemProgram.programId.toBase58(), false, false],+ ]);+ });++ it('encodes the door id, then the price, then the window', () => {+ const ix = openDoorIx({+ owner: OWNER,+ mint: USDC_MINT,+ priceAtomics: 50_000n,+ replyWindowSeconds: 86_400,+ handle: HANDLE,+ });+ expect(ix.data).toHaveLength(8 + 32 + 8 + 8);+ expect(hex(ix.data.subarray(8, 40))).toBe(EXPECT.doorIdHex);+ expect(ix.data.readBigUInt64LE(40)).toBe(50_000n);+ expect(ix.data.readBigInt64LE(48)).toBe(86_400n);+ });+});++describe('set_door', () => {+ // borsh encodes Option<T> as a 1-byte tag then the value, so a patch that+ // only shuts the door must not smuggle a price change in beside it.+ it('shuts a door without touching its price or window', () => {+ const ix = setDoorIx({ owner: OWNER, handle: HANDLE, open: false });+ expect(Array.from(ix.data.subarray(8))).toEqual([0, 0, 1, 0]);+ });++ it('reprices without shutting', () => {+ const ix = setDoorIx({ owner: OWNER, handle: HANDLE, priceAtomics: 250_000n });+ expect(ix.data[8]).toBe(1);+ expect(ix.data.readBigUInt64LE(9)).toBe(250_000n);+ expect(ix.data[17]).toBe(0); // window: None+ expect(ix.data[18]).toBe(0); // open: None+ });+});++describe('answer', () => {+ it('lists the accounts the program expects, in order', () => {+ const ownerTokens = ataFor(USDC_MINT, OWNER);+ const treasuryTokens = ataFor(USDC_MINT, SENDER);+ const ix = answerIx({+ owner: OWNER,+ door: doorKey(),+ knock: knockKey(),+ mint: USDC_MINT,+ sender: SENDER,+ ownerTokens,+ treasuryTokens,+ replyHash: sha256('here is my reply'),+ });+ expect(shape(ix)).toEqual([+ [OWNER, true, false],+ [EXPECT.config, false, false],+ [EXPECT.door, false, true],+ [EXPECT.knock, false, true],+ [USDC_MINT, false, false],+ [EXPECT.vault, false, true],+ [ownerTokens.toBase58(), false, true],+ [treasuryTokens.toBase58(), false, true],+ // The rent destination is the sender, and the program address-checks+ // it, so a mis-ordered account here fails rather than paying a stranger.+ [SENDER, false, true],+ [TOKEN_PROGRAM_ID.toBase58(), false, false],+ ]);+ expect(ix.data).toHaveLength(8 + 32);+ });+});++describe('refuse and reclaim', () => {+ const common = {+ door: doorKey(),+ knock: knockKey(),+ mint: USDC_MINT,+ sender: SENDER,+ senderTokens: ataFor(USDC_MINT, SENDER),+ };++ it('refuse is owner-signed and carries no arguments', () => {+ const ix = refuseIx({ owner: OWNER, ...common });+ expect(shape(ix)).toEqual([+ [OWNER, true, false],+ [EXPECT.door, false, true],+ [EXPECT.knock, false, true],+ [USDC_MINT, false, false],+ [EXPECT.vault, false, true],+ [common.senderTokens.toBase58(), false, true],+ [SENDER, false, true],+ [TOKEN_PROGRAM_ID.toBase58(), false, false],+ ]);+ expect(ix.data).toHaveLength(8);+ });++ it('reclaim takes the same accounts but any signer at all', () => {+ const cranker = 'SysvarRent111111111111111111111111111111111';+ const ix = reclaimIx({ cranker, ...common });+ expect(shape(ix)[0]).toEqual([cranker, true, false]);+ // Everything after the signer is identical to refuse: the crank is not a+ // different settlement, it is the same refund with a different signer.+ expect(shape(ix).slice(1)).toEqual(shape(refuseIx({ owner: OWNER, ...common })).slice(1));+ expect(ix.data).toHaveLength(8);+ });+});++describe('token accounts', () => {+ it('creates a payout account idempotently, so answering never fails on a missing ATA', () => {+ const ix = createAtaIfMissingIx({ payer: OWNER, owner: OWNER, mint: USDC_MINT });+ expect(ix.keys[1].pubkey.toBase58()).toBe(ataFor(USDC_MINT, OWNER).toBase58());+ // Tag 1 is CreateIdempotent; tag 0 would throw when the account exists.+ expect(ix.data[0]).toBe(1);+ });++ it('picks the token program from the mint account owner', () => {+ expect(tokenProgramForOwner(TOKEN_2022_PROGRAM_ID.toBase58()).toBase58()).toBe(+ TOKEN_2022_PROGRAM_ID.toBase58(),+ );+ expect(tokenProgramForOwner(TOKEN_PROGRAM_ID.toBase58()).toBase58()).toBe(TOKEN_PROGRAM_ID.toBase58());+ });+});++describe('account decoding', () => {+ function encodeConfig({ treasury = SENDER, feeBps = 250 } = {}) {+ const buf = Buffer.alloc(75);+ Buffer.from('9b0caae01efacc82', 'hex').copy(buf, 0); // sha256("account:Config")[..8]+ new PublicKey(OWNER).toBuffer().copy(buf, 8);+ new PublicKey(treasury).toBuffer().copy(buf, 40);+ buf.writeUInt16LE(feeBps, 72);+ return buf;+ }++ it('reads the treasury an answer has to pay the fee to', () => {+ // The discriminator is recomputed here rather than trusted, because the+ // fixture above is only correct if it matches sha256("account:Config").+ const expected = hex(sha256('account:Config').slice(0, 8));+ expect(hex(encodeConfig().subarray(0, 8))).toBe(expected);+ const config = decodeConfig(encodeConfig());+ expect(config.treasury).toBe(SENDER);+ expect(config.feeBps).toBe(250);+ });++ it('refuses an account of the wrong type rather than reading its bytes', () => {+ const wrong = encodeConfig();+ wrong.writeUInt8(0, 0);+ expect(() => decodeConfig(wrong)).toThrow(/not a knock_escrow Config/);+ expect(() => decodeDoor(Buffer.alloc(20))).toThrow(/too small/);+ expect(() => decodeKnock(Buffer.alloc(20))).toThrow(/too small/);+ });++ it('decodes a knock the same way the server does', async () => {+ const server = await import('../api/_lib/knock/escrow.js');+ const buf = Buffer.alloc(205);+ Buffer.from('f9c621b06c558191', 'hex').copy(buf, 0);+ new PublicKey(EXPECT.door).toBuffer().copy(buf, 8);+ new PublicKey(SENDER).toBuffer().copy(buf, 40);+ new PublicKey(USDC_MINT).toBuffer().copy(buf, 72);+ buf.writeBigUInt64LE(50_000n, 104);+ buf.writeUInt16LE(250, 112);+ buf.writeBigUInt64LE(7n, 114);+ Buffer.from(server.sha256('hello')).copy(buf, 122);+ buf.writeBigInt64LE(1_767_225_600n, 186);+ buf.writeBigInt64LE(1_767_312_000n, 194);+ buf[202] = 0;++ const mine = decodeKnock(buf);+ const theirs = server.decodeKnock(buf);+ expect(mine.sender).toBe(theirs.sender);+ expect(mine.amount).toBe(theirs.amount);+ expect(mine.messageHash).toBe(theirs.messageHash);+ expect(mine.expiresAt).toBe(theirs.expiresAt);+ expect(mine.stateName).toBe('pending');+ });+});