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

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 (71) hide show
  1. package/dist/{chunk-HTZ3QFY4.js → chunk-23QNUJIB.js} +4 -3
  2. package/dist/chunk-CXRILT3C.js +68 -0
  3. package/dist/{chunk-CTI5CRDY.js → chunk-E46A7I6B.js} +1 -1
  4. package/dist/{chunk-XAQGMFSR.js → chunk-HEZZ74SI.js} +6 -0
  5. package/dist/chunk-NQWSCY44.js +70 -0
  6. package/dist/chunk-PCJEJYP6.js +68 -0
  7. package/dist/chunk-PPVS3X5Z.js +99 -0
  8. package/dist/chunk-QWQUSRLY.js +99 -0
  9. package/dist/chunk-U73CZU3X.js +237 -0
  10. package/dist/chunk-WO2MYZXT.js +0 -0
  11. package/dist/chunk-ZLCKBFVJ.js +237 -0
  12. package/dist/chunk-ZROK2XOB.js +70 -0
  13. package/dist/client.d.cts +4 -4
  14. package/dist/client.d.ts +4 -4
  15. package/dist/client.js +2 -2
  16. package/dist/{constants-CVFF0ray.d.ts → constants-0ncqvV_O.d.ts} +1 -1
  17. package/dist/{constants-DzCGK0Q3.d.cts → constants-CsIL25uQ.d.cts} +1 -1
  18. package/dist/{createMantleClient-NN0Nitp9.d.cts → createMantleClient-CO0uWPb-.d.cts} +1 -1
  19. package/dist/{createMantleClient-DVFkbBfS.d.ts → createMantleClient-CuiPsTa6.d.ts} +1 -1
  20. package/dist/express-D8EwEcOL.d.ts +66 -0
  21. package/dist/express-eQOPxfnI.d.cts +66 -0
  22. package/dist/index.cjs +186 -109
  23. package/dist/index.d.cts +6 -4
  24. package/dist/index.d.ts +6 -4
  25. package/dist/index.js +6 -4
  26. package/dist/nextjs-Duecps0q.d.cts +45 -0
  27. package/dist/nextjs-TFhFiQuL.d.ts +45 -0
  28. package/dist/react.cjs +3 -2
  29. package/dist/react.d.cts +7 -4
  30. package/dist/react.d.ts +7 -4
  31. package/dist/react.js +3 -3
  32. package/dist/server-express.cjs +368 -0
  33. package/dist/server-express.d.cts +5 -0
  34. package/dist/server-express.d.ts +5 -0
  35. package/dist/server-express.js +13 -0
  36. package/dist/server-nextjs.cjs +339 -0
  37. package/dist/server-nextjs.d.cts +5 -0
  38. package/dist/server-nextjs.d.ts +5 -0
  39. package/dist/server-nextjs.js +11 -0
  40. package/dist/server-web.cjs +339 -0
  41. package/dist/server-web.d.cts +4 -0
  42. package/dist/server-web.d.ts +4 -0
  43. package/dist/server-web.js +11 -0
  44. package/dist/server.cjs +316 -111
  45. package/dist/server.d.cts +67 -104
  46. package/dist/server.d.ts +67 -104
  47. package/dist/server.js +29 -5
  48. package/dist/{types-2zqbJvcz.d.cts → types-BFUqKBBO.d.cts} +1 -1
  49. package/dist/{types-2zqbJvcz.d.ts → types-BFUqKBBO.d.ts} +1 -1
  50. package/dist/types-CoOdbZSp.d.cts +97 -0
  51. package/dist/types-CqQ6OgRi.d.ts +85 -0
  52. package/dist/types-CrOsOHcX.d.cts +85 -0
  53. package/dist/types-DTzov_EE.d.ts +97 -0
  54. package/dist/web-standards-BNQyWzBC.d.cts +77 -0
  55. package/dist/web-standards-D8j1kZxd.d.ts +77 -0
  56. package/package.json +49 -2
  57. package/dist/chunk-DA6ZBXNO.js +0 -275
  58. package/dist/chunk-FD4HG7KR.js +0 -135
  59. package/dist/chunk-GWVWPS3R.js +0 -277
  60. package/dist/chunk-MQALBRGV.js +0 -135
  61. package/dist/chunk-PYIYE3HI.js +0 -135
  62. package/dist/chunk-Q6SPMEIW.js +0 -235
  63. package/dist/chunk-RNKXSBT7.js +0 -135
  64. package/dist/chunk-SPCXFN7C.js +0 -284
  65. package/dist/chunk-T5DRYLNB.js +0 -135
  66. package/dist/chunk-TSEE5NSJ.js +0 -297
  67. package/dist/chunk-WELDWRDX.js +0 -307
  68. package/dist/constants-C7aY8u5b.d.cts +0 -77
  69. package/dist/constants-C7aY8u5b.d.ts +0 -77
  70. package/dist/createMantleClient-DS1Ghqrz.d.cts +0 -51
  71. package/dist/createMantleClient-DS1Ghqrz.d.ts +0 -51
@@ -0,0 +1,77 @@
1
+ import { M as MinimalPaywallOptions } from './types-CrOsOHcX.cjs';
2
+
3
+ /**
4
+ * Web Standards route handler type.
5
+ * Takes a Request and returns a Response.
6
+ */
7
+ type WebHandler = (request: Request) => Promise<Response>;
8
+ /**
9
+ * Wrapper function that adds x402 payment verification to Web Standards handler.
10
+ */
11
+ type WebPaywallWrapper = (handler: WebHandler) => WebHandler;
12
+ /**
13
+ * Create Web Standards middleware for x402 payment verification.
14
+ * Uses Mantle mainnet defaults (USDC, exact scheme, etc.).
15
+ *
16
+ * Compatible with:
17
+ * - Hono
18
+ * - Cloudflare Workers
19
+ * - Deno
20
+ * - Bun
21
+ * - Any platform supporting Web Request/Response API
22
+ *
23
+ * @example
24
+ * ```typescript
25
+ * // Hono example
26
+ * import { Hono } from 'hono'
27
+ * import { mantlePaywall } from '@puga-labs/x402-mantle-sdk/server/web'
28
+ *
29
+ * const app = new Hono()
30
+ * const pay = mantlePaywall({
31
+ * priceUsd: 0.01,
32
+ * payTo: '0x...',
33
+ * });
34
+ *
35
+ * app.post('/api/generate', pay(async (req) => {
36
+ * const body = await req.json();
37
+ * // Your handler code here
38
+ * return new Response(JSON.stringify({ success: true }), {
39
+ * headers: { 'Content-Type': 'application/json' }
40
+ * });
41
+ * }));
42
+ * ```
43
+ *
44
+ * @example
45
+ * ```typescript
46
+ * // Cloudflare Workers example
47
+ * import { mantlePaywall } from '@puga-labs/x402-mantle-sdk/server/web'
48
+ *
49
+ * const pay = mantlePaywall({
50
+ * priceUsd: 0.01,
51
+ * payTo: '0x...',
52
+ * });
53
+ *
54
+ * export default {
55
+ * async fetch(request: Request) {
56
+ * const handler = pay(async (req) => {
57
+ * // Your handler code here
58
+ * return new Response('Hello World');
59
+ * });
60
+ * return handler(request);
61
+ * }
62
+ * }
63
+ * ```
64
+ *
65
+ * @param opts - Minimal configuration (price, payTo, optional facilitator/telemetry).
66
+ * @returns Function that wraps Web Standards handlers with payment verification.
67
+ */
68
+ declare function mantlePaywall(opts: MinimalPaywallOptions): WebPaywallWrapper;
69
+
70
+ type webStandards_WebHandler = WebHandler;
71
+ type webStandards_WebPaywallWrapper = WebPaywallWrapper;
72
+ declare const webStandards_mantlePaywall: typeof mantlePaywall;
73
+ declare namespace webStandards {
74
+ export { type webStandards_WebHandler as WebHandler, type webStandards_WebPaywallWrapper as WebPaywallWrapper, webStandards_mantlePaywall as mantlePaywall };
75
+ }
76
+
77
+ export { type WebHandler as W, type WebPaywallWrapper as a, mantlePaywall as m, webStandards as w };
@@ -0,0 +1,77 @@
1
+ import { M as MinimalPaywallOptions } from './types-CqQ6OgRi.js';
2
+
3
+ /**
4
+ * Web Standards route handler type.
5
+ * Takes a Request and returns a Response.
6
+ */
7
+ type WebHandler = (request: Request) => Promise<Response>;
8
+ /**
9
+ * Wrapper function that adds x402 payment verification to Web Standards handler.
10
+ */
11
+ type WebPaywallWrapper = (handler: WebHandler) => WebHandler;
12
+ /**
13
+ * Create Web Standards middleware for x402 payment verification.
14
+ * Uses Mantle mainnet defaults (USDC, exact scheme, etc.).
15
+ *
16
+ * Compatible with:
17
+ * - Hono
18
+ * - Cloudflare Workers
19
+ * - Deno
20
+ * - Bun
21
+ * - Any platform supporting Web Request/Response API
22
+ *
23
+ * @example
24
+ * ```typescript
25
+ * // Hono example
26
+ * import { Hono } from 'hono'
27
+ * import { mantlePaywall } from '@puga-labs/x402-mantle-sdk/server/web'
28
+ *
29
+ * const app = new Hono()
30
+ * const pay = mantlePaywall({
31
+ * priceUsd: 0.01,
32
+ * payTo: '0x...',
33
+ * });
34
+ *
35
+ * app.post('/api/generate', pay(async (req) => {
36
+ * const body = await req.json();
37
+ * // Your handler code here
38
+ * return new Response(JSON.stringify({ success: true }), {
39
+ * headers: { 'Content-Type': 'application/json' }
40
+ * });
41
+ * }));
42
+ * ```
43
+ *
44
+ * @example
45
+ * ```typescript
46
+ * // Cloudflare Workers example
47
+ * import { mantlePaywall } from '@puga-labs/x402-mantle-sdk/server/web'
48
+ *
49
+ * const pay = mantlePaywall({
50
+ * priceUsd: 0.01,
51
+ * payTo: '0x...',
52
+ * });
53
+ *
54
+ * export default {
55
+ * async fetch(request: Request) {
56
+ * const handler = pay(async (req) => {
57
+ * // Your handler code here
58
+ * return new Response('Hello World');
59
+ * });
60
+ * return handler(request);
61
+ * }
62
+ * }
63
+ * ```
64
+ *
65
+ * @param opts - Minimal configuration (price, payTo, optional facilitator/telemetry).
66
+ * @returns Function that wraps Web Standards handlers with payment verification.
67
+ */
68
+ declare function mantlePaywall(opts: MinimalPaywallOptions): WebPaywallWrapper;
69
+
70
+ type webStandards_WebHandler = WebHandler;
71
+ type webStandards_WebPaywallWrapper = WebPaywallWrapper;
72
+ declare const webStandards_mantlePaywall: typeof mantlePaywall;
73
+ declare namespace webStandards {
74
+ export { type webStandards_WebHandler as WebHandler, type webStandards_WebPaywallWrapper as WebPaywallWrapper, webStandards_mantlePaywall as mantlePaywall };
75
+ }
76
+
77
+ export { type WebHandler as W, type WebPaywallWrapper as a, mantlePaywall as m, webStandards as w };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@puga-labs/x402-mantle-sdk",
3
- "version": "0.3.1",
3
+ "version": "0.3.3",
4
4
  "description": "x402 payments SDK for Mantle (USDC, gasless, facilitator-based)",
5
5
  "license": "MIT",
6
6
  "author": "Evgenii Pugachev <cyprus.pugamuga@gmail.com>",
@@ -47,6 +47,36 @@
47
47
  "default": "./dist/server.cjs"
48
48
  }
49
49
  },
50
+ "./server/express": {
51
+ "import": {
52
+ "types": "./dist/server-express.d.ts",
53
+ "default": "./dist/server-express.js"
54
+ },
55
+ "require": {
56
+ "types": "./dist/server-express.d.cts",
57
+ "default": "./dist/server-express.cjs"
58
+ }
59
+ },
60
+ "./server/nextjs": {
61
+ "import": {
62
+ "types": "./dist/server-nextjs.d.ts",
63
+ "default": "./dist/server-nextjs.js"
64
+ },
65
+ "require": {
66
+ "types": "./dist/server-nextjs.d.cts",
67
+ "default": "./dist/server-nextjs.cjs"
68
+ }
69
+ },
70
+ "./server/web": {
71
+ "import": {
72
+ "types": "./dist/server-web.d.ts",
73
+ "default": "./dist/server-web.js"
74
+ },
75
+ "require": {
76
+ "types": "./dist/server-web.d.cts",
77
+ "default": "./dist/server-web.cjs"
78
+ }
79
+ },
50
80
  "./react": {
51
81
  "import": {
52
82
  "types": "./dist/react.d.ts",
@@ -62,7 +92,7 @@
62
92
  "dist"
63
93
  ],
64
94
  "scripts": {
65
- "build": "tsup src/index.ts src/client.ts src/server.ts src/react.ts --format cjs,esm --dts",
95
+ "build": "tsup src/index.ts src/client.ts src/server.ts src/server-express.ts src/server-nextjs.ts src/server-web.ts src/react.ts --format cjs,esm --dts",
66
96
  "dev": "tsup src/index.ts --format esm --watch",
67
97
  "clean": "rimraf dist",
68
98
  "lint": "eslint src --ext .ts",
@@ -77,13 +107,30 @@
77
107
  },
78
108
  "peerDependencies": {
79
109
  "ethers": "^6.0.0",
110
+ "express": "^4.0.0 || ^5.0.0",
111
+ "next": "^14.0.0 || ^15.0.0 || ^16.0.0",
80
112
  "react": "^18.0.0 || ^19.0.0"
81
113
  },
114
+ "peerDependenciesMeta": {
115
+ "express": {
116
+ "optional": true
117
+ },
118
+ "next": {
119
+ "optional": true
120
+ },
121
+ "ethers": {
122
+ "optional": true
123
+ },
124
+ "react": {
125
+ "optional": true
126
+ }
127
+ },
82
128
  "devDependencies": {
83
129
  "@eslint/js": "^9.17.0",
84
130
  "@types/express": "^5.0.6",
85
131
  "@types/node": "^22.0.0",
86
132
  "@types/react": "^18.3.1",
133
+ "next": "^15.1.6",
87
134
  "@typescript-eslint/eslint-plugin": "^8.20.0",
88
135
  "@typescript-eslint/parser": "^8.20.0",
89
136
  "@vitest/coverage-v8": "^4.0.15",
@@ -1,275 +0,0 @@
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
- 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
- console.log("[SDK] Using authorization.from:", authorization.from);
172
- const paymentHeaderObject = {
173
- x402Version: 1,
174
- scheme: paymentRequirements.scheme,
175
- network: paymentRequirements.network,
176
- payload: {
177
- signature,
178
- authorization
179
- }
180
- };
181
- const paymentHeader = encodeJsonToBase64(paymentHeaderObject);
182
- const settleUrl = joinUrl(facilitatorUrl, "/settle");
183
- const settleRes = await fetch(settleUrl, {
184
- method: "POST",
185
- headers: {
186
- "Content-Type": "application/json",
187
- ...projectKey ? { "X-Project-Key": projectKey } : {}
188
- },
189
- body: JSON.stringify({
190
- x402Version: 1,
191
- paymentHeader,
192
- paymentRequirements
193
- })
194
- });
195
- if (!settleRes.ok) {
196
- const text = await settleRes.text().catch((err) => {
197
- console.error("[x402] Failed to read settle response text:", err);
198
- return "";
199
- });
200
- throw new Error(
201
- `Facilitator /settle failed with HTTP ${settleRes.status}: ${text}`
202
- );
203
- }
204
- const settleJson = await settleRes.json();
205
- if (!settleJson.success) {
206
- throw new Error(
207
- `Facilitator /settle returned error: ${settleJson.error ?? "unknown error"}`
208
- );
209
- }
210
- const txHash = settleJson.txHash ?? void 0;
211
- const retryHeaders = {
212
- ...headers,
213
- "X-PAYMENT": paymentHeader
214
- };
215
- const retryRes = await fetch(initialUrl, {
216
- method,
217
- headers: retryHeaders,
218
- body
219
- });
220
- if (!retryRes.ok) {
221
- const text = await retryRes.text().catch((err) => {
222
- console.error("[x402] Failed to read retry response text:", err);
223
- return "";
224
- });
225
- throw new Error(
226
- `Protected request with X-PAYMENT failed: HTTP ${retryRes.status} ${text}`
227
- );
228
- }
229
- const finalJson = await retryRes.json();
230
- return {
231
- response: finalJson,
232
- txHash,
233
- paymentHeader,
234
- paymentRequirements
235
- };
236
- }
237
- };
238
- }
239
-
240
- // src/client/createMantleClient.ts
241
- function createMantleClient(config) {
242
- const resourceUrl = config?.resourceUrl ?? (typeof window !== "undefined" ? window.location.origin : "");
243
- const facilitatorUrl = config?.facilitatorUrl ?? (typeof process !== "undefined" ? process.env?.NEXT_PUBLIC_FACILITATOR_URL : void 0) ?? "http://localhost:8080";
244
- return {
245
- async postWithPayment(url, body) {
246
- const account = await config?.getAccount?.();
247
- if (!account) {
248
- throw new Error(
249
- "Wallet not connected. Please connect your wallet first."
250
- );
251
- }
252
- const provider = config?.getProvider?.();
253
- if (!provider) {
254
- throw new Error("Wallet provider not available");
255
- }
256
- const client = createPaymentClient({
257
- resourceUrl,
258
- facilitatorUrl,
259
- provider,
260
- userAddress: account,
261
- projectKey: config?.projectKey
262
- });
263
- const result = await client.callWithPayment(url, {
264
- method: "POST",
265
- body
266
- });
267
- return result.response;
268
- }
269
- };
270
- }
271
-
272
- export {
273
- createPaymentClient,
274
- createMantleClient
275
- };
@@ -1,135 +0,0 @@
1
- import {
2
- createMantleClient
3
- } from "./chunk-GWVWPS3R.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
- };