@puga-labs/x402-mantle-sdk 0.2.1 → 0.3.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (95) hide show
  1. package/dist/chunk-23QNUJIB.js +136 -0
  2. package/dist/chunk-6GLR5EBK.js +96 -0
  3. package/dist/chunk-BRGW36P7.js +211 -0
  4. package/dist/chunk-CTI5CRDY.js +274 -0
  5. package/dist/chunk-DA6ZBXNO.js +275 -0
  6. package/dist/chunk-E46A7I6B.js +274 -0
  7. package/dist/chunk-FD4HG7KR.js +135 -0
  8. package/dist/chunk-FHU6CFHF.js +0 -0
  9. package/dist/chunk-GHUWTX7J.js +66 -0
  10. package/dist/chunk-GWVWPS3R.js +277 -0
  11. package/dist/chunk-HEZZ74SI.js +62 -0
  12. package/dist/chunk-HTZ3QFY4.js +135 -0
  13. package/dist/chunk-MQALBRGV.js +135 -0
  14. package/dist/chunk-NQWSCY44.js +70 -0
  15. package/dist/chunk-PCJEJYP6.js +68 -0
  16. package/dist/chunk-PPVS3X5Z.js +99 -0
  17. package/dist/chunk-PYIYE3HI.js +135 -0
  18. package/dist/chunk-Q6SPMEIW.js +235 -0
  19. package/dist/chunk-RNKXSBT7.js +135 -0
  20. package/dist/chunk-SPCXFN7C.js +284 -0
  21. package/dist/chunk-T5DRYLNB.js +135 -0
  22. package/dist/chunk-TSEE5NSJ.js +297 -0
  23. package/dist/chunk-U73CZU3X.js +237 -0
  24. package/dist/chunk-WAKJRVUP.js +135 -0
  25. package/dist/chunk-WELDWRDX.js +307 -0
  26. package/dist/chunk-WFUDGBKK.js +68 -0
  27. package/dist/chunk-WO2MYZXT.js +0 -0
  28. package/dist/chunk-XAQGMFSR.js +56 -0
  29. package/dist/client.cjs +328 -0
  30. package/dist/client.d.cts +17 -0
  31. package/dist/client.d.ts +17 -0
  32. package/dist/client.js +12 -0
  33. package/dist/constants-0ncqvV_O.d.ts +17 -0
  34. package/dist/constants-C7aY8u5b.d.cts +77 -0
  35. package/dist/constants-C7aY8u5b.d.ts +77 -0
  36. package/dist/constants-CVFF0ray.d.ts +17 -0
  37. package/dist/constants-CsIL25uQ.d.cts +17 -0
  38. package/dist/constants-DzCGK0Q3.d.cts +17 -0
  39. package/dist/createMantleClient-CO0uWPb-.d.cts +87 -0
  40. package/dist/createMantleClient-CuiPsTa6.d.ts +87 -0
  41. package/dist/createMantleClient-DS1Ghqrz.d.cts +51 -0
  42. package/dist/createMantleClient-DS1Ghqrz.d.ts +51 -0
  43. package/dist/createMantleClient-DVFkbBfS.d.ts +87 -0
  44. package/dist/createMantleClient-NN0Nitp9.d.cts +87 -0
  45. package/dist/express-Ck7eryef.d.cts +66 -0
  46. package/dist/express-CmEg5hR3.d.ts +66 -0
  47. package/dist/express-D8EwEcOL.d.ts +66 -0
  48. package/dist/express-eQOPxfnI.d.cts +66 -0
  49. package/dist/index.cjs +342 -155
  50. package/dist/index.d.cts +10 -290
  51. package/dist/index.d.ts +10 -290
  52. package/dist/index.js +18 -567
  53. package/dist/nextjs-Bp8DxYDN.d.ts +45 -0
  54. package/dist/nextjs-CliiaTPe.d.cts +45 -0
  55. package/dist/nextjs-D7t-BC4N.d.ts +45 -0
  56. package/dist/nextjs-Duecps0q.d.cts +45 -0
  57. package/dist/nextjs-TFhFiQuL.d.ts +45 -0
  58. package/dist/nextjs-ZO2J9mdo.d.cts +45 -0
  59. package/dist/react.cjs +454 -0
  60. package/dist/react.d.cts +93 -0
  61. package/dist/react.d.ts +93 -0
  62. package/dist/react.js +10 -0
  63. package/dist/server-express.cjs +368 -0
  64. package/dist/server-express.d.cts +5 -0
  65. package/dist/server-express.d.ts +5 -0
  66. package/dist/server-express.js +13 -0
  67. package/dist/server-nextjs.cjs +339 -0
  68. package/dist/server-nextjs.d.cts +5 -0
  69. package/dist/server-nextjs.d.ts +5 -0
  70. package/dist/server-nextjs.js +11 -0
  71. package/dist/server-web.cjs +339 -0
  72. package/dist/server-web.d.cts +4 -0
  73. package/dist/server-web.d.ts +4 -0
  74. package/dist/server-web.js +11 -0
  75. package/dist/server.cjs +497 -0
  76. package/dist/server.d.cts +79 -0
  77. package/dist/server.d.ts +79 -0
  78. package/dist/server.js +36 -0
  79. package/dist/types-2zqbJvcz.d.cts +63 -0
  80. package/dist/types-2zqbJvcz.d.ts +63 -0
  81. package/dist/types-BFUqKBBO.d.cts +63 -0
  82. package/dist/types-BFUqKBBO.d.ts +63 -0
  83. package/dist/types-C7EPJ6Hd.d.ts +85 -0
  84. package/dist/types-CEttmr1U.d.cts +97 -0
  85. package/dist/types-CoOdbZSp.d.cts +97 -0
  86. package/dist/types-CqQ6OgRi.d.ts +85 -0
  87. package/dist/types-CrOsOHcX.d.cts +85 -0
  88. package/dist/types-D20K36pc.d.ts +97 -0
  89. package/dist/types-DTzov_EE.d.ts +97 -0
  90. package/dist/types-xkNm0uzE.d.cts +85 -0
  91. package/dist/web-standards-BNQyWzBC.d.cts +77 -0
  92. package/dist/web-standards-C3D2vdTg.d.ts +77 -0
  93. package/dist/web-standards-D8j1kZxd.d.ts +77 -0
  94. package/dist/web-standards-DOYp0UDT.d.cts +77 -0
  95. package/package.json +80 -8
@@ -0,0 +1,70 @@
1
+ import {
2
+ buildRouteKey,
3
+ checkPayment,
4
+ validateAddress
5
+ } from "./chunk-U73CZU3X.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 mantlePaywall(opts) {
19
+ const { priceUsd, payTo, facilitatorUrl, telemetry, onPaymentSettled } = opts;
20
+ validateAddress(payTo, "payTo");
21
+ const priceUsdCents = Math.round(priceUsd * 100);
22
+ return function(handler) {
23
+ return async (request) => {
24
+ const url = new URL(request.url);
25
+ const method = request.method;
26
+ const path = url.pathname;
27
+ const routeKey = buildRouteKey(method, path);
28
+ const network = MANTLE_DEFAULTS.NETWORK;
29
+ const assetConfig = getDefaultAssetForNetwork(network);
30
+ const maxAmountRequiredBigInt = usdCentsToAtomic(
31
+ priceUsdCents,
32
+ assetConfig.decimals
33
+ );
34
+ const paymentRequirements = {
35
+ scheme: "exact",
36
+ network,
37
+ asset: assetConfig.address,
38
+ maxAmountRequired: maxAmountRequiredBigInt.toString(),
39
+ payTo,
40
+ price: `$${(priceUsdCents / 100).toFixed(2)}`,
41
+ currency: "USD"
42
+ };
43
+ const paymentHeader = request.headers.get("X-PAYMENT") || request.headers.get("x-payment") || null;
44
+ const result = await checkPayment({
45
+ paymentHeader,
46
+ paymentRequirements,
47
+ facilitatorUrl: facilitatorUrl || MANTLE_DEFAULTS.FACILITATOR_URL,
48
+ routeKey,
49
+ network,
50
+ asset: assetConfig.address,
51
+ telemetry,
52
+ onPaymentSettled
53
+ });
54
+ if (!result.isValid) {
55
+ return new Response(JSON.stringify(result.responseBody), {
56
+ status: result.statusCode,
57
+ headers: {
58
+ "Content-Type": "application/json"
59
+ }
60
+ });
61
+ }
62
+ return handler(request);
63
+ };
64
+ };
65
+ }
66
+
67
+ export {
68
+ mantlePaywall,
69
+ web_standards_exports
70
+ };
@@ -0,0 +1,68 @@
1
+ import {
2
+ buildRouteKey,
3
+ checkPayment,
4
+ validateAddress
5
+ } from "./chunk-U73CZU3X.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
+ mantlePaywall: () => mantlePaywall
17
+ });
18
+ import { NextResponse } from "next/server";
19
+ function mantlePaywall(opts) {
20
+ const { priceUsd, payTo, facilitatorUrl, telemetry, onPaymentSettled } = opts;
21
+ validateAddress(payTo, "payTo");
22
+ const priceUsdCents = Math.round(priceUsd * 100);
23
+ return function(handler) {
24
+ return async (req) => {
25
+ const url = new URL(req.url);
26
+ const method = req.method;
27
+ const path = url.pathname;
28
+ const routeKey = buildRouteKey(method, path);
29
+ const network = MANTLE_DEFAULTS.NETWORK;
30
+ const assetConfig = getDefaultAssetForNetwork(network);
31
+ const maxAmountRequiredBigInt = usdCentsToAtomic(
32
+ priceUsdCents,
33
+ assetConfig.decimals
34
+ );
35
+ const paymentRequirements = {
36
+ scheme: "exact",
37
+ network,
38
+ asset: assetConfig.address,
39
+ maxAmountRequired: maxAmountRequiredBigInt.toString(),
40
+ payTo,
41
+ price: `$${(priceUsdCents / 100).toFixed(2)}`,
42
+ currency: "USD"
43
+ };
44
+ const paymentHeader = req.headers.get("X-PAYMENT") || req.headers.get("x-payment") || null;
45
+ const result = await checkPayment({
46
+ paymentHeader,
47
+ paymentRequirements,
48
+ facilitatorUrl: facilitatorUrl || MANTLE_DEFAULTS.FACILITATOR_URL,
49
+ routeKey,
50
+ network,
51
+ asset: assetConfig.address,
52
+ telemetry,
53
+ onPaymentSettled
54
+ });
55
+ if (!result.isValid) {
56
+ return NextResponse.json(result.responseBody, {
57
+ status: result.statusCode
58
+ });
59
+ }
60
+ return handler(req);
61
+ };
62
+ };
63
+ }
64
+
65
+ export {
66
+ mantlePaywall,
67
+ nextjs_exports
68
+ };
@@ -0,0 +1,99 @@
1
+ import {
2
+ buildRouteKey,
3
+ checkPayment,
4
+ validateAddress
5
+ } from "./chunk-U73CZU3X.js";
6
+ import {
7
+ MANTLE_DEFAULTS,
8
+ __export,
9
+ getDefaultAssetForNetwork,
10
+ usdCentsToAtomic
11
+ } from "./chunk-HEZZ74SI.js";
12
+
13
+ // src/server/adapters/express.ts
14
+ var express_exports = {};
15
+ __export(express_exports, {
16
+ createPaymentMiddleware: () => createPaymentMiddleware,
17
+ mantlePaywall: () => mantlePaywall
18
+ });
19
+ function createPaymentMiddleware(config) {
20
+ const { facilitatorUrl, receiverAddress, routes, onPaymentSettled, telemetry } = config;
21
+ if (!facilitatorUrl) {
22
+ throw new Error("facilitatorUrl is required");
23
+ }
24
+ if (!receiverAddress) {
25
+ throw new Error("receiverAddress is required");
26
+ }
27
+ validateAddress(receiverAddress, "receiverAddress");
28
+ if (!routes || Object.keys(routes).length === 0) {
29
+ throw new Error("routes config must not be empty");
30
+ }
31
+ return async function paymentMiddleware(req, res, next) {
32
+ const routeKey = buildRouteKey(req.method, req.path);
33
+ const routeConfig = routes[routeKey];
34
+ if (!routeConfig) {
35
+ next();
36
+ return;
37
+ }
38
+ const { priceUsdCents, network } = routeConfig;
39
+ const assetConfig = getDefaultAssetForNetwork(network);
40
+ const maxAmountRequiredBigInt = usdCentsToAtomic(
41
+ priceUsdCents,
42
+ assetConfig.decimals
43
+ );
44
+ const paymentRequirements = {
45
+ scheme: "exact",
46
+ network,
47
+ asset: assetConfig.address,
48
+ maxAmountRequired: maxAmountRequiredBigInt.toString(),
49
+ payTo: receiverAddress,
50
+ price: `$${(priceUsdCents / 100).toFixed(2)}`,
51
+ currency: "USD"
52
+ };
53
+ const paymentHeader = req.header("X-PAYMENT") || req.header("x-payment") || null;
54
+ const result = await checkPayment({
55
+ paymentHeader,
56
+ paymentRequirements,
57
+ facilitatorUrl,
58
+ routeKey,
59
+ network,
60
+ asset: assetConfig.address,
61
+ telemetry,
62
+ onPaymentSettled
63
+ });
64
+ if (!result.isValid) {
65
+ res.status(result.statusCode).json(result.responseBody);
66
+ return;
67
+ }
68
+ next();
69
+ };
70
+ }
71
+ function mantlePaywall(opts) {
72
+ const { priceUsd, payTo, facilitatorUrl, telemetry, onPaymentSettled } = opts;
73
+ validateAddress(payTo, "payTo");
74
+ const priceUsdCents = Math.round(priceUsd * 100);
75
+ return async (req, res, next) => {
76
+ const method = (req.method || "GET").toUpperCase();
77
+ const path = req.path || "/";
78
+ const routeKey = `${method} ${path}`;
79
+ const middleware = createPaymentMiddleware({
80
+ facilitatorUrl: facilitatorUrl || MANTLE_DEFAULTS.FACILITATOR_URL,
81
+ receiverAddress: payTo,
82
+ routes: {
83
+ [routeKey]: {
84
+ priceUsdCents,
85
+ network: MANTLE_DEFAULTS.NETWORK
86
+ }
87
+ },
88
+ telemetry,
89
+ onPaymentSettled
90
+ });
91
+ return middleware(req, res, next);
92
+ };
93
+ }
94
+
95
+ export {
96
+ createPaymentMiddleware,
97
+ mantlePaywall,
98
+ express_exports
99
+ };
@@ -0,0 +1,135 @@
1
+ import {
2
+ createMantleClient
3
+ } from "./chunk-DA6ZBXNO.js";
4
+
5
+ // src/client/react/useEthersWallet.ts
6
+ import { useState, useEffect, useCallback } from "react";
7
+ import { ethers } from "ethers";
8
+ function useEthersWallet(options) {
9
+ const [address, setAddress] = useState(void 0);
10
+ const [isConnected, setIsConnected] = useState(false);
11
+ const [provider, setProvider] = useState(
12
+ void 0
13
+ );
14
+ const [chainId, setChainId] = useState(void 0);
15
+ const [error, setError] = useState(void 0);
16
+ const connect = useCallback(async () => {
17
+ try {
18
+ setError(void 0);
19
+ if (typeof window === "undefined" || !window.ethereum) {
20
+ throw new Error(
21
+ "No Ethereum wallet detected. Please install MetaMask or another wallet."
22
+ );
23
+ }
24
+ const browserProvider = new ethers.BrowserProvider(
25
+ window.ethereum
26
+ );
27
+ setProvider(browserProvider);
28
+ const accounts = await window.ethereum.request({
29
+ method: "eth_requestAccounts"
30
+ });
31
+ if (!accounts || accounts.length === 0) {
32
+ throw new Error("No accounts returned from wallet");
33
+ }
34
+ const userAddress = accounts[0];
35
+ setAddress(userAddress);
36
+ setIsConnected(true);
37
+ const network = await browserProvider.getNetwork();
38
+ setChainId(Number(network.chainId));
39
+ } catch (err) {
40
+ const errorObj = err instanceof Error ? err : new Error(String(err));
41
+ setError(errorObj);
42
+ setIsConnected(false);
43
+ setAddress(void 0);
44
+ setChainId(void 0);
45
+ throw errorObj;
46
+ }
47
+ }, []);
48
+ const disconnect = useCallback(() => {
49
+ setAddress(void 0);
50
+ setIsConnected(false);
51
+ setChainId(void 0);
52
+ setError(void 0);
53
+ }, []);
54
+ useEffect(() => {
55
+ if (typeof window === "undefined" || !window.ethereum) return;
56
+ const ethereum = window.ethereum;
57
+ const handleAccountsChanged = (accounts) => {
58
+ const accountsArray = accounts;
59
+ if (!accountsArray || accountsArray.length === 0) {
60
+ disconnect();
61
+ } else {
62
+ setAddress(accountsArray[0]);
63
+ setIsConnected(true);
64
+ }
65
+ };
66
+ if (ethereum.on) {
67
+ ethereum.on("accountsChanged", handleAccountsChanged);
68
+ }
69
+ return () => {
70
+ if (ethereum.removeListener) {
71
+ ethereum.removeListener("accountsChanged", handleAccountsChanged);
72
+ }
73
+ };
74
+ }, [disconnect]);
75
+ useEffect(() => {
76
+ if (typeof window === "undefined" || !window.ethereum) return;
77
+ const ethereum = window.ethereum;
78
+ const handleChainChanged = (chainIdHex) => {
79
+ const newChainId = parseInt(chainIdHex, 16);
80
+ setChainId(newChainId);
81
+ };
82
+ if (ethereum.on) {
83
+ ethereum.on("chainChanged", handleChainChanged);
84
+ }
85
+ return () => {
86
+ if (ethereum.removeListener) {
87
+ ethereum.removeListener("chainChanged", handleChainChanged);
88
+ }
89
+ };
90
+ }, []);
91
+ useEffect(() => {
92
+ if (options?.autoConnect) {
93
+ connect().catch((err) => {
94
+ console.warn("[useEthersWallet] Auto-connect failed:", err);
95
+ });
96
+ }
97
+ }, [options?.autoConnect, connect]);
98
+ return {
99
+ address,
100
+ isConnected,
101
+ provider,
102
+ chainId,
103
+ connect,
104
+ disconnect,
105
+ error
106
+ };
107
+ }
108
+
109
+ // src/client/react/useMantleX402.ts
110
+ function useMantleX402(opts) {
111
+ const { address, isConnected } = useEthersWallet({
112
+ autoConnect: opts?.autoConnect ?? false
113
+ });
114
+ const client = createMantleClient({
115
+ facilitatorUrl: opts?.facilitatorUrl,
116
+ resourceUrl: opts?.resourceUrl,
117
+ projectKey: opts?.projectKey,
118
+ getAccount: () => {
119
+ if (!isConnected || !address) return void 0;
120
+ return address;
121
+ },
122
+ getProvider: () => {
123
+ if (typeof window !== "undefined" && window.ethereum) {
124
+ return window.ethereum;
125
+ }
126
+ return void 0;
127
+ }
128
+ });
129
+ return client;
130
+ }
131
+
132
+ export {
133
+ useEthersWallet,
134
+ useMantleX402
135
+ };
@@ -0,0 +1,235 @@
1
+ import {
2
+ MANTLE_DEFAULTS,
3
+ getDefaultAssetForNetwork,
4
+ usdCentsToAtomic
5
+ } from "./chunk-XAQGMFSR.js";
6
+
7
+ // src/server/constants.ts
8
+ var DEFAULT_TELEMETRY_ENDPOINT = void 0;
9
+
10
+ // src/server/telemetry.ts
11
+ function createTelemetryEvent(entry, config) {
12
+ const assetConfig = getDefaultAssetForNetwork(entry.network);
13
+ return {
14
+ event: "payment_verified",
15
+ ts: entry.timestamp,
16
+ projectKey: config.projectKey,
17
+ network: entry.network,
18
+ buyer: entry.from,
19
+ payTo: entry.to,
20
+ amountAtomic: entry.valueAtomic,
21
+ asset: entry.asset,
22
+ decimals: assetConfig.decimals,
23
+ nonce: entry.id,
24
+ route: entry.route ?? "unknown",
25
+ // Facilitator metadata
26
+ facilitatorType: "hosted",
27
+ // SDK always uses hosted mode
28
+ facilitatorUrl: entry.facilitatorUrl,
29
+ // From PaymentLogEntry
30
+ // facilitatorAddress is undefined for SDK (not available)
31
+ // Optional metadata
32
+ txHash: entry.txHash,
33
+ priceUsd: entry.paymentRequirements?.price
34
+ };
35
+ }
36
+ async function sendTelemetry(event, endpoint) {
37
+ const targetEndpoint = endpoint ?? DEFAULT_TELEMETRY_ENDPOINT;
38
+ if (!targetEndpoint) {
39
+ return;
40
+ }
41
+ try {
42
+ const response = await fetch(targetEndpoint, {
43
+ method: "POST",
44
+ headers: {
45
+ "Content-Type": "application/json",
46
+ "Authorization": `Bearer ${event.projectKey}`
47
+ },
48
+ body: JSON.stringify(event)
49
+ });
50
+ if (!response.ok) {
51
+ console.warn(
52
+ `[x402-telemetry] Failed to send event: HTTP ${response.status}`
53
+ );
54
+ }
55
+ } catch (err) {
56
+ console.error("[x402-telemetry] Error sending telemetry:", err);
57
+ }
58
+ }
59
+
60
+ // src/server/paymentMiddleware.ts
61
+ function getRouteKey(req) {
62
+ const method = (req.method || "GET").toUpperCase();
63
+ const path = req.path || "/";
64
+ return `${method} ${path}`;
65
+ }
66
+ function decodePaymentHeader(paymentHeaderBase64) {
67
+ try {
68
+ if (typeof Buffer !== "undefined") {
69
+ const json = Buffer.from(paymentHeaderBase64, "base64").toString("utf8");
70
+ return JSON.parse(json);
71
+ }
72
+ if (typeof atob === "function") {
73
+ const json = atob(paymentHeaderBase64);
74
+ return JSON.parse(json);
75
+ }
76
+ throw new Error("No base64 decoding available in this environment");
77
+ } catch (err) {
78
+ const msg = err instanceof Error ? err.message : "Unknown error";
79
+ throw new Error(`Failed to decode paymentHeader: ${msg}`);
80
+ }
81
+ }
82
+ function createPaymentMiddleware(config) {
83
+ const { facilitatorUrl, receiverAddress, routes, onPaymentSettled, telemetry } = config;
84
+ if (!facilitatorUrl) {
85
+ throw new Error("facilitatorUrl is required");
86
+ }
87
+ if (!receiverAddress) {
88
+ throw new Error("receiverAddress is required");
89
+ }
90
+ if (!routes || Object.keys(routes).length === 0) {
91
+ throw new Error("routes config must not be empty");
92
+ }
93
+ return async function paymentMiddleware(req, res, next) {
94
+ const routeKey = getRouteKey(req);
95
+ const routeConfig = routes[routeKey];
96
+ if (!routeConfig) {
97
+ next();
98
+ return;
99
+ }
100
+ const { priceUsdCents, network } = routeConfig;
101
+ const assetConfig = getDefaultAssetForNetwork(network);
102
+ const maxAmountRequiredBigInt = usdCentsToAtomic(
103
+ priceUsdCents,
104
+ assetConfig.decimals
105
+ );
106
+ const paymentRequirements = {
107
+ scheme: "exact",
108
+ network,
109
+ asset: assetConfig.address,
110
+ maxAmountRequired: maxAmountRequiredBigInt.toString(),
111
+ payTo: receiverAddress,
112
+ price: `$${(priceUsdCents / 100).toFixed(2)}`,
113
+ currency: "USD"
114
+ };
115
+ const paymentHeader = req.header("X-PAYMENT") ?? req.header("x-payment");
116
+ if (!paymentHeader) {
117
+ res.status(402).json({
118
+ error: "Payment Required",
119
+ paymentRequirements,
120
+ paymentHeader: null
121
+ });
122
+ return;
123
+ }
124
+ try {
125
+ const verifyUrl = `${facilitatorUrl.replace(/\/+$/, "")}/verify`;
126
+ const verifyRes = await fetch(verifyUrl, {
127
+ method: "POST",
128
+ headers: {
129
+ "Content-Type": "application/json"
130
+ },
131
+ body: JSON.stringify({
132
+ x402Version: 1,
133
+ paymentHeader,
134
+ paymentRequirements
135
+ })
136
+ });
137
+ if (!verifyRes.ok) {
138
+ const text = await verifyRes.text().catch(() => "");
139
+ console.error(
140
+ "[x402-mantle-sdk] Facilitator /verify returned non-OK:",
141
+ verifyRes.status,
142
+ text
143
+ );
144
+ res.status(500).json({
145
+ error: "Payment verification error",
146
+ details: `Facilitator responded with HTTP ${verifyRes.status}`
147
+ });
148
+ return;
149
+ }
150
+ const verifyJson = await verifyRes.json();
151
+ if (!verifyJson.isValid) {
152
+ res.status(402).json({
153
+ error: "Payment verification failed",
154
+ invalidReason: verifyJson.invalidReason ?? null,
155
+ paymentRequirements,
156
+ paymentHeader: null
157
+ });
158
+ return;
159
+ }
160
+ if (onPaymentSettled) {
161
+ try {
162
+ const headerObj = decodePaymentHeader(paymentHeader);
163
+ const { authorization } = headerObj.payload;
164
+ const logEntry = {
165
+ id: authorization.nonce,
166
+ from: authorization.from,
167
+ to: authorization.to,
168
+ valueAtomic: authorization.value,
169
+ network,
170
+ asset: assetConfig.address,
171
+ route: routeKey,
172
+ timestamp: Date.now(),
173
+ facilitatorUrl,
174
+ // Pass from config closure
175
+ paymentRequirements
176
+ };
177
+ onPaymentSettled(logEntry);
178
+ if (telemetry) {
179
+ const event = createTelemetryEvent(logEntry, telemetry);
180
+ sendTelemetry(event, telemetry.endpoint).catch(
181
+ (err) => console.error("[x402-telemetry] Async send failed:", err)
182
+ );
183
+ }
184
+ } catch (err) {
185
+ console.error(
186
+ "[x402-mantle-sdk] Error calling onPaymentSettled hook:",
187
+ err
188
+ );
189
+ }
190
+ }
191
+ next();
192
+ return;
193
+ } catch (err) {
194
+ console.error(
195
+ "[x402-mantle-sdk] Error while calling facilitator /verify:",
196
+ err
197
+ );
198
+ const message = err instanceof Error ? err.message : "Unknown verification error";
199
+ res.status(500).json({
200
+ error: "Payment verification error",
201
+ details: message
202
+ });
203
+ return;
204
+ }
205
+ };
206
+ }
207
+
208
+ // src/server/mantlePaywall.ts
209
+ function mantlePaywall(opts) {
210
+ const { priceUsd, payTo, facilitatorUrl, telemetry, onPaymentSettled } = opts;
211
+ const priceUsdCents = Math.round(priceUsd * 100);
212
+ return async (req, res, next) => {
213
+ const method = (req.method || "GET").toUpperCase();
214
+ const path = req.path || "/";
215
+ const routeKey = `${method} ${path}`;
216
+ const middleware = createPaymentMiddleware({
217
+ facilitatorUrl: facilitatorUrl || MANTLE_DEFAULTS.FACILITATOR_URL,
218
+ receiverAddress: payTo,
219
+ routes: {
220
+ [routeKey]: {
221
+ priceUsdCents,
222
+ network: MANTLE_DEFAULTS.NETWORK
223
+ }
224
+ },
225
+ telemetry,
226
+ onPaymentSettled
227
+ });
228
+ return middleware(req, res, next);
229
+ };
230
+ }
231
+
232
+ export {
233
+ createPaymentMiddleware,
234
+ mantlePaywall
235
+ };