@witnet/sdk 1.2.2 → 1.2.4

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 (75) hide show
  1. package/.env_witnet +2 -1
  2. package/dist/package.json +4 -4
  3. package/dist/src/bin/helpers.js +1 -1
  4. package/dist/src/index.js +1 -1
  5. package/dist/src/lib/crypto/account.js +1 -1
  6. package/dist/src/lib/crypto/coinbase.js +1 -1
  7. package/dist/src/lib/crypto/index.js +1 -1
  8. package/dist/src/lib/crypto/interfaces.js +1 -1
  9. package/dist/src/lib/crypto/payloads/DataRequestPayload.js +1 -1
  10. package/dist/src/lib/crypto/payloads/StakePayload.js +1 -1
  11. package/dist/src/lib/crypto/payloads/UnstakePayload.js +1 -1
  12. package/dist/src/lib/crypto/payloads/ValueTransferPayload.js +1 -1
  13. package/dist/src/lib/crypto/payloads.js +1 -1
  14. package/dist/src/lib/crypto/signer.js +1 -1
  15. package/dist/src/lib/crypto/transmitters/DataRequests.js +1 -1
  16. package/dist/src/lib/crypto/transmitters/StakeDeposits.js +1 -1
  17. package/dist/src/lib/crypto/transmitters/StakeWithdrawals.js +1 -1
  18. package/dist/src/lib/crypto/transmitters/ValueTransfers.js +1 -1
  19. package/dist/src/lib/crypto/transmitters.js +1 -1
  20. package/dist/src/lib/crypto/types.js +1 -1
  21. package/dist/src/lib/crypto/utils.js +1 -1
  22. package/dist/src/lib/crypto/wallet.js +1 -1
  23. package/dist/src/lib/index.js +1 -1
  24. package/dist/src/lib/radon/ccdr/eth.js +1 -1
  25. package/dist/src/lib/radon/ccdr/index.js +1 -1
  26. package/dist/src/lib/radon/ccdr/wit.js +1 -1
  27. package/dist/src/lib/radon/filters.js +1 -1
  28. package/dist/src/lib/radon/index.js +1 -1
  29. package/dist/src/lib/radon/reducers.js +1 -1
  30. package/dist/src/lib/radon/types.js +1 -1
  31. package/dist/src/lib/radon/utils.d.ts.map +1 -1
  32. package/dist/src/lib/radon/utils.js +1 -1
  33. package/dist/src/lib/rest/kermit.d.ts.map +1 -1
  34. package/dist/src/lib/rest/kermit.js +2 -4
  35. package/dist/src/lib/rest/types.js +1 -1
  36. package/dist/src/lib/rpc/index.js +1 -1
  37. package/dist/src/lib/rpc/nodes.js +1 -1
  38. package/dist/src/lib/rpc/provider.js +1 -1
  39. package/dist/src/lib/rpc/types.js +1 -1
  40. package/dist/src/lib/types.js +1 -1
  41. package/dist/src/lib/utils.js +1 -1
  42. package/package.json +4 -4
  43. package/scripts/clean.cjs +21 -21
  44. package/scripts/postinstall.cjs +9 -9
  45. package/src/bin/bots/watcher.cjs +365 -354
  46. package/src/bin/cli/history.cjs +31 -31
  47. package/src/bin/cli/inspect.js +581 -581
  48. package/src/bin/cli/network.js +695 -695
  49. package/src/bin/cli/nodes.js +424 -424
  50. package/src/bin/cli/radon.js +1124 -1122
  51. package/src/bin/cli/wallet.js +1362 -1362
  52. package/src/bin/helpers.js +974 -974
  53. package/src/bin/index.js +328 -328
  54. package/witnet/assets/_index.cjs +0 -5
  55. package/witnet/assets/_requests.cjs +0 -25
  56. package/witnet/assets/_sources.cjs +0 -36
  57. package/witnet/assets/_templates.cjs +0 -36
  58. package/witnet/assets/index.cjs +0 -4
  59. package/witnet/assets/modals/index.cjs +0 -7
  60. package/witnet/assets/modals/web3/btc.cjs +0 -0
  61. package/witnet/assets/modals/web3/eth.cjs +0 -27
  62. package/witnet/assets/modals/web3/ipfs.cjs +0 -22
  63. package/witnet/assets/modals/web3/sol.cjs +0 -0
  64. package/witnet/assets/modals/web3/wit.cjs +0 -28
  65. package/witnet/assets/requests.cjs +0 -49
  66. package/witnet/witnet copy.proto +0 -457
  67. package/witnet/witnet.proto +0 -456
  68. package/witnet/witnet.proto.json +0 -1322
  69. package/witnet/witnet_toolkit-1.6.7-x86_64-pc-windows-msvc.exe +0 -0
  70. package/witnet/witnet_toolkit-1.7.1-x86_64-pc-windows-msvc.exe +0 -0
  71. package/witnet/witnet_toolkit-2.0.0-rc.7-x86_64-pc-windows-msvc.exe +0 -0
  72. package/witnet/witnet_toolkit-2.0.2-x86_64-pc-windows-msvc.exe +0 -0
  73. package/witnet/witnet_toolkit-2.0.21-x86_64-pc-windows-msvc.exe +0 -0
  74. package/witnet/witnet_toolkit-2.0.7-x86_64-pc-windows-msvc.exe +0 -0
  75. package/witnet/witnet_toolkit-2.0.8-x86_64-pc-windows-msvc.exe +0 -0
@@ -1,1122 +1,1124 @@
1
- import fs from "node:fs";
2
- import { createRequire } from "node:module";
3
- import dotenv from "dotenv";
4
- dotenv.config({ quiet: true })
5
- import path from "node:path";
6
- import inquirer from "inquirer";
7
- import merge from "lodash.merge";
8
-
9
- const require = createRequire(import.meta.url);
10
-
11
- import { utils, Witnet } from "../../../dist/src/index.js";
12
- import { default as legacy } from "../../../witnet/assets/index.cjs";
13
- import * as helpers from "../helpers.js";
14
-
15
- const WITNET_ASSETS_PATH =
16
- process.env.WITNET_SDK_RADON_ASSETS_PATH || "../../../../../witnet/assets";
17
-
18
- /// ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
19
- /// CLI SUBMODULE CONSTANTS ===========================================================================================
20
-
21
- const isModuleInitialized = fs.existsSync("./witnet/assets/index.cjs");
22
-
23
- export const flags = {
24
- module: {
25
- hint: "Package where to fetch Radon assets from (supersedes --legacy).",
26
- param: "NPM_PACKAGE",
27
- },
28
- };
29
-
30
- export const router = isModuleInitialized
31
- ? {
32
- assets: {
33
- hint: "List available Witnet Radon assets.",
34
- params: "[RADON_ASSETS ...]",
35
- options: {
36
- filter: {
37
- hint: "Restrict output to name-matching assets.",
38
- },
39
- legacy: {
40
- hint: "List only those declared in witnet/assets folder.",
41
- },
42
- modals: {
43
- hint: "Restrict output to Radon modals.",
44
- },
45
- requests: {
46
- hint: "Restrict output to Radon requests.",
47
- },
48
- templates: {
49
- hint: "Restrict output to Radon templates.",
50
- },
51
- },
52
- },
53
- check: {
54
- hint: "Check correctness of Witnet Radon artifacts declared in witnet/assets folder.",
55
- params: [],
56
- options: {},
57
- },
58
- decode: {
59
- hint: "Break down specs of one or more Radon assets.",
60
- params: ["RAD_BYTECODE | RAD_HASH | RADON_ASSET"],
61
- options: {
62
- bytecode: {
63
- hint: "Outputs RAD bytecode as hex string (supersedes --json)."
64
- },
65
- json: {
66
- hint: "Outputs data in JSON format.",
67
- },
68
- headline: {
69
- hint: "Settles output report headline.",
70
- param: ":string",
71
- },
72
- indent: {
73
- hint: "Prefixes given number of white spaces for every output line.",
74
- param: ":number",
75
- },
76
- },
77
- },
78
- "dry-run": {
79
- hint: "Simulate resolution of one or more Radon assets, as if solved by the Wit/Oracle.",
80
- params: ["RAD_BYTECODE | RAD_HASH | RADON_ASSET"],
81
- options: {
82
- default: {
83
- hint: "Use default sample parameters on parametrized Radon assets.",
84
- },
85
- json: {
86
- hint: "Outputs data in JSON format.",
87
- },
88
- headline: {
89
- hint: "Settles output report headline.",
90
- param: ":string",
91
- },
92
- indent: {
93
- hint: "Prefixes given number of white spaces for every output line.",
94
- param: ":number",
95
- },
96
- verbose: {
97
- hint: "Outputs detailed dry-run report.",
98
- },
99
- },
100
- },
101
- }
102
- : {
103
- assets: {
104
- hint: "List available Witnet Radon assets.",
105
- params: "[RADON_ASSETS ...]",
106
- options: {
107
- filter: {
108
- hint: "Restrict output to name-matching assets.",
109
- },
110
- legacy: {
111
- hint: "List only those declared in witnet/assets folder.",
112
- },
113
- },
114
- },
115
- decode: {
116
- hint: "Break down specs of one or more Radon assets.",
117
- params: ["RAD_BYTECODE | RAD_HASH | RADON_ASSET"],
118
- options: {
119
- json: {
120
- hint: "Outputs data in JSON format.",
121
- },
122
- headline: {
123
- hint: "Settles output report headline.",
124
- param: ":string",
125
- },
126
- indent: {
127
- hint: "Prefixes given number of white spaces for every output line.",
128
- param: ":number",
129
- },
130
- },
131
- },
132
- "dry-run": {
133
- hint: "Simulate resolution of one or more Radon assets, as if solved by the Wit/Oracle.",
134
- params: ["RAD_BYTECODE | RAD_HASH | RADON_ASSET"],
135
- options: {
136
- json: {
137
- hint: "Outputs data in JSON format.",
138
- },
139
- headline: {
140
- hint: "Settles output report headline.",
141
- param: ":string",
142
- },
143
- indent: {
144
- hint: "Prefixes given number of white spaces for every output line.",
145
- param: ":number",
146
- },
147
- verbose: {
148
- hint: "Outputs detailed dry-run report.",
149
- },
150
- },
151
- },
152
- init: {
153
- hint: "Initialize a Witnet Radon workspace in this project.",
154
- },
155
- };
156
-
157
- export const subcommands = {
158
- assets,
159
- init,
160
- check,
161
- decode,
162
- "dry-run": dryrun,
163
- };
164
-
165
- ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
166
- /// CLI SUBMODULE COMMANDS ============================================================================================
167
-
168
- async function init() {
169
- if (!fs.existsSync("./witnet/assets/")) {
170
- fs.mkdirSync("./witnet/assets", { recursive: true });
171
- }
172
- if (!fs.existsSync(".env_witnet")) {
173
- fs.cpSync("node_modules/@witnet/sdk/.env_witnet", ".env_witnet");
174
- }
175
- if (!fs.existsSync("./witnet/assets/index.js")) {
176
- fs.cpSync(
177
- "node_modules/@witnet/sdk/witnet/assets/_index.js",
178
- "./witnet/assets/index.js",
179
- );
180
- }
181
- if (!fs.existsSync("./witnet/assets/requests.js")) {
182
- fs.cpSync(
183
- "node_modules/@witnet/sdk/witnet/assets/_requests.js",
184
- "./witnet/assets/requests.js",
185
- );
186
- }
187
- if (!fs.existsSync("./witnet/assets/sources.js")) {
188
- fs.cpSync(
189
- "node_modules/@witnet/sdk/witnet/assets/_sources.js",
190
- "./witnet/assets/sources.js",
191
- );
192
- }
193
- if (!fs.existsSync("./witnet/assets/templates.js")) {
194
- fs.cpSync(
195
- "node_modules/@witnet/sdk/witnet/assets/_templates.js",
196
- "./witnet/assets/templates.js",
197
- );
198
- }
199
- console.info(
200
- `Initialized Witnet Radon workspace at folder ${process.cwd()}/witnet/assets`,
201
- );
202
- }
203
-
204
- async function assets(options = {}, [...patterns]) {
205
- helpers.traceHeader(
206
- `${options?.module ? options.module.toUpperCase() : path.basename(process.cwd()).toUpperCase()} RADON ASSETS`,
207
- helpers.colors.white,
208
- );
209
- const assets = clearEmptyBranches(
210
- options?.module ? require(`${options.module}/assets`) : loadAssets(options),
211
- patterns,
212
- options,
213
- );
214
- if (assets && Object.keys(assets).length > 0) {
215
- traceWitnetArtifacts(assets, patterns, " ", options);
216
- } else {
217
- console.info("> No custom Radon assets declared just yet.");
218
- }
219
- }
220
- /// -------------------------------------------------------------------------------------------------------------------
221
-
222
- async function check() {
223
- if (!isModuleInitialized) {
224
- throw new Error(
225
- `No Witnet Radon workspace has been initialized. Please, run ${white("npx witsdk radon init")} if willing to declare your own Radon assets.`,
226
- );
227
- }
228
- try {
229
- const assets = loadAssets({ legacy: true });
230
- const [modals, requests, sources, templates] = [
231
- helpers.countLeaves(Witnet.Radon.RadonModal, assets),
232
- helpers.countLeaves(Witnet.Radon.RadonRequest, assets),
233
- helpers.countLeaves(Witnet.Radon.RadonRetrieval, assets?.sources),
234
- helpers.countLeaves(Witnet.Radon.RadonTemplate, assets),
235
- ];
236
- if (modals > 0) console.info("> Radon modals: ", modals);
237
- if (sources > 0) console.info("> Radon sources: ", sources);
238
- if (requests > 0) console.info("> Radon requests: ", requests);
239
- if (templates > 0) console.info("> Radon templates:", templates);
240
-
241
- if (modals + sources + requests + templates === 0) {
242
- console.info("-----------------------------");
243
- console.info("No Radon assets declared yet!");
244
- } else {
245
- console.info("--------------------------------------");
246
- console.info("All Radon assets checked successfully!");
247
- }
248
- } catch (e) {
249
- console.error("Radon assets verification failed:");
250
- console.info("----------------------------------");
251
- console.info(e);
252
- }
253
- }
254
- /// -------------------------------------------------------------------------------------------------------------------
255
-
256
- async function decode(options = {}, args = []) {
257
- if (args.length === 0) {
258
- throw Error("No Radon asset was specified");
259
- }
260
- const asset = args[0];
261
- if (helpers.isHexString(asset)) {
262
- try {
263
- const request = Witnet.Radon.RadonRequest.fromBytecode(asset);
264
- traceWitnetRadonRequest(request, options);
265
- } catch (err) {
266
- console.error(err);
267
- if (
268
- (asset.startsWith("0x") && asset.length === 66) ||
269
- (!asset.startsWith("0x") && asset.length === 64)
270
- ) {
271
- // TODO: assume it's a DR_TX_HASH
272
- // TODO: assume it's a RAD_HASH
273
- }
274
- }
275
- } else {
276
- args = args.slice(1);
277
-
278
- const assets = options?.module
279
- ? require(`${options.module}/assets`)
280
- : loadAssets(options);
281
- const headline = options?.headline;
282
- const crafts = flattenRadonArtifacts(assets).filter(
283
- (craft) => craft.key.toLowerCase().indexOf(asset.toLowerCase()) >= 0,
284
- );
285
- if (crafts.length === 0) {
286
- throw Error(`No matched found for pattern "${asset}"`);
287
- }
288
- for (let { artifact, key } of crafts) {
289
- let prefix = "";
290
- if (artifact instanceof Witnet.Radon.RadonRequest) {
291
- prefix = "RadonRequest::";
292
- } else if (artifact instanceof Witnet.Radon.RadonModal) {
293
- artifact.providers = [...(args[0]?.split(";") || ["https://dummy"])];
294
- const modalArgs = [];
295
- let argIndex = 1;
296
- while (modalArgs.length < artifact.argsCount) {
297
- modalArgs.push(args[argIndex] || `{:${argIndex}}`);
298
- argIndex += 1;
299
- }
300
- artifact = artifact.buildRadonRequest(modalArgs);
301
- prefix = "RadonModal::";
302
- } else if (artifact instanceof Witnet.Radon.RadonTemplate) {
303
- const templateArgs = artifact.sources.map(({ argsCount }) =>
304
- Array.from({ length: argsCount }, (_, i) => `{:${i}}`),
305
- );
306
- artifact = artifact.buildRadonRequest(templateArgs);
307
- prefix = "RadonTemplate::";
308
- } else if (artifact instanceof Witnet.Radon.RadonRetrieval) {
309
- if (artifact.argsCount > 0) {
310
- const retrievalArgs = Array.from(
311
- { length: artifact.argsCount },
312
- (_, i) => `{:${i + 1}}`,
313
- );
314
- artifact = artifact.foldArgs(retrievalArgs);
315
- }
316
- artifact = new Witnet.Radon.RadonRequest({ sources: artifact });
317
- prefix = "RadonRetrieval::";
318
- }
319
- if (!headline) {
320
- options.headline = `${prefix}${key}`;
321
- }
322
- traceWitnetRadonRequest(artifact, options);
323
- if (options?.verbose && key !== crafts[crafts.length - 1].key) {
324
- console.info(`${options?.indent || ""}${"─".repeat(150)}`);
325
- }
326
- console.info();
327
- }
328
- }
329
- }
330
- /// -------------------------------------------------------------------------------------------------------------------
331
-
332
- async function dryrun(options = {}, args = []) {
333
- if (args.length === 0) {
334
- throw Error("No Radon asset was specified");
335
- }
336
- const asset = args[0];
337
- if (helpers.isHexString(asset)) {
338
- try {
339
- const request = Witnet.Radon.RadonRequest.fromBytecode(asset);
340
- await traceWitnetRadonRequestDryRun(request, options);
341
- } catch {
342
- if (
343
- (asset.startsWith("0x") && asset.length === 66) ||
344
- (!asset.startsWith("0x") && asset.length === 64)
345
- ) {
346
- // TODO: assume it's a RAD_HASH, and try to retrieve the BYTECODE from the Witnet network
347
- }
348
- }
349
- } else {
350
- args = args.slice(1);
351
- const assets = options?.module
352
- ? require(`${options.module}/assets`)
353
- : loadAssets(options);
354
- const headline = options?.headline;
355
- const crafts = flattenRadonArtifacts(assets).filter(
356
- (craft) => craft.key.toLowerCase().indexOf(asset.toLowerCase()) >= 0,
357
- );
358
- if (crafts.length === 0) {
359
- throw Error(`No matched found for pattern "${asset}"`);
360
- }
361
- for (let { artifact, key } of crafts) {
362
- let prefix = "";
363
- if (artifact instanceof Witnet.Radon.RadonRequest) {
364
- prefix = "RadonRequest::";
365
- } else {
366
- let artifactArgs = [];
367
- if (artifact instanceof Witnet.Radon.RadonModal) {
368
- if (args.length < artifact.argsCount) {
369
- throw new Error(`missing parameters for Radon Modal.`);
370
- }
371
- artifact.providers = [...args[0].split(";")];
372
- const modalArgs = [];
373
- let argIndex = 1;
374
- while (modalArgs.length < artifact.argsCount) {
375
- modalArgs.push(args[argIndex]);
376
- argIndex += 1;
377
- }
378
- artifact = artifact.homogeneous
379
- ? artifact.buildRadonRequest(modalArgs)
380
- : artifact.buildRadonRequest([
381
- ...artifact.sources.map((source) =>
382
- modalArgs.slice(0, source.argsCount),
383
- ),
384
- ]);
385
- prefix = "RadonModal::";
386
- } else {
387
- if (!artifact?.samples) {
388
- console.error(
389
- `${artifact.constructor.name}::${key}: cannot dry-run if no sample parameters are declared.\n`,
390
- );
391
- continue;
392
- }
393
- if (options?.default) {
394
- artifactArgs = Object.values(artifact.samples)[0];
395
- } else {
396
- const prompt = inquirer.createPromptModule();
397
- const sample = await prompt([
398
- {
399
- choices: Object.keys(artifact.samples),
400
- message: `${artifact.constructor.name}::${key} args:`,
401
- name: "key",
402
- type: "list",
403
- },
404
- ]);
405
- artifactArgs = artifact.samples[sample.key];
406
- }
407
- if (artifact instanceof Witnet.Radon.RadonTemplate) {
408
- artifact = artifact.buildRadonRequest(artifactArgs);
409
- prefix = "RadonTemplate::";
410
- } else if (artifact instanceof Witnet.Radon.RadonRetrieval) {
411
- artifact = new Witnet.Radon.RadonRequest({
412
- sources: artifact.foldArgs(artifactArgs),
413
- });
414
- prefix = "RadonRetrieval::";
415
- }
416
- }
417
- }
418
- if (!headline) {
419
- options.headline = `${prefix}${key}`;
420
- }
421
- await traceWitnetRadonRequestDryRun(artifact, options);
422
- if (options?.verbose && key !== crafts[crafts.length - 1].key) {
423
- console.info(`${options?.indent || ""}${"─".repeat(150)}`);
424
- }
425
- console.info();
426
- }
427
- }
428
- }
429
- /// -------------------------------------------------------------------------------------------------------------------
430
-
431
- /// ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
432
- /// CLI SUBMODULE INTERNAL METHODS ------------------------------------------------------------------------------------
433
-
434
- const extractTypeName = (str) =>
435
- str
436
- ? str
437
- .split(/(?=[A-Z])/)
438
- .slice(1)
439
- .join("")
440
- : "Any";
441
-
442
- const stringifyFilter = (x, c) => {
443
- const color = c || helpers.colors.mcyan;
444
- return color(
445
- `${Witnet.Radon.filters.Opcodes[x.opcode]}(${x.args ? JSON.stringify(x.args) : ""})`,
446
- );
447
- };
448
-
449
- const stringifyReducer = (x, c) => {
450
- const color = c || helpers.colors.mcyan;
451
- return color(`${Witnet.Radon.reducers.Opcodes[x.opcode]}()`);
452
- };
453
-
454
- export function loadAssets(options) {
455
- const assets = options?.legacy ? {} : legacy;
456
- return isModuleInitialized
457
- ? merge(assets, require(`${WITNET_ASSETS_PATH}/index.cjs`))
458
- : assets;
459
- }
460
-
461
- function flattenRadonArtifacts(tree, headers) {
462
- if (!headers) headers = [];
463
- const matches = [];
464
- for (const key in tree) {
465
- if (
466
- tree[key] instanceof Witnet.Radon.RadonRetrieval ||
467
- tree[key] instanceof Witnet.Radon.RadonModal ||
468
- tree[key] instanceof Witnet.Radon.RadonRequest ||
469
- tree[key] instanceof Witnet.Radon.RadonTemplate
470
- ) {
471
- matches.push({
472
- key,
473
- artifact: tree[key],
474
- });
475
- } else if (typeof tree[key] === "object") {
476
- matches.push(...flattenRadonArtifacts(tree[key], [...headers, key]));
477
- }
478
- }
479
- return matches;
480
- }
481
-
482
- function countWitnetArtifacts(assets, args, options) {
483
- let counter = 0;
484
- Object.entries(assets).forEach(([key, value]) => {
485
- let include =
486
- (options?.modals && value instanceof Witnet.Radon.RadonModal) ||
487
- (options?.templates && value instanceof Witnet.Radon.RadonTemplate) ||
488
- (options?.retrievals && value instanceof Witnet.Radon.RadonRetrieval) ||
489
- (options?.requests && value instanceof Witnet.Radon.RadonRequest);
490
- if (
491
- !(
492
- options?.modals ||
493
- options?.templates ||
494
- options?.retrievals ||
495
- options?.requests
496
- )
497
- ) {
498
- include =
499
- value instanceof Witnet.Radon.RadonModal ||
500
- value instanceof Witnet.Radon.RadonRequest ||
501
- value instanceof Witnet.Radon.RadonTemplate ||
502
- value instanceof Witnet.Radon.RadonRetrieval;
503
- }
504
- if (
505
- include &&
506
- (!options?.filter ||
507
- !args ||
508
- args.length === 0 ||
509
- args.find((arg) => key.toLowerCase().indexOf(arg.toLowerCase()) >= 0))
510
- ) {
511
- counter++;
512
- } else if (typeof value === "object") {
513
- counter += countWitnetArtifacts(value, args, options);
514
- }
515
- });
516
- return counter;
517
- }
518
-
519
- function clearEmptyBranches(node, args, options) {
520
- if (node) {
521
- const assets = Object.fromEntries(
522
- Object.entries(node)
523
- .map(([key, value]) => {
524
- let include =
525
- (options?.modals && value instanceof Witnet.Radon.RadonModal) ||
526
- (options?.templates &&
527
- value instanceof Witnet.Radon.RadonTemplate) ||
528
- (options?.retrievals &&
529
- value instanceof Witnet.Radon.RadonRetrieval) ||
530
- (options?.requests && value instanceof Witnet.Radon.RadonRequest);
531
- if (
532
- !(
533
- options?.modals ||
534
- options?.templates ||
535
- options?.retrievals ||
536
- options?.requests
537
- )
538
- ) {
539
- include =
540
- value instanceof Witnet.Radon.RadonModal ||
541
- value instanceof Witnet.Radon.RadonRequest ||
542
- value instanceof Witnet.Radon.RadonTemplate ||
543
- value instanceof Witnet.Radon.RadonRetrieval;
544
- }
545
- if (
546
- include &&
547
- (!options?.filter ||
548
- args.find(
549
- (arg) => key.toLowerCase().indexOf(arg.toLowerCase()) >= 0,
550
- ))
551
- ) {
552
- return [key, value];
553
- } else if (typeof value === "object") {
554
- if (countWitnetArtifacts(value, args, options) > 0) {
555
- return [key, clearEmptyBranches(value, args, options)];
556
- } else {
557
- return [key, undefined];
558
- }
559
- } else {
560
- return [key, undefined];
561
- }
562
- })
563
- .filter(([, value]) => value !== undefined),
564
- );
565
- if (Object.keys(assets).length > 0) {
566
- return assets;
567
- } else {
568
- return undefined;
569
- }
570
- }
571
- }
572
-
573
- function traceWitnetArtifacts(assets, args, indent = "", options) {
574
- const prefix = `${indent}`;
575
- Object.keys(assets).forEach((key, index) => {
576
- const isLast = index === Object.keys(assets).length - 1;
577
- const found = args.find(
578
- (arg) => key.toLowerCase().indexOf(arg.toLowerCase()) >= 0,
579
- );
580
- const color = found ? helpers.colors.mcyan : helpers.colors.cyan;
581
- if (assets[key] instanceof Witnet.Radon.RadonRequest) {
582
- if (!options?.filter || found) {
583
- console.info(
584
- `${prefix}${color(key)} ${assets[key].sources.length > 1 ? helpers.colors.yellow(`(${assets[key].sources.length} sources)`) : ""}`,
585
- );
586
- if (isLast) {
587
- console.info(`${prefix}`);
588
- }
589
- }
590
- } else if (
591
- assets[key] instanceof Witnet.Radon.RadonTemplate ||
592
- assets[key] instanceof Witnet.Radon.RadonModal
593
- ) {
594
- const argsCount = assets[key].argsCount;
595
- if (!options?.filter || found) {
596
- console.info(
597
- `${prefix}${color(key)} ${argsCount > 0 ? helpers.colors.green(`(${argsCount} args)`) : ""}`,
598
- );
599
- if (isLast) {
600
- console.info(`${prefix}`);
601
- }
602
- }
603
- } else if (assets[key] instanceof Witnet.Radon.RadonRetrieval) {
604
- const argsCount = assets[key].argsCount;
605
- if (!options?.filter || found) {
606
- console.info(
607
- `${prefix}${color(key)} ${argsCount > 0 ? helpers.colors.green(`(${argsCount} args)`) : ""}`,
608
- );
609
- if (isLast) {
610
- console.info(`${prefix}`);
611
- }
612
- }
613
- } else if (
614
- typeof assets[key] === "object" &&
615
- countWitnetArtifacts(assets[key], args, options) > 0
616
- ) {
617
- console.info(`${indent}${isLast ? "└─ " : "├─ "}${key}`);
618
- traceWitnetArtifacts(
619
- assets[key],
620
- args,
621
- !isLast ? `${indent}│ ` : `${indent} `,
622
- options,
623
- );
624
- }
625
- });
626
- }
627
-
628
- function traceWitnetRadonReportHeadline(request, options) {
629
- const trait = (str) => `${str}${" ".repeat(66 - str.length)}`;
630
- const indent = options?.indent ? " ".repeat(options.indent) : "";
631
- const resultDataType = `Result<${extractTypeName(request.sources[0]?.script?.outputType.constructor.name)}, RadonError>`;
632
- console.info(
633
- `${indent}╔══════════════════════════════════════════════════════════════════════════════╗`,
634
- );
635
- console.info(
636
- `${indent}║ ${helpers.colors.white(options?.headline)}${" ".repeat(77 - options?.headline.length)}║`,
637
- );
638
- console.info(
639
- `${indent}╠══════════════════════════════════════════════════════════════════════════════╣`,
640
- );
641
- console.info(
642
- `${indent}║ ${helpers.colors.white("RAD hash")}: ${helpers.colors.lgreen(request.radHash)} ║`,
643
- );
644
- console.info(
645
- `${indent}║ RAD size: ${helpers.colors.green(trait(`${helpers.commas(request.weight())} bytes`))} ║`,
646
- );
647
- console.info(
648
- `${indent}║ RAD type: ${helpers.colors.yellow(trait(resultDataType))} ║`,
649
- );
650
- // if (!options.verbose) {
651
- // console.info(`${indent}║ > Radon operators: ${white(trait(commas(request.opsCount())))} ║`)
652
- // }
653
- // console.info(`${indent}╠════════════════════════════════════════════════════════════════════════════╣`)
654
- // console.info(`${indent}║ > Times solved: ${white(trait("{ values: 123, errors: 220 }"))} ║`)
655
- // console.info(`${indent}║ > Times witnessed: ${white(trait("{ values: 2130, errors: 1326 }"))} ║`)
656
- // console.info(`${indent}║ > Total fees: ${white(trait("15,234.123 Wits"))} ║`)
657
- // console.info(`${indent}║ > Total slash: ${white(trait(" 56.123 Wits"))} ║`)
658
- // console.info(`${indent}║ > Total burn: ${white(trait(" 0.789 Wits"))} ║`)
659
- // if (verbose) {
660
- // console.info(`${indent}╚══╤═════════════════════════════════════════════════════════════════════════╝`)
661
- // } else {
662
- // console.info(`${indent}╚════════════════════════════════════════════════════════════════════════════╝`)
663
- // }
664
- }
665
-
666
- function traceWitnetRadonRequest(request, options) {
667
- const indent = options?.indent
668
- ? " ".repeat(parseInt(options.indent, 10))
669
- : "";
670
- if (options?.json) {
671
- console.info(
672
- JSON.stringify(request.toProtobuf(), null, options?.indent || 0),
673
- );
674
- } else {
675
- if (!options.headline) options.headline = "WITNET DATA REQUEST DISASSEMBLE";
676
- traceWitnetRadonReportHeadline(request, options);
677
- console.info(
678
- `${indent}╚══╤═══════════════════════════════════════════════════════════════════════════╝`,
679
- );
680
- if (options?.bytecode) {
681
- console.info(request.toBytecode())
682
- return
683
- }
684
- console.info(`${indent}┌──┴─────────────────┐`);
685
- console.info(`${indent}│ ${helpers.colors.white("RETRIEVE DATA")} │`); // ├ ┤
686
- console.info(`${indent}└──┬─┬───────────────┘`);
687
- request.sources.forEach((source, sourceIndex) => {
688
- const authority =
689
- source.authority?.toUpperCase().split(".").slice(-2).join(".") ||
690
- (source.method === Witnet.Radon.retrievals.Methods.RNG
691
- ? "WIT/RNG"
692
- : "");
693
- const corner = sourceIndex === request.sources.length - 1 ? "" : "├";
694
- const sep = sourceIndex === request.sources.length - 1 ? " " : "";
695
- console.info(
696
- `${indent} │ ${corner}─ ${helpers.colors.white("[ ")}${helpers.colors.white(
697
- `Data source #${sourceIndex + 1}`,
698
- )} ${" ".repeat(3 - sourceIndex.toString().length)}${helpers.colors.white(authority)} ${helpers.colors.white("]")}`,
699
- );
700
- if (source.method !== Witnet.Radon.retrievals.Methods.RNG) {
701
- console.info(
702
- `${indent} │ ${sep} > Request: ${helpers.colors.mgreen(
703
- Witnet.Radon.retrievals.Methods[source.method]
704
- .split(/(?=[A-Z])/)
705
- .join("-")
706
- .toUpperCase(),
707
- )}`,
708
- );
709
- console.info(
710
- `${indent} │ ${sep} > URL query: ${helpers.colors.green(source.url)}`,
711
- );
712
- if (source?.headers && Object.keys(source.headers).length > 0) {
713
- console.info(
714
- `${indent} │ ${sep} > HTTP headers: ${helpers.colors.green(JSON.stringify(source.headers))}`,
715
- );
716
- }
717
- if (source?.body) {
718
- console.info(
719
- `${indent} │ ${sep} > HTTP body: ${helpers.colors.green(source.body)}`,
720
- );
721
- }
722
- if (source?.script) {
723
- // console.log(source.script.toBytecode())
724
- const steps = source.script.disect();
725
- console.info(
726
- `${indent} │ ${sep} > Radon script: ${helpers.colors.lyellow(
727
- "[ ",
728
- )}${helpers.colors.yellow(steps[0][1])}${" ".repeat(
729
- 12 - steps[0][1].length,
730
- )}${helpers.colors.lyellow(
731
- " ]",
732
- )} ${helpers.colors.mcyan(steps[0][2])}`,
733
- );
734
- steps.slice(1).forEach((step) => {
735
- console.info(
736
- `${indent} │ ${sep} ${helpers.colors.lyellow(
737
- "[ ",
738
- )}${helpers.colors.yellow(step[1])}${" ".repeat(
739
- 12 - step[1].length,
740
- )}${helpers.colors.lyellow(
741
- " ]",
742
- )} ${" ".repeat(2 * step[0])}${helpers.colors.mcyan(step[2])}`,
743
- );
744
- });
745
- const outputType =
746
- source.script.outputType.constructor.name || "RadonAny";
747
- console.info(
748
- `${indent} │ ${sep} ${helpers.colors.lyellow(
749
- "[ ",
750
- )}${helpers.colors.yellow(outputType)}${" ".repeat(
751
- 12 - outputType.length,
752
- )}${helpers.colors.lyellow(" ]")}`,
753
- );
754
- }
755
- }
756
- if (sourceIndex < request.sources.length - 1) {
757
- console.info(`${indent} │ │`);
758
- }
759
- });
760
- console.info(`${indent}┌──┴──────────────────┐`);
761
- console.info(`${indent}│ ${helpers.colors.white("AGGREGATE SOURCES")} │`);
762
- console.info(`${indent}└──┬──────────────────┘`); // ┬
763
- request.sourcesReducer?.filters.forEach((filter) =>
764
- console.info(
765
- `${indent} │ > Radon filter: ${stringifyFilter(filter)}`,
766
- ),
767
- );
768
- console.info(
769
- `${indent} │ > Radon reducer: ${stringifyReducer(request.sourcesReducer)}`,
770
- );
771
- console.info(`${indent}┌──┴──────────────────┐`);
772
- console.info(`${indent}│ ${helpers.colors.white("WITNESSING TALLY")} │`);
773
- console.info(`${indent}└─────────────────────┘`); // ┬
774
- request.witnessReducer?.filters.forEach((filter) =>
775
- console.info(
776
- `${indent} > Radon filter: ${stringifyFilter(filter)}`,
777
- ),
778
- );
779
- console.info(
780
- `${indent} > Radon reducer: ${stringifyReducer(request.witnessReducer)}`,
781
- );
782
- }
783
- }
784
-
785
- async function traceWitnetRadonRequestDryRun(request, options) {
786
- const bytecode = request.toBytecode();
787
- let report = await helpers
788
- .toolkitRun(options, [
789
- "try-data-request",
790
- "--hex",
791
- bytecode.startsWith("0x") ? bytecode.slice(2) : bytecode,
792
- ])
793
- .catch((err) => {
794
- let errorMessage = err.message.split("\n").slice(1).join("\n").trim();
795
- const errorRegex = /.*^error: (?<message>.*)$.*/gm;
796
- const matched = errorRegex.exec(err.message);
797
- if (matched) {
798
- errorMessage = matched.groups.message;
799
- }
800
- throw errorMessage || err;
801
- });
802
- if (!report) {
803
- throw Error("No dry-report?");
804
- } else {
805
- report = JSON.parse(report);
806
- }
807
- const result = report?.aggregate.result;
808
- const resultType = Object.keys(result)[0];
809
- const resultValue = Object.values(result)[0];
810
- let resultSize;
811
- const parseRadonResult = (value) => {
812
- if (Array.isArray(value)) {
813
- return value.map((item) => parseRadonResult(item));
814
- }
815
- if (typeof value === "object") {
816
- return parseRadonResult(Object.values(value)[0]);
817
- } else {
818
- return JSON.parse(value);
819
- }
820
- };
821
- switch (resultType) {
822
- case "RadonBoolean":
823
- resultSize = 1;
824
- break;
825
- case "RadonBytes":
826
- resultSize =
827
- utils.cbor.encode(Uint8Array.from(resultValue)).byteLength - 2;
828
- break;
829
- case "RadonInteger":
830
- case "RadonFloat":
831
- resultSize = utils.cbor.encode(resultValue).byteLength;
832
- break;
833
- case "RadonArray":
834
- case "RadonMap": {
835
- const parsed = parseRadonResult(resultValue);
836
- resultSize = utils.cbor.encode(parsed).byteLength;
837
- break;
838
- }
839
- }
840
- if (options?.json) {
841
- if (options?.verbose) {
842
- console.info(
843
- JSON.stringify(
844
- report,
845
- null,
846
- options?.indent ? " ".repeat(options.indent) : "",
847
- ),
848
- );
849
- } else {
850
- result[resultType] = resultValue;
851
- console.info(
852
- JSON.stringify(
853
- result,
854
- null,
855
- options?.indent ? " ".repeat(options.indent) : "",
856
- ),
857
- );
858
- }
859
- return;
860
- }
861
- if (!options.headline)
862
- options.headline = "WITNET DATA REQUEST DRY-RUN REPORT";
863
- traceWitnetRadonReportHeadline(request, options);
864
- const indent = options?.indent ? " ".repeat(options.indent) : "";
865
- console.info(
866
- `${indent}╚══╤═══════════════════════════════════════════════════════════════════════════╝`,
867
- );
868
- let execTimeMs = report.retrieve
869
- ?.map(
870
- (retrieval) =>
871
- (retrieval?.running_time.secs || 0) +
872
- (retrieval?.running_time.nanos || 0) / 1000,
873
- )
874
- .reduce((sum, secs) => sum + secs);
875
- execTimeMs = `${Math.round(execTimeMs)} ms`;
876
- let flexbar = "─".repeat(17);
877
- let flexspc = " ".repeat(flexbar.length + 12);
878
- console.info(`${indent}┌──┴─────────────────────────────${flexbar}──────┐`);
879
- console.info(
880
- `${indent}│ ${helpers.colors.white("Data providers")} ${flexspc} │`,
881
- ); // ├ ┤
882
- console.info(`${indent}├────────────────────────────────${flexbar}──────┤`);
883
- console.info(
884
- `${indent}│ Execution time: ${helpers.colors.green(execTimeMs)} ${" ".repeat(flexbar.length + 19 - execTimeMs.length)} │`,
885
- );
886
- console.info(`${indent}└──┬─┬───────────────────────────${flexbar}──────┘`);
887
- request.sources.forEach((source, sourceIndex) => {
888
- const authority =
889
- source.authority?.toUpperCase().split(".").slice(-2).join(".") ||
890
- (source.method === Witnet.Radon.retrievals.Methods.RNG ? "WIT/RNG" : "");
891
- const corner = sourceIndex === request.sources.length - 1 ? "" : "├";
892
- const sep = sourceIndex === request.sources.length - 1 ? " " : "";
893
- const color = report.retrieve[sourceIndex].result?.RadonError
894
- ? options?.verbose
895
- ? helpers.colors.lgray
896
- : helpers.colors.gray
897
- : options?.verbose
898
- ? helpers.colors.lgreen
899
- : helpers.colors.green;
900
- if (options?.verbose) {
901
- console.info(
902
- `${indent} │ ${corner}─ ${helpers.colors.white(
903
- "[ ",
904
- )}${helpers.colors.white(
905
- `Data Source #${sourceIndex + 1}`,
906
- )} ${" ".repeat(3 - sourceIndex.toString().length)}${color(
907
- authority,
908
- )} ${helpers.colors.white("]")}`,
909
- );
910
- } else {
911
- console.info(`${indent} │ ${corner}─ [ ${color(authority)} ]`);
912
- }
913
- if (
914
- source.method !== Witnet.Radon.retrievals.Methods.RNG &&
915
- options?.verbose
916
- ) {
917
- console.info(
918
- `${indent} │ ${sep} > Request: ${helpers.colors.mgreen(
919
- Witnet.Radon.retrievals.Methods[source.method]
920
- .split(/(?=[A-Z])/)
921
- .join("-")
922
- .toUpperCase(),
923
- )}`,
924
- );
925
- console.info(
926
- `${indent} │ ${sep} > URL query: ${helpers.colors.green(source.url)}`,
927
- );
928
- if (source?.headers && Object.keys(source.headers).length > 0) {
929
- console.info(
930
- `${indent} │ ${sep} > HTTP headers: ${helpers.colors.green(JSON.stringify(source.headers))}`,
931
- );
932
- }
933
- if (source?.body) {
934
- console.info(
935
- `${indent} │ ${sep} > HTTP body: ${helpers.colors.green(source.body)}`,
936
- );
937
- }
938
- const printData = (headline, data, color) => {
939
- const type = Object.keys(data)[0];
940
- data =
941
- (typeof data[type] === "object" ||
942
- typeof data[type] === "boolean" ||
943
- Array.isArray(data[type])
944
- ? JSON.stringify(data[type])
945
- : data[type]) || "";
946
- const lines = data.match(/.{1,96}/g)?.slice(0, 256) || [""];
947
- if (lines.length === 256) lines[255] += "...";
948
- const typeColor =
949
- type === "RadonError" ? helpers.colors.red : helpers.colors.yellow;
950
- const lineColor = type === "RadonError" ? helpers.colors.gray : color;
951
- console.info(
952
- `${indent} │ ${sep} > ${headline}${" ".repeat(15 - headline.length)} \x1b[1;m${typeColor(
953
- "[ ",
954
- )}\x1b[0m${typeColor(type)}${" ".repeat(
955
- 12 - type.length,
956
- )}\x1b[1;m${typeColor(" ]")}\x1b[0m ${lineColor(lines[0])}`,
957
- );
958
- lines.slice(1).forEach((line) => {
959
- console.info(
960
- `${indent} │ ${sep} ${lineColor(line)}`,
961
- );
962
- });
963
- };
964
- if (report?.retrieve[sourceIndex]?.partial_results) {
965
- printData(
966
- "HTTP response:",
967
- report?.retrieve[sourceIndex]?.partial_results[0],
968
- helpers.colors.cyan,
969
- );
970
- }
971
- printData(
972
- "Radon result:",
973
- report?.retrieve[sourceIndex]?.result,
974
- helpers.colors.mcyan,
975
- );
976
- }
977
- if (options?.verbose && sourceIndex < request.sources.length - 1) {
978
- console.info(`${indent} │ │`);
979
- }
980
- });
981
- flexbar = "─".repeat(24);
982
- flexspc = " ".repeat(36);
983
- console.info(`${indent}┌──┴───────────────────────────${flexbar}─┐`);
984
- console.info(
985
- `${indent}│ ${helpers.colors.white("Aggregated result")}${flexspc} │`,
986
- ); // ├ ┤
987
- console.info(`${indent}├──────────────────────────────${flexbar}─┤`);
988
- if (options?.verbose) {
989
- let partial_index = 0;
990
- const partial_results = report.sourcesReducer?.partial_results;
991
- request.sourcesReducer?.filters.forEach((filter) => {
992
- const color = partial_results?.[partial_index]?.RadonArray
993
- ? helpers.colors.mcyan
994
- : helpers.colors.gray;
995
- const items = partial_results?.[partial_index]?.RadonArray
996
- ? ` over ${partial_results[partial_index]?.RadonArray.length} sources`
997
- : "";
998
- partial_index += 1;
999
- filter = stringifyFilter(filter, color);
1000
- console.info(
1001
- `${indent}│ Radon filter: ${filter}${helpers.colors.cyan(
1002
- items,
1003
- )}${" ".repeat(flexbar.length + 22 - filter.length - items.length)} │`,
1004
- );
1005
- });
1006
- const color = partial_results?.[partial_index]?.RadonArray
1007
- ? helpers.colors.mcyan
1008
- : helpers.colors.gray;
1009
- const items = partial_results?.[partial_index]?.RadonArray
1010
- ? ` over ${partial_results[partial_index]?.RadonArray.length} sources`
1011
- : "";
1012
- const reducer = stringifyReducer(request.sourcesReducer, color);
1013
- console.info(
1014
- `${indent}│ Radon reducer: ${reducer}${helpers.colors.cyan(items)}${" ".repeat(
1015
- flexbar.length + 22 - reducer.length - items.length,
1016
- )} │`,
1017
- );
1018
- }
1019
- if (resultSize) {
1020
- console.info(
1021
- `${indent}│ CBOR size: ${helpers.colors.cyan(
1022
- `${resultSize} bytes`,
1023
- )}${" ".repeat(flexbar.length + 7 - resultSize.toString().length)} │`,
1024
- );
1025
- }
1026
- console.info(`${indent}└────┬─────────────────────────${flexbar}─┘`);
1027
- const printMapItem = (indent, width, key, value, indent2 = "") => {
1028
- if (key) key = `${indent2}${key}: `;
1029
- else key = `${indent2}`;
1030
- let type = extractTypeName(Object.keys(value)[0]);
1031
- value = Object.values(value)[0];
1032
- if (["Map", "Array"].includes(type)) {
1033
- if (key.length > width - 12) {
1034
- console.info(
1035
- `${indent} ${helpers.colors.myellow(
1036
- `[ ${type}${" ".repeat(7 - type.length)} ]`,
1037
- )} ${" ".repeat(width - 15)}${helpers.colors.green("...")}`,
1038
- );
1039
- } else {
1040
- console.info(
1041
- `${indent} ${helpers.colors.myellow(
1042
- `[ ${type}${" ".repeat(7 - type.length)} ]`,
1043
- )} ${helpers.colors.green(key)}${" ".repeat(
1044
- width - 12 - key.length,
1045
- )}`,
1046
- );
1047
- }
1048
- Object.entries(value).forEach(([key, value]) =>
1049
- printMapItem(
1050
- indent,
1051
- width,
1052
- type === "Map" ? key : null,
1053
- helpers.unescapeSlashes(value),
1054
- `${indent2} `,
1055
- ),
1056
- );
1057
- } else {
1058
- if (key.length > width - 12) {
1059
- console.info(
1060
- `${indent} ${helpers.colors.yellow(type)} ${" ".repeat(width - 15)}${helpers.colors.green("...")}`,
1061
- );
1062
- } else {
1063
- type = `[ ${type}${" ".repeat(7 - type.length)} ]`;
1064
- const result = key + value;
1065
- // let spaces = width - 12 - result.length
1066
- if (result.length > width - 15) {
1067
- value = `${value.slice(0, width - 15 - key.length)}...`;
1068
- // spaces = 0
1069
- }
1070
- if (["String", "Error"].includes(type)) {
1071
- console.info(
1072
- `${indent} ${helpers.colors.yellow(type)} ${helpers.colors.green(key)}"${helpers.colors.mcyan(value)}"`,
1073
- );
1074
- } else {
1075
- console.info(
1076
- `${indent} ${helpers.colors.yellow(type)} ${helpers.colors.green(key)}${helpers.colors.mcyan(value)}`,
1077
- );
1078
- }
1079
- }
1080
- }
1081
- };
1082
- const printResult = (indent, width, resultType, resultValue) => {
1083
- resultType = extractTypeName(resultType);
1084
- resultValue =
1085
- typeof resultValue === "object" || Array.isArray(resultValue)
1086
- ? JSON.stringify(resultValue)
1087
- : resultValue;
1088
- if (["Map", "Array"].includes(resultType)) {
1089
- console.info(
1090
- `${indent} └─ ${helpers.colors.lyellow(`[ ${resultType}${" ".repeat(7 - resultType.length)} ]`)}`,
1091
- );
1092
- const obj = JSON.parse(resultValue);
1093
- Object.entries(obj).forEach(([key, value]) =>
1094
- printMapItem(indent, width, resultType === "Map" ? key : null, value),
1095
- );
1096
- } else {
1097
- if (resultType === "Bytes") {
1098
- resultValue = JSON.parse(resultValue)
1099
- .map((char) => `00${char.toString(16)}`.slice(-2))
1100
- .join("");
1101
- } else if (resultType === "Boolean") {
1102
- resultValue = JSON.stringify(resultValue);
1103
- }
1104
- const color =
1105
- resultType.indexOf("Error") > -1
1106
- ? helpers.colors.gray
1107
- : helpers.colors.lcyan;
1108
- const typeText =
1109
- resultType.indexOf("Error") > -1
1110
- ? "\x1b[1;98;41m Error \x1b[0m"
1111
- : helpers.colors.lyellow(`[ ${resultType} ]`);
1112
- const lines = resultValue.match(/.{1,96}/g)?.slice(0, 256) || [""];
1113
- console.info(`${indent} └─ ${typeText} ${color(lines[0])}`);
1114
- lines.slice(1).forEach((line) => {
1115
- console.info(
1116
- `${indent} ${" ".repeat(resultType.length)}${color(line)}`,
1117
- );
1118
- });
1119
- }
1120
- };
1121
- printResult(indent, 134, resultType, resultValue);
1122
- }
1
+ import fs from "node:fs";
2
+ import { createRequire } from "node:module";
3
+ import dotenv from "dotenv";
4
+
5
+ dotenv.config({ quiet: true });
6
+
7
+ import path from "node:path";
8
+ import inquirer from "inquirer";
9
+ import merge from "lodash.merge";
10
+
11
+ const require = createRequire(import.meta.url);
12
+
13
+ import { utils, Witnet } from "../../../dist/src/index.js";
14
+ import { default as legacy } from "../../../witnet/assets/index.cjs";
15
+ import * as helpers from "../helpers.js";
16
+
17
+ const WITNET_ASSETS_PATH =
18
+ process.env.WITNET_SDK_RADON_ASSETS_PATH || "../../../../../witnet/assets";
19
+
20
+ /// ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
21
+ /// CLI SUBMODULE CONSTANTS ===========================================================================================
22
+
23
+ const isModuleInitialized = fs.existsSync("./witnet/assets/index.cjs");
24
+
25
+ export const flags = {
26
+ module: {
27
+ hint: "Package where to fetch Radon assets from (supersedes --legacy).",
28
+ param: "NPM_PACKAGE",
29
+ },
30
+ };
31
+
32
+ export const router = isModuleInitialized
33
+ ? {
34
+ assets: {
35
+ hint: "List available Witnet Radon assets.",
36
+ params: "[RADON_ASSETS ...]",
37
+ options: {
38
+ filter: {
39
+ hint: "Restrict output to name-matching assets.",
40
+ },
41
+ legacy: {
42
+ hint: "List only those declared in witnet/assets folder.",
43
+ },
44
+ modals: {
45
+ hint: "Restrict output to Radon modals.",
46
+ },
47
+ requests: {
48
+ hint: "Restrict output to Radon requests.",
49
+ },
50
+ templates: {
51
+ hint: "Restrict output to Radon templates.",
52
+ },
53
+ },
54
+ },
55
+ check: {
56
+ hint: "Check correctness of Witnet Radon artifacts declared in witnet/assets folder.",
57
+ params: [],
58
+ options: {},
59
+ },
60
+ decode: {
61
+ hint: "Break down specs of one or more Radon assets.",
62
+ params: ["RAD_BYTECODE | RAD_HASH | RADON_ASSET"],
63
+ options: {
64
+ bytecode: {
65
+ hint: "Outputs RAD bytecode as hex string (supersedes --json).",
66
+ },
67
+ json: {
68
+ hint: "Outputs data in JSON format.",
69
+ },
70
+ headline: {
71
+ hint: "Settles output report headline.",
72
+ param: ":string",
73
+ },
74
+ indent: {
75
+ hint: "Prefixes given number of white spaces for every output line.",
76
+ param: ":number",
77
+ },
78
+ },
79
+ },
80
+ "dry-run": {
81
+ hint: "Simulate resolution of one or more Radon assets, as if solved by the Wit/Oracle.",
82
+ params: ["RAD_BYTECODE | RAD_HASH | RADON_ASSET"],
83
+ options: {
84
+ default: {
85
+ hint: "Use default sample parameters on parametrized Radon assets.",
86
+ },
87
+ json: {
88
+ hint: "Outputs data in JSON format.",
89
+ },
90
+ headline: {
91
+ hint: "Settles output report headline.",
92
+ param: ":string",
93
+ },
94
+ indent: {
95
+ hint: "Prefixes given number of white spaces for every output line.",
96
+ param: ":number",
97
+ },
98
+ verbose: {
99
+ hint: "Outputs detailed dry-run report.",
100
+ },
101
+ },
102
+ },
103
+ }
104
+ : {
105
+ assets: {
106
+ hint: "List available Witnet Radon assets.",
107
+ params: "[RADON_ASSETS ...]",
108
+ options: {
109
+ filter: {
110
+ hint: "Restrict output to name-matching assets.",
111
+ },
112
+ legacy: {
113
+ hint: "List only those declared in witnet/assets folder.",
114
+ },
115
+ },
116
+ },
117
+ decode: {
118
+ hint: "Break down specs of one or more Radon assets.",
119
+ params: ["RAD_BYTECODE | RAD_HASH | RADON_ASSET"],
120
+ options: {
121
+ json: {
122
+ hint: "Outputs data in JSON format.",
123
+ },
124
+ headline: {
125
+ hint: "Settles output report headline.",
126
+ param: ":string",
127
+ },
128
+ indent: {
129
+ hint: "Prefixes given number of white spaces for every output line.",
130
+ param: ":number",
131
+ },
132
+ },
133
+ },
134
+ "dry-run": {
135
+ hint: "Simulate resolution of one or more Radon assets, as if solved by the Wit/Oracle.",
136
+ params: ["RAD_BYTECODE | RAD_HASH | RADON_ASSET"],
137
+ options: {
138
+ json: {
139
+ hint: "Outputs data in JSON format.",
140
+ },
141
+ headline: {
142
+ hint: "Settles output report headline.",
143
+ param: ":string",
144
+ },
145
+ indent: {
146
+ hint: "Prefixes given number of white spaces for every output line.",
147
+ param: ":number",
148
+ },
149
+ verbose: {
150
+ hint: "Outputs detailed dry-run report.",
151
+ },
152
+ },
153
+ },
154
+ init: {
155
+ hint: "Initialize a Witnet Radon workspace in this project.",
156
+ },
157
+ };
158
+
159
+ export const subcommands = {
160
+ assets,
161
+ init,
162
+ check,
163
+ decode,
164
+ "dry-run": dryrun,
165
+ };
166
+
167
+ ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
168
+ /// CLI SUBMODULE COMMANDS ============================================================================================
169
+
170
+ async function init() {
171
+ if (!fs.existsSync("./witnet/assets/")) {
172
+ fs.mkdirSync("./witnet/assets", { recursive: true });
173
+ }
174
+ if (!fs.existsSync(".env_witnet")) {
175
+ fs.cpSync("node_modules/@witnet/sdk/.env_witnet", ".env_witnet");
176
+ }
177
+ if (!fs.existsSync("./witnet/assets/index.js")) {
178
+ fs.cpSync(
179
+ "node_modules/@witnet/sdk/witnet/assets/_index.js",
180
+ "./witnet/assets/index.js",
181
+ );
182
+ }
183
+ if (!fs.existsSync("./witnet/assets/requests.js")) {
184
+ fs.cpSync(
185
+ "node_modules/@witnet/sdk/witnet/assets/_requests.js",
186
+ "./witnet/assets/requests.js",
187
+ );
188
+ }
189
+ if (!fs.existsSync("./witnet/assets/sources.js")) {
190
+ fs.cpSync(
191
+ "node_modules/@witnet/sdk/witnet/assets/_sources.js",
192
+ "./witnet/assets/sources.js",
193
+ );
194
+ }
195
+ if (!fs.existsSync("./witnet/assets/templates.js")) {
196
+ fs.cpSync(
197
+ "node_modules/@witnet/sdk/witnet/assets/_templates.js",
198
+ "./witnet/assets/templates.js",
199
+ );
200
+ }
201
+ console.info(
202
+ `Initialized Witnet Radon workspace at folder ${process.cwd()}/witnet/assets`,
203
+ );
204
+ }
205
+
206
+ async function assets(options = {}, [...patterns]) {
207
+ helpers.traceHeader(
208
+ `${options?.module ? options.module.toUpperCase() : path.basename(process.cwd()).toUpperCase()} RADON ASSETS`,
209
+ helpers.colors.white,
210
+ );
211
+ const assets = clearEmptyBranches(
212
+ options?.module ? require(`${options.module}/assets`) : loadAssets(options),
213
+ patterns,
214
+ options,
215
+ );
216
+ if (assets && Object.keys(assets).length > 0) {
217
+ traceWitnetArtifacts(assets, patterns, " ", options);
218
+ } else {
219
+ console.info("> No custom Radon assets declared just yet.");
220
+ }
221
+ }
222
+ /// -------------------------------------------------------------------------------------------------------------------
223
+
224
+ async function check() {
225
+ if (!isModuleInitialized) {
226
+ throw new Error(
227
+ `No Witnet Radon workspace has been initialized. Please, run ${white("npx witsdk radon init")} if willing to declare your own Radon assets.`,
228
+ );
229
+ }
230
+ try {
231
+ const assets = loadAssets({ legacy: true });
232
+ const [modals, requests, sources, templates] = [
233
+ helpers.countLeaves(Witnet.Radon.RadonModal, assets),
234
+ helpers.countLeaves(Witnet.Radon.RadonRequest, assets),
235
+ helpers.countLeaves(Witnet.Radon.RadonRetrieval, assets?.sources),
236
+ helpers.countLeaves(Witnet.Radon.RadonTemplate, assets),
237
+ ];
238
+ if (modals > 0) console.info("> Radon modals: ", modals);
239
+ if (sources > 0) console.info("> Radon sources: ", sources);
240
+ if (requests > 0) console.info("> Radon requests: ", requests);
241
+ if (templates > 0) console.info("> Radon templates:", templates);
242
+
243
+ if (modals + sources + requests + templates === 0) {
244
+ console.info("-----------------------------");
245
+ console.info("No Radon assets declared yet!");
246
+ } else {
247
+ console.info("--------------------------------------");
248
+ console.info("All Radon assets checked successfully!");
249
+ }
250
+ } catch (e) {
251
+ console.error("Radon assets verification failed:");
252
+ console.info("----------------------------------");
253
+ console.info(e);
254
+ }
255
+ }
256
+ /// -------------------------------------------------------------------------------------------------------------------
257
+
258
+ async function decode(options = {}, args = []) {
259
+ if (args.length === 0) {
260
+ throw Error("No Radon asset was specified");
261
+ }
262
+ const asset = args[0];
263
+ if (helpers.isHexString(asset)) {
264
+ try {
265
+ const request = Witnet.Radon.RadonRequest.fromBytecode(asset);
266
+ traceWitnetRadonRequest(request, options);
267
+ } catch (err) {
268
+ console.error(err);
269
+ if (
270
+ (asset.startsWith("0x") && asset.length === 66) ||
271
+ (!asset.startsWith("0x") && asset.length === 64)
272
+ ) {
273
+ // TODO: assume it's a DR_TX_HASH
274
+ // TODO: assume it's a RAD_HASH
275
+ }
276
+ }
277
+ } else {
278
+ args = args.slice(1);
279
+
280
+ const assets = options?.module
281
+ ? require(`${options.module}/assets`)
282
+ : loadAssets(options);
283
+ const headline = options?.headline;
284
+ const crafts = flattenRadonArtifacts(assets).filter(
285
+ (craft) => craft.key.toLowerCase().indexOf(asset.toLowerCase()) >= 0,
286
+ );
287
+ if (crafts.length === 0) {
288
+ throw Error(`No matched found for pattern "${asset}"`);
289
+ }
290
+ for (let { artifact, key } of crafts) {
291
+ let prefix = "";
292
+ if (artifact instanceof Witnet.Radon.RadonRequest) {
293
+ prefix = "RadonRequest::";
294
+ } else if (artifact instanceof Witnet.Radon.RadonModal) {
295
+ artifact.providers = [...(args[0]?.split(";") || ["https://dummy"])];
296
+ const modalArgs = [];
297
+ let argIndex = 1;
298
+ while (modalArgs.length < artifact.argsCount) {
299
+ modalArgs.push(args[argIndex] || `{:${argIndex}}`);
300
+ argIndex += 1;
301
+ }
302
+ artifact = artifact.buildRadonRequest(modalArgs);
303
+ prefix = "RadonModal::";
304
+ } else if (artifact instanceof Witnet.Radon.RadonTemplate) {
305
+ const templateArgs = artifact.sources.map(({ argsCount }) =>
306
+ Array.from({ length: argsCount }, (_, i) => `{:${i}}`),
307
+ );
308
+ artifact = artifact.buildRadonRequest(templateArgs);
309
+ prefix = "RadonTemplate::";
310
+ } else if (artifact instanceof Witnet.Radon.RadonRetrieval) {
311
+ if (artifact.argsCount > 0) {
312
+ const retrievalArgs = Array.from(
313
+ { length: artifact.argsCount },
314
+ (_, i) => `{:${i + 1}}`,
315
+ );
316
+ artifact = artifact.foldArgs(retrievalArgs);
317
+ }
318
+ artifact = new Witnet.Radon.RadonRequest({ sources: artifact });
319
+ prefix = "RadonRetrieval::";
320
+ }
321
+ if (!headline) {
322
+ options.headline = `${prefix}${key}`;
323
+ }
324
+ traceWitnetRadonRequest(artifact, options);
325
+ if (options?.verbose && key !== crafts[crafts.length - 1].key) {
326
+ console.info(`${options?.indent || ""}${"─".repeat(150)}`);
327
+ }
328
+ console.info();
329
+ }
330
+ }
331
+ }
332
+ /// -------------------------------------------------------------------------------------------------------------------
333
+
334
+ async function dryrun(options = {}, args = []) {
335
+ if (args.length === 0) {
336
+ throw Error("No Radon asset was specified");
337
+ }
338
+ const asset = args[0];
339
+ if (helpers.isHexString(asset)) {
340
+ try {
341
+ const request = Witnet.Radon.RadonRequest.fromBytecode(asset);
342
+ await traceWitnetRadonRequestDryRun(request, options);
343
+ } catch {
344
+ if (
345
+ (asset.startsWith("0x") && asset.length === 66) ||
346
+ (!asset.startsWith("0x") && asset.length === 64)
347
+ ) {
348
+ // TODO: assume it's a RAD_HASH, and try to retrieve the BYTECODE from the Witnet network
349
+ }
350
+ }
351
+ } else {
352
+ args = args.slice(1);
353
+ const assets = options?.module
354
+ ? require(`${options.module}/assets`)
355
+ : loadAssets(options);
356
+ const headline = options?.headline;
357
+ const crafts = flattenRadonArtifacts(assets).filter(
358
+ (craft) => craft.key.toLowerCase().indexOf(asset.toLowerCase()) >= 0,
359
+ );
360
+ if (crafts.length === 0) {
361
+ throw Error(`No matched found for pattern "${asset}"`);
362
+ }
363
+ for (let { artifact, key } of crafts) {
364
+ let prefix = "";
365
+ if (artifact instanceof Witnet.Radon.RadonRequest) {
366
+ prefix = "RadonRequest::";
367
+ } else {
368
+ let artifactArgs = [];
369
+ if (artifact instanceof Witnet.Radon.RadonModal) {
370
+ if (args.length < artifact.argsCount) {
371
+ throw new Error(`missing parameters for Radon Modal.`);
372
+ }
373
+ artifact.providers = [...args[0].split(";")];
374
+ const modalArgs = [];
375
+ let argIndex = 1;
376
+ while (modalArgs.length < artifact.argsCount) {
377
+ modalArgs.push(args[argIndex]);
378
+ argIndex += 1;
379
+ }
380
+ artifact = artifact.homogeneous
381
+ ? artifact.buildRadonRequest(modalArgs)
382
+ : artifact.buildRadonRequest([
383
+ ...artifact.sources.map((source) =>
384
+ modalArgs.slice(0, source.argsCount),
385
+ ),
386
+ ]);
387
+ prefix = "RadonModal::";
388
+ } else {
389
+ if (!artifact?.samples) {
390
+ console.error(
391
+ `${artifact.constructor.name}::${key}: cannot dry-run if no sample parameters are declared.\n`,
392
+ );
393
+ continue;
394
+ }
395
+ if (options?.default) {
396
+ artifactArgs = Object.values(artifact.samples)[0];
397
+ } else {
398
+ const prompt = inquirer.createPromptModule();
399
+ const sample = await prompt([
400
+ {
401
+ choices: Object.keys(artifact.samples),
402
+ message: `${artifact.constructor.name}::${key} args:`,
403
+ name: "key",
404
+ type: "list",
405
+ },
406
+ ]);
407
+ artifactArgs = artifact.samples[sample.key];
408
+ }
409
+ if (artifact instanceof Witnet.Radon.RadonTemplate) {
410
+ artifact = artifact.buildRadonRequest(artifactArgs);
411
+ prefix = "RadonTemplate::";
412
+ } else if (artifact instanceof Witnet.Radon.RadonRetrieval) {
413
+ artifact = new Witnet.Radon.RadonRequest({
414
+ sources: artifact.foldArgs(artifactArgs),
415
+ });
416
+ prefix = "RadonRetrieval::";
417
+ }
418
+ }
419
+ }
420
+ if (!headline) {
421
+ options.headline = `${prefix}${key}`;
422
+ }
423
+ await traceWitnetRadonRequestDryRun(artifact, options);
424
+ if (options?.verbose && key !== crafts[crafts.length - 1].key) {
425
+ console.info(`${options?.indent || ""}${"─".repeat(150)}`);
426
+ }
427
+ console.info();
428
+ }
429
+ }
430
+ }
431
+ /// -------------------------------------------------------------------------------------------------------------------
432
+
433
+ /// ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
434
+ /// CLI SUBMODULE INTERNAL METHODS ------------------------------------------------------------------------------------
435
+
436
+ const extractTypeName = (str) =>
437
+ str
438
+ ? str
439
+ .split(/(?=[A-Z])/)
440
+ .slice(1)
441
+ .join("")
442
+ : "Any";
443
+
444
+ const stringifyFilter = (x, c) => {
445
+ const color = c || helpers.colors.mcyan;
446
+ return color(
447
+ `${Witnet.Radon.filters.Opcodes[x.opcode]}(${x.args ? JSON.stringify(x.args) : ""})`,
448
+ );
449
+ };
450
+
451
+ const stringifyReducer = (x, c) => {
452
+ const color = c || helpers.colors.mcyan;
453
+ return color(`${Witnet.Radon.reducers.Opcodes[x.opcode]}()`);
454
+ };
455
+
456
+ export function loadAssets(options) {
457
+ const assets = options?.legacy ? {} : legacy;
458
+ return isModuleInitialized
459
+ ? merge(assets, require(`${WITNET_ASSETS_PATH}/index.cjs`))
460
+ : assets;
461
+ }
462
+
463
+ function flattenRadonArtifacts(tree, headers) {
464
+ if (!headers) headers = [];
465
+ const matches = [];
466
+ for (const key in tree) {
467
+ if (
468
+ tree[key] instanceof Witnet.Radon.RadonRetrieval ||
469
+ tree[key] instanceof Witnet.Radon.RadonModal ||
470
+ tree[key] instanceof Witnet.Radon.RadonRequest ||
471
+ tree[key] instanceof Witnet.Radon.RadonTemplate
472
+ ) {
473
+ matches.push({
474
+ key,
475
+ artifact: tree[key],
476
+ });
477
+ } else if (typeof tree[key] === "object") {
478
+ matches.push(...flattenRadonArtifacts(tree[key], [...headers, key]));
479
+ }
480
+ }
481
+ return matches;
482
+ }
483
+
484
+ function countWitnetArtifacts(assets, args, options) {
485
+ let counter = 0;
486
+ Object.entries(assets).forEach(([key, value]) => {
487
+ let include =
488
+ (options?.modals && value instanceof Witnet.Radon.RadonModal) ||
489
+ (options?.templates && value instanceof Witnet.Radon.RadonTemplate) ||
490
+ (options?.retrievals && value instanceof Witnet.Radon.RadonRetrieval) ||
491
+ (options?.requests && value instanceof Witnet.Radon.RadonRequest);
492
+ if (
493
+ !(
494
+ options?.modals ||
495
+ options?.templates ||
496
+ options?.retrievals ||
497
+ options?.requests
498
+ )
499
+ ) {
500
+ include =
501
+ value instanceof Witnet.Radon.RadonModal ||
502
+ value instanceof Witnet.Radon.RadonRequest ||
503
+ value instanceof Witnet.Radon.RadonTemplate ||
504
+ value instanceof Witnet.Radon.RadonRetrieval;
505
+ }
506
+ if (
507
+ include &&
508
+ (!options?.filter ||
509
+ !args ||
510
+ args.length === 0 ||
511
+ args.find((arg) => key.toLowerCase().indexOf(arg.toLowerCase()) >= 0))
512
+ ) {
513
+ counter++;
514
+ } else if (typeof value === "object") {
515
+ counter += countWitnetArtifacts(value, args, options);
516
+ }
517
+ });
518
+ return counter;
519
+ }
520
+
521
+ function clearEmptyBranches(node, args, options) {
522
+ if (node) {
523
+ const assets = Object.fromEntries(
524
+ Object.entries(node)
525
+ .map(([key, value]) => {
526
+ let include =
527
+ (options?.modals && value instanceof Witnet.Radon.RadonModal) ||
528
+ (options?.templates &&
529
+ value instanceof Witnet.Radon.RadonTemplate) ||
530
+ (options?.retrievals &&
531
+ value instanceof Witnet.Radon.RadonRetrieval) ||
532
+ (options?.requests && value instanceof Witnet.Radon.RadonRequest);
533
+ if (
534
+ !(
535
+ options?.modals ||
536
+ options?.templates ||
537
+ options?.retrievals ||
538
+ options?.requests
539
+ )
540
+ ) {
541
+ include =
542
+ value instanceof Witnet.Radon.RadonModal ||
543
+ value instanceof Witnet.Radon.RadonRequest ||
544
+ value instanceof Witnet.Radon.RadonTemplate ||
545
+ value instanceof Witnet.Radon.RadonRetrieval;
546
+ }
547
+ if (
548
+ include &&
549
+ (!options?.filter ||
550
+ args.find(
551
+ (arg) => key.toLowerCase().indexOf(arg.toLowerCase()) >= 0,
552
+ ))
553
+ ) {
554
+ return [key, value];
555
+ } else if (typeof value === "object") {
556
+ if (countWitnetArtifacts(value, args, options) > 0) {
557
+ return [key, clearEmptyBranches(value, args, options)];
558
+ } else {
559
+ return [key, undefined];
560
+ }
561
+ } else {
562
+ return [key, undefined];
563
+ }
564
+ })
565
+ .filter(([, value]) => value !== undefined),
566
+ );
567
+ if (Object.keys(assets).length > 0) {
568
+ return assets;
569
+ } else {
570
+ return undefined;
571
+ }
572
+ }
573
+ }
574
+
575
+ function traceWitnetArtifacts(assets, args, indent = "", options) {
576
+ const prefix = `${indent}`;
577
+ Object.keys(assets).forEach((key, index) => {
578
+ const isLast = index === Object.keys(assets).length - 1;
579
+ const found = args.find(
580
+ (arg) => key.toLowerCase().indexOf(arg.toLowerCase()) >= 0,
581
+ );
582
+ const color = found ? helpers.colors.mcyan : helpers.colors.cyan;
583
+ if (assets[key] instanceof Witnet.Radon.RadonRequest) {
584
+ if (!options?.filter || found) {
585
+ console.info(
586
+ `${prefix}${color(key)} ${assets[key].sources.length > 1 ? helpers.colors.yellow(`(${assets[key].sources.length} sources)`) : ""}`,
587
+ );
588
+ if (isLast) {
589
+ console.info(`${prefix}`);
590
+ }
591
+ }
592
+ } else if (
593
+ assets[key] instanceof Witnet.Radon.RadonTemplate ||
594
+ assets[key] instanceof Witnet.Radon.RadonModal
595
+ ) {
596
+ const argsCount = assets[key].argsCount;
597
+ if (!options?.filter || found) {
598
+ console.info(
599
+ `${prefix}${color(key)} ${argsCount > 0 ? helpers.colors.green(`(${argsCount} args)`) : ""}`,
600
+ );
601
+ if (isLast) {
602
+ console.info(`${prefix}`);
603
+ }
604
+ }
605
+ } else if (assets[key] instanceof Witnet.Radon.RadonRetrieval) {
606
+ const argsCount = assets[key].argsCount;
607
+ if (!options?.filter || found) {
608
+ console.info(
609
+ `${prefix}${color(key)} ${argsCount > 0 ? helpers.colors.green(`(${argsCount} args)`) : ""}`,
610
+ );
611
+ if (isLast) {
612
+ console.info(`${prefix}`);
613
+ }
614
+ }
615
+ } else if (
616
+ typeof assets[key] === "object" &&
617
+ countWitnetArtifacts(assets[key], args, options) > 0
618
+ ) {
619
+ console.info(`${indent}${isLast ? "└─ " : "├─ "}${key}`);
620
+ traceWitnetArtifacts(
621
+ assets[key],
622
+ args,
623
+ !isLast ? `${indent}│ ` : `${indent} `,
624
+ options,
625
+ );
626
+ }
627
+ });
628
+ }
629
+
630
+ function traceWitnetRadonReportHeadline(request, options) {
631
+ const trait = (str) => `${str}${" ".repeat(66 - str.length)}`;
632
+ const indent = options?.indent ? " ".repeat(options.indent) : "";
633
+ const resultDataType = `Result<${extractTypeName(request.sources[0]?.script?.outputType.constructor.name)}, RadonError>`;
634
+ console.info(
635
+ `${indent}╔══════════════════════════════════════════════════════════════════════════════╗`,
636
+ );
637
+ console.info(
638
+ `${indent}║ ${helpers.colors.white(options?.headline)}${" ".repeat(77 - options?.headline.length)}║`,
639
+ );
640
+ console.info(
641
+ `${indent}╠══════════════════════════════════════════════════════════════════════════════╣`,
642
+ );
643
+ console.info(
644
+ `${indent}║ ${helpers.colors.white("RAD hash")}: ${helpers.colors.lgreen(request.radHash)} ║`,
645
+ );
646
+ console.info(
647
+ `${indent}║ RAD size: ${helpers.colors.green(trait(`${helpers.commas(request.weight())} bytes`))} ║`,
648
+ );
649
+ console.info(
650
+ `${indent}║ RAD type: ${helpers.colors.yellow(trait(resultDataType))} ║`,
651
+ );
652
+ // if (!options.verbose) {
653
+ // console.info(`${indent}║ > Radon operators: ${white(trait(commas(request.opsCount())))} ║`)
654
+ // }
655
+ // console.info(`${indent}╠════════════════════════════════════════════════════════════════════════════╣`)
656
+ // console.info(`${indent}║ > Times solved: ${white(trait("{ values: 123, errors: 220 }"))} ║`)
657
+ // console.info(`${indent}║ > Times witnessed: ${white(trait("{ values: 2130, errors: 1326 }"))} ║`)
658
+ // console.info(`${indent}║ > Total fees: ${white(trait("15,234.123 Wits"))} ║`)
659
+ // console.info(`${indent}║ > Total slash: ${white(trait(" 56.123 Wits"))} ║`)
660
+ // console.info(`${indent}║ > Total burn: ${white(trait(" 0.789 Wits"))} ║`)
661
+ // if (verbose) {
662
+ // console.info(`${indent}╚══╤═════════════════════════════════════════════════════════════════════════╝`)
663
+ // } else {
664
+ // console.info(`${indent}╚════════════════════════════════════════════════════════════════════════════╝`)
665
+ // }
666
+ }
667
+
668
+ function traceWitnetRadonRequest(request, options) {
669
+ const indent = options?.indent
670
+ ? " ".repeat(parseInt(options.indent, 10))
671
+ : "";
672
+ if (options?.json) {
673
+ console.info(
674
+ JSON.stringify(request.toProtobuf(), null, options?.indent || 0),
675
+ );
676
+ } else {
677
+ if (!options.headline) options.headline = "WITNET DATA REQUEST DISASSEMBLE";
678
+ traceWitnetRadonReportHeadline(request, options);
679
+ console.info(
680
+ `${indent}╚══╤═══════════════════════════════════════════════════════════════════════════╝`,
681
+ );
682
+ if (options?.bytecode) {
683
+ console.info(request.toBytecode());
684
+ return;
685
+ }
686
+ console.info(`${indent}┌──┴─────────────────┐`);
687
+ console.info(`${indent}│ ${helpers.colors.white("RETRIEVE DATA")} │`); // ├ ┤
688
+ console.info(`${indent}└──┬─┬───────────────┘`);
689
+ request.sources.forEach((source, sourceIndex) => {
690
+ const authority =
691
+ source.authority?.toUpperCase().split(".").slice(-2).join(".") ||
692
+ (source.method === Witnet.Radon.retrievals.Methods.RNG
693
+ ? "WIT/RNG"
694
+ : "");
695
+ const corner = sourceIndex === request.sources.length - 1 ? "└" : "├";
696
+ const sep = sourceIndex === request.sources.length - 1 ? " " : "│";
697
+ console.info(
698
+ `${indent}${corner}─ ${helpers.colors.white("[ ")}${helpers.colors.white(
699
+ `Data source #${sourceIndex + 1}`,
700
+ )} ${" ".repeat(3 - sourceIndex.toString().length)}${helpers.colors.white(authority)} ${helpers.colors.white("]")}`,
701
+ );
702
+ if (source.method !== Witnet.Radon.retrievals.Methods.RNG) {
703
+ console.info(
704
+ `${indent} │ ${sep} > Request: ${helpers.colors.mgreen(
705
+ Witnet.Radon.retrievals.Methods[source.method]
706
+ .split(/(?=[A-Z])/)
707
+ .join("-")
708
+ .toUpperCase(),
709
+ )}`,
710
+ );
711
+ console.info(
712
+ `${indent} │ ${sep} > URL query: ${helpers.colors.green(source.url)}`,
713
+ );
714
+ if (source?.headers && Object.keys(source.headers).length > 0) {
715
+ console.info(
716
+ `${indent} │ ${sep} > HTTP headers: ${helpers.colors.green(JSON.stringify(source.headers))}`,
717
+ );
718
+ }
719
+ if (source?.body) {
720
+ console.info(
721
+ `${indent} │ ${sep} > HTTP body: ${helpers.colors.green(source.body)}`,
722
+ );
723
+ }
724
+ if (source?.script) {
725
+ // console.log(source.script.toBytecode())
726
+ const steps = source.script.disect();
727
+ console.info(
728
+ `${indent}${sep} > Radon script: ${helpers.colors.lyellow(
729
+ "[ ",
730
+ )}${helpers.colors.yellow(steps[0][1])}${" ".repeat(
731
+ 12 - steps[0][1].length,
732
+ )}${helpers.colors.lyellow(
733
+ " ]",
734
+ )} ${helpers.colors.mcyan(steps[0][2])}`,
735
+ );
736
+ steps.slice(1).forEach((step) => {
737
+ console.info(
738
+ `${indent}${sep} ${helpers.colors.lyellow(
739
+ "[ ",
740
+ )}${helpers.colors.yellow(step[1])}${" ".repeat(
741
+ 12 - step[1].length,
742
+ )}${helpers.colors.lyellow(
743
+ " ]",
744
+ )} ${" ".repeat(2 * step[0])}${helpers.colors.mcyan(step[2])}`,
745
+ );
746
+ });
747
+ const outputType =
748
+ source.script.outputType.constructor.name || "RadonAny";
749
+ console.info(
750
+ `${indent}${sep} ${helpers.colors.lyellow(
751
+ "[ ",
752
+ )}${helpers.colors.yellow(outputType)}${" ".repeat(
753
+ 12 - outputType.length,
754
+ )}${helpers.colors.lyellow(" ]")}`,
755
+ );
756
+ }
757
+ }
758
+ if (sourceIndex < request.sources.length - 1) {
759
+ console.info(`${indent} │ │`);
760
+ }
761
+ });
762
+ console.info(`${indent}┌──┴──────────────────┐`);
763
+ console.info(`${indent}│ ${helpers.colors.white("AGGREGATE SOURCES")} │`);
764
+ console.info(`${indent}└──┬──────────────────┘`); // ┬
765
+ request.sourcesReducer?.filters.forEach((filter) =>
766
+ console.info(
767
+ `${indent} │ > Radon filter: ${stringifyFilter(filter)}`,
768
+ ),
769
+ );
770
+ console.info(
771
+ `${indent} │ > Radon reducer: ${stringifyReducer(request.sourcesReducer)}`,
772
+ );
773
+ console.info(`${indent}┌──┴──────────────────┐`);
774
+ console.info(`${indent}│ ${helpers.colors.white("WITNESSING TALLY")} │`);
775
+ console.info(`${indent}└─────────────────────┘`); // ┬
776
+ request.witnessReducer?.filters.forEach((filter) =>
777
+ console.info(
778
+ `${indent} > Radon filter: ${stringifyFilter(filter)}`,
779
+ ),
780
+ );
781
+ console.info(
782
+ `${indent} > Radon reducer: ${stringifyReducer(request.witnessReducer)}`,
783
+ );
784
+ }
785
+ }
786
+
787
+ async function traceWitnetRadonRequestDryRun(request, options) {
788
+ const bytecode = request.toBytecode();
789
+ let report = await helpers
790
+ .toolkitRun(options, [
791
+ "try-data-request",
792
+ "--hex",
793
+ bytecode.startsWith("0x") ? bytecode.slice(2) : bytecode,
794
+ ])
795
+ .catch((err) => {
796
+ let errorMessage = err.message.split("\n").slice(1).join("\n").trim();
797
+ const errorRegex = /.*^error: (?<message>.*)$.*/gm;
798
+ const matched = errorRegex.exec(err.message);
799
+ if (matched) {
800
+ errorMessage = matched.groups.message;
801
+ }
802
+ throw errorMessage || err;
803
+ });
804
+ if (!report) {
805
+ throw Error("No dry-report?");
806
+ } else {
807
+ report = JSON.parse(report);
808
+ }
809
+ const result = report?.aggregate.result;
810
+ const resultType = Object.keys(result)[0];
811
+ const resultValue = Object.values(result)[0];
812
+ let resultSize;
813
+ const parseRadonResult = (value) => {
814
+ if (Array.isArray(value)) {
815
+ return value.map((item) => parseRadonResult(item));
816
+ }
817
+ if (typeof value === "object") {
818
+ return parseRadonResult(Object.values(value)[0]);
819
+ } else {
820
+ return JSON.parse(value);
821
+ }
822
+ };
823
+ switch (resultType) {
824
+ case "RadonBoolean":
825
+ resultSize = 1;
826
+ break;
827
+ case "RadonBytes":
828
+ resultSize =
829
+ utils.cbor.encode(Uint8Array.from(resultValue)).byteLength - 2;
830
+ break;
831
+ case "RadonInteger":
832
+ case "RadonFloat":
833
+ resultSize = utils.cbor.encode(resultValue).byteLength;
834
+ break;
835
+ case "RadonArray":
836
+ case "RadonMap": {
837
+ const parsed = parseRadonResult(resultValue);
838
+ resultSize = utils.cbor.encode(parsed).byteLength;
839
+ break;
840
+ }
841
+ }
842
+ if (options?.json) {
843
+ if (options?.verbose) {
844
+ console.info(
845
+ JSON.stringify(
846
+ report,
847
+ null,
848
+ options?.indent ? " ".repeat(options.indent) : "",
849
+ ),
850
+ );
851
+ } else {
852
+ result[resultType] = resultValue;
853
+ console.info(
854
+ JSON.stringify(
855
+ result,
856
+ null,
857
+ options?.indent ? " ".repeat(options.indent) : "",
858
+ ),
859
+ );
860
+ }
861
+ return;
862
+ }
863
+ if (!options.headline)
864
+ options.headline = "WITNET DATA REQUEST DRY-RUN REPORT";
865
+ traceWitnetRadonReportHeadline(request, options);
866
+ const indent = options?.indent ? " ".repeat(options.indent) : "";
867
+ console.info(
868
+ `${indent}╚══╤═══════════════════════════════════════════════════════════════════════════╝`,
869
+ );
870
+ let execTimeMs = report.retrieve
871
+ ?.map(
872
+ (retrieval) =>
873
+ (retrieval?.running_time.secs || 0) +
874
+ (retrieval?.running_time.nanos || 0) / 1000,
875
+ )
876
+ .reduce((sum, secs) => sum + secs);
877
+ execTimeMs = `${Math.round(execTimeMs)} ms`;
878
+ let flexbar = "─".repeat(17);
879
+ let flexspc = " ".repeat(flexbar.length + 12);
880
+ console.info(`${indent}┌──┴─────────────────────────────${flexbar}──────┐`);
881
+ console.info(
882
+ `${indent}│ ${helpers.colors.white("Data providers")} ${flexspc} │`,
883
+ ); // ├ ┤
884
+ console.info(`${indent}├────────────────────────────────${flexbar}──────┤`);
885
+ console.info(
886
+ `${indent}│ Execution time: ${helpers.colors.green(execTimeMs)} ${" ".repeat(flexbar.length + 19 - execTimeMs.length)} │`,
887
+ );
888
+ console.info(`${indent}└──┬─┬───────────────────────────${flexbar}──────┘`);
889
+ request.sources.forEach((source, sourceIndex) => {
890
+ const authority =
891
+ source.authority?.toUpperCase().split(".").slice(-2).join(".") ||
892
+ (source.method === Witnet.Radon.retrievals.Methods.RNG ? "WIT/RNG" : "");
893
+ const corner = sourceIndex === request.sources.length - 1 ? "└" : "├";
894
+ const sep = sourceIndex === request.sources.length - 1 ? " " : "│";
895
+ const color = report.retrieve[sourceIndex].result?.RadonError
896
+ ? options?.verbose
897
+ ? helpers.colors.lgray
898
+ : helpers.colors.gray
899
+ : options?.verbose
900
+ ? helpers.colors.lgreen
901
+ : helpers.colors.green;
902
+ if (options?.verbose) {
903
+ console.info(
904
+ `${indent}${corner}─ ${helpers.colors.white(
905
+ "[ ",
906
+ )}${helpers.colors.white(
907
+ `Data Source #${sourceIndex + 1}`,
908
+ )} ${" ".repeat(3 - sourceIndex.toString().length)}${color(
909
+ authority,
910
+ )} ${helpers.colors.white("]")}`,
911
+ );
912
+ } else {
913
+ console.info(`${indent} │ ${corner}─ [ ${color(authority)} ]`);
914
+ }
915
+ if (
916
+ source.method !== Witnet.Radon.retrievals.Methods.RNG &&
917
+ options?.verbose
918
+ ) {
919
+ console.info(
920
+ `${indent} │ ${sep} > Request: ${helpers.colors.mgreen(
921
+ Witnet.Radon.retrievals.Methods[source.method]
922
+ .split(/(?=[A-Z])/)
923
+ .join("-")
924
+ .toUpperCase(),
925
+ )}`,
926
+ );
927
+ console.info(
928
+ `${indent} │ ${sep} > URL query: ${helpers.colors.green(source.url)}`,
929
+ );
930
+ if (source?.headers && Object.keys(source.headers).length > 0) {
931
+ console.info(
932
+ `${indent} │ ${sep} > HTTP headers: ${helpers.colors.green(JSON.stringify(source.headers))}`,
933
+ );
934
+ }
935
+ if (source?.body) {
936
+ console.info(
937
+ `${indent} │ ${sep} > HTTP body: ${helpers.colors.green(source.body)}`,
938
+ );
939
+ }
940
+ const printData = (headline, data, color) => {
941
+ const type = Object.keys(data)[0];
942
+ data =
943
+ (typeof data[type] === "object" ||
944
+ typeof data[type] === "boolean" ||
945
+ Array.isArray(data[type])
946
+ ? JSON.stringify(data[type])
947
+ : data[type]) || "";
948
+ const lines = data.match(/.{1,96}/g)?.slice(0, 256) || [""];
949
+ if (lines.length === 256) lines[255] += "...";
950
+ const typeColor =
951
+ type === "RadonError" ? helpers.colors.red : helpers.colors.yellow;
952
+ const lineColor = type === "RadonError" ? helpers.colors.gray : color;
953
+ console.info(
954
+ `${indent}${sep} > ${headline}${" ".repeat(15 - headline.length)} \x1b[1;m${typeColor(
955
+ "[ ",
956
+ )}\x1b[0m${typeColor(type)}${" ".repeat(
957
+ 12 - type.length,
958
+ )}\x1b[1;m${typeColor(" ]")}\x1b[0m ${lineColor(lines[0])}`,
959
+ );
960
+ lines.slice(1).forEach((line) => {
961
+ console.info(
962
+ `${indent} │ ${sep} ${lineColor(line)}`,
963
+ );
964
+ });
965
+ };
966
+ if (report?.retrieve[sourceIndex]?.partial_results) {
967
+ printData(
968
+ "HTTP response:",
969
+ report?.retrieve[sourceIndex]?.partial_results[0],
970
+ helpers.colors.cyan,
971
+ );
972
+ }
973
+ printData(
974
+ "Radon result:",
975
+ report?.retrieve[sourceIndex]?.result,
976
+ helpers.colors.mcyan,
977
+ );
978
+ }
979
+ if (options?.verbose && sourceIndex < request.sources.length - 1) {
980
+ console.info(`${indent} │ │`);
981
+ }
982
+ });
983
+ flexbar = "─".repeat(24);
984
+ flexspc = " ".repeat(36);
985
+ console.info(`${indent}┌──┴───────────────────────────${flexbar}─┐`);
986
+ console.info(
987
+ `${indent}│ ${helpers.colors.white("Aggregated result")}${flexspc} │`,
988
+ ); // ├ ┤
989
+ console.info(`${indent}├──────────────────────────────${flexbar}─┤`);
990
+ if (options?.verbose) {
991
+ let partial_index = 0;
992
+ const partial_results = report.sourcesReducer?.partial_results;
993
+ request.sourcesReducer?.filters.forEach((filter) => {
994
+ const color = partial_results?.[partial_index]?.RadonArray
995
+ ? helpers.colors.mcyan
996
+ : helpers.colors.gray;
997
+ const items = partial_results?.[partial_index]?.RadonArray
998
+ ? ` over ${partial_results[partial_index]?.RadonArray.length} sources`
999
+ : "";
1000
+ partial_index += 1;
1001
+ filter = stringifyFilter(filter, color);
1002
+ console.info(
1003
+ `${indent} Radon filter: ${filter}${helpers.colors.cyan(
1004
+ items,
1005
+ )}${" ".repeat(flexbar.length + 22 - filter.length - items.length)} │`,
1006
+ );
1007
+ });
1008
+ const color = partial_results?.[partial_index]?.RadonArray
1009
+ ? helpers.colors.mcyan
1010
+ : helpers.colors.gray;
1011
+ const items = partial_results?.[partial_index]?.RadonArray
1012
+ ? ` over ${partial_results[partial_index]?.RadonArray.length} sources`
1013
+ : "";
1014
+ const reducer = stringifyReducer(request.sourcesReducer, color);
1015
+ console.info(
1016
+ `${indent}│ Radon reducer: ${reducer}${helpers.colors.cyan(items)}${" ".repeat(
1017
+ flexbar.length + 22 - reducer.length - items.length,
1018
+ )} │`,
1019
+ );
1020
+ }
1021
+ if (resultSize) {
1022
+ console.info(
1023
+ `${indent}│ CBOR size: ${helpers.colors.cyan(
1024
+ `${resultSize} bytes`,
1025
+ )}${" ".repeat(flexbar.length + 7 - resultSize.toString().length)} │`,
1026
+ );
1027
+ }
1028
+ console.info(`${indent}└────┬─────────────────────────${flexbar}─┘`);
1029
+ const printMapItem = (indent, width, key, value, indent2 = "") => {
1030
+ if (key) key = `${indent2}${key}: `;
1031
+ else key = `${indent2}`;
1032
+ let type = extractTypeName(Object.keys(value)[0]);
1033
+ value = Object.values(value)[0];
1034
+ if (["Map", "Array"].includes(type)) {
1035
+ if (key.length > width - 12) {
1036
+ console.info(
1037
+ `${indent} ${helpers.colors.myellow(
1038
+ `[ ${type}${" ".repeat(7 - type.length)} ]`,
1039
+ )} ${" ".repeat(width - 15)}${helpers.colors.green("...")}`,
1040
+ );
1041
+ } else {
1042
+ console.info(
1043
+ `${indent} ${helpers.colors.myellow(
1044
+ `[ ${type}${" ".repeat(7 - type.length)} ]`,
1045
+ )} ${helpers.colors.green(key)}${" ".repeat(
1046
+ width - 12 - key.length,
1047
+ )}`,
1048
+ );
1049
+ }
1050
+ Object.entries(value).forEach(([key, value]) =>
1051
+ printMapItem(
1052
+ indent,
1053
+ width,
1054
+ type === "Map" ? key : null,
1055
+ helpers.unescapeSlashes(value),
1056
+ `${indent2} `,
1057
+ ),
1058
+ );
1059
+ } else {
1060
+ if (key.length > width - 12) {
1061
+ console.info(
1062
+ `${indent} ${helpers.colors.yellow(type)} ${" ".repeat(width - 15)}${helpers.colors.green("...")}`,
1063
+ );
1064
+ } else {
1065
+ type = `[ ${type}${" ".repeat(7 - type.length)} ]`;
1066
+ const result = key + value;
1067
+ // let spaces = width - 12 - result.length
1068
+ if (result.length > width - 15) {
1069
+ value = `${value.slice(0, width - 15 - key.length)}...`;
1070
+ // spaces = 0
1071
+ }
1072
+ if (["String", "Error"].includes(type)) {
1073
+ console.info(
1074
+ `${indent} ${helpers.colors.yellow(type)} ${helpers.colors.green(key)}"${helpers.colors.mcyan(value)}"`,
1075
+ );
1076
+ } else {
1077
+ console.info(
1078
+ `${indent} ${helpers.colors.yellow(type)} ${helpers.colors.green(key)}${helpers.colors.mcyan(value)}`,
1079
+ );
1080
+ }
1081
+ }
1082
+ }
1083
+ };
1084
+ const printResult = (indent, width, resultType, resultValue) => {
1085
+ resultType = extractTypeName(resultType);
1086
+ resultValue =
1087
+ typeof resultValue === "object" || Array.isArray(resultValue)
1088
+ ? JSON.stringify(resultValue)
1089
+ : resultValue;
1090
+ if (["Map", "Array"].includes(resultType)) {
1091
+ console.info(
1092
+ `${indent} └─ ${helpers.colors.lyellow(`[ ${resultType}${" ".repeat(7 - resultType.length)} ]`)}`,
1093
+ );
1094
+ const obj = JSON.parse(resultValue);
1095
+ Object.entries(obj).forEach(([key, value]) =>
1096
+ printMapItem(indent, width, resultType === "Map" ? key : null, value),
1097
+ );
1098
+ } else {
1099
+ if (resultType === "Bytes") {
1100
+ resultValue = JSON.parse(resultValue)
1101
+ .map((char) => `00${char.toString(16)}`.slice(-2))
1102
+ .join("");
1103
+ } else if (resultType === "Boolean") {
1104
+ resultValue = JSON.stringify(resultValue);
1105
+ }
1106
+ const color =
1107
+ resultType.indexOf("Error") > -1
1108
+ ? helpers.colors.gray
1109
+ : helpers.colors.lcyan;
1110
+ const typeText =
1111
+ resultType.indexOf("Error") > -1
1112
+ ? "\x1b[1;98;41m Error \x1b[0m"
1113
+ : helpers.colors.lyellow(`[ ${resultType} ]`);
1114
+ const lines = resultValue.match(/.{1,96}/g)?.slice(0, 256) || [""];
1115
+ console.info(`${indent} └─ ${typeText} ${color(lines[0])}`);
1116
+ lines.slice(1).forEach((line) => {
1117
+ console.info(
1118
+ `${indent} ${" ".repeat(resultType.length)}${color(line)}`,
1119
+ );
1120
+ });
1121
+ }
1122
+ };
1123
+ printResult(indent, 134, resultType, resultValue);
1124
+ }