@puga-labs/x402-mantle-sdk 0.2.0 → 0.3.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/chunk-CTI5CRDY.js +274 -0
- package/dist/chunk-DA6ZBXNO.js +275 -0
- package/dist/chunk-FD4HG7KR.js +135 -0
- package/dist/chunk-GWVWPS3R.js +277 -0
- package/dist/chunk-HTZ3QFY4.js +135 -0
- package/dist/chunk-MQALBRGV.js +135 -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-WELDWRDX.js +307 -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-C7aY8u5b.d.cts +77 -0
- package/dist/constants-C7aY8u5b.d.ts +77 -0
- package/dist/constants-CVFF0ray.d.ts +17 -0
- package/dist/constants-DzCGK0Q3.d.cts +17 -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/index.cjs +244 -43
- package/dist/index.d.cts +8 -164
- package/dist/index.d.ts +8 -164
- package/dist/index.js +21 -485
- package/dist/react.cjs +453 -0
- package/dist/react.d.cts +90 -0
- package/dist/react.d.ts +90 -0
- package/dist/react.js +10 -0
- package/dist/server.cjs +292 -0
- package/dist/server.d.cts +116 -0
- package/dist/server.d.ts +116 -0
- package/dist/server.js +12 -0
- package/dist/types-2zqbJvcz.d.cts +63 -0
- package/dist/types-2zqbJvcz.d.ts +63 -0
- package/package.json +37 -3
package/dist/index.d.ts
CHANGED
|
@@ -1,164 +1,8 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
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
|
-
facilitatorUrl?: string;
|
|
68
|
-
paymentRequirements?: PaymentRequirements;
|
|
69
|
-
}
|
|
70
|
-
/** Config for optional telemetry (billing/analytics). */
|
|
71
|
-
interface TelemetryConfig {
|
|
72
|
-
/** Project key from nosubs.ai dashboard. */
|
|
73
|
-
projectKey: string;
|
|
74
|
-
/**
|
|
75
|
-
* Telemetry endpoint URL.
|
|
76
|
-
* If not specified, uses DEFAULT_TELEMETRY_ENDPOINT (see server/constants.ts).
|
|
77
|
-
* If both are undefined, telemetry is not sent.
|
|
78
|
-
*/
|
|
79
|
-
endpoint?: string;
|
|
80
|
-
}
|
|
81
|
-
/** Telemetry event payload for payment_verified. */
|
|
82
|
-
interface TelemetryEvent {
|
|
83
|
-
event: "payment_verified";
|
|
84
|
-
ts: number;
|
|
85
|
-
projectKey: string;
|
|
86
|
-
network: string;
|
|
87
|
-
buyer: string;
|
|
88
|
-
payTo: string;
|
|
89
|
-
amountAtomic: string;
|
|
90
|
-
asset: string;
|
|
91
|
-
decimals: number;
|
|
92
|
-
nonce: string;
|
|
93
|
-
route: string;
|
|
94
|
-
facilitatorType: "hosted" | "self-hosted";
|
|
95
|
-
facilitatorUrl?: string;
|
|
96
|
-
facilitatorAddress?: string;
|
|
97
|
-
txHash?: string;
|
|
98
|
-
priceUsd?: string;
|
|
99
|
-
}
|
|
100
|
-
/** Config for createPaymentMiddleware. */
|
|
101
|
-
interface PaymentMiddlewareConfig {
|
|
102
|
-
/** Base URL of facilitator, e.g. https://facilitator.nosubs.ai */
|
|
103
|
-
facilitatorUrl: string;
|
|
104
|
-
/** Recipient address (developer). */
|
|
105
|
-
receiverAddress: string;
|
|
106
|
-
/** Map of protected routes and their pricing. */
|
|
107
|
-
routes: RoutesConfig;
|
|
108
|
-
/**
|
|
109
|
-
* Optional hook called whenever a payment is successfully settled.
|
|
110
|
-
* You can use this to push logs into your DB / analytics pipeline.
|
|
111
|
-
*/
|
|
112
|
-
onPaymentSettled?: (entry: PaymentLogEntry) => void;
|
|
113
|
-
/** Optional: Send usage telemetry for billing/analytics. */
|
|
114
|
-
telemetry?: TelemetryConfig;
|
|
115
|
-
}
|
|
116
|
-
|
|
117
|
-
declare function createPaymentMiddleware(config: PaymentMiddlewareConfig): (req: Request, res: Response, next: NextFunction) => Promise<void>;
|
|
118
|
-
|
|
119
|
-
/** Config for the client-side payment helper. */
|
|
120
|
-
interface PaymentClientConfig {
|
|
121
|
-
/** Base URL of your protected resource server. */
|
|
122
|
-
resourceUrl: string;
|
|
123
|
-
/** Facilitator URL (hosted or self-hosted). */
|
|
124
|
-
facilitatorUrl: string;
|
|
125
|
-
/** EIP-1193 provider (window.ethereum) or similar. */
|
|
126
|
-
provider: unknown;
|
|
127
|
-
/** Optional user address override; otherwise derived from provider. */
|
|
128
|
-
userAddress?: string;
|
|
129
|
-
/** Optional: Project key for hosted facilitator billing. */
|
|
130
|
-
projectKey?: string;
|
|
131
|
-
}
|
|
132
|
-
/** Result of a callWithPayment() client operation. */
|
|
133
|
-
interface CallWithPaymentResult<TResponseBody = unknown> {
|
|
134
|
-
response: TResponseBody;
|
|
135
|
-
txHash?: string;
|
|
136
|
-
paymentHeader: PaymentHeaderBase64;
|
|
137
|
-
paymentRequirements: PaymentRequirements;
|
|
138
|
-
}
|
|
139
|
-
/** Shape of the client instance returned by createPaymentClient. */
|
|
140
|
-
interface PaymentClient {
|
|
141
|
-
callWithPayment<TBody = unknown, TResp = unknown>(path: string, options?: {
|
|
142
|
-
method?: "GET" | "POST" | "PUT" | "DELETE";
|
|
143
|
-
body?: TBody;
|
|
144
|
-
headers?: Record<string, string>;
|
|
145
|
-
/**
|
|
146
|
-
* Optional override if you want to send less than maxAmountRequired.
|
|
147
|
-
* In most cases you won't need this and will just pay maxAmountRequired.
|
|
148
|
-
*/
|
|
149
|
-
valueOverrideAtomic?: string;
|
|
150
|
-
}): Promise<CallWithPaymentResult<TResp>>;
|
|
151
|
-
}
|
|
152
|
-
|
|
153
|
-
/**
|
|
154
|
-
* Creates a high-level payment client that:
|
|
155
|
-
* - makes an initial request
|
|
156
|
-
* - if it receives 402 + paymentRequirements, builds & signs an authorization
|
|
157
|
-
* - calls facilitator /settle
|
|
158
|
-
* - retries the original request with X-PAYMENT header
|
|
159
|
-
*
|
|
160
|
-
* This logic is x402 and tailored for Mantle + USDC.
|
|
161
|
-
*/
|
|
162
|
-
declare function createPaymentClient(config: PaymentClientConfig): PaymentClient;
|
|
163
|
-
|
|
164
|
-
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, type TelemetryConfig, type TelemetryEvent, createPaymentClient, createPaymentMiddleware };
|
|
1
|
+
export { A as AssetConfig, a as Authorization, E as EIP1193Provider, N as NetworkId, d as PaymentHeaderBase64, c as PaymentHeaderObject, b as PaymentHeaderPayload, P as PaymentRequirements } from './types-2zqbJvcz.js';
|
|
2
|
+
export { M as MANTLE_DEFAULTS } from './constants-CVFF0ray.js';
|
|
3
|
+
export { MantleMiddleware, MinimalPaywallOptions, PaymentLogEntry, PaymentMiddlewareConfig, RouteKey, RoutePricingConfig, RoutesConfig, TelemetryConfig, TelemetryEvent, createPaymentMiddleware, mantlePaywall } from './server.js';
|
|
4
|
+
export { C as CallWithPaymentResult, M as MantleClient, a as MantleClientConfig, b as PaymentClient, P as PaymentClientConfig, c as createMantleClient } from './createMantleClient-DVFkbBfS.js';
|
|
5
|
+
export { createPaymentClient } from './client.js';
|
|
6
|
+
export { UseEthersWalletOptions, UseEthersWalletReturn, UseMantleX402Options, useEthersWallet, useMantleX402 } from './react.js';
|
|
7
|
+
import 'express';
|
|
8
|
+
import 'ethers';
|
package/dist/index.js
CHANGED
|
@@ -1,488 +1,24 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
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/constants.ts
|
|
42
|
-
var DEFAULT_TELEMETRY_ENDPOINT = void 0;
|
|
43
|
-
|
|
44
|
-
// src/server/telemetry.ts
|
|
45
|
-
function createTelemetryEvent(entry, config) {
|
|
46
|
-
const assetConfig = getDefaultAssetForNetwork(entry.network);
|
|
47
|
-
return {
|
|
48
|
-
event: "payment_verified",
|
|
49
|
-
ts: entry.timestamp,
|
|
50
|
-
projectKey: config.projectKey,
|
|
51
|
-
network: entry.network,
|
|
52
|
-
buyer: entry.from,
|
|
53
|
-
payTo: entry.to,
|
|
54
|
-
amountAtomic: entry.valueAtomic,
|
|
55
|
-
asset: entry.asset,
|
|
56
|
-
decimals: assetConfig.decimals,
|
|
57
|
-
nonce: entry.id,
|
|
58
|
-
route: entry.route ?? "unknown",
|
|
59
|
-
// Facilitator metadata
|
|
60
|
-
facilitatorType: "hosted",
|
|
61
|
-
// SDK always uses hosted mode
|
|
62
|
-
facilitatorUrl: entry.facilitatorUrl,
|
|
63
|
-
// From PaymentLogEntry
|
|
64
|
-
// facilitatorAddress is undefined for SDK (not available)
|
|
65
|
-
// Optional metadata
|
|
66
|
-
txHash: entry.txHash,
|
|
67
|
-
priceUsd: entry.paymentRequirements?.price
|
|
68
|
-
};
|
|
69
|
-
}
|
|
70
|
-
async function sendTelemetry(event, endpoint) {
|
|
71
|
-
const targetEndpoint = endpoint ?? DEFAULT_TELEMETRY_ENDPOINT;
|
|
72
|
-
if (!targetEndpoint) {
|
|
73
|
-
return;
|
|
74
|
-
}
|
|
75
|
-
try {
|
|
76
|
-
const response = await fetch(targetEndpoint, {
|
|
77
|
-
method: "POST",
|
|
78
|
-
headers: {
|
|
79
|
-
"Content-Type": "application/json",
|
|
80
|
-
"Authorization": `Bearer ${event.projectKey}`
|
|
81
|
-
},
|
|
82
|
-
body: JSON.stringify(event)
|
|
83
|
-
});
|
|
84
|
-
if (!response.ok) {
|
|
85
|
-
console.warn(
|
|
86
|
-
`[x402-telemetry] Failed to send event: HTTP ${response.status}`
|
|
87
|
-
);
|
|
88
|
-
}
|
|
89
|
-
} catch (err) {
|
|
90
|
-
console.error("[x402-telemetry] Error sending telemetry:", err);
|
|
91
|
-
}
|
|
92
|
-
}
|
|
93
|
-
|
|
94
|
-
// src/server/paymentMiddleware.ts
|
|
95
|
-
function getRouteKey(req) {
|
|
96
|
-
const method = (req.method || "GET").toUpperCase();
|
|
97
|
-
const path = req.path || "/";
|
|
98
|
-
return `${method} ${path}`;
|
|
99
|
-
}
|
|
100
|
-
function decodePaymentHeader(paymentHeaderBase64) {
|
|
101
|
-
try {
|
|
102
|
-
if (typeof Buffer !== "undefined") {
|
|
103
|
-
const json = Buffer.from(paymentHeaderBase64, "base64").toString("utf8");
|
|
104
|
-
return JSON.parse(json);
|
|
105
|
-
}
|
|
106
|
-
if (typeof atob === "function") {
|
|
107
|
-
const json = atob(paymentHeaderBase64);
|
|
108
|
-
return JSON.parse(json);
|
|
109
|
-
}
|
|
110
|
-
throw new Error("No base64 decoding available in this environment");
|
|
111
|
-
} catch (err) {
|
|
112
|
-
const msg = err instanceof Error ? err.message : "Unknown error";
|
|
113
|
-
throw new Error(`Failed to decode paymentHeader: ${msg}`);
|
|
114
|
-
}
|
|
115
|
-
}
|
|
116
|
-
function createPaymentMiddleware(config) {
|
|
117
|
-
const { facilitatorUrl, receiverAddress, routes, onPaymentSettled, telemetry } = config;
|
|
118
|
-
if (!facilitatorUrl) {
|
|
119
|
-
throw new Error("facilitatorUrl is required");
|
|
120
|
-
}
|
|
121
|
-
if (!receiverAddress) {
|
|
122
|
-
throw new Error("receiverAddress is required");
|
|
123
|
-
}
|
|
124
|
-
if (!routes || Object.keys(routes).length === 0) {
|
|
125
|
-
throw new Error("routes config must not be empty");
|
|
126
|
-
}
|
|
127
|
-
return async function paymentMiddleware(req, res, next) {
|
|
128
|
-
const routeKey = getRouteKey(req);
|
|
129
|
-
const routeConfig = routes[routeKey];
|
|
130
|
-
if (!routeConfig) {
|
|
131
|
-
next();
|
|
132
|
-
return;
|
|
133
|
-
}
|
|
134
|
-
const { priceUsdCents, network } = routeConfig;
|
|
135
|
-
const assetConfig = getDefaultAssetForNetwork(network);
|
|
136
|
-
const maxAmountRequiredBigInt = usdCentsToAtomic(
|
|
137
|
-
priceUsdCents,
|
|
138
|
-
assetConfig.decimals
|
|
139
|
-
);
|
|
140
|
-
const paymentRequirements = {
|
|
141
|
-
scheme: "exact",
|
|
142
|
-
network,
|
|
143
|
-
asset: assetConfig.address,
|
|
144
|
-
maxAmountRequired: maxAmountRequiredBigInt.toString(),
|
|
145
|
-
payTo: receiverAddress,
|
|
146
|
-
price: `$${(priceUsdCents / 100).toFixed(2)}`,
|
|
147
|
-
currency: "USD"
|
|
148
|
-
};
|
|
149
|
-
const paymentHeader = req.header("X-PAYMENT") ?? req.header("x-payment");
|
|
150
|
-
if (!paymentHeader) {
|
|
151
|
-
res.status(402).json({
|
|
152
|
-
error: "Payment Required",
|
|
153
|
-
paymentRequirements,
|
|
154
|
-
paymentHeader: null
|
|
155
|
-
});
|
|
156
|
-
return;
|
|
157
|
-
}
|
|
158
|
-
try {
|
|
159
|
-
const verifyUrl = `${facilitatorUrl.replace(/\/+$/, "")}/verify`;
|
|
160
|
-
const verifyRes = await fetch(verifyUrl, {
|
|
161
|
-
method: "POST",
|
|
162
|
-
headers: {
|
|
163
|
-
"Content-Type": "application/json"
|
|
164
|
-
},
|
|
165
|
-
body: JSON.stringify({
|
|
166
|
-
x402Version: 1,
|
|
167
|
-
paymentHeader,
|
|
168
|
-
paymentRequirements
|
|
169
|
-
})
|
|
170
|
-
});
|
|
171
|
-
if (!verifyRes.ok) {
|
|
172
|
-
const text = await verifyRes.text().catch(() => "");
|
|
173
|
-
console.error(
|
|
174
|
-
"[x402-mantle-sdk] Facilitator /verify returned non-OK:",
|
|
175
|
-
verifyRes.status,
|
|
176
|
-
text
|
|
177
|
-
);
|
|
178
|
-
res.status(500).json({
|
|
179
|
-
error: "Payment verification error",
|
|
180
|
-
details: `Facilitator responded with HTTP ${verifyRes.status}`
|
|
181
|
-
});
|
|
182
|
-
return;
|
|
183
|
-
}
|
|
184
|
-
const verifyJson = await verifyRes.json();
|
|
185
|
-
if (!verifyJson.isValid) {
|
|
186
|
-
res.status(402).json({
|
|
187
|
-
error: "Payment verification failed",
|
|
188
|
-
invalidReason: verifyJson.invalidReason ?? null,
|
|
189
|
-
paymentRequirements,
|
|
190
|
-
paymentHeader: null
|
|
191
|
-
});
|
|
192
|
-
return;
|
|
193
|
-
}
|
|
194
|
-
if (onPaymentSettled) {
|
|
195
|
-
try {
|
|
196
|
-
const headerObj = decodePaymentHeader(paymentHeader);
|
|
197
|
-
const { authorization } = headerObj.payload;
|
|
198
|
-
const logEntry = {
|
|
199
|
-
id: authorization.nonce,
|
|
200
|
-
from: authorization.from,
|
|
201
|
-
to: authorization.to,
|
|
202
|
-
valueAtomic: authorization.value,
|
|
203
|
-
network,
|
|
204
|
-
asset: assetConfig.address,
|
|
205
|
-
route: routeKey,
|
|
206
|
-
timestamp: Date.now(),
|
|
207
|
-
facilitatorUrl,
|
|
208
|
-
// Pass from config closure
|
|
209
|
-
paymentRequirements
|
|
210
|
-
};
|
|
211
|
-
onPaymentSettled(logEntry);
|
|
212
|
-
if (telemetry) {
|
|
213
|
-
const event = createTelemetryEvent(logEntry, telemetry);
|
|
214
|
-
sendTelemetry(event, telemetry.endpoint).catch(
|
|
215
|
-
(err) => console.error("[x402-telemetry] Async send failed:", err)
|
|
216
|
-
);
|
|
217
|
-
}
|
|
218
|
-
} catch (err) {
|
|
219
|
-
console.error(
|
|
220
|
-
"[x402-mantle-sdk] Error calling onPaymentSettled hook:",
|
|
221
|
-
err
|
|
222
|
-
);
|
|
223
|
-
}
|
|
224
|
-
}
|
|
225
|
-
next();
|
|
226
|
-
return;
|
|
227
|
-
} catch (err) {
|
|
228
|
-
console.error(
|
|
229
|
-
"[x402-mantle-sdk] Error while calling facilitator /verify:",
|
|
230
|
-
err
|
|
231
|
-
);
|
|
232
|
-
const message = err instanceof Error ? err.message : "Unknown verification error";
|
|
233
|
-
res.status(500).json({
|
|
234
|
-
error: "Payment verification error",
|
|
235
|
-
details: message
|
|
236
|
-
});
|
|
237
|
-
return;
|
|
238
|
-
}
|
|
239
|
-
};
|
|
240
|
-
}
|
|
241
|
-
|
|
242
|
-
// src/shared/utils.ts
|
|
243
|
-
function encodeJsonToBase64(value) {
|
|
244
|
-
const json = JSON.stringify(value);
|
|
245
|
-
if (typeof btoa === "function") {
|
|
246
|
-
const bytes = new TextEncoder().encode(json);
|
|
247
|
-
const binString = Array.from(
|
|
248
|
-
bytes,
|
|
249
|
-
(byte) => String.fromCodePoint(byte)
|
|
250
|
-
).join("");
|
|
251
|
-
return btoa(binString);
|
|
252
|
-
}
|
|
253
|
-
if (typeof globalThis.Buffer !== "undefined") {
|
|
254
|
-
return globalThis.Buffer.from(json, "utf8").toString("base64");
|
|
255
|
-
}
|
|
256
|
-
throw new Error("No base64 implementation found in this environment");
|
|
257
|
-
}
|
|
258
|
-
function randomBytes32Hex() {
|
|
259
|
-
if (typeof crypto !== "undefined" && "getRandomValues" in crypto) {
|
|
260
|
-
const arr = new Uint8Array(32);
|
|
261
|
-
crypto.getRandomValues(arr);
|
|
262
|
-
return "0x" + Array.from(arr).map((b) => b.toString(16).padStart(2, "0")).join("");
|
|
263
|
-
}
|
|
264
|
-
try {
|
|
265
|
-
const nodeCrypto = __require("crypto");
|
|
266
|
-
const buf = nodeCrypto.randomBytes(32);
|
|
267
|
-
return "0x" + buf.toString("hex");
|
|
268
|
-
} catch {
|
|
269
|
-
throw new Error(
|
|
270
|
-
"No cryptographically secure random number generator found. This environment does not support crypto.getRandomValues or Node.js crypto module."
|
|
271
|
-
);
|
|
272
|
-
}
|
|
273
|
-
}
|
|
274
|
-
|
|
275
|
-
// src/client/paymentClient.ts
|
|
276
|
-
function joinUrl(base, path) {
|
|
277
|
-
const normalizedBase = base.replace(/\/+$/, "");
|
|
278
|
-
const normalizedPath = path.startsWith("/") ? path : `/${path}`;
|
|
279
|
-
return `${normalizedBase}${normalizedPath}`;
|
|
280
|
-
}
|
|
281
|
-
async function getUserAddressFromProvider(provider) {
|
|
282
|
-
const p = provider;
|
|
283
|
-
if (!p || typeof p.request !== "function") {
|
|
284
|
-
throw new Error("provider must implement EIP-1193 request()");
|
|
285
|
-
}
|
|
286
|
-
const accounts = await p.request({
|
|
287
|
-
method: "eth_requestAccounts"
|
|
288
|
-
});
|
|
289
|
-
if (!accounts || accounts.length === 0) {
|
|
290
|
-
throw new Error("No accounts returned from provider");
|
|
291
|
-
}
|
|
292
|
-
return accounts[0];
|
|
293
|
-
}
|
|
294
|
-
function buildTypedDataForAuthorization(authorization, paymentRequirements) {
|
|
295
|
-
const chainId = getChainIdForNetwork(paymentRequirements.network);
|
|
296
|
-
const verifyingContract = paymentRequirements.asset;
|
|
297
|
-
const domain = {
|
|
298
|
-
name: "USD Coin",
|
|
299
|
-
version: "2",
|
|
300
|
-
chainId,
|
|
301
|
-
verifyingContract
|
|
302
|
-
};
|
|
303
|
-
const types = {
|
|
304
|
-
TransferWithAuthorization: [
|
|
305
|
-
{ name: "from", type: "address" },
|
|
306
|
-
{ name: "to", type: "address" },
|
|
307
|
-
{ name: "value", type: "uint256" },
|
|
308
|
-
{ name: "validAfter", type: "uint256" },
|
|
309
|
-
{ name: "validBefore", type: "uint256" },
|
|
310
|
-
{ name: "nonce", type: "bytes32" }
|
|
311
|
-
]
|
|
312
|
-
};
|
|
313
|
-
return {
|
|
314
|
-
domain,
|
|
315
|
-
types,
|
|
316
|
-
primaryType: "TransferWithAuthorization",
|
|
317
|
-
message: authorization
|
|
318
|
-
};
|
|
319
|
-
}
|
|
320
|
-
async function signAuthorizationWithProvider(provider, address, authorization, paymentRequirements) {
|
|
321
|
-
const p = provider;
|
|
322
|
-
if (!p || typeof p.request !== "function") {
|
|
323
|
-
throw new Error("provider must implement EIP-1193 request()");
|
|
324
|
-
}
|
|
325
|
-
const typedData = buildTypedDataForAuthorization(
|
|
326
|
-
authorization,
|
|
327
|
-
paymentRequirements
|
|
328
|
-
);
|
|
329
|
-
const params = [address, JSON.stringify(typedData)];
|
|
330
|
-
const signature = await p.request({
|
|
331
|
-
method: "eth_signTypedData_v4",
|
|
332
|
-
params
|
|
333
|
-
});
|
|
334
|
-
if (typeof signature !== "string" || !signature.startsWith("0x")) {
|
|
335
|
-
throw new Error("Invalid signature returned from provider");
|
|
336
|
-
}
|
|
337
|
-
return signature;
|
|
338
|
-
}
|
|
339
|
-
function createPaymentClient(config) {
|
|
340
|
-
const {
|
|
341
|
-
resourceUrl,
|
|
342
|
-
facilitatorUrl,
|
|
343
|
-
provider,
|
|
344
|
-
userAddress: userAddressOverride,
|
|
345
|
-
projectKey
|
|
346
|
-
} = config;
|
|
347
|
-
if (!resourceUrl) {
|
|
348
|
-
throw new Error("resourceUrl is required");
|
|
349
|
-
}
|
|
350
|
-
if (!facilitatorUrl) {
|
|
351
|
-
throw new Error("facilitatorUrl is required");
|
|
352
|
-
}
|
|
353
|
-
if (!provider) {
|
|
354
|
-
throw new Error("provider is required (e.g. window.ethereum)");
|
|
355
|
-
}
|
|
356
|
-
return {
|
|
357
|
-
async callWithPayment(path, options) {
|
|
358
|
-
const method = options?.method ?? "GET";
|
|
359
|
-
const headers = {
|
|
360
|
-
...options?.headers ?? {}
|
|
361
|
-
};
|
|
362
|
-
let body;
|
|
363
|
-
if (options?.body !== void 0) {
|
|
364
|
-
headers["Content-Type"] = headers["Content-Type"] ?? "application/json";
|
|
365
|
-
body = JSON.stringify(options.body);
|
|
366
|
-
}
|
|
367
|
-
const initialUrl = joinUrl(resourceUrl, path);
|
|
368
|
-
const initialRes = await fetch(initialUrl, {
|
|
369
|
-
method,
|
|
370
|
-
headers,
|
|
371
|
-
body
|
|
372
|
-
});
|
|
373
|
-
if (initialRes.status !== 402) {
|
|
374
|
-
const json = await initialRes.json().catch((err) => {
|
|
375
|
-
console.error("[x402] Failed to parse initial response JSON:", err);
|
|
376
|
-
return null;
|
|
377
|
-
});
|
|
378
|
-
return {
|
|
379
|
-
response: json,
|
|
380
|
-
paymentHeader: "",
|
|
381
|
-
paymentRequirements: {
|
|
382
|
-
scheme: "exact",
|
|
383
|
-
network: "mantle-mainnet",
|
|
384
|
-
asset: "",
|
|
385
|
-
maxAmountRequired: "0",
|
|
386
|
-
payTo: ""
|
|
387
|
-
},
|
|
388
|
-
txHash: void 0
|
|
389
|
-
};
|
|
390
|
-
}
|
|
391
|
-
const bodyJson = await initialRes.json();
|
|
392
|
-
const paymentRequirements = bodyJson.paymentRequirements;
|
|
393
|
-
if (!paymentRequirements) {
|
|
394
|
-
throw new Error(
|
|
395
|
-
"402 response did not include paymentRequirements field"
|
|
396
|
-
);
|
|
397
|
-
}
|
|
398
|
-
const fromAddress = userAddressOverride ?? await getUserAddressFromProvider(provider);
|
|
399
|
-
const nowSec = Math.floor(Date.now() / 1e3);
|
|
400
|
-
const validAfter = "0";
|
|
401
|
-
const validBefore = String(nowSec + 10 * 60);
|
|
402
|
-
const nonce = randomBytes32Hex();
|
|
403
|
-
const valueAtomic = options?.valueOverrideAtomic ?? paymentRequirements.maxAmountRequired;
|
|
404
|
-
const authorization = {
|
|
405
|
-
from: fromAddress,
|
|
406
|
-
to: paymentRequirements.payTo,
|
|
407
|
-
value: valueAtomic,
|
|
408
|
-
validAfter,
|
|
409
|
-
validBefore,
|
|
410
|
-
nonce
|
|
411
|
-
};
|
|
412
|
-
const signature = await signAuthorizationWithProvider(
|
|
413
|
-
provider,
|
|
414
|
-
fromAddress,
|
|
415
|
-
authorization,
|
|
416
|
-
paymentRequirements
|
|
417
|
-
);
|
|
418
|
-
const paymentHeaderObject = {
|
|
419
|
-
x402Version: 1,
|
|
420
|
-
scheme: paymentRequirements.scheme,
|
|
421
|
-
network: paymentRequirements.network,
|
|
422
|
-
payload: {
|
|
423
|
-
signature,
|
|
424
|
-
authorization
|
|
425
|
-
}
|
|
426
|
-
};
|
|
427
|
-
const paymentHeader = encodeJsonToBase64(paymentHeaderObject);
|
|
428
|
-
const settleUrl = joinUrl(facilitatorUrl, "/settle");
|
|
429
|
-
const settleRes = await fetch(settleUrl, {
|
|
430
|
-
method: "POST",
|
|
431
|
-
headers: {
|
|
432
|
-
"Content-Type": "application/json",
|
|
433
|
-
...projectKey ? { "X-Project-Key": projectKey } : {}
|
|
434
|
-
},
|
|
435
|
-
body: JSON.stringify({
|
|
436
|
-
x402Version: 1,
|
|
437
|
-
paymentHeader,
|
|
438
|
-
paymentRequirements
|
|
439
|
-
})
|
|
440
|
-
});
|
|
441
|
-
if (!settleRes.ok) {
|
|
442
|
-
const text = await settleRes.text().catch((err) => {
|
|
443
|
-
console.error("[x402] Failed to read settle response text:", err);
|
|
444
|
-
return "";
|
|
445
|
-
});
|
|
446
|
-
throw new Error(
|
|
447
|
-
`Facilitator /settle failed with HTTP ${settleRes.status}: ${text}`
|
|
448
|
-
);
|
|
449
|
-
}
|
|
450
|
-
const settleJson = await settleRes.json();
|
|
451
|
-
if (!settleJson.success) {
|
|
452
|
-
throw new Error(
|
|
453
|
-
`Facilitator /settle returned error: ${settleJson.error ?? "unknown error"}`
|
|
454
|
-
);
|
|
455
|
-
}
|
|
456
|
-
const txHash = settleJson.txHash ?? void 0;
|
|
457
|
-
const retryHeaders = {
|
|
458
|
-
...headers,
|
|
459
|
-
"X-PAYMENT": paymentHeader
|
|
460
|
-
};
|
|
461
|
-
const retryRes = await fetch(initialUrl, {
|
|
462
|
-
method,
|
|
463
|
-
headers: retryHeaders,
|
|
464
|
-
body
|
|
465
|
-
});
|
|
466
|
-
if (!retryRes.ok) {
|
|
467
|
-
const text = await retryRes.text().catch((err) => {
|
|
468
|
-
console.error("[x402] Failed to read retry response text:", err);
|
|
469
|
-
return "";
|
|
470
|
-
});
|
|
471
|
-
throw new Error(
|
|
472
|
-
`Protected request with X-PAYMENT failed: HTTP ${retryRes.status} ${text}`
|
|
473
|
-
);
|
|
474
|
-
}
|
|
475
|
-
const finalJson = await retryRes.json();
|
|
476
|
-
return {
|
|
477
|
-
response: finalJson,
|
|
478
|
-
txHash,
|
|
479
|
-
paymentHeader,
|
|
480
|
-
paymentRequirements
|
|
481
|
-
};
|
|
482
|
-
}
|
|
483
|
-
};
|
|
484
|
-
}
|
|
1
|
+
import {
|
|
2
|
+
useEthersWallet,
|
|
3
|
+
useMantleX402
|
|
4
|
+
} from "./chunk-T5DRYLNB.js";
|
|
5
|
+
import {
|
|
6
|
+
createMantleClient,
|
|
7
|
+
createPaymentClient
|
|
8
|
+
} from "./chunk-CTI5CRDY.js";
|
|
9
|
+
import {
|
|
10
|
+
createPaymentMiddleware,
|
|
11
|
+
mantlePaywall
|
|
12
|
+
} from "./chunk-Q6SPMEIW.js";
|
|
13
|
+
import {
|
|
14
|
+
MANTLE_DEFAULTS
|
|
15
|
+
} from "./chunk-XAQGMFSR.js";
|
|
485
16
|
export {
|
|
17
|
+
MANTLE_DEFAULTS,
|
|
18
|
+
createMantleClient,
|
|
486
19
|
createPaymentClient,
|
|
487
|
-
createPaymentMiddleware
|
|
20
|
+
createPaymentMiddleware,
|
|
21
|
+
mantlePaywall,
|
|
22
|
+
useEthersWallet,
|
|
23
|
+
useMantleX402
|
|
488
24
|
};
|