@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,967 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.MAX_RECEIPT_NONCE_LENGTH = exports.SolanaReceiptVerifier = exports.DEFAULT_MAX_TRANSACTION_AGE_SECONDS = exports.SOLANA_GENESIS_HASHES = exports.DemoPaymentVerifier = exports.MAINNET_STABLECOIN_MINTS = exports.DIRECT_PAYMENT_CURRENCIES = exports.SOL_PROTOCOL_FEE_CAP_LAMPORTS = exports.FEE_RATE_SWITCH_GRACE_MS = exports.LAUNCH_RATE_ENDS_AT_MS = exports.LAUNCH_PROTOCOL_FEE_BPS = exports.PROTOCOL_FEE_BPS = exports.isValidPaymentAddress = void 0;
4
+ exports.isValidSolanaPublicKey = isValidSolanaPublicKey;
5
+ exports.protocolFeeBpsAt = protocolFeeBpsAt;
6
+ exports.protocolFeeBpsNear = protocolFeeBpsNear;
7
+ exports.directPaymentCurrency = directPaymentCurrency;
8
+ exports.decimalToBaseUnits = decimalToBaseUnits;
9
+ exports.baseUnitsToDecimal = baseUnitsToDecimal;
10
+ exports.protocolFeeBaseUnits = protocolFeeBaseUnits;
11
+ exports.protocolFeeCapBaseUnits = protocolFeeCapBaseUnits;
12
+ exports.protocolFeeTerms = protocolFeeTerms;
13
+ exports.buildX402Challenge = buildX402Challenge;
14
+ exports.parseX402Header = parseX402Header;
15
+ exports.parseX402PaymentHeader = parseX402PaymentHeader;
16
+ exports.verifyDemoPaymentReceipt = verifyDemoPaymentReceipt;
17
+ exports.transactionReplayKey = transactionReplayKey;
18
+ exports.isValidReceiptNonce = isValidReceiptNonce;
19
+ exports.nonceReplayKey = nonceReplayKey;
20
+ exports.demoNonceReplayKey = demoNonceReplayKey;
21
+ exports.solAmountToLamports = solAmountToLamports;
22
+ exports.sendPayment = sendPayment;
23
+ const web3_js_1 = require("@solana/web3.js");
24
+ const jupiter_1 = require("./jupiter");
25
+ const spl_token_observer_1 = require("./spl-token-observer");
26
+ const nonce_1 = require("./nonce");
27
+ const SUPPORTED_NETWORKS = ['solana-devnet', 'solana-mainnet-beta', 'solana-testnet'];
28
+ /**
29
+ * Strictly validate canonical Solana public-key text.
30
+ * Requires base58 decode to exactly 32 bytes and round-trips to the same string.
31
+ */
32
+ function isValidSolanaPublicKey(address) {
33
+ if (typeof address !== 'string' || address.trim() !== address || address.length === 0)
34
+ return false;
35
+ try {
36
+ const publicKey = new web3_js_1.PublicKey(address);
37
+ return publicKey.toBytes().length === 32 && publicKey.toBase58() === address;
38
+ }
39
+ catch {
40
+ return false;
41
+ }
42
+ }
43
+ /** Backwards-compatible alias for older callers. */
44
+ exports.isValidPaymentAddress = isValidSolanaPublicKey;
45
+ /** Standard protocol fee rate: 500 basis points, which is 5% of the price paid. */
46
+ exports.PROTOCOL_FEE_BPS = 500;
47
+ /** Launch rate: 250 basis points (2.5%) for payments made before LAUNCH_RATE_ENDS_AT_MS. */
48
+ exports.LAUNCH_PROTOCOL_FEE_BPS = 250;
49
+ /**
50
+ * 2027-04-01T00:00:00Z in milliseconds. The escrow program holds the same
51
+ * instant (LAUNCH_RATE_ENDS_UNIX, in seconds) and reads it at payout.
52
+ */
53
+ exports.LAUNCH_RATE_ENDS_AT_MS = 1806537600000;
54
+ /** Either side of the switch, how long a payment may still be checked at the other rate (block times and clocks drift). */
55
+ exports.FEE_RATE_SWITCH_GRACE_MS = 10 * 60 * 1000;
56
+ /** The protocol fee rate in force at `atMs` (milliseconds since the epoch). */
57
+ function protocolFeeBpsAt(atMs = Date.now()) {
58
+ return atMs < exports.LAUNCH_RATE_ENDS_AT_MS ? exports.LAUNCH_PROTOCOL_FEE_BPS : exports.PROTOCOL_FEE_BPS;
59
+ }
60
+ /**
61
+ * The rates a payment made around `atMs` may carry: the rate then, plus the
62
+ * other rate within FEE_RATE_SWITCH_GRACE_MS of the switch. With no time
63
+ * known, both.
64
+ */
65
+ function protocolFeeBpsNear(atMs) {
66
+ if (atMs === undefined || atMs === null || !Number.isFinite(atMs))
67
+ return [exports.LAUNCH_PROTOCOL_FEE_BPS, exports.PROTOCOL_FEE_BPS];
68
+ if (Math.abs(atMs - exports.LAUNCH_RATE_ENDS_AT_MS) <= exports.FEE_RATE_SWITCH_GRACE_MS)
69
+ return [exports.LAUNCH_PROTOCOL_FEE_BPS, exports.PROTOCOL_FEE_BPS];
70
+ return [protocolFeeBpsAt(atMs)];
71
+ }
72
+ /** Ceiling on the protocol fee for a SOL payment: 0.1 SOL. Token payments have no ceiling. */
73
+ exports.SOL_PROTOCOL_FEE_CAP_LAMPORTS = BigInt(100000000);
74
+ const BPS_DENOMINATOR = 10000;
75
+ /** Highest fee rate this package will state or verify: 10%. Guards against a mistyped configuration. */
76
+ const MAX_PROTOCOL_FEE_BPS = 1000;
77
+ /**
78
+ * Currencies accepted for direct per-call payments. The token program is fixed
79
+ * per currency: USDC and AUDD are classic SPL Token mints, PYUSD and USDG are
80
+ * Token-2022 mints. The mint address itself always comes from configuration.
81
+ */
82
+ exports.DIRECT_PAYMENT_CURRENCIES = Object.freeze({
83
+ SOL: { decimals: 9 },
84
+ USDC: { decimals: 6, tokenProgram: spl_token_observer_1.SPL_TOKEN_PROGRAM_ID },
85
+ AUDD: { decimals: 6, tokenProgram: spl_token_observer_1.SPL_TOKEN_PROGRAM_ID },
86
+ PYUSD: { decimals: 6, tokenProgram: spl_token_observer_1.TOKEN_2022_PROGRAM_ID },
87
+ USDG: { decimals: 6, tokenProgram: spl_token_observer_1.TOKEN_2022_PROGRAM_ID },
88
+ });
89
+ /** Looks up a direct payment currency without reading inherited object keys. */
90
+ function directPaymentCurrency(currency) {
91
+ return Object.prototype.hasOwnProperty.call(exports.DIRECT_PAYMENT_CURRENCIES, currency) ? exports.DIRECT_PAYMENT_CURRENCIES[currency] : undefined;
92
+ }
93
+ /**
94
+ * Mainnet mint addresses, read on-chain on 20 November 2026. Reference values
95
+ * for operator configuration; nothing in this package uses them by default.
96
+ */
97
+ exports.MAINNET_STABLECOIN_MINTS = Object.freeze({
98
+ USDC: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v',
99
+ AUDD: 'AUDDttiEpCydTm7joUMbYddm72jAWXZnCpPZtDoxqBSw',
100
+ PYUSD: '2b1kV6DkPAnxd5ixfnxCpjxmKwqjjaYmCZfHsFu24GXo',
101
+ USDG: '2u1tszSeqZ3qBWF3uNGPFc8TzMk2tdiwknnRMWGWjGWH',
102
+ });
103
+ /**
104
+ * Converts a decimal amount to whole base units without floating point
105
+ * multiplication. Returns undefined for anything that is not a positive amount
106
+ * with at most `decimals` decimal places.
107
+ */
108
+ function decimalToBaseUnits(amount, decimals) {
109
+ if (!Number.isInteger(decimals) || decimals < 0 || decimals > 18)
110
+ return undefined;
111
+ let text;
112
+ if (typeof amount === 'number') {
113
+ if (!Number.isFinite(amount) || amount <= 0)
114
+ return undefined;
115
+ // toFixed avoids exponent notation for small numbers; one extra place exposes
116
+ // a value finer than the smallest unit instead of silently rounding it.
117
+ text = amount.toFixed(decimals + 1).replace(/0+$/, '').replace(/\.$/, '');
118
+ }
119
+ else {
120
+ text = amount;
121
+ }
122
+ const match = new RegExp(`^(\\d+)(?:\\.(\\d{1,${Math.max(decimals, 1)}}))?$`).exec(text);
123
+ if (!match || (decimals === 0 && match[2] !== undefined))
124
+ return undefined;
125
+ const units = BigInt(match[1]) * BigInt(10) ** BigInt(decimals) + BigInt((match[2] ?? '').padEnd(decimals, '0') || '0');
126
+ return units > BigInt(0) ? units : undefined;
127
+ }
128
+ /** Renders whole base units as a decimal string with no trailing zeros. */
129
+ function baseUnitsToDecimal(units, decimals) {
130
+ const text = units.toString().padStart(decimals + 1, '0');
131
+ const whole = text.slice(0, text.length - decimals);
132
+ const fraction = decimals === 0 ? '' : text.slice(text.length - decimals).replace(/0+$/, '');
133
+ return fraction ? `${whole}.${fraction}` : whole;
134
+ }
135
+ /**
136
+ * Fee in base units: the price times the rate, rounded down, never above
137
+ * `capBaseUnits` when one is given. There is no minimum fee.
138
+ */
139
+ function protocolFeeBaseUnits(priceBaseUnits, bps = protocolFeeBpsAt(), capBaseUnits) {
140
+ if (!Number.isInteger(bps) || bps < 0 || bps > MAX_PROTOCOL_FEE_BPS)
141
+ throw new Error(`protocol fee bps must be a whole number from 0 to ${MAX_PROTOCOL_FEE_BPS}`);
142
+ if (priceBaseUnits < BigInt(0))
143
+ throw new Error('price must not be negative');
144
+ const fee = (priceBaseUnits * BigInt(bps)) / BigInt(BPS_DENOMINATOR);
145
+ return capBaseUnits !== undefined && fee > capBaseUnits ? capBaseUnits : fee;
146
+ }
147
+ /** Fee ceiling for a currency in its base units: 0.1 SOL for SOL, none for tokens. */
148
+ function protocolFeeCapBaseUnits(currency) {
149
+ return currency === 'SOL' ? exports.SOL_PROTOCOL_FEE_CAP_LAMPORTS : undefined;
150
+ }
151
+ function feeSplit(amount, currency, payTo, config, atMs = Date.now()) {
152
+ const decimals = directPaymentCurrency(currency)?.decimals;
153
+ if (decimals === undefined)
154
+ throw new Error(`a protocol fee is not supported for currency ${currency}`);
155
+ if (!isValidSolanaPublicKey(config.treasury))
156
+ throw new Error('protocol fee treasury must be a valid Solana public key');
157
+ if (config.treasury === payTo)
158
+ throw new Error('protocol fee treasury must differ from the payee');
159
+ const bps = config.bps ?? protocolFeeBpsAt(atMs);
160
+ const price = decimalToBaseUnits(amount, decimals);
161
+ if (price === undefined)
162
+ throw new Error(`amount must be a positive ${currency} amount with at most ${decimals} decimal places`);
163
+ const cap = protocolFeeCapBaseUnits(currency);
164
+ const feeUnits = protocolFeeBaseUnits(price, bps, cap);
165
+ const providerUnits = price - feeUnits;
166
+ return {
167
+ decimals,
168
+ feeUnits,
169
+ providerUnits,
170
+ terms: {
171
+ bps,
172
+ payTo: config.treasury,
173
+ amount: baseUnitsToDecimal(feeUnits, decimals),
174
+ providerAmount: baseUnitsToDecimal(providerUnits, decimals),
175
+ ...(cap !== undefined ? { cap: baseUnitsToDecimal(cap, decimals) } : {}),
176
+ },
177
+ };
178
+ }
179
+ /** Fee terms for a listed price, as a challenge states them. Throws on an unusable amount, currency or configuration. */
180
+ function protocolFeeTerms(amount, currency, payTo, config) {
181
+ return feeSplit(amount, currency, payTo, config).terms;
182
+ }
183
+ function buildX402Challenge(input, options = {}) {
184
+ if (!SUPPORTED_NETWORKS.includes(input.network))
185
+ throw new Error(`unsupported Solana network: ${input.network}`);
186
+ if (!isValidSolanaPublicKey(input.payTo))
187
+ throw new Error('payTo must be a valid Solana public key');
188
+ if (!input.nonce || typeof input.nonce !== 'string')
189
+ throw new Error('nonce is required');
190
+ if (!input.currency || typeof input.currency !== 'string')
191
+ throw new Error('currency is required');
192
+ if (String(input.amount).length === 0 || Number(input.amount) <= 0)
193
+ throw new Error('amount must be positive');
194
+ if (!input.endpoint || typeof input.endpoint !== 'string')
195
+ throw new Error('endpoint is required');
196
+ const challenge = { version: input.version ?? '1', ...input };
197
+ if (options.protocolFee)
198
+ challenge.fee = protocolFeeTerms(input.amount, input.currency, input.payTo, options.protocolFee);
199
+ return challenge;
200
+ }
201
+ /**
202
+ * Parse x402-request header into structured request.
203
+ * Expected format: JSON string with amount, currency, paymentAddress, nonce.
204
+ * @throws Error if header is invalid.
205
+ */
206
+ function parseX402Header(header) {
207
+ try {
208
+ const parsed = JSON.parse(header);
209
+ const amount = typeof parsed.amount === 'number' ? parsed.amount : typeof parsed.amount === 'string' ? Number(parsed.amount) : Number.NaN;
210
+ if (!Number.isFinite(amount) || amount <= 0)
211
+ throw new Error('amount must be a positive number');
212
+ if (!parsed.currency || typeof parsed.currency !== 'string')
213
+ throw new Error('currency is required (e.g., "SOL")');
214
+ const paymentAddress = typeof parsed.paymentAddress === 'string' ? parsed.paymentAddress : typeof parsed.payTo === 'string' ? parsed.payTo : undefined;
215
+ if (!paymentAddress)
216
+ throw new Error('paymentAddress is required');
217
+ if (!parsed.nonce || typeof parsed.nonce !== 'string')
218
+ throw new Error('nonce is required');
219
+ if (!isValidSolanaPublicKey(paymentAddress))
220
+ throw new Error('paymentAddress must be a valid Solana public key');
221
+ return {
222
+ amount,
223
+ currency: parsed.currency,
224
+ paymentAddress,
225
+ nonce: parsed.nonce,
226
+ network: typeof parsed.network === 'string' ? parsed.network : undefined,
227
+ endpoint: typeof parsed.endpoint === 'string' ? parsed.endpoint : undefined,
228
+ memo: typeof parsed.memo === 'string' ? parsed.memo : undefined,
229
+ payerCurrency: typeof parsed.payerCurrency === 'string' ? parsed.payerCurrency : undefined,
230
+ payerAddress: typeof parsed.payerAddress === 'string' ? parsed.payerAddress : undefined,
231
+ autoSwap: typeof parsed.autoSwap === 'boolean' ? parsed.autoSwap : false,
232
+ };
233
+ }
234
+ catch (e) {
235
+ if (e instanceof SyntaxError)
236
+ throw new Error('x402-request header is not valid JSON');
237
+ throw e;
238
+ }
239
+ }
240
+ function parseX402PaymentHeader(header) {
241
+ if (header.startsWith('demo:'))
242
+ return header;
243
+ try {
244
+ return JSON.parse(header);
245
+ }
246
+ catch {
247
+ return header;
248
+ }
249
+ }
250
+ function normalizeReceipt(receipt) {
251
+ if (typeof receipt === 'string' && receipt.startsWith('demo:')) {
252
+ return {
253
+ demo: true,
254
+ network: 'solana-devnet',
255
+ payTo: '',
256
+ amount: '',
257
+ currency: '',
258
+ nonce: receipt.slice('demo:'.length),
259
+ };
260
+ }
261
+ if (!receipt || typeof receipt !== 'object')
262
+ return undefined;
263
+ const record = receipt;
264
+ if (record.demo === true)
265
+ return undefined;
266
+ if (typeof record.network !== 'string' ||
267
+ typeof record.payTo !== 'string' ||
268
+ (typeof record.amount !== 'string' && typeof record.amount !== 'number') ||
269
+ typeof record.currency !== 'string' ||
270
+ typeof record.nonce !== 'string') {
271
+ return undefined;
272
+ }
273
+ return {
274
+ network: record.network,
275
+ payTo: record.payTo,
276
+ amount: record.amount,
277
+ currency: record.currency,
278
+ nonce: record.nonce,
279
+ signature: typeof record.signature === 'string' ? record.signature : undefined,
280
+ txSignature: typeof record.txSignature === 'string' ? record.txSignature : undefined,
281
+ payer: typeof record.payer === 'string' ? record.payer : undefined,
282
+ mint: typeof record.mint === 'string' ? record.mint : undefined,
283
+ destinationTokenAccount: typeof record.destinationTokenAccount === 'string' ? record.destinationTokenAccount : undefined,
284
+ demo: record.demo === true,
285
+ };
286
+ }
287
+ async function verifyDemoPaymentReceipt(input) {
288
+ if (!input.allowDemoPayment) {
289
+ return { ok: false, reason: 'demo_payment_disabled', message: 'demo x402 payments require explicit ALLOW_DEMO_X402_PAYMENT' };
290
+ }
291
+ const receipt = normalizeReceipt(input.receipt);
292
+ if (!receipt)
293
+ return { ok: false, reason: 'invalid_receipt', message: 'x402 payment receipt is not an explicit demo receipt' };
294
+ if (!receipt.demo)
295
+ return { ok: false, reason: 'unsupported_receipt', message: 'real Solana receipt verification is not implemented yet' };
296
+ const expected = input.challenge;
297
+ if (receipt.demo && receipt.payTo === '' && receipt.amount === '' && receipt.currency === '') {
298
+ receipt.payTo = expected.payTo;
299
+ receipt.amount = expected.amount;
300
+ receipt.currency = expected.currency;
301
+ receipt.network = expected.network;
302
+ }
303
+ if (receipt.network !== expected.network) {
304
+ return { ok: false, reason: 'wrong_network', message: 'receipt network does not match challenge', expected: expected.network, actual: receipt.network };
305
+ }
306
+ if (!isValidSolanaPublicKey(receipt.payTo)) {
307
+ return { ok: false, reason: 'invalid_payee', message: 'receipt payTo is not a valid Solana public key', actual: receipt.payTo };
308
+ }
309
+ if (receipt.payTo !== expected.payTo) {
310
+ return { ok: false, reason: 'wrong_payee', message: 'receipt payee does not match challenge', expected: expected.payTo, actual: receipt.payTo };
311
+ }
312
+ if (String(receipt.amount) !== String(expected.amount)) {
313
+ return { ok: false, reason: 'wrong_amount', message: 'receipt amount does not match challenge', expected: expected.amount, actual: receipt.amount };
314
+ }
315
+ if (receipt.currency !== expected.currency) {
316
+ return { ok: false, reason: 'wrong_currency', message: 'receipt currency does not match challenge', expected: expected.currency, actual: receipt.currency };
317
+ }
318
+ if (receipt.nonce !== expected.nonce) {
319
+ return { ok: false, reason: 'invalid_nonce', message: 'receipt nonce does not match challenge', expected: expected.nonce, actual: receipt.nonce };
320
+ }
321
+ if (input.replayStore) {
322
+ const accepted = await input.replayStore.checkAndStore(demoNonceReplayKey(receipt.nonce));
323
+ if (!accepted)
324
+ return { ok: false, reason: 'duplicate_nonce', message: 'receipt nonce has already been used', actual: receipt.nonce };
325
+ }
326
+ return { ok: true, receipt, demo: true };
327
+ }
328
+ class DemoPaymentVerifier {
329
+ constructor(allowDemoPayment) {
330
+ this.allowDemoPayment = allowDemoPayment;
331
+ }
332
+ verifyReceipt(receipt, challenge, replayStore) {
333
+ return verifyDemoPaymentReceipt({ receipt, challenge, allowDemoPayment: this.allowDemoPayment, replayStore });
334
+ }
335
+ }
336
+ exports.DemoPaymentVerifier = DemoPaymentVerifier;
337
+ /** Genesis hashes of the public Solana clusters. */
338
+ exports.SOLANA_GENESIS_HASHES = {
339
+ 'solana-mainnet-beta': '5eykt4UsFv8P8NJdTREpY1vzqKqZKvdpKuc147dw2N9d',
340
+ 'solana-devnet': 'EtWTRABZaYq6iMfeYKouRu166VU2xqa1wcaWoxPkrZBG',
341
+ 'solana-testnet': '4uhcVJyU9pJkvQyS88uRDiswHXSCkY3zQawwpjk2NsNY',
342
+ };
343
+ /** Default limit on how old a payment transaction may be when it is presented. */
344
+ exports.DEFAULT_MAX_TRANSACTION_AGE_SECONDS = 900;
345
+ /** Tolerance for a block time slightly ahead of the verifier's clock. */
346
+ const MAX_CLOCK_SKEW_SECONDS = 60;
347
+ class SolanaReceiptVerifier {
348
+ constructor(options) {
349
+ this.options = options;
350
+ }
351
+ /**
352
+ * Confirms the RPC endpoint serves the challenged network, so a transaction from
353
+ * a cheaper cluster cannot settle a challenge for another. Always enforced on
354
+ * solana-mainnet-beta against the public genesis hash. On other networks it runs
355
+ * only when expectedGenesisHash is set, so local validators keep working.
356
+ * A successful answer is remembered; a failure is asked again.
357
+ */
358
+ async clusterFailure(network) {
359
+ const mainnet = network === 'solana-mainnet-beta';
360
+ const configured = this.options.expectedGenesisHash;
361
+ if (!mainnet && configured === undefined)
362
+ return undefined;
363
+ const expected = mainnet ? exports.SOLANA_GENESIS_HASHES[network] : configured;
364
+ if (mainnet && configured !== undefined && configured !== expected) {
365
+ return { ok: false, reason: 'unsupported_receipt', message: 'expectedGenesisHash cannot replace the public mainnet genesis hash' };
366
+ }
367
+ const connection = this.options.connection;
368
+ if (typeof connection.getGenesisHash !== 'function') {
369
+ return { ok: false, reason: 'unsupported_receipt', message: 'network check requires a connection that reports its genesis hash' };
370
+ }
371
+ const actual = this.verifiedGenesisHash ?? await connection.getGenesisHash();
372
+ if (actual !== expected) {
373
+ return { ok: false, reason: 'wrong_network', message: 'RPC endpoint does not serve the challenged network', expected, actual };
374
+ }
375
+ this.verifiedGenesisHash = actual;
376
+ return undefined;
377
+ }
378
+ /** Refuses a transaction older than the configured limit, or one with no usable block time when a limit applies. */
379
+ ageFailure(parsed, network) {
380
+ const configured = this.options.maxTransactionAgeSeconds;
381
+ if (configured !== undefined && !(Number.isFinite(configured) && configured > 0)) {
382
+ return { ok: false, reason: 'unsupported_receipt', message: 'maxTransactionAgeSeconds must be a positive number' };
383
+ }
384
+ const limit = configured ?? (network === 'solana-mainnet-beta' ? exports.DEFAULT_MAX_TRANSACTION_AGE_SECONDS : undefined);
385
+ if (limit === undefined)
386
+ return undefined;
387
+ const blockTime = parsed.blockTime;
388
+ if (typeof blockTime !== 'number' || !Number.isSafeInteger(blockTime) || blockTime <= 0) {
389
+ return { ok: false, reason: 'invalid_receipt', message: 'transaction has no block time yet; present the receipt again shortly' };
390
+ }
391
+ const nowSeconds = Math.floor((this.options.now ?? Date.now)() / 1000);
392
+ const age = nowSeconds - blockTime;
393
+ if (age > limit) {
394
+ return { ok: false, reason: 'invalid_receipt', message: 'transaction is older than the accepted payment window', expected: `at most ${limit} seconds old`, actual: `${age} seconds old` };
395
+ }
396
+ if (age < -MAX_CLOCK_SKEW_SECONDS) {
397
+ return { ok: false, reason: 'invalid_receipt', message: 'transaction block time is in the future', actual: blockTime };
398
+ }
399
+ return undefined;
400
+ }
401
+ async verifyReceipt(receiptInput, challenge, replayStore, payerProof) {
402
+ if (!this.options.allowRealPayment) {
403
+ return { ok: false, reason: 'unsupported_receipt', message: 'real Solana receipt verification is disabled' };
404
+ }
405
+ const receipt = normalizeReceipt(receiptInput);
406
+ if (!receipt || receipt.demo)
407
+ return { ok: false, reason: 'invalid_receipt', message: 'real Solana receipt is required' };
408
+ const base = validateReceiptShape(receipt, challenge);
409
+ if (base)
410
+ return base;
411
+ const signature = receipt.signature ?? receipt.txSignature;
412
+ if (!signature)
413
+ return { ok: false, reason: 'invalid_receipt', message: 'receipt signature is required' };
414
+ const proofRequired = this.options.payerProof !== 'not-required';
415
+ if (proofRequired) {
416
+ if (!payerProof)
417
+ return { ok: false, reason: 'payer_proof_required', message: 'this verifier requires a payer proof check for each receipt (see directPaymentProofCheck)' };
418
+ if (!receipt.payer || !isValidSolanaPublicKey(receipt.payer))
419
+ return { ok: false, reason: 'payer_proof_required', message: 'the receipt must name the paying wallet in payer' };
420
+ }
421
+ const feeDecision = this.feeSplitFor(challenge);
422
+ if ('failure' in feeDecision)
423
+ return feeDecision.failure;
424
+ const split = feeDecision.split;
425
+ const wrongCluster = await this.clusterFailure(challenge.network);
426
+ if (wrongCluster)
427
+ return wrongCluster;
428
+ const parsed = asRecord(await this.options.connection.getParsedTransaction(signature, {
429
+ commitment: 'confirmed',
430
+ maxSupportedTransactionVersion: 0,
431
+ }));
432
+ const meta = asRecord(parsed?.meta);
433
+ if (!parsed || !meta || meta.err)
434
+ return { ok: false, reason: 'invalid_receipt', message: 'transaction is missing or failed' };
435
+ const tooOld = this.ageFailure(parsed, challenge.network);
436
+ if (tooOld)
437
+ return tooOld;
438
+ const unpaid = await this.challengePaymentFailure(parsed, receipt, challenge, signature, replayStore, split, proofRequired);
439
+ if (unpaid)
440
+ return unpaid;
441
+ if (proofRequired && payerProof && receipt.payer) {
442
+ // The payer named in the receipt signed the transaction and moved the funds
443
+ // (checked strictly above). The request must now be signed by that wallet, or
444
+ // by a key it delegated to, before the payment is recorded as used.
445
+ if (!transactionSignedBy(parsed, receipt.payer)) {
446
+ return { ok: false, reason: 'invalid_receipt', message: 'the receipt payer did not sign the payment transaction', actual: receipt.payer };
447
+ }
448
+ const proof = await payerProof({ network: challenge.network, txSignature: signature, payer: receipt.payer, payTo: challenge.payTo });
449
+ if (!proof.ok)
450
+ return { ok: false, reason: proof.reason, message: proof.message };
451
+ }
452
+ // A verified on-chain payment satisfies exactly one challenge. The nonce alone
453
+ // cannot enforce that, because the caller that presents the receipt may also
454
+ // choose the nonce, so the transaction signature is recorded as well. Without a
455
+ // replay store there is nothing to record it in, and the receipt is refused.
456
+ if (!replayStore) {
457
+ return { ok: false, reason: 'unsupported_receipt', message: 'real Solana receipt verification requires a replay store' };
458
+ }
459
+ // Recorded only after the transaction is shown to pay this challenge, so a
460
+ // third party cannot burn someone else's signature with a non-matching receipt.
461
+ // Both keys are recorded together or not at all. The nonce is stored under
462
+ // its own namespace, so a caller-chosen nonce can never equal another
463
+ // payment's transaction key or escrow key.
464
+ const accepted = await (0, nonce_1.checkAndStoreReplayKeys)(replayStore, [
465
+ transactionReplayKey(challenge.network, signature),
466
+ nonceReplayKey(challenge.network, challenge.payTo, receipt.nonce),
467
+ ]);
468
+ if (!accepted) {
469
+ return { ok: false, reason: 'duplicate_nonce', message: 'transaction signature or receipt nonce has already been used for a payment', actual: signature };
470
+ }
471
+ return split ? { ok: true, receipt, demo: false, fee: split.terms } : { ok: true, receipt, demo: false };
472
+ }
473
+ /**
474
+ * Works out the fee split this verifier requires for a challenge, from its own
475
+ * configuration. Fee terms printed in the challenge are only compared against
476
+ * that, so a challenge cannot lower the fee or redirect it.
477
+ */
478
+ feeSplitFor(challenge) {
479
+ const config = this.options.protocolFee;
480
+ if (config === undefined && challenge.network === 'solana-mainnet-beta') {
481
+ return { failure: { ok: false, reason: 'unsupported_receipt', message: "mainnet receipt verification requires a protocol fee treasury, or protocolFee: 'disabled'" } };
482
+ }
483
+ if (config === undefined || config === 'disabled') {
484
+ if (challenge.fee !== undefined) {
485
+ return { failure: { ok: false, reason: 'unsupported_receipt', message: 'challenge states a protocol fee but this verifier has none configured', actual: challenge.fee } };
486
+ }
487
+ return {};
488
+ }
489
+ let split;
490
+ try {
491
+ const nowMs = (this.options.now ?? Date.now)();
492
+ split = feeSplit(challenge.amount, challenge.currency, challenge.payTo, config, nowMs);
493
+ // Near the switch from the launch rate, a challenge issued at the other
494
+ // scheduled rate is still checked at the rate it states.
495
+ const stated = challenge.fee?.bps;
496
+ if (config.bps === undefined && stated !== undefined && stated !== split.terms.bps && protocolFeeBpsNear(nowMs).includes(stated)) {
497
+ split = feeSplit(challenge.amount, challenge.currency, challenge.payTo, { ...config, bps: stated }, nowMs);
498
+ }
499
+ }
500
+ catch (error) {
501
+ return { failure: { ok: false, reason: 'unsupported_receipt', message: error instanceof Error ? error.message : 'protocol fee cannot be computed for this challenge' } };
502
+ }
503
+ const stated = challenge.fee;
504
+ if (stated !== undefined && (stated.bps !== split.terms.bps
505
+ || stated.payTo !== split.terms.payTo
506
+ || stated.amount !== split.terms.amount
507
+ || stated.providerAmount !== split.terms.providerAmount)) {
508
+ return { failure: { ok: false, reason: 'unsupported_receipt', message: 'challenge fee terms do not match the configured protocol fee', expected: split.terms, actual: stated } };
509
+ }
510
+ return { split };
511
+ }
512
+ /** Returns a failure result when the parsed transaction does not settle the challenge, otherwise undefined. */
513
+ async challengePaymentFailure(parsed, receipt, challenge, signature, replayStore, split, strictPayer = false) {
514
+ // A fee that rounds down to zero leaves a single transfer of the full price.
515
+ const fee = split && split.feeUnits > BigInt(0) ? split : undefined;
516
+ if (challenge.currency === 'SOL') {
517
+ if (fee) {
518
+ return transactionHasSolSplit(parsed, receipt.payer, challenge.payTo, fee)
519
+ ? undefined
520
+ : unsatisfiedChallenge('transaction does not pay both the provider share and the protocol fee', fee.terms);
521
+ }
522
+ return transactionHasSolTransfer(parsed, receipt.payer, challenge.payTo, challenge.amount)
523
+ ? undefined
524
+ : unsatisfiedChallenge();
525
+ }
526
+ const token = directPaymentCurrency(challenge.currency);
527
+ const configuredMints = this.options.mints;
528
+ const configuredMint = (configuredMints && Object.prototype.hasOwnProperty.call(configuredMints, challenge.currency)
529
+ ? configuredMints[challenge.currency]
530
+ : undefined) ?? (challenge.currency === 'USDC' ? this.options.usdcMint : undefined);
531
+ if (token?.tokenProgram && (configuredMint || challenge.currency !== 'AUDD' || !this.options.auddMint)) {
532
+ const mint = configuredMint;
533
+ if (!mint) {
534
+ return { ok: false, reason: 'unsupported_receipt', message: `${challenge.currency} receipt verification requires a configured ${challenge.currency === 'USDC' ? 'usdcMint' : `mint (mints.${challenge.currency}${challenge.currency === 'AUDD' ? ' or the legacy auddMint' : ''})`}` };
535
+ }
536
+ if (receipt.mint !== undefined && receipt.mint !== mint) {
537
+ return unsatisfiedChallenge(`receipt mint does not match the configured ${challenge.currency} mint`, mint, receipt.mint);
538
+ }
539
+ if (fee) {
540
+ return transactionHasTokenSplit(parsed, receipt, challenge, mint, token.tokenProgram, fee, strictPayer)
541
+ ? undefined
542
+ : unsatisfiedChallenge('transaction does not pay both the provider share and the protocol fee', fee.terms);
543
+ }
544
+ return transactionHasTokenTransfer(parsed, receipt, challenge, mint, token.tokenProgram, strictPayer)
545
+ ? undefined
546
+ : unsatisfiedChallenge();
547
+ }
548
+ if (challenge.currency === 'AUDD') {
549
+ // Legacy AUDD exact receipts state the amount in base units and carry no
550
+ // fee split. A deployment that takes a fee must configure `mints.AUDD`.
551
+ if (split) {
552
+ return { ok: false, reason: 'unsupported_receipt', message: 'a protocol fee on AUDD requires the AUDD mint in `mints`, not the legacy auddMint option' };
553
+ }
554
+ if (strictPayer) {
555
+ return { ok: false, reason: 'unsupported_receipt', message: 'a payer proof on AUDD requires the AUDD mint in `mints`, not the legacy auddMint option' };
556
+ }
557
+ const mint = this.options.auddMint;
558
+ if (!mint) {
559
+ return { ok: false, reason: 'unsupported_receipt', message: 'AUDD receipt verification requires a configured auddMint' };
560
+ }
561
+ if (receipt.mint !== undefined && receipt.mint !== mint) {
562
+ return unsatisfiedChallenge('receipt mint does not match the configured AUDD mint', mint, receipt.mint);
563
+ }
564
+ const result = await (0, spl_token_observer_1.verifySplTransferCheckedObservation)({
565
+ parsedTransaction: parsed,
566
+ commitment: 'confirmed',
567
+ replayStore,
568
+ evidenceSource: 'parsed-rpc-transaction',
569
+ expected: {
570
+ network: challenge.network,
571
+ signature,
572
+ mint,
573
+ tokenProgram: this.options.auddTokenProgram ?? spl_token_observer_1.SPL_TOKEN_PROGRAM_ID,
574
+ payTo: challenge.payTo,
575
+ amountBaseUnits: String(challenge.amount),
576
+ destinationTokenAccount: receipt.destinationTokenAccount,
577
+ authority: receipt.payer,
578
+ memo: challenge.memo,
579
+ memoRequired: challenge.memo !== undefined,
580
+ },
581
+ });
582
+ if (result.ok)
583
+ return undefined;
584
+ return unsatisfiedChallenge(`transaction does not satisfy x402 challenge payment terms (${result.reason}: ${result.message})`, result.expected, result.actual);
585
+ }
586
+ return { ok: false, reason: 'unsupported_receipt', message: `unsupported challenge currency: ${challenge.currency}` };
587
+ }
588
+ }
589
+ exports.SolanaReceiptVerifier = SolanaReceiptVerifier;
590
+ /** Replay key for a settled transaction; namespaced so it cannot collide with a caller-chosen nonce. */
591
+ function transactionReplayKey(network, signature) {
592
+ return `x402:tx:${network}:${signature}`;
593
+ }
594
+ /** Longest receipt nonce accepted, so every namespaced key fits the replay ledger's 300-character limit. */
595
+ exports.MAX_RECEIPT_NONCE_LENGTH = 128;
596
+ const RECEIPT_NONCE = new RegExp(`^[A-Za-z0-9._:~-]{1,${exports.MAX_RECEIPT_NONCE_LENGTH}}$`);
597
+ /** True for a nonce of 1 to 128 characters from letters, digits and `. _ : ~ -`. */
598
+ function isValidReceiptNonce(nonce) {
599
+ return typeof nonce === 'string' && RECEIPT_NONCE.test(nonce);
600
+ }
601
+ /** Replay key for a real payment's challenge nonce, scoped to the network and payee. */
602
+ function nonceReplayKey(network, payTo, nonce) {
603
+ return `x402:nonce:${network}:${payTo}:${nonce}`;
604
+ }
605
+ /** Replay key for a demo receipt's nonce; demo keys never share a namespace with real payments. */
606
+ function demoNonceReplayKey(nonce) {
607
+ return `x402:demo-nonce:${nonce}`;
608
+ }
609
+ function unsatisfiedChallenge(message = 'transaction does not satisfy x402 challenge payment terms', expected, actual) {
610
+ return { ok: false, reason: 'invalid_receipt', message, expected, actual };
611
+ }
612
+ function validateReceiptShape(receipt, challenge) {
613
+ if (receipt.network !== challenge.network)
614
+ return { ok: false, reason: 'wrong_network', message: 'receipt network does not match challenge', expected: challenge.network, actual: receipt.network };
615
+ if (!isValidSolanaPublicKey(receipt.payTo))
616
+ return { ok: false, reason: 'invalid_payee', message: 'receipt payTo is not a valid Solana public key', actual: receipt.payTo };
617
+ if (receipt.payTo !== challenge.payTo)
618
+ return { ok: false, reason: 'wrong_payee', message: 'receipt payee does not match challenge', expected: challenge.payTo, actual: receipt.payTo };
619
+ if (String(receipt.amount) !== String(challenge.amount))
620
+ return { ok: false, reason: 'wrong_amount', message: 'receipt amount does not match challenge', expected: challenge.amount, actual: receipt.amount };
621
+ if (receipt.currency !== challenge.currency)
622
+ return { ok: false, reason: 'wrong_currency', message: 'receipt currency does not match challenge', expected: challenge.currency, actual: receipt.currency };
623
+ if (receipt.nonce !== challenge.nonce)
624
+ return { ok: false, reason: 'invalid_nonce', message: 'receipt nonce does not match challenge', expected: challenge.nonce, actual: receipt.nonce };
625
+ if (!isValidReceiptNonce(receipt.nonce))
626
+ return { ok: false, reason: 'invalid_nonce', message: `receipt nonce must be 1 to ${exports.MAX_RECEIPT_NONCE_LENGTH} characters of letters, digits and . _ : ~ -` };
627
+ return undefined;
628
+ }
629
+ /**
630
+ * Converts a SOL amount to lamports without floating point multiplication, which
631
+ * can land one lamport above the exact value (0.00051 SOL becomes 510000.00000000006,
632
+ * which rounds up to 510001 and rejects an exact payment).
633
+ * Returns undefined for anything that is not a positive amount with at most nine
634
+ * decimal places.
635
+ */
636
+ function solAmountToLamports(amount) {
637
+ return decimalToBaseUnits(amount, 9);
638
+ }
639
+ function lamportsOf(value) {
640
+ if (typeof value === 'bigint')
641
+ return value >= BigInt(0) ? value : undefined;
642
+ if (typeof value === 'number')
643
+ return Number.isSafeInteger(value) && value >= 0 ? BigInt(value) : undefined;
644
+ if (typeof value === 'string' && /^\d+$/.test(value))
645
+ return BigInt(value);
646
+ return undefined;
647
+ }
648
+ function transactionHasSolTransfer(parsed, payer, payTo, amountSol) {
649
+ const lamports = solAmountToLamports(amountSol);
650
+ if (lamports === undefined)
651
+ return false;
652
+ const instructions = parsedInstructions(parsed);
653
+ return instructions.some((ix) => {
654
+ const parsedInstruction = asRecord(ix.parsed);
655
+ const info = asRecord(parsedInstruction?.info);
656
+ const paid = lamportsOf(info?.lamports);
657
+ return publicKeyText(ix.programId) === web3_js_1.SystemProgram.programId.toBase58()
658
+ && parsedInstruction?.type === 'transfer'
659
+ && (!payer || info?.source === payer)
660
+ && info?.destination === payTo
661
+ && paid !== undefined
662
+ && paid >= lamports;
663
+ });
664
+ }
665
+ /**
666
+ * Both legs of a fee-bearing SOL payment must be present as separate transfers:
667
+ * the provider's share to the payee and the fee to the treasury. One transfer
668
+ * cannot count for both.
669
+ */
670
+ function transactionHasSolSplit(parsed, payer, payTo, split) {
671
+ const transfers = parsedInstructions(parsed).map((ix) => {
672
+ const parsedInstruction = asRecord(ix.parsed);
673
+ const info = asRecord(parsedInstruction?.info);
674
+ const paid = lamportsOf(info?.lamports);
675
+ const isTransfer = publicKeyText(ix.programId) === web3_js_1.SystemProgram.programId.toBase58()
676
+ && parsedInstruction?.type === 'transfer'
677
+ && (!payer || info?.source === payer)
678
+ && paid !== undefined;
679
+ return isTransfer ? { destination: info?.destination, paid: paid } : undefined;
680
+ });
681
+ const providerLeg = transfers.findIndex((t) => t !== undefined && t.destination === payTo && t.paid >= split.providerUnits);
682
+ const feeLeg = transfers.findIndex((t, index) => index !== providerLeg && t !== undefined && t.destination === split.terms.payTo && t.paid >= split.feeUnits);
683
+ return providerLeg !== -1 && feeLeg !== -1;
684
+ }
685
+ /** Raw base units moved by a parsed `transferChecked`, or undefined when they cannot be read exactly. */
686
+ function tokenTransferBaseUnits(info, decimals) {
687
+ const tokenAmount = asRecord(info.tokenAmount);
688
+ if (!tokenAmount)
689
+ return undefined;
690
+ if (tokenAmount.decimals !== undefined && tokenAmount.decimals !== decimals)
691
+ return undefined;
692
+ if (typeof tokenAmount.amount === 'string' && /^\d+$/.test(tokenAmount.amount))
693
+ return BigInt(tokenAmount.amount);
694
+ const ui = tokenAmount.uiAmountString;
695
+ return typeof ui === 'string' ? decimalToBaseUnits(ui, decimals) : undefined;
696
+ }
697
+ /**
698
+ * Both legs of a fee-bearing token payment must be present as separate
699
+ * `transferChecked` instructions of the configured mint: the provider's share to
700
+ * a token account the payee owns, and the fee to a token account the treasury owns.
701
+ */
702
+ function transactionHasTokenSplit(parsed, receipt, challenge, mint, tokenProgram, split, strictPayer = false) {
703
+ const legs = parsedInstructions(parsed).map((ix) => {
704
+ const parsedInstruction = asRecord(ix.parsed);
705
+ const info = asRecord(parsedInstruction?.info);
706
+ if (!info || parsedInstruction?.type !== 'transferChecked')
707
+ return undefined;
708
+ if (!instructionIsFromTokenProgram(ix, tokenProgram))
709
+ return undefined;
710
+ if (info.mint !== mint)
711
+ return undefined;
712
+ if (!authorityMatches(info, receipt.payer, strictPayer))
713
+ return undefined;
714
+ const units = tokenTransferBaseUnits(info, split.decimals);
715
+ if (units === undefined || typeof info.destination !== 'string')
716
+ return undefined;
717
+ return { destination: info.destination, units };
718
+ });
719
+ const providerLeg = legs.findIndex((leg) => leg !== undefined
720
+ && leg.units === split.providerUnits
721
+ && (!receipt.destinationTokenAccount || leg.destination === receipt.destinationTokenAccount)
722
+ && transactionTokenAccountOwnedBy(parsed, leg.destination, mint, challenge.payTo)
723
+ && tokenAccountNetlyCredited(parsed, leg.destination, mint, challenge.payTo, tokenProgram, split.providerUnits));
724
+ const feeLeg = legs.findIndex((leg, index) => index !== providerLeg && leg !== undefined
725
+ && leg.units === split.feeUnits
726
+ && transactionTokenAccountOwnedBy(parsed, leg.destination, mint, split.terms.payTo)
727
+ && tokenAccountNetlyCredited(parsed, leg.destination, mint, split.terms.payTo, tokenProgram, split.feeUnits));
728
+ return providerLeg !== -1 && feeLeg !== -1;
729
+ }
730
+ /**
731
+ * A matching `transferChecked` only shows that units passed through an account.
732
+ * Payment is what stays there: the account's balance after the transaction minus
733
+ * its balance before must cover `requiredUnits`, the account must belong to
734
+ * `owner` before (when it existed) and after, and no instruction in the
735
+ * transaction, inner instructions included, may move tokens out of it or change
736
+ * its authority.
737
+ */
738
+ function tokenAccountNetlyCredited(parsed, tokenAccount, mint, owner, tokenProgram, requiredUnits) {
739
+ if (requiredUnits <= BigInt(0))
740
+ return false;
741
+ const meta = asRecord(parsed.meta);
742
+ const accountKeys = asArray(asRecord(asRecord(parsed.transaction)?.message)?.accountKeys);
743
+ // Both balance lists are needed to read a net change; a missing one is refused.
744
+ if (!meta || !accountKeys || !Array.isArray(meta.preTokenBalances) || !Array.isArray(meta.postTokenBalances))
745
+ return false;
746
+ const index = accountKeys.findIndex((key) => accountKeyText(key) === tokenAccount);
747
+ if (index < 0)
748
+ return false;
749
+ const post = tokenBalanceAt(meta.postTokenBalances, index, mint);
750
+ if (!post || post.owner !== owner)
751
+ return false;
752
+ const pre = tokenBalanceAt(meta.preTokenBalances, index, mint);
753
+ if (pre === null)
754
+ return false;
755
+ if (pre && pre.owner !== owner)
756
+ return false;
757
+ const before = pre ? pre.units : BigInt(0);
758
+ if (post.units - before < requiredUnits)
759
+ return false;
760
+ return !tokenAccountTouchedAsSource(parsed, tokenAccount, tokenProgram);
761
+ }
762
+ /**
763
+ * The balance entry for an account index and mint. `undefined` when there is no
764
+ * entry; `null` when an entry exists but its amount cannot be read exactly.
765
+ */
766
+ function tokenBalanceAt(balances, accountIndex, mint) {
767
+ const list = asArray(balances);
768
+ if (!list)
769
+ return undefined;
770
+ const entries = list.map((item) => asRecord(item)).filter((item) => item !== undefined && item.accountIndex === accountIndex);
771
+ if (entries.length === 0)
772
+ return undefined;
773
+ if (entries.length > 1)
774
+ return null;
775
+ const entry = entries[0];
776
+ if (entry.mint !== mint)
777
+ return null;
778
+ const amount = asRecord(entry.uiTokenAmount)?.amount;
779
+ if (typeof amount !== 'string' || !/^\d+$/.test(amount))
780
+ return null;
781
+ return { owner: entry.owner, units: BigInt(amount) };
782
+ }
783
+ /** Token instruction types that take funds or control away from the account they name. */
784
+ const TOKEN_ACCOUNT_DEBIT_FIELDS = ['source', 'account'];
785
+ const TOKEN_ACCOUNT_SAFE_TYPES = new Set(['initializeAccount', 'initializeAccount2', 'initializeAccount3', 'getAccountDataSize', 'initializeImmutableOwner', 'syncNative', 'reallocate']);
786
+ /**
787
+ * True when any parsed instruction of the token program, top level or inner,
788
+ * names the account as a source (transfers), or as the account it acts on
789
+ * (burn, close, approve, set authority, freeze, withdraw withheld fees and so on).
790
+ * Unparsed instructions of the token program also count, because what they do
791
+ * cannot be read. Instructions that only create the account are allowed.
792
+ */
793
+ function tokenAccountTouchedAsSource(parsed, tokenAccount, tokenProgram) {
794
+ const accountKeys = asArray(asRecord(asRecord(parsed.transaction)?.message)?.accountKeys) ?? [];
795
+ const inner = (asArray(asRecord(parsed.meta)?.innerInstructions) ?? [])
796
+ .flatMap((group) => asArray(asRecord(group)?.instructions) ?? [])
797
+ .map((item) => asRecord(item))
798
+ .filter((item) => item !== undefined);
799
+ return [...parsedInstructions(parsed), ...inner].some((ix) => {
800
+ if (!instructionIsFromTokenProgram(ix, tokenProgram))
801
+ return false;
802
+ const parsedInstruction = asRecord(ix.parsed);
803
+ const info = asRecord(parsedInstruction?.info);
804
+ if (!parsedInstruction || !info) {
805
+ // Unparsed: refuse if the account appears among its accounts at all.
806
+ const accounts = asArray(ix.accounts) ?? [];
807
+ return accounts.some((entry) => (typeof entry === 'number' ? accountKeyText(accountKeys[entry]) : publicKeyText(entry)) === tokenAccount);
808
+ }
809
+ if (typeof parsedInstruction.type === 'string' && TOKEN_ACCOUNT_SAFE_TYPES.has(parsedInstruction.type))
810
+ return false;
811
+ return TOKEN_ACCOUNT_DEBIT_FIELDS.some((field) => info[field] === tokenAccount);
812
+ });
813
+ }
814
+ function accountKeyText(key) {
815
+ if (typeof key === 'string')
816
+ return key;
817
+ const record = asRecord(key);
818
+ if (record && 'pubkey' in record)
819
+ return publicKeyText(record.pubkey);
820
+ return publicKeyText(key);
821
+ }
822
+ /**
823
+ * `mint` is the verifier's configured mint, never a value taken from the receipt.
824
+ * Only `transferChecked` is accepted: it names its mint and carries a decimal-aware
825
+ * amount, whereas a plain `transfer` names no mint and reports raw base units.
826
+ */
827
+ /** True only when a parsed instruction names the token program the currency is issued under. */
828
+ function instructionIsFromTokenProgram(ix, tokenProgram) {
829
+ return publicKeyText(ix.programId) === tokenProgram;
830
+ }
831
+ /**
832
+ * The token transfer's signing authority against the receipt's payer. Strict
833
+ * (a payer proof is required): the authority must be stated and be the payer,
834
+ * so a multisig or unparsed authority does not count.
835
+ */
836
+ function authorityMatches(info, payer, strict) {
837
+ if (strict)
838
+ return typeof payer === 'string' && info.authority === payer;
839
+ return !(payer && info.authority && info.authority !== payer);
840
+ }
841
+ /** True when `key` is among the transaction's signers. */
842
+ function transactionSignedBy(parsed, key) {
843
+ const accountKeys = asArray(asRecord(asRecord(parsed.transaction)?.message)?.accountKeys);
844
+ if (!accountKeys)
845
+ return false;
846
+ return accountKeys.some((entry) => {
847
+ const record = asRecord(entry);
848
+ return record !== undefined && record.signer === true && publicKeyText(record.pubkey) === key;
849
+ });
850
+ }
851
+ function transactionHasTokenTransfer(parsed, receipt, challenge, mint, tokenProgram, strictPayer = false) {
852
+ const expectedAmount = String(challenge.amount);
853
+ const decimals = directPaymentCurrency(challenge.currency)?.decimals;
854
+ const expectedUnits = decimals === undefined ? undefined : decimalToBaseUnits(challenge.amount, decimals);
855
+ const instructions = parsedInstructions(parsed);
856
+ return instructions.some((ix) => {
857
+ const parsedInstruction = asRecord(ix.parsed);
858
+ const info = asRecord(parsedInstruction?.info);
859
+ if (!info || parsedInstruction?.type !== 'transferChecked')
860
+ return false;
861
+ if (!instructionIsFromTokenProgram(ix, tokenProgram))
862
+ return false;
863
+ if (info.mint !== mint)
864
+ return false;
865
+ if (!authorityMatches(info, receipt.payer, strictPayer))
866
+ return false;
867
+ if (receipt.destinationTokenAccount && info.destination !== receipt.destinationTokenAccount)
868
+ return false;
869
+ const tokenAmountRecord = asRecord(info.tokenAmount);
870
+ const tokenAmount = tokenAmountRecord?.uiAmountString ?? tokenAmountRecord?.uiAmount;
871
+ if (String(tokenAmount) !== expectedAmount)
872
+ return false;
873
+ const destination = typeof info.destination === 'string' ? info.destination : receipt.destinationTokenAccount;
874
+ if (!destination)
875
+ return false;
876
+ if (!transactionTokenAccountOwnedBy(parsed, destination, mint, challenge.payTo))
877
+ return false;
878
+ return expectedUnits !== undefined && tokenAccountNetlyCredited(parsed, destination, mint, challenge.payTo, tokenProgram, expectedUnits);
879
+ });
880
+ }
881
+ function transactionTokenAccountOwnedBy(parsed, tokenAccount, mint, owner) {
882
+ const accountKeys = asArray(asRecord(asRecord(parsed.transaction)?.message)?.accountKeys);
883
+ const postTokenBalances = asArray(asRecord(parsed.meta)?.postTokenBalances);
884
+ if (!accountKeys || !postTokenBalances)
885
+ return false;
886
+ return postTokenBalances.some((item) => {
887
+ const balance = asRecord(item);
888
+ if (!balance)
889
+ return false;
890
+ if (balance.owner !== owner)
891
+ return false;
892
+ if (mint && balance.mint !== mint)
893
+ return false;
894
+ if (!Number.isSafeInteger(balance.accountIndex))
895
+ return false;
896
+ const key = accountKeys[Number(balance.accountIndex)];
897
+ const keyRecord = asRecord(key);
898
+ const pubkey = typeof key === 'string' ? key : publicKeyText(keyRecord?.pubkey) ?? publicKeyText(key);
899
+ return pubkey === tokenAccount;
900
+ });
901
+ }
902
+ function parsedInstructions(parsed) {
903
+ return (asArray(asRecord(asRecord(parsed.transaction)?.message)?.instructions) ?? [])
904
+ .map((item) => asRecord(item))
905
+ .filter((item) => item !== undefined);
906
+ }
907
+ function asArray(value) {
908
+ return Array.isArray(value) ? value : undefined;
909
+ }
910
+ function asRecord(value) {
911
+ return value !== null && typeof value === 'object' ? value : undefined;
912
+ }
913
+ function publicKeyText(value) {
914
+ if (typeof value === 'string')
915
+ return value;
916
+ if (value === null || typeof value !== 'object')
917
+ return undefined;
918
+ const toString = value.toString;
919
+ if (typeof toString !== 'function' || toString === Object.prototype.toString)
920
+ return undefined;
921
+ const rendered = toString.call(value);
922
+ return typeof rendered === 'string' ? rendered : undefined;
923
+ }
924
+ /**
925
+ * Send a payment via Solana SystemProgram.transfer.
926
+ * In this package version, this remains a test stub; no funding transactions are submitted.
927
+ */
928
+ async function sendPayment(request, options = {}) {
929
+ let swapMeta;
930
+ if ((0, jupiter_1.needsAutoSwap)(request)) {
931
+ if (!options.swapClient)
932
+ throw new Error('token_mismatch_requires_swap_client');
933
+ if (!request.payerAddress)
934
+ throw new Error('payerAddress is required when autoSwap=true');
935
+ const swapResult = await options.swapClient.swap({
936
+ inputMint: (0, jupiter_1.resolveMint)(request.payerCurrency || request.currency),
937
+ outputMint: (0, jupiter_1.resolveMint)(request.currency),
938
+ amount: String(request.amount),
939
+ userPublicKey: request.payerAddress,
940
+ slippageBps: options.slippageBps ?? 50,
941
+ });
942
+ swapMeta = {
943
+ performed: true,
944
+ fromCurrency: request.payerCurrency,
945
+ toCurrency: request.currency,
946
+ orderId: swapResult.orderId,
947
+ executeId: swapResult.executeId,
948
+ inAmount: swapResult.inAmount,
949
+ outAmount: swapResult.outAmount,
950
+ };
951
+ }
952
+ else {
953
+ swapMeta = {
954
+ performed: false,
955
+ fromCurrency: request.payerCurrency || request.currency,
956
+ toCurrency: request.currency,
957
+ };
958
+ }
959
+ return {
960
+ txSignature: 'mock_tx_signature_' + Math.random().toString(36).substring(7),
961
+ slot: Math.floor(Math.random() * 1000000),
962
+ lamports: request.amount,
963
+ nonce: request.nonce,
964
+ settlementCurrency: request.currency,
965
+ swap: swapMeta,
966
+ };
967
+ }