@aeternity/aepp-sdk 11.0.1 → 12.0.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 (376) hide show
  1. package/LICENSE +1 -1
  2. package/dist/aepp-sdk.browser-script.js +1 -1
  3. package/dist/aepp-sdk.browser-script.js.LICENSE.txt +12 -19
  4. package/dist/aepp-sdk.browser-script.js.map +1 -1
  5. package/dist/aepp-sdk.browser.js +1 -1
  6. package/dist/aepp-sdk.browser.js.map +1 -1
  7. package/dist/aepp-sdk.js +1 -1
  8. package/dist/aepp-sdk.js.map +1 -1
  9. package/es/AeSdk.d.ts +37 -0
  10. package/es/AeSdk.mjs +81 -0
  11. package/es/AeSdk.mjs.map +1 -0
  12. package/es/AeSdkAepp.d.ts +69 -0
  13. package/es/AeSdkAepp.mjs +175 -0
  14. package/es/AeSdkAepp.mjs.map +1 -0
  15. package/es/AeSdkBase.d.ts +212 -0
  16. package/es/AeSdkBase.mjs +310 -0
  17. package/es/AeSdkBase.mjs.map +1 -0
  18. package/es/AeSdkWallet.d.ts +103 -0
  19. package/es/AeSdkWallet.mjs +322 -0
  20. package/es/AeSdkWallet.mjs.map +1 -0
  21. package/es/Node.d.ts +44 -0
  22. package/es/Node.mjs +141 -0
  23. package/es/Node.mjs.map +1 -0
  24. package/es/account/Base.d.ts +65 -0
  25. package/es/account/Base.mjs +123 -0
  26. package/es/account/Base.mjs.map +1 -0
  27. package/es/account/Memory.d.ts +25 -0
  28. package/es/account/Memory.mjs +81 -0
  29. package/es/account/Memory.mjs.map +1 -0
  30. package/es/account/Rpc.d.ts +27 -0
  31. package/es/account/Rpc.mjs +79 -0
  32. package/es/account/Rpc.mjs.map +1 -0
  33. package/es/aens.d.ts +209 -0
  34. package/es/aens.mjs +332 -0
  35. package/es/aens.mjs.map +1 -0
  36. package/es/aepp-wallet-communication/connection/Browser.d.ts +32 -0
  37. package/es/aepp-wallet-communication/connection/Browser.mjs +70 -0
  38. package/es/aepp-wallet-communication/connection/Browser.mjs.map +1 -0
  39. package/es/aepp-wallet-communication/connection/BrowserRuntime.d.ts +17 -0
  40. package/es/aepp-wallet-communication/connection/BrowserRuntime.mjs +57 -0
  41. package/es/aepp-wallet-communication/connection/BrowserRuntime.mjs.map +1 -0
  42. package/es/aepp-wallet-communication/connection/BrowserWindowMessage.d.ts +35 -0
  43. package/es/aepp-wallet-communication/connection/BrowserWindowMessage.mjs +142 -0
  44. package/es/aepp-wallet-communication/connection/BrowserWindowMessage.mjs.map +1 -0
  45. package/es/aepp-wallet-communication/connection-proxy.d.ts +10 -0
  46. package/{src/utils/crypto-ts.ts → es/aepp-wallet-communication/connection-proxy.mjs} +15 -11
  47. package/es/aepp-wallet-communication/connection-proxy.mjs.map +1 -0
  48. package/es/aepp-wallet-communication/rpc/RpcClient.d.ts +33 -0
  49. package/es/aepp-wallet-communication/rpc/RpcClient.mjs +169 -0
  50. package/es/aepp-wallet-communication/rpc/RpcClient.mjs.map +1 -0
  51. package/es/aepp-wallet-communication/rpc/types.d.ts +77 -0
  52. package/es/aepp-wallet-communication/rpc/types.mjs +3 -0
  53. package/es/aepp-wallet-communication/rpc/types.mjs.map +1 -0
  54. package/es/aepp-wallet-communication/schema.d.ts +90 -46
  55. package/es/aepp-wallet-communication/schema.mjs +214 -0
  56. package/es/aepp-wallet-communication/schema.mjs.map +1 -0
  57. package/es/aepp-wallet-communication/wallet-detector.d.ts +24 -0
  58. package/es/aepp-wallet-communication/wallet-detector.mjs +63 -0
  59. package/es/aepp-wallet-communication/wallet-detector.mjs.map +1 -0
  60. package/es/apis/compiler/compiler.d.ts +92 -0
  61. package/es/apis/compiler/compiler.mjs +576 -0
  62. package/es/apis/compiler/compiler.mjs.map +1 -0
  63. package/es/apis/compiler/index.d.ts +2 -0
  64. package/es/apis/compiler/index.mjs +3 -0
  65. package/es/apis/compiler/index.mjs.map +1 -0
  66. package/es/apis/compiler/models/index.d.ts +248 -0
  67. package/es/apis/compiler/models/index.mjs +48 -0
  68. package/es/apis/compiler/models/index.mjs.map +1 -0
  69. package/es/apis/compiler/models/mappers.d.ts +23 -0
  70. package/es/apis/compiler/models/mappers.mjs +585 -0
  71. package/es/apis/compiler/models/mappers.mjs.map +1 -0
  72. package/es/apis/compiler/models/parameters.d.ts +13 -0
  73. package/es/apis/compiler/models/parameters.mjs +71 -0
  74. package/es/apis/compiler/models/parameters.mjs.map +1 -0
  75. package/es/apis/node/index.d.ts +2 -0
  76. package/es/apis/node/index.mjs +3 -0
  77. package/es/apis/node/index.mjs.map +1 -0
  78. package/es/apis/node/models/index.d.ts +1061 -0
  79. package/es/apis/node/models/index.mjs +2 -0
  80. package/es/apis/node/models/index.mjs.map +1 -0
  81. package/es/apis/node/models/mappers.d.ts +95 -0
  82. package/es/apis/node/models/mappers.mjs +4164 -0
  83. package/es/apis/node/models/mappers.mjs.map +1 -0
  84. package/es/apis/node/models/parameters.d.ts +17 -0
  85. package/es/apis/node/models/parameters.mjs +165 -0
  86. package/es/apis/node/models/parameters.mjs.map +1 -0
  87. package/es/apis/node/node.d.ts +215 -0
  88. package/es/apis/node/node.mjs +1165 -0
  89. package/es/apis/node/node.mjs.map +1 -0
  90. package/es/chain.d.ts +220 -0
  91. package/es/chain.mjs +524 -0
  92. package/es/chain.mjs.map +1 -0
  93. package/es/channel/handlers.d.ts +34 -0
  94. package/es/channel/handlers.mjs +147 -112
  95. package/es/channel/handlers.mjs.map +1 -1
  96. package/es/channel/index.d.ts +634 -0
  97. package/es/channel/index.mjs +898 -900
  98. package/es/channel/index.mjs.map +1 -1
  99. package/es/channel/internal.d.ts +100 -0
  100. package/es/channel/internal.mjs +97 -51
  101. package/es/channel/internal.mjs.map +1 -1
  102. package/es/contract/Compiler.d.ts +17 -0
  103. package/es/contract/Compiler.mjs +67 -0
  104. package/es/contract/Compiler.mjs.map +1 -0
  105. package/es/contract/aci.d.ts +125 -0
  106. package/es/contract/aci.mjs +199 -180
  107. package/es/contract/aci.mjs.map +1 -1
  108. package/es/contract/ga.d.ts +68 -0
  109. package/es/contract/ga.mjs +190 -0
  110. package/es/contract/ga.mjs.map +1 -0
  111. package/es/contract/methods.d.ts +68 -0
  112. package/es/contract/methods.mjs +101 -0
  113. package/es/contract/methods.mjs.map +1 -0
  114. package/es/index.d.ts +32 -0
  115. package/es/index.mjs +32 -40
  116. package/es/index.mjs.map +1 -1
  117. package/es/oracle.d.ts +154 -0
  118. package/es/oracle.mjs +288 -0
  119. package/es/oracle.mjs.map +1 -0
  120. package/es/spend.d.ts +61 -0
  121. package/es/spend.mjs +122 -0
  122. package/es/spend.mjs.map +1 -0
  123. package/es/tx/builder/constants.d.ts +41 -0
  124. package/es/tx/builder/constants.mjs +11 -19
  125. package/es/tx/builder/constants.mjs.map +1 -1
  126. package/es/tx/builder/field-types.d.ts +62 -0
  127. package/es/tx/builder/field-types.mjs +62 -10
  128. package/es/tx/builder/field-types.mjs.map +1 -1
  129. package/es/tx/builder/helpers.d.ts +131 -0
  130. package/es/tx/builder/helpers.mjs +71 -169
  131. package/es/tx/builder/helpers.mjs.map +1 -1
  132. package/es/tx/builder/index.d.ts +75 -0
  133. package/es/tx/builder/index.mjs +141 -323
  134. package/es/tx/builder/index.mjs.map +1 -1
  135. package/es/tx/builder/schema.d.ts +350 -0
  136. package/es/tx/builder/schema.mjs +173 -510
  137. package/es/tx/builder/schema.mjs.map +1 -1
  138. package/es/tx/index.d.ts +63 -0
  139. package/es/tx/index.mjs +171 -265
  140. package/es/tx/index.mjs.map +1 -1
  141. package/es/tx/min-fee.d.ts +20 -0
  142. package/es/tx/min-fee.mjs +148 -0
  143. package/es/tx/min-fee.mjs.map +1 -0
  144. package/es/tx/validator.d.ts +19 -0
  145. package/es/tx/validator.mjs +64 -71
  146. package/es/tx/validator.mjs.map +1 -1
  147. package/es/typings/@aeternity__argon2-browser/index.d.mjs +2 -0
  148. package/es/typings/@aeternity__argon2-browser/index.d.mjs.map +1 -0
  149. package/es/typings/@aeternity__uuid/index.d.mjs +2 -0
  150. package/es/typings/@aeternity__uuid/index.d.mjs.map +1 -0
  151. package/es/typings/bip32-path/index.d.mjs +2 -0
  152. package/es/typings/bip32-path/index.d.mjs.map +1 -0
  153. package/es/typings/blakejs/index.d.mjs.map +1 -1
  154. package/es/typings/tweetnacl-auth/index.d.mjs +2 -0
  155. package/es/typings/tweetnacl-auth/index.d.mjs.map +1 -0
  156. package/es/utils/amount-formatter.d.ts +42 -0
  157. package/es/utils/amount-formatter.mjs +28 -41
  158. package/es/utils/amount-formatter.mjs.map +1 -1
  159. package/es/utils/autorest.d.ts +6 -0
  160. package/es/utils/autorest.mjs +97 -0
  161. package/es/utils/autorest.mjs.map +1 -0
  162. package/es/utils/bignumber.d.ts +13 -0
  163. package/es/utils/bignumber.mjs +10 -8
  164. package/es/utils/bignumber.mjs.map +1 -1
  165. package/es/{bytes.d.ts → utils/bytes.d.ts} +10 -13
  166. package/es/utils/bytes.mjs +10 -14
  167. package/es/utils/bytes.mjs.map +1 -1
  168. package/es/utils/crypto.d.ts +103 -0
  169. package/es/utils/crypto.mjs +60 -68
  170. package/es/utils/crypto.mjs.map +1 -1
  171. package/es/utils/encoder.d.ts +26 -0
  172. package/es/utils/encoder.mjs +47 -51
  173. package/es/utils/encoder.mjs.map +1 -1
  174. package/es/{errors.d.ts → utils/errors.d.ts} +254 -57
  175. package/es/utils/errors.mjs +318 -125
  176. package/es/utils/errors.mjs.map +1 -1
  177. package/es/utils/hd-wallet.d.ts +34 -0
  178. package/es/utils/hd-wallet.mjs +27 -16
  179. package/es/utils/hd-wallet.mjs.map +1 -1
  180. package/es/utils/json-big.d.ts +5 -0
  181. package/es/utils/json-big.mjs +10 -14
  182. package/es/utils/json-big.mjs.map +1 -1
  183. package/es/utils/keystore.d.ts +51 -0
  184. package/es/utils/keystore.mjs +98 -193
  185. package/es/utils/keystore.mjs.map +1 -1
  186. package/es/{mptree.d.ts → utils/mptree.d.ts} +5 -8
  187. package/es/utils/mptree.mjs +13 -14
  188. package/es/utils/mptree.mjs.map +1 -1
  189. package/es/utils/other.d.ts +14 -0
  190. package/es/utils/other.mjs +21 -36
  191. package/es/utils/other.mjs.map +1 -1
  192. package/es/{semver-satisfies.d.ts → utils/semver-satisfies.d.ts} +0 -0
  193. package/es/utils/semver-satisfies.mjs.map +1 -1
  194. package/es/utils/string.d.ts +24 -0
  195. package/es/utils/string.mjs +8 -10
  196. package/es/utils/string.mjs.map +1 -1
  197. package/package.json +49 -39
  198. package/src/AeSdk.ts +65 -0
  199. package/src/AeSdkAepp.ts +167 -0
  200. package/src/AeSdkBase.ts +320 -0
  201. package/src/AeSdkWallet.ts +332 -0
  202. package/src/Node.ts +167 -0
  203. package/src/account/Base.ts +114 -0
  204. package/src/account/Memory.ts +83 -0
  205. package/src/account/Rpc.ts +67 -0
  206. package/src/aens.ts +391 -0
  207. package/src/aepp-wallet-communication/connection/Browser.ts +68 -0
  208. package/src/aepp-wallet-communication/connection/BrowserRuntime.ts +58 -0
  209. package/src/aepp-wallet-communication/connection/BrowserWindowMessage.ts +111 -0
  210. package/{es/utils/crypto-ts.mjs → src/aepp-wallet-communication/connection-proxy.ts} +16 -17
  211. package/src/aepp-wallet-communication/rpc/RpcClient.ts +137 -0
  212. package/src/aepp-wallet-communication/rpc/types.ts +66 -0
  213. package/src/aepp-wallet-communication/schema.ts +181 -0
  214. package/src/aepp-wallet-communication/wallet-detector.ts +71 -0
  215. package/src/apis/compiler/code-model-v4.yaml +2649 -0
  216. package/src/apis/compiler/compiler.ts +585 -0
  217. package/src/apis/compiler/index.ts +2 -0
  218. package/src/apis/compiler/models/index.ts +301 -0
  219. package/src/apis/compiler/models/mappers.ts +583 -0
  220. package/src/apis/compiler/models/parameters.ts +93 -0
  221. package/src/apis/node/code-model-v4.yaml +10046 -0
  222. package/src/apis/node/index.ts +2 -0
  223. package/src/apis/node/models/index.ts +1253 -0
  224. package/src/apis/node/models/mappers.ts +4278 -0
  225. package/src/apis/node/models/parameters.ts +188 -0
  226. package/src/apis/node/node.ts +1299 -0
  227. package/src/chain.ts +444 -0
  228. package/src/channel/{handlers.js → handlers.ts} +220 -128
  229. package/src/channel/index.ts +991 -0
  230. package/src/channel/internal.ts +345 -0
  231. package/src/contract/Compiler.ts +66 -0
  232. package/src/contract/aci.ts +529 -0
  233. package/src/contract/ga.ts +178 -0
  234. package/src/contract/methods.ts +118 -0
  235. package/src/index.ts +51 -0
  236. package/src/oracle.ts +342 -0
  237. package/src/spend.ts +152 -0
  238. package/src/tx/builder/{constants.js → constants.ts} +12 -16
  239. package/src/tx/builder/field-types.ts +111 -0
  240. package/src/tx/builder/helpers.ts +253 -0
  241. package/src/tx/builder/index.ts +394 -0
  242. package/src/tx/builder/schema.ts +771 -0
  243. package/src/tx/index.ts +199 -0
  244. package/src/tx/min-fee.ts +136 -0
  245. package/src/tx/validator.ts +226 -0
  246. package/src/typings/@aeternity__argon2-browser/index.d.ts +3 -0
  247. package/src/typings/@aeternity__uuid/index.d.ts +3 -0
  248. package/src/typings/bip32-path/index.d.ts +33 -0
  249. package/src/typings/tweetnacl-auth/index.d.ts +14 -0
  250. package/src/utils/amount-formatter.ts +29 -42
  251. package/src/utils/autorest.ts +90 -0
  252. package/src/utils/bignumber.ts +9 -11
  253. package/src/utils/bytes.ts +12 -14
  254. package/src/utils/crypto.ts +217 -0
  255. package/src/utils/encoder.ts +52 -55
  256. package/src/utils/errors.ts +268 -134
  257. package/src/utils/hd-wallet.ts +134 -0
  258. package/src/utils/json-big.ts +26 -0
  259. package/src/utils/keystore.ts +179 -0
  260. package/src/utils/mptree.ts +14 -14
  261. package/src/utils/other.ts +28 -43
  262. package/src/utils/string.ts +8 -10
  263. package/es/account/base.mjs +0 -179
  264. package/es/account/base.mjs.map +0 -1
  265. package/es/account/memory.mjs +0 -99
  266. package/es/account/memory.mjs.map +0 -1
  267. package/es/account/multiple.mjs +0 -179
  268. package/es/account/multiple.mjs.map +0 -1
  269. package/es/ae/aens.mjs +0 -404
  270. package/es/ae/aens.mjs.map +0 -1
  271. package/es/ae/aepp.mjs +0 -45
  272. package/es/ae/aepp.mjs.map +0 -1
  273. package/es/ae/contract.mjs +0 -159
  274. package/es/ae/contract.mjs.map +0 -1
  275. package/es/ae/index.mjs +0 -207
  276. package/es/ae/index.mjs.map +0 -1
  277. package/es/ae/oracle.mjs +0 -339
  278. package/es/ae/oracle.mjs.map +0 -1
  279. package/es/ae/universal.mjs +0 -45
  280. package/es/ae/universal.mjs.map +0 -1
  281. package/es/ae/wallet.mjs +0 -50
  282. package/es/ae/wallet.mjs.map +0 -1
  283. package/es/amount-formatter.d.ts +0 -58
  284. package/es/bignumber.d.ts +0 -18
  285. package/es/chain/index.mjs +0 -272
  286. package/es/chain/index.mjs.map +0 -1
  287. package/es/chain/node.mjs +0 -442
  288. package/es/chain/node.mjs.map +0 -1
  289. package/es/contract/compiler.mjs +0 -115
  290. package/es/contract/compiler.mjs.map +0 -1
  291. package/es/contract/ga/helpers.mjs +0 -30
  292. package/es/contract/ga/helpers.mjs.map +0 -1
  293. package/es/contract/ga/index.mjs +0 -178
  294. package/es/contract/ga/index.mjs.map +0 -1
  295. package/es/crypto-ts.d.ts +0 -9
  296. package/es/encoder.d.ts +0 -26
  297. package/es/node-pool/index.mjs +0 -188
  298. package/es/node-pool/index.mjs.map +0 -1
  299. package/es/node.mjs +0 -133
  300. package/es/node.mjs.map +0 -1
  301. package/es/other.d.ts +0 -31
  302. package/es/string.d.ts +0 -26
  303. package/es/tx/tx-object.mjs +0 -283
  304. package/es/tx/tx-object.mjs.map +0 -1
  305. package/es/tx/tx.mjs +0 -938
  306. package/es/tx/tx.mjs.map +0 -1
  307. package/es/utils/aepp-wallet-communication/connection/browser-runtime.mjs +0 -132
  308. package/es/utils/aepp-wallet-communication/connection/browser-runtime.mjs.map +0 -1
  309. package/es/utils/aepp-wallet-communication/connection/browser-window-message.mjs +0 -183
  310. package/es/utils/aepp-wallet-communication/connection/browser-window-message.mjs.map +0 -1
  311. package/es/utils/aepp-wallet-communication/connection/index.mjs +0 -87
  312. package/es/utils/aepp-wallet-communication/connection/index.mjs.map +0 -1
  313. package/es/utils/aepp-wallet-communication/content-script-bridge.mjs +0 -98
  314. package/es/utils/aepp-wallet-communication/content-script-bridge.mjs.map +0 -1
  315. package/es/utils/aepp-wallet-communication/helpers.mjs +0 -92
  316. package/es/utils/aepp-wallet-communication/helpers.mjs.map +0 -1
  317. package/es/utils/aepp-wallet-communication/rpc/aepp-rpc.mjs +0 -375
  318. package/es/utils/aepp-wallet-communication/rpc/aepp-rpc.mjs.map +0 -1
  319. package/es/utils/aepp-wallet-communication/rpc/rpc-client.mjs +0 -275
  320. package/es/utils/aepp-wallet-communication/rpc/rpc-client.mjs.map +0 -1
  321. package/es/utils/aepp-wallet-communication/rpc/wallet-rpc.mjs +0 -541
  322. package/es/utils/aepp-wallet-communication/rpc/wallet-rpc.mjs.map +0 -1
  323. package/es/utils/aepp-wallet-communication/schema.mjs +0 -102
  324. package/es/utils/aepp-wallet-communication/schema.mjs.map +0 -1
  325. package/es/utils/aepp-wallet-communication/wallet-detector.mjs +0 -110
  326. package/es/utils/aepp-wallet-communication/wallet-detector.mjs.map +0 -1
  327. package/es/utils/async-init.mjs +0 -64
  328. package/es/utils/async-init.mjs.map +0 -1
  329. package/es/utils/crypto-ts.mjs.map +0 -1
  330. package/es/utils/swagger.mjs +0 -164
  331. package/es/utils/swagger.mjs.map +0 -1
  332. package/src/account/base.js +0 -153
  333. package/src/account/memory.js +0 -83
  334. package/src/account/multiple.js +0 -162
  335. package/src/ae/aens.js +0 -361
  336. package/src/ae/aepp.js +0 -45
  337. package/src/ae/contract.js +0 -148
  338. package/src/ae/index.js +0 -168
  339. package/src/ae/oracle.js +0 -311
  340. package/src/ae/universal.js +0 -47
  341. package/src/ae/wallet.js +0 -50
  342. package/src/chain/index.js +0 -269
  343. package/src/chain/node.js +0 -320
  344. package/src/channel/index.js +0 -903
  345. package/src/channel/internal.js +0 -236
  346. package/src/contract/aci.js +0 -376
  347. package/src/contract/compiler.js +0 -100
  348. package/src/contract/ga/helpers.js +0 -19
  349. package/src/contract/ga/index.js +0 -150
  350. package/src/index.js +0 -89
  351. package/src/node-pool/index.js +0 -172
  352. package/src/node.js +0 -116
  353. package/src/tx/builder/field-types.js +0 -61
  354. package/src/tx/builder/helpers.js +0 -334
  355. package/src/tx/builder/index.js +0 -465
  356. package/src/tx/builder/schema.js +0 -1100
  357. package/src/tx/index.js +0 -301
  358. package/src/tx/tx-object.js +0 -187
  359. package/src/tx/tx.js +0 -631
  360. package/src/tx/validator.js +0 -181
  361. package/src/utils/aepp-wallet-communication/connection/browser-runtime.js +0 -119
  362. package/src/utils/aepp-wallet-communication/connection/browser-window-message.js +0 -165
  363. package/src/utils/aepp-wallet-communication/connection/index.js +0 -85
  364. package/src/utils/aepp-wallet-communication/content-script-bridge.js +0 -86
  365. package/src/utils/aepp-wallet-communication/helpers.js +0 -60
  366. package/src/utils/aepp-wallet-communication/rpc/aepp-rpc.js +0 -294
  367. package/src/utils/aepp-wallet-communication/rpc/rpc-client.js +0 -232
  368. package/src/utils/aepp-wallet-communication/rpc/wallet-rpc.js +0 -401
  369. package/src/utils/aepp-wallet-communication/schema.ts +0 -80
  370. package/src/utils/aepp-wallet-communication/wallet-detector.js +0 -92
  371. package/src/utils/async-init.js +0 -45
  372. package/src/utils/crypto.js +0 -219
  373. package/src/utils/hd-wallet.js +0 -100
  374. package/src/utils/json-big.js +0 -26
  375. package/src/utils/keystore.js +0 -219
  376. package/src/utils/swagger.js +0 -156
@@ -14,33 +14,24 @@
14
14
  * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
15
15
  * PERFORMANCE OF THIS SOFTWARE.
16
16
  */
17
-
18
- /**
19
- * Amount Formatter
20
- * @module @aeternity/aepp-sdk/es/utils/amount-formatter
21
- * @example import { AmountFormatter } from '@aeternity/aepp-sdk'
22
- */
23
17
  import BigNumber from 'bignumber.js'
24
18
  import { isBigNumber } from './bignumber'
25
- import { ArgumentError, InvalidDenominationError } from './errors'
19
+ import { ArgumentError } from './errors'
26
20
 
27
- /**
28
- * AE amount formats
29
- */
30
- export const AE_AMOUNT_FORMATS = {
31
- AE: 'ae',
32
- MILI_AE: 'miliAE',
33
- MICRO_AE: 'microAE',
34
- NANO_AE: 'nanoAE',
35
- PICO_AE: 'picoAE',
36
- FEMTO_AE: 'femtoAE',
37
- AETTOS: 'aettos'
21
+ export enum AE_AMOUNT_FORMATS {
22
+ AE = 'ae',
23
+ MILI_AE = 'miliAE',
24
+ MICRO_AE = 'microAE',
25
+ NANO_AE = 'nanoAE',
26
+ PICO_AE = 'picoAE',
27
+ FEMTO_AE = 'femtoAE',
28
+ AETTOS = 'aettos'
38
29
  }
39
30
 
40
31
  /**
41
32
  * DENOMINATION_MAGNITUDE
42
33
  */
43
- export const DENOMINATION_MAGNITUDE = {
34
+ const DENOMINATION_MAGNITUDE = {
44
35
  [AE_AMOUNT_FORMATS.AE]: 0,
45
36
  [AE_AMOUNT_FORMATS.MILI_AE]: -3,
46
37
  [AE_AMOUNT_FORMATS.MICRO_AE]: -6,
@@ -48,50 +39,46 @@ export const DENOMINATION_MAGNITUDE = {
48
39
  [AE_AMOUNT_FORMATS.PICO_AE]: -12,
49
40
  [AE_AMOUNT_FORMATS.FEMTO_AE]: -15,
50
41
  [AE_AMOUNT_FORMATS.AETTOS]: -18
51
- }
42
+ } as const
52
43
 
53
44
  /**
54
45
  * Convert amount to AE
55
- * @param {String|Number|BigNumber} value amount to convert
56
- * @param {Object} [options={}] options
57
- * @param {String} [options.denomination='aettos'] denomination of amount, can be ['ae', 'aettos']
58
- * @return {String}
46
+ * @param value - amount to convert
47
+ * @param options - options
48
+ * @param options.denomination - denomination of amount, can be ['ae', 'aettos']
59
49
  */
60
50
  export const toAe = (
61
51
  value: string | number | BigNumber,
62
- { denomination = AE_AMOUNT_FORMATS.AETTOS } = {}
52
+ { denomination = AE_AMOUNT_FORMATS.AETTOS }: { denomination?: AE_AMOUNT_FORMATS } = {}
63
53
  ): string => formatAmount(value, { denomination, targetDenomination: AE_AMOUNT_FORMATS.AE })
64
54
 
65
55
  /**
66
56
  * Convert amount to aettos
67
- * @param {String|Number|BigNumber} value amount to convert
68
- * @param {Object} [options={}] options
69
- * @param {String} [options.denomination='ae'] denomination of amount, can be ['ae', 'aettos']
70
- * @return {String}
57
+ * @param value - amount to convert
58
+ * @param options - options
59
+ * @param options.denomination - denomination of amount, can be ['ae', 'aettos']
71
60
  */
72
61
  export const toAettos = (
73
62
  value: string | number | BigNumber,
74
- { denomination = AE_AMOUNT_FORMATS.AE } = {}
63
+ { denomination = AE_AMOUNT_FORMATS.AE }: { denomination?: AE_AMOUNT_FORMATS } = {}
75
64
  ): string => formatAmount(value, { denomination })
76
65
 
77
66
  /**
78
67
  * Convert amount from one to other denomination
79
- * @param {String|Number|BigNumber} value amount to convert
80
- * @param {Object} [options={}] options
81
- * @param {String} [options.denomination='aettos'] denomination of amount, can be ['ae', 'aettos']
82
- * @param {String} [options.targetDenomination='aettos'] target denomination, can be ['ae', 'aettos']
83
- * @return {String}
68
+ * @param value - amount to convert
69
+ * @param options - options
70
+ * @param options.denomination - denomination of amount, can be ['ae', 'aettos']
71
+ * @param options.targetDenomination - target denomination,
72
+ * can be ['ae', 'aettos']
84
73
  */
85
74
  export const formatAmount = (
86
- value: string | number | BigNumber,
87
- { denomination = AE_AMOUNT_FORMATS.AETTOS, targetDenomination = AE_AMOUNT_FORMATS.AETTOS } = {}
75
+ value: string | number | bigint | BigNumber,
76
+ { denomination = AE_AMOUNT_FORMATS.AETTOS, targetDenomination = AE_AMOUNT_FORMATS.AETTOS }:
77
+ { denomination?: AE_AMOUNT_FORMATS, targetDenomination?: AE_AMOUNT_FORMATS }
88
78
  ): string => {
89
- const denominations = Object.values(AE_AMOUNT_FORMATS)
90
- if (!denominations.includes(denomination)) throw new InvalidDenominationError(`Invalid denomination: ${denomination}`)
91
- if (!denominations.includes(targetDenomination)) throw new InvalidDenominationError(`Invalid target denomination: ${targetDenomination}`)
92
- if (!isBigNumber(value)) throw new ArgumentError('value', `a number`, value)
79
+ if (!isBigNumber(value)) throw new ArgumentError('value', 'a number', value)
93
80
 
94
- return new BigNumber(value)
81
+ return new BigNumber(typeof value === 'bigint' ? value.toString() : value)
95
82
  .shiftedBy(DENOMINATION_MAGNITUDE[denomination] - DENOMINATION_MAGNITUDE[targetDenomination])
96
83
  .toFixed()
97
84
  }
@@ -0,0 +1,90 @@
1
+ import { RestError, PipelineResponse, PipelinePolicy } from '@azure/core-rest-pipeline'
2
+ import { AdditionalPolicyConfig } from '@azure/core-client'
3
+ import { pause } from './other'
4
+ import semverSatisfies from './semver-satisfies'
5
+ import { UnsupportedVersionError } from './errors'
6
+
7
+ export const genRequestQueuesPolicy = (): AdditionalPolicyConfig => {
8
+ const requestQueues = new Map<string, Promise<unknown>>()
9
+
10
+ return {
11
+ policy: {
12
+ name: 'request-queues',
13
+ async sendRequest (request, next) {
14
+ const key = request.headers.get('__queue')
15
+ request.headers.delete('__queue')
16
+ const getResponse = async (): Promise<PipelineResponse> => await next(request)
17
+ if (key == null) return await getResponse()
18
+ const req = (requestQueues.get(key) ?? Promise.resolve()).then(getResponse, getResponse)
19
+ // TODO: remove after fixing https://github.com/aeternity/aeternity/issues/3803
20
+ // gap to ensure that node won't reject the nonce
21
+ requestQueues.set(key, req.then(async () => await pause(750)))
22
+ return await req
23
+ }
24
+ },
25
+ position: 'perCall'
26
+ }
27
+ }
28
+
29
+ export const genCombineGetRequestsPolicy = (): AdditionalPolicyConfig => {
30
+ const pendingGetRequests = new Map<string, Promise<PipelineResponse>>()
31
+
32
+ return {
33
+ policy: {
34
+ name: 'combine-requests',
35
+ async sendRequest (request, next) {
36
+ if (request.method !== 'GET') return await next(request)
37
+ const key = JSON.stringify([request.url, request.body])
38
+ const response = pendingGetRequests.get(key) ?? next(request)
39
+ pendingGetRequests.set(key, response)
40
+ try {
41
+ return await response
42
+ } finally {
43
+ pendingGetRequests.delete(key)
44
+ }
45
+ }
46
+ },
47
+ position: 'perCall'
48
+ }
49
+ }
50
+
51
+ export const genErrorFormatterPolicy = (
52
+ getMessage: (b: any) => string
53
+ ): AdditionalPolicyConfig => ({
54
+ policy: {
55
+ name: 'error-formatter',
56
+ async sendRequest (request, next) {
57
+ try {
58
+ return await next(request)
59
+ } catch (error) {
60
+ if (!(error instanceof RestError) || error.request == null) throw error
61
+ if (error.response?.bodyAsText == null) throw error
62
+
63
+ let body
64
+ try {
65
+ body = JSON.parse(error.response.bodyAsText)
66
+ } catch (e) {
67
+ throw error
68
+ }
69
+ error.message = `${new URL(error.request.url).pathname.slice(1)} error`
70
+ const message = getMessage(body)
71
+ if (message !== '') error.message += `:${message}`
72
+ throw error
73
+ }
74
+ }
75
+ },
76
+ position: 'perCall'
77
+ })
78
+
79
+ export const genVersionCheckPolicy = (
80
+ name: string, ignorePath: string,
81
+ versionPromise: Promise<string>, geVersion: string, ltVersion: string
82
+ ): PipelinePolicy => ({
83
+ name: 'version-check',
84
+ async sendRequest (request, next) {
85
+ if (new URL(request.url).pathname === ignorePath) return await next(request)
86
+ const args = [await versionPromise, geVersion, ltVersion] as const
87
+ if (!semverSatisfies(...args)) throw new UnsupportedVersionError(name, ...args)
88
+ return await next(request)
89
+ }
90
+ })
@@ -1,22 +1,20 @@
1
1
  /**
2
2
  * Big Number Helpers
3
- * @module @aeternity/aepp-sdk/es/utils/bignumber
4
- * @example import { isBigNumber, ceil } from '@aeternity/aepp-sdk/es/utils/bignumber'
5
3
  */
6
4
  import BigNumber from 'bignumber.js'
7
5
 
8
6
  /**
9
- * Check if value is BigNumber, Number or number string representation
10
- * @param {String|Number|BigNumber} number number to convert
11
- * @return {Boolean}
7
+ * Check if value is BigNumber, Number, BigInt or number string representation
8
+ * @param number - number to check
12
9
  */
13
- export const isBigNumber = (number: string | number | BigNumber): boolean =>
14
- ['number', 'object', 'string', 'bigint'].includes(typeof number) &&
15
- (!isNaN(number as number) || Number.isInteger(number) || BigNumber.isBigNumber(number))
10
+ export const isBigNumber = (number: string | number | bigint | BigNumber): boolean => {
11
+ if (typeof number === 'bigint') return true
12
+ return ['number', 'object', 'string'].includes(typeof number) &&
13
+ (!isNaN(number as number) || Number.isInteger(number) || BigNumber.isBigNumber(number))
14
+ }
16
15
 
17
16
  /**
18
17
  * BigNumber ceil operation
19
- * @param {BigNumber} bigNumber
20
- * @return {BigNumber}
21
18
  */
22
- export const ceil = (bigNumber: BigNumber): BigNumber => bigNumber.integerValue(BigNumber.ROUND_CEIL)
19
+ export const ceil = (bigNumber: BigNumber): BigNumber => bigNumber
20
+ .integerValue(BigNumber.ROUND_CEIL)
@@ -18,16 +18,10 @@ import BigNumber from 'bignumber.js'
18
18
  import { NoSerializerFoundError, TypeError } from './errors'
19
19
  import { isBase64, isHex } from './string'
20
20
 
21
- /**
22
- * Bytes module
23
- * @module @aeternity/aepp-sdk/es/utils/bytes
24
- * @example import { Crypto } from '@aeternity/aepp-sdk'
25
- */
26
-
27
21
  /**
28
22
  * Convert bignumber to byte array
29
- * @param {BigNumber} x bignumber instance
30
- * @return Buffer
23
+ * @param x - bignumber instance
24
+ * @returns Buffer
31
25
  */
32
26
  export function bigNumberToByteArray (x: BigNumber): Buffer {
33
27
  if (!x.isInteger()) throw new TypeError(`Unexpected not integer value: ${x.toFixed()}`)
@@ -38,9 +32,9 @@ export function bigNumberToByteArray (x: BigNumber): Buffer {
38
32
 
39
33
  /**
40
34
  * Convert string, number, or BigNumber to byte array
41
- * @param {null|string|number|BigNumber} val
42
- * @param {boolean} big enables force conversion to BigNumber
43
- * @return Buffer
35
+ * @param val - value to convert
36
+ * @param big - enables force conversion to BigNumber
37
+ * @returns Buffer
44
38
  */
45
39
  export function toBytes (val?: null | string | number | BigNumber, big: boolean = false): Buffer {
46
40
  // Encode a value to bytes.
@@ -62,9 +56,9 @@ export function toBytes (val?: null | string | number | BigNumber, big: boolean
62
56
  * Convert a string to a Buffer. If encoding is not specified, hex-encoding
63
57
  * will be used if the input is valid hex. If the input is valid base64 but
64
58
  * not valid hex, base64 will be used. Otherwise, utf8 will be used.
65
- * @param {string} str String to be converted.
66
- * @param {string} [enc] Encoding of the input string.
67
- * @return {buffer} Buffer containing the input data.
59
+ * @param str - String to be converted.
60
+ * @param enc - Encoding of the input string.
61
+ * @returns Buffer containing the input data.
68
62
  */
69
63
  export function str2buf (str: string, enc?: BufferEncoding): Buffer {
70
64
  return Buffer.from(
@@ -72,3 +66,7 @@ export function str2buf (str: string, enc?: BufferEncoding): Buffer {
72
66
  enc ?? (isHex(str) ? 'hex' : undefined) ?? (isBase64(str) ? 'base64' : undefined)
73
67
  )
74
68
  }
69
+
70
+ export const bytesToHex = (b: Uint8Array): string => Buffer.from(b).toString('hex')
71
+
72
+ export const hexToBytes = (s: string): Uint8Array => Buffer.from(s, 'hex')
@@ -0,0 +1,217 @@
1
+ /*
2
+ * ISC License (ISC)
3
+ * Copyright 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
+ import nacl, { SignKeyPair } from 'tweetnacl'
18
+ import aesjs from 'aes-js'
19
+ import { blake2b, Data } from 'blakejs'
20
+ import { encode as varuintEncode } from 'varuint-bitcoin'
21
+
22
+ import { str2buf } from './bytes'
23
+ import { concatBuffers } from './other'
24
+ import { encode, decode, sha256hash, EncodedData, EncodingType } from './encoder'
25
+
26
+ export { sha256hash }
27
+
28
+ const Ecb = aesjs.ModeOfOperation.ecb
29
+
30
+ /**
31
+ * Generate address from secret key
32
+ * @param secret - Private key
33
+ * @returns Public key encoded as address
34
+ */
35
+ export function getAddressFromPriv (secret: string | Uint8Array): EncodedData<'ak'> {
36
+ const secretBuffer = typeof secret === 'string' ? str2buf(secret) : secret
37
+ const keys = nacl.sign.keyPair.fromSecretKey(secretBuffer)
38
+ return encode(keys.publicKey, 'ak')
39
+ }
40
+
41
+ /**
42
+ * Check if address is valid
43
+ * @param address - Address
44
+ * @param prefix - Transaction prefix. Default: 'ak'
45
+ * @returns is valid
46
+ */
47
+ export function isAddressValid (address: string, prefix: EncodingType = 'ak'): boolean {
48
+ try {
49
+ decode(address as EncodedData<typeof prefix>)
50
+ return true
51
+ } catch (e) {
52
+ return false
53
+ }
54
+ }
55
+
56
+ /**
57
+ * Generate a random salt (positive integer)
58
+ * @returns random salt
59
+ */
60
+ export function salt (): number {
61
+ return Math.floor(Math.random() * Math.floor(Number.MAX_SAFE_INTEGER))
62
+ }
63
+
64
+ /**
65
+ * Converts a positive integer to the smallest possible
66
+ * representation in a binary digit representation
67
+ * @param value - Value to encode
68
+ * @returns Encoded number
69
+ */
70
+ export function encodeUnsigned (value: number): Buffer {
71
+ const binary = Buffer.allocUnsafe(4)
72
+ binary.writeUInt32BE(value)
73
+ return binary.slice(binary.findIndex(i => i !== 0))
74
+ }
75
+
76
+ /**
77
+ * Calculate 256bits Blake2b hash of `input`
78
+ * @param input - Data to hash
79
+ * @returns Hash
80
+ */
81
+ export function hash (input: Data): Buffer {
82
+ return Buffer.from(blake2b(input, undefined, 32)) // 256 bits
83
+ }
84
+
85
+ // Todo Duplicated in tx builder. remove
86
+ /**
87
+ * Compute contract address
88
+ * @param owner - Address of contract owner
89
+ * @param nonce - Round when contract was created
90
+ * @returns Contract address
91
+ */
92
+ export function encodeContractAddress (owner: EncodedData<'ak'>, nonce: number): EncodedData<'ct'> {
93
+ const publicKey = decode(owner)
94
+ const binary = concatBuffers([publicKey, encodeUnsigned(nonce)])
95
+ return encode(hash(binary), 'ct')
96
+ }
97
+
98
+ // KEY-PAIR HELPERS
99
+
100
+ /**
101
+ * Generate keyPair from secret key
102
+ * @param secret - secret key
103
+ * @returns Object with Private(privateKey) and Public(publicKey) keys
104
+ */
105
+ export function generateKeyPairFromSecret (secret: Uint8Array): SignKeyPair {
106
+ return nacl.sign.keyPair.fromSecretKey(secret)
107
+ }
108
+
109
+ /**
110
+ * Generate a random ED25519 keypair
111
+ * @param raw - Whether to return raw (binary) keys
112
+ * @returns Key pair
113
+ */
114
+ export function generateKeyPair (raw: true): { publicKey: Buffer, secretKey: Buffer }
115
+ export function generateKeyPair (raw?: false): { publicKey: EncodedData<'ak'>, secretKey: string }
116
+ export function generateKeyPair (raw: boolean = false): {
117
+ publicKey: EncodedData<'ak'> | Buffer
118
+ secretKey: string | Buffer
119
+ } {
120
+ const keyPair = nacl.sign.keyPair()
121
+ const publicBuffer = Buffer.from(keyPair.publicKey)
122
+ const secretBuffer = Buffer.from(keyPair.secretKey)
123
+
124
+ if (raw) {
125
+ return {
126
+ publicKey: publicBuffer,
127
+ secretKey: secretBuffer
128
+ }
129
+ } else {
130
+ return {
131
+ publicKey: encode(publicBuffer, 'ak'),
132
+ secretKey: secretBuffer.toString('hex')
133
+ }
134
+ }
135
+ }
136
+
137
+ /**
138
+ * Encrypt given data using `password`
139
+ * @param password - Password to encrypt with
140
+ * @param binaryData - Data to encrypt
141
+ * @returns Encrypted data
142
+ */
143
+ export function encryptKey (password: string, binaryData: Uint8Array): Uint8Array {
144
+ const hashedPasswordBytes = sha256hash(password)
145
+ const aesEcb = new Ecb(hashedPasswordBytes)
146
+ return aesEcb.encrypt(binaryData)
147
+ }
148
+
149
+ /**
150
+ * Decrypt given data using `password`
151
+ * @param password - Password to decrypt with
152
+ * @param encrypted - Data to decrypt
153
+ * @returns Decrypted data
154
+ */
155
+ export function decryptKey (password: string, encrypted: Uint8Array): Uint8Array {
156
+ const encryptedBytes = Buffer.from(encrypted)
157
+ const hashedPasswordBytes = sha256hash(password)
158
+ const aesEcb = new Ecb(hashedPasswordBytes)
159
+ return aesEcb.decrypt(encryptedBytes)
160
+ }
161
+
162
+ // SIGNATURES
163
+
164
+ /**
165
+ * Generate signature
166
+ * @param data - Data to sign
167
+ * @param privateKey - Key to sign with
168
+ * @returns Signature
169
+ */
170
+ export function sign (data: string | Uint8Array, privateKey: string | Uint8Array): Uint8Array {
171
+ return nacl.sign.detached(Buffer.from(data), Buffer.from(privateKey))
172
+ }
173
+
174
+ /**
175
+ * Verify that signature was signed by public key
176
+ * @param data - Data to verify
177
+ * @param signature - Signature to verify
178
+ * @param publicKey - Key to verify against
179
+ * @returns Valid?
180
+ */
181
+ export function verify (
182
+ data: Uint8Array, signature: Uint8Array, publicKey: string | Uint8Array
183
+ ): boolean {
184
+ const publicKeyBuffer = typeof publicKey === 'string' ? str2buf(publicKey) : publicKey
185
+ return nacl.sign.detached.verify(data, signature, publicKeyBuffer)
186
+ }
187
+
188
+ export function messageToHash (message: string): Buffer {
189
+ const p = Buffer.from('aeternity Signed Message:\n', 'utf8')
190
+ const msg = Buffer.from(message, 'utf8')
191
+ return hash(concatBuffers([varuintEncode(p.length), p, varuintEncode(msg.length), msg]))
192
+ }
193
+
194
+ export function signMessage (message: string, privateKey: string | Buffer): Uint8Array {
195
+ return sign(messageToHash(message), privateKey)
196
+ }
197
+
198
+ export function verifyMessage (
199
+ str: string, signature: Uint8Array, publicKey: string | Uint8Array): boolean {
200
+ return verify(messageToHash(str), signature, publicKey)
201
+ }
202
+
203
+ /**
204
+ * Check key pair for validity
205
+ *
206
+ * Sign a message, and then verifying that signature
207
+ * @param privateKey - Private key to verify
208
+ * @param publicKey - Public key to verify
209
+ * @returns Valid?
210
+ */
211
+ export function isValidKeypair (
212
+ privateKey: string | Uint8Array, publicKey: string | Uint8Array
213
+ ): boolean {
214
+ const message = Buffer.from('TheMessage')
215
+ const signature = sign(message, privateKey)
216
+ return verify(message, signature, publicKey)
217
+ }
@@ -1,101 +1,98 @@
1
- import * as bs58 from 'bs58'
2
- import { sha256 } from 'sha.js'
1
+ import { encode as bs58Encode, decode as bs58Decode } from 'bs58'
2
+ import { sha256 as Sha256 } from 'sha.js'
3
3
  import {
4
4
  DecodeError,
5
- EncodeError,
5
+ ArgumentError,
6
6
  InvalidChecksumError,
7
- PayloadLengthError,
8
- PrefixMismatchError
7
+ PayloadLengthError
9
8
  } from './errors'
9
+ import { concatBuffers } from './other'
10
10
 
11
11
  /**
12
12
  * Calculate SHA256 hash of `input`
13
- * @rtype (input: String) => hash: String
14
- * @param {Buffer|String} input - Data to hash
15
- * @return {String} Hash
13
+ * @param input - Data to hash
14
+ * @returns Hash
16
15
  */
17
- export function sha256hash (input: Buffer | string) {
18
- return new sha256().update(input).digest()
16
+ export function sha256hash (input: Uint8Array | string): Buffer {
17
+ return new Sha256().update(input).digest()
19
18
  }
20
19
 
21
20
  // based on https://github.com/aeternity/protocol/blob/master/node/api/api_encoding.md
22
- const base64Types = ['ba', 'cb', 'or', 'ov', 'pi', 'ss', 'cs', 'ck', 'cv', 'st', 'tx']
23
- const base58Types = ['ak', 'bf', 'bs', 'bx', 'ch', 'cm', 'ct', 'kh', 'mh', 'nm', 'ok', 'oq', 'pp', 'sg', 'th']
21
+ const base64Types = ['ba', 'cb', 'or', 'ov', 'pi', 'ss', 'cs', 'ck', 'cv', 'st', 'tx'] as const
22
+ const base58Types = ['ak', 'bf', 'bs', 'bx', 'ch', 'cm', 'ct', 'kh', 'mh', 'nm', 'ok', 'oq', 'pp', 'sg', 'th'] as const
23
+
24
+ export type EncodingType = typeof base64Types[number] | typeof base58Types[number]
25
+ export type EncodedData<Type extends EncodingType> = `${Type}_${string}`
24
26
  // TODO: add all types with a fixed length
25
- const typesLength: { [name: string]: number } = {
27
+ const typesLength: { [name in EncodingType]?: number } = {
26
28
  ak: 32,
27
29
  ct: 32,
28
30
  ok: 32
29
31
  } as const
30
32
 
31
- function ensureValidLength (data: Buffer | string, type: string) {
32
- if (!typesLength[type]) return
33
- if (data.length === typesLength[type]) return
34
- throw new PayloadLengthError(`Payload should be ${typesLength[type]} bytes, got ${data.length} instead`)
33
+ function ensureValidLength (data: Uint8Array, type: EncodingType): void {
34
+ const reqLen = typesLength[type]
35
+ if (reqLen == null || data.length === reqLen) return
36
+ throw new PayloadLengthError(`Payload should be ${reqLen} bytes, got ${data.length} instead`)
35
37
  }
36
38
 
37
- const getChecksum = (payload: Buffer | string) => sha256hash(sha256hash(payload)).slice(0, 4)
39
+ const getChecksum = (payload: Uint8Array): Buffer =>
40
+ sha256hash(sha256hash(payload)).slice(0, 4)
38
41
 
39
- const addChecksum = (input: Buffer | string) => {
40
- const payload = Buffer.from(input)
41
- return Buffer.concat([payload, getChecksum(payload)])
42
+ const addChecksum = (payload: Uint8Array): Buffer => {
43
+ return concatBuffers([payload, getChecksum(payload)])
42
44
  }
43
45
 
44
- function getPayload (buffer: Buffer) {
46
+ function getPayload (buffer: Buffer): Buffer {
45
47
  const payload = buffer.slice(0, -4)
46
48
  if (!getChecksum(payload).equals(buffer.slice(-4))) throw new InvalidChecksumError()
47
49
  return payload
48
50
  }
49
51
 
50
52
  const base64 = {
51
- encode: (buffer: Buffer | string) => addChecksum(buffer).toString('base64'),
53
+ encode: (buffer: Uint8Array) => addChecksum(buffer).toString('base64'),
52
54
  decode: (string: string) => getPayload(Buffer.from(string, 'base64'))
53
55
  }
54
56
 
55
57
  const base58 = {
56
- encode: (buffer: Buffer | string) => bs58.encode(addChecksum(buffer)),
57
- decode: (string: string) => getPayload(bs58.decode(string))
58
+ encode: (buffer: Uint8Array) => bs58Encode(addChecksum(buffer)),
59
+ decode: (string: string) => getPayload(Buffer.from(bs58Decode(string)))
60
+ }
61
+
62
+ const parseType = (maybeType: unknown): [EncodingType, typeof base64] => {
63
+ const base64Type = base64Types.find(t => t === maybeType)
64
+ if (base64Type != null) return [base64Type, base64]
65
+ const base58Type = base58Types.find(t => t === maybeType)
66
+ if (base58Type != null) return [base58Type, base58]
67
+ throw new ArgumentError('prefix', `one of ${[...base58Types, ...base64Types].join(', ')}`, maybeType)
58
68
  }
59
69
 
60
70
  /**
61
71
  * Decode data using the default encoding/decoding algorithm
62
- * @function
63
- * @alias module:@aeternity/aepp-sdk/es/tx/builder/helpers
64
- * @param {string} data An Base58/64check encoded and prefixed string (ex tx_..., sg_..., ak_....)
65
- * @param {string} [requiredPrefix] Ensure that data have this prefix
66
- * @return {Buffer} Decoded data
72
+ * @param data - An Base58/64check encoded and prefixed string
73
+ * (ex tx_..., sg_..., ak_....)
74
+ * @returns Decoded data
67
75
  */
68
- export function decode (data: string, requiredPrefix?: string) {
76
+ export function decode (data: EncodedData<EncodingType>): Buffer {
69
77
  const [prefix, encodedPayload, extra] = data.split('_')
70
- if (!encodedPayload) throw new DecodeError(`Encoded string missing payload: ${data}`)
71
- if (extra) throw new DecodeError(`Encoded string have extra parts: ${data}`)
72
- if (requiredPrefix && requiredPrefix !== prefix) {
73
- throw new PrefixMismatchError(prefix, requiredPrefix)
74
- }
75
- const decoder = (base64Types.includes(prefix) && base64.decode) ||
76
- (base58Types.includes(prefix) && base58.decode)
77
- if (!decoder) {
78
- throw new DecodeError(`Encoded string have unknown type: ${prefix}`)
79
- }
80
- const payload = decoder(encodedPayload)
81
- ensureValidLength(payload, prefix)
78
+ if (encodedPayload == null) throw new DecodeError(`Encoded string missing payload: ${data}`)
79
+ if (extra != null) throw new DecodeError(`Encoded string have extra parts: ${data}`)
80
+ const [type, { decode }] = parseType(prefix)
81
+ const payload = decode(encodedPayload)
82
+ ensureValidLength(payload, type)
82
83
  return payload
83
84
  }
84
85
 
85
86
  /**
86
87
  * Encode data using the default encoding/decoding algorithm
87
- * @function
88
- * @alias module:@aeternity/aepp-sdk/es/tx/builder/helpers
89
- * @param {Buffer|String} data An decoded data
90
- * @param {string} type Prefix of Transaction
91
- * @return {String} Encoded string Base58check or Base64check data
88
+ * @param data - An decoded data
89
+ * @param type - Prefix of Transaction
90
+ * @returns Encoded string Base58check or Base64check data
92
91
  */
93
- export function encode (data: Buffer | string, type: string) {
94
- const encoder = (base64Types.includes(type) && base64.encode) ||
95
- (base58Types.includes(type) && base58.encode)
96
- if (!encoder) {
97
- throw new EncodeError(`Unknown type: ${type}`)
98
- }
92
+ export function encode<Type extends EncodingType> (
93
+ data: Uint8Array, type: Type
94
+ ): EncodedData<Type> {
95
+ const [, { encode }] = parseType(type)
99
96
  ensureValidLength(data, type)
100
- return `${type}_${encoder(data)}`
97
+ return `${type}_${encode(data)}`
101
98
  }