@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.
- package/README.md +38 -0
- package/dist/agent/index.cjs +451 -0
- package/dist/agent/index.d.cts +77 -1
- package/dist/agent/index.d.ts +77 -1
- package/dist/agent/index.js +452 -2
- package/dist/fetch/index.cjs +19 -0
- package/dist/fetch/index.js +19 -0
- package/dist/index.cjs +451 -0
- package/dist/index.d.cts +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +451 -1
- package/dist/next/index.cjs +29 -45
- package/dist/next/index.d.cts +1 -1
- package/dist/next/index.d.ts +1 -1
- package/dist/next/index.js +29 -45
- package/package.json +2 -2
package/dist/index.js
CHANGED
|
@@ -626,6 +626,456 @@ 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
|
+
const paymentRequired = response.headers.get("payment-required");
|
|
821
|
+
if (paymentRequired) {
|
|
822
|
+
try {
|
|
823
|
+
const jsonStr = atob(paymentRequired.trim());
|
|
824
|
+
const parsed = JSON.parse(jsonStr);
|
|
825
|
+
const option = Array.isArray(parsed.accepts) && parsed.accepts.length > 0 ? parsed.accepts[0] : parsed;
|
|
826
|
+
return {
|
|
827
|
+
payTo: option.payTo ?? option.recipient,
|
|
828
|
+
amount: String(option.amount),
|
|
829
|
+
asset: option.asset ?? "SOL",
|
|
830
|
+
network: option.network ?? "solana-mainnet",
|
|
831
|
+
description: parsed.description ?? option.description,
|
|
832
|
+
resource: parsed.resource ?? option.resource,
|
|
833
|
+
maxAge: parsed.maxAge ?? option.maxAge
|
|
834
|
+
};
|
|
835
|
+
} catch {
|
|
836
|
+
throw invalid402ResponseError("Invalid payment-required header");
|
|
837
|
+
}
|
|
838
|
+
}
|
|
839
|
+
throw invalid402ResponseError("No payment requirements found in 402 response");
|
|
840
|
+
}
|
|
841
|
+
function buildPaymentHeader(signature) {
|
|
842
|
+
const payload = {
|
|
843
|
+
x402Version: 2,
|
|
844
|
+
scheme: "exact",
|
|
845
|
+
payload: { signature }
|
|
846
|
+
};
|
|
847
|
+
return `X402 ${btoa(JSON.stringify(payload))}`;
|
|
848
|
+
}
|
|
849
|
+
function createX402Fetch(config) {
|
|
850
|
+
const {
|
|
851
|
+
wallet,
|
|
852
|
+
network = "mainnet-beta",
|
|
853
|
+
connection: providedConnection,
|
|
854
|
+
// Reserved for future facilitator integration
|
|
855
|
+
onPaymentRequired,
|
|
856
|
+
onPaymentSuccess,
|
|
857
|
+
onPaymentError,
|
|
858
|
+
priorityFee,
|
|
859
|
+
maxRetries = DEFAULT_MAX_RETRIES,
|
|
860
|
+
timeout = DEFAULT_CONFIRMATION_TIMEOUT,
|
|
861
|
+
// Security options
|
|
862
|
+
maxPaymentPerRequest,
|
|
863
|
+
allowedRecipients,
|
|
864
|
+
// UX options
|
|
865
|
+
commitment = "confirmed",
|
|
866
|
+
rateLimit
|
|
867
|
+
} = config;
|
|
868
|
+
const paymentTimestamps = [];
|
|
869
|
+
const rateLimitMax = rateLimit?.maxPayments ?? DEFAULT_RATE_LIMIT_MAX_PAYMENTS;
|
|
870
|
+
const rateLimitWindow = rateLimit?.windowMs ?? DEFAULT_RATE_LIMIT_WINDOW_MS;
|
|
871
|
+
function checkRateLimit() {
|
|
872
|
+
const now = Date.now();
|
|
873
|
+
while (paymentTimestamps.length > 0 && paymentTimestamps[0] < now - rateLimitWindow) {
|
|
874
|
+
paymentTimestamps.shift();
|
|
875
|
+
}
|
|
876
|
+
if (paymentTimestamps.length >= rateLimitMax) {
|
|
877
|
+
throw rateLimitExceededError(rateLimitMax, rateLimitWindow);
|
|
878
|
+
}
|
|
879
|
+
}
|
|
880
|
+
function recordPayment() {
|
|
881
|
+
paymentTimestamps.push(Date.now());
|
|
882
|
+
}
|
|
883
|
+
function validateSecurityRequirements(requirements) {
|
|
884
|
+
const amountLamports = BigInt(requirements.amount);
|
|
885
|
+
if (maxPaymentPerRequest !== void 0 && amountLamports > maxPaymentPerRequest) {
|
|
886
|
+
throw amountExceedsLimitError(requirements, maxPaymentPerRequest);
|
|
887
|
+
}
|
|
888
|
+
if (allowedRecipients !== void 0 && allowedRecipients.length > 0) {
|
|
889
|
+
if (!allowedRecipients.includes(requirements.payTo)) {
|
|
890
|
+
throw recipientNotAllowedError(requirements, requirements.payTo);
|
|
891
|
+
}
|
|
892
|
+
}
|
|
893
|
+
}
|
|
894
|
+
const connection = providedConnection ?? new Connection(RPC_ENDPOINTS[network], {
|
|
895
|
+
commitment
|
|
896
|
+
});
|
|
897
|
+
async function executePayment(requirements) {
|
|
898
|
+
const payer = getPublicKey(wallet);
|
|
899
|
+
const recipient = new PublicKey(requirements.payTo);
|
|
900
|
+
const amountLamports = BigInt(requirements.amount);
|
|
901
|
+
const balance = await connection.getBalance(payer);
|
|
902
|
+
if (BigInt(balance) < amountLamports) {
|
|
903
|
+
throw insufficientBalanceError(requirements, BigInt(balance));
|
|
904
|
+
}
|
|
905
|
+
const instructions = [];
|
|
906
|
+
if (priorityFee?.enabled) {
|
|
907
|
+
instructions.push(
|
|
908
|
+
ComputeBudgetProgram.setComputeUnitPrice({
|
|
909
|
+
microLamports: priorityFee.microLamports ?? 5e3
|
|
910
|
+
})
|
|
911
|
+
);
|
|
912
|
+
}
|
|
913
|
+
instructions.push(
|
|
914
|
+
SystemProgram.transfer({
|
|
915
|
+
fromPubkey: payer,
|
|
916
|
+
toPubkey: recipient,
|
|
917
|
+
lamports: amountLamports
|
|
918
|
+
})
|
|
919
|
+
);
|
|
920
|
+
const { blockhash, lastValidBlockHeight } = await connection.getLatestBlockhash();
|
|
921
|
+
const messageV0 = new TransactionMessage({
|
|
922
|
+
payerKey: payer,
|
|
923
|
+
recentBlockhash: blockhash,
|
|
924
|
+
instructions
|
|
925
|
+
}).compileToV0Message();
|
|
926
|
+
const tx = new VersionedTransaction(messageV0);
|
|
927
|
+
if (isKeypair(wallet)) {
|
|
928
|
+
tx.sign([wallet]);
|
|
929
|
+
} else {
|
|
930
|
+
const signerWallet = wallet;
|
|
931
|
+
if (!signerWallet.signTransaction) {
|
|
932
|
+
throw new X402PaymentError(
|
|
933
|
+
"Wallet does not support transaction signing. Use a SignerWalletAdapter.",
|
|
934
|
+
"WALLET_NOT_CONNECTED"
|
|
935
|
+
);
|
|
936
|
+
}
|
|
937
|
+
const signedTx = await signerWallet.signTransaction(tx);
|
|
938
|
+
if (signedTx.signatures[0]) {
|
|
939
|
+
tx.signatures[0] = signedTx.signatures[0];
|
|
940
|
+
}
|
|
941
|
+
}
|
|
942
|
+
const signature = await connection.sendTransaction(tx, {
|
|
943
|
+
maxRetries
|
|
944
|
+
});
|
|
945
|
+
await connection.confirmTransaction({
|
|
946
|
+
signature,
|
|
947
|
+
blockhash,
|
|
948
|
+
lastValidBlockHeight
|
|
949
|
+
}, commitment);
|
|
950
|
+
return signature;
|
|
951
|
+
}
|
|
952
|
+
async function x402Fetch(input, init) {
|
|
953
|
+
const { skipPayment, paymentOverride, ...fetchInit } = init ?? {};
|
|
954
|
+
let response;
|
|
955
|
+
try {
|
|
956
|
+
response = await fetch(input, fetchInit);
|
|
957
|
+
} catch (error) {
|
|
958
|
+
throw networkError(error instanceof Error ? error : void 0);
|
|
959
|
+
}
|
|
960
|
+
if (response.status !== 402) {
|
|
961
|
+
return response;
|
|
962
|
+
}
|
|
963
|
+
if (skipPayment) {
|
|
964
|
+
return response;
|
|
965
|
+
}
|
|
966
|
+
if (!isWalletConnected(wallet)) {
|
|
967
|
+
throw walletNotConnectedError();
|
|
968
|
+
}
|
|
969
|
+
let requirements;
|
|
970
|
+
try {
|
|
971
|
+
requirements = parse402Response(response);
|
|
972
|
+
if (paymentOverride) {
|
|
973
|
+
requirements = { ...requirements, ...paymentOverride };
|
|
974
|
+
}
|
|
975
|
+
} catch (error) {
|
|
976
|
+
if (error instanceof X402PaymentError) throw error;
|
|
977
|
+
throw invalid402ResponseError(error instanceof Error ? error.message : void 0);
|
|
978
|
+
}
|
|
979
|
+
validateSecurityRequirements(requirements);
|
|
980
|
+
checkRateLimit();
|
|
981
|
+
if (onPaymentRequired) {
|
|
982
|
+
const url = typeof input === "string" ? input : input instanceof URL ? input.href : input.url;
|
|
983
|
+
const shouldProceed = await onPaymentRequired(requirements, url);
|
|
984
|
+
if (!shouldProceed) {
|
|
985
|
+
throw userRejectedError(requirements);
|
|
986
|
+
}
|
|
987
|
+
}
|
|
988
|
+
let signature;
|
|
989
|
+
try {
|
|
990
|
+
const paymentPromise = executePayment(requirements);
|
|
991
|
+
const timeoutPromise = new Promise((_, reject) => {
|
|
992
|
+
setTimeout(() => reject(timeoutError(requirements)), timeout);
|
|
993
|
+
});
|
|
994
|
+
signature = await Promise.race([paymentPromise, timeoutPromise]);
|
|
995
|
+
recordPayment();
|
|
996
|
+
if (onPaymentSuccess) {
|
|
997
|
+
await onPaymentSuccess(signature, requirements);
|
|
998
|
+
}
|
|
999
|
+
} catch (error) {
|
|
1000
|
+
if (error instanceof X402PaymentError) {
|
|
1001
|
+
if (onPaymentError) {
|
|
1002
|
+
await onPaymentError(error, requirements);
|
|
1003
|
+
}
|
|
1004
|
+
throw error;
|
|
1005
|
+
}
|
|
1006
|
+
const wrappedError = transactionFailedError(
|
|
1007
|
+
requirements,
|
|
1008
|
+
error instanceof Error ? error : void 0
|
|
1009
|
+
);
|
|
1010
|
+
if (onPaymentError) {
|
|
1011
|
+
await onPaymentError(wrappedError, requirements);
|
|
1012
|
+
}
|
|
1013
|
+
throw wrappedError;
|
|
1014
|
+
}
|
|
1015
|
+
const retryHeaders = new Headers(fetchInit?.headers);
|
|
1016
|
+
retryHeaders.set("Authorization", buildPaymentHeader(signature));
|
|
1017
|
+
try {
|
|
1018
|
+
return await fetch(input, {
|
|
1019
|
+
...fetchInit,
|
|
1020
|
+
headers: retryHeaders
|
|
1021
|
+
});
|
|
1022
|
+
} catch (error) {
|
|
1023
|
+
throw networkError(error instanceof Error ? error : void 0);
|
|
1024
|
+
}
|
|
1025
|
+
}
|
|
1026
|
+
return x402Fetch;
|
|
1027
|
+
}
|
|
1028
|
+
|
|
1029
|
+
// src/agent/payingAgent.ts
|
|
1030
|
+
function createPayingAgent(privateKey, config = {}) {
|
|
1031
|
+
const {
|
|
1032
|
+
network = "mainnet-beta",
|
|
1033
|
+
rpcUrl,
|
|
1034
|
+
maxPaymentPerRequest,
|
|
1035
|
+
allowedRecipients,
|
|
1036
|
+
priorityFee = true
|
|
1037
|
+
} = config;
|
|
1038
|
+
let keypair;
|
|
1039
|
+
if (privateKey.includes(",")) {
|
|
1040
|
+
const bytes = new Uint8Array(privateKey.split(",").map((n) => parseInt(n.trim(), 10)));
|
|
1041
|
+
keypair = Keypair.fromSecretKey(bytes);
|
|
1042
|
+
} else {
|
|
1043
|
+
keypair = Keypair.fromSecretKey(bs58.decode(privateKey));
|
|
1044
|
+
}
|
|
1045
|
+
const endpoint = rpcUrl ?? RPC_ENDPOINTS[network];
|
|
1046
|
+
const connection = new Connection(endpoint, "confirmed");
|
|
1047
|
+
const fetchConfig = {
|
|
1048
|
+
wallet: keypair,
|
|
1049
|
+
network,
|
|
1050
|
+
connection,
|
|
1051
|
+
maxPaymentPerRequest,
|
|
1052
|
+
allowedRecipients,
|
|
1053
|
+
priorityFee: priorityFee ? { enabled: true, microLamports: 5e3 } : void 0
|
|
1054
|
+
};
|
|
1055
|
+
const x402Fetch = createX402Fetch(fetchConfig);
|
|
1056
|
+
return {
|
|
1057
|
+
get: (url, init) => x402Fetch(url, { ...init, method: "GET" }),
|
|
1058
|
+
post: (url, body, init) => x402Fetch(url, {
|
|
1059
|
+
...init,
|
|
1060
|
+
method: "POST",
|
|
1061
|
+
body: JSON.stringify(body),
|
|
1062
|
+
headers: {
|
|
1063
|
+
"Content-Type": "application/json",
|
|
1064
|
+
...init?.headers
|
|
1065
|
+
}
|
|
1066
|
+
}),
|
|
1067
|
+
fetch: (url, init) => x402Fetch(url, init),
|
|
1068
|
+
publicKey: keypair.publicKey.toBase58(),
|
|
1069
|
+
getBalance: async () => {
|
|
1070
|
+
const lamports = await connection.getBalance(keypair.publicKey);
|
|
1071
|
+
return {
|
|
1072
|
+
lamports: BigInt(lamports),
|
|
1073
|
+
sol: lamports / 1e9
|
|
1074
|
+
};
|
|
1075
|
+
}
|
|
1076
|
+
};
|
|
1077
|
+
}
|
|
1078
|
+
|
|
629
1079
|
// src/pricing/utils.ts
|
|
630
1080
|
function lamportsToSol(lamports) {
|
|
631
1081
|
return Number(lamports) / 1e9;
|
|
@@ -777,4 +1227,4 @@ function getProviders() {
|
|
|
777
1227
|
return PROVIDERS.map((p) => ({ name: p.name, url: p.url }));
|
|
778
1228
|
}
|
|
779
1229
|
|
|
780
|
-
export { LocalSvmFacilitator, RemoteSvmFacilitator, addCredits, clearPriceCache, configurePricing, createCreditSession, executeAgentPayment, formatPriceDisplay, formatPriceSync, generateAgentKeypair, getAgentBalance, getProviders, getRemainingCredits, getSolPrice, hasAgentSufficientBalance, keypairFromBase58, lamportsToSol, lamportsToUsd, usdToLamports, useCredit, validateCreditSession };
|
|
1230
|
+
export { LocalSvmFacilitator, RemoteSvmFacilitator, addCredits, clearPriceCache, configurePricing, createCreditSession, createPayingAgent, executeAgentPayment, formatPriceDisplay, formatPriceSync, generateAgentKeypair, getAgentBalance, getProviders, getRemainingCredits, getSolPrice, hasAgentSufficientBalance, keypairFromBase58, lamportsToSol, lamportsToUsd, usdToLamports, useCredit, validateCreditSession };
|
package/dist/next/index.cjs
CHANGED
|
@@ -233,31 +233,14 @@ function createX402Middleware(config) {
|
|
|
233
233
|
const server$2 = new server.x402ResourceServer(facilitatorClient);
|
|
234
234
|
server$1.registerExactSvmScheme(server$2);
|
|
235
235
|
const networkId = config.network === "mainnet-beta" ? "solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp" : "solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1";
|
|
236
|
-
return function withMicropay(handler,
|
|
236
|
+
return function withMicropay(handler, _routeConfig) {
|
|
237
237
|
const priceValue = config.price?.toString() || "0";
|
|
238
|
-
const amountValue = (BigInt(priceValue) * BigInt(1e6)).toString();
|
|
239
|
-
const paymentSpec = {
|
|
240
|
-
scheme: "exact",
|
|
241
|
-
payTo: config.walletAddress,
|
|
242
|
-
amount: amountValue,
|
|
243
|
-
network: networkId,
|
|
244
|
-
asset: "4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU"
|
|
245
|
-
// Native SOL asset
|
|
246
|
-
};
|
|
247
|
-
const finalConfig = routeConfig || {
|
|
248
|
-
accepts: {
|
|
249
|
-
...paymentSpec,
|
|
250
|
-
price: priceValue
|
|
251
|
-
// Include for x402 SDK 402 generation
|
|
252
|
-
}
|
|
253
|
-
};
|
|
254
|
-
const wrappedHandler = next.withX402(handler, finalConfig, server$2);
|
|
255
238
|
return async (req, ctx) => {
|
|
256
239
|
const authHeader = req.headers?.get?.("authorization") || req.headers?.authorization;
|
|
257
240
|
if (authHeader && authHeader.toLowerCase().startsWith("x402 ")) {
|
|
258
241
|
try {
|
|
259
|
-
const
|
|
260
|
-
const payloadJson = Buffer.from(
|
|
242
|
+
const base64Payload2 = authHeader.slice(5);
|
|
243
|
+
const payloadJson = Buffer.from(base64Payload2, "base64").toString("utf8");
|
|
261
244
|
let payload = JSON.parse(payloadJson);
|
|
262
245
|
if (payload.scheme === "exact-svm" || payload.scheme === "exact-evm") {
|
|
263
246
|
payload = transformPayAIToX402(payload, networkId);
|
|
@@ -267,7 +250,7 @@ function createX402Middleware(config) {
|
|
|
267
250
|
const verifyPaymentSpec = {
|
|
268
251
|
scheme: payload.scheme || "exact",
|
|
269
252
|
network: payload.network || networkId,
|
|
270
|
-
amount:
|
|
253
|
+
amount: priceValue,
|
|
271
254
|
payTo: config.walletAddress
|
|
272
255
|
};
|
|
273
256
|
let verifyResult;
|
|
@@ -290,32 +273,33 @@ function createX402Middleware(config) {
|
|
|
290
273
|
} catch (parseError) {
|
|
291
274
|
}
|
|
292
275
|
}
|
|
293
|
-
const
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
276
|
+
const paymentPayload = {
|
|
277
|
+
x402Version: 2,
|
|
278
|
+
error: "Payment required",
|
|
279
|
+
resource: {
|
|
280
|
+
url: req.nextUrl?.pathname || req.url,
|
|
281
|
+
description: "",
|
|
282
|
+
mimeType: ""
|
|
283
|
+
},
|
|
284
|
+
accepts: [{
|
|
285
|
+
scheme: "exact",
|
|
286
|
+
network: networkId,
|
|
287
|
+
amount: priceValue,
|
|
288
|
+
// Use raw lamports, no multiplier
|
|
289
|
+
asset: "4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU",
|
|
290
|
+
payTo: config.walletAddress,
|
|
291
|
+
maxTimeoutSeconds: 300,
|
|
292
|
+
extra: { feePayer: "11111111111111111111111111111111" }
|
|
293
|
+
}]
|
|
294
|
+
};
|
|
295
|
+
const base64Payload = Buffer.from(JSON.stringify(paymentPayload)).toString("base64");
|
|
296
|
+
return new Response(JSON.stringify({}), {
|
|
297
|
+
status: 402,
|
|
298
|
+
headers: {
|
|
299
|
+
"Content-Type": "application/json",
|
|
300
|
+
"payment-required": base64Payload
|
|
316
301
|
}
|
|
317
302
|
});
|
|
318
|
-
return await wrappedHandler(compatibleReq, ctx);
|
|
319
303
|
};
|
|
320
304
|
};
|
|
321
305
|
}
|
package/dist/next/index.d.cts
CHANGED
|
@@ -19,7 +19,7 @@ interface X402Config {
|
|
|
19
19
|
/**
|
|
20
20
|
* Create a specialized Next.js middleware with Solana support pre-configured
|
|
21
21
|
*/
|
|
22
|
-
declare function createX402Middleware(config: X402Config): (handler: any,
|
|
22
|
+
declare function createX402Middleware(config: X402Config): (handler: any, _routeConfig?: any) => (req: any, ctx: any) => Promise<any>;
|
|
23
23
|
declare const withX402: typeof withX402$1;
|
|
24
24
|
|
|
25
25
|
export { type X402Config, createX402Middleware, withX402 };
|
package/dist/next/index.d.ts
CHANGED
|
@@ -19,7 +19,7 @@ interface X402Config {
|
|
|
19
19
|
/**
|
|
20
20
|
* Create a specialized Next.js middleware with Solana support pre-configured
|
|
21
21
|
*/
|
|
22
|
-
declare function createX402Middleware(config: X402Config): (handler: any,
|
|
22
|
+
declare function createX402Middleware(config: X402Config): (handler: any, _routeConfig?: any) => (req: any, ctx: any) => Promise<any>;
|
|
23
23
|
declare const withX402: typeof withX402$1;
|
|
24
24
|
|
|
25
25
|
export { type X402Config, createX402Middleware, withX402 };
|
package/dist/next/index.js
CHANGED
|
@@ -232,31 +232,14 @@ function createX402Middleware(config) {
|
|
|
232
232
|
const server = new x402ResourceServer(facilitatorClient);
|
|
233
233
|
registerExactSvmScheme(server);
|
|
234
234
|
const networkId = config.network === "mainnet-beta" ? "solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp" : "solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1";
|
|
235
|
-
return function withMicropay(handler,
|
|
235
|
+
return function withMicropay(handler, _routeConfig) {
|
|
236
236
|
const priceValue = config.price?.toString() || "0";
|
|
237
|
-
const amountValue = (BigInt(priceValue) * BigInt(1e6)).toString();
|
|
238
|
-
const paymentSpec = {
|
|
239
|
-
scheme: "exact",
|
|
240
|
-
payTo: config.walletAddress,
|
|
241
|
-
amount: amountValue,
|
|
242
|
-
network: networkId,
|
|
243
|
-
asset: "4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU"
|
|
244
|
-
// Native SOL asset
|
|
245
|
-
};
|
|
246
|
-
const finalConfig = routeConfig || {
|
|
247
|
-
accepts: {
|
|
248
|
-
...paymentSpec,
|
|
249
|
-
price: priceValue
|
|
250
|
-
// Include for x402 SDK 402 generation
|
|
251
|
-
}
|
|
252
|
-
};
|
|
253
|
-
const wrappedHandler = withX402$1(handler, finalConfig, server);
|
|
254
237
|
return async (req, ctx) => {
|
|
255
238
|
const authHeader = req.headers?.get?.("authorization") || req.headers?.authorization;
|
|
256
239
|
if (authHeader && authHeader.toLowerCase().startsWith("x402 ")) {
|
|
257
240
|
try {
|
|
258
|
-
const
|
|
259
|
-
const payloadJson = Buffer.from(
|
|
241
|
+
const base64Payload2 = authHeader.slice(5);
|
|
242
|
+
const payloadJson = Buffer.from(base64Payload2, "base64").toString("utf8");
|
|
260
243
|
let payload = JSON.parse(payloadJson);
|
|
261
244
|
if (payload.scheme === "exact-svm" || payload.scheme === "exact-evm") {
|
|
262
245
|
payload = transformPayAIToX402(payload, networkId);
|
|
@@ -266,7 +249,7 @@ function createX402Middleware(config) {
|
|
|
266
249
|
const verifyPaymentSpec = {
|
|
267
250
|
scheme: payload.scheme || "exact",
|
|
268
251
|
network: payload.network || networkId,
|
|
269
|
-
amount:
|
|
252
|
+
amount: priceValue,
|
|
270
253
|
payTo: config.walletAddress
|
|
271
254
|
};
|
|
272
255
|
let verifyResult;
|
|
@@ -289,32 +272,33 @@ function createX402Middleware(config) {
|
|
|
289
272
|
} catch (parseError) {
|
|
290
273
|
}
|
|
291
274
|
}
|
|
292
|
-
const
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
275
|
+
const paymentPayload = {
|
|
276
|
+
x402Version: 2,
|
|
277
|
+
error: "Payment required",
|
|
278
|
+
resource: {
|
|
279
|
+
url: req.nextUrl?.pathname || req.url,
|
|
280
|
+
description: "",
|
|
281
|
+
mimeType: ""
|
|
282
|
+
},
|
|
283
|
+
accepts: [{
|
|
284
|
+
scheme: "exact",
|
|
285
|
+
network: networkId,
|
|
286
|
+
amount: priceValue,
|
|
287
|
+
// Use raw lamports, no multiplier
|
|
288
|
+
asset: "4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU",
|
|
289
|
+
payTo: config.walletAddress,
|
|
290
|
+
maxTimeoutSeconds: 300,
|
|
291
|
+
extra: { feePayer: "11111111111111111111111111111111" }
|
|
292
|
+
}]
|
|
293
|
+
};
|
|
294
|
+
const base64Payload = Buffer.from(JSON.stringify(paymentPayload)).toString("base64");
|
|
295
|
+
return new Response(JSON.stringify({}), {
|
|
296
|
+
status: 402,
|
|
297
|
+
headers: {
|
|
298
|
+
"Content-Type": "application/json",
|
|
299
|
+
"payment-required": base64Payload
|
|
315
300
|
}
|
|
316
301
|
});
|
|
317
|
-
return await wrappedHandler(compatibleReq, ctx);
|
|
318
302
|
};
|
|
319
303
|
};
|
|
320
304
|
}
|