@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,125 @@
1
+ import type { Connection } from '@solana/web3.js';
2
+ import type { TransactionInstruction } from '@solana/web3.js';
3
+ import { TokenEscrowTerms } from './token-escrow';
4
+ /** RAP-specific escrow extension; not the interoperable x402 SVM exact scheme. */
5
+ export interface EscrowChallenge {
6
+ scheme: 'rap-spl-escrow-v1';
7
+ network: 'solana-local-validator' | 'solana-devnet';
8
+ genesisHash: string;
9
+ tokenProgram: string;
10
+ decimals: number;
11
+ endpoint: string;
12
+ requestHash: string;
13
+ programId: string;
14
+ payer: string;
15
+ payee: string;
16
+ mint: string;
17
+ source: string;
18
+ recipient: string;
19
+ amount: string;
20
+ nonce: string;
21
+ expiresAt: number;
22
+ /**
23
+ * Slots after the lock from which the payee may claim. A whole number,
24
+ * at least 1 and at most `cancelWindowSlots`. Omitted: about 10 minutes.
25
+ */
26
+ claimWindowSlots?: number;
27
+ /**
28
+ * Slots after the lock from which the payer may refund itself, at most
29
+ * about 30 days. Omitted: about 30 minutes.
30
+ */
31
+ cancelWindowSlots?: number;
32
+ }
33
+ export interface EscrowProof {
34
+ nonce: string;
35
+ lockSignature: string;
36
+ }
37
+ export interface EscrowReceipt extends EscrowProof {
38
+ scheme: 'rap-spl-escrow-v1';
39
+ status: 'locked';
40
+ escrow: string;
41
+ amount: string;
42
+ mint: string;
43
+ requestHash: string;
44
+ slot: number;
45
+ /**
46
+ * Present, and true, only when the buyer opted the escrow in to rating and
47
+ * the seller accepts rated escrows. Every exit of that escrow must then
48
+ * pass its rating account: build the seller's claim or decline with
49
+ * `buildEscrowSellerExit`.
50
+ */
51
+ rated?: true;
52
+ /**
53
+ * Present with `rated`: the rating account's `opened_slot` (a decimal u64)
54
+ * as read when the lock was verified. It names this job, and the seller's
55
+ * claim or decline must carry it (`buildEscrowSellerExit`), so an exit
56
+ * prepared for this job is refused (6051) once another job has taken the
57
+ * address.
58
+ */
59
+ openedSlot?: string;
60
+ }
61
+ export interface EscrowVerifyOptions {
62
+ /**
63
+ * Serve escrows the buyer opted in to rating. Default false: a rated escrow
64
+ * is refused before anything is served. A seller that claims a rated escrow
65
+ * has agreed to be rated and must then commit and reveal a rating of its
66
+ * own within the program's windows or lose reputation.
67
+ */
68
+ acceptRatedEscrows?: boolean;
69
+ }
70
+ export declare const escrowRequestHash: (body: string) => string;
71
+ export declare function escrowTerms(c: EscrowChallenge): TokenEscrowTerms;
72
+ export declare function createEscrowChallenge(input: Omit<EscrowChallenge, 'scheme' | 'nonce'>): EscrowChallenge;
73
+ /**
74
+ * Read-only verification against a trusted RPC. No caller-supplied state or token identity.
75
+ * The escrow is read at `finalized`, in or after the slot of the lock, which is the only slot a
76
+ * buyer can opt it in to rating in, so the rated bit read here is final. A rated escrow is
77
+ * refused unless `options.acceptRatedEscrows` is true; when accepted, the receipt says `rated`.
78
+ */
79
+ export declare function verifyEscrowLock(connection: Connection, c: EscrowChallenge, proof: EscrowProof, options?: EscrowVerifyOptions): Promise<EscrowReceipt>;
80
+ /**
81
+ * The seller's exit of an escrow it accepted, signed by the payee: `claim`
82
+ * (release to itself, once the claim window has elapsed) or `decline`
83
+ * (everything back to the payer, at any time). It names the escrow by the
84
+ * receipt's `slot`, the lock's slot, which the escrow recorded; an exit
85
+ * prepared for this escrow is refused (6053) once another escrow has taken
86
+ * the address. For a receipt that says `rated` the escrow's rating account
87
+ * follows the usual accounts. Throws for a receipt without a valid slot, or
88
+ * a rated one whose `openedSlot` is not that slot.
89
+ */
90
+ export declare function buildEscrowSellerExit(c: EscrowChallenge, receipt: Pick<EscrowReceipt, 'rated' | 'openedSlot' | 'slot'>, kind: 'claim' | 'decline'): TransactionInstruction;
91
+ /** Single-process replay protection. Use durable atomic storage for multiple sellers/workers. */
92
+ export declare class EscrowSeller {
93
+ private connection;
94
+ private options;
95
+ private pending;
96
+ private busy;
97
+ /** `options.acceptRatedEscrows` (default false): serve escrows opted in to rating; see `EscrowVerifyOptions`. */
98
+ constructor(connection: Connection, options?: EscrowVerifyOptions);
99
+ issue(input: Omit<EscrowChallenge, 'scheme' | 'nonce'>): EscrowChallenge;
100
+ accept(endpoint: string, body: string, proof: EscrowProof): Promise<EscrowReceipt>;
101
+ }
102
+ /** Recovery context survives a paid retry/transport failure; never auto-pay twice. */
103
+ export declare class EscrowPurchaseError extends Error {
104
+ readonly challenge: EscrowChallenge;
105
+ readonly proof: EscrowProof;
106
+ constructor(message: string, challenge: EscrowChallenge, proof: EscrowProof);
107
+ }
108
+ export interface EscrowHttpResponse {
109
+ status: number;
110
+ headers: {
111
+ get(name: string): string | null;
112
+ };
113
+ json(): Promise<unknown>;
114
+ }
115
+ /** At most one approved lock and one retry; transport and signing remain caller-owned. */
116
+ export declare function buyWithEscrow(input: {
117
+ endpoint: string;
118
+ body: string;
119
+ request(proof?: EscrowProof): Promise<EscrowHttpResponse>;
120
+ approve(c: EscrowChallenge): Promise<void>;
121
+ lock(c: EscrowChallenge): Promise<string>;
122
+ }): Promise<{
123
+ result: unknown;
124
+ receipt: EscrowReceipt;
125
+ }>;
@@ -0,0 +1,192 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.EscrowPurchaseError = exports.EscrowSeller = exports.escrowRequestHash = void 0;
4
+ exports.escrowTerms = escrowTerms;
5
+ exports.createEscrowChallenge = createEscrowChallenge;
6
+ exports.verifyEscrowLock = verifyEscrowLock;
7
+ exports.buildEscrowSellerExit = buildEscrowSellerExit;
8
+ exports.buyWithEscrow = buyWithEscrow;
9
+ const node_crypto_1 = require("node:crypto");
10
+ const web3_js_1 = require("@solana/web3.js");
11
+ const spl_token_1 = require("@solana/spl-token");
12
+ const rating_1 = require("./rating");
13
+ const token_escrow_1 = require("./token-escrow");
14
+ const escrowRequestHash = (body) => (0, node_crypto_1.createHash)('sha256').update(body).digest('hex');
15
+ exports.escrowRequestHash = escrowRequestHash;
16
+ function escrowTerms(c) {
17
+ if (c.scheme !== 'rap-spl-escrow-v1' || !['solana-local-validator', 'solana-devnet'].includes(c.network))
18
+ throw new Error('unsupported escrow scheme/network');
19
+ if (!/^[0-9a-f]{32}$/.test(c.nonce) || !/^[1-9][0-9]*$/.test(c.amount))
20
+ throw new Error('invalid escrow nonce/amount');
21
+ if (!Number.isInteger(c.decimals) || c.decimals < 0 || c.decimals > 255)
22
+ throw new Error('invalid mint decimals');
23
+ for (const window of [c.claimWindowSlots, c.cancelWindowSlots]) {
24
+ if (window !== undefined && (!Number.isSafeInteger(window) || window < 1))
25
+ throw new Error('invalid escrow window');
26
+ }
27
+ const t = { tokenProgram: new web3_js_1.PublicKey(c.tokenProgram), programId: new web3_js_1.PublicKey(c.programId), payer: new web3_js_1.PublicKey(c.payer), payee: new web3_js_1.PublicKey(c.payee),
28
+ mint: new web3_js_1.PublicKey(c.mint), source: new web3_js_1.PublicKey(c.source), recipient: new web3_js_1.PublicKey(c.recipient), amount: BigInt(c.amount), nonce: Buffer.from(c.nonce, 'hex'),
29
+ ...(c.claimWindowSlots !== undefined ? { claimWindowSlots: BigInt(c.claimWindowSlots) } : {}),
30
+ ...(c.cancelWindowSlots !== undefined ? { cancelWindowSlots: BigInt(c.cancelWindowSlots) } : {}) };
31
+ (0, token_escrow_1.buildLockTokenEscrowInstruction)(t); // Validate u64 and native-mint boundary before signing.
32
+ return t;
33
+ }
34
+ function createEscrowChallenge(input) {
35
+ const c = { ...input, scheme: 'rap-spl-escrow-v1', nonce: (0, node_crypto_1.randomBytes)(16).toString('hex') };
36
+ escrowTerms(c);
37
+ if (!Number.isSafeInteger(c.expiresAt) || c.expiresAt <= Date.now() || !/^[a-f0-9]{64}$/.test(c.requestHash))
38
+ throw new Error('invalid challenge lifetime/request hash');
39
+ return c;
40
+ }
41
+ /**
42
+ * Read-only verification against a trusted RPC. No caller-supplied state or token identity.
43
+ * The escrow is read at `finalized`, in or after the slot of the lock, which is the only slot a
44
+ * buyer can opt it in to rating in, so the rated bit read here is final. A rated escrow is
45
+ * refused unless `options.acceptRatedEscrows` is true; when accepted, the receipt says `rated`.
46
+ */
47
+ async function verifyEscrowLock(connection, c, proof, options = {}) {
48
+ const t = escrowTerms(c);
49
+ if (!Number.isSafeInteger(c.expiresAt) || Date.now() >= c.expiresAt || proof.nonce !== c.nonce || !/^[1-9A-HJ-NP-Za-km-z]{64,88}$/.test(proof.lockSignature))
50
+ throw new Error('invalid or expired payment proof');
51
+ if (await connection.getGenesisHash() !== c.genesisHash)
52
+ throw new Error('wrong cluster');
53
+ const tx = await connection.getTransaction(proof.lockSignature, { commitment: 'finalized', maxSupportedTransactionVersion: 0 });
54
+ if (!tx || !tx.meta || tx.meta.err)
55
+ throw new Error('lock transaction missing or failed');
56
+ const ix = (0, token_escrow_1.buildLockTokenEscrowInstruction)(t);
57
+ const keys = tx.transaction.message.getAccountKeys({ accountKeysFromLookups: tx.meta.loadedAddresses });
58
+ const found = tx.transaction.message.compiledInstructions.some(i => keys.get(i.programIdIndex)?.equals(t.programId)
59
+ && Buffer.from(i.data).equals(ix.data) && i.accountKeyIndexes.length === ix.keys.length
60
+ && i.accountKeyIndexes.every((k, n) => keys.get(k)?.equals(ix.keys[n].pubkey))
61
+ && tx.transaction.message.isAccountSigner(i.accountKeyIndexes[2]));
62
+ if (!found)
63
+ throw new Error('signature does not prove this lock');
64
+ const { escrow, vault, bump } = (0, token_escrow_1.tokenEscrowAddresses)(t);
65
+ const state = await connection.getAccountInfo(escrow, { commitment: 'finalized', minContextSlot: tx.slot });
66
+ if (!state || !state.owner.equals(t.programId))
67
+ throw new Error('escrow missing or wrong owner');
68
+ const decoded = (0, token_escrow_1.decodeTokenEscrowAccount)(state.data);
69
+ for (const field of ['payer', 'payee', 'mint', 'source', 'recipient']) {
70
+ if (!decoded[field].equals(t[field]))
71
+ throw new Error(`wrong escrow ${field}`);
72
+ }
73
+ if (decoded.rated && options.acceptRatedEscrows !== true)
74
+ throw new Error('rated escrow declined: this seller does not take escrows opted in to rating');
75
+ if (decoded.amount !== t.amount || !decoded.nonce.equals(Buffer.from(t.nonce)) || decoded.status !== 0 || decoded.bump !== bump || decoded.createdSlot !== BigInt(tx.slot))
76
+ throw new Error('escrow terms mismatch');
77
+ // An account the earlier program wrote stores no windows (they were fixed); otherwise they must be the challenge's.
78
+ const expected = (0, token_escrow_1.escrowWindows)(t);
79
+ if (decoded.claimWindowSlots !== undefined && (decoded.claimWindowSlots !== expected.claimWindowSlots || decoded.cancelWindowSlots !== expected.cancelWindowSlots))
80
+ throw new Error('escrow windows mismatch');
81
+ const mintInfo = await connection.getAccountInfo(t.mint, { commitment: 'finalized', minContextSlot: tx.slot });
82
+ if (!mintInfo || (0, spl_token_1.unpackMint)(t.mint, mintInfo, t.tokenProgram).decimals !== c.decimals)
83
+ throw new Error('mint decimals mismatch');
84
+ const info = await connection.getAccountInfo(vault, { commitment: 'finalized', minContextSlot: tx.slot });
85
+ if (!info)
86
+ throw new Error('vault missing');
87
+ const token = (0, spl_token_1.unpackAccount)(vault, info, t.tokenProgram);
88
+ if (!token.owner.equals(escrow) || !token.mint.equals(t.mint) || token.amount < t.amount || !token.isInitialized || token.isFrozen)
89
+ throw new Error('vault mismatch');
90
+ let rating;
91
+ if (decoded.rated) {
92
+ const ratingInfo = await connection.getAccountInfo((0, rating_1.ratingPda)(escrow, t.programId), { commitment: 'finalized', minContextSlot: tx.slot });
93
+ if (!ratingInfo || !ratingInfo.owner.equals(t.programId))
94
+ throw new Error('rating account missing or wrong owner');
95
+ const decodedRating = (0, rating_1.decodeRatingAccount)(ratingInfo.data);
96
+ if (!decodedRating.escrow.equals(escrow) || decodedRating.state !== 'awaiting_settlement')
97
+ throw new Error('rating account mismatch');
98
+ rating = { rated: true, openedSlot: decodedRating.openedSlot.toString() };
99
+ }
100
+ return { ...proof, scheme: c.scheme, status: 'locked', escrow: escrow.toBase58(), amount: c.amount, mint: c.mint, requestHash: c.requestHash, slot: tx.slot, ...(rating ?? {}) };
101
+ }
102
+ /**
103
+ * The seller's exit of an escrow it accepted, signed by the payee: `claim`
104
+ * (release to itself, once the claim window has elapsed) or `decline`
105
+ * (everything back to the payer, at any time). It names the escrow by the
106
+ * receipt's `slot`, the lock's slot, which the escrow recorded; an exit
107
+ * prepared for this escrow is refused (6053) once another escrow has taken
108
+ * the address. For a receipt that says `rated` the escrow's rating account
109
+ * follows the usual accounts. Throws for a receipt without a valid slot, or
110
+ * a rated one whose `openedSlot` is not that slot.
111
+ */
112
+ function buildEscrowSellerExit(c, receipt, kind) {
113
+ const t = escrowTerms(c);
114
+ const rated = receipt.rated === true;
115
+ if (!Number.isSafeInteger(receipt.slot) || receipt.slot < 0)
116
+ throw new Error('the receipt must carry the slot of the lock');
117
+ const createdSlot = BigInt(receipt.slot);
118
+ if (rated && receipt.openedSlot !== createdSlot.toString())
119
+ throw new Error('a rated receipt must carry the opened slot of its rating, which is the slot of the lock');
120
+ return (0, rating_1.buildTokenEscrowExitInstruction)(t, { rated, createdSlot, refund: kind === 'decline', authority: t.payee });
121
+ }
122
+ /** Single-process replay protection. Use durable atomic storage for multiple sellers/workers. */
123
+ class EscrowSeller {
124
+ /** `options.acceptRatedEscrows` (default false): serve escrows opted in to rating; see `EscrowVerifyOptions`. */
125
+ constructor(connection, options = {}) {
126
+ this.connection = connection;
127
+ this.options = options;
128
+ this.pending = new Map();
129
+ this.busy = new Set();
130
+ }
131
+ issue(input) {
132
+ for (const [nonce, c] of this.pending)
133
+ if (c.expiresAt <= Date.now())
134
+ this.pending.delete(nonce);
135
+ if (this.pending.size >= 1000)
136
+ throw new Error('challenge capacity exceeded');
137
+ const c = createEscrowChallenge(input);
138
+ this.pending.set(c.nonce, c);
139
+ return c;
140
+ }
141
+ async accept(endpoint, body, proof) {
142
+ const c = this.pending.get(proof.nonce);
143
+ if (!c || this.busy.has(c.nonce) || c.endpoint !== endpoint || c.requestHash !== (0, exports.escrowRequestHash)(body))
144
+ throw new Error('unknown, replayed or mismatched challenge');
145
+ this.busy.add(c.nonce);
146
+ try {
147
+ const receipt = await verifyEscrowLock(this.connection, c, proof, this.options);
148
+ this.pending.delete(c.nonce);
149
+ return receipt;
150
+ }
151
+ finally {
152
+ this.busy.delete(c.nonce);
153
+ }
154
+ }
155
+ }
156
+ exports.EscrowSeller = EscrowSeller;
157
+ /** Recovery context survives a paid retry/transport failure; never auto-pay twice. */
158
+ class EscrowPurchaseError extends Error {
159
+ constructor(message, challenge, proof) {
160
+ super(message);
161
+ this.challenge = challenge;
162
+ this.proof = proof;
163
+ this.name = 'EscrowPurchaseError';
164
+ }
165
+ }
166
+ exports.EscrowPurchaseError = EscrowPurchaseError;
167
+ /** At most one approved lock and one retry; transport and signing remain caller-owned. */
168
+ async function buyWithEscrow(input) {
169
+ const first = await input.request();
170
+ if (first.status !== 402)
171
+ throw new Error('expected HTTP 402');
172
+ const c = JSON.parse(first.headers.get('x402-request') ?? 'null');
173
+ if (!c || !Number.isSafeInteger(c.expiresAt) || c.endpoint !== input.endpoint || c.requestHash !== (0, exports.escrowRequestHash)(input.body) || c.expiresAt <= Date.now())
174
+ throw new Error('challenge request mismatch');
175
+ escrowTerms(c);
176
+ await input.approve(c); // Caller must pin cluster/program/mint/payer/recipient and a raw-unit spend cap.
177
+ const proof = { nonce: c.nonce, lockSignature: await input.lock(c) };
178
+ try {
179
+ const retry = await input.request(proof);
180
+ if (retry.status !== 200)
181
+ throw new Error(`paid retry failed: ${retry.status}; retain lock proof for recovery`);
182
+ const receipt = JSON.parse(retry.headers.get('x402-receipt') ?? 'null');
183
+ if (!receipt || !Number.isSafeInteger(receipt.slot) || receipt.slot < 0 || receipt.scheme !== c.scheme || receipt.status !== 'locked' || receipt.nonce !== c.nonce
184
+ || receipt.lockSignature !== proof.lockSignature || receipt.amount !== c.amount || receipt.mint !== c.mint
185
+ || receipt.requestHash !== c.requestHash || receipt.escrow !== (0, token_escrow_1.tokenEscrowAddresses)(escrowTerms(c)).escrow.toBase58())
186
+ throw new Error('invalid seller receipt');
187
+ return { result: await retry.json(), receipt };
188
+ }
189
+ catch (error) {
190
+ throw new EscrowPurchaseError(error instanceof Error ? error.message : String(error), c, proof);
191
+ }
192
+ }
@@ -0,0 +1,132 @@
1
+ import { PublicKey, TransactionInstruction } from '@solana/web3.js';
2
+ import { TokenEscrowTerms } from './token-escrow';
3
+ /**
4
+ * Launch and payout checks for the V1 escrow program. These guard against
5
+ * payouts that the program would accept but the runtime would refuse: a SOL
6
+ * transfer that leaves the receiver below the rent-exempt minimum, and a token
7
+ * payout to a treasury or refund token account that does not exist yet.
8
+ */
9
+ /** Rent-exempt minimum of a plain system account (0 bytes of data). */
10
+ export declare const SYSTEM_ACCOUNT_RENT_EXEMPT_LAMPORTS = 890880n;
11
+ /** The treasury holds at least this much SOL before the first SOL payout, so a small fee never fails on rent. */
12
+ export declare const TREASURY_MIN_LAMPORTS = 1000000n;
13
+ /**
14
+ * True when sending `incomingLamports` to an account holding `currentLamports`
15
+ * would leave it above zero but below the rent-exempt minimum, which the
16
+ * runtime refuses (InsufficientFundsForRent). A zero transfer never fails.
17
+ */
18
+ export declare function solPayoutWouldFail(currentLamports: bigint, incomingLamports: bigint, rentExemptLamports?: bigint): boolean;
19
+ /**
20
+ * The smallest payout a payee holding `currentLamports` can receive. Zero when
21
+ * the payee is already rent-exempt.
22
+ */
23
+ export declare function minimumSolPayout(currentLamports: bigint, rentExemptLamports?: bigint): bigint;
24
+ export interface SettlePreparation {
25
+ /** Creates to put before the settle in the same transaction. Empty unless a create was asked for. */
26
+ instructions: TransactionInstruction[];
27
+ /** Where the unused part returns: the account named in the options, or the payer's associated token account. */
28
+ refundTo: PublicKey;
29
+ treasuryToken: PublicKey;
30
+ }
31
+ export interface TokenPayoutOptions {
32
+ /** Return the unused part to this token account of the payer instead of its associated token account. */
33
+ refundTo?: PublicKey;
34
+ /**
35
+ * Create the treasury's associated token account if it is missing, at the
36
+ * funder's cost. Off by default: readiness is checked before a currency
37
+ * opens, and a settle should not carry the create every time.
38
+ */
39
+ createTreasuryAccount?: boolean;
40
+ /**
41
+ * Create the payer's associated token account if it is missing, at the
42
+ * funder's cost (its rent, about 0.002 SOL, is not returned to the funder).
43
+ * Off by default: this is a subsidy, and the caller decides when to pay it.
44
+ */
45
+ createRefundAccount?: boolean;
46
+ }
47
+ /**
48
+ * The accounts a token payout names next to the escrow's own: the treasury's
49
+ * associated token account for the mint, and the account the unused part
50
+ * returns to. Nothing is created unless the options ask for it; a create is
51
+ * idempotent, `funder` pays its rent and must sign the transaction.
52
+ */
53
+ export declare function prepareTokenPayout(t: Pick<TokenEscrowTerms, 'mint' | 'tokenProgram' | 'payer'>, funder: PublicKey, treasury?: PublicKey, options?: TokenPayoutOptions): SettlePreparation;
54
+ export type TokenAccountProblem = 'missing' | 'wrong_program' | 'not_token_account' | 'uninitialised' | 'frozen' | 'wrong_mint' | 'wrong_owner' | 'memo_required';
55
+ export type TokenAccountCheck = {
56
+ ok: true;
57
+ amount: bigint;
58
+ } | {
59
+ ok: false;
60
+ problem: TokenAccountProblem;
61
+ detail: string;
62
+ };
63
+ /**
64
+ * Whether a token account can receive a transfer of `mint` right now: it
65
+ * exists under the mint's token program, is initialised and not frozen, holds
66
+ * the mint, belongs to `owner` when one is named, and does not require a memo
67
+ * on incoming transfers (the escrow program sends none). Reads the whole
68
+ * account, not only its first fields.
69
+ */
70
+ export declare function checkTokenAccount(address: PublicKey, account: Pick<ReadAccount, 'owner' | 'data'> | null, expected: {
71
+ mint: PublicKey;
72
+ tokenProgram: PublicKey;
73
+ owner?: PublicKey;
74
+ }): TokenAccountCheck;
75
+ export interface EscrowMint {
76
+ symbol: string;
77
+ mint: PublicKey;
78
+ tokenProgram: PublicKey;
79
+ }
80
+ /** The mainnet allowlist of the V1 escrow program (programs/pinocchio-escrow/program/src/consts.rs). */
81
+ export declare const ESCROW_MAINNET_MINTS: readonly EscrowMint[];
82
+ /** The devnet build's extra mint (devnet USDC). */
83
+ export declare const ESCROW_DEVNET_MINTS: readonly EscrowMint[];
84
+ export interface ReadAccount {
85
+ lamports: number | bigint;
86
+ owner: PublicKey;
87
+ data: Uint8Array;
88
+ }
89
+ export type AccountLookup = (address: PublicKey) => Promise<ReadAccount | null>;
90
+ export interface ReadinessItem {
91
+ name: string;
92
+ address: string;
93
+ ok: boolean;
94
+ detail: string;
95
+ }
96
+ /**
97
+ * Read-only check that the treasury can receive every payout: enough SOL for a
98
+ * small fee to land, and for each mint a token account under the mint's token
99
+ * program that the treasury owns, initialised, not frozen and not requiring a
100
+ * memo. Nothing is sent.
101
+ */
102
+ export declare function checkTreasuryReadiness(lookup: AccountLookup, mints?: readonly EscrowMint[], treasury?: PublicKey): Promise<{
103
+ ok: boolean;
104
+ items: ReadinessItem[];
105
+ }>;
106
+ /**
107
+ * What an issuer can change on a Token-2022 mint that would affect escrows in
108
+ * it: the extensions present, the transfer hook program, the transfer fee, the
109
+ * permanent delegate and the freeze, close and pause authorities. Supply and
110
+ * metadata text are left out because they change in normal use.
111
+ */
112
+ export interface Token2022MintPosture {
113
+ extensionTypes: number[];
114
+ transferHookProgram: string | null;
115
+ transferFee: {
116
+ olderBps: number;
117
+ newerBps: number;
118
+ newerEpoch: string;
119
+ newerMaximumFee: string;
120
+ } | null;
121
+ permanentDelegate: string | null;
122
+ freezeAuthority: string | null;
123
+ mintCloseAuthority: string | null;
124
+ pausable: {
125
+ authority: string | null;
126
+ paused: boolean;
127
+ } | null;
128
+ }
129
+ /** Reads the posture from a Token-2022 mint account's raw data. */
130
+ export declare function token2022MintPosture(data: Uint8Array, address?: PublicKey): Token2022MintPosture;
131
+ /** Each field that differs from the recorded posture, as "field: before -> after". Empty when nothing changed. */
132
+ export declare function mintPostureChanges(recorded: Token2022MintPosture, current: Token2022MintPosture): string[];
@@ -0,0 +1,171 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ESCROW_DEVNET_MINTS = exports.ESCROW_MAINNET_MINTS = exports.TREASURY_MIN_LAMPORTS = exports.SYSTEM_ACCOUNT_RENT_EXEMPT_LAMPORTS = void 0;
4
+ exports.solPayoutWouldFail = solPayoutWouldFail;
5
+ exports.minimumSolPayout = minimumSolPayout;
6
+ exports.prepareTokenPayout = prepareTokenPayout;
7
+ exports.checkTokenAccount = checkTokenAccount;
8
+ exports.checkTreasuryReadiness = checkTreasuryReadiness;
9
+ exports.token2022MintPosture = token2022MintPosture;
10
+ exports.mintPostureChanges = mintPostureChanges;
11
+ const web3_js_1 = require("@solana/web3.js");
12
+ const spl_token_1 = require("@solana/spl-token");
13
+ const token_escrow_1 = require("./token-escrow");
14
+ /**
15
+ * Launch and payout checks for the V1 escrow program. These guard against
16
+ * payouts that the program would accept but the runtime would refuse: a SOL
17
+ * transfer that leaves the receiver below the rent-exempt minimum, and a token
18
+ * payout to a treasury or refund token account that does not exist yet.
19
+ */
20
+ /** Rent-exempt minimum of a plain system account (0 bytes of data). */
21
+ exports.SYSTEM_ACCOUNT_RENT_EXEMPT_LAMPORTS = 890880n;
22
+ /** The treasury holds at least this much SOL before the first SOL payout, so a small fee never fails on rent. */
23
+ exports.TREASURY_MIN_LAMPORTS = 1000000n;
24
+ /**
25
+ * True when sending `incomingLamports` to an account holding `currentLamports`
26
+ * would leave it above zero but below the rent-exempt minimum, which the
27
+ * runtime refuses (InsufficientFundsForRent). A zero transfer never fails.
28
+ */
29
+ function solPayoutWouldFail(currentLamports, incomingLamports, rentExemptLamports = exports.SYSTEM_ACCOUNT_RENT_EXEMPT_LAMPORTS) {
30
+ if (incomingLamports <= 0n)
31
+ return false;
32
+ return currentLamports + incomingLamports < rentExemptLamports;
33
+ }
34
+ /**
35
+ * The smallest payout a payee holding `currentLamports` can receive. Zero when
36
+ * the payee is already rent-exempt.
37
+ */
38
+ function minimumSolPayout(currentLamports, rentExemptLamports = exports.SYSTEM_ACCOUNT_RENT_EXEMPT_LAMPORTS) {
39
+ return currentLamports >= rentExemptLamports ? 0n : rentExemptLamports - currentLamports;
40
+ }
41
+ /**
42
+ * The accounts a token payout names next to the escrow's own: the treasury's
43
+ * associated token account for the mint, and the account the unused part
44
+ * returns to. Nothing is created unless the options ask for it; a create is
45
+ * idempotent, `funder` pays its rent and must sign the transaction.
46
+ */
47
+ function prepareTokenPayout(t, funder, treasury = token_escrow_1.ESCROW_PROTOCOL_TREASURY, options = {}) {
48
+ if (!t.tokenProgram.equals(spl_token_1.TOKEN_PROGRAM_ID) && !t.tokenProgram.equals(spl_token_1.TOKEN_2022_PROGRAM_ID)) {
49
+ throw new Error('token program must be classic SPL Token or Token-2022');
50
+ }
51
+ const treasuryToken = (0, token_escrow_1.treasuryTokenAccount)(t, treasury);
52
+ const payerToken = (0, spl_token_1.getAssociatedTokenAddressSync)(t.mint, t.payer, true, t.tokenProgram);
53
+ if (options.createRefundAccount && options.refundTo && !options.refundTo.equals(payerToken)) {
54
+ throw new Error("only the payer's associated token account can be created here");
55
+ }
56
+ const instructions = [];
57
+ if (options.createTreasuryAccount)
58
+ instructions.push((0, spl_token_1.createAssociatedTokenAccountIdempotentInstruction)(funder, treasuryToken, treasury, t.mint, t.tokenProgram));
59
+ if (options.createRefundAccount)
60
+ instructions.push((0, spl_token_1.createAssociatedTokenAccountIdempotentInstruction)(funder, payerToken, t.payer, t.mint, t.tokenProgram));
61
+ return { treasuryToken, refundTo: options.refundTo ?? payerToken, instructions };
62
+ }
63
+ /**
64
+ * Whether a token account can receive a transfer of `mint` right now: it
65
+ * exists under the mint's token program, is initialised and not frozen, holds
66
+ * the mint, belongs to `owner` when one is named, and does not require a memo
67
+ * on incoming transfers (the escrow program sends none). Reads the whole
68
+ * account, not only its first fields.
69
+ */
70
+ function checkTokenAccount(address, account, expected) {
71
+ if (!account)
72
+ return { ok: false, problem: 'missing', detail: 'missing' };
73
+ if (!account.owner.equals(expected.tokenProgram)) {
74
+ return { ok: false, problem: 'wrong_program', detail: `owned by ${account.owner.toBase58()}, expected ${expected.tokenProgram.toBase58()}` };
75
+ }
76
+ let token;
77
+ try {
78
+ token = (0, spl_token_1.unpackAccount)(address, { data: Buffer.from(account.data), owner: account.owner, lamports: 0, executable: false }, expected.tokenProgram);
79
+ }
80
+ catch {
81
+ return { ok: false, problem: 'not_token_account', detail: 'not a token account' };
82
+ }
83
+ if (!token.isInitialized)
84
+ return { ok: false, problem: 'uninitialised', detail: 'not initialised' };
85
+ if (!token.mint.equals(expected.mint))
86
+ return { ok: false, problem: 'wrong_mint', detail: `holds mint ${token.mint.toBase58()}` };
87
+ if (expected.owner && !token.owner.equals(expected.owner))
88
+ return { ok: false, problem: 'wrong_owner', detail: `owned by ${token.owner.toBase58()}` };
89
+ if (token.isFrozen)
90
+ return { ok: false, problem: 'frozen', detail: 'frozen by the issuer' };
91
+ if ((0, spl_token_1.getMemoTransfer)(token)?.requireIncomingTransferMemos)
92
+ return { ok: false, problem: 'memo_required', detail: 'requires a memo on incoming transfers' };
93
+ return { ok: true, amount: token.amount };
94
+ }
95
+ /** The mainnet allowlist of the V1 escrow program (programs/pinocchio-escrow/program/src/consts.rs). */
96
+ exports.ESCROW_MAINNET_MINTS = Object.freeze([
97
+ { symbol: 'USDC', mint: new web3_js_1.PublicKey('EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v'), tokenProgram: spl_token_1.TOKEN_PROGRAM_ID },
98
+ { symbol: 'AUDD', mint: new web3_js_1.PublicKey('AUDDttiEpCydTm7joUMbYddm72jAWXZnCpPZtDoxqBSw'), tokenProgram: spl_token_1.TOKEN_PROGRAM_ID },
99
+ { symbol: 'PYUSD', mint: new web3_js_1.PublicKey('2b1kV6DkPAnxd5ixfnxCpjxmKwqjjaYmCZfHsFu24GXo'), tokenProgram: spl_token_1.TOKEN_2022_PROGRAM_ID },
100
+ { symbol: 'USDG', mint: new web3_js_1.PublicKey('2u1tszSeqZ3qBWF3uNGPFc8TzMk2tdiwknnRMWGWjGWH'), tokenProgram: spl_token_1.TOKEN_2022_PROGRAM_ID },
101
+ ]);
102
+ /** The devnet build's extra mint (devnet USDC). */
103
+ exports.ESCROW_DEVNET_MINTS = Object.freeze([
104
+ { symbol: 'USDC (devnet)', mint: new web3_js_1.PublicKey('4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU'), tokenProgram: spl_token_1.TOKEN_PROGRAM_ID },
105
+ ]);
106
+ /**
107
+ * Read-only check that the treasury can receive every payout: enough SOL for a
108
+ * small fee to land, and for each mint a token account under the mint's token
109
+ * program that the treasury owns, initialised, not frozen and not requiring a
110
+ * memo. Nothing is sent.
111
+ */
112
+ async function checkTreasuryReadiness(lookup, mints = exports.ESCROW_MAINNET_MINTS, treasury = token_escrow_1.ESCROW_PROTOCOL_TREASURY) {
113
+ const items = [];
114
+ const sol = await lookup(treasury);
115
+ const lamports = BigInt(sol?.lamports ?? 0);
116
+ items.push({
117
+ name: 'Treasury SOL balance',
118
+ address: treasury.toBase58(),
119
+ ok: lamports >= exports.TREASURY_MIN_LAMPORTS,
120
+ detail: `${lamports} lamports held, at least ${exports.TREASURY_MIN_LAMPORTS} needed`,
121
+ });
122
+ for (const m of mints) {
123
+ const ata = (0, spl_token_1.getAssociatedTokenAddressSync)(m.mint, treasury, true, m.tokenProgram);
124
+ const account = await lookup(ata);
125
+ const check = checkTokenAccount(ata, account, { mint: m.mint, tokenProgram: m.tokenProgram, owner: treasury });
126
+ const ok = check.ok;
127
+ const detail = check.ok
128
+ ? 'exists, initialised and not frozen'
129
+ : check.problem === 'missing'
130
+ ? 'missing: create the associated token account before the first payout in this mint'
131
+ : check.problem === 'wrong_owner'
132
+ ? `${check.detail}, not the treasury`
133
+ : check.detail;
134
+ items.push({ name: `Treasury ${m.symbol} token account`, address: ata.toBase58(), ok, detail });
135
+ }
136
+ return { ok: items.every((i) => i.ok), items };
137
+ }
138
+ const addressOrNull = (key) => (key && !key.equals(web3_js_1.PublicKey.default) ? key.toBase58() : null);
139
+ /** Reads the posture from a Token-2022 mint account's raw data. */
140
+ function token2022MintPosture(data, address = web3_js_1.PublicKey.default) {
141
+ const mint = (0, spl_token_1.unpackMint)(address, { data: Buffer.from(data), owner: spl_token_1.TOKEN_2022_PROGRAM_ID, lamports: 0, executable: false }, spl_token_1.TOKEN_2022_PROGRAM_ID);
142
+ const fee = (0, spl_token_1.getTransferFeeConfig)(mint);
143
+ const pausable = (0, spl_token_1.getPausableConfig)(mint);
144
+ return {
145
+ extensionTypes: (0, spl_token_1.getExtensionTypes)(mint.tlvData).map(Number).sort((a, b) => a - b),
146
+ transferHookProgram: addressOrNull((0, spl_token_1.getTransferHook)(mint)?.programId),
147
+ transferFee: fee
148
+ ? {
149
+ olderBps: fee.olderTransferFee.transferFeeBasisPoints,
150
+ newerBps: fee.newerTransferFee.transferFeeBasisPoints,
151
+ newerEpoch: fee.newerTransferFee.epoch.toString(),
152
+ newerMaximumFee: fee.newerTransferFee.maximumFee.toString(),
153
+ }
154
+ : null,
155
+ permanentDelegate: addressOrNull((0, spl_token_1.getPermanentDelegate)(mint)?.delegate),
156
+ freezeAuthority: addressOrNull(mint.freezeAuthority),
157
+ mintCloseAuthority: addressOrNull((0, spl_token_1.getMintCloseAuthority)(mint)?.closeAuthority),
158
+ pausable: pausable ? { authority: addressOrNull(pausable.authority), paused: Boolean(pausable.paused) } : null,
159
+ };
160
+ }
161
+ /** Each field that differs from the recorded posture, as "field: before -> after". Empty when nothing changed. */
162
+ function mintPostureChanges(recorded, current) {
163
+ const changes = [];
164
+ for (const key of Object.keys(recorded)) {
165
+ const before = JSON.stringify(recorded[key]);
166
+ const after = JSON.stringify(current[key]);
167
+ if (before !== after)
168
+ changes.push(`${key}: ${before} -> ${after}`);
169
+ }
170
+ return changes;
171
+ }
@@ -0,0 +1,26 @@
1
+ /**
2
+ * @redditech/x402-solana - HTTP 402 primitives for Solana-oriented RAP workflows.
3
+ *
4
+ * Repo-local v0.1 OSS candidate. Clean-checkout smoke must stay local and
5
+ * must not imply npm publication, live payment, custody, mainnet, or
6
+ * settlement-finality readiness.
7
+ */
8
+ export * from './types';
9
+ export * from './nonce';
10
+ export * from './payment';
11
+ export * from './direct-payment';
12
+ export * from './metered';
13
+ export * from './buyer';
14
+ export * from './spl-token-observer';
15
+ export * from './middleware';
16
+ export * from './jupiter';
17
+ export * from './client';
18
+ export * from './budget-policy';
19
+ export * from './token-escrow';
20
+ export * from './escrow-http';
21
+ export * from './escrow-readiness';
22
+ export * from './provider';
23
+ export * from './rating';
24
+ export * from './session';
25
+ export * from './session-auth';
26
+ export * from './direct-auth';