@aeternity/aepp-sdk 14.0.0 → 14.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (205) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +11 -19
  3. package/dist/aepp-sdk.browser-script.cjs +1 -1
  4. package/dist/aepp-sdk.browser-script.cjs.LICENSE.txt +2 -0
  5. package/dist/aepp-sdk.browser-script.cjs.map +1 -1
  6. package/dist/aepp-sdk.browser.cjs +1 -1
  7. package/dist/aepp-sdk.browser.cjs.map +1 -1
  8. package/dist/aepp-sdk.cjs +11678 -6969
  9. package/dist/aepp-sdk.cjs.map +1 -1
  10. package/es/AeSdkBase.d.ts +10 -1
  11. package/es/AeSdkBase.js +12 -2
  12. package/es/AeSdkBase.js.map +1 -1
  13. package/es/AeSdkMethods.d.ts +1 -1
  14. package/es/AeSdkMethods.js.map +1 -1
  15. package/es/AeSdkWallet.js +1 -1
  16. package/es/AeSdkWallet.js.map +1 -1
  17. package/es/Middleware.d.ts +5 -1
  18. package/es/Middleware.js +7 -2
  19. package/es/Middleware.js.map +1 -1
  20. package/es/MiddlewareSubscriber.d.ts +3 -0
  21. package/es/MiddlewareSubscriber.js +4 -0
  22. package/es/MiddlewareSubscriber.js.map +1 -1
  23. package/es/Node.d.ts +6 -1
  24. package/es/Node.js +28 -4
  25. package/es/Node.js.map +1 -1
  26. package/es/account/Base.d.ts +12 -0
  27. package/es/account/Base.js +1 -0
  28. package/es/account/Base.js.map +1 -1
  29. package/es/account/BaseFactory.d.ts +1 -0
  30. package/es/account/BaseFactory.js +1 -0
  31. package/es/account/BaseFactory.js.map +1 -1
  32. package/es/account/Generalized.d.ts +5 -0
  33. package/es/account/Generalized.js +9 -0
  34. package/es/account/Generalized.js.map +1 -1
  35. package/es/account/Ledger.d.ts +5 -0
  36. package/es/account/Ledger.js +9 -0
  37. package/es/account/Ledger.js.map +1 -1
  38. package/es/account/LedgerFactory.d.ts +2 -0
  39. package/es/account/LedgerFactory.js +10 -4
  40. package/es/account/LedgerFactory.js.map +1 -1
  41. package/es/account/Memory.d.ts +5 -0
  42. package/es/account/Memory.js +14 -5
  43. package/es/account/Memory.js.map +1 -1
  44. package/es/account/Metamask.d.ts +8 -0
  45. package/es/account/Metamask.js +13 -0
  46. package/es/account/Metamask.js.map +1 -1
  47. package/es/account/MetamaskFactory.d.ts +20 -2
  48. package/es/account/MetamaskFactory.js +93 -39
  49. package/es/account/MetamaskFactory.js.map +1 -1
  50. package/es/account/MnemonicFactory.d.ts +12 -2
  51. package/es/account/MnemonicFactory.js +48 -24
  52. package/es/account/MnemonicFactory.js.map +1 -1
  53. package/es/account/Rpc.d.ts +5 -0
  54. package/es/account/Rpc.js +8 -0
  55. package/es/account/Rpc.js.map +1 -1
  56. package/es/aens.d.ts +25 -5
  57. package/es/aens.js +52 -18
  58. package/es/aens.js.map +1 -1
  59. package/es/aepp-wallet-communication/connection/BrowserRuntime.d.ts +1 -1
  60. package/es/aepp-wallet-communication/connection/BrowserRuntime.js.map +1 -1
  61. package/es/apis/middleware/middleware.d.ts +99 -9
  62. package/es/apis/middleware/middleware.js +560 -91
  63. package/es/apis/middleware/middleware.js.map +1 -1
  64. package/es/apis/middleware/models/index.d.ts +1267 -1582
  65. package/es/apis/middleware/models/index.js +1 -1363
  66. package/es/apis/middleware/models/index.js.map +1 -1
  67. package/es/apis/middleware/models/mappers.d.ts +126 -56
  68. package/es/apis/middleware/models/mappers.js +6250 -2989
  69. package/es/apis/middleware/models/mappers.js.map +1 -1
  70. package/es/apis/middleware/models/parameters.d.ts +54 -33
  71. package/es/apis/middleware/models/parameters.js +389 -134
  72. package/es/apis/middleware/models/parameters.js.map +1 -1
  73. package/es/apis/node/models/index.d.ts +60 -15
  74. package/es/apis/node/models/index.js.map +1 -1
  75. package/es/apis/node/models/mappers.d.ts +3 -0
  76. package/es/apis/node/models/mappers.js +130 -2
  77. package/es/apis/node/models/mappers.js.map +1 -1
  78. package/es/apis/node/node.d.ts +13 -1
  79. package/es/apis/node/node.js +54 -0
  80. package/es/apis/node/node.js.map +1 -1
  81. package/es/chain.d.ts +19 -6
  82. package/es/chain.js +30 -24
  83. package/es/chain.js.map +1 -1
  84. package/es/channel/Contract.d.ts +6 -3
  85. package/es/channel/Contract.js +5 -2
  86. package/es/channel/Contract.js.map +1 -1
  87. package/es/channel/Spend.d.ts +1 -1
  88. package/es/channel/Spend.js.map +1 -1
  89. package/es/channel/handlers.js +1 -2
  90. package/es/channel/handlers.js.map +1 -1
  91. package/es/channel/internal.d.ts +1 -1
  92. package/es/channel/internal.js +2 -2
  93. package/es/channel/internal.js.map +1 -1
  94. package/es/contract/Contract.d.ts +13 -2
  95. package/es/contract/Contract.js +22 -12
  96. package/es/contract/Contract.js.map +1 -1
  97. package/es/contract/compiler/Base.d.ts +1 -0
  98. package/es/contract/compiler/Base.js +1 -0
  99. package/es/contract/compiler/Base.js.map +1 -1
  100. package/es/contract/compiler/Cli.d.ts +2 -1
  101. package/es/contract/compiler/Cli.js +11 -9
  102. package/es/contract/compiler/Cli.js.map +1 -1
  103. package/es/contract/compiler/Http.d.ts +2 -1
  104. package/es/contract/compiler/Http.js +3 -2
  105. package/es/contract/compiler/Http.js.map +1 -1
  106. package/es/contract/compiler/getFileSystem.d.ts +1 -0
  107. package/es/contract/compiler/getFileSystem.js +1 -0
  108. package/es/contract/compiler/getFileSystem.js.map +1 -1
  109. package/es/contract/ga.d.ts +3 -3
  110. package/es/contract/ga.js +3 -3
  111. package/es/contract/ga.js.map +1 -1
  112. package/es/index-browser.d.ts +32 -2
  113. package/es/index-browser.js +32 -2
  114. package/es/index-browser.js.map +1 -1
  115. package/es/oracle/Oracle.d.ts +10 -1
  116. package/es/oracle/Oracle.js +16 -6
  117. package/es/oracle/Oracle.js.map +1 -1
  118. package/es/oracle/OracleBase.d.ts +15 -2
  119. package/es/oracle/OracleBase.js +23 -1
  120. package/es/oracle/OracleBase.js.map +1 -1
  121. package/es/oracle/OracleClient.d.ts +3 -0
  122. package/es/oracle/OracleClient.js +6 -1
  123. package/es/oracle/OracleClient.js.map +1 -1
  124. package/es/spend.js +1 -1
  125. package/es/spend.js.map +1 -1
  126. package/es/tx/builder/common.js +6 -3
  127. package/es/tx/builder/common.js.map +1 -1
  128. package/es/tx/builder/constants.d.ts +53 -3
  129. package/es/tx/builder/constants.js +62 -12
  130. package/es/tx/builder/constants.js.map +1 -1
  131. package/es/tx/builder/delegation/schema.js +15 -0
  132. package/es/tx/builder/delegation/schema.js.map +1 -1
  133. package/es/tx/builder/entry/constants.d.ts +4 -1
  134. package/es/tx/builder/entry/constants.js +10 -1
  135. package/es/tx/builder/entry/constants.js.map +1 -1
  136. package/es/tx/builder/entry/index.js +1 -2
  137. package/es/tx/builder/entry/index.js.map +1 -1
  138. package/es/tx/builder/field-types/ct-version.js +1 -2
  139. package/es/tx/builder/field-types/ct-version.js.map +1 -1
  140. package/es/tx/builder/field-types/fee.d.ts +1 -1
  141. package/es/tx/builder/field-types/fee.js +4 -4
  142. package/es/tx/builder/field-types/fee.js.map +1 -1
  143. package/es/tx/builder/field-types/gas-price.d.ts +3 -0
  144. package/es/tx/builder/field-types/gas-price.js +1 -1
  145. package/es/tx/builder/field-types/gas-price.js.map +1 -1
  146. package/es/tx/builder/field-types/name-fee.js +1 -1
  147. package/es/tx/builder/field-types/name-fee.js.map +1 -1
  148. package/es/tx/builder/field-types/name-id.js +2 -2
  149. package/es/tx/builder/field-types/name-id.js.map +1 -1
  150. package/es/tx/builder/field-types/nonce.d.ts +1 -1
  151. package/es/tx/builder/field-types/nonce.js.map +1 -1
  152. package/es/tx/builder/field-types/pointers.js +3 -3
  153. package/es/tx/builder/field-types/pointers.js.map +1 -1
  154. package/es/tx/builder/field-types/ttl.js +1 -2
  155. package/es/tx/builder/field-types/ttl.js.map +1 -1
  156. package/es/tx/builder/helpers.d.ts +18 -12
  157. package/es/tx/builder/helpers.js +25 -17
  158. package/es/tx/builder/helpers.js.map +1 -1
  159. package/es/tx/builder/schema.d.ts +27 -24
  160. package/es/tx/builder/schema.generated.d.ts +12 -12
  161. package/es/tx/builder/schema.generated.js.map +1 -1
  162. package/es/tx/builder/schema.js +5 -3
  163. package/es/tx/builder/schema.js.map +1 -1
  164. package/es/tx/execution-cost.d.ts +3 -0
  165. package/es/tx/execution-cost.js +7 -4
  166. package/es/tx/execution-cost.js.map +1 -1
  167. package/es/tx/transaction-signer.d.ts +1 -0
  168. package/es/tx/transaction-signer.js +1 -0
  169. package/es/tx/transaction-signer.js.map +1 -1
  170. package/es/tx/validator.js +4 -3
  171. package/es/tx/validator.js.map +1 -1
  172. package/es/utils/MiddlewarePage.d.ts +4 -3
  173. package/es/utils/MiddlewarePage.js.map +1 -1
  174. package/es/utils/amount-formatter.d.ts +15 -1
  175. package/es/utils/amount-formatter.js +17 -1
  176. package/es/utils/amount-formatter.js.map +1 -1
  177. package/es/utils/autorest.d.ts +1 -1
  178. package/es/utils/autorest.js +10 -4
  179. package/es/utils/autorest.js.map +1 -1
  180. package/es/utils/bignumber.d.ts +1 -1
  181. package/es/utils/bignumber.js +1 -1
  182. package/es/utils/bignumber.js.map +1 -1
  183. package/es/utils/bytes.d.ts +3 -1
  184. package/es/utils/bytes.js +3 -1
  185. package/es/utils/bytes.js.map +1 -1
  186. package/es/utils/crypto.d.ts +48 -15
  187. package/es/utils/crypto.js +80 -29
  188. package/es/utils/crypto.js.map +1 -1
  189. package/es/utils/encoder-types.d.ts +1 -1
  190. package/es/utils/encoder-types.js +1 -1
  191. package/es/utils/encoder-types.js.map +1 -1
  192. package/es/utils/encoder.d.ts +2 -0
  193. package/es/utils/encoder.js +2 -0
  194. package/es/utils/encoder.js.map +1 -1
  195. package/es/utils/errors.d.ts +2 -2
  196. package/es/utils/errors.js +2 -2
  197. package/es/utils/errors.js.map +1 -1
  198. package/es/utils/json-big.js +1 -1
  199. package/es/utils/json-big.js.map +1 -1
  200. package/es/utils/jwt.js +3 -3
  201. package/es/utils/jwt.js.map +1 -1
  202. package/es/utils/typed-data.d.ts +5 -0
  203. package/es/utils/typed-data.js +6 -0
  204. package/es/utils/typed-data.js.map +1 -1
  205. package/package.json +50 -51
package/es/chain.js CHANGED
@@ -1,31 +1,30 @@
1
1
  import { AE_AMOUNT_FORMATS, formatAmount } from './utils/amount-formatter.js';
2
2
  import { isAccountNotFoundError, pause } from './utils/other.js';
3
3
  import { unwrapProxy } from './utils/wrap-proxy.js';
4
- import { isNameValid, produceNameId } from './tx/builder/helpers.js';
4
+ import { isName, produceNameId } from './tx/builder/helpers.js';
5
5
  import { DRY_RUN_ACCOUNT } from './tx/builder/constants.js';
6
6
  import { AensPointerContextError, DryRunError, InvalidAensNameError, TxTimedOutError, TxNotInChainError, InternalError } from './utils/errors.js';
7
7
  import { decode, encode, Encoding } from './utils/encoder.js';
8
+ async function getEventInterval(type, {
9
+ _expectedMineRate,
10
+ _microBlockCycle,
11
+ onNode
12
+ }) {
13
+ if (_expectedMineRate != null && type === 'key-block') return _expectedMineRate;
14
+ if (_microBlockCycle != null && type === 'micro-block') return _microBlockCycle;
15
+ const networkId = await onNode.getNetworkId();
16
+ if (networkId === 'ae_dev') return 0;
17
+ if (!['ae_mainnet', 'ae_uat'].includes(networkId) && (await onNode._isHyperchain())) return 3000;
18
+ if (type === 'key-block') return 180000;else return 3000;
19
+ }
8
20
 
9
21
  /**
10
22
  * @category chain
11
23
  * @param type - Type
12
24
  * @param options - Options
13
25
  */
14
- export async function _getPollInterval(type, {
15
- _expectedMineRate,
16
- _microBlockCycle,
17
- onNode
18
- }) {
19
- var _ref, _await$getVal;
20
- const getVal = async (t, val, devModeDef, def) => {
21
- if (t !== type) return null;
22
- if (val != null) return val;
23
- return (await onNode?.getNetworkId()) === 'ae_dev' ? devModeDef : def;
24
- };
25
- const base = (_ref = (_await$getVal = await getVal('key-block', _expectedMineRate, 0, 180000)) !== null && _await$getVal !== void 0 ? _await$getVal : await getVal('micro-block', _microBlockCycle, 0, 3000)) !== null && _ref !== void 0 ? _ref : (() => {
26
- throw new InternalError(`Unknown type: ${type}`);
27
- })();
28
- return Math.floor(base / 3);
26
+ export async function _getPollInterval(type, options) {
27
+ return Math.floor((await getEventInterval(type, options)) / 3);
29
28
  }
30
29
  const heightCache = new WeakMap();
31
30
 
@@ -76,8 +75,7 @@ export async function poll(th, {
76
75
  interval,
77
76
  ...options
78
77
  }) {
79
- var _interval;
80
- (_interval = interval) !== null && _interval !== void 0 ? _interval : interval = await _getPollInterval('micro-block', options);
78
+ interval !== null && interval !== void 0 ? interval : interval = await _getPollInterval('micro-block', options);
81
79
  let max;
82
80
  do {
83
81
  const tx = await options.onNode.getTransactionByHash(th);
@@ -109,8 +107,7 @@ export async function awaitHeight(height, {
109
107
  interval,
110
108
  ...options
111
109
  }) {
112
- var _interval2;
113
- (_interval2 = interval) !== null && _interval2 !== void 0 ? _interval2 : interval = Math.min(await _getPollInterval('key-block', options), 5000);
110
+ interval !== null && interval !== void 0 ? interval : interval = Math.min(await _getPollInterval('key-block', options), 5000);
114
111
  let currentHeight;
115
112
  do {
116
113
  if (currentHeight != null) await pause(interval);
@@ -187,6 +184,9 @@ export async function getAccount(address, {
187
184
  * @param options.hash - The block hash on which to obtain the balance for (default: top of chain)
188
185
  */
189
186
  export async function getBalance(address, {
187
+ /**
188
+ * @deprecated no replacement implemented yet
189
+ */
190
190
  format = AE_AMOUNT_FORMATS.AETTOS,
191
191
  ...options
192
192
  }) {
@@ -210,6 +210,7 @@ export async function getBalance(address, {
210
210
  * @param options - Options
211
211
  * @param options.onNode - Node to use
212
212
  * @returns Current Generation
213
+ * @deprecated Use {@link Node.getCurrentGeneration} instead
213
214
  */
214
215
  export async function getCurrentGeneration({
215
216
  onNode
@@ -224,6 +225,7 @@ export async function getCurrentGeneration({
224
225
  * @param options - Options
225
226
  * @param options.onNode - Node to use
226
227
  * @returns Generation
228
+ * @deprecated Use {@link Node.getGenerationByHash} or {@link Node.getGenerationByHeight} instead
227
229
  */
228
230
  export async function getGeneration(hashOrHeight, {
229
231
  onNode
@@ -239,6 +241,7 @@ export async function getGeneration(hashOrHeight, {
239
241
  * @param options - Options
240
242
  * @param options.onNode - Node to use
241
243
  * @returns Transactions
244
+ * @deprecated Use {@link Node.getMicroBlockTransactionsByHash} instead
242
245
  */
243
246
  export async function getMicroBlockTransactions(hash, {
244
247
  onNode
@@ -253,6 +256,7 @@ export async function getMicroBlockTransactions(hash, {
253
256
  * @param options - Options
254
257
  * @param options.onNode - Node to use
255
258
  * @returns Key Block
259
+ * @deprecated Use {@link Node.getKeyBlockByHeight} or {@link Node.getKeyBlockByHash} instead
256
260
  */
257
261
  export async function getKeyBlock(hashOrHeight, {
258
262
  onNode
@@ -268,6 +272,7 @@ export async function getKeyBlock(hashOrHeight, {
268
272
  * @param options - Options
269
273
  * @param options.onNode - Node to use
270
274
  * @returns Micro block header
275
+ * @deprecated Use {@link Node.getMicroBlockHeaderByHash} instead
271
276
  */
272
277
  export async function getMicroBlockHeader(hash, {
273
278
  onNode
@@ -281,9 +286,7 @@ async function txDryRunHandler(key, onNode) {
281
286
  if (rs == null) throw new InternalError("Can't get dry-run request");
282
287
  let dryRunRes;
283
288
  try {
284
- const top = typeof rs[0].top === 'number' ? (await getKeyBlock(rs[0].top, {
285
- onNode
286
- })).hash : rs[0].top;
289
+ const top = typeof rs[0].top === 'number' ? (await onNode.getKeyBlockByHeight(rs[0].top)).hash : rs[0].top;
287
290
  dryRunRes = await onNode.protectedDryRunTxs({
288
291
  top,
289
292
  txEvents: rs[0].txEvents,
@@ -373,6 +376,7 @@ export async function txDryRun(tx, accountAddress, {
373
376
  * @param contractId - Contract address
374
377
  * @param options - Options
375
378
  * @param options.onNode - Node to use
379
+ * @deprecated Use {@link Node.getContractCode} instead
376
380
  */
377
381
  export async function getContractByteCode(contractId, {
378
382
  onNode
@@ -386,6 +390,7 @@ export async function getContractByteCode(contractId, {
386
390
  * @param contractId - Contract address
387
391
  * @param options - Options
388
392
  * @param options.onNode - Node to use
393
+ * @deprecated Use {@link Node.getContract} instead
389
394
  */
390
395
  export async function getContract(contractId, {
391
396
  onNode
@@ -399,6 +404,7 @@ export async function getContract(contractId, {
399
404
  * @param name - AENS name
400
405
  * @param options - Options
401
406
  * @param options.onNode - Node to use
407
+ * @deprecated Use {@link Node.getNameEntryByName} or {@link Name.getState} instead
402
408
  */
403
409
  export async function getName(name, {
404
410
  onNode
@@ -423,7 +429,7 @@ export async function resolveName(nameOrId, key, {
423
429
  resolveByNode = false,
424
430
  onNode
425
431
  }) {
426
- if (isNameValid(nameOrId)) {
432
+ if (isName(nameOrId)) {
427
433
  if (verify || resolveByNode) {
428
434
  const name = await onNode.getNameEntryByName(nameOrId);
429
435
  const pointer = name.pointers.find(p => p.key === key);
package/es/chain.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"chain.js","names":["AE_AMOUNT_FORMATS","formatAmount","isAccountNotFoundError","pause","unwrapProxy","isNameValid","produceNameId","DRY_RUN_ACCOUNT","AensPointerContextError","DryRunError","InvalidAensNameError","TxTimedOutError","TxNotInChainError","InternalError","decode","encode","Encoding","_getPollInterval","type","_expectedMineRate","_microBlockCycle","onNode","_ref","_await$getVal","getVal","t","val","devModeDef","def","getNetworkId","base","Math","floor","heightCache","WeakMap","getHeight","cached","options","cache","get","time","Date","now","height","getCurrentKeyBlockHeight","set","poll","th","blocks","interval","_interval","max","tx","getTransactionByHash","blockHeight","ttl","awaitHeight","_interval2","min","currentHeight","waitForTxConfirm","txHash","confirm","newBlockHeight","getAccount","address","hash","getAccountByPubkeyAndHeight","getAccountByPubkeyAndHash","getAccountByPubkey","getBalance","format","AETTOS","addr","startsWith","AccountAddress","balance","catch","error","targetDenomination","getCurrentGeneration","getGeneration","hashOrHeight","getGenerationByHeight","getGenerationByHash","getMicroBlockTransactions","getMicroBlockTransactionsByHash","transactions","getKeyBlock","getKeyBlockByHeight","getKeyBlockByHash","getMicroBlockHeader","getMicroBlockHeaderByHash","txDryRunRequests","Map","txDryRunHandler","key","rs","delete","dryRunRes","top","protectedDryRunTxs","txEvents","txs","map","req","accounts","Array","from","Set","accountAddress","pubKey","amount","forEach","reject","results","result","reason","resultPayload","idx","resolve","Object","assign","txDryRun","combine","_txDryRunRequests$get","join","requests","Promise","_requests$timeout","push","timeout","setTimeout","getContractByteCode","contractId","getContractCode","getContract","getName","name","getNameEntryByName","resolveName","nameOrId","verify","resolveByNode","pointer","pointers","find","p","id"],"sources":["../src/chain.ts"],"sourcesContent":["import { AE_AMOUNT_FORMATS, formatAmount } from './utils/amount-formatter.js';\nimport { isAccountNotFoundError, pause } from './utils/other.js';\nimport { unwrapProxy } from './utils/wrap-proxy.js';\nimport { isNameValid, produceNameId } from './tx/builder/helpers.js';\nimport { AensName, DRY_RUN_ACCOUNT } from './tx/builder/constants.js';\nimport {\n AensPointerContextError,\n DryRunError,\n InvalidAensNameError,\n TxTimedOutError,\n TxNotInChainError,\n InternalError,\n} from './utils/errors.js';\nimport Node from './Node.js';\nimport { DryRunResult, DryRunResults, SignedTx } from './apis/node/index.js';\nimport { decode, encode, Encoded, Encoding } from './utils/encoder.js';\n\n/**\n * @category chain\n * @param type - Type\n * @param options - Options\n */\nexport async function _getPollInterval(\n type: 'key-block' | 'micro-block',\n {\n _expectedMineRate,\n _microBlockCycle,\n onNode,\n }: { _expectedMineRate?: number; _microBlockCycle?: number; onNode: Node },\n): Promise<number> {\n const getVal = async (\n t: string,\n val: number | undefined,\n devModeDef: number,\n def: number,\n ): Promise<number | null> => {\n if (t !== type) return null;\n if (val != null) return val;\n return (await onNode?.getNetworkId()) === 'ae_dev' ? devModeDef : def;\n };\n\n const base =\n (await getVal('key-block', _expectedMineRate, 0, 180000)) ??\n (await getVal('micro-block', _microBlockCycle, 0, 3000)) ??\n (() => {\n throw new InternalError(`Unknown type: ${type}`);\n })();\n return Math.floor(base / 3);\n}\n\nconst heightCache: WeakMap<Node, { time: number; height: number }> = new WeakMap();\n\n/**\n * Obtain current height of the chain\n * @category chain\n * @param options - Options\n * @param options.cached - Get height from the cache. The lag behind the actual height shouldn't\n * be more than 1 block. Use if needed to reduce requests count, and approximate value can be used.\n * For example, for timeout check in transaction status polling.\n * @returns Current chain height\n */\nexport async function getHeight({\n cached = false,\n ...options\n}: {\n onNode: Node;\n cached?: boolean;\n} & Parameters<typeof _getPollInterval>[1]): Promise<number> {\n const onNode = unwrapProxy(options.onNode);\n if (cached) {\n const cache = heightCache.get(onNode);\n if (cache != null && cache.time > Date.now() - (await _getPollInterval('key-block', options))) {\n return cache.height;\n }\n }\n const { height } = await onNode.getCurrentKeyBlockHeight();\n heightCache.set(onNode, { height, time: Date.now() });\n return height;\n}\n\n/**\n * Return transaction details if it is mined, fail otherwise.\n * If the transaction has ttl specified then would wait till it leaves the mempool.\n * Otherwise would fail if a specified amount of blocks were mined.\n * @category chain\n * @param th - The hash of transaction to poll\n * @param options - Options\n * @param options.interval - Interval (in ms) at which to poll the chain\n * @param options.blocks - Number of blocks mined after which to fail if transaction ttl is not set\n * @param options.onNode - Node to use\n * @returns The transaction as it was mined\n */\nexport async function poll(\n th: Encoded.TxHash,\n {\n blocks = 5,\n interval,\n ...options\n }: { blocks?: number; interval?: number; onNode: Node } & Parameters<typeof _getPollInterval>[1],\n): ReturnType<Node['getTransactionByHash']> {\n interval ??= await _getPollInterval('micro-block', options);\n let max;\n do {\n const tx = await options.onNode.getTransactionByHash(th);\n if (tx.blockHeight !== -1) return tx;\n if (max == null) {\n max = tx.tx.ttl !== 0 ? -1 : (await getHeight({ ...options, cached: true })) + blocks;\n }\n await pause(interval);\n } while (max === -1 ? true : (await getHeight({ ...options, cached: true })) < max);\n throw new TxTimedOutError(blocks, th);\n}\n\n/**\n * Wait for the chain to reach a specific height\n * @category chain\n * @param height - Height to wait for\n * @param options - Options\n * @param options.interval - Interval (in ms) at which to poll the chain\n * @param options.onNode - Node to use\n * @returns Current chain height\n */\nexport async function awaitHeight(\n height: number,\n {\n interval,\n ...options\n }: { interval?: number; onNode: Node } & Parameters<typeof _getPollInterval>[1],\n): Promise<number> {\n interval ??= Math.min(await _getPollInterval('key-block', options), 5000);\n let currentHeight;\n do {\n if (currentHeight != null) await pause(interval);\n currentHeight = await getHeight(options);\n } while (currentHeight < height);\n return currentHeight;\n}\n\n/**\n * Wait for transaction confirmation\n * @category chain\n * @param txHash - Transaction hash\n * @param options - Options\n * @param options.confirm - Number of micro blocks to wait for transaction confirmation\n * @param options.onNode - Node to use\n * @returns Current Height\n */\nexport async function waitForTxConfirm(\n txHash: Encoded.TxHash,\n {\n confirm = 3,\n onNode,\n ...options\n }: { confirm?: number; onNode: Node } & Parameters<typeof awaitHeight>[1],\n): Promise<number> {\n const { blockHeight } = await onNode.getTransactionByHash(txHash);\n const height = await awaitHeight(blockHeight + confirm, { onNode, ...options });\n const { blockHeight: newBlockHeight } = await onNode.getTransactionByHash(txHash);\n switch (newBlockHeight) {\n case -1:\n throw new TxNotInChainError(txHash);\n case blockHeight:\n return height;\n default:\n return waitForTxConfirm(txHash, { onNode, confirm, ...options });\n }\n}\n\n/**\n * Get account by account public key\n * @category chain\n * @param address - Account address (public key)\n * @param options - Options\n * @param options.height - Get account on specific block by block height\n * @param options.hash - Get account on specific block by micro block hash or key block hash\n * @param options.onNode - Node to use\n */\nexport async function getAccount(\n address: Encoded.AccountAddress | Encoded.ContractAddress,\n {\n height,\n hash,\n onNode,\n }: { height?: number; hash?: Encoded.KeyBlockHash | Encoded.MicroBlockHash; onNode: Node },\n): ReturnType<Node['getAccountByPubkey']> {\n if (height != null) return onNode.getAccountByPubkeyAndHeight(address, height);\n if (hash != null) return onNode.getAccountByPubkeyAndHash(address, hash);\n return onNode.getAccountByPubkey(address);\n}\n\n/**\n * Request the balance of specified account\n * @category chain\n * @param address - The public account address to obtain the balance for\n * @param options - Options\n * @param options.format\n * @param options.height - The chain height at which to obtain the balance for\n * (default: top of chain)\n * @param options.hash - The block hash on which to obtain the balance for (default: top of chain)\n */\nexport async function getBalance(\n address: Encoded.AccountAddress | Encoded.ContractAddress | Encoded.OracleAddress,\n {\n format = AE_AMOUNT_FORMATS.AETTOS,\n ...options\n }: { format?: AE_AMOUNT_FORMATS } & Parameters<typeof getAccount>[1],\n): Promise<string> {\n const addr = address.startsWith('ok_')\n ? encode(decode(address), Encoding.AccountAddress)\n : (address as Encoded.AccountAddress | Encoded.ContractAddress);\n\n const { balance } = await getAccount(addr, options).catch((error) => {\n if (!isAccountNotFoundError(error)) throw error;\n return { balance: 0n };\n });\n\n return formatAmount(balance, { targetDenomination: format });\n}\n\n/**\n * Obtain current generation\n * @category chain\n * @param options - Options\n * @param options.onNode - Node to use\n * @returns Current Generation\n */\nexport async function getCurrentGeneration({\n onNode,\n}: {\n onNode: Node;\n}): ReturnType<Node['getCurrentGeneration']> {\n return onNode.getCurrentGeneration();\n}\n\n/**\n * Get generation by hash or height\n * @category chain\n * @param hashOrHeight - Generation hash or height\n * @param options - Options\n * @param options.onNode - Node to use\n * @returns Generation\n */\nexport async function getGeneration(\n hashOrHeight: Encoded.KeyBlockHash | number,\n { onNode }: { onNode: Node },\n): ReturnType<Node['getGenerationByHash']> {\n if (typeof hashOrHeight === 'number') return onNode.getGenerationByHeight(hashOrHeight);\n return onNode.getGenerationByHash(hashOrHeight);\n}\n\n/**\n * Get micro block transactions\n * @category chain\n * @param hash - Micro block hash\n * @param options - Options\n * @param options.onNode - Node to use\n * @returns Transactions\n */\nexport async function getMicroBlockTransactions(\n hash: Encoded.MicroBlockHash,\n { onNode }: { onNode: Node },\n): Promise<SignedTx[]> {\n return (await onNode.getMicroBlockTransactionsByHash(hash)).transactions;\n}\n\n/**\n * Get key block\n * @category chain\n * @param hashOrHeight - Key block hash or height\n * @param options - Options\n * @param options.onNode - Node to use\n * @returns Key Block\n */\nexport async function getKeyBlock(\n hashOrHeight: Encoded.KeyBlockHash | number,\n { onNode }: { onNode: Node },\n): ReturnType<Node['getKeyBlockByHash']> {\n if (typeof hashOrHeight === 'number') return onNode.getKeyBlockByHeight(hashOrHeight);\n return onNode.getKeyBlockByHash(hashOrHeight);\n}\n\n/**\n * Get micro block header\n * @category chain\n * @param hash - Micro block hash\n * @param options - Options\n * @param options.onNode - Node to use\n * @returns Micro block header\n */\nexport async function getMicroBlockHeader(\n hash: Encoded.MicroBlockHash,\n { onNode }: { onNode: Node },\n): ReturnType<Node['getMicroBlockHeaderByHash']> {\n return onNode.getMicroBlockHeaderByHash(hash);\n}\n\ninterface TxDryRunArguments {\n tx: Encoded.Transaction;\n accountAddress: Encoded.AccountAddress;\n top?: number | Encoded.KeyBlockHash | Encoded.MicroBlockHash;\n txEvents?: any;\n resolve: Function;\n reject: Function;\n}\nconst txDryRunRequests: Map<string, TxDryRunArguments[] & { timeout?: NodeJS.Timeout }> = new Map();\n\nasync function txDryRunHandler(key: string, onNode: Node): Promise<void> {\n const rs = txDryRunRequests.get(key);\n txDryRunRequests.delete(key);\n if (rs == null) throw new InternalError(\"Can't get dry-run request\");\n\n let dryRunRes;\n try {\n const top =\n typeof rs[0].top === 'number' ? (await getKeyBlock(rs[0].top, { onNode })).hash : rs[0].top;\n dryRunRes = await onNode.protectedDryRunTxs({\n top,\n txEvents: rs[0].txEvents,\n txs: rs.map((req) => ({ tx: req.tx })),\n accounts: Array.from(new Set(rs.map((req) => req.accountAddress))).map((pubKey) => ({\n pubKey,\n amount: DRY_RUN_ACCOUNT.amount,\n })),\n });\n } catch (error) {\n rs.forEach(({ reject }) => reject(error));\n return;\n }\n\n const { results, txEvents } = dryRunRes;\n results.forEach(({ result, reason, ...resultPayload }, idx) => {\n const { resolve, reject, tx, accountAddress } = rs[idx];\n if (result === 'ok') resolve({ ...resultPayload, txEvents });\n else reject(Object.assign(new DryRunError(reason as string), { tx, accountAddress }));\n });\n}\n\n/**\n * Transaction dry-run\n * @category chain\n * @param tx - transaction to execute\n * @param accountAddress - address that will be used to execute transaction\n * @param options - Options\n * @param options.top - hash of block on which to make dry-run\n * @param options.txEvents - collect and return on-chain tx events that would result from the call\n * @param options.combine - Enables combining of similar requests to a single dry-run call\n * @param options.onNode - Node to use\n */\nexport async function txDryRun(\n tx: Encoded.Transaction,\n accountAddress: Encoded.AccountAddress,\n {\n top,\n txEvents,\n combine,\n onNode,\n }: { top?: TxDryRunArguments['top']; txEvents?: boolean; combine?: boolean; onNode: Node },\n): Promise<{ txEvents?: DryRunResults['txEvents'] } & DryRunResult> {\n const key = combine === true ? [top, txEvents].join() : 'immediate';\n const requests = txDryRunRequests.get(key) ?? [];\n txDryRunRequests.set(key, requests);\n return new Promise((resolve, reject) => {\n requests.push({\n tx,\n accountAddress,\n top,\n txEvents,\n resolve,\n reject,\n });\n if (combine !== true) {\n void txDryRunHandler(key, onNode);\n return;\n }\n requests.timeout ??= setTimeout(() => {\n void txDryRunHandler(key, onNode);\n });\n });\n}\n\n/**\n * Get contract byte code\n * @category contract\n * @param contractId - Contract address\n * @param options - Options\n * @param options.onNode - Node to use\n */\nexport async function getContractByteCode(\n contractId: Encoded.ContractAddress,\n { onNode }: { onNode: Node },\n): ReturnType<Node['getContractCode']> {\n return onNode.getContractCode(contractId);\n}\n\n/**\n * Get contract entry\n * @category contract\n * @param contractId - Contract address\n * @param options - Options\n * @param options.onNode - Node to use\n */\nexport async function getContract(\n contractId: Encoded.ContractAddress,\n { onNode }: { onNode: Node },\n): ReturnType<Node['getContract']> {\n return onNode.getContract(contractId);\n}\n\n/**\n * Get name entry\n * @category AENS\n * @param name - AENS name\n * @param options - Options\n * @param options.onNode - Node to use\n */\nexport async function getName(\n name: AensName,\n { onNode }: { onNode: Node },\n): ReturnType<Node['getNameEntryByName']> {\n return onNode.getNameEntryByName(name);\n}\n\n/**\n * Resolve AENS name and return name hash\n * @category AENS\n * @param nameOrId - AENS name or address\n * @param key - in AENS pointers record\n * @param options - Options\n * @param options.verify - To ensure that name exist and have a corresponding pointer\n * // TODO: avoid that to don't trust to current api gateway\n * @param options.resolveByNode - Enables pointer resolving using node\n * @param options.onNode - Node to use\n * @returns Address or AENS name hash\n */\nexport async function resolveName<Type extends Encoding.AccountAddress | Encoding.ContractAddress>(\n nameOrId: AensName | Encoded.Generic<Type>,\n key: string,\n {\n verify = true,\n resolveByNode = false,\n onNode,\n }: { verify?: boolean; resolveByNode?: boolean; onNode: Node },\n): Promise<Encoded.Generic<Type | Encoding.Name>> {\n if (isNameValid(nameOrId)) {\n if (verify || resolveByNode) {\n const name = await onNode.getNameEntryByName(nameOrId);\n const pointer = name.pointers.find((p) => p.key === key);\n if (pointer == null) throw new AensPointerContextError(nameOrId, key);\n if (resolveByNode) return pointer.id as Encoded.Generic<Type>;\n }\n return produceNameId(nameOrId);\n }\n try {\n decode(nameOrId);\n return nameOrId;\n } catch (error) {\n throw new InvalidAensNameError(`Invalid name or address: ${nameOrId}`);\n }\n}\n"],"mappings":"AAAA,SAASA,iBAAiB,EAAEC,YAAY,QAAQ,6BAA6B;AAC7E,SAASC,sBAAsB,EAAEC,KAAK,QAAQ,kBAAkB;AAChE,SAASC,WAAW,QAAQ,uBAAuB;AACnD,SAASC,WAAW,EAAEC,aAAa,QAAQ,yBAAyB;AACpE,SAAmBC,eAAe,QAAQ,2BAA2B;AACrE,SACEC,uBAAuB,EACvBC,WAAW,EACXC,oBAAoB,EACpBC,eAAe,EACfC,iBAAiB,EACjBC,aAAa,QACR,mBAAmB;AAG1B,SAASC,MAAM,EAAEC,MAAM,EAAWC,QAAQ,QAAQ,oBAAoB;;AAEtE;AACA;AACA;AACA;AACA;AACA,OAAO,eAAeC,gBAAgBA,CACpCC,IAAiC,EACjC;EACEC,iBAAiB;EACjBC,gBAAgB;EAChBC;AACuE,CAAC,EACzD;EAAA,IAAAC,IAAA,EAAAC,aAAA;EACjB,MAAMC,MAAM,GAAG,MAAAA,CACbC,CAAS,EACTC,GAAuB,EACvBC,UAAkB,EAClBC,GAAW,KACgB;IAC3B,IAAIH,CAAC,KAAKP,IAAI,EAAE,OAAO,IAAI;IAC3B,IAAIQ,GAAG,IAAI,IAAI,EAAE,OAAOA,GAAG;IAC3B,OAAO,CAAC,MAAML,MAAM,EAAEQ,YAAY,CAAC,CAAC,MAAM,QAAQ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"chain.js","names":["AE_AMOUNT_FORMATS","formatAmount","isAccountNotFoundError","pause","unwrapProxy","isName","produceNameId","DRY_RUN_ACCOUNT","AensPointerContextError","DryRunError","InvalidAensNameError","TxTimedOutError","TxNotInChainError","InternalError","decode","encode","Encoding","getEventInterval","type","_expectedMineRate","_microBlockCycle","onNode","networkId","getNetworkId","includes","_isHyperchain","_getPollInterval","options","Math","floor","heightCache","WeakMap","getHeight","cached","cache","get","time","Date","now","height","getCurrentKeyBlockHeight","set","poll","th","blocks","interval","max","tx","getTransactionByHash","blockHeight","ttl","awaitHeight","min","currentHeight","waitForTxConfirm","txHash","confirm","newBlockHeight","getAccount","address","hash","getAccountByPubkeyAndHeight","getAccountByPubkeyAndHash","getAccountByPubkey","getBalance","format","AETTOS","addr","startsWith","AccountAddress","balance","catch","error","targetDenomination","getCurrentGeneration","getGeneration","hashOrHeight","getGenerationByHeight","getGenerationByHash","getMicroBlockTransactions","getMicroBlockTransactionsByHash","transactions","getKeyBlock","getKeyBlockByHeight","getKeyBlockByHash","getMicroBlockHeader","getMicroBlockHeaderByHash","txDryRunRequests","Map","txDryRunHandler","key","rs","delete","dryRunRes","top","protectedDryRunTxs","txEvents","txs","map","req","accounts","Array","from","Set","accountAddress","pubKey","amount","forEach","reject","results","result","reason","resultPayload","idx","resolve","Object","assign","txDryRun","combine","_txDryRunRequests$get","join","requests","Promise","_requests$timeout","push","timeout","setTimeout","getContractByteCode","contractId","getContractCode","getContract","getName","name","getNameEntryByName","resolveName","nameOrId","verify","resolveByNode","pointer","pointers","find","p","id"],"sources":["../src/chain.ts"],"sourcesContent":["import { AE_AMOUNT_FORMATS, formatAmount } from './utils/amount-formatter.js';\nimport { isAccountNotFoundError, pause } from './utils/other.js';\nimport { unwrapProxy } from './utils/wrap-proxy.js';\nimport { isName, produceNameId } from './tx/builder/helpers.js';\nimport { AensName, DRY_RUN_ACCOUNT } from './tx/builder/constants.js';\nimport {\n AensPointerContextError,\n DryRunError,\n InvalidAensNameError,\n TxTimedOutError,\n TxNotInChainError,\n InternalError,\n} from './utils/errors.js';\nimport Node from './Node.js';\nimport { DryRunResult, DryRunResults, SignedTx } from './apis/node/index.js';\nimport { decode, encode, Encoded, Encoding } from './utils/encoder.js';\n\nasync function getEventInterval(\n type: 'key-block' | 'micro-block',\n {\n _expectedMineRate,\n _microBlockCycle,\n onNode,\n }: { _expectedMineRate?: number; _microBlockCycle?: number; onNode: Node },\n): Promise<number> {\n if (_expectedMineRate != null && type === 'key-block') return _expectedMineRate;\n if (_microBlockCycle != null && type === 'micro-block') return _microBlockCycle;\n\n const networkId = await onNode.getNetworkId();\n if (networkId === 'ae_dev') return 0;\n if (!['ae_mainnet', 'ae_uat'].includes(networkId) && (await onNode._isHyperchain())) return 3000;\n\n if (type === 'key-block') return 180000;\n else return 3000;\n}\n\n/**\n * @category chain\n * @param type - Type\n * @param options - Options\n */\nexport async function _getPollInterval(\n type: Parameters<typeof getEventInterval>[0],\n options: Parameters<typeof getEventInterval>[1],\n): Promise<number> {\n return Math.floor((await getEventInterval(type, options)) / 3);\n}\n\nconst heightCache: WeakMap<Node, { time: number; height: number }> = new WeakMap();\n\n/**\n * Obtain current height of the chain\n * @category chain\n * @param options - Options\n * @param options.cached - Get height from the cache. The lag behind the actual height shouldn't\n * be more than 1 block. Use if needed to reduce requests count, and approximate value can be used.\n * For example, for timeout check in transaction status polling.\n * @returns Current chain height\n */\nexport async function getHeight({\n cached = false,\n ...options\n}: {\n onNode: Node;\n cached?: boolean;\n} & Parameters<typeof _getPollInterval>[1]): Promise<number> {\n const onNode = unwrapProxy(options.onNode);\n if (cached) {\n const cache = heightCache.get(onNode);\n if (cache != null && cache.time > Date.now() - (await _getPollInterval('key-block', options))) {\n return cache.height;\n }\n }\n const { height } = await onNode.getCurrentKeyBlockHeight();\n heightCache.set(onNode, { height, time: Date.now() });\n return height;\n}\n\n/**\n * Return transaction details if it is mined, fail otherwise.\n * If the transaction has ttl specified then would wait till it leaves the mempool.\n * Otherwise would fail if a specified amount of blocks were mined.\n * @category chain\n * @param th - The hash of transaction to poll\n * @param options - Options\n * @param options.interval - Interval (in ms) at which to poll the chain\n * @param options.blocks - Number of blocks mined after which to fail if transaction ttl is not set\n * @param options.onNode - Node to use\n * @returns The transaction as it was mined\n */\nexport async function poll(\n th: Encoded.TxHash,\n {\n blocks = 5,\n interval,\n ...options\n }: { blocks?: number; interval?: number; onNode: Node } & Parameters<typeof _getPollInterval>[1],\n): ReturnType<Node['getTransactionByHash']> {\n interval ??= await _getPollInterval('micro-block', options);\n let max;\n do {\n const tx = await options.onNode.getTransactionByHash(th);\n if (tx.blockHeight !== -1) return tx;\n if (max == null) {\n max = tx.tx.ttl !== 0 ? -1 : (await getHeight({ ...options, cached: true })) + blocks;\n }\n await pause(interval);\n } while (max === -1 ? true : (await getHeight({ ...options, cached: true })) < max);\n throw new TxTimedOutError(blocks, th);\n}\n\n/**\n * Wait for the chain to reach a specific height\n * @category chain\n * @param height - Height to wait for\n * @param options - Options\n * @param options.interval - Interval (in ms) at which to poll the chain\n * @param options.onNode - Node to use\n * @returns Current chain height\n */\nexport async function awaitHeight(\n height: number,\n {\n interval,\n ...options\n }: { interval?: number; onNode: Node } & Parameters<typeof _getPollInterval>[1],\n): Promise<number> {\n interval ??= Math.min(await _getPollInterval('key-block', options), 5000);\n let currentHeight;\n do {\n if (currentHeight != null) await pause(interval);\n currentHeight = await getHeight(options);\n } while (currentHeight < height);\n return currentHeight;\n}\n\n/**\n * Wait for transaction confirmation\n * @category chain\n * @param txHash - Transaction hash\n * @param options - Options\n * @param options.confirm - Number of micro blocks to wait for transaction confirmation\n * @param options.onNode - Node to use\n * @returns Current Height\n */\nexport async function waitForTxConfirm(\n txHash: Encoded.TxHash,\n {\n confirm = 3,\n onNode,\n ...options\n }: { confirm?: number; onNode: Node } & Parameters<typeof awaitHeight>[1],\n): Promise<number> {\n const { blockHeight } = await onNode.getTransactionByHash(txHash);\n const height = await awaitHeight(blockHeight + confirm, { onNode, ...options });\n const { blockHeight: newBlockHeight } = await onNode.getTransactionByHash(txHash);\n switch (newBlockHeight) {\n case -1:\n throw new TxNotInChainError(txHash);\n case blockHeight:\n return height;\n default:\n return waitForTxConfirm(txHash, { onNode, confirm, ...options });\n }\n}\n\n/**\n * Get account by account public key\n * @category chain\n * @param address - Account address (public key)\n * @param options - Options\n * @param options.height - Get account on specific block by block height\n * @param options.hash - Get account on specific block by micro block hash or key block hash\n * @param options.onNode - Node to use\n */\nexport async function getAccount(\n address: Encoded.AccountAddress | Encoded.ContractAddress,\n {\n height,\n hash,\n onNode,\n }: { height?: number; hash?: Encoded.KeyBlockHash | Encoded.MicroBlockHash; onNode: Node },\n): ReturnType<Node['getAccountByPubkey']> {\n if (height != null) return onNode.getAccountByPubkeyAndHeight(address, height);\n if (hash != null) return onNode.getAccountByPubkeyAndHash(address, hash);\n return onNode.getAccountByPubkey(address);\n}\n\n/**\n * Request the balance of specified account\n * @category chain\n * @param address - The public account address to obtain the balance for\n * @param options - Options\n * @param options.format\n * @param options.height - The chain height at which to obtain the balance for\n * (default: top of chain)\n * @param options.hash - The block hash on which to obtain the balance for (default: top of chain)\n */\nexport async function getBalance(\n address: Encoded.AccountAddress | Encoded.ContractAddress | Encoded.OracleAddress,\n {\n /**\n * @deprecated no replacement implemented yet\n */\n format = AE_AMOUNT_FORMATS.AETTOS,\n ...options\n }: { format?: AE_AMOUNT_FORMATS } & Parameters<typeof getAccount>[1],\n): Promise<string> {\n const addr = address.startsWith('ok_')\n ? encode(decode(address), Encoding.AccountAddress)\n : (address as Encoded.AccountAddress | Encoded.ContractAddress);\n\n const { balance } = await getAccount(addr, options).catch((error) => {\n if (!isAccountNotFoundError(error)) throw error;\n return { balance: 0n };\n });\n\n return formatAmount(balance, { targetDenomination: format });\n}\n\n/**\n * Obtain current generation\n * @category chain\n * @param options - Options\n * @param options.onNode - Node to use\n * @returns Current Generation\n * @deprecated Use {@link Node.getCurrentGeneration} instead\n */\nexport async function getCurrentGeneration({\n onNode,\n}: {\n onNode: Node;\n}): ReturnType<Node['getCurrentGeneration']> {\n return onNode.getCurrentGeneration();\n}\n\n/**\n * Get generation by hash or height\n * @category chain\n * @param hashOrHeight - Generation hash or height\n * @param options - Options\n * @param options.onNode - Node to use\n * @returns Generation\n * @deprecated Use {@link Node.getGenerationByHash} or {@link Node.getGenerationByHeight} instead\n */\nexport async function getGeneration(\n hashOrHeight: Encoded.KeyBlockHash | number,\n { onNode }: { onNode: Node },\n): ReturnType<Node['getGenerationByHash']> {\n if (typeof hashOrHeight === 'number') return onNode.getGenerationByHeight(hashOrHeight);\n return onNode.getGenerationByHash(hashOrHeight);\n}\n\n/**\n * Get micro block transactions\n * @category chain\n * @param hash - Micro block hash\n * @param options - Options\n * @param options.onNode - Node to use\n * @returns Transactions\n * @deprecated Use {@link Node.getMicroBlockTransactionsByHash} instead\n */\nexport async function getMicroBlockTransactions(\n hash: Encoded.MicroBlockHash,\n { onNode }: { onNode: Node },\n): Promise<SignedTx[]> {\n return (await onNode.getMicroBlockTransactionsByHash(hash)).transactions;\n}\n\n/**\n * Get key block\n * @category chain\n * @param hashOrHeight - Key block hash or height\n * @param options - Options\n * @param options.onNode - Node to use\n * @returns Key Block\n * @deprecated Use {@link Node.getKeyBlockByHeight} or {@link Node.getKeyBlockByHash} instead\n */\nexport async function getKeyBlock(\n hashOrHeight: Encoded.KeyBlockHash | number,\n { onNode }: { onNode: Node },\n): ReturnType<Node['getKeyBlockByHash']> {\n if (typeof hashOrHeight === 'number') return onNode.getKeyBlockByHeight(hashOrHeight);\n return onNode.getKeyBlockByHash(hashOrHeight);\n}\n\n/**\n * Get micro block header\n * @category chain\n * @param hash - Micro block hash\n * @param options - Options\n * @param options.onNode - Node to use\n * @returns Micro block header\n * @deprecated Use {@link Node.getMicroBlockHeaderByHash} instead\n */\nexport async function getMicroBlockHeader(\n hash: Encoded.MicroBlockHash,\n { onNode }: { onNode: Node },\n): ReturnType<Node['getMicroBlockHeaderByHash']> {\n return onNode.getMicroBlockHeaderByHash(hash);\n}\n\ninterface TxDryRunArguments {\n tx: Encoded.Transaction;\n accountAddress: Encoded.AccountAddress;\n top?: number | Encoded.KeyBlockHash | Encoded.MicroBlockHash;\n txEvents?: any;\n resolve: Function;\n reject: Function;\n}\nconst txDryRunRequests: Map<string, TxDryRunArguments[] & { timeout?: NodeJS.Timeout }> = new Map();\n\nasync function txDryRunHandler(key: string, onNode: Node): Promise<void> {\n const rs = txDryRunRequests.get(key);\n txDryRunRequests.delete(key);\n if (rs == null) throw new InternalError(\"Can't get dry-run request\");\n\n let dryRunRes;\n try {\n const top =\n typeof rs[0].top === 'number'\n ? (await onNode.getKeyBlockByHeight(rs[0].top)).hash\n : rs[0].top;\n dryRunRes = await onNode.protectedDryRunTxs({\n top,\n txEvents: rs[0].txEvents,\n txs: rs.map((req) => ({ tx: req.tx })),\n accounts: Array.from(new Set(rs.map((req) => req.accountAddress))).map((pubKey) => ({\n pubKey,\n amount: DRY_RUN_ACCOUNT.amount,\n })),\n });\n } catch (error) {\n rs.forEach(({ reject }) => reject(error));\n return;\n }\n\n const { results, txEvents } = dryRunRes;\n results.forEach(({ result, reason, ...resultPayload }, idx) => {\n const { resolve, reject, tx, accountAddress } = rs[idx];\n if (result === 'ok') resolve({ ...resultPayload, txEvents });\n else reject(Object.assign(new DryRunError(reason as string), { tx, accountAddress }));\n });\n}\n\n/**\n * Transaction dry-run\n * @category chain\n * @param tx - transaction to execute\n * @param accountAddress - address that will be used to execute transaction\n * @param options - Options\n * @param options.top - hash of block on which to make dry-run\n * @param options.txEvents - collect and return on-chain tx events that would result from the call\n * @param options.combine - Enables combining of similar requests to a single dry-run call\n * @param options.onNode - Node to use\n */\nexport async function txDryRun(\n tx: Encoded.Transaction,\n accountAddress: Encoded.AccountAddress,\n {\n top,\n txEvents,\n combine,\n onNode,\n }: { top?: TxDryRunArguments['top']; txEvents?: boolean; combine?: boolean; onNode: Node },\n): Promise<{ txEvents?: DryRunResults['txEvents'] } & DryRunResult> {\n const key = combine === true ? [top, txEvents].join() : 'immediate';\n const requests = txDryRunRequests.get(key) ?? [];\n txDryRunRequests.set(key, requests);\n return new Promise((resolve, reject) => {\n requests.push({\n tx,\n accountAddress,\n top,\n txEvents,\n resolve,\n reject,\n });\n if (combine !== true) {\n void txDryRunHandler(key, onNode);\n return;\n }\n requests.timeout ??= setTimeout(() => {\n void txDryRunHandler(key, onNode);\n });\n });\n}\n\n/**\n * Get contract byte code\n * @category contract\n * @param contractId - Contract address\n * @param options - Options\n * @param options.onNode - Node to use\n * @deprecated Use {@link Node.getContractCode} instead\n */\nexport async function getContractByteCode(\n contractId: Encoded.ContractAddress,\n { onNode }: { onNode: Node },\n): ReturnType<Node['getContractCode']> {\n return onNode.getContractCode(contractId);\n}\n\n/**\n * Get contract entry\n * @category contract\n * @param contractId - Contract address\n * @param options - Options\n * @param options.onNode - Node to use\n * @deprecated Use {@link Node.getContract} instead\n */\nexport async function getContract(\n contractId: Encoded.ContractAddress,\n { onNode }: { onNode: Node },\n): ReturnType<Node['getContract']> {\n return onNode.getContract(contractId);\n}\n\n/**\n * Get name entry\n * @category AENS\n * @param name - AENS name\n * @param options - Options\n * @param options.onNode - Node to use\n * @deprecated Use {@link Node.getNameEntryByName} or {@link Name.getState} instead\n */\nexport async function getName(\n name: AensName,\n { onNode }: { onNode: Node },\n): ReturnType<Node['getNameEntryByName']> {\n return onNode.getNameEntryByName(name);\n}\n\n/**\n * Resolve AENS name and return name hash\n * @category AENS\n * @param nameOrId - AENS name or address\n * @param key - in AENS pointers record\n * @param options - Options\n * @param options.verify - To ensure that name exist and have a corresponding pointer\n * // TODO: avoid that to don't trust to current api gateway\n * @param options.resolveByNode - Enables pointer resolving using node\n * @param options.onNode - Node to use\n * @returns Address or AENS name hash\n */\nexport async function resolveName<Type extends Encoding.AccountAddress | Encoding.ContractAddress>(\n nameOrId: AensName | Encoded.Generic<Type>,\n key: string,\n {\n verify = true,\n resolveByNode = false,\n onNode,\n }: { verify?: boolean; resolveByNode?: boolean; onNode: Node },\n): Promise<Encoded.Generic<Type | Encoding.Name>> {\n if (isName(nameOrId)) {\n if (verify || resolveByNode) {\n const name = await onNode.getNameEntryByName(nameOrId);\n const pointer = name.pointers.find((p) => p.key === key);\n if (pointer == null) throw new AensPointerContextError(nameOrId, key);\n if (resolveByNode) return pointer.id as Encoded.Generic<Type>;\n }\n return produceNameId(nameOrId);\n }\n try {\n decode(nameOrId);\n return nameOrId;\n } catch (error) {\n throw new InvalidAensNameError(`Invalid name or address: ${nameOrId}`);\n }\n}\n"],"mappings":"AAAA,SAASA,iBAAiB,EAAEC,YAAY,QAAQ,6BAA6B;AAC7E,SAASC,sBAAsB,EAAEC,KAAK,QAAQ,kBAAkB;AAChE,SAASC,WAAW,QAAQ,uBAAuB;AACnD,SAASC,MAAM,EAAEC,aAAa,QAAQ,yBAAyB;AAC/D,SAAmBC,eAAe,QAAQ,2BAA2B;AACrE,SACEC,uBAAuB,EACvBC,WAAW,EACXC,oBAAoB,EACpBC,eAAe,EACfC,iBAAiB,EACjBC,aAAa,QACR,mBAAmB;AAG1B,SAASC,MAAM,EAAEC,MAAM,EAAWC,QAAQ,QAAQ,oBAAoB;AAEtE,eAAeC,gBAAgBA,CAC7BC,IAAiC,EACjC;EACEC,iBAAiB;EACjBC,gBAAgB;EAChBC;AACuE,CAAC,EACzD;EACjB,IAAIF,iBAAiB,IAAI,IAAI,IAAID,IAAI,KAAK,WAAW,EAAE,OAAOC,iBAAiB;EAC/E,IAAIC,gBAAgB,IAAI,IAAI,IAAIF,IAAI,KAAK,aAAa,EAAE,OAAOE,gBAAgB;EAE/E,MAAME,SAAS,GAAG,MAAMD,MAAM,CAACE,YAAY,CAAC,CAAC;EAC7C,IAAID,SAAS,KAAK,QAAQ,EAAE,OAAO,CAAC;EACpC,IAAI,CAAC,CAAC,YAAY,EAAE,QAAQ,CAAC,CAACE,QAAQ,CAACF,SAAS,CAAC,KAAK,MAAMD,MAAM,CAACI,aAAa,CAAC,CAAC,CAAC,EAAE,OAAO,IA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AACA;AACA;AACA,OAAO,eAAeG,OAAOA,CAC3BC,IAAc,EACd;EAAE/G;AAAyB,CAAC,EACY;EACxC,OAAOA,MAAM,CAACgH,kBAAkB,CAACD,IAAI,CAAC;AACxC;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,eAAeE,WAAWA,CAC/BC,QAA0C,EAC1C7C,GAAW,EACX;EACE8C,MAAM,GAAG,IAAI;EACbC,aAAa,GAAG,KAAK;EACrBpH;AAC2D,CAAC,EACd;EAChD,IAAIhB,MAAM,CAACkI,QAAQ,CAAC,EAAE;IACpB,IAAIC,MAAM,IAAIC,aAAa,EAAE;MAC3B,MAAML,IAAI,GAAG,MAAM/G,MAAM,CAACgH,kBAAkB,CAACE,QAAQ,CAAC;MACtD,MAAMG,OAAO,GAAGN,IAAI,CAACO,QAAQ,CAACC,IAAI,CAAEC,CAAC,IAAKA,CAAC,CAACnD,GAAG,KAAKA,GAAG,CAAC;MACxD,IAAIgD,OAAO,IAAI,IAAI,EAAE,MAAM,IAAIlI,uBAAuB,CAAC+H,QAAQ,EAAE7C,GAAG,CAAC;MACrE,IAAI+C,aAAa,EAAE,OAAOC,OAAO,CAACI,EAAE;IACtC;IACA,OAAOxI,aAAa,CAACiI,QAAQ,CAAC;EAChC;EACA,IAAI;IACFzH,MAAM,CAACyH,QAAQ,CAAC;IAChB,OAAOA,QAAQ;EACjB,CAAC,CAAC,OAAO/D,KAAK,EAAE;IACd,MAAM,IAAI9D,oBAAoB,CAAC,4BAA4B6H,QAAQ,EAAE,CAAC;EACxE;AACF","ignoreList":[]}
@@ -1,8 +1,8 @@
1
- import { BigNumber } from 'bignumber.js';
1
+ import BigNumber from 'bignumber.js';
2
2
  import { AbiVersion, VmVersion } from '../tx/builder/constants.js';
3
3
  import { SignTx, ChannelState, ChannelOptions } from './internal.js';
4
4
  import { Encoded } from '../utils/encoder.js';
5
- import { ContractCallReturnType } from '../apis/node/index.js';
5
+ import { ContractCallObjectReturnType } from '../apis/node/index.js';
6
6
  import { ContractCallObject } from '../contract/Contract.js';
7
7
  import ChannelSpend from './Spend.js';
8
8
  interface CallContractOptions {
@@ -30,7 +30,7 @@ interface CallContractResult extends CallContractOptions {
30
30
  height?: number;
31
31
  callerNonce?: number;
32
32
  log?: any;
33
- returnType?: ContractCallReturnType;
33
+ returnType?: ContractCallObjectReturnType;
34
34
  }
35
35
  interface Contract {
36
36
  abiVersion: AbiVersion;
@@ -41,6 +41,9 @@ interface Contract {
41
41
  referrerIds: string[];
42
42
  vmVersion: VmVersion;
43
43
  }
44
+ /**
45
+ * @category state channel
46
+ */
44
47
  export default class ChannelContract extends ChannelSpend {
45
48
  static initialize(options: ChannelOptions): Promise<ChannelContract>;
46
49
  /**
@@ -6,13 +6,16 @@ import Channel from './Base.js';
6
6
  import ChannelSpend from './Spend.js';
7
7
  import { ChannelError, UnexpectedChannelMessageError } from '../utils/errors.js';
8
8
  import { unpackTx } from '../tx/builder/index.js';
9
- import { encodeContractAddress } from '../utils/crypto.js';
9
+ import { buildContractId } from '../tx/builder/helpers.js';
10
10
  function snakeToPascalObjKeys(obj) {
11
11
  return Object.entries(obj).reduce((result, [key, val]) => ({
12
12
  ...result,
13
13
  [snakeToPascal(key)]: val
14
14
  }), {});
15
15
  }
16
+ /**
17
+ * @category state channel
18
+ */
16
19
  export default class ChannelContract extends ChannelSpend {
17
20
  static async initialize(options) {
18
21
  return Channel._initialize(new ChannelContract(), options);
@@ -82,7 +85,7 @@ export default class ChannelContract extends ChannelSpend {
82
85
  const addressKey = this._options.role === 'initiator' ? 'initiatorId' : 'responderId';
83
86
  const owner = this._options[addressKey];
84
87
  changeState(this, message2.params.data.state);
85
- const address = encodeContractAddress(owner, params.round);
88
+ const address = buildContractId(owner, params.round);
86
89
  emit(this, 'newContract', address);
87
90
  state2.resolve({
88
91
  accepted: true,
@@ -1 +1 @@
1
- {"version":3,"file":"Contract.js","names":["snakeToPascal","MIN_GAS_PRICE","Tag","signAndNotify","awaitingCompletion","channelClosed","channelOpen","handleUnexpectedMessage","notify","call","changeState","emit","Channel","ChannelSpend","ChannelError","UnexpectedChannelMessageError","unpackTx","encodeContractAddress","snakeToPascalObjKeys","obj","Object","entries","reduce","result","key","val","ChannelContract","initialize","options","_initialize","createContract","code","callData","deposit","vmVersion","abiVersion","sign","enqueueAction","call_data","vm_version","abi_version","handler","_","message","state","method","params","data","tx","_2","message2","state2","SignedTx","encodedTx","tag","ChannelOffChainTx","addressKey","_options","role","owner","address","round","resolve","accepted","signedTx","callContract","amount","contract","contract_id","updates","forceProgress","gasLimit","gasPrice","onOnChainTx","gas_price","gas","info","type","callContractStatic","getContractCall","caller","caller_id","getContractState","pubkey","cleanContractCalls","reject"],"sources":["../../src/channel/Contract.ts"],"sourcesContent":["import { BigNumber } from 'bignumber.js';\nimport { snakeToPascal } from '../utils/string.js';\nimport { MIN_GAS_PRICE, Tag, AbiVersion, VmVersion } from '../tx/builder/constants.js';\nimport {\n signAndNotify,\n awaitingCompletion,\n channelClosed,\n channelOpen,\n handleUnexpectedMessage,\n} from './handlers.js';\nimport {\n notify,\n call,\n SignTx,\n ChannelState,\n ChannelOptions,\n ChannelMessage,\n ChannelFsm,\n changeState,\n emit,\n} from './internal.js';\nimport { Encoded } from '../utils/encoder.js';\nimport { ContractCallReturnType } from '../apis/node/index.js';\nimport { ContractCallObject } from '../contract/Contract.js';\nimport Channel from './Base.js';\nimport ChannelSpend from './Spend.js';\nimport { ChannelError, UnexpectedChannelMessageError } from '../utils/errors.js';\nimport { unpackTx } from '../tx/builder/index.js';\nimport { encodeContractAddress } from '../utils/crypto.js';\n\nfunction snakeToPascalObjKeys<Type>(obj: object): Type {\n return Object.entries(obj).reduce(\n (result, [key, val]) => ({\n ...result,\n [snakeToPascal(key)]: val,\n }),\n {},\n ) as Type;\n}\n\ninterface CallContractOptions {\n /**\n * Amount the caller of the contract commits to it\n */\n amount?: number | BigNumber;\n /**\n * ABI encoded compiled AEVM call data for the code\n */\n callData?: Encoded.ContractBytearray;\n /**\n * Version of the ABI\n */\n abiVersion?: AbiVersion;\n /**\n * Address of the contract to call\n */\n contract?: Encoded.ContractAddress;\n}\n\ninterface CallContractResult extends CallContractOptions {\n returnValue?: any;\n gasUsed?: number | BigNumber;\n gasPrice?: number | BigNumber;\n height?: number;\n callerNonce?: number;\n log?: any;\n returnType?: ContractCallReturnType;\n}\n\ninterface Contract {\n abiVersion: AbiVersion;\n active: boolean;\n deposit: number | BigNumber;\n id: string;\n ownerId: string;\n referrerIds: string[];\n vmVersion: VmVersion;\n}\n\nexport default class ChannelContract extends ChannelSpend {\n static override async initialize(options: ChannelOptions): Promise<ChannelContract> {\n return Channel._initialize(new ChannelContract(), options);\n }\n\n /**\n * Trigger create contract update\n *\n * The create contract update is creating a contract inside the channel's internal state tree.\n * The update is a change to be applied on top of the latest state.\n *\n * That would create a contract with the poster being the owner of it. Poster commits initially\n * a deposit amount of coins to the new contract.\n *\n * @param options - Options\n * @param options.code - Api encoded compiled AEVM byte code\n * @param options.callData - Api encoded compiled AEVM call data for the code\n * @param options.deposit - Initial amount the owner of the contract commits to it\n * @param options.vmVersion - Version of the Virtual Machine\n * @param options.abiVersion - Version of the Application Binary Interface\n * @param sign - Function which verifies and signs create contract transaction\n * @example\n * ```js\n * channel.createContract({\n * code: 'cb_HKtpipK4aCgYb17wZ...',\n * callData: 'cb_1111111111111111...',\n * deposit: 10,\n * vmVersion: 3,\n * abiVersion: 1\n * }).then(({ accepted, signedTx, address }) => {\n * if (accepted) {\n * console.log('New contract has been created')\n * console.log('Contract address:', address)\n * } else {\n * console.log('New contract has been rejected')\n * }\n * })\n * ```\n */\n async createContract(\n {\n code,\n callData,\n deposit,\n vmVersion,\n abiVersion,\n }: {\n code: Encoded.ContractBytearray;\n callData: Encoded.ContractBytearray;\n deposit: number | BigNumber;\n vmVersion: VmVersion;\n abiVersion: AbiVersion;\n },\n sign: SignTx,\n ): Promise<{\n accepted: boolean;\n signedTx: Encoded.Transaction;\n address: Encoded.ContractAddress;\n }> {\n return this.enqueueAction(() => {\n notify(this, 'channels.update.new_contract', {\n code,\n call_data: callData,\n deposit,\n vm_version: vmVersion,\n abi_version: abiVersion,\n });\n return {\n handler: async (\n _: Channel,\n message: ChannelMessage,\n state: ChannelState,\n ): Promise<ChannelFsm> => {\n if (message.method !== 'channels.sign.update') {\n return handleUnexpectedMessage(this, message, state);\n }\n await signAndNotify(this, 'channels.update', message.params.data, async (tx) =>\n state.sign(tx),\n );\n return {\n handler: (_2: Channel, message2: ChannelMessage, state2: ChannelState): ChannelFsm =>\n awaitingCompletion(this, message2, state2, () => {\n const params = unpackTx(message2.params.data.state, Tag.SignedTx).encodedTx;\n if (params.tag !== Tag.ChannelOffChainTx) {\n throw new ChannelError(\n `Tag should be ${Tag[Tag.ChannelOffChainTx]}, got ${Tag[params.tag]} instead`,\n );\n }\n const addressKey =\n this._options.role === 'initiator' ? 'initiatorId' : 'responderId';\n const owner = this._options[addressKey];\n changeState(this, message2.params.data.state);\n const address = encodeContractAddress(owner, params.round);\n emit(this, 'newContract', address);\n state2.resolve({ accepted: true, address, signedTx: message2.params.data.state });\n return { handler: channelOpen };\n }),\n state,\n };\n },\n state: { sign },\n };\n });\n }\n\n /**\n * Trigger call a contract update\n *\n * The call contract update is calling a preexisting contract inside the channel's\n * internal state tree. The update is a change to be applied on top of the latest state.\n *\n * That would call a contract with the poster being the caller of it. Poster commits\n * an amount of coins to the contract.\n *\n * The call would also create a call object inside the channel state tree. It contains\n * the result of the contract call.\n *\n * It is worth mentioning that the gas is not consumed, because this is an off-chain\n * contract call. It would be consumed if it were an on-chain one. This could happen\n * if a call with a similar computation amount is to be forced on-chain.\n *\n * @param options - Options\n * @param sign - Function which verifies and signs contract call transaction\n * @example\n * ```js\n * channel.callContract({\n * contract: 'ct_9sRA9AVE4BYTAkh5RNfJYmwQe1NZ4MErasQLXZkFWG43TPBqa',\n * callData: 'cb_1111111111111111...',\n * amount: 0,\n * abiVersion: 1\n * }).then(({ accepted, signedTx }) => {\n * if (accepted) {\n * console.log('Contract called succesfully')\n * } else {\n * console.log('Contract call has been rejected')\n * }\n * })\n * ```\n */\n async callContract(\n { amount, callData, contract, abiVersion }: CallContractOptions,\n sign: SignTx,\n ): Promise<{ accepted: boolean; signedTx: Encoded.Transaction }> {\n return this.enqueueAction(() => {\n notify(this, 'channels.update.call_contract', {\n amount,\n call_data: callData,\n contract_id: contract,\n abi_version: abiVersion,\n });\n return {\n handler: async (\n _: Channel,\n message: ChannelMessage,\n state: ChannelState,\n ): Promise<ChannelFsm> => {\n if (message.method !== 'channels.sign.update') {\n return handleUnexpectedMessage(this, message, state);\n }\n await signAndNotify(this, 'channels.update', message.params.data, async (tx) =>\n state.sign(tx, { updates: message.params.data.updates }),\n );\n return {\n handler: (_2: Channel, message2: ChannelMessage, state2: ChannelState): ChannelFsm =>\n awaitingCompletion(this, message2, state2, () => {\n changeState(this, message2.params.data.state);\n state2.resolve({ accepted: true, signedTx: message2.params.data.state });\n return { handler: channelOpen };\n }),\n state,\n };\n },\n state: { sign },\n };\n });\n }\n\n /**\n * Trigger a force progress contract call\n * This call is going on-chain\n * @param options - Options\n * @param sign - Function which verifies and signs contract force progress transaction\n * @param callbacks - Callbacks\n * @example\n * ```js\n * channel.forceProgress({\n * contract: 'ct_9sRA9AVE4BYTAkh5RNfJYmwQe1NZ4MErasQLXZkFWG43TPBqa',\n * callData: 'cb_1111111111111111...',\n * amount: 0,\n * abiVersion: 1,\n * gasPrice: 1000005554\n * }).then(({ accepted, signedTx }) => {\n * if (accepted) {\n * console.log('Contract force progress call successful')\n * } else {\n * console.log('Contract force progress call has been rejected')\n * }\n * })\n * ```\n */\n async forceProgress(\n {\n amount,\n callData,\n contract,\n abiVersion,\n gasLimit = 1000000,\n gasPrice = MIN_GAS_PRICE,\n }: CallContractOptions & {\n gasLimit?: number;\n gasPrice?: number;\n },\n sign: SignTx,\n { onOnChainTx }: Pick<ChannelState, 'onOnChainTx'> = {},\n ): Promise<{\n accepted: boolean;\n signedTx: Encoded.Transaction;\n tx: Encoded.Transaction | Uint8Array;\n }> {\n return this.enqueueAction(() => {\n notify(this, 'channels.force_progress', {\n amount,\n call_data: callData,\n contract_id: contract,\n abi_version: abiVersion,\n gas_price: gasPrice,\n gas: gasLimit,\n });\n return {\n handler: async (\n _: Channel,\n message: ChannelMessage,\n state: ChannelState,\n ): Promise<ChannelFsm> => {\n if (message.method !== 'channels.sign.force_progress_tx') {\n return handleUnexpectedMessage(this, message, state);\n }\n await signAndNotify(\n this,\n 'channels.force_progress_sign',\n message.params.data,\n async (tx) => state.sign(tx, { updates: message.params.data.updates }),\n );\n return {\n handler: (_2: Channel, message2: ChannelMessage, state2: ChannelState): ChannelFsm => {\n if (message2.method === 'channels.on_chain_tx') {\n state2.onOnChainTx?.(message2.params.data.tx);\n emit(this, 'onChainTx', message2.params.data.tx, {\n info: message2.params.data.info,\n type: message2.params.data.type,\n });\n state2.resolve({ accepted: true, tx: message2.params.data.tx });\n // TODO: shouldn't be unexpected message in this case\n }\n return handleUnexpectedMessage(this, message2, state2);\n },\n state,\n };\n },\n state: { sign, onOnChainTx },\n };\n });\n }\n\n /**\n * Call contract using dry-run\n *\n * In order to get the result of a potential contract call, one might need to\n * dry-run a contract call. It takes the exact same arguments as a call would\n * and returns the call object.\n *\n * The call is executed in the channel's state, but it does not impact the state\n * whatsoever. It uses as an environment the latest channel's state and the current\n * top of the blockchain as seen by the node.\n *\n * @param options - Options\n * @example\n * ```js\n * channel.callContractStatic({\n * contract: 'ct_9sRA9AVE4BYTAkh5RNfJYmwQe1NZ4MErasQLXZkFWG43TPBqa',\n * callData: 'cb_1111111111111111...',\n * amount: 0,\n * abiVersion: 1\n * }).then(({ returnValue, gasUsed }) => {\n * console.log('Returned value:', returnValue)\n * console.log('Gas used:', gasUsed)\n * })\n * ```\n */\n async callContractStatic({\n amount,\n callData,\n contract,\n abiVersion,\n }: CallContractOptions): Promise<CallContractResult> {\n return snakeToPascalObjKeys(\n await call(this, 'channels.dry_run.call_contract', {\n amount,\n call_data: callData,\n contract_id: contract,\n abi_version: abiVersion,\n }),\n );\n }\n\n /**\n * Get contract call result\n *\n * The combination of a caller, contract and a round of execution determines the\n * contract call. Providing an incorrect set of those results in an error response.\n *\n * @param options - Options\n * @param options.caller - Address of contract caller\n * @param options.contract - Address of the contract\n * @param options.round - Round when contract was called\n * @example\n * ```js\n * channel.getContractCall({\n * caller: 'ak_Y1NRjHuoc3CGMYMvCmdHSBpJsMDR6Ra2t5zjhRcbtMeXXLpLH',\n * contract: 'ct_9sRA9AVE4BYTAkh5RNfJYmwQe1NZ4MErasQLXZkFWG43TPBqa',\n * round: 3\n * }).then(({ returnType, returnValue }) => {\n * if (returnType === 'ok') console.log(returnValue)\n * })\n * ```\n */\n async getContractCall({\n caller,\n contract,\n round,\n }: {\n caller: Encoded.AccountAddress;\n contract: Encoded.ContractAddress;\n round: number;\n }): Promise<ContractCallObject> {\n return snakeToPascalObjKeys(\n await call(this, 'channels.get.contract_call', {\n caller_id: caller,\n contract_id: contract,\n round,\n }),\n );\n }\n\n /**\n * Get the latest contract state\n *\n * @param contract - Address of the contract\n * @example\n * ```js\n * channel.getContractState(\n * 'ct_9sRA9AVE4BYTAkh5RNfJYmwQe1NZ4MErasQLXZkFWG43TPBqa'\n * ).then(({ contract }) => {\n * console.log('deposit:', contract.deposit)\n * })\n * ```\n */\n async getContractState(\n contract: Encoded.ContractAddress,\n ): Promise<{ contract: Contract; contractState: object }> {\n const result = await call(this, 'channels.get.contract', { pubkey: contract });\n return snakeToPascalObjKeys({\n ...result,\n contract: snakeToPascalObjKeys(result.contract),\n });\n }\n\n /**\n * Clean up all locally stored contract calls\n *\n * Contract calls are kept locally in order for the participant to be able to look them up.\n * They consume memory and in order for the participant to free it - one can prune all messages.\n * This cleans up all locally stored contract calls and those will no longer be available for\n * fetching and inspection.\n */\n async cleanContractCalls(): Promise<void> {\n return this.enqueueAction(() => {\n notify(this, 'channels.clean_contract_calls');\n return {\n handler(_: Channel, message: ChannelMessage, state: ChannelState): ChannelFsm {\n if (message.method === 'channels.calls_pruned.reply') {\n state.resolve();\n return { handler: channelOpen };\n }\n state.reject(new UnexpectedChannelMessageError('Unexpected message received'));\n return { handler: channelClosed };\n },\n };\n });\n }\n}\n"],"mappings":"AACA,SAASA,aAAa,QAAQ,oBAAoB;AAClD,SAASC,aAAa,EAAEC,GAAG,QAA+B,4BAA4B;AACtF,SACEC,aAAa,EACbC,kBAAkB,EAClBC,aAAa,EACbC,WAAW,EACXC,uBAAuB,QAClB,eAAe;AACtB,SACEC,MAAM,EACNC,IAAI,EAMJC,WAAW,EACXC,IAAI,QACC,eAAe;AAItB,OAAOC,OAAO,MAAM,WAAW;AAC/B,OAAOC,YAAY,MAAM,YAAY;AACrC,SAASC,YAAY,EAAEC,6BAA6B,QAAQ,oBAAoB;AAChF,SAASC,QAAQ,QAAQ,wBAAwB;AACjD,SAASC,qBAAqB,QAAQ,oBAAoB;AAE1D,SAASC,oBAAoBA,CAAOC,GAAW,EAAQ;EACrD,OAAOC,MAAM,CAACC,OAAO,CAACF,GAAG,CAAC,CAACG,MAAM,CAC/B,CAACC,MAAM,EAAE,CAACC,GAAG,EAAEC,GAAG,CAAC,MAAM;IACvB,GAAGF,MAAM;IACT,CAACvB,aAAa,CAACwB,GAAG,CAAC,GAAGC;EACxB,CAAC,CAAC,EACF,CAAC,CACH,CAAC;AACH;AAyCA,eAAe,MAAMC,eAAe,SAASb,YAAY,CAAC;EACxD,aAAsBc,UAAUA,CAACC,OAAuB,EAA4B;IAClF,OAAOhB,OAAO,CAACiB,WAAW,CAAC,IAAIH,eAAe,CAAC,CAAC,EAAEE,OAAO,CAAC;EAC5D;;EAEA;AACF;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;EACE,MAAME,cAAcA,CAClB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4C,QAAQ,EAAEjD,oBAAoB,CAACK,MAAM,CAAC4C,QAAQ;IAChD,CAAC,CAAC;EACJ;;EAEA;AACF;AACA;AACA;AACA;AACA;AACA;AACA;EACE,MAAMiB,kBAAkBA,CAAA,EAAkB;IACxC,OAAO,IAAI,CAAC/C,aAAa,CAAC,MAAM;MAC9B7B,MAAM,CAAC,IAAI,EAAE,+BAA+B,CAAC;MAC7C,OAAO;QACLiC,OAAOA,CAACC,CAAU,EAAEC,OAAuB,EAAEC,KAAmB,EAAc;UAC5E,IAAID,OAAO,CAACE,MAAM,KAAK,6BAA6B,EAAE;YACpDD,KAAK,CAACkB,OAAO,CAAC,CAAC;YACf,OAAO;cAAErB,OAAO,EAAEnC;YAAY,CAAC;UACjC;UACAsC,KAAK,CAACyC,MAAM,CAAC,IAAItE,6BAA6B,CAAC,6BAA6B,CAAC,CAAC;UAC9E,OAAO;YAAE0B,OAAO,EAAEpC;UAAc,CAAC;QACnC;MACF,CAAC;IACH,CAAC,CAAC;EACJ;AACF","ignoreList":[]}
1
+ {"version":3,"file":"Contract.js","names":["snakeToPascal","MIN_GAS_PRICE","Tag","signAndNotify","awaitingCompletion","channelClosed","channelOpen","handleUnexpectedMessage","notify","call","changeState","emit","Channel","ChannelSpend","ChannelError","UnexpectedChannelMessageError","unpackTx","buildContractId","snakeToPascalObjKeys","obj","Object","entries","reduce","result","key","val","ChannelContract","initialize","options","_initialize","createContract","code","callData","deposit","vmVersion","abiVersion","sign","enqueueAction","call_data","vm_version","abi_version","handler","_","message","state","method","params","data","tx","_2","message2","state2","SignedTx","encodedTx","tag","ChannelOffChainTx","addressKey","_options","role","owner","address","round","resolve","accepted","signedTx","callContract","amount","contract","contract_id","updates","forceProgress","gasLimit","gasPrice","onOnChainTx","gas_price","gas","info","type","callContractStatic","getContractCall","caller","caller_id","getContractState","pubkey","cleanContractCalls","reject"],"sources":["../../src/channel/Contract.ts"],"sourcesContent":["import BigNumber from 'bignumber.js';\nimport { snakeToPascal } from '../utils/string.js';\nimport { MIN_GAS_PRICE, Tag, AbiVersion, VmVersion } from '../tx/builder/constants.js';\nimport {\n signAndNotify,\n awaitingCompletion,\n channelClosed,\n channelOpen,\n handleUnexpectedMessage,\n} from './handlers.js';\nimport {\n notify,\n call,\n SignTx,\n ChannelState,\n ChannelOptions,\n ChannelMessage,\n ChannelFsm,\n changeState,\n emit,\n} from './internal.js';\nimport { Encoded } from '../utils/encoder.js';\nimport { ContractCallObjectReturnType } from '../apis/node/index.js';\nimport { ContractCallObject } from '../contract/Contract.js';\nimport Channel from './Base.js';\nimport ChannelSpend from './Spend.js';\nimport { ChannelError, UnexpectedChannelMessageError } from '../utils/errors.js';\nimport { unpackTx } from '../tx/builder/index.js';\nimport { buildContractId } from '../tx/builder/helpers.js';\n\nfunction snakeToPascalObjKeys<Type>(obj: object): Type {\n return Object.entries(obj).reduce(\n (result, [key, val]) => ({\n ...result,\n [snakeToPascal(key)]: val,\n }),\n {},\n ) as Type;\n}\n\ninterface CallContractOptions {\n /**\n * Amount the caller of the contract commits to it\n */\n amount?: number | BigNumber;\n /**\n * ABI encoded compiled AEVM call data for the code\n */\n callData?: Encoded.ContractBytearray;\n /**\n * Version of the ABI\n */\n abiVersion?: AbiVersion;\n /**\n * Address of the contract to call\n */\n contract?: Encoded.ContractAddress;\n}\n\ninterface CallContractResult extends CallContractOptions {\n returnValue?: any;\n gasUsed?: number | BigNumber;\n gasPrice?: number | BigNumber;\n height?: number;\n callerNonce?: number;\n log?: any;\n returnType?: ContractCallObjectReturnType;\n}\n\ninterface Contract {\n abiVersion: AbiVersion;\n active: boolean;\n deposit: number | BigNumber;\n id: string;\n ownerId: string;\n referrerIds: string[];\n vmVersion: VmVersion;\n}\n\n/**\n * @category state channel\n */\nexport default class ChannelContract extends ChannelSpend {\n static override async initialize(options: ChannelOptions): Promise<ChannelContract> {\n return Channel._initialize(new ChannelContract(), options);\n }\n\n /**\n * Trigger create contract update\n *\n * The create contract update is creating a contract inside the channel's internal state tree.\n * The update is a change to be applied on top of the latest state.\n *\n * That would create a contract with the poster being the owner of it. Poster commits initially\n * a deposit amount of coins to the new contract.\n *\n * @param options - Options\n * @param options.code - Api encoded compiled AEVM byte code\n * @param options.callData - Api encoded compiled AEVM call data for the code\n * @param options.deposit - Initial amount the owner of the contract commits to it\n * @param options.vmVersion - Version of the Virtual Machine\n * @param options.abiVersion - Version of the Application Binary Interface\n * @param sign - Function which verifies and signs create contract transaction\n * @example\n * ```js\n * channel.createContract({\n * code: 'cb_HKtpipK4aCgYb17wZ...',\n * callData: 'cb_1111111111111111...',\n * deposit: 10,\n * vmVersion: 3,\n * abiVersion: 1\n * }).then(({ accepted, signedTx, address }) => {\n * if (accepted) {\n * console.log('New contract has been created')\n * console.log('Contract address:', address)\n * } else {\n * console.log('New contract has been rejected')\n * }\n * })\n * ```\n */\n async createContract(\n {\n code,\n callData,\n deposit,\n vmVersion,\n abiVersion,\n }: {\n code: Encoded.ContractBytearray;\n callData: Encoded.ContractBytearray;\n deposit: number | BigNumber;\n vmVersion: VmVersion;\n abiVersion: AbiVersion;\n },\n sign: SignTx,\n ): Promise<{\n accepted: boolean;\n signedTx: Encoded.Transaction;\n address: Encoded.ContractAddress;\n }> {\n return this.enqueueAction(() => {\n notify(this, 'channels.update.new_contract', {\n code,\n call_data: callData,\n deposit,\n vm_version: vmVersion,\n abi_version: abiVersion,\n });\n return {\n handler: async (\n _: Channel,\n message: ChannelMessage,\n state: ChannelState,\n ): Promise<ChannelFsm> => {\n if (message.method !== 'channels.sign.update') {\n return handleUnexpectedMessage(this, message, state);\n }\n await signAndNotify(this, 'channels.update', message.params.data, async (tx) =>\n state.sign(tx),\n );\n return {\n handler: (_2: Channel, message2: ChannelMessage, state2: ChannelState): ChannelFsm =>\n awaitingCompletion(this, message2, state2, () => {\n const params = unpackTx(message2.params.data.state, Tag.SignedTx).encodedTx;\n if (params.tag !== Tag.ChannelOffChainTx) {\n throw new ChannelError(\n `Tag should be ${Tag[Tag.ChannelOffChainTx]}, got ${Tag[params.tag]} instead`,\n );\n }\n const addressKey =\n this._options.role === 'initiator' ? 'initiatorId' : 'responderId';\n const owner = this._options[addressKey];\n changeState(this, message2.params.data.state);\n const address = buildContractId(owner, params.round);\n emit(this, 'newContract', address);\n state2.resolve({ accepted: true, address, signedTx: message2.params.data.state });\n return { handler: channelOpen };\n }),\n state,\n };\n },\n state: { sign },\n };\n });\n }\n\n /**\n * Trigger call a contract update\n *\n * The call contract update is calling a preexisting contract inside the channel's\n * internal state tree. The update is a change to be applied on top of the latest state.\n *\n * That would call a contract with the poster being the caller of it. Poster commits\n * an amount of coins to the contract.\n *\n * The call would also create a call object inside the channel state tree. It contains\n * the result of the contract call.\n *\n * It is worth mentioning that the gas is not consumed, because this is an off-chain\n * contract call. It would be consumed if it were an on-chain one. This could happen\n * if a call with a similar computation amount is to be forced on-chain.\n *\n * @param options - Options\n * @param sign - Function which verifies and signs contract call transaction\n * @example\n * ```js\n * channel.callContract({\n * contract: 'ct_9sRA9AVE4BYTAkh5RNfJYmwQe1NZ4MErasQLXZkFWG43TPBqa',\n * callData: 'cb_1111111111111111...',\n * amount: 0,\n * abiVersion: 1\n * }).then(({ accepted, signedTx }) => {\n * if (accepted) {\n * console.log('Contract called succesfully')\n * } else {\n * console.log('Contract call has been rejected')\n * }\n * })\n * ```\n */\n async callContract(\n { amount, callData, contract, abiVersion }: CallContractOptions,\n sign: SignTx,\n ): Promise<{ accepted: boolean; signedTx: Encoded.Transaction }> {\n return this.enqueueAction(() => {\n notify(this, 'channels.update.call_contract', {\n amount,\n call_data: callData,\n contract_id: contract,\n abi_version: abiVersion,\n });\n return {\n handler: async (\n _: Channel,\n message: ChannelMessage,\n state: ChannelState,\n ): Promise<ChannelFsm> => {\n if (message.method !== 'channels.sign.update') {\n return handleUnexpectedMessage(this, message, state);\n }\n await signAndNotify(this, 'channels.update', message.params.data, async (tx) =>\n state.sign(tx, { updates: message.params.data.updates }),\n );\n return {\n handler: (_2: Channel, message2: ChannelMessage, state2: ChannelState): ChannelFsm =>\n awaitingCompletion(this, message2, state2, () => {\n changeState(this, message2.params.data.state);\n state2.resolve({ accepted: true, signedTx: message2.params.data.state });\n return { handler: channelOpen };\n }),\n state,\n };\n },\n state: { sign },\n };\n });\n }\n\n /**\n * Trigger a force progress contract call\n * This call is going on-chain\n * @param options - Options\n * @param sign - Function which verifies and signs contract force progress transaction\n * @param callbacks - Callbacks\n * @example\n * ```js\n * channel.forceProgress({\n * contract: 'ct_9sRA9AVE4BYTAkh5RNfJYmwQe1NZ4MErasQLXZkFWG43TPBqa',\n * callData: 'cb_1111111111111111...',\n * amount: 0,\n * abiVersion: 1,\n * gasPrice: 1000005554\n * }).then(({ accepted, signedTx }) => {\n * if (accepted) {\n * console.log('Contract force progress call successful')\n * } else {\n * console.log('Contract force progress call has been rejected')\n * }\n * })\n * ```\n */\n async forceProgress(\n {\n amount,\n callData,\n contract,\n abiVersion,\n gasLimit = 1000000,\n gasPrice = MIN_GAS_PRICE,\n }: CallContractOptions & {\n gasLimit?: number;\n gasPrice?: number;\n },\n sign: SignTx,\n { onOnChainTx }: Pick<ChannelState, 'onOnChainTx'> = {},\n ): Promise<{\n accepted: boolean;\n signedTx: Encoded.Transaction;\n tx: Encoded.Transaction | Uint8Array;\n }> {\n return this.enqueueAction(() => {\n notify(this, 'channels.force_progress', {\n amount,\n call_data: callData,\n contract_id: contract,\n abi_version: abiVersion,\n gas_price: gasPrice,\n gas: gasLimit,\n });\n return {\n handler: async (\n _: Channel,\n message: ChannelMessage,\n state: ChannelState,\n ): Promise<ChannelFsm> => {\n if (message.method !== 'channels.sign.force_progress_tx') {\n return handleUnexpectedMessage(this, message, state);\n }\n await signAndNotify(\n this,\n 'channels.force_progress_sign',\n message.params.data,\n async (tx) => state.sign(tx, { updates: message.params.data.updates }),\n );\n return {\n handler: (_2: Channel, message2: ChannelMessage, state2: ChannelState): ChannelFsm => {\n if (message2.method === 'channels.on_chain_tx') {\n state2.onOnChainTx?.(message2.params.data.tx);\n emit(this, 'onChainTx', message2.params.data.tx, {\n info: message2.params.data.info,\n type: message2.params.data.type,\n });\n state2.resolve({ accepted: true, tx: message2.params.data.tx });\n // TODO: shouldn't be unexpected message in this case\n }\n return handleUnexpectedMessage(this, message2, state2);\n },\n state,\n };\n },\n state: { sign, onOnChainTx },\n };\n });\n }\n\n /**\n * Call contract using dry-run\n *\n * In order to get the result of a potential contract call, one might need to\n * dry-run a contract call. It takes the exact same arguments as a call would\n * and returns the call object.\n *\n * The call is executed in the channel's state, but it does not impact the state\n * whatsoever. It uses as an environment the latest channel's state and the current\n * top of the blockchain as seen by the node.\n *\n * @param options - Options\n * @example\n * ```js\n * channel.callContractStatic({\n * contract: 'ct_9sRA9AVE4BYTAkh5RNfJYmwQe1NZ4MErasQLXZkFWG43TPBqa',\n * callData: 'cb_1111111111111111...',\n * amount: 0,\n * abiVersion: 1\n * }).then(({ returnValue, gasUsed }) => {\n * console.log('Returned value:', returnValue)\n * console.log('Gas used:', gasUsed)\n * })\n * ```\n */\n async callContractStatic({\n amount,\n callData,\n contract,\n abiVersion,\n }: CallContractOptions): Promise<CallContractResult> {\n return snakeToPascalObjKeys(\n await call(this, 'channels.dry_run.call_contract', {\n amount,\n call_data: callData,\n contract_id: contract,\n abi_version: abiVersion,\n }),\n );\n }\n\n /**\n * Get contract call result\n *\n * The combination of a caller, contract and a round of execution determines the\n * contract call. Providing an incorrect set of those results in an error response.\n *\n * @param options - Options\n * @param options.caller - Address of contract caller\n * @param options.contract - Address of the contract\n * @param options.round - Round when contract was called\n * @example\n * ```js\n * channel.getContractCall({\n * caller: 'ak_Y1NRjHuoc3CGMYMvCmdHSBpJsMDR6Ra2t5zjhRcbtMeXXLpLH',\n * contract: 'ct_9sRA9AVE4BYTAkh5RNfJYmwQe1NZ4MErasQLXZkFWG43TPBqa',\n * round: 3\n * }).then(({ returnType, returnValue }) => {\n * if (returnType === 'ok') console.log(returnValue)\n * })\n * ```\n */\n async getContractCall({\n caller,\n contract,\n round,\n }: {\n caller: Encoded.AccountAddress;\n contract: Encoded.ContractAddress;\n round: number;\n }): Promise<ContractCallObject> {\n return snakeToPascalObjKeys(\n await call(this, 'channels.get.contract_call', {\n caller_id: caller,\n contract_id: contract,\n round,\n }),\n );\n }\n\n /**\n * Get the latest contract state\n *\n * @param contract - Address of the contract\n * @example\n * ```js\n * channel.getContractState(\n * 'ct_9sRA9AVE4BYTAkh5RNfJYmwQe1NZ4MErasQLXZkFWG43TPBqa'\n * ).then(({ contract }) => {\n * console.log('deposit:', contract.deposit)\n * })\n * ```\n */\n async getContractState(\n contract: Encoded.ContractAddress,\n ): Promise<{ contract: Contract; contractState: object }> {\n const result = await call(this, 'channels.get.contract', { pubkey: contract });\n return snakeToPascalObjKeys({\n ...result,\n contract: snakeToPascalObjKeys(result.contract),\n });\n }\n\n /**\n * Clean up all locally stored contract calls\n *\n * Contract calls are kept locally in order for the participant to be able to look them up.\n * They consume memory and in order for the participant to free it - one can prune all messages.\n * This cleans up all locally stored contract calls and those will no longer be available for\n * fetching and inspection.\n */\n async cleanContractCalls(): Promise<void> {\n return this.enqueueAction(() => {\n notify(this, 'channels.clean_contract_calls');\n return {\n handler(_: Channel, message: ChannelMessage, state: ChannelState): ChannelFsm {\n if (message.method === 'channels.calls_pruned.reply') {\n state.resolve();\n return { handler: channelOpen };\n }\n state.reject(new UnexpectedChannelMessageError('Unexpected message received'));\n return { handler: channelClosed };\n },\n };\n });\n }\n}\n"],"mappings":"AACA,SAASA,aAAa,QAAQ,oBAAoB;AAClD,SAASC,aAAa,EAAEC,GAAG,QAA+B,4BAA4B;AACtF,SACEC,aAAa,EACbC,kBAAkB,EAClBC,aAAa,EACbC,WAAW,EACXC,uBAAuB,QAClB,eAAe;AACtB,SACEC,MAAM,EACNC,IAAI,EAMJC,WAAW,EACXC,IAAI,QACC,eAAe;AAItB,OAAOC,OAAO,MAAM,WAAW;AAC/B,OAAOC,YAAY,MAAM,YAAY;AACrC,SAASC,YAAY,EAAEC,6BAA6B,QAAQ,oB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6BAA6B,CAAC,6BAA6B,CAAC,CAAC;UAC9E,OAAO;YAAE0B,OAAO,EAAEpC;UAAc,CAAC;QACnC;MACF,CAAC;IACH,CAAC,CAAC;EACJ;AACF","ignoreList":[]}
@@ -1,4 +1,4 @@
1
- import { BigNumber } from 'bignumber.js';
1
+ import BigNumber from 'bignumber.js';
2
2
  import { SignTx, ChannelState } from './internal.js';
3
3
  import { Encoded } from '../utils/encoder.js';
4
4
  import Channel from './Base.js';
@@ -1 +1 @@
1
- {"version":3,"file":"Spend.js","names":["notify","call","changeState","pause","Channel","ChannelConnectionError","awaitingCompletion","channelOpen","handleUnexpectedMessage","signAndNotify","unpackEntry","ChannelSpend","update","from","to","amount","sign","metadata","enqueueAction","meta","awaitingOffChainTx","_","message","state","method","isError","params","data","tx","updates","handler","_2","message2","resolve","accepted","signedTx","reject","poi","accounts","contracts","balances","Object","fromEntries","map","item","account","balance","awaitingActionTx","action","awaitingActionCompletion","onOnChainTx","includes","event","Action","isOwn","startsWith","withdraw","onOwnWithdrawLocked","onWithdrawLocked","deposit","onOwnDepositLocked","onDepositLocked","sendMessage","recipient","info","JSON","stringify","status","Promise","onStatusChanged","off","on"],"sources":["../../src/channel/Spend.ts"],"sourcesContent":["import { BigNumber } from 'bignumber.js';\nimport {\n notify,\n call,\n SignTx,\n ChannelState,\n ChannelMessage,\n ChannelFsm,\n changeState,\n} from './internal.js';\nimport { Encoded } from '../utils/encoder.js';\nimport { pause } from '../utils/other.js';\nimport Channel from './Base.js';\nimport { ChannelConnectionError } from '../utils/errors.js';\nimport {\n awaitingCompletion,\n channelOpen,\n handleUnexpectedMessage,\n signAndNotify,\n} from './handlers.js';\nimport { EntryTag } from '../tx/builder/entry/constants.js';\nimport { EntUnpacked } from '../tx/builder/entry/schema.generated.js';\nimport { unpackEntry } from '../tx/builder/entry/index.js';\n\nexport default class ChannelSpend extends Channel {\n /**\n * Trigger a transfer update\n *\n * The transfer update is moving coins from one channel account to another.\n * The update is a change to be applied on top of the latest state.\n *\n * Sender and receiver are the channel parties. Both the initiator and responder\n * can take those roles. Any public key outside the channel is considered invalid.\n *\n * @param from - Sender's public address\n * @param to - Receiver's public address\n * @param amount - Transaction amount\n * @param sign - Function which verifies and signs offchain transaction\n * @param metadata - Metadata\n\n * @example\n * ```js\n * channel.update(\n * 'ak_Y1NRjHuoc3CGMYMvCmdHSBpJsMDR6Ra2t5zjhRcbtMeXXLpLH',\n * 'ak_V6an1xhec1xVaAhLuak7QoEbi6t7w5hEtYWp9bMKaJ19i6A9E',\n * 10,\n * async (tx) => await account.signTransaction(tx)\n * ).then(({ accepted, signedTx }) =>\n * if (accepted) {\n * console.log('Update has been accepted')\n * }\n * )\n * ```\n */\n async update(\n from: Encoded.AccountAddress,\n to: Encoded.AccountAddress,\n amount: number | BigNumber,\n sign: SignTx,\n metadata: string[] = [],\n ): Promise<{\n accepted: boolean;\n signedTx?: Encoded.Transaction;\n errorCode?: number;\n errorMessage?: string;\n }> {\n return this.enqueueAction(() => {\n notify(this, 'channels.update.new', {\n from,\n to,\n amount,\n meta: metadata,\n });\n\n const awaitingOffChainTx = async (\n _: Channel,\n message: ChannelMessage,\n state: ChannelState,\n ): Promise<ChannelFsm> => {\n if (message.method === 'channels.sign.update') {\n const isError = await signAndNotify(\n this,\n 'channels.update',\n message.params.data,\n async (tx) => sign(tx, { updates: message.params.data.updates }),\n );\n if (isError) return { handler: awaitingOffChainTx, state };\n return {\n handler: (_2: Channel, message2: ChannelMessage): ChannelFsm =>\n awaitingCompletion(this, message2, state, () => {\n changeState(this, message2.params.data.state);\n state.resolve({ accepted: true, signedTx: message2.params.data.state });\n return { handler: channelOpen };\n }),\n state,\n };\n }\n if (message.method === 'channels.error') {\n state.reject(new ChannelConnectionError(message.data.message));\n return { handler: channelOpen };\n }\n return awaitingCompletion(this, message, state);\n };\n\n return { handler: awaitingOffChainTx };\n });\n }\n\n /**\n * Get proof of inclusion\n *\n * If a certain address of an account or a contract is not found\n * in the state tree - the response is an error.\n *\n * @param addresses - Addresses\n * @param addresses.accounts - List of account addresses to include in poi\n * @param addresses.contracts - List of contract addresses to include in poi\n * @example\n * ```js\n * channel.poi({\n * accounts: [\n * 'ak_Y1NRjHuoc3CGMYMvCmdHSBpJsMDR6Ra2t5zjhRcbtMeXXLpLH',\n * 'ak_V6an1xhec1xVaAhLuak7QoEbi6t7w5hEtYWp9bMKaJ19i6A9E'\n * ],\n * contracts: ['ct_2dCUAWYZdrWfACz3a2faJeKVTVrfDYxCQHCqAt5zM15f3u2UfA']\n * }).then(poi => console.log(poi))\n * ```\n */\n async poi({\n accounts,\n contracts,\n }: {\n accounts: Encoded.AccountAddress[];\n contracts?: Encoded.ContractAddress[];\n }): Promise<EntUnpacked & { tag: EntryTag.TreesPoi }> {\n const { poi }: { poi: Encoded.Poi } = await call(this, 'channels.get.poi', {\n accounts,\n contracts,\n });\n return unpackEntry(poi);\n }\n\n /**\n * Get balances\n *\n * The accounts param contains a list of addresses to fetch balances of.\n * Those can be either account balances or a contract ones, encoded as an account addresses.\n *\n * If a certain account address had not being found in the state tree - it is simply\n * skipped in the response.\n *\n * @param accounts - List of addresses to fetch balances from\n * @example\n * ```js\n * channel.balances([\n * 'ak_Y1NRjHuoc3CGMYMvCmdHSBpJsMDR6Ra2t5zjhRcbtMeXXLpLH',\n * 'ak_V6an1xhec1xVaAhLuak7QoEbi6t7w5hEtYWp9bMKaJ19i6A9E'\n * 'ct_2dCUAWYZdrWfACz3a2faJeKVTVrfDYxCQHCqAt5zM15f3u2UfA'\n * ]).then(balances =>\n * console.log(balances['ak_Y1NRjHuoc3CGMYMvCmdHSBpJsMDR6Ra2t5zjhRcbtMeXXLpLH'])\n * )\n * ```\n */\n async balances(\n accounts: Encoded.AccountAddress[],\n ): Promise<{ [key: Encoded.AccountAddress]: string }> {\n return Object.fromEntries(\n (await call(this, 'channels.get.balances', { accounts })).map(\n (item: { account: Encoded.AccountAddress; balance: string }) => [\n item.account,\n item.balance,\n ],\n ),\n );\n }\n\n private async awaitingActionTx(\n action: 'deposit' | 'withdraw',\n message: ChannelMessage,\n state: ChannelState,\n ): Promise<ChannelFsm> {\n if (message.method !== `channels.sign.${action}_tx`) {\n return handleUnexpectedMessage(this, message, state);\n }\n\n const awaitingActionCompletion = (_: Channel, message2: ChannelMessage): ChannelFsm => {\n if (message2.method === 'channels.on_chain_tx') {\n state.onOnChainTx?.(message2.params.data.tx);\n return { handler: awaitingActionCompletion, state };\n }\n if (\n message2.method === 'channels.info' &&\n [`own_${action}_locked`, `${action}_locked`].includes(message2.params.data.event)\n ) {\n const Action = action === 'deposit' ? 'Deposit' : 'Withdraw';\n const isOwn: boolean = message2.params.data.event.startsWith('own_');\n state[`on${isOwn ? 'Own' : ''}${Action}Locked`]?.();\n return { handler: awaitingActionCompletion, state };\n }\n return awaitingCompletion(this, message2, state, () => {\n changeState(this, message2.params.data.state);\n state.resolve({ accepted: true, signedTx: message2.params.data.state });\n return { handler: channelOpen };\n });\n };\n\n const { sign } = state;\n await signAndNotify(this, `channels.${action}_tx`, message.params.data, async (tx) =>\n sign(tx, { updates: message.params.data.updates }),\n );\n return { handler: awaitingActionCompletion, state };\n }\n\n /**\n * Withdraw coins from the channel\n *\n * After the channel had been opened any of the participants can initiate a withdrawal.\n * The process closely resembles the update. The most notable difference is that the\n * transaction has been co-signed: it is channel_withdraw_tx and after the procedure\n * is finished - it is being posted on-chain.\n *\n * Any of the participants can initiate a withdrawal. The only requirements are:\n *\n * - Channel is already opened\n * - No off-chain update/deposit/withdrawal is currently being performed\n * - Channel is not being closed or in a solo closing state\n * - The withdrawal amount must be equal to or greater than zero, and cannot exceed\n * the available balance on the channel (minus the channel_reserve)\n *\n * After the other party had signed the withdraw transaction, the transaction is posted\n * on-chain and onOnChainTx callback is called with on-chain transaction as first argument.\n * After computing transaction hash it can be tracked on the chain: entering the mempool,\n * block inclusion and a number of confirmations.\n *\n * After the minimum_depth block confirmations onOwnWithdrawLocked callback is called\n * (without any arguments).\n *\n * When the other party had confirmed that the block height needed is reached\n * onWithdrawLocked callback is called (without any arguments).\n *\n * @param amount - Amount of coins to withdraw\n * @param sign - Function which verifies and signs withdraw transaction\n * @param callbacks - Callbacks\n * @example\n * ```js\n * channel.withdraw(\n * 100,\n * async (tx) => await account.signTransaction(tx),\n * { onOnChainTx: (tx) => console.log('on_chain_tx', tx) }\n * ).then(({ accepted, signedTx }) => {\n * if (accepted) {\n * console.log('Withdrawal has been accepted')\n * } else {\n * console.log('Withdrawal has been rejected')\n * }\n * })\n * ```\n */\n async withdraw(\n amount: number | BigNumber,\n sign: SignTx,\n {\n onOnChainTx,\n onOwnWithdrawLocked,\n onWithdrawLocked,\n }: Pick<ChannelState, 'onOnChainTx' | 'onOwnWithdrawLocked' | 'onWithdrawLocked'> = {},\n ): Promise<{ accepted: boolean; signedTx: Encoded.Transaction }> {\n return this.enqueueAction(() => {\n notify(this, 'channels.withdraw', { amount });\n return {\n handler: async (\n _: Channel,\n message: ChannelMessage,\n state: ChannelState,\n ): Promise<ChannelFsm> => this.awaitingActionTx('withdraw', message, state),\n state: {\n sign,\n onOnChainTx,\n onOwnWithdrawLocked,\n onWithdrawLocked,\n },\n };\n });\n }\n\n /**\n * Deposit coins into the channel\n *\n * After the channel had been opened any of the participants can initiate a deposit.\n * The process closely resembles the update. The most notable difference is that the\n * transaction has been co-signed: it is channel_deposit_tx and after the procedure\n * is finished - it is being posted on-chain.\n *\n * Any of the participants can initiate a deposit. The only requirements are:\n *\n * - Channel is already opened\n * - No off-chain update/deposit/withdrawal is currently being performed\n * - Channel is not being closed or in a solo closing state\n * - The deposit amount must be equal to or greater than zero, and cannot exceed\n * the available balance on the channel (minus the channel_reserve)\n *\n * After the other party had signed the deposit transaction, the transaction is posted\n * on-chain and onOnChainTx callback is called with on-chain transaction as first argument.\n * After computing transaction hash it can be tracked on the chain: entering the mempool,\n * block inclusion and a number of confirmations.\n *\n * After the minimum_depth block confirmations onOwnDepositLocked callback is called\n * (without any arguments).\n *\n * When the other party had confirmed that the block height needed is reached\n * onDepositLocked callback is called (without any arguments).\n *\n * @param amount - Amount of coins to deposit\n * @param sign - Function which verifies and signs deposit transaction\n * @param callbacks - Callbacks\n * @example\n * ```js\n * channel.deposit(\n * 100,\n * async (tx) => await account.signTransaction(tx),\n * { onOnChainTx: (tx) => console.log('on_chain_tx', tx) }\n * ).then(({ accepted, state }) => {\n * if (accepted) {\n * console.log('Deposit has been accepted')\n * console.log('The new state is:', state)\n * } else {\n * console.log('Deposit has been rejected')\n * }\n * })\n * ```\n */\n async deposit(\n amount: number | BigNumber,\n sign: SignTx,\n {\n onOnChainTx,\n onOwnDepositLocked,\n onDepositLocked,\n }: Pick<ChannelState, 'onOnChainTx' | 'onOwnDepositLocked' | 'onDepositLocked'> = {},\n ): Promise<{ accepted: boolean; state: ChannelState }> {\n return this.enqueueAction(() => {\n notify(this, 'channels.deposit', { amount });\n return {\n handler: async (\n _: Channel,\n message: ChannelMessage,\n state: ChannelState,\n ): Promise<ChannelFsm> => this.awaitingActionTx('deposit', message, state),\n state: {\n sign,\n onOnChainTx,\n onOwnDepositLocked,\n onDepositLocked,\n },\n };\n });\n }\n\n /**\n * Send generic message\n *\n * If message is an object it will be serialized into JSON string\n * before sending.\n *\n * If there is ongoing update that has not yet been finished the message\n * will be sent after that update is finalized.\n *\n * @param message - Message\n * @param recipient - Address of the recipient\n * @example\n * ```js\n * channel.sendMessage(\n * 'hello world',\n * 'ak_Y1NRjHuoc3CGMYMvCmdHSBpJsMDR6Ra2t5zjhRcbtMeXXLpLH'\n * )\n * ```\n */\n async sendMessage(message: string | object, recipient: Encoded.AccountAddress): Promise<void> {\n const info = typeof message === 'object' ? JSON.stringify(message) : message;\n if (this.status() === 'connecting') {\n await new Promise<void>((resolve) => {\n const onStatusChanged = (status: string): void => {\n if (status === 'connecting') return;\n resolve();\n this.off('statusChanged', onStatusChanged);\n };\n this.on('statusChanged', onStatusChanged);\n });\n // For some reason we can't immediately send a message when connection is\n // established. Thus we wait 500ms which seems to work.\n await pause(500);\n }\n notify(this, 'channels.message', { info, to: recipient });\n }\n}\n"],"mappings":"AACA,SACEA,MAAM,EACNC,IAAI,EAKJC,WAAW,QACN,eAAe;AAEtB,SAASC,KAAK,QAAQ,mBAAmB;AACzC,OAAOC,OAAO,MAAM,WAAW;AAC/B,SAASC,sBAAsB,QAAQ,oBAAoB;AAC3D,SACEC,kBAAkB,EAClBC,WAAW,EACXC,uBAAuB,EACvBC,aAAa,QACR,eAAe;AAGtB,SAASC,WAAW,QAAQ,8BAA8B;AAE1D,eAAe,MAAMC,YAAY,SAASP,OAAO,CAAC;EAChD;AACF;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;EAEE,MAAMQ,MAAMA,CACVC,IAA4B,EAC5BC,EAA0B,EAC1BC,MAA0B,EAC1BC,IAAY,EACZC,QAAkB,GAAG,EAAE,EAMtB;IACD,OAAO,IAAI,CAACC,aAAa,CAAC,MAAM;MAC9BlB,MAAM,CAAC,IAAI,EAAE,qBAAqB,EAAE;QAClCa,IAAI;QACJC,EAAE;QACFC,MAAM;QACNI,IAAI,EAAEF;MACR,CAAC,CAAC;MAEF,MAAMG,kBAAkB,GAAG,MAAAA,CACzBC,CAAU,EACVC,OAAuB,EACvBC,KAAmB,KACK;QACxB,IAAID,OAAO,CAACE,MAAM,KAAK,sBAAsB,EAAE;UAC7C,MAAMC,OAAO,GAAG,MAAMhB,aAAa,CACjC,IAAI,EACJ,iBAAiB,EACjBa,OAAO,CAACI,MAAM,CAACC,IAAI,EACnB,MAAOC,EAAE,IAAKZ,IAAI,CAACY,EAAE,EAAE;YAAEC,OAAO,EAAEP,OAAO,CAACI,MAAM,CAACC,IAAI,CAACE;UAAQ,CAAC,CACjE,CAAC;UACD,IAAIJ,OAAO,EAAE,OAAO;YAAEK,OAAO,EAAEV,kBAAkB;YAAEG;UAAM,CAAC;UAC1D,OAAO;YACLO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6C,MAAM,CAAC,CAAC,KAAK,YAAY,EAAE;MAClC,MAAM,IAAIC,OAAO,CAAQnC,OAAO,IAAK;QACnC,MAAMoC,eAAe,GAAIF,MAAc,IAAW;UAChD,IAAIA,MAAM,KAAK,YAAY,EAAE;UAC7BlC,OAAO,CAAC,CAAC;UACT,IAAI,CAACqC,GAAG,CAAC,eAAe,EAAED,eAAe,CAAC;QAC5C,CAAC;QACD,IAAI,CAACE,EAAE,CAAC,eAAe,EAAEF,eAAe,CAAC;MAC3C,CAAC,CAAC;MACF;MACA;MACA,MAAMlE,KAAK,CAAC,GAAG,CAAC;IAClB;IACAH,MAAM,CAAC,IAAI,EAAE,kBAAkB,EAAE;MAAEgE,IAAI;MAAElD,EAAE,EAAEiD;IAAU,CAAC,CAAC;EAC3D;AACF","ignoreList":[]}
1
+ {"version":3,"file":"Spend.js","names":["notify","call","changeState","pause","Channel","ChannelConnectionError","awaitingCompletion","channelOpen","handleUnexpectedMessage","signAndNotify","unpackEntry","ChannelSpend","update","from","to","amount","sign","metadata","enqueueAction","meta","awaitingOffChainTx","_","message","state","method","isError","params","data","tx","updates","handler","_2","message2","resolve","accepted","signedTx","reject","poi","accounts","contracts","balances","Object","fromEntries","map","item","account","balance","awaitingActionTx","action","awaitingActionCompletion","onOnChainTx","includes","event","Action","isOwn","startsWith","withdraw","onOwnWithdrawLocked","onWithdrawLocked","deposit","onOwnDepositLocked","onDepositLocked","sendMessage","recipient","info","JSON","stringify","status","Promise","onStatusChanged","off","on"],"sources":["../../src/channel/Spend.ts"],"sourcesContent":["import BigNumber from 'bignumber.js';\nimport {\n notify,\n call,\n SignTx,\n ChannelState,\n ChannelMessage,\n ChannelFsm,\n changeState,\n} from './internal.js';\nimport { Encoded } from '../utils/encoder.js';\nimport { pause } from '../utils/other.js';\nimport Channel from './Base.js';\nimport { ChannelConnectionError } from '../utils/errors.js';\nimport {\n awaitingCompletion,\n channelOpen,\n handleUnexpectedMessage,\n signAndNotify,\n} from './handlers.js';\nimport { EntryTag } from '../tx/builder/entry/constants.js';\nimport { EntUnpacked } from '../tx/builder/entry/schema.generated.js';\nimport { unpackEntry } from '../tx/builder/entry/index.js';\n\nexport default class ChannelSpend extends Channel {\n /**\n * Trigger a transfer update\n *\n * The transfer update is moving coins from one channel account to another.\n * The update is a change to be applied on top of the latest state.\n *\n * Sender and receiver are the channel parties. Both the initiator and responder\n * can take those roles. Any public key outside the channel is considered invalid.\n *\n * @param from - Sender's public address\n * @param to - Receiver's public address\n * @param amount - Transaction amount\n * @param sign - Function which verifies and signs offchain transaction\n * @param metadata - Metadata\n\n * @example\n * ```js\n * channel.update(\n * 'ak_Y1NRjHuoc3CGMYMvCmdHSBpJsMDR6Ra2t5zjhRcbtMeXXLpLH',\n * 'ak_V6an1xhec1xVaAhLuak7QoEbi6t7w5hEtYWp9bMKaJ19i6A9E',\n * 10,\n * async (tx) => await account.signTransaction(tx)\n * ).then(({ accepted, signedTx }) =>\n * if (accepted) {\n * console.log('Update has been accepted')\n * }\n * )\n * ```\n */\n async update(\n from: Encoded.AccountAddress,\n to: Encoded.AccountAddress,\n amount: number | BigNumber,\n sign: SignTx,\n metadata: string[] = [],\n ): Promise<{\n accepted: boolean;\n signedTx?: Encoded.Transaction;\n errorCode?: number;\n errorMessage?: string;\n }> {\n return this.enqueueAction(() => {\n notify(this, 'channels.update.new', {\n from,\n to,\n amount,\n meta: metadata,\n });\n\n const awaitingOffChainTx = async (\n _: Channel,\n message: ChannelMessage,\n state: ChannelState,\n ): Promise<ChannelFsm> => {\n if (message.method === 'channels.sign.update') {\n const isError = await signAndNotify(\n this,\n 'channels.update',\n message.params.data,\n async (tx) => sign(tx, { updates: message.params.data.updates }),\n );\n if (isError) return { handler: awaitingOffChainTx, state };\n return {\n handler: (_2: Channel, message2: ChannelMessage): ChannelFsm =>\n awaitingCompletion(this, message2, state, () => {\n changeState(this, message2.params.data.state);\n state.resolve({ accepted: true, signedTx: message2.params.data.state });\n return { handler: channelOpen };\n }),\n state,\n };\n }\n if (message.method === 'channels.error') {\n state.reject(new ChannelConnectionError(message.data.message));\n return { handler: channelOpen };\n }\n return awaitingCompletion(this, message, state);\n };\n\n return { handler: awaitingOffChainTx };\n });\n }\n\n /**\n * Get proof of inclusion\n *\n * If a certain address of an account or a contract is not found\n * in the state tree - the response is an error.\n *\n * @param addresses - Addresses\n * @param addresses.accounts - List of account addresses to include in poi\n * @param addresses.contracts - List of contract addresses to include in poi\n * @example\n * ```js\n * channel.poi({\n * accounts: [\n * 'ak_Y1NRjHuoc3CGMYMvCmdHSBpJsMDR6Ra2t5zjhRcbtMeXXLpLH',\n * 'ak_V6an1xhec1xVaAhLuak7QoEbi6t7w5hEtYWp9bMKaJ19i6A9E'\n * ],\n * contracts: ['ct_2dCUAWYZdrWfACz3a2faJeKVTVrfDYxCQHCqAt5zM15f3u2UfA']\n * }).then(poi => console.log(poi))\n * ```\n */\n async poi({\n accounts,\n contracts,\n }: {\n accounts: Encoded.AccountAddress[];\n contracts?: Encoded.ContractAddress[];\n }): Promise<EntUnpacked & { tag: EntryTag.TreesPoi }> {\n const { poi }: { poi: Encoded.Poi } = await call(this, 'channels.get.poi', {\n accounts,\n contracts,\n });\n return unpackEntry(poi);\n }\n\n /**\n * Get balances\n *\n * The accounts param contains a list of addresses to fetch balances of.\n * Those can be either account balances or a contract ones, encoded as an account addresses.\n *\n * If a certain account address had not being found in the state tree - it is simply\n * skipped in the response.\n *\n * @param accounts - List of addresses to fetch balances from\n * @example\n * ```js\n * channel.balances([\n * 'ak_Y1NRjHuoc3CGMYMvCmdHSBpJsMDR6Ra2t5zjhRcbtMeXXLpLH',\n * 'ak_V6an1xhec1xVaAhLuak7QoEbi6t7w5hEtYWp9bMKaJ19i6A9E'\n * 'ct_2dCUAWYZdrWfACz3a2faJeKVTVrfDYxCQHCqAt5zM15f3u2UfA'\n * ]).then(balances =>\n * console.log(balances['ak_Y1NRjHuoc3CGMYMvCmdHSBpJsMDR6Ra2t5zjhRcbtMeXXLpLH'])\n * )\n * ```\n */\n async balances(\n accounts: Encoded.AccountAddress[],\n ): Promise<{ [key: Encoded.AccountAddress]: string }> {\n return Object.fromEntries(\n (await call(this, 'channels.get.balances', { accounts })).map(\n (item: { account: Encoded.AccountAddress; balance: string }) => [\n item.account,\n item.balance,\n ],\n ),\n );\n }\n\n private async awaitingActionTx(\n action: 'deposit' | 'withdraw',\n message: ChannelMessage,\n state: ChannelState,\n ): Promise<ChannelFsm> {\n if (message.method !== `channels.sign.${action}_tx`) {\n return handleUnexpectedMessage(this, message, state);\n }\n\n const awaitingActionCompletion = (_: Channel, message2: ChannelMessage): ChannelFsm => {\n if (message2.method === 'channels.on_chain_tx') {\n state.onOnChainTx?.(message2.params.data.tx);\n return { handler: awaitingActionCompletion, state };\n }\n if (\n message2.method === 'channels.info' &&\n [`own_${action}_locked`, `${action}_locked`].includes(message2.params.data.event)\n ) {\n const Action = action === 'deposit' ? 'Deposit' : 'Withdraw';\n const isOwn: boolean = message2.params.data.event.startsWith('own_');\n state[`on${isOwn ? 'Own' : ''}${Action}Locked`]?.();\n return { handler: awaitingActionCompletion, state };\n }\n return awaitingCompletion(this, message2, state, () => {\n changeState(this, message2.params.data.state);\n state.resolve({ accepted: true, signedTx: message2.params.data.state });\n return { handler: channelOpen };\n });\n };\n\n const { sign } = state;\n await signAndNotify(this, `channels.${action}_tx`, message.params.data, async (tx) =>\n sign(tx, { updates: message.params.data.updates }),\n );\n return { handler: awaitingActionCompletion, state };\n }\n\n /**\n * Withdraw coins from the channel\n *\n * After the channel had been opened any of the participants can initiate a withdrawal.\n * The process closely resembles the update. The most notable difference is that the\n * transaction has been co-signed: it is channel_withdraw_tx and after the procedure\n * is finished - it is being posted on-chain.\n *\n * Any of the participants can initiate a withdrawal. The only requirements are:\n *\n * - Channel is already opened\n * - No off-chain update/deposit/withdrawal is currently being performed\n * - Channel is not being closed or in a solo closing state\n * - The withdrawal amount must be equal to or greater than zero, and cannot exceed\n * the available balance on the channel (minus the channel_reserve)\n *\n * After the other party had signed the withdraw transaction, the transaction is posted\n * on-chain and onOnChainTx callback is called with on-chain transaction as first argument.\n * After computing transaction hash it can be tracked on the chain: entering the mempool,\n * block inclusion and a number of confirmations.\n *\n * After the minimum_depth block confirmations onOwnWithdrawLocked callback is called\n * (without any arguments).\n *\n * When the other party had confirmed that the block height needed is reached\n * onWithdrawLocked callback is called (without any arguments).\n *\n * @param amount - Amount of coins to withdraw\n * @param sign - Function which verifies and signs withdraw transaction\n * @param callbacks - Callbacks\n * @example\n * ```js\n * channel.withdraw(\n * 100,\n * async (tx) => await account.signTransaction(tx),\n * { onOnChainTx: (tx) => console.log('on_chain_tx', tx) }\n * ).then(({ accepted, signedTx }) => {\n * if (accepted) {\n * console.log('Withdrawal has been accepted')\n * } else {\n * console.log('Withdrawal has been rejected')\n * }\n * })\n * ```\n */\n async withdraw(\n amount: number | BigNumber,\n sign: SignTx,\n {\n onOnChainTx,\n onOwnWithdrawLocked,\n onWithdrawLocked,\n }: Pick<ChannelState, 'onOnChainTx' | 'onOwnWithdrawLocked' | 'onWithdrawLocked'> = {},\n ): Promise<{ accepted: boolean; signedTx: Encoded.Transaction }> {\n return this.enqueueAction(() => {\n notify(this, 'channels.withdraw', { amount });\n return {\n handler: async (\n _: Channel,\n message: ChannelMessage,\n state: ChannelState,\n ): Promise<ChannelFsm> => this.awaitingActionTx('withdraw', message, state),\n state: {\n sign,\n onOnChainTx,\n onOwnWithdrawLocked,\n onWithdrawLocked,\n },\n };\n });\n }\n\n /**\n * Deposit coins into the channel\n *\n * After the channel had been opened any of the participants can initiate a deposit.\n * The process closely resembles the update. The most notable difference is that the\n * transaction has been co-signed: it is channel_deposit_tx and after the procedure\n * is finished - it is being posted on-chain.\n *\n * Any of the participants can initiate a deposit. The only requirements are:\n *\n * - Channel is already opened\n * - No off-chain update/deposit/withdrawal is currently being performed\n * - Channel is not being closed or in a solo closing state\n * - The deposit amount must be equal to or greater than zero, and cannot exceed\n * the available balance on the channel (minus the channel_reserve)\n *\n * After the other party had signed the deposit transaction, the transaction is posted\n * on-chain and onOnChainTx callback is called with on-chain transaction as first argument.\n * After computing transaction hash it can be tracked on the chain: entering the mempool,\n * block inclusion and a number of confirmations.\n *\n * After the minimum_depth block confirmations onOwnDepositLocked callback is called\n * (without any arguments).\n *\n * When the other party had confirmed that the block height needed is reached\n * onDepositLocked callback is called (without any arguments).\n *\n * @param amount - Amount of coins to deposit\n * @param sign - Function which verifies and signs deposit transaction\n * @param callbacks - Callbacks\n * @example\n * ```js\n * channel.deposit(\n * 100,\n * async (tx) => await account.signTransaction(tx),\n * { onOnChainTx: (tx) => console.log('on_chain_tx', tx) }\n * ).then(({ accepted, state }) => {\n * if (accepted) {\n * console.log('Deposit has been accepted')\n * console.log('The new state is:', state)\n * } else {\n * console.log('Deposit has been rejected')\n * }\n * })\n * ```\n */\n async deposit(\n amount: number | BigNumber,\n sign: SignTx,\n {\n onOnChainTx,\n onOwnDepositLocked,\n onDepositLocked,\n }: Pick<ChannelState, 'onOnChainTx' | 'onOwnDepositLocked' | 'onDepositLocked'> = {},\n ): Promise<{ accepted: boolean; state: ChannelState }> {\n return this.enqueueAction(() => {\n notify(this, 'channels.deposit', { amount });\n return {\n handler: async (\n _: Channel,\n message: ChannelMessage,\n state: ChannelState,\n ): Promise<ChannelFsm> => this.awaitingActionTx('deposit', message, state),\n state: {\n sign,\n onOnChainTx,\n onOwnDepositLocked,\n onDepositLocked,\n },\n };\n });\n }\n\n /**\n * Send generic message\n *\n * If message is an object it will be serialized into JSON string\n * before sending.\n *\n * If there is ongoing update that has not yet been finished the message\n * will be sent after that update is finalized.\n *\n * @param message - Message\n * @param recipient - Address of the recipient\n * @example\n * ```js\n * channel.sendMessage(\n * 'hello world',\n * 'ak_Y1NRjHuoc3CGMYMvCmdHSBpJsMDR6Ra2t5zjhRcbtMeXXLpLH'\n * )\n * ```\n */\n async sendMessage(message: string | object, recipient: Encoded.AccountAddress): Promise<void> {\n const info = typeof message === 'object' ? JSON.stringify(message) : message;\n if (this.status() === 'connecting') {\n await new Promise<void>((resolve) => {\n const onStatusChanged = (status: string): void => {\n if (status === 'connecting') return;\n resolve();\n this.off('statusChanged', onStatusChanged);\n };\n this.on('statusChanged', onStatusChanged);\n });\n // For some reason we can't immediately send a message when connection is\n // established. Thus we wait 500ms which seems to work.\n await pause(500);\n }\n notify(this, 'channels.message', { info, to: recipient });\n }\n}\n"],"mappings":"AACA,SACEA,MAAM,EACNC,IAAI,EAKJC,WAAW,QACN,eAAe;AAEtB,SAASC,KAAK,QAAQ,mBAAmB;AACzC,OAAOC,OAAO,MAAM,WAAW;AAC/B,SAASC,sBAAsB,QAAQ,oBAAoB;AAC3D,SACEC,kBAAkB,EAClBC,WAAW,EACXC,uBAAuB,EACvBC,aAAa,QACR,eAAe;AAGtB,SAASC,WAAW,QAAQ,8BAA8B;AAE1D,eAAe,MAAMC,YAAY,SAASP,OAAO,CAAC;EAChD;AACF;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;EAEE,MAAMQ,MAAMA,CACVC,IAA4B,EAC5BC,EAA0B,EAC1BC,MAA0B,EAC1BC,IAAY,EACZC,QAAkB,GAAG,EAAE,EAMtB;IACD,OAAO,IAAI,CAACC,aAAa,CAAC,MAAM;MAC9BlB,MAAM,CAAC,IAAI,EAAE,qBAAqB,EAAE;QAClCa,IAAI;QACJC,EAAE;QACFC,MAAM;QACNI,IAAI,EAAEF;MACR,CAAC,CAAC;MAEF,MAAMG,kBAAkB,GAAG,MAAAA,CACzBC,CAAU,EACVC,OAAuB,EACvBC,KAAmB,KACK;QACxB,IAAID,OAAO,CAACE,MAAM,KAAK,sBAAsB,EAAE;UAC7C,MAAMC,OAAO,GAAG,MAAMhB,aAAa,CACjC,IAAI,EACJ,iBAAiB,EACjBa,OAAO,CAACI,MAAM,CAACC,IAAI,EACnB,MAAOC,EAAE,IAAKZ,IAAI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ACA;EACE,MAAMC,WAAWA,CAACxC,OAAwB,EAAEyC,SAAiC,EAAiB;IAC5F,MAAMC,IAAI,GAAG,OAAO1C,OAAO,KAAK,QAAQ,GAAG2C,IAAI,CAACC,SAAS,CAAC5C,OAAO,CAAC,GAAGA,OAAO;IAC5E,IAAI,IAAI,CAAC6C,MAAM,CAAC,CAAC,KAAK,YAAY,EAAE;MAClC,MAAM,IAAIC,OAAO,CAAQnC,OAAO,IAAK;QACnC,MAAMoC,eAAe,GAAIF,MAAc,IAAW;UAChD,IAAIA,MAAM,KAAK,YAAY,EAAE;UAC7BlC,OAAO,CAAC,CAAC;UACT,IAAI,CAACqC,GAAG,CAAC,eAAe,EAAED,eAAe,CAAC;QAC5C,CAAC;QACD,IAAI,CAACE,EAAE,CAAC,eAAe,EAAEF,eAAe,CAAC;MAC3C,CAAC,CAAC;MACF;MACA;MACA,MAAMlE,KAAK,CAAC,GAAG,CAAC;IAClB;IACAH,MAAM,CAAC,IAAI,EAAE,kBAAkB,EAAE;MAAEgE,IAAI;MAAElD,EAAE,EAAEiD;IAAU,CAAC,CAAC;EAC3D;AACF","ignoreList":[]}
@@ -27,13 +27,12 @@ export async function appendSignature(tx, signFn) {
27
27
  return result;
28
28
  }
29
29
  export async function signAndNotify(channel, method, data, signFn) {
30
- var _signedTx;
31
30
  let signedTx;
32
31
  if (data.tx != null) signedTx = await signFn(data.tx);else if (data.signed_tx != null) signedTx = await appendSignature(data.signed_tx, signFn);else throw new ChannelError("Can't find transaction in message");
33
32
  const isError = typeof signedTx !== 'string';
34
33
  const key = data.tx != null ? 'tx' : 'signed_tx';
35
34
  notify(channel, method, isError ? {
36
- error: (_signedTx = signedTx) !== null && _signedTx !== void 0 ? _signedTx : 1
35
+ error: signedTx !== null && signedTx !== void 0 ? signedTx : 1
37
36
  } : {
38
37
  [key]: signedTx
39
38
  });