@alleyboss/micropay-solana-x402-paywall 3.3.14 → 3.5.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.
@@ -0,0 +1,402 @@
1
+ import { Connection, PublicKey, ComputeBudgetProgram, SystemProgram, TransactionMessage, VersionedTransaction, Keypair } from '@solana/web3.js';
2
+
3
+ // src/fetch/x402Fetch.ts
4
+
5
+ // src/fetch/types.ts
6
+ var X402ErrorCode = {
7
+ /** User rejected the payment */
8
+ USER_REJECTED: "USER_REJECTED",
9
+ /** Insufficient wallet balance */
10
+ INSUFFICIENT_BALANCE: "INSUFFICIENT_BALANCE",
11
+ /** Transaction failed on-chain */
12
+ TRANSACTION_FAILED: "TRANSACTION_FAILED",
13
+ /** Payment verification failed */
14
+ VERIFICATION_FAILED: "VERIFICATION_FAILED",
15
+ /** Network/RPC error */
16
+ NETWORK_ERROR: "NETWORK_ERROR",
17
+ /** Invalid 402 response format */
18
+ INVALID_402_RESPONSE: "INVALID_402_RESPONSE",
19
+ /** Payment timeout */
20
+ TIMEOUT: "TIMEOUT",
21
+ /** Wallet not connected */
22
+ WALLET_NOT_CONNECTED: "WALLET_NOT_CONNECTED",
23
+ /** Payment amount exceeds maxPaymentPerRequest */
24
+ AMOUNT_EXCEEDS_LIMIT: "AMOUNT_EXCEEDS_LIMIT",
25
+ /** Recipient address not in allowedRecipients whitelist */
26
+ RECIPIENT_NOT_ALLOWED: "RECIPIENT_NOT_ALLOWED",
27
+ /** Rate limit exceeded */
28
+ RATE_LIMIT_EXCEEDED: "RATE_LIMIT_EXCEEDED"
29
+ };
30
+
31
+ // src/fetch/errors.ts
32
+ var X402PaymentError = class _X402PaymentError extends Error {
33
+ constructor(message, code, requirements, cause) {
34
+ super(message);
35
+ this.code = code;
36
+ this.requirements = requirements;
37
+ this.cause = cause;
38
+ if (Error.captureStackTrace) {
39
+ Error.captureStackTrace(this, _X402PaymentError);
40
+ }
41
+ }
42
+ name = "X402PaymentError";
43
+ /**
44
+ * Check if error is retryable
45
+ */
46
+ get isRetryable() {
47
+ const retryableCodes = [
48
+ X402ErrorCode.NETWORK_ERROR,
49
+ X402ErrorCode.TIMEOUT,
50
+ X402ErrorCode.TRANSACTION_FAILED
51
+ ];
52
+ return retryableCodes.includes(this.code);
53
+ }
54
+ /**
55
+ * Convert to JSON-serializable object
56
+ */
57
+ toJSON() {
58
+ return {
59
+ name: this.name,
60
+ message: this.message,
61
+ code: this.code,
62
+ requirements: this.requirements,
63
+ isRetryable: this.isRetryable
64
+ };
65
+ }
66
+ };
67
+ function userRejectedError(requirements) {
68
+ return new X402PaymentError(
69
+ "User rejected the payment request",
70
+ X402ErrorCode.USER_REJECTED,
71
+ requirements
72
+ );
73
+ }
74
+ function insufficientBalanceError(requirements, balance) {
75
+ return new X402PaymentError(
76
+ `Insufficient balance: have ${balance} lamports, need ${requirements.amount}`,
77
+ X402ErrorCode.INSUFFICIENT_BALANCE,
78
+ requirements
79
+ );
80
+ }
81
+ function transactionFailedError(requirements, cause) {
82
+ return new X402PaymentError(
83
+ `Transaction failed: ${cause?.message ?? "Unknown error"}`,
84
+ X402ErrorCode.TRANSACTION_FAILED,
85
+ requirements,
86
+ cause
87
+ );
88
+ }
89
+ function verificationFailedError(requirements, reason) {
90
+ return new X402PaymentError(
91
+ `Payment verification failed: ${reason ?? "Unknown reason"}`,
92
+ X402ErrorCode.VERIFICATION_FAILED,
93
+ requirements
94
+ );
95
+ }
96
+ function networkError(cause) {
97
+ return new X402PaymentError(
98
+ `Network error: ${cause?.message ?? "Connection failed"}`,
99
+ X402ErrorCode.NETWORK_ERROR,
100
+ void 0,
101
+ cause
102
+ );
103
+ }
104
+ function invalid402ResponseError(details) {
105
+ return new X402PaymentError(
106
+ `Invalid 402 response: ${details ?? "Missing or malformed payment requirements"}`,
107
+ X402ErrorCode.INVALID_402_RESPONSE
108
+ );
109
+ }
110
+ function timeoutError(requirements) {
111
+ return new X402PaymentError(
112
+ "Payment flow timed out",
113
+ X402ErrorCode.TIMEOUT,
114
+ requirements
115
+ );
116
+ }
117
+ function walletNotConnectedError() {
118
+ return new X402PaymentError(
119
+ "Wallet is not connected",
120
+ X402ErrorCode.WALLET_NOT_CONNECTED
121
+ );
122
+ }
123
+ function amountExceedsLimitError(requirements, limit) {
124
+ return new X402PaymentError(
125
+ `Payment amount ${requirements.amount} exceeds limit of ${limit} lamports`,
126
+ X402ErrorCode.AMOUNT_EXCEEDS_LIMIT,
127
+ requirements
128
+ );
129
+ }
130
+ function recipientNotAllowedError(requirements, recipient) {
131
+ return new X402PaymentError(
132
+ `Recipient ${recipient} is not in the allowed recipients list`,
133
+ X402ErrorCode.RECIPIENT_NOT_ALLOWED,
134
+ requirements
135
+ );
136
+ }
137
+ function rateLimitExceededError(limit, windowMs) {
138
+ return new X402PaymentError(
139
+ `Rate limit exceeded: max ${limit} payments per ${windowMs / 1e3}s`,
140
+ X402ErrorCode.RATE_LIMIT_EXCEEDED
141
+ );
142
+ }
143
+ function isX402PaymentError(error) {
144
+ return error instanceof X402PaymentError;
145
+ }
146
+ function isUserRejection(error) {
147
+ return isX402PaymentError(error) && error.code === X402ErrorCode.USER_REJECTED;
148
+ }
149
+
150
+ // src/shared/constants.ts
151
+ var RPC_ENDPOINTS = {
152
+ "mainnet-beta": "https://api.mainnet-beta.solana.com",
153
+ "devnet": "https://api.devnet.solana.com",
154
+ "testnet": "https://api.testnet.solana.com"
155
+ };
156
+ var DEFAULT_CONFIRMATION_TIMEOUT = 3e4;
157
+ var DEFAULT_MAX_RETRIES = 3;
158
+ var DEFAULT_RATE_LIMIT_WINDOW_MS = 6e4;
159
+ var DEFAULT_RATE_LIMIT_MAX_PAYMENTS = 10;
160
+
161
+ // src/fetch/x402Fetch.ts
162
+ function isKeypair(wallet) {
163
+ return wallet instanceof Keypair;
164
+ }
165
+ function isWalletConnected(wallet) {
166
+ if (isKeypair(wallet)) return true;
167
+ return wallet.connected && wallet.publicKey != null;
168
+ }
169
+ function getPublicKey(wallet) {
170
+ if (isKeypair(wallet)) return wallet.publicKey;
171
+ if (!wallet.publicKey) throw walletNotConnectedError();
172
+ return wallet.publicKey;
173
+ }
174
+ function parse402Response(response) {
175
+ const x402Header = response.headers.get("X-Payment-Requirements");
176
+ if (x402Header) {
177
+ try {
178
+ const parsed = JSON.parse(x402Header);
179
+ return {
180
+ payTo: parsed.payTo ?? parsed.recipient,
181
+ amount: String(parsed.amount),
182
+ asset: parsed.asset ?? "SOL",
183
+ network: parsed.network ?? "solana-mainnet",
184
+ description: parsed.description,
185
+ resource: parsed.resource,
186
+ maxAge: parsed.maxAge
187
+ };
188
+ } catch {
189
+ throw invalid402ResponseError("Invalid X-Payment-Requirements header");
190
+ }
191
+ }
192
+ const wwwAuth = response.headers.get("WWW-Authenticate");
193
+ if (wwwAuth?.startsWith("X402")) {
194
+ try {
195
+ const base64Part = wwwAuth.slice(5).trim();
196
+ const jsonStr = atob(base64Part);
197
+ const parsed = JSON.parse(jsonStr);
198
+ return {
199
+ payTo: parsed.payTo ?? parsed.recipient,
200
+ amount: String(parsed.amount),
201
+ asset: parsed.asset ?? "SOL",
202
+ network: parsed.network ?? "solana-mainnet",
203
+ description: parsed.description,
204
+ resource: parsed.resource,
205
+ maxAge: parsed.maxAge
206
+ };
207
+ } catch {
208
+ throw invalid402ResponseError("Invalid WWW-Authenticate header");
209
+ }
210
+ }
211
+ throw invalid402ResponseError("No payment requirements found in 402 response");
212
+ }
213
+ function buildPaymentHeader(signature) {
214
+ const payload = {
215
+ x402Version: 2,
216
+ scheme: "exact",
217
+ payload: { signature }
218
+ };
219
+ return `X402 ${btoa(JSON.stringify(payload))}`;
220
+ }
221
+ function createX402Fetch(config) {
222
+ const {
223
+ wallet,
224
+ network = "mainnet-beta",
225
+ connection: providedConnection,
226
+ facilitatorUrl: _facilitatorUrl,
227
+ // Reserved for future facilitator integration
228
+ onPaymentRequired,
229
+ onPaymentSuccess,
230
+ onPaymentError,
231
+ priorityFee,
232
+ maxRetries = DEFAULT_MAX_RETRIES,
233
+ timeout = DEFAULT_CONFIRMATION_TIMEOUT,
234
+ // Security options
235
+ maxPaymentPerRequest,
236
+ allowedRecipients,
237
+ // UX options
238
+ commitment = "confirmed",
239
+ rateLimit
240
+ } = config;
241
+ const paymentTimestamps = [];
242
+ const rateLimitMax = rateLimit?.maxPayments ?? DEFAULT_RATE_LIMIT_MAX_PAYMENTS;
243
+ const rateLimitWindow = rateLimit?.windowMs ?? DEFAULT_RATE_LIMIT_WINDOW_MS;
244
+ function checkRateLimit() {
245
+ const now = Date.now();
246
+ while (paymentTimestamps.length > 0 && paymentTimestamps[0] < now - rateLimitWindow) {
247
+ paymentTimestamps.shift();
248
+ }
249
+ if (paymentTimestamps.length >= rateLimitMax) {
250
+ throw rateLimitExceededError(rateLimitMax, rateLimitWindow);
251
+ }
252
+ }
253
+ function recordPayment() {
254
+ paymentTimestamps.push(Date.now());
255
+ }
256
+ function validateSecurityRequirements(requirements) {
257
+ const amountLamports = BigInt(requirements.amount);
258
+ if (maxPaymentPerRequest !== void 0 && amountLamports > maxPaymentPerRequest) {
259
+ throw amountExceedsLimitError(requirements, maxPaymentPerRequest);
260
+ }
261
+ if (allowedRecipients !== void 0 && allowedRecipients.length > 0) {
262
+ if (!allowedRecipients.includes(requirements.payTo)) {
263
+ throw recipientNotAllowedError(requirements, requirements.payTo);
264
+ }
265
+ }
266
+ }
267
+ const connection = providedConnection ?? new Connection(RPC_ENDPOINTS[network], {
268
+ commitment
269
+ });
270
+ async function executePayment(requirements) {
271
+ const payer = getPublicKey(wallet);
272
+ const recipient = new PublicKey(requirements.payTo);
273
+ const amountLamports = BigInt(requirements.amount);
274
+ const balance = await connection.getBalance(payer);
275
+ if (BigInt(balance) < amountLamports) {
276
+ throw insufficientBalanceError(requirements, BigInt(balance));
277
+ }
278
+ const instructions = [];
279
+ if (priorityFee?.enabled) {
280
+ instructions.push(
281
+ ComputeBudgetProgram.setComputeUnitPrice({
282
+ microLamports: priorityFee.microLamports ?? 5e3
283
+ })
284
+ );
285
+ }
286
+ instructions.push(
287
+ SystemProgram.transfer({
288
+ fromPubkey: payer,
289
+ toPubkey: recipient,
290
+ lamports: amountLamports
291
+ })
292
+ );
293
+ const { blockhash, lastValidBlockHeight } = await connection.getLatestBlockhash();
294
+ const messageV0 = new TransactionMessage({
295
+ payerKey: payer,
296
+ recentBlockhash: blockhash,
297
+ instructions
298
+ }).compileToV0Message();
299
+ const tx = new VersionedTransaction(messageV0);
300
+ if (isKeypair(wallet)) {
301
+ tx.sign([wallet]);
302
+ } else {
303
+ const signerWallet = wallet;
304
+ if (!signerWallet.signTransaction) {
305
+ throw new X402PaymentError(
306
+ "Wallet does not support transaction signing. Use a SignerWalletAdapter.",
307
+ "WALLET_NOT_CONNECTED"
308
+ );
309
+ }
310
+ const signedTx = await signerWallet.signTransaction(tx);
311
+ if (signedTx.signatures[0]) {
312
+ tx.signatures[0] = signedTx.signatures[0];
313
+ }
314
+ }
315
+ const signature = await connection.sendTransaction(tx, {
316
+ maxRetries
317
+ });
318
+ await connection.confirmTransaction({
319
+ signature,
320
+ blockhash,
321
+ lastValidBlockHeight
322
+ }, commitment);
323
+ return signature;
324
+ }
325
+ async function x402Fetch(input, init) {
326
+ const { skipPayment, paymentOverride, ...fetchInit } = init ?? {};
327
+ let response;
328
+ try {
329
+ response = await fetch(input, fetchInit);
330
+ } catch (error) {
331
+ throw networkError(error instanceof Error ? error : void 0);
332
+ }
333
+ if (response.status !== 402) {
334
+ return response;
335
+ }
336
+ if (skipPayment) {
337
+ return response;
338
+ }
339
+ if (!isWalletConnected(wallet)) {
340
+ throw walletNotConnectedError();
341
+ }
342
+ let requirements;
343
+ try {
344
+ requirements = parse402Response(response);
345
+ if (paymentOverride) {
346
+ requirements = { ...requirements, ...paymentOverride };
347
+ }
348
+ } catch (error) {
349
+ if (error instanceof X402PaymentError) throw error;
350
+ throw invalid402ResponseError(error instanceof Error ? error.message : void 0);
351
+ }
352
+ validateSecurityRequirements(requirements);
353
+ checkRateLimit();
354
+ if (onPaymentRequired) {
355
+ const url = typeof input === "string" ? input : input instanceof URL ? input.href : input.url;
356
+ const shouldProceed = await onPaymentRequired(requirements, url);
357
+ if (!shouldProceed) {
358
+ throw userRejectedError(requirements);
359
+ }
360
+ }
361
+ let signature;
362
+ try {
363
+ const paymentPromise = executePayment(requirements);
364
+ const timeoutPromise = new Promise((_, reject) => {
365
+ setTimeout(() => reject(timeoutError(requirements)), timeout);
366
+ });
367
+ signature = await Promise.race([paymentPromise, timeoutPromise]);
368
+ recordPayment();
369
+ if (onPaymentSuccess) {
370
+ await onPaymentSuccess(signature, requirements);
371
+ }
372
+ } catch (error) {
373
+ if (error instanceof X402PaymentError) {
374
+ if (onPaymentError) {
375
+ await onPaymentError(error, requirements);
376
+ }
377
+ throw error;
378
+ }
379
+ const wrappedError = transactionFailedError(
380
+ requirements,
381
+ error instanceof Error ? error : void 0
382
+ );
383
+ if (onPaymentError) {
384
+ await onPaymentError(wrappedError, requirements);
385
+ }
386
+ throw wrappedError;
387
+ }
388
+ const retryHeaders = new Headers(fetchInit?.headers);
389
+ retryHeaders.set("Authorization", buildPaymentHeader(signature));
390
+ try {
391
+ return await fetch(input, {
392
+ ...fetchInit,
393
+ headers: retryHeaders
394
+ });
395
+ } catch (error) {
396
+ throw networkError(error instanceof Error ? error : void 0);
397
+ }
398
+ }
399
+ return x402Fetch;
400
+ }
401
+
402
+ export { X402ErrorCode, X402PaymentError, amountExceedsLimitError, buildPaymentHeader, createX402Fetch, insufficientBalanceError, invalid402ResponseError, isUserRejection, isX402PaymentError, networkError, parse402Response as parsePaymentRequirements, rateLimitExceededError, recipientNotAllowedError, timeoutError, transactionFailedError, userRejectedError, verificationFailedError, walletNotConnectedError };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@alleyboss/micropay-solana-x402-paywall",
3
- "version": "3.3.14",
3
+ "version": "3.5.0",
4
4
  "description": "Production-ready Solana micropayments library wrapper for official x402 SDK",
5
5
  "author": "AlleyBoss",
6
6
  "license": "MIT",
@@ -8,6 +8,7 @@
8
8
  "type": "git",
9
9
  "url": "git@github.com:AlleyBo55/micropay-solana-x402-paywall.git"
10
10
  },
11
+ "homepage": "https://solana-x402-paywall.vercel.app/",
11
12
  "keywords": [
12
13
  "solana",
13
14
  "x402",
@@ -15,7 +16,8 @@
15
16
  "micropayments",
16
17
  "web3",
17
18
  "coinbase",
18
- "agent-payments"
19
+ "agent-payments",
20
+ "fetch"
19
21
  ],
20
22
  "type": "module",
21
23
  "main": "./dist/index.cjs",
@@ -91,6 +93,16 @@
91
93
  "types": "./dist/session/index.d.cts",
92
94
  "default": "./dist/session/index.cjs"
93
95
  }
96
+ },
97
+ "./fetch": {
98
+ "import": {
99
+ "types": "./dist/fetch/index.d.ts",
100
+ "default": "./dist/fetch/index.js"
101
+ },
102
+ "require": {
103
+ "types": "./dist/fetch/index.d.cts",
104
+ "default": "./dist/fetch/index.cjs"
105
+ }
94
106
  }
95
107
  },
96
108
  "files": [
@@ -117,10 +129,23 @@
117
129
  },
118
130
  "peerDependencies": {
119
131
  "@solana/web3.js": "^1.90.0",
132
+ "@solana/wallet-adapter-base": "^0.9.0",
120
133
  "react": ">=16.8.0",
121
134
  "react-dom": ">=16.8.0"
122
135
  },
136
+ "peerDependenciesMeta": {
137
+ "@solana/wallet-adapter-base": {
138
+ "optional": true
139
+ },
140
+ "react": {
141
+ "optional": true
142
+ },
143
+ "react-dom": {
144
+ "optional": true
145
+ }
146
+ },
123
147
  "devDependencies": {
148
+ "@solana/wallet-adapter-base": "^0.9.27",
124
149
  "@solana/web3.js": "^1.98.4",
125
150
  "@types/express": "^5.0.6",
126
151
  "@types/node": "^20",