@aeternity/aepp-sdk 13.0.0 → 13.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +4 -2
- 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 +27068 -16862
- package/dist/aepp-sdk.js.map +1 -1
- package/es/AeSdkBase.d.ts +11 -3
- package/es/AeSdkBase.mjs +24 -3
- package/es/AeSdkBase.mjs.map +1 -1
- package/es/AeSdkMethods.d.ts +9 -14
- package/es/AeSdkMethods.mjs +20 -49
- package/es/AeSdkMethods.mjs.map +1 -1
- package/es/AeSdkWallet.mjs +28 -5
- package/es/AeSdkWallet.mjs.map +1 -1
- package/es/Middleware.d.ts +38 -0
- package/es/Middleware.mjs +90 -0
- package/es/Middleware.mjs.map +1 -0
- package/es/MiddlewareSubscriber.d.ts +30 -0
- package/es/MiddlewareSubscriber.mjs +198 -0
- package/es/MiddlewareSubscriber.mjs.map +1 -0
- package/es/Node.d.ts +1 -1
- package/es/Node.mjs.map +1 -1
- package/es/account/Base.d.ts +14 -2
- package/es/account/Base.mjs.map +1 -1
- package/es/account/Generalized.d.ts +1 -0
- package/es/account/Generalized.mjs +5 -0
- package/es/account/Generalized.mjs.map +1 -1
- package/es/account/Ledger.d.ts +1 -0
- package/es/account/Ledger.mjs +5 -0
- package/es/account/Ledger.mjs.map +1 -1
- package/es/account/Memory.d.ts +2 -0
- package/es/account/Memory.mjs +18 -0
- package/es/account/Memory.mjs.map +1 -1
- package/es/account/Rpc.d.ts +1 -6
- package/es/account/Rpc.mjs +24 -10
- package/es/account/Rpc.mjs.map +1 -1
- package/es/aens.d.ts +1 -1
- package/es/aens.mjs +1 -1
- package/es/aens.mjs.map +1 -1
- package/es/aepp-wallet-communication/rpc/RpcClient.mjs +5 -2
- package/es/aepp-wallet-communication/rpc/RpcClient.mjs.map +1 -1
- package/es/aepp-wallet-communication/rpc/types.d.ts +10 -0
- package/es/aepp-wallet-communication/rpc/types.mjs.map +1 -1
- package/es/aepp-wallet-communication/schema.d.ts +1 -8
- package/es/aepp-wallet-communication/schema.mjs +1 -14
- package/es/aepp-wallet-communication/schema.mjs.map +1 -1
- package/es/aepp-wallet-communication/wallet-detector.d.ts +1 -1
- package/es/aepp-wallet-communication/wallet-detector.mjs +0 -3
- package/es/aepp-wallet-communication/wallet-detector.mjs.map +1 -1
- package/es/apis/compiler/compiler.mjs +15 -1
- package/es/apis/compiler/compiler.mjs.map +1 -1
- package/es/apis/compiler/models/index.d.ts +1 -7
- package/es/apis/compiler/models/index.mjs.map +1 -1
- package/es/apis/compiler/models/mappers.d.ts +0 -1
- package/es/apis/compiler/models/mappers.mjs +0 -43
- package/es/apis/compiler/models/mappers.mjs.map +1 -1
- package/es/apis/middleware/index.d.ts +2 -0
- package/es/apis/middleware/index.mjs +3 -0
- package/es/apis/middleware/index.mjs.map +1 -0
- package/es/apis/middleware/middleware.d.ts +309 -0
- package/es/apis/middleware/middleware.mjs +1527 -0
- package/es/apis/middleware/middleware.mjs.map +1 -0
- package/es/apis/middleware/models/index.d.ts +1496 -0
- package/es/apis/middleware/models/index.mjs +364 -0
- package/es/apis/middleware/models/index.mjs.map +1 -0
- package/es/apis/middleware/models/mappers.d.ts +102 -0
- package/es/apis/middleware/models/mappers.mjs +3334 -0
- package/es/apis/middleware/models/mappers.mjs.map +1 -0
- package/es/apis/middleware/models/parameters.d.ts +43 -0
- package/es/apis/middleware/models/parameters.mjs +417 -0
- package/es/apis/middleware/models/parameters.mjs.map +1 -0
- package/es/chain.d.ts +2 -1
- package/es/chain.mjs +4 -2
- package/es/chain.mjs.map +1 -1
- package/es/channel/Base.d.ts +1 -1
- package/es/channel/Base.mjs +1 -4
- package/es/channel/Base.mjs.map +1 -1
- package/es/channel/internal.mjs +2 -0
- package/es/channel/internal.mjs.map +1 -1
- package/es/contract/Contract.d.ts +1 -2
- package/es/contract/Contract.mjs +1 -1
- package/es/contract/Contract.mjs.map +1 -1
- package/es/contract/compiler/Base.d.ts +21 -0
- package/es/contract/compiler/Base.mjs.map +1 -1
- package/es/contract/compiler/Cli.d.ts +2 -0
- package/es/contract/compiler/Cli.mjs +24 -3
- package/es/contract/compiler/Cli.mjs.map +1 -1
- package/es/contract/compiler/Http.d.ts +2 -0
- package/es/contract/compiler/Http.mjs +22 -2
- package/es/contract/compiler/Http.mjs.map +1 -1
- package/es/contract/compiler/HttpNode.d.ts +1 -0
- package/es/contract/compiler/HttpNode.mjs +5 -0
- package/es/contract/compiler/HttpNode.mjs.map +1 -1
- package/es/deprecated.d.ts +14 -0
- package/es/deprecated.mjs +22 -0
- package/es/deprecated.mjs.map +1 -0
- package/es/index-browser.d.ts +20 -14
- package/es/index-browser.mjs +19 -15
- package/es/index-browser.mjs.map +1 -1
- package/es/tx/builder/constants.d.ts +0 -1
- package/es/tx/builder/constants.mjs +0 -1
- package/es/tx/builder/constants.mjs.map +1 -1
- package/es/tx/builder/field-types/coin-amount.d.ts +1 -1
- package/es/tx/builder/field-types/coin-amount.mjs +2 -1
- package/es/tx/builder/field-types/coin-amount.mjs.map +1 -1
- package/es/tx/builder/field-types/deposit.d.ts +1 -1
- package/es/tx/builder/field-types/entry.mjs +2 -1
- package/es/tx/builder/field-types/entry.mjs.map +1 -1
- package/es/tx/builder/field-types/index.d.ts +2 -2
- package/es/tx/builder/helpers.d.ts +8 -1
- package/es/tx/builder/helpers.mjs +53 -9
- package/es/tx/builder/helpers.mjs.map +1 -1
- package/es/tx/builder/index.d.ts +4 -2
- package/es/tx/builder/index.mjs +0 -1
- package/es/tx/builder/index.mjs.map +1 -1
- package/es/tx/builder/schema.d.ts +9 -9
- package/es/tx/execution-cost.d.ts +17 -0
- package/es/tx/execution-cost.mjs +17 -0
- package/es/tx/execution-cost.mjs.map +1 -1
- package/es/tx/validator.mjs +6 -3
- package/es/tx/validator.mjs.map +1 -1
- package/es/utils/amount-formatter.d.ts +1 -2
- package/es/utils/amount-formatter.mjs +2 -2
- package/es/utils/amount-formatter.mjs.map +1 -1
- package/es/utils/autorest.mjs +6 -8
- package/es/utils/autorest.mjs.map +1 -1
- package/es/utils/crypto.d.ts +1 -0
- package/es/utils/crypto.mjs +12 -2
- package/es/utils/crypto.mjs.map +1 -1
- package/es/utils/errors.d.ts +2 -2
- package/es/utils/errors.mjs.map +1 -1
- package/es/utils/other.d.ts +1 -0
- package/es/utils/other.mjs +5 -0
- package/es/utils/other.mjs.map +1 -1
- package/es/utils/typed-data.d.ts +45 -0
- package/es/utils/typed-data.mjs +71 -0
- package/es/utils/typed-data.mjs.map +1 -0
- package/package.json +23 -4
- package/src/AeSdkBase.ts +30 -5
- package/src/AeSdkMethods.ts +31 -50
- package/src/AeSdkWallet.ts +27 -5
- package/src/Middleware.ts +141 -0
- package/src/MiddlewareSubscriber.ts +207 -0
- package/src/Node.ts +1 -1
- package/src/account/Base.ts +20 -3
- package/src/account/Generalized.ts +5 -0
- package/src/account/Ledger.ts +5 -0
- package/src/account/Memory.ts +15 -0
- package/src/account/Rpc.ts +19 -7
- package/src/aens.ts +1 -1
- package/src/aepp-wallet-communication/rpc/RpcClient.ts +11 -3
- package/src/aepp-wallet-communication/rpc/types.ts +11 -0
- package/src/aepp-wallet-communication/schema.ts +2 -17
- package/src/aepp-wallet-communication/wallet-detector.ts +1 -2
- package/src/apis/compiler/compiler.ts +8 -1
- package/src/apis/compiler/models/index.ts +1 -8
- package/src/apis/compiler/models/mappers.ts +0 -36
- package/src/apis/middleware/index.ts +2 -0
- package/src/apis/middleware/middleware.ts +1807 -0
- package/src/apis/middleware/models/index.ts +1747 -0
- package/src/apis/middleware/models/mappers.ts +3370 -0
- package/src/apis/middleware/models/parameters.ts +463 -0
- package/src/chain.ts +3 -2
- package/src/channel/Base.ts +5 -5
- package/src/channel/internal.ts +2 -0
- package/src/contract/Contract.ts +2 -1
- package/src/contract/compiler/Base.ts +26 -0
- package/src/contract/compiler/Cli.ts +27 -3
- package/src/contract/compiler/Http.ts +21 -2
- package/src/contract/compiler/HttpNode.ts +6 -0
- package/src/deprecated.ts +23 -0
- package/src/index-browser.ts +77 -15
- package/src/tx/builder/constants.ts +0 -1
- package/src/tx/builder/field-types/coin-amount.ts +2 -1
- package/src/tx/builder/field-types/entry.ts +1 -1
- package/src/tx/builder/helpers.ts +54 -9
- package/src/tx/builder/index.ts +6 -9
- package/src/tx/execution-cost.ts +17 -0
- package/src/tx/validator.ts +4 -2
- package/src/utils/amount-formatter.ts +1 -1
- package/src/utils/autorest.ts +5 -10
- package/src/utils/crypto.ts +12 -2
- package/src/utils/errors.ts +2 -2
- package/src/utils/other.ts +5 -0
- package/src/utils/typed-data.ts +95 -0
- package/types-legacy/ts4.2/AeSdkBase.d.ts +11 -3
- package/types-legacy/ts4.2/AeSdkMethods.d.ts +9 -14
- package/types-legacy/ts4.2/Middleware.d.ts +46 -0
- package/types-legacy/ts4.2/MiddlewareSubscriber.d.ts +30 -0
- package/types-legacy/ts4.2/Node.d.ts +1 -1
- package/types-legacy/ts4.2/account/Base.d.ts +14 -2
- package/types-legacy/ts4.2/account/Generalized.d.ts +1 -0
- package/types-legacy/ts4.2/account/Ledger.d.ts +1 -0
- package/types-legacy/ts4.2/account/Memory.d.ts +2 -0
- package/types-legacy/ts4.2/account/Rpc.d.ts +1 -6
- package/types-legacy/ts4.2/aens.d.ts +1 -1
- package/types-legacy/ts4.2/aepp-wallet-communication/rpc/types.d.ts +10 -0
- package/types-legacy/ts4.2/aepp-wallet-communication/schema.d.ts +1 -8
- package/types-legacy/ts4.2/aepp-wallet-communication/wallet-detector.d.ts +1 -1
- package/types-legacy/ts4.2/apis/compiler/models/index.d.ts +1 -7
- package/types-legacy/ts4.2/apis/compiler/models/mappers.d.ts +0 -1
- package/types-legacy/ts4.2/apis/middleware/index.d.ts +2 -0
- package/types-legacy/ts4.2/apis/middleware/middleware.d.ts +309 -0
- package/types-legacy/ts4.2/apis/middleware/models/index.d.ts +1496 -0
- package/types-legacy/ts4.2/apis/middleware/models/mappers.d.ts +102 -0
- package/types-legacy/ts4.2/apis/middleware/models/parameters.d.ts +43 -0
- package/types-legacy/ts4.2/chain.d.ts +2 -1
- package/types-legacy/ts4.2/channel/Base.d.ts +1 -1
- package/types-legacy/ts4.2/contract/Contract.d.ts +1 -2
- package/types-legacy/ts4.2/contract/compiler/Base.d.ts +21 -0
- package/types-legacy/ts4.2/contract/compiler/Cli.d.ts +2 -0
- package/types-legacy/ts4.2/contract/compiler/Http.d.ts +2 -0
- package/types-legacy/ts4.2/contract/compiler/HttpNode.d.ts +1 -0
- package/types-legacy/ts4.2/deprecated.d.ts +14 -0
- package/types-legacy/ts4.2/index-browser.d.ts +20 -14
- package/types-legacy/ts4.2/tx/builder/constants.d.ts +0 -1
- package/types-legacy/ts4.2/tx/builder/field-types/coin-amount.d.ts +1 -1
- package/types-legacy/ts4.2/tx/builder/field-types/deposit.d.ts +1 -1
- package/types-legacy/ts4.2/tx/builder/field-types/index.d.ts +2 -2
- package/types-legacy/ts4.2/tx/builder/helpers.d.ts +8 -1
- package/types-legacy/ts4.2/tx/builder/index.d.ts +4 -2
- package/types-legacy/ts4.2/tx/builder/schema.d.ts +9 -9
- package/types-legacy/ts4.2/tx/execution-cost.d.ts +17 -0
- package/types-legacy/ts4.2/utils/amount-formatter.d.ts +1 -2
- package/types-legacy/ts4.2/utils/crypto.d.ts +1 -0
- package/types-legacy/ts4.2/utils/errors.d.ts +2 -2
- package/types-legacy/ts4.2/utils/other.d.ts +1 -0
- package/types-legacy/ts4.2/utils/typed-data.d.ts +60 -0
- package/types-legacy/ts4.5/AeSdkBase.d.ts +11 -3
- package/types-legacy/ts4.5/AeSdkMethods.d.ts +9 -14
- package/types-legacy/ts4.5/Middleware.d.ts +46 -0
- package/types-legacy/ts4.5/MiddlewareSubscriber.d.ts +30 -0
- package/types-legacy/ts4.5/Node.d.ts +1 -1
- package/types-legacy/ts4.5/account/Base.d.ts +14 -2
- package/types-legacy/ts4.5/account/Generalized.d.ts +1 -0
- package/types-legacy/ts4.5/account/Ledger.d.ts +1 -0
- package/types-legacy/ts4.5/account/Memory.d.ts +2 -0
- package/types-legacy/ts4.5/account/Rpc.d.ts +1 -6
- package/types-legacy/ts4.5/aens.d.ts +1 -1
- package/types-legacy/ts4.5/aepp-wallet-communication/rpc/types.d.ts +10 -0
- package/types-legacy/ts4.5/aepp-wallet-communication/schema.d.ts +1 -8
- package/types-legacy/ts4.5/aepp-wallet-communication/wallet-detector.d.ts +1 -1
- package/types-legacy/ts4.5/apis/compiler/models/index.d.ts +1 -7
- package/types-legacy/ts4.5/apis/compiler/models/mappers.d.ts +0 -1
- package/types-legacy/ts4.5/apis/middleware/index.d.ts +2 -0
- package/types-legacy/ts4.5/apis/middleware/middleware.d.ts +309 -0
- package/types-legacy/ts4.5/apis/middleware/models/index.d.ts +1496 -0
- package/types-legacy/ts4.5/apis/middleware/models/mappers.d.ts +102 -0
- package/types-legacy/ts4.5/apis/middleware/models/parameters.d.ts +43 -0
- package/types-legacy/ts4.5/chain.d.ts +2 -1
- package/types-legacy/ts4.5/channel/Base.d.ts +1 -1
- package/types-legacy/ts4.5/contract/Contract.d.ts +1 -2
- package/types-legacy/ts4.5/contract/compiler/Base.d.ts +21 -0
- package/types-legacy/ts4.5/contract/compiler/Cli.d.ts +2 -0
- package/types-legacy/ts4.5/contract/compiler/Http.d.ts +2 -0
- package/types-legacy/ts4.5/contract/compiler/HttpNode.d.ts +1 -0
- package/types-legacy/ts4.5/deprecated.d.ts +14 -0
- package/types-legacy/ts4.5/index-browser.d.ts +20 -14
- package/types-legacy/ts4.5/tx/builder/constants.d.ts +0 -1
- package/types-legacy/ts4.5/tx/builder/field-types/coin-amount.d.ts +1 -1
- package/types-legacy/ts4.5/tx/builder/field-types/deposit.d.ts +1 -1
- package/types-legacy/ts4.5/tx/builder/field-types/index.d.ts +2 -2
- package/types-legacy/ts4.5/tx/builder/helpers.d.ts +8 -1
- package/types-legacy/ts4.5/tx/builder/index.d.ts +4 -2
- package/types-legacy/ts4.5/tx/builder/schema.d.ts +9 -9
- package/types-legacy/ts4.5/tx/execution-cost.d.ts +17 -0
- package/types-legacy/ts4.5/utils/amount-formatter.d.ts +1 -2
- package/types-legacy/ts4.5/utils/crypto.d.ts +1 -0
- package/types-legacy/ts4.5/utils/errors.d.ts +2 -2
- package/types-legacy/ts4.5/utils/other.d.ts +1 -0
- package/types-legacy/ts4.5/utils/typed-data.d.ts +60 -0
- package/es/typings/@aeternity__aepp-calldata/index.d.mjs +0 -2
- package/es/typings/@aeternity__aepp-calldata/index.d.mjs.map +0 -1
- package/src/typings/@aeternity__aepp-calldata/index.d.ts +0 -20
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
function _classPrivateMethodInitSpec(obj, privateSet) { _checkPrivateRedeclaration(obj, privateSet); privateSet.add(obj); }
|
|
2
|
+
function _checkPrivateRedeclaration(obj, privateCollection) { if (privateCollection.has(obj)) { throw new TypeError("Cannot initialize the same private elements twice on an object"); } }
|
|
3
|
+
function _classPrivateMethodGet(receiver, privateSet, fn) { if (!privateSet.has(receiver)) { throw new TypeError("attempted to get private field on non-instance"); } return fn; }
|
|
4
|
+
// eslint-disable-next-line max-classes-per-file
|
|
5
|
+
import BigNumber from 'bignumber.js';
|
|
6
|
+
import { genRequestQueuesPolicy, genCombineGetRequestsPolicy, genErrorFormatterPolicy, genVersionCheckPolicy, genRetryOnFailurePolicy } from "./utils/autorest.mjs";
|
|
7
|
+
import { Middleware as MiddlewareApi } from "./apis/middleware/index.mjs";
|
|
8
|
+
import { mapObject } from "./utils/other.mjs";
|
|
9
|
+
const bigIntPropertyNames = [];
|
|
10
|
+
const numberPropertyNames = [];
|
|
11
|
+
var _mapData = /*#__PURE__*/new WeakSet();
|
|
12
|
+
var _encodeArg = /*#__PURE__*/new WeakSet();
|
|
13
|
+
var _decodeRes = /*#__PURE__*/new WeakSet();
|
|
14
|
+
class MiddlewareTransformed extends MiddlewareApi {
|
|
15
|
+
constructor() {
|
|
16
|
+
super(...arguments);
|
|
17
|
+
_classPrivateMethodInitSpec(this, _decodeRes);
|
|
18
|
+
_classPrivateMethodInitSpec(this, _encodeArg);
|
|
19
|
+
_classPrivateMethodInitSpec(this, _mapData);
|
|
20
|
+
}
|
|
21
|
+
async sendOperationRequest(operationArguments, operationSpec) {
|
|
22
|
+
const args = mapObject(operationArguments, _ref => {
|
|
23
|
+
let [key, value] = _ref;
|
|
24
|
+
return [key, _classPrivateMethodGet(this, _encodeArg, _encodeArg2).call(this, value)];
|
|
25
|
+
});
|
|
26
|
+
return _classPrivateMethodGet(this, _decodeRes, _decodeRes2).call(this, await super.sendOperationRequest(args, operationSpec));
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
function _mapData2(data, transform) {
|
|
30
|
+
if (Array.isArray(data)) return data.map(d => _classPrivateMethodGet(this, _mapData, _mapData2).call(this, d, transform));
|
|
31
|
+
if (data != null && typeof data === 'object') {
|
|
32
|
+
return mapObject(data, _ref3 => {
|
|
33
|
+
let [key, value] = _ref3;
|
|
34
|
+
if (value == null) return [key, value];
|
|
35
|
+
if (bigIntPropertyNames.some(k => k === key)) return [key, transform.bigInt(value)];
|
|
36
|
+
if (numberPropertyNames.some(k => k === key)) return [key, transform.number(value)];
|
|
37
|
+
return [key, _classPrivateMethodGet(this, _mapData, _mapData2).call(this, value, transform)];
|
|
38
|
+
});
|
|
39
|
+
}
|
|
40
|
+
return data;
|
|
41
|
+
}
|
|
42
|
+
function _encodeArg2(data) {
|
|
43
|
+
return _classPrivateMethodGet(this, _mapData, _mapData2).call(this, data, {
|
|
44
|
+
bigInt: value => {
|
|
45
|
+
if (value instanceof BigNumber) return value.toFixed();
|
|
46
|
+
return value.toString();
|
|
47
|
+
},
|
|
48
|
+
number: value => value.toString()
|
|
49
|
+
});
|
|
50
|
+
}
|
|
51
|
+
function _decodeRes2(data) {
|
|
52
|
+
return _classPrivateMethodGet(this, _mapData, _mapData2).call(this, data, {
|
|
53
|
+
bigInt: value => BigInt(value),
|
|
54
|
+
number: value => +value
|
|
55
|
+
});
|
|
56
|
+
}
|
|
57
|
+
export default class Middleware extends MiddlewareTransformed {
|
|
58
|
+
/**
|
|
59
|
+
* @param url - Url for middleware API
|
|
60
|
+
* @param options - Options
|
|
61
|
+
* @param options.ignoreVersion - Don't check node version
|
|
62
|
+
* @param options.retryCount - Amount of extra requests to do in case of failure
|
|
63
|
+
* @param options.retryOverallDelay - Time in ms to wait between all retries
|
|
64
|
+
*/
|
|
65
|
+
constructor(url) {
|
|
66
|
+
let {
|
|
67
|
+
ignoreVersion = false,
|
|
68
|
+
retryCount = 3,
|
|
69
|
+
retryOverallDelay = 800,
|
|
70
|
+
...options
|
|
71
|
+
} = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
|
|
72
|
+
// eslint-disable-next-line constructor-super
|
|
73
|
+
super(url, {
|
|
74
|
+
allowInsecureConnection: true,
|
|
75
|
+
additionalPolicies: [genRequestQueuesPolicy(), genCombineGetRequestsPolicy(), genRetryOnFailurePolicy(retryCount, retryOverallDelay), genErrorFormatterPolicy(body => ` ${body.error}`)],
|
|
76
|
+
...options
|
|
77
|
+
});
|
|
78
|
+
if (!ignoreVersion) {
|
|
79
|
+
const statusPromise = this.getStatus();
|
|
80
|
+
const versionPromise = statusPromise.then(_ref2 => {
|
|
81
|
+
let {
|
|
82
|
+
mdwVersion
|
|
83
|
+
} = _ref2;
|
|
84
|
+
return mdwVersion;
|
|
85
|
+
}, error => error);
|
|
86
|
+
this.pipeline.addPolicy(genVersionCheckPolicy('middleware', '/v2/status', versionPromise, '1.47.0', '2.0.0'));
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
//# sourceMappingURL=Middleware.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"Middleware.mjs","names":["BigNumber","genRequestQueuesPolicy","genCombineGetRequestsPolicy","genErrorFormatterPolicy","genVersionCheckPolicy","genRetryOnFailurePolicy","Middleware","MiddlewareApi","mapObject","bigIntPropertyNames","numberPropertyNames","_mapData","WeakSet","_encodeArg","_decodeRes","MiddlewareTransformed","constructor","arguments","_classPrivateMethodInitSpec","sendOperationRequest","operationArguments","operationSpec","args","_ref","key","value","_classPrivateMethodGet","_encodeArg2","call","_decodeRes2","_mapData2","data","transform","Array","isArray","map","d","_ref3","some","k","bigInt","number","toFixed","toString","BigInt","url","ignoreVersion","retryCount","retryOverallDelay","options","length","undefined","allowInsecureConnection","additionalPolicies","body","error","statusPromise","getStatus","versionPromise","then","_ref2","mdwVersion","pipeline","addPolicy"],"sources":["../src/Middleware.ts"],"sourcesContent":["// eslint-disable-next-line max-classes-per-file\nimport BigNumber from 'bignumber.js';\nimport { OperationArguments, OperationSpec } from '@azure/core-client';\nimport {\n genRequestQueuesPolicy, genCombineGetRequestsPolicy, genErrorFormatterPolicy,\n genVersionCheckPolicy, genRetryOnFailurePolicy,\n} from './utils/autorest';\nimport { Middleware as MiddlewareApi, MiddlewareOptionalParams, ErrorResponse } from './apis/middleware';\nimport { mapObject } from './utils/other';\nimport { Encoded } from './utils/encoder';\nimport { ConsensusProtocolVersion } from './tx/builder/constants';\n\nconst bigIntPropertyNames = [] as const;\n\nconst numberPropertyNames = [] as const;\n\nclass MiddlewareTransformed extends MiddlewareApi {\n override async sendOperationRequest(\n operationArguments: OperationArguments,\n operationSpec: OperationSpec,\n ): Promise<any> {\n const args = mapObject(\n operationArguments,\n ([key, value]) => [key, this.#encodeArg(value)],\n ) as OperationArguments;\n return this.#decodeRes(await super.sendOperationRequest(args, operationSpec));\n }\n\n #mapData(data: any, transform: {\n bigInt: (v: any) => any;\n number: (v: any) => any;\n }): unknown {\n if (Array.isArray(data)) return data.map((d) => this.#mapData(d, transform));\n if (data != null && typeof data === 'object') {\n return mapObject(data, ([key, value]) => {\n if (value == null) return [key, value];\n if (bigIntPropertyNames.some((k) => k === key)) return [key, transform.bigInt(value)];\n if (numberPropertyNames.some((k) => k === key)) return [key, transform.number(value)];\n return [key, this.#mapData(value, transform)];\n });\n }\n return data;\n }\n\n #encodeArg(data: any): any {\n return this.#mapData(data, {\n bigInt: (value) => {\n if (value instanceof BigNumber) return value.toFixed();\n return value.toString();\n },\n number: (value) => value.toString(),\n });\n }\n\n #decodeRes(data: any): any {\n return this.#mapData(data, {\n bigInt: (value) => BigInt(value),\n number: (value) => +value,\n });\n }\n}\n\ntype BigIntPropertyNames = typeof bigIntPropertyNames[number];\ntype NumberPropertyNames = typeof numberPropertyNames[number];\ntype PreserveOptional<NewType, OrigType> =\n OrigType extends undefined ? NewType | undefined : NewType;\nexport type TransformMiddlewareType<Type> =\n Type extends (...args: infer Args) => infer Ret\n ? (...args: TransformMiddlewareType<Args>) => TransformMiddlewareType<Ret>\n : Type extends [infer Item, ...infer Rest]\n ? [TransformMiddlewareType<Item>, ...TransformMiddlewareType<Rest>]\n : Type extends Array<infer Item>\n ? Array<TransformMiddlewareType<Item>>\n : Type extends Promise<infer T>\n ? Promise<TransformMiddlewareType<T>>\n : Type extends { [P in any]: any }\n ? {\n [Property in keyof Type]:\n Property extends BigIntPropertyNames\n ? PreserveOptional<bigint, Type[Property]>\n : Property extends NumberPropertyNames\n ? PreserveOptional<number, Type[Property]>\n : Property extends 'txHash'\n ? PreserveOptional<Encoded.TxHash, Type[Property]>\n : Property extends 'bytecode'\n ? PreserveOptional<Encoded.ContractBytearray, Type[Property]>\n : TransformMiddlewareType<Type[Property]>\n }\n : Type;\ntype MiddlewareTransformedApi = new (...args: ConstructorParameters<typeof MiddlewareApi>) => {\n [Name in keyof InstanceType<typeof MiddlewareApi>]:\n Name extends 'pipeline' | 'sendRequest' | 'sendOperationRequest'\n ? MiddlewareApi[Name] : TransformMiddlewareType<MiddlewareApi[Name]>\n};\n\nexport interface MiddlewareInfo {\n url: string;\n nodeNetworkId: string;\n version: string;\n consensusProtocolVersion: ConsensusProtocolVersion;\n}\n\nexport default class Middleware\n extends (MiddlewareTransformed as unknown as MiddlewareTransformedApi) {\n /**\n * @param url - Url for middleware API\n * @param options - Options\n * @param options.ignoreVersion - Don't check node version\n * @param options.retryCount - Amount of extra requests to do in case of failure\n * @param options.retryOverallDelay - Time in ms to wait between all retries\n */\n constructor(\n url: string,\n {\n ignoreVersion = false, retryCount = 3, retryOverallDelay = 800, ...options\n }: MiddlewareOptionalParams & {\n ignoreVersion?: boolean;\n retryCount?: number;\n retryOverallDelay?: number;\n } = {},\n ) {\n // eslint-disable-next-line constructor-super\n super(url, {\n allowInsecureConnection: true,\n additionalPolicies: [\n genRequestQueuesPolicy(),\n genCombineGetRequestsPolicy(),\n genRetryOnFailurePolicy(retryCount, retryOverallDelay),\n genErrorFormatterPolicy((body: ErrorResponse) => ` ${body.error}`),\n ],\n ...options,\n });\n if (!ignoreVersion) {\n const statusPromise = this.getStatus();\n const versionPromise = statusPromise.then(({ mdwVersion }) => mdwVersion, (error) => error);\n this.pipeline.addPolicy(\n genVersionCheckPolicy('middleware', '/v2/status', versionPromise, '1.47.0', '2.0.0'),\n );\n }\n }\n}\n"],"mappings":";;;AAAA;AACA,OAAOA,SAAS,MAAM,cAAc;AAAC,SAGnCC,sBAAsB,EAAEC,2BAA2B,EAAEC,uBAAuB,EAC5EC,qBAAqB,EAAEC,uBAAuB;AAAA,SAEvCC,UAAU,IAAIC,aAAa;AAAA,SAC3BC,SAAS;AAIlB,MAAMC,mBAAmB,GAAG,EAAW;AAEvC,MAAMC,mBAAmB,GAAG,EAAW;AAAC,IAAAC,QAAA,oBAAAC,OAAA;AAAA,IAAAC,UAAA,oBAAAD,OAAA;AAAA,IAAAE,UAAA,oBAAAF,OAAA;AAExC,MAAMG,qBAAqB,SAASR,aAAa,CAAC;EAAAS,YAAA;IAAA,SAAAC,SAAA;IAAAC,2BAAA,OAAAJ,UAAA;IAAAI,2BAAA,OAAAL,UAAA;IAAAK,2BAAA,OAAAP,QAAA;EAAA;EAChD,MAAe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AG,EAAE;MACTO,uBAAuB,EAAE,IAAI;MAC7BC,kBAAkB,EAAE,CAClBpD,sBAAsB,EAAE,EACxBC,2BAA2B,EAAE,EAC7BG,uBAAuB,CAAC0C,UAAU,EAAEC,iBAAiB,CAAC,EACtD7C,uBAAuB,CAAEmD,IAAmB,IAAM,IAAGA,IAAI,CAACC,KAAM,EAAC,CAAC,CACnE;MACD,GAAGN;IACL,CAAC,CAAC;IACF,IAAI,CAACH,aAAa,EAAE;MAClB,MAAMU,aAAa,GAAG,IAAI,CAACC,SAAS,EAAE;MACtC,MAAMC,cAAc,GAAGF,aAAa,CAACG,IAAI,CAACC,KAAA;QAAA,IAAC;UAAEC;QAAW,CAAC,GAAAD,KAAA;QAAA,OAAKC,UAAU;MAAA,GAAGN,KAAK,IAAKA,KAAK,CAAC;MAC3F,IAAI,CAACO,QAAQ,CAACC,SAAS,CACrB3D,qBAAqB,CAAC,YAAY,EAAE,YAAY,EAAEsD,cAAc,EAAE,QAAQ,EAAE,OAAO,CAAC,CACrF;IACH;EACF;AACF"}
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
/// <reference types="ws" />
|
|
2
|
+
import WebSocket from 'isomorphic-ws';
|
|
3
|
+
import { BaseError } from './utils/errors';
|
|
4
|
+
import { Encoded } from './utils/encoder';
|
|
5
|
+
export declare class MiddlewareSubscriberError extends BaseError {
|
|
6
|
+
constructor(message: string);
|
|
7
|
+
}
|
|
8
|
+
export declare class MiddlewareSubscriberDisconnected extends MiddlewareSubscriberError {
|
|
9
|
+
readonly closeEvent: WebSocket.CloseEvent;
|
|
10
|
+
constructor(closeEvent: WebSocket.CloseEvent);
|
|
11
|
+
}
|
|
12
|
+
export default class MiddlewareSubscriber {
|
|
13
|
+
#private;
|
|
14
|
+
readonly url: string;
|
|
15
|
+
get webSocket(): WebSocket | undefined;
|
|
16
|
+
constructor(url: string);
|
|
17
|
+
reconnect(): Promise<void>;
|
|
18
|
+
subscribeKeyBlocks(cb: (p?: any, e?: Error) => void): () => void;
|
|
19
|
+
subscribeKeyBlocksNode(cb: (p?: any, e?: Error) => void): () => void;
|
|
20
|
+
subscribeKeyBlocksAll(cb: (p?: any, e?: Error) => void): () => void;
|
|
21
|
+
subscribeMicroBlocks(cb: (p?: any, e?: Error) => void): () => void;
|
|
22
|
+
subscribeMicroBlocksNode(cb: (p?: any, e?: Error) => void): () => void;
|
|
23
|
+
subscribeMicroBlocksAll(cb: (p?: any, e?: Error) => void): () => void;
|
|
24
|
+
subscribeTransactions(cb: (p?: any, e?: Error) => void): () => void;
|
|
25
|
+
subscribeTransactionsNode(cb: (p?: any, e?: Error) => void): () => void;
|
|
26
|
+
subscribeTransactionsAll(cb: (p?: any, e?: Error) => void): () => void;
|
|
27
|
+
subscribeObject(target: Encoded.KeyBlockHash | Encoded.Channel | Encoded.ContractAddress | Encoded.OracleAddress | Encoded.OracleQueryId | Encoded.AccountAddress | Encoded.Name | `${string}.chain`, cb: (p?: any, e?: Error) => void): () => void;
|
|
28
|
+
subscribeObjectNode(target: Encoded.KeyBlockHash | Encoded.Channel | Encoded.ContractAddress | Encoded.OracleAddress | Encoded.OracleQueryId | Encoded.AccountAddress | Encoded.Name | `${string}.chain`, cb: (p?: any, e?: Error) => void): () => void;
|
|
29
|
+
subscribeObjectAll(target: Encoded.KeyBlockHash | Encoded.Channel | Encoded.ContractAddress | Encoded.OracleAddress | Encoded.OracleQueryId | Encoded.AccountAddress | Encoded.Name | `${string}.chain`, cb: (p?: any, e?: Error) => void): () => void;
|
|
30
|
+
}
|
|
@@ -0,0 +1,198 @@
|
|
|
1
|
+
import _classPrivateFieldSet from "@babel/runtime-corejs3/helpers/classPrivateFieldSet";
|
|
2
|
+
import _classPrivateFieldGet from "@babel/runtime-corejs3/helpers/classPrivateFieldGet";
|
|
3
|
+
function _classPrivateMethodInitSpec(obj, privateSet) { _checkPrivateRedeclaration(obj, privateSet); privateSet.add(obj); }
|
|
4
|
+
function _classPrivateFieldInitSpec(obj, privateMap, value) { _checkPrivateRedeclaration(obj, privateMap); privateMap.set(obj, value); }
|
|
5
|
+
function _checkPrivateRedeclaration(obj, privateCollection) { if (privateCollection.has(obj)) { throw new TypeError("Cannot initialize the same private elements twice on an object"); } }
|
|
6
|
+
function _classPrivateMethodGet(receiver, privateSet, fn) { if (!privateSet.has(receiver)) { throw new TypeError("attempted to get private field on non-instance"); } return fn; }
|
|
7
|
+
/* eslint-disable max-classes-per-file */
|
|
8
|
+
import WebSocket from 'isomorphic-ws';
|
|
9
|
+
import { BaseError, UnexpectedTsError, InternalError } from "./utils/errors.mjs";
|
|
10
|
+
var Source;
|
|
11
|
+
(function (Source) {
|
|
12
|
+
Source["Middleware"] = "mdw";
|
|
13
|
+
Source["Node"] = "node";
|
|
14
|
+
Source["All"] = "all";
|
|
15
|
+
})(Source || (Source = {}));
|
|
16
|
+
export class MiddlewareSubscriberError extends BaseError {
|
|
17
|
+
constructor(message) {
|
|
18
|
+
super(message);
|
|
19
|
+
this.name = 'MiddlewareSubscriberError';
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
export class MiddlewareSubscriberDisconnected extends MiddlewareSubscriberError {
|
|
23
|
+
constructor(closeEvent) {
|
|
24
|
+
super('Connection closed');
|
|
25
|
+
this.closeEvent = closeEvent;
|
|
26
|
+
this.name = 'MiddlewareSubscriberDisconnected';
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
var _subscriptions = /*#__PURE__*/new WeakMap();
|
|
30
|
+
var _requestQueue = /*#__PURE__*/new WeakMap();
|
|
31
|
+
var _webSocket = /*#__PURE__*/new WeakMap();
|
|
32
|
+
var _targets = /*#__PURE__*/new WeakMap();
|
|
33
|
+
var _sendMessage = /*#__PURE__*/new WeakSet();
|
|
34
|
+
var _sendSubscribe = /*#__PURE__*/new WeakSet();
|
|
35
|
+
var _emit = /*#__PURE__*/new WeakSet();
|
|
36
|
+
var _disconnect = /*#__PURE__*/new WeakSet();
|
|
37
|
+
var _messageHandler = /*#__PURE__*/new WeakSet();
|
|
38
|
+
var _subscribe = /*#__PURE__*/new WeakSet();
|
|
39
|
+
export default class MiddlewareSubscriber {
|
|
40
|
+
get webSocket() {
|
|
41
|
+
return _classPrivateFieldGet(this, _webSocket);
|
|
42
|
+
}
|
|
43
|
+
constructor(url) {
|
|
44
|
+
_classPrivateMethodInitSpec(this, _subscribe);
|
|
45
|
+
_classPrivateMethodInitSpec(this, _messageHandler);
|
|
46
|
+
_classPrivateMethodInitSpec(this, _disconnect);
|
|
47
|
+
_classPrivateMethodInitSpec(this, _emit);
|
|
48
|
+
_classPrivateMethodInitSpec(this, _sendSubscribe);
|
|
49
|
+
_classPrivateMethodInitSpec(this, _sendMessage);
|
|
50
|
+
_classPrivateFieldInitSpec(this, _targets, {
|
|
51
|
+
get: _get_targets,
|
|
52
|
+
set: void 0
|
|
53
|
+
});
|
|
54
|
+
_classPrivateFieldInitSpec(this, _subscriptions, {
|
|
55
|
+
writable: true,
|
|
56
|
+
value: []
|
|
57
|
+
});
|
|
58
|
+
_classPrivateFieldInitSpec(this, _requestQueue, {
|
|
59
|
+
writable: true,
|
|
60
|
+
value: []
|
|
61
|
+
});
|
|
62
|
+
_classPrivateFieldInitSpec(this, _webSocket, {
|
|
63
|
+
writable: true,
|
|
64
|
+
value: void 0
|
|
65
|
+
});
|
|
66
|
+
this.url = url;
|
|
67
|
+
}
|
|
68
|
+
async reconnect() {
|
|
69
|
+
_classPrivateMethodGet(this, _disconnect, _disconnect2).call(this);
|
|
70
|
+
_classPrivateFieldSet(this, _webSocket, await new Promise(resolve => {
|
|
71
|
+
const webSocket = new WebSocket(this.url);
|
|
72
|
+
Object.assign(webSocket, {
|
|
73
|
+
onopen: () => resolve(webSocket),
|
|
74
|
+
onerror: errorEvent => {
|
|
75
|
+
_classPrivateMethodGet(this, _emit, _emit2).call(this, () => true, undefined, errorEvent.error);
|
|
76
|
+
},
|
|
77
|
+
onmessage: event => {
|
|
78
|
+
if (typeof event.data !== 'string') {
|
|
79
|
+
throw new InternalError(`Unknown incoming message type: ${typeof event.data}`);
|
|
80
|
+
}
|
|
81
|
+
_classPrivateMethodGet(this, _messageHandler, _messageHandler2).call(this, JSON.parse(event.data));
|
|
82
|
+
},
|
|
83
|
+
onclose: event => {
|
|
84
|
+
_classPrivateMethodGet(this, _emit, _emit2).call(this, () => true, undefined, new MiddlewareSubscriberDisconnected(event));
|
|
85
|
+
_classPrivateMethodGet(this, _disconnect, _disconnect2).call(this, true);
|
|
86
|
+
}
|
|
87
|
+
});
|
|
88
|
+
}));
|
|
89
|
+
await Promise.all([..._classPrivateFieldGet(this, _targets)].map(target => _classPrivateMethodGet(this, _sendSubscribe, _sendSubscribe2).call(this, true, target)));
|
|
90
|
+
}
|
|
91
|
+
// TODO: replace p?: any with a proper type definition
|
|
92
|
+
|
|
93
|
+
subscribeKeyBlocks(cb) {
|
|
94
|
+
return _classPrivateMethodGet(this, _subscribe, _subscribe2).call(this, 'KeyBlocks', Source.Middleware, cb);
|
|
95
|
+
}
|
|
96
|
+
subscribeKeyBlocksNode(cb) {
|
|
97
|
+
return _classPrivateMethodGet(this, _subscribe, _subscribe2).call(this, 'KeyBlocks', Source.Node, cb);
|
|
98
|
+
}
|
|
99
|
+
subscribeKeyBlocksAll(cb) {
|
|
100
|
+
return _classPrivateMethodGet(this, _subscribe, _subscribe2).call(this, 'KeyBlocks', Source.All, cb);
|
|
101
|
+
}
|
|
102
|
+
subscribeMicroBlocks(cb) {
|
|
103
|
+
return _classPrivateMethodGet(this, _subscribe, _subscribe2).call(this, 'MicroBlocks', Source.Middleware, cb);
|
|
104
|
+
}
|
|
105
|
+
subscribeMicroBlocksNode(cb) {
|
|
106
|
+
return _classPrivateMethodGet(this, _subscribe, _subscribe2).call(this, 'MicroBlocks', Source.Node, cb);
|
|
107
|
+
}
|
|
108
|
+
subscribeMicroBlocksAll(cb) {
|
|
109
|
+
return _classPrivateMethodGet(this, _subscribe, _subscribe2).call(this, 'MicroBlocks', Source.All, cb);
|
|
110
|
+
}
|
|
111
|
+
subscribeTransactions(cb) {
|
|
112
|
+
return _classPrivateMethodGet(this, _subscribe, _subscribe2).call(this, 'Transactions', Source.Middleware, cb);
|
|
113
|
+
}
|
|
114
|
+
subscribeTransactionsNode(cb) {
|
|
115
|
+
return _classPrivateMethodGet(this, _subscribe, _subscribe2).call(this, 'Transactions', Source.Node, cb);
|
|
116
|
+
}
|
|
117
|
+
subscribeTransactionsAll(cb) {
|
|
118
|
+
return _classPrivateMethodGet(this, _subscribe, _subscribe2).call(this, 'Transactions', Source.All, cb);
|
|
119
|
+
}
|
|
120
|
+
subscribeObject(target, cb) {
|
|
121
|
+
return _classPrivateMethodGet(this, _subscribe, _subscribe2).call(this, target, Source.Middleware, cb);
|
|
122
|
+
}
|
|
123
|
+
subscribeObjectNode(target, cb) {
|
|
124
|
+
return _classPrivateMethodGet(this, _subscribe, _subscribe2).call(this, target, Source.Node, cb);
|
|
125
|
+
}
|
|
126
|
+
subscribeObjectAll(target, cb) {
|
|
127
|
+
return _classPrivateMethodGet(this, _subscribe, _subscribe2).call(this, target, Source.All, cb);
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
function _get_targets() {
|
|
131
|
+
return new Set(_classPrivateFieldGet(this, _subscriptions).map(_ref => {
|
|
132
|
+
let [target] = _ref;
|
|
133
|
+
return target;
|
|
134
|
+
}));
|
|
135
|
+
}
|
|
136
|
+
function _sendMessage2(message) {
|
|
137
|
+
if (_classPrivateFieldGet(this, _webSocket) == null) throw new UnexpectedTsError();
|
|
138
|
+
_classPrivateFieldGet(this, _webSocket).send(JSON.stringify(message));
|
|
139
|
+
}
|
|
140
|
+
function _sendSubscribe2(isSubscribe, target) {
|
|
141
|
+
if (_classPrivateFieldGet(this, _webSocket) == null) return;
|
|
142
|
+
const payload = ['KeyBlocks', 'MicroBlocks', 'Transactions'].includes(target) ? target : 'Object';
|
|
143
|
+
_classPrivateMethodGet(this, _sendMessage, _sendMessage2).call(this, {
|
|
144
|
+
op: isSubscribe ? 'Subscribe' : 'Unsubscribe',
|
|
145
|
+
payload,
|
|
146
|
+
...(payload === 'Object' && {
|
|
147
|
+
target
|
|
148
|
+
})
|
|
149
|
+
});
|
|
150
|
+
_classPrivateFieldGet(this, _requestQueue).push([isSubscribe, target]);
|
|
151
|
+
}
|
|
152
|
+
function _emit2(condition, p, e) {
|
|
153
|
+
_classPrivateFieldGet(this, _subscriptions).filter(_ref2 => {
|
|
154
|
+
let [target, source] = _ref2;
|
|
155
|
+
return condition(target, source);
|
|
156
|
+
}).forEach(_ref3 => {
|
|
157
|
+
let [,, cb] = _ref3;
|
|
158
|
+
return cb(p, e);
|
|
159
|
+
});
|
|
160
|
+
}
|
|
161
|
+
function _disconnect2() {
|
|
162
|
+
let onlyReset = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
|
|
163
|
+
if (_classPrivateFieldGet(this, _webSocket) == null) return;
|
|
164
|
+
if (!onlyReset) _classPrivateFieldGet(this, _webSocket).close();
|
|
165
|
+
Object.assign(_classPrivateFieldGet(this, _webSocket), {
|
|
166
|
+
onopen: undefined,
|
|
167
|
+
onerror: undefined,
|
|
168
|
+
onmessage: undefined
|
|
169
|
+
});
|
|
170
|
+
_classPrivateFieldSet(this, _webSocket, undefined);
|
|
171
|
+
}
|
|
172
|
+
function _messageHandler2(message) {
|
|
173
|
+
if (typeof message === 'string' || Array.isArray(message)) {
|
|
174
|
+
const request = _classPrivateFieldGet(this, _requestQueue).shift();
|
|
175
|
+
if (request == null) throw new InternalError('Request queue is empty');
|
|
176
|
+
const [isSubscribe, target] = request;
|
|
177
|
+
let error;
|
|
178
|
+
if (typeof message === 'string') error = new MiddlewareSubscriberError(message);
|
|
179
|
+
if (message.includes(target) !== isSubscribe) {
|
|
180
|
+
error = new InternalError(`Expected ${target} to be${isSubscribe ? '' : ' not'} included into ${message}`);
|
|
181
|
+
}
|
|
182
|
+
if (error != null) _classPrivateMethodGet(this, _emit, _emit2).call(this, t => target === t, undefined, error);
|
|
183
|
+
return;
|
|
184
|
+
}
|
|
185
|
+
_classPrivateMethodGet(this, _emit, _emit2).call(this, (target, source) => (target === message.subscription || target === message.target) && (source === message.source || source === Source.All), message.payload);
|
|
186
|
+
}
|
|
187
|
+
function _subscribe2(target, source, cb) {
|
|
188
|
+
const subscription = [target, source, cb];
|
|
189
|
+
if (_classPrivateFieldGet(this, _targets).size === 0) this.reconnect();
|
|
190
|
+
if (!_classPrivateFieldGet(this, _targets).has(target)) _classPrivateMethodGet(this, _sendSubscribe, _sendSubscribe2).call(this, true, target);
|
|
191
|
+
_classPrivateFieldGet(this, _subscriptions).push(subscription);
|
|
192
|
+
return () => {
|
|
193
|
+
_classPrivateFieldSet(this, _subscriptions, _classPrivateFieldGet(this, _subscriptions).filter(item => item !== subscription));
|
|
194
|
+
if (!_classPrivateFieldGet(this, _targets).has(target)) _classPrivateMethodGet(this, _sendSubscribe, _sendSubscribe2).call(this, false, target);
|
|
195
|
+
if (_classPrivateFieldGet(this, _targets).size === 0) _classPrivateMethodGet(this, _disconnect, _disconnect2).call(this);
|
|
196
|
+
};
|
|
197
|
+
}
|
|
198
|
+
//# sourceMappingURL=MiddlewareSubscriber.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"MiddlewareSubscriber.mjs","names":["WebSocket","BaseError","UnexpectedTsError","InternalError","Source","MiddlewareSubscriberError","constructor","message","name","MiddlewareSubscriberDisconnected","closeEvent","_subscriptions","WeakMap","_requestQueue","_webSocket","_targets","_sendMessage","WeakSet","_sendSubscribe","_emit","_disconnect","_messageHandler","_subscribe","MiddlewareSubscriber","webSocket","_classPrivateFieldGet","url","_classPrivateMethodInitSpec","_classPrivateFieldInitSpec","get","_get_targets","set","writable","value","reconnect","_classPrivateMethodGet","_disconnect2","call","_classPrivateFieldSet","Promise","resolve","Object","assign","onopen","onerror","errorEvent","_emit2","undefined","error","onmessage","event","data","_messageHandler2","JSON","parse","onclose","all","map","target","_sendSubscribe2","subscribeKeyBlocks","cb","_subscribe2","Middleware","subscribeKeyBlocksNode","Node","subscribeKeyBlocksAll","All","subscribeMicroBlocks","subscribeMicroBlocksNode","subscribeMicroBlocksAll","subscribeTransactions","subscribeTransactionsNode","subscribeTransactionsAll","subscribeObject","subscribeObjectNode","subscribeObjectAll","Set","_ref","_sendMessage2","send","stringify","isSubscribe","payload","includes","op","push","condition","p","e","filter","_ref2","source","forEach","_ref3","onlyReset","arguments","length","close","Array","isArray","request","shift","t","subscription","size","has","item"],"sources":["../src/MiddlewareSubscriber.ts"],"sourcesContent":["/* eslint-disable max-classes-per-file */\nimport WebSocket from 'isomorphic-ws';\nimport { BaseError, UnexpectedTsError, InternalError } from './utils/errors';\nimport { Encoded } from './utils/encoder';\n\ninterface Message {\n payload: Object;\n source: Source.Middleware | Source.Node;\n subscription: 'KeyBlocks' | 'MicroBlocks' | 'Transactions' | 'Object';\n target?: string;\n}\n\nenum Source {\n Middleware = 'mdw',\n Node = 'node',\n All = 'all',\n}\n\nexport class MiddlewareSubscriberError extends BaseError {\n constructor(message: string) {\n super(message);\n this.name = 'MiddlewareSubscriberError';\n }\n}\n\nexport class MiddlewareSubscriberDisconnected extends MiddlewareSubscriberError {\n constructor(readonly closeEvent: WebSocket.CloseEvent) {\n super('Connection closed');\n this.name = 'MiddlewareSubscriberDisconnected';\n }\n}\n\nexport default class MiddlewareSubscriber {\n #subscriptions: Array<\n readonly [target: string, s: Source, cb: (p?: Object, e?: Error) => void]\n > = [];\n\n #requestQueue: Array<[isSubscribe: boolean, target: string]> = [];\n\n #webSocket?: WebSocket;\n\n get webSocket(): WebSocket | undefined {\n return this.#webSocket;\n }\n\n get #targets(): Set<string> {\n return new Set(this.#subscriptions.map(([target]) => target));\n }\n\n #sendMessage(message: any): void {\n if (this.#webSocket == null) throw new UnexpectedTsError();\n this.#webSocket.send(JSON.stringify(message));\n }\n\n #sendSubscribe(isSubscribe: boolean, target: string): void {\n if (this.#webSocket == null) return;\n const payload = ['KeyBlocks', 'MicroBlocks', 'Transactions'].includes(target)\n ? target : 'Object';\n this.#sendMessage({\n op: isSubscribe ? 'Subscribe' : 'Unsubscribe',\n payload,\n ...payload === 'Object' && { target },\n });\n this.#requestQueue.push([isSubscribe, target]);\n }\n\n #emit(condition: (target: string, source: Source) => boolean, p?: Object, e?: Error): void {\n this.#subscriptions\n .filter(([target, source]) => condition(target, source))\n .forEach(([, , cb]) => cb(p, e));\n }\n\n constructor(readonly url: string) {\n }\n\n #disconnect(onlyReset = false): void {\n if (this.#webSocket == null) return;\n if (!onlyReset) this.#webSocket.close();\n Object.assign(this.#webSocket, {\n onopen: undefined,\n onerror: undefined,\n onmessage: undefined,\n });\n this.#webSocket = undefined;\n }\n\n async reconnect(): Promise<void> {\n this.#disconnect();\n this.#webSocket = await new Promise((resolve) => {\n const webSocket = new WebSocket(this.url);\n Object.assign(webSocket, {\n onopen: () => resolve(webSocket),\n onerror: (errorEvent: WebSocket.ErrorEvent) => {\n this.#emit(() => true, undefined, errorEvent.error);\n },\n onmessage: (event: WebSocket.MessageEvent) => {\n if (typeof event.data !== 'string') {\n throw new InternalError(`Unknown incoming message type: ${typeof event.data}`);\n }\n this.#messageHandler(JSON.parse(event.data));\n },\n onclose: (event: WebSocket.CloseEvent) => {\n this.#emit(() => true, undefined, new MiddlewareSubscriberDisconnected(event));\n this.#disconnect(true);\n },\n });\n });\n await Promise.all([...this.#targets].map((target) => this.#sendSubscribe(true, target)));\n }\n\n #messageHandler(message: string | string[] | Message): void {\n if (typeof message === 'string' || Array.isArray(message)) {\n const request = this.#requestQueue.shift();\n if (request == null) throw new InternalError('Request queue is empty');\n const [isSubscribe, target] = request;\n let error;\n if (typeof message === 'string') error = new MiddlewareSubscriberError(message);\n if (message.includes(target) !== isSubscribe) {\n error = new InternalError(`Expected ${target} to be${isSubscribe ? '' : ' not'} included into ${message}`);\n }\n if (error != null) this.#emit((t) => target === t, undefined, error);\n return;\n }\n this.#emit(\n (target, source) => (target === message.subscription || target === message.target)\n && (source === message.source || source === Source.All),\n message.payload,\n );\n }\n\n #subscribe(target: string, source: Source, cb: (p?: Object, e?: Error) => void): () => void {\n const subscription = [target, source, cb] as const;\n if (this.#targets.size === 0) this.reconnect();\n if (!this.#targets.has(target)) this.#sendSubscribe(true, target);\n this.#subscriptions.push(subscription);\n return () => {\n this.#subscriptions = this.#subscriptions.filter((item) => item !== subscription);\n if (!this.#targets.has(target)) this.#sendSubscribe(false, target);\n if (this.#targets.size === 0) this.#disconnect();\n };\n }\n\n // TODO: replace p?: any with a proper type definition\n\n subscribeKeyBlocks(cb: (p?: any, e?: Error) => void): () => void {\n return this.#subscribe('KeyBlocks', Source.Middleware, cb);\n }\n\n subscribeKeyBlocksNode(cb: (p?: any, e?: Error) => void): () => void {\n return this.#subscribe('KeyBlocks', Source.Node, cb);\n }\n\n subscribeKeyBlocksAll(cb: (p?: any, e?: Error) => void): () => void {\n return this.#subscribe('KeyBlocks', Source.All, cb);\n }\n\n subscribeMicroBlocks(cb: (p?: any, e?: Error) => void): () => void {\n return this.#subscribe('MicroBlocks', Source.Middleware, cb);\n }\n\n subscribeMicroBlocksNode(cb: (p?: any, e?: Error) => void): () => void {\n return this.#subscribe('MicroBlocks', Source.Node, cb);\n }\n\n subscribeMicroBlocksAll(cb: (p?: any, e?: Error) => void): () => void {\n return this.#subscribe('MicroBlocks', Source.All, cb);\n }\n\n subscribeTransactions(cb: (p?: any, e?: Error) => void): () => void {\n return this.#subscribe('Transactions', Source.Middleware, cb);\n }\n\n subscribeTransactionsNode(cb: (p?: any, e?: Error) => void): () => void {\n return this.#subscribe('Transactions', Source.Node, cb);\n }\n\n subscribeTransactionsAll(cb: (p?: any, e?: Error) => void): () => void {\n return this.#subscribe('Transactions', Source.All, cb);\n }\n\n subscribeObject(\n target: Encoded.KeyBlockHash | Encoded.Channel | Encoded.ContractAddress\n | Encoded.OracleAddress | Encoded.OracleQueryId | Encoded.AccountAddress\n | Encoded.Name | `${string}.chain`,\n cb: (p?: any, e?: Error) => void,\n ): () => void {\n return this.#subscribe(target, Source.Middleware, cb);\n }\n\n subscribeObjectNode(\n target: Encoded.KeyBlockHash | Encoded.Channel | Encoded.ContractAddress\n | Encoded.OracleAddress | Encoded.OracleQueryId | Encoded.AccountAddress\n | Encoded.Name | `${string}.chain`,\n cb: (p?: any, e?: Error) => void,\n ): () => void {\n return this.#subscribe(target, Source.Node, cb);\n }\n\n subscribeObjectAll(\n target: Encoded.KeyBlockHash | Encoded.Channel | Encoded.ContractAddress\n | Encoded.OracleAddress | Encoded.OracleQueryId | Encoded.AccountAddress\n | Encoded.Name | `${string}.chain`,\n cb: (p?: any, e?: Error) => void,\n ): () => void {\n return this.#subscribe(target, Source.All, cb);\n }\n}\n"],"mappings":";;;;;;AAAA;AACA,OAAOA,SAAS,MAAM,eAAe;AAAC,SAC7BC,SAAS,EAAEC,iBAAiB,EAAEC,aAAa;AAAA,IAU/CC,MAAM;AAAA,WAANA,MAAM;EAANA,MAAM;EAANA,MAAM;EAANA,MAAM;AAAA,GAANA,MAAM,KAANA,MAAM;AAMX,OAAO,MAAMC,yBAAyB,SAASJ,SAAS,CAAC;EACvDK,WAAWA,CAACC,OAAe,EAAE;IAC3B,KAAK,CAACA,OAAO,CAAC;IACd,IAAI,CAACC,IAAI,GAAG,2BAA2B;EACzC;AACF;AAEA,OAAO,MAAMC,gCAAgC,SAASJ,yBAAyB,CAAC;EAC9EC,WAAWA,CAAUI,UAAgC,EAAE;IACrD,KAAK,CAAC,mBAAmB,CAAC;IAAC,KADRA,UAAgC,GAAhCA,UAAgC;IAEnD,IAAI,CAACF,IAAI,GAAG,kCAAkC;EAChD;AACF;AAAC,IAAAG,cAAA,oBAAAC,OAAA;AAAA,IAAAC,aAAA,oBAAAD,OAAA;AAAA,IAAAE,UAAA,oBAAAF,OAAA;AAAA,IAAAG,QAAA,oBAAAH,OAAA;AAAA,IAAAI,YAAA,oBAAAC,OAAA;AAAA,IAAAC,cAAA,oBAAAD,OAAA;AAAA,IAAAE,KAAA,oBAAAF,OAAA;AAAA,IAAAG,WAA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
14
14
|
type NodeTransformedApi = new (...args: ConstructorParameters<typeof NodeApi>) => {
|
|
15
15
|
[Name in keyof InstanceType<typeof NodeApi>]: Name extends 'pipeline' | 'sendRequest' | 'sendOperationRequest' ? NodeApi[Name] : TransformNodeType<NodeApi[Name]>;
|
|
16
16
|
};
|
|
17
|
-
|
|
17
|
+
interface NodeInfo {
|
|
18
18
|
url: string;
|
|
19
19
|
nodeNetworkId: string;
|
|
20
20
|
version: string;
|
package/es/Node.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Node.mjs","names":["BigNumber","genRequestQueuesPolicy","genCombineGetRequestsPolicy","genErrorFormatterPolicy","genVersionCheckPolicy","genRetryOnFailurePolicy","Node","NodeApi","mapObject","bigIntPropertyNames","numberPropertyNames","_mapData","WeakSet","_encodeArg","_decodeRes","NodeTransformed","constructor","arguments","_classPrivateMethodInitSpec","sendOperationRequest","operationArguments","operationSpec","args","_ref","key","value","_classPrivateMethodGet","_encodeArg2","call","_decodeRes2","_mapData2","data","transform","Array","isArray","map","d","_ref6","some","k","bigInt","number","toFixed","toString","BigInt","_networkIdPromise","WeakMap","url","ignoreVersion","retryCount","retryOverallDelay","options","length","undefined","allowInsecureConnection","additionalPolicies","body","reason","_classPrivateFieldInitSpec","writable","statusPromise","getStatus","versionPromise","then","_ref2","nodeVersion","error","_classPrivateFieldSet","_ref3","networkId","pipeline","addPolicy","intAsString","getNetworkId","_classPrivateFieldGet2","_classPrivateFieldGet","_ref4","Error","getNodeInfo","version","nodeNetworkId","protocols","topBlockHeight","consensusProtocolVersion","filter","_ref5","effectiveAtHeight","reduce","acc","p","$host"],"sources":["../src/Node.ts"],"sourcesContent":["// eslint-disable-next-line max-classes-per-file\nimport BigNumber from 'bignumber.js';\nimport { OperationArguments, OperationSpec } from '@azure/core-client';\nimport {\n genRequestQueuesPolicy, genCombineGetRequestsPolicy, genErrorFormatterPolicy,\n genVersionCheckPolicy, genRetryOnFailurePolicy,\n} from './utils/autorest';\nimport { Node as NodeApi, NodeOptionalParams, ErrorModel } from './apis/node';\nimport { mapObject } from './utils/other';\nimport { Encoded } from './utils/encoder';\nimport { ConsensusProtocolVersion } from './tx/builder/constants';\n\nconst bigIntPropertyNames = [\n 'balance', 'queryFee', 'fee', 'amount', 'nameFee', 'channelAmount',\n 'initiatorAmount', 'responderAmount', 'channelReserve', 'initiatorAmountFinal',\n 'responderAmountFinal', 'gasPrice', 'deposit',\n] as const;\n\nconst numberPropertyNames = [\n 'time', 'gas', 'gasUsed', 'nameSalt',\n 'nonce', 'nextNonce', 'height', 'blockHeight', 'topBlockHeight',\n 'ttl', 'nameTtl', 'clientTtl',\n 'inbound', 'outbound', 'peerCount', 'pendingTransactionsCount', 'effectiveAtHeight',\n 'version', 'solutions', 'round',\n] as const;\n\nclass NodeTransformed extends NodeApi {\n override async sendOperationRequest(\n operationArguments: OperationArguments,\n operationSpec: OperationSpec,\n ): Promise<any> {\n const args = mapObject(\n operationArguments,\n ([key, value]) => [key, this.#encodeArg(value)],\n ) as OperationArguments;\n return this.#decodeRes(await super.sendOperationRequest(args, operationSpec));\n }\n\n #mapData(data: any, transform: {\n bigInt: (v: any) => any;\n number: (v: any) => any;\n }): unknown {\n if (Array.isArray(data)) return data.map((d) => this.#mapData(d, transform));\n if (data != null && typeof data === 'object') {\n return mapObject(data, ([key, value]) => {\n if (value == null) return [key, value];\n if (bigIntPropertyNames.some((k) => k === key)) return [key, transform.bigInt(value)];\n if (numberPropertyNames.some((k) => k === key)) return [key, transform.number(value)];\n return [key, this.#mapData(value, transform)];\n });\n }\n return data;\n }\n\n #encodeArg(data: any): any {\n return this.#mapData(data, {\n bigInt: (value) => {\n if (value instanceof BigNumber) return value.toFixed();\n return value.toString();\n },\n number: (value) => value.toString(),\n });\n }\n\n #decodeRes(data: any): any {\n return this.#mapData(data, {\n bigInt: (value) => BigInt(value),\n number: (value) => +value,\n });\n }\n}\n\ntype BigIntPropertyNames = typeof bigIntPropertyNames[number];\ntype NumberPropertyNames = typeof numberPropertyNames[number];\ntype PreserveOptional<NewType, OrigType> =\n OrigType extends undefined ? NewType | undefined : NewType;\nexport type TransformNodeType<Type> =\n Type extends (...args: infer Args) => infer Ret\n ? (...args: TransformNodeType<Args>) => TransformNodeType<Ret>\n : Type extends [infer Item, ...infer Rest]\n ? [TransformNodeType<Item>, ...TransformNodeType<Rest>]\n : Type extends Array<infer Item>\n ? Array<TransformNodeType<Item>>\n : Type extends Promise<infer T>\n ? Promise<TransformNodeType<T>>\n : Type extends { [P in any]: any }\n ? {\n [Property in keyof Type]:\n Property extends BigIntPropertyNames\n ? PreserveOptional<bigint, Type[Property]>\n : Property extends NumberPropertyNames\n ? PreserveOptional<number, Type[Property]>\n : Property extends 'txHash'\n ? PreserveOptional<Encoded.TxHash, Type[Property]>\n : Property extends 'bytecode'\n ? PreserveOptional<Encoded.ContractBytearray, Type[Property]>\n : TransformNodeType<Type[Property]>\n }\n : Type;\ntype NodeTransformedApi = new (...args: ConstructorParameters<typeof NodeApi>) => {\n [Name in keyof InstanceType<typeof NodeApi>]:\n Name extends 'pipeline' | 'sendRequest' | 'sendOperationRequest'\n ? NodeApi[Name] : TransformNodeType<NodeApi[Name]>\n};\n\nexport interface NodeInfo {\n url: string;\n nodeNetworkId: string;\n version: string;\n consensusProtocolVersion: ConsensusProtocolVersion;\n}\n\nexport default class Node extends (NodeTransformed as unknown as NodeTransformedApi) {\n #networkIdPromise?: Promise<string | Error>;\n\n /**\n * @param url - Url for node API\n * @param options - Options\n * @param options.ignoreVersion - Don't check node version\n * @param options.retryCount - Amount of extra requests to do in case of failure\n * @param options.retryOverallDelay - Time in ms to wait between all retries\n */\n constructor(\n url: string,\n {\n ignoreVersion = false, retryCount = 3, retryOverallDelay = 800, ...options\n }: NodeOptionalParams & {\n ignoreVersion?: boolean;\n retryCount?: number;\n retryOverallDelay?: number;\n } = {},\n ) {\n // eslint-disable-next-line constructor-super\n super(url, {\n allowInsecureConnection: true,\n additionalPolicies: [\n genRequestQueuesPolicy(),\n genCombineGetRequestsPolicy(),\n genRetryOnFailurePolicy(retryCount, retryOverallDelay),\n genErrorFormatterPolicy((body: ErrorModel) => ` ${body.reason}`),\n ],\n ...options,\n });\n if (!ignoreVersion) {\n const statusPromise = this.getStatus();\n const versionPromise = statusPromise.then(({ nodeVersion }) => nodeVersion, (error) => error);\n this.#networkIdPromise = statusPromise.then(({ networkId }) => networkId, (error) => error);\n this.pipeline.addPolicy(\n genVersionCheckPolicy('node', '/v3/status', versionPromise, '6.2.0', '7.0.0'),\n );\n }\n this.intAsString = true;\n }\n\n async getNetworkId(): Promise<string> {\n this.#networkIdPromise ??= this.getStatus().then(({ networkId }) => networkId);\n const networkId = await this.#networkIdPromise;\n if (networkId instanceof Error) throw networkId;\n return networkId;\n }\n\n async getNodeInfo(): Promise<NodeInfo> {\n const {\n nodeVersion: version,\n networkId: nodeNetworkId,\n protocols,\n topBlockHeight,\n } = await this.getStatus();\n const consensusProtocolVersion = protocols\n .filter(({ effectiveAtHeight }) => topBlockHeight >= effectiveAtHeight)\n .reduce(\n (acc, p) => (p.effectiveAtHeight > acc.effectiveAtHeight ? p : acc),\n { effectiveAtHeight: -1, version: 0 },\n )\n .version;\n return {\n url: this.$host,\n nodeNetworkId,\n version,\n consensusProtocolVersion,\n };\n }\n}\n"],"mappings":";;;;;;AAAA;AACA,OAAOA,SAAS,MAAM,cAAc;AAAC,SAGnCC,sBAAsB,EAAEC,2BAA2B,EAAEC,uBAAuB,EAC5EC,qBAAqB,EAAEC,uBAAuB;AAAA,SAEvCC,IAAI,IAAIC,OAAO;AAAA,SACfC,SAAS;AAIlB,MAAMC,mBAAmB,GAAG,CAC1B,SAAS,EAAE,UAAU,EAAE,KAAK,EAAE,QAAQ,EAAE,SAAS,EAAE,eAAe,EAClE,iBAAiB,EAAE,iBAAiB,EAAE,gBAAgB,EAAE,sBAAsB,EAC9E,sBAAsB,EAAE,UAAU,EAAE,SAAS,CACrC;AAEV,MAAMC,mBAAmB,GAA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;IAAE,CAAC,CACtC,CACAA,OAAO;IACV,OAAO;MACLhC,GAAG,EAAE,IAAI,CAAC2C,KAAK;MACfV,aAAa;MACbD,OAAO;MACPI;IACF,CAAC;EACH;AACF"}
|
|
1
|
+
{"version":3,"file":"Node.mjs","names":["BigNumber","genRequestQueuesPolicy","genCombineGetRequestsPolicy","genErrorFormatterPolicy","genVersionCheckPolicy","genRetryOnFailurePolicy","Node","NodeApi","mapObject","bigIntPropertyNames","numberPropertyNames","_mapData","WeakSet","_encodeArg","_decodeRes","NodeTransformed","constructor","arguments","_classPrivateMethodInitSpec","sendOperationRequest","operationArguments","operationSpec","args","_ref","key","value","_classPrivateMethodGet","_encodeArg2","call","_decodeRes2","_mapData2","data","transform","Array","isArray","map","d","_ref6","some","k","bigInt","number","toFixed","toString","BigInt","_networkIdPromise","WeakMap","url","ignoreVersion","retryCount","retryOverallDelay","options","length","undefined","allowInsecureConnection","additionalPolicies","body","reason","_classPrivateFieldInitSpec","writable","statusPromise","getStatus","versionPromise","then","_ref2","nodeVersion","error","_classPrivateFieldSet","_ref3","networkId","pipeline","addPolicy","intAsString","getNetworkId","_classPrivateFieldGet2","_classPrivateFieldGet","_ref4","Error","getNodeInfo","version","nodeNetworkId","protocols","topBlockHeight","consensusProtocolVersion","filter","_ref5","effectiveAtHeight","reduce","acc","p","$host"],"sources":["../src/Node.ts"],"sourcesContent":["// eslint-disable-next-line max-classes-per-file\nimport BigNumber from 'bignumber.js';\nimport { OperationArguments, OperationSpec } from '@azure/core-client';\nimport {\n genRequestQueuesPolicy, genCombineGetRequestsPolicy, genErrorFormatterPolicy,\n genVersionCheckPolicy, genRetryOnFailurePolicy,\n} from './utils/autorest';\nimport { Node as NodeApi, NodeOptionalParams, ErrorModel } from './apis/node';\nimport { mapObject } from './utils/other';\nimport { Encoded } from './utils/encoder';\nimport { ConsensusProtocolVersion } from './tx/builder/constants';\n\nconst bigIntPropertyNames = [\n 'balance', 'queryFee', 'fee', 'amount', 'nameFee', 'channelAmount',\n 'initiatorAmount', 'responderAmount', 'channelReserve', 'initiatorAmountFinal',\n 'responderAmountFinal', 'gasPrice', 'deposit',\n] as const;\n\nconst numberPropertyNames = [\n 'time', 'gas', 'gasUsed', 'nameSalt',\n 'nonce', 'nextNonce', 'height', 'blockHeight', 'topBlockHeight',\n 'ttl', 'nameTtl', 'clientTtl',\n 'inbound', 'outbound', 'peerCount', 'pendingTransactionsCount', 'effectiveAtHeight',\n 'version', 'solutions', 'round',\n] as const;\n\nclass NodeTransformed extends NodeApi {\n override async sendOperationRequest(\n operationArguments: OperationArguments,\n operationSpec: OperationSpec,\n ): Promise<any> {\n const args = mapObject(\n operationArguments,\n ([key, value]) => [key, this.#encodeArg(value)],\n ) as OperationArguments;\n return this.#decodeRes(await super.sendOperationRequest(args, operationSpec));\n }\n\n #mapData(data: any, transform: {\n bigInt: (v: any) => any;\n number: (v: any) => any;\n }): unknown {\n if (Array.isArray(data)) return data.map((d) => this.#mapData(d, transform));\n if (data != null && typeof data === 'object') {\n return mapObject(data, ([key, value]) => {\n if (value == null) return [key, value];\n if (bigIntPropertyNames.some((k) => k === key)) return [key, transform.bigInt(value)];\n if (numberPropertyNames.some((k) => k === key)) return [key, transform.number(value)];\n return [key, this.#mapData(value, transform)];\n });\n }\n return data;\n }\n\n #encodeArg(data: any): any {\n return this.#mapData(data, {\n bigInt: (value) => {\n if (value instanceof BigNumber) return value.toFixed();\n return value.toString();\n },\n number: (value) => value.toString(),\n });\n }\n\n #decodeRes(data: any): any {\n return this.#mapData(data, {\n bigInt: (value) => BigInt(value),\n number: (value) => +value,\n });\n }\n}\n\ntype BigIntPropertyNames = typeof bigIntPropertyNames[number];\ntype NumberPropertyNames = typeof numberPropertyNames[number];\ntype PreserveOptional<NewType, OrigType> =\n OrigType extends undefined ? NewType | undefined : NewType;\nexport type TransformNodeType<Type> =\n Type extends (...args: infer Args) => infer Ret\n ? (...args: TransformNodeType<Args>) => TransformNodeType<Ret>\n : Type extends [infer Item, ...infer Rest]\n ? [TransformNodeType<Item>, ...TransformNodeType<Rest>]\n : Type extends Array<infer Item>\n ? Array<TransformNodeType<Item>>\n : Type extends Promise<infer T>\n ? Promise<TransformNodeType<T>>\n : Type extends { [P in any]: any }\n ? {\n [Property in keyof Type]:\n Property extends BigIntPropertyNames\n ? PreserveOptional<bigint, Type[Property]>\n : Property extends NumberPropertyNames\n ? PreserveOptional<number, Type[Property]>\n : Property extends 'txHash'\n ? PreserveOptional<Encoded.TxHash, Type[Property]>\n : Property extends 'bytecode'\n ? PreserveOptional<Encoded.ContractBytearray, Type[Property]>\n : TransformNodeType<Type[Property]>\n }\n : Type;\ntype NodeTransformedApi = new (...args: ConstructorParameters<typeof NodeApi>) => {\n [Name in keyof InstanceType<typeof NodeApi>]:\n Name extends 'pipeline' | 'sendRequest' | 'sendOperationRequest'\n ? NodeApi[Name] : TransformNodeType<NodeApi[Name]>\n};\n\ninterface NodeInfo {\n url: string;\n nodeNetworkId: string;\n version: string;\n consensusProtocolVersion: ConsensusProtocolVersion;\n}\n\nexport default class Node extends (NodeTransformed as unknown as NodeTransformedApi) {\n #networkIdPromise?: Promise<string | Error>;\n\n /**\n * @param url - Url for node API\n * @param options - Options\n * @param options.ignoreVersion - Don't check node version\n * @param options.retryCount - Amount of extra requests to do in case of failure\n * @param options.retryOverallDelay - Time in ms to wait between all retries\n */\n constructor(\n url: string,\n {\n ignoreVersion = false, retryCount = 3, retryOverallDelay = 800, ...options\n }: NodeOptionalParams & {\n ignoreVersion?: boolean;\n retryCount?: number;\n retryOverallDelay?: number;\n } = {},\n ) {\n // eslint-disable-next-line constructor-super\n super(url, {\n allowInsecureConnection: true,\n additionalPolicies: [\n genRequestQueuesPolicy(),\n genCombineGetRequestsPolicy(),\n genRetryOnFailurePolicy(retryCount, retryOverallDelay),\n genErrorFormatterPolicy((body: ErrorModel) => ` ${body.reason}`),\n ],\n ...options,\n });\n if (!ignoreVersion) {\n const statusPromise = this.getStatus();\n const versionPromise = statusPromise.then(({ nodeVersion }) => nodeVersion, (error) => error);\n this.#networkIdPromise = statusPromise.then(({ networkId }) => networkId, (error) => error);\n this.pipeline.addPolicy(\n genVersionCheckPolicy('node', '/v3/status', versionPromise, '6.2.0', '7.0.0'),\n );\n }\n this.intAsString = true;\n }\n\n async getNetworkId(): Promise<string> {\n this.#networkIdPromise ??= this.getStatus().then(({ networkId }) => networkId);\n const networkId = await this.#networkIdPromise;\n if (networkId instanceof Error) throw networkId;\n return networkId;\n }\n\n async getNodeInfo(): Promise<NodeInfo> {\n const {\n nodeVersion: version,\n networkId: nodeNetworkId,\n protocols,\n topBlockHeight,\n } = await this.getStatus();\n const consensusProtocolVersion = protocols\n .filter(({ effectiveAtHeight }) => topBlockHeight >= effectiveAtHeight)\n .reduce(\n (acc, p) => (p.effectiveAtHeight > acc.effectiveAtHeight ? p : acc),\n { effectiveAtHeight: -1, version: 0 },\n )\n .version;\n return {\n url: this.$host,\n nodeNetworkId,\n version,\n consensusProtocolVersion,\n };\n }\n}\n"],"mappings":";;;;;;AAAA;AACA,OAAOA,SAAS,MAAM,cAAc;AAAC,SAGnCC,sBAAsB,EAAEC,2BAA2B,EAAEC,uBAAuB,EAC5EC,qBAAqB,EAAEC,uBAAuB;AAAA,SAEvCC,IAAI,IAAIC,OAAO;AAAA,SACfC,SAAS;AAIlB,MAAMC,mBAAmB,GAAG,CAC1B,SAAS,EAAE,UAAU,EAAE,KAAK,EAAE,QAAQ,EAAE,SAAS,EAAE,eAAe,EAClE,iBAAiB,EAAE,iBAAiB,EAAE,gBAAgB,EAAE,sBAAsB,EAC9E,sBAAsB,EAAE,UAAU,EAAE,SAAS,CACrC;AAEV,MAAMC,mBAAmB,GAAG,CAC1B,MAAM,EAAE,KAAK,EAAE,SAAS,EAAE,UAAU,EACpC,OAAO,EAAE,WAAW,EAAE,QAAQ,EAAE,aAAa,EAAE,gBAAgB,EAC/D,KAAK,EAAE,SAAS,EAAE,WAAW,EAC7B,SAAS,EAAE,UAAU,EAAE,WAAW,EAAE,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ils/encoder';
|
|
|
2
2
|
import Node from '../Node';
|
|
3
3
|
import CompilerBase from '../contract/compiler/Base';
|
|
4
4
|
import { Int } from '../tx/builder/constants';
|
|
5
|
+
import { AciValue, Domain } from '../utils/typed-data';
|
|
5
6
|
interface AuthData {
|
|
6
7
|
fee?: Int;
|
|
7
8
|
gasLimit?: number;
|
|
@@ -36,17 +37,28 @@ export default abstract class AccountBase {
|
|
|
36
37
|
* Sign message
|
|
37
38
|
* @param message - Message to sign
|
|
38
39
|
* @param options - Options
|
|
39
|
-
* @returns Signature
|
|
40
|
+
* @returns Signature
|
|
40
41
|
*/
|
|
41
42
|
abstract signMessage(message: string, options?: {
|
|
42
43
|
aeppOrigin?: string;
|
|
43
44
|
aeppRpcClientId?: string;
|
|
44
45
|
}): Promise<Uint8Array>;
|
|
46
|
+
/**
|
|
47
|
+
* Sign typed data
|
|
48
|
+
* @param type - Type of data to sign
|
|
49
|
+
* @param data - Encoded data to sign
|
|
50
|
+
* @param options - Options
|
|
51
|
+
* @returns Signature
|
|
52
|
+
*/
|
|
53
|
+
abstract signTypedData(data: Encoded.ContractBytearray, aci: AciValue, options?: Domain & {
|
|
54
|
+
aeppOrigin?: string;
|
|
55
|
+
aeppRpcClientId?: string;
|
|
56
|
+
}): Promise<Encoded.Signature>;
|
|
45
57
|
/**
|
|
46
58
|
* Sign data blob
|
|
47
59
|
* @param data - Data blob to sign
|
|
48
60
|
* @param options - Options
|
|
49
|
-
* @returns
|
|
61
|
+
* @returns Signature
|
|
50
62
|
*/
|
|
51
63
|
abstract sign(data: string | Uint8Array, options?: any): Promise<Uint8Array>;
|
|
52
64
|
/**
|
package/es/account/Base.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Base.mjs","names":["AccountBase"],"sources":["../../src/account/Base.ts"],"sourcesContent":["import { Encoded } from '../utils/encoder';\nimport Node from '../Node';\nimport CompilerBase from '../contract/compiler/Base';\nimport { Int } from '../tx/builder/constants';\n\ninterface AuthData {\n fee?: Int;\n gasLimit?: number;\n gasPrice?: Int;\n callData?: Encoded.ContractBytearray;\n sourceCode?: string;\n args?: any[];\n}\n\n/**\n * Account is one of the three basic building blocks of an\n * {@link AeSdk} and provides access to a signing key pair.\n */\nexport default abstract class AccountBase {\n /**\n * Sign encoded transaction\n * @param tx - Transaction to sign\n * @param options - Options\n * @param options.innerTx - Sign as inner transaction for PayingFor\n * @param options.authData - Object with gaMeta params\n * @returns Signed transaction\n */\n abstract signTransaction(\n tx: Encoded.Transaction,\n options: {\n innerTx?: boolean;\n networkId?: string;\n authData?: AuthData | ((tx: Encoded.Transaction) => Promise<AuthData>);\n onNode?: Node;\n onCompiler?: CompilerBase;\n aeppOrigin?: string;\n aeppRpcClientId?: string;\n },\n ): Promise<Encoded.Transaction>;\n\n /**\n * Sign message\n * @param message - Message to sign\n * @param options - Options\n * @returns Signature
|
|
1
|
+
{"version":3,"file":"Base.mjs","names":["AccountBase"],"sources":["../../src/account/Base.ts"],"sourcesContent":["import { Encoded } from '../utils/encoder';\nimport Node from '../Node';\nimport CompilerBase from '../contract/compiler/Base';\nimport { Int } from '../tx/builder/constants';\nimport { AciValue, Domain } from '../utils/typed-data';\n\ninterface AuthData {\n fee?: Int;\n gasLimit?: number;\n gasPrice?: Int;\n callData?: Encoded.ContractBytearray;\n sourceCode?: string;\n args?: any[];\n}\n\n/**\n * Account is one of the three basic building blocks of an\n * {@link AeSdk} and provides access to a signing key pair.\n */\nexport default abstract class AccountBase {\n /**\n * Sign encoded transaction\n * @param tx - Transaction to sign\n * @param options - Options\n * @param options.innerTx - Sign as inner transaction for PayingFor\n * @param options.authData - Object with gaMeta params\n * @returns Signed transaction\n */\n abstract signTransaction(\n tx: Encoded.Transaction,\n options: {\n innerTx?: boolean;\n networkId?: string;\n authData?: AuthData | ((tx: Encoded.Transaction) => Promise<AuthData>);\n onNode?: Node;\n onCompiler?: CompilerBase;\n aeppOrigin?: string;\n aeppRpcClientId?: string;\n },\n ): Promise<Encoded.Transaction>;\n\n /**\n * Sign message\n * @param message - Message to sign\n * @param options - Options\n * @returns Signature\n */\n abstract signMessage(\n message: string,\n options?: {\n aeppOrigin?: string;\n aeppRpcClientId?: string;\n },\n ): Promise<Uint8Array>;\n\n /**\n * Sign typed data\n * @param type - Type of data to sign\n * @param data - Encoded data to sign\n * @param options - Options\n * @returns Signature\n */\n abstract signTypedData(\n data: Encoded.ContractBytearray,\n aci: AciValue,\n options?: Domain & {\n aeppOrigin?: string;\n aeppRpcClientId?: string;\n },\n ): Promise<Encoded.Signature>;\n\n /**\n * Sign data blob\n * @param data - Data blob to sign\n * @param options - Options\n * @returns Signature\n */\n abstract sign(data: string | Uint8Array, options?: any): Promise<Uint8Array>;\n\n /**\n * Account address\n */\n readonly address!: Encoded.AccountAddress;\n}\n"],"mappings":"AAeA;AACA;AACA;AACA;AACA,eAAe,MAAeA,WAAW,CAAC"}
|
|
@@ -12,5 +12,6 @@ export default class AccountGeneralized extends AccountBase {
|
|
|
12
12
|
constructor(address: Encoded.AccountAddress);
|
|
13
13
|
sign(): Promise<Uint8Array>;
|
|
14
14
|
signMessage(): Promise<Uint8Array>;
|
|
15
|
+
signTypedData(): Promise<Encoded.Signature>;
|
|
15
16
|
signTransaction(tx: Encoded.Transaction, { authData, onCompiler, onNode }: Parameters<AccountBase['signTransaction']>[1]): Promise<Encoded.Transaction>;
|
|
16
17
|
}
|
|
@@ -36,6 +36,11 @@ export default class AccountGeneralized extends AccountBase {
|
|
|
36
36
|
async signMessage() {
|
|
37
37
|
throw new NotImplementedError('Can\'t sign using generalized account');
|
|
38
38
|
}
|
|
39
|
+
|
|
40
|
+
// eslint-disable-next-line class-methods-use-this
|
|
41
|
+
async signTypedData() {
|
|
42
|
+
throw new NotImplementedError('Can\'t sign using generalized account');
|
|
43
|
+
}
|
|
39
44
|
async signTransaction(tx, _ref) {
|
|
40
45
|
let {
|
|
41
46
|
authData,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Generalized.mjs","names":["AccountBase","ArgumentError","InternalError","InvalidAuthDataError","NotImplementedError","decode","getAccount","Contract","buildTxAsync","buildTx","Tag","_authFun","WeakMap","AccountGeneralized","constructor","address","_classPrivateFieldInitSpec","writable","value","sign","signMessage","signTransaction","tx","_ref","authData","onCompiler","onNode","callData","sourceCode","args","fee","gasLimit","gasPrice","authCallData","_classPrivateFieldGet","account","kind","_classPrivateFieldSet","authFun","contract","initialize","_calldata","encode","_name","gaMetaTx","tag","GaMetaTx","SignedTx","encodedTx","signatures","gaId"],"sources":["../../src/account/Generalized.ts"],"sourcesContent":["import AccountBase from './Base';\nimport {\n ArgumentError,\n InternalError,\n InvalidAuthDataError,\n NotImplementedError,\n} from '../utils/errors';\nimport { decode, Encoded } from '../utils/encoder';\nimport { getAccount } from '../chain';\nimport Contract from '../contract/Contract';\nimport { buildTxAsync, buildTx } from '../tx/builder';\nimport { Tag } from '../tx/builder/constants';\n\n/**\n * Generalized account class\n */\nexport default class AccountGeneralized extends AccountBase {\n override readonly address: Encoded.AccountAddress;\n\n #authFun?: string;\n\n /**\n * @param address - Address of generalized account\n */\n constructor(address: Encoded.AccountAddress) {\n super();\n decode(address);\n this.address = address;\n }\n\n // eslint-disable-next-line class-methods-use-this\n override async sign(): Promise<Uint8Array> {\n throw new NotImplementedError('Can\\'t sign using generalized account');\n }\n\n // eslint-disable-next-line class-methods-use-this\n override async signMessage(): Promise<Uint8Array> {\n throw new NotImplementedError('Can\\'t sign using generalized account');\n }\n\n override async signTransaction(\n tx: Encoded.Transaction,\n { authData, onCompiler, onNode }: Parameters<AccountBase['signTransaction']>[1],\n ): Promise<Encoded.Transaction> {\n if (authData == null || onCompiler == null || onNode == null) {\n throw new ArgumentError('authData, onCompiler, onNode', 'provided', null);\n }\n const {\n callData, sourceCode, args, fee, gasLimit, gasPrice,\n } = typeof authData === 'function' ? await authData(tx) : authData;\n\n const authCallData = callData ?? await (async () => {\n if (this.#authFun == null) {\n const account = await getAccount(this.address, { onNode });\n if (account.kind !== 'generalized') {\n throw new ArgumentError('account kind', 'generalized', account.kind);\n }\n this.#authFun = account.authFun;\n }\n if (this.#authFun == null) {\n throw new InternalError('Account in generalised, but authFun not provided');\n }\n\n if (sourceCode == null || args == null) {\n throw new InvalidAuthDataError('Auth data must contain sourceCode and args or callData.');\n }\n const contract = await Contract.initialize({ onCompiler, onNode, sourceCode });\n return contract._calldata.encode(contract._name, this.#authFun, args);\n })();\n\n const gaMetaTx = await buildTxAsync({\n tag: Tag.GaMetaTx,\n tx: { tag: Tag.SignedTx, encodedTx: decode(tx), signatures: [] },\n gaId: this.address,\n authData: authCallData,\n fee,\n gasLimit,\n gasPrice,\n onNode,\n });\n return buildTx({ tag: Tag.SignedTx, encodedTx: decode(gaMetaTx), signatures: [] });\n }\n}\n"],"mappings":";;;;OAAOA,WAAW;AAAA,SAEhBC,aAAa,EACbC,aAAa,EACbC,oBAAoB,EACpBC,mBAAmB;AAAA,SAEZC,MAAM;AAAA,SACNC,UAAU;AAAA,OACZC,QAAQ;AAAA,SACNC,YAAY,EAAEC,OAAO;AAAA,SACrBC,GAAG;AAEZ;AACA;AACA;AAFA,IAAAC,QAAA,oBAAAC,OAAA;AAGA,eAAe,MAAMC,kBAAkB,SAASb,WAAW,CAAC;EAK1D;AACF;AACA;EACEc,WAAWA,CAACC,OAA+B,EAAE;IAC3C,KAAK,EAAE;IAACC,0BAAA,OAAAL,QAAA;MAAAM,QAAA;MAAAC,KAAA;IAAA;IACRb,MAAM,CAACU,OAAO,CAAC;IACf,IAAI,CAACA,OAAO,GAAGA,OAAO;EACxB;;EAEA;EACA,MAAeI,IAAIA,CAAA,EAAwB;IACzC,MAAM,IAAIf,mBAAmB,CAAC,uCAAuC,CAAC;EACxE;;EAEA;EACA,MAAegB,WAAWA,CAAA,EAAwB;IAChD,MAAM,IAAIhB,mBAAmB,CAAC,uCAAuC,CAAC;EACxE;
|
|
1
|
+
{"version":3,"file":"Generalized.mjs","names":["AccountBase","ArgumentError","InternalError","InvalidAuthDataError","NotImplementedError","decode","getAccount","Contract","buildTxAsync","buildTx","Tag","_authFun","WeakMap","AccountGeneralized","constructor","address","_classPrivateFieldInitSpec","writable","value","sign","signMessage","signTypedData","signTransaction","tx","_ref","authData","onCompiler","onNode","callData","sourceCode","args","fee","gasLimit","gasPrice","authCallData","_classPrivateFieldGet","account","kind","_classPrivateFieldSet","authFun","contract","initialize","_calldata","encode","_name","gaMetaTx","tag","GaMetaTx","SignedTx","encodedTx","signatures","gaId"],"sources":["../../src/account/Generalized.ts"],"sourcesContent":["import AccountBase from './Base';\nimport {\n ArgumentError,\n InternalError,\n InvalidAuthDataError,\n NotImplementedError,\n} from '../utils/errors';\nimport { decode, Encoded } from '../utils/encoder';\nimport { getAccount } from '../chain';\nimport Contract from '../contract/Contract';\nimport { buildTxAsync, buildTx } from '../tx/builder';\nimport { Tag } from '../tx/builder/constants';\n\n/**\n * Generalized account class\n */\nexport default class AccountGeneralized extends AccountBase {\n override readonly address: Encoded.AccountAddress;\n\n #authFun?: string;\n\n /**\n * @param address - Address of generalized account\n */\n constructor(address: Encoded.AccountAddress) {\n super();\n decode(address);\n this.address = address;\n }\n\n // eslint-disable-next-line class-methods-use-this\n override async sign(): Promise<Uint8Array> {\n throw new NotImplementedError('Can\\'t sign using generalized account');\n }\n\n // eslint-disable-next-line class-methods-use-this\n override async signMessage(): Promise<Uint8Array> {\n throw new NotImplementedError('Can\\'t sign using generalized account');\n }\n\n // eslint-disable-next-line class-methods-use-this\n override async signTypedData(): Promise<Encoded.Signature> {\n throw new NotImplementedError('Can\\'t sign using generalized account');\n }\n\n override async signTransaction(\n tx: Encoded.Transaction,\n { authData, onCompiler, onNode }: Parameters<AccountBase['signTransaction']>[1],\n ): Promise<Encoded.Transaction> {\n if (authData == null || onCompiler == null || onNode == null) {\n throw new ArgumentError('authData, onCompiler, onNode', 'provided', null);\n }\n const {\n callData, sourceCode, args, fee, gasLimit, gasPrice,\n } = typeof authData === 'function' ? await authData(tx) : authData;\n\n const authCallData = callData ?? await (async () => {\n if (this.#authFun == null) {\n const account = await getAccount(this.address, { onNode });\n if (account.kind !== 'generalized') {\n throw new ArgumentError('account kind', 'generalized', account.kind);\n }\n this.#authFun = account.authFun;\n }\n if (this.#authFun == null) {\n throw new InternalError('Account in generalised, but authFun not provided');\n }\n\n if (sourceCode == null || args == null) {\n throw new InvalidAuthDataError('Auth data must contain sourceCode and args or callData.');\n }\n const contract = await Contract.initialize({ onCompiler, onNode, sourceCode });\n return contract._calldata.encode(contract._name, this.#authFun, args);\n })();\n\n const gaMetaTx = await buildTxAsync({\n tag: Tag.GaMetaTx,\n tx: { tag: Tag.SignedTx, encodedTx: decode(tx), signatures: [] },\n gaId: this.address,\n authData: authCallData,\n fee,\n gasLimit,\n gasPrice,\n onNode,\n });\n return buildTx({ tag: Tag.SignedTx, encodedTx: decode(gaMetaTx), signatures: [] });\n }\n}\n"],"mappings":";;;;OAAOA,WAAW;AAAA,SAEhBC,aAAa,EACbC,aAAa,EACbC,oBAAoB,EACpBC,mBAAmB;AAAA,SAEZC,MAAM;AAAA,SACNC,UAAU;AAAA,OACZC,QAAQ;AAAA,SACNC,YAAY,EAAEC,OAAO;AAAA,SACrBC,GAAG;AAEZ;AACA;AACA;AAFA,IAAAC,QAAA,oBAAAC,OAAA;AAGA,eAAe,MAAMC,kBAAkB,SAASb,WAAW,CAAC;EAK1D;AACF;AACA;EACEc,WAAWA,CAACC,OAA+B,EAAE;IAC3C,KAAK,EAAE;IAACC,0BAAA,OAAAL,QAAA;MAAAM,QAAA;MAAAC,KAAA;IAAA;IACRb,MAAM,CAACU,OAAO,CAAC;IACf,IAAI,CAACA,OAAO,GAAGA,OAAO;EACxB;;EAEA;EACA,MAAeI,IAAIA,CAAA,EAAwB;IACzC,MAAM,IAAIf,mBAAmB,CAAC,uCAAuC,CAAC;EACxE;;EAEA;EACA,MAAegB,WAAWA,CAAA,EAAwB;IAChD,MAAM,IAAIhB,mBAAmB,CAAC,uCAAuC,CAAC;EACxE;;E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AC,yDAAyD,CAAC;MAC3F;MACA,MAAMqC,QAAQ,GAAG,MAAMjC,QAAQ,CAACkC,UAAU,CAAC;QAAEf,UAAU;QAAEC,MAAM;QAAEE;MAAW,CAAC,CAAC;MAC9E,OAAOW,QAAQ,CAACE,SAAS,CAACC,MAAM,CAACH,QAAQ,CAACI,KAAK,EAAAT,qBAAA,CAAE,IAAI,EAAAxB,QAAA,GAAWmB,IAAI,CAAC;IACvE,CAAC,GAAG;IAEJ,MAAMe,QAAQ,GAAG,MAAMrC,YAAY,CAAC;MAClCsC,GAAG,EAAEpC,GAAG,CAACqC,QAAQ;MACjBxB,EAAE,EAAE;QAAEuB,GAAG,EAAEpC,GAAG,CAACsC,QAAQ;QAAEC,SAAS,EAAE5C,MAAM,CAACkB,EAAE,CAAC;QAAE2B,UAAU,EAAE;MAAG,CAAC;MAChEC,IAAI,EAAE,IAAI,CAACpC,OAAO;MAClBU,QAAQ,EAAES,YAAY;MACtBH,GAAG;MACHC,QAAQ;MACRC,QAAQ;MACRN;IACF,CAAC,CAAC;IACF,OAAOlB,OAAO,CAAC;MAAEqC,GAAG,EAAEpC,GAAG,CAACsC,QAAQ;MAAEC,SAAS,EAAE5C,MAAM,CAACwC,QAAQ,CAAC;MAAEK,UAAU,EAAE;IAAG,CAAC,CAAC;EACpF;AACF"}
|
package/es/account/Ledger.d.ts
CHANGED
|
@@ -20,6 +20,7 @@ export default class AccountLedger extends AccountBase {
|
|
|
20
20
|
*/
|
|
21
21
|
constructor(transport: Transport, index: number, address: Encoded.AccountAddress);
|
|
22
22
|
sign(): Promise<Uint8Array>;
|
|
23
|
+
signTypedData(): Promise<Encoded.Signature>;
|
|
23
24
|
signTransaction(tx: Encoded.Transaction, { innerTx, networkId }?: {
|
|
24
25
|
innerTx?: boolean;
|
|
25
26
|
networkId?: string;
|
package/es/account/Ledger.mjs
CHANGED
|
@@ -35,6 +35,11 @@ export default class AccountLedger extends AccountBase {
|
|
|
35
35
|
async sign() {
|
|
36
36
|
throw new NotImplementedError('RAW signing using Ledger HW');
|
|
37
37
|
}
|
|
38
|
+
|
|
39
|
+
// eslint-disable-next-line class-methods-use-this
|
|
40
|
+
async signTypedData() {
|
|
41
|
+
throw new NotImplementedError('Typed data signing using Ledger HW');
|
|
42
|
+
}
|
|
38
43
|
async signTransaction(tx) {
|
|
39
44
|
let {
|
|
40
45
|
innerTx,
|