@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.
Files changed (41) hide show
  1. package/dist/chunk-CTI5CRDY.js +274 -0
  2. package/dist/chunk-DA6ZBXNO.js +275 -0
  3. package/dist/chunk-FD4HG7KR.js +135 -0
  4. package/dist/chunk-GWVWPS3R.js +277 -0
  5. package/dist/chunk-HTZ3QFY4.js +135 -0
  6. package/dist/chunk-MQALBRGV.js +135 -0
  7. package/dist/chunk-PYIYE3HI.js +135 -0
  8. package/dist/chunk-Q6SPMEIW.js +235 -0
  9. package/dist/chunk-RNKXSBT7.js +135 -0
  10. package/dist/chunk-SPCXFN7C.js +284 -0
  11. package/dist/chunk-T5DRYLNB.js +135 -0
  12. package/dist/chunk-TSEE5NSJ.js +297 -0
  13. package/dist/chunk-WELDWRDX.js +307 -0
  14. package/dist/chunk-XAQGMFSR.js +56 -0
  15. package/dist/client.cjs +328 -0
  16. package/dist/client.d.cts +17 -0
  17. package/dist/client.d.ts +17 -0
  18. package/dist/client.js +12 -0
  19. package/dist/constants-C7aY8u5b.d.cts +77 -0
  20. package/dist/constants-C7aY8u5b.d.ts +77 -0
  21. package/dist/constants-CVFF0ray.d.ts +17 -0
  22. package/dist/constants-DzCGK0Q3.d.cts +17 -0
  23. package/dist/createMantleClient-DS1Ghqrz.d.cts +51 -0
  24. package/dist/createMantleClient-DS1Ghqrz.d.ts +51 -0
  25. package/dist/createMantleClient-DVFkbBfS.d.ts +87 -0
  26. package/dist/createMantleClient-NN0Nitp9.d.cts +87 -0
  27. package/dist/index.cjs +244 -43
  28. package/dist/index.d.cts +8 -164
  29. package/dist/index.d.ts +8 -164
  30. package/dist/index.js +21 -485
  31. package/dist/react.cjs +453 -0
  32. package/dist/react.d.cts +90 -0
  33. package/dist/react.d.ts +90 -0
  34. package/dist/react.js +10 -0
  35. package/dist/server.cjs +292 -0
  36. package/dist/server.d.cts +116 -0
  37. package/dist/server.d.ts +116 -0
  38. package/dist/server.js +12 -0
  39. package/dist/types-2zqbJvcz.d.cts +63 -0
  40. package/dist/types-2zqbJvcz.d.ts +63 -0
  41. package/package.json +37 -3
@@ -0,0 +1,307 @@
1
+ import {
2
+ __require,
3
+ getChainIdForNetwork
4
+ } from "./chunk-XAQGMFSR.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
+ async function getUserAddressFromProvider(provider) {
46
+ const p = provider;
47
+ if (!p || typeof p.request !== "function") {
48
+ throw new Error("provider must implement EIP-1193 request()");
49
+ }
50
+ const accounts = await p.request({
51
+ method: "eth_requestAccounts"
52
+ });
53
+ if (!accounts || accounts.length === 0) {
54
+ throw new Error("No accounts returned from provider");
55
+ }
56
+ return accounts[0];
57
+ }
58
+ function buildTypedDataForAuthorization(authorization, paymentRequirements) {
59
+ const chainId = getChainIdForNetwork(paymentRequirements.network);
60
+ const verifyingContract = paymentRequirements.asset;
61
+ const domain = {
62
+ name: "USD Coin",
63
+ version: "2",
64
+ chainId,
65
+ verifyingContract
66
+ };
67
+ const types = {
68
+ TransferWithAuthorization: [
69
+ { name: "from", type: "address" },
70
+ { name: "to", type: "address" },
71
+ { name: "value", type: "uint256" },
72
+ { name: "validAfter", type: "uint256" },
73
+ { name: "validBefore", type: "uint256" },
74
+ { name: "nonce", type: "bytes32" }
75
+ ]
76
+ };
77
+ return {
78
+ domain,
79
+ types,
80
+ primaryType: "TransferWithAuthorization",
81
+ message: authorization
82
+ };
83
+ }
84
+ async function signAuthorizationWithProvider(provider, address, authorization, paymentRequirements) {
85
+ const p = provider;
86
+ if (!p || typeof p.request !== "function") {
87
+ throw new Error("provider must implement EIP-1193 request()");
88
+ }
89
+ const typedData = buildTypedDataForAuthorization(
90
+ authorization,
91
+ paymentRequirements
92
+ );
93
+ const params = [address, JSON.stringify(typedData)];
94
+ const signature = await p.request({
95
+ method: "eth_signTypedData_v4",
96
+ params
97
+ });
98
+ if (typeof signature !== "string" || !signature.startsWith("0x")) {
99
+ throw new Error("Invalid signature returned from provider");
100
+ }
101
+ return signature;
102
+ }
103
+ function createPaymentClient(config) {
104
+ const {
105
+ resourceUrl,
106
+ facilitatorUrl,
107
+ provider,
108
+ userAddress: userAddressOverride,
109
+ projectKey
110
+ } = config;
111
+ if (!resourceUrl) {
112
+ throw new Error("resourceUrl is required");
113
+ }
114
+ if (!facilitatorUrl) {
115
+ throw new Error("facilitatorUrl is required");
116
+ }
117
+ if (!provider) {
118
+ throw new Error("provider is required (e.g. window.ethereum)");
119
+ }
120
+ return {
121
+ async callWithPayment(path, options) {
122
+ const method = options?.method ?? "GET";
123
+ const headers = {
124
+ ...options?.headers ?? {}
125
+ };
126
+ let body;
127
+ if (options?.body !== void 0) {
128
+ headers["Content-Type"] = headers["Content-Type"] ?? "application/json";
129
+ body = JSON.stringify(options.body);
130
+ }
131
+ const initialUrl = joinUrl(resourceUrl, path);
132
+ const initialRes = await fetch(initialUrl, {
133
+ method,
134
+ headers,
135
+ body
136
+ });
137
+ if (initialRes.status !== 402) {
138
+ const json = await initialRes.json().catch((err) => {
139
+ console.error("[x402] Failed to parse initial response JSON:", err);
140
+ return null;
141
+ });
142
+ return {
143
+ response: json,
144
+ txHash: void 0
145
+ };
146
+ }
147
+ const bodyJson = await initialRes.json();
148
+ const paymentRequirements = bodyJson.paymentRequirements;
149
+ if (!paymentRequirements) {
150
+ throw new Error(
151
+ "402 response did not include paymentRequirements field"
152
+ );
153
+ }
154
+ const fromAddress = userAddressOverride ?? await getUserAddressFromProvider(provider);
155
+ try {
156
+ const p = provider;
157
+ const accounts = await p.request({ method: "eth_accounts" });
158
+ console.log("[SDK] Wallet accounts:", accounts);
159
+ console.log("[SDK] Using fromAddress:", fromAddress);
160
+ } catch (err) {
161
+ }
162
+ const nowSec = Math.floor(Date.now() / 1e3);
163
+ const validAfter = "0";
164
+ const validBefore = String(nowSec + 10 * 60);
165
+ const nonce = randomBytes32Hex();
166
+ const valueAtomic = options?.valueOverrideAtomic ?? paymentRequirements.maxAmountRequired;
167
+ let authorization = {
168
+ from: fromAddress,
169
+ to: paymentRequirements.payTo,
170
+ value: valueAtomic,
171
+ validAfter,
172
+ validBefore,
173
+ nonce
174
+ };
175
+ const signature = await signAuthorizationWithProvider(
176
+ provider,
177
+ fromAddress,
178
+ authorization,
179
+ paymentRequirements
180
+ );
181
+ const { ethers } = await import("ethers");
182
+ const typedData = buildTypedDataForAuthorization(
183
+ authorization,
184
+ paymentRequirements
185
+ );
186
+ const recovered = ethers.verifyTypedData(
187
+ typedData.domain,
188
+ typedData.types,
189
+ typedData.message,
190
+ signature
191
+ );
192
+ if (recovered.toLowerCase() !== authorization.from.toLowerCase()) {
193
+ console.warn("[SDK WARNING] Signer address differs from expected, using recovered address", {
194
+ expected: authorization.from,
195
+ recovered,
196
+ message: "This may indicate multiple accounts in wallet or wrong active account"
197
+ });
198
+ authorization = {
199
+ ...authorization,
200
+ from: recovered
201
+ };
202
+ }
203
+ console.log("[SDK] Using authorization.from:", authorization.from);
204
+ const paymentHeaderObject = {
205
+ x402Version: 1,
206
+ scheme: paymentRequirements.scheme,
207
+ network: paymentRequirements.network,
208
+ payload: {
209
+ signature,
210
+ authorization
211
+ }
212
+ };
213
+ const paymentHeader = encodeJsonToBase64(paymentHeaderObject);
214
+ const settleUrl = joinUrl(facilitatorUrl, "/settle");
215
+ const settleRes = await fetch(settleUrl, {
216
+ method: "POST",
217
+ headers: {
218
+ "Content-Type": "application/json",
219
+ ...projectKey ? { "X-Project-Key": projectKey } : {}
220
+ },
221
+ body: JSON.stringify({
222
+ x402Version: 1,
223
+ paymentHeader,
224
+ paymentRequirements
225
+ })
226
+ });
227
+ if (!settleRes.ok) {
228
+ const text = await settleRes.text().catch((err) => {
229
+ console.error("[x402] Failed to read settle response text:", err);
230
+ return "";
231
+ });
232
+ throw new Error(
233
+ `Facilitator /settle failed with HTTP ${settleRes.status}: ${text}`
234
+ );
235
+ }
236
+ const settleJson = await settleRes.json();
237
+ if (!settleJson.success) {
238
+ throw new Error(
239
+ `Facilitator /settle returned error: ${settleJson.error ?? "unknown error"}`
240
+ );
241
+ }
242
+ const txHash = settleJson.txHash ?? void 0;
243
+ const retryHeaders = {
244
+ ...headers,
245
+ "X-PAYMENT": paymentHeader
246
+ };
247
+ const retryRes = await fetch(initialUrl, {
248
+ method,
249
+ headers: retryHeaders,
250
+ body
251
+ });
252
+ if (!retryRes.ok) {
253
+ const text = await retryRes.text().catch((err) => {
254
+ console.error("[x402] Failed to read retry response text:", err);
255
+ return "";
256
+ });
257
+ throw new Error(
258
+ `Protected request with X-PAYMENT failed: HTTP ${retryRes.status} ${text}`
259
+ );
260
+ }
261
+ const finalJson = await retryRes.json();
262
+ return {
263
+ response: finalJson,
264
+ txHash,
265
+ paymentHeader,
266
+ paymentRequirements
267
+ };
268
+ }
269
+ };
270
+ }
271
+
272
+ // src/client/createMantleClient.ts
273
+ function createMantleClient(config) {
274
+ const resourceUrl = config?.resourceUrl ?? (typeof window !== "undefined" ? window.location.origin : "");
275
+ const facilitatorUrl = config?.facilitatorUrl ?? (typeof process !== "undefined" ? process.env?.NEXT_PUBLIC_FACILITATOR_URL : void 0) ?? "http://localhost:8080";
276
+ return {
277
+ async postWithPayment(url, body) {
278
+ const account = await config?.getAccount?.();
279
+ if (!account) {
280
+ throw new Error(
281
+ "Wallet not connected. Please connect your wallet first."
282
+ );
283
+ }
284
+ const provider = config?.getProvider?.();
285
+ if (!provider) {
286
+ throw new Error("Wallet provider not available");
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.response;
300
+ }
301
+ };
302
+ }
303
+
304
+ export {
305
+ createPaymentClient,
306
+ createMantleClient
307
+ };
@@ -0,0 +1,56 @@
1
+ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
2
+ get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
3
+ }) : x)(function(x) {
4
+ if (typeof require !== "undefined") return require.apply(this, arguments);
5
+ throw Error('Dynamic require of "' + x + '" is not supported');
6
+ });
7
+
8
+ // src/shared/constants.ts
9
+ var MANTLE_MAINNET_NETWORK_ID = "mantle-mainnet";
10
+ var MANTLE_MAINNET_CHAIN_ID = 5e3;
11
+ var MANTLE_MAINNET_USDC = {
12
+ symbol: "USDC",
13
+ address: "0x09Bc4E0D864854c6aFB6eB9A9cdF58aC190D0dF9",
14
+ decimals: 6
15
+ };
16
+ var MANTLE_DEFAULTS = {
17
+ NETWORK: "mantle-mainnet",
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
+ export {
51
+ __require,
52
+ MANTLE_DEFAULTS,
53
+ getDefaultAssetForNetwork,
54
+ getChainIdForNetwork,
55
+ usdCentsToAtomic
56
+ };
@@ -0,0 +1,328 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // src/client.ts
31
+ var client_exports = {};
32
+ __export(client_exports, {
33
+ MANTLE_DEFAULTS: () => MANTLE_DEFAULTS,
34
+ createMantleClient: () => createMantleClient,
35
+ createPaymentClient: () => createPaymentClient
36
+ });
37
+ module.exports = __toCommonJS(client_exports);
38
+
39
+ // src/shared/constants.ts
40
+ var MANTLE_MAINNET_NETWORK_ID = "mantle-mainnet";
41
+ var MANTLE_MAINNET_CHAIN_ID = 5e3;
42
+ var MANTLE_DEFAULTS = {
43
+ NETWORK: "mantle-mainnet",
44
+ CHAIN_ID: 5e3,
45
+ USDC_ADDRESS: "0x09Bc4E0D864854c6aFB6eB9A9cdF58aC190D0dF9",
46
+ USDC_DECIMALS: 6,
47
+ CURRENCY: "USD",
48
+ SCHEME: "exact",
49
+ FACILITATOR_URL: (typeof process !== "undefined" ? process.env?.NEXT_PUBLIC_FACILITATOR_URL : void 0) || "http://localhost:8080"
50
+ };
51
+ function getChainIdForNetwork(network) {
52
+ switch (network) {
53
+ case MANTLE_MAINNET_NETWORK_ID:
54
+ default:
55
+ return MANTLE_MAINNET_CHAIN_ID;
56
+ }
57
+ }
58
+
59
+ // src/shared/utils.ts
60
+ function encodeJsonToBase64(value) {
61
+ const json = JSON.stringify(value);
62
+ if (typeof btoa === "function") {
63
+ const bytes = new TextEncoder().encode(json);
64
+ const binString = Array.from(
65
+ bytes,
66
+ (byte) => String.fromCodePoint(byte)
67
+ ).join("");
68
+ return btoa(binString);
69
+ }
70
+ if (typeof globalThis.Buffer !== "undefined") {
71
+ return globalThis.Buffer.from(json, "utf8").toString("base64");
72
+ }
73
+ throw new Error("No base64 implementation found in this environment");
74
+ }
75
+ function randomBytes32Hex() {
76
+ if (typeof crypto !== "undefined" && "getRandomValues" in crypto) {
77
+ const arr = new Uint8Array(32);
78
+ crypto.getRandomValues(arr);
79
+ return "0x" + Array.from(arr).map((b) => b.toString(16).padStart(2, "0")).join("");
80
+ }
81
+ try {
82
+ const nodeCrypto = require("crypto");
83
+ const buf = nodeCrypto.randomBytes(32);
84
+ return "0x" + buf.toString("hex");
85
+ } catch {
86
+ throw new Error(
87
+ "No cryptographically secure random number generator found. This environment does not support crypto.getRandomValues or Node.js crypto module."
88
+ );
89
+ }
90
+ }
91
+
92
+ // src/client/paymentClient.ts
93
+ function joinUrl(base, path) {
94
+ const normalizedBase = base.replace(/\/+$/, "");
95
+ const normalizedPath = path.startsWith("/") ? path : `/${path}`;
96
+ return `${normalizedBase}${normalizedPath}`;
97
+ }
98
+ function buildTypedDataForAuthorization(authorization, paymentRequirements) {
99
+ const chainId = getChainIdForNetwork(paymentRequirements.network);
100
+ const verifyingContract = paymentRequirements.asset;
101
+ const domain = {
102
+ name: "USD Coin",
103
+ version: "2",
104
+ chainId,
105
+ verifyingContract
106
+ };
107
+ const types = {
108
+ TransferWithAuthorization: [
109
+ { name: "from", type: "address" },
110
+ { name: "to", type: "address" },
111
+ { name: "value", type: "uint256" },
112
+ { name: "validAfter", type: "uint256" },
113
+ { name: "validBefore", type: "uint256" },
114
+ { name: "nonce", type: "bytes32" }
115
+ ]
116
+ };
117
+ return {
118
+ domain,
119
+ types,
120
+ primaryType: "TransferWithAuthorization",
121
+ message: authorization
122
+ };
123
+ }
124
+ async function signAuthorizationWithProvider(provider, authorization, paymentRequirements) {
125
+ const { BrowserProvider } = await import("ethers");
126
+ const chainId = getChainIdForNetwork(paymentRequirements.network);
127
+ const browserProvider = new BrowserProvider(provider, chainId);
128
+ const signer = await browserProvider.getSigner();
129
+ const from = await signer.getAddress();
130
+ const authWithFrom = {
131
+ ...authorization,
132
+ from
133
+ };
134
+ const typedData = buildTypedDataForAuthorization(
135
+ authWithFrom,
136
+ paymentRequirements
137
+ );
138
+ const signature = await signer.signTypedData(
139
+ typedData.domain,
140
+ typedData.types,
141
+ typedData.message
142
+ );
143
+ return { signature, from };
144
+ }
145
+ function createPaymentClient(config) {
146
+ const {
147
+ resourceUrl,
148
+ facilitatorUrl,
149
+ provider,
150
+ userAddress: userAddressOverride,
151
+ projectKey
152
+ } = config;
153
+ if (!resourceUrl) {
154
+ throw new Error("resourceUrl is required");
155
+ }
156
+ if (!facilitatorUrl) {
157
+ throw new Error("facilitatorUrl is required");
158
+ }
159
+ if (!provider) {
160
+ throw new Error("provider is required (e.g. window.ethereum)");
161
+ }
162
+ return {
163
+ async callWithPayment(path, options) {
164
+ const method = options?.method ?? "GET";
165
+ const headers = {
166
+ ...options?.headers ?? {}
167
+ };
168
+ let body;
169
+ if (options?.body !== void 0) {
170
+ headers["Content-Type"] = headers["Content-Type"] ?? "application/json";
171
+ body = JSON.stringify(options.body);
172
+ }
173
+ const initialUrl = joinUrl(resourceUrl, path);
174
+ const initialRes = await fetch(initialUrl, {
175
+ method,
176
+ headers,
177
+ body
178
+ });
179
+ if (initialRes.status !== 402) {
180
+ const json = await initialRes.json().catch((err) => {
181
+ console.error("[x402] Failed to parse initial response JSON:", err);
182
+ return null;
183
+ });
184
+ return {
185
+ response: json,
186
+ txHash: void 0
187
+ };
188
+ }
189
+ const bodyJson = await initialRes.json();
190
+ const paymentRequirements = bodyJson.paymentRequirements;
191
+ if (!paymentRequirements) {
192
+ throw new Error(
193
+ "402 response did not include paymentRequirements field"
194
+ );
195
+ }
196
+ const nowSec = Math.floor(Date.now() / 1e3);
197
+ const validAfter = "0";
198
+ const validBefore = String(nowSec + 10 * 60);
199
+ const nonce = randomBytes32Hex();
200
+ const valueAtomic = options?.valueOverrideAtomic ?? paymentRequirements.maxAmountRequired;
201
+ let authorization = {
202
+ from: "0x0000000000000000000000000000000000000000",
203
+ to: paymentRequirements.payTo,
204
+ value: valueAtomic,
205
+ validAfter,
206
+ validBefore,
207
+ nonce
208
+ };
209
+ const { signature, from } = await signAuthorizationWithProvider(
210
+ provider,
211
+ authorization,
212
+ paymentRequirements
213
+ );
214
+ authorization = {
215
+ ...authorization,
216
+ from
217
+ };
218
+ if (userAddressOverride && userAddressOverride.toLowerCase() !== from.toLowerCase()) {
219
+ console.warn(
220
+ "[SDK WARNING] userAddress override differs from signer address",
221
+ { override: userAddressOverride, signer: from }
222
+ );
223
+ }
224
+ const paymentHeaderObject = {
225
+ x402Version: 1,
226
+ scheme: paymentRequirements.scheme,
227
+ network: paymentRequirements.network,
228
+ payload: {
229
+ signature,
230
+ authorization
231
+ }
232
+ };
233
+ const paymentHeader = encodeJsonToBase64(paymentHeaderObject);
234
+ const settleUrl = joinUrl(facilitatorUrl, "/settle");
235
+ const settleRes = await fetch(settleUrl, {
236
+ method: "POST",
237
+ headers: {
238
+ "Content-Type": "application/json",
239
+ ...projectKey ? { "X-Project-Key": projectKey } : {}
240
+ },
241
+ body: JSON.stringify({
242
+ x402Version: 1,
243
+ paymentHeader,
244
+ paymentRequirements
245
+ })
246
+ });
247
+ if (!settleRes.ok) {
248
+ const text = await settleRes.text().catch((err) => {
249
+ console.error("[x402] Failed to read settle response text:", err);
250
+ return "";
251
+ });
252
+ throw new Error(
253
+ `Facilitator /settle failed with HTTP ${settleRes.status}: ${text}`
254
+ );
255
+ }
256
+ const settleJson = await settleRes.json();
257
+ if (!settleJson.success) {
258
+ throw new Error(
259
+ `Facilitator /settle returned error: ${settleJson.error ?? "unknown error"}`
260
+ );
261
+ }
262
+ const txHash = settleJson.txHash ?? void 0;
263
+ const retryHeaders = {
264
+ ...headers,
265
+ "X-PAYMENT": paymentHeader
266
+ };
267
+ const retryRes = await fetch(initialUrl, {
268
+ method,
269
+ headers: retryHeaders,
270
+ body
271
+ });
272
+ if (!retryRes.ok) {
273
+ const text = await retryRes.text().catch((err) => {
274
+ console.error("[x402] Failed to read retry response text:", err);
275
+ return "";
276
+ });
277
+ throw new Error(
278
+ `Protected request with X-PAYMENT failed: HTTP ${retryRes.status} ${text}`
279
+ );
280
+ }
281
+ const finalJson = await retryRes.json();
282
+ return {
283
+ response: finalJson,
284
+ txHash,
285
+ paymentHeader,
286
+ paymentRequirements
287
+ };
288
+ }
289
+ };
290
+ }
291
+
292
+ // src/client/createMantleClient.ts
293
+ function createMantleClient(config) {
294
+ const resourceUrl = config?.resourceUrl ?? (typeof window !== "undefined" ? window.location.origin : "");
295
+ const facilitatorUrl = config?.facilitatorUrl ?? (typeof process !== "undefined" ? process.env?.NEXT_PUBLIC_FACILITATOR_URL : void 0) ?? "http://localhost:8080";
296
+ return {
297
+ async postWithPayment(url, body) {
298
+ const account = await config?.getAccount?.();
299
+ if (!account) {
300
+ throw new Error(
301
+ "Wallet not connected. Please connect your wallet first."
302
+ );
303
+ }
304
+ const provider = config?.getProvider?.();
305
+ if (!provider) {
306
+ throw new Error("Wallet provider not available");
307
+ }
308
+ const client = createPaymentClient({
309
+ resourceUrl,
310
+ facilitatorUrl,
311
+ provider,
312
+ userAddress: account,
313
+ projectKey: config?.projectKey
314
+ });
315
+ const result = await client.callWithPayment(url, {
316
+ method: "POST",
317
+ body
318
+ });
319
+ return result;
320
+ }
321
+ };
322
+ }
323
+ // Annotate the CommonJS export names for ESM import in node:
324
+ 0 && (module.exports = {
325
+ MANTLE_DEFAULTS,
326
+ createMantleClient,
327
+ createPaymentClient
328
+ });
@@ -0,0 +1,17 @@
1
+ import { P as PaymentClientConfig, b as PaymentClient } from './createMantleClient-NN0Nitp9.cjs';
2
+ export { C as CallWithPaymentResult, M as MantleClient, a as MantleClientConfig, c as createMantleClient } from './createMantleClient-NN0Nitp9.cjs';
3
+ 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.cjs';
4
+ export { M as MANTLE_DEFAULTS } from './constants-DzCGK0Q3.cjs';
5
+
6
+ /**
7
+ * Creates a high-level payment client that:
8
+ * - makes an initial request
9
+ * - if it receives 402 + paymentRequirements, builds & signs an authorization
10
+ * - calls facilitator /settle
11
+ * - retries the original request with X-PAYMENT header
12
+ *
13
+ * This logic is x402 and tailored for Mantle + USDC.
14
+ */
15
+ declare function createPaymentClient(config: PaymentClientConfig): PaymentClient;
16
+
17
+ export { PaymentClient, PaymentClientConfig, createPaymentClient };