@springmint/x402-payment 1.0.0

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.
@@ -0,0 +1,643 @@
1
+ #!/usr/bin/env node
2
+ import { createRequire as __WEBPACK_EXTERNAL_createRequire } from "module";
3
+ /******/ var __webpack_modules__ = ({
4
+
5
+ /***/ 2613:
6
+ /***/ ((module) => {
7
+
8
+ module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("assert");
9
+
10
+ /***/ }),
11
+
12
+ /***/ 6982:
13
+ /***/ ((module) => {
14
+
15
+ module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("crypto");
16
+
17
+ /***/ }),
18
+
19
+ /***/ 4434:
20
+ /***/ ((module) => {
21
+
22
+ module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("events");
23
+
24
+ /***/ }),
25
+
26
+ /***/ 9896:
27
+ /***/ ((module) => {
28
+
29
+ module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("fs");
30
+
31
+ /***/ }),
32
+
33
+ /***/ 8611:
34
+ /***/ ((module) => {
35
+
36
+ module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("http");
37
+
38
+ /***/ }),
39
+
40
+ /***/ 5675:
41
+ /***/ ((module) => {
42
+
43
+ module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("http2");
44
+
45
+ /***/ }),
46
+
47
+ /***/ 5692:
48
+ /***/ ((module) => {
49
+
50
+ module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("https");
51
+
52
+ /***/ }),
53
+
54
+ /***/ 7598:
55
+ /***/ ((module) => {
56
+
57
+ module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:crypto");
58
+
59
+ /***/ }),
60
+
61
+ /***/ 6928:
62
+ /***/ ((module) => {
63
+
64
+ module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("path");
65
+
66
+ /***/ }),
67
+
68
+ /***/ 2203:
69
+ /***/ ((module) => {
70
+
71
+ module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("stream");
72
+
73
+ /***/ }),
74
+
75
+ /***/ 7016:
76
+ /***/ ((module) => {
77
+
78
+ module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("url");
79
+
80
+ /***/ }),
81
+
82
+ /***/ 9023:
83
+ /***/ ((module) => {
84
+
85
+ module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("util");
86
+
87
+ /***/ }),
88
+
89
+ /***/ 3106:
90
+ /***/ ((module) => {
91
+
92
+ module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("zlib");
93
+
94
+ /***/ })
95
+
96
+ /******/ });
97
+ /************************************************************************/
98
+ /******/ // The module cache
99
+ /******/ var __webpack_module_cache__ = {};
100
+ /******/
101
+ /******/ // The require function
102
+ /******/ function __nccwpck_require__(moduleId) {
103
+ /******/ // Check if module is in cache
104
+ /******/ var cachedModule = __webpack_module_cache__[moduleId];
105
+ /******/ if (cachedModule !== undefined) {
106
+ /******/ return cachedModule.exports;
107
+ /******/ }
108
+ /******/ // Create a new module (and put it into the cache)
109
+ /******/ var module = __webpack_module_cache__[moduleId] = {
110
+ /******/ // no module.id needed
111
+ /******/ // no module.loaded needed
112
+ /******/ exports: {}
113
+ /******/ };
114
+ /******/
115
+ /******/ // Execute the module function
116
+ /******/ var threw = true;
117
+ /******/ try {
118
+ /******/ __webpack_modules__[moduleId].call(module.exports, module, module.exports, __nccwpck_require__);
119
+ /******/ threw = false;
120
+ /******/ } finally {
121
+ /******/ if(threw) delete __webpack_module_cache__[moduleId];
122
+ /******/ }
123
+ /******/
124
+ /******/ // Return the exports of the module
125
+ /******/ return module.exports;
126
+ /******/ }
127
+ /******/
128
+ /******/ // expose the modules object (__webpack_modules__)
129
+ /******/ __nccwpck_require__.m = __webpack_modules__;
130
+ /******/
131
+ /************************************************************************/
132
+ /******/ /* webpack/runtime/create fake namespace object */
133
+ /******/ (() => {
134
+ /******/ var getProto = Object.getPrototypeOf ? (obj) => (Object.getPrototypeOf(obj)) : (obj) => (obj.__proto__);
135
+ /******/ var leafPrototypes;
136
+ /******/ // create a fake namespace object
137
+ /******/ // mode & 1: value is a module id, require it
138
+ /******/ // mode & 2: merge all properties of value into the ns
139
+ /******/ // mode & 4: return value when already ns object
140
+ /******/ // mode & 16: return value when it's Promise-like
141
+ /******/ // mode & 8|1: behave like require
142
+ /******/ __nccwpck_require__.t = function(value, mode) {
143
+ /******/ if(mode & 1) value = this(value);
144
+ /******/ if(mode & 8) return value;
145
+ /******/ if(typeof value === 'object' && value) {
146
+ /******/ if((mode & 4) && value.__esModule) return value;
147
+ /******/ if((mode & 16) && typeof value.then === 'function') return value;
148
+ /******/ }
149
+ /******/ var ns = Object.create(null);
150
+ /******/ __nccwpck_require__.r(ns);
151
+ /******/ var def = {};
152
+ /******/ leafPrototypes = leafPrototypes || [null, getProto({}), getProto([]), getProto(getProto)];
153
+ /******/ for(var current = mode & 2 && value; typeof current == 'object' && !~leafPrototypes.indexOf(current); current = getProto(current)) {
154
+ /******/ Object.getOwnPropertyNames(current).forEach((key) => (def[key] = () => (value[key])));
155
+ /******/ }
156
+ /******/ def['default'] = () => (value);
157
+ /******/ __nccwpck_require__.d(ns, def);
158
+ /******/ return ns;
159
+ /******/ };
160
+ /******/ })();
161
+ /******/
162
+ /******/ /* webpack/runtime/define property getters */
163
+ /******/ (() => {
164
+ /******/ // define getter functions for harmony exports
165
+ /******/ __nccwpck_require__.d = (exports, definition) => {
166
+ /******/ for(var key in definition) {
167
+ /******/ if(__nccwpck_require__.o(definition, key) && !__nccwpck_require__.o(exports, key)) {
168
+ /******/ Object.defineProperty(exports, key, { enumerable: true, get: definition[key] });
169
+ /******/ }
170
+ /******/ }
171
+ /******/ };
172
+ /******/ })();
173
+ /******/
174
+ /******/ /* webpack/runtime/ensure chunk */
175
+ /******/ (() => {
176
+ /******/ __nccwpck_require__.f = {};
177
+ /******/ // This file contains only the entry chunk.
178
+ /******/ // The chunk loading function for additional chunks
179
+ /******/ __nccwpck_require__.e = (chunkId) => {
180
+ /******/ return Promise.all(Object.keys(__nccwpck_require__.f).reduce((promises, key) => {
181
+ /******/ __nccwpck_require__.f[key](chunkId, promises);
182
+ /******/ return promises;
183
+ /******/ }, []));
184
+ /******/ };
185
+ /******/ })();
186
+ /******/
187
+ /******/ /* webpack/runtime/get javascript chunk filename */
188
+ /******/ (() => {
189
+ /******/ // This function allow to reference async chunks
190
+ /******/ __nccwpck_require__.u = (chunkId) => {
191
+ /******/ // return url for filenames based on template
192
+ /******/ return "" + chunkId + ".index.js";
193
+ /******/ };
194
+ /******/ })();
195
+ /******/
196
+ /******/ /* webpack/runtime/hasOwnProperty shorthand */
197
+ /******/ (() => {
198
+ /******/ __nccwpck_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))
199
+ /******/ })();
200
+ /******/
201
+ /******/ /* webpack/runtime/make namespace object */
202
+ /******/ (() => {
203
+ /******/ // define __esModule on exports
204
+ /******/ __nccwpck_require__.r = (exports) => {
205
+ /******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
206
+ /******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
207
+ /******/ }
208
+ /******/ Object.defineProperty(exports, '__esModule', { value: true });
209
+ /******/ };
210
+ /******/ })();
211
+ /******/
212
+ /******/ /* webpack/runtime/compat */
213
+ /******/
214
+ /******/ if (typeof __nccwpck_require__ !== 'undefined') __nccwpck_require__.ab = new URL('.', import.meta.url).pathname.slice(import.meta.url.match(/^file:\/\/\/\w:/) ? 1 : 0, -1) + "/";
215
+ /******/
216
+ /******/ /* webpack/runtime/import chunk loading */
217
+ /******/ (() => {
218
+ /******/ // no baseURI
219
+ /******/
220
+ /******/ // object to store loaded and loading chunks
221
+ /******/ // undefined = chunk not loaded, null = chunk preloaded/prefetched
222
+ /******/ // [resolve, Promise] = chunk loading, 0 = chunk loaded
223
+ /******/ var installedChunks = {
224
+ /******/ 792: 0
225
+ /******/ };
226
+ /******/
227
+ /******/ var installChunk = (data) => {
228
+ /******/ var {ids, modules, runtime} = data;
229
+ /******/ // add "modules" to the modules object,
230
+ /******/ // then flag all "ids" as loaded and fire callback
231
+ /******/ var moduleId, chunkId, i = 0;
232
+ /******/ for(moduleId in modules) {
233
+ /******/ if(__nccwpck_require__.o(modules, moduleId)) {
234
+ /******/ __nccwpck_require__.m[moduleId] = modules[moduleId];
235
+ /******/ }
236
+ /******/ }
237
+ /******/ if(runtime) runtime(__nccwpck_require__);
238
+ /******/ for(;i < ids.length; i++) {
239
+ /******/ chunkId = ids[i];
240
+ /******/ if(__nccwpck_require__.o(installedChunks, chunkId) && installedChunks[chunkId]) {
241
+ /******/ installedChunks[chunkId][0]();
242
+ /******/ }
243
+ /******/ installedChunks[ids[i]] = 0;
244
+ /******/ }
245
+ /******/
246
+ /******/ }
247
+ /******/
248
+ /******/ __nccwpck_require__.f.j = (chunkId, promises) => {
249
+ /******/ // import() chunk loading for javascript
250
+ /******/ var installedChunkData = __nccwpck_require__.o(installedChunks, chunkId) ? installedChunks[chunkId] : undefined;
251
+ /******/ if(installedChunkData !== 0) { // 0 means "already installed".
252
+ /******/
253
+ /******/ // a Promise means "currently loading".
254
+ /******/ if(installedChunkData) {
255
+ /******/ promises.push(installedChunkData[1]);
256
+ /******/ } else {
257
+ /******/ if(true) { // all chunks have JS
258
+ /******/ // setup Promise in chunk cache
259
+ /******/ var promise = import("./" + __nccwpck_require__.u(chunkId)).then(installChunk, (e) => {
260
+ /******/ if(installedChunks[chunkId] !== 0) installedChunks[chunkId] = undefined;
261
+ /******/ throw e;
262
+ /******/ });
263
+ /******/ var promise = Promise.race([promise, new Promise((resolve) => (installedChunkData = installedChunks[chunkId] = [resolve]))])
264
+ /******/ promises.push(installedChunkData[1] = promise);
265
+ /******/ }
266
+ /******/ }
267
+ /******/ }
268
+ /******/ };
269
+ /******/
270
+ /******/ // no prefetching
271
+ /******/
272
+ /******/ // no preloaded
273
+ /******/
274
+ /******/ // no external install chunk
275
+ /******/
276
+ /******/ // no on chunks loaded
277
+ /******/ })();
278
+ /******/
279
+ /************************************************************************/
280
+ var __webpack_exports__ = {};
281
+
282
+ // EXTERNAL MODULE: external "fs"
283
+ var external_fs_ = __nccwpck_require__(9896);
284
+ // EXTERNAL MODULE: external "path"
285
+ var external_path_ = __nccwpck_require__(6928);
286
+ ;// CONCATENATED MODULE: external "os"
287
+ const external_os_namespaceObject = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("os");
288
+ ;// CONCATENATED MODULE: ./src/config.ts
289
+
290
+
291
+
292
+ /**
293
+ * Search for a private key from environment variables, config files, and mcporter config.
294
+ *
295
+ * Lookup order:
296
+ * 1. Environment variables (TRON_PRIVATE_KEY / EVM_PRIVATE_KEY / ETH_PRIVATE_KEY / PRIVATE_KEY)
297
+ * 2. Local config files (./x402-config.json, ~/.x402-config.json)
298
+ * 3. mcporter config (~/.mcporter/mcporter.json)
299
+ */
300
+ async function findPrivateKey(type) {
301
+ // 1. Check environment variables
302
+ if (type === "tron") {
303
+ if (process.env.TRON_PRIVATE_KEY)
304
+ return process.env.TRON_PRIVATE_KEY;
305
+ }
306
+ else {
307
+ if (process.env.EVM_PRIVATE_KEY)
308
+ return process.env.EVM_PRIVATE_KEY;
309
+ if (process.env.ETH_PRIVATE_KEY)
310
+ return process.env.ETH_PRIVATE_KEY;
311
+ }
312
+ if (process.env.PRIVATE_KEY)
313
+ return process.env.PRIVATE_KEY;
314
+ // 2. Check local config files
315
+ const configFiles = [external_path_.join(process.cwd(), "x402-config.json"), external_path_.join(external_os_namespaceObject.homedir(), ".x402-config.json")];
316
+ for (const file of configFiles) {
317
+ if (external_fs_.existsSync(file)) {
318
+ try {
319
+ const config = JSON.parse(external_fs_.readFileSync(file, "utf8"));
320
+ if (type === "tron") {
321
+ const key = config.tron_private_key || config.private_key;
322
+ if (key)
323
+ return key;
324
+ }
325
+ else {
326
+ const key = config.evm_private_key || config.eth_private_key || config.private_key;
327
+ if (key)
328
+ return key;
329
+ }
330
+ }
331
+ catch (e) {
332
+ /* ignore */
333
+ }
334
+ }
335
+ }
336
+ // 3. Check mcporter config
337
+ const mcporterPath = external_path_.join(external_os_namespaceObject.homedir(), ".mcporter", "mcporter.json");
338
+ if (external_fs_.existsSync(mcporterPath)) {
339
+ try {
340
+ const config = JSON.parse(external_fs_.readFileSync(mcporterPath, "utf8"));
341
+ if (config.mcpServers) {
342
+ for (const serverName in config.mcpServers) {
343
+ const s = config.mcpServers[serverName];
344
+ if (type === "tron" && s?.env?.TRON_PRIVATE_KEY)
345
+ return s.env.TRON_PRIVATE_KEY;
346
+ if (type === "evm" && (s?.env?.EVM_PRIVATE_KEY || s?.env?.ETH_PRIVATE_KEY)) {
347
+ return s.env.EVM_PRIVATE_KEY || s.env.ETH_PRIVATE_KEY;
348
+ }
349
+ if (s?.env?.PRIVATE_KEY)
350
+ return s.env.PRIVATE_KEY;
351
+ }
352
+ }
353
+ }
354
+ catch (e) {
355
+ /* ignore */
356
+ }
357
+ }
358
+ return undefined;
359
+ }
360
+ /**
361
+ * Search for TronGrid API key from environment variables, config files, and mcporter config.
362
+ */
363
+ async function findApiKey() {
364
+ if (process.env.TRON_GRID_API_KEY)
365
+ return process.env.TRON_GRID_API_KEY;
366
+ const configFiles = [external_path_.join(process.cwd(), "x402-config.json"), external_path_.join(external_os_namespaceObject.homedir(), ".x402-config.json")];
367
+ for (const file of configFiles) {
368
+ if (external_fs_.existsSync(file)) {
369
+ try {
370
+ const config = JSON.parse(external_fs_.readFileSync(file, "utf8"));
371
+ const key = config.tron_grid_api_key || config.api_key;
372
+ if (key)
373
+ return key;
374
+ }
375
+ catch (e) {
376
+ /* ignore */
377
+ }
378
+ }
379
+ }
380
+ const mcporterPath = external_path_.join(external_os_namespaceObject.homedir(), ".mcporter", "mcporter.json");
381
+ if (external_fs_.existsSync(mcporterPath)) {
382
+ try {
383
+ const config = JSON.parse(external_fs_.readFileSync(mcporterPath, "utf8"));
384
+ if (config.mcpServers) {
385
+ for (const serverName in config.mcpServers) {
386
+ const s = config.mcpServers[serverName];
387
+ if (s?.env?.TRON_GRID_API_KEY)
388
+ return s.env.TRON_GRID_API_KEY;
389
+ }
390
+ }
391
+ }
392
+ catch (e) {
393
+ /* ignore */
394
+ }
395
+ }
396
+ return undefined;
397
+ }
398
+
399
+ ;// CONCATENATED MODULE: ./src/client.ts
400
+
401
+ /**
402
+ * Create a fully configured X402Client with TRON and EVM payment mechanisms registered.
403
+ *
404
+ * Automatically discovers private keys from environment variables, config files,
405
+ * and mcporter config. You can also pass keys explicitly.
406
+ */
407
+ async function createX402Client(options = {}) {
408
+ const { TronClientSigner, EvmClientSigner, X402Client, ExactTronClientMechanism, ExactEvmClientMechanism, ExactPermitTronClientMechanism, ExactPermitEvmClientMechanism, SufficientBalancePolicy, } = await __nccwpck_require__.e(/* import() */ 743).then(__nccwpck_require__.bind(__nccwpck_require__, 3743));
409
+ const tronKey = options.tronPrivateKey ?? (await findPrivateKey("tron"));
410
+ const evmKey = options.evmPrivateKey ?? (await findPrivateKey("evm"));
411
+ const apiKey = options.tronGridApiKey ?? (await findApiKey());
412
+ if (apiKey)
413
+ process.env.TRON_GRID_API_KEY = apiKey;
414
+ const log = options.silent ? () => { } : (...args) => console.error("[x402]", ...args);
415
+ const client = new X402Client();
416
+ if (tronKey) {
417
+ const signer = new TronClientSigner(tronKey);
418
+ const networks = ["mainnet", "nile", "shasta", "*"];
419
+ for (const net of networks) {
420
+ const networkId = net === "*" ? "tron:*" : `tron:${net}`;
421
+ client.register(networkId, new ExactTronClientMechanism(signer));
422
+ client.register(networkId, new ExactPermitTronClientMechanism(signer));
423
+ }
424
+ log("TRON mechanisms enabled.");
425
+ }
426
+ if (evmKey) {
427
+ const signer = new EvmClientSigner(evmKey);
428
+ client.register("eip155:*", new ExactEvmClientMechanism(signer));
429
+ client.register("eip155:*", new ExactPermitEvmClientMechanism(signer));
430
+ log("EVM mechanisms enabled.");
431
+ }
432
+ client.registerPolicy(new SufficientBalancePolicy(client));
433
+ return client;
434
+ }
435
+ /**
436
+ * Create a fetch client that automatically handles HTTP 402 Payment Required responses.
437
+ *
438
+ * Usage:
439
+ * ```ts
440
+ * const fetchClient = await createX402FetchClient();
441
+ * const response = await fetchClient.request("https://paid-api.com/endpoint", {
442
+ * method: "POST",
443
+ * headers: { "Content-Type": "application/json" },
444
+ * body: JSON.stringify({ key: "value" }),
445
+ * });
446
+ * ```
447
+ */
448
+ async function createX402FetchClient(options = {}) {
449
+ const { X402FetchClient } = await __nccwpck_require__.e(/* import() */ 743).then(__nccwpck_require__.bind(__nccwpck_require__, 3743));
450
+ const client = await createX402Client(options);
451
+ return new X402FetchClient(client);
452
+ }
453
+ /**
454
+ * High-level helper: invoke an x402-enabled endpoint and return the parsed response.
455
+ *
456
+ * Supports two modes:
457
+ * - **Entrypoint mode**: provide `entrypoint` to call `{url}/entrypoints/{entrypoint}/invoke`
458
+ * - **Direct mode**: omit `entrypoint` to request the URL directly
459
+ *
460
+ * Usage:
461
+ * ```ts
462
+ * // Entrypoint mode
463
+ * const result = await invokeEndpoint("https://api.example.com", {
464
+ * entrypoint: "chat",
465
+ * input: { prompt: "hello" },
466
+ * });
467
+ *
468
+ * // Direct mode
469
+ * const result = await invokeEndpoint("https://api.example.com/some/path", {
470
+ * method: "GET",
471
+ * });
472
+ * ```
473
+ */
474
+ async function invokeEndpoint(url, options = {}) {
475
+ const fetchClient = await createX402FetchClient(options.clientOptions);
476
+ let finalUrl = url;
477
+ let finalMethod = options.method || "GET";
478
+ let finalBody = undefined;
479
+ if (options.entrypoint) {
480
+ const baseUrl = url.endsWith("/") ? url.slice(0, -1) : url;
481
+ finalUrl = `${baseUrl}/entrypoints/${options.entrypoint}/invoke`;
482
+ finalMethod = "POST";
483
+ finalBody = JSON.stringify({ input: options.input ?? {} });
484
+ }
485
+ else if (options.input) {
486
+ finalBody = typeof options.input === "string" ? options.input : JSON.stringify(options.input);
487
+ }
488
+ const response = await fetchClient.request(finalUrl, {
489
+ method: finalMethod,
490
+ headers: { "Content-Type": "application/json" },
491
+ body: finalBody,
492
+ });
493
+ const contentType = response.headers.get("content-type") || "";
494
+ let body;
495
+ if (contentType.includes("application/json")) {
496
+ body = await response.json();
497
+ }
498
+ else {
499
+ body = await response.text();
500
+ }
501
+ return {
502
+ status: response.status,
503
+ headers: Object.fromEntries(response.headers.entries()),
504
+ body,
505
+ };
506
+ }
507
+
508
+ ;// CONCATENATED MODULE: ./src/cli.ts
509
+
510
+
511
+
512
+
513
+
514
+ async function main() {
515
+ const args = process.argv.slice(2);
516
+ const options = {};
517
+ for (let i = 0; i < args.length; i++) {
518
+ const arg = args[i];
519
+ if (arg.startsWith("--")) {
520
+ const key = arg.slice(2);
521
+ const value = args[i + 1];
522
+ if (value && !value.startsWith("--")) {
523
+ options[key] = value;
524
+ i++;
525
+ }
526
+ else {
527
+ options[key] = "true";
528
+ }
529
+ }
530
+ }
531
+ const url = options.url;
532
+ const entrypoint = options.entrypoint;
533
+ const inputRaw = options.input;
534
+ const methodArg = options.method;
535
+ const tronKey = await findPrivateKey("tron");
536
+ const evmKey = await findPrivateKey("evm");
537
+ const apiKey = await findApiKey();
538
+ if (options.check === "true" || options.status === "true") {
539
+ const { TronClientSigner, EvmClientSigner } = await __nccwpck_require__.e(/* import() */ 743).then(__nccwpck_require__.bind(__nccwpck_require__, 3743));
540
+ if (tronKey) {
541
+ const signer = new TronClientSigner(tronKey);
542
+ console.error(`[OK] TRON Wallet: ${signer.getAddress()}`);
543
+ if (apiKey)
544
+ console.error(`[OK] TRON_GRID_API_KEY is configured.`);
545
+ }
546
+ if (evmKey) {
547
+ const signer = new EvmClientSigner(evmKey);
548
+ console.error(`[OK] EVM Wallet: ${signer.getAddress()}`);
549
+ }
550
+ if (!tronKey && !evmKey) {
551
+ console.error("[WARN] No private keys found. Configure TRON_PRIVATE_KEY or EVM_PRIVATE_KEY.");
552
+ }
553
+ process.exit(0);
554
+ }
555
+ if (!url) {
556
+ console.error("Error: --url is required");
557
+ process.exit(1);
558
+ }
559
+ // Redirect console.log to console.error to prevent library pollution of STDOUT
560
+ console.log = console.error;
561
+ let finalUrl = url;
562
+ let finalMethod = methodArg || "GET";
563
+ let finalBody = undefined;
564
+ if (entrypoint) {
565
+ const baseUrl = url.endsWith("/") ? url.slice(0, -1) : url;
566
+ finalUrl = `${baseUrl}/entrypoints/${entrypoint}/invoke`;
567
+ finalMethod = "POST";
568
+ let inputData = {};
569
+ if (inputRaw) {
570
+ try {
571
+ inputData = JSON.parse(inputRaw);
572
+ }
573
+ catch (e) {
574
+ inputData = inputRaw;
575
+ }
576
+ }
577
+ finalBody = JSON.stringify({ input: inputData });
578
+ }
579
+ else {
580
+ if (methodArg)
581
+ finalMethod = methodArg.toUpperCase();
582
+ if (inputRaw)
583
+ finalBody = inputRaw;
584
+ }
585
+ try {
586
+ const fetchClient = await createX402FetchClient({
587
+ tronPrivateKey: tronKey,
588
+ evmPrivateKey: evmKey,
589
+ tronGridApiKey: apiKey,
590
+ });
591
+ const requestInit = {
592
+ method: finalMethod,
593
+ headers: { "Content-Type": "application/json" },
594
+ body: finalBody,
595
+ };
596
+ console.error(`[x402] Requesting: ${finalMethod} ${finalUrl}`);
597
+ const response = await fetchClient.request(finalUrl, requestInit);
598
+ const contentType = response.headers.get("content-type") || "";
599
+ let responseBody;
600
+ if (contentType.includes("application/json")) {
601
+ responseBody = await response.json();
602
+ }
603
+ else if (contentType.includes("image/") || contentType.includes("application/octet-stream")) {
604
+ const buffer = Buffer.from(await response.arrayBuffer());
605
+ const tmpDir = external_os_namespaceObject.tmpdir();
606
+ const isImage = contentType.includes("image/");
607
+ const ext = isImage ? contentType.split("/")[1]?.split(";")[0] || "bin" : "bin";
608
+ const fileName = `x402_${isImage ? "image" : "binary"}_${Date.now()}_${Math.random().toString(36).substring(7)}.${ext}`;
609
+ const filePath = external_path_.join(tmpDir, fileName);
610
+ external_fs_.writeFileSync(filePath, buffer);
611
+ console.error(`[x402] Binary data saved to: ${filePath}`);
612
+ responseBody = { file_path: filePath, content_type: contentType, bytes: buffer.length };
613
+ }
614
+ else {
615
+ responseBody = await response.text();
616
+ }
617
+ process.stdout.write(JSON.stringify({
618
+ status: response.status,
619
+ headers: Object.fromEntries(response.headers.entries()),
620
+ body: responseBody,
621
+ }, null, 2) + "\n");
622
+ }
623
+ catch (error) {
624
+ let message = error.message || "Unknown error";
625
+ let stack = error.stack || "";
626
+ // Sanitize any potential private key leaks in error messages/stacks
627
+ const keys = [tronKey, evmKey].filter(Boolean);
628
+ for (const key of keys) {
629
+ const escapedKey = key.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
630
+ const keyRegex = new RegExp(escapedKey, "g");
631
+ message = message.replace(keyRegex, "[REDACTED]");
632
+ stack = stack.replace(keyRegex, "[REDACTED]");
633
+ }
634
+ console.error(`[x402] Error: ${message}`);
635
+ process.stdout.write(JSON.stringify({
636
+ error: message,
637
+ stack: stack,
638
+ }, null, 2) + "\n");
639
+ process.exit(1);
640
+ }
641
+ }
642
+ main();
643
+