@redditech/x402-solana 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/CHANGELOG.md +84 -0
  2. package/LICENSE +21 -0
  3. package/README.md +301 -2
  4. package/dist/budget-policy.d.ts +68 -0
  5. package/dist/budget-policy.js +234 -0
  6. package/dist/buyer.d.ts +54 -0
  7. package/dist/buyer.js +147 -0
  8. package/dist/client.d.ts +80 -0
  9. package/dist/client.js +225 -0
  10. package/dist/direct-auth.d.ts +94 -0
  11. package/dist/direct-auth.js +120 -0
  12. package/dist/direct-payment.d.ts +33 -0
  13. package/dist/direct-payment.js +65 -0
  14. package/dist/ed25519.d.ts +6 -0
  15. package/dist/ed25519.js +42 -0
  16. package/dist/escrow-http.d.ts +125 -0
  17. package/dist/escrow-http.js +192 -0
  18. package/dist/escrow-readiness.d.ts +132 -0
  19. package/dist/escrow-readiness.js +171 -0
  20. package/dist/index.d.ts +26 -0
  21. package/dist/index.js +42 -0
  22. package/dist/jupiter.d.ts +36 -0
  23. package/dist/jupiter.js +120 -0
  24. package/dist/metered.d.ts +58 -0
  25. package/dist/metered.js +82 -0
  26. package/dist/middleware.d.ts +9 -0
  27. package/dist/middleware.js +71 -0
  28. package/dist/nonce.d.ts +57 -0
  29. package/dist/nonce.js +123 -0
  30. package/dist/payment.d.ts +202 -0
  31. package/dist/payment.js +967 -0
  32. package/dist/provider.d.ts +371 -0
  33. package/dist/provider.js +492 -0
  34. package/dist/rating.d.ts +552 -0
  35. package/dist/rating.js +829 -0
  36. package/dist/session-auth.d.ts +168 -0
  37. package/dist/session-auth.js +341 -0
  38. package/dist/session.d.ts +220 -0
  39. package/dist/session.js +297 -0
  40. package/dist/spl-token-observer.d.ts +70 -0
  41. package/dist/spl-token-observer.js +319 -0
  42. package/dist/token-escrow.d.ts +125 -0
  43. package/dist/token-escrow.js +163 -0
  44. package/dist/types.d.ts +148 -0
  45. package/dist/types.js +2 -0
  46. package/package.json +109 -4
@@ -0,0 +1,319 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.SPL_MEMO_PROGRAM_ID = exports.TOKEN_2022_PROGRAM_ID = exports.SPL_TOKEN_PROGRAM_ID = exports.SPL_TRANSFER_CHECKED_OBSERVER_VERSION = exports.SPL_TRANSFER_CHECKED_OBSERVATION_SCHEMA_VERSION = void 0;
4
+ exports.verifySplTransferCheckedObservation = verifySplTransferCheckedObservation;
5
+ exports.SPL_TRANSFER_CHECKED_OBSERVATION_SCHEMA_VERSION = 'reddi.svm-spl-transfer-checked-observation.v1';
6
+ exports.SPL_TRANSFER_CHECKED_OBSERVER_VERSION = 'reddi.x402-solana.spl-transfer-checked-observer.v1';
7
+ exports.SPL_TOKEN_PROGRAM_ID = 'TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA';
8
+ exports.TOKEN_2022_PROGRAM_ID = 'TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb';
9
+ exports.SPL_MEMO_PROGRAM_ID = 'MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr';
10
+ const POSITIVE_BASE_UNITS = /^[1-9]\d*$/;
11
+ const MEMO_PROGRAM_IDS = new Set([exports.SPL_MEMO_PROGRAM_ID, 'Memo1UhkJRfHyvLMcVucJwxXeuD728EqVDDwQDxFMNo']);
12
+ async function verifySplTransferCheckedObservation(input) {
13
+ const malformed = validateExpected(input.expected, input.commitment);
14
+ if (malformed)
15
+ return malformed;
16
+ const parsed = asRecord(input.parsedTransaction);
17
+ if (!parsed)
18
+ return failure('missing_transaction', 'parsed transaction is required');
19
+ const meta = asRecord(parsed.meta);
20
+ if (!meta)
21
+ return failure('missing_transaction', 'parsed transaction metadata is required');
22
+ if (meta.err !== null && meta.err !== undefined) {
23
+ return failure('failed_transaction', 'transaction metadata reports failure', null, meta.err);
24
+ }
25
+ if (!Number.isSafeInteger(parsed.slot) || Number(parsed.slot) <= 0) {
26
+ return failure('missing_confirmation_metadata', 'transaction must include a positive slot confirmation metadata value');
27
+ }
28
+ if (parsed.blockTime !== undefined && parsed.blockTime !== null && (!Number.isSafeInteger(parsed.blockTime) || Number(parsed.blockTime) <= 0)) {
29
+ return failure('missing_confirmation_metadata', 'transaction blockTime must be a positive integer when the node reports one', null, parsed.blockTime);
30
+ }
31
+ const signatures = asArray(asRecord(parsed.transaction)?.signatures);
32
+ const transactionSignature = signatures ? stringValue(signatures[0]) : undefined;
33
+ if (transactionSignature !== input.expected.signature) {
34
+ return failure('wrong_signature', 'parsed transaction first signature must equal the expected payment transaction signature', input.expected.signature, transactionSignature ?? signatures);
35
+ }
36
+ const instructions = collectInstructions(parsed);
37
+ const transferChecked = instructions.filter((item) => isTransferChecked(item.instruction));
38
+ if (transferChecked.length === 0)
39
+ return failure('no_transfer_checked', 'transaction contains no parsed SPL TransferChecked instruction');
40
+ const candidates = transferChecked.map((collected) => buildCandidate(parsed, collected, input.expected));
41
+ const matches = candidates.filter((candidate) => candidateMatches(candidate, input.expected));
42
+ if (matches.length === 0)
43
+ return candidateFailure(candidates, input.expected);
44
+ if (matches.length > 1) {
45
+ return failure('duplicate_matching_transfer', 'transaction contains more than one matching TransferChecked payment', 1, matches.length);
46
+ }
47
+ const memo = extractMemo(instructions, input.expected.memo);
48
+ if (input.expected.memoRequired === true || input.expected.memo !== undefined) {
49
+ if (!input.expected.memo)
50
+ return failure('malformed_expected_payment', 'memoRequired requires an expected memo value');
51
+ if (!memo.present)
52
+ return failure('missing_memo', 'expected memo binding is missing', input.expected.memo);
53
+ if (!memo.matched)
54
+ return failure('memo_mismatch', 'transaction memo does not match the expected payment binding', input.expected.memo, memo.values);
55
+ }
56
+ const match = matches[0];
57
+ if (input.replayStore) {
58
+ const replayKey = `spl-transfer-checked:${replayNetworkKey(input.expected.network)}:${input.expected.signature}:${match.collected.instructionIndex}`;
59
+ const accepted = await input.replayStore.checkAndStore(replayKey);
60
+ if (!accepted)
61
+ return failure('replay_detected', 'payment transfer has already been accepted by the replay store', replayKey);
62
+ }
63
+ const observation = {
64
+ schemaVersion: exports.SPL_TRANSFER_CHECKED_OBSERVATION_SCHEMA_VERSION,
65
+ verifierVersion: input.verifierVersion ?? exports.SPL_TRANSFER_CHECKED_OBSERVER_VERSION,
66
+ network: input.expected.network,
67
+ signature: input.expected.signature,
68
+ slot: Number(parsed.slot),
69
+ blockTime: typeof parsed.blockTime === 'number' ? Number(parsed.blockTime) : undefined,
70
+ commitment: input.commitment,
71
+ instructionIndex: match.collected.instructionIndex,
72
+ innerInstruction: match.collected.innerInstruction,
73
+ sourceTokenAccount: match.sourceTokenAccount,
74
+ destinationTokenAccount: match.destinationTokenAccount ?? input.expected.destinationTokenAccount ?? '',
75
+ destinationOwner: input.expected.payTo,
76
+ authority: match.authority,
77
+ mint: input.expected.mint,
78
+ tokenProgram: input.expected.tokenProgram,
79
+ amountBaseUnits: input.expected.amountBaseUnits,
80
+ decimals: match.decimals,
81
+ memo: memo.matched ? input.expected.memo : undefined,
82
+ paymentIntentId: input.expected.paymentIntentId,
83
+ evidence: {
84
+ source: input.evidenceSource ?? 'parsed-transaction-fixture',
85
+ grantEligible: input.grantEligible ?? false,
86
+ },
87
+ };
88
+ return { ok: true, observation };
89
+ }
90
+ function validateExpected(expected, commitment) {
91
+ if (!expected || typeof expected !== 'object')
92
+ return failure('malformed_expected_payment', 'expected payment terms are required');
93
+ if (!isNonEmptyString(expected.network))
94
+ return failure('malformed_expected_payment', 'expected network is required');
95
+ if (!isNonEmptyString(expected.signature))
96
+ return failure('malformed_expected_payment', 'expected signature is required');
97
+ if (!isNonEmptyString(expected.mint))
98
+ return failure('malformed_expected_payment', 'expected mint is required');
99
+ if (!isNonEmptyString(expected.tokenProgram))
100
+ return failure('malformed_expected_payment', 'expected token program is required');
101
+ if (!isNonEmptyString(expected.payTo))
102
+ return failure('malformed_expected_payment', 'expected payee owner is required');
103
+ if (!isNonEmptyString(expected.amountBaseUnits) || !POSITIVE_BASE_UNITS.test(expected.amountBaseUnits)) {
104
+ return failure('malformed_expected_payment', 'expected amount must be a positive integer base-unit string');
105
+ }
106
+ if (expected.destinationTokenAccount !== undefined && !isNonEmptyString(expected.destinationTokenAccount)) {
107
+ return failure('malformed_expected_payment', 'expected destination token account must be non-empty when present');
108
+ }
109
+ if (expected.authority !== undefined && !isNonEmptyString(expected.authority)) {
110
+ return failure('malformed_expected_payment', 'expected authority must be non-empty when present');
111
+ }
112
+ if (expected.decimals !== undefined && (!Number.isSafeInteger(expected.decimals) || expected.decimals < 0)) {
113
+ return failure('malformed_expected_payment', 'expected decimals must be a non-negative safe integer');
114
+ }
115
+ if (expected.memo !== undefined && !isNonEmptyString(expected.memo)) {
116
+ return failure('malformed_expected_payment', 'expected memo must be non-empty when present');
117
+ }
118
+ if (!['confirmed', 'finalized'].includes(String(commitment))) {
119
+ return failure('missing_confirmation_metadata', 'commitment must be confirmed or finalized');
120
+ }
121
+ return undefined;
122
+ }
123
+ function collectInstructions(parsed) {
124
+ const output = [];
125
+ const outer = asArray(asRecord(asRecord(parsed.transaction)?.message)?.instructions);
126
+ if (outer) {
127
+ outer.forEach((instruction, index) => {
128
+ if (asRecord(instruction))
129
+ output.push({ instruction: instruction, instructionIndex: String(index), innerInstruction: false });
130
+ });
131
+ }
132
+ const innerGroups = asArray(asRecord(parsed.meta)?.innerInstructions);
133
+ if (innerGroups) {
134
+ innerGroups.forEach((group) => {
135
+ const record = asRecord(group);
136
+ if (!record)
137
+ return;
138
+ const parentIndex = Number.isSafeInteger(record.index) ? String(record.index) : 'unknown';
139
+ const inner = asArray(record.instructions);
140
+ if (!inner)
141
+ return;
142
+ inner.forEach((instruction, index) => {
143
+ if (asRecord(instruction)) {
144
+ output.push({ instruction: instruction, instructionIndex: `${parentIndex}.${index}`, innerInstruction: true });
145
+ }
146
+ });
147
+ });
148
+ }
149
+ return output;
150
+ }
151
+ function buildCandidate(parsed, collected, expected) {
152
+ const parsedInstruction = asRecord(collected.instruction.parsed);
153
+ const info = asRecord(parsedInstruction?.info) ?? {};
154
+ const tokenAmount = asRecord(info.tokenAmount);
155
+ const destinationTokenAccount = stringValue(info.destination);
156
+ const mint = stringValue(info.mint);
157
+ const amountBaseUnits = stringValue(tokenAmount?.amount) ?? stringValue(info.amount);
158
+ const programId = publicKeyString(collected.instruction.programId);
159
+ const candidate = {
160
+ collected,
161
+ info,
162
+ tokenAmount,
163
+ programId,
164
+ sourceTokenAccount: stringValue(info.source),
165
+ destinationTokenAccount,
166
+ authority: stringValue(info.authority),
167
+ mint,
168
+ amountBaseUnits,
169
+ decimals: numberValue(tokenAmount?.decimals),
170
+ ownerStatus: destinationTokenAccount
171
+ ? tokenAccountOwnedBy(parsed, destinationTokenAccount, expected)
172
+ : { ok: false, reason: 'wrong_destination', actual: undefined },
173
+ };
174
+ return candidate;
175
+ }
176
+ function candidateMatches(candidate, expected) {
177
+ if (candidate.programId !== expected.tokenProgram)
178
+ return false;
179
+ if (candidate.mint !== expected.mint)
180
+ return false;
181
+ if (expected.destinationTokenAccount !== undefined && candidate.destinationTokenAccount !== expected.destinationTokenAccount)
182
+ return false;
183
+ if (!candidate.ownerStatus.ok)
184
+ return false;
185
+ if (candidate.amountBaseUnits !== expected.amountBaseUnits)
186
+ return false;
187
+ if (expected.decimals !== undefined && candidate.decimals !== expected.decimals)
188
+ return false;
189
+ if (expected.authority !== undefined && candidate.authority !== expected.authority)
190
+ return false;
191
+ return true;
192
+ }
193
+ function candidateFailure(candidates, expected) {
194
+ const withExpectedProgram = candidates.filter((candidate) => candidate.programId === expected.tokenProgram);
195
+ if (withExpectedProgram.length === 0) {
196
+ return failure('wrong_token_program', 'no TransferChecked instruction used the expected token program', expected.tokenProgram, candidates.map((candidate) => candidate.programId));
197
+ }
198
+ const withExpectedMint = withExpectedProgram.filter((candidate) => candidate.mint === expected.mint);
199
+ if (withExpectedMint.length === 0) {
200
+ return failure('wrong_mint', 'no TransferChecked instruction used the expected mint', expected.mint, withExpectedProgram.map((candidate) => candidate.mint));
201
+ }
202
+ const withExpectedDestination = expected.destinationTokenAccount === undefined
203
+ ? withExpectedMint
204
+ : withExpectedMint.filter((candidate) => candidate.destinationTokenAccount === expected.destinationTokenAccount);
205
+ if (withExpectedDestination.length === 0) {
206
+ return failure('wrong_destination', 'no TransferChecked instruction paid the expected destination token account', expected.destinationTokenAccount, withExpectedMint.map((candidate) => candidate.destinationTokenAccount));
207
+ }
208
+ const withExpectedOwner = withExpectedDestination.filter((candidate) => candidate.ownerStatus.ok);
209
+ if (withExpectedOwner.length === 0) {
210
+ const firstOwnerFailure = withExpectedDestination[0]?.ownerStatus;
211
+ if (firstOwnerFailure && !firstOwnerFailure.ok) {
212
+ return failure(firstOwnerFailure.reason, 'destination token account is not owned by the expected payee for the expected mint/program', expected.payTo, firstOwnerFailure.actual);
213
+ }
214
+ return failure('wrong_payee', 'destination token account is not owned by the expected payee for the expected mint/program', expected.payTo);
215
+ }
216
+ const withExpectedAmount = withExpectedOwner.filter((candidate) => candidate.amountBaseUnits === expected.amountBaseUnits);
217
+ if (withExpectedAmount.length === 0) {
218
+ return failure('wrong_amount', 'no TransferChecked instruction used the exact expected base-unit amount', expected.amountBaseUnits, withExpectedOwner.map((candidate) => candidate.amountBaseUnits));
219
+ }
220
+ if (expected.decimals !== undefined && withExpectedAmount.every((candidate) => candidate.decimals !== expected.decimals)) {
221
+ return failure('wrong_decimals', 'no TransferChecked instruction used the expected decimals', expected.decimals, withExpectedAmount.map((candidate) => candidate.decimals));
222
+ }
223
+ if (expected.authority !== undefined && withExpectedAmount.every((candidate) => candidate.authority !== expected.authority)) {
224
+ return failure('wrong_authority', 'no TransferChecked instruction used the expected transfer authority', expected.authority, withExpectedAmount.map((candidate) => candidate.authority));
225
+ }
226
+ return failure('wrong_amount', 'transaction does not contain a TransferChecked instruction satisfying the expected payment terms');
227
+ }
228
+ function tokenAccountOwnedBy(parsed, tokenAccount, expected) {
229
+ const postTokenBalances = asArray(asRecord(parsed.meta)?.postTokenBalances);
230
+ if (!postTokenBalances)
231
+ return { ok: false, reason: 'wrong_destination', actual: 'missing_post_token_balances' };
232
+ for (const item of postTokenBalances) {
233
+ const balance = asRecord(item);
234
+ if (!balance)
235
+ continue;
236
+ const balanceAccount = accountKeyAt(parsed, balance.accountIndex);
237
+ if (balanceAccount !== tokenAccount)
238
+ continue;
239
+ if (balance.owner !== expected.payTo)
240
+ return { ok: false, reason: 'wrong_payee', actual: balance.owner };
241
+ if (balance.mint !== expected.mint)
242
+ return { ok: false, reason: 'wrong_mint', actual: balance.mint };
243
+ if (balance.programId !== undefined && balance.programId !== expected.tokenProgram) {
244
+ return { ok: false, reason: 'wrong_token_program', actual: balance.programId };
245
+ }
246
+ return { ok: true, owner: expected.payTo };
247
+ }
248
+ return { ok: false, reason: 'wrong_destination', actual: tokenAccount };
249
+ }
250
+ function accountKeyAt(parsed, accountIndex) {
251
+ if (!Number.isSafeInteger(accountIndex))
252
+ return undefined;
253
+ const accountKeys = asArray(asRecord(asRecord(parsed.transaction)?.message)?.accountKeys);
254
+ const key = accountKeys?.[Number(accountIndex)];
255
+ return publicKeyString(key);
256
+ }
257
+ function extractMemo(instructions, expectedMemo) {
258
+ const values = [];
259
+ for (const { instruction } of instructions) {
260
+ const programId = publicKeyString(instruction.programId);
261
+ const program = stringValue(instruction.program);
262
+ if (!programId || !MEMO_PROGRAM_IDS.has(programId)) {
263
+ if (program !== 'spl-memo')
264
+ continue;
265
+ }
266
+ const parsed = instruction.parsed;
267
+ if (typeof parsed === 'string') {
268
+ values.push(parsed);
269
+ continue;
270
+ }
271
+ const parsedRecord = asRecord(parsed);
272
+ const info = parsedRecord ? parsedRecord.info : undefined;
273
+ if (typeof info === 'string')
274
+ values.push(info);
275
+ if (asRecord(info) && typeof asRecord(info)?.memo === 'string')
276
+ values.push(String(asRecord(info)?.memo));
277
+ }
278
+ return { present: values.length > 0, matched: expectedMemo !== undefined && values.includes(expectedMemo), values };
279
+ }
280
+ function isTransferChecked(instruction) {
281
+ const parsed = asRecord(instruction.parsed);
282
+ return parsed?.type === 'transferChecked';
283
+ }
284
+ function publicKeyString(value) {
285
+ if (typeof value === 'string')
286
+ return value;
287
+ const record = asRecord(value);
288
+ if (!record)
289
+ return undefined;
290
+ if (typeof record.pubkey === 'string')
291
+ return record.pubkey;
292
+ const pubkeyRecord = asRecord(record.pubkey);
293
+ if (pubkeyRecord && typeof pubkeyRecord.toString === 'function')
294
+ return String(pubkeyRecord.toString());
295
+ if (typeof record.toString === 'function' && record.toString !== Object.prototype.toString)
296
+ return String(record.toString());
297
+ return undefined;
298
+ }
299
+ function stringValue(value) {
300
+ return typeof value === 'string' && value.length > 0 ? value : undefined;
301
+ }
302
+ function numberValue(value) {
303
+ return Number.isSafeInteger(value) ? Number(value) : undefined;
304
+ }
305
+ function asRecord(value) {
306
+ return value !== null && typeof value === 'object' && !Array.isArray(value) ? value : undefined;
307
+ }
308
+ function asArray(value) {
309
+ return Array.isArray(value) ? value : undefined;
310
+ }
311
+ function isNonEmptyString(value) {
312
+ return typeof value === 'string' && value.trim().length > 0;
313
+ }
314
+ function replayNetworkKey(network) {
315
+ return network.trim().toLowerCase();
316
+ }
317
+ function failure(reason, message, expected, actual) {
318
+ return { ok: false, reason, message, expected, actual };
319
+ }
@@ -0,0 +1,125 @@
1
+ import { PublicKey, TransactionInstruction } from '@solana/web3.js';
2
+ /**
3
+ * Anchor discriminators: the first 8 bytes of sha256("<kind>:<name>"). Fixed
4
+ * here rather than hashed at runtime so this module also loads in a browser
5
+ * bundle, where `node:crypto` is not available. A test recomputes each one.
6
+ */
7
+ export declare const TOKEN_ESCROW_DISCRIMINATORS: Readonly<Record<string, readonly number[]>>;
8
+ export interface TokenEscrowTerms {
9
+ programId: PublicKey;
10
+ tokenProgram: PublicKey;
11
+ payer: PublicKey;
12
+ payee: PublicKey;
13
+ mint: PublicKey;
14
+ source: PublicKey;
15
+ recipient: PublicKey;
16
+ amount: bigint;
17
+ nonce: Uint8Array;
18
+ /**
19
+ * Metered (per-token) escrow: `amount` is the buyer's authorised maximum and
20
+ * the payee may settle the actual cost, up to it, at any time.
21
+ */
22
+ metered?: boolean;
23
+ /**
24
+ * Slots after the lock from which the payee may claim the whole amount.
25
+ * Defaults to `DEFAULT_CLAIM_WINDOW_SLOTS` (about 10 minutes).
26
+ */
27
+ claimWindowSlots?: bigint;
28
+ /**
29
+ * Slots after the lock from which the payer may refund itself. Never before
30
+ * the claim window. Defaults to `DEFAULT_CANCEL_WINDOW_SLOTS` (about 30 minutes).
31
+ */
32
+ cancelWindowSlots?: bigint;
33
+ }
34
+ /** Nominal slot time the program's windows are counted in. Real slot times drift, so a window is approximate in seconds. */
35
+ export declare const ESCROW_SLOT_MS = 400;
36
+ /** Windows used when a lock names none. Mirror `programs/pinocchio-escrow/program/src/consts.rs`. */
37
+ export declare const DEFAULT_CLAIM_WINDOW_SLOTS = 1500n;
38
+ export declare const DEFAULT_CANCEL_WINDOW_SLOTS = 4500n;
39
+ /** The longest refund window the program accepts: about 30 days. */
40
+ export declare const MAX_ESCROW_WINDOW_SLOTS = 6480000n;
41
+ /**
42
+ * The least a seller should have left of a metered escrow's refund window
43
+ * when it takes the call: about 10 minutes. The payer may refund once its
44
+ * window has elapsed, so the seller must settle before then. Compare it with
45
+ * `createdSlot + cancelWindowSlots - current slot`, not with the window named
46
+ * at lock, which a buyer can let run down before calling.
47
+ */
48
+ export declare const SELLER_MIN_CANCEL_WINDOW_SLOTS = 1500n;
49
+ /** A duration in seconds as a whole number of slots, rounded up, at the nominal slot time. */
50
+ export declare function escrowWindowSlots(seconds: number): bigint;
51
+ /** The program's rule: claim window of at least one slot, no later than the refund window, refund window at most the maximum. */
52
+ export declare function escrowWindows(t: Pick<TokenEscrowTerms, 'claimWindowSlots' | 'cancelWindowSlots'>): {
53
+ claimWindowSlots: bigint;
54
+ cancelWindowSlots: bigint;
55
+ };
56
+ /** Protocol fee treasury fixed in the escrow program: the Squads vault. */
57
+ export declare const ESCROW_PROTOCOL_TREASURY: PublicKey;
58
+ /** The treasury's associated token account for the escrow mint, which receives token fees. */
59
+ export declare function treasuryTokenAccount(t: Pick<TokenEscrowTerms, 'mint' | 'tokenProgram'>, treasury?: PublicKey): PublicKey;
60
+ export declare function tokenEscrowAddresses(t: Pick<TokenEscrowTerms, 'programId' | 'payer' | 'nonce'>): {
61
+ escrow: PublicKey;
62
+ vault: PublicKey;
63
+ bump: number;
64
+ };
65
+ export declare function buildLockTokenEscrowInstruction(t: TokenEscrowTerms): TransactionInstruction;
66
+ export interface SettleTokenEscrowOptions {
67
+ /**
68
+ * Settle at this actual cost (at most the locked amount) instead of the
69
+ * whole locked amount. Only the payee may, and only on a metered escrow.
70
+ */
71
+ actual?: bigint;
72
+ /**
73
+ * Pay the payee at this token account instead of the recipient recorded at
74
+ * lock. Only when the payee itself is the authority (claim or settle), and it
75
+ * must be a token account of the escrow mint that the payee owns. For a
76
+ * recorded recipient that was since closed or frozen.
77
+ */
78
+ payTo?: PublicKey;
79
+ /**
80
+ * Pass the mint writable, so that transfer fees withheld on a Token-2022
81
+ * vault are moved to the mint and the vault can close, returning its rent to
82
+ * the payer. Leave it off otherwise: a writable mint makes every such
83
+ * transaction contend for the same account. Applies to refunds too.
84
+ */
85
+ harvestWithheldFees?: boolean;
86
+ /** Treasury token account. The program accepts only the treasury's associated token account for the mint. */
87
+ treasuryToken?: PublicKey;
88
+ /** Where the unused part returns: any token account of the mint the payer owns. Defaults to the recorded source. */
89
+ refundTo?: PublicKey;
90
+ }
91
+ /**
92
+ * `authority` signs and defaults to the payer. The destination is the recipient in the lock terms, unless the
93
+ * payee is the authority and names another of its own token accounts (`options.payTo`).
94
+ * Release: the program accepts the payer at any time, or the payee once the claim window has elapsed.
95
+ * Settle (`options.actual`): only the payee, and only on a metered escrow; pass the payee as `authority`.
96
+ * The payer never chooses a smaller amount: it releases in full, or refunds once the cancel window has elapsed.
97
+ * Every payout sends the protocol fee (2.5% until 1 April 2027, then 5%) of the paid amount to the treasury and the rest of the vault back to the payer.
98
+ * Refund: the program accepts the payee at any time (decline), or the payer once the cancel window has elapsed.
99
+ *
100
+ * This builds the exit's own data and accounts only. The program also requires the escrow's lock slot
101
+ * (`createdSlot` of `decodeTokenEscrowAccount`) after the data, naming the escrow being ended, so send it through
102
+ * `buildTokenEscrowExitInstruction` (or `withRatingAccount`), which adds that and, for a rated escrow, its rating account.
103
+ */
104
+ export declare function buildSettleTokenEscrowInstruction(t: TokenEscrowTerms, refund?: boolean, authority?: PublicKey, options?: SettleTokenEscrowOptions): TransactionInstruction;
105
+ /**
106
+ * Reads a token escrow account. `claimWindowSlots` and `cancelWindowSlots` are
107
+ * undefined on an account the earlier program wrote, which stored no windows.
108
+ */
109
+ export declare function decodeTokenEscrowAccount(data: Buffer): {
110
+ claimWindowSlots: bigint | undefined;
111
+ cancelWindowSlots: bigint | undefined;
112
+ payer: PublicKey;
113
+ payee: PublicKey;
114
+ mint: PublicKey;
115
+ source: PublicKey;
116
+ recipient: PublicKey;
117
+ amount: bigint;
118
+ nonce: Buffer<ArrayBufferLike>;
119
+ status: number;
120
+ createdSlot: bigint;
121
+ bump: number;
122
+ metered: boolean;
123
+ /** The buyer opted this job in to rating: every exit must pass the rating account (`withRatingAccount`). */
124
+ rated: boolean;
125
+ };
@@ -0,0 +1,163 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ESCROW_PROTOCOL_TREASURY = exports.SELLER_MIN_CANCEL_WINDOW_SLOTS = exports.MAX_ESCROW_WINDOW_SLOTS = exports.DEFAULT_CANCEL_WINDOW_SLOTS = exports.DEFAULT_CLAIM_WINDOW_SLOTS = exports.ESCROW_SLOT_MS = exports.TOKEN_ESCROW_DISCRIMINATORS = void 0;
4
+ exports.escrowWindowSlots = escrowWindowSlots;
5
+ exports.escrowWindows = escrowWindows;
6
+ exports.treasuryTokenAccount = treasuryTokenAccount;
7
+ exports.tokenEscrowAddresses = tokenEscrowAddresses;
8
+ exports.buildLockTokenEscrowInstruction = buildLockTokenEscrowInstruction;
9
+ exports.buildSettleTokenEscrowInstruction = buildSettleTokenEscrowInstruction;
10
+ exports.decodeTokenEscrowAccount = decodeTokenEscrowAccount;
11
+ const web3_js_1 = require("@solana/web3.js");
12
+ const spl_token_1 = require("@solana/spl-token");
13
+ /**
14
+ * Anchor discriminators: the first 8 bytes of sha256("<kind>:<name>"). Fixed
15
+ * here rather than hashed at runtime so this module also loads in a browser
16
+ * bundle, where `node:crypto` is not available. A test recomputes each one.
17
+ */
18
+ exports.TOKEN_ESCROW_DISCRIMINATORS = Object.freeze({
19
+ 'global:lock_token_escrow': [206, 229, 150, 243, 193, 67, 46, 76],
20
+ 'global:lock_metered_token_escrow': [255, 200, 147, 208, 111, 112, 137, 160],
21
+ 'global:cancel_token_escrow': [208, 16, 138, 187, 26, 94, 168, 29],
22
+ 'global:release_token_escrow': [29, 158, 153, 156, 235, 117, 59, 61],
23
+ 'global:settle_token_escrow': [219, 152, 168, 185, 213, 166, 162, 209],
24
+ 'account:TokenEscrowAccount': [95, 163, 251, 252, 52, 125, 37, 71],
25
+ });
26
+ const disc = (kind, name) => {
27
+ const bytes = exports.TOKEN_ESCROW_DISCRIMINATORS[`${kind}:${name}`];
28
+ if (!bytes)
29
+ throw new Error(`unknown discriminator ${kind}:${name}`);
30
+ return Buffer.from(bytes);
31
+ };
32
+ /** Nominal slot time the program's windows are counted in. Real slot times drift, so a window is approximate in seconds. */
33
+ exports.ESCROW_SLOT_MS = 400;
34
+ /** Windows used when a lock names none. Mirror `programs/pinocchio-escrow/program/src/consts.rs`. */
35
+ exports.DEFAULT_CLAIM_WINDOW_SLOTS = 1500n;
36
+ exports.DEFAULT_CANCEL_WINDOW_SLOTS = 4500n;
37
+ /** The longest refund window the program accepts: about 30 days. */
38
+ exports.MAX_ESCROW_WINDOW_SLOTS = 6480000n;
39
+ /**
40
+ * The least a seller should have left of a metered escrow's refund window
41
+ * when it takes the call: about 10 minutes. The payer may refund once its
42
+ * window has elapsed, so the seller must settle before then. Compare it with
43
+ * `createdSlot + cancelWindowSlots - current slot`, not with the window named
44
+ * at lock, which a buyer can let run down before calling.
45
+ */
46
+ exports.SELLER_MIN_CANCEL_WINDOW_SLOTS = 1500n;
47
+ /** A duration in seconds as a whole number of slots, rounded up, at the nominal slot time. */
48
+ function escrowWindowSlots(seconds) {
49
+ if (!Number.isFinite(seconds) || seconds <= 0)
50
+ throw new Error('window must be a positive number of seconds');
51
+ return BigInt(Math.ceil((seconds * 1000) / exports.ESCROW_SLOT_MS));
52
+ }
53
+ /** The program's rule: claim window of at least one slot, no later than the refund window, refund window at most the maximum. */
54
+ function escrowWindows(t) {
55
+ const claimWindowSlots = t.claimWindowSlots ?? exports.DEFAULT_CLAIM_WINDOW_SLOTS;
56
+ const cancelWindowSlots = t.cancelWindowSlots ?? exports.DEFAULT_CANCEL_WINDOW_SLOTS;
57
+ if (claimWindowSlots < 1n || claimWindowSlots > cancelWindowSlots || cancelWindowSlots > exports.MAX_ESCROW_WINDOW_SLOTS) {
58
+ throw new Error('claim window must be at least one slot, no later than the refund window, and the refund window at most 30 days');
59
+ }
60
+ return { claimWindowSlots, cancelWindowSlots };
61
+ }
62
+ /** Protocol fee treasury fixed in the escrow program: the Squads vault. */
63
+ exports.ESCROW_PROTOCOL_TREASURY = new web3_js_1.PublicKey('5CsBuTBFKu12JSs4CUbmv5MR218RYtNmAoQmLf5x3Hxe');
64
+ /** The treasury's associated token account for the escrow mint, which receives token fees. */
65
+ function treasuryTokenAccount(t, treasury = exports.ESCROW_PROTOCOL_TREASURY) {
66
+ return (0, spl_token_1.getAssociatedTokenAddressSync)(t.mint, treasury, true, t.tokenProgram);
67
+ }
68
+ function tokenEscrowAddresses(t) {
69
+ if (t.nonce.length !== 16)
70
+ throw new Error('nonce must be 16 bytes');
71
+ const [escrow, bump] = web3_js_1.PublicKey.findProgramAddressSync([Buffer.from('token-escrow'), t.payer.toBuffer(), t.nonce], t.programId);
72
+ const [vault] = web3_js_1.PublicKey.findProgramAddressSync([Buffer.from('token-vault'), escrow.toBuffer()], t.programId);
73
+ return { escrow, vault, bump };
74
+ }
75
+ const meta = (pubkey, isWritable = false, isSigner = false) => ({ pubkey, isWritable, isSigner });
76
+ function buildLockTokenEscrowInstruction(t) {
77
+ // The on-chain allowlist decides which mint goes with which program; this only rejects any third program.
78
+ if (!t.tokenProgram.equals(spl_token_1.TOKEN_PROGRAM_ID) && !t.tokenProgram.equals(spl_token_1.TOKEN_2022_PROGRAM_ID))
79
+ throw new Error('token program must be classic SPL Token or Token-2022');
80
+ if (t.amount <= 0n || t.amount > 0xffffffffffffffffn)
81
+ throw new Error('amount must be a positive u64');
82
+ if (t.mint.equals(spl_token_1.NATIVE_MINT))
83
+ throw new Error('native mint unsupported');
84
+ const { escrow, vault } = tokenEscrowAddresses(t);
85
+ const amount = Buffer.alloc(8);
86
+ amount.writeBigUInt64LE(t.amount);
87
+ const { claimWindowSlots, cancelWindowSlots } = escrowWindows(t);
88
+ const windows = Buffer.alloc(16);
89
+ windows.writeBigUInt64LE(claimWindowSlots);
90
+ windows.writeBigUInt64LE(cancelWindowSlots, 8);
91
+ return new web3_js_1.TransactionInstruction({ programId: t.programId,
92
+ data: Buffer.concat([disc('global', t.metered ? 'lock_metered_token_escrow' : 'lock_token_escrow'), amount, Buffer.from(t.nonce), windows]),
93
+ keys: [meta(escrow, true), meta(vault, true), meta(t.payer, true, true), meta(t.payee), meta(t.mint),
94
+ meta(t.source, true), meta(t.recipient), meta(t.tokenProgram), meta(web3_js_1.SystemProgram.programId)] });
95
+ }
96
+ /**
97
+ * `authority` signs and defaults to the payer. The destination is the recipient in the lock terms, unless the
98
+ * payee is the authority and names another of its own token accounts (`options.payTo`).
99
+ * Release: the program accepts the payer at any time, or the payee once the claim window has elapsed.
100
+ * Settle (`options.actual`): only the payee, and only on a metered escrow; pass the payee as `authority`.
101
+ * The payer never chooses a smaller amount: it releases in full, or refunds once the cancel window has elapsed.
102
+ * Every payout sends the protocol fee (2.5% until 1 April 2027, then 5%) of the paid amount to the treasury and the rest of the vault back to the payer.
103
+ * Refund: the program accepts the payee at any time (decline), or the payer once the cancel window has elapsed.
104
+ *
105
+ * This builds the exit's own data and accounts only. The program also requires the escrow's lock slot
106
+ * (`createdSlot` of `decodeTokenEscrowAccount`) after the data, naming the escrow being ended, so send it through
107
+ * `buildTokenEscrowExitInstruction` (or `withRatingAccount`), which adds that and, for a rated escrow, its rating account.
108
+ */
109
+ function buildSettleTokenEscrowInstruction(t, refund = false, authority = t.payer, options = {}) {
110
+ buildLockTokenEscrowInstruction(t);
111
+ const { escrow, vault } = tokenEscrowAddresses(t);
112
+ const harvest = options.harvestWithheldFees === true;
113
+ if (refund) {
114
+ if (options.actual !== undefined)
115
+ throw new Error('a refund has no settled amount');
116
+ if (options.payTo)
117
+ throw new Error('a refund goes to the payer');
118
+ return new web3_js_1.TransactionInstruction({ programId: t.programId,
119
+ data: disc('global', 'cancel_token_escrow'),
120
+ keys: [meta(escrow, true), meta(vault, true), meta(authority, false, true), meta(t.payer, true), meta(t.mint, harvest),
121
+ meta(t.source, true), meta(t.tokenProgram)] });
122
+ }
123
+ if (options.payTo && !authority.equals(t.payee))
124
+ throw new Error('only the payee chooses another payout account: pass the payee as the authority');
125
+ let data = disc('global', 'release_token_escrow');
126
+ if (options.actual !== undefined) {
127
+ if (!authority.equals(t.payee))
128
+ throw new Error('only the payee settles: pass the payee as the authority');
129
+ if (options.actual <= 0n || options.actual > t.amount)
130
+ throw new Error('settled amount must be above zero and at most the locked amount');
131
+ const actual = Buffer.alloc(8);
132
+ actual.writeBigUInt64LE(options.actual);
133
+ data = Buffer.concat([disc('global', 'settle_token_escrow'), actual]);
134
+ }
135
+ return new web3_js_1.TransactionInstruction({ programId: t.programId, data,
136
+ keys: [meta(escrow, true), meta(vault, true), meta(authority, false, true), meta(t.payer, true), meta(t.mint, harvest),
137
+ meta(options.payTo ?? t.recipient, true), meta(options.treasuryToken ?? treasuryTokenAccount(t), true), meta(options.refundTo ?? t.source, true),
138
+ meta(t.tokenProgram)] });
139
+ }
140
+ /** Size of a token escrow account locked before windows were stored on it (fixed 3-day refund, 7-day claim). */
141
+ const LEGACY_TOKEN_ESCROW_LEN = 203;
142
+ const TOKEN_ESCROW_LEN = 219;
143
+ /**
144
+ * Reads a token escrow account. `claimWindowSlots` and `cancelWindowSlots` are
145
+ * undefined on an account the earlier program wrote, which stored no windows.
146
+ */
147
+ function decodeTokenEscrowAccount(data) {
148
+ if ((data.length !== TOKEN_ESCROW_LEN && data.length !== LEGACY_TOKEN_ESCROW_LEN) || !data.subarray(0, 8).equals(disc('account', 'TokenEscrowAccount')))
149
+ throw new Error('invalid token escrow layout');
150
+ const windows = data.length === TOKEN_ESCROW_LEN;
151
+ return {
152
+ claimWindowSlots: windows ? data.readBigUInt64LE(203) : undefined,
153
+ cancelWindowSlots: windows ? data.readBigUInt64LE(211) : undefined,
154
+ payer: new web3_js_1.PublicKey(data.subarray(8, 40)), payee: new web3_js_1.PublicKey(data.subarray(40, 72)),
155
+ mint: new web3_js_1.PublicKey(data.subarray(72, 104)), source: new web3_js_1.PublicKey(data.subarray(104, 136)),
156
+ recipient: new web3_js_1.PublicKey(data.subarray(136, 168)), amount: data.readBigUInt64LE(168),
157
+ nonce: data.subarray(176, 192), status: data[192], createdSlot: data.readBigUInt64LE(193), bump: data[201],
158
+ // One flag byte: bit 0x01 metered, bit 0x02 rated. A rated metered escrow stores 3.
159
+ metered: (data[202] & 0x01) !== 0,
160
+ /** The buyer opted this job in to rating: every exit must pass the rating account (`withRatingAccount`). */
161
+ rated: (data[202] & 0x02) !== 0,
162
+ };
163
+ }