@puga-labs/x402-mantle-sdk 0.1.0 → 0.2.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.
package/dist/index.cjs CHANGED
@@ -20,8 +20,12 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
20
20
  // src/index.ts
21
21
  var index_exports = {};
22
22
  __export(index_exports, {
23
+ MANTLE_DEFAULTS: () => MANTLE_DEFAULTS,
24
+ createMantleClient: () => createMantleClient,
23
25
  createPaymentClient: () => createPaymentClient,
24
- createPaymentMiddleware: () => createPaymentMiddleware
26
+ createPaymentMiddleware: () => createPaymentMiddleware,
27
+ mantlePaywall: () => mantlePaywall,
28
+ useMantleX402: () => useMantleX402
25
29
  });
26
30
  module.exports = __toCommonJS(index_exports);
27
31
 
@@ -33,6 +37,15 @@ var MANTLE_MAINNET_USDC = {
33
37
  address: "0x09Bc4E0D864854c6aFB6eB9A9cdF58aC190D0dF9",
34
38
  decimals: 6
35
39
  };
40
+ var MANTLE_DEFAULTS = {
41
+ NETWORK: "mantle-mainnet",
42
+ CHAIN_ID: 5e3,
43
+ USDC_ADDRESS: "0x09Bc4E0D864854c6aFB6eB9A9cdF58aC190D0dF9",
44
+ USDC_DECIMALS: 6,
45
+ CURRENCY: "USD",
46
+ SCHEME: "exact",
47
+ FACILITATOR_URL: (typeof process !== "undefined" ? process.env?.NEXT_PUBLIC_FACILITATOR_URL : void 0) || "http://localhost:8080"
48
+ };
36
49
  function getDefaultAssetForNetwork(network) {
37
50
  switch (network) {
38
51
  case MANTLE_MAINNET_NETWORK_ID:
@@ -58,6 +71,59 @@ function usdCentsToAtomic(cents, decimals) {
58
71
  return BigInt(cents) * base;
59
72
  }
60
73
 
74
+ // src/server/constants.ts
75
+ var DEFAULT_TELEMETRY_ENDPOINT = void 0;
76
+
77
+ // src/server/telemetry.ts
78
+ function createTelemetryEvent(entry, config) {
79
+ const assetConfig = getDefaultAssetForNetwork(entry.network);
80
+ return {
81
+ event: "payment_verified",
82
+ ts: entry.timestamp,
83
+ projectKey: config.projectKey,
84
+ network: entry.network,
85
+ buyer: entry.from,
86
+ payTo: entry.to,
87
+ amountAtomic: entry.valueAtomic,
88
+ asset: entry.asset,
89
+ decimals: assetConfig.decimals,
90
+ nonce: entry.id,
91
+ route: entry.route ?? "unknown",
92
+ // Facilitator metadata
93
+ facilitatorType: "hosted",
94
+ // SDK always uses hosted mode
95
+ facilitatorUrl: entry.facilitatorUrl,
96
+ // From PaymentLogEntry
97
+ // facilitatorAddress is undefined for SDK (not available)
98
+ // Optional metadata
99
+ txHash: entry.txHash,
100
+ priceUsd: entry.paymentRequirements?.price
101
+ };
102
+ }
103
+ async function sendTelemetry(event, endpoint) {
104
+ const targetEndpoint = endpoint ?? DEFAULT_TELEMETRY_ENDPOINT;
105
+ if (!targetEndpoint) {
106
+ return;
107
+ }
108
+ try {
109
+ const response = await fetch(targetEndpoint, {
110
+ method: "POST",
111
+ headers: {
112
+ "Content-Type": "application/json",
113
+ "Authorization": `Bearer ${event.projectKey}`
114
+ },
115
+ body: JSON.stringify(event)
116
+ });
117
+ if (!response.ok) {
118
+ console.warn(
119
+ `[x402-telemetry] Failed to send event: HTTP ${response.status}`
120
+ );
121
+ }
122
+ } catch (err) {
123
+ console.error("[x402-telemetry] Error sending telemetry:", err);
124
+ }
125
+ }
126
+
61
127
  // src/server/paymentMiddleware.ts
62
128
  function getRouteKey(req) {
63
129
  const method = (req.method || "GET").toUpperCase();
@@ -81,7 +147,7 @@ function decodePaymentHeader(paymentHeaderBase64) {
81
147
  }
82
148
  }
83
149
  function createPaymentMiddleware(config) {
84
- const { facilitatorUrl, receiverAddress, routes, onPaymentSettled } = config;
150
+ const { facilitatorUrl, receiverAddress, routes, onPaymentSettled, telemetry } = config;
85
151
  if (!facilitatorUrl) {
86
152
  throw new Error("facilitatorUrl is required");
87
153
  }
@@ -171,9 +237,17 @@ function createPaymentMiddleware(config) {
171
237
  asset: assetConfig.address,
172
238
  route: routeKey,
173
239
  timestamp: Date.now(),
240
+ facilitatorUrl,
241
+ // Pass from config closure
174
242
  paymentRequirements
175
243
  };
176
244
  onPaymentSettled(logEntry);
245
+ if (telemetry) {
246
+ const event = createTelemetryEvent(logEntry, telemetry);
247
+ sendTelemetry(event, telemetry.endpoint).catch(
248
+ (err) => console.error("[x402-telemetry] Async send failed:", err)
249
+ );
250
+ }
177
251
  } catch (err) {
178
252
  console.error(
179
253
  "[x402-mantle-sdk] Error calling onPaymentSettled hook:",
@@ -198,6 +272,30 @@ function createPaymentMiddleware(config) {
198
272
  };
199
273
  }
200
274
 
275
+ // src/server/mantlePaywall.ts
276
+ function mantlePaywall(opts) {
277
+ const { priceUsd, payTo, facilitatorUrl, telemetry, onPaymentSettled } = opts;
278
+ const priceUsdCents = Math.round(priceUsd * 100);
279
+ return (req, res, next) => {
280
+ const method = (req.method || "GET").toUpperCase();
281
+ const path = req.path || "/";
282
+ const routeKey = `${method} ${path}`;
283
+ const middleware = createPaymentMiddleware({
284
+ facilitatorUrl: facilitatorUrl || MANTLE_DEFAULTS.FACILITATOR_URL,
285
+ receiverAddress: payTo,
286
+ routes: {
287
+ [routeKey]: {
288
+ priceUsdCents,
289
+ network: MANTLE_DEFAULTS.NETWORK
290
+ }
291
+ },
292
+ telemetry,
293
+ onPaymentSettled
294
+ });
295
+ return middleware(req, res, next);
296
+ };
297
+ }
298
+
201
299
  // src/shared/utils.ts
202
300
  function encodeJsonToBase64(value) {
203
301
  const json = JSON.stringify(value);
@@ -300,7 +398,8 @@ function createPaymentClient(config) {
300
398
  resourceUrl,
301
399
  facilitatorUrl,
302
400
  provider,
303
- userAddress: userAddressOverride
401
+ userAddress: userAddressOverride,
402
+ projectKey
304
403
  } = config;
305
404
  if (!resourceUrl) {
306
405
  throw new Error("resourceUrl is required");
@@ -387,7 +486,8 @@ function createPaymentClient(config) {
387
486
  const settleRes = await fetch(settleUrl, {
388
487
  method: "POST",
389
488
  headers: {
390
- "Content-Type": "application/json"
489
+ "Content-Type": "application/json",
490
+ ...projectKey ? { "X-Project-Key": projectKey } : {}
391
491
  },
392
492
  body: JSON.stringify({
393
493
  x402Version: 1,
@@ -439,8 +539,62 @@ function createPaymentClient(config) {
439
539
  }
440
540
  };
441
541
  }
542
+
543
+ // src/client/createMantleClient.ts
544
+ function createMantleClient(config) {
545
+ const resourceUrl = config?.resourceUrl ?? (typeof window !== "undefined" ? window.location.origin : "");
546
+ const facilitatorUrl = config?.facilitatorUrl ?? (typeof process !== "undefined" ? process.env?.NEXT_PUBLIC_FACILITATOR_URL : void 0) ?? "http://localhost:8080";
547
+ return {
548
+ async post(url, body) {
549
+ const account = await config?.getAccount?.();
550
+ if (!account) {
551
+ throw new Error(
552
+ "Wallet not connected. Please connect your wallet first."
553
+ );
554
+ }
555
+ const provider = config?.getProvider?.();
556
+ if (!provider) {
557
+ throw new Error("Wallet provider not available");
558
+ }
559
+ const client = createPaymentClient({
560
+ resourceUrl,
561
+ facilitatorUrl,
562
+ provider,
563
+ userAddress: account,
564
+ projectKey: config?.projectKey
565
+ });
566
+ const result = await client.callWithPayment(url, {
567
+ method: "POST",
568
+ body
569
+ });
570
+ return result.response;
571
+ }
572
+ };
573
+ }
574
+
575
+ // src/client/react/useMantleX402.ts
576
+ var import_wagmi = require("wagmi");
577
+ function useMantleX402(opts) {
578
+ const { address, isConnected } = (0, import_wagmi.useAccount)();
579
+ const { data: walletClient } = (0, import_wagmi.useWalletClient)();
580
+ const client = createMantleClient({
581
+ facilitatorUrl: opts?.facilitatorUrl,
582
+ resourceUrl: opts?.resourceUrl,
583
+ projectKey: opts?.projectKey,
584
+ getAccount: () => {
585
+ if (!isConnected || !address) return void 0;
586
+ return address;
587
+ },
588
+ getProvider: () => walletClient
589
+ });
590
+ return client;
591
+ }
442
592
  // Annotate the CommonJS export names for ESM import in node:
443
593
  0 && (module.exports = {
594
+ MANTLE_DEFAULTS,
595
+ createMantleClient,
444
596
  createPaymentClient,
445
- createPaymentMiddleware
597
+ createPaymentMiddleware,
598
+ mantlePaywall,
599
+ useMantleX402
446
600
  });
package/dist/index.d.cts CHANGED
@@ -42,6 +42,20 @@ interface PaymentHeaderObject {
42
42
  /** Base64-encoded payment header, sent in X-PAYMENT. */
43
43
  type PaymentHeaderBase64 = string;
44
44
 
45
+ /**
46
+ * Default values for Mantle mainnet x402 payments.
47
+ * These are used by the simplified API (mantlePaywall, createMantleClient).
48
+ */
49
+ declare const MANTLE_DEFAULTS: {
50
+ readonly NETWORK: "mantle-mainnet";
51
+ readonly CHAIN_ID: 5000;
52
+ readonly USDC_ADDRESS: "0x09Bc4E0D864854c6aFB6eB9A9cdF58aC190D0dF9";
53
+ readonly USDC_DECIMALS: 6;
54
+ readonly CURRENCY: "USD";
55
+ readonly SCHEME: "exact";
56
+ readonly FACILITATOR_URL: string;
57
+ };
58
+
45
59
  /** Unique key for a protected route, e.g. "GET /api/protected". */
46
60
  type RouteKey = string;
47
61
  /** Pricing config for a single route. */
@@ -64,8 +78,39 @@ interface PaymentLogEntry {
64
78
  route?: RouteKey;
65
79
  txHash?: string;
66
80
  timestamp: number;
81
+ facilitatorUrl?: string;
67
82
  paymentRequirements?: PaymentRequirements;
68
83
  }
84
+ /** Config for optional telemetry (billing/analytics). */
85
+ interface TelemetryConfig {
86
+ /** Project key from nosubs.ai dashboard. */
87
+ projectKey: string;
88
+ /**
89
+ * Telemetry endpoint URL.
90
+ * If not specified, uses DEFAULT_TELEMETRY_ENDPOINT (see server/constants.ts).
91
+ * If both are undefined, telemetry is not sent.
92
+ */
93
+ endpoint?: string;
94
+ }
95
+ /** Telemetry event payload for payment_verified. */
96
+ interface TelemetryEvent {
97
+ event: "payment_verified";
98
+ ts: number;
99
+ projectKey: string;
100
+ network: string;
101
+ buyer: string;
102
+ payTo: string;
103
+ amountAtomic: string;
104
+ asset: string;
105
+ decimals: number;
106
+ nonce: string;
107
+ route: string;
108
+ facilitatorType: "hosted" | "self-hosted";
109
+ facilitatorUrl?: string;
110
+ facilitatorAddress?: string;
111
+ txHash?: string;
112
+ priceUsd?: string;
113
+ }
69
114
  /** Config for createPaymentMiddleware. */
70
115
  interface PaymentMiddlewareConfig {
71
116
  /** Base URL of facilitator, e.g. https://facilitator.nosubs.ai */
@@ -79,10 +124,43 @@ interface PaymentMiddlewareConfig {
79
124
  * You can use this to push logs into your DB / analytics pipeline.
80
125
  */
81
126
  onPaymentSettled?: (entry: PaymentLogEntry) => void;
127
+ /** Optional: Send usage telemetry for billing/analytics. */
128
+ telemetry?: TelemetryConfig;
129
+ }
130
+ /**
131
+ * Minimal config for mantlePaywall() - simplified API for single-route protection.
132
+ * This is the "sweet path" for Mantle mainnet + USDC with sensible defaults.
133
+ */
134
+ interface MinimalPaywallOptions {
135
+ /** Price in USD (e.g. 0.01 for 1 cent). */
136
+ priceUsd: number;
137
+ /** Recipient address (developer wallet). */
138
+ payTo: `0x${string}`;
139
+ /** Optional facilitator URL (defaults to localhost:8080 or NEXT_PUBLIC_FACILITATOR_URL). */
140
+ facilitatorUrl?: string;
141
+ /** Optional telemetry config. */
142
+ telemetry?: TelemetryConfig;
143
+ /** Optional payment settled hook. */
144
+ onPaymentSettled?: (entry: PaymentLogEntry) => void;
82
145
  }
83
146
 
84
147
  declare function createPaymentMiddleware(config: PaymentMiddlewareConfig): (req: Request, res: Response, next: NextFunction) => Promise<void>;
85
148
 
149
+ /**
150
+ * Simplified wrapper for protecting a single route with x402 payments.
151
+ * Uses Mantle mainnet defaults (USDC, exact scheme, etc.).
152
+ *
153
+ * Usage:
154
+ * ```typescript
155
+ * const pay = mantlePaywall({ priceUsd: 0.01, payTo: "0x..." });
156
+ * export const POST = pay(async (req) => { ... });
157
+ * ```
158
+ *
159
+ * @param opts - Minimal configuration (price, payTo, optional facilitator/telemetry).
160
+ * @returns Express middleware function for single-route protection.
161
+ */
162
+ declare function mantlePaywall(opts: MinimalPaywallOptions): (req: Request, res: Response, next: NextFunction) => Promise<void>;
163
+
86
164
  /** Config for the client-side payment helper. */
87
165
  interface PaymentClientConfig {
88
166
  /** Base URL of your protected resource server. */
@@ -93,6 +171,8 @@ interface PaymentClientConfig {
93
171
  provider: unknown;
94
172
  /** Optional user address override; otherwise derived from provider. */
95
173
  userAddress?: string;
174
+ /** Optional: Project key for hosted facilitator billing. */
175
+ projectKey?: string;
96
176
  }
97
177
  /** Result of a callWithPayment() client operation. */
98
178
  interface CallWithPaymentResult<TResponseBody = unknown> {
@@ -122,8 +202,89 @@ interface PaymentClient {
122
202
  * - calls facilitator /settle
123
203
  * - retries the original request with X-PAYMENT header
124
204
  *
125
- * This logic is x402-like and tailored for Mantle + USDC.
205
+ * This logic is x402 and tailored for Mantle + USDC.
126
206
  */
127
207
  declare function createPaymentClient(config: PaymentClientConfig): PaymentClient;
128
208
 
129
- export { type AssetConfig, type Authorization, type CallWithPaymentResult, type NetworkId, type PaymentClient, type PaymentClientConfig, type PaymentHeaderBase64, type PaymentHeaderObject, type PaymentHeaderPayload, type PaymentLogEntry, type PaymentMiddlewareConfig, type PaymentRequirements, type RouteKey, type RoutePricingConfig, type RoutesConfig, createPaymentClient, createPaymentMiddleware };
209
+ /**
210
+ * Configuration for createMantleClient().
211
+ * All fields are optional - the client auto-detects sensible defaults.
212
+ */
213
+ interface MantleClientConfig {
214
+ /** Optional facilitator URL (auto-detects from NEXT_PUBLIC_FACILITATOR_URL or defaults to localhost:8080). */
215
+ facilitatorUrl?: string;
216
+ /** Optional resource URL (defaults to current origin in browser, or empty string for relative paths). */
217
+ resourceUrl?: string;
218
+ /** Function to get user's wallet address (required for payments). */
219
+ getAccount?: () => Promise<string | undefined> | string | undefined;
220
+ /** Function to get wallet provider/client (e.g., viem WalletClient or window.ethereum). */
221
+ getProvider?: () => any;
222
+ /** Optional project key for hosted facilitator billing. */
223
+ projectKey?: string;
224
+ }
225
+ /**
226
+ * Simplified Mantle payment client interface.
227
+ * Provides a clean API for making paid POST requests.
228
+ */
229
+ interface MantleClient {
230
+ /**
231
+ * Make a paid POST request to a protected endpoint.
232
+ * Automatically handles x402 flow (402 response, signing, payment, retry).
233
+ *
234
+ * @param url - API endpoint path (e.g., "/api/generate-image").
235
+ * @param body - Request body (will be JSON stringified).
236
+ * @returns Response data from the protected endpoint.
237
+ * @throws Error if wallet is not connected or payment fails.
238
+ */
239
+ post<TResp = any>(url: string, body?: any): Promise<TResp>;
240
+ }
241
+ /**
242
+ * Create a simplified Mantle payment client with auto-detected defaults.
243
+ *
244
+ * Usage:
245
+ * ```typescript
246
+ * const client = createMantleClient({
247
+ * getAccount: () => account?.address,
248
+ * getProvider: () => walletClient,
249
+ * });
250
+ *
251
+ * const data = await client.post("/api/generate", { prompt: "..." });
252
+ * ```
253
+ *
254
+ * @param config - Optional configuration (auto-detects facilitatorUrl and resourceUrl).
255
+ * @returns MantleClient instance with simplified post() method.
256
+ */
257
+ declare function createMantleClient(config?: MantleClientConfig): MantleClient;
258
+
259
+ /**
260
+ * Options for useMantleX402 React hook.
261
+ */
262
+ interface UseMantleX402Options {
263
+ /** Optional facilitator URL (auto-detects from NEXT_PUBLIC_FACILITATOR_URL). */
264
+ facilitatorUrl?: string;
265
+ /** Optional resource URL (defaults to current origin). */
266
+ resourceUrl?: string;
267
+ /** Optional project key for hosted facilitator billing. */
268
+ projectKey?: string;
269
+ }
270
+ /**
271
+ * React hook for simplified Mantle x402 payments with wagmi integration.
272
+ *
273
+ * Automatically connects to the user's wallet via wagmi hooks and provides
274
+ * a clean API for making paid requests.
275
+ *
276
+ * Usage:
277
+ * ```typescript
278
+ * const { post } = useMantleX402();
279
+ *
280
+ * const data = await post("/api/generate-image", {
281
+ * prompt: "A beautiful sunset"
282
+ * });
283
+ * ```
284
+ *
285
+ * @param opts - Optional configuration (facilitatorUrl, resourceUrl, projectKey).
286
+ * @returns MantleClient instance with post() method.
287
+ */
288
+ declare function useMantleX402(opts?: UseMantleX402Options): MantleClient;
289
+
290
+ export { type AssetConfig, type Authorization, type CallWithPaymentResult, MANTLE_DEFAULTS, type MantleClient, type MantleClientConfig, type MinimalPaywallOptions, type NetworkId, type PaymentClient, type PaymentClientConfig, type PaymentHeaderBase64, type PaymentHeaderObject, type PaymentHeaderPayload, type PaymentLogEntry, type PaymentMiddlewareConfig, type PaymentRequirements, type RouteKey, type RoutePricingConfig, type RoutesConfig, type TelemetryConfig, type TelemetryEvent, type UseMantleX402Options, createMantleClient, createPaymentClient, createPaymentMiddleware, mantlePaywall, useMantleX402 };
package/dist/index.d.ts CHANGED
@@ -42,6 +42,20 @@ interface PaymentHeaderObject {
42
42
  /** Base64-encoded payment header, sent in X-PAYMENT. */
43
43
  type PaymentHeaderBase64 = string;
44
44
 
45
+ /**
46
+ * Default values for Mantle mainnet x402 payments.
47
+ * These are used by the simplified API (mantlePaywall, createMantleClient).
48
+ */
49
+ declare const MANTLE_DEFAULTS: {
50
+ readonly NETWORK: "mantle-mainnet";
51
+ readonly CHAIN_ID: 5000;
52
+ readonly USDC_ADDRESS: "0x09Bc4E0D864854c6aFB6eB9A9cdF58aC190D0dF9";
53
+ readonly USDC_DECIMALS: 6;
54
+ readonly CURRENCY: "USD";
55
+ readonly SCHEME: "exact";
56
+ readonly FACILITATOR_URL: string;
57
+ };
58
+
45
59
  /** Unique key for a protected route, e.g. "GET /api/protected". */
46
60
  type RouteKey = string;
47
61
  /** Pricing config for a single route. */
@@ -64,8 +78,39 @@ interface PaymentLogEntry {
64
78
  route?: RouteKey;
65
79
  txHash?: string;
66
80
  timestamp: number;
81
+ facilitatorUrl?: string;
67
82
  paymentRequirements?: PaymentRequirements;
68
83
  }
84
+ /** Config for optional telemetry (billing/analytics). */
85
+ interface TelemetryConfig {
86
+ /** Project key from nosubs.ai dashboard. */
87
+ projectKey: string;
88
+ /**
89
+ * Telemetry endpoint URL.
90
+ * If not specified, uses DEFAULT_TELEMETRY_ENDPOINT (see server/constants.ts).
91
+ * If both are undefined, telemetry is not sent.
92
+ */
93
+ endpoint?: string;
94
+ }
95
+ /** Telemetry event payload for payment_verified. */
96
+ interface TelemetryEvent {
97
+ event: "payment_verified";
98
+ ts: number;
99
+ projectKey: string;
100
+ network: string;
101
+ buyer: string;
102
+ payTo: string;
103
+ amountAtomic: string;
104
+ asset: string;
105
+ decimals: number;
106
+ nonce: string;
107
+ route: string;
108
+ facilitatorType: "hosted" | "self-hosted";
109
+ facilitatorUrl?: string;
110
+ facilitatorAddress?: string;
111
+ txHash?: string;
112
+ priceUsd?: string;
113
+ }
69
114
  /** Config for createPaymentMiddleware. */
70
115
  interface PaymentMiddlewareConfig {
71
116
  /** Base URL of facilitator, e.g. https://facilitator.nosubs.ai */
@@ -79,10 +124,43 @@ interface PaymentMiddlewareConfig {
79
124
  * You can use this to push logs into your DB / analytics pipeline.
80
125
  */
81
126
  onPaymentSettled?: (entry: PaymentLogEntry) => void;
127
+ /** Optional: Send usage telemetry for billing/analytics. */
128
+ telemetry?: TelemetryConfig;
129
+ }
130
+ /**
131
+ * Minimal config for mantlePaywall() - simplified API for single-route protection.
132
+ * This is the "sweet path" for Mantle mainnet + USDC with sensible defaults.
133
+ */
134
+ interface MinimalPaywallOptions {
135
+ /** Price in USD (e.g. 0.01 for 1 cent). */
136
+ priceUsd: number;
137
+ /** Recipient address (developer wallet). */
138
+ payTo: `0x${string}`;
139
+ /** Optional facilitator URL (defaults to localhost:8080 or NEXT_PUBLIC_FACILITATOR_URL). */
140
+ facilitatorUrl?: string;
141
+ /** Optional telemetry config. */
142
+ telemetry?: TelemetryConfig;
143
+ /** Optional payment settled hook. */
144
+ onPaymentSettled?: (entry: PaymentLogEntry) => void;
82
145
  }
83
146
 
84
147
  declare function createPaymentMiddleware(config: PaymentMiddlewareConfig): (req: Request, res: Response, next: NextFunction) => Promise<void>;
85
148
 
149
+ /**
150
+ * Simplified wrapper for protecting a single route with x402 payments.
151
+ * Uses Mantle mainnet defaults (USDC, exact scheme, etc.).
152
+ *
153
+ * Usage:
154
+ * ```typescript
155
+ * const pay = mantlePaywall({ priceUsd: 0.01, payTo: "0x..." });
156
+ * export const POST = pay(async (req) => { ... });
157
+ * ```
158
+ *
159
+ * @param opts - Minimal configuration (price, payTo, optional facilitator/telemetry).
160
+ * @returns Express middleware function for single-route protection.
161
+ */
162
+ declare function mantlePaywall(opts: MinimalPaywallOptions): (req: Request, res: Response, next: NextFunction) => Promise<void>;
163
+
86
164
  /** Config for the client-side payment helper. */
87
165
  interface PaymentClientConfig {
88
166
  /** Base URL of your protected resource server. */
@@ -93,6 +171,8 @@ interface PaymentClientConfig {
93
171
  provider: unknown;
94
172
  /** Optional user address override; otherwise derived from provider. */
95
173
  userAddress?: string;
174
+ /** Optional: Project key for hosted facilitator billing. */
175
+ projectKey?: string;
96
176
  }
97
177
  /** Result of a callWithPayment() client operation. */
98
178
  interface CallWithPaymentResult<TResponseBody = unknown> {
@@ -122,8 +202,89 @@ interface PaymentClient {
122
202
  * - calls facilitator /settle
123
203
  * - retries the original request with X-PAYMENT header
124
204
  *
125
- * This logic is x402-like and tailored for Mantle + USDC.
205
+ * This logic is x402 and tailored for Mantle + USDC.
126
206
  */
127
207
  declare function createPaymentClient(config: PaymentClientConfig): PaymentClient;
128
208
 
129
- export { type AssetConfig, type Authorization, type CallWithPaymentResult, type NetworkId, type PaymentClient, type PaymentClientConfig, type PaymentHeaderBase64, type PaymentHeaderObject, type PaymentHeaderPayload, type PaymentLogEntry, type PaymentMiddlewareConfig, type PaymentRequirements, type RouteKey, type RoutePricingConfig, type RoutesConfig, createPaymentClient, createPaymentMiddleware };
209
+ /**
210
+ * Configuration for createMantleClient().
211
+ * All fields are optional - the client auto-detects sensible defaults.
212
+ */
213
+ interface MantleClientConfig {
214
+ /** Optional facilitator URL (auto-detects from NEXT_PUBLIC_FACILITATOR_URL or defaults to localhost:8080). */
215
+ facilitatorUrl?: string;
216
+ /** Optional resource URL (defaults to current origin in browser, or empty string for relative paths). */
217
+ resourceUrl?: string;
218
+ /** Function to get user's wallet address (required for payments). */
219
+ getAccount?: () => Promise<string | undefined> | string | undefined;
220
+ /** Function to get wallet provider/client (e.g., viem WalletClient or window.ethereum). */
221
+ getProvider?: () => any;
222
+ /** Optional project key for hosted facilitator billing. */
223
+ projectKey?: string;
224
+ }
225
+ /**
226
+ * Simplified Mantle payment client interface.
227
+ * Provides a clean API for making paid POST requests.
228
+ */
229
+ interface MantleClient {
230
+ /**
231
+ * Make a paid POST request to a protected endpoint.
232
+ * Automatically handles x402 flow (402 response, signing, payment, retry).
233
+ *
234
+ * @param url - API endpoint path (e.g., "/api/generate-image").
235
+ * @param body - Request body (will be JSON stringified).
236
+ * @returns Response data from the protected endpoint.
237
+ * @throws Error if wallet is not connected or payment fails.
238
+ */
239
+ post<TResp = any>(url: string, body?: any): Promise<TResp>;
240
+ }
241
+ /**
242
+ * Create a simplified Mantle payment client with auto-detected defaults.
243
+ *
244
+ * Usage:
245
+ * ```typescript
246
+ * const client = createMantleClient({
247
+ * getAccount: () => account?.address,
248
+ * getProvider: () => walletClient,
249
+ * });
250
+ *
251
+ * const data = await client.post("/api/generate", { prompt: "..." });
252
+ * ```
253
+ *
254
+ * @param config - Optional configuration (auto-detects facilitatorUrl and resourceUrl).
255
+ * @returns MantleClient instance with simplified post() method.
256
+ */
257
+ declare function createMantleClient(config?: MantleClientConfig): MantleClient;
258
+
259
+ /**
260
+ * Options for useMantleX402 React hook.
261
+ */
262
+ interface UseMantleX402Options {
263
+ /** Optional facilitator URL (auto-detects from NEXT_PUBLIC_FACILITATOR_URL). */
264
+ facilitatorUrl?: string;
265
+ /** Optional resource URL (defaults to current origin). */
266
+ resourceUrl?: string;
267
+ /** Optional project key for hosted facilitator billing. */
268
+ projectKey?: string;
269
+ }
270
+ /**
271
+ * React hook for simplified Mantle x402 payments with wagmi integration.
272
+ *
273
+ * Automatically connects to the user's wallet via wagmi hooks and provides
274
+ * a clean API for making paid requests.
275
+ *
276
+ * Usage:
277
+ * ```typescript
278
+ * const { post } = useMantleX402();
279
+ *
280
+ * const data = await post("/api/generate-image", {
281
+ * prompt: "A beautiful sunset"
282
+ * });
283
+ * ```
284
+ *
285
+ * @param opts - Optional configuration (facilitatorUrl, resourceUrl, projectKey).
286
+ * @returns MantleClient instance with post() method.
287
+ */
288
+ declare function useMantleX402(opts?: UseMantleX402Options): MantleClient;
289
+
290
+ export { type AssetConfig, type Authorization, type CallWithPaymentResult, MANTLE_DEFAULTS, type MantleClient, type MantleClientConfig, type MinimalPaywallOptions, type NetworkId, type PaymentClient, type PaymentClientConfig, type PaymentHeaderBase64, type PaymentHeaderObject, type PaymentHeaderPayload, type PaymentLogEntry, type PaymentMiddlewareConfig, type PaymentRequirements, type RouteKey, type RoutePricingConfig, type RoutesConfig, type TelemetryConfig, type TelemetryEvent, type UseMantleX402Options, createMantleClient, createPaymentClient, createPaymentMiddleware, mantlePaywall, useMantleX402 };
package/dist/index.js CHANGED
@@ -13,6 +13,15 @@ var MANTLE_MAINNET_USDC = {
13
13
  address: "0x09Bc4E0D864854c6aFB6eB9A9cdF58aC190D0dF9",
14
14
  decimals: 6
15
15
  };
16
+ var MANTLE_DEFAULTS = {
17
+ NETWORK: "mantle-mainnet",
18
+ CHAIN_ID: 5e3,
19
+ USDC_ADDRESS: "0x09Bc4E0D864854c6aFB6eB9A9cdF58aC190D0dF9",
20
+ USDC_DECIMALS: 6,
21
+ CURRENCY: "USD",
22
+ SCHEME: "exact",
23
+ FACILITATOR_URL: (typeof process !== "undefined" ? process.env?.NEXT_PUBLIC_FACILITATOR_URL : void 0) || "http://localhost:8080"
24
+ };
16
25
  function getDefaultAssetForNetwork(network) {
17
26
  switch (network) {
18
27
  case MANTLE_MAINNET_NETWORK_ID:
@@ -38,6 +47,59 @@ function usdCentsToAtomic(cents, decimals) {
38
47
  return BigInt(cents) * base;
39
48
  }
40
49
 
50
+ // src/server/constants.ts
51
+ var DEFAULT_TELEMETRY_ENDPOINT = void 0;
52
+
53
+ // src/server/telemetry.ts
54
+ function createTelemetryEvent(entry, config) {
55
+ const assetConfig = getDefaultAssetForNetwork(entry.network);
56
+ return {
57
+ event: "payment_verified",
58
+ ts: entry.timestamp,
59
+ projectKey: config.projectKey,
60
+ network: entry.network,
61
+ buyer: entry.from,
62
+ payTo: entry.to,
63
+ amountAtomic: entry.valueAtomic,
64
+ asset: entry.asset,
65
+ decimals: assetConfig.decimals,
66
+ nonce: entry.id,
67
+ route: entry.route ?? "unknown",
68
+ // Facilitator metadata
69
+ facilitatorType: "hosted",
70
+ // SDK always uses hosted mode
71
+ facilitatorUrl: entry.facilitatorUrl,
72
+ // From PaymentLogEntry
73
+ // facilitatorAddress is undefined for SDK (not available)
74
+ // Optional metadata
75
+ txHash: entry.txHash,
76
+ priceUsd: entry.paymentRequirements?.price
77
+ };
78
+ }
79
+ async function sendTelemetry(event, endpoint) {
80
+ const targetEndpoint = endpoint ?? DEFAULT_TELEMETRY_ENDPOINT;
81
+ if (!targetEndpoint) {
82
+ return;
83
+ }
84
+ try {
85
+ const response = await fetch(targetEndpoint, {
86
+ method: "POST",
87
+ headers: {
88
+ "Content-Type": "application/json",
89
+ "Authorization": `Bearer ${event.projectKey}`
90
+ },
91
+ body: JSON.stringify(event)
92
+ });
93
+ if (!response.ok) {
94
+ console.warn(
95
+ `[x402-telemetry] Failed to send event: HTTP ${response.status}`
96
+ );
97
+ }
98
+ } catch (err) {
99
+ console.error("[x402-telemetry] Error sending telemetry:", err);
100
+ }
101
+ }
102
+
41
103
  // src/server/paymentMiddleware.ts
42
104
  function getRouteKey(req) {
43
105
  const method = (req.method || "GET").toUpperCase();
@@ -61,7 +123,7 @@ function decodePaymentHeader(paymentHeaderBase64) {
61
123
  }
62
124
  }
63
125
  function createPaymentMiddleware(config) {
64
- const { facilitatorUrl, receiverAddress, routes, onPaymentSettled } = config;
126
+ const { facilitatorUrl, receiverAddress, routes, onPaymentSettled, telemetry } = config;
65
127
  if (!facilitatorUrl) {
66
128
  throw new Error("facilitatorUrl is required");
67
129
  }
@@ -151,9 +213,17 @@ function createPaymentMiddleware(config) {
151
213
  asset: assetConfig.address,
152
214
  route: routeKey,
153
215
  timestamp: Date.now(),
216
+ facilitatorUrl,
217
+ // Pass from config closure
154
218
  paymentRequirements
155
219
  };
156
220
  onPaymentSettled(logEntry);
221
+ if (telemetry) {
222
+ const event = createTelemetryEvent(logEntry, telemetry);
223
+ sendTelemetry(event, telemetry.endpoint).catch(
224
+ (err) => console.error("[x402-telemetry] Async send failed:", err)
225
+ );
226
+ }
157
227
  } catch (err) {
158
228
  console.error(
159
229
  "[x402-mantle-sdk] Error calling onPaymentSettled hook:",
@@ -178,6 +248,30 @@ function createPaymentMiddleware(config) {
178
248
  };
179
249
  }
180
250
 
251
+ // src/server/mantlePaywall.ts
252
+ function mantlePaywall(opts) {
253
+ const { priceUsd, payTo, facilitatorUrl, telemetry, onPaymentSettled } = opts;
254
+ const priceUsdCents = Math.round(priceUsd * 100);
255
+ return (req, res, next) => {
256
+ const method = (req.method || "GET").toUpperCase();
257
+ const path = req.path || "/";
258
+ const routeKey = `${method} ${path}`;
259
+ const middleware = createPaymentMiddleware({
260
+ facilitatorUrl: facilitatorUrl || MANTLE_DEFAULTS.FACILITATOR_URL,
261
+ receiverAddress: payTo,
262
+ routes: {
263
+ [routeKey]: {
264
+ priceUsdCents,
265
+ network: MANTLE_DEFAULTS.NETWORK
266
+ }
267
+ },
268
+ telemetry,
269
+ onPaymentSettled
270
+ });
271
+ return middleware(req, res, next);
272
+ };
273
+ }
274
+
181
275
  // src/shared/utils.ts
182
276
  function encodeJsonToBase64(value) {
183
277
  const json = JSON.stringify(value);
@@ -280,7 +374,8 @@ function createPaymentClient(config) {
280
374
  resourceUrl,
281
375
  facilitatorUrl,
282
376
  provider,
283
- userAddress: userAddressOverride
377
+ userAddress: userAddressOverride,
378
+ projectKey
284
379
  } = config;
285
380
  if (!resourceUrl) {
286
381
  throw new Error("resourceUrl is required");
@@ -367,7 +462,8 @@ function createPaymentClient(config) {
367
462
  const settleRes = await fetch(settleUrl, {
368
463
  method: "POST",
369
464
  headers: {
370
- "Content-Type": "application/json"
465
+ "Content-Type": "application/json",
466
+ ...projectKey ? { "X-Project-Key": projectKey } : {}
371
467
  },
372
468
  body: JSON.stringify({
373
469
  x402Version: 1,
@@ -419,7 +515,61 @@ function createPaymentClient(config) {
419
515
  }
420
516
  };
421
517
  }
518
+
519
+ // src/client/createMantleClient.ts
520
+ function createMantleClient(config) {
521
+ const resourceUrl = config?.resourceUrl ?? (typeof window !== "undefined" ? window.location.origin : "");
522
+ const facilitatorUrl = config?.facilitatorUrl ?? (typeof process !== "undefined" ? process.env?.NEXT_PUBLIC_FACILITATOR_URL : void 0) ?? "http://localhost:8080";
523
+ return {
524
+ async post(url, body) {
525
+ const account = await config?.getAccount?.();
526
+ if (!account) {
527
+ throw new Error(
528
+ "Wallet not connected. Please connect your wallet first."
529
+ );
530
+ }
531
+ const provider = config?.getProvider?.();
532
+ if (!provider) {
533
+ throw new Error("Wallet provider not available");
534
+ }
535
+ const client = createPaymentClient({
536
+ resourceUrl,
537
+ facilitatorUrl,
538
+ provider,
539
+ userAddress: account,
540
+ projectKey: config?.projectKey
541
+ });
542
+ const result = await client.callWithPayment(url, {
543
+ method: "POST",
544
+ body
545
+ });
546
+ return result.response;
547
+ }
548
+ };
549
+ }
550
+
551
+ // src/client/react/useMantleX402.ts
552
+ import { useAccount, useWalletClient } from "wagmi";
553
+ function useMantleX402(opts) {
554
+ const { address, isConnected } = useAccount();
555
+ const { data: walletClient } = useWalletClient();
556
+ const client = createMantleClient({
557
+ facilitatorUrl: opts?.facilitatorUrl,
558
+ resourceUrl: opts?.resourceUrl,
559
+ projectKey: opts?.projectKey,
560
+ getAccount: () => {
561
+ if (!isConnected || !address) return void 0;
562
+ return address;
563
+ },
564
+ getProvider: () => walletClient
565
+ });
566
+ return client;
567
+ }
422
568
  export {
569
+ MANTLE_DEFAULTS,
570
+ createMantleClient,
423
571
  createPaymentClient,
424
- createPaymentMiddleware
572
+ createPaymentMiddleware,
573
+ mantlePaywall,
574
+ useMantleX402
425
575
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@puga-labs/x402-mantle-sdk",
3
- "version": "0.1.0",
3
+ "version": "0.2.1",
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>",
@@ -46,7 +46,13 @@
46
46
  "test:watch": "vitest watch"
47
47
  },
48
48
  "peerDependencies": {
49
- "ethers": "^6.0.0"
49
+ "ethers": "^6.0.0",
50
+ "wagmi": "^2.0.0"
51
+ },
52
+ "peerDependenciesMeta": {
53
+ "wagmi": {
54
+ "optional": true
55
+ }
50
56
  },
51
57
  "devDependencies": {
52
58
  "@eslint/js": "^9.17.0",
@@ -56,6 +62,7 @@
56
62
  "@typescript-eslint/parser": "^8.20.0",
57
63
  "@vitest/coverage-v8": "^4.0.15",
58
64
  "@vitest/ui": "^4.0.15",
65
+ "@wagmi/core": "^2.22.1",
59
66
  "eslint": "^9.17.0",
60
67
  "express": "^5.2.1",
61
68
  "globals": "^15.14.0",
@@ -63,6 +70,8 @@
63
70
  "rimraf": "^6.0.0",
64
71
  "tsup": "^8.0.0",
65
72
  "typescript": "^5.6.0",
66
- "vitest": "^4.0.15"
73
+ "viem": "^2.41.2",
74
+ "vitest": "^4.0.15",
75
+ "wagmi": "^2.19.5"
67
76
  }
68
77
  }