@puga-labs/x402-mantle-sdk 0.3.11 → 0.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (73) hide show
  1. package/README.md +33 -16
  2. package/dist/chunk-2IGT3ZXX.js +179 -0
  3. package/dist/chunk-4BUJR6G5.js +100 -0
  4. package/dist/chunk-5RSVKEVG.js +307 -0
  5. package/dist/chunk-5WQRPHQL.js +108 -0
  6. package/dist/chunk-6IR4GUG7.js +326 -0
  7. package/dist/chunk-AFKV23Q5.js +179 -0
  8. package/dist/chunk-HUKLI4UV.js +318 -0
  9. package/dist/chunk-IWRQEN5H.js +97 -0
  10. package/dist/chunk-KFLH22GF.js +179 -0
  11. package/dist/chunk-LOLJ2FXY.js +340 -0
  12. package/dist/chunk-N2XBZWB6.js +111 -0
  13. package/dist/chunk-OQYJHQP7.js +113 -0
  14. package/dist/chunk-RVPI6FMV.js +307 -0
  15. package/dist/chunk-UDRXM6TV.js +151 -0
  16. package/dist/chunk-UGW2GEWW.js +303 -0
  17. package/dist/chunk-ULC4DZMJ.js +116 -0
  18. package/dist/chunk-UOY3C2LF.js +128 -0
  19. package/dist/chunk-WZKYTDTE.js +64 -0
  20. package/dist/chunk-YCCM6HBF.js +149 -0
  21. package/dist/client.cjs +15 -9
  22. package/dist/client.d.cts +3 -3
  23. package/dist/client.d.ts +3 -3
  24. package/dist/client.js +2 -2
  25. package/dist/constants-CsYaiaSV.d.cts +16 -0
  26. package/dist/constants-CvPIZeTs.d.ts +16 -0
  27. package/dist/createMantleClient-CMwzWrtB.d.ts +103 -0
  28. package/dist/createMantleClient-DEqYPoMs.d.cts +103 -0
  29. package/dist/createMantleClient-DyOpGjHf.d.ts +103 -0
  30. package/dist/createMantleClient-MlVEklNy.d.cts +103 -0
  31. package/dist/express-BIIgsBDf.d.ts +73 -0
  32. package/dist/express-BrBmK46G.d.cts +73 -0
  33. package/dist/express-CLFK75z3.d.ts +84 -0
  34. package/dist/express-DVL-tJDp.d.ts +80 -0
  35. package/dist/express-DcopaNmZ.d.cts +80 -0
  36. package/dist/express-SkrJY9L9.d.cts +84 -0
  37. package/dist/index.cjs +108 -33
  38. package/dist/index.d.cts +4 -4
  39. package/dist/index.d.ts +4 -4
  40. package/dist/index.js +5 -5
  41. package/dist/nextjs-BD0e-jPY.d.cts +89 -0
  42. package/dist/nextjs-C062eZ_O.d.ts +89 -0
  43. package/dist/nextjs-CvArUfyl.d.ts +89 -0
  44. package/dist/nextjs-Xr2VtN1D.d.cts +89 -0
  45. package/dist/react.cjs +13 -16
  46. package/dist/react.d.cts +10 -4
  47. package/dist/react.d.ts +10 -4
  48. package/dist/react.js +3 -3
  49. package/dist/server-express.cjs +135 -56
  50. package/dist/server-express.d.cts +3 -3
  51. package/dist/server-express.d.ts +3 -3
  52. package/dist/server-express.js +3 -3
  53. package/dist/server-nextjs.cjs +120 -49
  54. package/dist/server-nextjs.d.cts +3 -3
  55. package/dist/server-nextjs.d.ts +3 -3
  56. package/dist/server-nextjs.js +3 -3
  57. package/dist/server-web.cjs +120 -49
  58. package/dist/server-web.d.cts +3 -3
  59. package/dist/server-web.d.ts +3 -3
  60. package/dist/server-web.js +3 -3
  61. package/dist/server.cjs +193 -78
  62. package/dist/server.d.cts +78 -7
  63. package/dist/server.d.ts +78 -7
  64. package/dist/server.js +9 -5
  65. package/dist/types-AMVZT3Hf.d.ts +125 -0
  66. package/dist/types-CED_oMWa.d.cts +143 -0
  67. package/dist/types-D1mhWKmb.d.ts +143 -0
  68. package/dist/types-pF3IaKvC.d.cts +125 -0
  69. package/dist/web-standards-BxG0Rdwk.d.ts +77 -0
  70. package/dist/web-standards-C8EBfBLy.d.ts +77 -0
  71. package/dist/web-standards-CXf21iDH.d.cts +77 -0
  72. package/dist/web-standards-D-2Neqyr.d.cts +77 -0
  73. package/package.json +1 -1
package/README.md CHANGED
@@ -250,23 +250,25 @@ Deno.serve(pay(async (req) => {
250
250
 
251
251
  | Option | Type | Default | Description |
252
252
  |--------|------|---------|-------------|
253
- | `facilitatorUrl` | `string` | `http://localhost:8080` | Facilitator service URL |
253
+ | `facilitatorUrl` | `string` | From 402 response | Facilitator service URL (auto-detected from backend) |
254
254
  | `resourceUrl` | `string` | `window.location.origin` | Your API base URL |
255
- | `projectKey` | `string` | - | Project key for hosted facilitator billing |
255
+ | `projectKey` | `string` | From 402 response | Project key (auto-detected from backend) |
256
256
  | `getProvider` | `() => EIP1193Provider` | - | Function returning wallet provider |
257
257
  | `getAccount` | `() => string` | - | Function returning user address |
258
258
 
259
+ **Note:** Both `facilitatorUrl` and `projectKey` are automatically passed from your backend via 402 responses, so clients typically don't need to configure them.
260
+
259
261
  ### Server Options (mantlePaywall)
260
262
 
261
263
  | Option | Type | Required | Description |
262
264
  |--------|------|----------|-------------|
263
265
  | `priceUsd` | `number` | Yes | Price in USD (e.g., `0.01` for 1 cent) |
264
266
  | `payTo` | `string` | Yes | Your wallet address to receive payments |
265
- | `facilitatorUrl` | `string` | No | Facilitator URL (default: localhost:8080) |
266
- | `apiKey` | `string` | No | API key for hosted facilitator |
267
- | `network` | `string` | No | Network ID (default: `mantle-mainnet`) |
267
+ | `projectKey` | `string` | For hosted | Project key from dashboard (for billing + analytics) |
268
+ | `facilitatorUrl` | `string` | For self-hosted | Your facilitator URL (defaults to hosted if not set) |
269
+ | `facilitatorSecret` | `string` | For self-hosted | Shared secret (when set, requires facilitatorUrl) |
268
270
  | `onPaymentSettled` | `function` | No | Callback when payment is verified |
269
- | `telemetry` | `object` | No | Analytics configuration |
271
+ | `telemetry` | `object` | No | Analytics configuration (auto-uses projectKey if not set) |
270
272
 
271
273
  ---
272
274
 
@@ -274,37 +276,52 @@ Deno.serve(pay(async (req) => {
274
276
 
275
277
  ### Hosted Facilitator (Recommended)
276
278
 
277
- Use our managed facilitator service:
279
+ Use our managed facilitator service - **zero URL config needed**:
278
280
 
279
281
  ```typescript
282
+ // Minimal setup - facilitatorUrl defaults to hosted service!
280
283
  const pay = mantlePaywall({
281
284
  priceUsd: 0.01,
282
285
  payTo: '0xYourWallet',
283
- facilitatorUrl: 'https://facilitator.x402mantlesdk.xyz',
284
- apiKey: 'your-api-key' // Get from dashboard
286
+ projectKey: 'pk_xxx' // Get from dashboard (for billing + analytics)
285
287
  });
286
288
  ```
287
289
 
288
- Get your API key from [Dashboard](https://x402mantlesdk.xyz/dashboard).
290
+ Get your project key from [Dashboard](https://x402mantlesdk.xyz/dashboard).
291
+
292
+ **Note:** `projectKey` is automatically passed to clients via 402 responses, so they don't need to configure it separately.
289
293
 
290
294
  ### Self-Hosted Facilitator
291
295
 
292
- Run your own facilitator:
296
+ Run your own facilitator for full control and cost savings:
293
297
 
294
298
  ```typescript
295
299
  const pay = mantlePaywall({
296
300
  priceUsd: 0.01,
297
301
  payTo: '0xYourWallet',
298
- facilitatorUrl: 'https://your-facilitator.com'
299
- // No apiKey needed for self-hosted
302
+ facilitatorUrl: 'https://your-facilitator.com', // Required for self-hosted
303
+ facilitatorSecret: process.env.FACILITATOR_SECRET! // Required for self-hosted
304
+ });
305
+
306
+ // Optional: add projectKey for telemetry
307
+ const payWithTelemetry = mantlePaywall({
308
+ priceUsd: 0.01,
309
+ payTo: '0xYourWallet',
310
+ facilitatorUrl: 'https://your-facilitator.com',
311
+ facilitatorSecret: process.env.FACILITATOR_SECRET!,
312
+ projectKey: 'pk_xxx' // Optional: for analytics
300
313
  });
301
314
  ```
302
315
 
316
+ The `facilitatorSecret` is **required** for self-hosted facilitators to prevent unauthorized usage. When `facilitatorSecret` is provided, `facilitatorUrl` is also required.
317
+
303
318
  Create a facilitator with:
304
319
  ```bash
305
320
  npx create-mantle-facilitator my-facilitator
306
321
  ```
307
322
 
323
+ After setup, copy `FACILITATOR_SECRET` from the generated `.env` file to your backend's environment variables.
324
+
308
325
  ---
309
326
 
310
327
  ## Analytics & Telemetry
@@ -316,11 +333,11 @@ const pay = mantlePaywall({
316
333
  priceUsd: 0.01,
317
334
  payTo: '0x...',
318
335
  facilitatorUrl: 'https://facilitator.x402mantlesdk.xyz',
336
+ projectKey: 'pk_xxx', // Get from dashboard - used for both billing AND analytics
319
337
 
320
- // Analytics configuration
338
+ // Optional: Advanced telemetry config
321
339
  telemetry: {
322
- projectKey: 'pk_xxx', // Get from dashboard
323
- debug: true // Enable console logging
340
+ debug: true // Enable console logging (projectKey auto-derived from above)
324
341
  },
325
342
 
326
343
  // Callback on each successful payment
@@ -0,0 +1,179 @@
1
+ import {
2
+ createMantleClient
3
+ } from "./chunk-RVPI6FMV.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 setProviderAndChain = useCallback(async () => {
17
+ if (typeof window === "undefined" || !window.ethereum) return;
18
+ const browserProvider = new ethers.BrowserProvider(
19
+ window.ethereum
20
+ );
21
+ setProvider(browserProvider);
22
+ const network = await browserProvider.getNetwork();
23
+ setChainId(Number(network.chainId));
24
+ }, []);
25
+ const hydrateFromPermissions = useCallback(async () => {
26
+ if (typeof window === "undefined" || !window.ethereum) return;
27
+ try {
28
+ const accounts = await window.ethereum.request({
29
+ method: "eth_accounts"
30
+ });
31
+ if (accounts && accounts.length > 0) {
32
+ const userAddress = accounts[0];
33
+ setAddress(userAddress);
34
+ setIsConnected(true);
35
+ await setProviderAndChain();
36
+ }
37
+ } catch (err) {
38
+ console.warn("[useEthersWallet] Failed to hydrate from permissions:", err);
39
+ }
40
+ }, [setProviderAndChain]);
41
+ const connect = useCallback(async () => {
42
+ try {
43
+ setError(void 0);
44
+ if (typeof window === "undefined" || !window.ethereum) {
45
+ throw new Error(
46
+ "No Ethereum wallet detected. Please install MetaMask or another wallet."
47
+ );
48
+ }
49
+ const browserProvider = new ethers.BrowserProvider(
50
+ window.ethereum
51
+ );
52
+ setProvider(browserProvider);
53
+ const accounts = await window.ethereum.request({
54
+ method: "eth_requestAccounts"
55
+ });
56
+ if (!accounts || accounts.length === 0) {
57
+ throw new Error("No accounts returned from wallet");
58
+ }
59
+ const userAddress = accounts[0];
60
+ setAddress(userAddress);
61
+ setIsConnected(true);
62
+ const network = await browserProvider.getNetwork();
63
+ setChainId(Number(network.chainId));
64
+ } catch (err) {
65
+ const errorObj = err instanceof Error ? err : new Error(String(err));
66
+ setError(errorObj);
67
+ setIsConnected(false);
68
+ setAddress(void 0);
69
+ setChainId(void 0);
70
+ throw errorObj;
71
+ }
72
+ }, []);
73
+ const disconnect = useCallback(() => {
74
+ setAddress(void 0);
75
+ setIsConnected(false);
76
+ setChainId(void 0);
77
+ setError(void 0);
78
+ }, []);
79
+ useEffect(() => {
80
+ if (typeof window === "undefined" || !window.ethereum) return;
81
+ const ethereum = window.ethereum;
82
+ const handleAccountsChanged = (accounts) => {
83
+ const accountsArray = accounts;
84
+ if (!accountsArray || accountsArray.length === 0) {
85
+ disconnect();
86
+ } else {
87
+ setAddress(accountsArray[0]);
88
+ setIsConnected(true);
89
+ void setProviderAndChain();
90
+ }
91
+ };
92
+ if (ethereum.on) {
93
+ ethereum.on("accountsChanged", handleAccountsChanged);
94
+ }
95
+ return () => {
96
+ if (ethereum.removeListener) {
97
+ ethereum.removeListener("accountsChanged", handleAccountsChanged);
98
+ }
99
+ };
100
+ }, [disconnect, setProviderAndChain]);
101
+ useEffect(() => {
102
+ if (typeof window === "undefined" || !window.ethereum) return;
103
+ const ethereum = window.ethereum;
104
+ const handleConnect = () => {
105
+ void hydrateFromPermissions();
106
+ };
107
+ if (ethereum.on) {
108
+ ethereum.on("connect", handleConnect);
109
+ }
110
+ return () => {
111
+ if (ethereum.removeListener) {
112
+ ethereum.removeListener("connect", handleConnect);
113
+ }
114
+ };
115
+ }, [hydrateFromPermissions]);
116
+ useEffect(() => {
117
+ if (typeof window === "undefined" || !window.ethereum) return;
118
+ const ethereum = window.ethereum;
119
+ const handleChainChanged = (chainIdHex) => {
120
+ const newChainId = parseInt(chainIdHex, 16);
121
+ setChainId(newChainId);
122
+ };
123
+ if (ethereum.on) {
124
+ ethereum.on("chainChanged", handleChainChanged);
125
+ }
126
+ return () => {
127
+ if (ethereum.removeListener) {
128
+ ethereum.removeListener("chainChanged", handleChainChanged);
129
+ }
130
+ };
131
+ }, []);
132
+ useEffect(() => {
133
+ void hydrateFromPermissions();
134
+ }, [hydrateFromPermissions]);
135
+ useEffect(() => {
136
+ if (options?.autoConnect) {
137
+ connect().catch((err) => {
138
+ console.warn("[useEthersWallet] Auto-connect failed:", err);
139
+ });
140
+ }
141
+ }, [options?.autoConnect, connect]);
142
+ return {
143
+ address,
144
+ isConnected,
145
+ provider,
146
+ chainId,
147
+ connect,
148
+ disconnect,
149
+ error
150
+ };
151
+ }
152
+
153
+ // src/client/react/useMantleX402.ts
154
+ function useMantleX402(opts) {
155
+ const { address, isConnected } = useEthersWallet({
156
+ autoConnect: opts?.autoConnect ?? false
157
+ });
158
+ const client = createMantleClient({
159
+ facilitatorUrl: opts?.facilitatorUrl,
160
+ resourceUrl: opts?.resourceUrl,
161
+ projectKey: opts?.projectKey,
162
+ getAccount: () => {
163
+ if (!isConnected || !address) return void 0;
164
+ return address;
165
+ },
166
+ getProvider: () => {
167
+ if (typeof window !== "undefined" && window.ethereum) {
168
+ return window.ethereum;
169
+ }
170
+ return void 0;
171
+ }
172
+ });
173
+ return client;
174
+ }
175
+
176
+ export {
177
+ useEthersWallet,
178
+ useMantleX402
179
+ };
@@ -0,0 +1,100 @@
1
+ import {
2
+ buildRouteKey,
3
+ checkPayment,
4
+ validateAddress
5
+ } from "./chunk-HUKLI4UV.js";
6
+ import {
7
+ MANTLE_DEFAULTS,
8
+ __export,
9
+ getDefaultAssetForNetwork,
10
+ usdCentsToAtomic
11
+ } from "./chunk-HEZZ74SI.js";
12
+
13
+ // src/server/adapters/nextjs.ts
14
+ var nextjs_exports = {};
15
+ __export(nextjs_exports, {
16
+ isPaywallErrorResponse: () => isPaywallErrorResponse,
17
+ mantlePaywall: () => mantlePaywall
18
+ });
19
+ import { NextResponse } from "next/server";
20
+ function debugLog(config, prefix, message, data) {
21
+ if (config?.debug) {
22
+ const timestamp = (/* @__PURE__ */ new Date()).toISOString();
23
+ console.log(`[${timestamp}] [x402-debug:${prefix}]`, message, data || "");
24
+ }
25
+ }
26
+ function mantlePaywall(opts) {
27
+ const { priceUsd, payTo, facilitatorUrl, apiKey, telemetry, onPaymentSettled, facilitatorSecret } = opts;
28
+ validateAddress(payTo, "payTo");
29
+ const priceUsdCents = Math.round(priceUsd * 100);
30
+ return function(handler) {
31
+ return async (req) => {
32
+ const url = new URL(req.url);
33
+ const method = req.method;
34
+ const path = url.pathname;
35
+ const routeKey = buildRouteKey(method, path);
36
+ const network = MANTLE_DEFAULTS.NETWORK;
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,
48
+ price: `$${(priceUsdCents / 100).toFixed(2)}`,
49
+ currency: "USD"
50
+ };
51
+ const paymentHeader = req.headers.get("X-PAYMENT") || req.headers.get("x-payment") || null;
52
+ const result = await checkPayment({
53
+ paymentHeader,
54
+ paymentRequirements,
55
+ facilitatorUrl: facilitatorUrl || MANTLE_DEFAULTS.FACILITATOR_URL,
56
+ apiKey,
57
+ routeKey,
58
+ network,
59
+ asset: assetConfig.address,
60
+ telemetry,
61
+ onPaymentSettled,
62
+ facilitatorSecret
63
+ });
64
+ if (!result.isValid) {
65
+ return NextResponse.json(result.responseBody, {
66
+ status: result.statusCode
67
+ });
68
+ }
69
+ try {
70
+ debugLog(telemetry, "handler", "Handler execution started");
71
+ const response = await handler(req);
72
+ debugLog(telemetry, "handler", `Handler completed: ${response.status}`);
73
+ if (result.sendTelemetryAfterResponse) {
74
+ debugLog(telemetry, "callback", `Calling telemetry callback with status ${response.status}`);
75
+ result.sendTelemetryAfterResponse(response.status);
76
+ } else {
77
+ debugLog(telemetry, "callback", "WARNING: No telemetry callback to call");
78
+ }
79
+ return response;
80
+ } catch (err) {
81
+ const errorMessage = err instanceof Error ? err.message : "Unknown error";
82
+ debugLog(telemetry, "handler", `ERROR: Handler error: ${errorMessage}`);
83
+ if (result.sendTelemetryAfterResponse) {
84
+ debugLog(telemetry, "callback", "Calling telemetry callback with error");
85
+ result.sendTelemetryAfterResponse(500, errorMessage);
86
+ }
87
+ throw err;
88
+ }
89
+ };
90
+ };
91
+ }
92
+ function isPaywallErrorResponse(response) {
93
+ return typeof response === "object" && response !== null && "error" in response && typeof response.error === "string";
94
+ }
95
+
96
+ export {
97
+ mantlePaywall,
98
+ isPaywallErrorResponse,
99
+ nextjs_exports
100
+ };
@@ -0,0 +1,307 @@
1
+ import {
2
+ __require,
3
+ getChainIdForNetwork
4
+ } from "./chunk-WZKYTDTE.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: configFacilitatorUrl,
96
+ provider,
97
+ userAddress: userAddressOverride,
98
+ projectKey: configProjectKey
99
+ } = config;
100
+ if (!resourceUrl) {
101
+ throw new Error("resourceUrl is required");
102
+ }
103
+ if (!provider) {
104
+ throw new Error("provider is required (e.g. window.ethereum)");
105
+ }
106
+ return {
107
+ async callWithPayment(path, options) {
108
+ const method = options?.method ?? "GET";
109
+ const headers = {
110
+ ...options?.headers ?? {}
111
+ };
112
+ let body;
113
+ if (options?.body !== void 0) {
114
+ headers["Content-Type"] = headers["Content-Type"] ?? "application/json";
115
+ body = JSON.stringify(options.body);
116
+ }
117
+ const initialUrl = joinUrl(resourceUrl, path);
118
+ const initialRes = await fetch(initialUrl, {
119
+ method,
120
+ headers,
121
+ body
122
+ });
123
+ if (initialRes.status !== 402) {
124
+ const json = await initialRes.json().catch((err) => {
125
+ console.error("[x402] Failed to parse initial response JSON:", err);
126
+ return null;
127
+ });
128
+ return {
129
+ response: json,
130
+ txHash: void 0
131
+ };
132
+ }
133
+ const bodyJson = await initialRes.json();
134
+ const paymentRequirements = bodyJson.paymentRequirements;
135
+ if (!paymentRequirements) {
136
+ throw new Error(
137
+ "402 response did not include paymentRequirements field"
138
+ );
139
+ }
140
+ const facilitatorUrl = configFacilitatorUrl ?? bodyJson.facilitatorUrl;
141
+ if (!facilitatorUrl) {
142
+ throw new Error(
143
+ "facilitatorUrl not provided in config and not in 402 response. Either set facilitatorUrl in client config or ensure your backend includes it in 402 responses."
144
+ );
145
+ }
146
+ const projectKey = configProjectKey ?? bodyJson.projectKey;
147
+ const settleToken = bodyJson.settleToken;
148
+ const nowSec = Math.floor(Date.now() / 1e3);
149
+ const validAfter = "0";
150
+ const validBefore = String(nowSec + 10 * 60);
151
+ const nonce = randomBytes32Hex();
152
+ const valueAtomic = options?.valueOverrideAtomic ?? paymentRequirements.maxAmountRequired;
153
+ let authorization = {
154
+ from: "0x0000000000000000000000000000000000000000",
155
+ to: paymentRequirements.payTo,
156
+ value: valueAtomic,
157
+ validAfter,
158
+ validBefore,
159
+ nonce
160
+ };
161
+ let signature;
162
+ let from;
163
+ try {
164
+ const signed = await signAuthorizationWithProvider(
165
+ provider,
166
+ authorization,
167
+ paymentRequirements
168
+ );
169
+ signature = signed.signature;
170
+ from = signed.from;
171
+ } catch (err) {
172
+ const code = err?.code;
173
+ if (code === 4001 || code === "ACTION_REJECTED") {
174
+ const userErr = new Error("User rejected payment signature");
175
+ userErr.code = "USER_REJECTED_SIGNATURE";
176
+ userErr.userRejected = true;
177
+ throw userErr;
178
+ }
179
+ throw err;
180
+ }
181
+ authorization = {
182
+ ...authorization,
183
+ from
184
+ };
185
+ if (userAddressOverride && userAddressOverride.toLowerCase() !== from.toLowerCase()) {
186
+ console.warn(
187
+ "[SDK WARNING] userAddress override differs from signer address",
188
+ { override: userAddressOverride, signer: from }
189
+ );
190
+ }
191
+ const paymentHeaderObject = {
192
+ x402Version: 1,
193
+ scheme: paymentRequirements.scheme,
194
+ network: paymentRequirements.network,
195
+ payload: {
196
+ signature,
197
+ authorization
198
+ }
199
+ };
200
+ const paymentHeader = encodeJsonToBase64(paymentHeaderObject);
201
+ const settleUrl = joinUrl(facilitatorUrl, "/settle");
202
+ const settleRes = await fetch(settleUrl, {
203
+ method: "POST",
204
+ headers: {
205
+ "Content-Type": "application/json",
206
+ ...projectKey ? { "X-Project-Key": projectKey } : {}
207
+ },
208
+ body: JSON.stringify({
209
+ x402Version: 1,
210
+ paymentHeader,
211
+ paymentRequirements,
212
+ ...settleToken && { settleToken }
213
+ })
214
+ });
215
+ if (!settleRes.ok) {
216
+ const text = await settleRes.text().catch((err) => {
217
+ console.error("[x402] Failed to read settle response text:", err);
218
+ return "";
219
+ });
220
+ throw new Error(
221
+ `Facilitator /settle failed with HTTP ${settleRes.status}: ${text}`
222
+ );
223
+ }
224
+ const settleJson = await settleRes.json();
225
+ if (!settleJson.success) {
226
+ throw new Error(
227
+ `Facilitator /settle returned error: ${settleJson.error ?? "unknown error"}`
228
+ );
229
+ }
230
+ const txHash = settleJson.txHash ?? void 0;
231
+ const retryHeaders = {
232
+ ...headers,
233
+ "X-PAYMENT": paymentHeader
234
+ };
235
+ const retryRes = await fetch(initialUrl, {
236
+ method,
237
+ headers: retryHeaders,
238
+ body
239
+ });
240
+ if (!retryRes.ok) {
241
+ const text = await retryRes.text().catch((err) => {
242
+ console.error("[x402] Failed to read retry response text:", err);
243
+ return "";
244
+ });
245
+ throw new Error(
246
+ `Protected request with X-PAYMENT failed: HTTP ${retryRes.status} ${text}`
247
+ );
248
+ }
249
+ const finalJson = await retryRes.json();
250
+ return {
251
+ response: finalJson,
252
+ txHash,
253
+ paymentHeader,
254
+ paymentRequirements
255
+ };
256
+ }
257
+ };
258
+ }
259
+
260
+ // src/client/createMantleClient.ts
261
+ function createMantleClient(config) {
262
+ const resourceUrl = config?.resourceUrl ?? (typeof window !== "undefined" ? window.location.origin : "");
263
+ const facilitatorUrl = config?.facilitatorUrl ?? (typeof process !== "undefined" ? process.env?.NEXT_PUBLIC_FACILITATOR_URL : void 0);
264
+ return {
265
+ async postWithPayment(url, body) {
266
+ const provider = config?.getProvider?.();
267
+ if (!provider) {
268
+ throw new Error("Wallet provider not available");
269
+ }
270
+ let account = await config?.getAccount?.();
271
+ if (!account && provider?.request) {
272
+ try {
273
+ const accounts = await provider.request({
274
+ method: "eth_accounts"
275
+ });
276
+ if (Array.isArray(accounts) && accounts.length > 0) {
277
+ account = accounts[0];
278
+ }
279
+ } catch (err) {
280
+ console.warn("[x402] Failed to hydrate account from provider:", err);
281
+ }
282
+ }
283
+ if (!account) {
284
+ throw new Error(
285
+ "Wallet not connected. Please connect your wallet first."
286
+ );
287
+ }
288
+ const client = createPaymentClient({
289
+ resourceUrl,
290
+ facilitatorUrl,
291
+ provider,
292
+ userAddress: account,
293
+ projectKey: config?.projectKey
294
+ });
295
+ const result = await client.callWithPayment(url, {
296
+ method: "POST",
297
+ body
298
+ });
299
+ return result;
300
+ }
301
+ };
302
+ }
303
+
304
+ export {
305
+ createPaymentClient,
306
+ createMantleClient
307
+ };