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

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 (62) hide show
  1. package/README.md +22 -12
  2. package/dist/chunk-2IGT3ZXX.js +179 -0
  3. package/dist/chunk-4BUJR6G5.js +100 -0
  4. package/dist/chunk-5WQRPHQL.js +108 -0
  5. package/dist/chunk-6IR4GUG7.js +326 -0
  6. package/dist/chunk-HUKLI4UV.js +318 -0
  7. package/dist/chunk-IWRQEN5H.js +97 -0
  8. package/dist/chunk-KFLH22GF.js +179 -0
  9. package/dist/chunk-N2XBZWB6.js +111 -0
  10. package/dist/chunk-RVPI6FMV.js +307 -0
  11. package/dist/chunk-UGW2GEWW.js +303 -0
  12. package/dist/chunk-UOY3C2LF.js +128 -0
  13. package/dist/chunk-YCCM6HBF.js +149 -0
  14. package/dist/client.cjs +13 -7
  15. package/dist/client.d.cts +2 -2
  16. package/dist/client.d.ts +2 -2
  17. package/dist/client.js +1 -1
  18. package/dist/createMantleClient-CMwzWrtB.d.ts +103 -0
  19. package/dist/createMantleClient-DEqYPoMs.d.cts +103 -0
  20. package/dist/createMantleClient-DyOpGjHf.d.ts +103 -0
  21. package/dist/createMantleClient-MlVEklNy.d.cts +103 -0
  22. package/dist/express-BIIgsBDf.d.ts +73 -0
  23. package/dist/express-BrBmK46G.d.cts +73 -0
  24. package/dist/express-DVL-tJDp.d.ts +80 -0
  25. package/dist/express-DcopaNmZ.d.cts +80 -0
  26. package/dist/index.cjs +87 -26
  27. package/dist/index.d.cts +3 -3
  28. package/dist/index.d.ts +3 -3
  29. package/dist/index.js +4 -4
  30. package/dist/nextjs-BD0e-jPY.d.cts +89 -0
  31. package/dist/nextjs-C062eZ_O.d.ts +89 -0
  32. package/dist/nextjs-CvArUfyl.d.ts +89 -0
  33. package/dist/nextjs-Xr2VtN1D.d.cts +89 -0
  34. package/dist/react.cjs +13 -7
  35. package/dist/react.d.cts +10 -4
  36. package/dist/react.d.ts +10 -4
  37. package/dist/react.js +2 -2
  38. package/dist/server-express.cjs +84 -19
  39. package/dist/server-express.d.cts +2 -2
  40. package/dist/server-express.d.ts +2 -2
  41. package/dist/server-express.js +2 -2
  42. package/dist/server-nextjs.cjs +70 -16
  43. package/dist/server-nextjs.d.cts +2 -2
  44. package/dist/server-nextjs.d.ts +2 -2
  45. package/dist/server-nextjs.js +2 -2
  46. package/dist/server-web.cjs +70 -16
  47. package/dist/server-web.d.cts +2 -2
  48. package/dist/server-web.d.ts +2 -2
  49. package/dist/server-web.js +2 -2
  50. package/dist/server.cjs +130 -39
  51. package/dist/server.d.cts +35 -7
  52. package/dist/server.d.ts +35 -7
  53. package/dist/server.js +6 -4
  54. package/dist/types-AMVZT3Hf.d.ts +125 -0
  55. package/dist/types-CED_oMWa.d.cts +143 -0
  56. package/dist/types-D1mhWKmb.d.ts +143 -0
  57. package/dist/types-pF3IaKvC.d.cts +125 -0
  58. package/dist/web-standards-BxG0Rdwk.d.ts +77 -0
  59. package/dist/web-standards-C8EBfBLy.d.ts +77 -0
  60. package/dist/web-standards-CXf21iDH.d.cts +77 -0
  61. package/dist/web-standards-D-2Neqyr.d.cts +77 -0
  62. package/package.json +1 -1
package/README.md CHANGED
@@ -250,12 +250,14 @@ 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 |
@@ -263,10 +265,11 @@ Deno.serve(pay(async (req) => {
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
267
  | `facilitatorUrl` | `string` | No | Facilitator URL (default: localhost:8080) |
266
- | `apiKey` | `string` | No | API key for hosted facilitator |
268
+ | `projectKey` | `string` | No | Project key from dashboard (for hosted facilitator + analytics) |
269
+ | `facilitatorSecret` | `string` | For self-hosted | Shared secret with your facilitator (required for self-hosted) |
267
270
  | `network` | `string` | No | Network ID (default: `mantle-mainnet`) |
268
271
  | `onPaymentSettled` | `function` | No | Callback when payment is verified |
269
- | `telemetry` | `object` | No | Analytics configuration |
272
+ | `telemetry` | `object` | No | Analytics configuration (auto-uses projectKey if not set) |
270
273
 
271
274
  ---
272
275
 
@@ -281,30 +284,37 @@ const pay = mantlePaywall({
281
284
  priceUsd: 0.01,
282
285
  payTo: '0xYourWallet',
283
286
  facilitatorUrl: 'https://facilitator.x402mantlesdk.xyz',
284
- apiKey: 'your-api-key' // Get from dashboard
287
+ projectKey: 'pk_xxx' // Get from dashboard (used for billing + analytics)
285
288
  });
286
289
  ```
287
290
 
288
- Get your API key from [Dashboard](https://x402mantlesdk.xyz/dashboard).
291
+ Get your project key from [Dashboard](https://x402mantlesdk.xyz/dashboard).
292
+
293
+ **Note:** `projectKey` is automatically passed to clients via 402 responses, so they don't need to configure it separately.
289
294
 
290
295
  ### Self-Hosted Facilitator
291
296
 
292
- Run your own facilitator:
297
+ Run your own facilitator for full control and cost savings:
293
298
 
294
299
  ```typescript
295
300
  const pay = mantlePaywall({
296
301
  priceUsd: 0.01,
297
302
  payTo: '0xYourWallet',
298
- facilitatorUrl: 'https://your-facilitator.com'
299
- // No apiKey needed for self-hosted
303
+ facilitatorUrl: 'https://your-facilitator.com',
304
+ // REQUIRED: Must match FACILITATOR_SECRET in your facilitator's .env
305
+ facilitatorSecret: process.env.FACILITATOR_SECRET
300
306
  });
301
307
  ```
302
308
 
309
+ The `facilitatorSecret` is **required** for self-hosted facilitators to prevent unauthorized usage of your facilitator by third parties.
310
+
303
311
  Create a facilitator with:
304
312
  ```bash
305
313
  npx create-mantle-facilitator my-facilitator
306
314
  ```
307
315
 
316
+ After setup, copy `FACILITATOR_SECRET` from the generated `.env` file to your backend's environment variables.
317
+
308
318
  ---
309
319
 
310
320
  ## Analytics & Telemetry
@@ -316,11 +326,11 @@ const pay = mantlePaywall({
316
326
  priceUsd: 0.01,
317
327
  payTo: '0x...',
318
328
  facilitatorUrl: 'https://facilitator.x402mantlesdk.xyz',
329
+ projectKey: 'pk_xxx', // Get from dashboard - used for both billing AND analytics
319
330
 
320
- // Analytics configuration
331
+ // Optional: Advanced telemetry config
321
332
  telemetry: {
322
- projectKey: 'pk_xxx', // Get from dashboard
323
- debug: true // Enable console logging
333
+ debug: true // Enable console logging (projectKey auto-derived from above)
324
334
  },
325
335
 
326
336
  // 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,108 @@
1
+ import {
2
+ buildRouteKey,
3
+ checkPayment,
4
+ validateAddress
5
+ } from "./chunk-6IR4GUG7.js";
6
+ import {
7
+ MANTLE_DEFAULTS,
8
+ __export,
9
+ getDefaultAssetForNetwork,
10
+ usdCentsToAtomic
11
+ } from "./chunk-HEZZ74SI.js";
12
+
13
+ // src/server/adapters/web-standards.ts
14
+ var web_standards_exports = {};
15
+ __export(web_standards_exports, {
16
+ mantlePaywall: () => mantlePaywall
17
+ });
18
+ function debugLog(config, prefix, message, data) {
19
+ if (config?.debug) {
20
+ const timestamp = (/* @__PURE__ */ new Date()).toISOString();
21
+ console.log(`[${timestamp}] [x402-debug:${prefix}]`, message, data || "");
22
+ }
23
+ }
24
+ function mantlePaywall(opts) {
25
+ const {
26
+ priceUsd,
27
+ payTo,
28
+ facilitatorUrl,
29
+ projectKey: inputProjectKey,
30
+ apiKey,
31
+ telemetry,
32
+ onPaymentSettled,
33
+ facilitatorSecret
34
+ } = opts;
35
+ const projectKey = inputProjectKey ?? apiKey;
36
+ const effectiveTelemetry = telemetry ? { ...telemetry, projectKey: telemetry.projectKey ?? projectKey ?? "" } : projectKey ? { projectKey } : void 0;
37
+ validateAddress(payTo, "payTo");
38
+ const priceUsdCents = Math.round(priceUsd * 100);
39
+ return function(handler) {
40
+ return async (request) => {
41
+ const url = new URL(request.url);
42
+ const method = request.method;
43
+ const path = url.pathname;
44
+ const routeKey = buildRouteKey(method, path);
45
+ const network = MANTLE_DEFAULTS.NETWORK;
46
+ const assetConfig = getDefaultAssetForNetwork(network);
47
+ const maxAmountRequiredBigInt = usdCentsToAtomic(
48
+ priceUsdCents,
49
+ assetConfig.decimals
50
+ );
51
+ const paymentRequirements = {
52
+ scheme: "exact",
53
+ network,
54
+ asset: assetConfig.address,
55
+ maxAmountRequired: maxAmountRequiredBigInt.toString(),
56
+ payTo,
57
+ price: `$${(priceUsdCents / 100).toFixed(2)}`,
58
+ currency: "USD"
59
+ };
60
+ const paymentHeader = request.headers.get("X-PAYMENT") || request.headers.get("x-payment") || null;
61
+ const result = await checkPayment({
62
+ paymentHeader,
63
+ paymentRequirements,
64
+ facilitatorUrl: facilitatorUrl || MANTLE_DEFAULTS.FACILITATOR_URL,
65
+ projectKey,
66
+ routeKey,
67
+ network,
68
+ asset: assetConfig.address,
69
+ telemetry: effectiveTelemetry,
70
+ onPaymentSettled,
71
+ facilitatorSecret
72
+ });
73
+ if (!result.isValid) {
74
+ return new Response(JSON.stringify(result.responseBody), {
75
+ status: result.statusCode,
76
+ headers: {
77
+ "Content-Type": "application/json"
78
+ }
79
+ });
80
+ }
81
+ try {
82
+ debugLog(effectiveTelemetry, "handler", "Handler execution started");
83
+ const response = await handler(request);
84
+ debugLog(effectiveTelemetry, "handler", `Handler completed: ${response.status}`);
85
+ if (result.sendTelemetryAfterResponse) {
86
+ debugLog(effectiveTelemetry, "callback", `Calling telemetry callback with status ${response.status}`);
87
+ result.sendTelemetryAfterResponse(response.status);
88
+ } else {
89
+ debugLog(effectiveTelemetry, "callback", "WARNING: No telemetry callback to call");
90
+ }
91
+ return response;
92
+ } catch (err) {
93
+ const errorMessage = err instanceof Error ? err.message : "Unknown error";
94
+ debugLog(effectiveTelemetry, "handler", `ERROR: Handler error: ${errorMessage}`);
95
+ if (result.sendTelemetryAfterResponse) {
96
+ debugLog(effectiveTelemetry, "callback", "Calling telemetry callback with error");
97
+ result.sendTelemetryAfterResponse(500, errorMessage);
98
+ }
99
+ throw err;
100
+ }
101
+ };
102
+ };
103
+ }
104
+
105
+ export {
106
+ mantlePaywall,
107
+ web_standards_exports
108
+ };