@witnet/sdk 1.0.15 → 1.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/dist/package.json +13 -13
  2. package/dist/src/bin/helpers.d.ts +1 -0
  3. package/dist/src/bin/helpers.d.ts.map +1 -1
  4. package/dist/src/bin/helpers.js +34 -5
  5. package/dist/src/lib/crypto/payloads/DataRequestPayload.d.ts +7 -4
  6. package/dist/src/lib/crypto/payloads/DataRequestPayload.d.ts.map +1 -1
  7. package/dist/src/lib/crypto/payloads/DataRequestPayload.js +42 -16
  8. package/dist/src/lib/crypto/payloads.d.ts.map +1 -1
  9. package/dist/src/lib/crypto/payloads.js +1 -2
  10. package/dist/src/lib/crypto/signer.js +12 -9
  11. package/dist/src/lib/crypto/transmitters.js +2 -2
  12. package/dist/src/lib/crypto/types.d.ts.map +1 -1
  13. package/dist/src/lib/crypto/types.js +1 -2
  14. package/dist/src/lib/radon/index.d.ts +4 -2
  15. package/dist/src/lib/radon/index.d.ts.map +1 -1
  16. package/dist/src/lib/radon/index.js +50 -32
  17. package/dist/src/lib/radon/types.d.ts +31 -27
  18. package/dist/src/lib/radon/types.d.ts.map +1 -1
  19. package/dist/src/lib/radon/types.js +88 -46
  20. package/dist/src/lib/radon/utils.js +3 -3
  21. package/dist/src/lib/rpc/provider.d.ts +12 -0
  22. package/dist/src/lib/rpc/provider.d.ts.map +1 -1
  23. package/dist/src/lib/rpc/provider.js +11 -1
  24. package/dist/witnet/assets/index.d.ts +1 -2
  25. package/dist/witnet/assets/modals/index.d.ts +1 -2
  26. package/dist/witnet/assets/modals/web3/eth.js +3 -3
  27. package/dist/witnet/assets/modals/web3/ipfs.d.ts +1 -2
  28. package/dist/witnet/assets/modals/web3/ipfs.js +11 -9
  29. package/dist/witnet/assets/modals/web3/wit.js +4 -4
  30. package/dist/witnet/assets/requests.js +6 -51
  31. package/package.json +13 -13
  32. package/src/bin/cli/inspect.js +103 -13
  33. package/src/bin/cli/radon.js +157 -79
  34. package/src/bin/cli/wallet.js +4 -6
  35. package/src/bin/helpers.js +37 -4
  36. package/src/bin/toolkit.js +2 -2
  37. package/witnet/assets/modals/web3/eth.js +2 -2
  38. package/witnet/assets/modals/web3/ipfs.js +9 -6
  39. package/witnet/assets/modals/web3/wit.js +3 -3
  40. package/witnet/assets/requests.js +5 -51
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@witnet/sdk",
3
- "version": "1.0.15",
3
+ "version": "1.1.1",
4
4
  "description": "Typescript library and CLI tooling for Web3 buidlers willing to interact with the Witnet blockchain.",
5
5
  "author": "Witnet Foundation",
6
6
  "license": "MIT",
@@ -19,45 +19,45 @@
19
19
  ],
20
20
  "exports": {
21
21
  ".": {
22
+ "types": "./dist/src/*.d.ts",
22
23
  "require": "./dist/src/index.js",
23
- "default": "./dist/src/index.js",
24
- "types": "./dist/src/*.d.ts"
24
+ "default": "./dist/src/index.js"
25
25
  },
26
26
  "./assets": "./dist/witnet/assets/index.js",
27
27
  "./utils": {
28
+ "types": "./dist/src/lib/*.d.ts",
28
29
  "require": "./dist/src/lib/utils.js",
29
- "default": "./dist/src/lib/utils.js",
30
- "types": "./dist/src/lib/*.d.ts"
30
+ "default": "./dist/src/lib/utils.js"
31
31
  }
32
32
  },
33
33
  "types": "./dist",
34
34
  "dependencies": {
35
- "axios": "^1.11.0",
35
+ "axios": "^1.12.2",
36
36
  "bech32": "~2.0.0",
37
37
  "bip32": "^4.0.0",
38
- "cbor": "^10.0.10",
38
+ "cbor": "^10.0.11",
39
39
  "dotenv": "^16.6.1",
40
- "ethers": "^5.8.0",
40
+ "ethers": "^6.15.0",
41
41
  "graphql-query-compress": "1.2.4",
42
- "inquirer": "^12.9.1",
42
+ "inquirer": "^12.9.6",
43
43
  "json-bigint": "^1.0.0",
44
44
  "keccak256": "^1.0.6",
45
45
  "lodash.merge": "^4.6.2",
46
46
  "long": "^5.3.2",
47
47
  "moment": "^2.30.1",
48
48
  "promise-poller": "~1.9.1",
49
- "protobufjs": "^7.5.3",
49
+ "protobufjs": "^7.5.4",
50
50
  "qrcode-terminal": "^0.12.0",
51
51
  "secp256k1": "^5.0.1",
52
52
  "tiny-secp256k1": "~2.2.4"
53
53
  },
54
54
  "devDependencies": {
55
- "@types/node": "^22.17.1",
56
- "cross-env": "7.0.3",
55
+ "@types/node": "^22.18.5",
56
+ "cross-env": "10.0.0",
57
57
  "eslint": "8.56.0",
58
58
  "eslint-config-standard": "^17.1.0",
59
59
  "eslint-plugin-import": "^2.32.0",
60
- "eslint-plugin-n": "^17.21.3",
60
+ "eslint-plugin-n": "^17.23.0",
61
61
  "eslint-plugin-promise": "^7.2.1",
62
62
  "protobufjs-cli": "^1.1.3",
63
63
  "typescript": "^5.9.2"
@@ -1,3 +1,4 @@
1
+ const cbor = require("cbor")
1
2
  const moment = require("moment")
2
3
 
3
4
  const helpers = require("../helpers")
@@ -5,6 +6,8 @@ const { utils, Witnet } = require("../../../dist/src")
5
6
 
6
7
  const { cyan, gray, green, lyellow, magenta, mgreen, mmagenta, myellow, yellow } = helpers.colors
7
8
 
9
+ const DEFAULT_LIMIT = 100
10
+
8
11
  /// ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
9
12
  /// CLI SUBMODULE CONSTANTS ===========================================================================================
10
13
 
@@ -15,7 +18,10 @@ module.exports = {
15
18
  flags: {
16
19
  provider: {
17
20
  hint: "Public Wit/Oracle JSON-RPC provider, other than default.",
18
- param: ":http-url",
21
+ param: "URL",
22
+ },
23
+ reverse: {
24
+ hint: "List most recent data requests first (default: true).",
19
25
  },
20
26
  verbose: {
21
27
  hint: "Outputs validators' nonce and last validation epochs.",
@@ -43,22 +49,22 @@ module.exports = {
43
49
  },
44
50
  },
45
51
  },
46
- "dataRequests*": {
52
+ dataRequests: {
47
53
  hint: "Search for in-flight or recently solved data request transactions.",
48
- params: "BYTECODE | RAD_HASH | DDR_HASH",
54
+ params: "RAD_BYTECODE | RAD_HASH",
49
55
  options: {
50
56
  limit: { hint: "Limit output records (default: 100).", param: "LIMIT" },
51
- since: {
52
- hint: "Number of past epochs to search for (default: 256; max: 2048).",
53
- param: "EPOCH|MINUS_EPOCHS",
57
+ offset: {
58
+ hint: "Skips first records as found on server side (default: 0).",
59
+ param: "SKIP",
54
60
  },
55
- "min-unitary-reward": {
56
- hint: "Filters out those providing less unitary reward than specified.",
57
- param: "NANOWITS",
61
+ mode: {
62
+ hint: "Possible report formats (default: `ethereal`).",
63
+ param: "`ethereal` | `full``",
58
64
  },
59
- "min-witnesses": {
60
- hint: "Filters out those solved with less than specified witnesses.",
61
- param: "NUM_WITNESSES",
65
+ since: {
66
+ hint: "Number of past epochs to search for (default: -30240).",
67
+ param: "EPOCH|MINUS_EPOCHS",
62
68
  },
63
69
  },
64
70
  },
@@ -111,7 +117,7 @@ module.exports = {
111
117
  },
112
118
  },
113
119
  subcommands: {
114
- balance, block, dataRequest, superblock, transaction, validators, withdrawers, utxos, valueTransfer,
120
+ balance, block, dataRequest, dataRequests, superblock, transaction, validators, withdrawers, utxos, valueTransfer,
115
121
  },
116
122
  }
117
123
 
@@ -167,6 +173,90 @@ async function block (options = {}, args = []) {
167
173
  }, 2)))
168
174
  }
169
175
 
176
+ async function dataRequests(options = {}, [arg]) {
177
+ // if (!args || args.length === 0) {
178
+ if (!arg) {
179
+ throw new Error("No RAD_HASH or RAD_RAD_BYTECODE was specified.")
180
+ }
181
+ const provider = new Witnet.JsonRpcProvider(options?.provider)
182
+ // const radHashes = args.map(arg => {
183
+ if (!helpers.isHexString(arg)) {
184
+ throw new Error(`Invalid hex string was provided: '${arg}'`)
185
+ }
186
+ let radHash
187
+ if (helpers.isHexStringOfLength(arg, 32)) {
188
+ radHash = arg
189
+ } else {
190
+ const request = Witnet.Radon.RadonRequest.fromBytecode(arg)
191
+ radHash = request.radHash
192
+ }
193
+ // return radHash
194
+ // })
195
+ // let results = await helpers.prompter(
196
+ // Promise.all(
197
+ // [...new Set(radHashes)].map(radHash => provider.searchDataRequests(radHash, {
198
+ // limit: options?.limit ? parseInt(options.limit) : undefined,
199
+ // offset: options?.offset ? parseInt(options.offset) : undefined,
200
+ // reverse: options?.reverse,
201
+ // }))
202
+ // ).then(results => results
203
+ // .flat()
204
+ // .sort((a, b) => options?.reverse ? b.block_epoch - a.block_epoch : a.block_epoch - b.block_epoch)
205
+ // .slice(options?.offset)
206
+ // .slice(0, options?.limit || DEFAULT_LIMIT)
207
+ // )
208
+ // )
209
+ const results = await helpers.prompter(
210
+ provider.searchDataRequests(radHash, {
211
+ limit: options?.limit ? parseInt(options.limit) : undefined,
212
+ offset: options?.offset ? parseInt(options.offset) : undefined,
213
+ mode: options?.mode,
214
+ reverse: options?.reverse,
215
+ })
216
+ )
217
+ helpers.traceTable(
218
+ results.map(record => {
219
+ let result = record?.result.cbor_bytes ? cbor.decode(record?.result.cbor_bytes, { encoding: "hex" }) : ""
220
+ const request = Witnet.Radon.RadonRequest.fromBytecode(record.query.rad_bytecode)
221
+ const dataType = result.constructor.name === "Tagged" ? "RadonError" : request.dataType
222
+ if (dataType !== "RadonError") result = Buffer.from(utils.fromHexString(record?.result.cbor_bytes)).toString('base64');
223
+ else if (result.constructor.name === "Buffer") result = result.toString('base64');
224
+ return [
225
+ record.block_epoch,
226
+ record.hash,
227
+ record.query.witnesses,
228
+ Witnet.Coins.fromPedros(record.query.unitary_reward).toString(2),
229
+ dataType === "RadonError" ? helpers.colors.mred("RadonError") : helpers.colors.mgreen(dataType),
230
+ ...(options?.verbose ? [
231
+ dataType === "RadonError" ? helpers.colors.red(result) : (
232
+ record?.result.finalized ? helpers.colors.mcyan(result) : helpers.colors.cyan(result)
233
+ ),
234
+ ] : [
235
+ record?.result ? record.result.cbor_bytes.length / 2 + " bytes" : "",
236
+ record?.result.timestamp ? moment.unix(record.result.timestamp).fromNow() : "",
237
+ ]),
238
+ ]
239
+ }), {
240
+ headlines: [
241
+ "EPOCH:",
242
+ "DATA REQUEST TRANSACION HASH",
243
+ "witnesses",
244
+ "total fees",
245
+ ":data type",
246
+ ...(options?.verbose ? [":DATA REQUEST RESULT"] : ["CBOR SIZE:", "DATA FRESHNESS:"])
247
+ ],
248
+ humanizers: [ helpers.commas ],
249
+ colors: [
250
+ , helpers.colors.gray,
251
+ helpers.colors.green,
252
+ helpers.colors.green,,
253
+ helpers.colors.cyan,
254
+ helpers.colors.mcyan,
255
+ ]
256
+ }
257
+ )
258
+ }
259
+
170
260
  async function dataRequest (options = {}, args = []) {
171
261
  if (args.length === 0) {
172
262
  throw Error("No DR_TX_HASH was specified")
@@ -1,3 +1,4 @@
1
+ const cbor = require("cbor")
1
2
  const fs = require("fs")
2
3
  const inquirer = require("inquirer")
3
4
  const merge = require("lodash.merge")
@@ -26,12 +27,21 @@ module.exports = {
26
27
  hint: "List available Witnet Radon assets.",
27
28
  params: "[RADON_ASSETS ...]",
28
29
  options: {
30
+ filter: {
31
+ hint: "Restrict output to name-matching assets.",
32
+ },
29
33
  legacy: {
30
34
  hint: "List only those declared in witnet/assets folder.",
31
35
  },
32
- filter: {
33
- hint: "Restrict output to name-matching assets.",
36
+ modals: {
37
+ hint: "Restrict output to Radon modals.",
38
+ },
39
+ requests: {
40
+ hint: "Restrict output to Radon requests.",
34
41
  },
42
+ templates: {
43
+ hint: "Restrict output to Radon templates.",
44
+ },
35
45
  },
36
46
  },
37
47
  check: {
@@ -168,21 +178,25 @@ async function assets (options = {}, [...patterns]) {
168
178
  `${options?.module ? options.module.toUpperCase() : path.basename(process.cwd()).toUpperCase()} RADON ASSETS`,
169
179
  helpers.colors.white
170
180
  )
171
- const assets = clearEmptyBranches(loadAssets(options), patterns, options?.filter)
181
+ const assets = clearEmptyBranches(
182
+ options?.module ? require(options.module) : loadAssets(options),
183
+ patterns,
184
+ options
185
+ );
172
186
  if (assets && Object.keys(assets).length > 0) {
173
- traceWitnetArtifacts(assets, patterns, " ", options?.filter)
187
+ traceWitnetArtifacts(assets, patterns, " ", options)
174
188
  } else {
175
189
  console.info("> No custom Radon assets declared just yet.")
176
190
  }
177
191
  }
178
192
  /// -------------------------------------------------------------------------------------------------------------------
179
193
 
180
- async function check (options = {}) {
194
+ async function check () {
181
195
  if (!isModuleInitialized) {
182
196
  throw new Error(`No Witnet Radon workspace has been initialized. Please, run ${white("npx witsdk radon init")} if willing to declare your own Radon assets.`)
183
197
  }
184
198
  try {
185
- const assets = loadAssets({ ...options, legacy: true })
199
+ const assets = loadAssets({ legacy: true })
186
200
  const [
187
201
  modals,
188
202
  requests,
@@ -233,7 +247,7 @@ async function decode (options = {}, args = []) {
233
247
  } else {
234
248
  args = args.slice(1)
235
249
 
236
- const assets = loadAssets(options)
250
+ const assets = options?.module ? require(options.module) : loadAssets(options)
237
251
  const headline = options?.headline
238
252
  const crafts = flattenRadonArtifacts(assets).filter(craft => craft.key.toLowerCase().indexOf(asset.toLowerCase()) >= 0)
239
253
  if (crafts.length === 0) {
@@ -244,11 +258,12 @@ async function decode (options = {}, args = []) {
244
258
  if (artifact instanceof Witnet.Radon.RadonRequest) {
245
259
  prefix = "RadonRequest::"
246
260
  } else if (artifact instanceof Witnet.Radon.RadonModal) {
247
- artifact.providers = ["https://dummy"]
261
+ artifact.providers = [...args[0].split(";") || "https://dummy"]
248
262
  const modalArgs = []
249
- let argIndex = 0
263
+ let argIndex = 1
250
264
  while (modalArgs.length < artifact.argsCount) {
251
- modalArgs.push(`{:${++argIndex}}`)
265
+ modalArgs.push(args[argIndex] || `{:${argIndex}}`)
266
+ argIndex += 1
252
267
  }
253
268
  artifact = artifact.buildRadonRequest(modalArgs)
254
269
  prefix = "RadonModal::"
@@ -298,7 +313,7 @@ async function dryrun (options = {}, args = []) {
298
313
  }
299
314
  } else {
300
315
  args = args.slice(1)
301
- const assets = loadAssets(options)
316
+ const assets = options?.module ? require(options.module) : loadAssets(options)
302
317
  const headline = options?.headline
303
318
  const crafts = flattenRadonArtifacts(assets).filter(craft => craft.key.toLowerCase().indexOf(asset.toLowerCase()) >= 0)
304
319
  if (crafts.length === 0) {
@@ -309,33 +324,48 @@ async function dryrun (options = {}, args = []) {
309
324
  if (artifact instanceof Witnet.Radon.RadonRequest) {
310
325
  prefix = "RadonRequest::"
311
326
  } else {
312
- if (!artifact?.samples) {
313
- console.error(`${artifact.constructor.name}::${key}: cannot dry-run if no sample parameters are declared.\n`)
314
- continue
315
- }
316
327
  let artifactArgs = []
317
- if (options?.default) {
318
- artifactArgs = Object.values(artifact.samples)[0]
319
- } else {
320
- const prompt = inquirer.createPromptModule()
321
- const sample = await prompt([{
322
- choices: Object.keys(artifact.samples),
323
- message: `${artifact.constructor.name}::${key} args:`,
324
- name: "key",
325
- type: "list",
326
- }])
327
- artifactArgs = artifact.samples[sample.key]
328
- }
329
328
  if (artifact instanceof Witnet.Radon.RadonModal) {
330
- artifact.providers = artifactArgs.shift().split(";")
331
- artifact = artifact.buildRadonRequest(artifactArgs)
329
+ if (args.length < artifact.argsCount) {
330
+ throw new Error(`missing parameters for Radon Modal.`)
331
+ }
332
+ artifact.providers = [...args[0].split(";")]
333
+ const modalArgs = []
334
+ let argIndex = 1
335
+ while (modalArgs.length < artifact.argsCount) {
336
+ modalArgs.push(args[argIndex])
337
+ argIndex += 1
338
+ }
339
+ artifact = (
340
+ artifact.homogeneous
341
+ ? artifact.buildRadonRequest(modalArgs)
342
+ : artifact.buildRadonRequest([ ...artifact.sources.map(source => modalArgs.slice(0, source.argsCount)) ])
343
+ )
332
344
  prefix = "RadonModal::"
333
- } else if (artifact instanceof Witnet.Radon.RadonTemplate) {
334
- artifact = artifact.buildRadonRequest(artifactArgs)
335
- prefix = "RadonTemplate::"
336
- } else if (artifact instanceof Witnet.Radon.RadonRetrieval) {
337
- artifact = new Witnet.Radon.RadonRequest({ sources: artifact.foldArgs(artifactArgs) })
338
- prefix = "RadonRetrieval::"
345
+ } else {
346
+ if (!artifact?.samples) {
347
+ console.error(`${artifact.constructor.name}::${key}: cannot dry-run if no sample parameters are declared.\n`)
348
+ continue
349
+ }
350
+ if (options?.default) {
351
+ artifactArgs = Object.values(artifact.samples)[0]
352
+ } else {
353
+ const prompt = inquirer.createPromptModule()
354
+ const sample = await prompt([{
355
+ choices: Object.keys(artifact.samples),
356
+ message: `${artifact.constructor.name}::${key} args:`,
357
+ name: "key",
358
+ type: "list",
359
+ }])
360
+ artifactArgs = artifact.samples[sample.key]
361
+ }
362
+ if (artifact instanceof Witnet.Radon.RadonTemplate) {
363
+ artifact = artifact.buildRadonRequest(artifactArgs)
364
+ prefix = "RadonTemplate::"
365
+ } else if (artifact instanceof Witnet.Radon.RadonRetrieval) {
366
+ artifact = new Witnet.Radon.RadonRequest({ sources: artifact.foldArgs(artifactArgs) })
367
+ prefix = "RadonRetrieval::"
368
+ }
339
369
  }
340
370
  }
341
371
  if (!headline) {
@@ -367,8 +397,12 @@ const stringifyReducer = (x, c) => {
367
397
  }
368
398
 
369
399
  function loadAssets (options) {
370
- const { assets } = options?.module ? require(options.module) : (options?.legacy ? {} : require("@witnet/sdk"))
371
- return isModuleInitialized && fs.existsSync(`${WITNET_ASSETS_PATH}`) ? merge(assets, require(`${WITNET_ASSETS_PATH}`)) : assets
400
+ const { assets } = options?.legacy ? {} : require("@witnet/sdk")
401
+ return (
402
+ isModuleInitialized && fs.existsSync(`${WITNET_ASSETS_PATH}`)
403
+ ? merge(assets, require(`${WITNET_ASSETS_PATH}`))
404
+ : assets
405
+ );
372
406
  }
373
407
 
374
408
  function flattenRadonArtifacts (tree, headers) {
@@ -395,44 +429,64 @@ function flattenRadonArtifacts (tree, headers) {
395
429
  return matches
396
430
  };
397
431
 
398
- function countWitnetArtifacts (assets, args, filter = false) {
432
+ function countWitnetArtifacts (assets, args, options) {
399
433
  let counter = 0
400
434
  Object.entries(assets).forEach(([key, value]) => {
401
- if ((
402
- value instanceof Witnet.Radon.RadonModal ||
403
- value instanceof Witnet.Radon.RadonRequest ||
404
- value instanceof Witnet.Radon.RadonTemplate ||
405
- value instanceof Witnet.Radon.RadonRetrieval
406
- ) && (
407
- !filter ||
408
- !args ||
409
- args.length === 0 ||
410
- args.find(arg => key.toLowerCase().indexOf(arg.toLowerCase()) >= 0)
435
+ let include = (
436
+ (options?.modals && value instanceof Witnet.Radon.RadonModal)
437
+ || (options?.templates && value instanceof Witnet.Radon.RadonTemplate)
438
+ || (options?.retrievals && value instanceof Witnet.Radon.RadonRetrieval)
439
+ || (options?.requests && value instanceof Witnet.Radon.RadonRequest)
440
+ );
441
+ if (!(options?.modals || options?.templates || options?.retrievals || options?.requests)) {
442
+ include = (
443
+ value instanceof Witnet.Radon.RadonModal ||
444
+ value instanceof Witnet.Radon.RadonRequest ||
445
+ value instanceof Witnet.Radon.RadonTemplate ||
446
+ value instanceof Witnet.Radon.RadonRetrieval
447
+ );
448
+ }
449
+ if (include && (
450
+ !options?.filter
451
+ || !args
452
+ || args.length === 0
453
+ || args.find(arg => key.toLowerCase().indexOf(arg.toLowerCase()) >= 0)
411
454
  )) {
412
455
  counter++
413
456
  } else if (typeof value === "object") {
414
- counter += countWitnetArtifacts(value, args)
457
+ counter += countWitnetArtifacts(value, args, options)
415
458
  }
416
459
  })
417
460
  return counter
418
461
  }
419
462
 
420
- function clearEmptyBranches (node, args, filter) {
463
+ function clearEmptyBranches (node, args, options) {
421
464
  if (node) {
422
465
  const assets = Object.fromEntries(
423
466
  Object.entries(node).map(([key, value]) => {
467
+ let include = (
468
+ (options?.modals && value instanceof Witnet.Radon.RadonModal)
469
+ || (options?.templates && value instanceof Witnet.Radon.RadonTemplate)
470
+ || (options?.retrievals && value instanceof Witnet.Radon.RadonRetrieval)
471
+ || (options?.requests && value instanceof Witnet.Radon.RadonRequest)
472
+ );
473
+ if (!(options?.modals || options?.templates || options?.retrievals || options?.requests)) {
474
+ include = (
475
+ value instanceof Witnet.Radon.RadonModal ||
476
+ value instanceof Witnet.Radon.RadonRequest ||
477
+ value instanceof Witnet.Radon.RadonTemplate ||
478
+ value instanceof Witnet.Radon.RadonRetrieval
479
+ );
480
+ }
424
481
  if (
425
- (!filter || args.find(arg => key.toLowerCase().indexOf(arg.toLowerCase()) >= 0)) && (
426
- value instanceof Witnet.Radon.RadonRetrieval ||
427
- value instanceof Witnet.Radon.RadonModal ||
428
- value instanceof Witnet.Radon.RadonRequest ||
429
- value instanceof Witnet.Radon.RadonTemplate
482
+ include && (
483
+ !options?.filter || args.find(arg => key.toLowerCase().indexOf(arg.toLowerCase()) >= 0)
430
484
  )
431
485
  ) {
432
486
  return [key, value]
433
487
  } else if (typeof value === "object") {
434
- if (countWitnetArtifacts(value, args, filter) > 0) {
435
- return [key, clearEmptyBranches(value, args, filter)]
488
+ if (countWitnetArtifacts(value, args, options) > 0) {
489
+ return [key, clearEmptyBranches(value, args, options)]
436
490
  } else {
437
491
  return [key, undefined]
438
492
  }
@@ -450,25 +504,25 @@ function clearEmptyBranches (node, args, filter) {
450
504
  }
451
505
  }
452
506
 
453
- function traceWitnetArtifacts (assets, args, indent = "", filter = false) {
507
+ function traceWitnetArtifacts (assets, args, indent = "", options) {
454
508
  const prefix = `${indent}`
455
509
  Object.keys(assets).forEach((key, index) => {
456
510
  const isLast = index === Object.keys(assets).length - 1
457
511
  const found = args.find(arg => key.toLowerCase().indexOf(arg.toLowerCase()) >= 0)
458
512
  const color = found ? helpers.colors.mcyan : helpers.colors.cyan
459
513
  if (assets[key] instanceof Witnet.Radon.RadonRequest) {
460
- if (!filter || found) {
461
- console.info(`${prefix}${color(key)}`)
514
+ if (!options?.filter || found) {
515
+ console.info(`${prefix}${color(key)} ${assets[key].sources.length > 1 ? helpers.colors.yellow(`(${assets[key].sources.length} sources)`) : ""}`)
462
516
  if (isLast) {
463
517
  console.info(`${prefix}`)
464
518
  }
465
519
  }
466
- } else if (
520
+ } else if ((
467
521
  assets[key] instanceof Witnet.Radon.RadonTemplate ||
468
522
  assets[key] instanceof Witnet.Radon.RadonModal
469
- ) {
523
+ )) {
470
524
  const argsCount = assets[key].argsCount
471
- if (!filter || found) {
525
+ if (!options?.filter || found) {
472
526
  console.info(`${prefix}${color(key)} ${argsCount > 0 ? helpers.colors.green(`(${argsCount} args)`) : ""}`)
473
527
  if (isLast) {
474
528
  console.info(`${prefix}`)
@@ -476,15 +530,15 @@ function traceWitnetArtifacts (assets, args, indent = "", filter = false) {
476
530
  }
477
531
  } else if (assets[key] instanceof Witnet.Radon.RadonRetrieval) {
478
532
  const argsCount = assets[key].argsCount
479
- if (!filter || found) {
533
+ if (!options?.filter || found) {
480
534
  console.info(`${prefix}${color(key)} ${argsCount > 0 ? helpers.colors.green(`(${argsCount} args)`) : ""}`)
481
535
  if (isLast) {
482
536
  console.info(`${prefix}`)
483
537
  }
484
538
  }
485
- } else if (typeof assets[key] === "object" && countWitnetArtifacts(assets[key], args, filter) > 0) {
539
+ } else if (typeof assets[key] === "object" && countWitnetArtifacts(assets[key], args, options) > 0) {
486
540
  console.info(`${indent}${isLast ? "└─ " : "├─ "}${key}`)
487
- traceWitnetArtifacts(assets[key], args, !isLast ? `${indent}│ ` : `${indent} `, filter)
541
+ traceWitnetArtifacts(assets[key], args, !isLast ? `${indent}│ ` : `${indent} `, options)
488
542
  }
489
543
  })
490
544
  }
@@ -617,6 +671,25 @@ async function traceWitnetRadonRequestDryRun (request, options) {
617
671
  const result = report?.aggregate.result
618
672
  const resultType = Object.keys(result)[0]
619
673
  const resultValue = Object.values(result)[0]
674
+ let resultSize
675
+ const parseRadonResult = (value) => {
676
+ if (Array.isArray(value)) {
677
+ return value.map(item => parseRadonResult(item))
678
+ } if (typeof value === 'object') {
679
+ return parseRadonResult(Object.values(value)[0])
680
+ } else {
681
+ return JSON.parse(value);
682
+ }
683
+ }
684
+ switch (resultType) {
685
+ case "RadonBoolean": resultSize = 1; break;
686
+ case "RadonBytes": resultSize = cbor.encode(Uint8Array.from(resultValue)).byteLength - 2; break;
687
+ case "RadonInteger": case "RadonFloat": resultSize = cbor.encode(resultValue).byteLength; break;
688
+ case "RadonArray": case "RadonMap":
689
+ const parsed = parseRadonResult(resultValue)
690
+ resultSize = cbor.encode(parsed).byteLength;
691
+ break;
692
+ }
620
693
  if (options?.json) {
621
694
  if (options?.verbose) {
622
695
  console.info(JSON.stringify(report, null, options?.indent ? " ".repeat(options.indent) : ""))
@@ -670,9 +743,6 @@ async function traceWitnetRadonRequestDryRun (request, options) {
670
743
  console.info(`${indent} │ ${corner}─ [ ${color(authority)} ]`)
671
744
  }
672
745
  if (source.method !== Witnet.Radon.retrievals.Methods.RNG && options?.verbose) {
673
- // const result = report.retrieve[sourceIndex].result
674
- // const resultType = Object.keys(result)[0]
675
- // const resultValue = JSON.stringify(Object.values(result)[0])
676
746
  console.info(
677
747
  `${indent} │ ${sep} > Request: ${
678
748
  helpers.colors.mgreen(Witnet.Radon.retrievals.Methods[source.method].split(/(?=[A-Z])/).join("-").toUpperCase())
@@ -687,8 +757,8 @@ async function traceWitnetRadonRequestDryRun (request, options) {
687
757
  }
688
758
  const printData = (headline, data, color) => {
689
759
  const type = Object.keys(data)[0]
690
- data = typeof data[type] === "object" || Array.isArray(data[type]) ? JSON.stringify(data[type]) : data[type]
691
- const lines = data.match(/.{1,96}/g).slice(0, 256)
760
+ data = (typeof data[type] === "object" || typeof data[type] === "boolean" || Array.isArray(data[type]) ? JSON.stringify(data[type]) : data[type]) || ""
761
+ const lines = data.match(/.{1,96}/g)?.slice(0, 256) || [""]
692
762
  if (lines.length === 256) lines[255] += "..."
693
763
  const typeColor = (type === "RadonError") ? helpers.colors.red : helpers.colors.yellow
694
764
  const lineColor = (type === "RadonError") ? helpers.colors.gray : color
@@ -747,10 +817,15 @@ async function traceWitnetRadonRequestDryRun (request, options) {
747
817
  } │`
748
818
  )
749
819
  }
750
- console.info(`${indent}│ Result size: ${helpers.colors.cyan("xxx bytes")}${" ".repeat(flexbar.length + 13 - 9)} │`)
820
+ if (resultSize) {
821
+ console.info(`${indent}│ CBOR size: ${
822
+ helpers.colors.cyan(`${resultSize} bytes`)
823
+ }${" ".repeat(flexbar.length + 7 - resultSize.toString().length)
824
+ } │`)
825
+ }
751
826
  console.info(`${indent}└────┬─────────────────────────${flexbar}─┘`)
752
827
  const printMapItem = (indent, width, key, value, indent2 = "") => {
753
- if (key) key = `${indent2}"${key}": `
828
+ if (key) key = `${indent2}${key}: `
754
829
  else key = `${indent2}`
755
830
  let type = extractTypeName(Object.keys(value)[0])
756
831
  value = Object.values(value)[0]
@@ -774,14 +849,11 @@ async function traceWitnetRadonRequestDryRun (request, options) {
774
849
  }`
775
850
  )
776
851
  }
777
- Object.entries(value).forEach(([key, value]) => printMapItem(indent, width, type === "Map" ? key : null, value, indent2 + " "))
852
+ Object.entries(value).forEach(([key, value]) => printMapItem(indent, width, type === "Map" ? key : null, helpers.unescapeSlashes(value), indent2 + " "))
778
853
  } else {
779
854
  if (key.length > width - 12) {
780
855
  console.info(`${indent} ${helpers.colors.yellow(type)} ${" ".repeat(width - 15)}${helpers.colors.green("...")}`)
781
856
  } else {
782
- if (["String", "Error"].includes(type)) {
783
- value = JSON.stringify(value)
784
- }
785
857
  type = `[ ${type}${" ".repeat(7 - type.length)} ]`
786
858
  const result = key + value
787
859
  // let spaces = width - 12 - result.length
@@ -789,7 +861,11 @@ async function traceWitnetRadonRequestDryRun (request, options) {
789
861
  value = value.slice(0, width - 15 - key.length) + "..."
790
862
  // spaces = 0
791
863
  }
792
- console.info(`${indent} ${helpers.colors.yellow(type)} ${helpers.colors.green(key)}${helpers.colors.mcyan(value)}`)
864
+ if (["String", "Error"].includes(type)) {
865
+ console.info(`${indent} ${helpers.colors.yellow(type)} ${helpers.colors.green(key)}"${helpers.colors.mcyan(value)}"`)
866
+ } else {
867
+ console.info(`${indent} ${helpers.colors.yellow(type)} ${helpers.colors.green(key)}${helpers.colors.mcyan(value)}`)
868
+ }
793
869
  }
794
870
  }
795
871
  }
@@ -803,10 +879,12 @@ async function traceWitnetRadonRequestDryRun (request, options) {
803
879
  } else {
804
880
  if (resultType === "Bytes") {
805
881
  resultValue = JSON.parse(resultValue).map(char => ("00" + char.toString(16)).slice(-2)).join("")
882
+ } else if (resultType === "Boolean") {
883
+ resultValue = JSON.stringify(resultValue)
806
884
  }
807
885
  const color = resultType.indexOf("Error") > -1 ? helpers.colors.gray : helpers.colors.lcyan
808
886
  const typeText = resultType.indexOf("Error") > -1 ? "\x1b[1;98;41m Error \x1b[0m" : helpers.colors.lyellow(`[ ${resultType} ]`)
809
- const lines = resultValue.match(/.{1,96}/g).slice(0, 256)
887
+ const lines = resultValue.match(/.{1,96}/g)?.slice(0, 256) || [""]
810
888
  console.info(`${indent} └─ ${typeText} ${color(lines[0])}`)
811
889
  lines.slice(1).forEach(line => {
812
890
  console.info(`${indent} ${" ".repeat(resultType.length)}${color(line)}`)
@@ -528,7 +528,6 @@ async function resolve (options = {}, [pattern, ...args]) {
528
528
  throw Error("--from address not found in wallet")
529
529
  }
530
530
  const request = await _loadRadonRequest({ ...options, pattern, args })
531
- // console.log(request)
532
531
  await helpers.traceTransaction(
533
532
  Witnet.DataRequests.from(ledger, request), {
534
533
  headline: "DATA REQUEST TRANSACTION",
@@ -947,13 +946,12 @@ async function _loadRadonRequest (options = {}) {
947
946
  }
948
947
 
949
948
  // load Radon assets from environment
950
- let assets = utils.searchRadonAssets(
951
- {
952
- assets: loadAssets(options),
949
+ const assets = utils.searchRadonAssets({
950
+ assets: options?.module ? require(options.module) : loadAssets(options),
953
951
  pattern: options?.pattern,
954
- },
952
+ },
955
953
  (key, pattern) => key.toLowerCase().indexOf(pattern.toLowerCase()) >= 0
956
- )
954
+ );
957
955
 
958
956
  if (args.length > 0) {
959
957
  // ignore RadonRequests if args were passed from the CLI