@aeternity/aepp-sdk 8.2.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 (159) hide show
  1. package/CHANGELOG.md +216 -337
  2. package/README.md +16 -9
  3. package/dist/aepp-sdk.browser-script.js +1 -1
  4. package/dist/aepp-sdk.browser-script.js.LICENSE.txt +0 -9
  5. package/dist/aepp-sdk.browser-script.js.map +1 -1
  6. package/dist/aepp-sdk.browser.js +1 -1
  7. package/dist/aepp-sdk.browser.js.map +1 -1
  8. package/dist/aepp-sdk.js +1 -1
  9. package/dist/aepp-sdk.js.map +1 -1
  10. package/es/account/base.js +36 -120
  11. package/es/account/base.js.map +1 -1
  12. package/es/account/memory.js +17 -19
  13. package/es/account/memory.js.map +1 -1
  14. package/es/account/multiple.js +79 -156
  15. package/es/account/multiple.js.map +1 -1
  16. package/es/ae/aens.js +205 -626
  17. package/es/ae/aens.js.map +1 -1
  18. package/es/ae/contract.js +114 -918
  19. package/es/ae/contract.js.map +1 -1
  20. package/es/ae/index.js +90 -250
  21. package/es/ae/index.js.map +1 -1
  22. package/es/ae/oracle.js +136 -504
  23. package/es/ae/oracle.js.map +1 -1
  24. package/es/ae/universal.js.map +1 -1
  25. package/es/chain/index.js +12 -27
  26. package/es/chain/index.js.map +1 -1
  27. package/es/chain/node.js +289 -1020
  28. package/es/chain/node.js.map +1 -1
  29. package/es/channel/handlers.js +597 -1086
  30. package/es/channel/handlers.js.map +1 -1
  31. package/es/channel/index.js +238 -465
  32. package/es/channel/index.js.map +1 -1
  33. package/es/channel/internal.js +129 -301
  34. package/es/channel/internal.js.map +1 -1
  35. package/es/contract/aci/index.js +328 -495
  36. package/es/contract/aci/index.js.map +1 -1
  37. package/es/contract/aci/transformation.js +35 -711
  38. package/es/contract/aci/transformation.js.map +1 -1
  39. package/es/contract/compiler.js +131 -203
  40. package/es/contract/compiler.js.map +1 -1
  41. package/es/contract/ga/helpers.js +17 -122
  42. package/es/contract/ga/helpers.js.map +1 -1
  43. package/es/contract/ga/index.js +108 -249
  44. package/es/contract/ga/index.js.map +1 -1
  45. package/es/contract/index.js +7 -3
  46. package/es/contract/index.js.map +1 -1
  47. package/es/index.js +3 -3
  48. package/es/index.js.map +1 -1
  49. package/es/node-pool/index.js +57 -74
  50. package/es/node-pool/index.js.map +1 -1
  51. package/es/node.js +65 -161
  52. package/es/node.js.map +1 -1
  53. package/es/other.d.ts +1 -1
  54. package/es/tx/builder/helpers.js +62 -115
  55. package/es/tx/builder/helpers.js.map +1 -1
  56. package/es/tx/builder/index.js +218 -309
  57. package/es/tx/builder/index.js.map +1 -1
  58. package/es/tx/builder/schema.js +586 -573
  59. package/es/tx/builder/schema.js.map +1 -1
  60. package/es/tx/index.js +102 -13
  61. package/es/tx/index.js.map +1 -1
  62. package/es/tx/tx-object.js +114 -138
  63. package/es/tx/tx-object.js.map +1 -1
  64. package/es/tx/tx.js +810 -1586
  65. package/es/tx/tx.js.map +1 -1
  66. package/es/tx/validator.js +191 -426
  67. package/es/tx/validator.js.map +1 -1
  68. package/es/utils/aepp-wallet-communication/connection/browser-runtime.js +20 -23
  69. package/es/utils/aepp-wallet-communication/connection/browser-runtime.js.map +1 -1
  70. package/es/utils/aepp-wallet-communication/connection/browser-window-message.js +53 -80
  71. package/es/utils/aepp-wallet-communication/connection/browser-window-message.js.map +1 -1
  72. package/es/utils/aepp-wallet-communication/connection/index.js +2 -1
  73. package/es/utils/aepp-wallet-communication/connection/index.js.map +1 -1
  74. package/es/utils/aepp-wallet-communication/content-script-bridge.js +24 -19
  75. package/es/utils/aepp-wallet-communication/content-script-bridge.js.map +1 -1
  76. package/es/utils/aepp-wallet-communication/helpers.js +60 -105
  77. package/es/utils/aepp-wallet-communication/helpers.js.map +1 -1
  78. package/es/utils/aepp-wallet-communication/rpc/aepp-rpc.js +191 -514
  79. package/es/utils/aepp-wallet-communication/rpc/aepp-rpc.js.map +1 -1
  80. package/es/utils/aepp-wallet-communication/rpc/rpc-client.js +78 -93
  81. package/es/utils/aepp-wallet-communication/rpc/rpc-client.js.map +1 -1
  82. package/es/utils/aepp-wallet-communication/rpc/wallet-rpc.js +381 -613
  83. package/es/utils/aepp-wallet-communication/rpc/wallet-rpc.js.map +1 -1
  84. package/es/utils/aepp-wallet-communication/schema.js +43 -39
  85. package/es/utils/aepp-wallet-communication/schema.js.map +1 -1
  86. package/es/utils/aepp-wallet-communication/wallet-detector.js +32 -58
  87. package/es/utils/aepp-wallet-communication/wallet-detector.js.map +1 -1
  88. package/es/utils/amount-formatter.js +41 -61
  89. package/es/utils/amount-formatter.js.map +1 -1
  90. package/es/utils/async-init.js +28 -64
  91. package/es/utils/async-init.js.map +1 -1
  92. package/es/utils/bignumber.js +3 -11
  93. package/es/utils/bignumber.js.map +1 -1
  94. package/es/utils/bytes.js +5 -9
  95. package/es/utils/bytes.js.map +1 -1
  96. package/es/utils/crypto.js +41 -106
  97. package/es/utils/crypto.js.map +1 -1
  98. package/es/utils/hd-wallet.js +45 -81
  99. package/es/utils/hd-wallet.js.map +1 -1
  100. package/es/utils/json-big.js +16 -49
  101. package/es/utils/json-big.js.map +1 -1
  102. package/es/utils/keystore.js +81 -246
  103. package/es/utils/keystore.js.map +1 -1
  104. package/es/utils/mptree.js +88 -134
  105. package/es/utils/mptree.js.map +1 -1
  106. package/es/utils/other.js +10 -60
  107. package/es/utils/other.js.map +1 -1
  108. package/es/utils/semver-satisfies.js +9 -28
  109. package/es/utils/semver-satisfies.js.map +1 -1
  110. package/es/utils/string.js +4 -13
  111. package/es/utils/string.js.map +1 -1
  112. package/es/utils/swagger.js +87 -224
  113. package/es/utils/swagger.js.map +1 -1
  114. package/package.json +51 -44
  115. package/src/account/base.js +11 -10
  116. package/src/account/multiple.js +24 -18
  117. package/src/ae/aens.js +64 -61
  118. package/src/ae/contract.js +71 -248
  119. package/src/ae/index.js +34 -9
  120. package/src/ae/oracle.js +30 -22
  121. package/src/ae/universal.js +3 -1
  122. package/src/chain/index.js +10 -16
  123. package/src/chain/node.js +38 -38
  124. package/src/channel/handlers.js +10 -4
  125. package/src/channel/index.js +44 -20
  126. package/src/contract/aci/index.js +234 -112
  127. package/src/contract/aci/transformation.js +30 -422
  128. package/src/contract/compiler.js +50 -5
  129. package/src/contract/ga/helpers.js +6 -14
  130. package/src/contract/ga/index.js +28 -28
  131. package/src/contract/index.js +6 -2
  132. package/src/index.js +4 -4
  133. package/src/node-pool/index.js +24 -13
  134. package/src/node.js +29 -30
  135. package/src/tx/builder/helpers.js +31 -56
  136. package/src/tx/builder/index.js +67 -28
  137. package/src/tx/builder/schema.js +79 -121
  138. package/src/tx/index.js +101 -12
  139. package/src/tx/tx-object.js +25 -8
  140. package/src/tx/tx.js +229 -150
  141. package/src/tx/validator.js +134 -202
  142. package/src/utils/aepp-wallet-communication/connection/browser-runtime.js +3 -2
  143. package/src/utils/aepp-wallet-communication/connection/browser-window-message.js +25 -7
  144. package/src/utils/aepp-wallet-communication/connection/index.js +2 -1
  145. package/src/utils/aepp-wallet-communication/content-script-bridge.js +10 -4
  146. package/src/utils/aepp-wallet-communication/helpers.js +4 -2
  147. package/src/utils/aepp-wallet-communication/rpc/aepp-rpc.js +33 -12
  148. package/src/utils/aepp-wallet-communication/rpc/rpc-client.js +9 -5
  149. package/src/utils/aepp-wallet-communication/rpc/wallet-rpc.js +59 -29
  150. package/src/utils/aepp-wallet-communication/schema.js +1 -3
  151. package/src/utils/aepp-wallet-communication/wallet-detector.js +4 -1
  152. package/src/utils/amount-formatter.ts +1 -1
  153. package/src/utils/bignumber.ts +2 -1
  154. package/src/utils/crypto.js +4 -68
  155. package/src/utils/keystore.js +10 -2
  156. package/src/utils/other.ts +1 -1
  157. package/src/utils/semver-satisfies.ts +1 -1
  158. package/src/utils/swagger.js +22 -10
  159. package/src/contract/aci/helpers.js +0 -140
@@ -1,443 +1,208 @@
1
- import _Object$keys from "@babel/runtime-corejs3/core-js-stable/object/keys";
2
- import _Object$getOwnPropertySymbols from "@babel/runtime-corejs3/core-js-stable/object/get-own-property-symbols";
3
- import _filterInstanceProperty from "@babel/runtime-corejs3/core-js-stable/instance/filter";
4
- import _Object$getOwnPropertyDescriptor from "@babel/runtime-corejs3/core-js-stable/object/get-own-property-descriptor";
5
- import _forEachInstanceProperty from "@babel/runtime-corejs3/core-js-stable/instance/for-each";
6
- import _Object$getOwnPropertyDescriptors from "@babel/runtime-corejs3/core-js-stable/object/get-own-property-descriptors";
7
- import _Object$defineProperties from "@babel/runtime-corejs3/core-js-stable/object/define-properties";
8
- import _Object$defineProperty from "@babel/runtime-corejs3/core-js-stable/object/define-property";
9
- import _defineProperty from "@babel/runtime-corejs3/helpers/defineProperty";
10
- import _asyncToGenerator from "@babel/runtime-corejs3/helpers/asyncToGenerator";
11
- import _toConsumableArray from "@babel/runtime-corejs3/helpers/toConsumableArray";
12
- import _slicedToArray from "@babel/runtime-corejs3/helpers/slicedToArray";
13
- import _regeneratorRuntime from "@babel/runtime-corejs3/regenerator";
14
-
15
- function ownKeys(object, enumerableOnly) { var keys = _Object$keys(object); if (_Object$getOwnPropertySymbols) { var symbols = _Object$getOwnPropertySymbols(object); if (enumerableOnly) { symbols = _filterInstanceProperty(symbols).call(symbols, function (sym) { return _Object$getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; }
16
-
17
- function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { var _context11; _forEachInstanceProperty(_context11 = ownKeys(Object(source), true)).call(_context11, function (key) { _defineProperty(target, key, source[key]); }); } else if (_Object$getOwnPropertyDescriptors) { _Object$defineProperties(target, _Object$getOwnPropertyDescriptors(source)); } else { var _context12; _forEachInstanceProperty(_context12 = ownKeys(Object(source))).call(_context12, function (key) { _Object$defineProperty(target, key, _Object$getOwnPropertyDescriptor(source, key)); }); } } return target; }
18
-
19
- import _concatInstanceProperty from "@babel/runtime-corejs3/core-js-stable/instance/concat";
20
- import _includesInstanceProperty from "@babel/runtime-corejs3/core-js-stable/instance/includes";
21
- import _reduceInstanceProperty from "@babel/runtime-corejs3/core-js-stable/instance/reduce";
22
- import _Object$entries from "@babel/runtime-corejs3/core-js-stable/object/entries";
23
- import _parseInt from "@babel/runtime-corejs3/core-js-stable/parse-int";
24
- import _findInstanceProperty from "@babel/runtime-corejs3/core-js-stable/instance/find";
25
- import _mapInstanceProperty from "@babel/runtime-corejs3/core-js-stable/instance/map";
26
- import { verify, decodeBase58Check, assertedType } from '../utils/crypto';
27
- import { encode } from '../tx/builder/helpers';
1
+ import { verify, hash } from '../utils/crypto';
2
+ import { encode, decode } from './builder/helpers';
28
3
  import BigNumber from 'bignumber.js';
29
- import { BASE_VERIFICATION_SCHEMA, CONTRACT_VERIFICATION_SCHEMA, MIN_GAS_PRICE, NAME_CLAIM_VERIFICATION_SCHEMA, OBJECT_ID_TX_TYPE, OBJECT_TAG_SIGNED_TRANSACTION, PROTOCOL_VM_ABI, SIGNATURE_VERIFICATION_SCHEMA, TX_TYPE } from './builder/schema';
30
- import { buildTxHash, calculateFee, unpackTx } from './builder';
31
- import NodePool from '../node-pool';
4
+ import { MIN_GAS_PRICE, PROTOCOL_VM_ABI, TX_TYPE } from './builder/schema';
5
+ import { calculateFee, unpackTx } from './builder';
32
6
  /**
33
7
  * Transaction validator
34
8
  * @module @aeternity/aepp-sdk/es/tx/validator
35
- * @export TransactionValidator
36
- * @example import { TransactionValidator } from '@aeternity/aepp-sdk'
9
+ * @export verifyTransaction
10
+ * @example import { verifyTransaction } from '@aeternity/aepp-sdk'
37
11
  */
38
12
 
39
- var VALIDATORS = {
40
- // VALIDATE SIGNATURE
41
- signature: function signature(_ref) {
42
- var rlpEncoded = _ref.rlpEncoded,
43
- signature = _ref.signature,
44
- ownerPublicKey = _ref.ownerPublicKey,
45
- _ref$networkId = _ref.networkId,
46
- networkId = _ref$networkId === void 0 ? 'ae_mainnet' : _ref$networkId;
47
-
48
- var txWithNetworkId = _concatInstanceProperty(Buffer).call(Buffer, [Buffer.from(networkId), rlpEncoded]);
49
-
50
- var txHashWithNetworkId = _concatInstanceProperty(Buffer).call(Buffer, [Buffer.from(networkId), buildTxHash(rlpEncoded, {
51
- raw: true
52
- })]);
53
-
54
- var decodedPub = decodeBase58Check(assertedType(ownerPublicKey, 'ak'));
55
- return verify(txWithNetworkId, signature, decodedPub) || verify(txHashWithNetworkId, signature, decodedPub);
56
- },
57
- // VALIDATE IF ENOUGH FEE
58
- insufficientFee: function insufficientFee(_ref2) {
59
- var minFee = _ref2.minFee,
60
- fee = _ref2.fee;
61
- return BigNumber(minFee).lte(BigNumber(fee));
62
- },
63
- // VALIDATE IF TTL VALID
64
- expiredTTL: function expiredTTL(_ref3) {
65
- var ttl = _ref3.ttl,
66
- height = _ref3.height;
67
- return BigNumber(ttl).eq(0) || BigNumber(ttl).gte(BigNumber(height));
68
- },
69
- // Insufficient Balance for Amount plus Fee
70
- insufficientBalanceForAmountFee: function insufficientBalanceForAmountFee(_ref4) {
71
- var balance = _ref4.balance,
72
- _ref4$amount = _ref4.amount,
73
- amount = _ref4$amount === void 0 ? 0 : _ref4$amount,
74
- fee = _ref4.fee;
75
- return BigNumber(balance).gte(BigNumber(amount).plus(fee));
76
- },
77
- // Insufficient Balance for Amount
78
- insufficientBalanceForAmount: function insufficientBalanceForAmount(_ref5) {
79
- var balance = _ref5.balance,
80
- _ref5$amount = _ref5.amount,
81
- amount = _ref5$amount === void 0 ? 0 : _ref5$amount;
82
- return BigNumber(balance).gte(BigNumber(amount));
83
- },
84
- // IF NONCE USED
85
- nonceUsed: function nonceUsed(_ref6) {
86
- var accountNonce = _ref6.accountNonce,
87
- nonce = _ref6.nonce;
88
- return BigNumber(nonce).gt(BigNumber(accountNonce));
89
- },
90
- // IF NONCE TO HIGH
91
- nonceHigh: function nonceHigh(_ref7) {
92
- var accountNonce = _ref7.accountNonce,
93
- nonce = _ref7.nonce;
94
- return !BigNumber(nonce).gt(BigNumber(accountNonce).plus(1));
95
- },
96
- minGasPrice: function minGasPrice(_ref8) {
97
- var gasPrice = _ref8.gasPrice;
98
- return isNaN(gasPrice) || BigNumber(gasPrice).gte(BigNumber(MIN_GAS_PRICE));
99
- },
100
- // VM/ABI version validation based on consensus protocol version
101
- vmAndAbiVersion: function vmAndAbiVersion(_ref9) {
102
- var _context, _context2;
103
-
104
- var ctVersion = _ref9.ctVersion,
105
- abiVersion = _ref9.abiVersion,
106
- consensusProtocolVersion = _ref9.consensusProtocolVersion,
107
- txType = _ref9.txType;
108
- // If not contract tx
109
- if (!ctVersion) ctVersion = {
110
- abiVersion: abiVersion
111
- };
112
- var supportedProtocol = PROTOCOL_VM_ABI[consensusProtocolVersion]; // If protocol not implemented
113
-
114
- if (!supportedProtocol) return true; // If protocol for tx type not implemented
115
-
116
- var txProtocol = supportedProtocol[txType];
117
- return !_includesInstanceProperty(_context = _reduceInstanceProperty(_context2 = _Object$entries(ctVersion)).call(_context2, function (acc, _ref10) {
118
- var _context3, _context4;
119
-
120
- var _ref11 = _slicedToArray(_ref10, 2),
121
- key = _ref11[0],
122
- value = _ref11[1];
123
-
124
- return _concatInstanceProperty(_context3 = []).call(_context3, _toConsumableArray(acc), [value === undefined ? true : _includesInstanceProperty(_context4 = txProtocol[key]).call(_context4, _parseInt(value))]);
125
- }, [])).call(_context, false);
126
- },
127
- insufficientBalanceForFeeNameFee: function insufficientBalanceForFeeNameFee(_ref12) {
128
- var nameFee = _ref12.nameFee,
129
- fee = _ref12.fee,
130
- balance = _ref12.balance,
131
- VSN = _ref12.VSN;
132
- return VSN === 1 || BigNumber(balance).gte(BigNumber(nameFee).plus(fee));
133
- }
134
- };
135
-
136
- var resolveDataForBase = /*#__PURE__*/function () {
137
- var _ref14 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee(chain, _ref13) {
138
- var ownerPublicKey, accountNonce, accountBalance, _yield$chain$api$getA, nonce, balance;
139
-
140
- return _regeneratorRuntime.wrap(function _callee$(_context5) {
141
- while (1) {
142
- switch (_context5.prev = _context5.next) {
143
- case 0:
144
- ownerPublicKey = _ref13.ownerPublicKey;
145
- accountNonce = 0;
146
- accountBalance = 0;
147
- _context5.prev = 3;
148
- _context5.next = 6;
149
- return chain.api.getAccountByPubkey(ownerPublicKey);
150
-
151
- case 6:
152
- _yield$chain$api$getA = _context5.sent;
153
- nonce = _yield$chain$api$getA.nonce;
154
- balance = _yield$chain$api$getA.balance;
155
- accountNonce = nonce;
156
- accountBalance = balance;
157
- _context5.next = 16;
158
- break;
159
-
160
- case 13:
161
- _context5.prev = 13;
162
- _context5.t0 = _context5["catch"](3);
163
- console.log('We can not get info about this publicKey');
164
-
165
- case 16:
166
- _context5.t1 = _objectSpread;
167
- _context5.next = 19;
168
- return chain.api.getCurrentKeyBlockHeight();
169
-
170
- case 19:
171
- _context5.t2 = _context5.sent.height;
172
- _context5.t3 = accountBalance;
173
- _context5.t4 = accountNonce;
174
- _context5.t5 = ownerPublicKey;
175
- _context5.t6 = {
176
- height: _context5.t2,
177
- balance: _context5.t3,
178
- accountNonce: _context5.t4,
179
- ownerPublicKey: _context5.t5
180
- };
181
- _context5.t7 = chain.getNodeInfo();
182
- return _context5.abrupt("return", (0, _context5.t1)(_context5.t6, _context5.t7));
183
-
184
- case 26:
185
- case "end":
186
- return _context5.stop();
187
- }
188
- }
189
- }, _callee, null, [[3, 13]]);
190
- }));
191
-
192
- return function resolveDataForBase(_x, _x2) {
193
- return _ref14.apply(this, arguments);
13
+ const validators = [async (_ref, _ref2) => {
14
+ let {
15
+ encodedTx,
16
+ signatures
17
+ } = _ref;
18
+ let {
19
+ account,
20
+ node,
21
+ parentTxTypes
22
+ } = _ref2;
23
+ if ((encodedTx ?? signatures) === undefined) return [];
24
+ if (signatures.length !== 1) return []; // TODO: Support multisignature?
25
+
26
+ const prefix = Buffer.from([node.nodeNetworkId, ...(parentTxTypes.includes(TX_TYPE.payingFor) ? ['inner_tx'] : [])].join('-'));
27
+ const txWithNetworkId = Buffer.concat([prefix, encodedTx.rlpEncoded]);
28
+ const txHashWithNetworkId = Buffer.concat([prefix, hash(encodedTx.rlpEncoded)]);
29
+ const decodedPub = decode(account.id, 'ak');
30
+ if (verify(txWithNetworkId, signatures[0], decodedPub) || verify(txHashWithNetworkId, signatures[0], decodedPub)) return [];
31
+ return [{
32
+ message: 'Signature cannot be verified, please ensure that you transaction have' + ' the correct prefix and the correct private key for the sender address',
33
+ key: 'InvalidSignature',
34
+ checkedKeys: ['encodedTx', 'signatures']
35
+ }];
36
+ }, async (_ref3, _ref4) => {
37
+ let {
38
+ encodedTx,
39
+ tx
40
+ } = _ref3;
41
+ let {
42
+ node,
43
+ parentTxTypes,
44
+ txType
45
+ } = _ref4;
46
+ if ((encodedTx ?? tx) === undefined) return [];
47
+ return verifyTransaction(encode((encodedTx ?? tx).rlpEncoded, 'tx'), node, [...parentTxTypes, txType]);
48
+ }, (tx, _ref5) => {
49
+ let {
50
+ txType
51
+ } = _ref5;
52
+ if (tx.fee === undefined) return [];
53
+ const minFee = calculateFee(0, txType, {
54
+ gas: +tx.gas || 0,
55
+ params: tx,
56
+ showWarning: false,
57
+ vsn: tx.VSN
58
+ });
59
+ if (new BigNumber(minFee).lte(tx.fee)) return [];
60
+ return [{
61
+ message: `Fee ${tx.fee} is too low, minimum fee for this transaction is ${minFee}`,
62
+ key: 'InsufficientFee',
63
+ checkedKeys: ['fee']
64
+ }];
65
+ }, (_ref6, _ref7) => {
66
+ let {
67
+ ttl
68
+ } = _ref6;
69
+ let {
70
+ height
71
+ } = _ref7;
72
+ if (ttl === undefined) return [];
73
+ ttl = +ttl;
74
+ if (ttl === 0 || ttl >= height) return [];
75
+ return [{
76
+ message: `TTL ${ttl} is already expired, current height is ${height}`,
77
+ key: 'ExpiredTTL',
78
+ checkedKeys: ['ttl']
79
+ }];
80
+ }, (_ref8, _ref9) => {
81
+ let {
82
+ amount,
83
+ fee,
84
+ nameFee,
85
+ tx
86
+ } = _ref8;
87
+ let {
88
+ account,
89
+ parentTxTypes,
90
+ txType
91
+ } = _ref9;
92
+ if ((amount ?? fee ?? nameFee) === undefined) return [];
93
+ const cost = new BigNumber(fee).plus(nameFee || 0).plus(amount || 0).plus(txType === TX_TYPE.payingFor ? tx.tx.encodedTx.tx.fee : 0).minus(parentTxTypes.includes(TX_TYPE.payingFor) ? fee : 0);
94
+ if (cost.lte(account.balance)) return [];
95
+ return [{
96
+ message: `Account balance ${account.balance} is not enough to execute the transaction that costs ${cost.toFixed()}`,
97
+ key: 'InsufficientBalance',
98
+ checkedKeys: ['amount', 'fee', 'nameFee']
99
+ }];
100
+ }, (_ref10, _ref11) => {
101
+ let {
102
+ nonce
103
+ } = _ref10;
104
+ let {
105
+ account,
106
+ parentTxTypes
107
+ } = _ref11;
108
+ if (nonce === undefined || parentTxTypes.includes(TX_TYPE.gaMeta)) return [];
109
+ nonce = +nonce;
110
+ const validNonce = account.nonce + 1;
111
+ if (nonce === validNonce) return [];
112
+ return [{ ...(nonce < validNonce ? {
113
+ message: `Nonce ${nonce} is already used, valid nonce is ${validNonce}`,
114
+ key: 'NonceAlreadyUsed'
115
+ } : {
116
+ message: `Nonce ${nonce} is too high, valid nonce is ${validNonce}`,
117
+ key: 'NonceHigh'
118
+ }),
119
+ checkedKeys: ['nonce']
120
+ }];
121
+ }, _ref12 => {
122
+ let {
123
+ gasPrice
124
+ } = _ref12;
125
+ if (gasPrice === undefined) return [];
126
+ if (gasPrice >= MIN_GAS_PRICE) return [];
127
+ return [{
128
+ message: `Gas price ${gasPrice} must be bigger then ${MIN_GAS_PRICE}`,
129
+ key: 'MinGasPrice',
130
+ checkedKeys: ['gasPrice']
131
+ }];
132
+ }, (_ref13, _ref14) => {
133
+ let {
134
+ ctVersion,
135
+ abiVersion
136
+ } = _ref13;
137
+ let {
138
+ txType,
139
+ node
140
+ } = _ref14;
141
+ const {
142
+ consensusProtocolVersion
143
+ } = node.getNodeInfo();
144
+ const protocol = PROTOCOL_VM_ABI[consensusProtocolVersion];
145
+ if (!protocol) throw new Error(`Unsupported protocol: ${consensusProtocolVersion}`); // If not contract create tx
146
+
147
+ if (!ctVersion) ctVersion = {
148
+ abiVersion
194
149
  };
195
- }(); // Verification using SCHEMA
196
-
197
-
198
- var verifySchema = function verifySchema(schema, data) {
199
- // Verify through schema
200
- return _reduceInstanceProperty(schema).call(schema, function (acc, _ref15) {
201
- var _ref16 = _slicedToArray(_ref15, 3),
202
- msg = _ref16[0],
203
- validatorKey = _ref16[1],
204
- _ref16$ = _ref16[2],
205
- key = _ref16$.key,
206
- type = _ref16$.type,
207
- txKey = _ref16$.txKey;
208
-
209
- if (!VALIDATORS[validatorKey](data)) acc.push({
210
- msg: msg(data),
211
- txKey: txKey,
212
- type: type
213
- });
214
- return acc;
215
- }, []);
216
- };
217
- /**
218
- * Unpack and verify transaction (verify nonce, ttl, fee, signature, account balance)
219
- * @function
220
- * @alias module:@aeternity/aepp-sdk/es/tx/validator
221
- *
222
- * @param {String} txHash Base64Check transaction hash
223
- * @param {Object} [options={}] Options
224
- * @param {String} [options.networkId] networkId Use in signature verification
225
- * @return {Promise<Object>} Object with verification errors and warnings
226
- */
227
-
228
-
229
- function unpackAndVerify(_x3) {
230
- return _unpackAndVerify.apply(this, arguments);
231
- }
232
-
233
- function _unpackAndVerify() {
234
- _unpackAndVerify = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee2(txHash) {
235
- var _ref18,
236
- networkId,
237
- _unpackTx,
238
- unpackedTx,
239
- rlpEncoded,
240
- txType,
241
- _context7,
242
- _unpackedTx$encodedTx,
243
- _txType,
244
- tx,
245
- signatures,
246
- rlpEncodedTx,
247
- _args2 = arguments;
248
-
249
- return _regeneratorRuntime.wrap(function _callee2$(_context8) {
250
- while (1) {
251
- switch (_context8.prev = _context8.next) {
252
- case 0:
253
- _ref18 = _args2.length > 1 && _args2[1] !== undefined ? _args2[1] : {}, networkId = _ref18.networkId;
254
- _unpackTx = unpackTx(txHash), unpackedTx = _unpackTx.tx, rlpEncoded = _unpackTx.rlpEncoded, txType = _unpackTx.txType;
255
-
256
- if (!(+unpackedTx.tag === OBJECT_TAG_SIGNED_TRANSACTION)) {
257
- _context8.next = 13;
258
- break;
259
- }
260
-
261
- _unpackedTx$encodedTx = unpackedTx.encodedTx, _txType = _unpackedTx$encodedTx.txType, tx = _unpackedTx$encodedTx.tx;
262
- signatures = _mapInstanceProperty(_context7 = unpackedTx.signatures).call(_context7, function (raw) {
263
- return {
264
- raw: raw,
265
- hash: encode(raw, 'sg')
266
- };
267
- });
268
- rlpEncodedTx = unpackedTx.encodedTx.rlpEncoded;
269
- _context8.next = 8;
270
- return this.verifyTx({
271
- tx: tx,
272
- signatures: signatures,
273
- rlpEncoded: rlpEncodedTx
274
- }, networkId);
275
-
276
- case 8:
277
- _context8.t0 = _context8.sent;
278
- _context8.t1 = tx;
279
- _context8.t2 = signatures;
280
- _context8.t3 = _txType;
281
- return _context8.abrupt("return", {
282
- validation: _context8.t0,
283
- tx: _context8.t1,
284
- signatures: _context8.t2,
285
- txType: _context8.t3
286
- });
287
-
288
- case 13:
289
- _context8.next = 15;
290
- return this.verifyTx({
291
- tx: unpackedTx,
292
- rlpEncoded: rlpEncoded
293
- }, networkId);
294
-
295
- case 15:
296
- _context8.t4 = _context8.sent;
297
- _context8.t5 = unpackedTx;
298
- _context8.t6 = txType;
299
- return _context8.abrupt("return", {
300
- validation: _context8.t4,
301
- tx: _context8.t5,
302
- txType: _context8.t6
303
- });
304
-
305
- case 19:
306
- case "end":
307
- return _context8.stop();
308
- }
309
- }
310
- }, _callee2, this);
311
- }));
312
- return _unpackAndVerify.apply(this, arguments);
313
- }
150
+ const txProtocol = protocol[txType];
151
+ if (!txProtocol) return [];
152
+
153
+ if (Object.entries(ctVersion).some(_ref15 => {
154
+ let [key, value] = _ref15;
155
+ return !txProtocol[key].includes(+value);
156
+ })) {
157
+ return [{
158
+ message: `ABI/VM version ${JSON.stringify(ctVersion)} is wrong, supported is: ${JSON.stringify(txProtocol)}`,
159
+ key: 'VmAndAbiVersionMismatch',
160
+ checkedKeys: ['ctVersion', 'abiVersion']
161
+ }];
162
+ }
314
163
 
315
- var getOwnerPublicKey = function getOwnerPublicKey(tx) {
316
- var _context6;
164
+ return [];
165
+ }];
317
166
 
318
- return tx[_findInstanceProperty(_context6 = ['senderId', 'accountId', 'ownerId', 'callerId', 'oracleId', 'fromId', 'initiator', 'gaId']).call(_context6, function (key) {
319
- return tx[key];
320
- })].replace('ok_', 'ak_');
321
- };
167
+ const getSenderAddress = tx => ['senderId', 'accountId', 'ownerId', 'callerId', 'oracleId', 'fromId', 'initiator', 'gaId', 'payerId'].map(key => tx[key]).filter(a => a).map(a => a.replace(/^ok_/, 'ak_'))[0];
322
168
  /**
323
- * Verify transaction (verify nonce, ttl, fee, signature, account balance)
169
+ * Transaction Validator
170
+ * This function validates some of transaction properties,
171
+ * to make sure it can be posted it to the chain
324
172
  * @function
325
173
  * @alias module:@aeternity/aepp-sdk/es/tx/validator
326
- *
327
- * @param {Object} [data={}] data TX data object
328
- * @param {String} [data.tx] tx Transaction hash
329
- * @param {Array} [data.signatures] signatures Transaction signature's
330
- * @param {Array} [data.rlpEncoded] rlpEncoded RLP encoded transaction
331
- * @param {String} networkId networkId Use in signature verification
332
- * @return {Promise<Array>} Object with verification errors and warnings
174
+ * @rtype (tx: String, node) => void
175
+ * @param {String} transaction Base64Check-encoded transaction
176
+ * @param {Object} node Node to validate transaction against
177
+ * @param {String[]} [parentTxTypes] Types of parent transactions
178
+ * @return {Promise<Object[]>} Array with verification errors
179
+ * @example const errors = await verifyTransaction(transaction, node)
333
180
  */
334
181
 
335
182
 
336
- function verifyTx(_x4, _x5) {
337
- return _verifyTx.apply(this, arguments);
338
- }
339
- /**
340
- * Verification for speciific txType
341
- * @param txType
342
- * @param data
343
- * @return {Array}
344
- */
345
-
346
-
347
- function _verifyTx() {
348
- _verifyTx = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee3(_ref17, networkId) {
349
- var _context9;
350
-
351
- var tx, signatures, rlpEncoded, ownerPublicKey, gas, txType, resolvedData, signatureVerification, baseVerification;
352
- return _regeneratorRuntime.wrap(function _callee3$(_context10) {
353
- while (1) {
354
- switch (_context10.prev = _context10.next) {
355
- case 0:
356
- tx = _ref17.tx, signatures = _ref17.signatures, rlpEncoded = _ref17.rlpEncoded;
357
- networkId = networkId || this.getNetworkId() || 'ae_mainnet'; // Fetch data for verification
358
-
359
- ownerPublicKey = getOwnerPublicKey(tx);
360
- gas = Object.prototype.hasOwnProperty.call(tx, 'gas') ? +tx.gas : 0;
361
- txType = OBJECT_ID_TX_TYPE[+tx.tag];
362
- _context10.t0 = _objectSpread;
363
- _context10.t1 = _objectSpread;
364
- _context10.t2 = _objectSpread;
365
- _context10.t3 = {
366
- minFee: calculateFee(0, txType, {
367
- gas: gas,
368
- params: tx,
369
- showWarning: false,
370
- vsn: tx.VSN
371
- })
372
- };
373
- _context10.next = 11;
374
- return resolveDataForBase(this, {
375
- ownerPublicKey: ownerPublicKey
376
- });
377
-
378
- case 11:
379
- _context10.t4 = _context10.sent;
380
- _context10.t5 = (0, _context10.t2)(_context10.t3, _context10.t4);
381
- _context10.t6 = tx;
382
- _context10.t7 = (0, _context10.t1)(_context10.t5, _context10.t6);
383
- _context10.t8 = {};
384
- _context10.t9 = {
385
- txType: txType
386
- };
387
- resolvedData = (0, _context10.t0)(_context10.t7, _context10.t8, _context10.t9);
388
- signatureVerification = signatures && signatures.length ? verifySchema(SIGNATURE_VERIFICATION_SCHEMA, {
389
- rlpEncoded: rlpEncoded,
390
- signature: signatures[0].raw,
391
- ownerPublicKey: ownerPublicKey,
392
- networkId: networkId
393
- }) : [];
394
- baseVerification = verifySchema(BASE_VERIFICATION_SCHEMA, resolvedData);
395
- return _context10.abrupt("return", _concatInstanceProperty(_context9 = []).call(_context9, _toConsumableArray(baseVerification), _toConsumableArray(signatureVerification), _toConsumableArray(customVerification(txType, resolvedData))));
396
-
397
- case 21:
398
- case "end":
399
- return _context10.stop();
400
- }
401
- }
402
- }, _callee3, this);
403
- }));
404
- return _verifyTx.apply(this, arguments);
405
- }
406
-
407
- function customVerification(txType, data) {
408
- switch (txType) {
409
- case TX_TYPE.contractCreate:
410
- case TX_TYPE.contractCall:
411
- case TX_TYPE.oracleRegister:
412
- return verifySchema(CONTRACT_VERIFICATION_SCHEMA, data);
413
-
414
- case TX_TYPE.nameClaim:
415
- return verifySchema(NAME_CLAIM_VERIFICATION_SCHEMA, data);
416
-
417
- default:
418
- return [];
419
- }
183
+ export default async function verifyTransaction(transaction, node) {
184
+ let parentTxTypes = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : [];
185
+ const {
186
+ tx,
187
+ txType
188
+ } = unpackTx(transaction);
189
+ const address = getSenderAddress(tx) ?? (txType === TX_TYPE.signed ? getSenderAddress(tx.encodedTx.tx) : null);
190
+ const [account, height] = await Promise.all([address && node.api.getAccountByPubkey(address).catch(() => ({
191
+ id: address,
192
+ balance: new BigNumber(0),
193
+ nonce: 0
194
+ })), node.api.getCurrentKeyBlockHeight().then(_ref16 => {
195
+ let {
196
+ height
197
+ } = _ref16;
198
+ return height;
199
+ })]);
200
+ return (await Promise.all(validators.map(v => v(tx, {
201
+ txType,
202
+ node,
203
+ account,
204
+ height,
205
+ parentTxTypes
206
+ })))).flat();
420
207
  }
421
- /**
422
- * Transaction Validator Stamp
423
- * This stamp give us possibility to unpack and validate some of transaction properties,
424
- * to make sure we can post it to the chain
425
- * @function
426
- * @alias module:@aeternity/aepp-sdk/es/tx/validator
427
- * @rtype Stamp
428
- * @param {Object} [options={}] - Initializer object
429
- * @param {Object} [options.url] - Node url
430
- * @param {Object} [options.internalUrl] - Node internal url
431
- * @return {Object} Transaction Validator instance
432
- * @example TransactionValidator({url: 'https://testnet.aeternity.io'})
433
- */
434
-
435
-
436
- var TransactionValidator = NodePool.compose({
437
- methods: {
438
- verifyTx: verifyTx,
439
- unpackAndVerify: unpackAndVerify
440
- }
441
- });
442
- export default TransactionValidator;
443
208
  //# sourceMappingURL=validator.js.map