@puga-labs/x402-mantle-sdk 0.4.0 → 0.4.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/README.md CHANGED
@@ -264,10 +264,9 @@ Deno.serve(pay(async (req) => {
264
264
  |--------|------|----------|-------------|
265
265
  | `priceUsd` | `number` | Yes | Price in USD (e.g., `0.01` for 1 cent) |
266
266
  | `payTo` | `string` | Yes | Your wallet address to receive payments |
267
- | `facilitatorUrl` | `string` | No | Facilitator URL (default: localhost:8080) |
268
- | `projectKey` | `string` | No | Project key from dashboard (for hosted facilitator + analytics) |
269
- | `facilitatorSecret` | `string` | For self-hosted | Shared secret with your facilitator (required for self-hosted) |
270
- | `network` | `string` | No | Network ID (default: `mantle-mainnet`) |
267
+ | `projectKey` | `string` | For hosted | Project key from dashboard (for billing + analytics) |
268
+ | `facilitatorUrl` | `string` | For self-hosted | Your facilitator URL (defaults to hosted if not set) |
269
+ | `facilitatorSecret` | `string` | For self-hosted | Shared secret (when set, requires facilitatorUrl) |
271
270
  | `onPaymentSettled` | `function` | No | Callback when payment is verified |
272
271
  | `telemetry` | `object` | No | Analytics configuration (auto-uses projectKey if not set) |
273
272
 
@@ -277,14 +276,14 @@ Deno.serve(pay(async (req) => {
277
276
 
278
277
  ### Hosted Facilitator (Recommended)
279
278
 
280
- Use our managed facilitator service:
279
+ Use our managed facilitator service - **zero URL config needed**:
281
280
 
282
281
  ```typescript
282
+ // Minimal setup - facilitatorUrl defaults to hosted service!
283
283
  const pay = mantlePaywall({
284
284
  priceUsd: 0.01,
285
285
  payTo: '0xYourWallet',
286
- facilitatorUrl: 'https://facilitator.x402mantlesdk.xyz',
287
- projectKey: 'pk_xxx' // Get from dashboard (used for billing + analytics)
286
+ projectKey: 'pk_xxx' // Get from dashboard (for billing + analytics)
288
287
  });
289
288
  ```
290
289
 
@@ -298,15 +297,23 @@ Run your own facilitator for full control and cost savings:
298
297
 
299
298
  ```typescript
300
299
  const pay = mantlePaywall({
300
+ priceUsd: 0.01,
301
+ payTo: '0xYourWallet',
302
+ facilitatorUrl: 'https://your-facilitator.com', // Required for self-hosted
303
+ facilitatorSecret: process.env.FACILITATOR_SECRET! // Required for self-hosted
304
+ });
305
+
306
+ // Optional: add projectKey for telemetry
307
+ const payWithTelemetry = mantlePaywall({
301
308
  priceUsd: 0.01,
302
309
  payTo: '0xYourWallet',
303
310
  facilitatorUrl: 'https://your-facilitator.com',
304
- // REQUIRED: Must match FACILITATOR_SECRET in your facilitator's .env
305
- facilitatorSecret: process.env.FACILITATOR_SECRET
311
+ facilitatorSecret: process.env.FACILITATOR_SECRET!,
312
+ projectKey: 'pk_xxx' // Optional: for analytics
306
313
  });
307
314
  ```
308
315
 
309
- The `facilitatorSecret` is **required** for self-hosted facilitators to prevent unauthorized usage of your facilitator by third parties.
316
+ The `facilitatorSecret` is **required** for self-hosted facilitators to prevent unauthorized usage. When `facilitatorSecret` is provided, `facilitatorUrl` is also required.
310
317
 
311
318
  Create a facilitator with:
312
319
  ```bash
@@ -0,0 +1,307 @@
1
+ import {
2
+ __require,
3
+ getChainIdForNetwork
4
+ } from "./chunk-WZKYTDTE.js";
5
+
6
+ // src/shared/utils.ts
7
+ function encodeJsonToBase64(value) {
8
+ const json = JSON.stringify(value);
9
+ if (typeof btoa === "function") {
10
+ const bytes = new TextEncoder().encode(json);
11
+ const binString = Array.from(
12
+ bytes,
13
+ (byte) => String.fromCodePoint(byte)
14
+ ).join("");
15
+ return btoa(binString);
16
+ }
17
+ if (typeof globalThis.Buffer !== "undefined") {
18
+ return globalThis.Buffer.from(json, "utf8").toString("base64");
19
+ }
20
+ throw new Error("No base64 implementation found in this environment");
21
+ }
22
+ function randomBytes32Hex() {
23
+ if (typeof crypto !== "undefined" && "getRandomValues" in crypto) {
24
+ const arr = new Uint8Array(32);
25
+ crypto.getRandomValues(arr);
26
+ return "0x" + Array.from(arr).map((b) => b.toString(16).padStart(2, "0")).join("");
27
+ }
28
+ try {
29
+ const nodeCrypto = __require("crypto");
30
+ const buf = nodeCrypto.randomBytes(32);
31
+ return "0x" + buf.toString("hex");
32
+ } catch {
33
+ throw new Error(
34
+ "No cryptographically secure random number generator found. This environment does not support crypto.getRandomValues or Node.js crypto module."
35
+ );
36
+ }
37
+ }
38
+
39
+ // src/client/paymentClient.ts
40
+ function joinUrl(base, path) {
41
+ const normalizedBase = base.replace(/\/+$/, "");
42
+ const normalizedPath = path.startsWith("/") ? path : `/${path}`;
43
+ return `${normalizedBase}${normalizedPath}`;
44
+ }
45
+ function buildTypedDataForAuthorization(authorization, paymentRequirements) {
46
+ const chainId = getChainIdForNetwork(paymentRequirements.network);
47
+ const verifyingContract = paymentRequirements.asset;
48
+ const domain = {
49
+ name: "USD Coin",
50
+ version: "2",
51
+ chainId,
52
+ verifyingContract
53
+ };
54
+ const types = {
55
+ TransferWithAuthorization: [
56
+ { name: "from", type: "address" },
57
+ { name: "to", type: "address" },
58
+ { name: "value", type: "uint256" },
59
+ { name: "validAfter", type: "uint256" },
60
+ { name: "validBefore", type: "uint256" },
61
+ { name: "nonce", type: "bytes32" }
62
+ ]
63
+ };
64
+ return {
65
+ domain,
66
+ types,
67
+ primaryType: "TransferWithAuthorization",
68
+ message: authorization
69
+ };
70
+ }
71
+ async function signAuthorizationWithProvider(provider, authorization, paymentRequirements) {
72
+ const { BrowserProvider } = await import("ethers");
73
+ const chainId = getChainIdForNetwork(paymentRequirements.network);
74
+ const browserProvider = new BrowserProvider(provider, chainId);
75
+ const signer = await browserProvider.getSigner();
76
+ const from = await signer.getAddress();
77
+ const authWithFrom = {
78
+ ...authorization,
79
+ from
80
+ };
81
+ const typedData = buildTypedDataForAuthorization(
82
+ authWithFrom,
83
+ paymentRequirements
84
+ );
85
+ const signature = await signer.signTypedData(
86
+ typedData.domain,
87
+ typedData.types,
88
+ typedData.message
89
+ );
90
+ return { signature, from };
91
+ }
92
+ function createPaymentClient(config) {
93
+ const {
94
+ resourceUrl,
95
+ facilitatorUrl: configFacilitatorUrl,
96
+ provider,
97
+ userAddress: userAddressOverride,
98
+ projectKey: configProjectKey
99
+ } = config;
100
+ if (!resourceUrl) {
101
+ throw new Error("resourceUrl is required");
102
+ }
103
+ if (!provider) {
104
+ throw new Error("provider is required (e.g. window.ethereum)");
105
+ }
106
+ return {
107
+ async callWithPayment(path, options) {
108
+ const method = options?.method ?? "GET";
109
+ const headers = {
110
+ ...options?.headers ?? {}
111
+ };
112
+ let body;
113
+ if (options?.body !== void 0) {
114
+ headers["Content-Type"] = headers["Content-Type"] ?? "application/json";
115
+ body = JSON.stringify(options.body);
116
+ }
117
+ const initialUrl = joinUrl(resourceUrl, path);
118
+ const initialRes = await fetch(initialUrl, {
119
+ method,
120
+ headers,
121
+ body
122
+ });
123
+ if (initialRes.status !== 402) {
124
+ const json = await initialRes.json().catch((err) => {
125
+ console.error("[x402] Failed to parse initial response JSON:", err);
126
+ return null;
127
+ });
128
+ return {
129
+ response: json,
130
+ txHash: void 0
131
+ };
132
+ }
133
+ const bodyJson = await initialRes.json();
134
+ const paymentRequirements = bodyJson.paymentRequirements;
135
+ if (!paymentRequirements) {
136
+ throw new Error(
137
+ "402 response did not include paymentRequirements field"
138
+ );
139
+ }
140
+ const facilitatorUrl = configFacilitatorUrl ?? bodyJson.facilitatorUrl;
141
+ if (!facilitatorUrl) {
142
+ throw new Error(
143
+ "facilitatorUrl not provided in config and not in 402 response. Either set facilitatorUrl in client config or ensure your backend includes it in 402 responses."
144
+ );
145
+ }
146
+ const projectKey = configProjectKey ?? bodyJson.projectKey;
147
+ const settleToken = bodyJson.settleToken;
148
+ const nowSec = Math.floor(Date.now() / 1e3);
149
+ const validAfter = "0";
150
+ const validBefore = String(nowSec + 10 * 60);
151
+ const nonce = randomBytes32Hex();
152
+ const valueAtomic = options?.valueOverrideAtomic ?? paymentRequirements.maxAmountRequired;
153
+ let authorization = {
154
+ from: "0x0000000000000000000000000000000000000000",
155
+ to: paymentRequirements.payTo,
156
+ value: valueAtomic,
157
+ validAfter,
158
+ validBefore,
159
+ nonce
160
+ };
161
+ let signature;
162
+ let from;
163
+ try {
164
+ const signed = await signAuthorizationWithProvider(
165
+ provider,
166
+ authorization,
167
+ paymentRequirements
168
+ );
169
+ signature = signed.signature;
170
+ from = signed.from;
171
+ } catch (err) {
172
+ const code = err?.code;
173
+ if (code === 4001 || code === "ACTION_REJECTED") {
174
+ const userErr = new Error("User rejected payment signature");
175
+ userErr.code = "USER_REJECTED_SIGNATURE";
176
+ userErr.userRejected = true;
177
+ throw userErr;
178
+ }
179
+ throw err;
180
+ }
181
+ authorization = {
182
+ ...authorization,
183
+ from
184
+ };
185
+ if (userAddressOverride && userAddressOverride.toLowerCase() !== from.toLowerCase()) {
186
+ console.warn(
187
+ "[SDK WARNING] userAddress override differs from signer address",
188
+ { override: userAddressOverride, signer: from }
189
+ );
190
+ }
191
+ const paymentHeaderObject = {
192
+ x402Version: 1,
193
+ scheme: paymentRequirements.scheme,
194
+ network: paymentRequirements.network,
195
+ payload: {
196
+ signature,
197
+ authorization
198
+ }
199
+ };
200
+ const paymentHeader = encodeJsonToBase64(paymentHeaderObject);
201
+ const settleUrl = joinUrl(facilitatorUrl, "/settle");
202
+ const settleRes = await fetch(settleUrl, {
203
+ method: "POST",
204
+ headers: {
205
+ "Content-Type": "application/json",
206
+ ...projectKey ? { "X-Project-Key": projectKey } : {}
207
+ },
208
+ body: JSON.stringify({
209
+ x402Version: 1,
210
+ paymentHeader,
211
+ paymentRequirements,
212
+ ...settleToken && { settleToken }
213
+ })
214
+ });
215
+ if (!settleRes.ok) {
216
+ const text = await settleRes.text().catch((err) => {
217
+ console.error("[x402] Failed to read settle response text:", err);
218
+ return "";
219
+ });
220
+ throw new Error(
221
+ `Facilitator /settle failed with HTTP ${settleRes.status}: ${text}`
222
+ );
223
+ }
224
+ const settleJson = await settleRes.json();
225
+ if (!settleJson.success) {
226
+ throw new Error(
227
+ `Facilitator /settle returned error: ${settleJson.error ?? "unknown error"}`
228
+ );
229
+ }
230
+ const txHash = settleJson.txHash ?? void 0;
231
+ const retryHeaders = {
232
+ ...headers,
233
+ "X-PAYMENT": paymentHeader
234
+ };
235
+ const retryRes = await fetch(initialUrl, {
236
+ method,
237
+ headers: retryHeaders,
238
+ body
239
+ });
240
+ if (!retryRes.ok) {
241
+ const text = await retryRes.text().catch((err) => {
242
+ console.error("[x402] Failed to read retry response text:", err);
243
+ return "";
244
+ });
245
+ throw new Error(
246
+ `Protected request with X-PAYMENT failed: HTTP ${retryRes.status} ${text}`
247
+ );
248
+ }
249
+ const finalJson = await retryRes.json();
250
+ return {
251
+ response: finalJson,
252
+ txHash,
253
+ paymentHeader,
254
+ paymentRequirements
255
+ };
256
+ }
257
+ };
258
+ }
259
+
260
+ // src/client/createMantleClient.ts
261
+ function createMantleClient(config) {
262
+ const resourceUrl = config?.resourceUrl ?? (typeof window !== "undefined" ? window.location.origin : "");
263
+ const facilitatorUrl = config?.facilitatorUrl ?? (typeof process !== "undefined" ? process.env?.NEXT_PUBLIC_FACILITATOR_URL : void 0);
264
+ return {
265
+ async postWithPayment(url, body) {
266
+ const provider = config?.getProvider?.();
267
+ if (!provider) {
268
+ throw new Error("Wallet provider not available");
269
+ }
270
+ let account = await config?.getAccount?.();
271
+ if (!account && provider?.request) {
272
+ try {
273
+ const accounts = await provider.request({
274
+ method: "eth_accounts"
275
+ });
276
+ if (Array.isArray(accounts) && accounts.length > 0) {
277
+ account = accounts[0];
278
+ }
279
+ } catch (err) {
280
+ console.warn("[x402] Failed to hydrate account from provider:", err);
281
+ }
282
+ }
283
+ if (!account) {
284
+ throw new Error(
285
+ "Wallet not connected. Please connect your wallet first."
286
+ );
287
+ }
288
+ const client = createPaymentClient({
289
+ resourceUrl,
290
+ facilitatorUrl,
291
+ provider,
292
+ userAddress: account,
293
+ projectKey: config?.projectKey
294
+ });
295
+ const result = await client.callWithPayment(url, {
296
+ method: "POST",
297
+ body
298
+ });
299
+ return result;
300
+ }
301
+ };
302
+ }
303
+
304
+ export {
305
+ createPaymentClient,
306
+ createMantleClient
307
+ };
@@ -0,0 +1,179 @@
1
+ import {
2
+ createMantleClient
3
+ } from "./chunk-5RSVKEVG.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 setProviderAndChain = useCallback(async () => {
17
+ if (typeof window === "undefined" || !window.ethereum) return;
18
+ const browserProvider = new ethers.BrowserProvider(
19
+ window.ethereum
20
+ );
21
+ setProvider(browserProvider);
22
+ const network = await browserProvider.getNetwork();
23
+ setChainId(Number(network.chainId));
24
+ }, []);
25
+ const hydrateFromPermissions = useCallback(async () => {
26
+ if (typeof window === "undefined" || !window.ethereum) return;
27
+ try {
28
+ const accounts = await window.ethereum.request({
29
+ method: "eth_accounts"
30
+ });
31
+ if (accounts && accounts.length > 0) {
32
+ const userAddress = accounts[0];
33
+ setAddress(userAddress);
34
+ setIsConnected(true);
35
+ await setProviderAndChain();
36
+ }
37
+ } catch (err) {
38
+ console.warn("[useEthersWallet] Failed to hydrate from permissions:", err);
39
+ }
40
+ }, [setProviderAndChain]);
41
+ const connect = useCallback(async () => {
42
+ try {
43
+ setError(void 0);
44
+ if (typeof window === "undefined" || !window.ethereum) {
45
+ throw new Error(
46
+ "No Ethereum wallet detected. Please install MetaMask or another wallet."
47
+ );
48
+ }
49
+ const browserProvider = new ethers.BrowserProvider(
50
+ window.ethereum
51
+ );
52
+ setProvider(browserProvider);
53
+ const accounts = await window.ethereum.request({
54
+ method: "eth_requestAccounts"
55
+ });
56
+ if (!accounts || accounts.length === 0) {
57
+ throw new Error("No accounts returned from wallet");
58
+ }
59
+ const userAddress = accounts[0];
60
+ setAddress(userAddress);
61
+ setIsConnected(true);
62
+ const network = await browserProvider.getNetwork();
63
+ setChainId(Number(network.chainId));
64
+ } catch (err) {
65
+ const errorObj = err instanceof Error ? err : new Error(String(err));
66
+ setError(errorObj);
67
+ setIsConnected(false);
68
+ setAddress(void 0);
69
+ setChainId(void 0);
70
+ throw errorObj;
71
+ }
72
+ }, []);
73
+ const disconnect = useCallback(() => {
74
+ setAddress(void 0);
75
+ setIsConnected(false);
76
+ setChainId(void 0);
77
+ setError(void 0);
78
+ }, []);
79
+ useEffect(() => {
80
+ if (typeof window === "undefined" || !window.ethereum) return;
81
+ const ethereum = window.ethereum;
82
+ const handleAccountsChanged = (accounts) => {
83
+ const accountsArray = accounts;
84
+ if (!accountsArray || accountsArray.length === 0) {
85
+ disconnect();
86
+ } else {
87
+ setAddress(accountsArray[0]);
88
+ setIsConnected(true);
89
+ void setProviderAndChain();
90
+ }
91
+ };
92
+ if (ethereum.on) {
93
+ ethereum.on("accountsChanged", handleAccountsChanged);
94
+ }
95
+ return () => {
96
+ if (ethereum.removeListener) {
97
+ ethereum.removeListener("accountsChanged", handleAccountsChanged);
98
+ }
99
+ };
100
+ }, [disconnect, setProviderAndChain]);
101
+ useEffect(() => {
102
+ if (typeof window === "undefined" || !window.ethereum) return;
103
+ const ethereum = window.ethereum;
104
+ const handleConnect = () => {
105
+ void hydrateFromPermissions();
106
+ };
107
+ if (ethereum.on) {
108
+ ethereum.on("connect", handleConnect);
109
+ }
110
+ return () => {
111
+ if (ethereum.removeListener) {
112
+ ethereum.removeListener("connect", handleConnect);
113
+ }
114
+ };
115
+ }, [hydrateFromPermissions]);
116
+ useEffect(() => {
117
+ if (typeof window === "undefined" || !window.ethereum) return;
118
+ const ethereum = window.ethereum;
119
+ const handleChainChanged = (chainIdHex) => {
120
+ const newChainId = parseInt(chainIdHex, 16);
121
+ setChainId(newChainId);
122
+ };
123
+ if (ethereum.on) {
124
+ ethereum.on("chainChanged", handleChainChanged);
125
+ }
126
+ return () => {
127
+ if (ethereum.removeListener) {
128
+ ethereum.removeListener("chainChanged", handleChainChanged);
129
+ }
130
+ };
131
+ }, []);
132
+ useEffect(() => {
133
+ void hydrateFromPermissions();
134
+ }, [hydrateFromPermissions]);
135
+ useEffect(() => {
136
+ if (options?.autoConnect) {
137
+ connect().catch((err) => {
138
+ console.warn("[useEthersWallet] Auto-connect failed:", err);
139
+ });
140
+ }
141
+ }, [options?.autoConnect, connect]);
142
+ return {
143
+ address,
144
+ isConnected,
145
+ provider,
146
+ chainId,
147
+ connect,
148
+ disconnect,
149
+ error
150
+ };
151
+ }
152
+
153
+ // src/client/react/useMantleX402.ts
154
+ function useMantleX402(opts) {
155
+ const { address, isConnected } = useEthersWallet({
156
+ autoConnect: opts?.autoConnect ?? false
157
+ });
158
+ const client = createMantleClient({
159
+ facilitatorUrl: opts?.facilitatorUrl,
160
+ resourceUrl: opts?.resourceUrl,
161
+ projectKey: opts?.projectKey,
162
+ getAccount: () => {
163
+ if (!isConnected || !address) return void 0;
164
+ return address;
165
+ },
166
+ getProvider: () => {
167
+ if (typeof window !== "undefined" && window.ethereum) {
168
+ return window.ethereum;
169
+ }
170
+ return void 0;
171
+ }
172
+ });
173
+ return client;
174
+ }
175
+
176
+ export {
177
+ useEthersWallet,
178
+ useMantleX402
179
+ };