@aeternity/aepp-sdk 13.0.0-alpha.0 → 13.0.0-beta.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 (481) hide show
  1. package/bin/aesophia_cli +0 -0
  2. package/dist/aepp-sdk.browser-script.js +1 -1
  3. package/dist/aepp-sdk.browser-script.js.map +1 -1
  4. package/dist/aepp-sdk.browser.js +1 -1
  5. package/dist/aepp-sdk.browser.js.map +1 -1
  6. package/dist/aepp-sdk.js +5595 -2249
  7. package/dist/aepp-sdk.js.map +1 -1
  8. package/es/AeSdk.mjs.map +1 -1
  9. package/es/AeSdkAepp.mjs.map +1 -1
  10. package/es/AeSdkBase.d.ts +3 -3
  11. package/es/AeSdkBase.mjs +4 -0
  12. package/es/AeSdkBase.mjs.map +1 -1
  13. package/es/AeSdkMethods.d.ts +12 -14
  14. package/es/AeSdkMethods.mjs +6 -8
  15. package/es/AeSdkMethods.mjs.map +1 -1
  16. package/es/AeSdkWallet.mjs +1 -1
  17. package/es/AeSdkWallet.mjs.map +1 -1
  18. package/es/Node.d.ts +9 -4
  19. package/es/Node.mjs +12 -6
  20. package/es/Node.mjs.map +1 -1
  21. package/es/account/Base.d.ts +13 -8
  22. package/es/account/Base.mjs +0 -17
  23. package/es/account/Base.mjs.map +1 -1
  24. package/es/account/Generalized.mjs +14 -25
  25. package/es/account/Generalized.mjs.map +1 -1
  26. package/es/account/Ledger.mjs +2 -1
  27. package/es/account/Ledger.mjs.map +1 -1
  28. package/es/account/LedgerFactory.mjs.map +1 -1
  29. package/es/account/Memory.d.ts +2 -1
  30. package/es/account/Memory.mjs +11 -22
  31. package/es/account/Memory.mjs.map +1 -1
  32. package/es/account/Rpc.mjs.map +1 -1
  33. package/es/aens.d.ts +12 -14
  34. package/es/aens.mjs +22 -32
  35. package/es/aens.mjs.map +1 -1
  36. package/es/aepp-wallet-communication/connection/Browser.mjs +0 -16
  37. package/es/aepp-wallet-communication/connection/Browser.mjs.map +1 -1
  38. package/es/aepp-wallet-communication/connection/BrowserRuntime.d.ts +1 -0
  39. package/es/aepp-wallet-communication/connection/BrowserRuntime.mjs +19 -20
  40. package/es/aepp-wallet-communication/connection/BrowserRuntime.mjs.map +1 -1
  41. package/es/aepp-wallet-communication/connection/BrowserWindowMessage.mjs +0 -16
  42. package/es/aepp-wallet-communication/connection/BrowserWindowMessage.mjs.map +1 -1
  43. package/es/aepp-wallet-communication/connection-proxy.mjs +0 -17
  44. package/es/aepp-wallet-communication/connection-proxy.mjs.map +1 -1
  45. package/es/aepp-wallet-communication/rpc/RpcClient.mjs +5 -6
  46. package/es/aepp-wallet-communication/rpc/RpcClient.mjs.map +1 -1
  47. package/es/aepp-wallet-communication/rpc/types.d.ts +6 -2
  48. package/es/aepp-wallet-communication/rpc/types.mjs.map +1 -1
  49. package/es/aepp-wallet-communication/schema.mjs.map +1 -1
  50. package/es/aepp-wallet-communication/wallet-detector.mjs +0 -16
  51. package/es/aepp-wallet-communication/wallet-detector.mjs.map +1 -1
  52. package/es/apis/compiler/compiler.d.ts +1 -1
  53. package/es/apis/compiler/compiler.mjs +4 -20
  54. package/es/apis/compiler/compiler.mjs.map +1 -1
  55. package/es/apis/compiler/models/index.d.ts +3 -2
  56. package/es/apis/compiler/models/index.mjs.map +1 -1
  57. package/es/apis/compiler/models/mappers.d.ts +1 -1
  58. package/es/apis/compiler/models/mappers.mjs +19 -2
  59. package/es/apis/compiler/models/mappers.mjs.map +1 -1
  60. package/es/apis/node/models/index.d.ts +15 -15
  61. package/es/apis/node/models/index.mjs.map +1 -1
  62. package/es/apis/node/models/mappers.d.ts +1 -1
  63. package/es/apis/node/models/mappers.mjs +2 -1
  64. package/es/apis/node/models/mappers.mjs.map +1 -1
  65. package/es/apis/node/models/parameters.d.ts +2 -2
  66. package/es/apis/node/models/parameters.mjs +2 -2
  67. package/es/apis/node/models/parameters.mjs.map +1 -1
  68. package/es/apis/node/node.mjs +3 -19
  69. package/es/apis/node/node.mjs.map +1 -1
  70. package/es/chain.d.ts +17 -9
  71. package/es/chain.mjs +23 -23
  72. package/es/chain.mjs.map +1 -1
  73. package/es/channel/Base.d.ts +27 -9
  74. package/es/channel/Base.mjs +27 -27
  75. package/es/channel/Base.mjs.map +1 -1
  76. package/es/channel/Contract.d.ts +8 -7
  77. package/es/channel/Contract.mjs +8 -21
  78. package/es/channel/Contract.mjs.map +1 -1
  79. package/es/channel/Spend.d.ts +5 -1
  80. package/es/channel/Spend.mjs +4 -18
  81. package/es/channel/Spend.mjs.map +1 -1
  82. package/es/channel/handlers.mjs +16 -26
  83. package/es/channel/handlers.mjs.map +1 -1
  84. package/es/channel/internal.d.ts +19 -2
  85. package/es/channel/internal.mjs +22 -20
  86. package/es/channel/internal.mjs.map +1 -1
  87. package/es/contract/Contract.d.ts +43 -123
  88. package/es/contract/Contract.mjs +230 -250
  89. package/es/contract/Contract.mjs.map +1 -1
  90. package/es/contract/compiler/Base.d.ts +74 -0
  91. package/es/contract/compiler/Base.mjs +5 -0
  92. package/es/contract/compiler/Base.mjs.map +1 -0
  93. package/es/contract/compiler/Cli.d.ts +23 -0
  94. package/es/contract/compiler/Cli.mjs +149 -0
  95. package/es/contract/compiler/Cli.mjs.map +1 -0
  96. package/es/contract/compiler/Http.d.ts +32 -0
  97. package/es/contract/compiler/Http.mjs +94 -0
  98. package/es/contract/compiler/Http.mjs.map +1 -0
  99. package/es/contract/compiler/HttpNode.d.ts +17 -0
  100. package/es/contract/compiler/HttpNode.mjs +26 -0
  101. package/es/contract/compiler/HttpNode.mjs.map +1 -0
  102. package/es/contract/compiler/getFileSystem.d.ts +6 -0
  103. package/es/contract/compiler/getFileSystem.mjs +40 -0
  104. package/es/contract/compiler/getFileSystem.mjs.map +1 -0
  105. package/es/contract/delegation-signature.d.ts +43 -0
  106. package/es/contract/delegation-signature.mjs +45 -0
  107. package/es/contract/delegation-signature.mjs.map +1 -0
  108. package/es/contract/ga.d.ts +27 -10
  109. package/es/contract/ga.mjs +63 -29
  110. package/es/contract/ga.mjs.map +1 -1
  111. package/es/index-browser.d.ts +40 -0
  112. package/es/index-browser.mjs +41 -0
  113. package/es/index-browser.mjs.map +1 -0
  114. package/es/index.d.ts +4 -38
  115. package/es/index.mjs +4 -53
  116. package/es/index.mjs.map +1 -1
  117. package/es/oracle.d.ts +12 -17
  118. package/es/oracle.mjs +29 -49
  119. package/es/oracle.mjs.map +1 -1
  120. package/es/spend.d.ts +19 -27
  121. package/es/spend.mjs +21 -46
  122. package/es/spend.mjs.map +1 -1
  123. package/es/tx/builder/SchemaTypes.d.ts +37 -0
  124. package/es/tx/builder/SchemaTypes.mjs +2 -0
  125. package/es/tx/builder/SchemaTypes.mjs.map +1 -0
  126. package/es/tx/builder/constants.d.ts +31 -2
  127. package/es/tx/builder/constants.mjs +34 -3
  128. package/es/tx/builder/constants.mjs.map +1 -1
  129. package/es/tx/builder/field-types/abi-version.d.ts +19 -0
  130. package/es/tx/builder/field-types/abi-version.mjs +40 -0
  131. package/es/tx/builder/field-types/abi-version.mjs.map +1 -0
  132. package/es/tx/builder/field-types/address.d.ts +5 -6
  133. package/es/tx/builder/field-types/address.mjs +17 -8
  134. package/es/tx/builder/field-types/address.mjs.map +1 -1
  135. package/es/tx/builder/field-types/array.d.ts +7 -0
  136. package/es/tx/builder/field-types/array.mjs +11 -0
  137. package/es/tx/builder/field-types/array.mjs.map +1 -0
  138. package/es/tx/builder/field-types/boolean.d.ts +6 -0
  139. package/es/tx/builder/field-types/boolean.mjs +13 -0
  140. package/es/tx/builder/field-types/boolean.mjs.map +1 -0
  141. package/es/tx/builder/field-types/coin-amount.d.ts +4 -5
  142. package/es/tx/builder/field-types/coin-amount.mjs +4 -5
  143. package/es/tx/builder/field-types/coin-amount.mjs.map +1 -1
  144. package/es/tx/builder/field-types/ct-version.d.ts +49 -0
  145. package/es/tx/builder/field-types/ct-version.mjs +76 -0
  146. package/es/tx/builder/field-types/ct-version.mjs.map +1 -0
  147. package/es/tx/builder/field-types/deposit.d.ts +3 -2
  148. package/es/tx/builder/field-types/deposit.mjs +3 -2
  149. package/es/tx/builder/field-types/deposit.mjs.map +1 -1
  150. package/es/tx/builder/field-types/encoded.d.ts +6 -0
  151. package/es/tx/builder/field-types/encoded.mjs +21 -0
  152. package/es/tx/builder/field-types/encoded.mjs.map +1 -0
  153. package/es/tx/builder/field-types/entry.d.ts +11 -0
  154. package/es/tx/builder/field-types/entry.mjs +34 -0
  155. package/es/tx/builder/field-types/entry.mjs.map +1 -0
  156. package/es/tx/builder/field-types/enumeration.d.ts +5 -3
  157. package/es/tx/builder/field-types/enumeration.mjs +11 -2
  158. package/es/tx/builder/field-types/enumeration.mjs.map +1 -1
  159. package/es/tx/builder/field-types/fee.d.ts +12 -7
  160. package/es/tx/builder/field-types/fee.mjs +28 -20
  161. package/es/tx/builder/field-types/fee.mjs.map +1 -1
  162. package/es/tx/builder/field-types/field.mjs.map +1 -1
  163. package/es/tx/builder/field-types/gas-limit.d.ts +7 -3
  164. package/es/tx/builder/field-types/gas-limit.mjs +13 -8
  165. package/es/tx/builder/field-types/gas-limit.mjs.map +1 -1
  166. package/es/tx/builder/field-types/gas-price.d.ts +3 -1
  167. package/es/tx/builder/field-types/gas-price.mjs.map +1 -1
  168. package/es/tx/builder/field-types/index.d.ts +107 -30
  169. package/es/tx/builder/field-types/index.mjs +38 -12
  170. package/es/tx/builder/field-types/index.mjs.map +1 -1
  171. package/es/tx/builder/field-types/map.d.ts +13 -0
  172. package/es/tx/builder/field-types/map.mjs +49 -0
  173. package/es/tx/builder/field-types/map.mjs.map +1 -0
  174. package/es/tx/builder/field-types/mptree.d.ts +42 -0
  175. package/es/tx/builder/field-types/mptree.mjs +266 -0
  176. package/es/tx/builder/field-types/mptree.mjs.map +1 -0
  177. package/es/tx/builder/field-types/name-fee.d.ts +2 -3
  178. package/es/tx/builder/field-types/name-fee.mjs +2 -2
  179. package/es/tx/builder/field-types/name-fee.mjs.map +1 -1
  180. package/es/tx/builder/field-types/name-id.mjs +2 -1
  181. package/es/tx/builder/field-types/name-id.mjs.map +1 -1
  182. package/es/tx/builder/field-types/name.mjs.map +1 -1
  183. package/es/tx/builder/field-types/nonce.d.ts +14 -0
  184. package/es/tx/builder/field-types/nonce.mjs +29 -0
  185. package/es/tx/builder/field-types/nonce.mjs.map +1 -0
  186. package/es/tx/builder/field-types/pointers.mjs +2 -2
  187. package/es/tx/builder/field-types/pointers.mjs.map +1 -1
  188. package/es/tx/builder/field-types/raw.d.ts +6 -0
  189. package/es/tx/builder/field-types/raw.mjs +13 -0
  190. package/es/tx/builder/field-types/raw.mjs.map +1 -0
  191. package/es/tx/builder/field-types/short-u-int-const.d.ts +7 -0
  192. package/es/tx/builder/field-types/short-u-int-const.mjs +20 -0
  193. package/es/tx/builder/field-types/short-u-int-const.mjs.map +1 -0
  194. package/es/tx/builder/field-types/short-u-int.mjs.map +1 -1
  195. package/es/tx/builder/field-types/string.d.ts +6 -0
  196. package/es/tx/builder/field-types/string.mjs +10 -0
  197. package/es/tx/builder/field-types/string.mjs.map +1 -0
  198. package/es/tx/builder/field-types/ttl.d.ts +11 -0
  199. package/es/tx/builder/field-types/ttl.mjs +21 -0
  200. package/es/tx/builder/field-types/ttl.mjs.map +1 -0
  201. package/es/tx/builder/field-types/u-int.d.ts +1 -2
  202. package/es/tx/builder/field-types/u-int.mjs.map +1 -1
  203. package/es/tx/builder/field-types/wrapped.d.ts +14 -0
  204. package/es/tx/builder/field-types/wrapped.mjs +22 -0
  205. package/es/tx/builder/field-types/wrapped.mjs.map +1 -0
  206. package/es/tx/builder/helpers.mjs.map +1 -1
  207. package/es/tx/builder/index.d.ts +18 -36
  208. package/es/tx/builder/index.mjs +65 -236
  209. package/es/tx/builder/index.mjs.map +1 -1
  210. package/es/tx/builder/schema.d.ts +2734 -1324
  211. package/es/tx/builder/schema.generated.d.ts +2011 -0
  212. package/es/tx/builder/schema.generated.mjs +2 -0
  213. package/es/tx/builder/schema.generated.mjs.map +1 -0
  214. package/es/tx/builder/schema.mjs +459 -223
  215. package/es/tx/builder/schema.mjs.map +1 -1
  216. package/es/tx/execution-cost.d.ts +35 -0
  217. package/es/tx/execution-cost.mjs +123 -0
  218. package/es/tx/execution-cost.mjs.map +1 -0
  219. package/es/tx/transaction-signer.d.ts +6 -0
  220. package/es/tx/transaction-signer.mjs +27 -0
  221. package/es/tx/transaction-signer.mjs.map +1 -0
  222. package/es/tx/validator.d.ts +3 -5
  223. package/es/tx/validator.mjs +91 -153
  224. package/es/tx/validator.mjs.map +1 -1
  225. package/es/utils/amount-formatter.mjs +0 -16
  226. package/es/utils/amount-formatter.mjs.map +1 -1
  227. package/es/utils/autorest.d.ts +3 -2
  228. package/es/utils/autorest.mjs +43 -11
  229. package/es/utils/autorest.mjs.map +1 -1
  230. package/es/utils/bytes.mjs +1 -17
  231. package/es/utils/bytes.mjs.map +1 -1
  232. package/es/utils/crypto.mjs +0 -16
  233. package/es/utils/crypto.mjs.map +1 -1
  234. package/es/utils/encoder.mjs.map +1 -1
  235. package/es/utils/errors.d.ts +16 -38
  236. package/es/utils/errors.mjs +3 -43
  237. package/es/utils/errors.mjs.map +1 -1
  238. package/es/utils/hd-wallet.mjs.map +1 -1
  239. package/es/utils/json-big.mjs.map +1 -1
  240. package/es/utils/keystore.mjs.map +1 -1
  241. package/es/utils/other.mjs.map +1 -1
  242. package/es/utils/semver-satisfies.mjs.map +1 -1
  243. package/es/utils/string.mjs +0 -17
  244. package/es/utils/string.mjs.map +1 -1
  245. package/package.json +52 -40
  246. package/src/AeSdkBase.ts +6 -3
  247. package/src/AeSdkMethods.ts +12 -18
  248. package/src/AeSdkWallet.ts +1 -1
  249. package/src/Node.ts +23 -9
  250. package/src/account/Base.ts +13 -24
  251. package/src/account/Generalized.ts +9 -24
  252. package/src/account/Ledger.ts +1 -1
  253. package/src/account/Memory.ts +15 -22
  254. package/src/aens.ts +34 -49
  255. package/src/aepp-wallet-communication/connection/Browser.ts +0 -17
  256. package/src/aepp-wallet-communication/connection/BrowserRuntime.ts +18 -24
  257. package/src/aepp-wallet-communication/connection/BrowserWindowMessage.ts +0 -17
  258. package/src/aepp-wallet-communication/connection-proxy.ts +0 -17
  259. package/src/aepp-wallet-communication/rpc/RpcClient.ts +2 -2
  260. package/src/aepp-wallet-communication/rpc/types.ts +6 -2
  261. package/src/aepp-wallet-communication/wallet-detector.ts +0 -17
  262. package/src/apis/compiler/compiler.ts +3 -27
  263. package/src/apis/compiler/models/index.ts +3 -2
  264. package/src/apis/compiler/models/mappers.ts +15 -2
  265. package/src/apis/node/models/index.ts +16 -15
  266. package/src/apis/node/models/mappers.ts +2 -1
  267. package/src/apis/node/models/parameters.ts +2 -2
  268. package/src/apis/node/node.ts +3 -27
  269. package/src/chain.ts +33 -30
  270. package/src/channel/Base.ts +39 -31
  271. package/src/channel/Contract.ts +18 -32
  272. package/src/channel/Spend.ts +8 -18
  273. package/src/channel/handlers.ts +14 -26
  274. package/src/channel/internal.ts +41 -23
  275. package/src/contract/Contract.ts +188 -228
  276. package/src/contract/compiler/Base.ts +87 -0
  277. package/src/contract/compiler/Cli.ts +128 -0
  278. package/src/contract/compiler/Http.ts +105 -0
  279. package/src/contract/compiler/HttpNode.ts +26 -0
  280. package/src/contract/compiler/getFileSystem.ts +42 -0
  281. package/src/contract/delegation-signature.ts +56 -0
  282. package/src/contract/ga.ts +61 -37
  283. package/src/index-browser.ts +50 -0
  284. package/src/index.ts +4 -56
  285. package/src/oracle.ts +47 -57
  286. package/src/spend.ts +34 -68
  287. package/src/tx/builder/SchemaTypes.ts +79 -0
  288. package/src/tx/builder/constants.ts +34 -3
  289. package/src/tx/builder/field-types/abi-version.ts +44 -0
  290. package/src/tx/builder/field-types/address.ts +23 -13
  291. package/src/tx/builder/field-types/array.ts +19 -0
  292. package/src/tx/builder/field-types/boolean.ts +9 -0
  293. package/src/tx/builder/field-types/coin-amount.ts +8 -5
  294. package/src/tx/builder/field-types/ct-version.ts +83 -0
  295. package/src/tx/builder/field-types/deposit.ts +4 -2
  296. package/src/tx/builder/field-types/encoded.ts +27 -0
  297. package/src/tx/builder/field-types/entry.ts +36 -0
  298. package/src/tx/builder/field-types/enumeration.ts +15 -4
  299. package/src/tx/builder/field-types/fee.ts +41 -19
  300. package/src/tx/builder/field-types/gas-limit.ts +13 -8
  301. package/src/tx/builder/field-types/index.ts +60 -17
  302. package/src/tx/builder/field-types/map.ts +45 -0
  303. package/src/tx/builder/field-types/mptree.ts +243 -0
  304. package/src/tx/builder/field-types/name-fee.ts +3 -3
  305. package/src/tx/builder/field-types/name-id.ts +1 -1
  306. package/src/tx/builder/field-types/nonce.ts +40 -0
  307. package/src/tx/builder/field-types/pointers.ts +2 -2
  308. package/src/tx/builder/field-types/raw.ts +9 -0
  309. package/src/tx/builder/field-types/short-u-int-const.ts +30 -0
  310. package/src/tx/builder/field-types/string.ts +11 -0
  311. package/src/tx/builder/field-types/ttl.ts +24 -0
  312. package/src/tx/builder/field-types/u-int.ts +1 -3
  313. package/src/tx/builder/field-types/wrapped.ts +32 -0
  314. package/src/tx/builder/index.ts +82 -280
  315. package/src/tx/builder/schema.generated.ts +2013 -0
  316. package/src/tx/builder/schema.ts +536 -666
  317. package/src/tx/execution-cost.ts +146 -0
  318. package/src/tx/transaction-signer.ts +27 -0
  319. package/src/tx/validator.ts +100 -154
  320. package/src/utils/amount-formatter.ts +0 -16
  321. package/src/utils/autorest.ts +52 -11
  322. package/src/utils/bytes.ts +1 -17
  323. package/src/utils/crypto.ts +0 -16
  324. package/src/utils/errors.ts +18 -56
  325. package/src/utils/string.ts +0 -17
  326. package/types-legacy/ts4.2/AeSdkBase.d.ts +3 -3
  327. package/types-legacy/ts4.2/AeSdkMethods.d.ts +12 -14
  328. package/types-legacy/ts4.2/Node.d.ts +8 -4
  329. package/types-legacy/ts4.2/account/Base.d.ts +13 -8
  330. package/types-legacy/ts4.2/account/Memory.d.ts +2 -1
  331. package/types-legacy/ts4.2/aens.d.ts +12 -14
  332. package/types-legacy/ts4.2/aepp-wallet-communication/connection/BrowserRuntime.d.ts +1 -0
  333. package/types-legacy/ts4.2/aepp-wallet-communication/rpc/types.d.ts +6 -2
  334. package/types-legacy/ts4.2/apis/compiler/compiler.d.ts +1 -1
  335. package/types-legacy/ts4.2/apis/compiler/models/index.d.ts +3 -2
  336. package/types-legacy/ts4.2/apis/compiler/models/mappers.d.ts +1 -1
  337. package/types-legacy/ts4.2/apis/node/models/index.d.ts +15 -15
  338. package/types-legacy/ts4.2/apis/node/models/mappers.d.ts +1 -1
  339. package/types-legacy/ts4.2/apis/node/models/parameters.d.ts +2 -2
  340. package/types-legacy/ts4.2/chain.d.ts +17 -9
  341. package/types-legacy/ts4.2/channel/Base.d.ts +27 -9
  342. package/types-legacy/ts4.2/channel/Contract.d.ts +8 -7
  343. package/types-legacy/ts4.2/channel/Spend.d.ts +5 -1
  344. package/types-legacy/ts4.2/channel/internal.d.ts +22 -2
  345. package/types-legacy/ts4.2/contract/Contract.d.ts +42 -122
  346. package/types-legacy/ts4.2/contract/compiler/Base.d.ts +74 -0
  347. package/types-legacy/ts4.2/contract/compiler/Cli.d.ts +23 -0
  348. package/types-legacy/ts4.2/contract/compiler/Http.d.ts +32 -0
  349. package/types-legacy/ts4.2/contract/compiler/HttpNode.d.ts +17 -0
  350. package/types-legacy/ts4.2/contract/compiler/getFileSystem.d.ts +6 -0
  351. package/types-legacy/ts4.2/contract/delegation-signature.d.ts +43 -0
  352. package/types-legacy/ts4.2/contract/ga.d.ts +27 -10
  353. package/types-legacy/ts4.2/index-browser.d.ts +40 -0
  354. package/types-legacy/ts4.2/index.d.ts +4 -38
  355. package/types-legacy/ts4.2/oracle.d.ts +12 -17
  356. package/types-legacy/ts4.2/spend.d.ts +19 -27
  357. package/types-legacy/ts4.2/tx/builder/SchemaTypes.d.ts +37 -0
  358. package/types-legacy/ts4.2/tx/builder/constants.d.ts +31 -2
  359. package/types-legacy/ts4.2/tx/builder/field-types/abi-version.d.ts +19 -0
  360. package/types-legacy/ts4.2/tx/builder/field-types/address.d.ts +11 -12
  361. package/types-legacy/ts4.2/tx/builder/field-types/array.d.ts +7 -0
  362. package/types-legacy/ts4.2/tx/builder/field-types/boolean.d.ts +6 -0
  363. package/types-legacy/ts4.2/tx/builder/field-types/coin-amount.d.ts +4 -5
  364. package/types-legacy/ts4.2/tx/builder/field-types/ct-version.d.ts +72 -0
  365. package/types-legacy/ts4.2/tx/builder/field-types/deposit.d.ts +3 -2
  366. package/types-legacy/ts4.2/tx/builder/field-types/encoded.d.ts +6 -0
  367. package/types-legacy/ts4.2/tx/builder/field-types/entry.d.ts +11 -0
  368. package/types-legacy/ts4.2/tx/builder/field-types/enumeration.d.ts +5 -3
  369. package/types-legacy/ts4.2/tx/builder/field-types/fee.d.ts +12 -7
  370. package/types-legacy/ts4.2/tx/builder/field-types/gas-limit.d.ts +7 -3
  371. package/types-legacy/ts4.2/tx/builder/field-types/gas-price.d.ts +3 -1
  372. package/types-legacy/ts4.2/tx/builder/field-types/index.d.ts +113 -30
  373. package/types-legacy/ts4.2/tx/builder/field-types/map.d.ts +13 -0
  374. package/types-legacy/ts4.2/tx/builder/field-types/mptree.d.ts +48 -0
  375. package/types-legacy/ts4.2/tx/builder/field-types/name-fee.d.ts +2 -3
  376. package/types-legacy/ts4.2/tx/builder/field-types/nonce.d.ts +14 -0
  377. package/types-legacy/ts4.2/tx/builder/field-types/raw.d.ts +6 -0
  378. package/types-legacy/ts4.2/tx/builder/field-types/short-u-int-const.d.ts +7 -0
  379. package/types-legacy/ts4.2/tx/builder/field-types/string.d.ts +6 -0
  380. package/types-legacy/ts4.2/tx/builder/field-types/ttl.d.ts +11 -0
  381. package/types-legacy/ts4.2/tx/builder/field-types/u-int.d.ts +1 -2
  382. package/types-legacy/ts4.2/tx/builder/field-types/wrapped.d.ts +14 -0
  383. package/types-legacy/ts4.2/tx/builder/index.d.ts +21 -36
  384. package/types-legacy/ts4.2/tx/builder/schema.d.ts +2971 -2926
  385. package/types-legacy/ts4.2/tx/builder/schema.generated.d.ts +2011 -0
  386. package/types-legacy/ts4.2/tx/execution-cost.d.ts +35 -0
  387. package/types-legacy/ts4.2/tx/transaction-signer.d.ts +6 -0
  388. package/types-legacy/ts4.2/tx/validator.d.ts +3 -5
  389. package/types-legacy/ts4.2/utils/autorest.d.ts +3 -2
  390. package/types-legacy/ts4.2/utils/errors.d.ts +16 -38
  391. package/types-legacy/ts4.5/AeSdkBase.d.ts +3 -3
  392. package/types-legacy/ts4.5/AeSdkMethods.d.ts +12 -14
  393. package/types-legacy/ts4.5/Node.d.ts +8 -4
  394. package/types-legacy/ts4.5/account/Base.d.ts +13 -8
  395. package/types-legacy/ts4.5/account/Memory.d.ts +2 -1
  396. package/types-legacy/ts4.5/aens.d.ts +12 -14
  397. package/types-legacy/ts4.5/aepp-wallet-communication/connection/BrowserRuntime.d.ts +1 -0
  398. package/types-legacy/ts4.5/aepp-wallet-communication/rpc/types.d.ts +6 -2
  399. package/types-legacy/ts4.5/apis/compiler/compiler.d.ts +1 -1
  400. package/types-legacy/ts4.5/apis/compiler/models/index.d.ts +3 -2
  401. package/types-legacy/ts4.5/apis/compiler/models/mappers.d.ts +1 -1
  402. package/types-legacy/ts4.5/apis/node/models/index.d.ts +15 -15
  403. package/types-legacy/ts4.5/apis/node/models/mappers.d.ts +1 -1
  404. package/types-legacy/ts4.5/apis/node/models/parameters.d.ts +2 -2
  405. package/types-legacy/ts4.5/chain.d.ts +17 -9
  406. package/types-legacy/ts4.5/channel/Base.d.ts +27 -9
  407. package/types-legacy/ts4.5/channel/Contract.d.ts +8 -7
  408. package/types-legacy/ts4.5/channel/Spend.d.ts +5 -1
  409. package/types-legacy/ts4.5/channel/internal.d.ts +22 -2
  410. package/types-legacy/ts4.5/contract/Contract.d.ts +42 -122
  411. package/types-legacy/ts4.5/contract/compiler/Base.d.ts +74 -0
  412. package/types-legacy/ts4.5/contract/compiler/Cli.d.ts +23 -0
  413. package/types-legacy/ts4.5/contract/compiler/Http.d.ts +32 -0
  414. package/types-legacy/ts4.5/contract/compiler/HttpNode.d.ts +17 -0
  415. package/types-legacy/ts4.5/contract/compiler/getFileSystem.d.ts +6 -0
  416. package/types-legacy/ts4.5/contract/delegation-signature.d.ts +43 -0
  417. package/types-legacy/ts4.5/contract/ga.d.ts +27 -10
  418. package/types-legacy/ts4.5/index-browser.d.ts +40 -0
  419. package/types-legacy/ts4.5/index.d.ts +4 -38
  420. package/types-legacy/ts4.5/oracle.d.ts +12 -17
  421. package/types-legacy/ts4.5/spend.d.ts +19 -27
  422. package/types-legacy/ts4.5/tx/builder/SchemaTypes.d.ts +37 -0
  423. package/types-legacy/ts4.5/tx/builder/constants.d.ts +31 -2
  424. package/types-legacy/ts4.5/tx/builder/field-types/abi-version.d.ts +19 -0
  425. package/types-legacy/ts4.5/tx/builder/field-types/address.d.ts +11 -12
  426. package/types-legacy/ts4.5/tx/builder/field-types/array.d.ts +7 -0
  427. package/types-legacy/ts4.5/tx/builder/field-types/boolean.d.ts +6 -0
  428. package/types-legacy/ts4.5/tx/builder/field-types/coin-amount.d.ts +4 -5
  429. package/types-legacy/ts4.5/tx/builder/field-types/ct-version.d.ts +72 -0
  430. package/types-legacy/ts4.5/tx/builder/field-types/deposit.d.ts +3 -2
  431. package/types-legacy/ts4.5/tx/builder/field-types/encoded.d.ts +6 -0
  432. package/types-legacy/ts4.5/tx/builder/field-types/entry.d.ts +11 -0
  433. package/types-legacy/ts4.5/tx/builder/field-types/enumeration.d.ts +5 -3
  434. package/types-legacy/ts4.5/tx/builder/field-types/fee.d.ts +12 -7
  435. package/types-legacy/ts4.5/tx/builder/field-types/gas-limit.d.ts +7 -3
  436. package/types-legacy/ts4.5/tx/builder/field-types/gas-price.d.ts +3 -1
  437. package/types-legacy/ts4.5/tx/builder/field-types/index.d.ts +113 -30
  438. package/types-legacy/ts4.5/tx/builder/field-types/map.d.ts +13 -0
  439. package/types-legacy/ts4.5/tx/builder/field-types/mptree.d.ts +48 -0
  440. package/types-legacy/ts4.5/tx/builder/field-types/name-fee.d.ts +2 -3
  441. package/types-legacy/ts4.5/tx/builder/field-types/nonce.d.ts +14 -0
  442. package/types-legacy/ts4.5/tx/builder/field-types/raw.d.ts +6 -0
  443. package/types-legacy/ts4.5/tx/builder/field-types/short-u-int-const.d.ts +7 -0
  444. package/types-legacy/ts4.5/tx/builder/field-types/string.d.ts +6 -0
  445. package/types-legacy/ts4.5/tx/builder/field-types/ttl.d.ts +11 -0
  446. package/types-legacy/ts4.5/tx/builder/field-types/u-int.d.ts +1 -2
  447. package/types-legacy/ts4.5/tx/builder/field-types/wrapped.d.ts +14 -0
  448. package/types-legacy/ts4.5/tx/builder/index.d.ts +21 -36
  449. package/types-legacy/ts4.5/tx/builder/schema.d.ts +2971 -2926
  450. package/types-legacy/ts4.5/tx/builder/schema.generated.d.ts +2011 -0
  451. package/types-legacy/ts4.5/tx/execution-cost.d.ts +35 -0
  452. package/types-legacy/ts4.5/tx/transaction-signer.d.ts +6 -0
  453. package/types-legacy/ts4.5/tx/validator.d.ts +3 -5
  454. package/types-legacy/ts4.5/utils/autorest.d.ts +3 -2
  455. package/types-legacy/ts4.5/utils/errors.d.ts +16 -38
  456. package/es/contract/CompilerHttp.d.ts +0 -18
  457. package/es/contract/CompilerHttp.mjs +0 -63
  458. package/es/contract/CompilerHttp.mjs.map +0 -1
  459. package/es/tx/builder/field-types/addresses.d.ts +0 -6
  460. package/es/tx/builder/field-types/addresses.mjs +0 -13
  461. package/es/tx/builder/field-types/addresses.mjs.map +0 -1
  462. package/es/tx/index.d.ts +0 -34
  463. package/es/tx/index.mjs +0 -172
  464. package/es/tx/index.mjs.map +0 -1
  465. package/es/utils/mptree.d.ts +0 -26
  466. package/es/utils/mptree.mjs +0 -143
  467. package/es/utils/mptree.mjs.map +0 -1
  468. package/src/apis/compiler/code-model-v4.yaml +0 -2442
  469. package/src/apis/node/code-model-v4.yaml +0 -10080
  470. package/src/contract/CompilerHttp.ts +0 -67
  471. package/src/tx/builder/field-types/addresses.ts +0 -18
  472. package/src/tx/index.ts +0 -196
  473. package/src/utils/mptree.ts +0 -145
  474. package/types-legacy/ts4.2/contract/CompilerHttp.d.ts +0 -18
  475. package/types-legacy/ts4.2/tx/builder/field-types/addresses.d.ts +0 -6
  476. package/types-legacy/ts4.2/tx/index.d.ts +0 -34
  477. package/types-legacy/ts4.2/utils/mptree.d.ts +0 -32
  478. package/types-legacy/ts4.5/contract/CompilerHttp.d.ts +0 -18
  479. package/types-legacy/ts4.5/tx/builder/field-types/addresses.d.ts +0 -6
  480. package/types-legacy/ts4.5/tx/index.d.ts +0 -34
  481. package/types-legacy/ts4.5/utils/mptree.d.ts +0 -32
@@ -2,56 +2,26 @@ import _buffer from "buffer";
2
2
  const {
3
3
  Buffer: _Buffer
4
4
  } = _buffer;
5
- import BigNumber from 'bignumber.js';
6
5
  import { hash, verify } from "../utils/crypto.mjs";
7
- import { PROTOCOL_VM_ABI } from "./builder/schema.mjs";
6
+ import { ProtocolToVmAbi } from "./builder/field-types/ct-version.mjs";
8
7
  import { Tag } from "./builder/constants.mjs";
9
- import { unpackTx } from "./builder/index.mjs";
10
- import { UnsupportedProtocolError } from "../utils/errors.mjs";
11
- import { concatBuffers, isAccountNotFoundError, isKeyOfObject } from "../utils/other.mjs";
12
- import { encode, Encoding } from "../utils/encoder.mjs";
8
+ import { buildTx, unpackTx } from "./builder/index.mjs";
9
+ import { concatBuffers, isAccountNotFoundError } from "../utils/other.mjs";
10
+ import { decode } from "../utils/encoder.mjs";
13
11
  import Node from "../Node.mjs";
14
12
  import { genAggressiveCacheGetResponsesPolicy } from "../utils/autorest.mjs";
13
+ import { UnexpectedTsError } from "../utils/errors.mjs";
14
+ import getTransactionSignerAddress from "./transaction-signer.mjs";
15
+ import { getExecutionCostUsingNode } from "./execution-cost.mjs";
15
16
  const validators = [];
16
- const getSenderAddress = tx => ['senderId', 'accountId', 'ownerId', 'callerId', 'oracleId', 'fromId', 'initiator', 'gaId', 'payerId'].map(key => tx[key]).filter(a => a).map(a => a === null || a === void 0 ? void 0 : a.toString().replace(/^ok_/, 'ak_'))[0];
17
-
18
- /**
19
- * Transaction Validator
20
- * This function validates some of transaction properties,
21
- * to make sure it can be posted it to the chain
22
- * @category transaction builder
23
- * @param transaction - Base64Check-encoded transaction
24
- * @param nodeNotCached - Node to validate transaction against
25
- * @param parentTxTypes - Types of parent transactions
26
- * @returns Array with verification errors
27
- * @example const errors = await verifyTransaction(transaction, node)
28
- */
29
- export default async function verifyTransaction(transaction, nodeNotCached) {
30
- var _getSenderAddress;
31
- let parentTxTypes = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : [];
32
- let node = nodeNotCached;
33
- if (!node.pipeline.getOrderedPolicies().some(_ref => {
34
- let {
35
- name
36
- } = _ref;
37
- return name === 'aggressive-cache-get-responses';
38
- })) {
39
- node = new Node(nodeNotCached.$host, {
40
- ignoreVersion: true
41
- });
42
- node.pipeline.addPolicy(genAggressiveCacheGetResponsesPolicy());
43
- }
44
- const {
45
- tx,
46
- txType
47
- } = unpackTx(transaction);
48
- const address = (_getSenderAddress = getSenderAddress(tx)) !== null && _getSenderAddress !== void 0 ? _getSenderAddress : txType === Tag.SignedTx ? getSenderAddress(tx.encodedTx.tx) : undefined;
17
+ async function verifyTransactionInternal(tx, node, parentTxTypes) {
18
+ const address = getTransactionSignerAddress(buildTx(tx));
49
19
  const [account, {
50
20
  height
51
21
  }, {
52
22
  consensusProtocolVersion,
53
23
  nodeNetworkId
54
- }] = await Promise.all([address == null ? undefined : node.getAccountByPubkey(address).catch(error => {
24
+ }] = await Promise.all([node.getAccountByPubkey(address).catch(error => {
55
25
  if (!isAccountNotFoundError(error)) throw error;
56
26
  return {
57
27
  id: address,
@@ -64,8 +34,7 @@ export default async function verifyTransaction(transaction, nodeNotCached) {
64
34
  ...acc,
65
35
  id: acc.id
66
36
  })), node.getCurrentKeyBlockHeight(), node.getNodeInfo()]);
67
- return (await Promise.all(validators.map(v => v(tx, {
68
- txType,
37
+ return (await Promise.all(validators.map(async v => v(tx, {
69
38
  node,
70
39
  account,
71
40
  height,
@@ -74,92 +43,92 @@ export default async function verifyTransaction(transaction, nodeNotCached) {
74
43
  parentTxTypes
75
44
  })))).flat();
76
45
  }
77
- validators.push((_ref2, _ref3) => {
78
- let {
79
- encodedTx,
80
- signatures
81
- } = _ref2;
46
+
47
+ /**
48
+ * Transaction Validator
49
+ * This function validates some transaction properties,
50
+ * to make sure it can be posted it to the chain
51
+ * @category transaction builder
52
+ * @param transaction - Base64Check-encoded transaction
53
+ * @param nodeNotCached - Node to validate transaction against
54
+ * @returns Array with verification errors
55
+ * @example const errors = await verifyTransaction(transaction, node)
56
+ */
57
+ export default async function verifyTransaction(transaction, nodeNotCached) {
58
+ const node = new Node(nodeNotCached.$host, {
59
+ ignoreVersion: true,
60
+ pipeline: nodeNotCached.pipeline.clone(),
61
+ additionalPolicies: [genAggressiveCacheGetResponsesPolicy()]
62
+ });
63
+ return verifyTransactionInternal(unpackTx(transaction), node, []);
64
+ }
65
+ validators.push((tx, _ref) => {
82
66
  let {
83
67
  account,
84
68
  nodeNetworkId,
85
69
  parentTxTypes
86
- } = _ref3;
87
- if ((encodedTx !== null && encodedTx !== void 0 ? encodedTx : signatures) === undefined) return [];
88
- if (account == null) return [];
89
- if (signatures.length !== 1) return []; // TODO: Support multisignature?
70
+ } = _ref;
71
+ if (tx.tag !== Tag.SignedTx) return [];
72
+ const {
73
+ encodedTx,
74
+ signatures
75
+ } = tx;
76
+ if ((encodedTx !== null && encodedTx !== void 0 ? encodedTx : signatures) == null) return [];
77
+ if (signatures.length !== 1) return []; // TODO: Support multisignature like in state channels
90
78
  const prefix = _Buffer.from([nodeNetworkId, ...(parentTxTypes.includes(Tag.PayingForTx) ? ['inner_tx'] : [])].join('-'));
91
- const txWithNetworkId = concatBuffers([prefix, encodedTx.rlpEncoded]);
92
- const txHashWithNetworkId = concatBuffers([prefix, hash(encodedTx.rlpEncoded)]);
79
+ const txBinary = decode(buildTx(encodedTx));
80
+ const txWithNetworkId = concatBuffers([prefix, txBinary]);
81
+ const txHashWithNetworkId = concatBuffers([prefix, hash(txBinary)]);
93
82
  if (verify(txWithNetworkId, signatures[0], account.id) || verify(txHashWithNetworkId, signatures[0], account.id)) return [];
94
83
  return [{
95
84
  message: 'Signature cannot be verified, please ensure that you transaction have' + ' the correct prefix and the correct private key for the sender address',
96
85
  key: 'InvalidSignature',
97
86
  checkedKeys: ['encodedTx', 'signatures']
98
87
  }];
99
- }, async (_ref4, _ref5) => {
100
- let {
101
- encodedTx,
102
- tx
103
- } = _ref4;
88
+ }, async (tx, _ref2) => {
104
89
  let {
105
90
  node,
106
- parentTxTypes,
107
- txType
108
- } = _ref5;
109
- if ((encodedTx !== null && encodedTx !== void 0 ? encodedTx : tx) === undefined) return [];
110
- return verifyTransaction(encode((encodedTx !== null && encodedTx !== void 0 ? encodedTx : tx).rlpEncoded, Encoding.Transaction), node, [...parentTxTypes, txType]);
111
- }, (_ref6, _ref7) => {
112
- let {
113
- ttl
114
- } = _ref6;
91
+ parentTxTypes
92
+ } = _ref2;
93
+ let nestedTx;
94
+ if ('encodedTx' in tx) nestedTx = tx.encodedTx;
95
+ if ('tx' in tx) nestedTx = tx.tx;
96
+ if (nestedTx == null) return [];
97
+ return verifyTransactionInternal(nestedTx, node, [...parentTxTypes, tx.tag]);
98
+ }, (tx, _ref3) => {
115
99
  let {
116
100
  height
117
- } = _ref7;
118
- if (ttl === undefined) return [];
119
- ttl = +ttl;
120
- if (ttl === 0 || ttl >= height) return [];
101
+ } = _ref3;
102
+ if (!('ttl' in tx)) return [];
103
+ if (tx.ttl === 0 || tx.ttl >= height) return [];
121
104
  return [{
122
- message: `TTL ${ttl} is already expired, current height is ${height}`,
105
+ message: `TTL ${tx.ttl} is already expired, current height is ${height}`,
123
106
  key: 'ExpiredTTL',
124
107
  checkedKeys: ['ttl']
125
108
  }];
126
- }, (_ref8, _ref9) => {
127
- var _ref10, _fee;
128
- let {
129
- amount,
130
- fee,
131
- nameFee,
132
- tx
133
- } = _ref8;
109
+ }, async (tx, _ref4) => {
134
110
  let {
135
111
  account,
136
112
  parentTxTypes,
137
- txType
138
- } = _ref9;
139
- if (account == null) return [];
140
- if (((_ref10 = amount !== null && amount !== void 0 ? amount : fee) !== null && _ref10 !== void 0 ? _ref10 : nameFee) === undefined) return [];
141
- (_fee = fee) !== null && _fee !== void 0 ? _fee : fee = 0;
142
- const cost = new BigNumber(fee).plus(nameFee !== null && nameFee !== void 0 ? nameFee : 0).plus(amount !== null && amount !== void 0 ? amount : 0).plus(txType === Tag.PayingForTx ? tx.tx.encodedTx.tx.fee : 0).minus(parentTxTypes.includes(Tag.PayingForTx) ? fee : 0);
143
- if (cost.lte(account.balance.toString())) return [];
113
+ node
114
+ } = _ref4;
115
+ if (parentTxTypes.length !== 0) return [];
116
+ const cost = await getExecutionCostUsingNode(buildTx(tx), node).catch(() => 0n);
117
+ if (cost <= account.balance) return [];
144
118
  return [{
145
- message: `Account balance ${account.balance.toString()} is not enough to execute the transaction that costs ${cost.toFixed()}`,
119
+ message: `Account balance ${account.balance} is not enough to execute the transaction that costs ${cost}`,
146
120
  key: 'InsufficientBalance',
147
- checkedKeys: ['amount', 'fee', 'nameFee']
121
+ checkedKeys: ['amount', 'fee', 'nameFee', 'gasLimit', 'gasPrice']
148
122
  }];
149
- }, (_ref11, _ref12) => {
123
+ }, (tx, _ref5) => {
150
124
  let {
151
- signatures
152
- } = _ref11;
153
- let {
154
- account,
155
- txType
156
- } = _ref12;
157
- if (account == null) return [];
125
+ account
126
+ } = _ref5;
158
127
  let message;
159
- if (txType === Tag.SignedTx && account.kind === 'generalized' && signatures.length !== 0) {
128
+ if (tx.tag === Tag.SignedTx && account.kind === 'generalized' && tx.signatures.length !== 0) {
160
129
  message = 'Generalized account can\'t be used to generate SignedTx with signatures';
161
130
  }
162
- if (txType === Tag.GaMetaTx && account.kind === 'basic') {
131
+ if (tx.tag === Tag.GaMetaTx && account.kind === 'basic') {
163
132
  message = 'Basic account can\'t be used to generate GaMetaTx';
164
133
  }
165
134
  if (message == null) return [];
@@ -168,76 +137,45 @@ validators.push((_ref2, _ref3) => {
168
137
  key: 'InvalidAccountType',
169
138
  checkedKeys: ['tag']
170
139
  }];
171
- }, (_ref13, _ref14) => {
172
- let {
173
- nonce
174
- } = _ref13;
140
+ },
141
+ // TODO: revert nonce check
142
+ (tx, _ref6) => {
143
+ var _ref7, _ref8;
175
144
  let {
176
- account,
177
- parentTxTypes
178
- } = _ref14;
179
- if (nonce == null || account == null || parentTxTypes.includes(Tag.GaMetaTx)) return [];
180
- nonce = +nonce;
181
- const validNonce = account.nonce + 1;
182
- if (nonce === validNonce) return [];
183
- return [{
184
- ...(nonce < validNonce ? {
185
- message: `Nonce ${nonce} is already used, valid nonce is ${validNonce}`,
186
- key: 'NonceAlreadyUsed'
187
- } : {
188
- message: `Nonce ${nonce} is too high, valid nonce is ${validNonce}`,
189
- key: 'NonceHigh'
190
- }),
191
- checkedKeys: ['nonce']
192
- }];
193
- }, (_ref15, _ref16) => {
194
- let {
195
- ctVersion,
196
- abiVersion
197
- } = _ref15;
198
- let {
199
- txType,
200
145
  consensusProtocolVersion
201
- } = _ref16;
202
- if (!isKeyOfObject(consensusProtocolVersion, PROTOCOL_VM_ABI)) {
203
- throw new UnsupportedProtocolError(`Unsupported protocol: ${consensusProtocolVersion}`);
204
- }
205
- const protocol = PROTOCOL_VM_ABI[consensusProtocolVersion];
206
-
207
- // If not contract create tx
208
- if (ctVersion == null) ctVersion = {
209
- abiVersion
146
+ } = _ref6;
147
+ const oracleCall = Tag.Oracle === tx.tag || Tag.OracleRegisterTx === tx.tag;
148
+ const contractCreate = Tag.ContractCreateTx === tx.tag || Tag.GaAttachTx === tx.tag;
149
+ const contractCall = Tag.ContractCallTx === tx.tag || Tag.GaMetaTx === tx.tag;
150
+ const type = (_ref7 = (_ref8 = oracleCall ? 'oracle-call' : null) !== null && _ref8 !== void 0 ? _ref8 : contractCreate ? 'contract-create' : null) !== null && _ref7 !== void 0 ? _ref7 : contractCall ? 'contract-call' : null;
151
+ if (type == null) return [];
152
+ const protocol = ProtocolToVmAbi[consensusProtocolVersion][type];
153
+ let ctVersion;
154
+ if ('abiVersion' in tx) ctVersion = {
155
+ abiVersion: tx.abiVersion
210
156
  };
211
- const txProtocol = protocol[txType];
212
- if (txProtocol == null) return [];
213
- if (Object.entries(ctVersion).some(_ref17 => {
214
- let [key, value] = _ref17;
215
- return !txProtocol[key].includes(+value);
216
- })) {
157
+ if ('ctVersion' in tx) ctVersion = tx.ctVersion;
158
+ if (ctVersion == null) throw new UnexpectedTsError();
159
+ if (!protocol.abiVersion.includes(ctVersion.abiVersion) || contractCreate && !protocol.vmVersion.includes(ctVersion.vmVersion)) {
217
160
  return [{
218
- message: `ABI/VM version ${JSON.stringify(ctVersion)} is wrong, supported is: ${JSON.stringify(txProtocol)}`,
161
+ message: `ABI/VM version ${JSON.stringify(ctVersion)} is wrong, supported is: ${JSON.stringify(protocol)}`,
219
162
  key: 'VmAndAbiVersionMismatch',
220
163
  checkedKeys: ['ctVersion', 'abiVersion']
221
164
  }];
222
165
  }
223
166
  return [];
224
- }, async (_ref18, _ref19) => {
225
- let {
226
- contractId
227
- } = _ref18;
167
+ }, async (tx, _ref9) => {
228
168
  let {
229
- txType,
230
169
  node
231
- } = _ref19;
232
- if (Tag.ContractCallTx !== txType) return [];
233
- contractId = contractId;
170
+ } = _ref9;
171
+ if (Tag.ContractCallTx !== tx.tag) return [];
234
172
  try {
235
173
  const {
236
174
  active
237
- } = await node.getContract(contractId);
175
+ } = await node.getContract(tx.contractId);
238
176
  if (active) return [];
239
177
  return [{
240
- message: `Contract ${contractId} is not active`,
178
+ message: `Contract ${tx.contractId} is not active`,
241
179
  key: 'ContractNotActive',
242
180
  checkedKeys: ['contractId']
243
181
  }];
@@ -1 +1 @@
1
- {"version":3,"file":"validator.mjs","names":["BigNumber","hash","verify","PROTOCOL_VM_ABI","Tag","unpackTx","UnsupportedProtocolError","concatBuffers","isAccountNotFoundError","isKeyOfObject","encode","Encoding","Node","genAggressiveCacheGetResponsesPolicy","validators","getSenderAddress","tx","map","key","filter","a","toString","replace","verifyTransaction","transaction","nodeNotCached","parentTxTypes","node","pipeline","getOrderedPolicies","some","name","$host","ignoreVersion","addPolicy","txType","address","SignedTx","encodedTx","undefined","account","height","consensusProtocolVersion","nodeNetworkId","Promise","all","getAccountByPubkey","catch","error","id","balance","nonce","then","acc","getCurrentKeyBlockHeight","getNodeInfo","v","flat","push","signatures","length","prefix","from","includes","PayingForTx","join","txWithNetworkId","rlpEncoded","txHashWithNetworkId","message","checkedKeys","Transaction","ttl","amount","fee","nameFee","cost","plus","minus","lte","toFixed","kind","GaMetaTx","validNonce","ctVersion","abiVersion","protocol","txProtocol","Object","entries","value","JSON","stringify","contractId","ContractCallTx","active","getContract","response","parsedBody","reason"],"sources":["../../src/tx/validator.ts"],"sourcesContent":["import BigNumber from 'bignumber.js';\nimport { hash, verify } from '../utils/crypto';\nimport {\n CtVersion,\n PROTOCOL_VM_ABI,\n RawTxObject,\n TxParamsCommon,\n TxSchema,\n TxTypeSchemas,\n} from './builder/schema';\nimport { Tag } from './builder/constants';\nimport { TxUnpacked, unpackTx } from './builder';\nimport { UnsupportedProtocolError } from '../utils/errors';\nimport { concatBuffers, isAccountNotFoundError, isKeyOfObject } from '../utils/other';\nimport { encode, Encoded, Encoding } from '../utils/encoder';\nimport Node, { TransformNodeType } from '../Node';\nimport { Account } from '../apis/node';\nimport { genAggressiveCacheGetResponsesPolicy } from '../utils/autorest';\n\nexport interface ValidatorResult {\n message: string;\n key: string;\n checkedKeys: string[];\n}\n\ntype Validator = (\n tx: {\n encodedTx: TxUnpacked<TxSchema>;\n signatures: Buffer[];\n tx: TxUnpacked<TxSchema> & {\n tx: TxTypeSchemas[Tag.SignedTx];\n };\n nonce?: number;\n ttl?: number;\n amount?: number;\n fee?: number;\n nameFee?: number;\n ctVersion?: Partial<CtVersion>;\n abiVersion?: number;\n contractId?: Encoded.ContractAddress;\n },\n options: {\n // TODO: remove after fixing node types\n account?: TransformNodeType<Account> & { id: Encoded.AccountAddress };\n nodeNetworkId: string;\n parentTxTypes: Tag[];\n node: Node;\n txType: Tag;\n height: number;\n consensusProtocolVersion: number;\n }\n) => ValidatorResult[] | Promise<ValidatorResult[]>;\n\nconst validators: Validator[] = [];\n\nconst getSenderAddress = (\n tx: TxParamsCommon | RawTxObject<TxSchema>,\n): Encoded.AccountAddress | undefined => [\n 'senderId', 'accountId', 'ownerId', 'callerId',\n 'oracleId', 'fromId', 'initiator', 'gaId', 'payerId',\n]\n .map((key: keyof TxSchema) => tx[key])\n .filter((a) => a)\n .map((a) => a?.toString().replace(/^ok_/, 'ak_'))[0] as Encoded.AccountAddress | undefined;\n\n/**\n * Transaction Validator\n * This function validates some of transaction properties,\n * to make sure it can be posted it to the chain\n * @category transaction builder\n * @param transaction - Base64Check-encoded transaction\n * @param nodeNotCached - Node to validate transaction against\n * @param parentTxTypes - Types of parent transactions\n * @returns Array with verification errors\n * @example const errors = await verifyTransaction(transaction, node)\n */\nexport default async function verifyTransaction(\n transaction: Encoded.Transaction | Encoded.Poi,\n nodeNotCached: Node,\n parentTxTypes: Tag[] = [],\n): Promise<ValidatorResult[]> {\n let node = nodeNotCached;\n if (\n !node.pipeline.getOrderedPolicies()\n .some(({ name }) => name === 'aggressive-cache-get-responses')\n ) {\n node = new Node(nodeNotCached.$host, { ignoreVersion: true });\n node.pipeline.addPolicy(genAggressiveCacheGetResponsesPolicy());\n }\n\n const { tx, txType } = unpackTx<Tag.SignedTx>(transaction);\n const address = getSenderAddress(tx)\n ?? (txType === Tag.SignedTx ? getSenderAddress(tx.encodedTx.tx) : undefined);\n const [account, { height }, { consensusProtocolVersion, nodeNetworkId }] = await Promise.all([\n address == null\n ? undefined\n : node.getAccountByPubkey(address)\n .catch((error) => {\n if (!isAccountNotFoundError(error)) throw error;\n return { id: address, balance: 0n, nonce: 0 };\n })\n // TODO: remove after fixing https://github.com/aeternity/aepp-sdk-js/issues/1537\n .then((acc) => ({ ...acc, id: acc.id as Encoded.AccountAddress })),\n node.getCurrentKeyBlockHeight(),\n node.getNodeInfo(),\n ]);\n\n return (await Promise.all(\n validators.map((v) => v(\n tx as any,\n {\n txType, node, account, height, consensusProtocolVersion, nodeNetworkId, parentTxTypes,\n },\n )),\n )).flat();\n}\n\nvalidators.push(\n ({ encodedTx, signatures }, { account, nodeNetworkId, parentTxTypes }) => {\n if ((encodedTx ?? signatures) === undefined) return [];\n if (account == null) return [];\n if (signatures.length !== 1) return []; // TODO: Support multisignature?\n const prefix = Buffer.from([\n nodeNetworkId,\n ...parentTxTypes.includes(Tag.PayingForTx) ? ['inner_tx'] : [],\n ].join('-'));\n const txWithNetworkId = concatBuffers([prefix, encodedTx.rlpEncoded]);\n const txHashWithNetworkId = concatBuffers([prefix, hash(encodedTx.rlpEncoded)]);\n if (verify(txWithNetworkId, signatures[0], account.id)\n || verify(txHashWithNetworkId, signatures[0], account.id)) return [];\n return [{\n message: 'Signature cannot be verified, please ensure that you transaction have'\n + ' the correct prefix and the correct private key for the sender address',\n key: 'InvalidSignature',\n checkedKeys: ['encodedTx', 'signatures'],\n }];\n },\n async ({ encodedTx, tx }, { node, parentTxTypes, txType }) => {\n if ((encodedTx ?? tx) === undefined) return [];\n return verifyTransaction(\n encode((encodedTx ?? tx).rlpEncoded, Encoding.Transaction),\n node,\n [...parentTxTypes, txType],\n );\n },\n ({ ttl }, { height }) => {\n if (ttl === undefined) return [];\n ttl = +ttl;\n if (ttl === 0 || ttl >= height) return [];\n return [{\n message: `TTL ${ttl} is already expired, current height is ${height}`,\n key: 'ExpiredTTL',\n checkedKeys: ['ttl'],\n }];\n },\n ({\n amount, fee, nameFee, tx,\n }, { account, parentTxTypes, txType }) => {\n if (account == null) return [];\n if ((amount ?? fee ?? nameFee) === undefined) return [];\n fee ??= 0;\n const cost = new BigNumber(fee).plus(nameFee ?? 0).plus(amount ?? 0)\n .plus(txType === Tag.PayingForTx ? (tx.tx.encodedTx.tx).fee : 0)\n .minus(parentTxTypes.includes(Tag.PayingForTx) ? fee : 0);\n if (cost.lte(account.balance.toString())) return [];\n return [{\n message: `Account balance ${account.balance.toString()} is not enough to execute the transaction that costs ${cost.toFixed()}`,\n key: 'InsufficientBalance',\n checkedKeys: ['amount', 'fee', 'nameFee'],\n }];\n },\n ({ signatures }, { account, txType }) => {\n if (account == null) return [];\n let message;\n if (txType === Tag.SignedTx && account.kind === 'generalized' && signatures.length !== 0) {\n message = 'Generalized account can\\'t be used to generate SignedTx with signatures';\n }\n if (txType === Tag.GaMetaTx && account.kind === 'basic') {\n message = 'Basic account can\\'t be used to generate GaMetaTx';\n }\n if (message == null) return [];\n return [{ message, key: 'InvalidAccountType', checkedKeys: ['tag'] }];\n },\n ({ nonce }, { account, parentTxTypes }) => {\n if (nonce == null || account == null || parentTxTypes.includes(Tag.GaMetaTx)) return [];\n nonce = +nonce;\n const validNonce = account.nonce + 1;\n if (nonce === validNonce) return [];\n return [{\n ...nonce < validNonce\n ? {\n message: `Nonce ${nonce} is already used, valid nonce is ${validNonce}`,\n key: 'NonceAlreadyUsed',\n }\n : {\n message: `Nonce ${nonce} is too high, valid nonce is ${validNonce}`,\n key: 'NonceHigh',\n },\n checkedKeys: ['nonce'],\n }];\n },\n ({ ctVersion, abiVersion }, { txType, consensusProtocolVersion }) => {\n if (!isKeyOfObject(consensusProtocolVersion, PROTOCOL_VM_ABI)) {\n throw new UnsupportedProtocolError(`Unsupported protocol: ${consensusProtocolVersion}`);\n }\n const protocol = PROTOCOL_VM_ABI[consensusProtocolVersion];\n\n // If not contract create tx\n if (ctVersion == null) ctVersion = { abiVersion };\n const txProtocol = protocol[txType as keyof typeof protocol];\n if (txProtocol == null) return [];\n if (Object.entries(ctVersion).some(\n ([\n key,\n value,\n ]: [\n key:keyof typeof txProtocol,\n value:any]) => !(txProtocol[key].includes(+value as never)),\n )) {\n return [{\n message: `ABI/VM version ${JSON.stringify(ctVersion)} is wrong, supported is: ${JSON.stringify(txProtocol)}`,\n key: 'VmAndAbiVersionMismatch',\n checkedKeys: ['ctVersion', 'abiVersion'],\n }];\n }\n return [];\n },\n async ({ contractId }, { txType, node }) => {\n if (Tag.ContractCallTx !== txType) return [];\n contractId = contractId as Encoded.ContractAddress;\n try {\n const { active } = await node.getContract(contractId);\n if (active) return [];\n return [{\n message: `Contract ${contractId} is not active`,\n key: 'ContractNotActive',\n checkedKeys: ['contractId'],\n }];\n } catch (error) {\n if (error.response?.parsedBody?.reason == null) throw error;\n return [{\n message: error.response.parsedBody.reason,\n key: 'ContractNotFound',\n checkedKeys: ['contractId'],\n }];\n }\n },\n);\n"],"mappings":";;;;AAAA,OAAOA,SAAS,MAAM,cAAc;AAAC,SAC5BC,IAAI,EAAEC,MAAM;AAAA,SAGnBC,eAAe;AAAA,SAMRC,GAAG;AAAA,SACSC,QAAQ;AAAA,SACpBC,wBAAwB;AAAA,SACxBC,aAAa,EAAEC,sBAAsB,EAAEC,aAAa;AAAA,SACpDC,MAAM,EAAWC,QAAQ;AAAA,OAC3BC,IAAI;AAAA,SAEFC,oCAAoC;AAoC7C,MAAMC,UAAuB,GAAG,EAAE;AAElC,MAAMC,gBAAgB,GACpBC,EAA0C,IACH,CACvC,UAAU,EAAE,WAAW,EAAE,SAAS,EAAE,UAAU,EAC9C,UAAU,EAAE,QAAQ,EAAE,WAAW,EAAE,MAAM,EAAE,SAAS,CACrD,CACEC,GAAG,CAAEC,GAAmB,IAAKF,EAAE,CAACE,GAAG,CAAC,CAAC,CACrCC,MAAM,CAAEC,CAAC,IAAKA,CAAC,CAAC,CAChBH,GAAG,CAAEG,CAAC,IAAKA,CAAC,aAADA,CAAC,uBAADA,CAAC,CAAEC,QAAQ,EAAE,CAACC,OAAO,CAAC,MAAM,EAAE,KAAK,CAAC,CAAC,CAAC,CAAC,CAAuC;;AAE5F;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,eAAe,eAAeC,iBAAiB,CAC7CC,WAA8C,EAC9CC,aAAmB,EAES;EAAA;EAAA,IAD5BC,aAAoB,uEAAG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C,CAAC;EACJ,CAAC,CAAC,OAAOtB,KAAK,EAAE;IAAA;IACd,IAAI,oBAAAA,KAAK,CAACiD,QAAQ,6EAAd,gBAAgBC,UAAU,0DAA1B,sBAA4BC,MAAM,KAAI,IAAI,EAAE,MAAMnD,KAAK;IAC3D,OAAO,CAAC;MACNqB,OAAO,EAAErB,KAAK,CAACiD,QAAQ,CAACC,UAAU,CAACC,MAAM;MACzCjF,GAAG,EAAE,kBAAkB;MACvBoD,WAAW,EAAE,CAAC,YAAY;IAC5B,CAAC,CAAC;EACJ;AACF,CAAC,CACF"}
1
+ {"version":3,"file":"validator.mjs","names":["hash","verify","ProtocolToVmAbi","Tag","buildTx","unpackTx","concatBuffers","isAccountNotFoundError","decode","Node","genAggressiveCacheGetResponsesPolicy","UnexpectedTsError","getTransactionSignerAddress","getExecutionCostUsingNode","validators","verifyTransactionInternal","tx","node","parentTxTypes","address","account","height","consensusProtocolVersion","nodeNetworkId","Promise","all","getAccountByPubkey","catch","error","id","balance","nonce","then","acc","getCurrentKeyBlockHeight","getNodeInfo","map","v","flat","verifyTransaction","transaction","nodeNotCached","$host","ignoreVersion","pipeline","clone","additionalPolicies","push","_ref","tag","SignedTx","encodedTx","signatures","length","prefix","_Buffer","from","includes","PayingForTx","join","txBinary","txWithNetworkId","txHashWithNetworkId","message","key","checkedKeys","_ref2","nestedTx","_ref3","ttl","_ref4","cost","_ref5","kind","GaMetaTx","_ref6","_ref7","_ref8","oracleCall","Oracle","OracleRegisterTx","contractCreate","ContractCreateTx","GaAttachTx","contractCall","ContractCallTx","type","protocol","ctVersion","abiVersion","vmVersion","JSON","stringify","_ref9","active","getContract","contractId","_error$response","_error$response$parse","response","parsedBody","reason"],"sources":["../../src/tx/validator.ts"],"sourcesContent":["import { hash, verify } from '../utils/crypto';\nimport { TxUnpacked } from './builder/schema.generated';\nimport { CtVersion, ProtocolToVmAbi } from './builder/field-types/ct-version';\nimport { Tag, ConsensusProtocolVersion } from './builder/constants';\nimport { buildTx, unpackTx } from './builder';\nimport { concatBuffers, isAccountNotFoundError } from '../utils/other';\nimport { Encoded, decode } from '../utils/encoder';\nimport Node, { TransformNodeType } from '../Node';\nimport { Account } from '../apis/node';\nimport { genAggressiveCacheGetResponsesPolicy } from '../utils/autorest';\nimport { UnexpectedTsError } from '../utils/errors';\nimport getTransactionSignerAddress from './transaction-signer';\nimport { getExecutionCostUsingNode } from './execution-cost';\n\nexport interface ValidatorResult {\n message: string;\n key: string;\n checkedKeys: string[];\n}\n\ntype Validator = (\n tx: TxUnpacked,\n options: {\n // TODO: remove after fixing node types\n account: TransformNodeType<Account> & { id: Encoded.AccountAddress };\n nodeNetworkId: string;\n parentTxTypes: Tag[];\n node: Node;\n height: number;\n consensusProtocolVersion: ConsensusProtocolVersion;\n }\n) => ValidatorResult[] | Promise<ValidatorResult[]>;\n\nconst validators: Validator[] = [];\n\nasync function verifyTransactionInternal(\n tx: TxUnpacked,\n node: Node,\n parentTxTypes: Tag[],\n): Promise<ValidatorResult[]> {\n const address = getTransactionSignerAddress(buildTx(tx));\n const [account, { height }, { consensusProtocolVersion, nodeNetworkId }] = await Promise.all([\n node.getAccountByPubkey(address)\n .catch((error) => {\n if (!isAccountNotFoundError(error)) throw error;\n return { id: address, balance: 0n, nonce: 0 };\n })\n // TODO: remove after fixing https://github.com/aeternity/aepp-sdk-js/issues/1537\n .then((acc) => ({ ...acc, id: acc.id as Encoded.AccountAddress })),\n node.getCurrentKeyBlockHeight(),\n node.getNodeInfo(),\n ]);\n\n return (await Promise.all(\n validators.map(async (v) => v(\n tx,\n {\n node, account, height, consensusProtocolVersion, nodeNetworkId, parentTxTypes,\n },\n )),\n )).flat();\n}\n\n/**\n * Transaction Validator\n * This function validates some transaction properties,\n * to make sure it can be posted it to the chain\n * @category transaction builder\n * @param transaction - Base64Check-encoded transaction\n * @param nodeNotCached - Node to validate transaction against\n * @returns Array with verification errors\n * @example const errors = await verifyTransaction(transaction, node)\n */\nexport default async function verifyTransaction(\n transaction: Parameters<typeof unpackTx>[0],\n nodeNotCached: Node,\n): Promise<ValidatorResult[]> {\n const node = new Node(nodeNotCached.$host, {\n ignoreVersion: true,\n pipeline: nodeNotCached.pipeline.clone(),\n additionalPolicies: [genAggressiveCacheGetResponsesPolicy()],\n });\n return verifyTransactionInternal(unpackTx(transaction), node, []);\n}\n\nvalidators.push(\n (tx, { account, nodeNetworkId, parentTxTypes }) => {\n if (tx.tag !== Tag.SignedTx) return [];\n const { encodedTx, signatures } = tx;\n if ((encodedTx ?? signatures) == null) return [];\n if (signatures.length !== 1) return []; // TODO: Support multisignature like in state channels\n const prefix = Buffer.from([\n nodeNetworkId,\n ...parentTxTypes.includes(Tag.PayingForTx) ? ['inner_tx'] : [],\n ].join('-'));\n const txBinary = decode(buildTx(encodedTx));\n const txWithNetworkId = concatBuffers([prefix, txBinary]);\n const txHashWithNetworkId = concatBuffers([prefix, hash(txBinary)]);\n if (verify(txWithNetworkId, signatures[0], account.id)\n || verify(txHashWithNetworkId, signatures[0], account.id)) return [];\n return [{\n message: 'Signature cannot be verified, please ensure that you transaction have'\n + ' the correct prefix and the correct private key for the sender address',\n key: 'InvalidSignature',\n checkedKeys: ['encodedTx', 'signatures'],\n }];\n },\n async (tx, { node, parentTxTypes }) => {\n let nestedTx;\n if ('encodedTx' in tx) nestedTx = tx.encodedTx;\n if ('tx' in tx) nestedTx = tx.tx;\n if (nestedTx == null) return [];\n return verifyTransactionInternal(nestedTx, node, [...parentTxTypes, tx.tag]);\n },\n (tx, { height }) => {\n if (!('ttl' in tx)) return [];\n if (tx.ttl === 0 || tx.ttl >= height) return [];\n return [{\n message: `TTL ${tx.ttl} is already expired, current height is ${height}`,\n key: 'ExpiredTTL',\n checkedKeys: ['ttl'],\n }];\n },\n async (tx, { account, parentTxTypes, node }) => {\n if (parentTxTypes.length !== 0) return [];\n const cost = await getExecutionCostUsingNode(buildTx(tx), node).catch(() => 0n);\n if (cost <= account.balance) return [];\n return [{\n message: `Account balance ${account.balance} is not enough to execute the transaction that costs ${cost}`,\n key: 'InsufficientBalance',\n checkedKeys: ['amount', 'fee', 'nameFee', 'gasLimit', 'gasPrice'],\n }];\n },\n (tx, { account }) => {\n let message;\n if (tx.tag === Tag.SignedTx && account.kind === 'generalized' && tx.signatures.length !== 0) {\n message = 'Generalized account can\\'t be used to generate SignedTx with signatures';\n }\n if (tx.tag === Tag.GaMetaTx && account.kind === 'basic') {\n message = 'Basic account can\\'t be used to generate GaMetaTx';\n }\n if (message == null) return [];\n return [{ message, key: 'InvalidAccountType', checkedKeys: ['tag'] }];\n },\n // TODO: revert nonce check\n (tx, { consensusProtocolVersion }) => {\n const oracleCall = Tag.Oracle === tx.tag || Tag.OracleRegisterTx === tx.tag;\n const contractCreate = Tag.ContractCreateTx === tx.tag || Tag.GaAttachTx === tx.tag;\n const contractCall = Tag.ContractCallTx === tx.tag || Tag.GaMetaTx === tx.tag;\n const type = (oracleCall ? 'oracle-call' : null)\n ?? (contractCreate ? 'contract-create' : null)\n ?? (contractCall ? 'contract-call' : null);\n if (type == null) return [];\n const protocol = ProtocolToVmAbi[consensusProtocolVersion][type] as {\n abiVersion: readonly any[];\n vmVersion: readonly any[];\n };\n\n let ctVersion: Partial<CtVersion> | undefined;\n if ('abiVersion' in tx) ctVersion = { abiVersion: tx.abiVersion };\n if ('ctVersion' in tx) ctVersion = tx.ctVersion;\n if (ctVersion == null) throw new UnexpectedTsError();\n if (\n !protocol.abiVersion.includes(ctVersion.abiVersion)\n || (contractCreate && !protocol.vmVersion.includes(ctVersion.vmVersion))\n ) {\n return [{\n message: `ABI/VM version ${JSON.stringify(ctVersion)} is wrong, supported is: ${JSON.stringify(protocol)}`,\n key: 'VmAndAbiVersionMismatch',\n checkedKeys: ['ctVersion', 'abiVersion'],\n }];\n }\n return [];\n },\n async (tx, { node }) => {\n if (Tag.ContractCallTx !== tx.tag) return [];\n try {\n const { active } = await node.getContract(tx.contractId);\n if (active) return [];\n return [{\n message: `Contract ${tx.contractId} is not active`,\n key: 'ContractNotActive',\n checkedKeys: ['contractId'],\n }];\n } catch (error) {\n if (error.response?.parsedBody?.reason == null) throw error;\n return [{\n message: error.response.parsedBody.reason,\n key: 'ContractNotFound',\n checkedKeys: ['contractId'],\n }];\n }\n },\n);\n"],"mappings":";;;;SAASA,IAAI,EAAEC,MAAM;AAAA,SAEDC,eAAe;AAAA,SAC1BC,GAAG;AAAA,SACHC,OAAO,EAAEC,QAAQ;AAAA,SACjBC,aAAa,EAAEC,sBAAsB;AAAA,SAC5BC,MAAM;AAAA,OACjBC,IAAI;AAAA,SAEFC,oCAAoC;AAAA,SACpCC,iBAAiB;AAAA,OACnBC,2BAA2B;AAAA,SACzBC,yBAAyB;AAqBlC,MAAMC,UAAuB,GAAG,EAAE;AAElC,eAAeC,yBAAyBA,CACtCC,EAAc,EACdC,IAAU,EACVC,aAAoB,EACQ;EAC5B,MAAMC,OAAO,GAAGP,2BAA2B,CAACR,OAAO,CAACY,EAAE,CAAC,CAAC;EACxD,MAAM,CAACI,OAAO,EAAE;IAAEC;EAAO,CAAC,EAAE;IAAEC,wBAAwB;IAAEC;EAAc,CAAC,CAAC,GAAG,MAAMC,OAAO,CAACC,GAAG,CAAC,CAC3FR,IAAI,CAACS,kBAAkB,CAACP,OAAO,CAAC,CAC7BQ,KAAK,CAAEC,KAAK,IAAK;IAChB,IAAI,CAACrB,sBAAsB,CAACqB,KAAK,CAAC,EAAE,MAAMA,KAAK;IAC/C,OAAO;MAAEC,EAAE,EAAEV,OAAO;MAAEW,OAAO,EAAE,EAAE;MAAEC,KAAK,EAAE;IAAE,CAAC;EAC/C,CAAC;EACD;EAAA,CACCC,IAAI,CAAEC,GAAG,KAAM;IAAE,GAAGA,GAAG;IAAEJ,EAAE,EAAEI,GAAG,CAACJ;EAA6B,CAAC,CAAC,CAAC,EACpEZ,IAAI,CAACiB,wBAAwB,EAAE,EAC/BjB,IAAI,CAACkB,WAAW,EAAE,CACnB,CAAC;EAEF,OAAO,CAAC,MAAMX,OAAO,CAACC,GAA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AD,eAAA,GAAArE,KAAK,CAACuE,QAAQ,cAAAF,eAAA,wBAAAC,qBAAA,GAAdD,eAAA,CAAgBG,UAAU,cAAAF,qBAAA,uBAA1BA,qBAAA,CAA4BG,MAAM,KAAI,IAAI,EAAE,MAAMzE,KAAK;IAC3D,OAAO,CAAC;MACNmC,OAAO,EAAEnC,KAAK,CAACuE,QAAQ,CAACC,UAAU,CAACC,MAAM;MACzCrC,GAAG,EAAE,kBAAkB;MACvBC,WAAW,EAAE,CAAC,YAAY;IAC5B,CAAC,CAAC;EACJ;AACF,CAAC,CACF"}
@@ -1,19 +1,3 @@
1
- /*
2
- * ISC License (ISC)
3
- * Copyright (c) 2018 aeternity developers
4
- *
5
- * Permission to use, copy, modify, and/or distribute this software for any
6
- * purpose with or without fee is hereby granted, provided that the above
7
- * copyright notice and this permission notice appear in all copies.
8
- *
9
- * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
10
- * REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
11
- * AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
12
- * INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
13
- * LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
14
- * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
15
- * PERFORMANCE OF THIS SOFTWARE.
16
- */
17
1
  import BigNumber from 'bignumber.js';
18
2
  import { isBigNumber } from "./bignumber.mjs";
19
3
  import { ArgumentError } from "./errors.mjs";
@@ -1 +1 @@
1
- {"version":3,"file":"amount-formatter.mjs","names":["BigNumber","isBigNumber","ArgumentError","AE_AMOUNT_FORMATS","DENOMINATION_MAGNITUDE","AE","MILI_AE","MICRO_AE","NANO_AE","PICO_AE","FEMTO_AE","AETTOS","formatAmount","value","denomination","targetDenomination","toString","shiftedBy","toFixed","toAe","toAettos","prefixes","name","magnitude","getNearestPrefix","exponent","reduce","p","n","Math","abs","getLowerBoundPrefix","find","length","rawValue","exp","e","v","precision","min"],"sources":["../../src/utils/amount-formatter.ts"],"sourcesContent":["/*\n * ISC License (ISC)\n * Copyright (c) 2018 aeternity developers\n *\n * Permission to use, copy, modify, and/or distribute this software for any\n * purpose with or without fee is hereby granted, provided that the above\n * copyright notice and this permission notice appear in all copies.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\n * REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\n * AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\n * INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\n * LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\n * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\n * PERFORMANCE OF THIS SOFTWARE.\n */\nimport BigNumber from 'bignumber.js';\nimport { isBigNumber } from './bignumber';\nimport { ArgumentError } from './errors';\n\nexport enum AE_AMOUNT_FORMATS {\n AE = 'ae',\n MILI_AE = 'miliAE',\n MICRO_AE = 'microAE',\n NANO_AE = 'nanoAE',\n PICO_AE = 'picoAE',\n FEMTO_AE = 'femtoAE',\n AETTOS = 'aettos',\n}\n\n/**\n * DENOMINATION_MAGNITUDE\n */\nconst DENOMINATION_MAGNITUDE = {\n [AE_AMOUNT_FORMATS.AE]: 0,\n [AE_AMOUNT_FORMATS.MILI_AE]: -3,\n [AE_AMOUNT_FORMATS.MICRO_AE]: -6,\n [AE_AMOUNT_FORMATS.NANO_AE]: -9,\n [AE_AMOUNT_FORMATS.PICO_AE]: -12,\n [AE_AMOUNT_FORMATS.FEMTO_AE]: -15,\n [AE_AMOUNT_FORMATS.AETTOS]: -18,\n} as const;\n\n/**\n * Convert amount from one to other denomination\n * @param value - amount to convert\n * @param options - options\n * @param options.denomination - denomination of amount, can be ['ae', 'aettos']\n * @param options.targetDenomination - target denomination,\n * can be ['ae', 'aettos']\n */\nexport const formatAmount = (\n value: string | number | bigint | BigNumber,\n { denomination = AE_AMOUNT_FORMATS.AETTOS, targetDenomination = AE_AMOUNT_FORMATS.AETTOS }:\n { denomination?: AE_AMOUNT_FORMATS; targetDenomination?: AE_AMOUNT_FORMATS },\n): string => {\n if (!isBigNumber(value)) throw new ArgumentError('value', 'a number', value);\n\n return new BigNumber(typeof value === 'bigint' ? value.toString() : value)\n .shiftedBy(DENOMINATION_MAGNITUDE[denomination] - DENOMINATION_MAGNITUDE[targetDenomination])\n .toFixed();\n};\n\n/**\n * Convert amount to AE\n * @param value - amount to convert\n * @param options - options\n * @param options.denomination - denomination of amount, can be ['ae', 'aettos']\n */\nexport const toAe = (\n value: string | number | BigNumber,\n { denomination = AE_AMOUNT_FORMATS.AETTOS }: { denomination?: AE_AMOUNT_FORMATS } = {},\n): string => formatAmount(value, { denomination, targetDenomination: AE_AMOUNT_FORMATS.AE });\n\n/**\n * Convert amount to aettos\n * @param value - amount to convert\n * @param options - options\n * @param options.denomination - denomination of amount, can be ['ae', 'aettos']\n */\nexport const toAettos = (\n value: string | number | BigNumber,\n { denomination = AE_AMOUNT_FORMATS.AE }: { denomination?: AE_AMOUNT_FORMATS } = {},\n): string => formatAmount(value, { denomination });\n\ninterface Prefix {\n name: string;\n magnitude: number;\n}\n\nconst prefixes: Prefix[] = [\n { name: 'exa', magnitude: 18 },\n { name: 'giga', magnitude: 9 },\n { name: '', magnitude: 0 },\n { name: 'pico', magnitude: -12 },\n];\n\nconst getNearestPrefix = (exponent: number): Prefix => prefixes.reduce((p, n) => (\n Math.abs(n.magnitude - exponent) < Math.abs(p.magnitude - exponent) ? n : p));\n\nconst getLowerBoundPrefix = (exponent: number): Prefix => prefixes\n .find((p) => p.magnitude <= exponent) ?? prefixes[prefixes.length - 1];\n\nexport default (rawValue: string | number | BigNumber): string => {\n const value: BigNumber = new BigNumber(rawValue);\n\n const exp = value.e ?? 0;\n const { name, magnitude } = (exp < 0 ? getNearestPrefix : getLowerBoundPrefix)(exp);\n const v = value\n .shiftedBy(-magnitude)\n .precision(9 + Math.min(exp - magnitude, 0))\n .toFixed();\n return `${v}${name !== '' ? ' ' : ''}${name}`;\n};\n"],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAOA,SAAS,MAAM,cAAc;AAAC,SAC5BC,WAAW;AAAA,SACXC,aAAa;AAEtB,WAAYC,iBAAiB;;AAU7B;AACA;AACA;AAFA,WAVYA,iBAAiB;EAAjBA,iBAAiB;EAAjBA,iBAAiB;EAAjBA,iBAAiB;EAAjBA,iBAAiB;EAAjBA,iBAAiB;EAAjBA,iBAAiB;EAAjBA,iBAAiB;AAAA,GAAjBA,iBAAiB,KAAjBA,iBAAiB;AAa7B,MAAMC,sBAAsB,GAAG;EAC7B,CAACD,iBAAiB,CAACE,EAAE,GAAG,CAAC;EACzB,CAACF,iBAAiB,CAACG,OAAO,GAAG,CAAC,CAAC;EAC/B,CAACH,iBAAiB,CAACI,QAAQ,GAAG,CAAC,CAAC;EAChC,CAACJ,iBAAiB,CAACK,OAAO,GAAG,CAAC,CAAC;EAC/B,CAACL,iBAAiB,CAACM,OAAO,GAAG,CAAC,EAAE;EAChC,CAACN,iBAAiB,CAACO,QAAQ,GAAG,CAAC,EAAE;EACjC,CAACP,iBAAiB,CAACQ,MAAM,GAAG,CAAC;AAC/B,CAAU;;AAEV;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,MAAMC,YAAY,GAAG,CAC1BC,KAA2C,WAGhC;EAAA,IAFX;IAAEC,YAAY,GAAGX,iBAAiB,CAACQ,MAAM;IAAEI,kBAAkB,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AACC,CAAC,EAAEC,CAAC,KAC1EC,IAAI,CAACC,GAAG,CAACF,CAAC,CAACL,SAAS,GAAGE,QAAQ,CAAC,GAAGI,IAAI,CAACC,GAAG,CAACH,CAAC,CAACJ,SAAS,GAAGE,QAAQ,CAAC,GAAGG,CAAC,GAAGD,CAAE,CAAC;AAE/E,MAAMI,mBAAmB,GAAIN,QAAgB;EAAA;EAAA,yBAAaJ,QAAQ,CAC/DW,IAAI,CAAEL,CAAC,IAAKA,CAAC,CAACJ,SAAS,IAAIE,QAAQ,CAAC,2DAAIJ,QAAQ,CAACA,QAAQ,CAACY,MAAM,GAAG,CAAC,CAAC;AAAA;AAExE,gBAAgBC,QAAqC,IAAa;EAAA;EAChE,MAAMrB,KAAgB,GAAG,IAAIb,SAAS,CAACkC,QAAQ,CAAC;EAEhD,MAAMC,GAAG,eAAGtB,KAAK,CAACuB,CAAC,+CAAI,CAAC;EACxB,MAAM;IAAEd,IAAI;IAAEC;EAAU,CAAC,GAAG,CAACY,GAAG,GAAG,CAAC,GAAGX,gBAAgB,GAAGO,mBAAmB,EAAEI,GAAG,CAAC;EACnF,MAAME,CAAC,GAAGxB,KAAK,CACZI,SAAS,CAAC,CAACM,SAAS,CAAC,CACrBe,SAAS,CAAC,CAAC,GAAGT,IAAI,CAACU,GAAG,CAACJ,GAAG,GAAGZ,SAAS,EAAE,CAAC,CAAC,CAAC,CAC3CL,OAAO,EAAE;EACZ,OAAQ,GAAEmB,CAAE,GAAEf,IAAI,KAAK,EAAE,GAAG,GAAG,GAAG,EAAG,GAAEA,IAAK,EAAC;AAC/C,CAAC"}
1
+ {"version":3,"file":"amount-formatter.mjs","names":["BigNumber","isBigNumber","ArgumentError","AE_AMOUNT_FORMATS","DENOMINATION_MAGNITUDE","AE","MILI_AE","MICRO_AE","NANO_AE","PICO_AE","FEMTO_AE","AETTOS","formatAmount","value","_ref","denomination","targetDenomination","toString","shiftedBy","toFixed","toAe","arguments","length","undefined","toAettos","prefixes","name","magnitude","getNearestPrefix","exponent","reduce","p","n","Math","abs","getLowerBoundPrefix","_prefixes$find","find","rawValue","_value$e","exp","e","v","precision","min"],"sources":["../../src/utils/amount-formatter.ts"],"sourcesContent":["import BigNumber from 'bignumber.js';\nimport { isBigNumber } from './bignumber';\nimport { ArgumentError } from './errors';\n\nexport enum AE_AMOUNT_FORMATS {\n AE = 'ae',\n MILI_AE = 'miliAE',\n MICRO_AE = 'microAE',\n NANO_AE = 'nanoAE',\n PICO_AE = 'picoAE',\n FEMTO_AE = 'femtoAE',\n AETTOS = 'aettos',\n}\n\n/**\n * DENOMINATION_MAGNITUDE\n */\nconst DENOMINATION_MAGNITUDE = {\n [AE_AMOUNT_FORMATS.AE]: 0,\n [AE_AMOUNT_FORMATS.MILI_AE]: -3,\n [AE_AMOUNT_FORMATS.MICRO_AE]: -6,\n [AE_AMOUNT_FORMATS.NANO_AE]: -9,\n [AE_AMOUNT_FORMATS.PICO_AE]: -12,\n [AE_AMOUNT_FORMATS.FEMTO_AE]: -15,\n [AE_AMOUNT_FORMATS.AETTOS]: -18,\n} as const;\n\n/**\n * Convert amount from one to other denomination\n * @param value - amount to convert\n * @param options - options\n * @param options.denomination - denomination of amount, can be ['ae', 'aettos']\n * @param options.targetDenomination - target denomination,\n * can be ['ae', 'aettos']\n */\nexport const formatAmount = (\n value: string | number | bigint | BigNumber,\n { denomination = AE_AMOUNT_FORMATS.AETTOS, targetDenomination = AE_AMOUNT_FORMATS.AETTOS }:\n { denomination?: AE_AMOUNT_FORMATS; targetDenomination?: AE_AMOUNT_FORMATS },\n): string => {\n if (!isBigNumber(value)) throw new ArgumentError('value', 'a number', value);\n\n return new BigNumber(typeof value === 'bigint' ? value.toString() : value)\n .shiftedBy(DENOMINATION_MAGNITUDE[denomination] - DENOMINATION_MAGNITUDE[targetDenomination])\n .toFixed();\n};\n\n/**\n * Convert amount to AE\n * @param value - amount to convert\n * @param options - options\n * @param options.denomination - denomination of amount, can be ['ae', 'aettos']\n */\nexport const toAe = (\n value: string | number | BigNumber,\n { denomination = AE_AMOUNT_FORMATS.AETTOS }: { denomination?: AE_AMOUNT_FORMATS } = {},\n): string => formatAmount(value, { denomination, targetDenomination: AE_AMOUNT_FORMATS.AE });\n\n/**\n * Convert amount to aettos\n * @param value - amount to convert\n * @param options - options\n * @param options.denomination - denomination of amount, can be ['ae', 'aettos']\n */\nexport const toAettos = (\n value: string | number | BigNumber,\n { denomination = AE_AMOUNT_FORMATS.AE }: { denomination?: AE_AMOUNT_FORMATS } = {},\n): string => formatAmount(value, { denomination });\n\ninterface Prefix {\n name: string;\n magnitude: number;\n}\n\nconst prefixes: Prefix[] = [\n { name: 'exa', magnitude: 18 },\n { name: 'giga', magnitude: 9 },\n { name: '', magnitude: 0 },\n { name: 'pico', magnitude: -12 },\n];\n\nconst getNearestPrefix = (exponent: number): Prefix => prefixes.reduce((p, n) => (\n Math.abs(n.magnitude - exponent) < Math.abs(p.magnitude - exponent) ? n : p));\n\nconst getLowerBoundPrefix = (exponent: number): Prefix => prefixes\n .find((p) => p.magnitude <= exponent) ?? prefixes[prefixes.length - 1];\n\nexport default (rawValue: string | number | BigNumber): string => {\n const value: BigNumber = new BigNumber(rawValue);\n\n const exp = value.e ?? 0;\n const { name, magnitude } = (exp < 0 ? getNearestPrefix : getLowerBoundPrefix)(exp);\n const v = value\n .shiftedBy(-magnitude)\n .precision(9 + Math.min(exp - magnitude, 0))\n .toFixed();\n return `${v}${name !== '' ? ' ' : ''}${name}`;\n};\n"],"mappings":"AAAA,OAAOA,SAAS,MAAM,cAAc;AAAC,SAC5BC,WAAW;AAAA,SACXC,aAAa;AAEtB,WAAYC,iBAAiB;;AAU7B;AACA;AACA;AAFA,WAVYA,iBAAiB;EAAjBA,iBAAiB;EAAjBA,iBAAiB;EAAjBA,iBAAiB;EAAjBA,iBAAiB;EAAjBA,iBAAiB;EAAjBA,iBAAiB;EAAjBA,iBAAiB;AAAA,GAAjBA,iBAAiB,KAAjBA,iBAAiB;AAa7B,MAAMC,sBAAs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gB,GAAG,IAAIb,SAAS,CAACsC,QAAQ,CAAC;EAEhD,MAAME,GAAG,IAAAD,QAAA,GAAG1B,KAAK,CAAC4B,CAAC,cAAAF,QAAA,cAAAA,QAAA,GAAI,CAAC;EACxB,MAAM;IAAEb,IAAI;IAAEC;EAAU,CAAC,GAAG,CAACa,GAAG,GAAG,CAAC,GAAGZ,gBAAgB,GAAGO,mBAAmB,EAAEK,GAAG,CAAC;EACnF,MAAME,CAAC,GAAG7B,KAAK,CACZK,SAAS,CAAC,CAACS,SAAS,CAAC,CACrBgB,SAAS,CAAC,CAAC,GAAGV,IAAI,CAACW,GAAG,CAACJ,GAAG,GAAGb,SAAS,EAAE,CAAC,CAAC,CAAC,CAC3CR,OAAO,EAAE;EACZ,OAAQ,GAAEuB,CAAE,GAAEhB,IAAI,KAAK,EAAE,GAAG,GAAG,GAAG,EAAG,GAAEA,IAAK,EAAC;AAC/C,CAAC"}
@@ -2,6 +2,7 @@ import { PipelinePolicy } from '@azure/core-rest-pipeline';
2
2
  import { AdditionalPolicyConfig } from '@azure/core-client';
3
3
  export declare const genRequestQueuesPolicy: () => AdditionalPolicyConfig;
4
4
  export declare const genCombineGetRequestsPolicy: () => AdditionalPolicyConfig;
5
- export declare const genAggressiveCacheGetResponsesPolicy: () => PipelinePolicy;
5
+ export declare const genAggressiveCacheGetResponsesPolicy: () => AdditionalPolicyConfig;
6
6
  export declare const genErrorFormatterPolicy: (getMessage: (b: any) => string) => AdditionalPolicyConfig;
7
- export declare const genVersionCheckPolicy: (name: string, ignorePath: string, versionPromise: Promise<string>, geVersion: string, ltVersion: string) => PipelinePolicy;
7
+ export declare const genVersionCheckPolicy: (name: string, ignorePath: string, versionPromise: Promise<string | Error>, geVersion: string, ltVersion: string) => PipelinePolicy;
8
+ export declare const genRetryOnFailurePolicy: (retryCount: number, retryOverallDelay: number) => AdditionalPolicyConfig;
@@ -1,7 +1,7 @@
1
1
  import { RestError } from '@azure/core-rest-pipeline';
2
2
  import { pause } from "./other.mjs";
3
3
  import semverSatisfies from "./semver-satisfies.mjs";
4
- import { UnsupportedVersionError } from "./errors.mjs";
4
+ import { UnexpectedTsError, UnsupportedVersionError } from "./errors.mjs";
5
5
  export const genRequestQueuesPolicy = () => {
6
6
  const requestQueues = new Map();
7
7
  return {
@@ -47,15 +47,18 @@ export const genCombineGetRequestsPolicy = () => {
47
47
  export const genAggressiveCacheGetResponsesPolicy = () => {
48
48
  const getRequests = new Map();
49
49
  return {
50
- name: 'aggressive-cache-get-responses',
51
- async sendRequest(request, next) {
52
- var _getRequests$get;
53
- if (request.method !== 'GET') return next(request);
54
- const key = JSON.stringify([request.url, request.body]);
55
- const response = (_getRequests$get = getRequests.get(key)) !== null && _getRequests$get !== void 0 ? _getRequests$get : next(request);
56
- getRequests.set(key, response);
57
- return response;
58
- }
50
+ policy: {
51
+ name: 'aggressive-cache-get-responses',
52
+ async sendRequest(request, next) {
53
+ var _getRequests$get;
54
+ if (request.method !== 'GET') return next(request);
55
+ const key = JSON.stringify([request.url, request.body]);
56
+ const response = (_getRequests$get = getRequests.get(key)) !== null && _getRequests$get !== void 0 ? _getRequests$get : next(request);
57
+ getRequests.set(key, response);
58
+ return response;
59
+ }
60
+ },
61
+ position: 'perCall'
59
62
  };
60
63
  };
61
64
  export const genErrorFormatterPolicy = getMessage => ({
@@ -87,9 +90,38 @@ export const genVersionCheckPolicy = (name, ignorePath, versionPromise, geVersio
87
90
  name: 'version-check',
88
91
  async sendRequest(request, next) {
89
92
  if (new URL(request.url).pathname === ignorePath) return next(request);
90
- const args = [await versionPromise, geVersion, ltVersion];
93
+ const version = await versionPromise;
94
+ if (version instanceof Error) throw version;
95
+ const args = [version, geVersion, ltVersion];
91
96
  if (!semverSatisfies(...args)) throw new UnsupportedVersionError(name, ...args);
92
97
  return next(request);
93
98
  }
94
99
  });
100
+ export const genRetryOnFailurePolicy = (retryCount, retryOverallDelay) => ({
101
+ policy: {
102
+ name: 'retry-on-failure',
103
+ async sendRequest(request, next) {
104
+ const statusesToNotRetry = [200, 400, 403];
105
+ const intervals = new Array(retryCount).fill(0).map((_, idx) => ((idx + 1) / retryCount) ** 2);
106
+ const intervalSum = intervals.reduce((a, b) => a + b);
107
+ const intervalsInMs = intervals.map(el => el / intervalSum * retryOverallDelay);
108
+ let error;
109
+ for (let attempt = 0; attempt <= retryCount; attempt += 1) {
110
+ if (error != null) {
111
+ var _error$response$statu, _error$response2;
112
+ if (!(error instanceof RestError) || statusesToNotRetry.includes((_error$response$statu = (_error$response2 = error.response) === null || _error$response2 === void 0 ? void 0 : _error$response2.status) !== null && _error$response$statu !== void 0 ? _error$response$statu : 0)) throw error;
113
+ await pause(intervalsInMs[attempt - 1]);
114
+ }
115
+ try {
116
+ return await next(request);
117
+ } catch (e) {
118
+ error = e;
119
+ }
120
+ }
121
+ if (error == null) throw new UnexpectedTsError();
122
+ throw error;
123
+ }
124
+ },
125
+ position: 'perCall'
126
+ });
95
127
  //# sourceMappingURL=autorest.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"autorest.mjs","names":["RestError","pause","semverSatisfies","UnsupportedVersionError","genRequestQueuesPolicy","requestQueues","Map","policy","name","sendRequest","request","next","key","headers","get","delete","getResponse","req","Promise","resolve","then","set","position","genCombineGetRequestsPolicy","pendingGetRequests","method","JSON","stringify","url","body","response","genAggressiveCacheGetResponsesPolicy","getRequests","genErrorFormatterPolicy","getMessage","error","bodyAsText","parse","e","message","URL","pathname","slice","genVersionCheckPolicy","ignorePath","versionPromise","geVersion","ltVersion","args"],"sources":["../../src/utils/autorest.ts"],"sourcesContent":["import { RestError, PipelineResponse, PipelinePolicy } from '@azure/core-rest-pipeline';\nimport { AdditionalPolicyConfig } from '@azure/core-client';\nimport { pause } from './other';\nimport semverSatisfies from './semver-satisfies';\nimport { UnsupportedVersionError } from './errors';\n\nexport const genRequestQueuesPolicy = (): AdditionalPolicyConfig => {\n const requestQueues = new Map<string, Promise<unknown>>();\n\n return {\n policy: {\n name: 'request-queues',\n async sendRequest(request, next) {\n const key = request.headers.get('__queue');\n request.headers.delete('__queue');\n const getResponse = async (): Promise<PipelineResponse> => next(request);\n if (key == null) return getResponse();\n const req = (requestQueues.get(key) ?? Promise.resolve()).then(getResponse, getResponse);\n // TODO: remove after fixing https://github.com/aeternity/aeternity/issues/3803\n // gap to ensure that node won't reject the nonce\n requestQueues.set(key, req.then(async () => pause(750)));\n return req;\n },\n },\n position: 'perCall',\n };\n};\n\nexport const genCombineGetRequestsPolicy = (): AdditionalPolicyConfig => {\n const pendingGetRequests = new Map<string, Promise<PipelineResponse>>();\n\n return {\n policy: {\n name: 'combine-get-requests',\n async sendRequest(request, next) {\n if (request.method !== 'GET') return next(request);\n const key = JSON.stringify([request.url, request.body]);\n const response = pendingGetRequests.get(key) ?? next(request);\n pendingGetRequests.set(key, response);\n try {\n return await response;\n } finally {\n pendingGetRequests.delete(key);\n }\n },\n },\n position: 'perCall',\n };\n};\n\nexport const genAggressiveCacheGetResponsesPolicy = (): PipelinePolicy => {\n const getRequests = new Map<string, Promise<PipelineResponse>>();\n\n return {\n name: 'aggressive-cache-get-responses',\n async sendRequest(request, next) {\n if (request.method !== 'GET') return next(request);\n const key = JSON.stringify([request.url, request.body]);\n const response = getRequests.get(key) ?? next(request);\n getRequests.set(key, response);\n return response;\n },\n };\n};\n\nexport const genErrorFormatterPolicy = (\n getMessage: (b: any) => string,\n): AdditionalPolicyConfig => ({\n policy: {\n name: 'error-formatter',\n async sendRequest(request, next) {\n try {\n return await next(request);\n } catch (error) {\n if (!(error instanceof RestError) || error.request == null) throw error;\n if (error.response?.bodyAsText == null) throw error;\n\n let body;\n try {\n body = JSON.parse(error.response.bodyAsText);\n } catch (e) {\n throw error;\n }\n error.message = `${new URL(error.request.url).pathname.slice(1)} error`;\n const message = getMessage(body);\n if (message !== '') error.message += `:${message}`;\n throw error;\n }\n },\n },\n position: 'perCall',\n});\n\nexport const genVersionCheckPolicy = (\n name: string,\n ignorePath: string,\n versionPromise: Promise<string>,\n geVersion: string,\n ltVersion: string,\n): PipelinePolicy => ({\n name: 'version-check',\n async sendRequest(request, next) {\n if (new URL(request.url).pathname === ignorePath) return next(request);\n const args = [await versionPromise, geVersion, ltVersion] as const;\n if (!semverSatisfies(...args)) throw new UnsupportedVersionError(name, ...args);\n return next(request);\n },\n});\n"],"mappings":"AAAA,SAASA,SAAS,QAA0C,2BAA2B;AAAC,SAE/EC,KAAK;AAAA,OACPC,eAAe;AAAA,SACbC,uBAAuB;AAEhC,OAAO,MAAMC,sBAAsB,GAAG,MAA8B;EAClE,MAAMC,aAAa,GAAG,IAAIC,GAAG,EAA4B;EAEzD,OAAO;IACLC,MAAM,EAAE;MACNC,IAAI,EAAE,gBAAgB;MACtB,MAAMC,WAAW,CAACC,OAAO,EAAEC,IAAI,EAAE;QAAA;QAC/B,MAAMC,GAAG,GAAGF,OAAO,CAACG,OAAO,CAACC,GAAG,CAAC,SAAS,CAAC;QAC1CJ,OAAO,CAACG,OAAO,CAACE,MAAM,CAAC,SAAS,CAAC;QACjC,MAAMC,WAAW,GAAG,YAAuCL,IAAI,CAACD,OAAO,CAAC;QACxE,IAAIE,GAAG,IAAI,IAAI,EAAE,OAAOI,WAAW,EAAE;QACrC,MAAMC,GAAG,GAAG,uBAACZ,aAAa,CAACS,GAAG,CAACF,GAAG,CAAC,mEAAIM,OAAO,CAACC,OAAO,EAAE,EAAEC,IAAI,CAACJ,WAAW,EAAEA,WAAW,CAAC;QACxF;QACA;QACAX,aAAa,CAACgB,GAAG,CAACT,GAAG,EAAEK,GAAG,CAACG,IAAI,CAAC,YAAYnB,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC;QACxD,OAAOgB,GAAG;MACZ;IACF,CAAC;IACDK,QAAQ,EAAE;EACZ,CAAC;AACH,CAAC;AAED,OAAO,MAAMC,2BAA2B,GAAG,MAA8B;EACvE,MAAMC,kBAAkB,GAAG,IAAIlB,GAAG,EAAqC;EAEvE,OAAO;IACLC,MAAM,EAAE;MACNC,IAAI,EAAE,sBAAsB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sC,IAAI,GAAG,CAAC,MAAMH,cAAc,EAAEC,SAAS,EAAEC,SAAS,CAAU;IAClE,IAAI,CAAC7C,eAAe,CAAC,GAAG8C,IAAI,CAAC,EAAE,MAAM,IAAI7C,uBAAuB,CAACK,IAAI,EAAE,GAAGwC,IAAI,CAAC;IAC/E,OAAOrC,IAAI,CAACD,OAAO,CAAC;EACtB;AACF,CAAC,CAAC"}
1
+ {"version":3,"file":"autorest.mjs","names":["RestError","pause","semverSatisfies","UnexpectedTsError","UnsupportedVersionError","genRequestQueuesPolicy","requestQueues","Map","policy","name","sendRequest","request","next","_requestQueues$get","key","headers","get","delete","getResponse","req","Promise","resolve","then","set","position","genCombineGetRequestsPolicy","pendingGetRequests","_pendingGetRequests$g","method","JSON","stringify","url","body","response","genAggressiveCacheGetResponsesPolicy","getRequests","_getRequests$get","genErrorFormatterPolicy","getMessage","error","_error$response","bodyAsText","parse","e","message","URL","pathname","slice","genVersionCheckPolicy","ignorePath","versionPromise","geVersion","ltVersion","version","Error","args","genRetryOnFailurePolicy","retryCount","retryOverallDelay","statusesToNotRetry","intervals","Array","fill","map","_","idx","intervalSum","reduce","a","b","intervalsInMs","el","attempt","_error$response$statu","_error$response2","includes","status"],"sources":["../../src/utils/autorest.ts"],"sourcesContent":["import { RestError, PipelineResponse, PipelinePolicy } from '@azure/core-rest-pipeline';\nimport { AdditionalPolicyConfig } from '@azure/core-client';\nimport { pause } from './other';\nimport semverSatisfies from './semver-satisfies';\nimport { UnexpectedTsError, UnsupportedVersionError } from './errors';\n\nexport const genRequestQueuesPolicy = (): AdditionalPolicyConfig => {\n const requestQueues = new Map<string, Promise<unknown>>();\n\n return {\n policy: {\n name: 'request-queues',\n async sendRequest(request, next) {\n const key = request.headers.get('__queue');\n request.headers.delete('__queue');\n const getResponse = async (): Promise<PipelineResponse> => next(request);\n if (key == null) return getResponse();\n const req = (requestQueues.get(key) ?? Promise.resolve()).then(getResponse, getResponse);\n // TODO: remove after fixing https://github.com/aeternity/aeternity/issues/3803\n // gap to ensure that node won't reject the nonce\n requestQueues.set(key, req.then(async () => pause(750)));\n return req;\n },\n },\n position: 'perCall',\n };\n};\n\nexport const genCombineGetRequestsPolicy = (): AdditionalPolicyConfig => {\n const pendingGetRequests = new Map<string, Promise<PipelineResponse>>();\n\n return {\n policy: {\n name: 'combine-get-requests',\n async sendRequest(request, next) {\n if (request.method !== 'GET') return next(request);\n const key = JSON.stringify([request.url, request.body]);\n const response = pendingGetRequests.get(key) ?? next(request);\n pendingGetRequests.set(key, response);\n try {\n return await response;\n } finally {\n pendingGetRequests.delete(key);\n }\n },\n },\n position: 'perCall',\n };\n};\n\nexport const genAggressiveCacheGetResponsesPolicy = (): AdditionalPolicyConfig => {\n const getRequests = new Map<string, Promise<PipelineResponse>>();\n\n return {\n policy: {\n name: 'aggressive-cache-get-responses',\n async sendRequest(request, next) {\n if (request.method !== 'GET') return next(request);\n const key = JSON.stringify([request.url, request.body]);\n const response = getRequests.get(key) ?? next(request);\n getRequests.set(key, response);\n return response;\n },\n },\n position: 'perCall',\n };\n};\n\nexport const genErrorFormatterPolicy = (\n getMessage: (b: any) => string,\n): AdditionalPolicyConfig => ({\n policy: {\n name: 'error-formatter',\n async sendRequest(request, next) {\n try {\n return await next(request);\n } catch (error) {\n if (!(error instanceof RestError) || error.request == null) throw error;\n if (error.response?.bodyAsText == null) throw error;\n\n let body;\n try {\n body = JSON.parse(error.response.bodyAsText);\n } catch (e) {\n throw error;\n }\n error.message = `${new URL(error.request.url).pathname.slice(1)} error`;\n const message = getMessage(body);\n if (message !== '') error.message += `:${message}`;\n throw error;\n }\n },\n },\n position: 'perCall',\n});\n\nexport const genVersionCheckPolicy = (\n name: string,\n ignorePath: string,\n versionPromise: Promise<string | Error>,\n geVersion: string,\n ltVersion: string,\n): PipelinePolicy => ({\n name: 'version-check',\n async sendRequest(request, next) {\n if (new URL(request.url).pathname === ignorePath) return next(request);\n const version = await versionPromise;\n if (version instanceof Error) throw version;\n const args = [version, geVersion, ltVersion] as const;\n if (!semverSatisfies(...args)) throw new UnsupportedVersionError(name, ...args);\n return next(request);\n },\n});\n\nexport const genRetryOnFailurePolicy = (\n retryCount: number,\n retryOverallDelay: number,\n): AdditionalPolicyConfig => ({\n policy: {\n name: 'retry-on-failure',\n async sendRequest(request, next) {\n const statusesToNotRetry = [200, 400, 403];\n\n const intervals = new Array(retryCount).fill(0)\n .map((_, idx) => ((idx + 1) / retryCount) ** 2);\n const intervalSum = intervals.reduce((a, b) => a + b);\n const intervalsInMs = intervals.map((el) => (el / intervalSum) * retryOverallDelay);\n\n let error: Error | undefined;\n for (let attempt = 0; attempt <= retryCount; attempt += 1) {\n if (error != null) {\n if (\n !(error instanceof RestError)\n || statusesToNotRetry.includes(error.response?.status ?? 0)\n ) throw error;\n await pause(intervalsInMs[attempt - 1]);\n }\n try {\n return await next(request);\n } catch (e) {\n error = e;\n }\n }\n if (error == null) throw new UnexpectedTsError();\n throw error;\n },\n },\n position: 'perCall',\n});\n"],"mappings":"AAAA,SAASA,SAAS,QAA0C,2BAA2B;AAAC,SAE/EC,KAAK;AAAA,OACPC,eAAe;AAAA,SACbC,iBAAiB,EAAEC,uBAAuB;AAEnD,OAAO,MAAMC,sBAAsB,GAAGA,CAAA,KAA8B;EAClE,MAAMC,aAAa,GAAG,IAAIC,GAAG,EAA4B;EAEzD,OAAO;IACLC,MAAM,EAAE;MACNC,IAAI,EAAE,gBAAgB;MACtB,MAAMC,WAAWA,CAACC,OAAO,EAAEC,IAAI,EAAE;QAAA,IAAAC,kBAAA;QAC/B,MAAMC,GAAG,GAAGH,OAAO,CAACI,OAAO,CAACC,GAAG,CAAC,SAAS,CAAC;QAC1CL,OAAO,CAACI,OAAO,CAACE,MAAM,CAAC,SAAS,CAAC;QACjC,MAAMC,WAAW,GAAG,MAAAA,CAAA,KAAuCN,IAAI,CAACD,OAAO,CAAC;QACxE,IAAIG,GAAG,IAAI,IAAI,EAAE,OAAOI,WAAW,EAAE;QACrC,MAAMC,GAAG,GA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