@aeternity/aepp-sdk 12.0.0 → 12.1.2

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 (283) hide show
  1. package/dist/aepp-sdk.browser-script.js +1 -1
  2. package/dist/aepp-sdk.browser-script.js.LICENSE.txt +0 -15
  3. package/dist/aepp-sdk.browser-script.js.map +1 -1
  4. package/dist/aepp-sdk.browser.js +2 -1
  5. package/dist/aepp-sdk.browser.js.LICENSE.txt +1 -0
  6. package/dist/aepp-sdk.browser.js.map +1 -1
  7. package/dist/aepp-sdk.js +20765 -1
  8. package/dist/aepp-sdk.js.map +1 -1
  9. package/es/AeSdk.d.ts +7 -7
  10. package/es/AeSdk.mjs.map +1 -1
  11. package/es/AeSdkAepp.d.ts +4 -3
  12. package/es/AeSdkAepp.mjs +2 -1
  13. package/es/AeSdkAepp.mjs.map +1 -1
  14. package/es/AeSdkBase.d.ts +22 -21
  15. package/es/AeSdkBase.mjs +25 -21
  16. package/es/AeSdkBase.mjs.map +1 -1
  17. package/es/AeSdkWallet.d.ts +4 -3
  18. package/es/AeSdkWallet.mjs +5 -1
  19. package/es/AeSdkWallet.mjs.map +1 -1
  20. package/es/Node.d.ts +7 -10
  21. package/es/Node.mjs +63 -57
  22. package/es/Node.mjs.map +1 -1
  23. package/es/account/Base.d.ts +7 -4
  24. package/es/account/Base.mjs +3 -3
  25. package/es/account/Base.mjs.map +1 -1
  26. package/es/account/Memory.d.ts +5 -4
  27. package/es/account/Memory.mjs +24 -2
  28. package/es/account/Memory.mjs.map +1 -1
  29. package/es/account/Rpc.d.ts +6 -6
  30. package/es/account/Rpc.mjs +3 -2
  31. package/es/account/Rpc.mjs.map +1 -1
  32. package/es/aens.d.ts +27 -14
  33. package/es/aens.mjs +27 -21
  34. package/es/aens.mjs.map +1 -1
  35. package/es/aepp-wallet-communication/connection/Browser.d.ts +2 -1
  36. package/es/aepp-wallet-communication/connection/Browser.mjs +5 -2
  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 +1 -0
  40. package/es/aepp-wallet-communication/connection/BrowserRuntime.mjs.map +1 -1
  41. package/es/aepp-wallet-communication/connection/BrowserWindowMessage.d.ts +1 -0
  42. package/es/aepp-wallet-communication/connection/BrowserWindowMessage.mjs +5 -1
  43. package/es/aepp-wallet-communication/connection/BrowserWindowMessage.mjs.map +1 -1
  44. package/es/aepp-wallet-communication/connection-proxy.d.ts +1 -0
  45. package/es/aepp-wallet-communication/connection-proxy.mjs +1 -0
  46. package/es/aepp-wallet-communication/connection-proxy.mjs.map +1 -1
  47. package/es/aepp-wallet-communication/rpc/RpcClient.d.ts +1 -0
  48. package/es/aepp-wallet-communication/rpc/RpcClient.mjs +5 -5
  49. package/es/aepp-wallet-communication/rpc/RpcClient.mjs.map +1 -1
  50. package/es/aepp-wallet-communication/rpc/types.d.ts +8 -8
  51. package/es/aepp-wallet-communication/rpc/types.mjs.map +1 -1
  52. package/es/aepp-wallet-communication/schema.d.ts +17 -2
  53. package/es/aepp-wallet-communication/schema.mjs +54 -17
  54. package/es/aepp-wallet-communication/schema.mjs.map +1 -1
  55. package/es/aepp-wallet-communication/wallet-detector.d.ts +2 -1
  56. package/es/aepp-wallet-communication/wallet-detector.mjs +2 -3
  57. package/es/aepp-wallet-communication/wallet-detector.mjs.map +1 -1
  58. package/es/apis/node/models/index.d.ts +6 -2
  59. package/es/apis/node/models/index.mjs.map +1 -1
  60. package/es/apis/node/models/mappers.mjs +4 -2
  61. package/es/apis/node/models/mappers.mjs.map +1 -1
  62. package/es/chain.d.ts +92 -64
  63. package/es/chain.mjs +190 -154
  64. package/es/chain.mjs.map +1 -1
  65. package/es/channel/handlers.d.ts +3 -3
  66. package/es/channel/handlers.mjs +42 -44
  67. package/es/channel/handlers.mjs.map +1 -1
  68. package/es/channel/index.d.ts +43 -52
  69. package/es/channel/index.mjs +46 -49
  70. package/es/channel/index.mjs.map +1 -1
  71. package/es/channel/internal.d.ts +16 -15
  72. package/es/channel/internal.mjs +67 -62
  73. package/es/channel/internal.mjs.map +1 -1
  74. package/es/contract/Compiler.d.ts +1 -0
  75. package/es/contract/Compiler.mjs +5 -4
  76. package/es/contract/Compiler.mjs.map +1 -1
  77. package/es/contract/aci.d.ts +17 -15
  78. package/es/contract/aci.mjs +58 -45
  79. package/es/contract/aci.mjs.map +1 -1
  80. package/es/contract/ga.d.ts +16 -15
  81. package/es/contract/ga.mjs +12 -7
  82. package/es/contract/ga.mjs.map +1 -1
  83. package/es/contract/methods.d.ts +9 -6
  84. package/es/contract/methods.mjs +9 -6
  85. package/es/contract/methods.mjs.map +1 -1
  86. package/es/deprecated/index.d.ts +143 -0
  87. package/es/deprecated/index.mjs +162 -0
  88. package/es/deprecated/index.mjs.map +1 -0
  89. package/es/deprecated/methods.d.ts +18 -0
  90. package/es/deprecated/methods.mjs +26 -0
  91. package/es/deprecated/methods.mjs.map +1 -0
  92. package/es/index.d.ts +4 -1
  93. package/es/index.mjs +4 -1
  94. package/es/index.mjs.map +1 -1
  95. package/es/oracle.d.ts +69 -62
  96. package/es/oracle.mjs +121 -103
  97. package/es/oracle.mjs.map +1 -1
  98. package/es/spend.d.ts +16 -15
  99. package/es/spend.mjs +19 -30
  100. package/es/spend.mjs.map +1 -1
  101. package/es/tx/builder/address.d.ts +25 -0
  102. package/es/tx/builder/address.mjs +45 -0
  103. package/es/tx/builder/address.mjs.map +1 -0
  104. package/es/tx/builder/constants.d.ts +55 -26
  105. package/es/tx/builder/constants.mjs +60 -38
  106. package/es/tx/builder/constants.mjs.map +1 -1
  107. package/es/tx/builder/field-types/coin-amount.d.ts +13 -0
  108. package/es/tx/builder/field-types/coin-amount.mjs +26 -0
  109. package/es/tx/builder/field-types/coin-amount.mjs.map +1 -0
  110. package/es/tx/builder/field-types/deposit.d.ts +15 -0
  111. package/es/tx/builder/field-types/deposit.mjs +19 -0
  112. package/es/tx/builder/field-types/deposit.mjs.map +1 -0
  113. package/es/tx/builder/field-types/fee.d.ts +25 -0
  114. package/es/tx/{min-fee.mjs → builder/field-types/fee.mjs} +62 -60
  115. package/es/tx/builder/field-types/fee.mjs.map +1 -0
  116. package/es/tx/builder/field-types/field.d.ts +6 -0
  117. package/es/tx/builder/field-types/field.mjs +15 -0
  118. package/es/tx/builder/field-types/field.mjs.map +1 -0
  119. package/es/tx/builder/field-types/gas-limit.d.ts +12 -0
  120. package/es/tx/builder/field-types/gas-limit.mjs +33 -0
  121. package/es/tx/builder/field-types/gas-limit.mjs.map +1 -0
  122. package/es/tx/builder/field-types/gas-price.d.ts +8 -0
  123. package/es/tx/builder/field-types/gas-price.mjs +18 -0
  124. package/es/tx/builder/field-types/gas-price.mjs.map +1 -0
  125. package/es/tx/builder/field-types/index.d.ts +70 -0
  126. package/es/tx/builder/field-types/index.mjs +25 -0
  127. package/es/tx/builder/field-types/index.mjs.map +1 -0
  128. package/es/tx/builder/field-types/name-fee.d.ts +20 -0
  129. package/es/tx/builder/field-types/name-fee.mjs +24 -0
  130. package/es/tx/builder/field-types/name-fee.mjs.map +1 -0
  131. package/es/tx/builder/field-types/name-id.d.ts +14 -0
  132. package/es/tx/builder/field-types/name-id.mjs +19 -0
  133. package/es/tx/builder/field-types/name-id.mjs.map +1 -0
  134. package/es/tx/builder/field-types/name.d.ts +13 -0
  135. package/es/tx/builder/field-types/name.mjs +18 -0
  136. package/es/tx/builder/field-types/name.mjs.map +1 -0
  137. package/es/tx/builder/field-types/short-u-int.d.ts +6 -0
  138. package/es/tx/builder/field-types/short-u-int.mjs +12 -0
  139. package/es/tx/builder/field-types/short-u-int.mjs.map +1 -0
  140. package/es/tx/builder/field-types/u-int.d.ts +8 -0
  141. package/es/tx/builder/field-types/u-int.mjs +14 -0
  142. package/es/tx/builder/field-types/u-int.mjs.map +1 -0
  143. package/es/tx/builder/helpers.d.ts +27 -33
  144. package/es/tx/builder/helpers.mjs +41 -47
  145. package/es/tx/builder/helpers.mjs.map +1 -1
  146. package/es/tx/builder/index.d.ts +25 -12
  147. package/es/tx/builder/index.mjs +74 -83
  148. package/es/tx/builder/index.mjs.map +1 -1
  149. package/es/tx/builder/schema.d.ts +995 -144
  150. package/es/tx/builder/schema.mjs +121 -170
  151. package/es/tx/builder/schema.mjs.map +1 -1
  152. package/es/tx/index.d.ts +28 -27
  153. package/es/tx/index.mjs +97 -117
  154. package/es/tx/index.mjs.map +1 -1
  155. package/es/tx/validator.d.ts +4 -3
  156. package/es/tx/validator.mjs +79 -92
  157. package/es/tx/validator.mjs.map +1 -1
  158. package/es/typings/@aeternity__argon2-browser/index.d.mjs.map +1 -1
  159. package/es/typings/@aeternity__uuid/index.d.mjs.map +1 -1
  160. package/es/typings/bip32-path/index.d.mjs.map +1 -1
  161. package/es/typings/blakejs/index.d.mjs.map +1 -1
  162. package/es/typings/sha-js/index.d.mjs +2 -0
  163. package/es/typings/sha-js/index.d.mjs.map +1 -0
  164. package/es/typings/tweetnacl-auth/index.d.mjs.map +1 -1
  165. package/es/utils/amount-formatter.d.ts +9 -9
  166. package/es/utils/amount-formatter.mjs +17 -17
  167. package/es/utils/amount-formatter.mjs.map +1 -1
  168. package/es/utils/autorest.mjs +7 -7
  169. package/es/utils/autorest.mjs.map +1 -1
  170. package/es/utils/bignumber.mjs +2 -1
  171. package/es/utils/bignumber.mjs.map +1 -1
  172. package/es/utils/bytes.mjs +1 -1
  173. package/es/utils/bytes.mjs.map +1 -1
  174. package/es/utils/crypto.d.ts +8 -23
  175. package/es/utils/crypto.mjs +15 -41
  176. package/es/utils/crypto.mjs.map +1 -1
  177. package/es/utils/encoder-types.d.ts +61 -0
  178. package/es/utils/encoder-types.mjs +36 -0
  179. package/es/utils/encoder-types.mjs.map +1 -0
  180. package/es/utils/encoder.d.ts +6 -7
  181. package/es/utils/encoder.mjs +42 -26
  182. package/es/utils/encoder.mjs.map +1 -1
  183. package/es/utils/errors.d.ts +1 -11
  184. package/es/utils/errors.mjs +4 -20
  185. package/es/utils/errors.mjs.map +1 -1
  186. package/es/utils/hd-wallet.d.ts +18 -2
  187. package/es/utils/hd-wallet.mjs +64 -34
  188. package/es/utils/hd-wallet.mjs.map +1 -1
  189. package/es/utils/json-big.mjs +2 -2
  190. package/es/utils/json-big.mjs.map +1 -1
  191. package/es/utils/keystore.mjs +4 -2
  192. package/es/utils/keystore.mjs.map +1 -1
  193. package/es/utils/mptree.d.ts +2 -2
  194. package/es/utils/mptree.mjs +11 -6
  195. package/es/utils/mptree.mjs.map +1 -1
  196. package/es/utils/other.d.ts +8 -2
  197. package/es/utils/other.mjs +15 -3
  198. package/es/utils/other.mjs.map +1 -1
  199. package/es/utils/semver-satisfies.d.ts +1 -1
  200. package/es/utils/semver-satisfies.mjs +2 -2
  201. package/es/utils/semver-satisfies.mjs.map +1 -1
  202. package/es/utils/string.mjs.map +1 -1
  203. package/package.json +36 -34
  204. package/src/AeSdk.ts +30 -27
  205. package/src/AeSdkAepp.ts +93 -84
  206. package/src/AeSdkBase.ts +148 -130
  207. package/src/AeSdkWallet.ts +172 -156
  208. package/src/Node.ts +108 -102
  209. package/src/account/Base.ts +42 -32
  210. package/src/account/Memory.ts +45 -30
  211. package/src/account/Rpc.ts +32 -30
  212. package/src/aens.ts +124 -108
  213. package/src/aepp-wallet-communication/connection/Browser.ts +18 -15
  214. package/src/aepp-wallet-communication/connection/BrowserRuntime.ts +22 -21
  215. package/src/aepp-wallet-communication/connection/BrowserWindowMessage.ts +63 -52
  216. package/src/aepp-wallet-communication/connection-proxy.ts +8 -7
  217. package/src/aepp-wallet-communication/rpc/RpcClient.ts +67 -61
  218. package/src/aepp-wallet-communication/rpc/types.ts +32 -32
  219. package/src/aepp-wallet-communication/schema.ts +117 -74
  220. package/src/aepp-wallet-communication/wallet-detector.ts +29 -28
  221. package/src/apis/node/code-model-v4.yaml +54 -20
  222. package/src/apis/node/models/index.ts +6 -2
  223. package/src/apis/node/models/mappers.ts +4 -2
  224. package/src/chain.ts +286 -228
  225. package/src/channel/handlers.ts +424 -372
  226. package/src/channel/index.ts +285 -251
  227. package/src/channel/internal.ts +248 -232
  228. package/src/contract/Compiler.ts +22 -21
  229. package/src/contract/aci.ts +267 -258
  230. package/src/contract/ga.ts +93 -72
  231. package/src/contract/methods.ts +32 -27
  232. package/src/deprecated/index.ts +172 -0
  233. package/src/deprecated/methods.ts +25 -0
  234. package/src/index.ts +37 -32
  235. package/src/oracle.ts +211 -189
  236. package/src/spend.ts +82 -70
  237. package/src/tx/builder/address.ts +50 -0
  238. package/src/tx/builder/constants.ts +82 -52
  239. package/src/tx/builder/field-types/coin-amount.ts +27 -0
  240. package/src/tx/builder/field-types/deposit.ts +21 -0
  241. package/src/tx/builder/field-types/fee.ts +143 -0
  242. package/src/tx/builder/field-types/field.ts +9 -0
  243. package/src/tx/builder/field-types/gas-limit.ts +41 -0
  244. package/src/tx/builder/field-types/gas-price.ts +16 -0
  245. package/src/tx/builder/field-types/index.ts +45 -0
  246. package/src/tx/builder/field-types/name-fee.ts +32 -0
  247. package/src/tx/builder/field-types/name-id.ts +20 -0
  248. package/src/tx/builder/field-types/name.ts +18 -0
  249. package/src/tx/builder/field-types/short-u-int.ts +11 -0
  250. package/src/tx/builder/field-types/u-int.ts +16 -0
  251. package/src/tx/builder/helpers.ts +112 -117
  252. package/src/tx/builder/index.ts +203 -197
  253. package/src/tx/builder/schema.ts +421 -465
  254. package/src/tx/index.ts +128 -135
  255. package/src/tx/validator.ts +165 -161
  256. package/src/typings/@aeternity__argon2-browser/index.d.ts +1 -1
  257. package/src/typings/@aeternity__uuid/index.d.ts +3 -1
  258. package/src/typings/bip32-path/index.d.ts +6 -6
  259. package/src/typings/blakejs/index.d.ts +4 -32
  260. package/src/typings/sha-js/index.d.ts +5 -0
  261. package/src/typings/tweetnacl-auth/index.d.ts +2 -2
  262. package/src/utils/amount-formatter.ts +41 -41
  263. package/src/utils/autorest.ts +57 -54
  264. package/src/utils/bignumber.ts +7 -6
  265. package/src/utils/bytes.ts +19 -19
  266. package/src/utils/crypto.ts +82 -94
  267. package/src/utils/encoder-types.ts +63 -0
  268. package/src/utils/encoder.ts +104 -56
  269. package/src/utils/errors.ts +246 -264
  270. package/src/utils/hd-wallet.ts +114 -82
  271. package/src/utils/json-big.ts +16 -15
  272. package/src/utils/keystore.ts +65 -62
  273. package/src/utils/mptree.ts +59 -56
  274. package/src/utils/other.ts +26 -18
  275. package/src/utils/semver-satisfies.ts +15 -11
  276. package/src/utils/string.ts +10 -10
  277. package/es/tx/builder/field-types.d.ts +0 -62
  278. package/es/tx/builder/field-types.mjs +0 -126
  279. package/es/tx/builder/field-types.mjs.map +0 -1
  280. package/es/tx/min-fee.d.ts +0 -20
  281. package/es/tx/min-fee.mjs.map +0 -1
  282. package/src/tx/builder/field-types.ts +0 -111
  283. package/src/tx/min-fee.ts +0 -136
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","names":["ABI_VERSIONS","PROTOCOL_VM_ABI","TX_TYPE","TX_TTL","ArgumentError","UnsupportedProtocolError","UnknownTxError","InvalidTxParamsError","BigNumber","buildTx","syncBuildTx","unpackTx","calculateMinFee","isKeyOfObject","_buildTx","txType","denomination","absoluteTtl","_params","params","senderKey","spend","oracleQuery","nameClaim","nameUpdate","nameRevoke","nameTransfer","namePreClaim","oracleRegister","contractCreate","gaAttach","contractCall","oracleExtend","oracleResponse","channelCloseSolo","channelSlash","channelSettle","channelSnapshotSolo","payingFor","ctVersion","getVmVersion","abiVersion","NO_ABI","tx","senderId","extraParams","prepareTxParams","vmVersion","onNode","consensusProtocolVersion","getNodeInfo","supportedProtocol","protocolForTX","nonce","ttl","fee","f","vsn","strategy","txParams","getAccountNextNonce","catch","nextNonce","getCurrentKeyBlock","height"],"sources":["../../src/tx/index.ts"],"sourcesContent":["/*\n * ISC License (ISC)\n * Copyright (c) 2022 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 */\n\n/**\n * Transaction methods\n *\n * This is implementation of [Tx](api/tx.md) relays\n * the creation of transactions to {@link Node}.\n * These methods provide ability to create native transactions.\n */\nimport {\n ABI_VERSIONS, CtVersion, PROTOCOL_VM_ABI, TX_TYPE, TX_TTL, TxParamsCommon\n} from './builder/schema'\nimport {\n ArgumentError, UnsupportedProtocolError, UnknownTxError, InvalidTxParamsError\n} from '../utils/errors'\nimport BigNumber from 'bignumber.js'\nimport Node from '../Node'\nimport { EncodedData } from '../utils/encoder'\nimport { buildTx as syncBuildTx, unpackTx } from './builder/index'\nimport calculateMinFee from './min-fee'\nimport { isKeyOfObject } from '../utils/other'\nimport { AE_AMOUNT_FORMATS } from '../utils/amount-formatter'\n\ntype Int = number | string | BigNumber\n\n// uses a new feature, probably typescript-eslint doesn't support it yet\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nexport type BuildTxOptions <TxType extends TX_TYPE, OmitFields extends string> =\n Omit<Parameters<typeof _buildTx<TxType>>[1], OmitFields>\n\n// TODO: find a better name or rearrange methods\nexport async function _buildTx<TxType extends TX_TYPE> (\n txType: TxType,\n { denomination, absoluteTtl, ..._params }:\n Omit<Parameters<typeof syncBuildTx<TxType, 'tx'>>[0], 'fee' | 'nonce' | 'ttl' | 'ctVersion' | 'abiVersion'>\n & {\n onNode: Node\n fee?: Int\n nonce?: number\n ttl?: number\n denomination?: AE_AMOUNT_FORMATS\n absoluteTtl?: boolean\n }\n & (TxType extends TX_TYPE.oracleExtend | TX_TYPE.oracleResponse ? { callerId: EncodedData<'ak'> } : {})\n & (TxType extends TX_TYPE.contractCreate | TX_TYPE.gaAttach ? { ctVersion?: CtVersion } : {})\n & (TxType extends TX_TYPE.contractCall | TX_TYPE.oracleRegister\n ? { abiVersion?: ABI_VERSIONS } : {})\n): Promise<EncodedData<'tx'>> {\n // TODO: avoid this assertion\n const params = _params as unknown as TxParamsCommon & { onNode: Node }\n let senderKey: keyof TxParamsCommon | '<absent>'\n switch (txType) {\n case TX_TYPE.spend:\n case TX_TYPE.oracleQuery:\n senderKey = 'senderId'\n break\n case TX_TYPE.nameClaim:\n case TX_TYPE.nameUpdate:\n case TX_TYPE.nameRevoke:\n case TX_TYPE.nameTransfer:\n case TX_TYPE.namePreClaim:\n case TX_TYPE.oracleRegister:\n senderKey = 'accountId'\n break\n case TX_TYPE.contractCreate:\n case TX_TYPE.gaAttach:\n senderKey = 'ownerId'\n break\n case TX_TYPE.contractCall:\n case TX_TYPE.oracleExtend:\n case TX_TYPE.oracleResponse:\n senderKey = 'callerId'\n break\n case TX_TYPE.channelCloseSolo:\n case TX_TYPE.channelSlash:\n case TX_TYPE.channelSettle:\n case TX_TYPE.channelSnapshotSolo:\n senderKey = 'fromId'\n break\n case TX_TYPE.payingFor:\n senderKey = 'payerId'\n break\n default:\n throw new ArgumentError('txType', 'valid transaction type', txType)\n }\n // TODO: move specific cases to field-types\n if ([TX_TYPE.contractCreate, TX_TYPE.gaAttach].includes(txType)) {\n params.ctVersion = await getVmVersion(\n TX_TYPE.contractCreate, { ...params, ...params.ctVersion }\n )\n }\n if (txType === TX_TYPE.contractCall) {\n params.abiVersion = (await getVmVersion(TX_TYPE.contractCall, params)).abiVersion\n }\n if (txType === TX_TYPE.oracleRegister) {\n params.abiVersion ??= ABI_VERSIONS.NO_ABI\n }\n if (txType === TX_TYPE.payingFor) {\n params.tx = unpackTx(params.tx)\n }\n const senderId = params[senderKey]\n // TODO: do this check on TypeScript level\n if (senderId == null) throw new InvalidTxParamsError(`Transaction field ${senderKey} is missed`)\n const extraParams = await prepareTxParams(\n txType, { ...params, senderId, denomination, absoluteTtl }\n )\n return syncBuildTx({ ...params, ...extraParams } as any, txType, { denomination }).tx\n}\n\n/**\n * Validated vm/abi version or get default based on transaction type and NODE version\n *\n * @param txType - Type of transaction\n * @param ctVersion - Object with vm and abi version fields\n * @returns Object with vm/abi version\n */\nexport async function getVmVersion (\n txType: TX_TYPE.contractCreate, ctVersion: Partial<CtVersion> & { onNode: Node }\n): Promise<CtVersion>\nexport async function getVmVersion (\n txType: TX_TYPE, ctVersion: Partial<Pick<CtVersion, 'abiVersion'>> & { onNode: Node }\n): Promise<Pick<CtVersion, 'abiVersion'>>\nexport async function getVmVersion (\n txType: TX_TYPE, { vmVersion, abiVersion, onNode }: Partial<CtVersion> & { onNode: Node }\n): Promise<Partial<CtVersion>> {\n const { consensusProtocolVersion } = await onNode.getNodeInfo()\n if (!isKeyOfObject(consensusProtocolVersion, PROTOCOL_VM_ABI)) {\n throw new UnsupportedProtocolError('Not supported consensus protocol version')\n }\n const supportedProtocol = PROTOCOL_VM_ABI[consensusProtocolVersion]\n if (!isKeyOfObject(txType, supportedProtocol)) {\n throw new UnknownTxError('Not supported tx type')\n }\n const protocolForTX = supportedProtocol[txType]\n abiVersion ??= protocolForTX.abiVersion[0]\n vmVersion ??= protocolForTX.vmVersion[0]\n return { vmVersion, abiVersion }\n}\n\n/**\n * Calculate fee, get absolute ttl (ttl + height), get account nonce\n *\n * @param txType - Type of transaction\n * @param params - Object which contains all tx data\n * @returns Object with account nonce, absolute ttl and transaction fee\n */\nexport async function prepareTxParams (\n txType: TX_TYPE,\n {\n senderId,\n nonce,\n ttl = TX_TTL,\n fee: f,\n absoluteTtl,\n vsn,\n strategy,\n denomination,\n onNode,\n ...txParams\n }: PrepareTxParamsOptions\n): Promise<{ fee: BigNumber, ttl: number, nonce: number }> {\n nonce ??= (\n await onNode.getAccountNextNonce(senderId, { strategy }).catch(() => ({ nextNonce: 1 }))\n ).nextNonce\n\n if (ttl !== 0) {\n if (ttl < 0) throw new ArgumentError('ttl', 'greater or equal to 0', ttl)\n ttl += absoluteTtl === true ? 0 : (await onNode.getCurrentKeyBlock()).height\n }\n\n const fee = f != null\n ? new BigNumber(f)\n : calculateMinFee(txType, { params: { ...txParams, senderId, nonce, ttl }, vsn, denomination })\n return { fee, ttl, nonce }\n}\n\ninterface PrepareTxParamsOptions extends Pick<TxParamsCommon, 'nonce' | 'ttl' | 'fee'> {\n senderId: EncodedData<'ak'>\n vsn?: number\n absoluteTtl?: boolean\n strategy?: 'continuity' | 'max'\n denomination?: AE_AMOUNT_FORMATS\n onNode: Node\n}\n"],"mappings":";;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;SAEEA,Y,EAAyBC,e,EAAiBC,O,EAASC,M;SAGnDC,a,EAAeC,wB,EAA0BC,c,EAAgBC,oB;AAE3D,OAAOC,SAAP,MAAsB,cAAtB;SAGSC,OAAO,IAAIC,W,EAAaC,Q;OAC1BC,e;SACEC,a;AAUT;AACA,OAAO,eAAeC,QAAf,CACLC,MADK,QAgBuB;EAAA;;EAAA,IAd5B;IAAEC,YAAF;IAAgBC,WAAhB;IAA6B,GAAGC;EAAhC,CAc4B;EAC5B;EACA,MAAMC,MAAM,GAAGD,OAAf;EACA,IAAIE,SAAJ;;EACA,QAAQL,MAAR;IACE,KAAKb,OAAO,CAACmB,KAAb;IACA,KAAKnB,OAAO,CAACoB,WAAb;MACEF,SAAS,GAAG,UAAZ;MACA;;IACF,KAAKlB,OAAO,CAACqB,SAAb;IACA,KAAKrB,OAAO,CAACsB,UAAb;IACA,KAAKtB,OAAO,CAACuB,U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AAEuC,GAAF;IAAOD,GAAP;IAAYD;EAAZ,CAAP;AACD"}
1
+ {"version":3,"file":"index.mjs","names":["ABI_VERSIONS","PROTOCOL_VM_ABI","TX_TTL","Tag","ArgumentError","UnsupportedProtocolError","UnknownTxError","InvalidTxParamsError","buildTx","syncBuildTx","unpackTx","isKeyOfObject","getVmVersion","txType","vmVersion","abiVersion","onNode","consensusProtocolVersion","getNodeInfo","supportedProtocol","protocolForTX","prepareTxParams","senderId","nonce","ttl","absoluteTtl","strategy","getAccountNextNonce","catch","nextNonce","getCurrentKeyBlock","height","_buildTx","denomination","_params","params","senderKey","SpendTx","OracleQueryTx","NameClaimTx","NameUpdateTx","NameRevokeTx","NameTransferTx","NamePreclaimTx","OracleRegisterTx","ContractCreateTx","GaAttachTx","ContractCallTx","OracleExtendTx","OracleResponseTx","ChannelCloseSoloTx","ChannelSlashTx","ChannelSettleTx","ChannelSnapshotSoloTx","PayingForTx","ctVersion","NO_ABI","tx","extraParams"],"sources":["../../src/tx/index.ts"],"sourcesContent":["/*\n * ISC License (ISC)\n * Copyright (c) 2022 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 */\n\n/**\n * Transaction methods\n *\n * This is implementation of [Tx](api/tx.md) relays\n * the creation of transactions to {@link Node}.\n * These methods provide ability to create native transactions.\n */\nimport BigNumber from 'bignumber.js';\nimport {\n ABI_VERSIONS, CtVersion, PROTOCOL_VM_ABI, TX_TTL, TxParamsCommon,\n} from './builder/schema';\nimport { Tag } from './builder/constants';\nimport {\n ArgumentError, UnsupportedProtocolError, UnknownTxError, InvalidTxParamsError,\n} from '../utils/errors';\nimport Node from '../Node';\nimport { Encoded } from '../utils/encoder';\nimport { buildTx as syncBuildTx, unpackTx } from './builder/index';\nimport { isKeyOfObject } from '../utils/other';\nimport { AE_AMOUNT_FORMATS } from '../utils/amount-formatter';\n\ntype Int = number | string | BigNumber;\n\nexport type BuildTxOptions <TxType extends Tag, OmitFields extends string> =\n Omit<Parameters<typeof _buildTx<TxType>>[1], OmitFields>;\n\n/**\n * Validated vm/abi version or get default based on transaction type and NODE version\n * @category transaction builder\n * @param txType - Type of transaction\n * @param ctVersion - Object with vm and abi version fields\n * @returns Object with vm/abi version\n */\nexport async function getVmVersion(\n txType: Tag.ContractCreateTx, ctVersion: Partial<CtVersion> & { onNode: Node }\n): Promise<CtVersion>;\nexport async function getVmVersion(\n txType: Tag, ctVersion: Partial<Pick<CtVersion, 'abiVersion'>> & { onNode: Node }\n): Promise<Pick<CtVersion, 'abiVersion'>>;\nexport async function getVmVersion(\n txType: Tag,\n { vmVersion, abiVersion, onNode }: Partial<CtVersion> & { onNode: Node },\n): Promise<Partial<CtVersion>> {\n const { consensusProtocolVersion } = await onNode.getNodeInfo();\n if (!isKeyOfObject(consensusProtocolVersion, PROTOCOL_VM_ABI)) {\n throw new UnsupportedProtocolError('Not supported consensus protocol version');\n }\n const supportedProtocol = PROTOCOL_VM_ABI[consensusProtocolVersion];\n if (!isKeyOfObject(txType, supportedProtocol)) {\n throw new UnknownTxError('Not supported tx type');\n }\n const protocolForTX = supportedProtocol[txType];\n abiVersion ??= protocolForTX.abiVersion[0];\n vmVersion ??= protocolForTX.vmVersion[0];\n return { vmVersion, abiVersion };\n}\n\n/**\n * Calculate fee, get absolute ttl (ttl + height), get account nonce\n * @category transaction builder\n * @param txType - Type of transaction\n * @param params - Object which contains all tx data\n * @returns Object with account nonce, absolute ttl and transaction fee\n */\nexport async function prepareTxParams(\n txType: Tag,\n {\n senderId,\n nonce,\n ttl = TX_TTL,\n absoluteTtl,\n strategy,\n onNode,\n }: PrepareTxParamsOptions,\n): Promise<{ ttl: number; nonce: number }> {\n nonce ??= (\n await onNode.getAccountNextNonce(senderId, { strategy }).catch(() => ({ nextNonce: 1 }))\n ).nextNonce;\n\n if (ttl !== 0) {\n if (ttl < 0) throw new ArgumentError('ttl', 'greater or equal to 0', ttl);\n ttl += absoluteTtl === true ? 0 : (await onNode.getCurrentKeyBlock()).height;\n }\n\n return { ttl, nonce };\n}\n\ninterface PrepareTxParamsOptions extends Pick<TxParamsCommon, 'nonce' | 'ttl'> {\n senderId: Encoded.AccountAddress;\n absoluteTtl?: boolean;\n strategy?: 'continuity' | 'max';\n onNode: Node;\n}\n\n// TODO: find a better name or rearrange methods\n/**\n * @category transaction builder\n */\nexport async function _buildTx<TxType extends Tag>(\n txType: TxType,\n { denomination, absoluteTtl, ..._params }:\n Omit<Parameters<typeof syncBuildTx<TxType, 'tx'>>[0], 'fee' | 'nonce' | 'ttl' | 'ctVersion' | 'abiVersion'>\n & {\n onNode: Node;\n fee?: Int;\n nonce?: number;\n ttl?: number;\n denomination?: AE_AMOUNT_FORMATS;\n absoluteTtl?: boolean;\n }\n & (TxType extends Tag.OracleExtendTx | Tag.OracleResponseTx\n ? { callerId: Encoded.AccountAddress } : {})\n & (TxType extends Tag.ContractCreateTx | Tag.GaAttachTx ? { ctVersion?: CtVersion } : {})\n & (TxType extends Tag.ContractCallTx | Tag.OracleRegisterTx\n ? { abiVersion?: ABI_VERSIONS } : {}),\n): Promise<Encoded.Transaction> {\n // TODO: avoid this assertion\n const params = _params as unknown as TxParamsCommon & { onNode: Node };\n let senderKey: keyof TxParamsCommon | '<absent>';\n switch (txType) {\n case Tag.SpendTx:\n case Tag.OracleQueryTx:\n senderKey = 'senderId';\n break;\n case Tag.NameClaimTx:\n case Tag.NameUpdateTx:\n case Tag.NameRevokeTx:\n case Tag.NameTransferTx:\n case Tag.NamePreclaimTx:\n case Tag.OracleRegisterTx:\n senderKey = 'accountId';\n break;\n case Tag.ContractCreateTx:\n case Tag.GaAttachTx:\n senderKey = 'ownerId';\n break;\n case Tag.ContractCallTx:\n case Tag.OracleExtendTx:\n case Tag.OracleResponseTx:\n senderKey = 'callerId';\n break;\n case Tag.ChannelCloseSoloTx:\n case Tag.ChannelSlashTx:\n case Tag.ChannelSettleTx:\n case Tag.ChannelSnapshotSoloTx:\n senderKey = 'fromId';\n break;\n case Tag.PayingForTx:\n senderKey = 'payerId';\n break;\n default:\n throw new ArgumentError('txType', 'valid transaction type', txType);\n }\n // TODO: move specific cases to field-types\n if ([Tag.ContractCreateTx, Tag.GaAttachTx].includes(txType)) {\n params.ctVersion = await getVmVersion(\n Tag.ContractCreateTx,\n { ...params, ...params.ctVersion },\n );\n }\n if (txType === Tag.ContractCallTx) {\n params.abiVersion = (await getVmVersion(Tag.ContractCallTx, params)).abiVersion;\n }\n if (txType === Tag.OracleRegisterTx) {\n params.abiVersion ??= ABI_VERSIONS.NO_ABI;\n }\n if (txType === Tag.PayingForTx) {\n params.tx = unpackTx(params.tx);\n }\n const senderId = params[senderKey];\n // TODO: do this check on TypeScript level\n if (senderId == null) throw new InvalidTxParamsError(`Transaction field ${senderKey} is missed`);\n const extraParams = await prepareTxParams(txType, { ...params, senderId, absoluteTtl });\n return syncBuildTx({ ...params, ...extraParams } as any, txType, { denomination }).tx;\n}\n"],"mappings":";;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;SAGEA,Y,EAAyBC,e,EAAiBC,M;SAEnCC,G;SAEPC,a,EAAeC,wB,EAA0BC,c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E,GAAG0B,MAAL;IAAa,GAAGuB;EAAhB,CAAD,EAAuC7C,MAAvC,EAA+C;IAAEoB;EAAF,CAA/C,CAAX,CAA4EwB,EAAnF;AACD"}
@@ -1,5 +1,5 @@
1
- import { TX_TYPE } from './builder/schema';
2
- import { EncodedData } from '../utils/encoder';
1
+ import { Tag } from './builder/constants';
2
+ import { Encoded } from '../utils/encoder';
3
3
  import Node from '../Node';
4
4
  export interface ValidatorResult {
5
5
  message: string;
@@ -10,10 +10,11 @@ export interface ValidatorResult {
10
10
  * Transaction Validator
11
11
  * This function validates some of transaction properties,
12
12
  * to make sure it can be posted it to the chain
13
+ * @category transaction builder
13
14
  * @param transaction - Base64Check-encoded transaction
14
15
  * @param node - Node to validate transaction against
15
16
  * @param parentTxTypes - Types of parent transactions
16
17
  * @returns Array with verification errors
17
18
  * @example const errors = await verifyTransaction(transaction, node)
18
19
  */
19
- export default function verifyTransaction(transaction: EncodedData<'tx' | 'pi'>, node: Node, parentTxTypes?: TX_TYPE[]): Promise<ValidatorResult[]>;
20
+ export default function verifyTransaction(transaction: Encoded.Transaction | Encoded.Poi, node: Node, parentTxTypes?: Tag[]): Promise<ValidatorResult[]>;
@@ -1,17 +1,65 @@
1
1
  import _buffer from "buffer";
2
+ import _includesInstanceProperty from "@babel/runtime-corejs3/core-js-stable/instance/includes";
2
3
  const {
3
4
  Buffer: _Buffer
4
5
  } = _buffer;
5
- import _includesInstanceProperty from "@babel/runtime-corejs3/core-js-stable/instance/includes";
6
- import { verify, hash } from "../utils/crypto.mjs";
7
- import { encode, decode } from "./builder/helpers.mjs";
8
6
  import BigNumber from 'bignumber.js';
9
- import { PROTOCOL_VM_ABI, TX_TYPE } from "./builder/schema.mjs";
7
+ import { hash, verify } from "../utils/crypto.mjs";
8
+ import { PROTOCOL_VM_ABI } from "./builder/schema.mjs";
9
+ import { Tag } from "./builder/constants.mjs";
10
10
  import { unpackTx } from "./builder/index.mjs";
11
- import calculateMinFee from "./min-fee.mjs";
12
11
  import { UnsupportedProtocolError } from "../utils/errors.mjs";
13
12
  import { concatBuffers, isKeyOfObject } from "../utils/other.mjs";
14
- const validators = [(_ref, _ref2) => {
13
+ import { decode, encode, Encoding } from "../utils/encoder.mjs";
14
+ const validators = [];
15
+
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
+ * Transaction Validator
19
+ * This function validates some of transaction properties,
20
+ * to make sure it can be posted it to the chain
21
+ * @category transaction builder
22
+ * @param transaction - Base64Check-encoded transaction
23
+ * @param node - Node to validate transaction against
24
+ * @param parentTxTypes - Types of parent transactions
25
+ * @returns Array with verification errors
26
+ * @example const errors = await verifyTransaction(transaction, node)
27
+ */
28
+
29
+
30
+ export default async function verifyTransaction(transaction, node) {
31
+ var _getSenderAddress;
32
+
33
+ let parentTxTypes = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : [];
34
+ const {
35
+ tx,
36
+ txType
37
+ } = unpackTx(transaction);
38
+ const address = (_getSenderAddress = getSenderAddress(tx)) !== null && _getSenderAddress !== void 0 ? _getSenderAddress : txType === Tag.SignedTx ? getSenderAddress(tx.encodedTx.tx) : undefined;
39
+ const [account, {
40
+ height
41
+ }, {
42
+ consensusProtocolVersion,
43
+ nodeNetworkId
44
+ }] = await Promise.all([address == null ? undefined : node.getAccountByPubkey(address).catch(() => ({
45
+ id: address,
46
+ balance: 0n,
47
+ nonce: 0
48
+ })) // TODO: remove after fixing https://github.com/aeternity/aepp-sdk-js/issues/1537
49
+ .then(acc => ({ ...acc,
50
+ id: acc.id
51
+ })), node.getCurrentKeyBlockHeight(), node.getNodeInfo()]);
52
+ return (await Promise.all(validators.map(v => v(tx, {
53
+ txType,
54
+ node,
55
+ account,
56
+ height,
57
+ consensusProtocolVersion,
58
+ nodeNetworkId,
59
+ parentTxTypes
60
+ })))).flat();
61
+ }
62
+ validators.push((_ref, _ref2) => {
15
63
  let {
16
64
  encodedTx,
17
65
  signatures
@@ -25,7 +73,7 @@ const validators = [(_ref, _ref2) => {
25
73
  if (account == null) return [];
26
74
  if (signatures.length !== 1) return []; // TODO: Support multisignature?
27
75
 
28
- const prefix = _Buffer.from([nodeNetworkId, ...(_includesInstanceProperty(parentTxTypes).call(parentTxTypes, TX_TYPE.payingFor) ? ['inner_tx'] : [])].join('-'));
76
+ const prefix = _Buffer.from([nodeNetworkId, ...(_includesInstanceProperty(parentTxTypes).call(parentTxTypes, Tag.PayingForTx) ? ['inner_tx'] : [])].join('-'));
29
77
 
30
78
  const txWithNetworkId = concatBuffers([prefix, encodedTx.rlpEncoded]);
31
79
  const txHashWithNetworkId = concatBuffers([prefix, hash(encodedTx.rlpEncoded)]);
@@ -47,29 +95,14 @@ const validators = [(_ref, _ref2) => {
47
95
  txType
48
96
  } = _ref4;
49
97
  if ((encodedTx !== null && encodedTx !== void 0 ? encodedTx : tx) === undefined) return [];
50
- return await verifyTransaction(encode((encodedTx !== null && encodedTx !== void 0 ? encodedTx : tx).rlpEncoded, 'tx'), node, [...parentTxTypes, txType]);
51
- }, (tx, _ref5) => {
52
- let {
53
- txType
54
- } = _ref5;
55
- if (tx.fee === undefined) return [];
56
- const minFee = calculateMinFee(txType, {
57
- params: tx,
58
- vsn: tx.VSN
59
- });
60
- if (minFee.lte(tx.fee)) return [];
61
- return [{
62
- message: `Fee ${tx.fee} is too low, minimum fee for this transaction is ${minFee.toString()}`,
63
- key: 'InsufficientFee',
64
- checkedKeys: ['fee']
65
- }];
66
- }, (_ref6, _ref7) => {
98
+ return verifyTransaction(encode((encodedTx !== null && encodedTx !== void 0 ? encodedTx : tx).rlpEncoded, Encoding.Transaction), node, [...parentTxTypes, txType]);
99
+ }, (_ref5, _ref6) => {
67
100
  let {
68
101
  ttl
69
- } = _ref6;
102
+ } = _ref5;
70
103
  let {
71
104
  height
72
- } = _ref7;
105
+ } = _ref6;
73
106
  if (ttl === undefined) return [];
74
107
  ttl = +ttl;
75
108
  if (ttl === 0 || ttl >= height) return [];
@@ -78,39 +111,39 @@ const validators = [(_ref, _ref2) => {
78
111
  key: 'ExpiredTTL',
79
112
  checkedKeys: ['ttl']
80
113
  }];
81
- }, (_ref8, _ref9) => {
82
- var _ref10, _fee;
114
+ }, (_ref7, _ref8) => {
115
+ var _ref9, _fee;
83
116
 
84
117
  let {
85
118
  amount,
86
119
  fee,
87
120
  nameFee,
88
121
  tx
89
- } = _ref8;
122
+ } = _ref7;
90
123
  let {
91
124
  account,
92
125
  parentTxTypes,
93
126
  txType
94
- } = _ref9;
127
+ } = _ref8;
95
128
  if (account == null) return [];
96
- if (((_ref10 = amount !== null && amount !== void 0 ? amount : fee) !== null && _ref10 !== void 0 ? _ref10 : nameFee) === undefined) return [];
129
+ if (((_ref9 = amount !== null && amount !== void 0 ? amount : fee) !== null && _ref9 !== void 0 ? _ref9 : nameFee) === undefined) return [];
97
130
  (_fee = fee) !== null && _fee !== void 0 ? _fee : fee = 0;
98
- const cost = new BigNumber(fee).plus(nameFee !== null && nameFee !== void 0 ? nameFee : 0).plus(amount !== null && amount !== void 0 ? amount : 0).plus(txType === TX_TYPE.payingFor ? tx.tx.encodedTx.tx.fee : 0).minus(_includesInstanceProperty(parentTxTypes).call(parentTxTypes, TX_TYPE.payingFor) ? fee : 0);
131
+ 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(_includesInstanceProperty(parentTxTypes).call(parentTxTypes, Tag.PayingForTx) ? fee : 0);
99
132
  if (cost.lte(account.balance.toString())) return [];
100
133
  return [{
101
134
  message: `Account balance ${account.balance.toString()} is not enough to execute the transaction that costs ${cost.toFixed()}`,
102
135
  key: 'InsufficientBalance',
103
136
  checkedKeys: ['amount', 'fee', 'nameFee']
104
137
  }];
105
- }, (_ref11, _ref12) => {
138
+ }, (_ref10, _ref11) => {
106
139
  let {
107
140
  nonce
108
- } = _ref11;
141
+ } = _ref10;
109
142
  let {
110
143
  account,
111
144
  parentTxTypes
112
- } = _ref12;
113
- if (nonce == null || account == null || _includesInstanceProperty(parentTxTypes).call(parentTxTypes, TX_TYPE.gaMeta)) return [];
145
+ } = _ref11;
146
+ if (nonce == null || account == null || _includesInstanceProperty(parentTxTypes).call(parentTxTypes, Tag.GaMetaTx)) return [];
114
147
  nonce = +nonce;
115
148
  const validNonce = account.nonce + 1;
116
149
  if (nonce === validNonce) return [];
@@ -123,15 +156,15 @@ const validators = [(_ref, _ref2) => {
123
156
  }),
124
157
  checkedKeys: ['nonce']
125
158
  }];
126
- }, (_ref13, _ref14) => {
159
+ }, (_ref12, _ref13) => {
127
160
  let {
128
161
  ctVersion,
129
162
  abiVersion
130
- } = _ref13;
163
+ } = _ref12;
131
164
  let {
132
165
  txType,
133
166
  consensusProtocolVersion
134
- } = _ref14;
167
+ } = _ref13;
135
168
 
136
169
  if (!isKeyOfObject(consensusProtocolVersion, PROTOCOL_VM_ABI)) {
137
170
  throw new UnsupportedProtocolError(`Unsupported protocol: ${consensusProtocolVersion}`);
@@ -145,10 +178,10 @@ const validators = [(_ref, _ref2) => {
145
178
  const txProtocol = protocol[txType];
146
179
  if (txProtocol == null) return [];
147
180
 
148
- if (Object.entries(ctVersion).some(_ref15 => {
181
+ if (Object.entries(ctVersion).some(_ref14 => {
149
182
  var _context;
150
183
 
151
- let [key, value] = _ref15;
184
+ let [key, value] = _ref14;
152
185
  return !_includesInstanceProperty(_context = txProtocol[key]).call(_context, +value);
153
186
  })) {
154
187
  return [{
@@ -159,15 +192,15 @@ const validators = [(_ref, _ref2) => {
159
192
  }
160
193
 
161
194
  return [];
162
- }, async (_ref16, _ref17) => {
195
+ }, async (_ref15, _ref16) => {
163
196
  let {
164
197
  contractId
165
- } = _ref16;
198
+ } = _ref15;
166
199
  let {
167
200
  txType,
168
201
  node
169
- } = _ref17;
170
- if (TX_TYPE.contractCall !== txType) return [];
202
+ } = _ref16;
203
+ if (Tag.ContractCallTx !== txType) return [];
171
204
  contractId = contractId;
172
205
 
173
206
  try {
@@ -190,51 +223,5 @@ const validators = [(_ref, _ref2) => {
190
223
  checkedKeys: ['contractId']
191
224
  }];
192
225
  }
193
- }];
194
-
195
- 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];
196
- /**
197
- * Transaction Validator
198
- * This function validates some of transaction properties,
199
- * to make sure it can be posted it to the chain
200
- * @param transaction - Base64Check-encoded transaction
201
- * @param node - Node to validate transaction against
202
- * @param parentTxTypes - Types of parent transactions
203
- * @returns Array with verification errors
204
- * @example const errors = await verifyTransaction(transaction, node)
205
- */
206
-
207
-
208
- export default async function verifyTransaction(transaction, node) {
209
- var _getSenderAddress;
210
-
211
- let parentTxTypes = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : [];
212
- const {
213
- tx,
214
- txType
215
- } = unpackTx(transaction);
216
- const address = (_getSenderAddress = getSenderAddress(tx)) !== null && _getSenderAddress !== void 0 ? _getSenderAddress : txType === TX_TYPE.signed ? getSenderAddress(tx.encodedTx.tx) : undefined;
217
- const [account, {
218
- height
219
- }, {
220
- consensusProtocolVersion,
221
- nodeNetworkId
222
- }] = await Promise.all([address == null ? undefined : node.getAccountByPubkey(address).catch(() => ({
223
- id: address,
224
- balance: 0n,
225
- nonce: 0
226
- })) // TODO: remove after fixing https://github.com/aeternity/aepp-sdk-js/issues/1537
227
- .then(acc => ({ ...acc,
228
- id: acc.id
229
- })), node.getCurrentKeyBlockHeight(), node.getNodeInfo()]);
230
- return (await Promise.all(validators.map(v => v(tx, {
231
- txType,
232
- node,
233
- account,
234
- height,
235
- consensusProtocolVersion,
236
- nodeNetworkId,
237
- parentTxTypes
238
- })))).flat();
239
- }
226
+ });
240
227
  //# sourceMappingURL=validator.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"validator.mjs","names":["verify","hash","encode","decode","BigNumber","PROTOCOL_VM_ABI","TX_TYPE","unpackTx","calculateMinFee","UnsupportedProtocolError","concatBuffers","isKeyOfObject","validators","encodedTx","signatures","account","nodeNetworkId","parentTxTypes","undefined","length","prefix","from","payingFor","join","txWithNetworkId","rlpEncoded","txHashWithNetworkId","decodedPub","id","message","key","checkedKeys","tx","node","txType","verifyTransaction","fee","minFee","params","vsn","VSN","lte","toString","ttl","height","amount","nameFee","cost","plus","minus","balance","toFixed","nonce","gaMeta","validNonce","ctVersion","abiVersion","consensusProtocolVersion","protocol","txProtocol","Object","entries","some","value","JSON","stringify","contractId","contractCall","active","getContract","error","response","parsedBody","reason","getSenderAddress","map","filter","a","replace","transaction","address","signed","Promise","all","getAccountByPubkey","catch","then","acc","getCurrentKeyBlockHeight","getNodeInfo","v","flat"],"sources":["../../src/tx/validator.ts"],"sourcesContent":["import { verify, hash } from '../utils/crypto'\nimport { encode, decode } from './builder/helpers'\nimport BigNumber from 'bignumber.js'\nimport {\n PROTOCOL_VM_ABI, RawTxObject, TxSchema, TxParamsCommon, TX_TYPE, TxTypeSchemas, CtVersion\n} from './builder/schema'\nimport { TxUnpacked, unpackTx } from './builder'\nimport calculateMinFee from './min-fee'\nimport { UnsupportedProtocolError } from '../utils/errors'\nimport { concatBuffers, isKeyOfObject } from '../utils/other'\nimport { EncodedData } from '../utils/encoder'\nimport Node from '../Node'\n\ninterface Account {\n balance: bigint\n id: EncodedData<'ak'>\n nonce: number\n}\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[TX_TYPE.signed]\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?: EncodedData<'ct'>\n },\n options: {\n account?: Account\n nodeNetworkId: string\n parentTxTypes: TX_TYPE[]\n node: Node\n txType: TX_TYPE\n height: number\n consensusProtocolVersion: number\n }\n) => ValidatorResult[] | Promise<ValidatorResult[]>\n\nconst validators: Validator[] = [\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(TX_TYPE.payingFor) ? ['inner_tx'] : []\n ].join('-'))\n const txWithNetworkId = concatBuffers([prefix, encodedTx.rlpEncoded])\n const txHashWithNetworkId = concatBuffers([prefix, hash(encodedTx.rlpEncoded)])\n const decodedPub = decode(account.id)\n if (verify(txWithNetworkId, signatures[0], decodedPub) ||\n verify(txHashWithNetworkId, signatures[0], decodedPub)) 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 await verifyTransaction(\n encode((encodedTx ?? tx).rlpEncoded, 'tx'),\n node,\n [...parentTxTypes, txType]\n )\n },\n (tx: any, { txType }) => {\n if (tx.fee === undefined) return []\n const minFee = calculateMinFee(txType, { params: tx, vsn: tx.VSN })\n if (minFee.lte(tx.fee)) return []\n return [{\n message: `Fee ${tx.fee as string} is too low, minimum fee for this transaction is ${minFee.toString()}`,\n key: 'InsufficientFee',\n checkedKeys: ['fee']\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 ({ amount, fee, nameFee, tx }, { 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 === TX_TYPE.payingFor ? (tx.tx.encodedTx.tx).fee : 0)\n .minus(parentTxTypes.includes(TX_TYPE.payingFor) ? 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 ({ nonce }, { account, parentTxTypes }) => {\n if (nonce == null || account == null || parentTxTypes.includes(TX_TYPE.gaMeta)) 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 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 (TX_TYPE.contractCall !== txType) return []\n contractId = contractId as EncodedData<'ct'>\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\nconst getSenderAddress = (\n tx: TxParamsCommon | RawTxObject<TxSchema>\n): EncodedData<'ak'> | 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 EncodedData<'ak'> | 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 * @param transaction - Base64Check-encoded transaction\n * @param node - 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: EncodedData<'tx' | 'pi'>,\n node: Node,\n parentTxTypes: TX_TYPE[] = []\n): Promise<ValidatorResult[]> {\n const { tx, txType } = unpackTx<TX_TYPE.signed>(transaction)\n const address = getSenderAddress(tx) ??\n (txType === TX_TYPE.signed ? 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(() => ({ id: address, balance: 0n, nonce: 0 }))\n // TODO: remove after fixing https://github.com/aeternity/aepp-sdk-js/issues/1537\n .then(acc => ({ ...acc, id: acc.id as EncodedData<'ak'> })),\n node.getCurrentKeyBlockHeight(),\n node.getNodeInfo()\n ])\n\n return (await Promise.all(\n validators.map(v => v(\n tx as any,\n { txType, node, account, height, consensusProtocolVersion, nodeNetworkId, parentTxTypes }\n ))\n )).flat()\n}\n"],"mappings":";;;;;SAASA,M,EAAQC,I;SACRC,M,EAAQC,M;AACjB,OAAOC,SAAP,MAAsB,cAAtB;SAEEC,e,EAAwDC,O;SAErCC,Q;OACdC,e;SACEC,wB;SACAC,a,EAAeC,a;AA2CxB,MAAMC,UAAuB,GAAG,CAC9B,iBAA0E;EAAA,IAAzE;IAAEC,SAAF;IAAaC;EAAb,CAAyE;EAAA,IAA9C;IAAEC,OAAF;IAAWC,aAAX;IAA0BC;EAA1B,CAA8C;EACxE,IAAI,CAACJ,SAAD,aAACA,SAAD,cAACA,SAAD,GAAcC,UAAd,MAA8BI,SAAlC,EAA6C,OAAO,EAAP;EAC7C,IAAIH,OAAO,IAAI,IAAf,EAAqB,OAAO,EAAP;EACrB,IAAID,UAAU,CAACK,MAAX,KAAsB,CAA1B,EAA6B,OAAO,EAAP,CAH2C,CAGjC;;EACvC,MAAMC,MAAM,GAAG,QAAOC,IAAP,CAAY,CACzBL,aADyB,EAEzB,IAAG,0BAAAC,aAAa,MAAb,CAAAA,aAAa,EAAUX,OAAO,CAACgB,SAAlB,CAAb,GAA4C,CAAC,UAAD,CAA5C,GAA2D,EAA9D,CAFyB,EAGzBC,IAHyB,CAGpB,GAHoB,CAAZ,CAAf;;EAIA,MAAMC,eAAe,GAAGd,aAAa,CAAC,CAACU,MAAD,EAASP,SAAS,CAACY,UAAnB,CAAD,CAArC;EACA,MAAMC,mBAAmB,GAAGhB,aAAa,CAAC,CAACU,MAAD,EAASnB,IAAI,CAACY,SAAS,CAACY,UAAX,CAAb,CAAD,CAAzC;EACA,MAAME,UAAU,GAAGxB,MAAM,CAACY,OAAO,CAACa,EAAT,CAAzB;EACA,IAAI5B,MAAM,CAACwB,eAAD,EAAkBV,UAAU,CAAC,CAAD,CAA5B,EAAiCa,UAAjC,CAAN,IACF3B,MAAM,CAAC0B,mBAAD,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AM,CAACH,OAAD,EAAU;IAAE6B;EAAF,CAAV,EAAsB;IAAEa,wBAAF;IAA4BzC;EAA5B,CAAtB,IAAqE,MAAMkE,OAAO,CAACC,GAAR,CAAY,CAC3FH,OAAO,IAAI,IAAX,GACI9D,SADJ,GAEIe,IAAI,CAACmD,kBAAL,CAAwBJ,OAAxB,EACCK,KADD,CACO,OAAO;IAAEzD,EAAE,EAAEoD,OAAN;IAAe9B,OAAO,EAAE,EAAxB;IAA4BE,KAAK,EAAE;EAAnC,CAAP,CADP,EAEA;EAFA,CAGCkC,IAHD,CAGMC,GAAG,KAAK,EAAE,GAAGA,GAAL;IAAU3D,EAAE,EAAE2D,GAAG,CAAC3D;EAAlB,CAAL,CAHT,CAHuF,EAO3FK,IAAI,CAACuD,wBAAL,EAP2F,EAQ3FvD,IAAI,CAACwD,WAAL,EAR2F,CAAZ,CAAjF;EAWA,OAAO,CAAC,MAAMP,OAAO,CAACC,GAAR,CACZvE,UAAU,CAAC+D,GAAX,CAAee,CAAC,IAAIA,CAAC,CACnB1D,EADmB,EAEnB;IAAEE,MAAF;IAAUD,IAAV;IAAgBlB,OAAhB;IAAyB6B,MAAzB;IAAiCa,wBAAjC;IAA2DzC,aAA3D;IAA0EC;EAA1E,CAFmB,CAArB,CADY,CAAP,EAKJ0E,IALI,EAAP;AAMD"}
1
+ {"version":3,"file":"validator.mjs","names":["BigNumber","hash","verify","PROTOCOL_VM_ABI","Tag","unpackTx","UnsupportedProtocolError","concatBuffers","isKeyOfObject","decode","encode","Encoding","validators","getSenderAddress","tx","map","key","filter","a","toString","replace","verifyTransaction","transaction","node","parentTxTypes","txType","address","SignedTx","encodedTx","undefined","account","height","consensusProtocolVersion","nodeNetworkId","Promise","all","getAccountByPubkey","catch","id","balance","nonce","then","acc","getCurrentKeyBlockHeight","getNodeInfo","v","flat","push","signatures","length","prefix","from","PayingForTx","join","txWithNetworkId","rlpEncoded","txHashWithNetworkId","decodedPub","message","checkedKeys","Transaction","ttl","amount","fee","nameFee","cost","plus","minus","lte","toFixed","GaMetaTx","validNonce","ctVersion","abiVersion","protocol","txProtocol","Object","entries","some","value","JSON","stringify","contractId","ContractCallTx","active","getContract","error","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, isKeyOfObject } from '../utils/other';\nimport {\n decode, encode, Encoded, Encoding,\n} from '../utils/encoder';\nimport Node from '../Node';\n\ninterface Account {\n balance: bigint;\n id: Encoded.AccountAddress;\n nonce: number;\n}\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 account?: Account;\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 node - 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 node: Node,\n parentTxTypes: Tag[] = [],\n): Promise<ValidatorResult[]> {\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(() => ({ id: address, balance: 0n, nonce: 0 }))\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 const decodedPub = decode(account.id);\n if (verify(txWithNetworkId, signatures[0], decodedPub)\n || verify(txHashWithNetworkId, signatures[0], decodedPub)) 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 ({ 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,SAAP,MAAsB,cAAtB;SACSC,I,EAAMC,M;SAGbC,e;SAMOC,G;SACYC,Q;SACZC,wB;SACAC,a,EAAeC,a;SAEtBC,M,EAAQC,M,EAAiBC,Q;AA2C3B,MAAMC,UAAuB,GAAG,EAAhC;;AAEA,MAAMC,gBAAgB,GACpBC,EADuB,IAEgB,CACvC,UADuC,EAC3B,WAD2B,EACd,SADc,EACH,UADG,EAEvC,UAFuC,EAE3B,QAF2B,EAEjB,WAFiB,EAEJ,MAFI,EAEI,SAFJ,EAItCC,GAJsC,CAIjCC,GAAD,IAAyBF,EAAE,CAACE,GAAD,CAJO,EAKtCC,MALsC,CAK9BC,CAAD,IAAOA,CALwB,EAMtCH,GANsC,CAMjCG,CAAD,IAAOA,CAAP,aAAOA,CAAP,uBAAOA,CAAC,C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;MAEN3D,GAAG,EAAE,yBAFC;MAGN2C,WAAW,EAAE,CAAC,WAAD,EAAc,YAAd;IAHP,CAAD,CAAP;EAKD;;EACD,OAAO,EAAP;AACD,CAlGH,EAmGE,0BAA4C;EAAA,IAArC;IAAEuB;EAAF,CAAqC;EAAA,IAArB;IAAEzD,MAAF;IAAUF;EAAV,CAAqB;EAC1C,IAAInB,GAAG,CAAC+E,cAAJ,KAAuB1D,MAA3B,EAAmC,OAAO,EAAP;EACnCyD,UAAU,GAAGA,UAAb;;EACA,IAAI;IACF,MAAM;MAAEE;IAAF,IAAa,MAAM7D,IAAI,CAAC8D,WAAL,CAAiBH,UAAjB,CAAzB;IACA,IAAIE,MAAJ,EAAY,OAAO,EAAP;IACZ,OAAO,CAAC;MACN1B,OAAO,EAAG,YAAWwB,UAAW,gBAD1B;MAENlE,GAAG,EAAE,mBAFC;MAGN2C,WAAW,EAAE,CAAC,YAAD;IAHP,CAAD,CAAP;EAKD,CARD,CAQE,OAAO2B,KAAP,EAAc;IAAA;;IACd,IAAI,oBAAAA,KAAK,CAACC,QAAN,6FAAgBC,UAAhB,gFAA4BC,MAA5B,KAAsC,IAA1C,EAAgD,MAAMH,KAAN;IAChD,OAAO,CAAC;MACN5B,OAAO,EAAE4B,KAAK,CAACC,QAAN,CAAeC,UAAf,CAA0BC,MAD7B;MAENzE,GAAG,EAAE,kBAFC;MAGN2C,WAAW,EAAE,CAAC,YAAD;IAHP,CAAD,CAAP;EAKD;AACF,CAtHH"}
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.mjs","names":[],"sources":["../../../src/typings/@aeternity__argon2-browser/index.d.ts"],"sourcesContent":["declare module '@aeternity/argon2-browser/dist/argon2-bundled.min.js' {\n export * from 'argon2-browser'\n}\n"],"mappings":""}
1
+ {"version":3,"file":"index.d.mjs","names":[],"sources":["../../../src/typings/@aeternity__argon2-browser/index.d.ts"],"sourcesContent":["declare module '@aeternity/argon2-browser/dist/argon2-bundled.min.js' {\n export * from 'argon2-browser';\n}\n"],"mappings":""}
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.mjs","names":[],"sources":["../../../src/typings/@aeternity__uuid/index.d.ts"],"sourcesContent":["declare module '@aeternity/uuid' {\n export * from 'uuid'\n}\n"],"mappings":""}
1
+ {"version":3,"file":"index.d.mjs","names":[],"sources":["../../../src/typings/@aeternity__uuid/index.d.ts"],"sourcesContent":["declare module '@aeternity/uuid' {\n // Already depends on @types/uuid\n // eslint-disable-next-line import/no-extraneous-dependencies\n export * from 'uuid';\n}\n"],"mappings":""}
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.mjs","names":[],"sources":["../../../src/typings/bip32-path/index.d.ts"],"sourcesContent":["// TODO: remove after solving https://github.com/axic/bip32-path/issues/5\n\ndeclare module 'bip32-path' {\n interface BipPath {\n toPathArray: () => number[]\n /**\n * returns a text encoded path. Set to noRoot to true to omit the m/ prefix.\n * Set oldStyle true to use h instead of ' for marking hardened nodes.\n */\n toString: (noRoot: boolean, oldStyle: boolean) => string\n\n /**\n * returns true if the input is a valid path string\n */\n validateString: (path: string) => boolean\n\n /**\n * returns true if the input is a valid binary path array\n */\n validatePathArray: (path: string) => boolean\n }\n\n /**\n * creates an instance from a path written as text.\n * Set reqRoot to true if the m/ prefix is mandatory.\n */\n export const fromString: (text: string, reqRoot?: boolean) => BipPath\n\n /**\n * creates an instance from a binary path array\n */\n export const fromPathArray: (path: string) => BipPath\n}\n"],"mappings":""}
1
+ {"version":3,"file":"index.d.mjs","names":[],"sources":["../../../src/typings/bip32-path/index.d.ts"],"sourcesContent":["// TODO: remove after solving https://github.com/axic/bip32-path/issues/5\n\ndeclare module 'bip32-path' {\n interface BipPath {\n toPathArray: () => number[];\n /**\n * returns a text encoded path. Set to noRoot to true to omit the m/ prefix.\n * Set oldStyle true to use h instead of ' for marking hardened nodes.\n */\n toString: (noRoot: boolean, oldStyle: boolean) => string;\n\n /**\n * returns true if the input is a valid path string\n */\n validateString: (path: string) => boolean;\n\n /**\n * returns true if the input is a valid binary path array\n */\n validatePathArray: (path: string) => boolean;\n }\n\n /**\n * creates an instance from a path written as text.\n * Set reqRoot to true if the m/ prefix is mandatory.\n */\n export const fromString: (text: string, reqRoot?: boolean) => BipPath;\n\n /**\n * creates an instance from a binary path array\n */\n export const fromPathArray: (path: string) => BipPath;\n}\n"],"mappings":""}
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.mjs","names":[],"sources":["../../../src/typings/blakejs/index.d.ts"],"sourcesContent":["declare module 'blakejs' {\n interface Context {\n b: Uint8Array\n h: Uint32Array\n t: number\n c: number\n outlen: number\n }\n\n export type Data = Buffer | Uint8Array | string\n\n type Key = Uint8Array | null\n\n export const blake2b: (data: Data, key?: Key, outlen?: number) => Uint8Array\n\n export const blake2bFinal: (context: Context) => Uint8Array\n\n export const blake2bHex: (data: Data, key?: Key, outlen?: number) => string\n\n export const blake2bInit: (outlen?: number, key?: Key) => Context\n\n export const blake2bUpdate: (context: Context, data: Data) => void\n\n export const blake2s: (data: Data, key?: Key, outlen?: number) => Uint8Array\n\n export const blake2sFinal: (context: Context) => Uint8Array\n\n export const blake2sHex: (data: Data, key?: Key, outlen?: number) => string\n\n export const blake2sInit: (outlen?: number, key?: Key) => Context\n\n export const blake2sUpdate: (context: Context, data: Data) => void\n}\n"],"mappings":""}
1
+ {"version":3,"file":"index.d.mjs","names":[],"sources":["../../../src/typings/blakejs/index.d.ts"],"sourcesContent":["declare module 'blakejs/blake2b.js' {\n export {\n Blake2bCTX, blake2bInit, blake2bUpdate, blake2bFinal, blake2b, blake2bHex,\n } from 'blakejs';\n}\n"],"mappings":""}
@@ -0,0 +1,2 @@
1
+
2
+ //# sourceMappingURL=index.d.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.mjs","names":[],"sources":["../../../src/typings/sha-js/index.d.ts"],"sourcesContent":["declare module 'sha.js/sha256.js' {\n import { sha256 } from 'sha.js';\n\n export default sha256;\n}\n"],"mappings":""}
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.mjs","names":[],"sources":["../../../src/typings/tweetnacl-auth/index.d.ts"],"sourcesContent":["// TODO: remove after solving https://github.com/dchest/tweetnacl-auth-js/issues/3\n\ndeclare module 'tweetnacl-auth' {\n /**\n * Authenticates the given message with the secret key.\n * (In other words, returns HMAC-SHA-512-256 of the message under the key.)\n */\n export default function (message: Uint8Array, key: Uint8Array): Uint8Array\n\n /**\n * Returns HMAC-SHA-512 (without truncation) of the message under the key\n */\n export const full: (message: Uint8Array, key: Uint8Array) => Uint8Array\n}\n"],"mappings":""}
1
+ {"version":3,"file":"index.d.mjs","names":[],"sources":["../../../src/typings/tweetnacl-auth/index.d.ts"],"sourcesContent":["// TODO: remove after solving https://github.com/dchest/tweetnacl-auth-js/issues/3\n\ndeclare module 'tweetnacl-auth' {\n /**\n * Authenticates the given message with the secret key.\n * (In other words, returns HMAC-SHA-512-256 of the message under the key.)\n */\n export default function (message: Uint8Array, key: Uint8Array): Uint8Array;\n\n /**\n * Returns HMAC-SHA-512 (without truncation) of the message under the key\n */\n export const full: (message: Uint8Array, key: Uint8Array) => Uint8Array;\n}\n"],"mappings":""}
@@ -9,34 +9,34 @@ export declare enum AE_AMOUNT_FORMATS {
9
9
  AETTOS = "aettos"
10
10
  }
11
11
  /**
12
- * Convert amount to AE
12
+ * Convert amount from one to other denomination
13
13
  * @param value - amount to convert
14
14
  * @param options - options
15
15
  * @param options.denomination - denomination of amount, can be ['ae', 'aettos']
16
+ * @param options.targetDenomination - target denomination,
17
+ * can be ['ae', 'aettos']
16
18
  */
17
- export declare const toAe: (value: string | number | BigNumber, { denomination }?: {
19
+ export declare const formatAmount: (value: string | number | bigint | BigNumber, { denomination, targetDenomination }: {
18
20
  denomination?: AE_AMOUNT_FORMATS | undefined;
21
+ targetDenomination?: AE_AMOUNT_FORMATS | undefined;
19
22
  }) => string;
20
23
  /**
21
- * Convert amount to aettos
24
+ * Convert amount to AE
22
25
  * @param value - amount to convert
23
26
  * @param options - options
24
27
  * @param options.denomination - denomination of amount, can be ['ae', 'aettos']
25
28
  */
26
- export declare const toAettos: (value: string | number | BigNumber, { denomination }?: {
29
+ export declare const toAe: (value: string | number | BigNumber, { denomination }?: {
27
30
  denomination?: AE_AMOUNT_FORMATS | undefined;
28
31
  }) => string;
29
32
  /**
30
- * Convert amount from one to other denomination
33
+ * Convert amount to aettos
31
34
  * @param value - amount to convert
32
35
  * @param options - options
33
36
  * @param options.denomination - denomination of amount, can be ['ae', 'aettos']
34
- * @param options.targetDenomination - target denomination,
35
- * can be ['ae', 'aettos']
36
37
  */
37
- export declare const formatAmount: (value: string | number | bigint | BigNumber, { denomination, targetDenomination }: {
38
+ export declare const toAettos: (value: string | number | BigNumber, { denomination }?: {
38
39
  denomination?: AE_AMOUNT_FORMATS | undefined;
39
- targetDenomination?: AE_AMOUNT_FORMATS | undefined;
40
40
  }) => string;
41
41
  declare const _default: (rawValue: string | number | BigNumber) => string;
42
42
  export default _default;
@@ -41,6 +41,23 @@ const DENOMINATION_MAGNITUDE = {
41
41
  [AE_AMOUNT_FORMATS.FEMTO_AE]: -15,
42
42
  [AE_AMOUNT_FORMATS.AETTOS]: -18
43
43
  };
44
+ /**
45
+ * Convert amount from one to other denomination
46
+ * @param value - amount to convert
47
+ * @param options - options
48
+ * @param options.denomination - denomination of amount, can be ['ae', 'aettos']
49
+ * @param options.targetDenomination - target denomination,
50
+ * can be ['ae', 'aettos']
51
+ */
52
+
53
+ export const formatAmount = (value, _ref) => {
54
+ let {
55
+ denomination = AE_AMOUNT_FORMATS.AETTOS,
56
+ targetDenomination = AE_AMOUNT_FORMATS.AETTOS
57
+ } = _ref;
58
+ if (!isBigNumber(value)) throw new ArgumentError('value', 'a number', value);
59
+ return new BigNumber(typeof value === 'bigint' ? value.toString() : value).shiftedBy(DENOMINATION_MAGNITUDE[denomination] - DENOMINATION_MAGNITUDE[targetDenomination]).toFixed();
60
+ };
44
61
  /**
45
62
  * Convert amount to AE
46
63
  * @param value - amount to convert
@@ -72,23 +89,6 @@ export const toAettos = function (value) {
72
89
  denomination
73
90
  });
74
91
  };
75
- /**
76
- * Convert amount from one to other denomination
77
- * @param value - amount to convert
78
- * @param options - options
79
- * @param options.denomination - denomination of amount, can be ['ae', 'aettos']
80
- * @param options.targetDenomination - target denomination,
81
- * can be ['ae', 'aettos']
82
- */
83
-
84
- export const formatAmount = (value, _ref) => {
85
- let {
86
- denomination = AE_AMOUNT_FORMATS.AETTOS,
87
- targetDenomination = AE_AMOUNT_FORMATS.AETTOS
88
- } = _ref;
89
- if (!isBigNumber(value)) throw new ArgumentError('value', 'a number', value);
90
- return new BigNumber(typeof value === 'bigint' ? value.toString() : value).shiftedBy(DENOMINATION_MAGNITUDE[denomination] - DENOMINATION_MAGNITUDE[targetDenomination]).toFixed();
91
- };
92
92
  const prefixes = [{
93
93
  name: 'exa',
94
94
  magnitude: 18
@@ -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","toAe","value","denomination","formatAmount","targetDenomination","toAettos","toString","shiftedBy","toFixed","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 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\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\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,SAAP,MAAsB,cAAtB;SACSC,W;SACAC,a;AAET,WAAYC,iBAAZ;AAUA;AACA;AACA;;WAZYA,iB;EAAAA,iB;EAAAA,iB;EAAAA,iB;EAAAA,iB;EAAAA,iB;EAAAA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AEd,IAAF;IAAQC;EAAR,IAAsB,CAACY,GAAG,GAAG,CAAN,GAAUX,gBAAV,GAA6BO,mBAA9B,EAAmDI,GAAnD,CAA5B;EACA,MAAME,CAAC,GAAGxB,KAAK,CACZM,SADO,CACG,CAACI,SADJ,EAEPe,SAFO,CAEG,IAAIT,IAAI,CAACU,GAAL,CAASJ,GAAG,GAAGZ,SAAf,EAA0B,CAA1B,CAFP,EAGPH,OAHO,EAAV;EAIA,OAAQ,GAAEiB,CAAE,GAAEf,IAAI,KAAK,EAAT,GAAc,GAAd,GAAoB,EAAG,GAAEA,IAAK,EAA5C;AACD,CAVD"}
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,SAAP,MAAsB,cAAtB;SACSC,W;SACAC,a;AAET,WAAYC,iBAAZ;AAUA;AACA;AACA;;WAZYA,iB;EAAAA,iB;EAAAA,iB;EAAAA,iB;EAAAA,iB;EAAAA,iB;EAAAA,iB;EAAAA,iB;GAAAA,iB,KAAAA,iB;;AAaZ,MAAMC,sBAAsB,GAAG;EAC7B,CAACD,iBAAiB,CAACE,EAAnB,GAAwB,CADK;EAE7B,CAACF,iBAAiB,CAACG,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