@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,66 @@
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/nextjs.ts
13
+ var nextjs_exports = {};
14
+ __export(nextjs_exports, {
15
+ mantlePaywall: () => mantlePaywall
16
+ });
17
+ import { NextResponse } from "next/server";
18
+ function mantlePaywall(opts) {
19
+ const { priceUsd, payTo, facilitatorUrl, telemetry, onPaymentSettled } = opts;
20
+ const priceUsdCents = Math.round(priceUsd * 100);
21
+ return function(handler) {
22
+ return async (req) => {
23
+ const url = new URL(req.url);
24
+ const method = req.method;
25
+ const path = url.pathname;
26
+ const routeKey = buildRouteKey(method, path);
27
+ const network = MANTLE_DEFAULTS.NETWORK;
28
+ const assetConfig = getDefaultAssetForNetwork(network);
29
+ const maxAmountRequiredBigInt = usdCentsToAtomic(
30
+ priceUsdCents,
31
+ assetConfig.decimals
32
+ );
33
+ const paymentRequirements = {
34
+ scheme: "exact",
35
+ network,
36
+ asset: assetConfig.address,
37
+ maxAmountRequired: maxAmountRequiredBigInt.toString(),
38
+ payTo,
39
+ price: `$${(priceUsdCents / 100).toFixed(2)}`,
40
+ currency: "USD"
41
+ };
42
+ const paymentHeader = req.headers.get("X-PAYMENT") || req.headers.get("x-payment") || null;
43
+ const result = await checkPayment({
44
+ paymentHeader,
45
+ paymentRequirements,
46
+ facilitatorUrl: facilitatorUrl || MANTLE_DEFAULTS.FACILITATOR_URL,
47
+ routeKey,
48
+ network,
49
+ asset: assetConfig.address,
50
+ telemetry,
51
+ onPaymentSettled
52
+ });
53
+ if (!result.isValid) {
54
+ return NextResponse.json(result.responseBody, {
55
+ status: result.statusCode
56
+ });
57
+ }
58
+ return handler(req);
59
+ };
60
+ };
61
+ }
62
+
63
+ export {
64
+ mantlePaywall,
65
+ nextjs_exports
66
+ };
@@ -0,0 +1,277 @@
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
+ const params = [address, JSON.stringify(typedData)];
94
+ const signature = await p.request({
95
+ method: "eth_signTypedData_v4",
96
+ params
97
+ });
98
+ if (typeof signature !== "string" || !signature.startsWith("0x")) {
99
+ throw new Error("Invalid signature returned from provider");
100
+ }
101
+ return signature;
102
+ }
103
+ function createPaymentClient(config) {
104
+ const {
105
+ resourceUrl,
106
+ facilitatorUrl,
107
+ provider,
108
+ userAddress: userAddressOverride,
109
+ projectKey
110
+ } = config;
111
+ if (!resourceUrl) {
112
+ throw new Error("resourceUrl is required");
113
+ }
114
+ if (!facilitatorUrl) {
115
+ throw new Error("facilitatorUrl is required");
116
+ }
117
+ if (!provider) {
118
+ throw new Error("provider is required (e.g. window.ethereum)");
119
+ }
120
+ return {
121
+ async callWithPayment(path, options) {
122
+ const method = options?.method ?? "GET";
123
+ const headers = {
124
+ ...options?.headers ?? {}
125
+ };
126
+ let body;
127
+ if (options?.body !== void 0) {
128
+ headers["Content-Type"] = headers["Content-Type"] ?? "application/json";
129
+ body = JSON.stringify(options.body);
130
+ }
131
+ const initialUrl = joinUrl(resourceUrl, path);
132
+ const initialRes = await fetch(initialUrl, {
133
+ method,
134
+ headers,
135
+ body
136
+ });
137
+ if (initialRes.status !== 402) {
138
+ const json = await initialRes.json().catch((err) => {
139
+ console.error("[x402] Failed to parse initial response JSON:", err);
140
+ return null;
141
+ });
142
+ return {
143
+ response: json,
144
+ txHash: void 0
145
+ };
146
+ }
147
+ const bodyJson = await initialRes.json();
148
+ const paymentRequirements = bodyJson.paymentRequirements;
149
+ if (!paymentRequirements) {
150
+ throw new Error(
151
+ "402 response did not include paymentRequirements field"
152
+ );
153
+ }
154
+ const fromAddress = userAddressOverride ?? await getUserAddressFromProvider(provider);
155
+ const nowSec = Math.floor(Date.now() / 1e3);
156
+ const validAfter = "0";
157
+ const validBefore = String(nowSec + 10 * 60);
158
+ const nonce = randomBytes32Hex();
159
+ const valueAtomic = options?.valueOverrideAtomic ?? paymentRequirements.maxAmountRequired;
160
+ const authorization = {
161
+ from: fromAddress,
162
+ to: paymentRequirements.payTo,
163
+ value: valueAtomic,
164
+ validAfter,
165
+ validBefore,
166
+ nonce
167
+ };
168
+ const signature = await signAuthorizationWithProvider(
169
+ provider,
170
+ fromAddress,
171
+ authorization,
172
+ paymentRequirements
173
+ );
174
+ const paymentHeaderObject = {
175
+ x402Version: 1,
176
+ scheme: paymentRequirements.scheme,
177
+ network: paymentRequirements.network,
178
+ payload: {
179
+ signature,
180
+ authorization
181
+ }
182
+ };
183
+ const paymentHeader = encodeJsonToBase64(paymentHeaderObject);
184
+ const settleUrl = joinUrl(facilitatorUrl, "/settle");
185
+ const settleRes = await fetch(settleUrl, {
186
+ method: "POST",
187
+ headers: {
188
+ "Content-Type": "application/json",
189
+ ...projectKey ? { "X-Project-Key": projectKey } : {}
190
+ },
191
+ body: JSON.stringify({
192
+ x402Version: 1,
193
+ paymentHeader,
194
+ paymentRequirements
195
+ })
196
+ });
197
+ if (!settleRes.ok) {
198
+ const text = await settleRes.text().catch((err) => {
199
+ console.error("[x402] Failed to read settle response text:", err);
200
+ return "";
201
+ });
202
+ throw new Error(
203
+ `Facilitator /settle failed with HTTP ${settleRes.status}: ${text}`
204
+ );
205
+ }
206
+ const settleJson = await settleRes.json();
207
+ if (!settleJson.success) {
208
+ throw new Error(
209
+ `Facilitator /settle returned error: ${settleJson.error ?? "unknown error"}`
210
+ );
211
+ }
212
+ const txHash = settleJson.txHash ?? void 0;
213
+ const retryHeaders = {
214
+ ...headers,
215
+ "X-PAYMENT": paymentHeader
216
+ };
217
+ const retryRes = await fetch(initialUrl, {
218
+ method,
219
+ headers: retryHeaders,
220
+ body
221
+ });
222
+ if (!retryRes.ok) {
223
+ const text = await retryRes.text().catch((err) => {
224
+ console.error("[x402] Failed to read retry response text:", err);
225
+ return "";
226
+ });
227
+ throw new Error(
228
+ `Protected request with X-PAYMENT failed: HTTP ${retryRes.status} ${text}`
229
+ );
230
+ }
231
+ const finalJson = await retryRes.json();
232
+ return {
233
+ response: finalJson,
234
+ txHash,
235
+ paymentHeader,
236
+ paymentRequirements
237
+ };
238
+ }
239
+ };
240
+ }
241
+
242
+ // src/client/createMantleClient.ts
243
+ function createMantleClient(config) {
244
+ const resourceUrl = config?.resourceUrl ?? (typeof window !== "undefined" ? window.location.origin : "");
245
+ const facilitatorUrl = config?.facilitatorUrl ?? (typeof process !== "undefined" ? process.env?.NEXT_PUBLIC_FACILITATOR_URL : void 0) ?? "http://localhost:8080";
246
+ return {
247
+ async postWithPayment(url, body) {
248
+ const account = await config?.getAccount?.();
249
+ if (!account) {
250
+ throw new Error(
251
+ "Wallet not connected. Please connect your wallet first."
252
+ );
253
+ }
254
+ const provider = config?.getProvider?.();
255
+ if (!provider) {
256
+ throw new Error("Wallet provider not available");
257
+ }
258
+ const client = createPaymentClient({
259
+ resourceUrl,
260
+ facilitatorUrl,
261
+ provider,
262
+ userAddress: account,
263
+ projectKey: config?.projectKey
264
+ });
265
+ const result = await client.callWithPayment(url, {
266
+ method: "POST",
267
+ body
268
+ });
269
+ return result.response;
270
+ }
271
+ };
272
+ }
273
+
274
+ export {
275
+ createPaymentClient,
276
+ createMantleClient
277
+ };
@@ -0,0 +1,62 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
3
+ get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
4
+ }) : x)(function(x) {
5
+ if (typeof require !== "undefined") return require.apply(this, arguments);
6
+ throw Error('Dynamic require of "' + x + '" is not supported');
7
+ });
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+
13
+ // src/shared/constants.ts
14
+ var MANTLE_MAINNET_NETWORK_ID = "mantle-mainnet";
15
+ var MANTLE_MAINNET_CHAIN_ID = 5e3;
16
+ var MANTLE_MAINNET_USDC = {
17
+ symbol: "USDC",
18
+ address: "0x09Bc4E0D864854c6aFB6eB9A9cdF58aC190D0dF9",
19
+ decimals: 6
20
+ };
21
+ var MANTLE_DEFAULTS = {
22
+ NETWORK: "mantle-mainnet",
23
+ CHAIN_ID: 5e3,
24
+ USDC_ADDRESS: "0x09Bc4E0D864854c6aFB6eB9A9cdF58aC190D0dF9",
25
+ USDC_DECIMALS: 6,
26
+ CURRENCY: "USD",
27
+ SCHEME: "exact",
28
+ FACILITATOR_URL: (typeof process !== "undefined" ? process.env?.NEXT_PUBLIC_FACILITATOR_URL : void 0) || "http://localhost:8080"
29
+ };
30
+ function getDefaultAssetForNetwork(network) {
31
+ switch (network) {
32
+ case MANTLE_MAINNET_NETWORK_ID:
33
+ default:
34
+ return MANTLE_MAINNET_USDC;
35
+ }
36
+ }
37
+ function getChainIdForNetwork(network) {
38
+ switch (network) {
39
+ case MANTLE_MAINNET_NETWORK_ID:
40
+ default:
41
+ return MANTLE_MAINNET_CHAIN_ID;
42
+ }
43
+ }
44
+ function usdCentsToAtomic(cents, decimals) {
45
+ if (cents < 0) {
46
+ throw new Error("priceUsdCents must be non-negative");
47
+ }
48
+ if (decimals < 2) {
49
+ throw new Error("token decimals must be >= 2 for USD cent conversion");
50
+ }
51
+ const base = BigInt(10) ** BigInt(decimals - 2);
52
+ return BigInt(cents) * base;
53
+ }
54
+
55
+ export {
56
+ __require,
57
+ __export,
58
+ MANTLE_DEFAULTS,
59
+ getDefaultAssetForNetwork,
60
+ getChainIdForNetwork,
61
+ usdCentsToAtomic
62
+ };
@@ -0,0 +1,135 @@
1
+ import {
2
+ createMantleClient
3
+ } from "./chunk-WELDWRDX.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,135 @@
1
+ import {
2
+ createMantleClient
3
+ } from "./chunk-SPCXFN7C.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
+ };