@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
@@ -19,7 +19,7 @@ import { w3cwebsocket as W3CWebSocket } from 'websocket'
19
19
  import { EventEmitter } from 'events'
20
20
  import JsonBig from '../utils/json-big'
21
21
  import { pascalToSnake } from '../utils/string'
22
- import { awaitingConnection, awaitingReconnection, channelOpen } from './handlers'
22
+ import { ChannelCallError, ChannelPingTimedOutError, UnknownChannelStateError } from '../utils/errors'
23
23
 
24
24
  // Send ping message every 10 seconds
25
25
  const PING_TIMEOUT_MS = 10000
@@ -49,7 +49,7 @@ export function emit (channel, ...args) {
49
49
 
50
50
  function enterState (channel, nextState) {
51
51
  if (!nextState) {
52
- throw new Error('State Channels FSM entered unknown state')
52
+ throw new UnknownChannelStateError()
53
53
  }
54
54
  fsm.set(channel, nextState)
55
55
  if (nextState.handler.enter) {
@@ -109,16 +109,21 @@ async function handleMessage (channel, message) {
109
109
  }
110
110
 
111
111
  async function dequeueMessage (channel) {
112
- const queue = messageQueue.get(channel)
113
- if (messageQueueLocked.get(channel) || !queue.length) {
114
- return
115
- }
116
- const [message, ...remaining] = queue
117
- messageQueue.set(channel, remaining || [])
112
+ if (messageQueueLocked.get(channel)) return
113
+ const messages = messageQueue.get(channel)
114
+ if (!messages.length) return
118
115
  messageQueueLocked.set(channel, true)
119
- await handleMessage(channel, message)
116
+ while (messages.length) {
117
+ const message = messages.shift()
118
+ try {
119
+ await handleMessage(channel, message)
120
+ } catch (error) {
121
+ console.error('Error handling incoming message:')
122
+ console.error(message)
123
+ console.error(error)
124
+ }
125
+ }
120
126
  messageQueueLocked.set(channel, false)
121
- dequeueMessage(channel)
122
127
  }
123
128
 
124
129
  function ping (channel) {
@@ -134,7 +139,7 @@ function ping (channel) {
134
139
  })
135
140
  pongTimeoutId.set(channel, setTimeout(() => {
136
141
  disconnect(channel)
137
- emit(channel, 'error', new Error('Server pong timed out'))
142
+ emit(channel, 'error', new ChannelPingTimedOutError())
138
143
  }, PONG_TIMEOUT_MS))
139
144
  }, PING_TIMEOUT_MS))
140
145
  }
@@ -150,9 +155,13 @@ function onMessage (channel, data) {
150
155
  } finally {
151
156
  rpcCallbacks.get(channel).delete(message.id)
152
157
  }
153
- } else if (message.method === 'channels.message') {
158
+ return
159
+ }
160
+ if (message.method === 'channels.message') {
154
161
  emit(channel, 'message', message.params.data.message)
155
- } else if (message.method === 'channels.system.pong') {
162
+ return
163
+ }
164
+ if (message.method === 'channels.system.pong') {
156
165
  if (
157
166
  (message.params.channel_id === channelId.get(channel)) ||
158
167
  // Skip channelId check if channelId is not known yet
@@ -160,18 +169,10 @@ function onMessage (channel, data) {
160
169
  ) {
161
170
  ping(channel)
162
171
  }
163
- } else {
164
- messageQueue.set(channel, [...(messageQueue.get(channel) || []), message])
165
- dequeueMessage(channel)
166
- }
167
- }
168
-
169
- function wrapCallErrorMessage (message) {
170
- const [{ message: details } = {}] = message.error.data || []
171
- if (details) {
172
- return new Error(`${message.error.message}: ${details}`)
172
+ return
173
173
  }
174
- return new Error(message.error.message)
174
+ messageQueue.get(channel).push(message)
175
+ dequeueMessage(channel)
175
176
  }
176
177
 
177
178
  export function call (channel, method, params) {
@@ -179,7 +180,10 @@ export function call (channel, method, params) {
179
180
  const id = sequence.set(channel, sequence.get(channel) + 1).get(channel)
180
181
  rpcCallbacks.get(channel).set(id, (message) => {
181
182
  if (message.result) return resolve(message.result)
182
- if (message.error) return reject(wrapCallErrorMessage(message))
183
+ if (message.error) {
184
+ const [{ message: details } = {}] = message.error.data || []
185
+ return reject(new ChannelCallError(message.error.message + (details ? `: ${details}` : '')))
186
+ }
183
187
  })
184
188
  send(channel, { jsonrpc: '2.0', method, id, params })
185
189
  })
@@ -191,14 +195,15 @@ export function disconnect (channel) {
191
195
  clearTimeout(pongTimeoutId.get(channel))
192
196
  }
193
197
 
194
- export async function initialize (channel, { url, ...channelOptions }) {
198
+ export async function initialize (
199
+ channel, connectionHandler, openHandler, { url, ...channelOptions }
200
+ ) {
195
201
  options.set(channel, channelOptions)
196
- fsm.set(channel, {
197
- handler: channelOptions.existingFsmId ? awaitingReconnection : awaitingConnection
198
- })
202
+ fsm.set(channel, { handler: connectionHandler })
199
203
  eventEmitters.set(channel, new EventEmitter())
200
204
  sequence.set(channel, 0)
201
205
  rpcCallbacks.set(channel, new Map())
206
+ messageQueue.set(channel, [])
202
207
 
203
208
  const wsUrl = new URL(url)
204
209
  Object.entries(channelOptions)
@@ -213,7 +218,7 @@ export async function initialize (channel, { url, ...channelOptions }) {
213
218
  resolve()
214
219
  changeStatus(channel, 'connected')
215
220
  if (channelOptions.reconnectTx) {
216
- enterState(channel, { handler: channelOpen })
221
+ enterState(channel, { handler: openHandler })
217
222
  setTimeout(async () => changeState(channel,
218
223
  (await call(channel, 'channels.get.offchain_state', {})).signed_tx
219
224
  ))
@@ -0,0 +1,376 @@
1
+ /*
2
+ * ISC License (ISC)
3
+ * Copyright (c) 2018 aeternity developers
4
+ *
5
+ * Permission to use, copy, modify, and/or distribute this software for any
6
+ * purpose with or without fee is hereby granted, provided that the above
7
+ * copyright notice and this permission notice appear in all copies.
8
+ *
9
+ * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
10
+ * REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
11
+ * AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
12
+ * INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
13
+ * LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
14
+ * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
15
+ * PERFORMANCE OF THIS SOFTWARE.
16
+ */
17
+
18
+ /**
19
+ * ContractACI module
20
+ *
21
+ * @module @aeternity/aepp-sdk/es/contract/aci
22
+ * @export getContractInstance
23
+ */
24
+
25
+ import { Encoder as Calldata } from '@aeternity/aepp-calldata'
26
+ import { DRY_RUN_ACCOUNT, GAS_MAX } from '../tx/builder/schema'
27
+ import TxObject from '../tx/tx-object'
28
+ import { decode } from '../tx/builder/helpers'
29
+ import {
30
+ MissingContractDefError,
31
+ MissingContractAddressError,
32
+ InactiveContractError,
33
+ BytecodeMismatchError,
34
+ InternalError,
35
+ DuplicateContractError,
36
+ MissingFunctionNameError,
37
+ InvalidMethodInvocationError,
38
+ NotPayableFunctionError,
39
+ TypeError,
40
+ NodeInvocationError,
41
+ IllegalArgumentError,
42
+ NoSuchContractFunctionError,
43
+ MissingEventDefinitionError,
44
+ AmbiguousEventDefinitionError
45
+ } from '../utils/errors'
46
+ import { hash } from '../utils/crypto-ts'
47
+
48
+ /**
49
+ * Generate contract ACI object with predefined js methods for contract usage - can be used for
50
+ * creating a reference to already deployed contracts
51
+ * @alias module:@aeternity/aepp-sdk/es/contract/aci
52
+ * @param {Object} [options={}] Options object
53
+ * @param {String} [options.source] Contract source code
54
+ * @param {String} [options.bytecode] Contract bytecode
55
+ * @param {Object} [options.aci] Contract ACI
56
+ * @param {String} [options.contractAddress] Contract address
57
+ * @param {Object} [options.filesystem] Contact source external namespaces map
58
+ * @param {Boolean} [options.validateBytecode] Compare source code with on-chain version
59
+ * @return {ContractInstance} JS Contract API
60
+ * @example
61
+ * const contractIns = await aeSdk.getContractInstance({ source })
62
+ * await contractIns.deploy([321]) or await contractIns.methods.init(321)
63
+ * const callResult = await contractIns.call('setState', [123]) or
64
+ * await contractIns.methods.setState.send(123, options)
65
+ * const staticCallResult = await contractIns.call('setState', [123], { callStatic: true }) or
66
+ * await contractIns.methods.setState.get(123, options)
67
+ * Also you can call contract like: await contractIns.methods.setState(123, options)
68
+ * Then sdk decide to make on-chain or static call(dry-run API) transaction based on function is
69
+ * stateful or not
70
+ */
71
+ export default async function getContractInstance ({
72
+ source,
73
+ bytecode,
74
+ aci: _aci,
75
+ contractAddress,
76
+ filesystem = {},
77
+ validateBytecode,
78
+ ...otherOptions
79
+ } = {}) {
80
+ if (!_aci && source) {
81
+ _aci = await this.compilerApi.generateACI({ code: source, options: { filesystem } })
82
+ }
83
+ if (!_aci) throw new MissingContractDefError()
84
+ contractAddress = contractAddress && await this.resolveName(
85
+ contractAddress, 'contract_pubkey', { resolveByNode: true }
86
+ )
87
+ if (!contractAddress && !source && !bytecode) {
88
+ throw new MissingContractAddressError('Can\'t create instance by ACI without address')
89
+ }
90
+
91
+ if (contractAddress) {
92
+ const contract = await this.getContract(contractAddress)
93
+ if (!contract.active) throw new InactiveContractError(contractAddress)
94
+ }
95
+
96
+ const instance = {
97
+ _aci,
98
+ _name: _aci.encoded_aci.contract.name,
99
+ calldata: new Calldata([_aci.encoded_aci, ..._aci.external_encoded_aci]),
100
+ source,
101
+ bytecode,
102
+ deployInfo: { address: contractAddress },
103
+ options: {
104
+ ...this.Ae.defaults,
105
+ callStatic: false,
106
+ filesystem,
107
+ ...otherOptions
108
+ },
109
+ compilerVersion: this.compilerVersion
110
+ }
111
+
112
+ if (validateBytecode) {
113
+ if (!contractAddress) throw new MissingContractAddressError('Can\'t validate bytecode without contract address')
114
+ const onChanBytecode = (await this.getContractByteCode(contractAddress)).bytecode
115
+ const isValid = source
116
+ ? await this.compilerApi.validateByteCode(
117
+ { bytecode: onChanBytecode, source, options: instance.options }
118
+ ).then((res) => Object.entries(res).length === 0, () => false)
119
+ : bytecode === onChanBytecode
120
+ if (!isValid) throw new BytecodeMismatchError(source ? 'source' : 'bytecode')
121
+ }
122
+
123
+ /**
124
+ * Compile contract
125
+ * @alias module:@aeternity/aepp-sdk/es/contract/aci
126
+ * @rtype () => ContractInstance: Object
127
+ * @return {String} bytecode bytecode
128
+ */
129
+ instance.compile = async (options = {}) => {
130
+ if (instance.bytecode) throw new IllegalArgumentError('Contract already compiled')
131
+ if (!instance.source) throw new IllegalArgumentError('Can\'t compile without source code')
132
+ const { bytecode } = await this.compilerApi.compileContract({
133
+ code: instance.source, options: { ...instance.options, ...options }
134
+ })
135
+ instance.bytecode = bytecode
136
+ return instance.bytecode
137
+ }
138
+
139
+ const sendAndProcess = async (tx, options) => {
140
+ const txData = await this.send(tx, options)
141
+ const result = {
142
+ hash: txData.hash, tx: TxObject({ tx: txData.rawTx }), txData, rawTx: txData.rawTx
143
+ }
144
+ if (options.waitMined === false) return result
145
+ const { callInfo } = await this.api.getTransactionInfoByHash(txData.hash)
146
+ Object.assign(result.txData, callInfo) // TODO: don't duplicate data in result
147
+ await handleCallError(callInfo)
148
+ return { ...result, result: callInfo }
149
+ }
150
+
151
+ const handleCallError = ({ returnType, returnValue }) => {
152
+ let message
153
+ // TODO: ensure that it works correctly https://github.com/aeternity/aepp-calldata-js/issues/88
154
+ switch (returnType) {
155
+ case 'ok': return
156
+ case 'revert':
157
+ message = instance.calldata.decodeFateString(returnValue)
158
+ break
159
+ case 'error':
160
+ message = decode(returnValue).toString()
161
+ break
162
+ default: throw new InternalError(`Unknown returnType: ${returnType}`)
163
+ }
164
+ throw new NodeInvocationError(message)
165
+ }
166
+
167
+ instance._estimateGas = async (name, params, options) => {
168
+ const { result: { gasUsed } } =
169
+ await instance.call(name, params, { ...options, callStatic: true })
170
+ // taken from https://github.com/aeternity/aepp-sdk-js/issues/1286#issuecomment-977814771
171
+ return Math.floor(gasUsed * 1.25)
172
+ }
173
+
174
+ /**
175
+ * Deploy contract
176
+ * @alias module:@aeternity/aepp-sdk/es/contract/aci
177
+ * @rtype (init: Array, options: Object) => ContractInstance: Object
178
+ * @param {Array} params Contract init function arguments array
179
+ * @param {Object} [options] options
180
+ * @return {Object} deploy info
181
+ */
182
+ instance.deploy = async (params = [], options) => {
183
+ const opt = { ...instance.options, ...options }
184
+ if (!instance.bytecode) await instance.compile(opt)
185
+ if (opt.callStatic) return instance.call('init', params, opt)
186
+ if (instance.deployInfo.address) throw new DuplicateContractError()
187
+
188
+ const ownerId = await this.address(opt)
189
+ const { tx, contractId } = await this.contractCreateTx({
190
+ ...opt,
191
+ gas: opt.gas ?? await instance._estimateGas('init', params, opt),
192
+ callData: instance.calldata.encode(instance._name, 'init', params),
193
+ code: instance.bytecode,
194
+ ownerId
195
+ })
196
+ const { hash, rawTx, result, txData } = await sendAndProcess(tx, opt)
197
+ instance.deployInfo = Object.freeze({
198
+ result,
199
+ owner: ownerId,
200
+ transaction: hash,
201
+ rawTx,
202
+ txData,
203
+ address: contractId
204
+ })
205
+ return instance.deployInfo
206
+ }
207
+
208
+ /**
209
+ * Get function schema from contract ACI object
210
+ * @param {String} name Function name
211
+ * @return {Object} function ACI
212
+ */
213
+ function getFunctionACI (name) {
214
+ const fn = instance._aci.encoded_aci.contract.functions.find(f => f.name === name)
215
+ if (fn) return fn
216
+ if (name === 'init') return { payable: false }
217
+ throw new NoSuchContractFunctionError(`Function ${name} doesn't exist in contract`)
218
+ }
219
+
220
+ /**
221
+ * Call contract function
222
+ * @alias module:@aeternity/aepp-sdk/es/contract/aci
223
+ * @rtype (init: Array, options: Object = { callStatic: false }) => CallResult: Object
224
+ * @param {String} fn Function name
225
+ * @param {Array} params Array of function arguments
226
+ * @param {Object} [options={}] Array of function arguments
227
+ * @param {Boolean} [options.callStatic=false] Static function call
228
+ * @return {Object} CallResult
229
+ */
230
+ instance.call = async (fn, params = [], options = {}) => {
231
+ const opt = { ...instance.options, ...options }
232
+ const fnACI = getFunctionACI(fn)
233
+ const contractId = instance.deployInfo.address
234
+
235
+ if (!fn) throw new MissingFunctionNameError()
236
+ if (fn === 'init' && !opt.callStatic) throw new InvalidMethodInvocationError('"init" can be called only via dryRun')
237
+ if (!contractId && fn !== 'init') throw new InvalidMethodInvocationError('You need to deploy contract before calling!')
238
+ if (fn !== 'init' && opt.amount > 0 && fnACI.payable === false) throw new NotPayableFunctionError(`You try to pay "${opt.amount}" to function "${fn}" which is not payable. Only payable function can accept coins`)
239
+
240
+ const callerId = await this.address(opt).catch(error => {
241
+ if (opt.callStatic) return DRY_RUN_ACCOUNT.pub
242
+ else throw error
243
+ })
244
+ const callData = instance.calldata.encode(instance._name, fn, params)
245
+
246
+ let res
247
+ if (opt.callStatic) {
248
+ if (typeof opt.top === 'number') {
249
+ opt.top = (await this.getKeyBlock(opt.top)).hash
250
+ }
251
+ const txOpt = {
252
+ ...opt,
253
+ gas: opt.gas ?? GAS_MAX,
254
+ callData,
255
+ nonce: opt.nonce ??
256
+ (opt.top && (await this.getAccount(callerId, { hash: opt.top })).nonce + 1)
257
+ }
258
+ const tx = fn === 'init'
259
+ ? (await this.contractCreateTx({ ...txOpt, code: instance.bytecode, ownerId: callerId })).tx
260
+ : await this.contractCallTx({ ...txOpt, callerId, contractId })
261
+
262
+ const { callObj, ...dryRunOther } = await this.txDryRun(tx, callerId, opt)
263
+ await handleCallError(callObj)
264
+ res = { ...dryRunOther, tx: TxObject({ tx }), result: callObj }
265
+ } else {
266
+ const tx = await this.contractCallTx({
267
+ ...opt,
268
+ gas: opt.gas ?? await instance._estimateGas(fn, params, opt),
269
+ callerId,
270
+ contractId,
271
+ callData
272
+ })
273
+ res = await sendAndProcess(tx, opt)
274
+ }
275
+ if (opt.waitMined || opt.callStatic) {
276
+ res.decodedResult = fnACI.returns && fnACI.returns !== 'unit' && fn !== 'init' &&
277
+ instance.calldata.decode(instance._name, fn, res.result.returnValue)
278
+ res.decodedEvents = instance.decodeEvents(res.result.log, opt)
279
+ }
280
+ return res
281
+ }
282
+
283
+ /**
284
+ * @param {String} address Contract address that emitted event
285
+ * @param {BigInt} nameHash Hash of emitted event name
286
+ * @param {Object} [options]
287
+ * @param {Object} [options.contractAddressToName] Map of contract addresses to their names
288
+ * @return {String} Contract name
289
+ * @throws {MissingEventDefinitionError}
290
+ * @throws {AmbiguousEventDefinitionError}
291
+ */
292
+ function getContractNameByEvent (address, nameHash, { contractAddressToName }) {
293
+ const addressToName = { ...instance.options.contractAddressToName, ...contractAddressToName }
294
+ if (addressToName[address]) return addressToName[address]
295
+
296
+ const matchedEvents = [
297
+ instance._aci.encoded_aci,
298
+ ...instance._aci.external_encoded_aci
299
+ ]
300
+ .filter(({ contract }) => contract?.event)
301
+ .map(({ contract }) => [contract.name, contract.event.variant])
302
+ .map(([name, events]) => events.map(event => [name, Object.keys(event)[0]]))
303
+ .flat()
304
+ .filter(([, eventName]) => BigInt('0x' + hash(eventName).toString('hex')) === nameHash)
305
+ switch (matchedEvents.length) {
306
+ case 0: throw new MissingEventDefinitionError(nameHash, address)
307
+ case 1: return matchedEvents[0][0]
308
+ default: throw new AmbiguousEventDefinitionError(address, matchedEvents)
309
+ }
310
+ }
311
+
312
+ /**
313
+ * Decode Events
314
+ * @alias module:@aeternity/aepp-sdk/es/contract/aci
315
+ * @rtype (events: Array) => DecodedEvents: Array
316
+ * @param {Array} events Array of encoded events (callRes.result.log)
317
+ * @param {Object} [options]
318
+ * @param {Boolean} [options.omitUnknown] Omit events that can't be decoded in case ACI is not
319
+ * complete
320
+ * @return {Object} DecodedEvents
321
+ */
322
+ instance.decodeEvents = (events, { omitUnknown, ...opt } = {}) => events
323
+ .map(event => {
324
+ const topics = event.topics.map(t => BigInt(t))
325
+ let contractName
326
+ try {
327
+ contractName = getContractNameByEvent(event.address, topics[0], opt)
328
+ } catch (error) {
329
+ if (omitUnknown && error instanceof MissingEventDefinitionError) return null
330
+ throw error
331
+ }
332
+ const decoded = instance.calldata.decodeEvent(contractName, event.data, topics)
333
+ const [name, args] = Object.entries(decoded)[0]
334
+ return {
335
+ name,
336
+ args,
337
+ contract: {
338
+ name: contractName,
339
+ address: event.address
340
+ }
341
+ }
342
+ })
343
+ .filter(e => e)
344
+
345
+ /**
346
+ * Generate proto function based on contract function using Contract ACI schema
347
+ * All function can be called like:
348
+ * 'await contract.methods.testFunction()' -> then sdk will decide to use dry-run or send tx
349
+ * on-chain base on if function stateful or not.
350
+ * Also you can manually do that:
351
+ * `await contract.methods.testFunction.get()` -> use call-static(dry-run)
352
+ * `await contract.methods.testFunction.send()` -> send tx on-chain
353
+ */
354
+ instance.methods = Object.fromEntries(instance._aci.encoded_aci.contract.functions
355
+ .map(({ name, arguments: aciArgs, stateful }) => {
356
+ const genHandler = callStatic => (...args) => {
357
+ const options = args.length === aciArgs.length + 1 ? args.pop() : {}
358
+ if (typeof options !== 'object') throw new TypeError(`Options should be an object: ${options}`)
359
+ if (name === 'init') return instance.deploy(args, { callStatic, ...options })
360
+ return instance.call(name, args, { callStatic, ...options })
361
+ }
362
+ return [
363
+ name,
364
+ Object.assign(
365
+ genHandler(name === 'init' ? false : !stateful),
366
+ {
367
+ get: genHandler(true),
368
+ send: genHandler(false)
369
+ }
370
+ )
371
+ ]
372
+ })
373
+ )
374
+
375
+ return instance
376
+ }
@@ -1,6 +1,6 @@
1
1
  /*
2
2
  * ISC License (ISC)
3
- * Copyright (c) 2018 aeternity developers
3
+ * Copyright (c) 2021 aeternity developers
4
4
  *
5
5
  * Permission to use, copy, modify, and/or distribute this software for any
6
6
  * purpose with or without fee is hereby granted, provided that the above
@@ -16,18 +16,18 @@
16
16
  */
17
17
 
18
18
  /**
19
- * ContractCompilerAPI module
19
+ * ContractCompilerHttp module
20
20
  *
21
- * This is the complement to {@link module:@aeternity/aepp-sdk/es/contract}.
22
21
  * @module @aeternity/aepp-sdk/es/contract/compiler
23
- * @export ContractCompilerAPI
24
- * @example import { ContractCompilerAPI } from '@aeternity/aepp-sdk'
22
+ * @export ContractCompilerHttp
23
+ * @example import { ContractCompilerHttp } from '@aeternity/aepp-sdk'
25
24
  */
26
25
 
27
- import ContractBase from './index'
28
26
  import semverSatisfies from '../utils/semver-satisfies'
29
27
  import AsyncInit from '../utils/async-init'
30
28
  import genSwaggerClient from '../utils/swagger'
29
+ import { MissingParamError, UnsupportedVersionError } from '../utils/errors'
30
+ import { mapObject } from '../utils/other'
31
31
 
32
32
  /**
33
33
  * Contract Compiler Stamp
@@ -39,16 +39,16 @@ import genSwaggerClient from '../utils/swagger'
39
39
  * @param {Object} [options={}] - Initializer object
40
40
  * @param {String} [options.compilerUrl] compilerUrl - Url for compiler API
41
41
  * @return {Object} Contract compiler instance
42
- * @example ContractCompilerAPI({ compilerUrl: 'COMPILER_URL' })
42
+ * @example ContractCompilerHttp({ compilerUrl: 'COMPILER_URL' })
43
43
  */
44
- export default AsyncInit.compose(ContractBase, {
44
+ export default AsyncInit.compose({
45
45
  async init ({ compilerUrl, ignoreVersion }) {
46
46
  if (!compilerUrl) return
47
47
  await this.setCompilerUrl(compilerUrl, { ignoreVersion })
48
48
  },
49
49
  methods: {
50
50
  async setCompilerUrl (compilerUrl, { ignoreVersion = false } = {}) {
51
- if (!compilerUrl) throw new Error('"compilerUrl" required')
51
+ if (!compilerUrl) throw new MissingParamError('compilerUrl required')
52
52
  compilerUrl = compilerUrl.replace(/\/$/, '')
53
53
  const client = await genSwaggerClient(`${compilerUrl}/api`, {
54
54
  disableBigNumbers: true,
@@ -73,113 +73,22 @@ export default AsyncInit.compose(ContractBase, {
73
73
  }
74
74
  })
75
75
  this.compilerVersion = client.spec.info.version
76
- this._compilerApi = client.api
76
+ this.compilerApi = mapObject(
77
+ client.api,
78
+ ([key, fn]) => [
79
+ key,
80
+ ({ options: { filesystem, ...options } = {}, ...args } = {}) => fn({
81
+ ...args, options: { ...options, file_system: filesystem }
82
+ })
83
+ ]
84
+ )
77
85
 
78
86
  if (ignoreVersion) return
79
87
  if (!semverSatisfies(this.compilerVersion, COMPILER_GE_VERSION, COMPILER_LT_VERSION)) {
80
- throw new Error(`Unsupported compiler version ${this.compilerVersion}. ` +
81
- `Supported: >= ${COMPILER_GE_VERSION} < ${COMPILER_LT_VERSION}`)
88
+ throw new UnsupportedVersionError(
89
+ 'compiler', this.compilerVersion, COMPILER_GE_VERSION, COMPILER_LT_VERSION
90
+ )
82
91
  }
83
- },
84
- _ensureCompilerReady () {
85
- if (!this._compilerApi) throw new Error('Compiler is not ready')
86
- },
87
- _prepareCompilerOptions ({ filesystem = {} } = {}) {
88
- return { file_system: filesystem }
89
- },
90
- getCompilerVersion () {
91
- this._ensureCompilerReady()
92
- return Promise.resolve(this.compilerVersion)
93
- },
94
- /**
95
- * Encode call data for contract call
96
- * @function
97
- * @category async
98
- * @param {String} source Contract source code
99
- * @param {String} name Name of function to call
100
- * @param {Array} args Argument's for call
101
- * @param {Object} [options={}] Options
102
- * @param {Object} [options.filesystem={}] Contract external namespaces map
103
- * @return {Promise<String>}
104
- */
105
- async contractEncodeCallDataAPI (source, name, args = [], options) {
106
- this._ensureCompilerReady()
107
- const { calldata } = await this._compilerApi.encodeCalldata({
108
- source,
109
- function: name,
110
- arguments: args,
111
- options: this._prepareCompilerOptions(options)
112
- })
113
- return calldata
114
- },
115
- async compileContractAPI (code, options) {
116
- this._ensureCompilerReady()
117
- const { bytecode } = await this._compilerApi.compileContract({
118
- code,
119
- options: this._prepareCompilerOptions(options)
120
- })
121
- return bytecode
122
- },
123
- contractGetACI (code, options) {
124
- this._ensureCompilerReady()
125
- return this._compilerApi.generateACI({ code, options: this._prepareCompilerOptions(options) })
126
- },
127
- contractDecodeCallDataByCodeAPI (bytecode, calldata) {
128
- this._ensureCompilerReady()
129
- return this._compilerApi.decodeCalldataBytecode({ bytecode, calldata })
130
- },
131
- contractDecodeCallDataBySourceAPI (source, fn, callData, options) {
132
- this._ensureCompilerReady()
133
- return this._compilerApi.decodeCalldataSource({
134
- function: fn,
135
- source,
136
- calldata: callData,
137
- options: this._prepareCompilerOptions(options)
138
- })
139
- },
140
- /**
141
- * Decode contract call result data
142
- * @function
143
- * @category async
144
- * @param {String} source - source code
145
- * @param {String } fn - function name
146
- * @param {String} callValue - result call data
147
- * @param {String} callResult - result status
148
- * @param {Object} [options={}] Options
149
- * @param {Object} [options.filesystem={}] Contract external namespaces map
150
- * @return {Promise<String>} Result object
151
- * @example
152
- * const decodedData = await sdk.contractDecodeCallResultAPI(SourceCode ,'functionName', 'cb_asdasdasd...', 'ok|revert')lt
153
- */
154
- contractDecodeCallResultAPI (source, fn, callValue, callResult, options) {
155
- this._ensureCompilerReady()
156
- return this._compilerApi.decodeCallResult({
157
- function: fn,
158
- source,
159
- 'call-result': callResult,
160
- 'call-value': callValue,
161
- options: this._prepareCompilerOptions(options)
162
- })
163
- },
164
- async validateByteCodeAPI (bytecode, source, options) {
165
- this._ensureCompilerReady()
166
- const res = await this._compilerApi.validateByteCode({
167
- bytecode,
168
- source,
169
- options: this._prepareCompilerOptions(options)
170
- })
171
- return typeof res === 'object' ? true : res
172
- },
173
- getFateAssembler (bytecode, options) {
174
- this._ensureCompilerReady()
175
- return this._compilerApi.getFateAssemblerCode({ bytecode, options: this._prepareCompilerOptions(options) })
176
- },
177
- getBytecodeCompilerVersion (bytecode, options) {
178
- this._ensureCompilerReady()
179
- return this._compilerApi.getCompilerVersion({
180
- bytecode,
181
- options: this._prepareCompilerOptions(options)
182
- })
183
92
  }
184
93
  },
185
94
  props: {
@@ -187,5 +96,5 @@ export default AsyncInit.compose(ContractBase, {
187
96
  }
188
97
  })
189
98
 
190
- const COMPILER_GE_VERSION = '6.0.0'
99
+ const COMPILER_GE_VERSION = '6.1.0'
191
100
  const COMPILER_LT_VERSION = '7.0.0'