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

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.
package/dist/index.cjs CHANGED
@@ -631,6 +631,437 @@ async function getRemainingCredits(token, secret) {
631
631
  };
632
632
  }
633
633
 
634
+ // src/fetch/types.ts
635
+ var X402ErrorCode = {
636
+ /** User rejected the payment */
637
+ USER_REJECTED: "USER_REJECTED",
638
+ /** Insufficient wallet balance */
639
+ INSUFFICIENT_BALANCE: "INSUFFICIENT_BALANCE",
640
+ /** Transaction failed on-chain */
641
+ TRANSACTION_FAILED: "TRANSACTION_FAILED",
642
+ /** Network/RPC error */
643
+ NETWORK_ERROR: "NETWORK_ERROR",
644
+ /** Invalid 402 response format */
645
+ INVALID_402_RESPONSE: "INVALID_402_RESPONSE",
646
+ /** Payment timeout */
647
+ TIMEOUT: "TIMEOUT",
648
+ /** Wallet not connected */
649
+ WALLET_NOT_CONNECTED: "WALLET_NOT_CONNECTED",
650
+ /** Payment amount exceeds maxPaymentPerRequest */
651
+ AMOUNT_EXCEEDS_LIMIT: "AMOUNT_EXCEEDS_LIMIT",
652
+ /** Recipient address not in allowedRecipients whitelist */
653
+ RECIPIENT_NOT_ALLOWED: "RECIPIENT_NOT_ALLOWED",
654
+ /** Rate limit exceeded */
655
+ RATE_LIMIT_EXCEEDED: "RATE_LIMIT_EXCEEDED"
656
+ };
657
+
658
+ // src/fetch/errors.ts
659
+ var X402PaymentError = class _X402PaymentError extends Error {
660
+ constructor(message, code, requirements, cause) {
661
+ super(message);
662
+ this.code = code;
663
+ this.requirements = requirements;
664
+ this.cause = cause;
665
+ if (Error.captureStackTrace) {
666
+ Error.captureStackTrace(this, _X402PaymentError);
667
+ }
668
+ }
669
+ name = "X402PaymentError";
670
+ /**
671
+ * Check if error is retryable
672
+ */
673
+ get isRetryable() {
674
+ const retryableCodes = [
675
+ X402ErrorCode.NETWORK_ERROR,
676
+ X402ErrorCode.TIMEOUT,
677
+ X402ErrorCode.TRANSACTION_FAILED
678
+ ];
679
+ return retryableCodes.includes(this.code);
680
+ }
681
+ /**
682
+ * Convert to JSON-serializable object
683
+ */
684
+ toJSON() {
685
+ return {
686
+ name: this.name,
687
+ message: this.message,
688
+ code: this.code,
689
+ requirements: this.requirements,
690
+ isRetryable: this.isRetryable
691
+ };
692
+ }
693
+ };
694
+ function userRejectedError(requirements) {
695
+ return new X402PaymentError(
696
+ "User rejected the payment request",
697
+ X402ErrorCode.USER_REJECTED,
698
+ requirements
699
+ );
700
+ }
701
+ function insufficientBalanceError(requirements, balance) {
702
+ return new X402PaymentError(
703
+ `Insufficient balance: have ${balance} lamports, need ${requirements.amount}`,
704
+ X402ErrorCode.INSUFFICIENT_BALANCE,
705
+ requirements
706
+ );
707
+ }
708
+ function transactionFailedError(requirements, cause) {
709
+ return new X402PaymentError(
710
+ `Transaction failed: ${cause?.message ?? "Unknown error"}`,
711
+ X402ErrorCode.TRANSACTION_FAILED,
712
+ requirements,
713
+ cause
714
+ );
715
+ }
716
+ function networkError(cause) {
717
+ return new X402PaymentError(
718
+ `Network error: ${cause?.message ?? "Connection failed"}`,
719
+ X402ErrorCode.NETWORK_ERROR,
720
+ void 0,
721
+ cause
722
+ );
723
+ }
724
+ function invalid402ResponseError(details) {
725
+ return new X402PaymentError(
726
+ `Invalid 402 response: ${details ?? "Missing or malformed payment requirements"}`,
727
+ X402ErrorCode.INVALID_402_RESPONSE
728
+ );
729
+ }
730
+ function timeoutError(requirements) {
731
+ return new X402PaymentError(
732
+ "Payment flow timed out",
733
+ X402ErrorCode.TIMEOUT,
734
+ requirements
735
+ );
736
+ }
737
+ function walletNotConnectedError() {
738
+ return new X402PaymentError(
739
+ "Wallet is not connected",
740
+ X402ErrorCode.WALLET_NOT_CONNECTED
741
+ );
742
+ }
743
+ function amountExceedsLimitError(requirements, limit) {
744
+ return new X402PaymentError(
745
+ `Payment amount ${requirements.amount} exceeds limit of ${limit} lamports`,
746
+ X402ErrorCode.AMOUNT_EXCEEDS_LIMIT,
747
+ requirements
748
+ );
749
+ }
750
+ function recipientNotAllowedError(requirements, recipient) {
751
+ return new X402PaymentError(
752
+ `Recipient ${recipient} is not in the allowed recipients list`,
753
+ X402ErrorCode.RECIPIENT_NOT_ALLOWED,
754
+ requirements
755
+ );
756
+ }
757
+ function rateLimitExceededError(limit, windowMs) {
758
+ return new X402PaymentError(
759
+ `Rate limit exceeded: max ${limit} payments per ${windowMs / 1e3}s`,
760
+ X402ErrorCode.RATE_LIMIT_EXCEEDED
761
+ );
762
+ }
763
+
764
+ // src/shared/constants.ts
765
+ var RPC_ENDPOINTS = {
766
+ "mainnet-beta": "https://api.mainnet-beta.solana.com",
767
+ "devnet": "https://api.devnet.solana.com",
768
+ "testnet": "https://api.testnet.solana.com"
769
+ };
770
+ var DEFAULT_CONFIRMATION_TIMEOUT = 3e4;
771
+ var DEFAULT_MAX_RETRIES = 3;
772
+ var DEFAULT_RATE_LIMIT_WINDOW_MS = 6e4;
773
+ var DEFAULT_RATE_LIMIT_MAX_PAYMENTS = 10;
774
+
775
+ // src/fetch/x402Fetch.ts
776
+ function isKeypair(wallet) {
777
+ return wallet instanceof web3_js.Keypair;
778
+ }
779
+ function isWalletConnected(wallet) {
780
+ if (isKeypair(wallet)) return true;
781
+ return wallet.connected && wallet.publicKey != null;
782
+ }
783
+ function getPublicKey(wallet) {
784
+ if (isKeypair(wallet)) return wallet.publicKey;
785
+ if (!wallet.publicKey) throw walletNotConnectedError();
786
+ return wallet.publicKey;
787
+ }
788
+ function parse402Response(response) {
789
+ const x402Header = response.headers.get("X-Payment-Requirements");
790
+ if (x402Header) {
791
+ try {
792
+ const parsed = JSON.parse(x402Header);
793
+ return {
794
+ payTo: parsed.payTo ?? parsed.recipient,
795
+ amount: String(parsed.amount),
796
+ asset: parsed.asset ?? "SOL",
797
+ network: parsed.network ?? "solana-mainnet",
798
+ description: parsed.description,
799
+ resource: parsed.resource,
800
+ maxAge: parsed.maxAge
801
+ };
802
+ } catch {
803
+ throw invalid402ResponseError("Invalid X-Payment-Requirements header");
804
+ }
805
+ }
806
+ const wwwAuth = response.headers.get("WWW-Authenticate");
807
+ if (wwwAuth?.startsWith("X402")) {
808
+ try {
809
+ const base64Part = wwwAuth.slice(5).trim();
810
+ const jsonStr = atob(base64Part);
811
+ const parsed = JSON.parse(jsonStr);
812
+ return {
813
+ payTo: parsed.payTo ?? parsed.recipient,
814
+ amount: String(parsed.amount),
815
+ asset: parsed.asset ?? "SOL",
816
+ network: parsed.network ?? "solana-mainnet",
817
+ description: parsed.description,
818
+ resource: parsed.resource,
819
+ maxAge: parsed.maxAge
820
+ };
821
+ } catch {
822
+ throw invalid402ResponseError("Invalid WWW-Authenticate header");
823
+ }
824
+ }
825
+ throw invalid402ResponseError("No payment requirements found in 402 response");
826
+ }
827
+ function buildPaymentHeader(signature) {
828
+ const payload = {
829
+ x402Version: 2,
830
+ scheme: "exact",
831
+ payload: { signature }
832
+ };
833
+ return `X402 ${btoa(JSON.stringify(payload))}`;
834
+ }
835
+ function createX402Fetch(config) {
836
+ const {
837
+ wallet,
838
+ network = "mainnet-beta",
839
+ connection: providedConnection,
840
+ // Reserved for future facilitator integration
841
+ onPaymentRequired,
842
+ onPaymentSuccess,
843
+ onPaymentError,
844
+ priorityFee,
845
+ maxRetries = DEFAULT_MAX_RETRIES,
846
+ timeout = DEFAULT_CONFIRMATION_TIMEOUT,
847
+ // Security options
848
+ maxPaymentPerRequest,
849
+ allowedRecipients,
850
+ // UX options
851
+ commitment = "confirmed",
852
+ rateLimit
853
+ } = config;
854
+ const paymentTimestamps = [];
855
+ const rateLimitMax = rateLimit?.maxPayments ?? DEFAULT_RATE_LIMIT_MAX_PAYMENTS;
856
+ const rateLimitWindow = rateLimit?.windowMs ?? DEFAULT_RATE_LIMIT_WINDOW_MS;
857
+ function checkRateLimit() {
858
+ const now = Date.now();
859
+ while (paymentTimestamps.length > 0 && paymentTimestamps[0] < now - rateLimitWindow) {
860
+ paymentTimestamps.shift();
861
+ }
862
+ if (paymentTimestamps.length >= rateLimitMax) {
863
+ throw rateLimitExceededError(rateLimitMax, rateLimitWindow);
864
+ }
865
+ }
866
+ function recordPayment() {
867
+ paymentTimestamps.push(Date.now());
868
+ }
869
+ function validateSecurityRequirements(requirements) {
870
+ const amountLamports = BigInt(requirements.amount);
871
+ if (maxPaymentPerRequest !== void 0 && amountLamports > maxPaymentPerRequest) {
872
+ throw amountExceedsLimitError(requirements, maxPaymentPerRequest);
873
+ }
874
+ if (allowedRecipients !== void 0 && allowedRecipients.length > 0) {
875
+ if (!allowedRecipients.includes(requirements.payTo)) {
876
+ throw recipientNotAllowedError(requirements, requirements.payTo);
877
+ }
878
+ }
879
+ }
880
+ const connection = providedConnection ?? new web3_js.Connection(RPC_ENDPOINTS[network], {
881
+ commitment
882
+ });
883
+ async function executePayment(requirements) {
884
+ const payer = getPublicKey(wallet);
885
+ const recipient = new web3_js.PublicKey(requirements.payTo);
886
+ const amountLamports = BigInt(requirements.amount);
887
+ const balance = await connection.getBalance(payer);
888
+ if (BigInt(balance) < amountLamports) {
889
+ throw insufficientBalanceError(requirements, BigInt(balance));
890
+ }
891
+ const instructions = [];
892
+ if (priorityFee?.enabled) {
893
+ instructions.push(
894
+ web3_js.ComputeBudgetProgram.setComputeUnitPrice({
895
+ microLamports: priorityFee.microLamports ?? 5e3
896
+ })
897
+ );
898
+ }
899
+ instructions.push(
900
+ web3_js.SystemProgram.transfer({
901
+ fromPubkey: payer,
902
+ toPubkey: recipient,
903
+ lamports: amountLamports
904
+ })
905
+ );
906
+ const { blockhash, lastValidBlockHeight } = await connection.getLatestBlockhash();
907
+ const messageV0 = new web3_js.TransactionMessage({
908
+ payerKey: payer,
909
+ recentBlockhash: blockhash,
910
+ instructions
911
+ }).compileToV0Message();
912
+ const tx = new web3_js.VersionedTransaction(messageV0);
913
+ if (isKeypair(wallet)) {
914
+ tx.sign([wallet]);
915
+ } else {
916
+ const signerWallet = wallet;
917
+ if (!signerWallet.signTransaction) {
918
+ throw new X402PaymentError(
919
+ "Wallet does not support transaction signing. Use a SignerWalletAdapter.",
920
+ "WALLET_NOT_CONNECTED"
921
+ );
922
+ }
923
+ const signedTx = await signerWallet.signTransaction(tx);
924
+ if (signedTx.signatures[0]) {
925
+ tx.signatures[0] = signedTx.signatures[0];
926
+ }
927
+ }
928
+ const signature = await connection.sendTransaction(tx, {
929
+ maxRetries
930
+ });
931
+ await connection.confirmTransaction({
932
+ signature,
933
+ blockhash,
934
+ lastValidBlockHeight
935
+ }, commitment);
936
+ return signature;
937
+ }
938
+ async function x402Fetch(input, init) {
939
+ const { skipPayment, paymentOverride, ...fetchInit } = init ?? {};
940
+ let response;
941
+ try {
942
+ response = await fetch(input, fetchInit);
943
+ } catch (error) {
944
+ throw networkError(error instanceof Error ? error : void 0);
945
+ }
946
+ if (response.status !== 402) {
947
+ return response;
948
+ }
949
+ if (skipPayment) {
950
+ return response;
951
+ }
952
+ if (!isWalletConnected(wallet)) {
953
+ throw walletNotConnectedError();
954
+ }
955
+ let requirements;
956
+ try {
957
+ requirements = parse402Response(response);
958
+ if (paymentOverride) {
959
+ requirements = { ...requirements, ...paymentOverride };
960
+ }
961
+ } catch (error) {
962
+ if (error instanceof X402PaymentError) throw error;
963
+ throw invalid402ResponseError(error instanceof Error ? error.message : void 0);
964
+ }
965
+ validateSecurityRequirements(requirements);
966
+ checkRateLimit();
967
+ if (onPaymentRequired) {
968
+ const url = typeof input === "string" ? input : input instanceof URL ? input.href : input.url;
969
+ const shouldProceed = await onPaymentRequired(requirements, url);
970
+ if (!shouldProceed) {
971
+ throw userRejectedError(requirements);
972
+ }
973
+ }
974
+ let signature;
975
+ try {
976
+ const paymentPromise = executePayment(requirements);
977
+ const timeoutPromise = new Promise((_, reject) => {
978
+ setTimeout(() => reject(timeoutError(requirements)), timeout);
979
+ });
980
+ signature = await Promise.race([paymentPromise, timeoutPromise]);
981
+ recordPayment();
982
+ if (onPaymentSuccess) {
983
+ await onPaymentSuccess(signature, requirements);
984
+ }
985
+ } catch (error) {
986
+ if (error instanceof X402PaymentError) {
987
+ if (onPaymentError) {
988
+ await onPaymentError(error, requirements);
989
+ }
990
+ throw error;
991
+ }
992
+ const wrappedError = transactionFailedError(
993
+ requirements,
994
+ error instanceof Error ? error : void 0
995
+ );
996
+ if (onPaymentError) {
997
+ await onPaymentError(wrappedError, requirements);
998
+ }
999
+ throw wrappedError;
1000
+ }
1001
+ const retryHeaders = new Headers(fetchInit?.headers);
1002
+ retryHeaders.set("Authorization", buildPaymentHeader(signature));
1003
+ try {
1004
+ return await fetch(input, {
1005
+ ...fetchInit,
1006
+ headers: retryHeaders
1007
+ });
1008
+ } catch (error) {
1009
+ throw networkError(error instanceof Error ? error : void 0);
1010
+ }
1011
+ }
1012
+ return x402Fetch;
1013
+ }
1014
+
1015
+ // src/agent/payingAgent.ts
1016
+ function createPayingAgent(privateKey, config = {}) {
1017
+ const {
1018
+ network = "mainnet-beta",
1019
+ rpcUrl,
1020
+ maxPaymentPerRequest,
1021
+ allowedRecipients,
1022
+ priorityFee = true
1023
+ } = config;
1024
+ let keypair;
1025
+ if (privateKey.includes(",")) {
1026
+ const bytes = new Uint8Array(privateKey.split(",").map((n) => parseInt(n.trim(), 10)));
1027
+ keypair = web3_js.Keypair.fromSecretKey(bytes);
1028
+ } else {
1029
+ keypair = web3_js.Keypair.fromSecretKey(bs58__default.default.decode(privateKey));
1030
+ }
1031
+ const endpoint = rpcUrl ?? RPC_ENDPOINTS[network];
1032
+ const connection = new web3_js.Connection(endpoint, "confirmed");
1033
+ const fetchConfig = {
1034
+ wallet: keypair,
1035
+ network,
1036
+ connection,
1037
+ maxPaymentPerRequest,
1038
+ allowedRecipients,
1039
+ priorityFee: priorityFee ? { enabled: true, microLamports: 5e3 } : void 0
1040
+ };
1041
+ const x402Fetch = createX402Fetch(fetchConfig);
1042
+ return {
1043
+ get: (url, init) => x402Fetch(url, { ...init, method: "GET" }),
1044
+ post: (url, body, init) => x402Fetch(url, {
1045
+ ...init,
1046
+ method: "POST",
1047
+ body: JSON.stringify(body),
1048
+ headers: {
1049
+ "Content-Type": "application/json",
1050
+ ...init?.headers
1051
+ }
1052
+ }),
1053
+ fetch: (url, init) => x402Fetch(url, init),
1054
+ publicKey: keypair.publicKey.toBase58(),
1055
+ getBalance: async () => {
1056
+ const lamports = await connection.getBalance(keypair.publicKey);
1057
+ return {
1058
+ lamports: BigInt(lamports),
1059
+ sol: lamports / 1e9
1060
+ };
1061
+ }
1062
+ };
1063
+ }
1064
+
634
1065
  // src/pricing/utils.ts
635
1066
  function lamportsToSol(lamports) {
636
1067
  return Number(lamports) / 1e9;
@@ -788,6 +1219,7 @@ exports.addCredits = addCredits;
788
1219
  exports.clearPriceCache = clearPriceCache;
789
1220
  exports.configurePricing = configurePricing;
790
1221
  exports.createCreditSession = createCreditSession;
1222
+ exports.createPayingAgent = createPayingAgent;
791
1223
  exports.executeAgentPayment = executeAgentPayment;
792
1224
  exports.formatPriceDisplay = formatPriceDisplay;
793
1225
  exports.formatPriceSync = formatPriceSync;
package/dist/index.d.cts CHANGED
@@ -3,7 +3,7 @@ import { PaymentPayload, PaymentRequirements, VerifyResponse, SettleResponse, Su
3
3
  export * from '@x402/core/types';
4
4
  export * from '@x402/core/client';
5
5
  export * from '@x402/svm';
6
- export { AgentPaymentResult, CreditSessionClaims, CreditSessionConfig, CreditSessionData, CreditValidation, ExecuteAgentPaymentParams, UseCreditResult, addCredits, createCreditSession, executeAgentPayment, generateAgentKeypair, getAgentBalance, getRemainingCredits, hasAgentSufficientBalance, keypairFromBase58, useCredit, validateCreditSession } from './agent/index.cjs';
6
+ export { AgentPaymentResult, CreditSessionClaims, CreditSessionConfig, CreditSessionData, CreditValidation, ExecuteAgentPaymentParams, PayingAgent, PayingAgentConfig, UseCreditResult, addCredits, createCreditSession, createPayingAgent, executeAgentPayment, generateAgentKeypair, getAgentBalance, getRemainingCredits, hasAgentSufficientBalance, keypairFromBase58, useCredit, validateCreditSession } from './agent/index.cjs';
7
7
  export { CustomPriceProvider, PriceConfig, PriceData, clearPriceCache, configurePricing, formatPriceDisplay, formatPriceSync, getProviders, getSolPrice, lamportsToSol, lamportsToUsd, usdToLamports } from './pricing/index.cjs';
8
8
  import '@solana/web3.js';
9
9
  import './types-BfKfgout.cjs';
package/dist/index.d.ts CHANGED
@@ -3,7 +3,7 @@ import { PaymentPayload, PaymentRequirements, VerifyResponse, SettleResponse, Su
3
3
  export * from '@x402/core/types';
4
4
  export * from '@x402/core/client';
5
5
  export * from '@x402/svm';
6
- export { AgentPaymentResult, CreditSessionClaims, CreditSessionConfig, CreditSessionData, CreditValidation, ExecuteAgentPaymentParams, UseCreditResult, addCredits, createCreditSession, executeAgentPayment, generateAgentKeypair, getAgentBalance, getRemainingCredits, hasAgentSufficientBalance, keypairFromBase58, useCredit, validateCreditSession } from './agent/index.js';
6
+ export { AgentPaymentResult, CreditSessionClaims, CreditSessionConfig, CreditSessionData, CreditValidation, ExecuteAgentPaymentParams, PayingAgent, PayingAgentConfig, UseCreditResult, addCredits, createCreditSession, createPayingAgent, executeAgentPayment, generateAgentKeypair, getAgentBalance, getRemainingCredits, hasAgentSufficientBalance, keypairFromBase58, useCredit, validateCreditSession } from './agent/index.js';
7
7
  export { CustomPriceProvider, PriceConfig, PriceData, clearPriceCache, configurePricing, formatPriceDisplay, formatPriceSync, getProviders, getSolPrice, lamportsToSol, lamportsToUsd, usdToLamports } from './pricing/index.js';
8
8
  import '@solana/web3.js';
9
9
  import './types-BfKfgout.js';