@puga-labs/x402-mantle-sdk 0.2.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 (95) 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-CTI5CRDY.js +274 -0
  5. package/dist/chunk-DA6ZBXNO.js +275 -0
  6. package/dist/chunk-E46A7I6B.js +274 -0
  7. package/dist/chunk-FD4HG7KR.js +135 -0
  8. package/dist/chunk-FHU6CFHF.js +0 -0
  9. package/dist/chunk-GHUWTX7J.js +66 -0
  10. package/dist/chunk-GWVWPS3R.js +277 -0
  11. package/dist/chunk-HEZZ74SI.js +62 -0
  12. package/dist/chunk-HTZ3QFY4.js +135 -0
  13. package/dist/chunk-MQALBRGV.js +135 -0
  14. package/dist/chunk-NQWSCY44.js +70 -0
  15. package/dist/chunk-PCJEJYP6.js +68 -0
  16. package/dist/chunk-PPVS3X5Z.js +99 -0
  17. package/dist/chunk-PYIYE3HI.js +135 -0
  18. package/dist/chunk-Q6SPMEIW.js +235 -0
  19. package/dist/chunk-RNKXSBT7.js +135 -0
  20. package/dist/chunk-SPCXFN7C.js +284 -0
  21. package/dist/chunk-T5DRYLNB.js +135 -0
  22. package/dist/chunk-TSEE5NSJ.js +297 -0
  23. package/dist/chunk-U73CZU3X.js +237 -0
  24. package/dist/chunk-WAKJRVUP.js +135 -0
  25. package/dist/chunk-WELDWRDX.js +307 -0
  26. package/dist/chunk-WFUDGBKK.js +68 -0
  27. package/dist/chunk-WO2MYZXT.js +0 -0
  28. package/dist/chunk-XAQGMFSR.js +56 -0
  29. package/dist/client.cjs +328 -0
  30. package/dist/client.d.cts +17 -0
  31. package/dist/client.d.ts +17 -0
  32. package/dist/client.js +12 -0
  33. package/dist/constants-0ncqvV_O.d.ts +17 -0
  34. package/dist/constants-C7aY8u5b.d.cts +77 -0
  35. package/dist/constants-C7aY8u5b.d.ts +77 -0
  36. package/dist/constants-CVFF0ray.d.ts +17 -0
  37. package/dist/constants-CsIL25uQ.d.cts +17 -0
  38. package/dist/constants-DzCGK0Q3.d.cts +17 -0
  39. package/dist/createMantleClient-CO0uWPb-.d.cts +87 -0
  40. package/dist/createMantleClient-CuiPsTa6.d.ts +87 -0
  41. package/dist/createMantleClient-DS1Ghqrz.d.cts +51 -0
  42. package/dist/createMantleClient-DS1Ghqrz.d.ts +51 -0
  43. package/dist/createMantleClient-DVFkbBfS.d.ts +87 -0
  44. package/dist/createMantleClient-NN0Nitp9.d.cts +87 -0
  45. package/dist/express-Ck7eryef.d.cts +66 -0
  46. package/dist/express-CmEg5hR3.d.ts +66 -0
  47. package/dist/express-D8EwEcOL.d.ts +66 -0
  48. package/dist/express-eQOPxfnI.d.cts +66 -0
  49. package/dist/index.cjs +342 -155
  50. package/dist/index.d.cts +10 -290
  51. package/dist/index.d.ts +10 -290
  52. package/dist/index.js +18 -567
  53. package/dist/nextjs-Bp8DxYDN.d.ts +45 -0
  54. package/dist/nextjs-CliiaTPe.d.cts +45 -0
  55. package/dist/nextjs-D7t-BC4N.d.ts +45 -0
  56. package/dist/nextjs-Duecps0q.d.cts +45 -0
  57. package/dist/nextjs-TFhFiQuL.d.ts +45 -0
  58. package/dist/nextjs-ZO2J9mdo.d.cts +45 -0
  59. package/dist/react.cjs +454 -0
  60. package/dist/react.d.cts +93 -0
  61. package/dist/react.d.ts +93 -0
  62. package/dist/react.js +10 -0
  63. package/dist/server-express.cjs +368 -0
  64. package/dist/server-express.d.cts +5 -0
  65. package/dist/server-express.d.ts +5 -0
  66. package/dist/server-express.js +13 -0
  67. package/dist/server-nextjs.cjs +339 -0
  68. package/dist/server-nextjs.d.cts +5 -0
  69. package/dist/server-nextjs.d.ts +5 -0
  70. package/dist/server-nextjs.js +11 -0
  71. package/dist/server-web.cjs +339 -0
  72. package/dist/server-web.d.cts +4 -0
  73. package/dist/server-web.d.ts +4 -0
  74. package/dist/server-web.js +11 -0
  75. package/dist/server.cjs +497 -0
  76. package/dist/server.d.cts +79 -0
  77. package/dist/server.d.ts +79 -0
  78. package/dist/server.js +36 -0
  79. package/dist/types-2zqbJvcz.d.cts +63 -0
  80. package/dist/types-2zqbJvcz.d.ts +63 -0
  81. package/dist/types-BFUqKBBO.d.cts +63 -0
  82. package/dist/types-BFUqKBBO.d.ts +63 -0
  83. package/dist/types-C7EPJ6Hd.d.ts +85 -0
  84. package/dist/types-CEttmr1U.d.cts +97 -0
  85. package/dist/types-CoOdbZSp.d.cts +97 -0
  86. package/dist/types-CqQ6OgRi.d.ts +85 -0
  87. package/dist/types-CrOsOHcX.d.cts +85 -0
  88. package/dist/types-D20K36pc.d.ts +97 -0
  89. package/dist/types-DTzov_EE.d.ts +97 -0
  90. package/dist/types-xkNm0uzE.d.cts +85 -0
  91. package/dist/web-standards-BNQyWzBC.d.cts +77 -0
  92. package/dist/web-standards-C3D2vdTg.d.ts +77 -0
  93. package/dist/web-standards-D8j1kZxd.d.ts +77 -0
  94. package/dist/web-standards-DOYp0UDT.d.cts +77 -0
  95. package/package.json +80 -8
@@ -0,0 +1,45 @@
1
+ import { NextRequest, NextResponse } from 'next/server';
2
+ import { M as MinimalPaywallOptions } from './types-C7EPJ6Hd.js';
3
+
4
+ /**
5
+ * Next.js App Router route handler type.
6
+ */
7
+ type NextJSHandler<T = any> = (req: NextRequest) => Promise<NextResponse<T>>;
8
+ /**
9
+ * Wrapper function that adds x402 payment verification to Next.js route handler.
10
+ */
11
+ type NextJSPaywallWrapper = <T>(handler: NextJSHandler<T>) => NextJSHandler<T>;
12
+ /**
13
+ * Create Next.js App Router middleware for x402 payment verification.
14
+ * Uses Mantle mainnet defaults (USDC, exact scheme, etc.).
15
+ *
16
+ * @example
17
+ * ```typescript
18
+ * // app/api/generate-image/route.ts
19
+ * import { mantlePaywall } from '@puga-labs/x402-mantle-sdk/server/nextjs'
20
+ *
21
+ * const pay = mantlePaywall({
22
+ * priceUsd: 0.01,
23
+ * payTo: process.env.PAY_TO as `0x${string}`,
24
+ * });
25
+ *
26
+ * export const POST = pay(async (req: NextRequest) => {
27
+ * const { prompt } = await req.json();
28
+ * // Your handler code here
29
+ * return NextResponse.json({ success: true });
30
+ * });
31
+ * ```
32
+ *
33
+ * @param opts - Minimal configuration (price, payTo, optional facilitator/telemetry).
34
+ * @returns Function that wraps Next.js route handlers with payment verification.
35
+ */
36
+ declare function mantlePaywall(opts: MinimalPaywallOptions): NextJSPaywallWrapper;
37
+
38
+ type nextjs_NextJSHandler<T = any> = NextJSHandler<T>;
39
+ type nextjs_NextJSPaywallWrapper = NextJSPaywallWrapper;
40
+ declare const nextjs_mantlePaywall: typeof mantlePaywall;
41
+ declare namespace nextjs {
42
+ export { type nextjs_NextJSHandler as NextJSHandler, type nextjs_NextJSPaywallWrapper as NextJSPaywallWrapper, nextjs_mantlePaywall as mantlePaywall };
43
+ }
44
+
45
+ export { type NextJSHandler as N, type NextJSPaywallWrapper as a, mantlePaywall as m, nextjs as n };
@@ -0,0 +1,45 @@
1
+ import { NextRequest, NextResponse } from 'next/server';
2
+ import { M as MinimalPaywallOptions } from './types-CrOsOHcX.cjs';
3
+
4
+ /**
5
+ * Next.js App Router route handler type.
6
+ */
7
+ type NextJSHandler<T = any> = (req: NextRequest) => Promise<NextResponse<T>>;
8
+ /**
9
+ * Wrapper function that adds x402 payment verification to Next.js route handler.
10
+ */
11
+ type NextJSPaywallWrapper = <T>(handler: NextJSHandler<T>) => NextJSHandler<T>;
12
+ /**
13
+ * Create Next.js App Router middleware for x402 payment verification.
14
+ * Uses Mantle mainnet defaults (USDC, exact scheme, etc.).
15
+ *
16
+ * @example
17
+ * ```typescript
18
+ * // app/api/generate-image/route.ts
19
+ * import { mantlePaywall } from '@puga-labs/x402-mantle-sdk/server/nextjs'
20
+ *
21
+ * const pay = mantlePaywall({
22
+ * priceUsd: 0.01,
23
+ * payTo: process.env.PAY_TO!,
24
+ * });
25
+ *
26
+ * export const POST = pay(async (req: NextRequest) => {
27
+ * const { prompt } = await req.json();
28
+ * // Your handler code here
29
+ * return NextResponse.json({ success: true });
30
+ * });
31
+ * ```
32
+ *
33
+ * @param opts - Minimal configuration (price, payTo, optional facilitator/telemetry).
34
+ * @returns Function that wraps Next.js route handlers with payment verification.
35
+ */
36
+ declare function mantlePaywall(opts: MinimalPaywallOptions): NextJSPaywallWrapper;
37
+
38
+ type nextjs_NextJSHandler<T = any> = NextJSHandler<T>;
39
+ type nextjs_NextJSPaywallWrapper = NextJSPaywallWrapper;
40
+ declare const nextjs_mantlePaywall: typeof mantlePaywall;
41
+ declare namespace nextjs {
42
+ export { type nextjs_NextJSHandler as NextJSHandler, type nextjs_NextJSPaywallWrapper as NextJSPaywallWrapper, nextjs_mantlePaywall as mantlePaywall };
43
+ }
44
+
45
+ export { type NextJSHandler as N, type NextJSPaywallWrapper as a, mantlePaywall as m, nextjs as n };
@@ -0,0 +1,45 @@
1
+ import { NextRequest, NextResponse } from 'next/server';
2
+ import { M as MinimalPaywallOptions } from './types-CqQ6OgRi.js';
3
+
4
+ /**
5
+ * Next.js App Router route handler type.
6
+ */
7
+ type NextJSHandler<T = any> = (req: NextRequest) => Promise<NextResponse<T>>;
8
+ /**
9
+ * Wrapper function that adds x402 payment verification to Next.js route handler.
10
+ */
11
+ type NextJSPaywallWrapper = <T>(handler: NextJSHandler<T>) => NextJSHandler<T>;
12
+ /**
13
+ * Create Next.js App Router middleware for x402 payment verification.
14
+ * Uses Mantle mainnet defaults (USDC, exact scheme, etc.).
15
+ *
16
+ * @example
17
+ * ```typescript
18
+ * // app/api/generate-image/route.ts
19
+ * import { mantlePaywall } from '@puga-labs/x402-mantle-sdk/server/nextjs'
20
+ *
21
+ * const pay = mantlePaywall({
22
+ * priceUsd: 0.01,
23
+ * payTo: process.env.PAY_TO!,
24
+ * });
25
+ *
26
+ * export const POST = pay(async (req: NextRequest) => {
27
+ * const { prompt } = await req.json();
28
+ * // Your handler code here
29
+ * return NextResponse.json({ success: true });
30
+ * });
31
+ * ```
32
+ *
33
+ * @param opts - Minimal configuration (price, payTo, optional facilitator/telemetry).
34
+ * @returns Function that wraps Next.js route handlers with payment verification.
35
+ */
36
+ declare function mantlePaywall(opts: MinimalPaywallOptions): NextJSPaywallWrapper;
37
+
38
+ type nextjs_NextJSHandler<T = any> = NextJSHandler<T>;
39
+ type nextjs_NextJSPaywallWrapper = NextJSPaywallWrapper;
40
+ declare const nextjs_mantlePaywall: typeof mantlePaywall;
41
+ declare namespace nextjs {
42
+ export { type nextjs_NextJSHandler as NextJSHandler, type nextjs_NextJSPaywallWrapper as NextJSPaywallWrapper, nextjs_mantlePaywall as mantlePaywall };
43
+ }
44
+
45
+ export { type NextJSHandler as N, type NextJSPaywallWrapper as a, mantlePaywall as m, nextjs as n };
@@ -0,0 +1,45 @@
1
+ import { NextRequest, NextResponse } from 'next/server';
2
+ import { M as MinimalPaywallOptions } from './types-CrOsOHcX.cjs';
3
+
4
+ /**
5
+ * Next.js App Router route handler type.
6
+ */
7
+ type NextJSHandler<T = any> = (req: NextRequest) => Promise<NextResponse<T>>;
8
+ /**
9
+ * Wrapper function that adds x402 payment verification to Next.js route handler.
10
+ */
11
+ type NextJSPaywallWrapper = <T>(handler: NextJSHandler<T>) => NextJSHandler<T>;
12
+ /**
13
+ * Create Next.js App Router middleware for x402 payment verification.
14
+ * Uses Mantle mainnet defaults (USDC, exact scheme, etc.).
15
+ *
16
+ * @example
17
+ * ```typescript
18
+ * // app/api/generate-image/route.ts
19
+ * import { mantlePaywall } from '@puga-labs/x402-mantle-sdk/server/nextjs'
20
+ *
21
+ * const pay = mantlePaywall({
22
+ * priceUsd: 0.01,
23
+ * payTo: process.env.PAY_TO as `0x${string}`,
24
+ * });
25
+ *
26
+ * export const POST = pay(async (req: NextRequest) => {
27
+ * const { prompt } = await req.json();
28
+ * // Your handler code here
29
+ * return NextResponse.json({ success: true });
30
+ * });
31
+ * ```
32
+ *
33
+ * @param opts - Minimal configuration (price, payTo, optional facilitator/telemetry).
34
+ * @returns Function that wraps Next.js route handlers with payment verification.
35
+ */
36
+ declare function mantlePaywall(opts: MinimalPaywallOptions): NextJSPaywallWrapper;
37
+
38
+ type nextjs_NextJSHandler<T = any> = NextJSHandler<T>;
39
+ type nextjs_NextJSPaywallWrapper = NextJSPaywallWrapper;
40
+ declare const nextjs_mantlePaywall: typeof mantlePaywall;
41
+ declare namespace nextjs {
42
+ export { type nextjs_NextJSHandler as NextJSHandler, type nextjs_NextJSPaywallWrapper as NextJSPaywallWrapper, nextjs_mantlePaywall as mantlePaywall };
43
+ }
44
+
45
+ export { type NextJSHandler as N, type NextJSPaywallWrapper as a, mantlePaywall as m, nextjs as n };
package/dist/react.cjs ADDED
@@ -0,0 +1,454 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // src/react.ts
31
+ var react_exports = {};
32
+ __export(react_exports, {
33
+ useEthersWallet: () => useEthersWallet,
34
+ useMantleX402: () => useMantleX402
35
+ });
36
+ module.exports = __toCommonJS(react_exports);
37
+
38
+ // src/client/react/useEthersWallet.ts
39
+ var import_react = require("react");
40
+ var import_ethers = require("ethers");
41
+ function useEthersWallet(options) {
42
+ const [address, setAddress] = (0, import_react.useState)(void 0);
43
+ const [isConnected, setIsConnected] = (0, import_react.useState)(false);
44
+ const [provider, setProvider] = (0, import_react.useState)(
45
+ void 0
46
+ );
47
+ const [chainId, setChainId] = (0, import_react.useState)(void 0);
48
+ const [error, setError] = (0, import_react.useState)(void 0);
49
+ const connect = (0, import_react.useCallback)(async () => {
50
+ try {
51
+ setError(void 0);
52
+ if (typeof window === "undefined" || !window.ethereum) {
53
+ throw new Error(
54
+ "No Ethereum wallet detected. Please install MetaMask or another wallet."
55
+ );
56
+ }
57
+ const browserProvider = new import_ethers.ethers.BrowserProvider(
58
+ window.ethereum
59
+ );
60
+ setProvider(browserProvider);
61
+ const accounts = await window.ethereum.request({
62
+ method: "eth_requestAccounts"
63
+ });
64
+ if (!accounts || accounts.length === 0) {
65
+ throw new Error("No accounts returned from wallet");
66
+ }
67
+ const userAddress = accounts[0];
68
+ setAddress(userAddress);
69
+ setIsConnected(true);
70
+ const network = await browserProvider.getNetwork();
71
+ setChainId(Number(network.chainId));
72
+ } catch (err) {
73
+ const errorObj = err instanceof Error ? err : new Error(String(err));
74
+ setError(errorObj);
75
+ setIsConnected(false);
76
+ setAddress(void 0);
77
+ setChainId(void 0);
78
+ throw errorObj;
79
+ }
80
+ }, []);
81
+ const disconnect = (0, import_react.useCallback)(() => {
82
+ setAddress(void 0);
83
+ setIsConnected(false);
84
+ setChainId(void 0);
85
+ setError(void 0);
86
+ }, []);
87
+ (0, import_react.useEffect)(() => {
88
+ if (typeof window === "undefined" || !window.ethereum) return;
89
+ const ethereum = window.ethereum;
90
+ const handleAccountsChanged = (accounts) => {
91
+ const accountsArray = accounts;
92
+ if (!accountsArray || accountsArray.length === 0) {
93
+ disconnect();
94
+ } else {
95
+ setAddress(accountsArray[0]);
96
+ setIsConnected(true);
97
+ }
98
+ };
99
+ if (ethereum.on) {
100
+ ethereum.on("accountsChanged", handleAccountsChanged);
101
+ }
102
+ return () => {
103
+ if (ethereum.removeListener) {
104
+ ethereum.removeListener("accountsChanged", handleAccountsChanged);
105
+ }
106
+ };
107
+ }, [disconnect]);
108
+ (0, import_react.useEffect)(() => {
109
+ if (typeof window === "undefined" || !window.ethereum) return;
110
+ const ethereum = window.ethereum;
111
+ const handleChainChanged = (chainIdHex) => {
112
+ const newChainId = parseInt(chainIdHex, 16);
113
+ setChainId(newChainId);
114
+ };
115
+ if (ethereum.on) {
116
+ ethereum.on("chainChanged", handleChainChanged);
117
+ }
118
+ return () => {
119
+ if (ethereum.removeListener) {
120
+ ethereum.removeListener("chainChanged", handleChainChanged);
121
+ }
122
+ };
123
+ }, []);
124
+ const shouldAutoConnect = options?.autoConnect !== false;
125
+ (0, import_react.useEffect)(() => {
126
+ if (shouldAutoConnect) {
127
+ connect().catch((err) => {
128
+ console.warn("[useEthersWallet] Auto-connect failed:", err);
129
+ });
130
+ }
131
+ }, [shouldAutoConnect, connect]);
132
+ return {
133
+ address,
134
+ isConnected,
135
+ provider,
136
+ chainId,
137
+ connect,
138
+ disconnect,
139
+ error
140
+ };
141
+ }
142
+
143
+ // src/shared/constants.ts
144
+ var MANTLE_MAINNET_NETWORK_ID = "mantle-mainnet";
145
+ var MANTLE_MAINNET_CHAIN_ID = 5e3;
146
+ var MANTLE_DEFAULTS = {
147
+ NETWORK: "mantle-mainnet",
148
+ CHAIN_ID: 5e3,
149
+ USDC_ADDRESS: "0x09Bc4E0D864854c6aFB6eB9A9cdF58aC190D0dF9",
150
+ USDC_DECIMALS: 6,
151
+ CURRENCY: "USD",
152
+ SCHEME: "exact",
153
+ FACILITATOR_URL: (typeof process !== "undefined" ? process.env?.NEXT_PUBLIC_FACILITATOR_URL : void 0) || "http://localhost:8080"
154
+ };
155
+ function getChainIdForNetwork(network) {
156
+ switch (network) {
157
+ case MANTLE_MAINNET_NETWORK_ID:
158
+ default:
159
+ return MANTLE_MAINNET_CHAIN_ID;
160
+ }
161
+ }
162
+
163
+ // src/shared/utils.ts
164
+ function encodeJsonToBase64(value) {
165
+ const json = JSON.stringify(value);
166
+ if (typeof btoa === "function") {
167
+ const bytes = new TextEncoder().encode(json);
168
+ const binString = Array.from(
169
+ bytes,
170
+ (byte) => String.fromCodePoint(byte)
171
+ ).join("");
172
+ return btoa(binString);
173
+ }
174
+ if (typeof globalThis.Buffer !== "undefined") {
175
+ return globalThis.Buffer.from(json, "utf8").toString("base64");
176
+ }
177
+ throw new Error("No base64 implementation found in this environment");
178
+ }
179
+ function randomBytes32Hex() {
180
+ if (typeof crypto !== "undefined" && "getRandomValues" in crypto) {
181
+ const arr = new Uint8Array(32);
182
+ crypto.getRandomValues(arr);
183
+ return "0x" + Array.from(arr).map((b) => b.toString(16).padStart(2, "0")).join("");
184
+ }
185
+ try {
186
+ const nodeCrypto = require("crypto");
187
+ const buf = nodeCrypto.randomBytes(32);
188
+ return "0x" + buf.toString("hex");
189
+ } catch {
190
+ throw new Error(
191
+ "No cryptographically secure random number generator found. This environment does not support crypto.getRandomValues or Node.js crypto module."
192
+ );
193
+ }
194
+ }
195
+
196
+ // src/client/paymentClient.ts
197
+ function joinUrl(base, path) {
198
+ const normalizedBase = base.replace(/\/+$/, "");
199
+ const normalizedPath = path.startsWith("/") ? path : `/${path}`;
200
+ return `${normalizedBase}${normalizedPath}`;
201
+ }
202
+ function buildTypedDataForAuthorization(authorization, paymentRequirements) {
203
+ const chainId = getChainIdForNetwork(paymentRequirements.network);
204
+ const verifyingContract = paymentRequirements.asset;
205
+ const domain = {
206
+ name: "USD Coin",
207
+ version: "2",
208
+ chainId,
209
+ verifyingContract
210
+ };
211
+ const types = {
212
+ TransferWithAuthorization: [
213
+ { name: "from", type: "address" },
214
+ { name: "to", type: "address" },
215
+ { name: "value", type: "uint256" },
216
+ { name: "validAfter", type: "uint256" },
217
+ { name: "validBefore", type: "uint256" },
218
+ { name: "nonce", type: "bytes32" }
219
+ ]
220
+ };
221
+ return {
222
+ domain,
223
+ types,
224
+ primaryType: "TransferWithAuthorization",
225
+ message: authorization
226
+ };
227
+ }
228
+ async function signAuthorizationWithProvider(provider, authorization, paymentRequirements) {
229
+ const { BrowserProvider } = await import("ethers");
230
+ const chainId = getChainIdForNetwork(paymentRequirements.network);
231
+ const browserProvider = new BrowserProvider(provider, chainId);
232
+ const signer = await browserProvider.getSigner();
233
+ const from = await signer.getAddress();
234
+ const authWithFrom = {
235
+ ...authorization,
236
+ from
237
+ };
238
+ const typedData = buildTypedDataForAuthorization(
239
+ authWithFrom,
240
+ paymentRequirements
241
+ );
242
+ const signature = await signer.signTypedData(
243
+ typedData.domain,
244
+ typedData.types,
245
+ typedData.message
246
+ );
247
+ return { signature, from };
248
+ }
249
+ function createPaymentClient(config) {
250
+ const {
251
+ resourceUrl,
252
+ facilitatorUrl,
253
+ provider,
254
+ userAddress: userAddressOverride,
255
+ projectKey
256
+ } = config;
257
+ if (!resourceUrl) {
258
+ throw new Error("resourceUrl is required");
259
+ }
260
+ if (!facilitatorUrl) {
261
+ throw new Error("facilitatorUrl is required");
262
+ }
263
+ if (!provider) {
264
+ throw new Error("provider is required (e.g. window.ethereum)");
265
+ }
266
+ return {
267
+ async callWithPayment(path, options) {
268
+ const method = options?.method ?? "GET";
269
+ const headers = {
270
+ ...options?.headers ?? {}
271
+ };
272
+ let body;
273
+ if (options?.body !== void 0) {
274
+ headers["Content-Type"] = headers["Content-Type"] ?? "application/json";
275
+ body = JSON.stringify(options.body);
276
+ }
277
+ const initialUrl = joinUrl(resourceUrl, path);
278
+ const initialRes = await fetch(initialUrl, {
279
+ method,
280
+ headers,
281
+ body
282
+ });
283
+ if (initialRes.status !== 402) {
284
+ const json = await initialRes.json().catch((err) => {
285
+ console.error("[x402] Failed to parse initial response JSON:", err);
286
+ return null;
287
+ });
288
+ return {
289
+ response: json,
290
+ txHash: void 0
291
+ };
292
+ }
293
+ const bodyJson = await initialRes.json();
294
+ const paymentRequirements = bodyJson.paymentRequirements;
295
+ if (!paymentRequirements) {
296
+ throw new Error(
297
+ "402 response did not include paymentRequirements field"
298
+ );
299
+ }
300
+ const nowSec = Math.floor(Date.now() / 1e3);
301
+ const validAfter = "0";
302
+ const validBefore = String(nowSec + 10 * 60);
303
+ const nonce = randomBytes32Hex();
304
+ const valueAtomic = options?.valueOverrideAtomic ?? paymentRequirements.maxAmountRequired;
305
+ let authorization = {
306
+ from: "0x0000000000000000000000000000000000000000",
307
+ to: paymentRequirements.payTo,
308
+ value: valueAtomic,
309
+ validAfter,
310
+ validBefore,
311
+ nonce
312
+ };
313
+ const { signature, from } = await signAuthorizationWithProvider(
314
+ provider,
315
+ authorization,
316
+ paymentRequirements
317
+ );
318
+ authorization = {
319
+ ...authorization,
320
+ from
321
+ };
322
+ if (userAddressOverride && userAddressOverride.toLowerCase() !== from.toLowerCase()) {
323
+ console.warn(
324
+ "[SDK WARNING] userAddress override differs from signer address",
325
+ { override: userAddressOverride, signer: from }
326
+ );
327
+ }
328
+ const paymentHeaderObject = {
329
+ x402Version: 1,
330
+ scheme: paymentRequirements.scheme,
331
+ network: paymentRequirements.network,
332
+ payload: {
333
+ signature,
334
+ authorization
335
+ }
336
+ };
337
+ const paymentHeader = encodeJsonToBase64(paymentHeaderObject);
338
+ const settleUrl = joinUrl(facilitatorUrl, "/settle");
339
+ const settleRes = await fetch(settleUrl, {
340
+ method: "POST",
341
+ headers: {
342
+ "Content-Type": "application/json",
343
+ ...projectKey ? { "X-Project-Key": projectKey } : {}
344
+ },
345
+ body: JSON.stringify({
346
+ x402Version: 1,
347
+ paymentHeader,
348
+ paymentRequirements
349
+ })
350
+ });
351
+ if (!settleRes.ok) {
352
+ const text = await settleRes.text().catch((err) => {
353
+ console.error("[x402] Failed to read settle response text:", err);
354
+ return "";
355
+ });
356
+ throw new Error(
357
+ `Facilitator /settle failed with HTTP ${settleRes.status}: ${text}`
358
+ );
359
+ }
360
+ const settleJson = await settleRes.json();
361
+ if (!settleJson.success) {
362
+ throw new Error(
363
+ `Facilitator /settle returned error: ${settleJson.error ?? "unknown error"}`
364
+ );
365
+ }
366
+ const txHash = settleJson.txHash ?? void 0;
367
+ const retryHeaders = {
368
+ ...headers,
369
+ "X-PAYMENT": paymentHeader
370
+ };
371
+ const retryRes = await fetch(initialUrl, {
372
+ method,
373
+ headers: retryHeaders,
374
+ body
375
+ });
376
+ if (!retryRes.ok) {
377
+ const text = await retryRes.text().catch((err) => {
378
+ console.error("[x402] Failed to read retry response text:", err);
379
+ return "";
380
+ });
381
+ throw new Error(
382
+ `Protected request with X-PAYMENT failed: HTTP ${retryRes.status} ${text}`
383
+ );
384
+ }
385
+ const finalJson = await retryRes.json();
386
+ return {
387
+ response: finalJson,
388
+ txHash,
389
+ paymentHeader,
390
+ paymentRequirements
391
+ };
392
+ }
393
+ };
394
+ }
395
+
396
+ // src/client/createMantleClient.ts
397
+ function createMantleClient(config) {
398
+ const resourceUrl = config?.resourceUrl ?? (typeof window !== "undefined" ? window.location.origin : "");
399
+ const facilitatorUrl = config?.facilitatorUrl ?? (typeof process !== "undefined" ? process.env?.NEXT_PUBLIC_FACILITATOR_URL : void 0) ?? "http://localhost:8080";
400
+ return {
401
+ async postWithPayment(url, body) {
402
+ const account = await config?.getAccount?.();
403
+ if (!account) {
404
+ throw new Error(
405
+ "Wallet not connected. Please connect your wallet first."
406
+ );
407
+ }
408
+ const provider = config?.getProvider?.();
409
+ if (!provider) {
410
+ throw new Error("Wallet provider not available");
411
+ }
412
+ const client = createPaymentClient({
413
+ resourceUrl,
414
+ facilitatorUrl,
415
+ provider,
416
+ userAddress: account,
417
+ projectKey: config?.projectKey
418
+ });
419
+ const result = await client.callWithPayment(url, {
420
+ method: "POST",
421
+ body
422
+ });
423
+ return result;
424
+ }
425
+ };
426
+ }
427
+
428
+ // src/client/react/useMantleX402.ts
429
+ function useMantleX402(opts) {
430
+ const { address, isConnected } = useEthersWallet({
431
+ autoConnect: opts?.autoConnect ?? false
432
+ });
433
+ const client = createMantleClient({
434
+ facilitatorUrl: opts?.facilitatorUrl,
435
+ resourceUrl: opts?.resourceUrl,
436
+ projectKey: opts?.projectKey,
437
+ getAccount: () => {
438
+ if (!isConnected || !address) return void 0;
439
+ return address;
440
+ },
441
+ getProvider: () => {
442
+ if (typeof window !== "undefined" && window.ethereum) {
443
+ return window.ethereum;
444
+ }
445
+ return void 0;
446
+ }
447
+ });
448
+ return client;
449
+ }
450
+ // Annotate the CommonJS export names for ESM import in node:
451
+ 0 && (module.exports = {
452
+ useEthersWallet,
453
+ useMantleX402
454
+ });