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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (113) hide show
  1. package/CHANGELOG.md +1603 -0
  2. package/dist/aepp-sdk.browser-script.js +1 -1
  3. package/dist/aepp-sdk.browser-script.js.map +1 -1
  4. package/dist/aepp-sdk.browser.js +1 -1
  5. package/dist/aepp-sdk.browser.js.map +1 -1
  6. package/dist/aepp-sdk.js +1 -1
  7. package/dist/aepp-sdk.js.map +1 -1
  8. package/es/account/base.js +3 -1
  9. package/es/account/base.js.map +1 -1
  10. package/es/account/multiple.js +4 -2
  11. package/es/account/multiple.js.map +1 -1
  12. package/es/ae/aens.js +52 -38
  13. package/es/ae/aens.js.map +1 -1
  14. package/es/ae/contract.js +9 -5
  15. package/es/ae/contract.js.map +1 -1
  16. package/es/ae/index.js +4 -3
  17. package/es/ae/index.js.map +1 -1
  18. package/es/ae/oracle.js +4 -4
  19. package/es/ae/oracle.js.map +1 -1
  20. package/es/ae/universal.js.map +1 -1
  21. package/es/chain/index.js +8 -4
  22. package/es/chain/index.js.map +1 -1
  23. package/es/chain/node.js +15 -20
  24. package/es/chain/node.js.map +1 -1
  25. package/es/channel/handlers.js.map +1 -1
  26. package/es/channel/index.js +35 -14
  27. package/es/channel/index.js.map +1 -1
  28. package/es/contract/aci/index.js +12 -7
  29. package/es/contract/aci/index.js.map +1 -1
  30. package/es/contract/compiler.js +3 -1
  31. package/es/contract/compiler.js.map +1 -1
  32. package/es/contract/ga/helpers.js +6 -6
  33. package/es/contract/ga/helpers.js.map +1 -1
  34. package/es/contract/ga/index.js +6 -2
  35. package/es/contract/ga/index.js.map +1 -1
  36. package/es/contract/index.js +6 -2
  37. package/es/contract/index.js.map +1 -1
  38. package/es/index.js +1 -0
  39. package/es/index.js.map +1 -1
  40. package/es/node-pool/index.js +4 -2
  41. package/es/node-pool/index.js.map +1 -1
  42. package/es/node.js +9 -4
  43. package/es/node.js.map +1 -1
  44. package/es/tx/builder/helpers.js +20 -33
  45. package/es/tx/builder/helpers.js.map +1 -1
  46. package/es/tx/builder/index.js +13 -6
  47. package/es/tx/builder/index.js.map +1 -1
  48. package/es/tx/builder/schema.js +5 -4
  49. package/es/tx/builder/schema.js.map +1 -1
  50. package/es/tx/index.js +101 -12
  51. package/es/tx/index.js.map +1 -1
  52. package/es/tx/tx-object.js +9 -3
  53. package/es/tx/tx-object.js.map +1 -1
  54. package/es/tx/tx.js.map +1 -1
  55. package/es/utils/aepp-wallet-communication/connection/browser-runtime.js +3 -2
  56. package/es/utils/aepp-wallet-communication/connection/browser-runtime.js.map +1 -1
  57. package/es/utils/aepp-wallet-communication/connection/browser-window-message.js +15 -6
  58. package/es/utils/aepp-wallet-communication/connection/browser-window-message.js.map +1 -1
  59. package/es/utils/aepp-wallet-communication/connection/index.js +2 -1
  60. package/es/utils/aepp-wallet-communication/connection/index.js.map +1 -1
  61. package/es/utils/aepp-wallet-communication/content-script-bridge.js +10 -4
  62. package/es/utils/aepp-wallet-communication/content-script-bridge.js.map +1 -1
  63. package/es/utils/aepp-wallet-communication/helpers.js.map +1 -1
  64. package/es/utils/aepp-wallet-communication/rpc/aepp-rpc.js +13 -5
  65. package/es/utils/aepp-wallet-communication/rpc/aepp-rpc.js.map +1 -1
  66. package/es/utils/aepp-wallet-communication/rpc/rpc-client.js +9 -5
  67. package/es/utils/aepp-wallet-communication/rpc/rpc-client.js.map +1 -1
  68. package/es/utils/aepp-wallet-communication/rpc/wallet-rpc.js +57 -40
  69. package/es/utils/aepp-wallet-communication/rpc/wallet-rpc.js.map +1 -1
  70. package/es/utils/aepp-wallet-communication/wallet-detector.js.map +1 -1
  71. package/es/utils/crypto.js +1 -40
  72. package/es/utils/crypto.js.map +1 -1
  73. package/es/utils/keystore.js.map +1 -1
  74. package/es/utils/swagger.js +3 -1
  75. package/es/utils/swagger.js.map +1 -1
  76. package/package.json +11 -13
  77. package/src/account/base.js +3 -1
  78. package/src/account/multiple.js +4 -2
  79. package/src/ae/aens.js +41 -42
  80. package/src/ae/contract.js +9 -5
  81. package/src/ae/index.js +4 -3
  82. package/src/ae/oracle.js +9 -5
  83. package/src/ae/universal.js +3 -1
  84. package/src/chain/index.js +8 -4
  85. package/src/chain/node.js +17 -14
  86. package/src/channel/handlers.js +10 -3
  87. package/src/channel/index.js +40 -15
  88. package/src/contract/aci/index.js +15 -8
  89. package/src/contract/compiler.js +6 -2
  90. package/src/contract/ga/helpers.js +5 -3
  91. package/src/contract/ga/index.js +6 -2
  92. package/src/contract/index.js +6 -2
  93. package/src/index.js +2 -0
  94. package/src/node-pool/index.js +4 -2
  95. package/src/node.js +7 -4
  96. package/src/tx/builder/helpers.js +20 -33
  97. package/src/tx/builder/index.js +49 -13
  98. package/src/tx/builder/schema.js +37 -14
  99. package/src/tx/index.js +101 -12
  100. package/src/tx/tx-object.js +25 -6
  101. package/src/tx/tx.js +94 -28
  102. package/src/utils/aepp-wallet-communication/connection/browser-runtime.js +3 -2
  103. package/src/utils/aepp-wallet-communication/connection/browser-window-message.js +25 -7
  104. package/src/utils/aepp-wallet-communication/connection/index.js +2 -1
  105. package/src/utils/aepp-wallet-communication/content-script-bridge.js +10 -4
  106. package/src/utils/aepp-wallet-communication/helpers.js +4 -2
  107. package/src/utils/aepp-wallet-communication/rpc/aepp-rpc.js +32 -9
  108. package/src/utils/aepp-wallet-communication/rpc/rpc-client.js +9 -5
  109. package/src/utils/aepp-wallet-communication/rpc/wallet-rpc.js +53 -22
  110. package/src/utils/aepp-wallet-communication/wallet-detector.js +4 -1
  111. package/src/utils/crypto.js +1 -52
  112. package/src/utils/keystore.js +10 -2
  113. package/src/utils/swagger.js +1 -1
@@ -338,7 +338,8 @@ function shutdown (sign) {
338
338
  * @param {Number} amount - Amount of tokens to withdraw
339
339
  * @param {Function} sign - Function which verifies and signs withdraw transaction
340
340
  * @param {Object} [callbacks]
341
- * @param {Function} [callbacks.onOnChainTx] - Called when withdraw transaction has been posted on chain
341
+ * @param {Function} [callbacks.onOnChainTx] - Called when withdraw transaction has been posted
342
+ * on chain
342
343
  * @param {Function} [callbacks.onOwnWithdrawLocked]
343
344
  * @param {Function} [callbacks.onWithdrawLocked]
344
345
  * @return {Promise<Object>}
@@ -407,7 +408,8 @@ function withdraw (amount, sign, { onOnChainTx, onOwnWithdrawLocked, onWithdrawL
407
408
  * @param {Number} amount - Amount of tokens to deposit
408
409
  * @param {Function} sign - Function which verifies and signs deposit transaction
409
410
  * @param {Object} [callbacks]
410
- * @param {Function} [callbacks.onOnChainTx] - Called when deposit transaction has been posted on chain
411
+ * @param {Function} [callbacks.onOnChainTx] - Called when deposit transaction has been posted
412
+ * on chain
411
413
  * @param {Function} [callbacks.onOwnDepositLocked]
412
414
  * @param {Function} [callbacks.onDepositLocked]
413
415
  * @return {Promise<Object>}
@@ -597,7 +599,11 @@ function callContract ({ amount, callData, contract, abiVersion }, sign) {
597
599
  * }
598
600
  * })
599
601
  */
600
- function forceProgress ({ amount, callData, contract, abiVersion, gas = 1000000, gasPrice = 1000000000, nonce }, sign, { onOnChainTx } = {}) {
602
+ function forceProgress (
603
+ { amount, callData, contract, abiVersion, gas = 1000000, gasPrice = 1000000000, nonce },
604
+ sign,
605
+ { onOnChainTx } = {}
606
+ ) {
601
607
  return new Promise((resolve, reject) => {
602
608
  enqueueAction(
603
609
  this,
@@ -800,23 +806,42 @@ async function reconnect (options, txParams) {
800
806
  * @param {String} options.initiatorId - Initiator's public key
801
807
  * @param {String} options.responderId - Responder's public key
802
808
  * @param {Number} options.pushAmount - Initial deposit in favour of the responder by the initiator
803
- * @param {Number} options.initiatorAmount - Amount of tokens the initiator has committed to the channel
804
- * @param {Number} options.responderAmount - Amount of tokens the responder has committed to the channel
809
+ * @param {Number} options.initiatorAmount - Amount of tokens the initiator has committed to
810
+ * the channel
811
+ * @param {Number} options.responderAmount - Amount of tokens the responder has committed to
812
+ * the channel
805
813
  * @param {Number} options.channelReserve - The minimum amount both peers need to maintain
806
814
  * @param {Number} [options.ttl] - Minimum block height to include the channel_create_tx
807
815
  * @param {String} options.host - Host of the responder's node
808
816
  * @param {Number} options.port - The port of the responders node
809
817
  * @param {Number} options.lockPeriod - Amount of blocks for disputing a solo close
810
- * @param {Number} [options.existingChannelId] - Existing channel id (required if reestablishing a channel)
811
- * @param {Number} [options.offchainTx] - Offchain transaction (required if reestablishing a channel)
812
- * @param {Number} [options.timeoutIdle] - The time waiting for a new event to be initiated (default: 600000)
813
- * @param {Number} [options.timeoutFundingCreate] - The time waiting for the initiator to produce the create channel transaction after the noise session had been established (default: 120000)
814
- * @param {Number} [options.timeoutFundingSign] - The time frame the other client has to sign an off-chain update after our client had initiated and signed it. This applies only for double signed on-chain intended updates: channel create transaction, deposit, withdrawal and etc. (default: 120000)
815
- * @param {Number} [options.timeoutFundingLock] - The time frame the other client has to confirm an on-chain transaction reaching maturity (passing minimum depth) after the local node has detected this. This applies only for double signed on-chain intended updates: channel create transaction, deposit, withdrawal and etc. (default: 360000)
816
- * @param {Number} [options.timeoutSign] - The time frame the client has to return a signed off-chain update or to decline it. This applies for all off-chain updates (default: 500000)
817
- * @param {Number} [options.timeoutAccept] - The time frame the other client has to react to an event. This applies for all off-chain updates that are not meant to land on-chain, as well as some special cases: opening a noise connection, mutual closing acknowledgement and reestablishing an existing channel (default: 120000)
818
- * @param {Number} [options.timeoutInitialized] - the time frame the responder has to accept an incoming noise session. Applicable only for initiator (default: timeout_accept's value)
819
- * @param {Number} [options.timeoutAwaitingOpen] - The time frame the initiator has to start an outgoing noise session to the responder's node. Applicable only for responder (default: timeout_idle's value)
818
+ * @param {Number} [options.existingChannelId] - Existing channel id (required if reestablishing a
819
+ * channel)
820
+ * @param {Number} [options.offchainTx] - Offchain transaction (required if reestablishing
821
+ * a channel)
822
+ * @param {Number} [options.timeoutIdle] - The time waiting for a new event to be initiated
823
+ * (default: 600000)
824
+ * @param {Number} [options.timeoutFundingCreate] - The time waiting for the initiator to produce
825
+ * the create channel transaction after the noise session had been established (default: 120000)
826
+ * @param {Number} [options.timeoutFundingSign] - The time frame the other client has to sign an
827
+ * off-chain update after our client had initiated and signed it. This applies only for double
828
+ * signed on-chain intended updates: channel create transaction, deposit, withdrawal and etc.
829
+ * (default: 120000)
830
+ * @param {Number} [options.timeoutFundingLock] - The time frame the other client has to confirm an
831
+ * on-chain transaction reaching maturity (passing minimum depth) after the local node has detected
832
+ * this. This applies only for double signed on-chain intended updates: channel create transaction,
833
+ * deposit, withdrawal and etc. (default: 360000)
834
+ * @param {Number} [options.timeoutSign] - The time frame the client has to return a signed
835
+ * off-chain update or to decline it. This applies for all off-chain updates (default: 500000)
836
+ * @param {Number} [options.timeoutAccept] - The time frame the other client has to react to an
837
+ * event. This applies for all off-chain updates that are not meant to land on-chain, as well as
838
+ * some special cases: opening a noise connection, mutual closing acknowledgement and
839
+ * reestablishing an existing channel (default: 120000)
840
+ * @param {Number} [options.timeoutInitialized] - the time frame the responder has to accept an
841
+ * incoming noise session. Applicable only for initiator (default: timeout_accept's value)
842
+ * @param {Number} [options.timeoutAwaitingOpen] - The time frame the initiator has to start an
843
+ * outgoing noise session to the responder's node. Applicable only for responder (default:
844
+ * timeout_idle's value)
820
845
  * @param {Number} [options.debug=false] - Log websocket communication
821
846
  * @param {Function} options.sign - Function which verifies and signs transactions
822
847
  * @return {Promise<Object>} Channel instance
@@ -56,7 +56,8 @@ function getFunctionACI (aci, name, external) {
56
56
  }
57
57
 
58
58
  /**
59
- * Generate contract ACI object with predefined js methods for contract usage - can be used for creating a reference to already deployed contracts
59
+ * Generate contract ACI object with predefined js methods for contract usage - can be used for
60
+ * creating a reference to already deployed contracts
60
61
  * @alias module:@aeternity/aepp-sdk/es/contract/aci
61
62
  * @param {Object} [options={}] Options object
62
63
  * @param {String} [options.source] Contract source code
@@ -69,10 +70,13 @@ function getFunctionACI (aci, name, external) {
69
70
  * @example
70
71
  * const contractIns = await client.getContractInstance({ source })
71
72
  * await contractIns.deploy([321]) or await contractIns.methods.init(321)
72
- * const callResult = await contractIns.call('setState', [123]) or await contractIns.methods.setState.send(123, options)
73
- * const staticCallResult = await contractIns.call('setState', [123], { callStatic: true }) or await contractIns.methods.setState.get(123, options)
73
+ * const callResult = await contractIns.call('setState', [123]) or
74
+ * await contractIns.methods.setState.send(123, options)
75
+ * const staticCallResult = await contractIns.call('setState', [123], { callStatic: true }) or
76
+ * await contractIns.methods.setState.get(123, options)
74
77
  * Also you can call contract like: await contractIns.methods.setState(123, options)
75
- * Then sdk decide to make on-chain or static call(dry-run API) transaction based on function is stateful or not
78
+ * Then sdk decide to make on-chain or static call(dry-run API) transaction based on function is
79
+ * stateful or not
76
80
  */
77
81
  export default async function getContractInstance ({
78
82
  source,
@@ -86,7 +90,7 @@ export default async function getContractInstance ({
86
90
  aci = aci || (source && await this.contractGetACI(source, { filesystem }))
87
91
  if (!aci) throw new Error('Either ACI or source code is required')
88
92
  contractAddress = contractAddress && await this.resolveName(
89
- contractAddress, 'ct', { resolveByNode: true }
93
+ contractAddress, 'contract_pubkey', { resolveByNode: true }
90
94
  )
91
95
  if (!contractAddress && !source && !bytecode) throw new Error('Can\'t create instance by ACI without address')
92
96
 
@@ -100,7 +104,7 @@ export default async function getContractInstance ({
100
104
  interface: R.defaultTo(null, R.prop('interface', aci)),
101
105
  aci: R.defaultTo(null, R.path(['encoded_aci', 'contract'], aci)),
102
106
  calldata: new Calldata([aci.encoded_aci, ...aci.external_encoded_aci]),
103
- externalAci: aci.external_encoded_aci ? aci.external_encoded_aci.map(a => a.contract || a.namespace) : [],
107
+ externalAci: (aci.external_encoded_aci ?? []).map(a => a.contract || a.namespace),
104
108
  source,
105
109
  bytecode,
106
110
  deployInfo: { address: contractAddress },
@@ -131,7 +135,9 @@ export default async function getContractInstance ({
131
135
  instance.compile = async (options = {}) => {
132
136
  if (instance.bytecode) throw new Error('Contract already compiled')
133
137
  if (!instance.source) throw new Error('Can\'t compile without source code')
134
- const { bytecode } = await this.contractCompile(instance.source, { ...instance.options, ...options })
138
+ const { bytecode } = await this.contractCompile(
139
+ instance.source, { ...instance.options, ...options }
140
+ )
135
141
  instance.bytecode = bytecode
136
142
  return instance.bytecode
137
143
  }
@@ -279,7 +285,8 @@ export default async function getContractInstance ({
279
285
  /**
280
286
  * Generate proto function based on contract function using Contract ACI schema
281
287
  * All function can be called like:
282
- * 'await contract.methods.testFunction()' -> then sdk will decide to use dry-run or send tx on-chain base on if function stateful or not.
288
+ * 'await contract.methods.testFunction()' -> then sdk will decide to use dry-run or send tx
289
+ * on-chain base on if function stateful or not.
283
290
  * Also you can manually do that:
284
291
  * `await contract.methods.testFunction.get()` -> use call-static(dry-run)
285
292
  * `await contract.methods.testFunction.send()` -> send tx on-chain
@@ -149,7 +149,9 @@ export default AsyncInit.compose(ContractBase, {
149
149
  * @param {Object} [options.filesystem={}] Contract external namespaces map
150
150
  * @return {Promise<String>} Result object
151
151
  * @example
152
- * const decodedData = await sdk.contractDecodeCallResultAPI(SourceCode ,'functionName', 'cb_asdasdasd...', 'ok|revert')lt
152
+ * const decodedData = await sdk.contractDecodeCallResultAPI(
153
+ * SourceCode ,'functionName', 'cb_asdasdasd...', 'ok|revert'
154
+ * )
153
155
  */
154
156
  contractDecodeCallResultAPI (source, fn, callValue, callResult, options) {
155
157
  this._ensureCompilerReady()
@@ -172,7 +174,9 @@ export default AsyncInit.compose(ContractBase, {
172
174
  },
173
175
  getFateAssembler (bytecode, options) {
174
176
  this._ensureCompilerReady()
175
- return this._compilerApi.getFateAssemblerCode({ bytecode, options: this._prepareCompilerOptions(options) })
177
+ return this._compilerApi.getFateAssemblerCode(
178
+ { bytecode, options: this._prepareCompilerOptions(options) }
179
+ )
176
180
  },
177
181
  getBytecodeCompilerVersion (bytecode, options) {
178
182
  this._ensureCompilerReady()
@@ -8,8 +8,10 @@ export const prepareGaParams = (ins) => async (authData, authFnName) => {
8
8
  if (authData.callData) {
9
9
  if (authData.callData.split('_')[0] !== 'cb') throw new Error('Auth data must be a string with "cb" prefix.')
10
10
  return { authCallData: authData.callData, gas }
11
- } else {
12
- if (!authData.source || !authData.args) throw new Error('Auth data must contain source code and arguments.')
13
- return { authCallData: await ins.contractEncodeCallDataAPI(authData.source, authFnName, authData.args), gas }
11
+ }
12
+ if (!authData.source || !authData.args) throw new Error('Auth data must contain source code and arguments.')
13
+ return {
14
+ authCallData: await ins.contractEncodeCallDataAPI(authData.source, authFnName, authData.args),
15
+ gas
14
16
  }
15
17
  }
@@ -45,7 +45,9 @@ import { hash } from '../../utils/crypto'
45
45
  * const callData = 'cb_...' // encoded call data for auth contract
46
46
  * await client.spend(10000, receiverPub, { authData: { callData } })
47
47
  * // or
48
- * await client.spend(10000, receiverPub, { authData: { source: authContract, args: [...authContractArgs] } }) // sdk will prepare callData itself
48
+ * await client.spend(10000, receiverPub, {
49
+ * authData: { source: authContract, args: [...authContractArgs] }
50
+ * }) // sdk will prepare callData itself
49
51
  */
50
52
  export const GeneralizeAccount = ContractAPI.compose({
51
53
  methods: {
@@ -76,7 +78,9 @@ async function isGA (address) {
76
78
  * @param {String} source - Auth contract source code
77
79
  * @param {Array} [args] - init arguments
78
80
  * @param {Object} [options] - Options
79
- * @return {Promise<Readonly<{result: *, owner: *, createdAt: Date, address, rawTx: *, transaction: *}>>}
81
+ * @return {Promise<Readonly<{
82
+ * result: *, owner: *, createdAt: Date, address, rawTx: *, transaction: *
83
+ * }>>}
80
84
  */
81
85
  async function createGeneralizeAccount (authFnName, source, args = [], options = {}) {
82
86
  const opt = { ...this.Ae.defaults, ...options }
@@ -85,7 +85,9 @@ const ContractBase = stampit(required({
85
85
  * @instance
86
86
  * @abstract
87
87
  * @category async
88
- * @rtype (source: String, fn: String, callValue: String, callResult: String, options: Array) => decodedResult: Promise[String]
88
+ * @rtype (
89
+ * source: String, fn: String, callValue: String, callResult: String, options: Array
90
+ * ) => decodedResult: Promise[String]
89
91
  * @param {String} source - Contract source
90
92
  * @param {String} fn - Fn name
91
93
  * @param {String} callValue - result data (cb_das...)
@@ -101,7 +103,9 @@ const ContractBase = stampit(required({
101
103
  * @instance
102
104
  * @abstract
103
105
  * @category async
104
- * @rtype (source: String, function: String, callData: String, options: Array) => decodedResult: Promise[String]
106
+ * @rtype (
107
+ * source: String, function: String, callData: String, options: Array
108
+ * ) => decodedResult: Promise[String]
105
109
  * @param {String} source - contract source
106
110
  * @param {String} function - function name
107
111
  * @param {String} callData - Encoded contract call data
package/src/index.js CHANGED
@@ -54,6 +54,8 @@ export { default as WalletDetector } from './utils/aepp-wallet-communication/wal
54
54
  export { default as BrowserRuntimeConnection } from './utils/aepp-wallet-communication/connection/browser-runtime'
55
55
  export { default as BrowserWindowMessageConnection } from './utils/aepp-wallet-communication/connection/browser-window-message'
56
56
 
57
+ export const getDefaultPointerKey = TxBuilderHelper.getDefaultPointerKey
58
+
57
59
  export {
58
60
  AmountFormatter,
59
61
  AccountBase,
@@ -51,7 +51,8 @@ export default stampit({
51
51
  * @param {Boolean} select - Select this node as current
52
52
  * @return {void}
53
53
  * @example
54
- * nodePool.addNode('testNode', awaitNode({ url, internalUrl }), true) // add and select new node with name 'testNode'
54
+ * // add and select new node with name 'testNode'
55
+ * nodePool.addNode('testNode', awaitNode({ url, internalUrl }), true)
55
56
  */
56
57
  addNode (name, node, select = false) {
57
58
  if (this.pool.has(name)) throw new Error(`Node with name ${name} already exist`)
@@ -140,7 +141,8 @@ export default stampit({
140
141
  }))
141
142
  },
142
143
  validateNodes (nodes) {
143
- // TODO: validate it on TypeScript level instead (to speedup development, save runtime resources)
144
+ // TODO: validate it on TypeScript level instead
145
+ // (to speedup development, save runtime resources)
144
146
  if (!Array.isArray(nodes)) throw new Error('"nodes" should be an array')
145
147
  const notObject = nodes.map(n => typeof n).find(t => t !== 'object')
146
148
  if (notObject) throw new Error(`Each node should be an object, got ${notObject} instead`)
package/src/node.js CHANGED
@@ -34,9 +34,10 @@ import semverSatisfies from './utils/semver-satisfies'
34
34
  * @return {String} NetworkId
35
35
  */
36
36
  export function getNetworkId ({ networkId, force = false } = {}) {
37
- if (!force && !networkId && !this.networkId && (!this.selectedNode || !this.selectedNode.networkId)) throw new Error('networkId is not provided')
38
- if (force && !networkId && !this.networkId && (!this.selectedNode || !this.selectedNode.networkId)) return null
39
- return networkId || this.networkId || this.selectedNode.networkId
37
+ const res = networkId || this.networkId || this.selectedNode?.networkId
38
+ if (!force && !res) throw new Error('networkId is not provided')
39
+ if (force && !res) return null
40
+ return res
40
41
  }
41
42
 
42
43
  /**
@@ -47,7 +48,9 @@ export function getNetworkId ({ networkId, force = false } = {}) {
47
48
  * @param {Object} [options={}] - Options
48
49
  * @param {String} options.url - Base URL for Node
49
50
  * @param {String} options.internalUrl - Base URL for internal requests
50
- * @param {String} options.axiosConfig - Object with axios configuration. Example { config: {}, errorHandler: (err) => throw err }
51
+ * @param {Object} options.axiosConfig - Object with axios configuration
52
+ * @param {Object} options.axiosConfig.config
53
+ * @param {Function} options.axiosConfig.errorHandler - (err) => throw err
51
54
  * @return {Object} Node client
52
55
  * @example Node({url: 'https://testnet.aeternity.io'})
53
56
  */
@@ -18,7 +18,7 @@ import {
18
18
  NAME_FEE_BID_INCREMENT,
19
19
  NAME_BID_TIMEOUTS,
20
20
  NAME_MAX_LENGTH_FEE,
21
- NAME_ID_KEY
21
+ POINTER_KEY_BY_PREFIX
22
22
  } from './schema'
23
23
  import { ceil } from '../../utils/bignumber'
24
24
 
@@ -110,12 +110,13 @@ export function commitmentHash (name, salt = createSalt()) {
110
110
  * Decode data using the default encoding/decoding algorithm
111
111
  * @function
112
112
  * @alias module:@aeternity/aepp-sdk/es/tx/builder/helpers
113
- * @param {string} data An Base58check or Base64check encoded and prefixed string (ex tx_..., sg_..., ak_....)
113
+ * @param {string} data An Base58/64check encoded and prefixed string (ex tx_..., sg_..., ak_....)
114
114
  * @param {string} [requiredPrefix] Ensure that data have this prefix
115
115
  * @return {Buffer} Decoded data
116
116
  */
117
117
  export function decode (data, requiredPrefix) {
118
118
  const [prefix, payload, extra] = data.split('_')
119
+ if (!payload) throw new Error(`Encoded string missing payload: ${data}`)
119
120
  if (extra) throw new Error(`Encoded string have extra parts: ${data}`)
120
121
  if (requiredPrefix && requiredPrefix !== prefix) {
121
122
  throw new Error(`Encoded string have a wrong type: ${prefix} (expected: ${requiredPrefix})`)
@@ -145,6 +146,9 @@ export function encode (data, type) {
145
146
  * @return {Buffer} Buffer Buffer with ID tag and decoded HASh
146
147
  */
147
148
  export function writeId (hashId) {
149
+ if (typeof hashId !== 'string') {
150
+ throw new Error(`Address should be a string, got ${hashId} instead`)
151
+ }
148
152
  const prefix = hashId.slice(0, 2)
149
153
  const idTag = PREFIX_ID_TAG[prefix]
150
154
  if (!idTag) throw new Error(`Id tag for prefix ${prefix} not found.`)
@@ -191,7 +195,8 @@ export function readInt (buf = Buffer.from([])) {
191
195
  * Helper function to build pointers for name update TX
192
196
  * @function
193
197
  * @alias module:@aeternity/aepp-sdk/es/tx/builder/helpers
194
- * @param {Array} pointers - Array of pointers ([ { key: 'account_pubkey', id: 'ak_32klj5j23k23j5423l434l2j3423'} ])
198
+ * @param {Array} pointers - Array of pointers
199
+ * ([ { key: 'account_pubkey', id: 'ak_32klj5j23k23j5423l434l2j3423'} ])
195
200
  * @return {Array} Serialized pointers array
196
201
  */
197
202
  export function buildPointers (pointers) {
@@ -207,7 +212,8 @@ export function buildPointers (pointers) {
207
212
  * Helper function to read pointers from name update TX
208
213
  * @function
209
214
  * @alias module:@aeternity/aepp-sdk/es/tx/builder/helpers
210
- * @param {Array} pointers - Array of pointers ([ { key: 'account_pubkey', id: 'ak_32klj5j23k23j5423l434l2j3423'} ])
215
+ * @param {Array} pointers - Array of pointers
216
+ * ([ { key: 'account_pubkey', id: 'ak_32klj5j23k23j5423l434l2j3423'} ])
211
217
  * @return {Array} Deserialize pointer array
212
218
  */
213
219
  export function readPointers (pointers) {
@@ -249,35 +255,15 @@ export function isNameValid (name) {
249
255
  }
250
256
 
251
257
  /**
252
- * What kind of a hash is this? If it begins with 'ak_' it is an
253
- * account key, if with 'ok_' it's an oracle key.
254
- *
255
- * @param s - the hash.
256
- * returns the type, or throws an exception if type not found.
257
- */
258
- export function classify (s) {
259
- if (!s.match(/^[a-z]{2}_.+/)) {
260
- throw new Error('Not a valid hash')
261
- }
262
-
263
- const klass = s.substr(0, 2)
264
- if (klass in NAME_ID_KEY) {
265
- return NAME_ID_KEY[klass]
266
- } else {
267
- throw new Error(`Unknown class ${klass}`)
268
- }
269
- }
270
-
271
- /**
272
- * Validate name pointers array
273
- * @function
274
- * @alias module:@aeternity/aepp-sdk/es/tx/builder/helpers
275
- * @param {String[]} pointers Pointers array. Allowed values is: account(ak_), oracle(ok_), contract(ct_), channel(ch_)
276
- * @return {Boolean}
258
+ * @param identifier - account/oracle/contract address, or channel
259
+ * @returns {String} default AENS pointer key
260
+ * @throws exception when default key not defined
277
261
  */
278
- export function validatePointers (pointers = []) {
279
- return !pointers
280
- .find(p => !p || typeof p !== 'string' || !['ak', 'ok', 'ct', 'ch'].includes(p.split('_')[0]))
262
+ export function getDefaultPointerKey (identifier) {
263
+ decode(identifier)
264
+ const prefix = identifier.substr(0, 2)
265
+ return POINTER_KEY_BY_PREFIX[prefix] ||
266
+ (() => { throw new Error(`Default AENS pointer key is not defined for ${prefix} prefix`) })()
281
267
  }
282
268
 
283
269
  /**
@@ -305,7 +291,8 @@ export function computeBidFee (domain, startFee = NAME_FEE, increment = NAME_FEE
305
291
  if (!(Number(increment) === increment && increment % 1 !== 0)) throw new Error(`Increment must be float. Current increment ${increment}`)
306
292
  if (increment < NAME_FEE_BID_INCREMENT) throw new Error(`minimum increment percentage is ${NAME_FEE_BID_INCREMENT}`)
307
293
  return ceil(
308
- BigNumber(BigNumber(startFee).eq(NAME_FEE) ? getMinimumNameFee(domain) : startFee).times(BigNumber(NAME_FEE_BID_INCREMENT).plus(1))
294
+ BigNumber(BigNumber(startFee).eq(NAME_FEE) ? getMinimumNameFee(domain) : startFee)
295
+ .times(BigNumber(NAME_FEE_BID_INCREMENT).plus(1))
309
296
  )
310
297
  }
311
298
 
@@ -158,7 +158,10 @@ function validateField (value, key, type, prefix) {
158
158
  case FIELD_TYPES.amount:
159
159
  case FIELD_TYPES.int: {
160
160
  const isMinusValue = (!isNaN(value) || BigNumber.isBigNumber(value)) && BigNumber(value).lt(0)
161
- return assert((!isNaN(value) || BigNumber.isBigNumber(value)) && BigNumber(value).gte(0), { value, isMinusValue })
161
+ return assert(
162
+ (!isNaN(value) || BigNumber.isBigNumber(value)) && BigNumber(value).gte(0),
163
+ { value, isMinusValue }
164
+ )
162
165
  }
163
166
  case FIELD_TYPES.id: {
164
167
  const prefixes = Array.isArray(prefix) ? prefix : [prefix]
@@ -181,7 +184,10 @@ function validateField (value, key, type, prefix) {
181
184
  function transformParams (params, schema, { denomination } = {}) {
182
185
  params = schema
183
186
  .filter(([_, t]) => t === FIELD_TYPES.amount)
184
- .reduce((acc, [key]) => ({ ...params, [key]: formatAmount(params[key], { denomination }) }), params)
187
+ .reduce(
188
+ (acc, [key]) => ({ ...params, [key]: formatAmount(params[key], { denomination }) }),
189
+ params
190
+ )
185
191
  const schemaKeys = schema.map(([k]) => k)
186
192
  return Object
187
193
  .entries(params)
@@ -294,7 +300,9 @@ export function validateParams (params, schema, { excludeKeys = [] }) {
294
300
  return schema
295
301
  .filter(([key]) => !excludeKeys.includes(key) && key !== 'payload')
296
302
  .reduce(
297
- (acc, [key, type, prefix]) => Object.assign(acc, validateField(params[key], key, type, prefix)),
303
+ (acc, [key, type, prefix]) => Object.assign(
304
+ acc, validateField(params[key], key, type, prefix)
305
+ ),
298
306
  {}
299
307
  )
300
308
  }
@@ -306,12 +314,16 @@ export function validateParams (params, schema, { excludeKeys = [] }) {
306
314
  * @param {Object} params Object with tx params
307
315
  * @param {Array} schema Transaction schema
308
316
  * @param {Object} [options={}] options
309
- * @param {Array} [options.excludeKeys=[]] excludeKeys Array of keys to exclude for validation and build
310
- * @param {String} [options.denomination='aettos'] denomination Denomination of amounts (default: aettos)
317
+ * @param {String[]} [options.excludeKeys=[]] Array of keys to exclude for validation and build
318
+ * @param {String} [options.denomination='aettos'] Denomination of amounts
311
319
  * @throws {Error} Validation error
312
320
  * @return {Array} Array with binary fields of transaction
313
321
  */
314
- export function buildRawTx (params, schema, { excludeKeys = [], denomination = AE_AMOUNT_FORMATS.AETTOS } = {}) {
322
+ export function buildRawTx (
323
+ params,
324
+ schema,
325
+ { excludeKeys = [], denomination = AE_AMOUNT_FORMATS.AETTOS } = {}
326
+ ) {
315
327
  const filteredSchema = schema.filter(([key]) => !excludeKeys.includes(key))
316
328
 
317
329
  // Transform `amount` type fields to `aettos`
@@ -374,14 +386,25 @@ const getSchema = ({ vsn, objId, type }) => {
374
386
  * @param {Object} params Object with tx params
375
387
  * @param {String} type Transaction type
376
388
  * @param {Object} [options={}] options
377
- * @param {Object} [options.excludeKeys] excludeKeys Array of keys to exclude for validation and build
389
+ * @param {String[]} [options.excludeKeys] Array of keys to exclude for validation and build
378
390
  * @param {String} [options.prefix] Prefix of transaction
379
391
  * @throws {Error} Validation error
380
- * @return {Object} { tx, rlpEncoded, binary } Object with tx -> Base64Check transaction hash with 'tx_' prefix, rlp encoded transaction and binary transaction
392
+ * @returns {Object} object
393
+ * @returns {String} object.tx Base64Check transaction hash with 'tx_' prefix
394
+ * @returns {Buffer} object.rlpEncoded rlp encoded transaction
395
+ * @returns {Array<Buffer>} object.binary binary transaction
381
396
  */
382
- export function buildTx (params, type, { excludeKeys = [], prefix = 'tx', vsn = VSN, denomination = AE_AMOUNT_FORMATS.AETTOS } = {}) {
397
+ export function buildTx (
398
+ params,
399
+ type,
400
+ { excludeKeys = [], prefix = 'tx', vsn = VSN, denomination = AE_AMOUNT_FORMATS.AETTOS } = {}
401
+ ) {
383
402
  const [schema, tag] = getSchema({ type, vsn })
384
- const binary = buildRawTx({ ...params, VSN: vsn, tag }, schema, { excludeKeys, denomination: params.denomination || denomination }).filter(e => e !== undefined)
403
+ const binary = buildRawTx(
404
+ { ...params, VSN: vsn, tag },
405
+ schema,
406
+ { excludeKeys, denomination: params.denomination || denomination }
407
+ ).filter(e => e !== undefined)
385
408
 
386
409
  const rlpEncoded = rlpEncode(binary)
387
410
  const tx = encode(rlpEncoded, prefix)
@@ -393,10 +416,14 @@ export function buildTx (params, type, { excludeKeys = [], prefix = 'tx', vsn =
393
416
  * Unpack transaction hash
394
417
  * @function
395
418
  * @alias module:@aeternity/aepp-sdk/es/tx/builder
396
- * @param {String|Buffer} encodedTx String or RLP encoded transaction array (if fromRlpBinary flag is true)
419
+ * @param {String|Buffer} encodedTx String or RLP encoded transaction array
420
+ * (if fromRlpBinary flag is true)
397
421
  * @param {Boolean} fromRlpBinary Unpack from RLP encoded transaction (default: false)
398
422
  * @param {String} prefix - Prefix of data
399
- * @return {Object} { tx, rlpEncoded, binary } Object with tx -> Object with transaction param's, rlp encoded transaction and binary transaction
423
+ * @returns {Object} object
424
+ * @returns {Object} object.tx Object with transaction param's
425
+ * @returns {Buffer} object.rlpEncoded rlp encoded transaction
426
+ * @returns {Array<Buffer>} object.binary binary transaction
400
427
  */
401
428
  export function unpackTx (encodedTx, fromRlpBinary = false, prefix = 'tx') {
402
429
  const rlpEncoded = fromRlpBinary ? encodedTx : decode(encodedTx, prefix)
@@ -421,4 +448,13 @@ export function buildTxHash (rawTx) {
421
448
  return encode(hash(data), 'th')
422
449
  }
423
450
 
424
- export default { calculateMinFee, calculateFee, unpackTx, unpackRawTx, buildTx, buildRawTx, validateParams, buildTxHash }
451
+ export default {
452
+ calculateMinFee,
453
+ calculateFee,
454
+ unpackTx,
455
+ unpackRawTx,
456
+ buildTx,
457
+ buildRawTx,
458
+ validateParams,
459
+ buildTxHash
460
+ }
@@ -40,9 +40,10 @@ export const NAME_FEE_MULTIPLIER = 1e14 // 100000000000000
40
40
  export const NAME_FEE_BID_INCREMENT = 0.05 // # the increment is in percentage
41
41
  // # see https://github.com/aeternity/aeternity/blob/72e440b8731422e335f879a31ecbbee7ac23a1cf/apps/aecore/src/aec_governance.erl#L272
42
42
  export const NAME_BID_TIMEOUT_BLOCKS = 480 // # ~1 day
43
- export const NAME_MAX_LENGTH_FEE = 31 // # this is the max length for a domain that requires a base fee to be paid
43
+ // # this is the max length for a domain that requires a base fee to be paid
44
+ export const NAME_MAX_LENGTH_FEE = 31
44
45
  export const NAME_BID_MAX_LENGTH = 12 // # this is the max length for a domain to be part of a bid
45
- export const NAME_ID_KEY = {
46
+ export const POINTER_KEY_BY_PREFIX = {
46
47
  ak: 'account_pubkey',
47
48
  ok: 'oracle_pubkey',
48
49
  ct: 'contract_pubkey',
@@ -157,7 +158,8 @@ const OBJECT_TAG_SOPHIA_BYTE_CODE = 70
157
158
  const TX_FIELD = (name, type, prefix) => [name, type, prefix]
158
159
  const TX_SCHEMA_FIELD = (schema, objectId) => [schema, objectId]
159
160
 
160
- const revertObject = (obj) => Object.entries(obj).reduce((acc, [key, v]) => (acc[v] = key) && acc, {})
161
+ const revertObject = (obj) => Object.entries(obj)
162
+ .reduce((acc, [key, v]) => (acc[v] = key) && acc, {})
161
163
 
162
164
  /**
163
165
  * @constant
@@ -605,7 +607,8 @@ const CONTRACT_CALL_RESULT_TX = [
605
607
  TX_FIELD('gasUsed', FIELD_TYPES.int),
606
608
  TX_FIELD('returnValue', FIELD_TYPES.binary, 'cb'),
607
609
  TX_FIELD('returnType', FIELD_TYPES.callReturnType),
608
- // TODO: add serialization for <log> :: [ { <address> :: id, [ <topics> :: binary() ], <data> :: binary() } ]
610
+ // TODO: add serialization for
611
+ // <log> :: [ { <address> :: id, [ <topics> :: binary() ], <data> :: binary() } ]
609
612
  TX_FIELD('log', FIELD_TYPES.rawBinary)
610
613
  ]
611
614
 
@@ -985,19 +988,29 @@ export const TX_SERIALIZATION_SCHEMA = {
985
988
  1: TX_SCHEMA_FIELD(CHANNEL_SNAPSHOT_SOLO_TX, OBJECT_TAG_CHANNEL_SNAPSHOT_SOLO_TX)
986
989
  },
987
990
  [TX_TYPE.channelOffChainUpdateTransfer]: {
988
- 1: TX_SCHEMA_FIELD(CHANNEL_OFFCHAIN_UPDATE_TRANSFER_TX, OBJECT_TAG_CHANNEL_OFFCHAIN_UPDATE_TRANSFER_TX)
991
+ 1: TX_SCHEMA_FIELD(
992
+ CHANNEL_OFFCHAIN_UPDATE_TRANSFER_TX, OBJECT_TAG_CHANNEL_OFFCHAIN_UPDATE_TRANSFER_TX
993
+ )
989
994
  },
990
995
  [TX_TYPE.channelOffChainUpdateDeposit]: {
991
- 1: TX_SCHEMA_FIELD(CHANNEL_OFFCHAIN_UPDATE_DEPOSIT_TX, OBJECT_TAG_CHANNEL_OFFCHAIN_UPDATE_DEPOSIT_TX)
996
+ 1: TX_SCHEMA_FIELD(
997
+ CHANNEL_OFFCHAIN_UPDATE_DEPOSIT_TX, OBJECT_TAG_CHANNEL_OFFCHAIN_UPDATE_DEPOSIT_TX
998
+ )
992
999
  },
993
1000
  [TX_TYPE.channelOffChainUpdateWithdrawal]: {
994
- 1: TX_SCHEMA_FIELD(CHANNEL_OFFCHAIN_UPDATE_WITHDRAWAL_TX, OBJECT_TAG_CHANNEL_OFFCHAIN_UPDATE_WITHDRAWAL_TX)
1001
+ 1: TX_SCHEMA_FIELD(
1002
+ CHANNEL_OFFCHAIN_UPDATE_WITHDRAWAL_TX, OBJECT_TAG_CHANNEL_OFFCHAIN_UPDATE_WITHDRAWAL_TX
1003
+ )
995
1004
  },
996
1005
  [TX_TYPE.channelOffChainCreateContract]: {
997
- 1: TX_SCHEMA_FIELD(CHANNEL_OFFCHAIN_CREATE_CONTRACT_TX, OBJECT_TAG_CHANNEL_OFFCHAIN_CREATE_CONTRACT_TX)
1006
+ 1: TX_SCHEMA_FIELD(
1007
+ CHANNEL_OFFCHAIN_CREATE_CONTRACT_TX, OBJECT_TAG_CHANNEL_OFFCHAIN_CREATE_CONTRACT_TX
1008
+ )
998
1009
  },
999
1010
  [TX_TYPE.channelOffChainCallContract]: {
1000
- 1: TX_SCHEMA_FIELD(CHANNEL_OFFCHAIN_CALL_CONTRACT_TX, OBJECT_TAG_CHANNEL_OFFCHAIN_CALL_CONTRACT_TX)
1011
+ 1: TX_SCHEMA_FIELD(
1012
+ CHANNEL_OFFCHAIN_CALL_CONTRACT_TX, OBJECT_TAG_CHANNEL_OFFCHAIN_CALL_CONTRACT_TX
1013
+ )
1001
1014
  },
1002
1015
  [TX_TYPE.channelReconnect]: {
1003
1016
  1: TX_SCHEMA_FIELD(CHANNEL_RECONNECT_TX, OBJECT_TAG_CHANNEL_RECONNECT_TX)
@@ -1123,19 +1136,29 @@ export const TX_DESERIALIZATION_SCHEMA = {
1123
1136
  1: TX_SCHEMA_FIELD(CHANNEL_SNAPSHOT_SOLO_TX, OBJECT_TAG_CHANNEL_SNAPSHOT_SOLO_TX)
1124
1137
  },
1125
1138
  [OBJECT_TAG_CHANNEL_OFFCHAIN_UPDATE_TRANSFER_TX]: {
1126
- 1: TX_SCHEMA_FIELD(CHANNEL_OFFCHAIN_UPDATE_TRANSFER_TX, OBJECT_TAG_CHANNEL_OFFCHAIN_UPDATE_TRANSFER_TX)
1139
+ 1: TX_SCHEMA_FIELD(
1140
+ CHANNEL_OFFCHAIN_UPDATE_TRANSFER_TX, OBJECT_TAG_CHANNEL_OFFCHAIN_UPDATE_TRANSFER_TX
1141
+ )
1127
1142
  },
1128
1143
  [OBJECT_TAG_CHANNEL_OFFCHAIN_UPDATE_DEPOSIT_TX]: {
1129
- 1: TX_SCHEMA_FIELD(CHANNEL_OFFCHAIN_UPDATE_DEPOSIT_TX, OBJECT_TAG_CHANNEL_OFFCHAIN_UPDATE_DEPOSIT_TX)
1144
+ 1: TX_SCHEMA_FIELD(
1145
+ CHANNEL_OFFCHAIN_UPDATE_DEPOSIT_TX, OBJECT_TAG_CHANNEL_OFFCHAIN_UPDATE_DEPOSIT_TX
1146
+ )
1130
1147
  },
1131
1148
  [OBJECT_TAG_CHANNEL_OFFCHAIN_UPDATE_WITHDRAWAL_TX]: {
1132
- 1: TX_SCHEMA_FIELD(CHANNEL_OFFCHAIN_UPDATE_WITHDRAWAL_TX, OBJECT_TAG_CHANNEL_OFFCHAIN_UPDATE_WITHDRAWAL_TX)
1149
+ 1: TX_SCHEMA_FIELD(
1150
+ CHANNEL_OFFCHAIN_UPDATE_WITHDRAWAL_TX, OBJECT_TAG_CHANNEL_OFFCHAIN_UPDATE_WITHDRAWAL_TX
1151
+ )
1133
1152
  },
1134
1153
  [OBJECT_TAG_CHANNEL_OFFCHAIN_CREATE_CONTRACT_TX]: {
1135
- 1: TX_SCHEMA_FIELD(CHANNEL_OFFCHAIN_CREATE_CONTRACT_TX, OBJECT_TAG_CHANNEL_OFFCHAIN_CREATE_CONTRACT_TX)
1154
+ 1: TX_SCHEMA_FIELD(
1155
+ CHANNEL_OFFCHAIN_CREATE_CONTRACT_TX, OBJECT_TAG_CHANNEL_OFFCHAIN_CREATE_CONTRACT_TX
1156
+ )
1136
1157
  },
1137
1158
  [OBJECT_TAG_CHANNEL_OFFCHAIN_CALL_CONTRACT_TX]: {
1138
- 1: TX_SCHEMA_FIELD(CHANNEL_OFFCHAIN_CALL_CONTRACT_TX, OBJECT_TAG_CHANNEL_OFFCHAIN_CALL_CONTRACT_TX)
1159
+ 1: TX_SCHEMA_FIELD(
1160
+ CHANNEL_OFFCHAIN_CALL_CONTRACT_TX, OBJECT_TAG_CHANNEL_OFFCHAIN_CALL_CONTRACT_TX
1161
+ )
1139
1162
  },
1140
1163
  [OBJECT_TAG_CHANNEL_RECONNECT_TX]: {
1141
1164
  1: TX_SCHEMA_FIELD(CHANNEL_RECONNECT_TX, OBJECT_TAG_CHANNEL_RECONNECT_TX)