@witnet/sdk 1.0.15 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. package/dist/package.json +9 -9
  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 +33 -4
  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 +3 -1
  15. package/dist/src/lib/radon/index.d.ts.map +1 -1
  16. package/dist/src/lib/radon/index.js +48 -30
  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/rpc/provider.d.ts +12 -0
  21. package/dist/src/lib/rpc/provider.d.ts.map +1 -1
  22. package/dist/src/lib/rpc/provider.js +11 -1
  23. package/dist/witnet/assets/index.d.ts +1 -2
  24. package/dist/witnet/assets/modals/index.d.ts +1 -2
  25. package/dist/witnet/assets/modals/web3/eth.js +3 -3
  26. package/dist/witnet/assets/modals/web3/ipfs.d.ts +1 -2
  27. package/dist/witnet/assets/modals/web3/ipfs.js +11 -9
  28. package/dist/witnet/assets/modals/web3/wit.js +4 -4
  29. package/dist/witnet/assets/requests.js +6 -51
  30. package/package.json +9 -9
  31. package/src/bin/cli/inspect.js +103 -13
  32. package/src/bin/cli/radon.js +82 -41
  33. package/src/bin/cli/wallet.js +0 -1
  34. package/src/bin/helpers.js +36 -3
  35. package/src/bin/toolkit.js +1 -1
  36. package/witnet/assets/modals/web3/eth.js +2 -2
  37. package/witnet/assets/modals/web3/ipfs.js +9 -6
  38. package/witnet/assets/modals/web3/wit.js +3 -3
  39. package/witnet/assets/requests.js +5 -51
@@ -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")
@@ -244,11 +245,12 @@ async function decode (options = {}, args = []) {
244
245
  if (artifact instanceof Witnet.Radon.RadonRequest) {
245
246
  prefix = "RadonRequest::"
246
247
  } else if (artifact instanceof Witnet.Radon.RadonModal) {
247
- artifact.providers = ["https://dummy"]
248
+ artifact.providers = [...args[0].split(";") || "https://dummy"]
248
249
  const modalArgs = []
249
- let argIndex = 0
250
+ let argIndex = 1
250
251
  while (modalArgs.length < artifact.argsCount) {
251
- modalArgs.push(`{:${++argIndex}}`)
252
+ modalArgs.push(args[argIndex] || `{:${argIndex}}`)
253
+ argIndex += 1
252
254
  }
253
255
  artifact = artifact.buildRadonRequest(modalArgs)
254
256
  prefix = "RadonModal::"
@@ -309,33 +311,48 @@ async function dryrun (options = {}, args = []) {
309
311
  if (artifact instanceof Witnet.Radon.RadonRequest) {
310
312
  prefix = "RadonRequest::"
311
313
  } 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
314
  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
315
  if (artifact instanceof Witnet.Radon.RadonModal) {
330
- artifact.providers = artifactArgs.shift().split(";")
331
- artifact = artifact.buildRadonRequest(artifactArgs)
316
+ if (args.length < artifact.argsCount) {
317
+ throw new Error(`missing parameters for Radon Modal.`)
318
+ }
319
+ artifact.providers = [...args[0].split(";")]
320
+ const modalArgs = []
321
+ let argIndex = 1
322
+ while (modalArgs.length < artifact.argsCount) {
323
+ modalArgs.push(args[argIndex])
324
+ argIndex += 1
325
+ }
326
+ artifact = (
327
+ artifact.homogeneous
328
+ ? artifact.buildRadonRequest(modalArgs)
329
+ : artifact.buildRadonRequest([ ...artifact.sources.map(source => modalArgs.slice(0, source.argsCount)) ])
330
+ )
332
331
  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::"
332
+ } else {
333
+ if (!artifact?.samples) {
334
+ console.error(`${artifact.constructor.name}::${key}: cannot dry-run if no sample parameters are declared.\n`)
335
+ continue
336
+ }
337
+ if (options?.default) {
338
+ artifactArgs = Object.values(artifact.samples)[0]
339
+ } else {
340
+ const prompt = inquirer.createPromptModule()
341
+ const sample = await prompt([{
342
+ choices: Object.keys(artifact.samples),
343
+ message: `${artifact.constructor.name}::${key} args:`,
344
+ name: "key",
345
+ type: "list",
346
+ }])
347
+ artifactArgs = artifact.samples[sample.key]
348
+ }
349
+ if (artifact instanceof Witnet.Radon.RadonTemplate) {
350
+ artifact = artifact.buildRadonRequest(artifactArgs)
351
+ prefix = "RadonTemplate::"
352
+ } else if (artifact instanceof Witnet.Radon.RadonRetrieval) {
353
+ artifact = new Witnet.Radon.RadonRequest({ sources: artifact.foldArgs(artifactArgs) })
354
+ prefix = "RadonRetrieval::"
355
+ }
339
356
  }
340
357
  }
341
358
  if (!headline) {
@@ -458,7 +475,7 @@ function traceWitnetArtifacts (assets, args, indent = "", filter = false) {
458
475
  const color = found ? helpers.colors.mcyan : helpers.colors.cyan
459
476
  if (assets[key] instanceof Witnet.Radon.RadonRequest) {
460
477
  if (!filter || found) {
461
- console.info(`${prefix}${color(key)}`)
478
+ console.info(`${prefix}${color(key)} ${assets[key].sources.length > 1 ? helpers.colors.yellow(`(${assets[key].sources.length} sources)`) : ""}`)
462
479
  if (isLast) {
463
480
  console.info(`${prefix}`)
464
481
  }
@@ -617,6 +634,25 @@ async function traceWitnetRadonRequestDryRun (request, options) {
617
634
  const result = report?.aggregate.result
618
635
  const resultType = Object.keys(result)[0]
619
636
  const resultValue = Object.values(result)[0]
637
+ let resultSize
638
+ const parseRadonResult = (value) => {
639
+ if (Array.isArray(value)) {
640
+ return value.map(item => parseRadonResult(item))
641
+ } if (typeof value === 'object') {
642
+ return parseRadonResult(Object.values(value)[0])
643
+ } else {
644
+ return JSON.parse(value);
645
+ }
646
+ }
647
+ switch (resultType) {
648
+ case "RadonBoolean": resultSize = 1; break;
649
+ case "RadonBytes": resultSize = cbor.encode(Uint8Array.from(resultValue)).byteLength - 2; break;
650
+ case "RadonInteger": case "RadonFloat": resultSize = cbor.encode(resultValue).byteLength; break;
651
+ case "RadonArray": case "RadonMap":
652
+ const parsed = parseRadonResult(resultValue)
653
+ resultSize = cbor.encode(parsed).byteLength;
654
+ break;
655
+ }
620
656
  if (options?.json) {
621
657
  if (options?.verbose) {
622
658
  console.info(JSON.stringify(report, null, options?.indent ? " ".repeat(options.indent) : ""))
@@ -670,9 +706,6 @@ async function traceWitnetRadonRequestDryRun (request, options) {
670
706
  console.info(`${indent} │ ${corner}─ [ ${color(authority)} ]`)
671
707
  }
672
708
  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
709
  console.info(
677
710
  `${indent} │ ${sep} > Request: ${
678
711
  helpers.colors.mgreen(Witnet.Radon.retrievals.Methods[source.method].split(/(?=[A-Z])/).join("-").toUpperCase())
@@ -687,8 +720,8 @@ async function traceWitnetRadonRequestDryRun (request, options) {
687
720
  }
688
721
  const printData = (headline, data, color) => {
689
722
  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)
723
+ data = (typeof data[type] === "object" || typeof data[type] === "boolean" || Array.isArray(data[type]) ? JSON.stringify(data[type]) : data[type]) || ""
724
+ const lines = data.match(/.{1,96}/g)?.slice(0, 256) || [""]
692
725
  if (lines.length === 256) lines[255] += "..."
693
726
  const typeColor = (type === "RadonError") ? helpers.colors.red : helpers.colors.yellow
694
727
  const lineColor = (type === "RadonError") ? helpers.colors.gray : color
@@ -747,10 +780,15 @@ async function traceWitnetRadonRequestDryRun (request, options) {
747
780
  } │`
748
781
  )
749
782
  }
750
- console.info(`${indent}│ Result size: ${helpers.colors.cyan("xxx bytes")}${" ".repeat(flexbar.length + 13 - 9)} │`)
783
+ if (resultSize) {
784
+ console.info(`${indent}│ CBOR size: ${
785
+ helpers.colors.cyan(`${resultSize} bytes`)
786
+ }${" ".repeat(flexbar.length + 7 - resultSize.toString().length)
787
+ } │`)
788
+ }
751
789
  console.info(`${indent}└────┬─────────────────────────${flexbar}─┘`)
752
790
  const printMapItem = (indent, width, key, value, indent2 = "") => {
753
- if (key) key = `${indent2}"${key}": `
791
+ if (key) key = `${indent2}${key}: `
754
792
  else key = `${indent2}`
755
793
  let type = extractTypeName(Object.keys(value)[0])
756
794
  value = Object.values(value)[0]
@@ -774,14 +812,11 @@ async function traceWitnetRadonRequestDryRun (request, options) {
774
812
  }`
775
813
  )
776
814
  }
777
- Object.entries(value).forEach(([key, value]) => printMapItem(indent, width, type === "Map" ? key : null, value, indent2 + " "))
815
+ Object.entries(value).forEach(([key, value]) => printMapItem(indent, width, type === "Map" ? key : null, helpers.unescapeSlashes(value), indent2 + " "))
778
816
  } else {
779
817
  if (key.length > width - 12) {
780
818
  console.info(`${indent} ${helpers.colors.yellow(type)} ${" ".repeat(width - 15)}${helpers.colors.green("...")}`)
781
819
  } else {
782
- if (["String", "Error"].includes(type)) {
783
- value = JSON.stringify(value)
784
- }
785
820
  type = `[ ${type}${" ".repeat(7 - type.length)} ]`
786
821
  const result = key + value
787
822
  // let spaces = width - 12 - result.length
@@ -789,7 +824,11 @@ async function traceWitnetRadonRequestDryRun (request, options) {
789
824
  value = value.slice(0, width - 15 - key.length) + "..."
790
825
  // spaces = 0
791
826
  }
792
- console.info(`${indent} ${helpers.colors.yellow(type)} ${helpers.colors.green(key)}${helpers.colors.mcyan(value)}`)
827
+ if (["String", "Error"].includes(type)) {
828
+ console.info(`${indent} ${helpers.colors.yellow(type)} ${helpers.colors.green(key)}"${helpers.colors.mcyan(value)}"`)
829
+ } else {
830
+ console.info(`${indent} ${helpers.colors.yellow(type)} ${helpers.colors.green(key)}${helpers.colors.mcyan(value)}`)
831
+ }
793
832
  }
794
833
  }
795
834
  }
@@ -803,10 +842,12 @@ async function traceWitnetRadonRequestDryRun (request, options) {
803
842
  } else {
804
843
  if (resultType === "Bytes") {
805
844
  resultValue = JSON.parse(resultValue).map(char => ("00" + char.toString(16)).slice(-2)).join("")
845
+ } else if (resultType === "Boolean") {
846
+ resultValue = JSON.stringify(resultValue)
806
847
  }
807
848
  const color = resultType.indexOf("Error") > -1 ? helpers.colors.gray : helpers.colors.lcyan
808
849
  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)
850
+ const lines = resultValue.match(/.{1,96}/g)?.slice(0, 256) || [""]
810
851
  console.info(`${indent} └─ ${typeText} ${color(lines[0])}`)
811
852
  lines.slice(1).forEach(line => {
812
853
  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",
@@ -369,8 +369,8 @@ function checkRpcWildcards (wildcards) {
369
369
  } else if (typeof wildcards === "string") {
370
370
  if (isWildcard(wildcards)) {
371
371
  const char = wildcards.charAt(1)
372
- if (char < "1" || char > "9") {
373
- throw Error("RPC: wildcards not in range [1 .. 9]")
372
+ if (char < "0" || char > "9") {
373
+ throw Error("RPC: wildcards not in range [0 .. 9]")
374
374
  }
375
375
  }
376
376
  }
@@ -392,10 +392,25 @@ function replaceWildcards (obj, args) {
392
392
  ? replaceWildcards(value, args)
393
393
  : value
394
394
  )
395
+ } else if (obj && typeof obj === "object") {
396
+ obj = replaceObjectWildcards(obj, args)
395
397
  }
396
398
  return obj
397
399
  }
398
400
 
401
+ function replaceObjectWildcards(obj, args) {
402
+ return Object.fromEntries(
403
+ Object.entries(obj).map(([key, value]) => {
404
+ for (let argIndex = 0; argIndex < args.length; argIndex ++) {
405
+ const wildcard = `\\${argIndex}\\`
406
+ key = key.replaceAll(wildcard, args[argIndex])
407
+ value = replaceWildcards(value, args)
408
+ }
409
+ return [key, value]
410
+ })
411
+ )
412
+ }
413
+
399
414
  function spliceWildcard (obj, argIndex, argValue, argsCount) {
400
415
  if (obj && typeof obj === "string") {
401
416
  const wildcard = `\\${argIndex}\\`
@@ -716,7 +731,7 @@ function traceTransactionReceipt (receipt) {
716
731
  mblue(receipt.recipients.filter((pkh, index, array) => index === array.indexOf(pkh)))
717
732
  }`)
718
733
  }
719
- if (receipt?.fees) console.info(` > Fee: ${yellow(receipt.fees.toString(2))}`)
734
+ if (receipt?.fees) console.info(` > Network fee: ${yellow(receipt.fees.toString(2))}`)
720
735
  if (receipt?.value) console.info(` > Value: ${myellow(receipt.value.toString(2))}`)
721
736
  if (receipt?.weight) console.info(` > Weight: ${mgreen(commas(receipt.weight))}`)
722
737
  if (receipt?.witnesses) {
@@ -771,6 +786,23 @@ async function traceTransaction (transmitter, options) {
771
786
  return receipt
772
787
  }
773
788
 
789
+ function unescapeSlashes(str) {
790
+ // add another escaped slash if the string ends with an odd
791
+ // number of escaped slashes which will crash JSON.parse
792
+ let parsedStr = str.replace(/(^|[^\\])(\\\\)*\\$/, "$&\\");
793
+
794
+ // escape unescaped double quotes to prevent error with
795
+ // added double quotes in json string
796
+ parsedStr = parsedStr.replace(/(^|[^\\])((\\\\)*")/g, "$1\\$2");
797
+
798
+ try {
799
+ parsedStr = JSON.parse(`"${parsedStr}"`);
800
+ } catch(e) {
801
+ return str;
802
+ }
803
+ return parsedStr ;
804
+ }
805
+
774
806
  module.exports = {
775
807
  colors: {
776
808
  bblue,
@@ -837,4 +869,5 @@ module.exports = {
837
869
  replaceWildcards,
838
870
  spliceWildcard,
839
871
  txJsonReplacer,
872
+ unescapeSlashes,
840
873
  }
@@ -18,7 +18,7 @@ const {
18
18
 
19
19
  /// CONSTANTS =======================================================================================================
20
20
 
21
- const version = "2.0.8"
21
+ const version = "2.0.21"
22
22
  const toolkitDownloadUrlBase = `https://github.com/witnet/witnet-rust/releases/download/${version}/`
23
23
  const toolkitDownloadNames = {
24
24
  win32: (arch) => `witnet_toolkit-${arch}-pc-windows-msvc.exe`,
@@ -16,13 +16,13 @@ module.exports = {
16
16
  }),
17
17
  WitOracleEthGetBalance: new RadonModal({
18
18
  retrieval: retrievals.JsonRPC({
19
- rpc: retrievals.rpc.eth.getBalance("\\1\\"),
19
+ rpc: retrievals.rpc.eth.getBalance("\\0\\"),
20
20
  script: RadonScript(types.RadonString).asFloat().floor(),
21
21
  }),
22
22
  }),
23
23
  WitOracleEthGetTransactionReceipt: new RadonModal({
24
24
  retrieval: retrievals.JsonRPC({
25
- rpc: retrievals.rpc.eth.getTransactionByHash("\\1\\"),
25
+ rpc: retrievals.rpc.eth.getTransactionByHash("\\0\\"),
26
26
  script: RadonScript(types.RadonString).parseJSONMap(),
27
27
  }),
28
28
  }),
@@ -1,8 +1,6 @@
1
1
  const {
2
2
  RadonModal,
3
3
  RadonScript,
4
- // filters,
5
- // reducers,
6
4
  retrievals,
7
5
  types,
8
6
  } = require("../../../../src/lib/radon")
@@ -10,10 +8,15 @@ const {
10
8
  module.exports = {
11
9
  WitOracleIpfsFileExists: new RadonModal({
12
10
  retrieval: retrievals.HttpHead({
13
- headers: {},
14
- script: RadonScript(types.RadonString),
11
+ script: RadonScript(types.RadonMap)
12
+ .getString("etag")
13
+ .slice(1, -1)
14
+ .match(types.RadonBoolean, { "\\0\\": true }, false)
15
15
  }),
16
16
  }),
17
- WitOracleIpfsFileSha256: {},
18
- WitOracleIpfsFileSha256Sealed: {},
17
+ WitOracleIpfsFileSha256: new RadonModal({
18
+ retrieval: retrievals.HttpGet({
19
+ script: RadonScript(types.RadonBytes).hash()
20
+ })
21
+ })
19
22
  }
@@ -8,14 +8,14 @@ const {
8
8
  module.exports = {
9
9
  WitOracleWitGetBalance: new RadonModal({
10
10
  retrieval: retrievals.JsonRPC({
11
- rpc: retrievals.rpc.wit.getBalance("\\1\\"),
11
+ rpc: retrievals.rpc.wit.getBalance("\\0\\"),
12
12
  script: RadonScript(types.RadonString).parseJSONMap().getMap("result").values(),
13
13
  }),
14
14
  }),
15
15
  WitOracleWitGetValueTransfer: new RadonModal({
16
16
  retrieval: retrievals.JsonRPC({
17
- rpc: retrievals.rpc.wit.getValueTransfer("\\1\\", "\\2\\"),
18
- script: RadonScript(types.RadonString).parseJSONMap().getMap("result").getMap("\\2\\").values(),
17
+ rpc: retrievals.rpc.wit.getValueTransfer("\\0\\", "\\1\\"),
18
+ script: RadonScript(types.RadonString).parseJSONMap().getMap("result").getMap("\\1\\").values(),
19
19
  }),
20
20
  }),
21
21
  }
@@ -8,38 +8,16 @@ const {
8
8
  } = require("../../src/lib/radon")
9
9
 
10
10
  module.exports = {
11
-
12
11
  defi: {
13
12
  tickers: {
14
13
  crypto: {
15
14
  WitOracleRequestPriceCryptoWitUsdt6: new RadonRequest({
16
15
  sources: [
17
16
  retrievals.HttpGet({
18
- url: "https://api-cloud.bitmart.com/spot/v1/ticker?symbol=WIT_USDT",
19
- script: RadonScript(types.RadonString)
20
- .parseJSONMap()
21
- .getMap("data")
22
- .getArray("tickers")
23
- .getMap(0)
24
- .getFloat("last_price")
25
- .multiply(1e6)
26
- .round(),
27
- }),
28
- retrievals.HttpGet({
29
- url: "https://data.gateapi.io/api2/1/ticker/wit_usdt",
30
- script: RadonScript(types.RadonString)
31
- .parseJSONMap()
32
- .getFloat("last")
33
- .multiply(1e6)
34
- .round(),
35
- }),
36
- retrievals.HttpGet({
37
- url: "https://www.mexc.com/open/api/v2/market/ticker?symbol=WIT_USDT",
17
+ url: "https://api.mexc.com/api/v3/ticker/price?symbol=WITUSDT",
38
18
  script: RadonScript(types.RadonString)
39
19
  .parseJSONMap()
40
- .getArray("data")
41
- .getMap(0)
42
- .getFloat("last")
20
+ .getFloat("price")
43
21
  .multiply(1e6)
44
22
  .round(),
45
23
  }),
@@ -50,35 +28,11 @@ module.exports = {
50
28
  WitOracleRequestPriceCryptoUsdtWit9: new RadonRequest({
51
29
  sources: [
52
30
  retrievals.HttpGet({
53
- url: "https://api-cloud.bitmart.com/spot/v1/ticker?symbol=WIT_USDT",
54
- script: RadonScript(types.RadonString)
55
- .parseJSONMap()
56
- .getMap("data")
57
- .getArray("tickers")
58
- .getMap(0)
59
- .getFloat("last_price")
60
- .power(-1)
61
- .multiply(1e9)
62
- .round(),
63
- }),
64
- retrievals.HttpGet({
65
- url: "https://data.gateapi.io/api2/1/ticker/wit_usdt",
31
+ url: "https://api.mexc.com/api/v3/ticker/price?symbol=WITUSDT",
66
32
  script: RadonScript(types.RadonString)
67
33
  .parseJSONMap()
68
- .getFloat("last")
69
- .power(-1)
70
- .multiply(1e9)
71
- .round(),
72
- }),
73
- retrievals.HttpGet({
74
- url: "https://www.mexc.com/open/api/v2/market/ticker?symbol=WIT_USDT",
75
- script: RadonScript(types.RadonString)
76
- .parseJSONMap()
77
- .getArray("data")
78
- .getMap(0)
79
- .getFloat("last")
80
- .power(-1)
81
- .multiply(1e9)
34
+ .getFloat("price")
35
+ .multiply(1e6)
82
36
  .round(),
83
37
  }),
84
38
  ],