@aeternity/aepp-sdk 10.0.0-beta.1 → 11.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (250) hide show
  1. package/README.md +15 -14
  2. package/dist/aepp-sdk.browser-script.js +1 -1
  3. package/dist/aepp-sdk.browser-script.js.LICENSE.txt +7 -27
  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/account/{base.js → base.mjs} +23 -11
  10. package/es/account/base.mjs.map +1 -0
  11. package/es/account/{memory.js → memory.mjs} +29 -14
  12. package/es/account/memory.mjs.map +1 -0
  13. package/es/account/{multiple.js → multiple.mjs} +14 -11
  14. package/es/account/multiple.mjs.map +1 -0
  15. package/es/ae/{aens.js → aens.mjs} +69 -59
  16. package/es/ae/aens.mjs.map +1 -0
  17. package/es/ae/{aepp.js → aepp.mjs} +9 -9
  18. package/es/ae/aepp.mjs.map +1 -0
  19. package/es/ae/contract.mjs +159 -0
  20. package/es/ae/contract.mjs.map +1 -0
  21. package/es/ae/{index.js → index.mjs} +12 -10
  22. package/es/ae/index.mjs.map +1 -0
  23. package/es/ae/{oracle.js → oracle.mjs} +37 -20
  24. package/es/ae/oracle.mjs.map +1 -0
  25. package/es/ae/{universal.js → universal.mjs} +10 -10
  26. package/es/ae/universal.mjs.map +1 -0
  27. package/es/ae/{wallet.js → wallet.mjs} +10 -10
  28. package/es/ae/wallet.mjs.map +1 -0
  29. package/es/aepp-wallet-communication/schema.d.ts +74 -0
  30. package/es/bignumber.d.ts +1 -7
  31. package/es/chain/{index.js → index.mjs} +28 -8
  32. package/es/chain/index.mjs.map +1 -0
  33. package/es/chain/{node.js → node.mjs} +133 -90
  34. package/es/chain/node.mjs.map +1 -0
  35. package/es/channel/{handlers.js → handlers.mjs} +18 -20
  36. package/es/channel/handlers.mjs.map +1 -0
  37. package/es/channel/{index.js → index.mjs} +43 -22
  38. package/es/channel/index.mjs.map +1 -0
  39. package/es/channel/{internal.js → internal.mjs} +51 -35
  40. package/es/channel/internal.mjs.map +1 -0
  41. package/es/contract/aci.mjs +477 -0
  42. package/es/contract/aci.mjs.map +1 -0
  43. package/es/contract/compiler.mjs +115 -0
  44. package/es/contract/compiler.mjs.map +1 -0
  45. package/es/contract/ga/helpers.mjs +30 -0
  46. package/es/contract/ga/helpers.mjs.map +1 -0
  47. package/es/contract/ga/{index.js → index.mjs} +40 -28
  48. package/es/contract/ga/index.mjs.map +1 -0
  49. package/es/encoder.d.ts +26 -0
  50. package/es/errors.d.ts +284 -0
  51. package/es/index.mjs +57 -0
  52. package/es/index.mjs.map +1 -0
  53. package/es/node-pool/{index.js → index.mjs} +15 -12
  54. package/es/node-pool/index.mjs.map +1 -0
  55. package/es/{node.js → node.mjs} +17 -11
  56. package/es/node.mjs.map +1 -0
  57. package/es/tx/builder/constants.mjs +108 -0
  58. package/es/tx/builder/constants.mjs.map +1 -0
  59. package/es/tx/builder/field-types.mjs +74 -0
  60. package/es/tx/builder/field-types.mjs.map +1 -0
  61. package/es/tx/builder/helpers.mjs +321 -0
  62. package/es/tx/builder/helpers.mjs.map +1 -0
  63. package/es/tx/builder/{index.js → index.mjs} +92 -74
  64. package/es/tx/builder/index.mjs.map +1 -0
  65. package/es/tx/builder/{schema.js → schema.mjs} +16 -172
  66. package/es/tx/builder/schema.mjs.map +1 -0
  67. package/es/tx/{index.js → index.mjs} +106 -14
  68. package/es/tx/index.mjs.map +1 -0
  69. package/es/tx/{tx-object.js → tx-object.mjs} +31 -18
  70. package/es/tx/tx-object.mjs.map +1 -0
  71. package/es/tx/{tx.js → tx.mjs} +15 -14
  72. package/es/tx/tx.mjs.map +1 -0
  73. package/es/tx/{validator.js → validator.mjs} +72 -33
  74. package/es/tx/validator.mjs.map +1 -0
  75. package/es/typings/blakejs/index.d.mjs +2 -0
  76. package/es/typings/blakejs/{index.d.js.map → index.d.mjs.map} +1 -1
  77. package/es/utils/aepp-wallet-communication/connection/{browser-runtime.js → browser-runtime.mjs} +10 -8
  78. package/es/utils/aepp-wallet-communication/connection/browser-runtime.mjs.map +1 -0
  79. package/es/utils/aepp-wallet-communication/connection/{browser-window-message.js → browser-window-message.mjs} +25 -17
  80. package/es/utils/aepp-wallet-communication/connection/browser-window-message.mjs.map +1 -0
  81. package/es/utils/aepp-wallet-communication/connection/{index.js → index.mjs} +7 -3
  82. package/es/utils/aepp-wallet-communication/connection/index.mjs.map +1 -0
  83. package/es/utils/aepp-wallet-communication/{content-script-bridge.js → content-script-bridge.mjs} +15 -8
  84. package/es/utils/aepp-wallet-communication/content-script-bridge.mjs.map +1 -0
  85. package/es/utils/aepp-wallet-communication/{helpers.js → helpers.mjs} +3 -14
  86. package/es/utils/aepp-wallet-communication/helpers.mjs.map +1 -0
  87. package/es/utils/aepp-wallet-communication/rpc/{aepp-rpc.js → aepp-rpc.mjs} +126 -72
  88. package/es/utils/aepp-wallet-communication/rpc/aepp-rpc.mjs.map +1 -0
  89. package/es/utils/aepp-wallet-communication/rpc/{rpc-client.js → rpc-client.mjs} +23 -14
  90. package/es/utils/aepp-wallet-communication/rpc/rpc-client.mjs.map +1 -0
  91. package/es/utils/aepp-wallet-communication/rpc/{wallet-rpc.js → wallet-rpc.mjs} +116 -91
  92. package/es/utils/aepp-wallet-communication/rpc/wallet-rpc.mjs.map +1 -0
  93. package/es/utils/aepp-wallet-communication/schema.mjs +102 -0
  94. package/es/utils/aepp-wallet-communication/schema.mjs.map +1 -0
  95. package/es/utils/aepp-wallet-communication/{wallet-detector.js → wallet-detector.mjs} +6 -5
  96. package/es/utils/aepp-wallet-communication/wallet-detector.mjs.map +1 -0
  97. package/es/utils/{amount-formatter.js → amount-formatter.mjs} +14 -7
  98. package/es/utils/amount-formatter.mjs.map +1 -0
  99. package/es/utils/{async-init.js → async-init.mjs} +8 -11
  100. package/es/utils/async-init.mjs.map +1 -0
  101. package/es/utils/{bignumber.js → bignumber.mjs} +2 -9
  102. package/es/utils/bignumber.mjs.map +1 -0
  103. package/es/utils/{bytes.js → bytes.mjs} +16 -8
  104. package/es/utils/bytes.mjs.map +1 -0
  105. package/es/utils/{crypto-ts.js → crypto-ts.mjs} +11 -3
  106. package/es/utils/crypto-ts.mjs.map +1 -0
  107. package/es/utils/{crypto.js → crypto.mjs} +42 -156
  108. package/es/utils/crypto.mjs.map +1 -0
  109. package/es/utils/encoder.mjs +106 -0
  110. package/es/utils/encoder.mjs.map +1 -0
  111. package/es/utils/errors.mjs +689 -0
  112. package/es/utils/errors.mjs.map +1 -0
  113. package/es/utils/{hd-wallet.js → hd-wallet.mjs} +33 -34
  114. package/es/utils/hd-wallet.mjs.map +1 -0
  115. package/es/utils/{json-big.js → json-big.mjs} +1 -1
  116. package/es/utils/{json-big.js.map → json-big.mjs.map} +1 -1
  117. package/es/utils/{keystore.js → keystore.mjs} +63 -51
  118. package/es/utils/keystore.mjs.map +1 -0
  119. package/es/utils/{mptree.js → mptree.mjs} +21 -12
  120. package/es/utils/mptree.mjs.map +1 -0
  121. package/es/utils/{other.js → other.mjs} +2 -2
  122. package/es/utils/other.mjs.map +1 -0
  123. package/es/utils/{semver-satisfies.js → semver-satisfies.mjs} +1 -1
  124. package/es/utils/{semver-satisfies.js.map → semver-satisfies.mjs.map} +1 -1
  125. package/es/utils/{string.js → string.mjs} +1 -1
  126. package/es/utils/{string.js.map → string.mjs.map} +1 -1
  127. package/es/utils/{swagger.js → swagger.mjs} +49 -15
  128. package/es/utils/swagger.mjs.map +1 -0
  129. package/package.json +49 -58
  130. package/src/account/base.js +3 -1
  131. package/src/account/memory.js +13 -8
  132. package/src/account/multiple.js +16 -6
  133. package/src/ae/aens.js +52 -58
  134. package/src/ae/aepp.js +2 -2
  135. package/src/ae/contract.js +21 -154
  136. package/src/ae/index.js +6 -4
  137. package/src/ae/oracle.js +33 -14
  138. package/src/ae/universal.js +4 -2
  139. package/src/ae/wallet.js +2 -2
  140. package/src/chain/index.js +29 -6
  141. package/src/chain/node.js +95 -65
  142. package/src/channel/handlers.js +30 -20
  143. package/src/channel/index.js +46 -16
  144. package/src/channel/internal.js +35 -30
  145. package/src/contract/aci.js +376 -0
  146. package/src/contract/compiler.js +22 -113
  147. package/src/contract/ga/helpers.js +10 -6
  148. package/src/contract/ga/index.js +31 -24
  149. package/src/index.js +9 -8
  150. package/src/node-pool/index.js +13 -10
  151. package/src/node.js +11 -10
  152. package/src/tx/builder/constants.js +100 -0
  153. package/src/tx/builder/field-types.js +61 -0
  154. package/src/tx/builder/helpers.js +99 -103
  155. package/src/tx/builder/index.js +81 -40
  156. package/src/tx/builder/schema.js +44 -132
  157. package/src/tx/index.js +101 -12
  158. package/src/tx/tx-object.js +35 -15
  159. package/src/tx/tx.js +110 -35
  160. package/src/tx/validator.js +25 -5
  161. package/src/utils/aepp-wallet-communication/connection/browser-runtime.js +11 -5
  162. package/src/utils/aepp-wallet-communication/connection/browser-window-message.js +35 -13
  163. package/src/utils/aepp-wallet-communication/connection/index.js +2 -1
  164. package/src/utils/aepp-wallet-communication/content-script-bridge.js +14 -7
  165. package/src/utils/aepp-wallet-communication/helpers.js +6 -14
  166. package/src/utils/aepp-wallet-communication/rpc/aepp-rpc.js +106 -57
  167. package/src/utils/aepp-wallet-communication/rpc/rpc-client.js +24 -11
  168. package/src/utils/aepp-wallet-communication/rpc/wallet-rpc.js +95 -53
  169. package/src/utils/aepp-wallet-communication/schema.ts +80 -0
  170. package/src/utils/aepp-wallet-communication/wallet-detector.js +6 -2
  171. package/src/utils/amount-formatter.ts +4 -3
  172. package/src/utils/async-init.js +10 -6
  173. package/src/utils/bignumber.ts +1 -9
  174. package/src/utils/bytes.ts +3 -2
  175. package/src/utils/crypto-ts.ts +2 -2
  176. package/src/utils/crypto.js +11 -155
  177. package/src/utils/encoder.ts +101 -0
  178. package/src/utils/errors.ts +683 -0
  179. package/src/utils/hd-wallet.js +11 -26
  180. package/src/utils/keystore.js +57 -53
  181. package/src/utils/mptree.ts +12 -6
  182. package/src/utils/swagger.js +68 -45
  183. package/es/account/base.js.map +0 -1
  184. package/es/account/memory.js.map +0 -1
  185. package/es/account/multiple.js.map +0 -1
  186. package/es/ae/aens.js.map +0 -1
  187. package/es/ae/aepp.js.map +0 -1
  188. package/es/ae/contract.js +0 -308
  189. package/es/ae/contract.js.map +0 -1
  190. package/es/ae/index.js.map +0 -1
  191. package/es/ae/oracle.js.map +0 -1
  192. package/es/ae/universal.js.map +0 -1
  193. package/es/ae/wallet.js.map +0 -1
  194. package/es/chain/index.js.map +0 -1
  195. package/es/chain/node.js.map +0 -1
  196. package/es/channel/handlers.js.map +0 -1
  197. package/es/channel/index.js.map +0 -1
  198. package/es/channel/internal.js.map +0 -1
  199. package/es/contract/aci/helpers.js +0 -298
  200. package/es/contract/aci/helpers.js.map +0 -1
  201. package/es/contract/aci/index.js +0 -356
  202. package/es/contract/aci/index.js.map +0 -1
  203. package/es/contract/aci/transformation.js +0 -66
  204. package/es/contract/aci/transformation.js.map +0 -1
  205. package/es/contract/compiler.js +0 -242
  206. package/es/contract/compiler.js.map +0 -1
  207. package/es/contract/ga/helpers.js +0 -22
  208. package/es/contract/ga/helpers.js.map +0 -1
  209. package/es/contract/ga/index.js.map +0 -1
  210. package/es/contract/index.js +0 -158
  211. package/es/contract/index.js.map +0 -1
  212. package/es/index.js +0 -56
  213. package/es/index.js.map +0 -1
  214. package/es/node-pool/index.js.map +0 -1
  215. package/es/node.js.map +0 -1
  216. package/es/tx/builder/helpers.js +0 -318
  217. package/es/tx/builder/helpers.js.map +0 -1
  218. package/es/tx/builder/index.js.map +0 -1
  219. package/es/tx/builder/schema.js.map +0 -1
  220. package/es/tx/index.js.map +0 -1
  221. package/es/tx/tx-object.js.map +0 -1
  222. package/es/tx/tx.js.map +0 -1
  223. package/es/tx/validator.js.map +0 -1
  224. package/es/typings/blakejs/index.d.js +0 -2
  225. package/es/utils/aepp-wallet-communication/connection/browser-runtime.js.map +0 -1
  226. package/es/utils/aepp-wallet-communication/connection/browser-window-message.js.map +0 -1
  227. package/es/utils/aepp-wallet-communication/connection/index.js.map +0 -1
  228. package/es/utils/aepp-wallet-communication/content-script-bridge.js.map +0 -1
  229. package/es/utils/aepp-wallet-communication/helpers.js.map +0 -1
  230. package/es/utils/aepp-wallet-communication/rpc/aepp-rpc.js.map +0 -1
  231. package/es/utils/aepp-wallet-communication/rpc/rpc-client.js.map +0 -1
  232. package/es/utils/aepp-wallet-communication/rpc/wallet-rpc.js.map +0 -1
  233. package/es/utils/aepp-wallet-communication/schema.js +0 -107
  234. package/es/utils/aepp-wallet-communication/schema.js.map +0 -1
  235. package/es/utils/aepp-wallet-communication/wallet-detector.js.map +0 -1
  236. package/es/utils/amount-formatter.js.map +0 -1
  237. package/es/utils/async-init.js.map +0 -1
  238. package/es/utils/bignumber.js.map +0 -1
  239. package/es/utils/bytes.js.map +0 -1
  240. package/es/utils/crypto-ts.js.map +0 -1
  241. package/es/utils/crypto.js.map +0 -1
  242. package/es/utils/hd-wallet.js.map +0 -1
  243. package/es/utils/keystore.js.map +0 -1
  244. package/es/utils/mptree.js.map +0 -1
  245. package/es/utils/other.js.map +0 -1
  246. package/es/utils/swagger.js.map +0 -1
  247. package/src/contract/aci/index.js +0 -310
  248. package/src/contract/aci/transformation.js +0 -72
  249. package/src/contract/index.js +0 -159
  250. package/src/utils/aepp-wallet-communication/schema.js +0 -108
@@ -1,26 +1,26 @@
1
- import * as R from 'ramda'
2
1
  import BigNumber from 'bignumber.js'
3
-
4
- import {
5
- decodeBase58Check,
6
- decodeBase64Check,
7
- encodeBase58Check, encodeBase64Check,
8
- hash,
9
- salt
10
- } from '../../utils/crypto'
2
+ import { encode as bs58Encode, decode as bs58Decode } from 'bs58'
3
+ import { hash, salt } from '../../utils/crypto'
4
+ import { encode, decode } from '../../utils/encoder'
11
5
  import { toBytes } from '../../utils/bytes'
12
6
  import {
13
7
  ID_TAG_PREFIX,
14
8
  PREFIX_ID_TAG,
15
9
  NAME_BID_RANGES,
16
- NAME_BID_MAX_LENGTH,
17
- NAME_FEE,
18
10
  NAME_FEE_BID_INCREMENT,
19
11
  NAME_BID_TIMEOUTS,
20
12
  NAME_MAX_LENGTH_FEE,
21
- NAME_ID_KEY
22
- } from './schema'
13
+ POINTER_KEY_BY_PREFIX
14
+ } from './constants'
23
15
  import { ceil } from '../../utils/bignumber'
16
+ import {
17
+ TagNotFoundError,
18
+ PrefixNotFoundError,
19
+ InvalidNameError,
20
+ IllegalBidFeeError,
21
+ NoDefaultAensPointerError,
22
+ ArgumentError
23
+ } from '../../utils/errors'
24
24
 
25
25
  /**
26
26
  * JavaScript-based Transaction builder helper function's
@@ -31,7 +31,7 @@ import { ceil } from '../../utils/bignumber'
31
31
 
32
32
  export const createSalt = salt
33
33
 
34
- const base64Types = ['tx', 'st', 'ss', 'pi', 'ov', 'or', 'cb', 'cs', 'ba']
34
+ export { encode, decode }
35
35
 
36
36
  /**
37
37
  * Build a contract public key
@@ -78,11 +78,11 @@ export function formatSalt (salt) {
78
78
  }
79
79
 
80
80
  /**
81
- * Encode a domain name
81
+ * Encode an AENS name
82
82
  * @function
83
83
  * @alias module:@aeternity/aepp-sdk/es/tx/builder/helpers
84
84
  * @param {String} name Name to encode
85
- * @return {String} `nm_` prefixed encoded domain name
85
+ * @return {String} `nm_` prefixed encoded AENS name
86
86
  */
87
87
  export function produceNameId (name) {
88
88
  ensureNameValid(name)
@@ -103,38 +103,46 @@ export function produceNameId (name) {
103
103
  */
104
104
  export function commitmentHash (name, salt = createSalt()) {
105
105
  ensureNameValid(name)
106
- return `cm_${encodeBase58Check(hash(Buffer.concat([Buffer.from(name.toLowerCase()), formatSalt(salt)])))}`
106
+ return encode(hash(Buffer.concat([Buffer.from(name.toLowerCase()), formatSalt(salt)])), 'cm')
107
107
  }
108
108
 
109
- /**
110
- * Decode data using the default encoding/decoding algorithm
111
- * @function
112
- * @alias module:@aeternity/aepp-sdk/es/tx/builder/helpers
113
- * @param {string} data An Base58check or Base64check encoded and prefixed string (ex tx_..., sg_..., ak_....)
114
- * @param {string} [requiredPrefix] Ensure that data have this prefix
115
- * @return {Buffer} Decoded data
116
- */
117
- export function decode (data, requiredPrefix) {
118
- const [prefix, payload, extra] = data.split('_')
119
- if (extra) throw new Error(`Encoded string have extra parts: ${data}`)
120
- if (requiredPrefix && requiredPrefix !== prefix) {
121
- throw new Error(`Encoded string have a wrong type: ${prefix} (expected: ${requiredPrefix})`)
122
- }
123
- return (base64Types.includes(prefix) ? decodeBase64Check : decodeBase58Check)(payload)
109
+ // based on https://github.com/aeternity/protocol/blob/master/node/api/api_encoding.md
110
+ const base64Types = ['ba', 'cb', 'or', 'ov', 'pi', 'ss', 'cs', 'ck', 'cv', 'st', 'tx']
111
+ const base58Types = ['ak', 'bf', 'bs', 'bx', 'ch', 'cm', 'ct', 'kh', 'mh', 'nm', 'ok', 'oq', 'pp', 'sg', 'th']
112
+ // TODO: add all types with a fixed length
113
+ const typesLength = {
114
+ ak: 32,
115
+ ct: 32,
116
+ ok: 32
124
117
  }
125
118
 
126
- /**
127
- * Encode data using the default encoding/decoding algorithm
128
- * @function
129
- * @alias module:@aeternity/aepp-sdk/es/tx/builder/helpers
130
- * @param {Buffer|String} data An decoded data
131
- * @param {string} type Prefix of Transaction
132
- * @return {String} Encoded string Base58check or Base64check data
133
- */
134
- export function encode (data, type) {
135
- return `${type}_${base64Types.includes(type)
136
- ? encodeBase64Check(data)
137
- : encodeBase58Check(data)}`
119
+ function ensureValidLength (data, type) {
120
+ if (!typesLength[type]) return
121
+ if (data.length === typesLength[type]) return
122
+ throw new PayloadLengthError(`Payload should be ${typesLength[type]} bytes, got ${data.length} instead`)
123
+ }
124
+
125
+ const getChecksum = payload => sha256hash(sha256hash(payload)).slice(0, 4)
126
+
127
+ const addChecksum = (input) => {
128
+ const payload = Buffer.from(input)
129
+ return Buffer.concat([payload, getChecksum(payload)])
130
+ }
131
+
132
+ function getPayload (buffer) {
133
+ const payload = buffer.slice(0, -4)
134
+ if (!getChecksum(payload).equals(buffer.slice(-4))) throw new InvalidChecksumError()
135
+ return payload
136
+ }
137
+
138
+ const base64 = {
139
+ encode: buffer => addChecksum(buffer).toString('base64'),
140
+ decode: string => getPayload(Buffer.from(string, 'base64'))
141
+ }
142
+
143
+ const base58 = {
144
+ encode: buffer => bs58.encode(addChecksum(buffer)),
145
+ decode: string => getPayload(bs58.decode(string))
138
146
  }
139
147
 
140
148
  /**
@@ -145,9 +153,10 @@ export function encode (data, type) {
145
153
  * @return {Buffer} Buffer Buffer with ID tag and decoded HASh
146
154
  */
147
155
  export function writeId (hashId) {
156
+ if (typeof hashId !== 'string') throw new ArgumentError('hashId', 'a string', hashId)
148
157
  const prefix = hashId.slice(0, 2)
149
158
  const idTag = PREFIX_ID_TAG[prefix]
150
- if (!idTag) throw new Error(`Id tag for prefix ${prefix} not found.`)
159
+ if (!idTag) throw new TagNotFoundError(prefix)
151
160
  return Buffer.from([...toBytes(idTag), ...decode(hashId, prefix)])
152
161
  }
153
162
 
@@ -159,9 +168,9 @@ export function writeId (hashId) {
159
168
  * @return {String} Encoided hash string with prefix
160
169
  */
161
170
  export function readId (buf) {
162
- const tag = buf.readUIntBE(0, 1)
171
+ const tag = Buffer.from(buf).readUIntBE(0, 1)
163
172
  const prefix = ID_TAG_PREFIX[tag]
164
- if (!prefix) throw new Error(`Prefix for id-tag ${tag} not found.`)
173
+ if (!prefix) throw new PrefixNotFoundError(tag)
165
174
  return encode(buf.slice(1, buf.length), prefix)
166
175
  }
167
176
 
@@ -184,14 +193,15 @@ export function writeInt (val) {
184
193
  * @return {String} Buffer Buffer from number(BigEndian)
185
194
  */
186
195
  export function readInt (buf = Buffer.from([])) {
187
- return BigNumber(buf.toString('hex'), 16).toString(10)
196
+ return new BigNumber(Buffer.from(buf).toString('hex'), 16).toString(10)
188
197
  }
189
198
 
190
199
  /**
191
200
  * Helper function to build pointers for name update TX
192
201
  * @function
193
202
  * @alias module:@aeternity/aepp-sdk/es/tx/builder/helpers
194
- * @param {Array} pointers - Array of pointers ([ { key: 'account_pubkey', id: 'ak_32klj5j23k23j5423l434l2j3423'} ])
203
+ * @param {Array} pointers - Array of pointers
204
+ * ([ { key: 'account_pubkey', id: 'ak_32klj5j23k23j5423l434l2j3423'} ])
195
205
  * @return {Array} Serialized pointers array
196
206
  */
197
207
  export function buildPointers (pointers) {
@@ -207,7 +217,8 @@ export function buildPointers (pointers) {
207
217
  * Helper function to read pointers from name update TX
208
218
  * @function
209
219
  * @alias module:@aeternity/aepp-sdk/es/tx/builder/helpers
210
- * @param {Array} pointers - Array of pointers ([ { key: 'account_pubkey', id: 'ak_32klj5j23k23j5423l434l2j3423'} ])
220
+ * @param {Array} pointers - Array of pointers
221
+ * ([ { key: 'account_pubkey', id: 'ak_32klj5j23k23j5423l434l2j3423'} ])
211
222
  * @return {Array} Deserialize pointer array
212
223
  */
213
224
  export function readPointers (pointers) {
@@ -219,8 +230,10 @@ export function readPointers (pointers) {
219
230
  )
220
231
  }
221
232
 
233
+ const AENS_SUFFIX = '.chain'
234
+
222
235
  /**
223
- * Ensure that name is valid
236
+ * Ensure that AENS name is valid
224
237
  * @function
225
238
  * @alias module:@aeternity/aepp-sdk/es/tx/builder/helpers
226
239
  * @param {string} name
@@ -228,12 +241,12 @@ export function readPointers (pointers) {
228
241
  * @throws Error
229
242
  */
230
243
  export function ensureNameValid (name) {
231
- if (!name || typeof name !== 'string') throw new Error('Name must be a string')
232
- if (!name.endsWith('.chain')) throw new Error(`Name should end with .chain: ${name}`)
244
+ if (!name || typeof name !== 'string') throw new InvalidNameError('Name must be a string')
245
+ if (!name.endsWith(AENS_SUFFIX)) throw new InvalidNameError(`Name should end with ${AENS_SUFFIX}: ${name}`)
233
246
  }
234
247
 
235
248
  /**
236
- * Is name valid
249
+ * Is AENS name valid
237
250
  * @function
238
251
  * @alias module:@aeternity/aepp-sdk/es/tx/builder/helpers
239
252
  * @param {string} name
@@ -249,63 +262,44 @@ export function isNameValid (name) {
249
262
  }
250
263
 
251
264
  /**
252
- * What kind of a hash is this? If it begins with 'ak_' it is an
253
- * account key, if with 'ok_' it's an oracle key.
254
- *
255
- * @param s - the hash.
256
- * returns the type, or throws an exception if type not found.
257
- */
258
- export function classify (s) {
259
- if (!s.match(/^[a-z]{2}_.+/)) {
260
- throw new Error('Not a valid hash')
261
- }
262
-
263
- const klass = s.substr(0, 2)
264
- if (klass in NAME_ID_KEY) {
265
- return NAME_ID_KEY[klass]
266
- } else {
267
- throw new Error(`Unknown class ${klass}`)
268
- }
269
- }
270
-
271
- /**
272
- * Validate name pointers array
273
- * @function
274
- * @alias module:@aeternity/aepp-sdk/es/tx/builder/helpers
275
- * @param {String[]} pointers Pointers array. Allowed values is: account(ak_), oracle(ok_), contract(ct_), channel(ch_)
276
- * @return {Boolean}
265
+ * @param identifier - account/oracle/contract address, or channel
266
+ * @returns {String} default AENS pointer key
267
+ * @throws exception when default key not defined
277
268
  */
278
- export function validatePointers (pointers = []) {
279
- return !pointers
280
- .find(p => !p || typeof p !== 'string' || !['ak', 'ok', 'ct', 'ch'].includes(p.split('_')[0]))
269
+ export function getDefaultPointerKey (identifier) {
270
+ decode(identifier)
271
+ const prefix = identifier.substr(0, 2)
272
+ return POINTER_KEY_BY_PREFIX[prefix] ||
273
+ (() => { throw new NoDefaultAensPointerError(prefix) })()
281
274
  }
282
275
 
283
276
  /**
284
- * Get the minimum name fee for a domain
277
+ * Get the minimum AENS name fee
285
278
  * @function
286
279
  * @alias module:@aeternity/aepp-sdk/es/tx/builder/helpers
287
- * @param {String} domain the domain name to get the fee for
288
- * @return {String} the minimum fee for the domain auction
280
+ * @param {String} name the AENS name to get the fee for
281
+ * @return {String} the minimum fee for the AENS name auction
289
282
  */
290
- export function getMinimumNameFee (domain) {
291
- const nameLength = domain.replace('.chain', '').length
292
- return NAME_BID_RANGES[nameLength >= NAME_MAX_LENGTH_FEE ? NAME_MAX_LENGTH_FEE : nameLength]
283
+ export function getMinimumNameFee (name) {
284
+ ensureNameValid(name)
285
+ const nameLength = name.length - AENS_SUFFIX.length
286
+ return NAME_BID_RANGES[Math.min(nameLength, NAME_MAX_LENGTH_FEE)]
293
287
  }
294
288
 
295
289
  /**
296
290
  * Compute bid fee for AENS auction
297
291
  * @function
298
292
  * @alias module:@aeternity/aepp-sdk/es/tx/builder/helpers
299
- * @param {String} domain the domain name to get the fee for
293
+ * @param {String} name the AENS name to get the fee for
300
294
  * @param {Number|String} startFee Auction start fee
301
295
  * @param {Number} [increment=0.5] Bid multiplier(In percentage, must be between 0 and 1)
302
296
  * @return {String} Bid fee
303
297
  */
304
- export function computeBidFee (domain, startFee = NAME_FEE, increment = NAME_FEE_BID_INCREMENT) {
305
- if (!(Number(increment) === increment && increment % 1 !== 0)) throw new Error(`Increment must be float. Current increment ${increment}`)
306
- if (increment < NAME_FEE_BID_INCREMENT) throw new Error(`minimum increment percentage is ${NAME_FEE_BID_INCREMENT}`)
298
+ export function computeBidFee (name, startFee, increment = NAME_FEE_BID_INCREMENT) {
299
+ if (!(Number(increment) === increment && increment % 1 !== 0)) throw new IllegalBidFeeError(`Increment must be float. Current increment ${increment}`)
300
+ if (increment < NAME_FEE_BID_INCREMENT) throw new IllegalBidFeeError(`minimum increment percentage is ${NAME_FEE_BID_INCREMENT}`)
307
301
  return ceil(
308
- BigNumber(BigNumber(startFee).eq(NAME_FEE) ? getMinimumNameFee(domain) : startFee).times(BigNumber(NAME_FEE_BID_INCREMENT).plus(1))
302
+ BigNumber(startFee ?? getMinimumNameFee(name)).times(BigNumber(NAME_FEE_BID_INCREMENT).plus(1))
309
303
  )
310
304
  }
311
305
 
@@ -313,26 +307,28 @@ export function computeBidFee (domain, startFee = NAME_FEE, increment = NAME_FEE
313
307
  * Compute auction end height
314
308
  * @function
315
309
  * @alias module:@aeternity/aepp-sdk/es/tx/builder/helpers
316
- * @param {String} domain the domain name to get the fee for
310
+ * @param {String} name
317
311
  * @param {Number|String} claimHeight Auction starting height
318
312
  * @return {String} Auction end height
319
313
  */
320
- export function computeAuctionEndBlock (domain, claimHeight) {
321
- return R.cond([
322
- [R.lt(5), R.always(NAME_BID_TIMEOUTS[4].plus(claimHeight))],
323
- [R.lt(9), R.always(NAME_BID_TIMEOUTS[8].plus(claimHeight))],
324
- [R.lte(NAME_BID_MAX_LENGTH), R.always(NAME_BID_TIMEOUTS[12].plus(claimHeight))],
325
- [R.T, R.always(BigNumber(claimHeight))]
326
- ])(domain.replace('.chain', '').length).toString(10)
314
+ export function computeAuctionEndBlock (name, claimHeight) {
315
+ ensureNameValid(name)
316
+ const length = name.length - AENS_SUFFIX.length
317
+ const h = (length <= 4 && NAME_BID_TIMEOUTS[4]) ||
318
+ (length <= 8 && NAME_BID_TIMEOUTS[8]) ||
319
+ (length <= 12 && NAME_BID_TIMEOUTS[12]) ||
320
+ NAME_BID_TIMEOUTS[13]
321
+ return h.plus(claimHeight).toString(10)
327
322
  }
328
323
 
329
324
  /**
330
325
  * Is name accept going to auction
331
326
  * @function
332
327
  * @alias module:@aeternity/aepp-sdk/es/tx/builder/helpers
333
- * @param {String} name Transaction abiVersion
328
+ * @param {String} name
334
329
  * @return {Boolean}
335
330
  */
336
331
  export function isAuctionName (name) {
337
- return name.replace('.chain', '').length < 13
332
+ ensureNameValid(name)
333
+ return name.length < 13 + AENS_SUFFIX.length
338
334
  }
@@ -2,18 +2,17 @@ import BigNumber from 'bignumber.js'
2
2
  import { decode as rlpDecode, encode as rlpEncode } from 'rlp'
3
3
  import { AE_AMOUNT_FORMATS, formatAmount } from '../../utils/amount-formatter'
4
4
  import { hash } from '../../utils/crypto'
5
+ import { Field } from './field-types'
5
6
 
6
7
  import {
7
8
  DEFAULT_FEE,
8
9
  FIELD_TYPES,
9
10
  OBJECT_ID_TX_TYPE,
10
- PREFIX_ID_TAG,
11
11
  TX_DESERIALIZATION_SCHEMA,
12
12
  TX_FEE_BASE_GAS,
13
13
  TX_FEE_OTHER_GAS,
14
14
  TX_SERIALIZATION_SCHEMA,
15
15
  TX_TYPE,
16
- VALIDATION_MESSAGE,
17
16
  VSN
18
17
  } from './schema'
19
18
  import {
@@ -28,6 +27,7 @@ import {
28
27
  } from './helpers'
29
28
  import { toBytes } from '../../utils/bytes'
30
29
  import MPTree from '../../utils/mptree'
30
+ import { InvalidTxParamsError, SchemaNotFoundError } from '../../utils/errors'
31
31
 
32
32
  /**
33
33
  * JavaScript-based Transaction builder
@@ -50,7 +50,6 @@ function deserializeField (value, type, prefix) {
50
50
  return { vmVersion: readInt(Buffer.from([vm])), abiVersion: readInt(Buffer.from([abi])) }
51
51
  }
52
52
  case FIELD_TYPES.amount:
53
- return readInt(value)
54
53
  case FIELD_TYPES.int:
55
54
  return readInt(value)
56
55
  case FIELD_TYPES.id:
@@ -99,11 +98,12 @@ function deserializeField (value, type, prefix) {
99
98
  {}
100
99
  )
101
100
  default:
101
+ if (type.prototype instanceof Field) return type.deserialize(value)
102
102
  return value
103
103
  }
104
104
  }
105
105
 
106
- function serializeField (value, type, prefix) {
106
+ function serializeField (value, type, prefix, params) {
107
107
  switch (type) {
108
108
  case FIELD_TYPES.amount:
109
109
  case FIELD_TYPES.int:
@@ -144,44 +144,55 @@ function serializeField (value, type, prefix) {
144
144
  default: return value
145
145
  }
146
146
  default:
147
+ if (type.prototype instanceof Field) return type.serialize(value, params)
147
148
  return value
148
149
  }
149
150
  }
150
151
 
151
- function validateField (value, key, type, prefix) {
152
- const assert = (valid, params) => valid ? {} : { [key]: VALIDATION_MESSAGE[type](params) }
152
+ function validateField (value, type, prefix) {
153
153
  // All fields are required
154
- if (value === undefined || value === null) return { [key]: 'Field is required' }
154
+ if (value === undefined || value === null) return 'Field is required'
155
155
 
156
156
  // Validate type of value
157
157
  switch (type) {
158
158
  case FIELD_TYPES.amount:
159
159
  case FIELD_TYPES.int: {
160
- const isMinusValue = (!isNaN(value) || BigNumber.isBigNumber(value)) && BigNumber(value).lt(0)
161
- return assert((!isNaN(value) || BigNumber.isBigNumber(value)) && BigNumber(value).gte(0), { value, isMinusValue })
160
+ if (isNaN(value) && !BigNumber.isBigNumber(value)) {
161
+ return `${value} is not of type Number or BigNumber`
162
+ }
163
+ if (new BigNumber(value).lt(0)) return `${value} must be >= 0`
164
+ return
162
165
  }
163
166
  case FIELD_TYPES.id: {
164
167
  const prefixes = Array.isArray(prefix) ? prefix : [prefix]
165
- const p = prefixes.find(p => p === value.split('_')[0])
166
- return assert(p && PREFIX_ID_TAG[value.split('_')[0]], { value, prefix })
168
+ if (!prefixes.includes(value.split('_')[0])) {
169
+ return `'${value}' prefix doesn't match expected prefix '${prefix}'`
170
+ }
171
+ return
167
172
  }
168
- case FIELD_TYPES.binary:
169
- return assert(value.split('_')[0] === prefix, { prefix, value })
170
- case FIELD_TYPES.string:
171
- return assert(true)
172
173
  case FIELD_TYPES.ctVersion:
173
- return assert(typeof value === 'object' && Object.prototype.hasOwnProperty.call(value, 'abiVersion') && Object.prototype.hasOwnProperty.call(value, 'vmVersion'))
174
+ if (!value?.abiVersion || !value?.vmVersion) {
175
+ return 'Value must be an object with "vmVersion" and "abiVersion" fields'
176
+ }
177
+ return
174
178
  case FIELD_TYPES.pointers:
175
- return assert(Array.isArray(value) && !value.find(e => e !== Object(e)), { value })
176
- default:
177
- return {}
179
+ if (!Array.isArray(value)) return 'Value must be of type Array'
180
+ if (value.some(p => !p?.key || !p?.id)) {
181
+ return 'Value must contains only object\'s like \'{key: "account_pubkey", id: "ak_lkamsflkalsdalksdlasdlasdlamd"}\''
182
+ }
183
+ if (value.length > 32) {
184
+ return `Expected 32 pointers or less, got ${value.length} instead`
185
+ }
178
186
  }
179
187
  }
180
188
 
181
189
  function transformParams (params, schema, { denomination } = {}) {
182
190
  params = schema
183
191
  .filter(([_, t]) => t === FIELD_TYPES.amount)
184
- .reduce((acc, [key]) => ({ ...params, [key]: formatAmount(params[key], { denomination }) }), params)
192
+ .reduce(
193
+ (acc, [key]) => ({ ...params, [key]: formatAmount(params[key], { denomination }) }),
194
+ params
195
+ )
185
196
  const schemaKeys = schema.map(([k]) => k)
186
197
  return Object
187
198
  .entries(params)
@@ -291,12 +302,14 @@ export function calculateFee (fee = 0, txType, { gas = 0, params, showWarning =
291
302
  * @return {Object} Object with validation errors
292
303
  */
293
304
  export function validateParams (params, schema, { excludeKeys = [] }) {
294
- return schema
295
- .filter(([key]) => !excludeKeys.includes(key) && key !== 'payload')
296
- .reduce(
297
- (acc, [key, type, prefix]) => Object.assign(acc, validateField(params[key], key, type, prefix)),
298
- {}
299
- )
305
+ return Object.fromEntries(
306
+ schema
307
+ // TODO: allow optional keys in schema
308
+ .filter(([key]) => !excludeKeys.includes(key) &&
309
+ !['payload', 'nameFee', 'deposit'].includes(key))
310
+ .map(([key, type, prefix]) => [key, validateField(params[key], type, prefix)])
311
+ .filter(([, message]) => message)
312
+ )
300
313
  }
301
314
 
302
315
  /**
@@ -306,12 +319,16 @@ export function validateParams (params, schema, { excludeKeys = [] }) {
306
319
  * @param {Object} params Object with tx params
307
320
  * @param {Array} schema Transaction schema
308
321
  * @param {Object} [options={}] options
309
- * @param {Array} [options.excludeKeys=[]] excludeKeys Array of keys to exclude for validation and build
310
- * @param {String} [options.denomination='aettos'] denomination Denomination of amounts (default: aettos)
322
+ * @param {String[]} [options.excludeKeys=[]] Array of keys to exclude for validation and build
323
+ * @param {String} [options.denomination='aettos'] Denomination of amounts
311
324
  * @throws {Error} Validation error
312
325
  * @return {Array} Array with binary fields of transaction
313
326
  */
314
- export function buildRawTx (params, schema, { excludeKeys = [], denomination = AE_AMOUNT_FORMATS.AETTOS } = {}) {
327
+ export function buildRawTx (
328
+ params,
329
+ schema,
330
+ { excludeKeys = [], denomination = AE_AMOUNT_FORMATS.AETTOS } = {}
331
+ ) {
315
332
  const filteredSchema = schema.filter(([key]) => !excludeKeys.includes(key))
316
333
 
317
334
  // Transform `amount` type fields to `aettos`
@@ -319,11 +336,11 @@ export function buildRawTx (params, schema, { excludeKeys = [], denomination = A
319
336
  // Validation
320
337
  const valid = validateParams(params, schema, { excludeKeys })
321
338
  if (Object.keys(valid).length) {
322
- throw new Error('Transaction build error. ' + JSON.stringify(valid))
339
+ throw new InvalidTxParamsError('Transaction build error. ' + JSON.stringify(valid))
323
340
  }
324
341
 
325
342
  return filteredSchema
326
- .map(([key, fieldType, prefix]) => serializeField(params[key], fieldType, prefix))
343
+ .map(([key, fieldType, prefix]) => serializeField(params[key], fieldType, prefix, params))
327
344
  }
328
345
 
329
346
  /**
@@ -359,10 +376,10 @@ const getSchema = ({ vsn, objId, type }) => {
359
376
  const schema = isDeserialize ? TX_DESERIALIZATION_SCHEMA : TX_SERIALIZATION_SCHEMA
360
377
 
361
378
  if (!schema[firstKey]) {
362
- throw new Error(`Transaction ${isDeserialize ? 'deserialization' : 'serialization'} not implemented for ${isDeserialize ? 'tag ' + objId : type}`)
379
+ throw new SchemaNotFoundError(`Transaction ${isDeserialize ? 'deserialization' : 'serialization'} not implemented for ${isDeserialize ? 'tag ' + objId : type}`)
363
380
  }
364
381
  if (!schema[firstKey][vsn]) {
365
- throw new Error(`Transaction ${isDeserialize ? 'deserialization' : 'serialization'} not implemented for ${isDeserialize ? 'tag ' + objId : type} version ${vsn}`)
382
+ throw new SchemaNotFoundError(`Transaction ${isDeserialize ? 'deserialization' : 'serialization'} not implemented for ${isDeserialize ? 'tag ' + objId : type} version ${vsn}`)
366
383
  }
367
384
  return schema[firstKey][vsn]
368
385
  }
@@ -374,14 +391,25 @@ const getSchema = ({ vsn, objId, type }) => {
374
391
  * @param {Object} params Object with tx params
375
392
  * @param {String} type Transaction type
376
393
  * @param {Object} [options={}] options
377
- * @param {Object} [options.excludeKeys] excludeKeys Array of keys to exclude for validation and build
394
+ * @param {String[]} [options.excludeKeys] Array of keys to exclude for validation and build
378
395
  * @param {String} [options.prefix] Prefix of transaction
379
396
  * @throws {Error} Validation error
380
- * @return {Object} { tx, rlpEncoded, binary } Object with tx -> Base64Check transaction hash with 'tx_' prefix, rlp encoded transaction and binary transaction
397
+ * @returns {Object} object
398
+ * @returns {String} object.tx Base64Check transaction hash with 'tx_' prefix
399
+ * @returns {Buffer} object.rlpEncoded rlp encoded transaction
400
+ * @returns {Array<Buffer>} object.binary binary transaction
381
401
  */
382
- export function buildTx (params, type, { excludeKeys = [], prefix = 'tx', vsn = VSN, denomination = AE_AMOUNT_FORMATS.AETTOS } = {}) {
402
+ export function buildTx (
403
+ params,
404
+ type,
405
+ { excludeKeys = [], prefix = 'tx', vsn = VSN, denomination = AE_AMOUNT_FORMATS.AETTOS } = {}
406
+ ) {
383
407
  const [schema, tag] = getSchema({ type, vsn })
384
- const binary = buildRawTx({ ...params, VSN: vsn, tag }, schema, { excludeKeys, denomination: params.denomination || denomination }).filter(e => e !== undefined)
408
+ const binary = buildRawTx(
409
+ { ...params, VSN: vsn, tag },
410
+ schema,
411
+ { excludeKeys, denomination: params.denomination || denomination }
412
+ ).filter(e => e !== undefined)
385
413
 
386
414
  const rlpEncoded = rlpEncode(binary)
387
415
  const tx = encode(rlpEncoded, prefix)
@@ -393,10 +421,14 @@ export function buildTx (params, type, { excludeKeys = [], prefix = 'tx', vsn =
393
421
  * Unpack transaction hash
394
422
  * @function
395
423
  * @alias module:@aeternity/aepp-sdk/es/tx/builder
396
- * @param {String|Buffer} encodedTx String or RLP encoded transaction array (if fromRlpBinary flag is true)
424
+ * @param {String|Buffer} encodedTx String or RLP encoded transaction array
425
+ * (if fromRlpBinary flag is true)
397
426
  * @param {Boolean} fromRlpBinary Unpack from RLP encoded transaction (default: false)
398
427
  * @param {String} prefix - Prefix of data
399
- * @return {Object} { tx, rlpEncoded, binary } Object with tx -> Object with transaction param's, rlp encoded transaction and binary transaction
428
+ * @returns {Object} object
429
+ * @returns {Object} object.tx Object with transaction param's
430
+ * @returns {Buffer} object.rlpEncoded rlp encoded transaction
431
+ * @returns {Array<Buffer>} object.binary binary transaction
400
432
  */
401
433
  export function unpackTx (encodedTx, fromRlpBinary = false, prefix = 'tx') {
402
434
  const rlpEncoded = fromRlpBinary ? encodedTx : decode(encodedTx, prefix)
@@ -421,4 +453,13 @@ export function buildTxHash (rawTx) {
421
453
  return encode(hash(data), 'th')
422
454
  }
423
455
 
424
- export default { calculateMinFee, calculateFee, unpackTx, unpackRawTx, buildTx, buildRawTx, validateParams, buildTxHash }
456
+ export default {
457
+ calculateMinFee,
458
+ calculateFee,
459
+ unpackTx,
460
+ unpackRawTx,
461
+ buildTx,
462
+ buildRawTx,
463
+ validateParams,
464
+ buildTxHash
465
+ }