@alleyboss/micropay-solana-x402-paywall 3.5.0 → 3.5.2

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.
@@ -1,4 +1,4 @@
1
- import { PublicKey, SystemProgram, LAMPORTS_PER_SOL, Keypair, TransactionMessage, VersionedTransaction, ComputeBudgetProgram } from '@solana/web3.js';
1
+ import { PublicKey, SystemProgram, LAMPORTS_PER_SOL, Keypair, Connection, TransactionMessage, VersionedTransaction, ComputeBudgetProgram } from '@solana/web3.js';
2
2
  import bs58 from 'bs58';
3
3
  import { SignJWT, jwtVerify } from 'jose';
4
4
 
@@ -345,4 +345,454 @@ async function getRemainingCredits(token, secret) {
345
345
  };
346
346
  }
347
347
 
348
- export { addCredits, createCreditSession, executeAgentPayment, generateAgentKeypair, getAgentBalance, getRemainingCredits, hasAgentSufficientBalance, keypairFromBase58, useCredit, validateCreditSession };
348
+ // src/fetch/types.ts
349
+ var X402ErrorCode = {
350
+ /** User rejected the payment */
351
+ USER_REJECTED: "USER_REJECTED",
352
+ /** Insufficient wallet balance */
353
+ INSUFFICIENT_BALANCE: "INSUFFICIENT_BALANCE",
354
+ /** Transaction failed on-chain */
355
+ TRANSACTION_FAILED: "TRANSACTION_FAILED",
356
+ /** Network/RPC error */
357
+ NETWORK_ERROR: "NETWORK_ERROR",
358
+ /** Invalid 402 response format */
359
+ INVALID_402_RESPONSE: "INVALID_402_RESPONSE",
360
+ /** Payment timeout */
361
+ TIMEOUT: "TIMEOUT",
362
+ /** Wallet not connected */
363
+ WALLET_NOT_CONNECTED: "WALLET_NOT_CONNECTED",
364
+ /** Payment amount exceeds maxPaymentPerRequest */
365
+ AMOUNT_EXCEEDS_LIMIT: "AMOUNT_EXCEEDS_LIMIT",
366
+ /** Recipient address not in allowedRecipients whitelist */
367
+ RECIPIENT_NOT_ALLOWED: "RECIPIENT_NOT_ALLOWED",
368
+ /** Rate limit exceeded */
369
+ RATE_LIMIT_EXCEEDED: "RATE_LIMIT_EXCEEDED"
370
+ };
371
+
372
+ // src/fetch/errors.ts
373
+ var X402PaymentError = class _X402PaymentError extends Error {
374
+ constructor(message, code, requirements, cause) {
375
+ super(message);
376
+ this.code = code;
377
+ this.requirements = requirements;
378
+ this.cause = cause;
379
+ if (Error.captureStackTrace) {
380
+ Error.captureStackTrace(this, _X402PaymentError);
381
+ }
382
+ }
383
+ name = "X402PaymentError";
384
+ /**
385
+ * Check if error is retryable
386
+ */
387
+ get isRetryable() {
388
+ const retryableCodes = [
389
+ X402ErrorCode.NETWORK_ERROR,
390
+ X402ErrorCode.TIMEOUT,
391
+ X402ErrorCode.TRANSACTION_FAILED
392
+ ];
393
+ return retryableCodes.includes(this.code);
394
+ }
395
+ /**
396
+ * Convert to JSON-serializable object
397
+ */
398
+ toJSON() {
399
+ return {
400
+ name: this.name,
401
+ message: this.message,
402
+ code: this.code,
403
+ requirements: this.requirements,
404
+ isRetryable: this.isRetryable
405
+ };
406
+ }
407
+ };
408
+ function userRejectedError(requirements) {
409
+ return new X402PaymentError(
410
+ "User rejected the payment request",
411
+ X402ErrorCode.USER_REJECTED,
412
+ requirements
413
+ );
414
+ }
415
+ function insufficientBalanceError(requirements, balance) {
416
+ return new X402PaymentError(
417
+ `Insufficient balance: have ${balance} lamports, need ${requirements.amount}`,
418
+ X402ErrorCode.INSUFFICIENT_BALANCE,
419
+ requirements
420
+ );
421
+ }
422
+ function transactionFailedError(requirements, cause) {
423
+ return new X402PaymentError(
424
+ `Transaction failed: ${cause?.message ?? "Unknown error"}`,
425
+ X402ErrorCode.TRANSACTION_FAILED,
426
+ requirements,
427
+ cause
428
+ );
429
+ }
430
+ function networkError(cause) {
431
+ return new X402PaymentError(
432
+ `Network error: ${cause?.message ?? "Connection failed"}`,
433
+ X402ErrorCode.NETWORK_ERROR,
434
+ void 0,
435
+ cause
436
+ );
437
+ }
438
+ function invalid402ResponseError(details) {
439
+ return new X402PaymentError(
440
+ `Invalid 402 response: ${details ?? "Missing or malformed payment requirements"}`,
441
+ X402ErrorCode.INVALID_402_RESPONSE
442
+ );
443
+ }
444
+ function timeoutError(requirements) {
445
+ return new X402PaymentError(
446
+ "Payment flow timed out",
447
+ X402ErrorCode.TIMEOUT,
448
+ requirements
449
+ );
450
+ }
451
+ function walletNotConnectedError() {
452
+ return new X402PaymentError(
453
+ "Wallet is not connected",
454
+ X402ErrorCode.WALLET_NOT_CONNECTED
455
+ );
456
+ }
457
+ function amountExceedsLimitError(requirements, limit) {
458
+ return new X402PaymentError(
459
+ `Payment amount ${requirements.amount} exceeds limit of ${limit} lamports`,
460
+ X402ErrorCode.AMOUNT_EXCEEDS_LIMIT,
461
+ requirements
462
+ );
463
+ }
464
+ function recipientNotAllowedError(requirements, recipient) {
465
+ return new X402PaymentError(
466
+ `Recipient ${recipient} is not in the allowed recipients list`,
467
+ X402ErrorCode.RECIPIENT_NOT_ALLOWED,
468
+ requirements
469
+ );
470
+ }
471
+ function rateLimitExceededError(limit, windowMs) {
472
+ return new X402PaymentError(
473
+ `Rate limit exceeded: max ${limit} payments per ${windowMs / 1e3}s`,
474
+ X402ErrorCode.RATE_LIMIT_EXCEEDED
475
+ );
476
+ }
477
+
478
+ // src/shared/constants.ts
479
+ var RPC_ENDPOINTS = {
480
+ "mainnet-beta": "https://api.mainnet-beta.solana.com",
481
+ "devnet": "https://api.devnet.solana.com",
482
+ "testnet": "https://api.testnet.solana.com"
483
+ };
484
+ var DEFAULT_CONFIRMATION_TIMEOUT = 3e4;
485
+ var DEFAULT_MAX_RETRIES = 3;
486
+ var DEFAULT_RATE_LIMIT_WINDOW_MS = 6e4;
487
+ var DEFAULT_RATE_LIMIT_MAX_PAYMENTS = 10;
488
+
489
+ // src/fetch/x402Fetch.ts
490
+ function isKeypair(wallet) {
491
+ return wallet instanceof Keypair;
492
+ }
493
+ function isWalletConnected(wallet) {
494
+ if (isKeypair(wallet)) return true;
495
+ return wallet.connected && wallet.publicKey != null;
496
+ }
497
+ function getPublicKey(wallet) {
498
+ if (isKeypair(wallet)) return wallet.publicKey;
499
+ if (!wallet.publicKey) throw walletNotConnectedError();
500
+ return wallet.publicKey;
501
+ }
502
+ function parse402Response(response) {
503
+ const x402Header = response.headers.get("X-Payment-Requirements");
504
+ if (x402Header) {
505
+ try {
506
+ const parsed = JSON.parse(x402Header);
507
+ return {
508
+ payTo: parsed.payTo ?? parsed.recipient,
509
+ amount: String(parsed.amount),
510
+ asset: parsed.asset ?? "SOL",
511
+ network: parsed.network ?? "solana-mainnet",
512
+ description: parsed.description,
513
+ resource: parsed.resource,
514
+ maxAge: parsed.maxAge
515
+ };
516
+ } catch {
517
+ throw invalid402ResponseError("Invalid X-Payment-Requirements header");
518
+ }
519
+ }
520
+ const wwwAuth = response.headers.get("WWW-Authenticate");
521
+ if (wwwAuth?.startsWith("X402")) {
522
+ try {
523
+ const base64Part = wwwAuth.slice(5).trim();
524
+ const jsonStr = atob(base64Part);
525
+ const parsed = JSON.parse(jsonStr);
526
+ return {
527
+ payTo: parsed.payTo ?? parsed.recipient,
528
+ amount: String(parsed.amount),
529
+ asset: parsed.asset ?? "SOL",
530
+ network: parsed.network ?? "solana-mainnet",
531
+ description: parsed.description,
532
+ resource: parsed.resource,
533
+ maxAge: parsed.maxAge
534
+ };
535
+ } catch {
536
+ throw invalid402ResponseError("Invalid WWW-Authenticate header");
537
+ }
538
+ }
539
+ const paymentRequired = response.headers.get("payment-required");
540
+ if (paymentRequired) {
541
+ try {
542
+ const jsonStr = atob(paymentRequired.trim());
543
+ const parsed = JSON.parse(jsonStr);
544
+ const option = Array.isArray(parsed.accepts) && parsed.accepts.length > 0 ? parsed.accepts[0] : parsed;
545
+ return {
546
+ payTo: option.payTo ?? option.recipient,
547
+ amount: String(option.amount),
548
+ asset: option.asset ?? "SOL",
549
+ network: option.network ?? "solana-mainnet",
550
+ description: parsed.description ?? option.description,
551
+ resource: parsed.resource ?? option.resource,
552
+ maxAge: parsed.maxAge ?? option.maxAge
553
+ };
554
+ } catch {
555
+ throw invalid402ResponseError("Invalid payment-required header");
556
+ }
557
+ }
558
+ throw invalid402ResponseError("No payment requirements found in 402 response");
559
+ }
560
+ function buildPaymentHeader(signature) {
561
+ const payload = {
562
+ x402Version: 2,
563
+ scheme: "exact",
564
+ payload: { signature }
565
+ };
566
+ return `X402 ${btoa(JSON.stringify(payload))}`;
567
+ }
568
+ function createX402Fetch(config) {
569
+ const {
570
+ wallet,
571
+ network = "mainnet-beta",
572
+ connection: providedConnection,
573
+ // Reserved for future facilitator integration
574
+ onPaymentRequired,
575
+ onPaymentSuccess,
576
+ onPaymentError,
577
+ priorityFee,
578
+ maxRetries = DEFAULT_MAX_RETRIES,
579
+ timeout = DEFAULT_CONFIRMATION_TIMEOUT,
580
+ // Security options
581
+ maxPaymentPerRequest,
582
+ allowedRecipients,
583
+ // UX options
584
+ commitment = "confirmed",
585
+ rateLimit
586
+ } = config;
587
+ const paymentTimestamps = [];
588
+ const rateLimitMax = rateLimit?.maxPayments ?? DEFAULT_RATE_LIMIT_MAX_PAYMENTS;
589
+ const rateLimitWindow = rateLimit?.windowMs ?? DEFAULT_RATE_LIMIT_WINDOW_MS;
590
+ function checkRateLimit() {
591
+ const now = Date.now();
592
+ while (paymentTimestamps.length > 0 && paymentTimestamps[0] < now - rateLimitWindow) {
593
+ paymentTimestamps.shift();
594
+ }
595
+ if (paymentTimestamps.length >= rateLimitMax) {
596
+ throw rateLimitExceededError(rateLimitMax, rateLimitWindow);
597
+ }
598
+ }
599
+ function recordPayment() {
600
+ paymentTimestamps.push(Date.now());
601
+ }
602
+ function validateSecurityRequirements(requirements) {
603
+ const amountLamports = BigInt(requirements.amount);
604
+ if (maxPaymentPerRequest !== void 0 && amountLamports > maxPaymentPerRequest) {
605
+ throw amountExceedsLimitError(requirements, maxPaymentPerRequest);
606
+ }
607
+ if (allowedRecipients !== void 0 && allowedRecipients.length > 0) {
608
+ if (!allowedRecipients.includes(requirements.payTo)) {
609
+ throw recipientNotAllowedError(requirements, requirements.payTo);
610
+ }
611
+ }
612
+ }
613
+ const connection = providedConnection ?? new Connection(RPC_ENDPOINTS[network], {
614
+ commitment
615
+ });
616
+ async function executePayment(requirements) {
617
+ const payer = getPublicKey(wallet);
618
+ const recipient = new PublicKey(requirements.payTo);
619
+ const amountLamports = BigInt(requirements.amount);
620
+ const balance = await connection.getBalance(payer);
621
+ if (BigInt(balance) < amountLamports) {
622
+ throw insufficientBalanceError(requirements, BigInt(balance));
623
+ }
624
+ const instructions = [];
625
+ if (priorityFee?.enabled) {
626
+ instructions.push(
627
+ ComputeBudgetProgram.setComputeUnitPrice({
628
+ microLamports: priorityFee.microLamports ?? 5e3
629
+ })
630
+ );
631
+ }
632
+ instructions.push(
633
+ SystemProgram.transfer({
634
+ fromPubkey: payer,
635
+ toPubkey: recipient,
636
+ lamports: amountLamports
637
+ })
638
+ );
639
+ const { blockhash, lastValidBlockHeight } = await connection.getLatestBlockhash();
640
+ const messageV0 = new TransactionMessage({
641
+ payerKey: payer,
642
+ recentBlockhash: blockhash,
643
+ instructions
644
+ }).compileToV0Message();
645
+ const tx = new VersionedTransaction(messageV0);
646
+ if (isKeypair(wallet)) {
647
+ tx.sign([wallet]);
648
+ } else {
649
+ const signerWallet = wallet;
650
+ if (!signerWallet.signTransaction) {
651
+ throw new X402PaymentError(
652
+ "Wallet does not support transaction signing. Use a SignerWalletAdapter.",
653
+ "WALLET_NOT_CONNECTED"
654
+ );
655
+ }
656
+ const signedTx = await signerWallet.signTransaction(tx);
657
+ if (signedTx.signatures[0]) {
658
+ tx.signatures[0] = signedTx.signatures[0];
659
+ }
660
+ }
661
+ const signature = await connection.sendTransaction(tx, {
662
+ maxRetries
663
+ });
664
+ await connection.confirmTransaction({
665
+ signature,
666
+ blockhash,
667
+ lastValidBlockHeight
668
+ }, commitment);
669
+ return signature;
670
+ }
671
+ async function x402Fetch(input, init) {
672
+ const { skipPayment, paymentOverride, ...fetchInit } = init ?? {};
673
+ let response;
674
+ try {
675
+ response = await fetch(input, fetchInit);
676
+ } catch (error) {
677
+ throw networkError(error instanceof Error ? error : void 0);
678
+ }
679
+ if (response.status !== 402) {
680
+ return response;
681
+ }
682
+ if (skipPayment) {
683
+ return response;
684
+ }
685
+ if (!isWalletConnected(wallet)) {
686
+ throw walletNotConnectedError();
687
+ }
688
+ let requirements;
689
+ try {
690
+ requirements = parse402Response(response);
691
+ if (paymentOverride) {
692
+ requirements = { ...requirements, ...paymentOverride };
693
+ }
694
+ } catch (error) {
695
+ if (error instanceof X402PaymentError) throw error;
696
+ throw invalid402ResponseError(error instanceof Error ? error.message : void 0);
697
+ }
698
+ validateSecurityRequirements(requirements);
699
+ checkRateLimit();
700
+ if (onPaymentRequired) {
701
+ const url = typeof input === "string" ? input : input instanceof URL ? input.href : input.url;
702
+ const shouldProceed = await onPaymentRequired(requirements, url);
703
+ if (!shouldProceed) {
704
+ throw userRejectedError(requirements);
705
+ }
706
+ }
707
+ let signature;
708
+ try {
709
+ const paymentPromise = executePayment(requirements);
710
+ const timeoutPromise = new Promise((_, reject) => {
711
+ setTimeout(() => reject(timeoutError(requirements)), timeout);
712
+ });
713
+ signature = await Promise.race([paymentPromise, timeoutPromise]);
714
+ recordPayment();
715
+ if (onPaymentSuccess) {
716
+ await onPaymentSuccess(signature, requirements);
717
+ }
718
+ } catch (error) {
719
+ if (error instanceof X402PaymentError) {
720
+ if (onPaymentError) {
721
+ await onPaymentError(error, requirements);
722
+ }
723
+ throw error;
724
+ }
725
+ const wrappedError = transactionFailedError(
726
+ requirements,
727
+ error instanceof Error ? error : void 0
728
+ );
729
+ if (onPaymentError) {
730
+ await onPaymentError(wrappedError, requirements);
731
+ }
732
+ throw wrappedError;
733
+ }
734
+ const retryHeaders = new Headers(fetchInit?.headers);
735
+ retryHeaders.set("Authorization", buildPaymentHeader(signature));
736
+ try {
737
+ return await fetch(input, {
738
+ ...fetchInit,
739
+ headers: retryHeaders
740
+ });
741
+ } catch (error) {
742
+ throw networkError(error instanceof Error ? error : void 0);
743
+ }
744
+ }
745
+ return x402Fetch;
746
+ }
747
+
748
+ // src/agent/payingAgent.ts
749
+ function createPayingAgent(privateKey, config = {}) {
750
+ const {
751
+ network = "mainnet-beta",
752
+ rpcUrl,
753
+ maxPaymentPerRequest,
754
+ allowedRecipients,
755
+ priorityFee = true
756
+ } = config;
757
+ let keypair;
758
+ if (privateKey.includes(",")) {
759
+ const bytes = new Uint8Array(privateKey.split(",").map((n) => parseInt(n.trim(), 10)));
760
+ keypair = Keypair.fromSecretKey(bytes);
761
+ } else {
762
+ keypair = Keypair.fromSecretKey(bs58.decode(privateKey));
763
+ }
764
+ const endpoint = rpcUrl ?? RPC_ENDPOINTS[network];
765
+ const connection = new Connection(endpoint, "confirmed");
766
+ const fetchConfig = {
767
+ wallet: keypair,
768
+ network,
769
+ connection,
770
+ maxPaymentPerRequest,
771
+ allowedRecipients,
772
+ priorityFee: priorityFee ? { enabled: true, microLamports: 5e3 } : void 0
773
+ };
774
+ const x402Fetch = createX402Fetch(fetchConfig);
775
+ return {
776
+ get: (url, init) => x402Fetch(url, { ...init, method: "GET" }),
777
+ post: (url, body, init) => x402Fetch(url, {
778
+ ...init,
779
+ method: "POST",
780
+ body: JSON.stringify(body),
781
+ headers: {
782
+ "Content-Type": "application/json",
783
+ ...init?.headers
784
+ }
785
+ }),
786
+ fetch: (url, init) => x402Fetch(url, init),
787
+ publicKey: keypair.publicKey.toBase58(),
788
+ getBalance: async () => {
789
+ const lamports = await connection.getBalance(keypair.publicKey);
790
+ return {
791
+ lamports: BigInt(lamports),
792
+ sol: lamports / 1e9
793
+ };
794
+ }
795
+ };
796
+ }
797
+
798
+ export { addCredits, createCreditSession, createPayingAgent, executeAgentPayment, generateAgentKeypair, getAgentBalance, getRemainingCredits, hasAgentSufficientBalance, keypairFromBase58, useCredit, validateCreditSession };
@@ -210,6 +210,25 @@ function parse402Response(response) {
210
210
  throw invalid402ResponseError("Invalid WWW-Authenticate header");
211
211
  }
212
212
  }
213
+ const paymentRequired = response.headers.get("payment-required");
214
+ if (paymentRequired) {
215
+ try {
216
+ const jsonStr = atob(paymentRequired.trim());
217
+ const parsed = JSON.parse(jsonStr);
218
+ const option = Array.isArray(parsed.accepts) && parsed.accepts.length > 0 ? parsed.accepts[0] : parsed;
219
+ return {
220
+ payTo: option.payTo ?? option.recipient,
221
+ amount: String(option.amount),
222
+ asset: option.asset ?? "SOL",
223
+ network: option.network ?? "solana-mainnet",
224
+ description: parsed.description ?? option.description,
225
+ resource: parsed.resource ?? option.resource,
226
+ maxAge: parsed.maxAge ?? option.maxAge
227
+ };
228
+ } catch {
229
+ throw invalid402ResponseError("Invalid payment-required header");
230
+ }
231
+ }
213
232
  throw invalid402ResponseError("No payment requirements found in 402 response");
214
233
  }
215
234
  function buildPaymentHeader(signature) {
@@ -208,6 +208,25 @@ function parse402Response(response) {
208
208
  throw invalid402ResponseError("Invalid WWW-Authenticate header");
209
209
  }
210
210
  }
211
+ const paymentRequired = response.headers.get("payment-required");
212
+ if (paymentRequired) {
213
+ try {
214
+ const jsonStr = atob(paymentRequired.trim());
215
+ const parsed = JSON.parse(jsonStr);
216
+ const option = Array.isArray(parsed.accepts) && parsed.accepts.length > 0 ? parsed.accepts[0] : parsed;
217
+ return {
218
+ payTo: option.payTo ?? option.recipient,
219
+ amount: String(option.amount),
220
+ asset: option.asset ?? "SOL",
221
+ network: option.network ?? "solana-mainnet",
222
+ description: parsed.description ?? option.description,
223
+ resource: parsed.resource ?? option.resource,
224
+ maxAge: parsed.maxAge ?? option.maxAge
225
+ };
226
+ } catch {
227
+ throw invalid402ResponseError("Invalid payment-required header");
228
+ }
229
+ }
211
230
  throw invalid402ResponseError("No payment requirements found in 402 response");
212
231
  }
213
232
  function buildPaymentHeader(signature) {