@aeternity/aepp-sdk 13.0.0-alpha.0 → 13.0.0-alpha.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bin/aesophia_cli +0 -0
- package/dist/aepp-sdk.browser-script.js +1 -1
- package/dist/aepp-sdk.browser-script.js.map +1 -1
- package/dist/aepp-sdk.browser.js +1 -1
- package/dist/aepp-sdk.browser.js.map +1 -1
- package/dist/aepp-sdk.js +4206 -1127
- package/dist/aepp-sdk.js.map +1 -1
- package/es/AeSdkBase.d.ts +3 -3
- package/es/AeSdkBase.mjs +4 -0
- package/es/AeSdkBase.mjs.map +1 -1
- package/es/AeSdkMethods.d.ts +3 -4
- package/es/AeSdkMethods.mjs.map +1 -1
- package/es/Node.d.ts +4 -3
- package/es/Node.mjs +1 -1
- package/es/Node.mjs.map +1 -1
- package/es/account/Base.d.ts +2 -2
- package/es/account/Base.mjs.map +1 -1
- package/es/account/Generalized.mjs +5 -3
- package/es/account/Generalized.mjs.map +1 -1
- package/es/account/Ledger.mjs +2 -1
- package/es/account/Ledger.mjs.map +1 -1
- package/es/account/Memory.mjs +2 -1
- package/es/account/Memory.mjs.map +1 -1
- package/es/aens.d.ts +1 -1
- package/es/aens.mjs +5 -1
- package/es/aens.mjs.map +1 -1
- package/es/aepp-wallet-communication/connection/BrowserRuntime.d.ts +1 -0
- package/es/aepp-wallet-communication/connection/BrowserRuntime.mjs +19 -4
- package/es/aepp-wallet-communication/connection/BrowserRuntime.mjs.map +1 -1
- package/es/aepp-wallet-communication/rpc/RpcClient.mjs +1 -1
- package/es/aepp-wallet-communication/rpc/RpcClient.mjs.map +1 -1
- package/es/chain.d.ts +9 -1
- package/es/chain.mjs +4 -1
- package/es/chain.mjs.map +1 -1
- package/es/channel/Base.d.ts +6 -1
- package/es/channel/Base.mjs +9 -6
- package/es/channel/Base.mjs.map +1 -1
- package/es/channel/Contract.d.ts +8 -7
- package/es/channel/Contract.mjs +1 -1
- package/es/channel/Contract.mjs.map +1 -1
- package/es/channel/Spend.d.ts +3 -1
- package/es/channel/Spend.mjs +4 -2
- package/es/channel/Spend.mjs.map +1 -1
- package/es/channel/handlers.mjs +11 -9
- package/es/channel/handlers.mjs.map +1 -1
- package/es/channel/internal.mjs +3 -1
- package/es/channel/internal.mjs.map +1 -1
- package/es/contract/Contract.d.ts +21 -46
- package/es/contract/Contract.mjs +69 -52
- package/es/contract/Contract.mjs.map +1 -1
- package/es/contract/compiler/Base.d.ts +81 -0
- package/es/contract/compiler/Base.mjs +5 -0
- package/es/contract/compiler/Base.mjs.map +1 -0
- package/es/contract/compiler/Cli.d.ts +23 -0
- package/es/contract/compiler/Cli.mjs +155 -0
- package/es/contract/compiler/Cli.mjs.map +1 -0
- package/es/contract/compiler/Http.d.ts +32 -0
- package/es/contract/{CompilerHttp.mjs → compiler/Http.mjs} +64 -9
- package/es/contract/compiler/Http.mjs.map +1 -0
- package/es/contract/compiler/HttpNode.d.ts +17 -0
- package/es/contract/compiler/HttpNode.mjs +26 -0
- package/es/contract/compiler/HttpNode.mjs.map +1 -0
- package/es/contract/compiler/getFileSystem.d.ts +6 -0
- package/es/contract/compiler/getFileSystem.mjs +40 -0
- package/es/contract/compiler/getFileSystem.mjs.map +1 -0
- package/es/contract/ga.d.ts +5 -4
- package/es/contract/ga.mjs +11 -2
- package/es/contract/ga.mjs.map +1 -1
- package/es/index-browser.d.ts +39 -0
- package/es/index-browser.mjs +55 -0
- package/es/index-browser.mjs.map +1 -0
- package/es/index.d.ts +4 -38
- package/es/index.mjs +4 -53
- package/es/index.mjs.map +1 -1
- package/es/oracle.mjs +1 -1
- package/es/oracle.mjs.map +1 -1
- package/es/spend.mjs +1 -3
- package/es/spend.mjs.map +1 -1
- package/es/tx/builder/constants.d.ts +28 -1
- package/es/tx/builder/constants.mjs +32 -3
- package/es/tx/builder/constants.mjs.map +1 -1
- package/es/tx/builder/field-types/abi-version.d.ts +10 -0
- package/es/tx/builder/field-types/abi-version.mjs +20 -0
- package/es/tx/builder/field-types/abi-version.mjs.map +1 -0
- package/es/tx/builder/field-types/address.d.ts +5 -6
- package/es/tx/builder/field-types/address.mjs +17 -8
- package/es/tx/builder/field-types/address.mjs.map +1 -1
- package/es/tx/builder/field-types/array.d.ts +7 -0
- package/es/tx/builder/field-types/array.mjs +11 -0
- package/es/tx/builder/field-types/array.mjs.map +1 -0
- package/es/tx/builder/field-types/boolean.d.ts +6 -0
- package/es/tx/builder/field-types/boolean.mjs +13 -0
- package/es/tx/builder/field-types/boolean.mjs.map +1 -0
- package/es/tx/builder/field-types/coin-amount.d.ts +1 -1
- package/es/tx/builder/field-types/coin-amount.mjs.map +1 -1
- package/es/tx/builder/field-types/ct-version.d.ts +30 -0
- package/es/tx/builder/field-types/ct-version.mjs +48 -0
- package/es/tx/builder/field-types/ct-version.mjs.map +1 -0
- package/es/tx/builder/field-types/deposit.d.ts +1 -1
- package/es/tx/builder/field-types/deposit.mjs.map +1 -1
- package/es/tx/builder/field-types/encoded.d.ts +6 -0
- package/es/tx/builder/field-types/encoded.mjs +21 -0
- package/es/tx/builder/field-types/encoded.mjs.map +1 -0
- package/es/tx/builder/field-types/entry.d.ts +11 -0
- package/es/tx/builder/field-types/entry.mjs +31 -0
- package/es/tx/builder/field-types/entry.mjs.map +1 -0
- package/es/tx/builder/field-types/enumeration.d.ts +5 -3
- package/es/tx/builder/field-types/enumeration.mjs +11 -2
- package/es/tx/builder/field-types/enumeration.mjs.map +1 -1
- package/es/tx/builder/field-types/fee.d.ts +10 -7
- package/es/tx/builder/field-types/fee.mjs +24 -20
- package/es/tx/builder/field-types/fee.mjs.map +1 -1
- package/es/tx/builder/field-types/gas-limit.d.ts +5 -2
- package/es/tx/builder/field-types/gas-limit.mjs +9 -6
- package/es/tx/builder/field-types/gas-limit.mjs.map +1 -1
- package/es/tx/builder/field-types/gas-price.d.ts +1 -1
- package/es/tx/builder/field-types/index.d.ts +66 -28
- package/es/tx/builder/field-types/index.mjs +30 -12
- package/es/tx/builder/field-types/index.mjs.map +1 -1
- package/es/tx/builder/field-types/mptree.d.ts +37 -0
- package/es/tx/builder/field-types/mptree.mjs +268 -0
- package/es/tx/builder/field-types/mptree.mjs.map +1 -0
- package/es/tx/builder/field-types/name-fee.d.ts +1 -2
- package/es/tx/builder/field-types/name-fee.mjs.map +1 -1
- package/es/tx/builder/field-types/name-id.mjs +2 -1
- package/es/tx/builder/field-types/name-id.mjs.map +1 -1
- package/es/tx/builder/field-types/pointers.mjs +2 -2
- package/es/tx/builder/field-types/pointers.mjs.map +1 -1
- package/es/tx/builder/field-types/raw.d.ts +6 -0
- package/es/tx/builder/field-types/raw.mjs +13 -0
- package/es/tx/builder/field-types/raw.mjs.map +1 -0
- package/es/tx/builder/field-types/short-u-int-const.d.ts +5 -0
- package/es/tx/builder/field-types/short-u-int-const.mjs +16 -0
- package/es/tx/builder/field-types/short-u-int-const.mjs.map +1 -0
- package/es/tx/builder/field-types/string.d.ts +6 -0
- package/es/tx/builder/field-types/string.mjs +10 -0
- package/es/tx/builder/field-types/string.mjs.map +1 -0
- package/es/tx/builder/field-types/u-int.d.ts +1 -2
- package/es/tx/builder/field-types/u-int.mjs.map +1 -1
- package/es/tx/builder/index.d.ts +11 -29
- package/es/tx/builder/index.mjs +50 -211
- package/es/tx/builder/index.mjs.map +1 -1
- package/es/tx/builder/schema.d.ts +2111 -571
- package/es/tx/builder/schema.mjs +57 -125
- package/es/tx/builder/schema.mjs.map +1 -1
- package/es/tx/index.d.ts +5 -20
- package/es/tx/index.mjs +31 -88
- package/es/tx/index.mjs.map +1 -1
- package/es/tx/validator.d.ts +3 -5
- package/es/tx/validator.mjs +82 -95
- package/es/tx/validator.mjs.map +1 -1
- package/es/utils/bytes.mjs +1 -1
- package/es/utils/bytes.mjs.map +1 -1
- package/es/utils/errors.d.ts +3 -8
- package/es/utils/errors.mjs +1 -11
- package/es/utils/errors.mjs.map +1 -1
- package/es/utils/other.d.ts +1 -1
- package/package.json +35 -27
- package/src/AeSdkBase.ts +6 -3
- package/src/AeSdkMethods.ts +3 -4
- package/src/Node.ts +6 -3
- package/src/account/Base.ts +2 -2
- package/src/account/Generalized.ts +2 -2
- package/src/account/Ledger.ts +1 -1
- package/src/account/Memory.ts +1 -1
- package/src/aens.ts +3 -2
- package/src/aepp-wallet-communication/connection/BrowserRuntime.ts +18 -7
- package/src/aepp-wallet-communication/rpc/RpcClient.ts +2 -2
- package/src/chain.ts +5 -3
- package/src/channel/Base.ts +13 -5
- package/src/channel/Contract.ts +11 -10
- package/src/channel/Spend.ts +7 -2
- package/src/channel/handlers.ts +10 -9
- package/src/channel/internal.ts +1 -1
- package/src/contract/Contract.ts +69 -79
- package/src/contract/compiler/Base.ts +94 -0
- package/src/contract/compiler/Cli.ts +134 -0
- package/src/contract/compiler/Http.ts +124 -0
- package/src/contract/compiler/HttpNode.ts +26 -0
- package/src/contract/compiler/getFileSystem.ts +42 -0
- package/src/contract/ga.ts +9 -6
- package/src/index-browser.ts +58 -0
- package/src/index.ts +4 -56
- package/src/oracle.ts +1 -1
- package/src/spend.ts +1 -1
- package/src/tx/builder/constants.ts +32 -3
- package/src/tx/builder/field-types/abi-version.ts +21 -0
- package/src/tx/builder/field-types/address.ts +23 -13
- package/src/tx/builder/field-types/array.ts +19 -0
- package/src/tx/builder/field-types/boolean.ts +9 -0
- package/src/tx/builder/field-types/coin-amount.ts +2 -1
- package/src/tx/builder/field-types/ct-version.ts +50 -0
- package/src/tx/builder/field-types/deposit.ts +1 -1
- package/src/tx/builder/field-types/encoded.ts +27 -0
- package/src/tx/builder/field-types/entry.ts +31 -0
- package/src/tx/builder/field-types/enumeration.ts +15 -4
- package/src/tx/builder/field-types/fee.ts +38 -18
- package/src/tx/builder/field-types/gas-limit.ts +12 -7
- package/src/tx/builder/field-types/index.ts +46 -17
- package/src/tx/builder/field-types/mptree.ts +242 -0
- package/src/tx/builder/field-types/name-fee.ts +1 -2
- package/src/tx/builder/field-types/name-id.ts +1 -1
- package/src/tx/builder/field-types/pointers.ts +2 -2
- package/src/tx/builder/field-types/raw.ts +9 -0
- package/src/tx/builder/field-types/short-u-int-const.ts +20 -0
- package/src/tx/builder/field-types/string.ts +11 -0
- package/src/tx/builder/field-types/u-int.ts +1 -3
- package/src/tx/builder/index.ts +63 -247
- package/src/tx/builder/schema.ts +273 -323
- package/src/tx/index.ts +37 -104
- package/src/tx/validator.ts +72 -95
- package/src/utils/bytes.ts +1 -1
- package/src/utils/errors.ts +4 -13
- package/types-legacy/ts4.2/AeSdkBase.d.ts +3 -3
- package/types-legacy/ts4.2/AeSdkMethods.d.ts +3 -4
- package/types-legacy/ts4.2/Node.d.ts +3 -3
- package/types-legacy/ts4.2/account/Base.d.ts +2 -2
- package/types-legacy/ts4.2/aens.d.ts +1 -1
- package/types-legacy/ts4.2/aepp-wallet-communication/connection/BrowserRuntime.d.ts +1 -0
- package/types-legacy/ts4.2/chain.d.ts +9 -1
- package/types-legacy/ts4.2/channel/Base.d.ts +6 -1
- package/types-legacy/ts4.2/channel/Contract.d.ts +8 -7
- package/types-legacy/ts4.2/channel/Spend.d.ts +3 -1
- package/types-legacy/ts4.2/contract/Contract.d.ts +21 -46
- package/types-legacy/ts4.2/contract/compiler/Base.d.ts +81 -0
- package/types-legacy/ts4.2/contract/compiler/Cli.d.ts +23 -0
- package/types-legacy/ts4.2/contract/compiler/Http.d.ts +32 -0
- package/types-legacy/ts4.2/contract/compiler/HttpNode.d.ts +17 -0
- package/types-legacy/ts4.2/contract/compiler/getFileSystem.d.ts +6 -0
- package/types-legacy/ts4.2/contract/ga.d.ts +5 -4
- package/types-legacy/ts4.2/index-browser.d.ts +39 -0
- package/types-legacy/ts4.2/index.d.ts +4 -38
- package/types-legacy/ts4.2/tx/builder/constants.d.ts +28 -1
- package/types-legacy/ts4.2/tx/builder/field-types/abi-version.d.ts +10 -0
- package/types-legacy/ts4.2/tx/builder/field-types/address.d.ts +11 -12
- package/types-legacy/ts4.2/tx/builder/field-types/array.d.ts +7 -0
- package/types-legacy/ts4.2/tx/builder/field-types/boolean.d.ts +6 -0
- package/types-legacy/ts4.2/tx/builder/field-types/coin-amount.d.ts +1 -1
- package/types-legacy/ts4.2/tx/builder/field-types/ct-version.d.ts +42 -0
- package/types-legacy/ts4.2/tx/builder/field-types/deposit.d.ts +1 -1
- package/types-legacy/ts4.2/tx/builder/field-types/encoded.d.ts +6 -0
- package/types-legacy/ts4.2/tx/builder/field-types/entry.d.ts +11 -0
- package/types-legacy/ts4.2/tx/builder/field-types/enumeration.d.ts +5 -3
- package/types-legacy/ts4.2/tx/builder/field-types/fee.d.ts +10 -7
- package/types-legacy/ts4.2/tx/builder/field-types/gas-limit.d.ts +5 -2
- package/types-legacy/ts4.2/tx/builder/field-types/gas-price.d.ts +1 -1
- package/types-legacy/ts4.2/tx/builder/field-types/index.d.ts +72 -28
- package/types-legacy/ts4.2/tx/builder/field-types/mptree.d.ts +43 -0
- package/types-legacy/ts4.2/tx/builder/field-types/name-fee.d.ts +1 -2
- package/types-legacy/ts4.2/tx/builder/field-types/raw.d.ts +6 -0
- package/types-legacy/ts4.2/tx/builder/field-types/short-u-int-const.d.ts +5 -0
- package/types-legacy/ts4.2/tx/builder/field-types/string.d.ts +6 -0
- package/types-legacy/ts4.2/tx/builder/field-types/u-int.d.ts +1 -2
- package/types-legacy/ts4.2/tx/builder/index.d.ts +11 -29
- package/types-legacy/ts4.2/tx/builder/schema.d.ts +2380 -668
- package/types-legacy/ts4.2/tx/index.d.ts +5 -20
- package/types-legacy/ts4.2/tx/validator.d.ts +3 -5
- package/types-legacy/ts4.2/utils/errors.d.ts +3 -8
- package/types-legacy/ts4.2/utils/other.d.ts +1 -1
- package/types-legacy/ts4.5/AeSdkBase.d.ts +3 -3
- package/types-legacy/ts4.5/AeSdkMethods.d.ts +3 -4
- package/types-legacy/ts4.5/Node.d.ts +3 -3
- package/types-legacy/ts4.5/account/Base.d.ts +2 -2
- package/types-legacy/ts4.5/aens.d.ts +1 -1
- package/types-legacy/ts4.5/aepp-wallet-communication/connection/BrowserRuntime.d.ts +1 -0
- package/types-legacy/ts4.5/chain.d.ts +9 -1
- package/types-legacy/ts4.5/channel/Base.d.ts +6 -1
- package/types-legacy/ts4.5/channel/Contract.d.ts +8 -7
- package/types-legacy/ts4.5/channel/Spend.d.ts +3 -1
- package/types-legacy/ts4.5/contract/Contract.d.ts +21 -46
- package/types-legacy/ts4.5/contract/compiler/Base.d.ts +81 -0
- package/types-legacy/ts4.5/contract/compiler/Cli.d.ts +23 -0
- package/types-legacy/ts4.5/contract/compiler/Http.d.ts +32 -0
- package/types-legacy/ts4.5/contract/compiler/HttpNode.d.ts +17 -0
- package/types-legacy/ts4.5/contract/compiler/getFileSystem.d.ts +6 -0
- package/types-legacy/ts4.5/contract/ga.d.ts +5 -4
- package/types-legacy/ts4.5/index-browser.d.ts +39 -0
- package/types-legacy/ts4.5/index.d.ts +4 -38
- package/types-legacy/ts4.5/tx/builder/constants.d.ts +28 -1
- package/types-legacy/ts4.5/tx/builder/field-types/abi-version.d.ts +10 -0
- package/types-legacy/ts4.5/tx/builder/field-types/address.d.ts +11 -12
- package/types-legacy/ts4.5/tx/builder/field-types/array.d.ts +7 -0
- package/types-legacy/ts4.5/tx/builder/field-types/boolean.d.ts +6 -0
- package/types-legacy/ts4.5/tx/builder/field-types/coin-amount.d.ts +1 -1
- package/types-legacy/ts4.5/tx/builder/field-types/ct-version.d.ts +42 -0
- package/types-legacy/ts4.5/tx/builder/field-types/deposit.d.ts +1 -1
- package/types-legacy/ts4.5/tx/builder/field-types/encoded.d.ts +6 -0
- package/types-legacy/ts4.5/tx/builder/field-types/entry.d.ts +11 -0
- package/types-legacy/ts4.5/tx/builder/field-types/enumeration.d.ts +5 -3
- package/types-legacy/ts4.5/tx/builder/field-types/fee.d.ts +10 -7
- package/types-legacy/ts4.5/tx/builder/field-types/gas-limit.d.ts +5 -2
- package/types-legacy/ts4.5/tx/builder/field-types/gas-price.d.ts +1 -1
- package/types-legacy/ts4.5/tx/builder/field-types/index.d.ts +72 -28
- package/types-legacy/ts4.5/tx/builder/field-types/mptree.d.ts +43 -0
- package/types-legacy/ts4.5/tx/builder/field-types/name-fee.d.ts +1 -2
- package/types-legacy/ts4.5/tx/builder/field-types/raw.d.ts +6 -0
- package/types-legacy/ts4.5/tx/builder/field-types/short-u-int-const.d.ts +5 -0
- package/types-legacy/ts4.5/tx/builder/field-types/string.d.ts +6 -0
- package/types-legacy/ts4.5/tx/builder/field-types/u-int.d.ts +1 -2
- package/types-legacy/ts4.5/tx/builder/index.d.ts +11 -29
- package/types-legacy/ts4.5/tx/builder/schema.d.ts +2380 -668
- package/types-legacy/ts4.5/tx/index.d.ts +5 -20
- package/types-legacy/ts4.5/tx/validator.d.ts +3 -5
- package/types-legacy/ts4.5/utils/errors.d.ts +3 -8
- package/types-legacy/ts4.5/utils/other.d.ts +1 -1
- package/es/contract/CompilerHttp.d.ts +0 -18
- package/es/contract/CompilerHttp.mjs.map +0 -1
- package/es/tx/builder/field-types/addresses.d.ts +0 -6
- package/es/tx/builder/field-types/addresses.mjs +0 -13
- package/es/tx/builder/field-types/addresses.mjs.map +0 -1
- package/es/utils/mptree.d.ts +0 -26
- package/es/utils/mptree.mjs +0 -143
- package/es/utils/mptree.mjs.map +0 -1
- package/src/contract/CompilerHttp.ts +0 -67
- package/src/tx/builder/field-types/addresses.ts +0 -18
- package/src/utils/mptree.ts +0 -145
- package/types-legacy/ts4.2/contract/CompilerHttp.d.ts +0 -18
- package/types-legacy/ts4.2/tx/builder/field-types/addresses.d.ts +0 -6
- package/types-legacy/ts4.2/utils/mptree.d.ts +0 -32
- package/types-legacy/ts4.5/contract/CompilerHttp.d.ts +0 -18
- package/types-legacy/ts4.5/tx/builder/field-types/addresses.d.ts +0 -6
- package/types-legacy/ts4.5/utils/mptree.d.ts +0 -32
package/es/aens.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"aens.mjs","names":["genSalt","commitmentHash","isAuctionName","CLIENT_TTL","NAME_TTL","Tag","ArgumentError","send","getName","getHeight","_buildTx","aensRevoke","name","options","nameRevokeTx","NameRevokeTx","nameId","accountId","onAccount","address","aensUpdate","pointers","extendPointers","allPointers","Object","fromEntries","map","key","id","nameUpdateTx","NameUpdateTx","clientTtl","nameTtl","entries","aensTransfer","account","nameTransferTx","NameTransferTx","recipientId","aensQuery","opt","nameEntry","freeze","owner","update","transfer","revoke","extendTtl","aensClaim","salt","claimTx","NameClaimTx","nameSalt","result","nameInter","blockHeight","assign","aensPreclaim","height","commitmentId","preclaimTx","NamePreclaimTx","claim","opts","aensBid","nameFee"],"sources":["../src/aens.ts"],"sourcesContent":["/*\n * ISC License (ISC)\n * Copyright (c) 2022 aeternity developers\n *\n * Permission to use, copy, modify, and/or distribute this software for any\n * purpose with or without fee is hereby granted, provided that the above\n * copyright notice and this permission notice appear in all copies.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\n * REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\n * AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\n * INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\n * LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\n * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\n * PERFORMANCE OF THIS SOFTWARE.\n */\n\n/**\n * Aens methods - routines to interact with the æternity naming system\n *\n * The high-level description of the naming system is\n * https://github.com/aeternity/protocol/blob/master/AENS.md in the protocol\n * repository.\n */\n\nimport BigNumber from 'bignumber.js';\nimport { genSalt } from './utils/crypto';\nimport { commitmentHash, isAuctionName } from './tx/builder/helpers';\nimport {\n CLIENT_TTL, NAME_TTL, Tag, AensName,\n} from './tx/builder/constants';\nimport { ArgumentError } from './utils/errors';\nimport { Encoded } from './utils/encoder';\nimport { send, SendOptions } from './spend';\nimport { getName, getHeight } from './chain';\nimport { _buildTx, BuildTxOptions } from './tx';\nimport { TransformNodeType } from './Node';\nimport { NameEntry, NamePointer } from './apis/node';\nimport AccountBase from './account/Base';\nimport { AddressEncodings } from './tx/builder/field-types/address';\n\ninterface KeyPointers {\n [key: string]: Encoded.Generic<AddressEncodings>;\n}\n\n/**\n * Revoke a name\n * @category AENS\n * @param name - Name hash\n * @param options - Options\n * @param options.onAccount - Make operation on specific account from sdk (you pass\n * publickKey) or using provided KeyPair(Can be keypair object or MemoryAccount)\n * @param options.fee - fee\n * @param options.ttl - ttl\n * @param options.nonce - nonce\n * @returns Transaction result\n * @example\n * ```js\n * const name = 'test.chain'\n * const nameObject = await sdkInstance.aensQuery(name)\n *\n * await sdkInstance.aensRevoke(name, { fee, ttl , nonce })\n * // or\n * await nameObject.revoke({ fee, ttl, nonce })\n * ```\n */\nexport async function aensRevoke(\n name: AensName,\n options: AensRevokeOptions,\n): ReturnType<typeof send> {\n const nameRevokeTx = await _buildTx(Tag.NameRevokeTx, {\n ...options,\n nameId: name,\n accountId: options.onAccount.address,\n });\n return send(nameRevokeTx, options);\n}\n\ninterface AensRevokeOptions extends\n BuildTxOptions<Tag.NameRevokeTx, 'nameId' | 'accountId'>,\n SendOptions {}\n\n/**\n * Update a name\n * @category AENS\n * @param name - AENS name\n * @param pointers - Map of pointer keys to corresponding addresses\n * @param options - Options\n * @param options.extendPointers - Get the pointers from the node and merge with provided\n * ones. Pointers with the same type will be overwritten\n * @param options.onAccount - Make operation on specific account from sdk (you\n * pass publickKey) or using provided KeyPair(Can be keypair object or MemoryAccount)\n * @param options.fee - fee\n * @param options.ttl - ttl\n * @param options.nonce - nonce\n * @param options.nameTtl - Name ttl represented in number of\n * blocks (Max value is 50000 blocks)\n * @param options.clientTtl=84600 a suggestion as to how long any\n * clients should cache this information\n * @throws Invalid pointer array error\n * @example\n * ```js\n * const name = 'test.chain'\n * const pointersArray = ['ak_asd23dasdas...,' 'ct_asdf34fasdasd...']\n * const nameObject = await sdkInstance.aensQuery(name)\n *\n * await sdkInstance.aensUpdate(name, pointersArray, { nameTtl, ttl, fee, nonce, clientTtl })\n * // or\n * await nameObject.update(pointers, { nameTtl, ttl, fee, nonce, clientTtl })\n * ```\n */\nexport async function aensUpdate(\n name: AensName,\n pointers: KeyPointers,\n { extendPointers, ...options }: AensUpdateOptions,\n): ReturnType<typeof send> {\n const allPointers = {\n ...extendPointers === true && Object.fromEntries(\n (await getName(name, options)).pointers.map(({ key, id }) => [key, id]),\n ),\n ...pointers,\n };\n\n const nameUpdateTx = await _buildTx(Tag.NameUpdateTx, {\n clientTtl: CLIENT_TTL,\n nameTtl: NAME_TTL,\n ...options,\n nameId: name,\n accountId: options.onAccount.address,\n pointers: Object.entries(allPointers)\n .map(([key, id]: [string, Encoded.Generic<AddressEncodings>]) => ({ key, id })),\n });\n\n return send(nameUpdateTx, options);\n}\n\ninterface AensUpdateOptions extends\n BuildTxOptions<Tag.NameUpdateTx, 'nameId' | 'accountId' | 'pointers' | 'clientTtl' | 'nameTtl'>,\n SendOptions {\n extendPointers?: boolean;\n clientTtl?: number;\n nameTtl?: number;\n}\n\n/**\n * Transfer a domain to another account\n * @category AENS\n * @param name - AENS name\n * @param account - Recipient account publick key\n * @param options - Options\n * @param options.onAccount - Make operation on specific account from sdk (you pass\n * publickKey) or using provided KeyPair(Can be keypair object or MemoryAccount)\n * @param options.fee - fee\n * @param options.ttl - ttl\n * @param options.nonce - nonce\n * @returns Transaction result\n * @example\n * ```js\n * const name = 'test.chain'\n * const recipientPub = 'ak_asd23dasdas...'\n * const nameObject = await sdkInstance.aensQuery(name)\n *\n * await sdkInstance.aensTransfer(name, recipientPub, { ttl, fee, nonce })\n * // or\n * await nameObject.transfer(recipientPub, { ttl, fee, nonce })\n * ```\n */\nexport async function aensTransfer(\n name: AensName,\n account: Encoded.AccountAddress,\n options: AensTransferOptions,\n): ReturnType<typeof send> {\n const nameTransferTx = await _buildTx(Tag.NameTransferTx, {\n ...options,\n nameId: name,\n accountId: options.onAccount.address,\n recipientId: account,\n });\n\n return send(nameTransferTx, options);\n}\n\ninterface AensTransferOptions extends\n BuildTxOptions<Tag.NameTransferTx, 'nameId' | 'accountId' | 'recipientId'>,\n SendOptions {}\n\n/**\n * Query the AENS name info from the node\n * and return the object with info and predefined functions for manipulating name\n * @category AENS\n * @param name - AENS name\n * @param opt - Options\n * @returns\n * @example\n * ```js\n * const nameObject = sdkInstance.aensQuery('test.chain')\n * console.log(nameObject)\n * {\n * id, // name hash\n * pointers, // array of pointers\n * update, // Update name function\n * extendTtl, // Extend Ttl name function\n * transfer, // Transfer name function\n * revoke // Revoke name function\n * }\n * ```\n */\nexport async function aensQuery(\n name: AensName,\n opt: Parameters<typeof getName>[1] & Parameters<typeof aensUpdate>[2]\n & Parameters<typeof aensTransfer>[2],\n): Promise<Readonly<\n TransformNodeType<NameEntry> & {\n id: Encoded.Name;\n owner: Encoded.AccountAddress;\n pointers: KeyPointers | NamePointer[];\n ttl: number;\n update: (\n pointers: KeyPointers,\n options?: Omit<Parameters<typeof aensQuery>[1], 'onNode' | 'onCompiler' | 'onAccount'> & {\n onAccount?: AccountBase;\n }\n ) => ReturnType<typeof aensUpdate> & ReturnType<typeof aensQuery>;\n transfer: (\n account: Encoded.AccountAddress,\n options?: Parameters<typeof aensQuery>[1]\n ) => ReturnType<typeof aensUpdate> & ReturnType<typeof aensQuery>;\n revoke: (options?: Omit<Parameters<typeof aensRevoke>[1], 'onNode' | 'onCompiler' | 'onAccount'> & {\n onAccount?: AccountBase;\n }\n ) => ReturnType<typeof aensRevoke>;\n extendTtl: (\n nameTtl: number,\n options?: Omit<Parameters<typeof aensQuery>[1], 'onNode' | 'onCompiler' | 'onAccount'>\n ) => ReturnType<typeof aensUpdate> & ReturnType<typeof aensQuery>;\n }\n >> {\n const nameEntry = await getName(name, opt);\n return Object.freeze({\n ...nameEntry,\n id: nameEntry.id as Encoded.Name,\n owner: nameEntry.owner as Encoded.AccountAddress,\n async update(pointers, options) {\n return {\n ...await aensUpdate(name, pointers, { ...opt, ...options }),\n ...await aensQuery(name, { ...opt, ...options }),\n };\n },\n async transfer(account, options) {\n return {\n ...await aensTransfer(name, account, { ...opt, ...options }),\n ...await aensQuery(name, { ...opt, ...options }),\n };\n },\n async revoke(options) {\n return aensRevoke(name, { ...opt, ...options });\n },\n async extendTtl(nameTtl = NAME_TTL, options = {}) {\n if (nameTtl > NAME_TTL || nameTtl <= 0) {\n throw new ArgumentError('nameTtl', `a number between 1 and ${NAME_TTL} blocks`, nameTtl);\n }\n\n return {\n ...await aensUpdate(name, {}, {\n ...opt, ...options, nameTtl, extendPointers: true,\n }),\n ...await aensQuery(name, { ...opt, ...options }),\n };\n },\n });\n}\n\n/**\n * Claim a previously preclaimed registration. This can only be done after the\n * preclaim step\n * @category AENS\n * @param name - AENS name\n * @param salt - Salt from pre-claim, or 0 if it's a bid\n * @param options - options\n * @param options.onAccount - Make operation on specific account from sdk (you pass\n * publickKey) or using provided KeyPair(Can be keypair object or MemoryAccount)\n * @param options.fee - fee\n * @param options.ttl - ttl\n * @param options.nonce - nonce\n * @param options.nameFee - Name Fee (By default calculated by sdk)\n * @returns the result of the claim\n * @example\n * ```js\n * const name = 'test.chain'\n * const salt = preclaimResult.salt // salt from pre-claim transaction\n *\n * await sdkInstance.aensClaim(name, salt, { ttl, fee, nonce, nameFee })\n * ```\n */\nexport async function aensClaim(\n name: AensName,\n salt: number,\n options: AensClaimOptions,\n): Promise<AensClaimReturnType> {\n const claimTx = await _buildTx(Tag.NameClaimTx, {\n ...options,\n accountId: options.onAccount.address,\n nameSalt: salt,\n name,\n });\n\n const result = await send(claimTx, options);\n if (!isAuctionName(name)) {\n const nameInter = result.blockHeight != null && result.blockHeight > 0\n ? await aensQuery(name, options)\n : {};\n return Object.assign(result, nameInter);\n }\n return result;\n}\n\ntype AensClaimOptionsType = BuildTxOptions<Tag.NameClaimTx, 'accountId' | 'nameSalt' | 'name'>\n& SendOptions & Parameters<typeof aensQuery>[1];\ninterface AensClaimOptions extends AensClaimOptionsType {}\ninterface AensClaimReturnType extends\n Awaited<ReturnType<typeof send>>,\n Partial<Awaited<ReturnType<typeof aensQuery>>> {}\n\n/**\n * Preclaim a name. Sends a hash of the name and a random salt to the node\n * @category AENS\n * @param name - AENS name\n * @param options - Options\n * @param options.onAccount - Make operation on specific account from sdk (you pass\n * publickKey) or using provided KeyPair(Can be keypair object or MemoryAccount)\n * @param options.fee - fee\n * @param options.ttl - ttl\n * @param options.nonce - nonce\n * @example\n * ```js\n * const name = 'test.chain'\n * const salt = preclaimResult.salt // salt from pre-claim transaction\n *\n * await sdkInstance.aensPreclaim(name, { ttl, fee, nonce })\n * {\n * ...transactionResult,\n * claim, // Claim function (options={}) => claimTransactionResult\n * salt,\n * commitmentId\n * }\n * ```\n */\nexport async function aensPreclaim(name: AensName, options: AensPreclaimOptions): Promise<Readonly<\nAwaited<ReturnType<typeof send>> & {\n height: number;\n salt: number;\n commitmentId: string;\n claim: (opts?: Parameters<typeof aensClaim>[2]) => ReturnType<typeof aensClaim>;\n}\n>> {\n const salt = genSalt();\n const height = await getHeight(options);\n const commitmentId = commitmentHash(name, salt);\n\n const preclaimTx = await _buildTx(Tag.NamePreclaimTx, {\n ...options,\n accountId: options.onAccount.address,\n commitmentId,\n });\n\n return Object.freeze({\n ...await send(preclaimTx, options),\n height,\n salt,\n commitmentId,\n async claim(opts?: Parameters<typeof aensClaim>[2]) {\n return aensClaim(name, salt, { ...options, ...opts });\n },\n });\n}\n\ninterface AensPreclaimOptions extends\n BuildTxOptions<Tag.NamePreclaimTx, 'accountId' | 'commitmentId'>,\n SendOptions,\n AensClaimOptions {}\n\n/**\n * Bid to name auction\n * @category AENS\n * @param name - Domain name\n * @param nameFee - Name fee (bid fee)\n * @param options - Options\n * @param options.onAccount - Make operation on specific account from sdk (you pass\n * publickKey) or using provided KeyPair(Can be keypair object or MemoryAccount)\n * @param options.fee - fee\n * @param options.ttl - ttl\n * @param options.nonce - nonce\n * @returns Transaction result\n * @example\n * ```js\n * const name = 'test.chain'\n * const bidFee = computeBidFee(name, startFee, incrementPercentage)\n *\n * await sdkInstance.aensBid(name, 213109412839123, { ttl, fee, nonce })\n * ```\n */\nexport async function aensBid(\n name: AensName,\n nameFee: number | string | BigNumber,\n options: Omit<Parameters<typeof aensClaim>[2], 'nameFee'>,\n): ReturnType<typeof aensClaim> {\n return aensClaim(name, 0, { ...options, nameFee });\n}\n"],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AANA,SASSA,OAAO;AAAA,SACPC,cAAc,EAAEC,aAAa;AAAA,SAEpCC,UAAU,EAAEC,QAAQ,EAAEC,GAAG;AAAA,SAElBC,aAAa;AAAA,SAEbC,IAAI;AAAA,SACJC,OAAO,EAAEC,SAAS;AAAA,SAClBC,QAAQ;AAUjB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,eAAeC,UAAU,CAC9BC,IAAc,EACdC,OAA0B,EACD;EACzB,MAAMC,YAAY,GAAG,MAAMJ,QAAQ,CAACL,GAAG,CAACU,YAAY,EAAE;IACpD,GAAGF,OAAO;IACVG,MAAM,EAAEJ,IAAI;IACZK,SAAS,EAAEJ,OAAO,CAACK,SAAS,CAACC;EAC/B,CAAC,CAAC;EACF,OAAOZ,IAAI,CAACO,YAAY,EAAED,OAAO,CAAC;AACpC;AAMA;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,OAAO,eAAeO,UAAU,CAC9BR,IAAc,EACdS,QAAqB,QAEI;EAAA,IADzB;IAAEC,c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CAAC;EACzC;EACA,OAAOD,MAAM;AACf;AASA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,eAAeI,YAAY,CAAC7C,IAAc,EAAEC,OAA4B,EAO5E;EACD,MAAMoC,IAAI,GAAGjD,OAAO,EAAE;EACtB,MAAM0D,MAAM,GAAG,MAAMjD,SAAS,CAACI,OAAO,CAAC;EACvC,MAAM8C,YAAY,GAAG1D,cAAc,CAACW,IAAI,EAAEqC,IAAI,CAAC;EAE/C,MAAMW,UAAU,GAAG,MAAMlD,QAAQ,CAACL,GAAG,CAACwD,cAAc,EAAE;IACpD,GAAGhD,OAAO;IACVI,SAAS,EAAEJ,OAAO,CAACK,SAAS,CAACC,OAAO;IACpCwC;EACF,CAAC,CAAC;EAEF,OAAOnC,MAAM,CAACkB,MAAM,CAAC;IACnB,IAAG,MAAMnC,IAAI,CAACqD,UAAU,EAAE/C,OAAO,CAAC;IAClC6C,MAAM;IACNT,IAAI;IACJU,YAAY;IACZ,MAAMG,KAAK,CAACC,IAAsC,EAAE;MAClD,OAAOf,SAAS,CAACpC,IAAI,EAAEqC,IAAI,EAAE;QAAE,GAAGpC,OAAO;QAAE,GAAGkD;MAAK,CAAC,CAAC;IACvD;EACF,CAAC,CAAC;AACJ;AAOA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,eAAeC,OAAO,CAC3BpD,IAAc,EACdqD,OAAoC,EACpCpD,OAAyD,EAC3B;EAC9B,OAAOmC,SAAS,CAACpC,IAAI,EAAE,CAAC,EAAE;IAAE,GAAGC,OAAO;IAAEoD;EAAQ,CAAC,CAAC;AACpD"}
|
|
1
|
+
{"version":3,"file":"aens.mjs","names":["genSalt","commitmentHash","isAuctionName","CLIENT_TTL","NAME_TTL","Tag","ArgumentError","send","getName","getHeight","_buildTx","aensRevoke","name","options","nameRevokeTx","NameRevokeTx","nameId","accountId","onAccount","address","aensUpdate","pointers","extendPointers","allPointers","Object","fromEntries","map","key","id","nameUpdateTx","NameUpdateTx","clientTtl","nameTtl","entries","aensTransfer","account","nameTransferTx","NameTransferTx","recipientId","aensQuery","opt","nameEntry","freeze","owner","update","transfer","revoke","extendTtl","aensClaim","salt","claimTx","NameClaimTx","nameSalt","result","nameInter","blockHeight","assign","aensPreclaim","height","commitmentId","preclaimTx","NamePreclaimTx","claim","opts","version","otherOptions","aensBid","nameFee"],"sources":["../src/aens.ts"],"sourcesContent":["/*\n * ISC License (ISC)\n * Copyright (c) 2022 aeternity developers\n *\n * Permission to use, copy, modify, and/or distribute this software for any\n * purpose with or without fee is hereby granted, provided that the above\n * copyright notice and this permission notice appear in all copies.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\n * REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\n * AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\n * INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\n * LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\n * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\n * PERFORMANCE OF THIS SOFTWARE.\n */\n\n/**\n * Aens methods - routines to interact with the æternity naming system\n *\n * The high-level description of the naming system is\n * https://github.com/aeternity/protocol/blob/master/AENS.md in the protocol\n * repository.\n */\n\nimport BigNumber from 'bignumber.js';\nimport { genSalt } from './utils/crypto';\nimport { commitmentHash, isAuctionName } from './tx/builder/helpers';\nimport {\n CLIENT_TTL, NAME_TTL, Tag, AensName,\n} from './tx/builder/constants';\nimport { ArgumentError } from './utils/errors';\nimport { Encoded } from './utils/encoder';\nimport { send, SendOptions } from './spend';\nimport { getName, getHeight } from './chain';\nimport { _buildTx, BuildTxOptions } from './tx';\nimport { TransformNodeType } from './Node';\nimport { NameEntry, NamePointer } from './apis/node';\nimport AccountBase from './account/Base';\nimport { AddressEncodings } from './tx/builder/field-types/address';\n\ninterface KeyPointers {\n [key: string]: Encoded.Generic<AddressEncodings>;\n}\n\n/**\n * Revoke a name\n * @category AENS\n * @param name - Name hash\n * @param options - Options\n * @param options.onAccount - Make operation on specific account from sdk (you pass\n * publickKey) or using provided KeyPair(Can be keypair object or MemoryAccount)\n * @param options.fee - fee\n * @param options.ttl - ttl\n * @param options.nonce - nonce\n * @returns Transaction result\n * @example\n * ```js\n * const name = 'test.chain'\n * const nameObject = await sdkInstance.aensQuery(name)\n *\n * await sdkInstance.aensRevoke(name, { fee, ttl , nonce })\n * // or\n * await nameObject.revoke({ fee, ttl, nonce })\n * ```\n */\nexport async function aensRevoke(\n name: AensName,\n options: AensRevokeOptions,\n): ReturnType<typeof send> {\n const nameRevokeTx = await _buildTx(Tag.NameRevokeTx, {\n ...options,\n nameId: name,\n accountId: options.onAccount.address,\n });\n return send(nameRevokeTx, options);\n}\n\ninterface AensRevokeOptions extends\n BuildTxOptions<Tag.NameRevokeTx, 'nameId' | 'accountId'>,\n SendOptions {}\n\n/**\n * Update a name\n * @category AENS\n * @param name - AENS name\n * @param pointers - Map of pointer keys to corresponding addresses\n * @param options - Options\n * @param options.extendPointers - Get the pointers from the node and merge with provided\n * ones. Pointers with the same type will be overwritten\n * @param options.onAccount - Make operation on specific account from sdk (you\n * pass publickKey) or using provided KeyPair(Can be keypair object or MemoryAccount)\n * @param options.fee - fee\n * @param options.ttl - ttl\n * @param options.nonce - nonce\n * @param options.nameTtl - Name ttl represented in number of\n * blocks (Max value is 50000 blocks)\n * @param options.clientTtl=84600 a suggestion as to how long any\n * clients should cache this information\n * @throws Invalid pointer array error\n * @example\n * ```js\n * const name = 'test.chain'\n * const pointersArray = ['ak_asd23dasdas...,' 'ct_asdf34fasdasd...']\n * const nameObject = await sdkInstance.aensQuery(name)\n *\n * await sdkInstance.aensUpdate(name, pointersArray, { nameTtl, ttl, fee, nonce, clientTtl })\n * // or\n * await nameObject.update(pointers, { nameTtl, ttl, fee, nonce, clientTtl })\n * ```\n */\nexport async function aensUpdate(\n name: AensName,\n pointers: KeyPointers,\n { extendPointers, ...options }: AensUpdateOptions,\n): ReturnType<typeof send> {\n const allPointers = {\n ...extendPointers === true && Object.fromEntries(\n (await getName(name, options)).pointers.map(({ key, id }) => [key, id]),\n ),\n ...pointers,\n };\n\n const nameUpdateTx = await _buildTx(Tag.NameUpdateTx, {\n clientTtl: CLIENT_TTL,\n nameTtl: NAME_TTL,\n ...options,\n nameId: name,\n accountId: options.onAccount.address,\n pointers: Object.entries(allPointers)\n .map(([key, id]: [string, Encoded.Generic<AddressEncodings>]) => ({ key, id })),\n });\n\n return send(nameUpdateTx, options);\n}\n\ninterface AensUpdateOptions extends\n BuildTxOptions<Tag.NameUpdateTx, 'nameId' | 'accountId' | 'pointers' | 'clientTtl' | 'nameTtl'>,\n SendOptions {\n extendPointers?: boolean;\n clientTtl?: number;\n nameTtl?: number;\n}\n\n/**\n * Transfer a domain to another account\n * @category AENS\n * @param name - AENS name\n * @param account - Recipient account publick key\n * @param options - Options\n * @param options.onAccount - Make operation on specific account from sdk (you pass\n * publickKey) or using provided KeyPair(Can be keypair object or MemoryAccount)\n * @param options.fee - fee\n * @param options.ttl - ttl\n * @param options.nonce - nonce\n * @returns Transaction result\n * @example\n * ```js\n * const name = 'test.chain'\n * const recipientPub = 'ak_asd23dasdas...'\n * const nameObject = await sdkInstance.aensQuery(name)\n *\n * await sdkInstance.aensTransfer(name, recipientPub, { ttl, fee, nonce })\n * // or\n * await nameObject.transfer(recipientPub, { ttl, fee, nonce })\n * ```\n */\nexport async function aensTransfer(\n name: AensName,\n account: Encoded.AccountAddress,\n options: AensTransferOptions,\n): ReturnType<typeof send> {\n const nameTransferTx = await _buildTx(Tag.NameTransferTx, {\n ...options,\n nameId: name,\n accountId: options.onAccount.address,\n recipientId: account,\n });\n\n return send(nameTransferTx, options);\n}\n\ninterface AensTransferOptions extends\n BuildTxOptions<Tag.NameTransferTx, 'nameId' | 'accountId' | 'recipientId'>,\n SendOptions {}\n\n/**\n * Query the AENS name info from the node\n * and return the object with info and predefined functions for manipulating name\n * @category AENS\n * @param name - AENS name\n * @param opt - Options\n * @returns\n * @example\n * ```js\n * const nameObject = sdkInstance.aensQuery('test.chain')\n * console.log(nameObject)\n * {\n * id, // name hash\n * pointers, // array of pointers\n * update, // Update name function\n * extendTtl, // Extend Ttl name function\n * transfer, // Transfer name function\n * revoke // Revoke name function\n * }\n * ```\n */\nexport async function aensQuery(\n name: AensName,\n opt: Parameters<typeof getName>[1] & Parameters<typeof aensUpdate>[2]\n & Parameters<typeof aensTransfer>[2],\n): Promise<Readonly<\n TransformNodeType<NameEntry> & {\n id: Encoded.Name;\n owner: Encoded.AccountAddress;\n pointers: KeyPointers | NamePointer[];\n ttl: number;\n update: (\n pointers: KeyPointers,\n options?: Omit<Parameters<typeof aensQuery>[1], 'onNode' | 'onCompiler' | 'onAccount'> & {\n onAccount?: AccountBase;\n }\n ) => ReturnType<typeof aensUpdate> & ReturnType<typeof aensQuery>;\n transfer: (\n account: Encoded.AccountAddress,\n options?: Parameters<typeof aensQuery>[1]\n ) => ReturnType<typeof aensUpdate> & ReturnType<typeof aensQuery>;\n revoke: (options?: Omit<Parameters<typeof aensRevoke>[1], 'onNode' | 'onCompiler' | 'onAccount'> & {\n onAccount?: AccountBase;\n }\n ) => ReturnType<typeof aensRevoke>;\n extendTtl: (\n nameTtl: number,\n options?: Omit<Parameters<typeof aensQuery>[1], 'onNode' | 'onCompiler' | 'onAccount'>\n ) => ReturnType<typeof aensUpdate> & ReturnType<typeof aensQuery>;\n }\n >> {\n const nameEntry = await getName(name, opt);\n return Object.freeze({\n ...nameEntry,\n id: nameEntry.id as Encoded.Name,\n owner: nameEntry.owner as Encoded.AccountAddress,\n async update(pointers, options) {\n return {\n ...await aensUpdate(name, pointers, { ...opt, ...options }),\n ...await aensQuery(name, { ...opt, ...options }),\n };\n },\n async transfer(account, options) {\n return {\n ...await aensTransfer(name, account, { ...opt, ...options }),\n ...await aensQuery(name, { ...opt, ...options }),\n };\n },\n async revoke(options) {\n return aensRevoke(name, { ...opt, ...options });\n },\n async extendTtl(nameTtl = NAME_TTL, options = {}) {\n if (nameTtl > NAME_TTL || nameTtl <= 0) {\n throw new ArgumentError('nameTtl', `a number between 1 and ${NAME_TTL} blocks`, nameTtl);\n }\n\n return {\n ...await aensUpdate(name, {}, {\n ...opt, ...options, nameTtl, extendPointers: true,\n }),\n ...await aensQuery(name, { ...opt, ...options }),\n };\n },\n });\n}\n\n/**\n * Claim a previously preclaimed registration. This can only be done after the\n * preclaim step\n * @category AENS\n * @param name - AENS name\n * @param salt - Salt from pre-claim, or 0 if it's a bid\n * @param options - options\n * @param options.onAccount - Make operation on specific account from sdk (you pass\n * publickKey) or using provided KeyPair(Can be keypair object or MemoryAccount)\n * @param options.fee - fee\n * @param options.ttl - ttl\n * @param options.nonce - nonce\n * @param options.nameFee - Name Fee (By default calculated by sdk)\n * @returns the result of the claim\n * @example\n * ```js\n * const name = 'test.chain'\n * const salt = preclaimResult.salt // salt from pre-claim transaction\n *\n * await sdkInstance.aensClaim(name, salt, { ttl, fee, nonce, nameFee })\n * ```\n */\nexport async function aensClaim(\n name: AensName,\n salt: number,\n options: AensClaimOptions,\n): Promise<AensClaimReturnType> {\n const claimTx = await _buildTx(Tag.NameClaimTx, {\n ...options,\n accountId: options.onAccount.address,\n nameSalt: salt,\n name,\n });\n\n const result = await send(claimTx, options);\n if (!isAuctionName(name)) {\n const nameInter = result.blockHeight != null && result.blockHeight > 0\n ? await aensQuery(name, options)\n : {};\n return Object.assign(result, nameInter);\n }\n return result;\n}\n\ntype AensClaimOptionsType = BuildTxOptions<Tag.NameClaimTx, 'accountId' | 'nameSalt' | 'name'>\n& SendOptions & Parameters<typeof aensQuery>[1];\ninterface AensClaimOptions extends AensClaimOptionsType {}\ninterface AensClaimReturnType extends\n Awaited<ReturnType<typeof send>>,\n Partial<Awaited<ReturnType<typeof aensQuery>>> {}\n\n/**\n * Preclaim a name. Sends a hash of the name and a random salt to the node\n * @category AENS\n * @param name - AENS name\n * @param options - Options\n * @param options.onAccount - Make operation on specific account from sdk (you pass\n * publickKey) or using provided KeyPair(Can be keypair object or MemoryAccount)\n * @param options.fee - fee\n * @param options.ttl - ttl\n * @param options.nonce - nonce\n * @example\n * ```js\n * const name = 'test.chain'\n * const salt = preclaimResult.salt // salt from pre-claim transaction\n *\n * await sdkInstance.aensPreclaim(name, { ttl, fee, nonce })\n * {\n * ...transactionResult,\n * claim, // Claim function (options={}) => claimTransactionResult\n * salt,\n * commitmentId\n * }\n * ```\n */\nexport async function aensPreclaim(name: AensName, options: AensPreclaimOptions): Promise<Readonly<\nAwaited<ReturnType<typeof send>> & {\n height: number;\n salt: number;\n commitmentId: string;\n claim: (opts?: Parameters<typeof aensClaim>[2]) => ReturnType<typeof aensClaim>;\n}\n>> {\n const salt = genSalt();\n const height = await getHeight(options);\n const commitmentId = commitmentHash(name, salt);\n\n const preclaimTx = await _buildTx(Tag.NamePreclaimTx, {\n ...options,\n accountId: options.onAccount.address,\n commitmentId,\n });\n\n return Object.freeze({\n ...await send(preclaimTx, options),\n height,\n salt,\n commitmentId,\n async claim(opts?: Parameters<typeof aensClaim>[2]) {\n const { version, ...otherOptions } = options;\n return aensClaim(name, salt, { ...otherOptions, ...opts });\n },\n });\n}\n\ninterface AensPreclaimOptions extends\n BuildTxOptions<Tag.NamePreclaimTx, 'accountId' | 'commitmentId'>,\n SendOptions,\n Omit<AensClaimOptions, 'version'> {}\n\n/**\n * Bid to name auction\n * @category AENS\n * @param name - Domain name\n * @param nameFee - Name fee (bid fee)\n * @param options - Options\n * @param options.onAccount - Make operation on specific account from sdk (you pass\n * publickKey) or using provided KeyPair(Can be keypair object or MemoryAccount)\n * @param options.fee - fee\n * @param options.ttl - ttl\n * @param options.nonce - nonce\n * @returns Transaction result\n * @example\n * ```js\n * const name = 'test.chain'\n * const bidFee = computeBidFee(name, startFee, incrementPercentage)\n *\n * await sdkInstance.aensBid(name, 213109412839123, { ttl, fee, nonce })\n * ```\n */\nexport async function aensBid(\n name: AensName,\n nameFee: number | string | BigNumber,\n options: Omit<Parameters<typeof aensClaim>[2], 'nameFee'>,\n): ReturnType<typeof aensClaim> {\n return aensClaim(name, 0, { ...options, nameFee });\n}\n"],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AANA,SASSA,OAAO;AAAA,SACPC,cAAc,EAAEC,aAAa;AAAA,SAEpCC,UAAU,EAAEC,QAAQ,EAAEC,GAAG;AAAA,SAElBC,aAAa;AAAA,SAEbC,IAAI;AAAA,SACJC,OAAO,EAAEC,SAAS;AAAA,SAClBC,QAAQ;AAUjB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,eAAeC,UAAU,CAC9BC,IAAc,EACdC,OAA0B,EACD;EACzB,MAAMC,YAAY,GAAG,MAAMJ,QAAQ,CAACL,GAAG,CAACU,YAAY,EAAE;IACpD,GAAGF,OAAO;IACVG,MAAM,EAAEJ,IAAI;IACZK,SAAS,EAAEJ,OAAO,CAACK,SAAS,CAACC;EAC/B,CAAC,CAAC;EACF,OAAOZ,IAAI,CAACO,YAAY,EAAED,OAAO,CAAC;AACpC;AAMA;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,OAAO,eAAeO,UAAU,CAC9BR,IAAc,EACdS,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AACpD"}
|
|
@@ -1,3 +1,7 @@
|
|
|
1
|
+
import _classPrivateFieldSet from "@babel/runtime-corejs3/helpers/classPrivateFieldSet";
|
|
2
|
+
import _classPrivateFieldGet from "@babel/runtime-corejs3/helpers/classPrivateFieldGet";
|
|
3
|
+
function _classPrivateFieldInitSpec(obj, privateMap, value) { _checkPrivateRedeclaration(obj, privateMap); privateMap.set(obj, value); }
|
|
4
|
+
function _checkPrivateRedeclaration(obj, privateCollection) { if (privateCollection.has(obj)) { throw new TypeError("Cannot initialize the same private elements twice on an object"); } }
|
|
1
5
|
/*
|
|
2
6
|
* ISC License (ISC)
|
|
3
7
|
* Copyright (c) 2022 aeternity developers
|
|
@@ -15,11 +19,13 @@
|
|
|
15
19
|
* PERFORMANCE OF THIS SOFTWARE.
|
|
16
20
|
*/
|
|
17
21
|
import BrowserConnection from "./Browser.mjs";
|
|
22
|
+
import { UnexpectedTsError } from "../../utils/errors.mjs";
|
|
18
23
|
/**
|
|
19
24
|
* BrowserRuntimeConnection
|
|
20
25
|
* Handle browser runtime communication
|
|
21
26
|
* @category aepp wallet communication
|
|
22
27
|
*/
|
|
28
|
+
var _listeners = /*#__PURE__*/new WeakMap();
|
|
23
29
|
export default class BrowserRuntimeConnection extends BrowserConnection {
|
|
24
30
|
constructor(_ref) {
|
|
25
31
|
let {
|
|
@@ -27,28 +33,37 @@ export default class BrowserRuntimeConnection extends BrowserConnection {
|
|
|
27
33
|
...options
|
|
28
34
|
} = _ref;
|
|
29
35
|
super(options);
|
|
36
|
+
_classPrivateFieldInitSpec(this, _listeners, {
|
|
37
|
+
writable: true,
|
|
38
|
+
value: void 0
|
|
39
|
+
});
|
|
30
40
|
this.port = port;
|
|
31
41
|
}
|
|
32
42
|
disconnect() {
|
|
33
43
|
super.disconnect();
|
|
34
44
|
this.port.disconnect();
|
|
45
|
+
if (_classPrivateFieldGet(this, _listeners) == null) throw new UnexpectedTsError();
|
|
46
|
+
this.port.onMessage.removeListener(_classPrivateFieldGet(this, _listeners)[0]);
|
|
47
|
+
this.port.onDisconnect.removeListener(_classPrivateFieldGet(this, _listeners)[1]);
|
|
48
|
+
_classPrivateFieldSet(this, _listeners, undefined);
|
|
35
49
|
}
|
|
36
50
|
connect(onMessage, onDisconnect) {
|
|
37
51
|
super.connect(onMessage, onDisconnect);
|
|
38
|
-
this
|
|
52
|
+
_classPrivateFieldSet(this, _listeners, [(message, port) => {
|
|
39
53
|
var _port$sender$url, _port$sender;
|
|
40
54
|
this.receiveMessage(message);
|
|
41
55
|
// TODO: make `origin` optional because sender url is not available on aepp side
|
|
42
56
|
onMessage(message, (_port$sender$url = (_port$sender = port.sender) === null || _port$sender === void 0 ? void 0 : _port$sender.url) !== null && _port$sender$url !== void 0 ? _port$sender$url : '', port);
|
|
43
|
-
});
|
|
44
|
-
this.port.
|
|
57
|
+
}, onDisconnect]);
|
|
58
|
+
this.port.onMessage.addListener(_classPrivateFieldGet(this, _listeners)[0]);
|
|
59
|
+
this.port.onDisconnect.addListener(_classPrivateFieldGet(this, _listeners)[1]);
|
|
45
60
|
}
|
|
46
61
|
sendMessage(message) {
|
|
47
62
|
super.sendMessage(message);
|
|
48
63
|
this.port.postMessage(message);
|
|
49
64
|
}
|
|
50
65
|
isConnected() {
|
|
51
|
-
return this
|
|
66
|
+
return _classPrivateFieldGet(this, _listeners) != null;
|
|
52
67
|
}
|
|
53
68
|
}
|
|
54
69
|
//# sourceMappingURL=BrowserRuntime.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"BrowserRuntime.mjs","names":["BrowserConnection","BrowserRuntimeConnection","constructor","port","options","disconnect","
|
|
1
|
+
{"version":3,"file":"BrowserRuntime.mjs","names":["BrowserConnection","UnexpectedTsError","BrowserRuntimeConnection","constructor","port","options","disconnect","onMessage","removeListener","onDisconnect","undefined","connect","message","receiveMessage","sender","url","addListener","sendMessage","postMessage","isConnected"],"sources":["../../../src/aepp-wallet-communication/connection/BrowserRuntime.ts"],"sourcesContent":["/*\n * ISC License (ISC)\n * Copyright (c) 2022 aeternity developers\n *\n * Permission to use, copy, modify, and/or distribute this software for any\n * purpose with or without fee is hereby granted, provided that the above\n * copyright notice and this permission notice appear in all copies.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\n * REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\n * AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\n * INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\n * LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\n * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\n * PERFORMANCE OF THIS SOFTWARE.\n */\n\nimport { Runtime } from 'webextension-polyfill';\nimport BrowserConnection from './Browser';\nimport { UnexpectedTsError } from '../../utils/errors';\n\n/**\n * BrowserRuntimeConnection\n * Handle browser runtime communication\n * @category aepp wallet communication\n */\nexport default class BrowserRuntimeConnection extends BrowserConnection {\n port: Runtime.Port;\n\n #listeners?: [(message: any, port: Runtime.Port) => void, () => void];\n\n constructor({ port, ...options }: { port: Runtime.Port; debug: boolean }) {\n super(options);\n this.port = port;\n }\n\n override disconnect(): void {\n super.disconnect();\n this.port.disconnect();\n if (this.#listeners == null) throw new UnexpectedTsError();\n this.port.onMessage.removeListener(this.#listeners[0]);\n this.port.onDisconnect.removeListener(this.#listeners[1]);\n this.#listeners = undefined;\n }\n\n override connect(\n onMessage: (message: any, origin: string, source: Runtime.Port) => void,\n onDisconnect: () => void,\n ): void {\n super.connect(onMessage, onDisconnect);\n this.#listeners = [\n (message, port) => {\n this.receiveMessage(message);\n // TODO: make `origin` optional because sender url is not available on aepp side\n onMessage(message, port.sender?.url ?? '', port);\n },\n onDisconnect,\n ];\n this.port.onMessage.addListener(this.#listeners[0]);\n this.port.onDisconnect.addListener(this.#listeners[1]);\n }\n\n override sendMessage(message: any): void {\n super.sendMessage(message);\n this.port.postMessage(message);\n }\n\n isConnected(): boolean {\n return this.#listeners != null;\n }\n}\n"],"mappings":";;;;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAfA,OAkBOA,iBAAiB;AAAA,SACfC,iBAAiB;AAE1B;AACA;AACA;AACA;AACA;AAJA;AAKA,eAAe,MAAMC,wBAAwB,SAASF,iBAAiB,CAAC;EAKtEG,WAAW,OAA+D;IAAA,IAA9D;MAAEC,IAAI;MAAE,GAAGC;IAAgD,CAAC;IACtE,KAAK,CAACA,OAAO,CAAC;IAAC;MAAA;MAAA;IAAA;IACf,IAAI,CAACD,IAAI,GAAGA,IAAI;EAClB;EAESE,UAAU,GAAS;IAC1B,KAAK,CAACA,UAAU,EAAE;IAClB,IAAI,CAACF,IAAI,CAACE,UAAU,EAAE;IACtB,IAAI,0BAAI,iBAAe,IAAI,EAAE,MAAM,IAAIL,iBAAiB,EAAE;IAC1D,IAAI,CAACG,IAAI,CAACG,SAAS,CAACC,cAAc,CAAC,0BAAI,cAAY,CAAC,CAAC,CAAC;IACtD,IAAI,CAACJ,IAAI,CAACK,YAAY,CAACD,cAAc,CAAC,0BAAI,cAAY,CAAC,CAAC,CAAC;IACzD,0BAAI,cAAcE,SAAS;EAC7B;EAESC,OAAO,CACdJ,SAAuE,EACvEE,YAAwB,EAClB;IACN,KAAK,CAACE,OAAO,CAACJ,SAAS,EAAEE,YAAY,CAAC;IACtC,0BAAI,cAAc,CAChB,CAACG,OAAO,EAAER,IAAI,KAAK;MAAA;MACjB,IAAI,CAACS,cAAc,CAACD,OAAO,CAAC;MAC5B;MACAL,SAAS,CAACK,OAAO,sCAAER,IAAI,CAACU,MAAM,iDAAX,aAAaC,GAAG,+DAAI,EAAE,EAAEX,IAAI,CAAC;IAClD,CAAC,EACDK,YAAY,CACb;IACD,IAAI,CAACL,IAAI,CAACG,SAAS,CAACS,WAAW,CAAC,0BAAI,cAAY,CAAC,CAAC,CAAC;IACnD,IAAI,CAACZ,IAAI,CAACK,YAAY,CAACO,WAAW,CAAC,0BAAI,cAAY,CAAC,CAAC,CAAC;EACxD;EAESC,WAAW,CAACL,OAAY,EAAQ;IACvC,KAAK,CAACK,WAAW,CAACL,OAAO,CAAC;IAC1B,IAAI,CAACR,IAAI,CAACc,WAAW,CAACN,OAAO,CAAC;EAChC;EAEAO,WAAW,GAAY;IACrB,OAAO,0BAAI,iBAAe,IAAI;EAChC;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"RpcClient.mjs","names":["RpcError","RpcInternalError","RpcMethodNotFoundError","InvalidRpcMessageError","MissingCallbackError","RpcClient","constructor","connection","onDisconnect","methods","Map","connect","bind","request","name","params","Promise","resolve","reject","set","notify","undefined","msg","origin","jsonrpc","JSON","stringify","result","error","method","methodName","e","id","sendMessage","callbacks","get","deserialize","delete"],"sources":["../../../src/aepp-wallet-communication/rpc/RpcClient.ts"],"sourcesContent":["import { RpcError, RpcInternalError, RpcMethodNotFoundError } from '../schema';\nimport BrowserConnection from '../connection/Browser';\nimport { InvalidRpcMessageError, MissingCallbackError } from '../../utils/errors';\n\ninterface JsonRpcRequest {\n jsonrpc: '2.0';\n id: number;\n method: string;\n params?: any;\n}\n\ninterface JsonRpcResponse {\n jsonrpc: '2.0';\n id: number;\n method: string;\n result?: any;\n error?: {\n code: number;\n message: string;\n data?: any;\n };\n}\n\ntype RpcApiHandler = (p?: any) => any | undefined;\ntype RpcApi<Api> = { [k in keyof Api]: RpcApiHandler };\ntype WithOrigin<Api extends RpcApi<Api>> = {\n [k in keyof Api]: (p: Parameters<Api[k]>[0], origin: string) => ReturnType<Api[k]>\n};\n\n/**\n * Contain functionality for using RPC conection\n * @category aepp wallet communication\n * @param connection - Connection object\n * @param onDisconnect - Disconnect callback\n * @param methods - Object containing handlers for each request by name\n */\nexport default class RpcClient <\n RemoteApi extends RpcApi<RemoteApi>, LocalApi extends RpcApi<LocalApi>,\n> {\n connection: BrowserConnection;\n\n #callbacks = new Map<number, { resolve: (v: any) => void; reject: (e: Error) => void }>();\n\n #messageId = 0;\n\n #methods: WithOrigin<LocalApi>;\n\n constructor(\n connection: BrowserConnection,\n onDisconnect: () => void,\n methods: WithOrigin<LocalApi>,\n ) {\n this.connection = connection;\n this.#methods = methods;\n connection.connect(this.#handleMessage.bind(this), onDisconnect);\n }\n\n async #handleMessage(msg: JsonRpcRequest | JsonRpcResponse, origin: string): Promise<void> {\n if (msg?.jsonrpc !== '2.0') throw new InvalidRpcMessageError(JSON.stringify(msg));\n if ('result' in msg || 'error' in msg) {\n this.#processResponse(msg);\n return;\n }\n\n const request = msg as JsonRpcRequest;\n let result;\n let error;\n try {\n if (!(request.method in this.#methods)) throw new RpcMethodNotFoundError();\n const methodName = request.method as keyof LocalApi;\n result = await this.#methods[methodName](request.params, origin);\n } catch (e) {\n error = e instanceof RpcError ? e : new RpcInternalError();\n }\n if (request.id != null) {\n this.#sendResponse(request.id, request.method as keyof LocalApi, result, error);\n }\n }\n\n #sendRequest(\n id: number | undefined,\n method: keyof RemoteApi | keyof LocalApi,\n params?: any,\n ): void {\n this.connection.sendMessage({\n jsonrpc: '2.0',\n ...id != null ? { id } : {},\n method,\n ...params != null ? { params } : {},\n });\n }\n\n #sendResponse(\n id: number,\n method: keyof RemoteApi | keyof LocalApi, // TODO: remove as far it is not required in JSON RPC\n result?: any,\n error?:
|
|
1
|
+
{"version":3,"file":"RpcClient.mjs","names":["RpcError","RpcInternalError","RpcMethodNotFoundError","InvalidRpcMessageError","MissingCallbackError","RpcClient","constructor","connection","onDisconnect","methods","Map","connect","bind","request","name","params","Promise","resolve","reject","set","notify","undefined","msg","origin","jsonrpc","JSON","stringify","result","error","method","methodName","e","id","sendMessage","toJSON","callbacks","get","deserialize","delete"],"sources":["../../../src/aepp-wallet-communication/rpc/RpcClient.ts"],"sourcesContent":["import { RpcError, RpcInternalError, RpcMethodNotFoundError } from '../schema';\nimport BrowserConnection from '../connection/Browser';\nimport { InvalidRpcMessageError, MissingCallbackError } from '../../utils/errors';\n\ninterface JsonRpcRequest {\n jsonrpc: '2.0';\n id: number;\n method: string;\n params?: any;\n}\n\ninterface JsonRpcResponse {\n jsonrpc: '2.0';\n id: number;\n method: string;\n result?: any;\n error?: {\n code: number;\n message: string;\n data?: any;\n };\n}\n\ntype RpcApiHandler = (p?: any) => any | undefined;\ntype RpcApi<Api> = { [k in keyof Api]: RpcApiHandler };\ntype WithOrigin<Api extends RpcApi<Api>> = {\n [k in keyof Api]: (p: Parameters<Api[k]>[0], origin: string) => ReturnType<Api[k]>\n};\n\n/**\n * Contain functionality for using RPC conection\n * @category aepp wallet communication\n * @param connection - Connection object\n * @param onDisconnect - Disconnect callback\n * @param methods - Object containing handlers for each request by name\n */\nexport default class RpcClient <\n RemoteApi extends RpcApi<RemoteApi>, LocalApi extends RpcApi<LocalApi>,\n> {\n connection: BrowserConnection;\n\n #callbacks = new Map<number, { resolve: (v: any) => void; reject: (e: Error) => void }>();\n\n #messageId = 0;\n\n #methods: WithOrigin<LocalApi>;\n\n constructor(\n connection: BrowserConnection,\n onDisconnect: () => void,\n methods: WithOrigin<LocalApi>,\n ) {\n this.connection = connection;\n this.#methods = methods;\n connection.connect(this.#handleMessage.bind(this), onDisconnect);\n }\n\n async #handleMessage(msg: JsonRpcRequest | JsonRpcResponse, origin: string): Promise<void> {\n if (msg?.jsonrpc !== '2.0') throw new InvalidRpcMessageError(JSON.stringify(msg));\n if ('result' in msg || 'error' in msg) {\n this.#processResponse(msg);\n return;\n }\n\n const request = msg as JsonRpcRequest;\n let result;\n let error;\n try {\n if (!(request.method in this.#methods)) throw new RpcMethodNotFoundError();\n const methodName = request.method as keyof LocalApi;\n result = await this.#methods[methodName](request.params, origin);\n } catch (e) {\n error = e instanceof RpcError ? e : new RpcInternalError();\n }\n if (request.id != null) {\n this.#sendResponse(request.id, request.method as keyof LocalApi, result, error);\n }\n }\n\n #sendRequest(\n id: number | undefined,\n method: keyof RemoteApi | keyof LocalApi,\n params?: any,\n ): void {\n this.connection.sendMessage({\n jsonrpc: '2.0',\n ...id != null ? { id } : {},\n method,\n ...params != null ? { params } : {},\n });\n }\n\n #sendResponse(\n id: number,\n method: keyof RemoteApi | keyof LocalApi, // TODO: remove as far it is not required in JSON RPC\n result?: any,\n error?: RpcError,\n ): void {\n this.connection.sendMessage({\n jsonrpc: '2.0',\n id,\n method,\n ...error != null ? { error: error.toJSON() } : { result },\n });\n }\n\n /**\n * Make a request\n * @param name - Method name\n * @param params - Method params\n * @returns Promise which will be resolved after receiving response message\n */\n async request<Name extends keyof RemoteApi>(\n name: Name,\n params: Parameters<RemoteApi[Name]>[0],\n ): Promise<ReturnType<RemoteApi[Name]>> {\n this.#sendRequest(this.#messageId += 1, name, params);\n return new Promise((resolve, reject) => {\n this.#callbacks.set(this.#messageId, { resolve, reject });\n });\n }\n\n /**\n * Make a notification\n * @param name - Method name\n * @param params - Method params\n */\n notify<Name extends keyof RemoteApi>(name: Name, params: Parameters<RemoteApi[Name]>[0]): void {\n this.#sendRequest(undefined, name, params);\n }\n\n /**\n * Process response message\n * @param msg - Message object\n */\n #processResponse({ id, error, result }: { id: number; error?: any; result?: any }): void {\n const callbacks = this.#callbacks.get(id);\n if (callbacks == null) throw new MissingCallbackError(id);\n if (error != null) callbacks.reject(RpcError.deserialize(error));\n else callbacks.resolve(result);\n this.#callbacks.delete(id);\n }\n}\n"],"mappings":";;;;;;SAASA,QAAQ,EAAEC,gBAAgB,EAAEC,sBAAsB;AAAA,SAElDC,sBAAsB,EAAEC,oBAAoB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AA2BrD;AACA;AACA;AACA;AACA;AACA;AACA;AACA,eAAe,MAAMC,SAAS,CAE5B;EASAC,WAAW,CACTC,UAA6B,EAC7BC,YAAwB,EACxBC,OAA6B,EAC7B;IAAA;IAAA;I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BAAI,cAAYC,GAAG,CAACJ,EAAE,CAAC;EACzC,IAAIG,SAAS,IAAI,IAAI,EAAE,MAAM,IAAI/B,oBAAoB,CAAC4B,EAAE,CAAC;EACzD,IAAIJ,KAAK,IAAI,IAAI,EAAEO,SAAS,CAACjB,MAAM,CAAClB,QAAQ,CAACqC,WAAW,CAACT,KAAK,CAAC,CAAC,CAAC,KAC5DO,SAAS,CAAClB,OAAO,CAACU,MAAM,CAAC;EAC9B,0BAAI,cAAYW,MAAM,CAACN,EAAE,CAAC;AAC5B"}
|
package/es/chain.d.ts
CHANGED
|
@@ -179,6 +179,14 @@ export declare function getKeyBlock(hashOrHeight: Encoded.KeyBlockHash | number,
|
|
|
179
179
|
export declare function getMicroBlockHeader(hash: Encoded.MicroBlockHash, { onNode }: {
|
|
180
180
|
onNode: Node;
|
|
181
181
|
}): Promise<TransformNodeType<MicroBlockHeader>>;
|
|
182
|
+
interface TxDryRunArguments {
|
|
183
|
+
tx: Encoded.Transaction;
|
|
184
|
+
accountAddress: Encoded.AccountAddress;
|
|
185
|
+
top?: number | Encoded.KeyBlockHash | Encoded.MicroBlockHash;
|
|
186
|
+
txEvents?: any;
|
|
187
|
+
resolve: Function;
|
|
188
|
+
reject: Function;
|
|
189
|
+
}
|
|
182
190
|
/**
|
|
183
191
|
* Transaction dry-run
|
|
184
192
|
* @category chain
|
|
@@ -191,7 +199,7 @@ export declare function getMicroBlockHeader(hash: Encoded.MicroBlockHash, { onNo
|
|
|
191
199
|
* @param options.onNode - Node to use
|
|
192
200
|
*/
|
|
193
201
|
export declare function txDryRun(tx: Encoded.Transaction, accountAddress: Encoded.AccountAddress, { top, txEvents, combine, onNode, }: {
|
|
194
|
-
top?:
|
|
202
|
+
top?: TxDryRunArguments['top'];
|
|
195
203
|
txEvents?: boolean;
|
|
196
204
|
combine?: boolean;
|
|
197
205
|
onNode: Node;
|
package/es/chain.mjs
CHANGED
|
@@ -368,8 +368,11 @@ async function txDryRunHandler(key, onNode) {
|
|
|
368
368
|
if (rs == null) throw new InternalError('Can\'t get dry-run request');
|
|
369
369
|
let dryRunRes;
|
|
370
370
|
try {
|
|
371
|
+
const top = typeof rs[0].top === 'number' ? (await getKeyBlock(rs[0].top, {
|
|
372
|
+
onNode
|
|
373
|
+
})).hash : rs[0].top;
|
|
371
374
|
dryRunRes = await onNode.protectedDryRunTxs({
|
|
372
|
-
top
|
|
375
|
+
top,
|
|
373
376
|
txEvents: rs[0].txEvents,
|
|
374
377
|
txs: rs.map(req => ({
|
|
375
378
|
tx: req.tx
|
package/es/chain.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"chain.mjs","names":["AE_AMOUNT_FORMATS","formatAmount","verifyTransaction","isAccountNotFoundError","pause","isNameValid","produceNameId","DRY_RUN_ACCOUNT","AensPointerContextError","DryRunError","InvalidAensNameError","TransactionError","TxTimedOutError","TxNotInChainError","InternalError","decode","_getPollInterval","type","_expectedMineRate","_microBlockCycle","_maxPollInterval","base","block","microblock","Math","min","InvalidTxError","constructor","message","validation","transaction","name","getHeight","onNode","getCurrentKeyBlockHeight","height","poll","th","blocks","interval","options","max","tx","getTransactionByHash","blockHeight","awaitHeight","currentHeight","waitForTxConfirm","txHash","confirm","newBlockHeight","sendTransaction","onAccount","verify","waitMined","length","map","v","join","__queue","address","error","postTransaction","requestOptions","customHeaders","pollResult","txData","hash","rawTx","c","undefined","confirmationHeight","Object","assign","verifyTx","getAccount","getAccountByPubkeyAndHeight","getAccountByPubkeyAndHash","getAccountByPubkey","getBalance","format","AETTOS","balance","catch","targetDenomination","getCurrentGeneration","getGeneration","hashOrHeight","getGenerationByHeight","getGenerationByHash","getMicroBlockTransactions","getMicroBlockTransactionsByHash","transactions","getKeyBlock","getKeyBlockByHeight","getKeyBlockByHash","getMicroBlockHeader","getMicroBlockHeaderByHash","txDryRunRequests","Map","txDryRunHandler","key","rs","get","delete","dryRunRes","protectedDryRunTxs","top","txEvents","txs","req","accounts","Array","from","Set","accountAddress","pubKey","amount","forEach","reject","results","idx","result","reason","resultPayload","resolve","txDryRun","combine","requests","set","Promise","push","timeout","setTimeout","getContractByteCode","contractId","getContractCode","getContract","getName","getNameEntryByName","resolveName","nameOrId","resolveByNode","pointer","pointers","find","p","id"],"sources":["../src/chain.ts"],"sourcesContent":["/*\n * ISC License (ISC)\n * Copyright (c) 2022 aeternity developers\n *\n * Permission to use, copy, modify, and/or distribute this software for any\n * purpose with or without fee is hereby granted, provided that the above\n * copyright notice and this permission notice appear in all copies.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\n * REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\n * AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\n * INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\n * LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\n * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\n * PERFORMANCE OF THIS SOFTWARE.\n */\nimport { AE_AMOUNT_FORMATS, formatAmount } from './utils/amount-formatter';\nimport verifyTransaction, { ValidatorResult } from './tx/validator';\nimport { isAccountNotFoundError, pause } from './utils/other';\nimport { isNameValid, produceNameId } from './tx/builder/helpers';\nimport { DRY_RUN_ACCOUNT } from './tx/builder/schema';\nimport { AensName } from './tx/builder/constants';\nimport {\n AensPointerContextError, DryRunError, InvalidAensNameError, TransactionError,\n TxTimedOutError, TxNotInChainError, InternalError,\n} from './utils/errors';\nimport Node, { TransformNodeType } from './Node';\nimport {\n Account as AccountNode, ByteCode, ContractObject, DryRunResult, DryRunResults,\n Generation, KeyBlock, MicroBlockHeader, NameEntry, SignedTx,\n} from './apis/node';\nimport { decode, Encoded, Encoding } from './utils/encoder';\nimport AccountBase from './account/Base';\n\n/**\n * @category chain\n */\nexport function _getPollInterval(\n type: 'block' | 'microblock',\n { _expectedMineRate = 180000, _microBlockCycle = 3000, _maxPollInterval = 5000 }:\n { _expectedMineRate?: number; _microBlockCycle?: number; _maxPollInterval?: number },\n): number {\n const base = {\n block: _expectedMineRate,\n microblock: _microBlockCycle,\n }[type];\n return Math.min(base / 3, _maxPollInterval);\n}\n\n/**\n * @category exception\n */\nexport class InvalidTxError extends TransactionError {\n validation: ValidatorResult[];\n\n transaction: Encoded.Transaction;\n\n constructor(\n message: string,\n validation: ValidatorResult[],\n transaction: Encoded.Transaction,\n ) {\n super(message);\n this.name = 'InvalidTxError';\n this.validation = validation;\n this.transaction = transaction;\n }\n}\n\n/**\n * Obtain current height of the chain\n * @category chain\n * @returns Current chain height\n */\nexport async function getHeight({ onNode }: { onNode: Node }): Promise<number> {\n return (await onNode.getCurrentKeyBlockHeight()).height;\n}\n\n/**\n * Wait for a transaction to be 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\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 = 10, interval, onNode, ...options\n }:\n { blocks?: number; interval?: number; onNode: Node } & Parameters<typeof _getPollInterval>[1],\n): Promise<TransformNodeType<SignedTx>> {\n interval ??= _getPollInterval('microblock', options);\n const max = await getHeight({ onNode }) + blocks;\n do {\n const tx = await onNode.getTransactionByHash(th);\n if (tx.blockHeight !== -1) return tx;\n await pause(interval);\n } while (await getHeight({ onNode }) < 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 { interval, onNode, ...options }:\n { interval?: number; onNode: Node } & Parameters<typeof _getPollInterval>[1],\n): Promise<number> {\n interval ??= _getPollInterval('block', options);\n let currentHeight;\n do {\n if (currentHeight != null) await pause(interval);\n currentHeight = (await onNode.getCurrentKeyBlockHeight()).height;\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 { confirm = 3, onNode, ...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 * Submit a signed transaction for mining\n * @category chain\n * @param tx - Transaction to submit\n * @param options - Options\n * @param options.onNode - Node to use\n * @param options.onAccount - Account to use\n * @param options.verify - Verify transaction before sending\n * @param options.waitMined - Ensure that transaction get into block\n * @param options.confirm - Number of micro blocks that should be mined after tx get included\n * @returns Transaction details\n */\nexport async function sendTransaction(\n tx: Encoded.Transaction,\n {\n onNode, onAccount, verify = true, waitMined = true, confirm, ...options\n }:\n SendTransactionOptions,\n): Promise<SendTransactionReturnType> {\n if (verify) {\n const validation = await verifyTransaction(tx, onNode);\n if (validation.length > 0) {\n const message = `Transaction verification errors: ${\n validation.map((v: { message: string }) => v.message).join(', ')}`;\n throw new InvalidTxError(message, validation, tx);\n }\n }\n\n try {\n let __queue;\n try {\n __queue = onAccount != null ? `tx-${onAccount.address}` : null;\n } catch (error) {\n __queue = null;\n }\n const { txHash } = await onNode.postTransaction(\n { tx },\n __queue != null ? { requestOptions: { customHeaders: { __queue } } } : {},\n );\n\n if (waitMined) {\n const pollResult = await poll(txHash, { onNode, ...options });\n const txData = {\n ...pollResult,\n hash: pollResult.hash as Encoded.TxHash,\n rawTx: tx,\n };\n // wait for transaction confirmation\n if (confirm != null && (confirm === true || confirm > 0)) {\n const c = typeof confirm === 'boolean' ? undefined : confirm;\n return {\n ...txData,\n confirmationHeight: await waitForTxConfirm(txHash, { onNode, confirm: c, ...options }),\n };\n }\n return txData;\n }\n return { hash: txHash, rawTx: tx };\n } catch (error) {\n throw Object.assign(error, {\n rawTx: tx,\n verifyTx: async () => verifyTransaction(tx, onNode),\n });\n }\n}\n\ntype SendTransactionOptionsType = {\n onNode: Node;\n onAccount?: AccountBase;\n verify?: boolean;\n waitMined?: boolean;\n confirm?: boolean | number;\n} & Parameters<typeof poll>[1] & Omit<Parameters<typeof waitForTxConfirm>[1], 'confirm'>;\ninterface SendTransactionOptions extends SendTransactionOptionsType {}\ninterface SendTransactionReturnType extends Partial<TransformNodeType<SignedTx>> {\n hash: Encoded.TxHash;\n rawTx: Encoded.Transaction;\n confirmationHeight?: number;\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 { height, hash, onNode }:\n { height?: number; hash?: Encoded.KeyBlockHash | Encoded.MicroBlockHash; onNode: Node },\n): Promise<TransformNodeType<AccountNode>> {\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,\n { format = AE_AMOUNT_FORMATS.AETTOS, ...options }:\n { format?: AE_AMOUNT_FORMATS } & Parameters<typeof getAccount>[1],\n): Promise<string> {\n const { balance } = await getAccount(address, 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 }: { onNode: Node },\n): Promise<TransformNodeType<Generation>> {\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): Promise<TransformNodeType<Generation>> {\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<TransformNodeType<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): Promise<TransformNodeType<KeyBlock>> {\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): Promise<TransformNodeType<MicroBlockHeader>> {\n return onNode.getMicroBlockHeaderByHash(hash);\n}\n\ninterface TxDryRunArguments {\n tx: Encoded.Transaction;\n accountAddress: Encoded.AccountAddress;\n top?: number;\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 dryRunRes = await onNode.protectedDryRunTxs({\n top: rs[0].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)))\n .map((pubKey) => ({ pubKey, amount: DRY_RUN_ACCOUNT.amount })),\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 {\n resolve, reject, tx, accountAddress,\n } = 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, txEvents, combine, onNode,\n }:\n { top?: number; txEvents?: boolean; combine?: boolean; onNode: Node },\n): Promise<{\n txEvents?: TransformNodeType<DryRunResults['txEvents']>;\n } & TransformNodeType<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, accountAddress, top, txEvents, resolve, reject,\n });\n if (combine !== true) {\n void txDryRunHandler(key, onNode);\n return;\n }\n requests.timeout ??= setTimeout(() => { void txDryRunHandler(key, onNode); });\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): Promise<TransformNodeType<ByteCode>> {\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): Promise<TransformNodeType<ContractObject>> {\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): Promise<TransformNodeType<NameEntry>> {\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 <\n Type extends Encoding.AccountAddress | Encoding.ContractAddress,\n>(\n nameOrId: AensName | Encoded.Generic<Type>,\n key: string,\n { verify = true, resolveByNode = false, 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;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAfA,SAgBSA,iBAAiB,EAAEC,YAAY;AAAA,OACjCC,iBAAiB;AAAA,SACfC,sBAAsB,EAAEC,KAAK;AAAA,SAC7BC,WAAW,EAAEC,aAAa;AAAA,SAC1BC,eAAe;AAAA,SAGtBC,uBAAuB,EAAEC,WAAW,EAAEC,oBAAoB,EAAEC,gBAAgB,EAC5EC,eAAe,EAAEC,iBAAiB,EAAEC,aAAa;AAAA,SAO1CC,MAAM;AAGf;AACA;AACA;AACA,OAAO,SAASC,gBAAgB,CAC9BC,IAA4B,QAGpB;EAAA,IAFR;IAAEC,iBAAiB,GAAG,MAAM;IAAEC,gBAAgB,GAAG,IAAI;IAAEC,gBAAgB,GAAG;EACS,CAAC;EAEpF,MAAMC,IAAI,GAAG;IACXC,KAAK,EAAEJ,iBAAiB;IACxBK,UAAU,EAAEJ;EACd,CAAC,CAACF,IAAI,CAAC;EACP,OAAOO,IAAI,CAACC,GAAG,CAACJ,IAAI,GAAG,CAAC,EAAED,gBAAgB,CAAC;AAC7C;;AAEA;AACA;AACA;AACA,OAAO,MAAMM,cAAc,SAASf,gBAAgB,CAAC;EAKnDgB,WAAW,CACTC,OAAe,EACfC,UAA6B,EAC7BC,WAAgC,EAChC;IACA,KAAK,CAACF,OAAO,CAAC;IACd,IAAI,CAACG,IAAI,GAAG,gBAAgB;IAC5B,IAAI,CAACF,UAAU,GAAGA,UAAU;IAC5B,IAAI,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;IACF9H,MAAM,CAAC8H,QAAQ,CAAC;IAChB,OAAOA,QAAQ;EACjB,CAAC,CAAC,OAAOhF,KAAK,EAAE;IACd,MAAM,IAAInD,oBAAoB,CAAE,4BAA2BmI,QAAS,EAAC,CAAC;EACxE;AACF"}
|
|
1
|
+
{"version":3,"file":"chain.mjs","names":["AE_AMOUNT_FORMATS","formatAmount","verifyTransaction","isAccountNotFoundError","pause","isNameValid","produceNameId","DRY_RUN_ACCOUNT","AensPointerContextError","DryRunError","InvalidAensNameError","TransactionError","TxTimedOutError","TxNotInChainError","InternalError","decode","_getPollInterval","type","_expectedMineRate","_microBlockCycle","_maxPollInterval","base","block","microblock","Math","min","InvalidTxError","constructor","message","validation","transaction","name","getHeight","onNode","getCurrentKeyBlockHeight","height","poll","th","blocks","interval","options","max","tx","getTransactionByHash","blockHeight","awaitHeight","currentHeight","waitForTxConfirm","txHash","confirm","newBlockHeight","sendTransaction","onAccount","verify","waitMined","length","map","v","join","__queue","address","error","postTransaction","requestOptions","customHeaders","pollResult","txData","hash","rawTx","c","undefined","confirmationHeight","Object","assign","verifyTx","getAccount","getAccountByPubkeyAndHeight","getAccountByPubkeyAndHash","getAccountByPubkey","getBalance","format","AETTOS","balance","catch","targetDenomination","getCurrentGeneration","getGeneration","hashOrHeight","getGenerationByHeight","getGenerationByHash","getMicroBlockTransactions","getMicroBlockTransactionsByHash","transactions","getKeyBlock","getKeyBlockByHeight","getKeyBlockByHash","getMicroBlockHeader","getMicroBlockHeaderByHash","txDryRunRequests","Map","txDryRunHandler","key","rs","get","delete","dryRunRes","top","protectedDryRunTxs","txEvents","txs","req","accounts","Array","from","Set","accountAddress","pubKey","amount","forEach","reject","results","idx","result","reason","resultPayload","resolve","txDryRun","combine","requests","set","Promise","push","timeout","setTimeout","getContractByteCode","contractId","getContractCode","getContract","getName","getNameEntryByName","resolveName","nameOrId","resolveByNode","pointer","pointers","find","p","id"],"sources":["../src/chain.ts"],"sourcesContent":["/*\n * ISC License (ISC)\n * Copyright (c) 2022 aeternity developers\n *\n * Permission to use, copy, modify, and/or distribute this software for any\n * purpose with or without fee is hereby granted, provided that the above\n * copyright notice and this permission notice appear in all copies.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\n * REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\n * AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\n * INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\n * LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\n * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\n * PERFORMANCE OF THIS SOFTWARE.\n */\nimport { AE_AMOUNT_FORMATS, formatAmount } from './utils/amount-formatter';\nimport verifyTransaction, { ValidatorResult } from './tx/validator';\nimport { isAccountNotFoundError, pause } from './utils/other';\nimport { isNameValid, produceNameId } from './tx/builder/helpers';\nimport { DRY_RUN_ACCOUNT } from './tx/builder/schema';\nimport { AensName } from './tx/builder/constants';\nimport {\n AensPointerContextError, DryRunError, InvalidAensNameError, TransactionError,\n TxTimedOutError, TxNotInChainError, InternalError,\n} from './utils/errors';\nimport Node, { TransformNodeType } from './Node';\nimport {\n Account as AccountNode, ByteCode, ContractObject, DryRunResult, DryRunResults,\n Generation, KeyBlock, MicroBlockHeader, NameEntry, SignedTx,\n} from './apis/node';\nimport { decode, Encoded, Encoding } from './utils/encoder';\nimport AccountBase from './account/Base';\n\n/**\n * @category chain\n */\nexport function _getPollInterval(\n type: 'block' | 'microblock',\n { _expectedMineRate = 180000, _microBlockCycle = 3000, _maxPollInterval = 5000 }:\n { _expectedMineRate?: number; _microBlockCycle?: number; _maxPollInterval?: number },\n): number {\n const base = {\n block: _expectedMineRate,\n microblock: _microBlockCycle,\n }[type];\n return Math.min(base / 3, _maxPollInterval);\n}\n\n/**\n * @category exception\n */\nexport class InvalidTxError extends TransactionError {\n validation: ValidatorResult[];\n\n transaction: Encoded.Transaction;\n\n constructor(\n message: string,\n validation: ValidatorResult[],\n transaction: Encoded.Transaction,\n ) {\n super(message);\n this.name = 'InvalidTxError';\n this.validation = validation;\n this.transaction = transaction;\n }\n}\n\n/**\n * Obtain current height of the chain\n * @category chain\n * @returns Current chain height\n */\nexport async function getHeight({ onNode }: { onNode: Node }): Promise<number> {\n return (await onNode.getCurrentKeyBlockHeight()).height;\n}\n\n/**\n * Wait for a transaction to be 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\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 = 10, interval, onNode, ...options\n }:\n { blocks?: number; interval?: number; onNode: Node } & Parameters<typeof _getPollInterval>[1],\n): Promise<TransformNodeType<SignedTx>> {\n interval ??= _getPollInterval('microblock', options);\n const max = await getHeight({ onNode }) + blocks;\n do {\n const tx = await onNode.getTransactionByHash(th);\n if (tx.blockHeight !== -1) return tx;\n await pause(interval);\n } while (await getHeight({ onNode }) < 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 { interval, onNode, ...options }:\n { interval?: number; onNode: Node } & Parameters<typeof _getPollInterval>[1],\n): Promise<number> {\n interval ??= _getPollInterval('block', options);\n let currentHeight;\n do {\n if (currentHeight != null) await pause(interval);\n currentHeight = (await onNode.getCurrentKeyBlockHeight()).height;\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 { confirm = 3, onNode, ...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 * Submit a signed transaction for mining\n * @category chain\n * @param tx - Transaction to submit\n * @param options - Options\n * @param options.onNode - Node to use\n * @param options.onAccount - Account to use\n * @param options.verify - Verify transaction before sending\n * @param options.waitMined - Ensure that transaction get into block\n * @param options.confirm - Number of micro blocks that should be mined after tx get included\n * @returns Transaction details\n */\nexport async function sendTransaction(\n tx: Encoded.Transaction,\n {\n onNode, onAccount, verify = true, waitMined = true, confirm, ...options\n }:\n SendTransactionOptions,\n): Promise<SendTransactionReturnType> {\n if (verify) {\n const validation = await verifyTransaction(tx, onNode);\n if (validation.length > 0) {\n const message = `Transaction verification errors: ${\n validation.map((v: { message: string }) => v.message).join(', ')}`;\n throw new InvalidTxError(message, validation, tx);\n }\n }\n\n try {\n let __queue;\n try {\n __queue = onAccount != null ? `tx-${onAccount.address}` : null;\n } catch (error) {\n __queue = null;\n }\n const { txHash } = await onNode.postTransaction(\n { tx },\n __queue != null ? { requestOptions: { customHeaders: { __queue } } } : {},\n );\n\n if (waitMined) {\n const pollResult = await poll(txHash, { onNode, ...options });\n const txData = {\n ...pollResult,\n hash: pollResult.hash as Encoded.TxHash,\n rawTx: tx,\n };\n // wait for transaction confirmation\n if (confirm != null && (confirm === true || confirm > 0)) {\n const c = typeof confirm === 'boolean' ? undefined : confirm;\n return {\n ...txData,\n confirmationHeight: await waitForTxConfirm(txHash, { onNode, confirm: c, ...options }),\n };\n }\n return txData;\n }\n return { hash: txHash, rawTx: tx };\n } catch (error) {\n throw Object.assign(error, {\n rawTx: tx,\n verifyTx: async () => verifyTransaction(tx, onNode),\n });\n }\n}\n\ntype SendTransactionOptionsType = {\n onNode: Node;\n onAccount?: AccountBase;\n verify?: boolean;\n waitMined?: boolean;\n confirm?: boolean | number;\n} & Parameters<typeof poll>[1] & Omit<Parameters<typeof waitForTxConfirm>[1], 'confirm'>;\ninterface SendTransactionOptions extends SendTransactionOptionsType {}\ninterface SendTransactionReturnType extends Partial<TransformNodeType<SignedTx>> {\n hash: Encoded.TxHash;\n rawTx: Encoded.Transaction;\n confirmationHeight?: number;\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 { height, hash, onNode }:\n { height?: number; hash?: Encoded.KeyBlockHash | Encoded.MicroBlockHash; onNode: Node },\n): Promise<TransformNodeType<AccountNode>> {\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,\n { format = AE_AMOUNT_FORMATS.AETTOS, ...options }:\n { format?: AE_AMOUNT_FORMATS } & Parameters<typeof getAccount>[1],\n): Promise<string> {\n const { balance } = await getAccount(address, 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 }: { onNode: Node },\n): Promise<TransformNodeType<Generation>> {\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): Promise<TransformNodeType<Generation>> {\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<TransformNodeType<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): Promise<TransformNodeType<KeyBlock>> {\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): Promise<TransformNodeType<MicroBlockHeader>> {\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 = typeof rs[0].top === 'number'\n ? (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)))\n .map((pubKey) => ({ pubKey, amount: DRY_RUN_ACCOUNT.amount })),\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 {\n resolve, reject, tx, accountAddress,\n } = 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, txEvents, combine, onNode,\n }:\n { top?: TxDryRunArguments['top']; txEvents?: boolean; combine?: boolean; onNode: Node },\n): Promise<{\n txEvents?: TransformNodeType<DryRunResults['txEvents']>;\n } & TransformNodeType<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, accountAddress, top, txEvents, resolve, reject,\n });\n if (combine !== true) {\n void txDryRunHandler(key, onNode);\n return;\n }\n requests.timeout ??= setTimeout(() => { void txDryRunHandler(key, onNode); });\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): Promise<TransformNodeType<ByteCode>> {\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): Promise<TransformNodeType<ContractObject>> {\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): Promise<TransformNodeType<NameEntry>> {\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 <\n Type extends Encoding.AccountAddress | Encoding.ContractAddress,\n>(\n nameOrId: AensName | Encoded.Generic<Type>,\n key: string,\n { verify = true, resolveByNode = false, 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;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAfA,SAgBSA,iBAAiB,EAAEC,YAAY;AAAA,OACjCC,iBAAiB;AAAA,SACfC,sBAAsB,EAAEC,KAAK;AAAA,SAC7BC,WAAW,EAAEC,aAAa;AAAA,SAC1BC,eAAe;AAAA,SAGtBC,uBAAuB,EAAEC,WAAW,EAAEC,oBAAoB,EAAEC,gBAAgB,EAC5EC,eAAe,EAAEC,iBAAiB,EAAEC,aAAa;AAAA,SAO1CC,MAAM;AAGf;AACA;AACA;AACA,OAAO,SAASC,gBAAgB,CAC9BC,IAA4B,QAGpB;EAAA,IAFR;IAAEC,iBAAiB,GAAG,MAAM;IAAEC,gBAAgB,GAAG,IAAI;IAAEC,gBAAgB,GAAG;EACS,CAAC;EAEpF,MAAMC,IAAI,GAAG;IACXC,KAAK,EAAEJ,iBAAiB;IACxBK,UAAU,EAAEJ;EACd,CAAC,CAACF,IAAI,CAAC;EACP,OAAOO,IAAI,CAACC,GAAG,CAACJ,IAAI,GAAG,CAAC,EAAED,gBAAgB,CAAC;AAC7C;;AAEA;AACA;AACA;AACA,OAAO,MAAMM,cAAc,SAASf,gBAAgB,CAAC;EAKnDgB,WAAW,CACTC,OAAe,EACfC,UAA6B,EAC7BC,WAAgC,EAChC;IACA,KAAK,CAACF,OAAO,CAAC;IACd,IAAI,CAACG,IAAI,GAAG,gBAAgB;IAC5B,IAAI,CAACF,UAAU,GAAGA,UAAU;IAC5B,IAAI,CAACC,WAAW,GAAGA,WAAW;EAChC;AACF;;AAEA;AACA;AACA;AACA;AACA;AACA,OAAO,eAAeE,SAAS,QAAgD;EAAA,IA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aAAa,EAAE,OAAOC,OAAO,CAACI,EAAE;IACtC;IACA,OAAO7I,aAAa,CAACuI,QAAQ,CAAC;EAChC;EACA,IAAI;IACF9H,MAAM,CAAC8H,QAAQ,CAAC;IAChB,OAAOA,QAAQ;EACjB,CAAC,CAAC,OAAOhF,KAAK,EAAE;IACd,MAAM,IAAInD,oBAAoB,CAAE,4BAA2BmI,QAAS,EAAC,CAAC;EACxE;AACF"}
|
package/es/channel/Base.d.ts
CHANGED
|
@@ -129,7 +129,12 @@ export default class Channel {
|
|
|
129
129
|
/**
|
|
130
130
|
* Get current state
|
|
131
131
|
*/
|
|
132
|
-
state(): Promise<
|
|
132
|
+
state(): Promise<{
|
|
133
|
+
calls: Encoded.CallStateTree;
|
|
134
|
+
halfSignedTx: Encoded.Transaction | '';
|
|
135
|
+
signedTx: Encoded.Transaction;
|
|
136
|
+
trees: Encoded.StateTrees;
|
|
137
|
+
}>;
|
|
133
138
|
/**
|
|
134
139
|
* Get current round
|
|
135
140
|
*
|
package/es/channel/Base.mjs
CHANGED
|
@@ -187,16 +187,16 @@ export default class Channel {
|
|
|
187
187
|
return null;
|
|
188
188
|
}
|
|
189
189
|
const {
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
} = unpackTx(this._state, Tag.SignedTx).
|
|
193
|
-
switch (
|
|
190
|
+
tag,
|
|
191
|
+
round
|
|
192
|
+
} = unpackTx(this._state, Tag.SignedTx).encodedTx;
|
|
193
|
+
switch (tag) {
|
|
194
194
|
case Tag.ChannelCreateTx:
|
|
195
195
|
return 1;
|
|
196
196
|
case Tag.ChannelOffChainTx:
|
|
197
197
|
case Tag.ChannelWithdrawTx:
|
|
198
198
|
case Tag.ChannelDepositTx:
|
|
199
|
-
return
|
|
199
|
+
return round;
|
|
200
200
|
default:
|
|
201
201
|
return null;
|
|
202
202
|
}
|
|
@@ -283,7 +283,10 @@ export default class Channel {
|
|
|
283
283
|
} = options;
|
|
284
284
|
return Channel.initialize({
|
|
285
285
|
...options,
|
|
286
|
-
reconnectTx: await sign('reconnect', buildTx(
|
|
286
|
+
reconnectTx: await sign('reconnect', buildTx({
|
|
287
|
+
...txParams,
|
|
288
|
+
tag: Tag.ChannelClientReconnectTx
|
|
289
|
+
}))
|
|
287
290
|
});
|
|
288
291
|
}
|
|
289
292
|
}
|
package/es/channel/Base.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Base.mjs","names":["snakeToPascal","buildTx","unpackTx","Tag","handlers","initialize","enqueueAction","notify","call","disconnect","channelDisconnect","ChannelError","snakeToPascalObjKeys","obj","Object","entries","reduce","result","key","val","Channel","EventEmitter","Map","options","_initialize","channel","existingFsmId","awaitingReconnection","awaitingConnection","channelOpen","on","eventName","callback","_eventEmitter","off","removeListener","status","_status","state","round","_state","txType","tx","SignedTx","encodedTx","ChannelCreateTx","ChannelOffChainTx","ChannelWithdrawTx","ChannelDepositTx","id","_channelId","fsmId","_fsmId","action","handler","leave","awaitingLeave","shutdown","sign","awaitingShutdownTx","reconnect","txParams","reconnectTx","ChannelClientReconnectTx"],"sources":["../../src/channel/Base.ts"],"sourcesContent":["/*\n * ISC License (ISC)\n * Copyright (c) 2022 aeternity developers\n *\n * Permission to use, copy, modify, and/or distribute this software for any\n * purpose with or without fee is hereby granted, provided that the above\n * copyright notice and this permission notice appear in all copies.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\n * REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\n * AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\n * INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\n * LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\n * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\n * PERFORMANCE OF THIS SOFTWARE.\n */\nimport { EventEmitter } from 'events';\nimport { w3cwebsocket as W3CWebSocket } from 'websocket';\nimport { snakeToPascal } from '../utils/string';\nimport { buildTx, unpackTx } from '../tx/builder';\nimport { Tag } from '../tx/builder/constants';\nimport * as handlers from './handlers';\nimport {\n initialize,\n enqueueAction,\n notify,\n call,\n disconnect as channelDisconnect,\n SignTx,\n ChannelOptions,\n ChannelState,\n ChannelHandler,\n ChannelAction,\n ChannelStatus,\n ChannelFsm,\n} from './internal';\nimport { ChannelError } from '../utils/errors';\nimport { Encoded } from '../utils/encoder';\n\nfunction snakeToPascalObjKeys<Type>(obj: object): Type {\n return Object.entries(obj).reduce((result, [key, val]) => ({\n ...result,\n [snakeToPascal(key)]: val,\n }), {}) as Type;\n}\n\ntype EventCallback = (...args: any[]) => void;\n\n/**\n * Channel\n * @example\n * ```js\n * await Channel.initialize({\n * url: 'ws://localhost:3001',\n * role: 'initiator'\n * initiatorId: 'ak_Y1NRjHuoc3CGMYMvCmdHSBpJsMDR6Ra2t5zjhRcbtMeXXLpLH',\n * responderId: 'ak_V6an1xhec1xVaAhLuak7QoEbi6t7w5hEtYWp9bMKaJ19i6A9E',\n * initiatorAmount: 1e18,\n * responderAmount: 1e18,\n * pushAmount: 0,\n * channelReserve: 0,\n * ttl: 1000,\n * host: 'localhost',\n * port: 3002,\n * lockPeriod: 10,\n * async sign (tag, tx) => await account.signTransaction(tx)\n * })\n * ```\n */\nexport default class Channel {\n _eventEmitter = new EventEmitter();\n\n _pingTimeoutId: NodeJS.Timeout;\n\n _nextRpcMessageId = 0;\n\n _rpcCallbacks = new Map<number, (message: object) => void>();\n\n _fsmId?: Encoded.Bytearray;\n\n _messageQueue: object[] = [];\n\n _isMessageQueueLocked = false;\n\n _actionQueue: ChannelAction[] = [];\n\n _isActionQueueLocked = false;\n\n _status: ChannelStatus = 'disconnected';\n\n _fsm: ChannelFsm;\n\n _websocket: W3CWebSocket;\n\n _state?: Encoded.Transaction;\n\n _options: ChannelOptions;\n\n _channelId?: Encoded.Channel;\n\n /**\n * @param options - Channel params\n * @param options.url - Channel url (for example: \"ws://localhost:3001\")\n * @param options.role - Participant role (\"initiator\" or \"responder\")\n * @param options.initiatorId - Initiator's public key\n * @param options.responderId - Responder's public key\n * @param options.pushAmount - Initial deposit in favour of the responder by the initiator\n * @param options.initiatorAmount - Amount of coins the initiator has committed to\n * the channel\n * @param options.responderAmount - Amount of coins the responder has committed to\n * the channel\n * @param options.channelReserve - The minimum amount both peers need to maintain\n * @param options.ttl - Minimum block height to include the channel_create_tx\n * @param options.host - Host of the responder's node\n * @param options.port - The port of the responders node\n * @param options.lockPeriod - Amount of blocks for disputing a solo close\n * @param options.minimumDepthStrategy - How to calculate minimum depth (default: txfee)\n * @param options.minimumDepth - The minimum amount of blocks to be mined\n * @param options.fee - The fee to be used for the channel open transaction\n * @param options.gasPrice - Used for the fee computation of the channel open transaction\n * @param options.existingChannelId - Existing channel id (required if reestablishing a\n * channel)\n * @param options.offchainTx - Offchain transaction (required if reestablishing\n * a channel)\n * @param options.timeoutIdle - The time waiting for a new event to be initiated\n * (default: 600000)\n * @param options.timeoutFundingCreate - The time waiting for the initiator to produce\n * the create channel transaction after the noise session had been established (default: 120000)\n * @param options.timeoutFundingSign - The time frame the other client has to sign an\n * off-chain update after our client had initiated and signed it. This applies only for double\n * signed on-chain intended updates: channel create transaction, deposit, withdrawal and etc.\n * (default: 120000)\n * @param options.timeoutFundingLock - The time frame the other client has to confirm an\n * on-chain transaction reaching maturity (passing minimum depth) after the local node has\n * detected this. This applies only for double signed on-chain intended updates: channel create\n * transaction, deposit, withdrawal and etc. (default: 360000)\n * @param options.timeoutSign - The time frame the client has to return a signed\n * off-chain update or to decline it. This applies for all off-chain updates (default: 500000)\n * @param options.timeoutAccept - The time frame the other client has to react to an\n * event. This applies for all off-chain updates that are not meant to land on-chain, as well as\n * some special cases: opening a noise connection, mutual closing acknowledgement and\n * reestablishing an existing channel (default: 120000)\n * @param options.timeoutInitialized - the time frame the responder has to accept an\n * incoming noise session. Applicable only for initiator (default: timeout_accept's value)\n * @param options.timeoutAwaitingOpen - The time frame the initiator has to start an\n * outgoing noise session to the responder's node. Applicable only for responder (default:\n * timeout_idle's value)\n * @param options.debug=false - Log websocket communication\n * @param options.sign - Function which verifies and signs transactions\n */\n static async initialize(options: ChannelOptions): Promise<Channel> {\n return Channel._initialize(new Channel(), options);\n }\n\n static async _initialize<T extends Channel>(channel: T, options: ChannelOptions): Promise<T> {\n await initialize(\n channel,\n options.existingFsmId != null ? handlers.awaitingReconnection : handlers.awaitingConnection,\n handlers.channelOpen,\n options,\n );\n return channel;\n }\n\n /**\n * Register event listener function\n *\n * Possible events:\n *\n * - \"error\"\n * - \"onChainTx\"\n * - \"ownWithdrawLocked\"\n * - \"withdrawLocked\"\n * - \"ownDepositLocked\"\n * - \"depositLocked\"\n *\n * TODO: the event list looks outdated\n *\n * @param eventName - Event name\n * @param callback - Callback function\n */\n // TODO define specific callback type depending on the event name\n on(eventName: string, callback: EventCallback): void {\n this._eventEmitter.on(eventName, callback);\n }\n\n /**\n * Remove event listener function\n * @param eventName - Event name\n * @param callback - Callback function\n */\n off(eventName: string, callback: EventCallback): void {\n this._eventEmitter.removeListener(eventName, callback);\n }\n\n /**\n * Close the connection\n */\n disconnect(): void {\n return channelDisconnect(this);\n }\n\n /**\n * Get current status\n */\n status(): ChannelStatus {\n return this._status;\n }\n\n /**\n * Get current state\n */\n async state(): Promise<ChannelState> {\n return snakeToPascalObjKeys(await call(this, 'channels.get.offchain_state', {}));\n }\n\n /**\n * Get current round\n *\n * If round cannot be determined (for example when channel has not been opened)\n * it will return `null`.\n */\n round(): number | null {\n if (this._state == null) {\n return null;\n }\n const { txType, tx } = unpackTx(this._state, Tag.SignedTx).tx.encodedTx;\n switch (txType) {\n case Tag.ChannelCreateTx:\n return 1;\n case Tag.ChannelOffChainTx:\n case Tag.ChannelWithdrawTx:\n case Tag.ChannelDepositTx:\n return tx.round;\n default:\n return null;\n }\n }\n\n /**\n * Get channel id\n *\n */\n id(): Encoded.Channel {\n if (this._channelId == null) throw new ChannelError('Channel is not initialized');\n return this._channelId;\n }\n\n /**\n * Get channel's fsm id\n *\n */\n fsmId(): Encoded.Bytearray {\n if (this._fsmId == null) throw new ChannelError('Channel is not initialized');\n return this._fsmId;\n }\n\n protected async enqueueAction(\n action: () => { handler: ChannelHandler; state?: Partial<ChannelState> },\n ): Promise<any> {\n return enqueueAction(\n this,\n (channel, state) => state?.handler === handlers.channelOpen,\n action,\n );\n }\n\n /**\n * Leave channel\n *\n * It is possible to leave a channel and then later reestablish the channel\n * off-chain state and continue operation. When a leave method is called,\n * the channel fsm passes it on to the peer fsm, reports the current mutually\n * signed state and then terminates.\n *\n * The channel can be reestablished by instantiating another Channel instance\n * with two extra params: existingChannelId and offchainTx (returned from leave\n * method as channelId and signedTx respectively).\n *\n * @example\n * ```js\n * channel.leave().then(({ channelId, signedTx }) => {\n * console.log(channelId)\n * console.log(signedTx)\n * })\n * ```\n */\n async leave(): Promise<{ channelId: Encoded.Bytearray; signedTx: Encoded.Transaction }> {\n return this.enqueueAction(() => {\n notify(this, 'channels.leave');\n return { handler: handlers.awaitingLeave };\n });\n }\n\n /**\n * Trigger mutual close\n *\n * At any moment after the channel is opened, a closing procedure can be triggered.\n * This can be done by either of the parties. The process is similar to the off-chain updates.\n *\n * @param sign - Function which verifies and signs mutual close transaction\n * @example\n * ```js\n * channel.shutdown(\n * async (tx) => await account.signTransaction(tx)\n * ).then(tx => console.log('on_chain_tx', tx))\n * ```\n */\n async shutdown(sign: SignTx): Promise<Encoded.Transaction> {\n return this.enqueueAction(() => {\n notify(this, 'channels.shutdown');\n return {\n handler: handlers.awaitingShutdownTx,\n state: { sign },\n };\n });\n }\n\n static async reconnect(options: ChannelOptions, txParams: any): Promise<Channel> {\n const { sign } = options;\n\n return Channel.initialize({\n ...options,\n reconnectTx: await sign('reconnect', buildTx(txParams, Tag.ChannelClientReconnectTx).tx),\n });\n }\n}\n"],"mappings":";AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,oBAA6B,QAAQ;AAAC;EAAA;AAAA;AAAA,SAE7BA,aAAa;AAAA,SACbC,OAAO,EAAEC,QAAQ;AAAA,SACjBC,GAAG;AAAA,OACL,KAAKC,QAAQ;AAAA,SAElBC,UAAU,EACVC,aAAa,EACbC,MAAM,EACNC,IAAI,EACJC,UAAU,IAAIC,iBAAiB;AAAA,SASxBC,YAAY;AAGrB,SAASC,oBAAoB,CAAOC,GAAW,EAAQ;EACrD,OAAOC,MAAM,CAACC,OAAO,CAACF,GAAG,CAAC,CAACG,MAAM,CAAC,CAACC,MAAM;IAAA,IAAE,CAACC,GAAG,EAAEC,GAAG,CAAC;IAAA,OAAM;MACzD,GAAGF,MAAM;MACT,CAACjB,aAAa,CAACkB,GAAG,CAAC,GAAGC;IACxB,CAAC;EAAA,CAAC,EAAE,CAAC,CAAC,CAAC;AACT;AAIA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,eAAe,MAAMC,OAAO,CAAC;EAAA;IAAA,uCACX,IAAIC,YAAY,EAAE;IAAA,2CAId,CAAC;IAAA,uCAEL,IAAIC,GAAG,EAAqC;IAAA,uCAIlC,EAAE;IAAA,+CAEJ,KAAK;IAAA,sCAEG,EAAE;IAAA,8CAEX,KAAK;IAAA,iCAEH,cAAc;EAAA;EAYvC;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;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;EACE,aAAajB,UAAU,CAACkB,OAAuB,EAAoB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AAQ,CAACC,IAAY,EAAgC;IACzD,OAAO,IAAI,CAACpD,aAAa,CAAC,MAAM;MAC9BC,MAAM,CAAC,IAAI,EAAE,mBAAmB,CAAC;MACjC,OAAO;QACL+C,OAAO,EAAElD,QAAQ,CAACuD,kBAAkB;QACpCrB,KAAK,EAAE;UAAEoB;QAAK;MAChB,CAAC;IACH,CAAC,CAAC;EACJ;EAEA,aAAaE,SAAS,CAACrC,OAAuB,EAAEsC,QAAa,EAAoB;IAC/E,MAAM;MAAEH;IAAK,CAAC,GAAGnC,OAAO;IAExB,OAAOH,OAAO,CAACf,UAAU,CAAC;MACxB,GAAGkB,OAAO;MACVuC,WAAW,EAAE,MAAMJ,IAAI,CAAC,WAAW,EAAEzD,OAAO,CAAC4D,QAAQ,EAAE1D,GAAG,CAAC4D,wBAAwB,CAAC,CAACrB,EAAE;IACzF,CAAC,CAAC;EACJ;AACF"}
|
|
1
|
+
{"version":3,"file":"Base.mjs","names":["snakeToPascal","buildTx","unpackTx","Tag","handlers","initialize","enqueueAction","notify","call","disconnect","channelDisconnect","ChannelError","snakeToPascalObjKeys","obj","Object","entries","reduce","result","key","val","Channel","EventEmitter","Map","options","_initialize","channel","existingFsmId","awaitingReconnection","awaitingConnection","channelOpen","on","eventName","callback","_eventEmitter","off","removeListener","status","_status","state","round","_state","tag","SignedTx","encodedTx","ChannelCreateTx","ChannelOffChainTx","ChannelWithdrawTx","ChannelDepositTx","id","_channelId","fsmId","_fsmId","action","handler","leave","awaitingLeave","shutdown","sign","awaitingShutdownTx","reconnect","txParams","reconnectTx","ChannelClientReconnectTx"],"sources":["../../src/channel/Base.ts"],"sourcesContent":["/*\n * ISC License (ISC)\n * Copyright (c) 2022 aeternity developers\n *\n * Permission to use, copy, modify, and/or distribute this software for any\n * purpose with or without fee is hereby granted, provided that the above\n * copyright notice and this permission notice appear in all copies.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\n * REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\n * AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\n * INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\n * LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\n * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\n * PERFORMANCE OF THIS SOFTWARE.\n */\nimport { EventEmitter } from 'events';\nimport { w3cwebsocket as W3CWebSocket } from 'websocket';\nimport { snakeToPascal } from '../utils/string';\nimport { buildTx, unpackTx } from '../tx/builder';\nimport { Tag } from '../tx/builder/constants';\nimport * as handlers from './handlers';\nimport {\n initialize,\n enqueueAction,\n notify,\n call,\n disconnect as channelDisconnect,\n SignTx,\n ChannelOptions,\n ChannelState,\n ChannelHandler,\n ChannelAction,\n ChannelStatus,\n ChannelFsm,\n} from './internal';\nimport { ChannelError } from '../utils/errors';\nimport { Encoded } from '../utils/encoder';\n\nfunction snakeToPascalObjKeys<Type>(obj: object): Type {\n return Object.entries(obj).reduce((result, [key, val]) => ({\n ...result,\n [snakeToPascal(key)]: val,\n }), {}) as Type;\n}\n\ntype EventCallback = (...args: any[]) => void;\n\n/**\n * Channel\n * @example\n * ```js\n * await Channel.initialize({\n * url: 'ws://localhost:3001',\n * role: 'initiator'\n * initiatorId: 'ak_Y1NRjHuoc3CGMYMvCmdHSBpJsMDR6Ra2t5zjhRcbtMeXXLpLH',\n * responderId: 'ak_V6an1xhec1xVaAhLuak7QoEbi6t7w5hEtYWp9bMKaJ19i6A9E',\n * initiatorAmount: 1e18,\n * responderAmount: 1e18,\n * pushAmount: 0,\n * channelReserve: 0,\n * ttl: 1000,\n * host: 'localhost',\n * port: 3002,\n * lockPeriod: 10,\n * async sign (tag, tx) => await account.signTransaction(tx)\n * })\n * ```\n */\nexport default class Channel {\n _eventEmitter = new EventEmitter();\n\n _pingTimeoutId: NodeJS.Timeout;\n\n _nextRpcMessageId = 0;\n\n _rpcCallbacks = new Map<number, (message: object) => void>();\n\n _fsmId?: Encoded.Bytearray;\n\n _messageQueue: object[] = [];\n\n _isMessageQueueLocked = false;\n\n _actionQueue: ChannelAction[] = [];\n\n _isActionQueueLocked = false;\n\n _status: ChannelStatus = 'disconnected';\n\n _fsm: ChannelFsm;\n\n _websocket: W3CWebSocket;\n\n _state?: Encoded.Transaction;\n\n _options: ChannelOptions;\n\n _channelId?: Encoded.Channel;\n\n /**\n * @param options - Channel params\n * @param options.url - Channel url (for example: \"ws://localhost:3001\")\n * @param options.role - Participant role (\"initiator\" or \"responder\")\n * @param options.initiatorId - Initiator's public key\n * @param options.responderId - Responder's public key\n * @param options.pushAmount - Initial deposit in favour of the responder by the initiator\n * @param options.initiatorAmount - Amount of coins the initiator has committed to\n * the channel\n * @param options.responderAmount - Amount of coins the responder has committed to\n * the channel\n * @param options.channelReserve - The minimum amount both peers need to maintain\n * @param options.ttl - Minimum block height to include the channel_create_tx\n * @param options.host - Host of the responder's node\n * @param options.port - The port of the responders node\n * @param options.lockPeriod - Amount of blocks for disputing a solo close\n * @param options.minimumDepthStrategy - How to calculate minimum depth (default: txfee)\n * @param options.minimumDepth - The minimum amount of blocks to be mined\n * @param options.fee - The fee to be used for the channel open transaction\n * @param options.gasPrice - Used for the fee computation of the channel open transaction\n * @param options.existingChannelId - Existing channel id (required if reestablishing a\n * channel)\n * @param options.offchainTx - Offchain transaction (required if reestablishing\n * a channel)\n * @param options.timeoutIdle - The time waiting for a new event to be initiated\n * (default: 600000)\n * @param options.timeoutFundingCreate - The time waiting for the initiator to produce\n * the create channel transaction after the noise session had been established (default: 120000)\n * @param options.timeoutFundingSign - The time frame the other client has to sign an\n * off-chain update after our client had initiated and signed it. This applies only for double\n * signed on-chain intended updates: channel create transaction, deposit, withdrawal and etc.\n * (default: 120000)\n * @param options.timeoutFundingLock - The time frame the other client has to confirm an\n * on-chain transaction reaching maturity (passing minimum depth) after the local node has\n * detected this. This applies only for double signed on-chain intended updates: channel create\n * transaction, deposit, withdrawal and etc. (default: 360000)\n * @param options.timeoutSign - The time frame the client has to return a signed\n * off-chain update or to decline it. This applies for all off-chain updates (default: 500000)\n * @param options.timeoutAccept - The time frame the other client has to react to an\n * event. This applies for all off-chain updates that are not meant to land on-chain, as well as\n * some special cases: opening a noise connection, mutual closing acknowledgement and\n * reestablishing an existing channel (default: 120000)\n * @param options.timeoutInitialized - the time frame the responder has to accept an\n * incoming noise session. Applicable only for initiator (default: timeout_accept's value)\n * @param options.timeoutAwaitingOpen - The time frame the initiator has to start an\n * outgoing noise session to the responder's node. Applicable only for responder (default:\n * timeout_idle's value)\n * @param options.debug=false - Log websocket communication\n * @param options.sign - Function which verifies and signs transactions\n */\n static async initialize(options: ChannelOptions): Promise<Channel> {\n return Channel._initialize(new Channel(), options);\n }\n\n static async _initialize<T extends Channel>(channel: T, options: ChannelOptions): Promise<T> {\n await initialize(\n channel,\n options.existingFsmId != null ? handlers.awaitingReconnection : handlers.awaitingConnection,\n handlers.channelOpen,\n options,\n );\n return channel;\n }\n\n /**\n * Register event listener function\n *\n * Possible events:\n *\n * - \"error\"\n * - \"onChainTx\"\n * - \"ownWithdrawLocked\"\n * - \"withdrawLocked\"\n * - \"ownDepositLocked\"\n * - \"depositLocked\"\n *\n * TODO: the event list looks outdated\n *\n * @param eventName - Event name\n * @param callback - Callback function\n */\n // TODO define specific callback type depending on the event name\n on(eventName: string, callback: EventCallback): void {\n this._eventEmitter.on(eventName, callback);\n }\n\n /**\n * Remove event listener function\n * @param eventName - Event name\n * @param callback - Callback function\n */\n off(eventName: string, callback: EventCallback): void {\n this._eventEmitter.removeListener(eventName, callback);\n }\n\n /**\n * Close the connection\n */\n disconnect(): void {\n return channelDisconnect(this);\n }\n\n /**\n * Get current status\n */\n status(): ChannelStatus {\n return this._status;\n }\n\n /**\n * Get current state\n */\n async state(): Promise<{\n calls: Encoded.CallStateTree;\n halfSignedTx: Encoded.Transaction | '';\n signedTx: Encoded.Transaction;\n trees: Encoded.StateTrees;\n }> {\n return snakeToPascalObjKeys(await call(this, 'channels.get.offchain_state', {}));\n }\n\n /**\n * Get current round\n *\n * If round cannot be determined (for example when channel has not been opened)\n * it will return `null`.\n */\n round(): number | null {\n if (this._state == null) {\n return null;\n }\n const { tag, round } = unpackTx(this._state, Tag.SignedTx).encodedTx;\n switch (tag) {\n case Tag.ChannelCreateTx:\n return 1;\n case Tag.ChannelOffChainTx:\n case Tag.ChannelWithdrawTx:\n case Tag.ChannelDepositTx:\n return round;\n default:\n return null;\n }\n }\n\n /**\n * Get channel id\n *\n */\n id(): Encoded.Channel {\n if (this._channelId == null) throw new ChannelError('Channel is not initialized');\n return this._channelId;\n }\n\n /**\n * Get channel's fsm id\n *\n */\n fsmId(): Encoded.Bytearray {\n if (this._fsmId == null) throw new ChannelError('Channel is not initialized');\n return this._fsmId;\n }\n\n protected async enqueueAction(\n action: () => { handler: ChannelHandler; state?: Partial<ChannelState> },\n ): Promise<any> {\n return enqueueAction(\n this,\n (channel, state) => state?.handler === handlers.channelOpen,\n action,\n );\n }\n\n /**\n * Leave channel\n *\n * It is possible to leave a channel and then later reestablish the channel\n * off-chain state and continue operation. When a leave method is called,\n * the channel fsm passes it on to the peer fsm, reports the current mutually\n * signed state and then terminates.\n *\n * The channel can be reestablished by instantiating another Channel instance\n * with two extra params: existingChannelId and offchainTx (returned from leave\n * method as channelId and signedTx respectively).\n *\n * @example\n * ```js\n * channel.leave().then(({ channelId, signedTx }) => {\n * console.log(channelId)\n * console.log(signedTx)\n * })\n * ```\n */\n async leave(): Promise<{ channelId: Encoded.Bytearray; signedTx: Encoded.Transaction }> {\n return this.enqueueAction(() => {\n notify(this, 'channels.leave');\n return { handler: handlers.awaitingLeave };\n });\n }\n\n /**\n * Trigger mutual close\n *\n * At any moment after the channel is opened, a closing procedure can be triggered.\n * This can be done by either of the parties. The process is similar to the off-chain updates.\n *\n * @param sign - Function which verifies and signs mutual close transaction\n * @example\n * ```js\n * channel.shutdown(\n * async (tx) => await account.signTransaction(tx)\n * ).then(tx => console.log('on_chain_tx', tx))\n * ```\n */\n async shutdown(sign: SignTx): Promise<Encoded.Transaction> {\n return this.enqueueAction(() => {\n notify(this, 'channels.shutdown');\n return {\n handler: handlers.awaitingShutdownTx,\n state: { sign },\n };\n });\n }\n\n static async reconnect(options: ChannelOptions, txParams: any): Promise<Channel> {\n const { sign } = options;\n\n return Channel.initialize({\n ...options,\n reconnectTx: await sign(\n 'reconnect',\n buildTx({ ...txParams, tag: Tag.ChannelClientReconnectTx }),\n ),\n });\n }\n}\n"],"mappings":";AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,oBAA6B,QAAQ;AAAC;EAAA;AAAA;AAAA,SAE7BA,aAAa;AAAA,SACbC,OAAO,EAAEC,QAAQ;AAAA,SACjBC,GAAG;AAAA,OACL,KAAKC,QAAQ;AAAA,SAElBC,UAAU,EACVC,aAAa,EACbC,MAAM,EACNC,IAAI,EACJC,UAAU,IAAIC,iBAAiB;AAAA,SASxBC,YAAY;AAGrB,SAASC,oBAAoB,CAAOC,GAAW,EAAQ;EACrD,OAAOC,MAAM,CAACC,OAAO,CAACF,GAAG,CAAC,CAACG,MAAM,CAAC,CAACC,MAAM;IAAA,IAAE,CAACC,GAAG,EAAEC,GAAG,CAAC;IAAA,OAAM;MACzD,GAAGF,MAAM;MACT,CAACjB,aAAa,CAACkB,GAAG,CAAC,GAAGC;IACxB,CAAC;EAAA,CAAC,EAAE,CAAC,CAAC,CAAC;AACT;AAIA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,eAAe,MAAMC,OAAO,CAAC;EAAA;IAAA,uCACX,IAAIC,YAAY,EAAE;IAAA,2CAId,CAAC;IAAA,u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