@puga-labs/x402-mantle-sdk 0.2.0 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/dist/chunk-CTI5CRDY.js +274 -0
  2. package/dist/chunk-DA6ZBXNO.js +275 -0
  3. package/dist/chunk-FD4HG7KR.js +135 -0
  4. package/dist/chunk-GWVWPS3R.js +277 -0
  5. package/dist/chunk-HTZ3QFY4.js +135 -0
  6. package/dist/chunk-MQALBRGV.js +135 -0
  7. package/dist/chunk-PYIYE3HI.js +135 -0
  8. package/dist/chunk-Q6SPMEIW.js +235 -0
  9. package/dist/chunk-RNKXSBT7.js +135 -0
  10. package/dist/chunk-SPCXFN7C.js +284 -0
  11. package/dist/chunk-T5DRYLNB.js +135 -0
  12. package/dist/chunk-TSEE5NSJ.js +297 -0
  13. package/dist/chunk-WELDWRDX.js +307 -0
  14. package/dist/chunk-XAQGMFSR.js +56 -0
  15. package/dist/client.cjs +328 -0
  16. package/dist/client.d.cts +17 -0
  17. package/dist/client.d.ts +17 -0
  18. package/dist/client.js +12 -0
  19. package/dist/constants-C7aY8u5b.d.cts +77 -0
  20. package/dist/constants-C7aY8u5b.d.ts +77 -0
  21. package/dist/constants-CVFF0ray.d.ts +17 -0
  22. package/dist/constants-DzCGK0Q3.d.cts +17 -0
  23. package/dist/createMantleClient-DS1Ghqrz.d.cts +51 -0
  24. package/dist/createMantleClient-DS1Ghqrz.d.ts +51 -0
  25. package/dist/createMantleClient-DVFkbBfS.d.ts +87 -0
  26. package/dist/createMantleClient-NN0Nitp9.d.cts +87 -0
  27. package/dist/index.cjs +244 -43
  28. package/dist/index.d.cts +8 -164
  29. package/dist/index.d.ts +8 -164
  30. package/dist/index.js +21 -485
  31. package/dist/react.cjs +453 -0
  32. package/dist/react.d.cts +90 -0
  33. package/dist/react.d.ts +90 -0
  34. package/dist/react.js +10 -0
  35. package/dist/server.cjs +292 -0
  36. package/dist/server.d.cts +116 -0
  37. package/dist/server.d.ts +116 -0
  38. package/dist/server.js +12 -0
  39. package/dist/types-2zqbJvcz.d.cts +63 -0
  40. package/dist/types-2zqbJvcz.d.ts +63 -0
  41. package/package.json +37 -3
@@ -0,0 +1,235 @@
1
+ import {
2
+ MANTLE_DEFAULTS,
3
+ getDefaultAssetForNetwork,
4
+ usdCentsToAtomic
5
+ } from "./chunk-XAQGMFSR.js";
6
+
7
+ // src/server/constants.ts
8
+ var DEFAULT_TELEMETRY_ENDPOINT = void 0;
9
+
10
+ // src/server/telemetry.ts
11
+ function createTelemetryEvent(entry, config) {
12
+ const assetConfig = getDefaultAssetForNetwork(entry.network);
13
+ return {
14
+ event: "payment_verified",
15
+ ts: entry.timestamp,
16
+ projectKey: config.projectKey,
17
+ network: entry.network,
18
+ buyer: entry.from,
19
+ payTo: entry.to,
20
+ amountAtomic: entry.valueAtomic,
21
+ asset: entry.asset,
22
+ decimals: assetConfig.decimals,
23
+ nonce: entry.id,
24
+ route: entry.route ?? "unknown",
25
+ // Facilitator metadata
26
+ facilitatorType: "hosted",
27
+ // SDK always uses hosted mode
28
+ facilitatorUrl: entry.facilitatorUrl,
29
+ // From PaymentLogEntry
30
+ // facilitatorAddress is undefined for SDK (not available)
31
+ // Optional metadata
32
+ txHash: entry.txHash,
33
+ priceUsd: entry.paymentRequirements?.price
34
+ };
35
+ }
36
+ async function sendTelemetry(event, endpoint) {
37
+ const targetEndpoint = endpoint ?? DEFAULT_TELEMETRY_ENDPOINT;
38
+ if (!targetEndpoint) {
39
+ return;
40
+ }
41
+ try {
42
+ const response = await fetch(targetEndpoint, {
43
+ method: "POST",
44
+ headers: {
45
+ "Content-Type": "application/json",
46
+ "Authorization": `Bearer ${event.projectKey}`
47
+ },
48
+ body: JSON.stringify(event)
49
+ });
50
+ if (!response.ok) {
51
+ console.warn(
52
+ `[x402-telemetry] Failed to send event: HTTP ${response.status}`
53
+ );
54
+ }
55
+ } catch (err) {
56
+ console.error("[x402-telemetry] Error sending telemetry:", err);
57
+ }
58
+ }
59
+
60
+ // src/server/paymentMiddleware.ts
61
+ function getRouteKey(req) {
62
+ const method = (req.method || "GET").toUpperCase();
63
+ const path = req.path || "/";
64
+ return `${method} ${path}`;
65
+ }
66
+ function decodePaymentHeader(paymentHeaderBase64) {
67
+ try {
68
+ if (typeof Buffer !== "undefined") {
69
+ const json = Buffer.from(paymentHeaderBase64, "base64").toString("utf8");
70
+ return JSON.parse(json);
71
+ }
72
+ if (typeof atob === "function") {
73
+ const json = atob(paymentHeaderBase64);
74
+ return JSON.parse(json);
75
+ }
76
+ throw new Error("No base64 decoding available in this environment");
77
+ } catch (err) {
78
+ const msg = err instanceof Error ? err.message : "Unknown error";
79
+ throw new Error(`Failed to decode paymentHeader: ${msg}`);
80
+ }
81
+ }
82
+ function createPaymentMiddleware(config) {
83
+ const { facilitatorUrl, receiverAddress, routes, onPaymentSettled, telemetry } = config;
84
+ if (!facilitatorUrl) {
85
+ throw new Error("facilitatorUrl is required");
86
+ }
87
+ if (!receiverAddress) {
88
+ throw new Error("receiverAddress is required");
89
+ }
90
+ if (!routes || Object.keys(routes).length === 0) {
91
+ throw new Error("routes config must not be empty");
92
+ }
93
+ return async function paymentMiddleware(req, res, next) {
94
+ const routeKey = getRouteKey(req);
95
+ const routeConfig = routes[routeKey];
96
+ if (!routeConfig) {
97
+ next();
98
+ return;
99
+ }
100
+ const { priceUsdCents, network } = routeConfig;
101
+ const assetConfig = getDefaultAssetForNetwork(network);
102
+ const maxAmountRequiredBigInt = usdCentsToAtomic(
103
+ priceUsdCents,
104
+ assetConfig.decimals
105
+ );
106
+ const paymentRequirements = {
107
+ scheme: "exact",
108
+ network,
109
+ asset: assetConfig.address,
110
+ maxAmountRequired: maxAmountRequiredBigInt.toString(),
111
+ payTo: receiverAddress,
112
+ price: `$${(priceUsdCents / 100).toFixed(2)}`,
113
+ currency: "USD"
114
+ };
115
+ const paymentHeader = req.header("X-PAYMENT") ?? req.header("x-payment");
116
+ if (!paymentHeader) {
117
+ res.status(402).json({
118
+ error: "Payment Required",
119
+ paymentRequirements,
120
+ paymentHeader: null
121
+ });
122
+ return;
123
+ }
124
+ try {
125
+ const verifyUrl = `${facilitatorUrl.replace(/\/+$/, "")}/verify`;
126
+ const verifyRes = await fetch(verifyUrl, {
127
+ method: "POST",
128
+ headers: {
129
+ "Content-Type": "application/json"
130
+ },
131
+ body: JSON.stringify({
132
+ x402Version: 1,
133
+ paymentHeader,
134
+ paymentRequirements
135
+ })
136
+ });
137
+ if (!verifyRes.ok) {
138
+ const text = await verifyRes.text().catch(() => "");
139
+ console.error(
140
+ "[x402-mantle-sdk] Facilitator /verify returned non-OK:",
141
+ verifyRes.status,
142
+ text
143
+ );
144
+ res.status(500).json({
145
+ error: "Payment verification error",
146
+ details: `Facilitator responded with HTTP ${verifyRes.status}`
147
+ });
148
+ return;
149
+ }
150
+ const verifyJson = await verifyRes.json();
151
+ if (!verifyJson.isValid) {
152
+ res.status(402).json({
153
+ error: "Payment verification failed",
154
+ invalidReason: verifyJson.invalidReason ?? null,
155
+ paymentRequirements,
156
+ paymentHeader: null
157
+ });
158
+ return;
159
+ }
160
+ if (onPaymentSettled) {
161
+ try {
162
+ const headerObj = decodePaymentHeader(paymentHeader);
163
+ const { authorization } = headerObj.payload;
164
+ const logEntry = {
165
+ id: authorization.nonce,
166
+ from: authorization.from,
167
+ to: authorization.to,
168
+ valueAtomic: authorization.value,
169
+ network,
170
+ asset: assetConfig.address,
171
+ route: routeKey,
172
+ timestamp: Date.now(),
173
+ facilitatorUrl,
174
+ // Pass from config closure
175
+ paymentRequirements
176
+ };
177
+ onPaymentSettled(logEntry);
178
+ if (telemetry) {
179
+ const event = createTelemetryEvent(logEntry, telemetry);
180
+ sendTelemetry(event, telemetry.endpoint).catch(
181
+ (err) => console.error("[x402-telemetry] Async send failed:", err)
182
+ );
183
+ }
184
+ } catch (err) {
185
+ console.error(
186
+ "[x402-mantle-sdk] Error calling onPaymentSettled hook:",
187
+ err
188
+ );
189
+ }
190
+ }
191
+ next();
192
+ return;
193
+ } catch (err) {
194
+ console.error(
195
+ "[x402-mantle-sdk] Error while calling facilitator /verify:",
196
+ err
197
+ );
198
+ const message = err instanceof Error ? err.message : "Unknown verification error";
199
+ res.status(500).json({
200
+ error: "Payment verification error",
201
+ details: message
202
+ });
203
+ return;
204
+ }
205
+ };
206
+ }
207
+
208
+ // src/server/mantlePaywall.ts
209
+ function mantlePaywall(opts) {
210
+ const { priceUsd, payTo, facilitatorUrl, telemetry, onPaymentSettled } = opts;
211
+ const priceUsdCents = Math.round(priceUsd * 100);
212
+ return async (req, res, next) => {
213
+ const method = (req.method || "GET").toUpperCase();
214
+ const path = req.path || "/";
215
+ const routeKey = `${method} ${path}`;
216
+ const middleware = createPaymentMiddleware({
217
+ facilitatorUrl: facilitatorUrl || MANTLE_DEFAULTS.FACILITATOR_URL,
218
+ receiverAddress: payTo,
219
+ routes: {
220
+ [routeKey]: {
221
+ priceUsdCents,
222
+ network: MANTLE_DEFAULTS.NETWORK
223
+ }
224
+ },
225
+ telemetry,
226
+ onPaymentSettled
227
+ });
228
+ return middleware(req, res, next);
229
+ };
230
+ }
231
+
232
+ export {
233
+ createPaymentMiddleware,
234
+ mantlePaywall
235
+ };
@@ -0,0 +1,135 @@
1
+ import {
2
+ createMantleClient
3
+ } from "./chunk-TSEE5NSJ.js";
4
+
5
+ // src/client/react/useEthersWallet.ts
6
+ import { useState, useEffect, useCallback } from "react";
7
+ import { ethers } from "ethers";
8
+ function useEthersWallet(options) {
9
+ const [address, setAddress] = useState(void 0);
10
+ const [isConnected, setIsConnected] = useState(false);
11
+ const [provider, setProvider] = useState(
12
+ void 0
13
+ );
14
+ const [chainId, setChainId] = useState(void 0);
15
+ const [error, setError] = useState(void 0);
16
+ const connect = useCallback(async () => {
17
+ try {
18
+ setError(void 0);
19
+ if (typeof window === "undefined" || !window.ethereum) {
20
+ throw new Error(
21
+ "No Ethereum wallet detected. Please install MetaMask or another wallet."
22
+ );
23
+ }
24
+ const browserProvider = new ethers.BrowserProvider(
25
+ window.ethereum
26
+ );
27
+ setProvider(browserProvider);
28
+ const accounts = await window.ethereum.request({
29
+ method: "eth_requestAccounts"
30
+ });
31
+ if (!accounts || accounts.length === 0) {
32
+ throw new Error("No accounts returned from wallet");
33
+ }
34
+ const userAddress = accounts[0];
35
+ setAddress(userAddress);
36
+ setIsConnected(true);
37
+ const network = await browserProvider.getNetwork();
38
+ setChainId(Number(network.chainId));
39
+ } catch (err) {
40
+ const errorObj = err instanceof Error ? err : new Error(String(err));
41
+ setError(errorObj);
42
+ setIsConnected(false);
43
+ setAddress(void 0);
44
+ setChainId(void 0);
45
+ throw errorObj;
46
+ }
47
+ }, []);
48
+ const disconnect = useCallback(() => {
49
+ setAddress(void 0);
50
+ setIsConnected(false);
51
+ setChainId(void 0);
52
+ setError(void 0);
53
+ }, []);
54
+ useEffect(() => {
55
+ if (typeof window === "undefined" || !window.ethereum) return;
56
+ const ethereum = window.ethereum;
57
+ const handleAccountsChanged = (accounts) => {
58
+ const accountsArray = accounts;
59
+ if (!accountsArray || accountsArray.length === 0) {
60
+ disconnect();
61
+ } else {
62
+ setAddress(accountsArray[0]);
63
+ setIsConnected(true);
64
+ }
65
+ };
66
+ if (ethereum.on) {
67
+ ethereum.on("accountsChanged", handleAccountsChanged);
68
+ }
69
+ return () => {
70
+ if (ethereum.removeListener) {
71
+ ethereum.removeListener("accountsChanged", handleAccountsChanged);
72
+ }
73
+ };
74
+ }, [disconnect]);
75
+ useEffect(() => {
76
+ if (typeof window === "undefined" || !window.ethereum) return;
77
+ const ethereum = window.ethereum;
78
+ const handleChainChanged = (chainIdHex) => {
79
+ const newChainId = parseInt(chainIdHex, 16);
80
+ setChainId(newChainId);
81
+ };
82
+ if (ethereum.on) {
83
+ ethereum.on("chainChanged", handleChainChanged);
84
+ }
85
+ return () => {
86
+ if (ethereum.removeListener) {
87
+ ethereum.removeListener("chainChanged", handleChainChanged);
88
+ }
89
+ };
90
+ }, []);
91
+ useEffect(() => {
92
+ if (options?.autoConnect) {
93
+ connect().catch((err) => {
94
+ console.warn("[useEthersWallet] Auto-connect failed:", err);
95
+ });
96
+ }
97
+ }, [options?.autoConnect, connect]);
98
+ return {
99
+ address,
100
+ isConnected,
101
+ provider,
102
+ chainId,
103
+ connect,
104
+ disconnect,
105
+ error
106
+ };
107
+ }
108
+
109
+ // src/client/react/useMantleX402.ts
110
+ function useMantleX402(opts) {
111
+ const { address, isConnected } = useEthersWallet({
112
+ autoConnect: opts?.autoConnect ?? false
113
+ });
114
+ const client = createMantleClient({
115
+ facilitatorUrl: opts?.facilitatorUrl,
116
+ resourceUrl: opts?.resourceUrl,
117
+ projectKey: opts?.projectKey,
118
+ getAccount: () => {
119
+ if (!isConnected || !address) return void 0;
120
+ return address;
121
+ },
122
+ getProvider: () => {
123
+ if (typeof window !== "undefined" && window.ethereum) {
124
+ return window.ethereum;
125
+ }
126
+ return void 0;
127
+ }
128
+ });
129
+ return client;
130
+ }
131
+
132
+ export {
133
+ useEthersWallet,
134
+ useMantleX402
135
+ };
@@ -0,0 +1,284 @@
1
+ import {
2
+ __require,
3
+ getChainIdForNetwork
4
+ } from "./chunk-XAQGMFSR.js";
5
+
6
+ // src/shared/utils.ts
7
+ function encodeJsonToBase64(value) {
8
+ const json = JSON.stringify(value);
9
+ if (typeof btoa === "function") {
10
+ const bytes = new TextEncoder().encode(json);
11
+ const binString = Array.from(
12
+ bytes,
13
+ (byte) => String.fromCodePoint(byte)
14
+ ).join("");
15
+ return btoa(binString);
16
+ }
17
+ if (typeof globalThis.Buffer !== "undefined") {
18
+ return globalThis.Buffer.from(json, "utf8").toString("base64");
19
+ }
20
+ throw new Error("No base64 implementation found in this environment");
21
+ }
22
+ function randomBytes32Hex() {
23
+ if (typeof crypto !== "undefined" && "getRandomValues" in crypto) {
24
+ const arr = new Uint8Array(32);
25
+ crypto.getRandomValues(arr);
26
+ return "0x" + Array.from(arr).map((b) => b.toString(16).padStart(2, "0")).join("");
27
+ }
28
+ try {
29
+ const nodeCrypto = __require("crypto");
30
+ const buf = nodeCrypto.randomBytes(32);
31
+ return "0x" + buf.toString("hex");
32
+ } catch {
33
+ throw new Error(
34
+ "No cryptographically secure random number generator found. This environment does not support crypto.getRandomValues or Node.js crypto module."
35
+ );
36
+ }
37
+ }
38
+
39
+ // src/client/paymentClient.ts
40
+ function joinUrl(base, path) {
41
+ const normalizedBase = base.replace(/\/+$/, "");
42
+ const normalizedPath = path.startsWith("/") ? path : `/${path}`;
43
+ return `${normalizedBase}${normalizedPath}`;
44
+ }
45
+ async function getUserAddressFromProvider(provider) {
46
+ const p = provider;
47
+ if (!p || typeof p.request !== "function") {
48
+ throw new Error("provider must implement EIP-1193 request()");
49
+ }
50
+ const accounts = await p.request({
51
+ method: "eth_requestAccounts"
52
+ });
53
+ if (!accounts || accounts.length === 0) {
54
+ throw new Error("No accounts returned from provider");
55
+ }
56
+ return accounts[0];
57
+ }
58
+ function buildTypedDataForAuthorization(authorization, paymentRequirements) {
59
+ const chainId = getChainIdForNetwork(paymentRequirements.network);
60
+ const verifyingContract = paymentRequirements.asset;
61
+ const domain = {
62
+ name: "USD Coin",
63
+ version: "2",
64
+ chainId,
65
+ verifyingContract
66
+ };
67
+ const types = {
68
+ TransferWithAuthorization: [
69
+ { name: "from", type: "address" },
70
+ { name: "to", type: "address" },
71
+ { name: "value", type: "uint256" },
72
+ { name: "validAfter", type: "uint256" },
73
+ { name: "validBefore", type: "uint256" },
74
+ { name: "nonce", type: "bytes32" }
75
+ ]
76
+ };
77
+ return {
78
+ domain,
79
+ types,
80
+ primaryType: "TransferWithAuthorization",
81
+ message: authorization
82
+ };
83
+ }
84
+ async function signAuthorizationWithProvider(provider, address, authorization, paymentRequirements) {
85
+ const p = provider;
86
+ if (!p || typeof p.request !== "function") {
87
+ throw new Error("provider must implement EIP-1193 request()");
88
+ }
89
+ const typedData = buildTypedDataForAuthorization(
90
+ authorization,
91
+ paymentRequirements
92
+ );
93
+ console.log("[SDK DEBUG] Signing with address:", address);
94
+ console.log("[SDK DEBUG] Authorization.from:", authorization.from);
95
+ console.log("[SDK DEBUG] Match:", address.toLowerCase() === authorization.from.toLowerCase());
96
+ console.log("[SDK DEBUG] EIP-712 domain:", typedData.domain);
97
+ const params = [address, JSON.stringify(typedData)];
98
+ const signature = await p.request({
99
+ method: "eth_signTypedData_v4",
100
+ params
101
+ });
102
+ console.log("[SDK DEBUG] Signature created:", signature);
103
+ if (typeof signature !== "string" || !signature.startsWith("0x")) {
104
+ throw new Error("Invalid signature returned from provider");
105
+ }
106
+ return signature;
107
+ }
108
+ function createPaymentClient(config) {
109
+ const {
110
+ resourceUrl,
111
+ facilitatorUrl,
112
+ provider,
113
+ userAddress: userAddressOverride,
114
+ projectKey
115
+ } = config;
116
+ if (!resourceUrl) {
117
+ throw new Error("resourceUrl is required");
118
+ }
119
+ if (!facilitatorUrl) {
120
+ throw new Error("facilitatorUrl is required");
121
+ }
122
+ if (!provider) {
123
+ throw new Error("provider is required (e.g. window.ethereum)");
124
+ }
125
+ return {
126
+ async callWithPayment(path, options) {
127
+ const method = options?.method ?? "GET";
128
+ const headers = {
129
+ ...options?.headers ?? {}
130
+ };
131
+ let body;
132
+ if (options?.body !== void 0) {
133
+ headers["Content-Type"] = headers["Content-Type"] ?? "application/json";
134
+ body = JSON.stringify(options.body);
135
+ }
136
+ const initialUrl = joinUrl(resourceUrl, path);
137
+ const initialRes = await fetch(initialUrl, {
138
+ method,
139
+ headers,
140
+ body
141
+ });
142
+ if (initialRes.status !== 402) {
143
+ const json = await initialRes.json().catch((err) => {
144
+ console.error("[x402] Failed to parse initial response JSON:", err);
145
+ return null;
146
+ });
147
+ return {
148
+ response: json,
149
+ txHash: void 0
150
+ };
151
+ }
152
+ const bodyJson = await initialRes.json();
153
+ const paymentRequirements = bodyJson.paymentRequirements;
154
+ if (!paymentRequirements) {
155
+ throw new Error(
156
+ "402 response did not include paymentRequirements field"
157
+ );
158
+ }
159
+ const fromAddress = userAddressOverride ?? await getUserAddressFromProvider(provider);
160
+ console.log("[SDK DEBUG] fromAddress determined:", fromAddress);
161
+ console.log("[SDK DEBUG] userAddressOverride:", userAddressOverride);
162
+ const nowSec = Math.floor(Date.now() / 1e3);
163
+ const validAfter = "0";
164
+ const validBefore = String(nowSec + 10 * 60);
165
+ const nonce = randomBytes32Hex();
166
+ const valueAtomic = options?.valueOverrideAtomic ?? paymentRequirements.maxAmountRequired;
167
+ const authorization = {
168
+ from: fromAddress,
169
+ to: paymentRequirements.payTo,
170
+ value: valueAtomic,
171
+ validAfter,
172
+ validBefore,
173
+ nonce
174
+ };
175
+ const signature = await signAuthorizationWithProvider(
176
+ provider,
177
+ fromAddress,
178
+ authorization,
179
+ paymentRequirements
180
+ );
181
+ const paymentHeaderObject = {
182
+ x402Version: 1,
183
+ scheme: paymentRequirements.scheme,
184
+ network: paymentRequirements.network,
185
+ payload: {
186
+ signature,
187
+ authorization
188
+ }
189
+ };
190
+ const paymentHeader = encodeJsonToBase64(paymentHeaderObject);
191
+ const settleUrl = joinUrl(facilitatorUrl, "/settle");
192
+ const settleRes = await fetch(settleUrl, {
193
+ method: "POST",
194
+ headers: {
195
+ "Content-Type": "application/json",
196
+ ...projectKey ? { "X-Project-Key": projectKey } : {}
197
+ },
198
+ body: JSON.stringify({
199
+ x402Version: 1,
200
+ paymentHeader,
201
+ paymentRequirements
202
+ })
203
+ });
204
+ if (!settleRes.ok) {
205
+ const text = await settleRes.text().catch((err) => {
206
+ console.error("[x402] Failed to read settle response text:", err);
207
+ return "";
208
+ });
209
+ throw new Error(
210
+ `Facilitator /settle failed with HTTP ${settleRes.status}: ${text}`
211
+ );
212
+ }
213
+ const settleJson = await settleRes.json();
214
+ if (!settleJson.success) {
215
+ throw new Error(
216
+ `Facilitator /settle returned error: ${settleJson.error ?? "unknown error"}`
217
+ );
218
+ }
219
+ const txHash = settleJson.txHash ?? void 0;
220
+ const retryHeaders = {
221
+ ...headers,
222
+ "X-PAYMENT": paymentHeader
223
+ };
224
+ const retryRes = await fetch(initialUrl, {
225
+ method,
226
+ headers: retryHeaders,
227
+ body
228
+ });
229
+ if (!retryRes.ok) {
230
+ const text = await retryRes.text().catch((err) => {
231
+ console.error("[x402] Failed to read retry response text:", err);
232
+ return "";
233
+ });
234
+ throw new Error(
235
+ `Protected request with X-PAYMENT failed: HTTP ${retryRes.status} ${text}`
236
+ );
237
+ }
238
+ const finalJson = await retryRes.json();
239
+ return {
240
+ response: finalJson,
241
+ txHash,
242
+ paymentHeader,
243
+ paymentRequirements
244
+ };
245
+ }
246
+ };
247
+ }
248
+
249
+ // src/client/createMantleClient.ts
250
+ function createMantleClient(config) {
251
+ const resourceUrl = config?.resourceUrl ?? (typeof window !== "undefined" ? window.location.origin : "");
252
+ const facilitatorUrl = config?.facilitatorUrl ?? (typeof process !== "undefined" ? process.env?.NEXT_PUBLIC_FACILITATOR_URL : void 0) ?? "http://localhost:8080";
253
+ return {
254
+ async postWithPayment(url, body) {
255
+ const account = await config?.getAccount?.();
256
+ if (!account) {
257
+ throw new Error(
258
+ "Wallet not connected. Please connect your wallet first."
259
+ );
260
+ }
261
+ const provider = config?.getProvider?.();
262
+ if (!provider) {
263
+ throw new Error("Wallet provider not available");
264
+ }
265
+ const client = createPaymentClient({
266
+ resourceUrl,
267
+ facilitatorUrl,
268
+ provider,
269
+ userAddress: account,
270
+ projectKey: config?.projectKey
271
+ });
272
+ const result = await client.callWithPayment(url, {
273
+ method: "POST",
274
+ body
275
+ });
276
+ return result.response;
277
+ }
278
+ };
279
+ }
280
+
281
+ export {
282
+ createPaymentClient,
283
+ createMantleClient
284
+ };