@puga-labs/x402-mantle-sdk 0.1.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.
package/dist/index.cjs ADDED
@@ -0,0 +1,446 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/index.ts
21
+ var index_exports = {};
22
+ __export(index_exports, {
23
+ createPaymentClient: () => createPaymentClient,
24
+ createPaymentMiddleware: () => createPaymentMiddleware
25
+ });
26
+ module.exports = __toCommonJS(index_exports);
27
+
28
+ // src/shared/constants.ts
29
+ var MANTLE_MAINNET_NETWORK_ID = "mantle-mainnet";
30
+ var MANTLE_MAINNET_CHAIN_ID = 5e3;
31
+ var MANTLE_MAINNET_USDC = {
32
+ symbol: "USDC",
33
+ address: "0x09Bc4E0D864854c6aFB6eB9A9cdF58aC190D0dF9",
34
+ decimals: 6
35
+ };
36
+ function getDefaultAssetForNetwork(network) {
37
+ switch (network) {
38
+ case MANTLE_MAINNET_NETWORK_ID:
39
+ default:
40
+ return MANTLE_MAINNET_USDC;
41
+ }
42
+ }
43
+ function getChainIdForNetwork(network) {
44
+ switch (network) {
45
+ case MANTLE_MAINNET_NETWORK_ID:
46
+ default:
47
+ return MANTLE_MAINNET_CHAIN_ID;
48
+ }
49
+ }
50
+ function usdCentsToAtomic(cents, decimals) {
51
+ if (cents < 0) {
52
+ throw new Error("priceUsdCents must be non-negative");
53
+ }
54
+ if (decimals < 2) {
55
+ throw new Error("token decimals must be >= 2 for USD cent conversion");
56
+ }
57
+ const base = BigInt(10) ** BigInt(decimals - 2);
58
+ return BigInt(cents) * base;
59
+ }
60
+
61
+ // src/server/paymentMiddleware.ts
62
+ function getRouteKey(req) {
63
+ const method = (req.method || "GET").toUpperCase();
64
+ const path = req.path || "/";
65
+ return `${method} ${path}`;
66
+ }
67
+ function decodePaymentHeader(paymentHeaderBase64) {
68
+ try {
69
+ if (typeof Buffer !== "undefined") {
70
+ const json = Buffer.from(paymentHeaderBase64, "base64").toString("utf8");
71
+ return JSON.parse(json);
72
+ }
73
+ if (typeof atob === "function") {
74
+ const json = atob(paymentHeaderBase64);
75
+ return JSON.parse(json);
76
+ }
77
+ throw new Error("No base64 decoding available in this environment");
78
+ } catch (err) {
79
+ const msg = err instanceof Error ? err.message : "Unknown error";
80
+ throw new Error(`Failed to decode paymentHeader: ${msg}`);
81
+ }
82
+ }
83
+ function createPaymentMiddleware(config) {
84
+ const { facilitatorUrl, receiverAddress, routes, onPaymentSettled } = config;
85
+ if (!facilitatorUrl) {
86
+ throw new Error("facilitatorUrl is required");
87
+ }
88
+ if (!receiverAddress) {
89
+ throw new Error("receiverAddress is required");
90
+ }
91
+ if (!routes || Object.keys(routes).length === 0) {
92
+ throw new Error("routes config must not be empty");
93
+ }
94
+ return async function paymentMiddleware(req, res, next) {
95
+ const routeKey = getRouteKey(req);
96
+ const routeConfig = routes[routeKey];
97
+ if (!routeConfig) {
98
+ next();
99
+ return;
100
+ }
101
+ const { priceUsdCents, network } = routeConfig;
102
+ const assetConfig = getDefaultAssetForNetwork(network);
103
+ const maxAmountRequiredBigInt = usdCentsToAtomic(
104
+ priceUsdCents,
105
+ assetConfig.decimals
106
+ );
107
+ const paymentRequirements = {
108
+ scheme: "exact",
109
+ network,
110
+ asset: assetConfig.address,
111
+ maxAmountRequired: maxAmountRequiredBigInt.toString(),
112
+ payTo: receiverAddress,
113
+ price: `$${(priceUsdCents / 100).toFixed(2)}`,
114
+ currency: "USD"
115
+ };
116
+ const paymentHeader = req.header("X-PAYMENT") ?? req.header("x-payment");
117
+ if (!paymentHeader) {
118
+ res.status(402).json({
119
+ error: "Payment Required",
120
+ paymentRequirements,
121
+ paymentHeader: null
122
+ });
123
+ return;
124
+ }
125
+ try {
126
+ const verifyUrl = `${facilitatorUrl.replace(/\/+$/, "")}/verify`;
127
+ const verifyRes = await fetch(verifyUrl, {
128
+ method: "POST",
129
+ headers: {
130
+ "Content-Type": "application/json"
131
+ },
132
+ body: JSON.stringify({
133
+ x402Version: 1,
134
+ paymentHeader,
135
+ paymentRequirements
136
+ })
137
+ });
138
+ if (!verifyRes.ok) {
139
+ const text = await verifyRes.text().catch(() => "");
140
+ console.error(
141
+ "[x402-mantle-sdk] Facilitator /verify returned non-OK:",
142
+ verifyRes.status,
143
+ text
144
+ );
145
+ res.status(500).json({
146
+ error: "Payment verification error",
147
+ details: `Facilitator responded with HTTP ${verifyRes.status}`
148
+ });
149
+ return;
150
+ }
151
+ const verifyJson = await verifyRes.json();
152
+ if (!verifyJson.isValid) {
153
+ res.status(402).json({
154
+ error: "Payment verification failed",
155
+ invalidReason: verifyJson.invalidReason ?? null,
156
+ paymentRequirements,
157
+ paymentHeader: null
158
+ });
159
+ return;
160
+ }
161
+ if (onPaymentSettled) {
162
+ try {
163
+ const headerObj = decodePaymentHeader(paymentHeader);
164
+ const { authorization } = headerObj.payload;
165
+ const logEntry = {
166
+ id: authorization.nonce,
167
+ from: authorization.from,
168
+ to: authorization.to,
169
+ valueAtomic: authorization.value,
170
+ network,
171
+ asset: assetConfig.address,
172
+ route: routeKey,
173
+ timestamp: Date.now(),
174
+ paymentRequirements
175
+ };
176
+ onPaymentSettled(logEntry);
177
+ } catch (err) {
178
+ console.error(
179
+ "[x402-mantle-sdk] Error calling onPaymentSettled hook:",
180
+ err
181
+ );
182
+ }
183
+ }
184
+ next();
185
+ return;
186
+ } catch (err) {
187
+ console.error(
188
+ "[x402-mantle-sdk] Error while calling facilitator /verify:",
189
+ err
190
+ );
191
+ const message = err instanceof Error ? err.message : "Unknown verification error";
192
+ res.status(500).json({
193
+ error: "Payment verification error",
194
+ details: message
195
+ });
196
+ return;
197
+ }
198
+ };
199
+ }
200
+
201
+ // src/shared/utils.ts
202
+ function encodeJsonToBase64(value) {
203
+ const json = JSON.stringify(value);
204
+ if (typeof btoa === "function") {
205
+ const bytes = new TextEncoder().encode(json);
206
+ const binString = Array.from(
207
+ bytes,
208
+ (byte) => String.fromCodePoint(byte)
209
+ ).join("");
210
+ return btoa(binString);
211
+ }
212
+ if (typeof globalThis.Buffer !== "undefined") {
213
+ return globalThis.Buffer.from(json, "utf8").toString("base64");
214
+ }
215
+ throw new Error("No base64 implementation found in this environment");
216
+ }
217
+ function randomBytes32Hex() {
218
+ if (typeof crypto !== "undefined" && "getRandomValues" in crypto) {
219
+ const arr = new Uint8Array(32);
220
+ crypto.getRandomValues(arr);
221
+ return "0x" + Array.from(arr).map((b) => b.toString(16).padStart(2, "0")).join("");
222
+ }
223
+ try {
224
+ const nodeCrypto = require("crypto");
225
+ const buf = nodeCrypto.randomBytes(32);
226
+ return "0x" + buf.toString("hex");
227
+ } catch {
228
+ throw new Error(
229
+ "No cryptographically secure random number generator found. This environment does not support crypto.getRandomValues or Node.js crypto module."
230
+ );
231
+ }
232
+ }
233
+
234
+ // src/client/paymentClient.ts
235
+ function joinUrl(base, path) {
236
+ const normalizedBase = base.replace(/\/+$/, "");
237
+ const normalizedPath = path.startsWith("/") ? path : `/${path}`;
238
+ return `${normalizedBase}${normalizedPath}`;
239
+ }
240
+ async function getUserAddressFromProvider(provider) {
241
+ const p = provider;
242
+ if (!p || typeof p.request !== "function") {
243
+ throw new Error("provider must implement EIP-1193 request()");
244
+ }
245
+ const accounts = await p.request({
246
+ method: "eth_requestAccounts"
247
+ });
248
+ if (!accounts || accounts.length === 0) {
249
+ throw new Error("No accounts returned from provider");
250
+ }
251
+ return accounts[0];
252
+ }
253
+ function buildTypedDataForAuthorization(authorization, paymentRequirements) {
254
+ const chainId = getChainIdForNetwork(paymentRequirements.network);
255
+ const verifyingContract = paymentRequirements.asset;
256
+ const domain = {
257
+ name: "USD Coin",
258
+ version: "2",
259
+ chainId,
260
+ verifyingContract
261
+ };
262
+ const types = {
263
+ TransferWithAuthorization: [
264
+ { name: "from", type: "address" },
265
+ { name: "to", type: "address" },
266
+ { name: "value", type: "uint256" },
267
+ { name: "validAfter", type: "uint256" },
268
+ { name: "validBefore", type: "uint256" },
269
+ { name: "nonce", type: "bytes32" }
270
+ ]
271
+ };
272
+ return {
273
+ domain,
274
+ types,
275
+ primaryType: "TransferWithAuthorization",
276
+ message: authorization
277
+ };
278
+ }
279
+ async function signAuthorizationWithProvider(provider, address, authorization, paymentRequirements) {
280
+ const p = provider;
281
+ if (!p || typeof p.request !== "function") {
282
+ throw new Error("provider must implement EIP-1193 request()");
283
+ }
284
+ const typedData = buildTypedDataForAuthorization(
285
+ authorization,
286
+ paymentRequirements
287
+ );
288
+ const params = [address, JSON.stringify(typedData)];
289
+ const signature = await p.request({
290
+ method: "eth_signTypedData_v4",
291
+ params
292
+ });
293
+ if (typeof signature !== "string" || !signature.startsWith("0x")) {
294
+ throw new Error("Invalid signature returned from provider");
295
+ }
296
+ return signature;
297
+ }
298
+ function createPaymentClient(config) {
299
+ const {
300
+ resourceUrl,
301
+ facilitatorUrl,
302
+ provider,
303
+ userAddress: userAddressOverride
304
+ } = config;
305
+ if (!resourceUrl) {
306
+ throw new Error("resourceUrl is required");
307
+ }
308
+ if (!facilitatorUrl) {
309
+ throw new Error("facilitatorUrl is required");
310
+ }
311
+ if (!provider) {
312
+ throw new Error("provider is required (e.g. window.ethereum)");
313
+ }
314
+ return {
315
+ async callWithPayment(path, options) {
316
+ const method = options?.method ?? "GET";
317
+ const headers = {
318
+ ...options?.headers ?? {}
319
+ };
320
+ let body;
321
+ if (options?.body !== void 0) {
322
+ headers["Content-Type"] = headers["Content-Type"] ?? "application/json";
323
+ body = JSON.stringify(options.body);
324
+ }
325
+ const initialUrl = joinUrl(resourceUrl, path);
326
+ const initialRes = await fetch(initialUrl, {
327
+ method,
328
+ headers,
329
+ body
330
+ });
331
+ if (initialRes.status !== 402) {
332
+ const json = await initialRes.json().catch((err) => {
333
+ console.error("[x402] Failed to parse initial response JSON:", err);
334
+ return null;
335
+ });
336
+ return {
337
+ response: json,
338
+ paymentHeader: "",
339
+ paymentRequirements: {
340
+ scheme: "exact",
341
+ network: "mantle-mainnet",
342
+ asset: "",
343
+ maxAmountRequired: "0",
344
+ payTo: ""
345
+ },
346
+ txHash: void 0
347
+ };
348
+ }
349
+ const bodyJson = await initialRes.json();
350
+ const paymentRequirements = bodyJson.paymentRequirements;
351
+ if (!paymentRequirements) {
352
+ throw new Error(
353
+ "402 response did not include paymentRequirements field"
354
+ );
355
+ }
356
+ const fromAddress = userAddressOverride ?? await getUserAddressFromProvider(provider);
357
+ const nowSec = Math.floor(Date.now() / 1e3);
358
+ const validAfter = "0";
359
+ const validBefore = String(nowSec + 10 * 60);
360
+ const nonce = randomBytes32Hex();
361
+ const valueAtomic = options?.valueOverrideAtomic ?? paymentRequirements.maxAmountRequired;
362
+ const authorization = {
363
+ from: fromAddress,
364
+ to: paymentRequirements.payTo,
365
+ value: valueAtomic,
366
+ validAfter,
367
+ validBefore,
368
+ nonce
369
+ };
370
+ const signature = await signAuthorizationWithProvider(
371
+ provider,
372
+ fromAddress,
373
+ authorization,
374
+ paymentRequirements
375
+ );
376
+ const paymentHeaderObject = {
377
+ x402Version: 1,
378
+ scheme: paymentRequirements.scheme,
379
+ network: paymentRequirements.network,
380
+ payload: {
381
+ signature,
382
+ authorization
383
+ }
384
+ };
385
+ const paymentHeader = encodeJsonToBase64(paymentHeaderObject);
386
+ const settleUrl = joinUrl(facilitatorUrl, "/settle");
387
+ const settleRes = await fetch(settleUrl, {
388
+ method: "POST",
389
+ headers: {
390
+ "Content-Type": "application/json"
391
+ },
392
+ body: JSON.stringify({
393
+ x402Version: 1,
394
+ paymentHeader,
395
+ paymentRequirements
396
+ })
397
+ });
398
+ if (!settleRes.ok) {
399
+ const text = await settleRes.text().catch((err) => {
400
+ console.error("[x402] Failed to read settle response text:", err);
401
+ return "";
402
+ });
403
+ throw new Error(
404
+ `Facilitator /settle failed with HTTP ${settleRes.status}: ${text}`
405
+ );
406
+ }
407
+ const settleJson = await settleRes.json();
408
+ if (!settleJson.success) {
409
+ throw new Error(
410
+ `Facilitator /settle returned error: ${settleJson.error ?? "unknown error"}`
411
+ );
412
+ }
413
+ const txHash = settleJson.txHash ?? void 0;
414
+ const retryHeaders = {
415
+ ...headers,
416
+ "X-PAYMENT": paymentHeader
417
+ };
418
+ const retryRes = await fetch(initialUrl, {
419
+ method,
420
+ headers: retryHeaders,
421
+ body
422
+ });
423
+ if (!retryRes.ok) {
424
+ const text = await retryRes.text().catch((err) => {
425
+ console.error("[x402] Failed to read retry response text:", err);
426
+ return "";
427
+ });
428
+ throw new Error(
429
+ `Protected request with X-PAYMENT failed: HTTP ${retryRes.status} ${text}`
430
+ );
431
+ }
432
+ const finalJson = await retryRes.json();
433
+ return {
434
+ response: finalJson,
435
+ txHash,
436
+ paymentHeader,
437
+ paymentRequirements
438
+ };
439
+ }
440
+ };
441
+ }
442
+ // Annotate the CommonJS export names for ESM import in node:
443
+ 0 && (module.exports = {
444
+ createPaymentClient,
445
+ createPaymentMiddleware
446
+ });
@@ -0,0 +1,129 @@
1
+ import { Request, Response, NextFunction } from 'express';
2
+
3
+ /** Network identifier used in x402 paymentRequirements / paymentHeader. */
4
+ type NetworkId = "mantle-mainnet" | (string & {});
5
+ /** Basic ERC-20 asset config (e.g. USDC on Mantle). */
6
+ interface AssetConfig {
7
+ symbol: string;
8
+ address: string;
9
+ decimals: number;
10
+ }
11
+ /** x402-style payment requirements (returned in 402 response). */
12
+ interface PaymentRequirements {
13
+ scheme: "exact";
14
+ network: NetworkId;
15
+ asset: string;
16
+ maxAmountRequired: string;
17
+ payTo: string;
18
+ price?: string;
19
+ currency?: string;
20
+ }
21
+ /** EIP-3009 TransferWithAuthorization payload. */
22
+ interface Authorization {
23
+ from: string;
24
+ to: string;
25
+ value: string;
26
+ validAfter: string;
27
+ validBefore: string;
28
+ nonce: string;
29
+ }
30
+ /** Inner payload of x402-style payment header. */
31
+ interface PaymentHeaderPayload {
32
+ signature: string;
33
+ authorization: Authorization;
34
+ }
35
+ /** Structured x402-style payment header (before base64 encoding). */
36
+ interface PaymentHeaderObject {
37
+ x402Version: number;
38
+ scheme: "exact";
39
+ network: NetworkId;
40
+ payload: PaymentHeaderPayload;
41
+ }
42
+ /** Base64-encoded payment header, sent in X-PAYMENT. */
43
+ type PaymentHeaderBase64 = string;
44
+
45
+ /** Unique key for a protected route, e.g. "GET /api/protected". */
46
+ type RouteKey = string;
47
+ /** Pricing config for a single route. */
48
+ interface RoutePricingConfig {
49
+ /** Price in USD cents, e.g. 1 => $0.01. */
50
+ priceUsdCents: number;
51
+ /** Network identifier (e.g. "mantle-mainnet"). */
52
+ network: NetworkId;
53
+ }
54
+ /** Map of route keys to pricing config. */
55
+ type RoutesConfig = Record<RouteKey, RoutePricingConfig>;
56
+ /** Log entry for a successfully settled payment. */
57
+ interface PaymentLogEntry {
58
+ id: string;
59
+ from: string;
60
+ to: string;
61
+ valueAtomic: string;
62
+ network: NetworkId;
63
+ asset: string;
64
+ route?: RouteKey;
65
+ txHash?: string;
66
+ timestamp: number;
67
+ paymentRequirements?: PaymentRequirements;
68
+ }
69
+ /** Config for createPaymentMiddleware. */
70
+ interface PaymentMiddlewareConfig {
71
+ /** Base URL of facilitator, e.g. https://facilitator.nosubs.ai */
72
+ facilitatorUrl: string;
73
+ /** Recipient address (developer). */
74
+ receiverAddress: string;
75
+ /** Map of protected routes and their pricing. */
76
+ routes: RoutesConfig;
77
+ /**
78
+ * Optional hook called whenever a payment is successfully settled.
79
+ * You can use this to push logs into your DB / analytics pipeline.
80
+ */
81
+ onPaymentSettled?: (entry: PaymentLogEntry) => void;
82
+ }
83
+
84
+ declare function createPaymentMiddleware(config: PaymentMiddlewareConfig): (req: Request, res: Response, next: NextFunction) => Promise<void>;
85
+
86
+ /** Config for the client-side payment helper. */
87
+ interface PaymentClientConfig {
88
+ /** Base URL of your protected resource server. */
89
+ resourceUrl: string;
90
+ /** Facilitator URL (hosted or self-hosted). */
91
+ facilitatorUrl: string;
92
+ /** EIP-1193 provider (window.ethereum) or similar. */
93
+ provider: unknown;
94
+ /** Optional user address override; otherwise derived from provider. */
95
+ userAddress?: string;
96
+ }
97
+ /** Result of a callWithPayment() client operation. */
98
+ interface CallWithPaymentResult<TResponseBody = unknown> {
99
+ response: TResponseBody;
100
+ txHash?: string;
101
+ paymentHeader: PaymentHeaderBase64;
102
+ paymentRequirements: PaymentRequirements;
103
+ }
104
+ /** Shape of the client instance returned by createPaymentClient. */
105
+ interface PaymentClient {
106
+ callWithPayment<TBody = unknown, TResp = unknown>(path: string, options?: {
107
+ method?: "GET" | "POST" | "PUT" | "DELETE";
108
+ body?: TBody;
109
+ headers?: Record<string, string>;
110
+ /**
111
+ * Optional override if you want to send less than maxAmountRequired.
112
+ * In most cases you won't need this and will just pay maxAmountRequired.
113
+ */
114
+ valueOverrideAtomic?: string;
115
+ }): Promise<CallWithPaymentResult<TResp>>;
116
+ }
117
+
118
+ /**
119
+ * Creates a high-level payment client that:
120
+ * - makes an initial request
121
+ * - if it receives 402 + paymentRequirements, builds & signs an authorization
122
+ * - calls facilitator /settle
123
+ * - retries the original request with X-PAYMENT header
124
+ *
125
+ * This logic is x402-like and tailored for Mantle + USDC.
126
+ */
127
+ declare function createPaymentClient(config: PaymentClientConfig): PaymentClient;
128
+
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 };
@@ -0,0 +1,129 @@
1
+ import { Request, Response, NextFunction } from 'express';
2
+
3
+ /** Network identifier used in x402 paymentRequirements / paymentHeader. */
4
+ type NetworkId = "mantle-mainnet" | (string & {});
5
+ /** Basic ERC-20 asset config (e.g. USDC on Mantle). */
6
+ interface AssetConfig {
7
+ symbol: string;
8
+ address: string;
9
+ decimals: number;
10
+ }
11
+ /** x402-style payment requirements (returned in 402 response). */
12
+ interface PaymentRequirements {
13
+ scheme: "exact";
14
+ network: NetworkId;
15
+ asset: string;
16
+ maxAmountRequired: string;
17
+ payTo: string;
18
+ price?: string;
19
+ currency?: string;
20
+ }
21
+ /** EIP-3009 TransferWithAuthorization payload. */
22
+ interface Authorization {
23
+ from: string;
24
+ to: string;
25
+ value: string;
26
+ validAfter: string;
27
+ validBefore: string;
28
+ nonce: string;
29
+ }
30
+ /** Inner payload of x402-style payment header. */
31
+ interface PaymentHeaderPayload {
32
+ signature: string;
33
+ authorization: Authorization;
34
+ }
35
+ /** Structured x402-style payment header (before base64 encoding). */
36
+ interface PaymentHeaderObject {
37
+ x402Version: number;
38
+ scheme: "exact";
39
+ network: NetworkId;
40
+ payload: PaymentHeaderPayload;
41
+ }
42
+ /** Base64-encoded payment header, sent in X-PAYMENT. */
43
+ type PaymentHeaderBase64 = string;
44
+
45
+ /** Unique key for a protected route, e.g. "GET /api/protected". */
46
+ type RouteKey = string;
47
+ /** Pricing config for a single route. */
48
+ interface RoutePricingConfig {
49
+ /** Price in USD cents, e.g. 1 => $0.01. */
50
+ priceUsdCents: number;
51
+ /** Network identifier (e.g. "mantle-mainnet"). */
52
+ network: NetworkId;
53
+ }
54
+ /** Map of route keys to pricing config. */
55
+ type RoutesConfig = Record<RouteKey, RoutePricingConfig>;
56
+ /** Log entry for a successfully settled payment. */
57
+ interface PaymentLogEntry {
58
+ id: string;
59
+ from: string;
60
+ to: string;
61
+ valueAtomic: string;
62
+ network: NetworkId;
63
+ asset: string;
64
+ route?: RouteKey;
65
+ txHash?: string;
66
+ timestamp: number;
67
+ paymentRequirements?: PaymentRequirements;
68
+ }
69
+ /** Config for createPaymentMiddleware. */
70
+ interface PaymentMiddlewareConfig {
71
+ /** Base URL of facilitator, e.g. https://facilitator.nosubs.ai */
72
+ facilitatorUrl: string;
73
+ /** Recipient address (developer). */
74
+ receiverAddress: string;
75
+ /** Map of protected routes and their pricing. */
76
+ routes: RoutesConfig;
77
+ /**
78
+ * Optional hook called whenever a payment is successfully settled.
79
+ * You can use this to push logs into your DB / analytics pipeline.
80
+ */
81
+ onPaymentSettled?: (entry: PaymentLogEntry) => void;
82
+ }
83
+
84
+ declare function createPaymentMiddleware(config: PaymentMiddlewareConfig): (req: Request, res: Response, next: NextFunction) => Promise<void>;
85
+
86
+ /** Config for the client-side payment helper. */
87
+ interface PaymentClientConfig {
88
+ /** Base URL of your protected resource server. */
89
+ resourceUrl: string;
90
+ /** Facilitator URL (hosted or self-hosted). */
91
+ facilitatorUrl: string;
92
+ /** EIP-1193 provider (window.ethereum) or similar. */
93
+ provider: unknown;
94
+ /** Optional user address override; otherwise derived from provider. */
95
+ userAddress?: string;
96
+ }
97
+ /** Result of a callWithPayment() client operation. */
98
+ interface CallWithPaymentResult<TResponseBody = unknown> {
99
+ response: TResponseBody;
100
+ txHash?: string;
101
+ paymentHeader: PaymentHeaderBase64;
102
+ paymentRequirements: PaymentRequirements;
103
+ }
104
+ /** Shape of the client instance returned by createPaymentClient. */
105
+ interface PaymentClient {
106
+ callWithPayment<TBody = unknown, TResp = unknown>(path: string, options?: {
107
+ method?: "GET" | "POST" | "PUT" | "DELETE";
108
+ body?: TBody;
109
+ headers?: Record<string, string>;
110
+ /**
111
+ * Optional override if you want to send less than maxAmountRequired.
112
+ * In most cases you won't need this and will just pay maxAmountRequired.
113
+ */
114
+ valueOverrideAtomic?: string;
115
+ }): Promise<CallWithPaymentResult<TResp>>;
116
+ }
117
+
118
+ /**
119
+ * Creates a high-level payment client that:
120
+ * - makes an initial request
121
+ * - if it receives 402 + paymentRequirements, builds & signs an authorization
122
+ * - calls facilitator /settle
123
+ * - retries the original request with X-PAYMENT header
124
+ *
125
+ * This logic is x402-like and tailored for Mantle + USDC.
126
+ */
127
+ declare function createPaymentClient(config: PaymentClientConfig): PaymentClient;
128
+
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 };
package/dist/index.js ADDED
@@ -0,0 +1,425 @@
1
+ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
2
+ get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
3
+ }) : x)(function(x) {
4
+ if (typeof require !== "undefined") return require.apply(this, arguments);
5
+ throw Error('Dynamic require of "' + x + '" is not supported');
6
+ });
7
+
8
+ // src/shared/constants.ts
9
+ var MANTLE_MAINNET_NETWORK_ID = "mantle-mainnet";
10
+ var MANTLE_MAINNET_CHAIN_ID = 5e3;
11
+ var MANTLE_MAINNET_USDC = {
12
+ symbol: "USDC",
13
+ address: "0x09Bc4E0D864854c6aFB6eB9A9cdF58aC190D0dF9",
14
+ decimals: 6
15
+ };
16
+ function getDefaultAssetForNetwork(network) {
17
+ switch (network) {
18
+ case MANTLE_MAINNET_NETWORK_ID:
19
+ default:
20
+ return MANTLE_MAINNET_USDC;
21
+ }
22
+ }
23
+ function getChainIdForNetwork(network) {
24
+ switch (network) {
25
+ case MANTLE_MAINNET_NETWORK_ID:
26
+ default:
27
+ return MANTLE_MAINNET_CHAIN_ID;
28
+ }
29
+ }
30
+ function usdCentsToAtomic(cents, decimals) {
31
+ if (cents < 0) {
32
+ throw new Error("priceUsdCents must be non-negative");
33
+ }
34
+ if (decimals < 2) {
35
+ throw new Error("token decimals must be >= 2 for USD cent conversion");
36
+ }
37
+ const base = BigInt(10) ** BigInt(decimals - 2);
38
+ return BigInt(cents) * base;
39
+ }
40
+
41
+ // src/server/paymentMiddleware.ts
42
+ function getRouteKey(req) {
43
+ const method = (req.method || "GET").toUpperCase();
44
+ const path = req.path || "/";
45
+ return `${method} ${path}`;
46
+ }
47
+ function decodePaymentHeader(paymentHeaderBase64) {
48
+ try {
49
+ if (typeof Buffer !== "undefined") {
50
+ const json = Buffer.from(paymentHeaderBase64, "base64").toString("utf8");
51
+ return JSON.parse(json);
52
+ }
53
+ if (typeof atob === "function") {
54
+ const json = atob(paymentHeaderBase64);
55
+ return JSON.parse(json);
56
+ }
57
+ throw new Error("No base64 decoding available in this environment");
58
+ } catch (err) {
59
+ const msg = err instanceof Error ? err.message : "Unknown error";
60
+ throw new Error(`Failed to decode paymentHeader: ${msg}`);
61
+ }
62
+ }
63
+ function createPaymentMiddleware(config) {
64
+ const { facilitatorUrl, receiverAddress, routes, onPaymentSettled } = config;
65
+ if (!facilitatorUrl) {
66
+ throw new Error("facilitatorUrl is required");
67
+ }
68
+ if (!receiverAddress) {
69
+ throw new Error("receiverAddress is required");
70
+ }
71
+ if (!routes || Object.keys(routes).length === 0) {
72
+ throw new Error("routes config must not be empty");
73
+ }
74
+ return async function paymentMiddleware(req, res, next) {
75
+ const routeKey = getRouteKey(req);
76
+ const routeConfig = routes[routeKey];
77
+ if (!routeConfig) {
78
+ next();
79
+ return;
80
+ }
81
+ const { priceUsdCents, network } = routeConfig;
82
+ const assetConfig = getDefaultAssetForNetwork(network);
83
+ const maxAmountRequiredBigInt = usdCentsToAtomic(
84
+ priceUsdCents,
85
+ assetConfig.decimals
86
+ );
87
+ const paymentRequirements = {
88
+ scheme: "exact",
89
+ network,
90
+ asset: assetConfig.address,
91
+ maxAmountRequired: maxAmountRequiredBigInt.toString(),
92
+ payTo: receiverAddress,
93
+ price: `$${(priceUsdCents / 100).toFixed(2)}`,
94
+ currency: "USD"
95
+ };
96
+ const paymentHeader = req.header("X-PAYMENT") ?? req.header("x-payment");
97
+ if (!paymentHeader) {
98
+ res.status(402).json({
99
+ error: "Payment Required",
100
+ paymentRequirements,
101
+ paymentHeader: null
102
+ });
103
+ return;
104
+ }
105
+ try {
106
+ const verifyUrl = `${facilitatorUrl.replace(/\/+$/, "")}/verify`;
107
+ const verifyRes = await fetch(verifyUrl, {
108
+ method: "POST",
109
+ headers: {
110
+ "Content-Type": "application/json"
111
+ },
112
+ body: JSON.stringify({
113
+ x402Version: 1,
114
+ paymentHeader,
115
+ paymentRequirements
116
+ })
117
+ });
118
+ if (!verifyRes.ok) {
119
+ const text = await verifyRes.text().catch(() => "");
120
+ console.error(
121
+ "[x402-mantle-sdk] Facilitator /verify returned non-OK:",
122
+ verifyRes.status,
123
+ text
124
+ );
125
+ res.status(500).json({
126
+ error: "Payment verification error",
127
+ details: `Facilitator responded with HTTP ${verifyRes.status}`
128
+ });
129
+ return;
130
+ }
131
+ const verifyJson = await verifyRes.json();
132
+ if (!verifyJson.isValid) {
133
+ res.status(402).json({
134
+ error: "Payment verification failed",
135
+ invalidReason: verifyJson.invalidReason ?? null,
136
+ paymentRequirements,
137
+ paymentHeader: null
138
+ });
139
+ return;
140
+ }
141
+ if (onPaymentSettled) {
142
+ try {
143
+ const headerObj = decodePaymentHeader(paymentHeader);
144
+ const { authorization } = headerObj.payload;
145
+ const logEntry = {
146
+ id: authorization.nonce,
147
+ from: authorization.from,
148
+ to: authorization.to,
149
+ valueAtomic: authorization.value,
150
+ network,
151
+ asset: assetConfig.address,
152
+ route: routeKey,
153
+ timestamp: Date.now(),
154
+ paymentRequirements
155
+ };
156
+ onPaymentSettled(logEntry);
157
+ } catch (err) {
158
+ console.error(
159
+ "[x402-mantle-sdk] Error calling onPaymentSettled hook:",
160
+ err
161
+ );
162
+ }
163
+ }
164
+ next();
165
+ return;
166
+ } catch (err) {
167
+ console.error(
168
+ "[x402-mantle-sdk] Error while calling facilitator /verify:",
169
+ err
170
+ );
171
+ const message = err instanceof Error ? err.message : "Unknown verification error";
172
+ res.status(500).json({
173
+ error: "Payment verification error",
174
+ details: message
175
+ });
176
+ return;
177
+ }
178
+ };
179
+ }
180
+
181
+ // src/shared/utils.ts
182
+ function encodeJsonToBase64(value) {
183
+ const json = JSON.stringify(value);
184
+ if (typeof btoa === "function") {
185
+ const bytes = new TextEncoder().encode(json);
186
+ const binString = Array.from(
187
+ bytes,
188
+ (byte) => String.fromCodePoint(byte)
189
+ ).join("");
190
+ return btoa(binString);
191
+ }
192
+ if (typeof globalThis.Buffer !== "undefined") {
193
+ return globalThis.Buffer.from(json, "utf8").toString("base64");
194
+ }
195
+ throw new Error("No base64 implementation found in this environment");
196
+ }
197
+ function randomBytes32Hex() {
198
+ if (typeof crypto !== "undefined" && "getRandomValues" in crypto) {
199
+ const arr = new Uint8Array(32);
200
+ crypto.getRandomValues(arr);
201
+ return "0x" + Array.from(arr).map((b) => b.toString(16).padStart(2, "0")).join("");
202
+ }
203
+ try {
204
+ const nodeCrypto = __require("crypto");
205
+ const buf = nodeCrypto.randomBytes(32);
206
+ return "0x" + buf.toString("hex");
207
+ } catch {
208
+ throw new Error(
209
+ "No cryptographically secure random number generator found. This environment does not support crypto.getRandomValues or Node.js crypto module."
210
+ );
211
+ }
212
+ }
213
+
214
+ // src/client/paymentClient.ts
215
+ function joinUrl(base, path) {
216
+ const normalizedBase = base.replace(/\/+$/, "");
217
+ const normalizedPath = path.startsWith("/") ? path : `/${path}`;
218
+ return `${normalizedBase}${normalizedPath}`;
219
+ }
220
+ async function getUserAddressFromProvider(provider) {
221
+ const p = provider;
222
+ if (!p || typeof p.request !== "function") {
223
+ throw new Error("provider must implement EIP-1193 request()");
224
+ }
225
+ const accounts = await p.request({
226
+ method: "eth_requestAccounts"
227
+ });
228
+ if (!accounts || accounts.length === 0) {
229
+ throw new Error("No accounts returned from provider");
230
+ }
231
+ return accounts[0];
232
+ }
233
+ function buildTypedDataForAuthorization(authorization, paymentRequirements) {
234
+ const chainId = getChainIdForNetwork(paymentRequirements.network);
235
+ const verifyingContract = paymentRequirements.asset;
236
+ const domain = {
237
+ name: "USD Coin",
238
+ version: "2",
239
+ chainId,
240
+ verifyingContract
241
+ };
242
+ const types = {
243
+ TransferWithAuthorization: [
244
+ { name: "from", type: "address" },
245
+ { name: "to", type: "address" },
246
+ { name: "value", type: "uint256" },
247
+ { name: "validAfter", type: "uint256" },
248
+ { name: "validBefore", type: "uint256" },
249
+ { name: "nonce", type: "bytes32" }
250
+ ]
251
+ };
252
+ return {
253
+ domain,
254
+ types,
255
+ primaryType: "TransferWithAuthorization",
256
+ message: authorization
257
+ };
258
+ }
259
+ async function signAuthorizationWithProvider(provider, address, authorization, paymentRequirements) {
260
+ const p = provider;
261
+ if (!p || typeof p.request !== "function") {
262
+ throw new Error("provider must implement EIP-1193 request()");
263
+ }
264
+ const typedData = buildTypedDataForAuthorization(
265
+ authorization,
266
+ paymentRequirements
267
+ );
268
+ const params = [address, JSON.stringify(typedData)];
269
+ const signature = await p.request({
270
+ method: "eth_signTypedData_v4",
271
+ params
272
+ });
273
+ if (typeof signature !== "string" || !signature.startsWith("0x")) {
274
+ throw new Error("Invalid signature returned from provider");
275
+ }
276
+ return signature;
277
+ }
278
+ function createPaymentClient(config) {
279
+ const {
280
+ resourceUrl,
281
+ facilitatorUrl,
282
+ provider,
283
+ userAddress: userAddressOverride
284
+ } = config;
285
+ if (!resourceUrl) {
286
+ throw new Error("resourceUrl is required");
287
+ }
288
+ if (!facilitatorUrl) {
289
+ throw new Error("facilitatorUrl is required");
290
+ }
291
+ if (!provider) {
292
+ throw new Error("provider is required (e.g. window.ethereum)");
293
+ }
294
+ return {
295
+ async callWithPayment(path, options) {
296
+ const method = options?.method ?? "GET";
297
+ const headers = {
298
+ ...options?.headers ?? {}
299
+ };
300
+ let body;
301
+ if (options?.body !== void 0) {
302
+ headers["Content-Type"] = headers["Content-Type"] ?? "application/json";
303
+ body = JSON.stringify(options.body);
304
+ }
305
+ const initialUrl = joinUrl(resourceUrl, path);
306
+ const initialRes = await fetch(initialUrl, {
307
+ method,
308
+ headers,
309
+ body
310
+ });
311
+ if (initialRes.status !== 402) {
312
+ const json = await initialRes.json().catch((err) => {
313
+ console.error("[x402] Failed to parse initial response JSON:", err);
314
+ return null;
315
+ });
316
+ return {
317
+ response: json,
318
+ paymentHeader: "",
319
+ paymentRequirements: {
320
+ scheme: "exact",
321
+ network: "mantle-mainnet",
322
+ asset: "",
323
+ maxAmountRequired: "0",
324
+ payTo: ""
325
+ },
326
+ txHash: void 0
327
+ };
328
+ }
329
+ const bodyJson = await initialRes.json();
330
+ const paymentRequirements = bodyJson.paymentRequirements;
331
+ if (!paymentRequirements) {
332
+ throw new Error(
333
+ "402 response did not include paymentRequirements field"
334
+ );
335
+ }
336
+ const fromAddress = userAddressOverride ?? await getUserAddressFromProvider(provider);
337
+ const nowSec = Math.floor(Date.now() / 1e3);
338
+ const validAfter = "0";
339
+ const validBefore = String(nowSec + 10 * 60);
340
+ const nonce = randomBytes32Hex();
341
+ const valueAtomic = options?.valueOverrideAtomic ?? paymentRequirements.maxAmountRequired;
342
+ const authorization = {
343
+ from: fromAddress,
344
+ to: paymentRequirements.payTo,
345
+ value: valueAtomic,
346
+ validAfter,
347
+ validBefore,
348
+ nonce
349
+ };
350
+ const signature = await signAuthorizationWithProvider(
351
+ provider,
352
+ fromAddress,
353
+ authorization,
354
+ paymentRequirements
355
+ );
356
+ const paymentHeaderObject = {
357
+ x402Version: 1,
358
+ scheme: paymentRequirements.scheme,
359
+ network: paymentRequirements.network,
360
+ payload: {
361
+ signature,
362
+ authorization
363
+ }
364
+ };
365
+ const paymentHeader = encodeJsonToBase64(paymentHeaderObject);
366
+ const settleUrl = joinUrl(facilitatorUrl, "/settle");
367
+ const settleRes = await fetch(settleUrl, {
368
+ method: "POST",
369
+ headers: {
370
+ "Content-Type": "application/json"
371
+ },
372
+ body: JSON.stringify({
373
+ x402Version: 1,
374
+ paymentHeader,
375
+ paymentRequirements
376
+ })
377
+ });
378
+ if (!settleRes.ok) {
379
+ const text = await settleRes.text().catch((err) => {
380
+ console.error("[x402] Failed to read settle response text:", err);
381
+ return "";
382
+ });
383
+ throw new Error(
384
+ `Facilitator /settle failed with HTTP ${settleRes.status}: ${text}`
385
+ );
386
+ }
387
+ const settleJson = await settleRes.json();
388
+ if (!settleJson.success) {
389
+ throw new Error(
390
+ `Facilitator /settle returned error: ${settleJson.error ?? "unknown error"}`
391
+ );
392
+ }
393
+ const txHash = settleJson.txHash ?? void 0;
394
+ const retryHeaders = {
395
+ ...headers,
396
+ "X-PAYMENT": paymentHeader
397
+ };
398
+ const retryRes = await fetch(initialUrl, {
399
+ method,
400
+ headers: retryHeaders,
401
+ body
402
+ });
403
+ if (!retryRes.ok) {
404
+ const text = await retryRes.text().catch((err) => {
405
+ console.error("[x402] Failed to read retry response text:", err);
406
+ return "";
407
+ });
408
+ throw new Error(
409
+ `Protected request with X-PAYMENT failed: HTTP ${retryRes.status} ${text}`
410
+ );
411
+ }
412
+ const finalJson = await retryRes.json();
413
+ return {
414
+ response: finalJson,
415
+ txHash,
416
+ paymentHeader,
417
+ paymentRequirements
418
+ };
419
+ }
420
+ };
421
+ }
422
+ export {
423
+ createPaymentClient,
424
+ createPaymentMiddleware
425
+ };
package/package.json ADDED
@@ -0,0 +1,68 @@
1
+ {
2
+ "name": "@puga-labs/x402-mantle-sdk",
3
+ "version": "0.1.0",
4
+ "description": "x402 payments SDK for Mantle (USDC, gasless, facilitator-based)",
5
+ "license": "MIT",
6
+ "author": "Evgenii Pugachev <cyprus.pugamuga@gmail.com>",
7
+ "homepage": "https://github.com/puga-labs/mantle-x402-kit",
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "git+https://github.com/puga-labs/mantle-x402-kit.git"
11
+ },
12
+ "bugs": {
13
+ "url": "https://github.com/puga-labs/mantle-x402-kit/issues"
14
+ },
15
+ "type": "module",
16
+ "main": "./dist/index.cjs",
17
+ "module": "./dist/index.js",
18
+ "types": "./dist/index.d.ts",
19
+ "exports": {
20
+ ".": {
21
+ "import": {
22
+ "types": "./dist/index.d.ts",
23
+ "default": "./dist/index.js"
24
+ },
25
+ "require": {
26
+ "types": "./dist/index.d.cts",
27
+ "default": "./dist/index.cjs"
28
+ }
29
+ }
30
+ },
31
+ "files": [
32
+ "dist"
33
+ ],
34
+ "scripts": {
35
+ "build": "tsup src/index.ts --format cjs,esm --dts",
36
+ "dev": "tsup src/index.ts --format esm --watch",
37
+ "clean": "rimraf dist",
38
+ "lint": "eslint src --ext .ts",
39
+ "test": "vitest",
40
+ "test:run": "vitest run",
41
+ "test:unit": "vitest run tests/unit",
42
+ "test:integration": "vitest run tests/integration",
43
+ "test:security": "vitest run tests/security",
44
+ "test:coverage": "vitest run --coverage",
45
+ "test:ui": "vitest --ui",
46
+ "test:watch": "vitest watch"
47
+ },
48
+ "peerDependencies": {
49
+ "ethers": "^6.0.0"
50
+ },
51
+ "devDependencies": {
52
+ "@eslint/js": "^9.17.0",
53
+ "@types/express": "^5.0.6",
54
+ "@types/node": "^22.0.0",
55
+ "@typescript-eslint/eslint-plugin": "^8.20.0",
56
+ "@typescript-eslint/parser": "^8.20.0",
57
+ "@vitest/coverage-v8": "^4.0.15",
58
+ "@vitest/ui": "^4.0.15",
59
+ "eslint": "^9.17.0",
60
+ "express": "^5.2.1",
61
+ "globals": "^15.14.0",
62
+ "msw": "^2.12.4",
63
+ "rimraf": "^6.0.0",
64
+ "tsup": "^8.0.0",
65
+ "typescript": "^5.6.0",
66
+ "vitest": "^4.0.15"
67
+ }
68
+ }