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