@cedros/pay-react 0.1.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.
- package/LICENSE +21 -0
- package/README.md +1731 -0
- package/dist/CedrosContext-B3iCqN6e.js +11 -0
- package/dist/CedrosContext-vX9uqZKp.mjs +1796 -0
- package/dist/ar-LVoQZTFI.js +1 -0
- package/dist/ar-w27mU-4x.mjs +19 -0
- package/dist/bn-BR5Cv1T4.js +1 -0
- package/dist/bn-Ba_k3Kex.mjs +19 -0
- package/dist/components/CedrosPay.d.ts +54 -0
- package/dist/components/CedrosPay.d.ts.map +1 -0
- package/dist/components/CryptoButton.d.ts +26 -0
- package/dist/components/CryptoButton.d.ts.map +1 -0
- package/dist/components/PaymentModal.d.ts +28 -0
- package/dist/components/PaymentModal.d.ts.map +1 -0
- package/dist/components/ProductPrice.d.ts +56 -0
- package/dist/components/ProductPrice.d.ts.map +1 -0
- package/dist/components/PurchaseButton.d.ts +52 -0
- package/dist/components/PurchaseButton.d.ts.map +1 -0
- package/dist/components/StripeButton.d.ts +27 -0
- package/dist/components/StripeButton.d.ts.map +1 -0
- package/dist/context/CedrosContext.d.ts +46 -0
- package/dist/context/CedrosContext.d.ts.map +1 -0
- package/dist/context/ThemeContext.d.ts +30 -0
- package/dist/context/ThemeContext.d.ts.map +1 -0
- package/dist/context/index.d.ts +3 -0
- package/dist/context/index.d.ts.map +1 -0
- package/dist/crypto-only.d.ts +33 -0
- package/dist/crypto-only.d.ts.map +1 -0
- package/dist/crypto-only.js +1 -0
- package/dist/crypto-only.mjs +35 -0
- package/dist/de-CoZiPFN7.mjs +19 -0
- package/dist/de-pQxy-oD1.js +1 -0
- package/dist/en-CSsJl3nf.mjs +19 -0
- package/dist/en-D-uY3ltT.js +1 -0
- package/dist/es-BWGIBp2f.mjs +19 -0
- package/dist/es-D24cg8dD.js +1 -0
- package/dist/fil-BOBft9G-.js +1 -0
- package/dist/fil-Czo27xmj.mjs +19 -0
- package/dist/fr-Ct9ub8Fa.js +1 -0
- package/dist/fr-DQ-2ThBv.mjs +19 -0
- package/dist/he-DpV1WnBQ.mjs +19 -0
- package/dist/he-DtQqRKRq.js +1 -0
- package/dist/hooks/usePaymentMode.d.ts +39 -0
- package/dist/hooks/usePaymentMode.d.ts.map +1 -0
- package/dist/hooks/useRefundVerification.d.ts +30 -0
- package/dist/hooks/useRefundVerification.d.ts.map +1 -0
- package/dist/hooks/useStripeCheckout.d.ts +20 -0
- package/dist/hooks/useStripeCheckout.d.ts.map +1 -0
- package/dist/hooks/useX402Payment.d.ts +24 -0
- package/dist/hooks/useX402Payment.d.ts.map +1 -0
- package/dist/i18n/index.d.ts +107 -0
- package/dist/i18n/index.d.ts.map +1 -0
- package/dist/i18n/useTranslation.d.ts +55 -0
- package/dist/i18n/useTranslation.d.ts.map +1 -0
- package/dist/id-BJMqsu19.mjs +19 -0
- package/dist/id-CiM2mL7C.js +1 -0
- package/dist/in-BxgxKLQH.mjs +19 -0
- package/dist/in-Bzcjmxcc.js +1 -0
- package/dist/index.d.ts +33 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +1 -0
- package/dist/index.mjs +626 -0
- package/dist/it-Blb_pIJl.js +1 -0
- package/dist/it-DZFFPALf.mjs +19 -0
- package/dist/jp-9NHyIuwY.js +1 -0
- package/dist/jp-ZExTrlHK.mjs +19 -0
- package/dist/kr-DHX3i4Ht.mjs +19 -0
- package/dist/kr-DvzJ-0yX.js +1 -0
- package/dist/managers/ManagerCache.d.ts +49 -0
- package/dist/managers/ManagerCache.d.ts.map +1 -0
- package/dist/managers/RouteDiscoveryManager.d.ts +72 -0
- package/dist/managers/RouteDiscoveryManager.d.ts.map +1 -0
- package/dist/managers/StripeManager.d.ts +110 -0
- package/dist/managers/StripeManager.d.ts.map +1 -0
- package/dist/managers/WalletManager.d.ts +150 -0
- package/dist/managers/WalletManager.d.ts.map +1 -0
- package/dist/managers/X402Manager.d.ts +176 -0
- package/dist/managers/X402Manager.d.ts.map +1 -0
- package/dist/ms-BOAu5pUB.js +1 -0
- package/dist/ms-Cv1fdIi2.mjs +19 -0
- package/dist/nl-BmGonsKb.mjs +19 -0
- package/dist/nl-WHh_DfO8.js +1 -0
- package/dist/pa-B7kIhZCF.js +1 -0
- package/dist/pa-BfwcJIar.mjs +19 -0
- package/dist/pay-react.css +1 -0
- package/dist/pl-DE5IB9xv.mjs +19 -0
- package/dist/pl-H0hBKdvF.js +1 -0
- package/dist/pt-CLzkqDzf.mjs +19 -0
- package/dist/pt-DwGrViQ3.js +1 -0
- package/dist/ru-CB2m0UDT.js +1 -0
- package/dist/ru-DM6-oUR0.mjs +19 -0
- package/dist/stripe-only.d.ts +31 -0
- package/dist/stripe-only.d.ts.map +1 -0
- package/dist/stripe-only.js +1 -0
- package/dist/stripe-only.mjs +33 -0
- package/dist/styles-D3XGpsqb.js +1 -0
- package/dist/styles-zgmHs6Hs.mjs +1601 -0
- package/dist/ta-A5HnrGb5.mjs +19 -0
- package/dist/ta-CAS197uN.js +1 -0
- package/dist/telemetry.d.ts +27 -0
- package/dist/telemetry.d.ts.map +1 -0
- package/dist/telemetry.js +1 -0
- package/dist/telemetry.mjs +127 -0
- package/dist/testing/__tests__/providers.test.d.ts +10 -0
- package/dist/testing/__tests__/providers.test.d.ts.map +1 -0
- package/dist/testing/helpers.d.ts +242 -0
- package/dist/testing/helpers.d.ts.map +1 -0
- package/dist/testing/index.d.ts +12 -0
- package/dist/testing/index.d.ts.map +1 -0
- package/dist/testing/index.js +1 -0
- package/dist/testing/index.mjs +374 -0
- package/dist/testing/mocks.d.ts +225 -0
- package/dist/testing/mocks.d.ts.map +1 -0
- package/dist/testing/providers.d.ts +89 -0
- package/dist/testing/providers.d.ts.map +1 -0
- package/dist/th-3fbB3Ytp.mjs +19 -0
- package/dist/th-Cpz2cFcg.js +1 -0
- package/dist/tr-BrgfFFdq.mjs +19 -0
- package/dist/tr-hQrEFk86.js +1 -0
- package/dist/types/componentOptions.d.ts +138 -0
- package/dist/types/componentOptions.d.ts.map +1 -0
- package/dist/types/errors.d.ts +213 -0
- package/dist/types/errors.d.ts.map +1 -0
- package/dist/types/index.d.ts +248 -0
- package/dist/types/index.d.ts.map +1 -0
- package/dist/uk-0hFun_g_.mjs +19 -0
- package/dist/uk-DrK2Sv8C.js +1 -0
- package/dist/ur-CaOjJXai.mjs +19 -0
- package/dist/ur-D5-7mN9a.js +1 -0
- package/dist/utils/__tests__/cspHelper.test.d.ts +9 -0
- package/dist/utils/__tests__/cspHelper.test.d.ts.map +1 -0
- package/dist/utils/__tests__/fetchWithTimeout.test.d.ts +11 -0
- package/dist/utils/__tests__/fetchWithTimeout.test.d.ts.map +1 -0
- package/dist/utils/cartHelpers.d.ts +105 -0
- package/dist/utils/cartHelpers.d.ts.map +1 -0
- package/dist/utils/circuitBreaker.d.ts +112 -0
- package/dist/utils/circuitBreaker.d.ts.map +1 -0
- package/dist/utils/couponHelpers.d.ts +50 -0
- package/dist/utils/couponHelpers.d.ts.map +1 -0
- package/dist/utils/cspHelper.d.ts +162 -0
- package/dist/utils/cspHelper.d.ts.map +1 -0
- package/dist/utils/deprecation.d.ts +128 -0
- package/dist/utils/deprecation.d.ts.map +1 -0
- package/dist/utils/errorHandling.d.ts +30 -0
- package/dist/utils/errorHandling.d.ts.map +1 -0
- package/dist/utils/errorMessages.d.ts +47 -0
- package/dist/utils/errorMessages.d.ts.map +1 -0
- package/dist/utils/errorParser.d.ts +37 -0
- package/dist/utils/errorParser.d.ts.map +1 -0
- package/dist/utils/eventEmitter.d.ts +119 -0
- package/dist/utils/eventEmitter.d.ts.map +1 -0
- package/dist/utils/exponentialBackoff.d.ts +104 -0
- package/dist/utils/exponentialBackoff.d.ts.map +1 -0
- package/dist/utils/fetchWithTimeout.d.ts +13 -0
- package/dist/utils/fetchWithTimeout.d.ts.map +1 -0
- package/dist/utils/index.d.ts +15 -0
- package/dist/utils/index.d.ts.map +1 -0
- package/dist/utils/logger.d.ts +76 -0
- package/dist/utils/logger.d.ts.map +1 -0
- package/dist/utils/modalStyles.d.ts +13 -0
- package/dist/utils/modalStyles.d.ts.map +1 -0
- package/dist/utils/rateLimiter.d.ts +88 -0
- package/dist/utils/rateLimiter.d.ts.map +1 -0
- package/dist/utils/requestDeduplication.d.ts +124 -0
- package/dist/utils/requestDeduplication.d.ts.map +1 -0
- package/dist/utils/securityValidation.d.ts +75 -0
- package/dist/utils/securityValidation.d.ts.map +1 -0
- package/dist/utils/solanaCheck.d.ts +10 -0
- package/dist/utils/solanaCheck.d.ts.map +1 -0
- package/dist/utils/telemetry.d.ts +277 -0
- package/dist/utils/telemetry.d.ts.map +1 -0
- package/dist/utils/tokenMintValidator.d.ts +77 -0
- package/dist/utils/tokenMintValidator.d.ts.map +1 -0
- package/dist/utils/uuid.d.ts +13 -0
- package/dist/utils/uuid.d.ts.map +1 -0
- package/dist/utils/validateConfig.d.ts +13 -0
- package/dist/utils/validateConfig.d.ts.map +1 -0
- package/dist/utils/walletDetection.d.ts +6 -0
- package/dist/utils/walletDetection.d.ts.map +1 -0
- package/dist/utils/walletPool.d.ts +57 -0
- package/dist/utils/walletPool.d.ts.map +1 -0
- package/dist/uuid-C0iMjdcc.js +1 -0
- package/dist/uuid-UlzrVY8Y.mjs +17 -0
- package/dist/vn-0nlIZFLP.mjs +19 -0
- package/dist/vn-B_iut9YL.js +1 -0
- package/dist/walletDetection-JZR3UCOa.mjs +27 -0
- package/dist/walletDetection-bNmV5ItZ.js +1 -0
- package/dist/zh-B4Endr1F.mjs +19 -0
- package/dist/zh-PR82dCHr.js +1 -0
- package/package.json +139 -0
|
@@ -0,0 +1,1796 @@
|
|
|
1
|
+
import { jsx as H } from "react/jsx-runtime";
|
|
2
|
+
import { createContext as me, useContext as pe, useState as X, useRef as ye, useEffect as D, useMemo as Y } from "react";
|
|
3
|
+
import { g as N } from "./uuid-UlzrVY8Y.mjs";
|
|
4
|
+
import { clusterApiUrl as Le, Connection as $e, Transaction as ae, PublicKey as M, LAMPORTS_PER_SOL as _e } from "@solana/web3.js";
|
|
5
|
+
import { getAssociatedTokenAddress as je, createTransferInstruction as qe } from "@solana/spl-token";
|
|
6
|
+
import { PhantomWalletAdapter as We, SolflareWalletAdapter as Ke } from "@solana/wallet-adapter-wallets";
|
|
7
|
+
var we = "https://js.stripe.com/v3", ze = /^https:\/\/js\.stripe\.com\/v3\/?(\?.*)?$/;
|
|
8
|
+
var Ve = function() {
|
|
9
|
+
for (var e = document.querySelectorAll('script[src^="'.concat(we, '"]')), r = 0; r < e.length; r++) {
|
|
10
|
+
var n = e[r];
|
|
11
|
+
if (ze.test(n.src))
|
|
12
|
+
return n;
|
|
13
|
+
}
|
|
14
|
+
return null;
|
|
15
|
+
}, oe = function(e) {
|
|
16
|
+
var r = "", n = document.createElement("script");
|
|
17
|
+
n.src = "".concat(we).concat(r);
|
|
18
|
+
var a = document.head || document.body;
|
|
19
|
+
if (!a)
|
|
20
|
+
throw new Error("Expected document.body not to be null. Stripe.js requires a <body> element.");
|
|
21
|
+
return a.appendChild(n), n;
|
|
22
|
+
}, Ge = function(e, r) {
|
|
23
|
+
!e || !e._registerWrapper || e._registerWrapper({
|
|
24
|
+
name: "stripe-js",
|
|
25
|
+
version: "4.6.0",
|
|
26
|
+
startTime: r
|
|
27
|
+
});
|
|
28
|
+
}, U = null, $ = null, _ = null, He = function(e) {
|
|
29
|
+
return function() {
|
|
30
|
+
e(new Error("Failed to load Stripe.js"));
|
|
31
|
+
};
|
|
32
|
+
}, Xe = function(e, r) {
|
|
33
|
+
return function() {
|
|
34
|
+
window.Stripe ? e(window.Stripe) : r(new Error("Stripe.js not available"));
|
|
35
|
+
};
|
|
36
|
+
}, Ye = function(e) {
|
|
37
|
+
return U !== null ? U : (U = new Promise(function(r, n) {
|
|
38
|
+
if (typeof window > "u" || typeof document > "u") {
|
|
39
|
+
r(null);
|
|
40
|
+
return;
|
|
41
|
+
}
|
|
42
|
+
if (window.Stripe) {
|
|
43
|
+
r(window.Stripe);
|
|
44
|
+
return;
|
|
45
|
+
}
|
|
46
|
+
try {
|
|
47
|
+
var a = Ve();
|
|
48
|
+
if (!(a && e)) {
|
|
49
|
+
if (!a)
|
|
50
|
+
a = oe(e);
|
|
51
|
+
else if (a && _ !== null && $ !== null) {
|
|
52
|
+
var o;
|
|
53
|
+
a.removeEventListener("load", _), a.removeEventListener("error", $), (o = a.parentNode) === null || o === void 0 || o.removeChild(a), a = oe(e);
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
_ = Xe(r, n), $ = He(n), a.addEventListener("load", _), a.addEventListener("error", $);
|
|
57
|
+
} catch (s) {
|
|
58
|
+
n(s);
|
|
59
|
+
return;
|
|
60
|
+
}
|
|
61
|
+
}), U.catch(function(r) {
|
|
62
|
+
return U = null, Promise.reject(r);
|
|
63
|
+
}));
|
|
64
|
+
}, Qe = function(e, r, n) {
|
|
65
|
+
if (e === null)
|
|
66
|
+
return null;
|
|
67
|
+
var a = e.apply(void 0, r);
|
|
68
|
+
return Ge(a, n), a;
|
|
69
|
+
}, O, ge = !1, be = function() {
|
|
70
|
+
return O || (O = Ye(null).catch(function(e) {
|
|
71
|
+
return O = null, Promise.reject(e);
|
|
72
|
+
}), O);
|
|
73
|
+
};
|
|
74
|
+
Promise.resolve().then(function() {
|
|
75
|
+
return be();
|
|
76
|
+
}).catch(function(t) {
|
|
77
|
+
ge || console.warn(t);
|
|
78
|
+
});
|
|
79
|
+
var Je = function() {
|
|
80
|
+
for (var e = arguments.length, r = new Array(e), n = 0; n < e; n++)
|
|
81
|
+
r[n] = arguments[n];
|
|
82
|
+
ge = !0;
|
|
83
|
+
var a = Date.now();
|
|
84
|
+
return be().then(function(o) {
|
|
85
|
+
return Qe(o, r, a);
|
|
86
|
+
});
|
|
87
|
+
}, Ze = /* @__PURE__ */ ((t) => (t[t.DEBUG = 0] = "DEBUG", t[t.INFO = 1] = "INFO", t[t.WARN = 2] = "WARN", t[t.ERROR = 3] = "ERROR", t[t.SILENT = 4] = "SILENT", t))(Ze || {});
|
|
88
|
+
class ve {
|
|
89
|
+
config;
|
|
90
|
+
constructor(e) {
|
|
91
|
+
this.config = e;
|
|
92
|
+
}
|
|
93
|
+
/**
|
|
94
|
+
* Update the log level dynamically
|
|
95
|
+
*/
|
|
96
|
+
setLevel(e) {
|
|
97
|
+
this.config.level = e;
|
|
98
|
+
}
|
|
99
|
+
/**
|
|
100
|
+
* Get the current log level
|
|
101
|
+
*/
|
|
102
|
+
getLevel() {
|
|
103
|
+
return this.config.level;
|
|
104
|
+
}
|
|
105
|
+
/**
|
|
106
|
+
* Debug-level logging (most verbose)
|
|
107
|
+
* Use for detailed debugging information
|
|
108
|
+
*/
|
|
109
|
+
debug(...e) {
|
|
110
|
+
this.config.level <= 0 && this.log("DEBUG", console.log, e);
|
|
111
|
+
}
|
|
112
|
+
/**
|
|
113
|
+
* Info-level logging
|
|
114
|
+
* Use for general informational messages
|
|
115
|
+
*/
|
|
116
|
+
info(...e) {
|
|
117
|
+
this.config.level <= 1 && this.log("INFO", console.info, e);
|
|
118
|
+
}
|
|
119
|
+
/**
|
|
120
|
+
* Warning-level logging
|
|
121
|
+
* Use for potentially problematic situations
|
|
122
|
+
*/
|
|
123
|
+
warn(...e) {
|
|
124
|
+
this.config.level <= 2 && this.log("WARN", console.warn, e);
|
|
125
|
+
}
|
|
126
|
+
/**
|
|
127
|
+
* Error-level logging
|
|
128
|
+
* Use for error conditions
|
|
129
|
+
*/
|
|
130
|
+
error(...e) {
|
|
131
|
+
this.config.level <= 3 && this.log("ERROR", console.error, e);
|
|
132
|
+
}
|
|
133
|
+
/**
|
|
134
|
+
* Internal log method with formatting
|
|
135
|
+
*/
|
|
136
|
+
log(e, r, n) {
|
|
137
|
+
const a = this.config.prefix ? `${this.config.prefix} ` : "", o = (/* @__PURE__ */ new Date()).toISOString();
|
|
138
|
+
r(`[${o}] ${a}[${e}]`, ...n);
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
const et = () => typeof process < "u" && process.env.NODE_ENV === "development" ? 0 : 2;
|
|
142
|
+
let q = null;
|
|
143
|
+
function f() {
|
|
144
|
+
return q || (q = new ve({
|
|
145
|
+
level: et(),
|
|
146
|
+
prefix: "[CedrosPay]"
|
|
147
|
+
})), q;
|
|
148
|
+
}
|
|
149
|
+
function tt(t) {
|
|
150
|
+
q = t;
|
|
151
|
+
}
|
|
152
|
+
function rt(t) {
|
|
153
|
+
return new ve(t);
|
|
154
|
+
}
|
|
155
|
+
function F(t, e) {
|
|
156
|
+
return t instanceof Error ? t.message : typeof t == "string" ? t : e;
|
|
157
|
+
}
|
|
158
|
+
const nt = {
|
|
159
|
+
service_unavailable: "Service temporarily unavailable. Please try again later or contact support.",
|
|
160
|
+
server_insufficient_funds: "Service temporarily unavailable. Please try again later or contact support.",
|
|
161
|
+
insufficient_funds_token: "Insufficient token balance in your wallet. Please add more tokens and try again.",
|
|
162
|
+
insufficient_funds_sol: "Insufficient SOL for transaction fees. Please add some SOL to your wallet and try again.",
|
|
163
|
+
insufficient_amount: "Payment amount is insufficient. Please check the required amount.",
|
|
164
|
+
invalid_signature: "Transaction signature is invalid. Please try again.",
|
|
165
|
+
send_failed: "Failed to send transaction. Please try again or contact support.",
|
|
166
|
+
timeout: "Transaction timed out. Please check the blockchain explorer or try again."
|
|
167
|
+
};
|
|
168
|
+
async function T(t, e, r = !1) {
|
|
169
|
+
try {
|
|
170
|
+
const n = await t.json();
|
|
171
|
+
if (r && n.verificationError) {
|
|
172
|
+
f().debug(`Payment verification failed: ${n.verificationError.code}`);
|
|
173
|
+
const a = n.verificationError.code;
|
|
174
|
+
return nt[a] || n.verificationError.message || e;
|
|
175
|
+
}
|
|
176
|
+
return typeof n.error == "string" ? n.error : n.error && typeof n.error == "object" && "message" in n.error ? n.error.message : e;
|
|
177
|
+
} catch {
|
|
178
|
+
return await t.text() || e;
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
const at = 3e4;
|
|
182
|
+
async function S(t, e = {}, r = at) {
|
|
183
|
+
const n = new AbortController(), a = e.signal;
|
|
184
|
+
if (a?.aborted)
|
|
185
|
+
throw n.abort(), new DOMException("The operation was aborted", "AbortError");
|
|
186
|
+
const o = setTimeout(() => n.abort(), r);
|
|
187
|
+
let s = null;
|
|
188
|
+
a && (s = () => n.abort(), a.addEventListener("abort", s));
|
|
189
|
+
try {
|
|
190
|
+
return await fetch(t, {
|
|
191
|
+
...e,
|
|
192
|
+
signal: n.signal
|
|
193
|
+
});
|
|
194
|
+
} catch (i) {
|
|
195
|
+
throw i instanceof Error && i.name === "AbortError" ? a?.aborted ? i : new Error(`Request timeout after ${r}ms`) : i;
|
|
196
|
+
} finally {
|
|
197
|
+
clearTimeout(o), a && s && a.removeEventListener("abort", s);
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
function K(t) {
|
|
201
|
+
const { maxRequests: e, windowMs: r } = t;
|
|
202
|
+
let n = e, a = Date.now();
|
|
203
|
+
const o = e / r;
|
|
204
|
+
function s() {
|
|
205
|
+
const d = Date.now(), h = d - a;
|
|
206
|
+
if (h > 0) {
|
|
207
|
+
const p = h * o;
|
|
208
|
+
n = Math.min(e, n + p), a = d;
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
function i() {
|
|
212
|
+
return s(), n >= 1 ? (n -= 1, !0) : !1;
|
|
213
|
+
}
|
|
214
|
+
function l() {
|
|
215
|
+
return s(), Math.floor(n);
|
|
216
|
+
}
|
|
217
|
+
function c() {
|
|
218
|
+
if (s(), n >= 1)
|
|
219
|
+
return 0;
|
|
220
|
+
const h = (1 - n) / o;
|
|
221
|
+
return Math.ceil(h);
|
|
222
|
+
}
|
|
223
|
+
function u() {
|
|
224
|
+
n = e, a = Date.now();
|
|
225
|
+
}
|
|
226
|
+
return {
|
|
227
|
+
tryConsume: i,
|
|
228
|
+
getAvailableTokens: l,
|
|
229
|
+
getTimeUntilRefill: c,
|
|
230
|
+
reset: u
|
|
231
|
+
};
|
|
232
|
+
}
|
|
233
|
+
const Q = {
|
|
234
|
+
/** 10 requests per minute - recommended for payment requests */
|
|
235
|
+
PAYMENT: { maxRequests: 10, windowMs: 6e4 },
|
|
236
|
+
/** 30 requests per minute - for quote fetching */
|
|
237
|
+
QUOTE: { maxRequests: 30, windowMs: 6e4 },
|
|
238
|
+
/** 5 requests per minute - strict limit for sensitive operations */
|
|
239
|
+
STRICT: { maxRequests: 5, windowMs: 6e4 },
|
|
240
|
+
/** 100 requests per minute - permissive for UI interactions */
|
|
241
|
+
PERMISSIVE: { maxRequests: 100, windowMs: 6e4 }
|
|
242
|
+
};
|
|
243
|
+
var ot = /* @__PURE__ */ ((t) => (t.CLOSED = "CLOSED", t.OPEN = "OPEN", t.HALF_OPEN = "HALF_OPEN", t))(ot || {});
|
|
244
|
+
class E extends Error {
|
|
245
|
+
constructor(e) {
|
|
246
|
+
super(e), this.name = "CircuitBreakerOpenError";
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
function te(t) {
|
|
250
|
+
const { failureThreshold: e, timeout: r, name: n = "circuit-breaker" } = t;
|
|
251
|
+
let a = "CLOSED", o = 0, s = 0, i = 0, l = null, c = null, u = null;
|
|
252
|
+
function d() {
|
|
253
|
+
a === "OPEN" && u !== null && Date.now() >= u && (f().debug(`[CircuitBreaker:${n}] Transitioning OPEN → HALF_OPEN (timeout expired)`), a = "HALF_OPEN", u = null);
|
|
254
|
+
}
|
|
255
|
+
function h() {
|
|
256
|
+
c = Date.now(), s++, a === "HALF_OPEN" ? (f().debug(`[CircuitBreaker:${n}] Success in HALF_OPEN → CLOSED`), a = "CLOSED", o = 0) : a === "CLOSED" && (o = 0);
|
|
257
|
+
}
|
|
258
|
+
function p(b) {
|
|
259
|
+
l = Date.now(), o++, f().warn(`[CircuitBreaker:${n}] Failure recorded (${o}/${e}):`, b.message), a === "HALF_OPEN" ? (f().warn(`[CircuitBreaker:${n}] Failed in HALF_OPEN → OPEN`), a = "OPEN", u = Date.now() + r) : a === "CLOSED" && o >= e && (f().error(`[CircuitBreaker:${n}] Failure threshold reached (${o}) → OPEN`), a = "OPEN", u = Date.now() + r);
|
|
260
|
+
}
|
|
261
|
+
async function m(b) {
|
|
262
|
+
if (d(), a === "OPEN") {
|
|
263
|
+
i++;
|
|
264
|
+
const w = u ? Math.ceil((u - Date.now()) / 1e3) : 0;
|
|
265
|
+
throw new E(
|
|
266
|
+
`Circuit breaker is OPEN. Service is unavailable. Retry in ${w}s.`
|
|
267
|
+
);
|
|
268
|
+
}
|
|
269
|
+
try {
|
|
270
|
+
const w = await b();
|
|
271
|
+
return h(), w;
|
|
272
|
+
} catch (w) {
|
|
273
|
+
throw p(w instanceof Error ? w : new Error(String(w))), w;
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
function y() {
|
|
277
|
+
return d(), a;
|
|
278
|
+
}
|
|
279
|
+
function v() {
|
|
280
|
+
return d(), {
|
|
281
|
+
state: a,
|
|
282
|
+
failures: o,
|
|
283
|
+
successes: s,
|
|
284
|
+
rejections: i,
|
|
285
|
+
lastFailureTime: l,
|
|
286
|
+
lastSuccessTime: c
|
|
287
|
+
};
|
|
288
|
+
}
|
|
289
|
+
function A() {
|
|
290
|
+
f().debug(`[CircuitBreaker:${n}] Manual reset → CLOSED`), a = "CLOSED", o = 0, s = 0, i = 0, l = null, c = null, u = null;
|
|
291
|
+
}
|
|
292
|
+
function x() {
|
|
293
|
+
f().warn(`[CircuitBreaker:${n}] Manual trip → OPEN`), a = "OPEN", u = Date.now() + r;
|
|
294
|
+
}
|
|
295
|
+
return {
|
|
296
|
+
execute: m,
|
|
297
|
+
getState: y,
|
|
298
|
+
getStats: v,
|
|
299
|
+
reset: A,
|
|
300
|
+
trip: x
|
|
301
|
+
};
|
|
302
|
+
}
|
|
303
|
+
const Ht = {
|
|
304
|
+
/** Strict: Opens quickly (3 failures), long timeout (60s) */
|
|
305
|
+
STRICT: { failureThreshold: 3, timeout: 6e4 },
|
|
306
|
+
/** Standard: Balanced settings (5 failures, 30s timeout) */
|
|
307
|
+
STANDARD: { failureThreshold: 5, timeout: 3e4 },
|
|
308
|
+
/** Lenient: Tolerates more failures (10 failures, 15s timeout) */
|
|
309
|
+
LENIENT: { failureThreshold: 10, timeout: 15e3 }
|
|
310
|
+
};
|
|
311
|
+
function st(t, e) {
|
|
312
|
+
if (e >= 3)
|
|
313
|
+
return !1;
|
|
314
|
+
const r = t.message.toLowerCase();
|
|
315
|
+
return r.includes("network") || r.includes("timeout") || r.includes("fetch failed") || r.includes("econnrefused") || r.includes("503") || r.includes("502") || r.includes("500") || r.includes("429") ? !0 : (r.includes("400") || r.includes("401") || r.includes("403") || r.includes("404"), !1);
|
|
316
|
+
}
|
|
317
|
+
function it(t, e, r, n, a) {
|
|
318
|
+
const o = e * Math.pow(r, t), s = Math.min(o, n);
|
|
319
|
+
if (a) {
|
|
320
|
+
const i = Math.random() * s;
|
|
321
|
+
return Math.floor(i);
|
|
322
|
+
}
|
|
323
|
+
return Math.floor(s);
|
|
324
|
+
}
|
|
325
|
+
function ct(t) {
|
|
326
|
+
return new Promise((e) => setTimeout(e, t));
|
|
327
|
+
}
|
|
328
|
+
async function C(t, e = {}) {
|
|
329
|
+
const {
|
|
330
|
+
maxRetries: r = 3,
|
|
331
|
+
initialDelayMs: n = 1e3,
|
|
332
|
+
backoffFactor: a = 2,
|
|
333
|
+
maxDelayMs: o = 3e4,
|
|
334
|
+
jitter: s = !0,
|
|
335
|
+
shouldRetry: i = st,
|
|
336
|
+
name: l = "retry"
|
|
337
|
+
} = e;
|
|
338
|
+
let c = null, u = 0;
|
|
339
|
+
for (let d = 0; d <= r; d++)
|
|
340
|
+
try {
|
|
341
|
+
const h = await t();
|
|
342
|
+
return d > 0 && f().debug(
|
|
343
|
+
`[Retry:${l}] Succeeded on attempt ${d + 1}/${r + 1} after ${u}ms`
|
|
344
|
+
), h;
|
|
345
|
+
} catch (h) {
|
|
346
|
+
c = h instanceof Error ? h : new Error(String(h));
|
|
347
|
+
const p = d === r, m = i(c, d);
|
|
348
|
+
if (p || !m)
|
|
349
|
+
throw f().warn(
|
|
350
|
+
`[Retry:${l}] Failed on attempt ${d + 1}/${r + 1}. ${p ? "No more retries." : "Error not retryable."}`
|
|
351
|
+
), c;
|
|
352
|
+
const y = it(d, n, a, o, s);
|
|
353
|
+
u += y, f().warn(
|
|
354
|
+
`[Retry:${l}] Attempt ${d + 1}/${r + 1} failed: ${c.message}. Retrying in ${y}ms...`
|
|
355
|
+
), await ct(y);
|
|
356
|
+
}
|
|
357
|
+
throw c || new Error("Retry failed with no error");
|
|
358
|
+
}
|
|
359
|
+
const P = {
|
|
360
|
+
/** Quick retries for transient errors (3 retries, 1s initial, 2x backoff) */
|
|
361
|
+
QUICK: {
|
|
362
|
+
maxRetries: 3,
|
|
363
|
+
initialDelayMs: 1e3,
|
|
364
|
+
backoffFactor: 2,
|
|
365
|
+
maxDelayMs: 1e4
|
|
366
|
+
},
|
|
367
|
+
/** Standard retries (3 retries, 2s initial, 2x backoff) */
|
|
368
|
+
STANDARD: {
|
|
369
|
+
maxRetries: 3,
|
|
370
|
+
initialDelayMs: 2e3,
|
|
371
|
+
backoffFactor: 2,
|
|
372
|
+
maxDelayMs: 3e4
|
|
373
|
+
},
|
|
374
|
+
/** Aggressive retries for critical operations (5 retries, 500ms initial) */
|
|
375
|
+
AGGRESSIVE: {
|
|
376
|
+
maxRetries: 5,
|
|
377
|
+
initialDelayMs: 500,
|
|
378
|
+
backoffFactor: 1.5,
|
|
379
|
+
maxDelayMs: 15e3
|
|
380
|
+
},
|
|
381
|
+
/** Patient retries for slow backends (5 retries, 5s initial) */
|
|
382
|
+
PATIENT: {
|
|
383
|
+
maxRetries: 5,
|
|
384
|
+
initialDelayMs: 5e3,
|
|
385
|
+
backoffFactor: 2,
|
|
386
|
+
maxDelayMs: 6e4
|
|
387
|
+
}
|
|
388
|
+
};
|
|
389
|
+
class lt {
|
|
390
|
+
stripe = null;
|
|
391
|
+
publicKey;
|
|
392
|
+
routeDiscovery;
|
|
393
|
+
rateLimiter = K(Q.PAYMENT);
|
|
394
|
+
circuitBreaker = te({
|
|
395
|
+
failureThreshold: 5,
|
|
396
|
+
timeout: 1e4,
|
|
397
|
+
// 10 seconds for faster recovery in payment flows
|
|
398
|
+
name: "stripe-manager"
|
|
399
|
+
});
|
|
400
|
+
constructor(e, r) {
|
|
401
|
+
this.publicKey = e, this.routeDiscovery = r;
|
|
402
|
+
}
|
|
403
|
+
/**
|
|
404
|
+
* Initialize Stripe.js library
|
|
405
|
+
*/
|
|
406
|
+
async initialize() {
|
|
407
|
+
if (!this.stripe && (this.stripe = await Je(this.publicKey), !this.stripe))
|
|
408
|
+
throw new Error("Failed to initialize Stripe");
|
|
409
|
+
}
|
|
410
|
+
/**
|
|
411
|
+
* Create a Stripe checkout session
|
|
412
|
+
*/
|
|
413
|
+
async createSession(e) {
|
|
414
|
+
if (!this.rateLimiter.tryConsume())
|
|
415
|
+
throw new Error("Rate limit exceeded for Stripe session creation. Please try again later.");
|
|
416
|
+
try {
|
|
417
|
+
return await this.circuitBreaker.execute(async () => await C(
|
|
418
|
+
async () => {
|
|
419
|
+
const r = await this.routeDiscovery.buildUrl("/paywall/v1/stripe-session");
|
|
420
|
+
f().debug("[StripeManager] Creating session with request:", e), e.couponCode ? f().debug("[StripeManager] Coupon code included:", e.couponCode) : f().debug("[StripeManager] No coupon code in request");
|
|
421
|
+
const n = await S(r, {
|
|
422
|
+
method: "POST",
|
|
423
|
+
headers: {
|
|
424
|
+
"Content-Type": "application/json",
|
|
425
|
+
"Idempotency-Key": N()
|
|
426
|
+
},
|
|
427
|
+
body: JSON.stringify(e)
|
|
428
|
+
});
|
|
429
|
+
if (!n.ok) {
|
|
430
|
+
const a = await T(n, "Failed to create Stripe session");
|
|
431
|
+
throw new Error(a);
|
|
432
|
+
}
|
|
433
|
+
return n.json();
|
|
434
|
+
},
|
|
435
|
+
{ ...P.STANDARD, name: "stripe-create-session" }
|
|
436
|
+
));
|
|
437
|
+
} catch (r) {
|
|
438
|
+
throw r instanceof E ? (f().error("[StripeManager] Circuit breaker is OPEN - Stripe service unavailable"), new Error("Stripe payment service is temporarily unavailable. Please try again in a few moments.")) : r;
|
|
439
|
+
}
|
|
440
|
+
}
|
|
441
|
+
/**
|
|
442
|
+
* Redirect to Stripe checkout
|
|
443
|
+
*/
|
|
444
|
+
async redirectToCheckout(e) {
|
|
445
|
+
if (this.stripe || await this.initialize(), !this.stripe)
|
|
446
|
+
return {
|
|
447
|
+
success: !1,
|
|
448
|
+
error: "Stripe not initialized"
|
|
449
|
+
};
|
|
450
|
+
const r = await this.stripe.redirectToCheckout({ sessionId: e });
|
|
451
|
+
return r.error ? {
|
|
452
|
+
success: !1,
|
|
453
|
+
error: r.error.message
|
|
454
|
+
} : { success: !0 };
|
|
455
|
+
}
|
|
456
|
+
/**
|
|
457
|
+
* Handle complete payment flow: create session and redirect
|
|
458
|
+
*/
|
|
459
|
+
async processPayment(e) {
|
|
460
|
+
try {
|
|
461
|
+
const r = await this.createSession(e);
|
|
462
|
+
return await this.redirectToCheckout(r.sessionId);
|
|
463
|
+
} catch (r) {
|
|
464
|
+
return {
|
|
465
|
+
success: !1,
|
|
466
|
+
error: F(r, "Unknown error")
|
|
467
|
+
};
|
|
468
|
+
}
|
|
469
|
+
}
|
|
470
|
+
/**
|
|
471
|
+
* Create a Stripe cart checkout session for multiple items
|
|
472
|
+
*/
|
|
473
|
+
async processCartCheckout(e) {
|
|
474
|
+
const { items: r, successUrl: n, cancelUrl: a, metadata: o, customerEmail: s, couponCode: i } = e;
|
|
475
|
+
if (!this.rateLimiter.tryConsume())
|
|
476
|
+
return {
|
|
477
|
+
success: !1,
|
|
478
|
+
error: "Rate limit exceeded for cart checkout. Please try again later."
|
|
479
|
+
};
|
|
480
|
+
try {
|
|
481
|
+
const l = await this.circuitBreaker.execute(async () => await C(
|
|
482
|
+
async () => {
|
|
483
|
+
const c = await this.routeDiscovery.buildUrl("/paywall/v1/cart/checkout"), u = {
|
|
484
|
+
items: r,
|
|
485
|
+
successUrl: n,
|
|
486
|
+
cancelUrl: a,
|
|
487
|
+
metadata: o,
|
|
488
|
+
customerEmail: s,
|
|
489
|
+
couponCode: i
|
|
490
|
+
}, d = await S(c, {
|
|
491
|
+
method: "POST",
|
|
492
|
+
headers: {
|
|
493
|
+
"Content-Type": "application/json",
|
|
494
|
+
"Idempotency-Key": N()
|
|
495
|
+
},
|
|
496
|
+
body: JSON.stringify(u)
|
|
497
|
+
});
|
|
498
|
+
if (!d.ok) {
|
|
499
|
+
const h = await T(d, "Failed to create cart checkout session");
|
|
500
|
+
throw new Error(h);
|
|
501
|
+
}
|
|
502
|
+
return await d.json();
|
|
503
|
+
},
|
|
504
|
+
{ ...P.STANDARD, name: "stripe-cart-checkout" }
|
|
505
|
+
));
|
|
506
|
+
return await this.redirectToCheckout(l.sessionId);
|
|
507
|
+
} catch (l) {
|
|
508
|
+
return l instanceof E ? {
|
|
509
|
+
success: !1,
|
|
510
|
+
error: "Stripe payment service is temporarily unavailable. Please try again in a few moments."
|
|
511
|
+
} : {
|
|
512
|
+
success: !1,
|
|
513
|
+
error: F(l, "Cart checkout failed")
|
|
514
|
+
};
|
|
515
|
+
}
|
|
516
|
+
}
|
|
517
|
+
}
|
|
518
|
+
const Ee = "3.7.8", ut = Ee, R = typeof Buffer == "function", se = typeof TextDecoder == "function" ? new TextDecoder() : void 0, ie = typeof TextEncoder == "function" ? new TextEncoder() : void 0, dt = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=", B = Array.prototype.slice.call(dt), j = ((t) => {
|
|
519
|
+
let e = {};
|
|
520
|
+
return t.forEach((r, n) => e[r] = n), e;
|
|
521
|
+
})(B), ft = /^(?:[A-Za-z\d+\/]{4})*?(?:[A-Za-z\d+\/]{2}(?:==)?|[A-Za-z\d+\/]{3}=?)?$/, g = String.fromCharCode.bind(String), ce = typeof Uint8Array.from == "function" ? Uint8Array.from.bind(Uint8Array) : (t) => new Uint8Array(Array.prototype.slice.call(t, 0)), xe = (t) => t.replace(/=/g, "").replace(/[+\/]/g, (e) => e == "+" ? "-" : "_"), Ce = (t) => t.replace(/[^A-Za-z0-9\+\/]/g, ""), Pe = (t) => {
|
|
522
|
+
let e, r, n, a, o = "";
|
|
523
|
+
const s = t.length % 3;
|
|
524
|
+
for (let i = 0; i < t.length; ) {
|
|
525
|
+
if ((r = t.charCodeAt(i++)) > 255 || (n = t.charCodeAt(i++)) > 255 || (a = t.charCodeAt(i++)) > 255)
|
|
526
|
+
throw new TypeError("invalid character found");
|
|
527
|
+
e = r << 16 | n << 8 | a, o += B[e >> 18 & 63] + B[e >> 12 & 63] + B[e >> 6 & 63] + B[e & 63];
|
|
528
|
+
}
|
|
529
|
+
return s ? o.slice(0, s - 3) + "===".substring(s) : o;
|
|
530
|
+
}, re = typeof btoa == "function" ? (t) => btoa(t) : R ? (t) => Buffer.from(t, "binary").toString("base64") : Pe, J = R ? (t) => Buffer.from(t).toString("base64") : (t) => {
|
|
531
|
+
let r = [];
|
|
532
|
+
for (let n = 0, a = t.length; n < a; n += 4096)
|
|
533
|
+
r.push(g.apply(null, t.subarray(n, n + 4096)));
|
|
534
|
+
return re(r.join(""));
|
|
535
|
+
}, W = (t, e = !1) => e ? xe(J(t)) : J(t), ht = (t) => {
|
|
536
|
+
if (t.length < 2) {
|
|
537
|
+
var e = t.charCodeAt(0);
|
|
538
|
+
return e < 128 ? t : e < 2048 ? g(192 | e >>> 6) + g(128 | e & 63) : g(224 | e >>> 12 & 15) + g(128 | e >>> 6 & 63) + g(128 | e & 63);
|
|
539
|
+
} else {
|
|
540
|
+
var e = 65536 + (t.charCodeAt(0) - 55296) * 1024 + (t.charCodeAt(1) - 56320);
|
|
541
|
+
return g(240 | e >>> 18 & 7) + g(128 | e >>> 12 & 63) + g(128 | e >>> 6 & 63) + g(128 | e & 63);
|
|
542
|
+
}
|
|
543
|
+
}, mt = /[\uD800-\uDBFF][\uDC00-\uDFFFF]|[^\x00-\x7F]/g, Se = (t) => t.replace(mt, ht), le = R ? (t) => Buffer.from(t, "utf8").toString("base64") : ie ? (t) => J(ie.encode(t)) : (t) => re(Se(t)), k = (t, e = !1) => e ? xe(le(t)) : le(t), ue = (t) => k(t, !0), pt = /[\xC0-\xDF][\x80-\xBF]|[\xE0-\xEF][\x80-\xBF]{2}|[\xF0-\xF7][\x80-\xBF]{3}/g, yt = (t) => {
|
|
544
|
+
switch (t.length) {
|
|
545
|
+
case 4:
|
|
546
|
+
var e = (7 & t.charCodeAt(0)) << 18 | (63 & t.charCodeAt(1)) << 12 | (63 & t.charCodeAt(2)) << 6 | 63 & t.charCodeAt(3), r = e - 65536;
|
|
547
|
+
return g((r >>> 10) + 55296) + g((r & 1023) + 56320);
|
|
548
|
+
case 3:
|
|
549
|
+
return g((15 & t.charCodeAt(0)) << 12 | (63 & t.charCodeAt(1)) << 6 | 63 & t.charCodeAt(2));
|
|
550
|
+
default:
|
|
551
|
+
return g((31 & t.charCodeAt(0)) << 6 | 63 & t.charCodeAt(1));
|
|
552
|
+
}
|
|
553
|
+
}, Ae = (t) => t.replace(pt, yt), Te = (t) => {
|
|
554
|
+
if (t = t.replace(/\s+/g, ""), !ft.test(t))
|
|
555
|
+
throw new TypeError("malformed base64.");
|
|
556
|
+
t += "==".slice(2 - (t.length & 3));
|
|
557
|
+
let e, r, n, a = [];
|
|
558
|
+
for (let o = 0; o < t.length; )
|
|
559
|
+
e = j[t.charAt(o++)] << 18 | j[t.charAt(o++)] << 12 | (r = j[t.charAt(o++)]) << 6 | (n = j[t.charAt(o++)]), r === 64 ? a.push(g(e >> 16 & 255)) : n === 64 ? a.push(g(e >> 16 & 255, e >> 8 & 255)) : a.push(g(e >> 16 & 255, e >> 8 & 255, e & 255));
|
|
560
|
+
return a.join("");
|
|
561
|
+
}, ne = typeof atob == "function" ? (t) => atob(Ce(t)) : R ? (t) => Buffer.from(t, "base64").toString("binary") : Te, ke = R ? (t) => ce(Buffer.from(t, "base64")) : (t) => ce(ne(t).split("").map((e) => e.charCodeAt(0))), Re = (t) => ke(Me(t)), wt = R ? (t) => Buffer.from(t, "base64").toString("utf8") : se ? (t) => se.decode(ke(t)) : (t) => Ae(ne(t)), Me = (t) => Ce(t.replace(/[-_]/g, (e) => e == "-" ? "+" : "/")), Z = (t) => wt(Me(t)), gt = (t) => {
|
|
562
|
+
if (typeof t != "string")
|
|
563
|
+
return !1;
|
|
564
|
+
const e = t.replace(/\s+/g, "").replace(/={0,2}$/, "");
|
|
565
|
+
return !/[^\s0-9a-zA-Z\+/]/.test(e) || !/[^\s0-9a-zA-Z\-_]/.test(e);
|
|
566
|
+
}, Ue = (t) => ({
|
|
567
|
+
value: t,
|
|
568
|
+
enumerable: !1,
|
|
569
|
+
writable: !0,
|
|
570
|
+
configurable: !0
|
|
571
|
+
}), Oe = function() {
|
|
572
|
+
const t = (e, r) => Object.defineProperty(String.prototype, e, Ue(r));
|
|
573
|
+
t("fromBase64", function() {
|
|
574
|
+
return Z(this);
|
|
575
|
+
}), t("toBase64", function(e) {
|
|
576
|
+
return k(this, e);
|
|
577
|
+
}), t("toBase64URI", function() {
|
|
578
|
+
return k(this, !0);
|
|
579
|
+
}), t("toBase64URL", function() {
|
|
580
|
+
return k(this, !0);
|
|
581
|
+
}), t("toUint8Array", function() {
|
|
582
|
+
return Re(this);
|
|
583
|
+
});
|
|
584
|
+
}, De = function() {
|
|
585
|
+
const t = (e, r) => Object.defineProperty(Uint8Array.prototype, e, Ue(r));
|
|
586
|
+
t("toBase64", function(e) {
|
|
587
|
+
return W(this, e);
|
|
588
|
+
}), t("toBase64URI", function() {
|
|
589
|
+
return W(this, !0);
|
|
590
|
+
}), t("toBase64URL", function() {
|
|
591
|
+
return W(this, !0);
|
|
592
|
+
});
|
|
593
|
+
}, bt = () => {
|
|
594
|
+
Oe(), De();
|
|
595
|
+
}, I = {
|
|
596
|
+
version: Ee,
|
|
597
|
+
VERSION: ut,
|
|
598
|
+
atob: ne,
|
|
599
|
+
atobPolyfill: Te,
|
|
600
|
+
btoa: re,
|
|
601
|
+
btoaPolyfill: Pe,
|
|
602
|
+
fromBase64: Z,
|
|
603
|
+
toBase64: k,
|
|
604
|
+
encode: k,
|
|
605
|
+
encodeURI: ue,
|
|
606
|
+
encodeURL: ue,
|
|
607
|
+
utob: Se,
|
|
608
|
+
btou: Ae,
|
|
609
|
+
decode: Z,
|
|
610
|
+
isValid: gt,
|
|
611
|
+
fromUint8Array: W,
|
|
612
|
+
toUint8Array: Re,
|
|
613
|
+
extendString: Oe,
|
|
614
|
+
extendUint8Array: De,
|
|
615
|
+
extendBuiltins: bt
|
|
616
|
+
};
|
|
617
|
+
class vt {
|
|
618
|
+
routeDiscovery;
|
|
619
|
+
quoteRateLimiter = K(Q.QUOTE);
|
|
620
|
+
verifyRateLimiter = K(Q.PAYMENT);
|
|
621
|
+
circuitBreaker = te({
|
|
622
|
+
failureThreshold: 5,
|
|
623
|
+
timeout: 1e4,
|
|
624
|
+
// 10 seconds for faster recovery in payment flows
|
|
625
|
+
name: "x402-manager"
|
|
626
|
+
});
|
|
627
|
+
constructor(e) {
|
|
628
|
+
this.routeDiscovery = e;
|
|
629
|
+
}
|
|
630
|
+
/**
|
|
631
|
+
* Request a protected resource and get x402 requirement
|
|
632
|
+
* SECURITY: Resource ID and coupon codes sent in request body to prevent leakage
|
|
633
|
+
* Prevents exposure of product IDs, SKUs, and business-sensitive identifiers in logs
|
|
634
|
+
*/
|
|
635
|
+
async requestQuote(e) {
|
|
636
|
+
const { resource: r, couponCode: n } = e;
|
|
637
|
+
if (!this.quoteRateLimiter.tryConsume())
|
|
638
|
+
throw new Error("Rate limit exceeded for quote requests. Please try again later.");
|
|
639
|
+
try {
|
|
640
|
+
return await this.circuitBreaker.execute(async () => await C(
|
|
641
|
+
async () => {
|
|
642
|
+
const a = "/paywall/v1/quote";
|
|
643
|
+
f().debug(
|
|
644
|
+
"[X402Manager] Requesting quote",
|
|
645
|
+
n ? "with coupon" : "without coupon"
|
|
646
|
+
);
|
|
647
|
+
const o = await this.routeDiscovery.buildUrl(a), s = await S(o, {
|
|
648
|
+
method: "POST",
|
|
649
|
+
headers: {
|
|
650
|
+
"Content-Type": "application/json"
|
|
651
|
+
},
|
|
652
|
+
body: JSON.stringify({
|
|
653
|
+
resource: r,
|
|
654
|
+
couponCode: n || null
|
|
655
|
+
})
|
|
656
|
+
});
|
|
657
|
+
if (s.status !== 402)
|
|
658
|
+
throw new Error(`Expected 402 status, got ${s.status}`);
|
|
659
|
+
const i = await s.json();
|
|
660
|
+
if (!i.accepts || i.accepts.length === 0)
|
|
661
|
+
throw new Error("Invalid x402 response: missing accepts array");
|
|
662
|
+
return i.accepts[0];
|
|
663
|
+
},
|
|
664
|
+
{ ...P.QUICK, name: "x402-quote" }
|
|
665
|
+
));
|
|
666
|
+
} catch (a) {
|
|
667
|
+
throw a instanceof E ? (f().error("[X402Manager] Circuit breaker is OPEN - x402 service unavailable"), new Error("Payment service is temporarily unavailable. Please try again in a few moments.")) : a;
|
|
668
|
+
}
|
|
669
|
+
}
|
|
670
|
+
/**
|
|
671
|
+
* Request a cart quote for multiple items
|
|
672
|
+
*/
|
|
673
|
+
async requestCartQuote(e) {
|
|
674
|
+
const { items: r, metadata: n, couponCode: a } = e;
|
|
675
|
+
if (!this.quoteRateLimiter.tryConsume())
|
|
676
|
+
throw new Error("Rate limit exceeded for cart quote requests. Please try again later.");
|
|
677
|
+
try {
|
|
678
|
+
return await this.circuitBreaker.execute(async () => await C(
|
|
679
|
+
async () => {
|
|
680
|
+
const o = await this.routeDiscovery.buildUrl("/paywall/v1/cart/quote"), s = {
|
|
681
|
+
items: r,
|
|
682
|
+
metadata: n,
|
|
683
|
+
couponCode: a
|
|
684
|
+
}, i = await S(o, {
|
|
685
|
+
method: "POST",
|
|
686
|
+
headers: {
|
|
687
|
+
"Content-Type": "application/json",
|
|
688
|
+
"Idempotency-Key": N()
|
|
689
|
+
},
|
|
690
|
+
body: JSON.stringify(s)
|
|
691
|
+
});
|
|
692
|
+
if (i.status !== 402 && !i.ok) {
|
|
693
|
+
const l = await T(i, "Failed to get cart quote");
|
|
694
|
+
throw new Error(l);
|
|
695
|
+
}
|
|
696
|
+
return i.json();
|
|
697
|
+
},
|
|
698
|
+
{ ...P.QUICK, name: "x402-cart-quote" }
|
|
699
|
+
));
|
|
700
|
+
} catch (o) {
|
|
701
|
+
throw o instanceof E ? (f().error("[X402Manager] Circuit breaker is OPEN - cart quote service unavailable"), new Error("Payment service is temporarily unavailable. Please try again in a few moments.")) : o;
|
|
702
|
+
}
|
|
703
|
+
}
|
|
704
|
+
/**
|
|
705
|
+
* Build X-PAYMENT header from payment payload (base64 encoded)
|
|
706
|
+
*/
|
|
707
|
+
buildPaymentHeader(e) {
|
|
708
|
+
const r = JSON.stringify(e);
|
|
709
|
+
return I.encode(r);
|
|
710
|
+
}
|
|
711
|
+
/**
|
|
712
|
+
* Parse X-PAYMENT-RESPONSE header (base64 encoded settlement response)
|
|
713
|
+
*/
|
|
714
|
+
parseSettlementResponse(e) {
|
|
715
|
+
const r = e.headers.get("X-PAYMENT-RESPONSE");
|
|
716
|
+
if (!r)
|
|
717
|
+
return null;
|
|
718
|
+
try {
|
|
719
|
+
const n = I.decode(r), a = JSON.parse(n);
|
|
720
|
+
return typeof a.success != "boolean" ? (f().error("Invalid settlement response: missing success field"), null) : a;
|
|
721
|
+
} catch (n) {
|
|
722
|
+
return f().error("Failed to parse settlement response:", n), null;
|
|
723
|
+
}
|
|
724
|
+
}
|
|
725
|
+
/**
|
|
726
|
+
* Retry request with payment proof
|
|
727
|
+
* SECURITY: Coupon and metadata sent in X-PAYMENT header payload, NOT query strings
|
|
728
|
+
*/
|
|
729
|
+
async submitPayment(e) {
|
|
730
|
+
const {
|
|
731
|
+
resource: r,
|
|
732
|
+
payload: n,
|
|
733
|
+
couponCode: a,
|
|
734
|
+
metadata: o,
|
|
735
|
+
resourceType: s = "regular"
|
|
736
|
+
} = e;
|
|
737
|
+
if (!this.verifyRateLimiter.tryConsume())
|
|
738
|
+
return {
|
|
739
|
+
success: !1,
|
|
740
|
+
error: "Rate limit exceeded for payment verification. Please try again later."
|
|
741
|
+
};
|
|
742
|
+
try {
|
|
743
|
+
return await this.circuitBreaker.execute(async () => await C(
|
|
744
|
+
async () => {
|
|
745
|
+
const l = {
|
|
746
|
+
...n,
|
|
747
|
+
payload: {
|
|
748
|
+
...n.payload,
|
|
749
|
+
resource: r,
|
|
750
|
+
resourceType: s,
|
|
751
|
+
metadata: {
|
|
752
|
+
...n.payload.metadata || {},
|
|
753
|
+
// Preserve existing metadata
|
|
754
|
+
...o || {},
|
|
755
|
+
// Layer in new metadata
|
|
756
|
+
...a ? { couponCode: a } : {}
|
|
757
|
+
// Add coupon if present
|
|
758
|
+
}
|
|
759
|
+
}
|
|
760
|
+
}, c = this.buildPaymentHeader(l), u = "/paywall/v1/verify";
|
|
761
|
+
f().debug("[X402Manager] Submitting payment", {
|
|
762
|
+
resourceType: s,
|
|
763
|
+
hasCoupon: !!a,
|
|
764
|
+
hasMetadata: !!o
|
|
765
|
+
});
|
|
766
|
+
const d = await this.routeDiscovery.buildUrl(u), h = await S(d, {
|
|
767
|
+
method: "POST",
|
|
768
|
+
headers: {
|
|
769
|
+
"Content-Type": "application/json",
|
|
770
|
+
"X-PAYMENT": c,
|
|
771
|
+
"Idempotency-Key": N()
|
|
772
|
+
}
|
|
773
|
+
});
|
|
774
|
+
if (h.ok) {
|
|
775
|
+
const { settlement: m, transactionId: y } = await this.handlePaymentVerification(
|
|
776
|
+
h,
|
|
777
|
+
n.payload.signature
|
|
778
|
+
);
|
|
779
|
+
return {
|
|
780
|
+
success: !0,
|
|
781
|
+
transactionId: y,
|
|
782
|
+
settlement: m || void 0
|
|
783
|
+
};
|
|
784
|
+
}
|
|
785
|
+
return {
|
|
786
|
+
success: !1,
|
|
787
|
+
error: await T(h, "Payment verification failed", !0)
|
|
788
|
+
};
|
|
789
|
+
},
|
|
790
|
+
{ ...P.STANDARD, name: "x402-verify" }
|
|
791
|
+
));
|
|
792
|
+
} catch (i) {
|
|
793
|
+
return i instanceof E ? {
|
|
794
|
+
success: !1,
|
|
795
|
+
error: "Payment verification service is temporarily unavailable. Please try again in a few moments."
|
|
796
|
+
} : {
|
|
797
|
+
success: !1,
|
|
798
|
+
error: F(i, "Unknown error")
|
|
799
|
+
};
|
|
800
|
+
}
|
|
801
|
+
}
|
|
802
|
+
/**
|
|
803
|
+
* Build a complete gasless transaction on the backend
|
|
804
|
+
* Returns an unsigned transaction with all instructions (compute budget, transfer, memo)
|
|
805
|
+
*/
|
|
806
|
+
async buildGaslessTransaction(e) {
|
|
807
|
+
const { resourceId: r, userWallet: n, feePayer: a, couponCode: o } = e;
|
|
808
|
+
if (!this.quoteRateLimiter.tryConsume())
|
|
809
|
+
throw new Error("Rate limit exceeded for gasless transaction requests. Please try again later.");
|
|
810
|
+
try {
|
|
811
|
+
return await this.circuitBreaker.execute(async () => await C(
|
|
812
|
+
async () => {
|
|
813
|
+
const s = await this.routeDiscovery.buildUrl(
|
|
814
|
+
"/paywall/v1/gasless-transaction"
|
|
815
|
+
), i = await S(s, {
|
|
816
|
+
method: "POST",
|
|
817
|
+
headers: {
|
|
818
|
+
"Content-Type": "application/json"
|
|
819
|
+
},
|
|
820
|
+
body: JSON.stringify({
|
|
821
|
+
resourceId: r,
|
|
822
|
+
userWallet: n,
|
|
823
|
+
feePayer: a,
|
|
824
|
+
couponCode: o
|
|
825
|
+
})
|
|
826
|
+
});
|
|
827
|
+
if (!i.ok) {
|
|
828
|
+
const l = await T(i, "Failed to build gasless transaction");
|
|
829
|
+
throw new Error(l);
|
|
830
|
+
}
|
|
831
|
+
return i.json();
|
|
832
|
+
},
|
|
833
|
+
{ ...P.QUICK, name: "x402-gasless-build" }
|
|
834
|
+
));
|
|
835
|
+
} catch (s) {
|
|
836
|
+
throw s instanceof E ? (f().error("[X402Manager] Circuit breaker is OPEN - gasless transaction service unavailable"), new Error("Gasless transaction service is temporarily unavailable. Please try again in a few moments.")) : s;
|
|
837
|
+
}
|
|
838
|
+
}
|
|
839
|
+
/**
|
|
840
|
+
* Submit gasless partial transaction for co-signing
|
|
841
|
+
* Sends the partially-signed transaction in X-Payment header for backend co-signing
|
|
842
|
+
* SECURITY: Coupon and metadata sent in X-PAYMENT header payload, NOT query strings
|
|
843
|
+
*/
|
|
844
|
+
async submitGaslessTransaction(e) {
|
|
845
|
+
const {
|
|
846
|
+
resource: r,
|
|
847
|
+
partialTx: n,
|
|
848
|
+
couponCode: a,
|
|
849
|
+
metadata: o,
|
|
850
|
+
resourceType: s = "regular",
|
|
851
|
+
requirement: i
|
|
852
|
+
} = e;
|
|
853
|
+
if (!this.verifyRateLimiter.tryConsume())
|
|
854
|
+
return {
|
|
855
|
+
success: !1,
|
|
856
|
+
error: "Rate limit exceeded for gasless transaction verification. Please try again later."
|
|
857
|
+
};
|
|
858
|
+
try {
|
|
859
|
+
return await this.circuitBreaker.execute(async () => await C(
|
|
860
|
+
async () => {
|
|
861
|
+
const c = {
|
|
862
|
+
x402Version: 0,
|
|
863
|
+
scheme: i?.scheme || "solana-spl-transfer",
|
|
864
|
+
network: i?.network || "mainnet-beta",
|
|
865
|
+
payload: {
|
|
866
|
+
signature: "",
|
|
867
|
+
// Placeholder - backend will finalize after co-signing
|
|
868
|
+
transaction: n,
|
|
869
|
+
feePayer: i?.extra?.feePayer || "",
|
|
870
|
+
resource: r,
|
|
871
|
+
resourceType: s,
|
|
872
|
+
metadata: {
|
|
873
|
+
...o || {},
|
|
874
|
+
...a ? { couponCode: a } : {}
|
|
875
|
+
}
|
|
876
|
+
}
|
|
877
|
+
}, u = this.buildPaymentHeader(c), h = await this.routeDiscovery.buildUrl("/paywall/v1/verify"), p = await S(h, {
|
|
878
|
+
method: "POST",
|
|
879
|
+
headers: {
|
|
880
|
+
"Content-Type": "application/json",
|
|
881
|
+
"X-PAYMENT": u,
|
|
882
|
+
"Idempotency-Key": N()
|
|
883
|
+
}
|
|
884
|
+
});
|
|
885
|
+
if (p.ok) {
|
|
886
|
+
const { settlement: y, transactionId: v } = await this.handlePaymentVerification(
|
|
887
|
+
p,
|
|
888
|
+
"gasless-tx"
|
|
889
|
+
);
|
|
890
|
+
return {
|
|
891
|
+
success: !0,
|
|
892
|
+
transactionId: v,
|
|
893
|
+
settlement: y || void 0
|
|
894
|
+
};
|
|
895
|
+
}
|
|
896
|
+
return {
|
|
897
|
+
success: !1,
|
|
898
|
+
error: await T(p, "Gasless transaction failed", !0)
|
|
899
|
+
};
|
|
900
|
+
},
|
|
901
|
+
{ ...P.STANDARD, name: "x402-gasless-verify" }
|
|
902
|
+
));
|
|
903
|
+
} catch (l) {
|
|
904
|
+
return l instanceof E ? {
|
|
905
|
+
success: !1,
|
|
906
|
+
error: "Gasless transaction verification service is temporarily unavailable. Please try again in a few moments."
|
|
907
|
+
} : {
|
|
908
|
+
success: !1,
|
|
909
|
+
error: F(l, "Unknown error")
|
|
910
|
+
};
|
|
911
|
+
}
|
|
912
|
+
}
|
|
913
|
+
/**
|
|
914
|
+
* Handle payment verification response (shared logic for both submitPayment and submitGaslessTransaction)
|
|
915
|
+
* Parses settlement header and extracts transaction ID from response body
|
|
916
|
+
* @param response - HTTP response from payment verification endpoint
|
|
917
|
+
* @param defaultTxId - Fallback transaction ID if JSON parsing fails
|
|
918
|
+
* @returns Settlement data and transaction ID
|
|
919
|
+
*/
|
|
920
|
+
async handlePaymentVerification(e, r) {
|
|
921
|
+
const n = this.parseSettlementResponse(e), a = e.headers.get("Content-Type") || "";
|
|
922
|
+
let o = r;
|
|
923
|
+
if (a.includes("application/json"))
|
|
924
|
+
try {
|
|
925
|
+
o = (await e.json()).signature || r;
|
|
926
|
+
} catch (s) {
|
|
927
|
+
f().warn("Failed to parse JSON response body:", s);
|
|
928
|
+
}
|
|
929
|
+
return { settlement: n, transactionId: o };
|
|
930
|
+
}
|
|
931
|
+
/**
|
|
932
|
+
* Validate x402 requirement structure
|
|
933
|
+
*/
|
|
934
|
+
validateRequirement(e) {
|
|
935
|
+
return !!(e.scheme && e.network && e.maxAmountRequired && e.resource && e.payTo && e.asset && e.maxTimeoutSeconds > 0);
|
|
936
|
+
}
|
|
937
|
+
}
|
|
938
|
+
function Et(t) {
|
|
939
|
+
if (t.length >= 255)
|
|
940
|
+
throw new TypeError("Alphabet too long");
|
|
941
|
+
const e = new Uint8Array(256);
|
|
942
|
+
for (let c = 0; c < e.length; c++)
|
|
943
|
+
e[c] = 255;
|
|
944
|
+
for (let c = 0; c < t.length; c++) {
|
|
945
|
+
const u = t.charAt(c), d = u.charCodeAt(0);
|
|
946
|
+
if (e[d] !== 255)
|
|
947
|
+
throw new TypeError(u + " is ambiguous");
|
|
948
|
+
e[d] = c;
|
|
949
|
+
}
|
|
950
|
+
const r = t.length, n = t.charAt(0), a = Math.log(r) / Math.log(256), o = Math.log(256) / Math.log(r);
|
|
951
|
+
function s(c) {
|
|
952
|
+
if (c instanceof Uint8Array || (ArrayBuffer.isView(c) ? c = new Uint8Array(c.buffer, c.byteOffset, c.byteLength) : Array.isArray(c) && (c = Uint8Array.from(c))), !(c instanceof Uint8Array))
|
|
953
|
+
throw new TypeError("Expected Uint8Array");
|
|
954
|
+
if (c.length === 0)
|
|
955
|
+
return "";
|
|
956
|
+
let u = 0, d = 0, h = 0;
|
|
957
|
+
const p = c.length;
|
|
958
|
+
for (; h !== p && c[h] === 0; )
|
|
959
|
+
h++, u++;
|
|
960
|
+
const m = (p - h) * o + 1 >>> 0, y = new Uint8Array(m);
|
|
961
|
+
for (; h !== p; ) {
|
|
962
|
+
let x = c[h], b = 0;
|
|
963
|
+
for (let w = m - 1; (x !== 0 || b < d) && w !== -1; w--, b++)
|
|
964
|
+
x += 256 * y[w] >>> 0, y[w] = x % r >>> 0, x = x / r >>> 0;
|
|
965
|
+
if (x !== 0)
|
|
966
|
+
throw new Error("Non-zero carry");
|
|
967
|
+
d = b, h++;
|
|
968
|
+
}
|
|
969
|
+
let v = m - d;
|
|
970
|
+
for (; v !== m && y[v] === 0; )
|
|
971
|
+
v++;
|
|
972
|
+
let A = n.repeat(u);
|
|
973
|
+
for (; v < m; ++v)
|
|
974
|
+
A += t.charAt(y[v]);
|
|
975
|
+
return A;
|
|
976
|
+
}
|
|
977
|
+
function i(c) {
|
|
978
|
+
if (typeof c != "string")
|
|
979
|
+
throw new TypeError("Expected String");
|
|
980
|
+
if (c.length === 0)
|
|
981
|
+
return new Uint8Array();
|
|
982
|
+
let u = 0, d = 0, h = 0;
|
|
983
|
+
for (; c[u] === n; )
|
|
984
|
+
d++, u++;
|
|
985
|
+
const p = (c.length - u) * a + 1 >>> 0, m = new Uint8Array(p);
|
|
986
|
+
for (; u < c.length; ) {
|
|
987
|
+
const x = c.charCodeAt(u);
|
|
988
|
+
if (x > 255)
|
|
989
|
+
return;
|
|
990
|
+
let b = e[x];
|
|
991
|
+
if (b === 255)
|
|
992
|
+
return;
|
|
993
|
+
let w = 0;
|
|
994
|
+
for (let L = p - 1; (b !== 0 || w < h) && L !== -1; L--, w++)
|
|
995
|
+
b += r * m[L] >>> 0, m[L] = b % 256 >>> 0, b = b / 256 >>> 0;
|
|
996
|
+
if (b !== 0)
|
|
997
|
+
throw new Error("Non-zero carry");
|
|
998
|
+
h = w, u++;
|
|
999
|
+
}
|
|
1000
|
+
let y = p - h;
|
|
1001
|
+
for (; y !== p && m[y] === 0; )
|
|
1002
|
+
y++;
|
|
1003
|
+
const v = new Uint8Array(d + (p - y));
|
|
1004
|
+
let A = d;
|
|
1005
|
+
for (; y !== p; )
|
|
1006
|
+
v[A++] = m[y++];
|
|
1007
|
+
return v;
|
|
1008
|
+
}
|
|
1009
|
+
function l(c) {
|
|
1010
|
+
const u = i(c);
|
|
1011
|
+
if (u)
|
|
1012
|
+
return u;
|
|
1013
|
+
throw new Error("Non-base" + r + " character");
|
|
1014
|
+
}
|
|
1015
|
+
return {
|
|
1016
|
+
encode: s,
|
|
1017
|
+
decodeUnsafe: i,
|
|
1018
|
+
decode: l
|
|
1019
|
+
};
|
|
1020
|
+
}
|
|
1021
|
+
var xt = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
|
|
1022
|
+
const de = Et(xt), ee = {
|
|
1023
|
+
CASHx9KJUStyftLFWGvEVf59SGeG9sh5FfcnZMVPCASH: "CASH",
|
|
1024
|
+
EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v: "USDC",
|
|
1025
|
+
Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB: "USDT",
|
|
1026
|
+
"2b1kV6DkPAnxd5ixfnxCpjxmKwqjjaYmCZfHsFu24GXo": "PYUSD"
|
|
1027
|
+
};
|
|
1028
|
+
function Ct(t) {
|
|
1029
|
+
return t in ee;
|
|
1030
|
+
}
|
|
1031
|
+
function Be(t, e = "token mint", r = !1) {
|
|
1032
|
+
if (!t || t.trim().length === 0)
|
|
1033
|
+
return {
|
|
1034
|
+
isValid: !0,
|
|
1035
|
+
isKnownStablecoin: !1
|
|
1036
|
+
};
|
|
1037
|
+
const n = t.trim();
|
|
1038
|
+
if (Ct(n))
|
|
1039
|
+
return {
|
|
1040
|
+
isValid: !0,
|
|
1041
|
+
isKnownStablecoin: !0,
|
|
1042
|
+
symbol: ee[n]
|
|
1043
|
+
};
|
|
1044
|
+
const a = Object.entries(ee).map(([o, s]) => ` ${s}: ${o}`).join(`
|
|
1045
|
+
`);
|
|
1046
|
+
return r ? {
|
|
1047
|
+
isValid: !0,
|
|
1048
|
+
// Allow but warn
|
|
1049
|
+
isKnownStablecoin: !1,
|
|
1050
|
+
warning: [
|
|
1051
|
+
`Warning: Unrecognized token mint address in ${e}`,
|
|
1052
|
+
` Provided: ${n}`,
|
|
1053
|
+
"",
|
|
1054
|
+
"This token mint does not match any known stablecoin addresses.",
|
|
1055
|
+
"You have set dangerouslyAllowUnknownMint=true, so this will proceed.",
|
|
1056
|
+
"If this is a typo, payments will be sent to the wrong token and funds will be PERMANENTLY LOST.",
|
|
1057
|
+
"",
|
|
1058
|
+
"Known stablecoin mints (mainnet-beta):",
|
|
1059
|
+
a,
|
|
1060
|
+
"",
|
|
1061
|
+
"Double-check your token mint address before deploying to production."
|
|
1062
|
+
].join(`
|
|
1063
|
+
`)
|
|
1064
|
+
} : {
|
|
1065
|
+
isValid: !1,
|
|
1066
|
+
isKnownStablecoin: !1,
|
|
1067
|
+
error: [
|
|
1068
|
+
`SAFETY ERROR: Unrecognized token mint address in ${e}`,
|
|
1069
|
+
` Provided: ${n}`,
|
|
1070
|
+
"",
|
|
1071
|
+
"This token mint does not match any known stablecoin addresses.",
|
|
1072
|
+
"Using an unknown token mint can result in PERMANENT LOSS OF FUNDS if it's a typo.",
|
|
1073
|
+
"",
|
|
1074
|
+
"Known stablecoin mints (mainnet-beta):",
|
|
1075
|
+
a,
|
|
1076
|
+
"",
|
|
1077
|
+
"If you are CERTAIN this is the correct mint address (custom token, testnet, or new stablecoin),",
|
|
1078
|
+
"set dangerouslyAllowUnknownMint={true} in your CedrosProvider config:",
|
|
1079
|
+
"",
|
|
1080
|
+
" <CedrosProvider",
|
|
1081
|
+
" config={{",
|
|
1082
|
+
" ...",
|
|
1083
|
+
' tokenMint: "' + n + '",',
|
|
1084
|
+
" dangerouslyAllowUnknownMint: true, // ⚠️ I have verified this mint address",
|
|
1085
|
+
" }}",
|
|
1086
|
+
" />",
|
|
1087
|
+
"",
|
|
1088
|
+
"⚠️ WARNING: Only enable dangerouslyAllowUnknownMint if you have TRIPLE-CHECKED the mint address."
|
|
1089
|
+
].join(`
|
|
1090
|
+
`)
|
|
1091
|
+
};
|
|
1092
|
+
}
|
|
1093
|
+
function Pt(t, e = "unknown", r = !1) {
|
|
1094
|
+
return Be(t, `X402Requirement (resource: ${e})`, r);
|
|
1095
|
+
}
|
|
1096
|
+
class St {
|
|
1097
|
+
connection;
|
|
1098
|
+
cluster;
|
|
1099
|
+
endpoint;
|
|
1100
|
+
allowUnknownMint;
|
|
1101
|
+
rpcRateLimiter = K({
|
|
1102
|
+
maxRequests: 50,
|
|
1103
|
+
windowMs: 6e4
|
|
1104
|
+
// 50 requests per minute for RPC calls
|
|
1105
|
+
});
|
|
1106
|
+
rpcCircuitBreaker = te({
|
|
1107
|
+
failureThreshold: 5,
|
|
1108
|
+
timeout: 1e4,
|
|
1109
|
+
// 10 seconds for faster recovery in payment flows
|
|
1110
|
+
name: "solana-rpc"
|
|
1111
|
+
});
|
|
1112
|
+
constructor(e = "mainnet-beta", r, n = !1) {
|
|
1113
|
+
this.cluster = e, this.endpoint = r, this.allowUnknownMint = n, this.connection = this.createConnection();
|
|
1114
|
+
}
|
|
1115
|
+
/**
|
|
1116
|
+
* Create Solana RPC connection
|
|
1117
|
+
*/
|
|
1118
|
+
createConnection() {
|
|
1119
|
+
const e = this.endpoint ?? Le(this.cluster);
|
|
1120
|
+
return new $e(e, "confirmed");
|
|
1121
|
+
}
|
|
1122
|
+
/**
|
|
1123
|
+
* Transform RPC errors into user-friendly messages
|
|
1124
|
+
*/
|
|
1125
|
+
transformRpcError(e) {
|
|
1126
|
+
const r = e instanceof Error ? e.message : typeof e == "string" ? e : String(e);
|
|
1127
|
+
return r.includes("403") || r.includes("Access forbidden") ? new Error(
|
|
1128
|
+
"Public Solana RPC access denied. Please configure a custom RPC endpoint (e.g., from Helius, QuickNode, or Alchemy) in your CedrosProvider config using the solanaEndpoint option."
|
|
1129
|
+
) : r.includes("429") || r.includes("Too Many Requests") ? new Error(
|
|
1130
|
+
"Solana RPC rate limit exceeded. Please configure a custom RPC endpoint with higher limits in your CedrosProvider config using the solanaEndpoint option."
|
|
1131
|
+
) : e instanceof Error ? e : new Error(r);
|
|
1132
|
+
}
|
|
1133
|
+
/**
|
|
1134
|
+
* Build transaction from x402 requirement
|
|
1135
|
+
*/
|
|
1136
|
+
async buildTransaction(e) {
|
|
1137
|
+
const { requirement: r, payerPublicKey: n, blockhash: a } = e;
|
|
1138
|
+
if (!r || !r.payTo)
|
|
1139
|
+
throw new Error("Invalid requirement: missing payTo");
|
|
1140
|
+
console.log("🔨 [WalletManager] Building NEW transaction for resource:", r.resource);
|
|
1141
|
+
const o = new ae(), s = this.resolveAmountInMinorUnits(r), i = r.asset;
|
|
1142
|
+
if (!i)
|
|
1143
|
+
throw new Error("asset is required in x402 requirement");
|
|
1144
|
+
const l = Pt(i, r.resource, this.allowUnknownMint);
|
|
1145
|
+
if (!l.isValid && l.error)
|
|
1146
|
+
throw new Error(l.error);
|
|
1147
|
+
l.warning && f().warn(l.warning);
|
|
1148
|
+
const c = new M(i), u = await je(
|
|
1149
|
+
c,
|
|
1150
|
+
n
|
|
1151
|
+
);
|
|
1152
|
+
if (!this.rpcRateLimiter.tryConsume())
|
|
1153
|
+
throw new Error("RPC rate limit exceeded. Please try again in a moment.");
|
|
1154
|
+
let d;
|
|
1155
|
+
try {
|
|
1156
|
+
d = await this.rpcCircuitBreaker.execute(async () => await C(
|
|
1157
|
+
async () => await this.connection.getAccountInfo(u),
|
|
1158
|
+
{ ...P.QUICK, name: "rpc-get-account-info" }
|
|
1159
|
+
));
|
|
1160
|
+
} catch (m) {
|
|
1161
|
+
throw m instanceof E ? new Error("Solana RPC service is temporarily unavailable. Please try again in a few moments.") : this.transformRpcError(m);
|
|
1162
|
+
}
|
|
1163
|
+
if (!d)
|
|
1164
|
+
throw new Error("Payer is missing an associated token account for this mint");
|
|
1165
|
+
let h;
|
|
1166
|
+
try {
|
|
1167
|
+
h = r.extra?.recipientTokenAccount ? new M(r.extra.recipientTokenAccount) : new M(r.payTo);
|
|
1168
|
+
} catch {
|
|
1169
|
+
throw new Error("We are currently unable to process payment, please try again later");
|
|
1170
|
+
}
|
|
1171
|
+
if (o.add(
|
|
1172
|
+
qe(
|
|
1173
|
+
u,
|
|
1174
|
+
h,
|
|
1175
|
+
n,
|
|
1176
|
+
s
|
|
1177
|
+
)
|
|
1178
|
+
), r.extra?.memo) {
|
|
1179
|
+
const { TransactionInstruction: m } = await import("@solana/web3.js"), y = new m({
|
|
1180
|
+
keys: [],
|
|
1181
|
+
programId: new M("MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr"),
|
|
1182
|
+
data: Buffer.from(r.extra.memo, "utf8")
|
|
1183
|
+
});
|
|
1184
|
+
o.add(y);
|
|
1185
|
+
}
|
|
1186
|
+
let p;
|
|
1187
|
+
if (a)
|
|
1188
|
+
p = a;
|
|
1189
|
+
else {
|
|
1190
|
+
if (!this.rpcRateLimiter.tryConsume())
|
|
1191
|
+
throw new Error("RPC rate limit exceeded. Please try again in a moment.");
|
|
1192
|
+
try {
|
|
1193
|
+
p = (await this.rpcCircuitBreaker.execute(async () => await C(
|
|
1194
|
+
async () => await this.connection.getLatestBlockhash(),
|
|
1195
|
+
{ ...P.QUICK, name: "rpc-get-blockhash" }
|
|
1196
|
+
))).blockhash;
|
|
1197
|
+
} catch (m) {
|
|
1198
|
+
throw m instanceof E ? new Error("Solana RPC service is temporarily unavailable. Please try again in a few moments.") : this.transformRpcError(m);
|
|
1199
|
+
}
|
|
1200
|
+
}
|
|
1201
|
+
return o.recentBlockhash = p, r.extra?.feePayer ? o.feePayer = new M(r.extra.feePayer) : o.feePayer = n, o;
|
|
1202
|
+
}
|
|
1203
|
+
/**
|
|
1204
|
+
* Parse amount from x402 requirement (already in atomic units as string)
|
|
1205
|
+
*/
|
|
1206
|
+
resolveAmountInMinorUnits(e) {
|
|
1207
|
+
const r = parseInt(e.maxAmountRequired, 10);
|
|
1208
|
+
if (Number.isNaN(r) || r <= 0)
|
|
1209
|
+
throw new Error("Invalid maxAmountRequired in requirement");
|
|
1210
|
+
return r;
|
|
1211
|
+
}
|
|
1212
|
+
/**
|
|
1213
|
+
* Build payment payload from signed transaction (x402 spec)
|
|
1214
|
+
*/
|
|
1215
|
+
buildPaymentPayload(e) {
|
|
1216
|
+
const { requirement: r, signedTx: n, payerPublicKey: a } = e;
|
|
1217
|
+
return {
|
|
1218
|
+
x402Version: 0,
|
|
1219
|
+
scheme: r.scheme,
|
|
1220
|
+
network: r.network,
|
|
1221
|
+
payload: {
|
|
1222
|
+
signature: n.signature,
|
|
1223
|
+
transaction: n.serialized,
|
|
1224
|
+
payer: a.toString(),
|
|
1225
|
+
memo: r.extra?.memo,
|
|
1226
|
+
recipientTokenAccount: r.extra?.recipientTokenAccount
|
|
1227
|
+
}
|
|
1228
|
+
};
|
|
1229
|
+
}
|
|
1230
|
+
/**
|
|
1231
|
+
* Sign transaction using wallet adapter (fully signed for regular mode)
|
|
1232
|
+
*/
|
|
1233
|
+
async signTransaction(e) {
|
|
1234
|
+
const { transaction: r, signTransaction: n } = e;
|
|
1235
|
+
console.log("✍️ [WalletManager] Requesting wallet to sign transaction");
|
|
1236
|
+
const a = await n(r), o = a.serialize(), s = a.signatures[0]?.signature;
|
|
1237
|
+
if (!s)
|
|
1238
|
+
throw new Error("Signed transaction missing signature");
|
|
1239
|
+
const i = de.encode(s);
|
|
1240
|
+
return console.log("✅ [WalletManager] Transaction signed with signature:", i.substring(0, 20) + "..."), {
|
|
1241
|
+
serialized: I.fromUint8Array(o),
|
|
1242
|
+
signature: i
|
|
1243
|
+
};
|
|
1244
|
+
}
|
|
1245
|
+
/**
|
|
1246
|
+
* Deserialize a base64-encoded transaction from the backend
|
|
1247
|
+
* Used for gasless flow where backend builds the complete transaction
|
|
1248
|
+
*/
|
|
1249
|
+
deserializeTransaction(e) {
|
|
1250
|
+
try {
|
|
1251
|
+
const r = I.toUint8Array(e);
|
|
1252
|
+
return ae.from(r);
|
|
1253
|
+
} catch (r) {
|
|
1254
|
+
throw new Error(
|
|
1255
|
+
`Failed to deserialize transaction: ${F(r, "Unknown error")}`
|
|
1256
|
+
);
|
|
1257
|
+
}
|
|
1258
|
+
}
|
|
1259
|
+
/**
|
|
1260
|
+
* Partially sign transaction for gasless mode
|
|
1261
|
+
* User signs their authority, server will co-sign as fee payer
|
|
1262
|
+
*/
|
|
1263
|
+
async partiallySignTransaction(e) {
|
|
1264
|
+
const { transaction: r, signTransaction: n, blockhash: a } = e;
|
|
1265
|
+
a && r.recentBlockhash !== a && (r.recentBlockhash = a);
|
|
1266
|
+
const o = await n(r), s = o.signatures[0]?.signature;
|
|
1267
|
+
if (s) {
|
|
1268
|
+
const l = de.encode(s);
|
|
1269
|
+
console.log("✅ [WalletManager] Partially signed with signature:", l.substring(0, 20) + "...");
|
|
1270
|
+
}
|
|
1271
|
+
const i = o.serialize({
|
|
1272
|
+
requireAllSignatures: !1,
|
|
1273
|
+
verifySignatures: !1
|
|
1274
|
+
});
|
|
1275
|
+
return I.fromUint8Array(i);
|
|
1276
|
+
}
|
|
1277
|
+
/**
|
|
1278
|
+
* Get wallet balance
|
|
1279
|
+
*/
|
|
1280
|
+
async getBalance(e) {
|
|
1281
|
+
if (!this.rpcRateLimiter.tryConsume())
|
|
1282
|
+
throw new Error("RPC rate limit exceeded. Please try again in a moment.");
|
|
1283
|
+
try {
|
|
1284
|
+
return await this.rpcCircuitBreaker.execute(async () => await C(
|
|
1285
|
+
async () => await this.connection.getBalance(e),
|
|
1286
|
+
{ ...P.QUICK, name: "rpc-get-balance" }
|
|
1287
|
+
)) / _e;
|
|
1288
|
+
} catch (r) {
|
|
1289
|
+
throw r instanceof E ? new Error("Solana RPC service is temporarily unavailable. Please try again in a few moments.") : this.transformRpcError(r);
|
|
1290
|
+
}
|
|
1291
|
+
}
|
|
1292
|
+
/**
|
|
1293
|
+
* Verify transaction on-chain
|
|
1294
|
+
*/
|
|
1295
|
+
async verifyTransaction(e) {
|
|
1296
|
+
if (!this.rpcRateLimiter.tryConsume())
|
|
1297
|
+
return f().warn("[WalletManager] RPC rate limit exceeded for transaction verification"), !1;
|
|
1298
|
+
try {
|
|
1299
|
+
return !!(await this.rpcCircuitBreaker.execute(async () => await C(
|
|
1300
|
+
async () => await this.connection.getSignatureStatus(e),
|
|
1301
|
+
{ ...P.QUICK, name: "rpc-verify-tx" }
|
|
1302
|
+
))).value?.confirmationStatus;
|
|
1303
|
+
} catch (r) {
|
|
1304
|
+
return r instanceof E && f().warn("[WalletManager] Circuit breaker OPEN - cannot verify transaction"), !1;
|
|
1305
|
+
}
|
|
1306
|
+
}
|
|
1307
|
+
}
|
|
1308
|
+
class At {
|
|
1309
|
+
serverUrl;
|
|
1310
|
+
routePrefix = null;
|
|
1311
|
+
discoveryPromise = null;
|
|
1312
|
+
maxRetries = 3;
|
|
1313
|
+
baseDelayMs = 1e3;
|
|
1314
|
+
constructor(e) {
|
|
1315
|
+
this.serverUrl = e;
|
|
1316
|
+
}
|
|
1317
|
+
/**
|
|
1318
|
+
* Discover route prefix from backend health endpoint
|
|
1319
|
+
*
|
|
1320
|
+
* DEDUPLICATION: Multiple concurrent calls share the same in-flight request
|
|
1321
|
+
* SECURITY FIX: Only cache on success, retry on failures with exponential backoff
|
|
1322
|
+
* This prevents permanent bricking of payments due to transient failures
|
|
1323
|
+
*/
|
|
1324
|
+
async discoverPrefix() {
|
|
1325
|
+
if (this.routePrefix !== null)
|
|
1326
|
+
return this.routePrefix;
|
|
1327
|
+
if (this.discoveryPromise)
|
|
1328
|
+
return this.discoveryPromise;
|
|
1329
|
+
const e = (async () => {
|
|
1330
|
+
let r = 0;
|
|
1331
|
+
for (; r < this.maxRetries; )
|
|
1332
|
+
try {
|
|
1333
|
+
const n = await S(`${this.serverUrl}/cedros-health`);
|
|
1334
|
+
if (!n.ok) {
|
|
1335
|
+
if (n.status >= 400 && n.status < 500)
|
|
1336
|
+
return f().warn(`Route discovery received ${n.status} - not retrying client error`), this.routePrefix = "", "";
|
|
1337
|
+
throw new Error(`Health check returned ${n.status}`);
|
|
1338
|
+
}
|
|
1339
|
+
const o = (await n.json()).routePrefix || "";
|
|
1340
|
+
return this.routePrefix = o, f().debug("Route discovery successful, prefix:", o || "(empty)"), o;
|
|
1341
|
+
} catch (n) {
|
|
1342
|
+
if (r++, r >= this.maxRetries)
|
|
1343
|
+
return f().warn(
|
|
1344
|
+
`Route discovery failed after ${r} attempts, using empty prefix for this request:`,
|
|
1345
|
+
n
|
|
1346
|
+
), "";
|
|
1347
|
+
const a = this.baseDelayMs * Math.pow(2, r - 1);
|
|
1348
|
+
f().warn(
|
|
1349
|
+
`Route discovery failed (attempt ${r}/${this.maxRetries}), retrying in ${a}ms:`,
|
|
1350
|
+
n
|
|
1351
|
+
), await new Promise((o) => setTimeout(o, a));
|
|
1352
|
+
}
|
|
1353
|
+
return "";
|
|
1354
|
+
})();
|
|
1355
|
+
this.discoveryPromise = e;
|
|
1356
|
+
try {
|
|
1357
|
+
return await this.discoveryPromise;
|
|
1358
|
+
} finally {
|
|
1359
|
+
this.discoveryPromise = null;
|
|
1360
|
+
}
|
|
1361
|
+
}
|
|
1362
|
+
/**
|
|
1363
|
+
* Build API URL with discovered prefix
|
|
1364
|
+
*/
|
|
1365
|
+
async buildUrl(e) {
|
|
1366
|
+
const r = await this.discoverPrefix(), n = e.startsWith("/") ? e : `/${e}`;
|
|
1367
|
+
return `${this.serverUrl}${r}${n}`;
|
|
1368
|
+
}
|
|
1369
|
+
/**
|
|
1370
|
+
* Reset cached prefix (useful for testing or reconnecting)
|
|
1371
|
+
*/
|
|
1372
|
+
reset() {
|
|
1373
|
+
this.routePrefix = null, this.discoveryPromise = null;
|
|
1374
|
+
}
|
|
1375
|
+
}
|
|
1376
|
+
const z = /* @__PURE__ */ new Map();
|
|
1377
|
+
function Ne(t, e, r, n, a) {
|
|
1378
|
+
return JSON.stringify({
|
|
1379
|
+
stripePublicKey: t,
|
|
1380
|
+
serverUrl: e,
|
|
1381
|
+
solanaCluster: r,
|
|
1382
|
+
solanaEndpoint: n || "",
|
|
1383
|
+
dangerouslyAllowUnknownMint: a || !1
|
|
1384
|
+
});
|
|
1385
|
+
}
|
|
1386
|
+
function Tt(t, e, r, n, a) {
|
|
1387
|
+
const o = Ne(
|
|
1388
|
+
t,
|
|
1389
|
+
e,
|
|
1390
|
+
r,
|
|
1391
|
+
n,
|
|
1392
|
+
a
|
|
1393
|
+
);
|
|
1394
|
+
let s = z.get(o);
|
|
1395
|
+
if (s)
|
|
1396
|
+
return s.refCount++, f().debug(
|
|
1397
|
+
`[ManagerCache] Reusing cached managers (refCount: ${s.refCount}):`,
|
|
1398
|
+
{ stripePublicKey: t.slice(0, 10) + "...", serverUrl: e }
|
|
1399
|
+
), s;
|
|
1400
|
+
f().debug(
|
|
1401
|
+
"[ManagerCache] Creating new manager instances:",
|
|
1402
|
+
{ stripePublicKey: t.slice(0, 10) + "...", serverUrl: e }
|
|
1403
|
+
);
|
|
1404
|
+
const i = new At(e), l = new lt(t, i), c = new vt(i), u = new St(
|
|
1405
|
+
r,
|
|
1406
|
+
n,
|
|
1407
|
+
a ?? !1
|
|
1408
|
+
);
|
|
1409
|
+
return s = {
|
|
1410
|
+
stripeManager: l,
|
|
1411
|
+
x402Manager: c,
|
|
1412
|
+
walletManager: u,
|
|
1413
|
+
routeDiscovery: i,
|
|
1414
|
+
refCount: 1
|
|
1415
|
+
}, z.set(o, s), s;
|
|
1416
|
+
}
|
|
1417
|
+
function kt(t, e, r, n, a) {
|
|
1418
|
+
const o = Ne(
|
|
1419
|
+
t,
|
|
1420
|
+
e,
|
|
1421
|
+
r,
|
|
1422
|
+
n,
|
|
1423
|
+
a
|
|
1424
|
+
), s = z.get(o);
|
|
1425
|
+
if (!s) {
|
|
1426
|
+
f().warn("[ManagerCache] Attempted to release non-existent managers:", { cacheKey: o });
|
|
1427
|
+
return;
|
|
1428
|
+
}
|
|
1429
|
+
s.refCount--, f().debug(
|
|
1430
|
+
`[ManagerCache] Released manager reference (refCount: ${s.refCount}):`,
|
|
1431
|
+
{ stripePublicKey: t.slice(0, 10) + "...", serverUrl: e }
|
|
1432
|
+
), s.refCount <= 0 && (z.delete(o), f().debug("[ManagerCache] Removed managers from cache (refCount reached 0)"));
|
|
1433
|
+
}
|
|
1434
|
+
const Rt = [
|
|
1435
|
+
"stripePublicKey"
|
|
1436
|
+
], fe = /* @__PURE__ */ new Set(["mainnet-beta", "devnet", "testnet"]);
|
|
1437
|
+
function Mt() {
|
|
1438
|
+
if (typeof window < "u" && window.location)
|
|
1439
|
+
return window.location.origin;
|
|
1440
|
+
throw new Error(
|
|
1441
|
+
"serverUrl is required in SSR/Node environments. In browser environments, it defaults to window.location.origin"
|
|
1442
|
+
);
|
|
1443
|
+
}
|
|
1444
|
+
function Ut(t) {
|
|
1445
|
+
const e = [];
|
|
1446
|
+
Rt.forEach((n) => {
|
|
1447
|
+
const a = t[n];
|
|
1448
|
+
(typeof a != "string" || a.trim().length === 0) && e.push({
|
|
1449
|
+
field: n,
|
|
1450
|
+
message: "must be a non-empty string"
|
|
1451
|
+
});
|
|
1452
|
+
});
|
|
1453
|
+
let r;
|
|
1454
|
+
if (t.serverUrl !== void 0)
|
|
1455
|
+
typeof t.serverUrl != "string" || t.serverUrl.trim().length === 0 ? (e.push({
|
|
1456
|
+
field: "serverUrl",
|
|
1457
|
+
message: "must be a non-empty string when provided"
|
|
1458
|
+
}), r = "") : r = t.serverUrl;
|
|
1459
|
+
else
|
|
1460
|
+
try {
|
|
1461
|
+
r = Mt();
|
|
1462
|
+
} catch (n) {
|
|
1463
|
+
e.push({
|
|
1464
|
+
field: "serverUrl",
|
|
1465
|
+
message: n instanceof Error ? n.message : "failed to determine default"
|
|
1466
|
+
}), r = "";
|
|
1467
|
+
}
|
|
1468
|
+
if (fe.has(t.solanaCluster) || e.push({
|
|
1469
|
+
field: "solanaCluster",
|
|
1470
|
+
message: `must be one of ${Array.from(fe).join(", ")}`
|
|
1471
|
+
}), t.solanaEndpoint !== void 0 && (typeof t.solanaEndpoint != "string" ? e.push({
|
|
1472
|
+
field: "solanaEndpoint",
|
|
1473
|
+
message: "must be a string when provided"
|
|
1474
|
+
}) : t.solanaEndpoint.trim().length === 0 ? e.push({
|
|
1475
|
+
field: "solanaEndpoint",
|
|
1476
|
+
message: 'must be a non-empty string when provided (e.g., "https://api.mainnet-beta.solana.com")'
|
|
1477
|
+
}) : !t.solanaEndpoint.startsWith("http://") && !t.solanaEndpoint.startsWith("https://") && e.push({
|
|
1478
|
+
field: "solanaEndpoint",
|
|
1479
|
+
message: 'must start with "http://" or "https://" (e.g., "https://api.mainnet-beta.solana.com")'
|
|
1480
|
+
})), t.tokenMint && typeof t.tokenMint != "string" && e.push({
|
|
1481
|
+
field: "tokenMint",
|
|
1482
|
+
message: "must be a string when provided"
|
|
1483
|
+
}), e.length > 0) {
|
|
1484
|
+
const n = e.map((a) => `- ${a.field} ${a.message}`).join(`
|
|
1485
|
+
`);
|
|
1486
|
+
throw new Error(`Invalid Cedros configuration:
|
|
1487
|
+
${n}`);
|
|
1488
|
+
}
|
|
1489
|
+
if (t.tokenMint) {
|
|
1490
|
+
const n = t.dangerouslyAllowUnknownMint === !0, a = Be(t.tokenMint, "CedrosConfig.tokenMint", n);
|
|
1491
|
+
if (!a.isValid && a.error)
|
|
1492
|
+
throw new Error(a.error);
|
|
1493
|
+
a.warning && f().warn(a.warning);
|
|
1494
|
+
}
|
|
1495
|
+
return {
|
|
1496
|
+
...t,
|
|
1497
|
+
serverUrl: r
|
|
1498
|
+
};
|
|
1499
|
+
}
|
|
1500
|
+
class Ot {
|
|
1501
|
+
adapters = null;
|
|
1502
|
+
poolId;
|
|
1503
|
+
isCleanedUp = !1;
|
|
1504
|
+
constructor(e) {
|
|
1505
|
+
this.poolId = e ?? `pool_${Date.now()}_${Math.random().toString(36).slice(2, 11)}`, f().debug(`[WalletPool] Created pool: ${this.poolId}`);
|
|
1506
|
+
}
|
|
1507
|
+
/**
|
|
1508
|
+
* Get wallet adapters for this pool
|
|
1509
|
+
*
|
|
1510
|
+
* Lazy initialization: adapters are created on first access.
|
|
1511
|
+
* Returns empty array in SSR environments.
|
|
1512
|
+
*/
|
|
1513
|
+
getAdapters() {
|
|
1514
|
+
return typeof window > "u" ? [] : this.isCleanedUp ? (f().warn(`[WalletPool] Attempted to use pool after cleanup: ${this.poolId}`), []) : this.adapters !== null ? this.adapters : (f().debug(`[WalletPool] Initializing adapters for pool: ${this.poolId}`), this.adapters = [
|
|
1515
|
+
new We(),
|
|
1516
|
+
new Ke()
|
|
1517
|
+
], this.adapters);
|
|
1518
|
+
}
|
|
1519
|
+
/**
|
|
1520
|
+
* Cleanup wallet adapters
|
|
1521
|
+
*
|
|
1522
|
+
* Disconnects all wallets and clears the adapter cache.
|
|
1523
|
+
* Called automatically when CedrosProvider unmounts.
|
|
1524
|
+
*
|
|
1525
|
+
* IMPORTANT: After cleanup, getAdapters() will return empty array.
|
|
1526
|
+
*/
|
|
1527
|
+
async cleanup() {
|
|
1528
|
+
if (this.isCleanedUp) {
|
|
1529
|
+
f().debug(`[WalletPool] Pool already cleaned up: ${this.poolId}`);
|
|
1530
|
+
return;
|
|
1531
|
+
}
|
|
1532
|
+
if (f().debug(`[WalletPool] Cleaning up pool: ${this.poolId}`), this.isCleanedUp = !0, this.adapters === null)
|
|
1533
|
+
return;
|
|
1534
|
+
const e = this.adapters.map(async (r) => {
|
|
1535
|
+
try {
|
|
1536
|
+
r.connected && (f().debug(`[WalletPool] Disconnecting wallet: ${r.name}`), await r.disconnect());
|
|
1537
|
+
} catch (n) {
|
|
1538
|
+
f().warn(`[WalletPool] Failed to disconnect wallet ${r.name}:`, n);
|
|
1539
|
+
}
|
|
1540
|
+
});
|
|
1541
|
+
await Promise.allSettled(e), this.adapters = null, f().debug(`[WalletPool] Pool cleanup complete: ${this.poolId}`);
|
|
1542
|
+
}
|
|
1543
|
+
/**
|
|
1544
|
+
* Check if this pool has been initialized
|
|
1545
|
+
*
|
|
1546
|
+
* Useful for testing or debugging.
|
|
1547
|
+
*/
|
|
1548
|
+
isInitialized() {
|
|
1549
|
+
return this.adapters !== null;
|
|
1550
|
+
}
|
|
1551
|
+
/**
|
|
1552
|
+
* Get pool ID (for debugging/logging)
|
|
1553
|
+
*/
|
|
1554
|
+
getId() {
|
|
1555
|
+
return this.poolId;
|
|
1556
|
+
}
|
|
1557
|
+
}
|
|
1558
|
+
function Dt(t) {
|
|
1559
|
+
return new Ot(t);
|
|
1560
|
+
}
|
|
1561
|
+
const Bt = Object.freeze({
|
|
1562
|
+
surfaceBackground: "rgba(255, 255, 255, 0)",
|
|
1563
|
+
surfaceText: "#111827",
|
|
1564
|
+
surfaceBorder: "rgba(15, 23, 42, 0.08)",
|
|
1565
|
+
stripeBackground: "linear-gradient(135deg, #635bff 0%, #4f46e5 100%)",
|
|
1566
|
+
stripeText: "#ffffff",
|
|
1567
|
+
stripeShadow: "rgba(79, 70, 229, 0.25)",
|
|
1568
|
+
cryptoBackground: "linear-gradient(135deg, #14f195 0%, #9945ff 100%)",
|
|
1569
|
+
cryptoText: "#ffffff",
|
|
1570
|
+
cryptoShadow: "rgba(99, 102, 241, 0.25)",
|
|
1571
|
+
errorBackground: "#fee2e2",
|
|
1572
|
+
errorBorder: "#fca5a5",
|
|
1573
|
+
errorText: "#b91c1c",
|
|
1574
|
+
successBackground: "#dcfce7",
|
|
1575
|
+
successBorder: "#86efac",
|
|
1576
|
+
successText: "#166534",
|
|
1577
|
+
modalOverlay: "rgba(0, 0, 0, 0.5)",
|
|
1578
|
+
modalBackground: "#ffffff",
|
|
1579
|
+
modalBorder: "rgba(15, 23, 42, 0.08)",
|
|
1580
|
+
buttonBorderRadius: "8px",
|
|
1581
|
+
buttonPadding: "0.75rem 1.5rem",
|
|
1582
|
+
buttonFontSize: "1rem",
|
|
1583
|
+
buttonFontWeight: "600"
|
|
1584
|
+
}), Nt = Object.freeze({
|
|
1585
|
+
surfaceBackground: "rgba(17, 24, 39, 0.6)",
|
|
1586
|
+
surfaceText: "#f9fafb",
|
|
1587
|
+
surfaceBorder: "rgba(148, 163, 184, 0.25)",
|
|
1588
|
+
stripeBackground: "linear-gradient(135deg, #4f46e5 0%, #3730a3 100%)",
|
|
1589
|
+
stripeText: "#f5f3ff",
|
|
1590
|
+
stripeShadow: "rgba(99, 102, 241, 0.35)",
|
|
1591
|
+
cryptoBackground: "linear-gradient(135deg, #1dd4a6 0%, #6d28d9 100%)",
|
|
1592
|
+
cryptoText: "#ecfeff",
|
|
1593
|
+
cryptoShadow: "rgba(75, 85, 99, 0.35)",
|
|
1594
|
+
errorBackground: "#7f1d1d",
|
|
1595
|
+
errorBorder: "#fca5a5",
|
|
1596
|
+
errorText: "#fecaca",
|
|
1597
|
+
successBackground: "#14532d",
|
|
1598
|
+
successBorder: "#4ade80",
|
|
1599
|
+
successText: "#bbf7d0",
|
|
1600
|
+
modalOverlay: "rgba(0, 0, 0, 0.75)",
|
|
1601
|
+
modalBackground: "#1f2937",
|
|
1602
|
+
modalBorder: "rgba(148, 163, 184, 0.25)",
|
|
1603
|
+
buttonBorderRadius: "8px",
|
|
1604
|
+
buttonPadding: "0.75rem 1.5rem",
|
|
1605
|
+
buttonFontSize: "1rem",
|
|
1606
|
+
buttonFontWeight: "600"
|
|
1607
|
+
}), It = {
|
|
1608
|
+
surfaceBackground: "--cedros-surface-bg",
|
|
1609
|
+
surfaceText: "--cedros-surface-text",
|
|
1610
|
+
surfaceBorder: "--cedros-surface-border",
|
|
1611
|
+
stripeBackground: "--cedros-stripe-bg",
|
|
1612
|
+
stripeText: "--cedros-stripe-text",
|
|
1613
|
+
stripeShadow: "--cedros-stripe-shadow",
|
|
1614
|
+
cryptoBackground: "--cedros-crypto-bg",
|
|
1615
|
+
cryptoText: "--cedros-crypto-text",
|
|
1616
|
+
cryptoShadow: "--cedros-crypto-shadow",
|
|
1617
|
+
errorBackground: "--cedros-error-bg",
|
|
1618
|
+
errorBorder: "--cedros-error-border",
|
|
1619
|
+
errorText: "--cedros-error-text",
|
|
1620
|
+
successBackground: "--cedros-success-bg",
|
|
1621
|
+
successBorder: "--cedros-success-border",
|
|
1622
|
+
successText: "--cedros-success-text",
|
|
1623
|
+
modalOverlay: "--cedros-modal-overlay",
|
|
1624
|
+
modalBackground: "--cedros-modal-bg",
|
|
1625
|
+
modalBorder: "--cedros-modal-border",
|
|
1626
|
+
buttonBorderRadius: "--cedros-button-radius",
|
|
1627
|
+
buttonPadding: "--cedros-button-padding",
|
|
1628
|
+
buttonFontSize: "--cedros-button-font-size",
|
|
1629
|
+
buttonFontWeight: "--cedros-button-font-weight"
|
|
1630
|
+
}, Ie = me(null);
|
|
1631
|
+
function Ft(t, e) {
|
|
1632
|
+
return {
|
|
1633
|
+
...t === "dark" ? Nt : Bt,
|
|
1634
|
+
...e
|
|
1635
|
+
};
|
|
1636
|
+
}
|
|
1637
|
+
function Lt(t) {
|
|
1638
|
+
const e = Object.entries(t).map(([r, n]) => [
|
|
1639
|
+
It[r],
|
|
1640
|
+
n
|
|
1641
|
+
]);
|
|
1642
|
+
return Object.fromEntries(e);
|
|
1643
|
+
}
|
|
1644
|
+
function $t({
|
|
1645
|
+
initialMode: t = "light",
|
|
1646
|
+
overrides: e,
|
|
1647
|
+
unstyled: r = !1,
|
|
1648
|
+
children: n
|
|
1649
|
+
}) {
|
|
1650
|
+
const [a, o] = X(t), [s, i] = X(e), l = ye(e);
|
|
1651
|
+
D(() => {
|
|
1652
|
+
if (e === l.current)
|
|
1653
|
+
return;
|
|
1654
|
+
(!e || !l.current ? e !== l.current : Object.keys({ ...e, ...l.current }).some(
|
|
1655
|
+
(d) => e[d] !== l.current?.[d]
|
|
1656
|
+
)) && (l.current = e, i(e));
|
|
1657
|
+
}, [e]);
|
|
1658
|
+
const c = Y(() => {
|
|
1659
|
+
const u = Ft(a, s), d = r ? {} : Lt(u), h = r ? "" : `cedros-theme-root cedros-theme cedros-theme--${a}`;
|
|
1660
|
+
return {
|
|
1661
|
+
mode: a,
|
|
1662
|
+
setMode: o,
|
|
1663
|
+
tokens: u,
|
|
1664
|
+
className: h,
|
|
1665
|
+
style: d,
|
|
1666
|
+
unstyled: r
|
|
1667
|
+
};
|
|
1668
|
+
}, [a, s, r]);
|
|
1669
|
+
return /* @__PURE__ */ H(Ie.Provider, { value: c, children: n });
|
|
1670
|
+
}
|
|
1671
|
+
function Xt() {
|
|
1672
|
+
const t = pe(Ie);
|
|
1673
|
+
if (!t)
|
|
1674
|
+
throw new Error("useCedrosTheme must be used within CedrosProvider");
|
|
1675
|
+
return t;
|
|
1676
|
+
}
|
|
1677
|
+
let V = !1, G = !1;
|
|
1678
|
+
async function _t() {
|
|
1679
|
+
if (V)
|
|
1680
|
+
return G ? { available: !0 } : {
|
|
1681
|
+
available: !1,
|
|
1682
|
+
error: he()
|
|
1683
|
+
};
|
|
1684
|
+
try {
|
|
1685
|
+
return await import("@solana/web3.js"), V = !0, G = !0, { available: !0 };
|
|
1686
|
+
} catch {
|
|
1687
|
+
return V = !0, G = !1, {
|
|
1688
|
+
available: !1,
|
|
1689
|
+
error: he()
|
|
1690
|
+
};
|
|
1691
|
+
}
|
|
1692
|
+
}
|
|
1693
|
+
function he() {
|
|
1694
|
+
return `Solana dependencies not installed. To use crypto payments, install them with:
|
|
1695
|
+
|
|
1696
|
+
npm install @solana/web3.js @solana/spl-token @solana/wallet-adapter-react @solana/wallet-adapter-react-ui @solana/wallet-adapter-wallets @solana/wallet-adapter-base
|
|
1697
|
+
|
|
1698
|
+
Or if you only need Stripe payments, hide the crypto button with:
|
|
1699
|
+
<CedrosPay showCrypto={false} />`;
|
|
1700
|
+
}
|
|
1701
|
+
function jt() {
|
|
1702
|
+
return typeof process < "u" && process.env.NODE_ENV === "development" ? 0 : 2;
|
|
1703
|
+
}
|
|
1704
|
+
const Fe = me(null);
|
|
1705
|
+
function Yt({ config: t, children: e }) {
|
|
1706
|
+
const r = Y(() => Ut(t), [t]), n = ye(null);
|
|
1707
|
+
n.current === null && (n.current = Dt());
|
|
1708
|
+
const [a, o] = X(null);
|
|
1709
|
+
D(() => {
|
|
1710
|
+
let i = !1;
|
|
1711
|
+
return _t().then((l) => {
|
|
1712
|
+
i || (l.available ? o(void 0) : o(l.error || "Solana dependencies not available"));
|
|
1713
|
+
}), () => {
|
|
1714
|
+
i = !0;
|
|
1715
|
+
};
|
|
1716
|
+
}, []), D(() => {
|
|
1717
|
+
const i = r.logLevel ?? jt(), l = rt({
|
|
1718
|
+
level: i,
|
|
1719
|
+
prefix: "[CedrosPay]"
|
|
1720
|
+
});
|
|
1721
|
+
tt(l);
|
|
1722
|
+
}, [r.logLevel]), D(() => {
|
|
1723
|
+
const i = n.current;
|
|
1724
|
+
return () => {
|
|
1725
|
+
i && i.cleanup().catch((l) => {
|
|
1726
|
+
f().warn("[CedrosProvider] Wallet pool cleanup failed:", l);
|
|
1727
|
+
});
|
|
1728
|
+
};
|
|
1729
|
+
}, []), D(() => {
|
|
1730
|
+
const i = r.stripePublicKey, l = r.serverUrl ?? "", c = r.solanaCluster, u = r.solanaEndpoint, d = r.dangerouslyAllowUnknownMint;
|
|
1731
|
+
return () => {
|
|
1732
|
+
kt(i, l, c, u, d);
|
|
1733
|
+
};
|
|
1734
|
+
}, [
|
|
1735
|
+
r.stripePublicKey,
|
|
1736
|
+
r.serverUrl,
|
|
1737
|
+
r.solanaCluster,
|
|
1738
|
+
r.solanaEndpoint,
|
|
1739
|
+
r.dangerouslyAllowUnknownMint
|
|
1740
|
+
]);
|
|
1741
|
+
const s = Y(() => {
|
|
1742
|
+
const { stripeManager: i, x402Manager: l, walletManager: c } = Tt(
|
|
1743
|
+
r.stripePublicKey,
|
|
1744
|
+
r.serverUrl ?? "",
|
|
1745
|
+
r.solanaCluster,
|
|
1746
|
+
r.solanaEndpoint,
|
|
1747
|
+
r.dangerouslyAllowUnknownMint
|
|
1748
|
+
);
|
|
1749
|
+
return {
|
|
1750
|
+
config: r,
|
|
1751
|
+
stripeManager: i,
|
|
1752
|
+
x402Manager: l,
|
|
1753
|
+
walletManager: c,
|
|
1754
|
+
walletPool: n.current,
|
|
1755
|
+
solanaError: a
|
|
1756
|
+
};
|
|
1757
|
+
}, [r, a]);
|
|
1758
|
+
return /* @__PURE__ */ H(Fe.Provider, { value: s, children: /* @__PURE__ */ H(
|
|
1759
|
+
$t,
|
|
1760
|
+
{
|
|
1761
|
+
initialMode: r.theme ?? "light",
|
|
1762
|
+
overrides: r.themeOverrides,
|
|
1763
|
+
unstyled: r.unstyled ?? !1,
|
|
1764
|
+
children: e
|
|
1765
|
+
}
|
|
1766
|
+
) });
|
|
1767
|
+
}
|
|
1768
|
+
function Qt() {
|
|
1769
|
+
const t = pe(Fe);
|
|
1770
|
+
if (!t)
|
|
1771
|
+
throw new Error("useCedrosContext must be used within CedrosProvider");
|
|
1772
|
+
return t;
|
|
1773
|
+
}
|
|
1774
|
+
export {
|
|
1775
|
+
Yt as C,
|
|
1776
|
+
ee as K,
|
|
1777
|
+
Ze as L,
|
|
1778
|
+
Q as R,
|
|
1779
|
+
Ot as W,
|
|
1780
|
+
Xt as a,
|
|
1781
|
+
ve as b,
|
|
1782
|
+
K as c,
|
|
1783
|
+
rt as d,
|
|
1784
|
+
Be as e,
|
|
1785
|
+
F as f,
|
|
1786
|
+
f as g,
|
|
1787
|
+
te as h,
|
|
1788
|
+
ot as i,
|
|
1789
|
+
E as j,
|
|
1790
|
+
Ht as k,
|
|
1791
|
+
P as l,
|
|
1792
|
+
Dt as m,
|
|
1793
|
+
C as r,
|
|
1794
|
+
Qt as u,
|
|
1795
|
+
Ut as v
|
|
1796
|
+
};
|