@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.
- package/dist/chunk-23QNUJIB.js +136 -0
- package/dist/chunk-6GLR5EBK.js +96 -0
- package/dist/chunk-BRGW36P7.js +211 -0
- package/dist/chunk-CTI5CRDY.js +274 -0
- package/dist/chunk-DA6ZBXNO.js +275 -0
- package/dist/chunk-E46A7I6B.js +274 -0
- package/dist/chunk-FD4HG7KR.js +135 -0
- package/dist/chunk-FHU6CFHF.js +0 -0
- package/dist/chunk-GHUWTX7J.js +66 -0
- package/dist/chunk-GWVWPS3R.js +277 -0
- package/dist/chunk-HEZZ74SI.js +62 -0
- package/dist/chunk-HTZ3QFY4.js +135 -0
- package/dist/chunk-MQALBRGV.js +135 -0
- package/dist/chunk-NQWSCY44.js +70 -0
- package/dist/chunk-PCJEJYP6.js +68 -0
- package/dist/chunk-PPVS3X5Z.js +99 -0
- package/dist/chunk-PYIYE3HI.js +135 -0
- package/dist/chunk-Q6SPMEIW.js +235 -0
- package/dist/chunk-RNKXSBT7.js +135 -0
- package/dist/chunk-SPCXFN7C.js +284 -0
- package/dist/chunk-T5DRYLNB.js +135 -0
- package/dist/chunk-TSEE5NSJ.js +297 -0
- package/dist/chunk-U73CZU3X.js +237 -0
- package/dist/chunk-WAKJRVUP.js +135 -0
- package/dist/chunk-WELDWRDX.js +307 -0
- package/dist/chunk-WFUDGBKK.js +68 -0
- package/dist/chunk-WO2MYZXT.js +0 -0
- package/dist/chunk-XAQGMFSR.js +56 -0
- package/dist/client.cjs +328 -0
- package/dist/client.d.cts +17 -0
- package/dist/client.d.ts +17 -0
- package/dist/client.js +12 -0
- package/dist/constants-0ncqvV_O.d.ts +17 -0
- package/dist/constants-C7aY8u5b.d.cts +77 -0
- package/dist/constants-C7aY8u5b.d.ts +77 -0
- package/dist/constants-CVFF0ray.d.ts +17 -0
- package/dist/constants-CsIL25uQ.d.cts +17 -0
- package/dist/constants-DzCGK0Q3.d.cts +17 -0
- package/dist/createMantleClient-CO0uWPb-.d.cts +87 -0
- package/dist/createMantleClient-CuiPsTa6.d.ts +87 -0
- package/dist/createMantleClient-DS1Ghqrz.d.cts +51 -0
- package/dist/createMantleClient-DS1Ghqrz.d.ts +51 -0
- package/dist/createMantleClient-DVFkbBfS.d.ts +87 -0
- package/dist/createMantleClient-NN0Nitp9.d.cts +87 -0
- package/dist/express-Ck7eryef.d.cts +66 -0
- package/dist/express-CmEg5hR3.d.ts +66 -0
- package/dist/express-D8EwEcOL.d.ts +66 -0
- package/dist/express-eQOPxfnI.d.cts +66 -0
- package/dist/index.cjs +342 -155
- package/dist/index.d.cts +10 -290
- package/dist/index.d.ts +10 -290
- package/dist/index.js +18 -567
- package/dist/nextjs-Bp8DxYDN.d.ts +45 -0
- package/dist/nextjs-CliiaTPe.d.cts +45 -0
- package/dist/nextjs-D7t-BC4N.d.ts +45 -0
- package/dist/nextjs-Duecps0q.d.cts +45 -0
- package/dist/nextjs-TFhFiQuL.d.ts +45 -0
- package/dist/nextjs-ZO2J9mdo.d.cts +45 -0
- package/dist/react.cjs +454 -0
- package/dist/react.d.cts +93 -0
- package/dist/react.d.ts +93 -0
- package/dist/react.js +10 -0
- package/dist/server-express.cjs +368 -0
- package/dist/server-express.d.cts +5 -0
- package/dist/server-express.d.ts +5 -0
- package/dist/server-express.js +13 -0
- package/dist/server-nextjs.cjs +339 -0
- package/dist/server-nextjs.d.cts +5 -0
- package/dist/server-nextjs.d.ts +5 -0
- package/dist/server-nextjs.js +11 -0
- package/dist/server-web.cjs +339 -0
- package/dist/server-web.d.cts +4 -0
- package/dist/server-web.d.ts +4 -0
- package/dist/server-web.js +11 -0
- package/dist/server.cjs +497 -0
- package/dist/server.d.cts +79 -0
- package/dist/server.d.ts +79 -0
- package/dist/server.js +36 -0
- package/dist/types-2zqbJvcz.d.cts +63 -0
- package/dist/types-2zqbJvcz.d.ts +63 -0
- package/dist/types-BFUqKBBO.d.cts +63 -0
- package/dist/types-BFUqKBBO.d.ts +63 -0
- package/dist/types-C7EPJ6Hd.d.ts +85 -0
- package/dist/types-CEttmr1U.d.cts +97 -0
- package/dist/types-CoOdbZSp.d.cts +97 -0
- package/dist/types-CqQ6OgRi.d.ts +85 -0
- package/dist/types-CrOsOHcX.d.cts +85 -0
- package/dist/types-D20K36pc.d.ts +97 -0
- package/dist/types-DTzov_EE.d.ts +97 -0
- package/dist/types-xkNm0uzE.d.cts +85 -0
- package/dist/web-standards-BNQyWzBC.d.cts +77 -0
- package/dist/web-standards-C3D2vdTg.d.ts +77 -0
- package/dist/web-standards-D8j1kZxd.d.ts +77 -0
- package/dist/web-standards-DOYp0UDT.d.cts +77 -0
- package/package.json +80 -8
package/dist/index.js
CHANGED
|
@@ -1,575 +1,26 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
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
|
-
};
|
|
25
|
-
function getDefaultAssetForNetwork(network) {
|
|
26
|
-
switch (network) {
|
|
27
|
-
case MANTLE_MAINNET_NETWORK_ID:
|
|
28
|
-
default:
|
|
29
|
-
return MANTLE_MAINNET_USDC;
|
|
30
|
-
}
|
|
31
|
-
}
|
|
32
|
-
function getChainIdForNetwork(network) {
|
|
33
|
-
switch (network) {
|
|
34
|
-
case MANTLE_MAINNET_NETWORK_ID:
|
|
35
|
-
default:
|
|
36
|
-
return MANTLE_MAINNET_CHAIN_ID;
|
|
37
|
-
}
|
|
38
|
-
}
|
|
39
|
-
function usdCentsToAtomic(cents, decimals) {
|
|
40
|
-
if (cents < 0) {
|
|
41
|
-
throw new Error("priceUsdCents must be non-negative");
|
|
42
|
-
}
|
|
43
|
-
if (decimals < 2) {
|
|
44
|
-
throw new Error("token decimals must be >= 2 for USD cent conversion");
|
|
45
|
-
}
|
|
46
|
-
const base = BigInt(10) ** BigInt(decimals - 2);
|
|
47
|
-
return BigInt(cents) * base;
|
|
48
|
-
}
|
|
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
|
-
|
|
103
|
-
// src/server/paymentMiddleware.ts
|
|
104
|
-
function getRouteKey(req) {
|
|
105
|
-
const method = (req.method || "GET").toUpperCase();
|
|
106
|
-
const path = req.path || "/";
|
|
107
|
-
return `${method} ${path}`;
|
|
108
|
-
}
|
|
109
|
-
function decodePaymentHeader(paymentHeaderBase64) {
|
|
110
|
-
try {
|
|
111
|
-
if (typeof Buffer !== "undefined") {
|
|
112
|
-
const json = Buffer.from(paymentHeaderBase64, "base64").toString("utf8");
|
|
113
|
-
return JSON.parse(json);
|
|
114
|
-
}
|
|
115
|
-
if (typeof atob === "function") {
|
|
116
|
-
const json = atob(paymentHeaderBase64);
|
|
117
|
-
return JSON.parse(json);
|
|
118
|
-
}
|
|
119
|
-
throw new Error("No base64 decoding available in this environment");
|
|
120
|
-
} catch (err) {
|
|
121
|
-
const msg = err instanceof Error ? err.message : "Unknown error";
|
|
122
|
-
throw new Error(`Failed to decode paymentHeader: ${msg}`);
|
|
123
|
-
}
|
|
124
|
-
}
|
|
125
|
-
function createPaymentMiddleware(config) {
|
|
126
|
-
const { facilitatorUrl, receiverAddress, routes, onPaymentSettled, telemetry } = config;
|
|
127
|
-
if (!facilitatorUrl) {
|
|
128
|
-
throw new Error("facilitatorUrl is required");
|
|
129
|
-
}
|
|
130
|
-
if (!receiverAddress) {
|
|
131
|
-
throw new Error("receiverAddress is required");
|
|
132
|
-
}
|
|
133
|
-
if (!routes || Object.keys(routes).length === 0) {
|
|
134
|
-
throw new Error("routes config must not be empty");
|
|
135
|
-
}
|
|
136
|
-
return async function paymentMiddleware(req, res, next) {
|
|
137
|
-
const routeKey = getRouteKey(req);
|
|
138
|
-
const routeConfig = routes[routeKey];
|
|
139
|
-
if (!routeConfig) {
|
|
140
|
-
next();
|
|
141
|
-
return;
|
|
142
|
-
}
|
|
143
|
-
const { priceUsdCents, network } = routeConfig;
|
|
144
|
-
const assetConfig = getDefaultAssetForNetwork(network);
|
|
145
|
-
const maxAmountRequiredBigInt = usdCentsToAtomic(
|
|
146
|
-
priceUsdCents,
|
|
147
|
-
assetConfig.decimals
|
|
148
|
-
);
|
|
149
|
-
const paymentRequirements = {
|
|
150
|
-
scheme: "exact",
|
|
151
|
-
network,
|
|
152
|
-
asset: assetConfig.address,
|
|
153
|
-
maxAmountRequired: maxAmountRequiredBigInt.toString(),
|
|
154
|
-
payTo: receiverAddress,
|
|
155
|
-
price: `$${(priceUsdCents / 100).toFixed(2)}`,
|
|
156
|
-
currency: "USD"
|
|
157
|
-
};
|
|
158
|
-
const paymentHeader = req.header("X-PAYMENT") ?? req.header("x-payment");
|
|
159
|
-
if (!paymentHeader) {
|
|
160
|
-
res.status(402).json({
|
|
161
|
-
error: "Payment Required",
|
|
162
|
-
paymentRequirements,
|
|
163
|
-
paymentHeader: null
|
|
164
|
-
});
|
|
165
|
-
return;
|
|
166
|
-
}
|
|
167
|
-
try {
|
|
168
|
-
const verifyUrl = `${facilitatorUrl.replace(/\/+$/, "")}/verify`;
|
|
169
|
-
const verifyRes = await fetch(verifyUrl, {
|
|
170
|
-
method: "POST",
|
|
171
|
-
headers: {
|
|
172
|
-
"Content-Type": "application/json"
|
|
173
|
-
},
|
|
174
|
-
body: JSON.stringify({
|
|
175
|
-
x402Version: 1,
|
|
176
|
-
paymentHeader,
|
|
177
|
-
paymentRequirements
|
|
178
|
-
})
|
|
179
|
-
});
|
|
180
|
-
if (!verifyRes.ok) {
|
|
181
|
-
const text = await verifyRes.text().catch(() => "");
|
|
182
|
-
console.error(
|
|
183
|
-
"[x402-mantle-sdk] Facilitator /verify returned non-OK:",
|
|
184
|
-
verifyRes.status,
|
|
185
|
-
text
|
|
186
|
-
);
|
|
187
|
-
res.status(500).json({
|
|
188
|
-
error: "Payment verification error",
|
|
189
|
-
details: `Facilitator responded with HTTP ${verifyRes.status}`
|
|
190
|
-
});
|
|
191
|
-
return;
|
|
192
|
-
}
|
|
193
|
-
const verifyJson = await verifyRes.json();
|
|
194
|
-
if (!verifyJson.isValid) {
|
|
195
|
-
res.status(402).json({
|
|
196
|
-
error: "Payment verification failed",
|
|
197
|
-
invalidReason: verifyJson.invalidReason ?? null,
|
|
198
|
-
paymentRequirements,
|
|
199
|
-
paymentHeader: null
|
|
200
|
-
});
|
|
201
|
-
return;
|
|
202
|
-
}
|
|
203
|
-
if (onPaymentSettled) {
|
|
204
|
-
try {
|
|
205
|
-
const headerObj = decodePaymentHeader(paymentHeader);
|
|
206
|
-
const { authorization } = headerObj.payload;
|
|
207
|
-
const logEntry = {
|
|
208
|
-
id: authorization.nonce,
|
|
209
|
-
from: authorization.from,
|
|
210
|
-
to: authorization.to,
|
|
211
|
-
valueAtomic: authorization.value,
|
|
212
|
-
network,
|
|
213
|
-
asset: assetConfig.address,
|
|
214
|
-
route: routeKey,
|
|
215
|
-
timestamp: Date.now(),
|
|
216
|
-
facilitatorUrl,
|
|
217
|
-
// Pass from config closure
|
|
218
|
-
paymentRequirements
|
|
219
|
-
};
|
|
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
|
-
}
|
|
227
|
-
} catch (err) {
|
|
228
|
-
console.error(
|
|
229
|
-
"[x402-mantle-sdk] Error calling onPaymentSettled hook:",
|
|
230
|
-
err
|
|
231
|
-
);
|
|
232
|
-
}
|
|
233
|
-
}
|
|
234
|
-
next();
|
|
235
|
-
return;
|
|
236
|
-
} catch (err) {
|
|
237
|
-
console.error(
|
|
238
|
-
"[x402-mantle-sdk] Error while calling facilitator /verify:",
|
|
239
|
-
err
|
|
240
|
-
);
|
|
241
|
-
const message = err instanceof Error ? err.message : "Unknown verification error";
|
|
242
|
-
res.status(500).json({
|
|
243
|
-
error: "Payment verification error",
|
|
244
|
-
details: message
|
|
245
|
-
});
|
|
246
|
-
return;
|
|
247
|
-
}
|
|
248
|
-
};
|
|
249
|
-
}
|
|
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
|
-
|
|
275
|
-
// src/shared/utils.ts
|
|
276
|
-
function encodeJsonToBase64(value) {
|
|
277
|
-
const json = JSON.stringify(value);
|
|
278
|
-
if (typeof btoa === "function") {
|
|
279
|
-
const bytes = new TextEncoder().encode(json);
|
|
280
|
-
const binString = Array.from(
|
|
281
|
-
bytes,
|
|
282
|
-
(byte) => String.fromCodePoint(byte)
|
|
283
|
-
).join("");
|
|
284
|
-
return btoa(binString);
|
|
285
|
-
}
|
|
286
|
-
if (typeof globalThis.Buffer !== "undefined") {
|
|
287
|
-
return globalThis.Buffer.from(json, "utf8").toString("base64");
|
|
288
|
-
}
|
|
289
|
-
throw new Error("No base64 implementation found in this environment");
|
|
290
|
-
}
|
|
291
|
-
function randomBytes32Hex() {
|
|
292
|
-
if (typeof crypto !== "undefined" && "getRandomValues" in crypto) {
|
|
293
|
-
const arr = new Uint8Array(32);
|
|
294
|
-
crypto.getRandomValues(arr);
|
|
295
|
-
return "0x" + Array.from(arr).map((b) => b.toString(16).padStart(2, "0")).join("");
|
|
296
|
-
}
|
|
297
|
-
try {
|
|
298
|
-
const nodeCrypto = __require("crypto");
|
|
299
|
-
const buf = nodeCrypto.randomBytes(32);
|
|
300
|
-
return "0x" + buf.toString("hex");
|
|
301
|
-
} catch {
|
|
302
|
-
throw new Error(
|
|
303
|
-
"No cryptographically secure random number generator found. This environment does not support crypto.getRandomValues or Node.js crypto module."
|
|
304
|
-
);
|
|
305
|
-
}
|
|
306
|
-
}
|
|
307
|
-
|
|
308
|
-
// src/client/paymentClient.ts
|
|
309
|
-
function joinUrl(base, path) {
|
|
310
|
-
const normalizedBase = base.replace(/\/+$/, "");
|
|
311
|
-
const normalizedPath = path.startsWith("/") ? path : `/${path}`;
|
|
312
|
-
return `${normalizedBase}${normalizedPath}`;
|
|
313
|
-
}
|
|
314
|
-
async function getUserAddressFromProvider(provider) {
|
|
315
|
-
const p = provider;
|
|
316
|
-
if (!p || typeof p.request !== "function") {
|
|
317
|
-
throw new Error("provider must implement EIP-1193 request()");
|
|
318
|
-
}
|
|
319
|
-
const accounts = await p.request({
|
|
320
|
-
method: "eth_requestAccounts"
|
|
321
|
-
});
|
|
322
|
-
if (!accounts || accounts.length === 0) {
|
|
323
|
-
throw new Error("No accounts returned from provider");
|
|
324
|
-
}
|
|
325
|
-
return accounts[0];
|
|
326
|
-
}
|
|
327
|
-
function buildTypedDataForAuthorization(authorization, paymentRequirements) {
|
|
328
|
-
const chainId = getChainIdForNetwork(paymentRequirements.network);
|
|
329
|
-
const verifyingContract = paymentRequirements.asset;
|
|
330
|
-
const domain = {
|
|
331
|
-
name: "USD Coin",
|
|
332
|
-
version: "2",
|
|
333
|
-
chainId,
|
|
334
|
-
verifyingContract
|
|
335
|
-
};
|
|
336
|
-
const types = {
|
|
337
|
-
TransferWithAuthorization: [
|
|
338
|
-
{ name: "from", type: "address" },
|
|
339
|
-
{ name: "to", type: "address" },
|
|
340
|
-
{ name: "value", type: "uint256" },
|
|
341
|
-
{ name: "validAfter", type: "uint256" },
|
|
342
|
-
{ name: "validBefore", type: "uint256" },
|
|
343
|
-
{ name: "nonce", type: "bytes32" }
|
|
344
|
-
]
|
|
345
|
-
};
|
|
346
|
-
return {
|
|
347
|
-
domain,
|
|
348
|
-
types,
|
|
349
|
-
primaryType: "TransferWithAuthorization",
|
|
350
|
-
message: authorization
|
|
351
|
-
};
|
|
352
|
-
}
|
|
353
|
-
async function signAuthorizationWithProvider(provider, address, authorization, paymentRequirements) {
|
|
354
|
-
const p = provider;
|
|
355
|
-
if (!p || typeof p.request !== "function") {
|
|
356
|
-
throw new Error("provider must implement EIP-1193 request()");
|
|
357
|
-
}
|
|
358
|
-
const typedData = buildTypedDataForAuthorization(
|
|
359
|
-
authorization,
|
|
360
|
-
paymentRequirements
|
|
361
|
-
);
|
|
362
|
-
const params = [address, JSON.stringify(typedData)];
|
|
363
|
-
const signature = await p.request({
|
|
364
|
-
method: "eth_signTypedData_v4",
|
|
365
|
-
params
|
|
366
|
-
});
|
|
367
|
-
if (typeof signature !== "string" || !signature.startsWith("0x")) {
|
|
368
|
-
throw new Error("Invalid signature returned from provider");
|
|
369
|
-
}
|
|
370
|
-
return signature;
|
|
371
|
-
}
|
|
372
|
-
function createPaymentClient(config) {
|
|
373
|
-
const {
|
|
374
|
-
resourceUrl,
|
|
375
|
-
facilitatorUrl,
|
|
376
|
-
provider,
|
|
377
|
-
userAddress: userAddressOverride,
|
|
378
|
-
projectKey
|
|
379
|
-
} = config;
|
|
380
|
-
if (!resourceUrl) {
|
|
381
|
-
throw new Error("resourceUrl is required");
|
|
382
|
-
}
|
|
383
|
-
if (!facilitatorUrl) {
|
|
384
|
-
throw new Error("facilitatorUrl is required");
|
|
385
|
-
}
|
|
386
|
-
if (!provider) {
|
|
387
|
-
throw new Error("provider is required (e.g. window.ethereum)");
|
|
388
|
-
}
|
|
389
|
-
return {
|
|
390
|
-
async callWithPayment(path, options) {
|
|
391
|
-
const method = options?.method ?? "GET";
|
|
392
|
-
const headers = {
|
|
393
|
-
...options?.headers ?? {}
|
|
394
|
-
};
|
|
395
|
-
let body;
|
|
396
|
-
if (options?.body !== void 0) {
|
|
397
|
-
headers["Content-Type"] = headers["Content-Type"] ?? "application/json";
|
|
398
|
-
body = JSON.stringify(options.body);
|
|
399
|
-
}
|
|
400
|
-
const initialUrl = joinUrl(resourceUrl, path);
|
|
401
|
-
const initialRes = await fetch(initialUrl, {
|
|
402
|
-
method,
|
|
403
|
-
headers,
|
|
404
|
-
body
|
|
405
|
-
});
|
|
406
|
-
if (initialRes.status !== 402) {
|
|
407
|
-
const json = await initialRes.json().catch((err) => {
|
|
408
|
-
console.error("[x402] Failed to parse initial response JSON:", err);
|
|
409
|
-
return null;
|
|
410
|
-
});
|
|
411
|
-
return {
|
|
412
|
-
response: json,
|
|
413
|
-
paymentHeader: "",
|
|
414
|
-
paymentRequirements: {
|
|
415
|
-
scheme: "exact",
|
|
416
|
-
network: "mantle-mainnet",
|
|
417
|
-
asset: "",
|
|
418
|
-
maxAmountRequired: "0",
|
|
419
|
-
payTo: ""
|
|
420
|
-
},
|
|
421
|
-
txHash: void 0
|
|
422
|
-
};
|
|
423
|
-
}
|
|
424
|
-
const bodyJson = await initialRes.json();
|
|
425
|
-
const paymentRequirements = bodyJson.paymentRequirements;
|
|
426
|
-
if (!paymentRequirements) {
|
|
427
|
-
throw new Error(
|
|
428
|
-
"402 response did not include paymentRequirements field"
|
|
429
|
-
);
|
|
430
|
-
}
|
|
431
|
-
const fromAddress = userAddressOverride ?? await getUserAddressFromProvider(provider);
|
|
432
|
-
const nowSec = Math.floor(Date.now() / 1e3);
|
|
433
|
-
const validAfter = "0";
|
|
434
|
-
const validBefore = String(nowSec + 10 * 60);
|
|
435
|
-
const nonce = randomBytes32Hex();
|
|
436
|
-
const valueAtomic = options?.valueOverrideAtomic ?? paymentRequirements.maxAmountRequired;
|
|
437
|
-
const authorization = {
|
|
438
|
-
from: fromAddress,
|
|
439
|
-
to: paymentRequirements.payTo,
|
|
440
|
-
value: valueAtomic,
|
|
441
|
-
validAfter,
|
|
442
|
-
validBefore,
|
|
443
|
-
nonce
|
|
444
|
-
};
|
|
445
|
-
const signature = await signAuthorizationWithProvider(
|
|
446
|
-
provider,
|
|
447
|
-
fromAddress,
|
|
448
|
-
authorization,
|
|
449
|
-
paymentRequirements
|
|
450
|
-
);
|
|
451
|
-
const paymentHeaderObject = {
|
|
452
|
-
x402Version: 1,
|
|
453
|
-
scheme: paymentRequirements.scheme,
|
|
454
|
-
network: paymentRequirements.network,
|
|
455
|
-
payload: {
|
|
456
|
-
signature,
|
|
457
|
-
authorization
|
|
458
|
-
}
|
|
459
|
-
};
|
|
460
|
-
const paymentHeader = encodeJsonToBase64(paymentHeaderObject);
|
|
461
|
-
const settleUrl = joinUrl(facilitatorUrl, "/settle");
|
|
462
|
-
const settleRes = await fetch(settleUrl, {
|
|
463
|
-
method: "POST",
|
|
464
|
-
headers: {
|
|
465
|
-
"Content-Type": "application/json",
|
|
466
|
-
...projectKey ? { "X-Project-Key": projectKey } : {}
|
|
467
|
-
},
|
|
468
|
-
body: JSON.stringify({
|
|
469
|
-
x402Version: 1,
|
|
470
|
-
paymentHeader,
|
|
471
|
-
paymentRequirements
|
|
472
|
-
})
|
|
473
|
-
});
|
|
474
|
-
if (!settleRes.ok) {
|
|
475
|
-
const text = await settleRes.text().catch((err) => {
|
|
476
|
-
console.error("[x402] Failed to read settle response text:", err);
|
|
477
|
-
return "";
|
|
478
|
-
});
|
|
479
|
-
throw new Error(
|
|
480
|
-
`Facilitator /settle failed with HTTP ${settleRes.status}: ${text}`
|
|
481
|
-
);
|
|
482
|
-
}
|
|
483
|
-
const settleJson = await settleRes.json();
|
|
484
|
-
if (!settleJson.success) {
|
|
485
|
-
throw new Error(
|
|
486
|
-
`Facilitator /settle returned error: ${settleJson.error ?? "unknown error"}`
|
|
487
|
-
);
|
|
488
|
-
}
|
|
489
|
-
const txHash = settleJson.txHash ?? void 0;
|
|
490
|
-
const retryHeaders = {
|
|
491
|
-
...headers,
|
|
492
|
-
"X-PAYMENT": paymentHeader
|
|
493
|
-
};
|
|
494
|
-
const retryRes = await fetch(initialUrl, {
|
|
495
|
-
method,
|
|
496
|
-
headers: retryHeaders,
|
|
497
|
-
body
|
|
498
|
-
});
|
|
499
|
-
if (!retryRes.ok) {
|
|
500
|
-
const text = await retryRes.text().catch((err) => {
|
|
501
|
-
console.error("[x402] Failed to read retry response text:", err);
|
|
502
|
-
return "";
|
|
503
|
-
});
|
|
504
|
-
throw new Error(
|
|
505
|
-
`Protected request with X-PAYMENT failed: HTTP ${retryRes.status} ${text}`
|
|
506
|
-
);
|
|
507
|
-
}
|
|
508
|
-
const finalJson = await retryRes.json();
|
|
509
|
-
return {
|
|
510
|
-
response: finalJson,
|
|
511
|
-
txHash,
|
|
512
|
-
paymentHeader,
|
|
513
|
-
paymentRequirements
|
|
514
|
-
};
|
|
515
|
-
}
|
|
516
|
-
};
|
|
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
|
-
}
|
|
1
|
+
import {
|
|
2
|
+
useEthersWallet,
|
|
3
|
+
useMantleX402
|
|
4
|
+
} from "./chunk-23QNUJIB.js";
|
|
5
|
+
import {
|
|
6
|
+
createMantleClient,
|
|
7
|
+
createPaymentClient
|
|
8
|
+
} from "./chunk-E46A7I6B.js";
|
|
9
|
+
import "./chunk-WO2MYZXT.js";
|
|
10
|
+
import {
|
|
11
|
+
createPaymentMiddleware,
|
|
12
|
+
mantlePaywall
|
|
13
|
+
} from "./chunk-PPVS3X5Z.js";
|
|
14
|
+
import "./chunk-U73CZU3X.js";
|
|
15
|
+
import {
|
|
16
|
+
MANTLE_DEFAULTS
|
|
17
|
+
} from "./chunk-HEZZ74SI.js";
|
|
568
18
|
export {
|
|
569
19
|
MANTLE_DEFAULTS,
|
|
570
20
|
createMantleClient,
|
|
571
21
|
createPaymentClient,
|
|
572
22
|
createPaymentMiddleware,
|
|
573
23
|
mantlePaywall,
|
|
24
|
+
useEthersWallet,
|
|
574
25
|
useMantleX402
|
|
575
26
|
};
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import { NextRequest, NextResponse } from 'next/server';
|
|
2
|
+
import { M as MinimalPaywallOptions } from './types-CqQ6OgRi.js';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Next.js App Router route handler type.
|
|
6
|
+
*/
|
|
7
|
+
type NextJSHandler<T = any> = (req: NextRequest) => Promise<NextResponse<T>>;
|
|
8
|
+
/**
|
|
9
|
+
* Wrapper function that adds x402 payment verification to Next.js route handler.
|
|
10
|
+
*/
|
|
11
|
+
type NextJSPaywallWrapper = <T>(handler: NextJSHandler<T>) => NextJSHandler<T>;
|
|
12
|
+
/**
|
|
13
|
+
* Create Next.js App Router middleware for x402 payment verification.
|
|
14
|
+
* Uses Mantle mainnet defaults (USDC, exact scheme, etc.).
|
|
15
|
+
*
|
|
16
|
+
* @example
|
|
17
|
+
* ```typescript
|
|
18
|
+
* // app/api/generate-image/route.ts
|
|
19
|
+
* import { mantlePaywall } from '@puga-labs/x402-mantle-sdk/server/nextjs'
|
|
20
|
+
*
|
|
21
|
+
* const pay = mantlePaywall({
|
|
22
|
+
* priceUsd: 0.01,
|
|
23
|
+
* payTo: process.env.PAY_TO as `0x${string}`,
|
|
24
|
+
* });
|
|
25
|
+
*
|
|
26
|
+
* export const POST = pay(async (req: NextRequest) => {
|
|
27
|
+
* const { prompt } = await req.json();
|
|
28
|
+
* // Your handler code here
|
|
29
|
+
* return NextResponse.json({ success: true });
|
|
30
|
+
* });
|
|
31
|
+
* ```
|
|
32
|
+
*
|
|
33
|
+
* @param opts - Minimal configuration (price, payTo, optional facilitator/telemetry).
|
|
34
|
+
* @returns Function that wraps Next.js route handlers with payment verification.
|
|
35
|
+
*/
|
|
36
|
+
declare function mantlePaywall(opts: MinimalPaywallOptions): NextJSPaywallWrapper;
|
|
37
|
+
|
|
38
|
+
type nextjs_NextJSHandler<T = any> = NextJSHandler<T>;
|
|
39
|
+
type nextjs_NextJSPaywallWrapper = NextJSPaywallWrapper;
|
|
40
|
+
declare const nextjs_mantlePaywall: typeof mantlePaywall;
|
|
41
|
+
declare namespace nextjs {
|
|
42
|
+
export { type nextjs_NextJSHandler as NextJSHandler, type nextjs_NextJSPaywallWrapper as NextJSPaywallWrapper, nextjs_mantlePaywall as mantlePaywall };
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export { type NextJSHandler as N, type NextJSPaywallWrapper as a, mantlePaywall as m, nextjs as n };
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import { NextRequest, NextResponse } from 'next/server';
|
|
2
|
+
import { M as MinimalPaywallOptions } from './types-xkNm0uzE.cjs';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Next.js App Router route handler type.
|
|
6
|
+
*/
|
|
7
|
+
type NextJSHandler<T = any> = (req: NextRequest) => Promise<NextResponse<T>>;
|
|
8
|
+
/**
|
|
9
|
+
* Wrapper function that adds x402 payment verification to Next.js route handler.
|
|
10
|
+
*/
|
|
11
|
+
type NextJSPaywallWrapper = <T>(handler: NextJSHandler<T>) => NextJSHandler<T>;
|
|
12
|
+
/**
|
|
13
|
+
* Create Next.js App Router middleware for x402 payment verification.
|
|
14
|
+
* Uses Mantle mainnet defaults (USDC, exact scheme, etc.).
|
|
15
|
+
*
|
|
16
|
+
* @example
|
|
17
|
+
* ```typescript
|
|
18
|
+
* // app/api/generate-image/route.ts
|
|
19
|
+
* import { mantlePaywall } from '@puga-labs/x402-mantle-sdk/server/nextjs'
|
|
20
|
+
*
|
|
21
|
+
* const pay = mantlePaywall({
|
|
22
|
+
* priceUsd: 0.01,
|
|
23
|
+
* payTo: process.env.PAY_TO as `0x${string}`,
|
|
24
|
+
* });
|
|
25
|
+
*
|
|
26
|
+
* export const POST = pay(async (req: NextRequest) => {
|
|
27
|
+
* const { prompt } = await req.json();
|
|
28
|
+
* // Your handler code here
|
|
29
|
+
* return NextResponse.json({ success: true });
|
|
30
|
+
* });
|
|
31
|
+
* ```
|
|
32
|
+
*
|
|
33
|
+
* @param opts - Minimal configuration (price, payTo, optional facilitator/telemetry).
|
|
34
|
+
* @returns Function that wraps Next.js route handlers with payment verification.
|
|
35
|
+
*/
|
|
36
|
+
declare function mantlePaywall(opts: MinimalPaywallOptions): NextJSPaywallWrapper;
|
|
37
|
+
|
|
38
|
+
type nextjs_NextJSHandler<T = any> = NextJSHandler<T>;
|
|
39
|
+
type nextjs_NextJSPaywallWrapper = NextJSPaywallWrapper;
|
|
40
|
+
declare const nextjs_mantlePaywall: typeof mantlePaywall;
|
|
41
|
+
declare namespace nextjs {
|
|
42
|
+
export { type nextjs_NextJSHandler as NextJSHandler, type nextjs_NextJSPaywallWrapper as NextJSPaywallWrapper, nextjs_mantlePaywall as mantlePaywall };
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export { type NextJSHandler as N, type NextJSPaywallWrapper as a, mantlePaywall as m, nextjs as n };
|