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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (70) hide show
  1. package/dist/chunk-23QNUJIB.js +136 -0
  2. package/dist/chunk-6GLR5EBK.js +96 -0
  3. package/dist/chunk-BRGW36P7.js +211 -0
  4. package/dist/chunk-E46A7I6B.js +274 -0
  5. package/dist/chunk-FHU6CFHF.js +0 -0
  6. package/dist/chunk-GHUWTX7J.js +66 -0
  7. package/dist/chunk-HEZZ74SI.js +62 -0
  8. package/dist/chunk-NQWSCY44.js +70 -0
  9. package/dist/chunk-PCJEJYP6.js +68 -0
  10. package/dist/chunk-PPVS3X5Z.js +99 -0
  11. package/dist/chunk-U73CZU3X.js +237 -0
  12. package/dist/chunk-WAKJRVUP.js +135 -0
  13. package/dist/chunk-WFUDGBKK.js +68 -0
  14. package/dist/chunk-WO2MYZXT.js +0 -0
  15. package/dist/client.d.cts +4 -4
  16. package/dist/client.d.ts +4 -4
  17. package/dist/client.js +2 -2
  18. package/dist/constants-0ncqvV_O.d.ts +17 -0
  19. package/dist/constants-CsIL25uQ.d.cts +17 -0
  20. package/dist/createMantleClient-CO0uWPb-.d.cts +87 -0
  21. package/dist/createMantleClient-CuiPsTa6.d.ts +87 -0
  22. package/dist/express-Ck7eryef.d.cts +66 -0
  23. package/dist/express-CmEg5hR3.d.ts +66 -0
  24. package/dist/express-D8EwEcOL.d.ts +66 -0
  25. package/dist/express-eQOPxfnI.d.cts +66 -0
  26. package/dist/index.cjs +186 -109
  27. package/dist/index.d.cts +6 -4
  28. package/dist/index.d.ts +6 -4
  29. package/dist/index.js +6 -4
  30. package/dist/nextjs-Bp8DxYDN.d.ts +45 -0
  31. package/dist/nextjs-CliiaTPe.d.cts +45 -0
  32. package/dist/nextjs-D7t-BC4N.d.ts +45 -0
  33. package/dist/nextjs-Duecps0q.d.cts +45 -0
  34. package/dist/nextjs-TFhFiQuL.d.ts +45 -0
  35. package/dist/nextjs-ZO2J9mdo.d.cts +45 -0
  36. package/dist/react.cjs +3 -2
  37. package/dist/react.d.cts +7 -4
  38. package/dist/react.d.ts +7 -4
  39. package/dist/react.js +3 -3
  40. package/dist/server-express.cjs +368 -0
  41. package/dist/server-express.d.cts +5 -0
  42. package/dist/server-express.d.ts +5 -0
  43. package/dist/server-express.js +13 -0
  44. package/dist/server-nextjs.cjs +339 -0
  45. package/dist/server-nextjs.d.cts +5 -0
  46. package/dist/server-nextjs.d.ts +5 -0
  47. package/dist/server-nextjs.js +11 -0
  48. package/dist/server-web.cjs +339 -0
  49. package/dist/server-web.d.cts +4 -0
  50. package/dist/server-web.d.ts +4 -0
  51. package/dist/server-web.js +11 -0
  52. package/dist/server.cjs +316 -111
  53. package/dist/server.d.cts +67 -104
  54. package/dist/server.d.ts +67 -104
  55. package/dist/server.js +29 -5
  56. package/dist/types-BFUqKBBO.d.cts +63 -0
  57. package/dist/types-BFUqKBBO.d.ts +63 -0
  58. package/dist/types-C7EPJ6Hd.d.ts +85 -0
  59. package/dist/types-CEttmr1U.d.cts +97 -0
  60. package/dist/types-CoOdbZSp.d.cts +97 -0
  61. package/dist/types-CqQ6OgRi.d.ts +85 -0
  62. package/dist/types-CrOsOHcX.d.cts +85 -0
  63. package/dist/types-D20K36pc.d.ts +97 -0
  64. package/dist/types-DTzov_EE.d.ts +97 -0
  65. package/dist/types-xkNm0uzE.d.cts +85 -0
  66. package/dist/web-standards-BNQyWzBC.d.cts +77 -0
  67. package/dist/web-standards-C3D2vdTg.d.ts +77 -0
  68. package/dist/web-standards-D8j1kZxd.d.ts +77 -0
  69. package/dist/web-standards-DOYp0UDT.d.cts +77 -0
  70. package/package.json +49 -2
@@ -0,0 +1,136 @@
1
+ import {
2
+ createMantleClient
3
+ } from "./chunk-E46A7I6B.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
+ const shouldAutoConnect = options?.autoConnect !== false;
92
+ useEffect(() => {
93
+ if (shouldAutoConnect) {
94
+ connect().catch((err) => {
95
+ console.warn("[useEthersWallet] Auto-connect failed:", err);
96
+ });
97
+ }
98
+ }, [shouldAutoConnect, connect]);
99
+ return {
100
+ address,
101
+ isConnected,
102
+ provider,
103
+ chainId,
104
+ connect,
105
+ disconnect,
106
+ error
107
+ };
108
+ }
109
+
110
+ // src/client/react/useMantleX402.ts
111
+ function useMantleX402(opts) {
112
+ const { address, isConnected } = useEthersWallet({
113
+ autoConnect: opts?.autoConnect ?? false
114
+ });
115
+ const client = createMantleClient({
116
+ facilitatorUrl: opts?.facilitatorUrl,
117
+ resourceUrl: opts?.resourceUrl,
118
+ projectKey: opts?.projectKey,
119
+ getAccount: () => {
120
+ if (!isConnected || !address) return void 0;
121
+ return address;
122
+ },
123
+ getProvider: () => {
124
+ if (typeof window !== "undefined" && window.ethereum) {
125
+ return window.ethereum;
126
+ }
127
+ return void 0;
128
+ }
129
+ });
130
+ return client;
131
+ }
132
+
133
+ export {
134
+ useEthersWallet,
135
+ useMantleX402
136
+ };
@@ -0,0 +1,96 @@
1
+ import {
2
+ buildRouteKey,
3
+ checkPayment
4
+ } from "./chunk-BRGW36P7.js";
5
+ import {
6
+ MANTLE_DEFAULTS,
7
+ __export,
8
+ getDefaultAssetForNetwork,
9
+ usdCentsToAtomic
10
+ } from "./chunk-HEZZ74SI.js";
11
+
12
+ // src/server/adapters/express.ts
13
+ var express_exports = {};
14
+ __export(express_exports, {
15
+ createPaymentMiddleware: () => createPaymentMiddleware,
16
+ mantlePaywall: () => mantlePaywall
17
+ });
18
+ function createPaymentMiddleware(config) {
19
+ const { facilitatorUrl, receiverAddress, routes, onPaymentSettled, telemetry } = config;
20
+ if (!facilitatorUrl) {
21
+ throw new Error("facilitatorUrl is required");
22
+ }
23
+ if (!receiverAddress) {
24
+ throw new Error("receiverAddress is required");
25
+ }
26
+ if (!routes || Object.keys(routes).length === 0) {
27
+ throw new Error("routes config must not be empty");
28
+ }
29
+ return async function paymentMiddleware(req, res, next) {
30
+ const routeKey = buildRouteKey(req.method, req.path);
31
+ const routeConfig = routes[routeKey];
32
+ if (!routeConfig) {
33
+ next();
34
+ return;
35
+ }
36
+ const { priceUsdCents, network } = routeConfig;
37
+ const assetConfig = getDefaultAssetForNetwork(network);
38
+ const maxAmountRequiredBigInt = usdCentsToAtomic(
39
+ priceUsdCents,
40
+ assetConfig.decimals
41
+ );
42
+ const paymentRequirements = {
43
+ scheme: "exact",
44
+ network,
45
+ asset: assetConfig.address,
46
+ maxAmountRequired: maxAmountRequiredBigInt.toString(),
47
+ payTo: receiverAddress,
48
+ price: `$${(priceUsdCents / 100).toFixed(2)}`,
49
+ currency: "USD"
50
+ };
51
+ const paymentHeader = req.header("X-PAYMENT") || req.header("x-payment") || null;
52
+ const result = await checkPayment({
53
+ paymentHeader,
54
+ paymentRequirements,
55
+ facilitatorUrl,
56
+ routeKey,
57
+ network,
58
+ asset: assetConfig.address,
59
+ telemetry,
60
+ onPaymentSettled
61
+ });
62
+ if (!result.isValid) {
63
+ res.status(result.statusCode).json(result.responseBody);
64
+ return;
65
+ }
66
+ next();
67
+ };
68
+ }
69
+ function mantlePaywall(opts) {
70
+ const { priceUsd, payTo, facilitatorUrl, telemetry, onPaymentSettled } = opts;
71
+ const priceUsdCents = Math.round(priceUsd * 100);
72
+ return async (req, res, next) => {
73
+ const method = (req.method || "GET").toUpperCase();
74
+ const path = req.path || "/";
75
+ const routeKey = `${method} ${path}`;
76
+ const middleware = createPaymentMiddleware({
77
+ facilitatorUrl: facilitatorUrl || MANTLE_DEFAULTS.FACILITATOR_URL,
78
+ receiverAddress: payTo,
79
+ routes: {
80
+ [routeKey]: {
81
+ priceUsdCents,
82
+ network: MANTLE_DEFAULTS.NETWORK
83
+ }
84
+ },
85
+ telemetry,
86
+ onPaymentSettled
87
+ });
88
+ return middleware(req, res, next);
89
+ };
90
+ }
91
+
92
+ export {
93
+ createPaymentMiddleware,
94
+ mantlePaywall,
95
+ express_exports
96
+ };
@@ -0,0 +1,211 @@
1
+ import {
2
+ getDefaultAssetForNetwork
3
+ } from "./chunk-HEZZ74SI.js";
4
+
5
+ // src/server/core/utils.ts
6
+ function decodePaymentHeader(paymentHeaderBase64) {
7
+ try {
8
+ if (typeof Buffer !== "undefined") {
9
+ const json = Buffer.from(paymentHeaderBase64, "base64").toString("utf8");
10
+ return JSON.parse(json);
11
+ }
12
+ if (typeof atob === "function") {
13
+ const json = atob(paymentHeaderBase64);
14
+ return JSON.parse(json);
15
+ }
16
+ throw new Error("No base64 decoding available in this environment");
17
+ } catch (err) {
18
+ const msg = err instanceof Error ? err.message : "Unknown error";
19
+ throw new Error(`Failed to decode paymentHeader: ${msg}`);
20
+ }
21
+ }
22
+ function buildRouteKey(method, path) {
23
+ const normalizedMethod = (method || "GET").toUpperCase();
24
+ const normalizedPath = path || "/";
25
+ return `${normalizedMethod} ${normalizedPath}`;
26
+ }
27
+
28
+ // src/server/constants.ts
29
+ var DEFAULT_TELEMETRY_ENDPOINT = void 0;
30
+
31
+ // src/server/telemetry.ts
32
+ function createTelemetryEvent(entry, config) {
33
+ const assetConfig = getDefaultAssetForNetwork(entry.network);
34
+ return {
35
+ event: "payment_verified",
36
+ ts: entry.timestamp,
37
+ projectKey: config.projectKey,
38
+ network: entry.network,
39
+ buyer: entry.from,
40
+ payTo: entry.to,
41
+ amountAtomic: entry.valueAtomic,
42
+ asset: entry.asset,
43
+ decimals: assetConfig.decimals,
44
+ nonce: entry.id,
45
+ route: entry.route ?? "unknown",
46
+ // Facilitator metadata
47
+ facilitatorType: "hosted",
48
+ // SDK always uses hosted mode
49
+ facilitatorUrl: entry.facilitatorUrl,
50
+ // From PaymentLogEntry
51
+ // facilitatorAddress is undefined for SDK (not available)
52
+ // Optional metadata
53
+ txHash: entry.txHash,
54
+ priceUsd: entry.paymentRequirements?.price
55
+ };
56
+ }
57
+ async function sendTelemetry(event, endpoint) {
58
+ const targetEndpoint = endpoint ?? DEFAULT_TELEMETRY_ENDPOINT;
59
+ if (!targetEndpoint) {
60
+ return;
61
+ }
62
+ try {
63
+ const response = await fetch(targetEndpoint, {
64
+ method: "POST",
65
+ headers: {
66
+ "Content-Type": "application/json",
67
+ "Authorization": `Bearer ${event.projectKey}`
68
+ },
69
+ body: JSON.stringify(event)
70
+ });
71
+ if (!response.ok) {
72
+ console.warn(
73
+ `[x402-telemetry] Failed to send event: HTTP ${response.status}`
74
+ );
75
+ }
76
+ } catch (err) {
77
+ console.error("[x402-telemetry] Error sending telemetry:", err);
78
+ }
79
+ }
80
+
81
+ // src/server/core/verifyPayment.ts
82
+ async function checkPayment(input) {
83
+ const {
84
+ paymentHeader,
85
+ paymentRequirements,
86
+ facilitatorUrl,
87
+ routeKey,
88
+ network,
89
+ asset,
90
+ telemetry,
91
+ onPaymentSettled
92
+ } = input;
93
+ if (!paymentHeader) {
94
+ return {
95
+ status: "require_payment",
96
+ statusCode: 402,
97
+ responseBody: {
98
+ error: "Payment Required",
99
+ paymentRequirements,
100
+ paymentHeader: null
101
+ },
102
+ isValid: false
103
+ };
104
+ }
105
+ try {
106
+ const verifyUrl = `${facilitatorUrl.replace(/\/+$/, "")}/verify`;
107
+ const verifyRes = await fetch(verifyUrl, {
108
+ method: "POST",
109
+ headers: {
110
+ "Content-Type": "application/json"
111
+ },
112
+ body: JSON.stringify({
113
+ x402Version: 1,
114
+ paymentHeader,
115
+ paymentRequirements
116
+ })
117
+ });
118
+ if (!verifyRes.ok) {
119
+ const text = await verifyRes.text().catch(() => "");
120
+ console.error(
121
+ "[x402-mantle-sdk] Facilitator /verify returned non-OK:",
122
+ verifyRes.status,
123
+ text
124
+ );
125
+ return {
126
+ status: "verification_error",
127
+ statusCode: 500,
128
+ responseBody: {
129
+ error: "Payment verification error",
130
+ details: `Facilitator responded with HTTP ${verifyRes.status}`
131
+ },
132
+ isValid: false
133
+ };
134
+ }
135
+ const verifyJson = await verifyRes.json();
136
+ if (!verifyJson.isValid) {
137
+ return {
138
+ status: "invalid_payment",
139
+ statusCode: 402,
140
+ responseBody: {
141
+ error: "Payment verification failed",
142
+ invalidReason: verifyJson.invalidReason ?? null,
143
+ paymentRequirements,
144
+ paymentHeader: null
145
+ },
146
+ isValid: false
147
+ };
148
+ }
149
+ if (onPaymentSettled) {
150
+ try {
151
+ const headerObj = decodePaymentHeader(paymentHeader);
152
+ const { authorization } = headerObj.payload;
153
+ const assetConfig = getDefaultAssetForNetwork(network);
154
+ const logEntry = {
155
+ id: authorization.nonce,
156
+ from: authorization.from,
157
+ to: authorization.to,
158
+ valueAtomic: authorization.value,
159
+ network,
160
+ asset,
161
+ route: routeKey,
162
+ timestamp: Date.now(),
163
+ facilitatorUrl,
164
+ paymentRequirements
165
+ };
166
+ onPaymentSettled(logEntry);
167
+ if (telemetry) {
168
+ const event = createTelemetryEvent(logEntry, telemetry);
169
+ sendTelemetry(event, telemetry.endpoint).catch(
170
+ (err) => console.error("[x402-telemetry] Async send failed:", err)
171
+ );
172
+ }
173
+ } catch (err) {
174
+ console.error(
175
+ "[x402-mantle-sdk] Error calling onPaymentSettled hook:",
176
+ err
177
+ );
178
+ }
179
+ }
180
+ return {
181
+ status: "verified",
182
+ statusCode: 200,
183
+ responseBody: null,
184
+ isValid: true
185
+ };
186
+ } catch (err) {
187
+ console.error(
188
+ "[x402-mantle-sdk] Error while calling facilitator /verify:",
189
+ err
190
+ );
191
+ const message = err instanceof Error ? err.message : "Unknown verification error";
192
+ return {
193
+ status: "verification_error",
194
+ statusCode: 500,
195
+ responseBody: {
196
+ error: "Payment verification error",
197
+ details: message
198
+ },
199
+ isValid: false
200
+ };
201
+ }
202
+ }
203
+
204
+ export {
205
+ decodePaymentHeader,
206
+ buildRouteKey,
207
+ DEFAULT_TELEMETRY_ENDPOINT,
208
+ createTelemetryEvent,
209
+ sendTelemetry,
210
+ checkPayment
211
+ };
@@ -0,0 +1,274 @@
1
+ import {
2
+ __require,
3
+ getChainIdForNetwork
4
+ } from "./chunk-HEZZ74SI.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
+ function buildTypedDataForAuthorization(authorization, paymentRequirements) {
46
+ const chainId = getChainIdForNetwork(paymentRequirements.network);
47
+ const verifyingContract = paymentRequirements.asset;
48
+ const domain = {
49
+ name: "USD Coin",
50
+ version: "2",
51
+ chainId,
52
+ verifyingContract
53
+ };
54
+ const types = {
55
+ TransferWithAuthorization: [
56
+ { name: "from", type: "address" },
57
+ { name: "to", type: "address" },
58
+ { name: "value", type: "uint256" },
59
+ { name: "validAfter", type: "uint256" },
60
+ { name: "validBefore", type: "uint256" },
61
+ { name: "nonce", type: "bytes32" }
62
+ ]
63
+ };
64
+ return {
65
+ domain,
66
+ types,
67
+ primaryType: "TransferWithAuthorization",
68
+ message: authorization
69
+ };
70
+ }
71
+ async function signAuthorizationWithProvider(provider, authorization, paymentRequirements) {
72
+ const { BrowserProvider } = await import("ethers");
73
+ const chainId = getChainIdForNetwork(paymentRequirements.network);
74
+ const browserProvider = new BrowserProvider(provider, chainId);
75
+ const signer = await browserProvider.getSigner();
76
+ const from = await signer.getAddress();
77
+ const authWithFrom = {
78
+ ...authorization,
79
+ from
80
+ };
81
+ const typedData = buildTypedDataForAuthorization(
82
+ authWithFrom,
83
+ paymentRequirements
84
+ );
85
+ const signature = await signer.signTypedData(
86
+ typedData.domain,
87
+ typedData.types,
88
+ typedData.message
89
+ );
90
+ return { signature, from };
91
+ }
92
+ function createPaymentClient(config) {
93
+ const {
94
+ resourceUrl,
95
+ facilitatorUrl,
96
+ provider,
97
+ userAddress: userAddressOverride,
98
+ projectKey
99
+ } = config;
100
+ if (!resourceUrl) {
101
+ throw new Error("resourceUrl is required");
102
+ }
103
+ if (!facilitatorUrl) {
104
+ throw new Error("facilitatorUrl is required");
105
+ }
106
+ if (!provider) {
107
+ throw new Error("provider is required (e.g. window.ethereum)");
108
+ }
109
+ return {
110
+ async callWithPayment(path, options) {
111
+ const method = options?.method ?? "GET";
112
+ const headers = {
113
+ ...options?.headers ?? {}
114
+ };
115
+ let body;
116
+ if (options?.body !== void 0) {
117
+ headers["Content-Type"] = headers["Content-Type"] ?? "application/json";
118
+ body = JSON.stringify(options.body);
119
+ }
120
+ const initialUrl = joinUrl(resourceUrl, path);
121
+ const initialRes = await fetch(initialUrl, {
122
+ method,
123
+ headers,
124
+ body
125
+ });
126
+ if (initialRes.status !== 402) {
127
+ const json = await initialRes.json().catch((err) => {
128
+ console.error("[x402] Failed to parse initial response JSON:", err);
129
+ return null;
130
+ });
131
+ return {
132
+ response: json,
133
+ txHash: void 0
134
+ };
135
+ }
136
+ const bodyJson = await initialRes.json();
137
+ const paymentRequirements = bodyJson.paymentRequirements;
138
+ if (!paymentRequirements) {
139
+ throw new Error(
140
+ "402 response did not include paymentRequirements field"
141
+ );
142
+ }
143
+ const nowSec = Math.floor(Date.now() / 1e3);
144
+ const validAfter = "0";
145
+ const validBefore = String(nowSec + 10 * 60);
146
+ const nonce = randomBytes32Hex();
147
+ const valueAtomic = options?.valueOverrideAtomic ?? paymentRequirements.maxAmountRequired;
148
+ let authorization = {
149
+ from: "0x0000000000000000000000000000000000000000",
150
+ to: paymentRequirements.payTo,
151
+ value: valueAtomic,
152
+ validAfter,
153
+ validBefore,
154
+ nonce
155
+ };
156
+ const { signature, from } = await signAuthorizationWithProvider(
157
+ provider,
158
+ authorization,
159
+ paymentRequirements
160
+ );
161
+ authorization = {
162
+ ...authorization,
163
+ from
164
+ };
165
+ if (userAddressOverride && userAddressOverride.toLowerCase() !== from.toLowerCase()) {
166
+ console.warn(
167
+ "[SDK WARNING] userAddress override differs from signer address",
168
+ { override: userAddressOverride, signer: from }
169
+ );
170
+ }
171
+ const paymentHeaderObject = {
172
+ x402Version: 1,
173
+ scheme: paymentRequirements.scheme,
174
+ network: paymentRequirements.network,
175
+ payload: {
176
+ signature,
177
+ authorization
178
+ }
179
+ };
180
+ const paymentHeader = encodeJsonToBase64(paymentHeaderObject);
181
+ const settleUrl = joinUrl(facilitatorUrl, "/settle");
182
+ const settleRes = await fetch(settleUrl, {
183
+ method: "POST",
184
+ headers: {
185
+ "Content-Type": "application/json",
186
+ ...projectKey ? { "X-Project-Key": projectKey } : {}
187
+ },
188
+ body: JSON.stringify({
189
+ x402Version: 1,
190
+ paymentHeader,
191
+ paymentRequirements
192
+ })
193
+ });
194
+ if (!settleRes.ok) {
195
+ const text = await settleRes.text().catch((err) => {
196
+ console.error("[x402] Failed to read settle response text:", err);
197
+ return "";
198
+ });
199
+ throw new Error(
200
+ `Facilitator /settle failed with HTTP ${settleRes.status}: ${text}`
201
+ );
202
+ }
203
+ const settleJson = await settleRes.json();
204
+ if (!settleJson.success) {
205
+ throw new Error(
206
+ `Facilitator /settle returned error: ${settleJson.error ?? "unknown error"}`
207
+ );
208
+ }
209
+ const txHash = settleJson.txHash ?? void 0;
210
+ const retryHeaders = {
211
+ ...headers,
212
+ "X-PAYMENT": paymentHeader
213
+ };
214
+ const retryRes = await fetch(initialUrl, {
215
+ method,
216
+ headers: retryHeaders,
217
+ body
218
+ });
219
+ if (!retryRes.ok) {
220
+ const text = await retryRes.text().catch((err) => {
221
+ console.error("[x402] Failed to read retry response text:", err);
222
+ return "";
223
+ });
224
+ throw new Error(
225
+ `Protected request with X-PAYMENT failed: HTTP ${retryRes.status} ${text}`
226
+ );
227
+ }
228
+ const finalJson = await retryRes.json();
229
+ return {
230
+ response: finalJson,
231
+ txHash,
232
+ paymentHeader,
233
+ paymentRequirements
234
+ };
235
+ }
236
+ };
237
+ }
238
+
239
+ // src/client/createMantleClient.ts
240
+ function createMantleClient(config) {
241
+ const resourceUrl = config?.resourceUrl ?? (typeof window !== "undefined" ? window.location.origin : "");
242
+ const facilitatorUrl = config?.facilitatorUrl ?? (typeof process !== "undefined" ? process.env?.NEXT_PUBLIC_FACILITATOR_URL : void 0) ?? "http://localhost:8080";
243
+ return {
244
+ async postWithPayment(url, body) {
245
+ const account = await config?.getAccount?.();
246
+ if (!account) {
247
+ throw new Error(
248
+ "Wallet not connected. Please connect your wallet first."
249
+ );
250
+ }
251
+ const provider = config?.getProvider?.();
252
+ if (!provider) {
253
+ throw new Error("Wallet provider not available");
254
+ }
255
+ const client = createPaymentClient({
256
+ resourceUrl,
257
+ facilitatorUrl,
258
+ provider,
259
+ userAddress: account,
260
+ projectKey: config?.projectKey
261
+ });
262
+ const result = await client.callWithPayment(url, {
263
+ method: "POST",
264
+ body
265
+ });
266
+ return result;
267
+ }
268
+ };
269
+ }
270
+
271
+ export {
272
+ createPaymentClient,
273
+ createMantleClient
274
+ };