@witnet/sdk 1.1.5 → 1.2.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 (192) hide show
  1. package/.env_witnet +13 -1
  2. package/dist/package.json +41 -24
  3. package/dist/src/bin/helpers.d.ts +59 -49
  4. package/dist/src/bin/helpers.d.ts.map +1 -1
  5. package/dist/src/bin/helpers.js +228 -229
  6. package/dist/src/index.d.ts +3 -4
  7. package/dist/src/index.d.ts.map +1 -1
  8. package/dist/src/index.js +4 -47
  9. package/dist/src/lib/crypto/account.d.ts +3 -3
  10. package/dist/src/lib/crypto/account.d.ts.map +1 -1
  11. package/dist/src/lib/crypto/account.js +31 -25
  12. package/dist/src/lib/crypto/coinbase.d.ts +4 -4
  13. package/dist/src/lib/crypto/coinbase.d.ts.map +1 -1
  14. package/dist/src/lib/crypto/coinbase.js +8 -13
  15. package/dist/src/lib/crypto/index.d.ts +7 -7
  16. package/dist/src/lib/crypto/index.d.ts.map +1 -1
  17. package/dist/src/lib/crypto/index.js +7 -30
  18. package/dist/src/lib/crypto/interfaces.d.ts +5 -5
  19. package/dist/src/lib/crypto/interfaces.d.ts.map +1 -1
  20. package/dist/src/lib/crypto/interfaces.js +2 -3
  21. package/dist/src/lib/crypto/payloads/DataRequestPayload.d.ts +5 -5
  22. package/dist/src/lib/crypto/payloads/DataRequestPayload.d.ts.map +1 -1
  23. package/dist/src/lib/crypto/payloads/DataRequestPayload.js +98 -85
  24. package/dist/src/lib/crypto/payloads/StakePayload.d.ts +3 -4
  25. package/dist/src/lib/crypto/payloads/StakePayload.d.ts.map +1 -1
  26. package/dist/src/lib/crypto/payloads/StakePayload.js +81 -71
  27. package/dist/src/lib/crypto/payloads/UnstakePayload.d.ts +4 -5
  28. package/dist/src/lib/crypto/payloads/UnstakePayload.d.ts.map +1 -1
  29. package/dist/src/lib/crypto/payloads/UnstakePayload.js +36 -43
  30. package/dist/src/lib/crypto/payloads/ValueTransferPayload.d.ts +3 -4
  31. package/dist/src/lib/crypto/payloads/ValueTransferPayload.d.ts.map +1 -1
  32. package/dist/src/lib/crypto/payloads/ValueTransferPayload.js +46 -48
  33. package/dist/src/lib/crypto/payloads.d.ts +5 -5
  34. package/dist/src/lib/crypto/payloads.d.ts.map +1 -1
  35. package/dist/src/lib/crypto/payloads.js +44 -45
  36. package/dist/src/lib/crypto/signer.d.ts +3 -3
  37. package/dist/src/lib/crypto/signer.d.ts.map +1 -1
  38. package/dist/src/lib/crypto/signer.js +45 -88
  39. package/dist/src/lib/crypto/transmitters/DataRequests.d.ts +6 -6
  40. package/dist/src/lib/crypto/transmitters/DataRequests.d.ts.map +1 -1
  41. package/dist/src/lib/crypto/transmitters/DataRequests.js +6 -10
  42. package/dist/src/lib/crypto/transmitters/StakeDeposits.d.ts +5 -5
  43. package/dist/src/lib/crypto/transmitters/StakeDeposits.d.ts.map +1 -1
  44. package/dist/src/lib/crypto/transmitters/StakeDeposits.js +7 -11
  45. package/dist/src/lib/crypto/transmitters/StakeWithdrawals.d.ts +6 -7
  46. package/dist/src/lib/crypto/transmitters/StakeWithdrawals.d.ts.map +1 -1
  47. package/dist/src/lib/crypto/transmitters/StakeWithdrawals.js +9 -13
  48. package/dist/src/lib/crypto/transmitters/ValueTransfers.d.ts +5 -5
  49. package/dist/src/lib/crypto/transmitters/ValueTransfers.d.ts.map +1 -1
  50. package/dist/src/lib/crypto/transmitters/ValueTransfers.js +6 -10
  51. package/dist/src/lib/crypto/transmitters.d.ts +6 -6
  52. package/dist/src/lib/crypto/transmitters.d.ts.map +1 -1
  53. package/dist/src/lib/crypto/transmitters.js +89 -76
  54. package/dist/src/lib/crypto/types.d.ts +1 -2
  55. package/dist/src/lib/crypto/types.d.ts.map +1 -1
  56. package/dist/src/lib/crypto/types.js +71 -67
  57. package/dist/src/lib/crypto/utils.d.ts +5 -5
  58. package/dist/src/lib/crypto/utils.d.ts.map +1 -1
  59. package/dist/src/lib/crypto/utils.js +48 -66
  60. package/dist/src/lib/crypto/wallet.d.ts +3 -3
  61. package/dist/src/lib/crypto/wallet.d.ts.map +1 -1
  62. package/dist/src/lib/crypto/wallet.js +72 -89
  63. package/dist/src/lib/index.d.ts +5 -4
  64. package/dist/src/lib/index.d.ts.map +1 -1
  65. package/dist/src/lib/index.js +6 -44
  66. package/dist/src/lib/radon/ccdr/eth.d.ts +1 -1
  67. package/dist/src/lib/radon/ccdr/eth.d.ts.map +1 -1
  68. package/dist/src/lib/radon/ccdr/eth.js +95 -83
  69. package/dist/src/lib/radon/ccdr/index.d.ts +2 -2
  70. package/dist/src/lib/radon/ccdr/index.d.ts.map +1 -1
  71. package/dist/src/lib/radon/ccdr/index.js +3 -39
  72. package/dist/src/lib/radon/ccdr/wit.d.ts +2 -2
  73. package/dist/src/lib/radon/ccdr/wit.d.ts.map +1 -1
  74. package/dist/src/lib/radon/ccdr/wit.js +17 -19
  75. package/dist/src/lib/radon/filters.d.ts.map +1 -1
  76. package/dist/src/lib/radon/filters.js +23 -19
  77. package/dist/src/lib/radon/index.d.ts +10 -11
  78. package/dist/src/lib/radon/index.d.ts.map +1 -1
  79. package/dist/src/lib/radon/index.js +205 -187
  80. package/dist/src/lib/radon/reducers.d.ts +2 -2
  81. package/dist/src/lib/radon/reducers.d.ts.map +1 -1
  82. package/dist/src/lib/radon/reducers.js +48 -34
  83. package/dist/src/lib/radon/types.d.ts +2 -2
  84. package/dist/src/lib/radon/types.d.ts.map +1 -1
  85. package/dist/src/lib/radon/types.js +80 -110
  86. package/dist/src/lib/radon/utils.d.ts +3 -3
  87. package/dist/src/lib/radon/utils.d.ts.map +1 -1
  88. package/dist/src/lib/radon/utils.js +49 -52
  89. package/dist/src/lib/rest/kermit.d.ts +20 -0
  90. package/dist/src/lib/rest/kermit.d.ts.map +1 -0
  91. package/dist/src/lib/rest/kermit.js +68 -0
  92. package/dist/src/lib/rest/types.d.ts +5 -0
  93. package/dist/src/lib/rest/types.d.ts.map +1 -0
  94. package/dist/src/lib/rest/types.js +2 -0
  95. package/dist/src/lib/rpc/index.d.ts +2 -2
  96. package/dist/src/lib/rpc/index.d.ts.map +1 -1
  97. package/dist/src/lib/rpc/index.js +3 -19
  98. package/dist/src/lib/rpc/nodes.d.ts +13 -13
  99. package/dist/src/lib/rpc/nodes.d.ts.map +1 -1
  100. package/dist/src/lib/rpc/nodes.js +69 -98
  101. package/dist/src/lib/rpc/provider.d.ts +4 -4
  102. package/dist/src/lib/rpc/provider.d.ts.map +1 -1
  103. package/dist/src/lib/rpc/provider.js +106 -122
  104. package/dist/src/lib/rpc/types.d.ts +2 -2
  105. package/dist/src/lib/rpc/types.d.ts.map +1 -1
  106. package/dist/src/lib/rpc/types.js +13 -16
  107. package/dist/src/lib/types.d.ts +5 -4
  108. package/dist/src/lib/types.d.ts.map +1 -1
  109. package/dist/src/lib/types.js +3 -9
  110. package/dist/src/lib/utils.d.ts +5 -5
  111. package/dist/src/lib/utils.d.ts.map +1 -1
  112. package/dist/src/lib/utils.js +40 -99
  113. package/dist/witnet/assets/index.cjs +6 -0
  114. package/dist/witnet/assets/index.d.cts +29 -0
  115. package/dist/witnet/assets/index.d.cts.map +1 -0
  116. package/dist/witnet/assets/modals/index.cjs +9 -0
  117. package/dist/witnet/assets/modals/index.d.cts +16 -0
  118. package/dist/witnet/assets/modals/index.d.cts.map +1 -0
  119. package/dist/witnet/assets/modals/web3/eth.cjs +23 -0
  120. package/dist/witnet/assets/modals/web3/eth.d.cts +4 -0
  121. package/dist/witnet/assets/modals/web3/eth.d.cts.map +1 -0
  122. package/dist/witnet/assets/modals/web3/ipfs.cjs +18 -0
  123. package/dist/witnet/assets/modals/web3/ipfs.d.cts +3 -0
  124. package/dist/witnet/assets/modals/web3/ipfs.d.cts.map +1 -0
  125. package/dist/witnet/assets/modals/web3/wit.cjs +24 -0
  126. package/dist/witnet/assets/modals/web3/wit.d.cts +3 -0
  127. package/dist/witnet/assets/modals/web3/wit.d.cts.map +1 -0
  128. package/dist/witnet/assets/requests.cjs +43 -0
  129. package/dist/witnet/assets/requests.d.cts +10 -0
  130. package/dist/witnet/assets/requests.d.cts.map +1 -0
  131. package/package.json +41 -24
  132. package/src/bin/bots/watcher.cjs +354 -0
  133. package/src/bin/cli/history.cjs +31 -0
  134. package/src/bin/cli/inspect.js +545 -471
  135. package/src/bin/cli/network.js +658 -557
  136. package/src/bin/cli/nodes.js +392 -332
  137. package/src/bin/cli/radon.js +1071 -844
  138. package/src/bin/cli/wallet.js +1317 -1074
  139. package/src/bin/helpers.js +969 -868
  140. package/src/bin/index.js +329 -0
  141. package/witnet/assets/_index.cjs +5 -0
  142. package/witnet/assets/_requests.cjs +25 -0
  143. package/witnet/assets/_sources.cjs +36 -0
  144. package/witnet/assets/_templates.cjs +36 -0
  145. package/witnet/assets/index.cjs +4 -0
  146. package/witnet/assets/modals/index.cjs +7 -0
  147. package/witnet/assets/modals/web3/eth.cjs +27 -0
  148. package/witnet/assets/modals/web3/ipfs.cjs +22 -0
  149. package/witnet/assets/modals/web3/wit.cjs +28 -0
  150. package/witnet/assets/requests.cjs +49 -0
  151. package/witnet/witnet copy.proto +457 -0
  152. package/witnet/witnet.proto +456 -0
  153. package/witnet/witnet_toolkit-1.6.7-x86_64-pc-windows-msvc.exe +0 -0
  154. package/witnet/witnet_toolkit-1.7.1-x86_64-pc-windows-msvc.exe +0 -0
  155. package/witnet/witnet_toolkit-2.0.0-rc.7-x86_64-pc-windows-msvc.exe +0 -0
  156. package/witnet/witnet_toolkit-2.0.2-x86_64-pc-windows-msvc.exe +0 -0
  157. package/witnet/witnet_toolkit-2.0.21-x86_64-pc-windows-msvc.exe +0 -0
  158. package/witnet/witnet_toolkit-2.0.7-x86_64-pc-windows-msvc.exe +0 -0
  159. package/witnet/witnet_toolkit-2.0.8-x86_64-pc-windows-msvc.exe +0 -0
  160. package/dist/witnet/assets/index.d.ts +0 -29
  161. package/dist/witnet/assets/index.d.ts.map +0 -1
  162. package/dist/witnet/assets/index.js +0 -6
  163. package/dist/witnet/assets/modals/index.d.ts +0 -16
  164. package/dist/witnet/assets/modals/index.d.ts.map +0 -1
  165. package/dist/witnet/assets/modals/index.js +0 -11
  166. package/dist/witnet/assets/modals/web3/eth.d.ts +0 -5
  167. package/dist/witnet/assets/modals/web3/eth.d.ts.map +0 -1
  168. package/dist/witnet/assets/modals/web3/eth.js +0 -26
  169. package/dist/witnet/assets/modals/web3/ipfs.d.ts +0 -4
  170. package/dist/witnet/assets/modals/web3/ipfs.d.ts.map +0 -1
  171. package/dist/witnet/assets/modals/web3/ipfs.js +0 -18
  172. package/dist/witnet/assets/modals/web3/wit.d.ts +0 -4
  173. package/dist/witnet/assets/modals/web3/wit.d.ts.map +0 -1
  174. package/dist/witnet/assets/modals/web3/wit.js +0 -17
  175. package/dist/witnet/assets/requests.d.ts +0 -11
  176. package/dist/witnet/assets/requests.d.ts.map +0 -1
  177. package/dist/witnet/assets/requests.js +0 -43
  178. package/src/bin/cli/history.js +0 -31
  179. package/src/bin/postinstall.js +0 -9
  180. package/src/bin/toolkit.js +0 -290
  181. package/witnet/assets/_index.js +0 -8
  182. package/witnet/assets/_requests.js +0 -25
  183. package/witnet/assets/_sources.js +0 -36
  184. package/witnet/assets/_templates.js +0 -36
  185. package/witnet/assets/index.js +0 -4
  186. package/witnet/assets/modals/index.js +0 -9
  187. package/witnet/assets/modals/web3/eth.js +0 -29
  188. package/witnet/assets/modals/web3/ipfs.js +0 -22
  189. package/witnet/assets/modals/web3/wit.js +0 -21
  190. package/witnet/assets/requests.js +0 -49
  191. /package/witnet/assets/modals/web3/{btc.js → btc.cjs} +0 -0
  192. /package/witnet/assets/modals/web3/{sol.js → sol.cjs} +0 -0
@@ -1,895 +1,1122 @@
1
- const cbor = require("cbor")
2
- const fs = require("fs")
3
- const inquirer = require("inquirer")
4
- const merge = require("lodash.merge")
5
- const path = require("path")
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";
6
8
 
7
- const helpers = require("../helpers")
8
- const { Witnet } = require("../../../dist/src")
9
+ const require = createRequire(import.meta.url);
9
10
 
10
- const WITNET_ASSETS_PATH = process.env.WITNET_SDK_RADON_ASSETS_PATH || "../../../../../witnet/assets"
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";
11
17
 
12
18
  /// ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
13
19
  /// CLI SUBMODULE CONSTANTS ===========================================================================================
14
20
 
15
- const isModuleInitialized = fs.existsSync("./witnet/assets/index.js")
21
+ const isModuleInitialized = fs.existsSync("./witnet/assets/index.cjs");
16
22
 
17
- module.exports = {
18
- flags: {
19
- module: {
20
- hint: "Package where to fetch Radon assets from (supersedes --legacy).",
21
- param: "NPM_PACKAGE",
22
- },
23
- },
24
- router: isModuleInitialized
25
- ? {
26
- assets: {
27
- hint: "List available Witnet Radon assets.",
28
- params: "[RADON_ASSETS ...]",
29
- options: {
30
- filter: {
31
- hint: "Restrict output to name-matching assets.",
32
- },
33
- legacy: {
34
- hint: "List only those declared in witnet/assets folder.",
35
- },
36
- modals: {
37
- hint: "Restrict output to Radon modals.",
38
- },
39
- requests: {
40
- hint: "Restrict output to Radon requests.",
41
- },
42
- templates: {
43
- hint: "Restrict output to Radon templates.",
44
- },
45
- },
46
- },
47
- check: {
48
- hint: "Check correctness of Witnet Radon artifacts declared in witnet/assets folder.",
49
- params: [],
50
- options: {},
51
- },
52
- decode: {
53
- hint: "Break down specs of one or more Radon assets.",
54
- params: ["RAD_BYTECODE | RAD_HASH | RADON_ASSET"],
55
- options: {
56
- json: {
57
- hint: "Outputs data in JSON format.",
58
- },
59
- headline: {
60
- hint: "Settles output report headline.",
61
- param: ":string",
62
- },
63
- indent: {
64
- hint: "Prefixes given number of white spaces for every output line.",
65
- param: ":number",
66
- },
67
- },
68
- },
69
- "dry-run": {
70
- hint: "Simulate resolution of one or more Radon assets, as if solved by the Wit/Oracle.",
71
- params: ["RAD_BYTECODE | RAD_HASH | RADON_ASSET"],
72
- options: {
73
- default: {
74
- hint: "Use default sample parameters on parametrized Radon assets.",
75
- },
76
- json: {
77
- hint: "Outputs data in JSON format.",
78
- },
79
- headline: {
80
- hint: "Settles output report headline.",
81
- param: ":string",
82
- },
83
- indent: {
84
- hint: "Prefixes given number of white spaces for every output line.",
85
- param: ":number",
86
- },
87
- verbose: {
88
- hint: "Outputs detailed dry-run report.",
89
- },
90
- },
91
- },
92
- }
93
- : {
94
- assets: {
95
- hint: "List available Witnet Radon assets.",
96
- params: "[RADON_ASSETS ...]",
97
- options: {
98
- filter: {
99
- hint: "Restrict output to name-matching assets.",
100
- },
101
- },
102
- },
103
- decode: {
104
- hint: "Break down specs of one or more Radon assets.",
105
- params: ["RAD_BYTECODE | RAD_HASH | RADON_ASSET"],
106
- options: {
107
- json: {
108
- hint: "Outputs data in JSON format.",
109
- },
110
- headline: {
111
- hint: "Settles output report headline.",
112
- param: ":string",
113
- },
114
- indent: {
115
- hint: "Prefixes given number of white spaces for every output line.",
116
- param: ":number",
117
- },
118
- },
119
- },
120
- "dry-run": {
121
- hint: "Simulate resolution of one or more Radon assets, as if solved by the Wit/Oracle.",
122
- params: ["RAD_BYTECODE | RAD_HASH | RADON_ASSET"],
123
- options: {
124
- json: {
125
- hint: "Outputs data in JSON format.",
126
- },
127
- headline: {
128
- hint: "Settles output report headline.",
129
- param: ":string",
130
- },
131
- indent: {
132
- hint: "Prefixes given number of white spaces for every output line.",
133
- param: ":number",
134
- },
135
- verbose: {
136
- hint: "Outputs detailed dry-run report.",
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)."
137
64
  },
138
- },
139
- },
140
- init: {
141
- hint: "Initialize a Witnet Radon workspace in this project.",
142
- },
143
- },
144
- subcommands: {
145
- assets, init, check, decode, "dry-run": dryrun,
146
- },
147
- loadAssets,
148
- }
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
+ };
149
156
 
157
+ export const subcommands = {
158
+ assets,
159
+ init,
160
+ check,
161
+ decode,
162
+ "dry-run": dryrun,
163
+ };
150
164
 
151
165
  ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
152
166
  /// CLI SUBMODULE COMMANDS ============================================================================================
153
167
 
154
- async function init () {
155
- if (!fs.existsSync("./witnet/assets/")) {
156
- fs.mkdirSync("./witnet/assets", { recursive: true })
157
- }
158
- if (!fs.existsSync(".env_witnet")) {
159
- fs.cpSync("node_modules/@witnet/sdk/.env_witnet", ".env_witnet")
160
- }
161
- if (!fs.existsSync("./witnet/assets/index.js")) {
162
- fs.cpSync("node_modules/@witnet/sdk/witnet/assets/_index.js", "./witnet/assets/index.js")
163
- }
164
- if (!fs.existsSync("./witnet/assets/requests.js")) {
165
- fs.cpSync("node_modules/@witnet/sdk/witnet/assets/_requests.js", "./witnet/assets/requests.js")
166
- }
167
- if (!fs.existsSync("./witnet/assets/sources.js")) {
168
- fs.cpSync("node_modules/@witnet/sdk/witnet/assets/_sources.js", "./witnet/assets/sources.js")
169
- }
170
- if (!fs.existsSync("./witnet/assets/templates.js")) {
171
- fs.cpSync("node_modules/@witnet/sdk/witnet/assets/_templates.js", "./witnet/assets/templates.js")
172
- }
173
- console.info(`Initialized Witnet Radon workspace at folder ${process.cwd()}/witnet/assets`)
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
+ );
174
202
  }
175
203
 
176
- async function assets (options = {}, [...patterns]) {
177
- helpers.traceHeader(
178
- `${options?.module ? options.module.toUpperCase() : path.basename(process.cwd()).toUpperCase()} RADON ASSETS`,
179
- helpers.colors.white
180
- )
181
- const assets = clearEmptyBranches(
182
- options?.module ? require(options.module) : loadAssets(options),
183
- patterns,
184
- options
185
- );
186
- if (assets && Object.keys(assets).length > 0) {
187
- traceWitnetArtifacts(assets, patterns, " ", options)
188
- } else {
189
- console.info("> No custom Radon assets declared just yet.")
190
- }
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
+ }
191
219
  }
192
220
  /// -------------------------------------------------------------------------------------------------------------------
193
221
 
194
- async function check () {
195
- if (!isModuleInitialized) {
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.`)
197
- }
198
- try {
199
- const assets = loadAssets({ legacy: true })
200
- const [
201
- modals,
202
- requests,
203
- sources,
204
- templates,
205
- ] = [
206
- helpers.countLeaves(Witnet.Radon.RadonModal, assets),
207
- helpers.countLeaves(Witnet.Radon.RadonRequest, assets),
208
- helpers.countLeaves(Witnet.Radon.RadonRetrieval, assets?.sources),
209
- helpers.countLeaves(Witnet.Radon.RadonTemplate, assets),
210
- ]
211
- if (modals > 0) console.info("> Radon modals: ", modals)
212
- if (sources > 0) console.info("> Radon sources: ", sources)
213
- if (requests > 0) console.info("> Radon requests: ", requests)
214
- if (templates > 0) console.info("> Radon templates:", templates)
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);
215
240
 
216
- if (modals + sources + requests + templates === 0) {
217
- console.info("-----------------------------")
218
- console.info("No Radon assets declared yet!")
219
- } else {
220
- console.info("--------------------------------------")
221
- console.info("All Radon assets checked successfully!")
222
- }
223
- } catch (e) {
224
- console.error("Radon assets verification failed:")
225
- console.info("----------------------------------")
226
- console.info(e)
227
- }
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
+ }
228
253
  }
229
254
  /// -------------------------------------------------------------------------------------------------------------------
230
255
 
231
- async function decode (options = {}, args = []) {
232
- if (args.length === 0) {
233
- throw Error("No Radon asset was specified")
234
- }
235
- const asset = args[0]
236
- if (helpers.isHexString(asset)) {
237
- try {
238
- const request = Witnet.Radon.RadonRequest.fromBytecode(asset)
239
- traceWitnetRadonRequest(request, options)
240
- } catch (err) {
241
- console.error(err)
242
- if ((asset.startsWith("0x") && asset.length === 66) || (!asset.startsWith("0x") && asset.length === 64)) {
243
- // TODO: assume it's a DR_TX_HASH
244
- // TODO: assume it's a RAD_HASH
245
- }
246
- }
247
- } else {
248
- args = args.slice(1)
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);
249
277
 
250
- const assets = options?.module ? require(options.module) : loadAssets(options)
251
- const headline = options?.headline
252
- const crafts = flattenRadonArtifacts(assets).filter(craft => craft.key.toLowerCase().indexOf(asset.toLowerCase()) >= 0)
253
- if (crafts.length === 0) {
254
- throw Error(`No matched found for pattern "${asset}"`)
255
- }
256
- for (let { artifact, key } of crafts) {
257
- let prefix = ""
258
- if (artifact instanceof Witnet.Radon.RadonRequest) {
259
- prefix = "RadonRequest::"
260
- } else if (artifact instanceof Witnet.Radon.RadonModal) {
261
- artifact.providers = [...args[0].split(";") || "https://dummy"]
262
- const modalArgs = []
263
- let argIndex = 1
264
- while (modalArgs.length < artifact.argsCount) {
265
- modalArgs.push(args[argIndex] || `{:${argIndex}}`)
266
- argIndex += 1
267
- }
268
- artifact = artifact.buildRadonRequest(modalArgs)
269
- prefix = "RadonModal::"
270
- } else if (artifact instanceof Witnet.Radon.RadonTemplate) {
271
- const templateArgs = artifact.sources.map(({ argsCount }) =>
272
- Array.from({ length: argsCount }, (_, i) => `{:${i}}`)
273
- )
274
- artifact = artifact.buildRadonRequest(templateArgs)
275
- prefix = "RadonTemplate::"
276
- } else if (artifact instanceof Witnet.Radon.RadonRetrieval) {
277
- if (artifact.argsCount > 0) {
278
- const retrievalArgs = Array.from(
279
- { length: artifact.argsCount },
280
- (_, i) => `{:${i + 1}}`
281
- )
282
- artifact = artifact.foldArgs(retrievalArgs)
283
- }
284
- artifact = new Witnet.Radon.RadonRequest({ sources: artifact })
285
- prefix = "RadonRetrieval::"
286
- }
287
- if (!headline) {
288
- options.headline = `${prefix}${key}`
289
- }
290
- traceWitnetRadonRequest(artifact, options)
291
- if (options?.verbose && key !== crafts[crafts.length - 1].key) {
292
- console.info(`${options?.indent || ""}${"─".repeat(150)}`)
293
- }
294
- console.info()
295
- }
296
- }
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
+ }
297
329
  }
298
330
  /// -------------------------------------------------------------------------------------------------------------------
299
331
 
300
- async function dryrun (options = {}, args = []) {
301
- if (args.length === 0) {
302
- throw Error("No Radon asset was specified")
303
- }
304
- const asset = args[0]
305
- if (helpers.isHexString(asset)) {
306
- try {
307
- const request = Witnet.Radon.RadonRequest.fromBytecode(asset)
308
- await traceWitnetRadonRequestDryRun(request, options)
309
- } catch {
310
- if ((asset.startsWith("0x") && asset.length === 66) || (!asset.startsWith("0x") && asset.length === 64)) {
311
- // TODO: assume it's a RAD_HASH, and try to retrieve the BYTECODE from the Witnet network
312
- }
313
- }
314
- } else {
315
- args = args.slice(1)
316
- const assets = options?.module ? require(options.module) : loadAssets(options)
317
- const headline = options?.headline
318
- const crafts = flattenRadonArtifacts(assets).filter(craft => craft.key.toLowerCase().indexOf(asset.toLowerCase()) >= 0)
319
- if (crafts.length === 0) {
320
- throw Error(`No matched found for pattern "${asset}"`)
321
- }
322
- for (let { artifact, key } of crafts) {
323
- let prefix = ""
324
- if (artifact instanceof Witnet.Radon.RadonRequest) {
325
- prefix = "RadonRequest::"
326
- } else {
327
- let artifactArgs = []
328
- if (artifact instanceof Witnet.Radon.RadonModal) {
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
- )
344
- prefix = "RadonModal::"
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
- }
369
- }
370
- }
371
- if (!headline) {
372
- options.headline = `${prefix}${key}`
373
- }
374
- await traceWitnetRadonRequestDryRun(artifact, options)
375
- if (options?.verbose && key !== crafts[crafts.length - 1].key) {
376
- console.info(`${options?.indent || ""}${"─".repeat(150)}`)
377
- }
378
- console.info()
379
- }
380
- }
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
+ }
381
428
  }
382
429
  /// -------------------------------------------------------------------------------------------------------------------
383
430
 
384
431
  /// ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
385
432
  /// CLI SUBMODULE INTERNAL METHODS ------------------------------------------------------------------------------------
386
433
 
387
- const extractTypeName = (str) => str ? str.split(/(?=[A-Z])/).slice(1).join("") : "Any"
434
+ const extractTypeName = (str) =>
435
+ str
436
+ ? str
437
+ .split(/(?=[A-Z])/)
438
+ .slice(1)
439
+ .join("")
440
+ : "Any";
388
441
 
389
442
  const stringifyFilter = (x, c) => {
390
- const color = c || helpers.colors.mcyan
391
- return color(`${Witnet.Radon.filters.Opcodes[x.opcode]}(${x.args ? JSON.stringify(x.args) : ""})`)
392
- }
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
+ };
393
448
 
394
449
  const stringifyReducer = (x, c) => {
395
- const color = c || helpers.colors.mcyan
396
- return color(`${Witnet.Radon.reducers.Opcodes[x.opcode]}()`)
397
- }
398
-
399
- function loadAssets (options) {
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
- );
406
- }
407
-
408
- function flattenRadonArtifacts (tree, headers) {
409
- if (!headers) headers = []
410
- const matches = []
411
- for (const key in tree) {
412
- if (
413
- tree[key] instanceof Witnet.Radon.RadonRetrieval ||
414
- tree[key] instanceof Witnet.Radon.RadonModal ||
415
- tree[key] instanceof Witnet.Radon.RadonRequest ||
416
- tree[key] instanceof Witnet.Radon.RadonTemplate
417
- ) {
418
- matches.push({
419
- key,
420
- artifact: tree[key],
421
- })
422
- } else if (typeof tree[key] === "object") {
423
- matches.push(...flattenRadonArtifacts(
424
- tree[key],
425
- [...headers, key]
426
- ))
427
- }
428
- }
429
- return matches
450
+ const color = c || helpers.colors.mcyan;
451
+ return color(`${Witnet.Radon.reducers.Opcodes[x.opcode]}()`);
430
452
  };
431
453
 
432
- function countWitnetArtifacts (assets, args, options) {
433
- let counter = 0
434
- Object.entries(assets).forEach(([key, value]) => {
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)
454
- )) {
455
- counter++
456
- } else if (typeof value === "object") {
457
- counter += countWitnetArtifacts(value, args, options)
458
- }
459
- })
460
- return counter
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;
461
459
  }
462
460
 
463
- function clearEmptyBranches (node, args, options) {
464
- if (node) {
465
- const assets = Object.fromEntries(
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
- }
481
- if (
482
- include && (
483
- !options?.filter || args.find(arg => key.toLowerCase().indexOf(arg.toLowerCase()) >= 0)
484
- )
485
- ) {
486
- return [key, value]
487
- } else if (typeof value === "object") {
488
- if (countWitnetArtifacts(value, args, options) > 0) {
489
- return [key, clearEmptyBranches(value, args, options)]
490
- } else {
491
- return [key, undefined]
492
- }
493
- } else {
494
- return [key, undefined]
495
- }
496
- })
497
- .filter(([, value]) => value !== undefined)
498
- )
499
- if (Object.keys(assets).length > 0) {
500
- return assets
501
- } else {
502
- return undefined
503
- }
504
- }
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;
505
480
  }
506
481
 
507
- function traceWitnetArtifacts (assets, args, indent = "", options) {
508
- const prefix = `${indent}`
509
- Object.keys(assets).forEach((key, index) => {
510
- const isLast = index === Object.keys(assets).length - 1
511
- const found = args.find(arg => key.toLowerCase().indexOf(arg.toLowerCase()) >= 0)
512
- const color = found ? helpers.colors.mcyan : helpers.colors.cyan
513
- if (assets[key] instanceof Witnet.Radon.RadonRequest) {
514
- if (!options?.filter || found) {
515
- console.info(`${prefix}${color(key)} ${assets[key].sources.length > 1 ? helpers.colors.yellow(`(${assets[key].sources.length} sources)`) : ""}`)
516
- if (isLast) {
517
- console.info(`${prefix}`)
518
- }
519
- }
520
- } else if ((
521
- assets[key] instanceof Witnet.Radon.RadonTemplate ||
522
- assets[key] instanceof Witnet.Radon.RadonModal
523
- )) {
524
- const argsCount = assets[key].argsCount
525
- if (!options?.filter || found) {
526
- console.info(`${prefix}${color(key)} ${argsCount > 0 ? helpers.colors.green(`(${argsCount} args)`) : ""}`)
527
- if (isLast) {
528
- console.info(`${prefix}`)
529
- }
530
- }
531
- } else if (assets[key] instanceof Witnet.Radon.RadonRetrieval) {
532
- const argsCount = assets[key].argsCount
533
- if (!options?.filter || found) {
534
- console.info(`${prefix}${color(key)} ${argsCount > 0 ? helpers.colors.green(`(${argsCount} args)`) : ""}`)
535
- if (isLast) {
536
- console.info(`${prefix}`)
537
- }
538
- }
539
- } else if (typeof assets[key] === "object" && countWitnetArtifacts(assets[key], args, options) > 0) {
540
- console.info(`${indent}${isLast ? "└─ " : "├─ "}${key}`)
541
- traceWitnetArtifacts(assets[key], args, !isLast ? `${indent}│ ` : `${indent} `, options)
542
- }
543
- })
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;
544
517
  }
545
518
 
546
- function traceWitnetRadonReportHeadline (request, options) {
547
- const trait = (str) => `${str}${" ".repeat(66 - str.length)}`
548
- const indent = options?.indent ? " ".repeat(options.indent) : ""
549
- const resultDataType = `Result<${extractTypeName(request.sources[0]?.script?.outputType.constructor.name)}, RadonError>`
550
- console.info(`${indent}╔══════════════════════════════════════════════════════════════════════════════╗`)
551
- console.info(`${indent}║ ${helpers.colors.white(options?.headline)}${" ".repeat(77 - options?.headline.length)}║`)
552
- console.info(`${indent}╠══════════════════════════════════════════════════════════════════════════════╣`)
553
- console.info(`${indent}║ ${helpers.colors.white("RAD hash")}: ${helpers.colors.lgreen(request.radHash)} ║`)
554
- console.info(`${indent}║ RAD size: ${helpers.colors.green(trait(helpers.commas(request.weight()) + " bytes"))} ║`)
555
- console.info(`${indent}║ RAD type: ${helpers.colors.yellow(trait(resultDataType))} ║`)
556
- // if (!options.verbose) {
557
- // console.info(`${indent}║ > Radon operators: ${white(trait(commas(request.opsCount())))} ║`)
558
- // }
559
- // console.info(`${indent}╠════════════════════════════════════════════════════════════════════════════╣`)
560
- // console.info(`${indent}║ > Times solved: ${white(trait("{ values: 123, errors: 220 }"))} ║`)
561
- // console.info(`${indent}║ > Times witnessed: ${white(trait("{ values: 2130, errors: 1326 }"))} ║`)
562
- // console.info(`${indent}║ > Total fees: ${white(trait("15,234.123 Wits"))} ║`)
563
- // console.info(`${indent}║ > Total slash: ${white(trait(" 56.123 Wits"))} ║`)
564
- // console.info(`${indent}║ > Total burn: ${white(trait(" 0.789 Wits"))} ║`)
565
- // if (verbose) {
566
- // console.info(`${indent}╚══╤═════════════════════════════════════════════════════════════════════════╝`)
567
- // } else {
568
- // console.info(`${indent}╚════════════════════════════════════════════════════════════════════════════╝`)
569
- // }
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
+ }
570
571
  }
571
572
 
572
- function traceWitnetRadonRequest (request, options) {
573
- const indent = options?.indent ? " ".repeat(parseInt(options.indent)) : ""
574
- if (options?.json) {
575
- console.info(JSON.stringify(request.toProtobuf(), null, options?.indent || 0))
576
- } else {
577
- if (!options.headline) options.headline = "WITNET DATA REQUEST DISASSEMBLE"
578
- traceWitnetRadonReportHeadline(request, options)
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
+ }
579
627
 
580
- console.info(`${indent}╚══╤═══════════════════════════════════════════════════════════════════════════╝`)
581
- console.info(`${indent}┌──┴─────────────────┐`)
582
- console.info(`${indent}│ ${helpers.colors.white("RETRIEVE DATA")} │`) // ├ ┤
583
- console.info(`${indent}└──┬─┬───────────────┘`)
584
- request.sources.forEach((source, sourceIndex) => {
585
- const authority = source.authority?.toUpperCase().split(".").slice(-2).join(".") || (
586
- source.method === Witnet.Radon.retrievals.Methods.RNG ? "WIT/RNG" : ""
587
- )
588
- const corner = sourceIndex === request.sources.length - 1 ? "└" : "├"
589
- const sep = sourceIndex === request.sources.length - 1 ? " " : "│"
590
- console.info(
591
- `${indent} │ ${corner}─ ${helpers.colors.white("[ ")}${helpers.colors.white(`Data source #${sourceIndex + 1}`)
592
- } ${" ".repeat(3 - sourceIndex.toString().length)}${helpers.colors.white(authority)} ${helpers.colors.white("]")}`
593
- )
594
- if (source.method !== Witnet.Radon.retrievals.Methods.RNG) {
595
- console.info(
596
- `${indent} │ ${sep} > Request: ${
597
- helpers.colors.mgreen(Witnet.Radon.retrievals.Methods[source.method].split(/(?=[A-Z])/).join("-").toUpperCase())
598
- }`
599
- )
600
- console.info(`${indent} ${sep} > URL query: ${helpers.colors.green(source.url)}`)
601
- if (source?.headers && Object.keys(source.headers).length > 0) {
602
- console.info(`${indent} │ ${sep} > HTTP headers: ${helpers.colors.green(JSON.stringify(source.headers))}`)
603
- }
604
- if (source?.body) {
605
- console.info(`${indent} │ ${sep} > HTTP body: ${helpers.colors.green(source.body)}`)
606
- }
607
- if (source?.script) {
608
- // console.log(source.script.toBytecode())
609
- const steps = source.script.disect()
610
- console.info(
611
- `${indent} │ ${sep} > Radon script: ${helpers.colors.lyellow("[ ")
612
- }${helpers.colors.yellow(steps[0][1])}${" ".repeat(12 - steps[0][1].length)
613
- }${helpers.colors.lyellow(" ]")
614
- } ${helpers.colors.mcyan(steps[0][2])}`
615
- )
616
- steps.slice(1).forEach(step => {
617
- console.info(
618
- `${indent} │ ${sep} ${helpers.colors.lyellow("[ ")
619
- }${helpers.colors.yellow(step[1])
620
- }${" ".repeat(12 - step[1].length)
621
- }${helpers.colors.lyellow(" ]")
622
- } ${" ".repeat(2 * step[0])}${helpers.colors.mcyan(step[2])
623
- }`
624
- )
625
- })
626
- const outputType = source.script.outputType.constructor.name || "RadonAny"
627
- console.info(
628
- `${indent} │ ${sep} ${helpers.colors.lyellow("[ ")
629
- }${helpers.colors.yellow(outputType)
630
- }${" ".repeat(12 - outputType.length)
631
- }${helpers.colors.lyellow(" ]")
632
- }`
633
- )
634
- }
635
- }
636
- if (sourceIndex < request.sources.length - 1) {
637
- console.info(`${indent} │ │`)
638
- }
639
- })
640
- console.info(`${indent}┌──┴──────────────────┐`)
641
- console.info(`${indent}│ ${helpers.colors.white("AGGREGATE SOURCES")} │`)
642
- console.info(`${indent}└──┬──────────────────┘`) // ┬
643
- request.sourcesReducer?.filters.forEach(filter => console.info(`${indent} │ > Radon filter: ${stringifyFilter(filter)}`))
644
- console.info(`${indent} │ > Radon reducer: ${stringifyReducer(request.sourcesReducer)}`)
645
- console.info(`${indent}┌──┴──────────────────┐`)
646
- console.info(`${indent}│ ${helpers.colors.white("WITNESSING TALLY")} │`)
647
- console.info(`${indent}└─────────────────────┘`) // ┬
648
- request.witnessReducer?.filters.forEach(filter => console.info(`${indent} > Radon filter: ${stringifyFilter(filter)}`))
649
- console.info(`${indent} > Radon reducer: ${stringifyReducer(request.witnessReducer)}`)
650
- }
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
+ // }
651
664
  }
652
665
 
653
- async function traceWitnetRadonRequestDryRun (request, options) {
654
- const bytecode = request.toBytecode()
655
- let report = await helpers
656
- .toolkitRun(options, ["try-data-request", "--hex", bytecode.startsWith("0x") ? bytecode.slice(2) : bytecode])
657
- .catch((err) => {
658
- let errorMessage = err.message.split("\n").slice(1).join("\n").trim()
659
- const errorRegex = /.*^error: (?<message>.*)$.*/gm
660
- const matched = errorRegex.exec(err.message)
661
- if (matched) {
662
- errorMessage = matched.groups.message
663
- }
664
- throw errorMessage || err
665
- })
666
- if (!report) {
667
- throw Error("No dry-report?")
668
- } else {
669
- report = JSON.parse(report)
670
- }
671
- const result = report?.aggregate.result
672
- const resultType = Object.keys(result)[0]
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
- }
693
- if (options?.json) {
694
- if (options?.verbose) {
695
- console.info(JSON.stringify(report, null, options?.indent ? " ".repeat(options.indent) : ""))
696
- } else {
697
- result[resultType] = resultValue
698
- console.info(JSON.stringify(result, null, options?.indent ? " ".repeat(options.indent) : ""))
699
- }
700
- return
701
- }
702
- if (!options.headline) options.headline = "WITNET DATA REQUEST DRY-RUN REPORT"
703
- traceWitnetRadonReportHeadline(request, options)
704
- const indent = options?.indent ? " ".repeat(options.indent) : ""
705
- console.info(`${indent}╚══╤═══════════════════════════════════════════════════════════════════════════╝`)
706
- let execTimeMs = report.retrieve?.map(retrieval =>
707
- (retrieval?.running_time.secs || 0) + (retrieval?.running_time.nanos || 0) / 1000
708
- ).reduce(
709
- (sum, secs) => sum + secs
710
- )
711
- execTimeMs = Math.round(execTimeMs) + " ms"
712
- let flexbar = "─".repeat(17)
713
- let flexspc = " ".repeat(flexbar.length + 12)
714
- console.info(`${indent}┌──┴─────────────────────────────${flexbar}──────┐`)
715
- console.info(`${indent}│ ${helpers.colors.white("Data providers")} ${flexspc} │`) // ├ ┤
716
- console.info(`${indent}├────────────────────────────────${flexbar}──────┤`)
717
- console.info(`${indent}│ Execution time: ${helpers.colors.green(execTimeMs)} ${" ".repeat(flexbar.length + 19 - execTimeMs.length)} │`)
718
- console.info(`${indent}└──┬─┬───────────────────────────${flexbar}──────┘`)
719
- request.sources.forEach((source, sourceIndex) => {
720
- const authority = source.authority?.toUpperCase().split(".").slice(-2).join(".") || (
721
- source.method === Witnet.Radon.retrievals.Methods.RNG ? "WIT/RNG" : ""
722
- )
723
- const corner = sourceIndex === request.sources.length - 1 ? "└" : "├"
724
- const sep = sourceIndex === request.sources.length - 1 ? " " : "│"
725
- const color = report.retrieve[sourceIndex].result?.RadonError
726
- ? (options?.verbose ? helpers.colors.lgray : helpers.colors.gray)
727
- : (options?.verbose ? helpers.colors.lgreen : helpers.colors.green)
728
- if (options?.verbose) {
729
- console.info(
730
- `${indent} │ ${corner}─ ${
731
- helpers.colors.white("[ ")
732
- }${
733
- helpers.colors.white(`Data Source #${sourceIndex + 1}`)
734
- } ${
735
- " ".repeat(3 - sourceIndex.toString().length)
736
- }${
737
- color(authority)
738
- } ${
739
- helpers.colors.white("]")
740
- }`
741
- )
742
- } else {
743
- console.info(`${indent} │ ${corner}─ [ ${color(authority)} ]`)
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
744
683
  }
745
- if (source.method !== Witnet.Radon.retrievals.Methods.RNG && options?.verbose) {
746
- console.info(
747
- `${indent} │ ${sep} > Request: ${
748
- helpers.colors.mgreen(Witnet.Radon.retrievals.Methods[source.method].split(/(?=[A-Z])/).join("-").toUpperCase())
749
- }`
750
- )
751
- console.info(`${indent} │ ${sep} > URL query: ${helpers.colors.green(source.url)}`)
752
- if (source?.headers && Object.keys(source.headers).length > 0) {
753
- console.info(`${indent} │ ${sep} > HTTP headers: ${helpers.colors.green(JSON.stringify(source.headers))}`)
754
- }
755
- if (source?.body) {
756
- console.info(`${indent} │ ${sep} > HTTP body: ${helpers.colors.green(source.body)}`)
757
- }
758
- const printData = (headline, data, color) => {
759
- const type = Object.keys(data)[0]
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) || [""]
762
- if (lines.length === 256) lines[255] += "..."
763
- const typeColor = (type === "RadonError") ? helpers.colors.red : helpers.colors.yellow
764
- const lineColor = (type === "RadonError") ? helpers.colors.gray : color
765
- console.info(
766
- `${indent} │ ${sep} > ${headline}${" ".repeat(15 - headline.length)} \x1b[1;m${
767
- typeColor("[ ")
768
- }\x1b[0m${typeColor(type)}${
769
- " ".repeat(12 - type.length)
770
- }\x1b[1;m${typeColor(" ]")}\x1b[0m ${
771
- lineColor(lines[0])
772
- }`)
773
- lines.slice(1).forEach(line => {
774
- console.info(`${indent} │ ${sep} ${lineColor(line)}`)
775
- })
776
- }
777
- if (report?.retrieve[sourceIndex]?.partial_results) {
778
- printData("HTTP response:", report?.retrieve[sourceIndex]?.partial_results[0], helpers.colors.cyan)
779
- }
780
- printData("Radon result:", report?.retrieve[sourceIndex]?.result, helpers.colors.mcyan)
781
- }
782
- if (options?.verbose && sourceIndex < request.sources.length - 1) {
783
- console.info(`${indent} │ │`)
784
- }
785
- })
786
- flexbar = "─".repeat(24)
787
- flexspc = " ".repeat(36)
788
- console.info(`${indent}┌──┴───────────────────────────${flexbar}─┐`)
789
- console.info(`${indent}${helpers.colors.white("Aggregated result")}${flexspc} │`) // ├ ┤
790
- console.info(`${indent}├──────────────────────────────${flexbar}─┤`)
791
- if (options?.verbose) {
792
- let partial_index = 0
793
- const partial_results = report.sourcesReducer?.partial_results
794
- request.sourcesReducer?.filters.forEach(filter => {
795
- const color = (partial_results && partial_results[partial_index]?.RadonArray) ? helpers.colors.mcyan : helpers.colors.gray
796
- const items = (partial_results && partial_results[partial_index]?.RadonArray)
797
- ? ` over ${partial_results[partial_index]?.RadonArray.length} sources`
798
- : ""
799
- partial_index += 1
800
- filter = stringifyFilter(filter, color)
801
- console.info(
802
- `${indent}│ Radon filter: ${filter}${
803
- helpers.colors.cyan(items)
804
- }${
805
- " ".repeat(flexbar.length + 22 - filter.length - items.length)
806
- } │`
807
- )
808
- })
809
- const color = (partial_results && partial_results[partial_index]?.RadonArray) ? helpers.colors.mcyan : helpers.colors.gray
810
- const items = (partial_results && partial_results[partial_index]?.RadonArray)
811
- ? ` over ${partial_results[partial_index]?.RadonArray.length} sources`
812
- : ""
813
- const reducer = stringifyReducer(request.sourcesReducer, color)
814
- console.info(
815
- `${indent}│ Radon reducer: ${reducer}${
816
- helpers.colors.cyan(items)}${" ".repeat(flexbar.length + 22 - reducer.length - items.length)
817
- } │`
818
- )
819
- }
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
- }
826
- console.info(`${indent}└────┬─────────────────────────${flexbar}─┘`)
827
- const printMapItem = (indent, width, key, value, indent2 = "") => {
828
- if (key) key = `${indent2}${key}: `
829
- else key = `${indent2}`
830
- let type = extractTypeName(Object.keys(value)[0])
831
- value = Object.values(value)[0]
832
- if (["Map", "Array"].includes(type)) {
833
- if (key.length > width - 12) {
834
- console.info(
835
- `${indent} ${
836
- helpers.colors.myellow(`[ ${type}${" ".repeat(7 - type.length)} ]`)
837
- } ${
838
- " ".repeat(width - 15)}${helpers.colors.green("...")
839
- }`
840
- )
841
- } else {
842
- console.info(
843
- `${indent} ${
844
- helpers.colors.myellow(`[ ${type}${" ".repeat(7 - type.length)} ]`)
845
- } ${
846
- helpers.colors.green(key)
847
- }${
848
- " ".repeat(width - 12 - key.length)
849
- }`
850
- )
851
- }
852
- Object.entries(value).forEach(([key, value]) => printMapItem(indent, width, type === "Map" ? key : null, helpers.unescapeSlashes(value), indent2 + " "))
853
- } else {
854
- if (key.length > width - 12) {
855
- console.info(`${indent} ${helpers.colors.yellow(type)} ${" ".repeat(width - 15)}${helpers.colors.green("...")}`)
856
- } else {
857
- type = `[ ${type}${" ".repeat(7 - type.length)} ]`
858
- const result = key + value
859
- // let spaces = width - 12 - result.length
860
- if (result.length > width - 15) {
861
- value = value.slice(0, width - 15 - key.length) + "..."
862
- // spaces = 0
863
- }
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
- }
869
- }
870
- }
871
- }
872
- const printResult = (indent, width, resultType, resultValue) => {
873
- resultType = extractTypeName(resultType)
874
- resultValue = typeof resultValue === "object" || Array.isArray(resultValue) ? JSON.stringify(resultValue) : resultValue
875
- if (["Map", "Array"].includes(resultType)) {
876
- console.info(`${indent} └─ ${helpers.colors.lyellow(`[ ${resultType}${" ".repeat(7 - resultType.length)} ]`)}`)
877
- const obj = JSON.parse(resultValue)
878
- Object.entries(obj).forEach(([key, value]) => printMapItem(indent, width, resultType === "Map" ? key : null, value))
879
- } else {
880
- if (resultType === "Bytes") {
881
- resultValue = JSON.parse(resultValue).map(char => ("00" + char.toString(16)).slice(-2)).join("")
882
- } else if (resultType === "Boolean") {
883
- resultValue = JSON.stringify(resultValue)
884
- }
885
- const color = resultType.indexOf("Error") > -1 ? helpers.colors.gray : helpers.colors.lcyan
886
- const typeText = resultType.indexOf("Error") > -1 ? "\x1b[1;98;41m Error \x1b[0m" : helpers.colors.lyellow(`[ ${resultType} ]`)
887
- const lines = resultValue.match(/.{1,96}/g)?.slice(0, 256) || [""]
888
- console.info(`${indent} └─ ${typeText} ${color(lines[0])}`)
889
- lines.slice(1).forEach(line => {
890
- console.info(`${indent} ${" ".repeat(resultType.length)}${color(line)}`)
891
- })
892
- }
893
- }
894
- printResult(indent, 134, resultType, resultValue)
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);
895
1122
  }