@aeternity/aepp-sdk 14.0.0 → 14.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +1 -1
- package/README.md +11 -19
- package/dist/aepp-sdk.browser-script.cjs +1 -1
- package/dist/aepp-sdk.browser-script.cjs.LICENSE.txt +2 -0
- package/dist/aepp-sdk.browser-script.cjs.map +1 -1
- package/dist/aepp-sdk.browser.cjs +1 -1
- package/dist/aepp-sdk.browser.cjs.map +1 -1
- package/dist/aepp-sdk.cjs +11678 -6969
- package/dist/aepp-sdk.cjs.map +1 -1
- package/es/AeSdkBase.d.ts +10 -1
- package/es/AeSdkBase.js +12 -2
- package/es/AeSdkBase.js.map +1 -1
- package/es/AeSdkMethods.d.ts +1 -1
- package/es/AeSdkMethods.js.map +1 -1
- package/es/AeSdkWallet.js +1 -1
- package/es/AeSdkWallet.js.map +1 -1
- package/es/Middleware.d.ts +5 -1
- package/es/Middleware.js +7 -2
- package/es/Middleware.js.map +1 -1
- package/es/MiddlewareSubscriber.d.ts +3 -0
- package/es/MiddlewareSubscriber.js +4 -0
- package/es/MiddlewareSubscriber.js.map +1 -1
- package/es/Node.d.ts +6 -1
- package/es/Node.js +28 -4
- package/es/Node.js.map +1 -1
- package/es/account/Base.d.ts +12 -0
- package/es/account/Base.js +1 -0
- package/es/account/Base.js.map +1 -1
- package/es/account/BaseFactory.d.ts +1 -0
- package/es/account/BaseFactory.js +1 -0
- package/es/account/BaseFactory.js.map +1 -1
- package/es/account/Generalized.d.ts +5 -0
- package/es/account/Generalized.js +9 -0
- package/es/account/Generalized.js.map +1 -1
- package/es/account/Ledger.d.ts +5 -0
- package/es/account/Ledger.js +9 -0
- package/es/account/Ledger.js.map +1 -1
- package/es/account/LedgerFactory.d.ts +2 -0
- package/es/account/LedgerFactory.js +10 -4
- package/es/account/LedgerFactory.js.map +1 -1
- package/es/account/Memory.d.ts +5 -0
- package/es/account/Memory.js +14 -5
- package/es/account/Memory.js.map +1 -1
- package/es/account/Metamask.d.ts +8 -0
- package/es/account/Metamask.js +13 -0
- package/es/account/Metamask.js.map +1 -1
- package/es/account/MetamaskFactory.d.ts +20 -2
- package/es/account/MetamaskFactory.js +93 -39
- package/es/account/MetamaskFactory.js.map +1 -1
- package/es/account/MnemonicFactory.d.ts +12 -2
- package/es/account/MnemonicFactory.js +48 -24
- package/es/account/MnemonicFactory.js.map +1 -1
- package/es/account/Rpc.d.ts +5 -0
- package/es/account/Rpc.js +8 -0
- package/es/account/Rpc.js.map +1 -1
- package/es/aens.d.ts +25 -5
- package/es/aens.js +52 -18
- package/es/aens.js.map +1 -1
- package/es/aepp-wallet-communication/connection/BrowserRuntime.d.ts +1 -1
- package/es/aepp-wallet-communication/connection/BrowserRuntime.js.map +1 -1
- package/es/apis/middleware/middleware.d.ts +99 -9
- package/es/apis/middleware/middleware.js +560 -91
- package/es/apis/middleware/middleware.js.map +1 -1
- package/es/apis/middleware/models/index.d.ts +1267 -1582
- package/es/apis/middleware/models/index.js +1 -1363
- package/es/apis/middleware/models/index.js.map +1 -1
- package/es/apis/middleware/models/mappers.d.ts +126 -56
- package/es/apis/middleware/models/mappers.js +6250 -2989
- package/es/apis/middleware/models/mappers.js.map +1 -1
- package/es/apis/middleware/models/parameters.d.ts +54 -33
- package/es/apis/middleware/models/parameters.js +389 -134
- package/es/apis/middleware/models/parameters.js.map +1 -1
- package/es/apis/node/models/index.d.ts +60 -15
- package/es/apis/node/models/index.js.map +1 -1
- package/es/apis/node/models/mappers.d.ts +3 -0
- package/es/apis/node/models/mappers.js +130 -2
- package/es/apis/node/models/mappers.js.map +1 -1
- package/es/apis/node/node.d.ts +13 -1
- package/es/apis/node/node.js +54 -0
- package/es/apis/node/node.js.map +1 -1
- package/es/chain.d.ts +19 -6
- package/es/chain.js +30 -24
- package/es/chain.js.map +1 -1
- package/es/channel/Contract.d.ts +6 -3
- package/es/channel/Contract.js +5 -2
- package/es/channel/Contract.js.map +1 -1
- package/es/channel/Spend.d.ts +1 -1
- package/es/channel/Spend.js.map +1 -1
- package/es/channel/handlers.js +1 -2
- package/es/channel/handlers.js.map +1 -1
- package/es/channel/internal.d.ts +1 -1
- package/es/channel/internal.js +2 -2
- package/es/channel/internal.js.map +1 -1
- package/es/contract/Contract.d.ts +13 -2
- package/es/contract/Contract.js +22 -12
- package/es/contract/Contract.js.map +1 -1
- package/es/contract/compiler/Base.d.ts +1 -0
- package/es/contract/compiler/Base.js +1 -0
- package/es/contract/compiler/Base.js.map +1 -1
- package/es/contract/compiler/Cli.d.ts +2 -1
- package/es/contract/compiler/Cli.js +11 -9
- package/es/contract/compiler/Cli.js.map +1 -1
- package/es/contract/compiler/Http.d.ts +2 -1
- package/es/contract/compiler/Http.js +3 -2
- package/es/contract/compiler/Http.js.map +1 -1
- package/es/contract/compiler/getFileSystem.d.ts +1 -0
- package/es/contract/compiler/getFileSystem.js +1 -0
- package/es/contract/compiler/getFileSystem.js.map +1 -1
- package/es/contract/ga.d.ts +3 -3
- package/es/contract/ga.js +3 -3
- package/es/contract/ga.js.map +1 -1
- package/es/index-browser.d.ts +32 -2
- package/es/index-browser.js +32 -2
- package/es/index-browser.js.map +1 -1
- package/es/oracle/Oracle.d.ts +10 -1
- package/es/oracle/Oracle.js +16 -6
- package/es/oracle/Oracle.js.map +1 -1
- package/es/oracle/OracleBase.d.ts +15 -2
- package/es/oracle/OracleBase.js +23 -1
- package/es/oracle/OracleBase.js.map +1 -1
- package/es/oracle/OracleClient.d.ts +3 -0
- package/es/oracle/OracleClient.js +6 -1
- package/es/oracle/OracleClient.js.map +1 -1
- package/es/spend.js +1 -1
- package/es/spend.js.map +1 -1
- package/es/tx/builder/common.js +6 -3
- package/es/tx/builder/common.js.map +1 -1
- package/es/tx/builder/constants.d.ts +53 -3
- package/es/tx/builder/constants.js +62 -12
- package/es/tx/builder/constants.js.map +1 -1
- package/es/tx/builder/delegation/schema.js +15 -0
- package/es/tx/builder/delegation/schema.js.map +1 -1
- package/es/tx/builder/entry/constants.d.ts +4 -1
- package/es/tx/builder/entry/constants.js +10 -1
- package/es/tx/builder/entry/constants.js.map +1 -1
- package/es/tx/builder/entry/index.js +1 -2
- package/es/tx/builder/entry/index.js.map +1 -1
- package/es/tx/builder/field-types/ct-version.js +1 -2
- package/es/tx/builder/field-types/ct-version.js.map +1 -1
- package/es/tx/builder/field-types/fee.d.ts +1 -1
- package/es/tx/builder/field-types/fee.js +4 -4
- package/es/tx/builder/field-types/fee.js.map +1 -1
- package/es/tx/builder/field-types/gas-price.d.ts +3 -0
- package/es/tx/builder/field-types/gas-price.js +1 -1
- package/es/tx/builder/field-types/gas-price.js.map +1 -1
- package/es/tx/builder/field-types/name-fee.js +1 -1
- package/es/tx/builder/field-types/name-fee.js.map +1 -1
- package/es/tx/builder/field-types/name-id.js +2 -2
- package/es/tx/builder/field-types/name-id.js.map +1 -1
- package/es/tx/builder/field-types/nonce.d.ts +1 -1
- package/es/tx/builder/field-types/nonce.js.map +1 -1
- package/es/tx/builder/field-types/pointers.js +3 -3
- package/es/tx/builder/field-types/pointers.js.map +1 -1
- package/es/tx/builder/field-types/ttl.js +1 -2
- package/es/tx/builder/field-types/ttl.js.map +1 -1
- package/es/tx/builder/helpers.d.ts +18 -12
- package/es/tx/builder/helpers.js +25 -17
- package/es/tx/builder/helpers.js.map +1 -1
- package/es/tx/builder/schema.d.ts +27 -24
- package/es/tx/builder/schema.generated.d.ts +12 -12
- package/es/tx/builder/schema.generated.js.map +1 -1
- package/es/tx/builder/schema.js +5 -3
- package/es/tx/builder/schema.js.map +1 -1
- package/es/tx/execution-cost.d.ts +3 -0
- package/es/tx/execution-cost.js +7 -4
- package/es/tx/execution-cost.js.map +1 -1
- package/es/tx/transaction-signer.d.ts +1 -0
- package/es/tx/transaction-signer.js +1 -0
- package/es/tx/transaction-signer.js.map +1 -1
- package/es/tx/validator.js +4 -3
- package/es/tx/validator.js.map +1 -1
- package/es/utils/MiddlewarePage.d.ts +4 -3
- package/es/utils/MiddlewarePage.js.map +1 -1
- package/es/utils/amount-formatter.d.ts +15 -1
- package/es/utils/amount-formatter.js +17 -1
- package/es/utils/amount-formatter.js.map +1 -1
- package/es/utils/autorest.d.ts +1 -1
- package/es/utils/autorest.js +10 -4
- package/es/utils/autorest.js.map +1 -1
- package/es/utils/bignumber.d.ts +1 -1
- package/es/utils/bignumber.js +1 -1
- package/es/utils/bignumber.js.map +1 -1
- package/es/utils/bytes.d.ts +3 -1
- package/es/utils/bytes.js +3 -1
- package/es/utils/bytes.js.map +1 -1
- package/es/utils/crypto.d.ts +48 -15
- package/es/utils/crypto.js +80 -29
- package/es/utils/crypto.js.map +1 -1
- package/es/utils/encoder-types.d.ts +1 -1
- package/es/utils/encoder-types.js +1 -1
- package/es/utils/encoder-types.js.map +1 -1
- package/es/utils/encoder.d.ts +2 -0
- package/es/utils/encoder.js +2 -0
- package/es/utils/encoder.js.map +1 -1
- package/es/utils/errors.d.ts +2 -2
- package/es/utils/errors.js +2 -2
- package/es/utils/errors.js.map +1 -1
- package/es/utils/json-big.js +1 -1
- package/es/utils/json-big.js.map +1 -1
- package/es/utils/jwt.js +3 -3
- package/es/utils/jwt.js.map +1 -1
- package/es/utils/typed-data.d.ts +5 -0
- package/es/utils/typed-data.js +6 -0
- package/es/utils/typed-data.js.map +1 -1
- package/package.json +50 -51
package/es/AeSdkBase.d.ts
CHANGED
|
@@ -83,8 +83,17 @@ export default class AeSdkBase extends AeSdkMethods {
|
|
|
83
83
|
* Sign data blob
|
|
84
84
|
* @param data - Data to sign
|
|
85
85
|
* @param options - Options
|
|
86
|
+
* @deprecated Use `unsafeSign` method instead
|
|
86
87
|
*/
|
|
87
|
-
sign(data: string | Uint8Array,
|
|
88
|
+
sign(data: string | Uint8Array, options?: {
|
|
89
|
+
onAccount?: OnAccount;
|
|
90
|
+
}): Promise<Uint8Array>;
|
|
91
|
+
/**
|
|
92
|
+
* Sign data blob
|
|
93
|
+
* @param data - Data to sign
|
|
94
|
+
* @param options - Options
|
|
95
|
+
*/
|
|
96
|
+
unsafeSign(data: string | Uint8Array, { onAccount, ...options }?: {
|
|
88
97
|
onAccount?: OnAccount;
|
|
89
98
|
}): Promise<Uint8Array>;
|
|
90
99
|
/**
|
package/es/AeSdkBase.js
CHANGED
|
@@ -144,12 +144,22 @@ export default class AeSdkBase extends AeSdkMethods {
|
|
|
144
144
|
* Sign data blob
|
|
145
145
|
* @param data - Data to sign
|
|
146
146
|
* @param options - Options
|
|
147
|
+
* @deprecated Use `unsafeSign` method instead
|
|
147
148
|
*/
|
|
148
|
-
async sign(data, {
|
|
149
|
+
async sign(data, options = {}) {
|
|
150
|
+
return this.unsafeSign(data, options);
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/**
|
|
154
|
+
* Sign data blob
|
|
155
|
+
* @param data - Data to sign
|
|
156
|
+
* @param options - Options
|
|
157
|
+
*/
|
|
158
|
+
async unsafeSign(data, {
|
|
149
159
|
onAccount,
|
|
150
160
|
...options
|
|
151
161
|
} = {}) {
|
|
152
|
-
return this._resolveAccount(onAccount).
|
|
162
|
+
return this._resolveAccount(onAccount).unsafeSign(data, options);
|
|
153
163
|
}
|
|
154
164
|
|
|
155
165
|
/**
|
package/es/AeSdkBase.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"AeSdkBase.js","names":["CompilerError","DuplicateNodeError","NodeNotFoundError","NotImplementedError","TypeError","wrapWithProxy","AeSdkMethods","_wrappedOptions","WeakMap","AeSdkBase","constructor","nodes","options","_defineProperty","Map","_classPrivateFieldInitSpec","forEach","name","instance","i","addNode","_classPrivateFieldSet","onNode","api","onCompiler","compilerApi","onAccount","_resolveAccount","_options","ensureNodeConnected","pool","get","selectedNodeName","node","select","has","set","selectNode","isNodeConnected","getNodeInfo","getNodesInPool","Promise","all","Array","from","entries","map","addresses","account","String","address","sign","data","signTransaction","tx","networkId","getNetworkId","undefined","signMessage","message","signTypedData","aci","signDelegation","delegation","_options$networkId","getContext","mergeWith","_classPrivateFieldGet"],"sources":["../src/AeSdkBase.ts"],"sourcesContent":["import Node from './Node.js';\nimport AccountBase from './account/Base.js';\nimport {\n CompilerError,\n DuplicateNodeError,\n NodeNotFoundError,\n NotImplementedError,\n TypeError,\n} from './utils/errors.js';\nimport { Encoded } from './utils/encoder.js';\nimport { wrapWithProxy } from './utils/wrap-proxy.js';\nimport CompilerBase from './contract/compiler/Base.js';\nimport AeSdkMethods, { OnAccount, AeSdkMethodsOptions, WrappedOptions } from './AeSdkMethods.js';\n\ntype NodeInfo = Awaited<ReturnType<Node['getNodeInfo']>> & { name: string };\n\n/**\n * Basic AeSdk class implements:\n * - node selector,\n * - integrated compiler support,\n * - wrappers of account methods mapped to the current account.\n */\nexport default class AeSdkBase extends AeSdkMethods {\n pool: Map<string, Node> = new Map();\n\n selectedNodeName?: string;\n\n readonly #wrappedOptions: WrappedOptions;\n\n /**\n * @param options - Options\n * @param options.nodes - Array of nodes\n */\n constructor({\n nodes = [],\n ...options\n }: AeSdkMethodsOptions & {\n nodes?: Array<{ name: string; instance: Node }>;\n } = {}) {\n super(options);\n\n nodes.forEach(({ name, instance }, i) => this.addNode(name, instance, i === 0));\n\n this.#wrappedOptions = {\n onNode: wrapWithProxy(() => this.api),\n onCompiler: wrapWithProxy(() => this.compilerApi),\n onAccount: wrapWithProxy(() => this._resolveAccount()),\n };\n }\n\n // TODO: consider dropping this getter, because:\n // compiler is not intended to be used separately any more (functionality limited to sdk needs)\n // and user creates its instance by himself\n get compilerApi(): CompilerBase {\n if (this._options.onCompiler == null) {\n throw new CompilerError(\"You can't use Compiler API. Compiler is not ready!\");\n }\n return this._options.onCompiler;\n }\n\n get api(): Node {\n this.ensureNodeConnected();\n return this.pool.get(this.selectedNodeName) as Node;\n }\n\n /**\n * Add Node\n * @param name - Node name\n * @param node - Node instance\n * @param select - Select this node as current\n * @example\n * ```js\n * // add and select new node with name 'testNode'\n * aeSdkBase.addNode('testNode', new Node({ url }), true)\n * ```\n */\n addNode(name: string, node: Node, select = false): void {\n if (this.pool.has(name)) throw new DuplicateNodeError(name);\n\n this.pool.set(name, node);\n if (select || this.selectedNodeName == null) {\n this.selectNode(name);\n }\n }\n\n /**\n * Select Node\n * @param name - Node name\n * @example\n * nodePool.selectNode('testNode')\n */\n selectNode(name: string): void {\n if (!this.pool.has(name)) throw new NodeNotFoundError(`Node with name ${name} not in pool`);\n this.selectedNodeName = name;\n }\n\n /**\n * Check if you have selected node\n * @example\n * nodePool.isNodeConnected()\n */\n isNodeConnected(): this is AeSdkBase & { selectedNodeName: string } {\n return this.selectedNodeName != null;\n }\n\n protected ensureNodeConnected(): asserts this is AeSdkBase & { selectedNodeName: string } {\n if (!this.isNodeConnected()) {\n throw new NodeNotFoundError(\"You can't use Node API. Node is not connected or not defined!\");\n }\n }\n\n /**\n * Get information about node\n * @example\n * ```js\n * nodePool.getNodeInfo() // { name, version, networkId, protocol, ... }\n * ```\n */\n async getNodeInfo(): Promise<NodeInfo> {\n this.ensureNodeConnected();\n return {\n name: this.selectedNodeName,\n ...(await this.api.getNodeInfo()),\n };\n }\n\n /**\n * Get array of available nodes\n * @example\n * nodePool.getNodesInPool()\n */\n async getNodesInPool(): Promise<NodeInfo[]> {\n return Promise.all(\n Array.from(this.pool.entries()).map(async ([name, node]) => ({\n name,\n ...(await node.getNodeInfo()),\n })),\n );\n }\n\n // eslint-disable-next-line class-methods-use-this\n addresses(): Encoded.AccountAddress[] {\n return [];\n }\n\n /**\n * Resolves an account\n * @param account - ak-address, instance of AccountBase, or keypair\n */\n _resolveAccount(account: OnAccount = this._options.onAccount): AccountBase {\n if (typeof account === 'string') throw new NotImplementedError('Address in AccountResolver');\n if (typeof account === 'object') return account;\n throw new TypeError(\n 'Account should be an address (ak-prefixed string), ' +\n `or instance of AccountBase, got ${String(account)} instead`,\n );\n }\n\n get address(): Encoded.AccountAddress {\n return this._resolveAccount().address;\n }\n\n /**\n * Sign data blob\n * @param data - Data to sign\n * @param options - Options\n */\n async sign(\n data: string | Uint8Array,\n { onAccount, ...options }: { onAccount?: OnAccount } = {},\n ): Promise<Uint8Array> {\n return this._resolveAccount(onAccount).sign(data, options);\n }\n\n /**\n * Sign encoded transaction\n * @param tx - Transaction to sign\n * @param options - Options\n */\n async signTransaction(\n tx: Encoded.Transaction,\n {\n onAccount,\n ...options\n }: { onAccount?: OnAccount } & Parameters<AccountBase['signTransaction']>[1] = {},\n ): Promise<Encoded.Transaction> {\n const networkId = this.selectedNodeName !== null ? await this.api.getNetworkId() : undefined;\n return this._resolveAccount(onAccount).signTransaction(tx, { networkId, ...options });\n }\n\n /**\n * Sign message\n * @param message - Message to sign\n * @param options - Options\n */\n async signMessage(\n message: string,\n {\n onAccount,\n ...options\n }: { onAccount?: OnAccount } & Parameters<AccountBase['signMessage']>[1] = {},\n ): Promise<Uint8Array> {\n return this._resolveAccount(onAccount).signMessage(message, options);\n }\n\n /**\n * Sign typed data\n * @param data - Encoded data to sign\n * @param aci - Type of data to sign\n * @param options - Options\n */\n async signTypedData(\n data: Encoded.ContractBytearray,\n aci: Parameters<AccountBase['signTypedData']>[1],\n {\n onAccount,\n ...options\n }: { onAccount?: OnAccount } & Parameters<AccountBase['signTypedData']>[2] = {},\n ): Promise<Encoded.Signature> {\n return this._resolveAccount(onAccount).signTypedData(data, aci, options);\n }\n\n /**\n * Sign delegation, works only in Ceres\n * @param delegation - Delegation to sign\n * @param options - Options\n */\n async signDelegation(\n delegation: Encoded.Bytearray,\n {\n onAccount,\n ...options\n }: { onAccount?: OnAccount } & Parameters<AccountBase['signDelegation']>[1] = {},\n ): Promise<Encoded.Signature> {\n options.networkId ??=\n this.selectedNodeName !== null ? await this.api.getNetworkId() : undefined;\n return this._resolveAccount(onAccount).signDelegation(delegation, options);\n }\n\n /**\n * The same as AeSdkMethods:getContext, but it would resolve ak_-prefixed address in\n * `mergeWith.onAccount` to AccountBase.\n */\n override getContext(mergeWith: AeSdkMethodsOptions = {}): AeSdkMethodsOptions & WrappedOptions {\n return {\n ...this._options,\n ...this.#wrappedOptions,\n ...mergeWith,\n ...(mergeWith.onAccount != null && {\n onAccount: this._resolveAccount(mergeWith.onAccount),\n }),\n };\n }\n}\n"],"mappings":";;;;;;AAEA,SACEA,aAAa,EACbC,kBAAkB,EAClBC,iBAAiB,EACjBC,mBAAmB,EACnBC,SAAS,IAATA,UAAS,QACJ,mBAAmB;AAE1B,SAASC,aAAa,QAAQ,uBAAuB;AAErD,OAAOC,YAAY,MAA0D,mBAAmB;AAAC,IAAAC,eAAA,oBAAAC,OAAA;AAIjG;AACA;AACA;AACA;AACA;AACA;AACA,eAAe,MAAMC,SAAS,SAASH,YAAY,CAAC;EAOlD;AACF;AACA;AACA;EACEI,WAAWA,CAAC;IACVC,KAAK,GAAG,EAAE;IACV,GAAGC;EAGL,CAAC,GAAG,CAAC,CAAC,EAAE;IACN,KAAK,CAACA,OAAO,CAAC;IAACC,eAAA,eAhBS,IAAIC,GAAG,CAAC,CAAC;IAInCC,0BAAA,OAASR,eAAe;IActBI,KAAK,CAACK,OAAO,CAAC,CAAC;MAAEC,IAAI;MAAEC;IAAS,CAAC,EAAEC,CAAC,KAAK,IAAI,CAACC,OAAO,CAACH,IAAI,EAAEC,QAAQ,EAAEC,CAAC,KAAK,CAAC,CAAC,CAAC;IAE/EE,qBAAA,CAAKd,eAAe,EAApB,IAAI,EAAmB;MACrBe,MAAM,EAAEjB,aAAa,CAAC,MAAM,IAAI,CAACkB,GAAG,CAAC;MACrCC,UAAU,EAAEnB,aAAa,CAAC,MAAM,IAAI,CAACoB,WAAW,CAAC;MACjDC,SAAS,EAAErB,aAAa,CAAC,MAAM,IAAI,CAACsB,eAAe,CAAC,CAAC;IACvD,CAJmB,CAAC;EAKtB;;EAEA;EACA;EACA;EACA,IAAIF,WAAWA,CAAA,EAAiB;IAC9B,IAAI,IAAI,CAACG,QAAQ,CAACJ,UAAU,IAAI,IAAI,EAAE;MACpC,MAAM,IAAIxB,aAAa,CAAC,oDAAoD,CAAC;IAC/E;IACA,OAAO,IAAI,CA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e,CAACD,SAAS,CAAC,CAACoC,cAAc,CAACC,UAAU,EAAEnD,OAAO,CAAC;EAC5E;;EAEA;AACF;AACA;AACA;EACWqD,UAAUA,CAACC,SAA8B,GAAG,CAAC,CAAC,EAAwC;IAC7F,OAAO;MACL,GAAG,IAAI,CAACtC,QAAQ;MAChB,GAAGuC,qBAAA,CAAK5D,eAAe,EAApB,IAAmB,CAAC;MACvB,GAAG2D,SAAS;MACZ,IAAIA,SAAS,CAACxC,SAAS,IAAI,IAAI,IAAI;QACjCA,SAAS,EAAE,IAAI,CAACC,eAAe,CAACuC,SAAS,CAACxC,SAAS;MACrD,CAAC;IACH,CAAC;EACH;AACF","ignoreList":[]}
|
|
1
|
+
{"version":3,"file":"AeSdkBase.js","names":["CompilerError","DuplicateNodeError","NodeNotFoundError","NotImplementedError","TypeError","wrapWithProxy","AeSdkMethods","_wrappedOptions","WeakMap","AeSdkBase","constructor","nodes","options","_defineProperty","Map","_classPrivateFieldInitSpec","forEach","name","instance","i","addNode","_classPrivateFieldSet","onNode","api","onCompiler","compilerApi","onAccount","_resolveAccount","_options","ensureNodeConnected","pool","get","selectedNodeName","node","select","has","set","selectNode","isNodeConnected","getNodeInfo","getNodesInPool","Promise","all","Array","from","entries","map","addresses","account","String","address","sign","data","unsafeSign","signTransaction","tx","networkId","getNetworkId","undefined","signMessage","message","signTypedData","aci","signDelegation","delegation","_options$networkId","getContext","mergeWith","_classPrivateFieldGet"],"sources":["../src/AeSdkBase.ts"],"sourcesContent":["import Node from './Node.js';\nimport AccountBase from './account/Base.js';\nimport {\n CompilerError,\n DuplicateNodeError,\n NodeNotFoundError,\n NotImplementedError,\n TypeError,\n} from './utils/errors.js';\nimport { Encoded } from './utils/encoder.js';\nimport { wrapWithProxy } from './utils/wrap-proxy.js';\nimport CompilerBase from './contract/compiler/Base.js';\nimport AeSdkMethods, { OnAccount, AeSdkMethodsOptions, WrappedOptions } from './AeSdkMethods.js';\n\ntype NodeInfo = Awaited<ReturnType<Node['getNodeInfo']>> & { name: string };\n\n/**\n * Basic AeSdk class implements:\n * - node selector,\n * - integrated compiler support,\n * - wrappers of account methods mapped to the current account.\n */\nexport default class AeSdkBase extends AeSdkMethods {\n pool: Map<string, Node> = new Map();\n\n selectedNodeName?: string;\n\n readonly #wrappedOptions: WrappedOptions;\n\n /**\n * @param options - Options\n * @param options.nodes - Array of nodes\n */\n constructor({\n nodes = [],\n ...options\n }: AeSdkMethodsOptions & {\n nodes?: Array<{ name: string; instance: Node }>;\n } = {}) {\n super(options);\n\n nodes.forEach(({ name, instance }, i) => this.addNode(name, instance, i === 0));\n\n this.#wrappedOptions = {\n onNode: wrapWithProxy(() => this.api),\n onCompiler: wrapWithProxy(() => this.compilerApi),\n onAccount: wrapWithProxy(() => this._resolveAccount()),\n };\n }\n\n // TODO: consider dropping this getter, because:\n // compiler is not intended to be used separately any more (functionality limited to sdk needs)\n // and user creates its instance by himself\n get compilerApi(): CompilerBase {\n if (this._options.onCompiler == null) {\n throw new CompilerError(\"You can't use Compiler API. Compiler is not ready!\");\n }\n return this._options.onCompiler;\n }\n\n get api(): Node {\n this.ensureNodeConnected();\n return this.pool.get(this.selectedNodeName) as Node;\n }\n\n /**\n * Add Node\n * @param name - Node name\n * @param node - Node instance\n * @param select - Select this node as current\n * @example\n * ```js\n * // add and select new node with name 'testNode'\n * aeSdkBase.addNode('testNode', new Node({ url }), true)\n * ```\n */\n addNode(name: string, node: Node, select = false): void {\n if (this.pool.has(name)) throw new DuplicateNodeError(name);\n\n this.pool.set(name, node);\n if (select || this.selectedNodeName == null) {\n this.selectNode(name);\n }\n }\n\n /**\n * Select Node\n * @param name - Node name\n * @example\n * nodePool.selectNode('testNode')\n */\n selectNode(name: string): void {\n if (!this.pool.has(name)) throw new NodeNotFoundError(`Node with name ${name} not in pool`);\n this.selectedNodeName = name;\n }\n\n /**\n * Check if you have selected node\n * @example\n * nodePool.isNodeConnected()\n */\n isNodeConnected(): this is AeSdkBase & { selectedNodeName: string } {\n return this.selectedNodeName != null;\n }\n\n protected ensureNodeConnected(): asserts this is AeSdkBase & { selectedNodeName: string } {\n if (!this.isNodeConnected()) {\n throw new NodeNotFoundError(\"You can't use Node API. Node is not connected or not defined!\");\n }\n }\n\n /**\n * Get information about node\n * @example\n * ```js\n * nodePool.getNodeInfo() // { name, version, networkId, protocol, ... }\n * ```\n */\n async getNodeInfo(): Promise<NodeInfo> {\n this.ensureNodeConnected();\n return {\n name: this.selectedNodeName,\n ...(await this.api.getNodeInfo()),\n };\n }\n\n /**\n * Get array of available nodes\n * @example\n * nodePool.getNodesInPool()\n */\n async getNodesInPool(): Promise<NodeInfo[]> {\n return Promise.all(\n Array.from(this.pool.entries()).map(async ([name, node]) => ({\n name,\n ...(await node.getNodeInfo()),\n })),\n );\n }\n\n // eslint-disable-next-line class-methods-use-this\n addresses(): Encoded.AccountAddress[] {\n return [];\n }\n\n /**\n * Resolves an account\n * @param account - ak-address, instance of AccountBase, or keypair\n */\n _resolveAccount(account: OnAccount = this._options.onAccount): AccountBase {\n if (typeof account === 'string') throw new NotImplementedError('Address in AccountResolver');\n if (typeof account === 'object') return account;\n throw new TypeError(\n 'Account should be an address (ak-prefixed string), ' +\n `or instance of AccountBase, got ${String(account)} instead`,\n );\n }\n\n get address(): Encoded.AccountAddress {\n return this._resolveAccount().address;\n }\n\n /**\n * Sign data blob\n * @param data - Data to sign\n * @param options - Options\n * @deprecated Use `unsafeSign` method instead\n */\n async sign(\n data: string | Uint8Array,\n options: { onAccount?: OnAccount } = {},\n ): Promise<Uint8Array> {\n return this.unsafeSign(data, options);\n }\n\n /**\n * Sign data blob\n * @param data - Data to sign\n * @param options - Options\n */\n async unsafeSign(\n data: string | Uint8Array,\n { onAccount, ...options }: { onAccount?: OnAccount } = {},\n ): Promise<Uint8Array> {\n return this._resolveAccount(onAccount).unsafeSign(data, options);\n }\n\n /**\n * Sign encoded transaction\n * @param tx - Transaction to sign\n * @param options - Options\n */\n async signTransaction(\n tx: Encoded.Transaction,\n {\n onAccount,\n ...options\n }: { onAccount?: OnAccount } & Parameters<AccountBase['signTransaction']>[1] = {},\n ): Promise<Encoded.Transaction> {\n const networkId = this.selectedNodeName !== null ? await this.api.getNetworkId() : undefined;\n return this._resolveAccount(onAccount).signTransaction(tx, { networkId, ...options });\n }\n\n /**\n * Sign message\n * @param message - Message to sign\n * @param options - Options\n */\n async signMessage(\n message: string,\n {\n onAccount,\n ...options\n }: { onAccount?: OnAccount } & Parameters<AccountBase['signMessage']>[1] = {},\n ): Promise<Uint8Array> {\n return this._resolveAccount(onAccount).signMessage(message, options);\n }\n\n /**\n * Sign typed data\n * @param data - Encoded data to sign\n * @param aci - Type of data to sign\n * @param options - Options\n */\n async signTypedData(\n data: Encoded.ContractBytearray,\n aci: Parameters<AccountBase['signTypedData']>[1],\n {\n onAccount,\n ...options\n }: { onAccount?: OnAccount } & Parameters<AccountBase['signTypedData']>[2] = {},\n ): Promise<Encoded.Signature> {\n return this._resolveAccount(onAccount).signTypedData(data, aci, options);\n }\n\n /**\n * Sign delegation, works only in Ceres\n * @param delegation - Delegation to sign\n * @param options - Options\n */\n async signDelegation(\n delegation: Encoded.Bytearray,\n {\n onAccount,\n ...options\n }: { onAccount?: OnAccount } & Parameters<AccountBase['signDelegation']>[1] = {},\n ): Promise<Encoded.Signature> {\n options.networkId ??=\n this.selectedNodeName !== null ? await this.api.getNetworkId() : undefined;\n return this._resolveAccount(onAccount).signDelegation(delegation, options);\n }\n\n /**\n * The same as AeSdkMethods:getContext, but it would resolve ak_-prefixed address in\n * `mergeWith.onAccount` to AccountBase.\n */\n override getContext(mergeWith: AeSdkMethodsOptions = {}): AeSdkMethodsOptions & WrappedOptions {\n return {\n ...this._options,\n ...this.#wrappedOptions,\n ...mergeWith,\n ...(mergeWith.onAccount != null && {\n onAccount: this._resolveAccount(mergeWith.onAccount),\n }),\n };\n }\n}\n"],"mappings":";;;;;;AAEA,SACEA,aAAa,EACbC,kBAAkB,EAClBC,iBAAiB,EACjBC,mBAAmB,EACnBC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ACD,SAAS,CAAC,CAACqC,cAAc,CAACC,UAAU,EAAEpD,OAAO,CAAC;EAC5E;;EAEA;AACF;AACA;AACA;EACWsD,UAAUA,CAACC,SAA8B,GAAG,CAAC,CAAC,EAAwC;IAC7F,OAAO;MACL,GAAG,IAAI,CAACvC,QAAQ;MAChB,GAAGwC,qBAAA,CAAK7D,eAAe,EAApB,IAAmB,CAAC;MACvB,GAAG4D,SAAS;MACZ,IAAIA,SAAS,CAACzC,SAAS,IAAI,IAAI,IAAI;QACjCA,SAAS,EAAE,IAAI,CAACC,eAAe,CAACwC,SAAS,CAACzC,SAAS;MACrD,CAAC;IACH,CAAC;EACH;AACF","ignoreList":[]}
|
package/es/AeSdkMethods.d.ts
CHANGED
|
@@ -87,7 +87,7 @@ type ReplaceOnAccount<Options> = Options extends {
|
|
|
87
87
|
} ? Omit<Options, 'onAccount'> & {
|
|
88
88
|
/**
|
|
89
89
|
* Make operation on specific account by providing address (to use account from sdk) or instance
|
|
90
|
-
* of AccountBase (like
|
|
90
|
+
* of AccountBase (like AccountMemory)
|
|
91
91
|
*/
|
|
92
92
|
onAccount: OnAccount;
|
|
93
93
|
} : Options;
|
package/es/AeSdkMethods.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"AeSdkMethods.js","names":["chainMethods","sendTransaction","spendMethods","contractGaMethods","buildTxAsync","mapObject","wrapWithProxy","methods","_wrappedOptions","WeakMap","AeSdkMethods","constructor","options","_defineProperty","_classPrivateFieldInitSpec","Object","assign","_options","_classPrivateFieldSet","onAccount","onNode","onCompiler","getContext","mergeWith","_classPrivateFieldGet","buildTx","prototype","name","handler","methodWrapper","args","length","AeSdkMethodsTyped"],"sources":["../src/AeSdkMethods.ts"],"sourcesContent":["import * as chainMethods from './chain.js';\nimport { sendTransaction } from './send-transaction.js';\nimport * as spendMethods from './spend.js';\nimport * as contractGaMethods from './contract/ga.js';\nimport { buildTxAsync } from './tx/builder/index.js';\nimport { mapObject, UnionToIntersection } from './utils/other.js';\nimport { wrapWithProxy } from './utils/wrap-proxy.js';\nimport Node from './Node.js';\nimport { TxParamsAsync } from './tx/builder/schema.generated.js';\nimport AccountBase from './account/Base.js';\nimport { Encoded } from './utils/encoder.js';\nimport CompilerBase from './contract/compiler/Base.js';\n\nexport type OnAccount = Encoded.AccountAddress | AccountBase | undefined;\n\nconst methods = {\n ...chainMethods,\n sendTransaction,\n ...spendMethods,\n ...contractGaMethods,\n} as const;\n\ntype Decrement<Number extends number> = [-1, 0, 1, 2, 3, 4, 5][Number];\ntype GetMethodsOptions<Methods extends { [key: string]: Function }> = {\n [Name in keyof Methods]: Methods[Name] extends (...args: infer Args) => any\n ? Args[Decrement<Args['length']>]\n : never;\n};\ntype MethodsOptions = GetMethodsOptions<typeof methods>;\nexport interface AeSdkMethodsOptions\n extends Partial<UnionToIntersection<MethodsOptions[keyof MethodsOptions]>> {}\n\nexport interface WrappedOptions {\n onAccount: AccountBase;\n onCompiler: CompilerBase;\n onNode: Node;\n}\n\n/**\n * AeSdkMethods is the composition of:\n * - chain methods\n * - tx methods\n * - aens methods\n * - spend methods\n * - oracle methods\n * - contract methods\n * - contract ga methods\n *\n * While these methods can be used separately, this class provides a handy way to store\n * their context (current account, network, and compiler to use).\n */\nclass AeSdkMethods {\n _options: AeSdkMethodsOptions = {};\n\n readonly #wrappedOptions: WrappedOptions;\n\n /**\n * @param options - Options\n */\n constructor(options: AeSdkMethodsOptions = {}) {\n Object.assign(this._options, options);\n this.#wrappedOptions = {\n onAccount: wrapWithProxy(() => this._options.onAccount),\n onNode: wrapWithProxy(() => this._options.onNode),\n onCompiler: wrapWithProxy(() => this._options.onCompiler),\n };\n }\n\n /**\n * Returns sdk instance options with references to current account, node, compiler.\n * Used to create an instance (Contract, Oracle) bound to AeSdk state.\n * @param mergeWith - Merge context with these extra options\n * @returns Context object\n */\n getContext(mergeWith: AeSdkMethodsOptions = {}): AeSdkMethodsOptions & WrappedOptions {\n return {\n ...this._options,\n ...this.#wrappedOptions,\n ...mergeWith,\n };\n }\n\n // TODO: omit onNode from options, because it is already in context\n async buildTx(options: TxParamsAsync): Promise<Encoded.Transaction> {\n // TODO: remove `any` at the same time as AeSdk class\n return buildTxAsync({ ...(this.getContext() as any), ...options });\n }\n}\n\ntype RequiredKeys<T> = {\n [K in keyof T]-?: {} extends Pick<T, K> ? never : K;\n}[keyof T];\n\ntype OptionalIfNotRequired<T extends [any]> = RequiredKeys<T[0]> extends never ? T | [] : T;\n\ntype ReplaceOnAccount<Options> = Options extends { onAccount: any }\n ? Omit<Options, 'onAccount'> & {\n /**\n * Make operation on specific account by providing address (to use account from sdk) or instance\n * of AccountBase (like
|
|
1
|
+
{"version":3,"file":"AeSdkMethods.js","names":["chainMethods","sendTransaction","spendMethods","contractGaMethods","buildTxAsync","mapObject","wrapWithProxy","methods","_wrappedOptions","WeakMap","AeSdkMethods","constructor","options","_defineProperty","_classPrivateFieldInitSpec","Object","assign","_options","_classPrivateFieldSet","onAccount","onNode","onCompiler","getContext","mergeWith","_classPrivateFieldGet","buildTx","prototype","name","handler","methodWrapper","args","length","AeSdkMethodsTyped"],"sources":["../src/AeSdkMethods.ts"],"sourcesContent":["import * as chainMethods from './chain.js';\nimport { sendTransaction } from './send-transaction.js';\nimport * as spendMethods from './spend.js';\nimport * as contractGaMethods from './contract/ga.js';\nimport { buildTxAsync } from './tx/builder/index.js';\nimport { mapObject, UnionToIntersection } from './utils/other.js';\nimport { wrapWithProxy } from './utils/wrap-proxy.js';\nimport Node from './Node.js';\nimport { TxParamsAsync } from './tx/builder/schema.generated.js';\nimport AccountBase from './account/Base.js';\nimport { Encoded } from './utils/encoder.js';\nimport CompilerBase from './contract/compiler/Base.js';\n\nexport type OnAccount = Encoded.AccountAddress | AccountBase | undefined;\n\nconst methods = {\n ...chainMethods,\n sendTransaction,\n ...spendMethods,\n ...contractGaMethods,\n} as const;\n\ntype Decrement<Number extends number> = [-1, 0, 1, 2, 3, 4, 5][Number];\ntype GetMethodsOptions<Methods extends { [key: string]: Function }> = {\n [Name in keyof Methods]: Methods[Name] extends (...args: infer Args) => any\n ? Args[Decrement<Args['length']>]\n : never;\n};\ntype MethodsOptions = GetMethodsOptions<typeof methods>;\nexport interface AeSdkMethodsOptions\n extends Partial<UnionToIntersection<MethodsOptions[keyof MethodsOptions]>> {}\n\nexport interface WrappedOptions {\n onAccount: AccountBase;\n onCompiler: CompilerBase;\n onNode: Node;\n}\n\n/**\n * AeSdkMethods is the composition of:\n * - chain methods\n * - tx methods\n * - aens methods\n * - spend methods\n * - oracle methods\n * - contract methods\n * - contract ga methods\n *\n * While these methods can be used separately, this class provides a handy way to store\n * their context (current account, network, and compiler to use).\n */\nclass AeSdkMethods {\n _options: AeSdkMethodsOptions = {};\n\n readonly #wrappedOptions: WrappedOptions;\n\n /**\n * @param options - Options\n */\n constructor(options: AeSdkMethodsOptions = {}) {\n Object.assign(this._options, options);\n this.#wrappedOptions = {\n onAccount: wrapWithProxy(() => this._options.onAccount),\n onNode: wrapWithProxy(() => this._options.onNode),\n onCompiler: wrapWithProxy(() => this._options.onCompiler),\n };\n }\n\n /**\n * Returns sdk instance options with references to current account, node, compiler.\n * Used to create an instance (Contract, Oracle) bound to AeSdk state.\n * @param mergeWith - Merge context with these extra options\n * @returns Context object\n */\n getContext(mergeWith: AeSdkMethodsOptions = {}): AeSdkMethodsOptions & WrappedOptions {\n return {\n ...this._options,\n ...this.#wrappedOptions,\n ...mergeWith,\n };\n }\n\n // TODO: omit onNode from options, because it is already in context\n async buildTx(options: TxParamsAsync): Promise<Encoded.Transaction> {\n // TODO: remove `any` at the same time as AeSdk class\n return buildTxAsync({ ...(this.getContext() as any), ...options });\n }\n}\n\ntype RequiredKeys<T> = {\n [K in keyof T]-?: {} extends Pick<T, K> ? never : K;\n}[keyof T];\n\ntype OptionalIfNotRequired<T extends [any]> = RequiredKeys<T[0]> extends never ? T | [] : T;\n\ntype ReplaceOnAccount<Options> = Options extends { onAccount: any }\n ? Omit<Options, 'onAccount'> & {\n /**\n * Make operation on specific account by providing address (to use account from sdk) or instance\n * of AccountBase (like AccountMemory)\n */\n onAccount: OnAccount;\n }\n : Options;\n\ntype MakeOptional<Options> = OptionalIfNotRequired<\n [Omit<Options, 'onNode' | 'onCompiler' | 'onAccount'> & Partial<ReplaceOnAccount<Options>>]\n>;\n\ntype TransformMethods<Methods extends { [key: string]: Function }> = {\n [Name in keyof Methods]: Methods[Name] extends (\n ...args: [...infer Args, infer Options]\n ) => infer Ret\n ? (...args: [...Args, ...MakeOptional<Options>]) => Ret\n : never;\n};\n\ninterface AeSdkMethodsTransformed extends TransformMethods<typeof methods> {}\n\nObject.assign(\n AeSdkMethods.prototype,\n mapObject<Function, Function>(methods, ([name, handler]) => [\n name,\n function methodWrapper(this: AeSdkMethods, ...args: any[]) {\n args.length = handler.length;\n const options = args[args.length - 1];\n args[args.length - 1] = this.getContext(options);\n return handler(...args);\n },\n ]),\n);\n\ntype AeSdkMethodsTyped = AeSdkMethods & AeSdkMethodsTransformed;\n// eslint-disable-next-line @typescript-eslint/no-redeclare\nconst AeSdkMethodsTyped = AeSdkMethods as new (options?: AeSdkMethodsOptions) => AeSdkMethodsTyped;\nexport default AeSdkMethodsTyped;\n"],"mappings":";;;;;;AAAA,OAAO,KAAKA,YAAY,MAAM,YAAY;AAC1C,SAASC,eAAe,QAAQ,uBAAuB;AACvD,OAAO,KAAKC,YAAY,MAAM,YAAY;AAC1C,OAAO,KAAKC,iBAAiB,MAAM,kBAAkB;AACrD,SAASC,YAAY,QAAQ,uBAAuB;AACpD,SAASC,SAAS,QAA6B,kBAAkB;AACjE,SAASC,aAAa,QAAQ,uBAAuB;AASrD,MAAMC,OAAO,GAAG;EACd,GAAGP,YAAY;EACfC,eAAe;EACf,GAAGC,YAAY;EACf,GAAGC;AACL,CAAU;AAAC,IAAAK,eAAA,oBAAAC,OAAA;AAkBX;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAMC,YAAY,CAAC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C,CAAC,GAAG,IAAI,CAACT,UAAU,CAACV,OAAO,CAAC;EAChD,OAAOgB,OAAO,CAAC,GAAGE,IAAI,CAAC;AACzB,CAAC,CACF,CACH,CAAC;AAGD;AACA,MAAME,iBAAiB,GAAGtB,YAAwE;AAClG,eAAesB,iBAAiB","ignoreList":[]}
|
package/es/AeSdkWallet.js
CHANGED
|
@@ -271,7 +271,7 @@ export default class AeSdkWallet extends AeSdk {
|
|
|
271
271
|
aeppOrigin: origin,
|
|
272
272
|
aeppRpcClientId: id
|
|
273
273
|
};
|
|
274
|
-
const signature = encode(await this.
|
|
274
|
+
const signature = encode(await this.unsafeSign(decode(data), parameters), Encoding.Signature);
|
|
275
275
|
return {
|
|
276
276
|
signature
|
|
277
277
|
};
|
package/es/AeSdkWallet.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"AeSdkWallet.js","names":["nacl","AeSdk","verifyTransaction","RpcClient","METHODS","RPC_STATUS","SUBSCRIPTION_TYPES","RpcInvalidTransactionError","RpcNotAuthorizeError","RpcPermissionDenyError","RpcUnsupportedProtocolError","InternalError","UnknownRpcClientError","RPC_VERSION","Encoding","encode","decode","jsonBig","AeSdkWallet","constructor","name","id","type","onConnection","onSubscription","onDisconnect","onAskAccounts","onAskToSelectNetwork","options","_defineProperty","Map","_type","_getAccountsForClient","addressSubscription","current","connected","getAccounts","has","_pushAccountsToApps","_clients","Array","from","keys","filter","clientId","_isRpcClientConnected","map","_getClient","client","size","forEach","rpc","notify","updateAddress","selectAccount","address","addAccount","account","_getNode","ensureNodeConnected","node","url","api","$host","selectedNodeName","selectNode","networkId","getNetworkId","updateNetwork","connectNode","get","CONNECTED","status","connection","isConnected","_disconnectRpcClient","disconnect","DISCONNECTED","Set","removeRpcClient","delete","addRpcClient","clientConnection","_Buffer","randomBytes","toString","disconnectParams","WAITING_FOR_CONNECTION_REQUEST","closeConnection","params","connect","version","icons","origin","getWalletInfo","subscribeAddress","value","subscribe","add","unsubscribe","subscription","addresses","sign","tx","onAccount","returnSigned","innerTx","includes","parameters","aeppOrigin","aeppRpcClientId","signedTransaction","signTransaction","parse","stringify","transactionHash","sendTransaction","verify","error","validation","length","signMessage","message","signature","signTypedData","domain","aci","data","unsafeSign","Signature","signDelegation","delegation","set","shareWalletInfo","readyToConnect","window","location","selectedAddress","a","reduce","acc"],"sources":["../src/AeSdkWallet.ts"],"sourcesContent":["import nacl from 'tweetnacl';\nimport AeSdk from './AeSdk.js';\nimport verifyTransaction from './tx/validator.js';\nimport RpcClient from './aepp-wallet-communication/rpc/RpcClient.js';\nimport {\n METHODS,\n RPC_STATUS,\n SUBSCRIPTION_TYPES,\n WALLET_TYPE,\n RpcInvalidTransactionError,\n RpcNotAuthorizeError,\n RpcPermissionDenyError,\n RpcUnsupportedProtocolError,\n} from './aepp-wallet-communication/schema.js';\nimport { InternalError, UnknownRpcClientError } from './utils/errors.js';\nimport AccountBase from './account/Base.js';\nimport BrowserConnection from './aepp-wallet-communication/connection/Browser.js';\nimport {\n Accounts,\n AeppApi,\n Network,\n NetworkToSelect,\n RPC_VERSION,\n WalletApi,\n WalletInfo,\n} from './aepp-wallet-communication/rpc/types.js';\nimport { Encoded, Encoding, encode, decode } from './utils/encoder.js';\nimport jsonBig from './utils/json-big.js';\n\ntype RpcClientWallet = RpcClient<AeppApi, WalletApi>;\n\ntype OnConnection = (\n clientId: string,\n params: Omit<Parameters<WalletApi[METHODS.connect]>[0], 'version'>,\n origin: string,\n) => void;\n\ntype OnSubscription = (\n clientId: string,\n params: Parameters<WalletApi[METHODS.subscribeAddress]>[0],\n origin: string,\n) => void;\n\ntype OnDisconnect = (\n clientId: string,\n params: Parameters<WalletApi[METHODS.closeConnection]>[0],\n) => void;\n\ntype OnAskAccounts = (clientId: string, params: undefined, origin: string) => void;\n\ntype OnAskToSelectNetwork = (clientId: string, params: NetworkToSelect, origin: string) => void;\n\ninterface RpcClientsInfo {\n id: string;\n status: RPC_STATUS;\n connectNode: boolean;\n addressSubscription: Set<'connected' | 'current'>;\n rpc: RpcClientWallet;\n}\n\n/**\n * Contain functionality for aepp interaction and managing multiple aepps\n * @category aepp wallet communication\n */\nexport default class AeSdkWallet extends AeSdk {\n id: string;\n\n _type: WALLET_TYPE;\n\n name: string;\n\n _clients = new Map<string, RpcClientsInfo>();\n\n onConnection: OnConnection;\n\n onSubscription: OnSubscription;\n\n onDisconnect: OnDisconnect;\n\n onAskAccounts: OnAskAccounts;\n\n onAskToSelectNetwork: OnAskToSelectNetwork;\n\n /**\n * @param options - Options\n * @param options.name - Wallet name\n * @param options.id - Wallet id\n * @param options.type - Wallet type\n * @param options.onConnection - Call-back function for incoming AEPP connection\n * @param options.onSubscription - Call-back function for incoming AEPP account subscription\n * @param options.onAskAccounts - Call-back function for incoming AEPP get address request\n * @param options.onAskToSelectNetwork - Call-back function for incoming AEPP select network\n * request. If the request is fine then this function should change the current network.\n * @param options.onDisconnect - Call-back function for disconnect event\n */\n constructor({\n name,\n id,\n type,\n onConnection,\n onSubscription,\n onDisconnect,\n onAskAccounts,\n onAskToSelectNetwork,\n ...options\n }: {\n id: string;\n type: WALLET_TYPE;\n name: string;\n onConnection: OnConnection;\n onSubscription: OnSubscription;\n onDisconnect: OnDisconnect;\n onAskAccounts: OnAskAccounts;\n onAskToSelectNetwork: OnAskToSelectNetwork;\n } & ConstructorParameters<typeof AeSdk>[0]) {\n super(options);\n this.onConnection = onConnection;\n this.onSubscription = onSubscription;\n this.onDisconnect = onDisconnect;\n this.onAskAccounts = onAskAccounts;\n this.onAskToSelectNetwork = onAskToSelectNetwork;\n this.name = name;\n this.id = id;\n this._type = type;\n }\n\n _getAccountsForClient({ addressSubscription }: RpcClientsInfo): Accounts {\n const { current, connected } = this.getAccounts();\n return {\n current:\n addressSubscription.has('current') || addressSubscription.has('connected') ? current : {},\n connected: addressSubscription.has('connected') ? connected : {},\n };\n }\n\n _pushAccountsToApps(): void {\n if (this._clients == null) return;\n Array.from(this._clients.keys())\n .filter((clientId) => this._isRpcClientConnected(clientId))\n .map((clientId) => this._getClient(clientId))\n .filter((client) => client.addressSubscription.size !== 0)\n .forEach((client) =>\n client.rpc.notify(METHODS.updateAddress, this._getAccountsForClient(client)),\n );\n }\n\n override selectAccount(address: Encoded.AccountAddress): void {\n super.selectAccount(address);\n this._pushAccountsToApps();\n }\n\n override addAccount(account: AccountBase, options?: Parameters<AeSdk['addAccount']>[1]): void {\n super.addAccount(account, options);\n this._pushAccountsToApps();\n }\n\n _getNode(): { node: Network['node'] } {\n this.ensureNodeConnected();\n return { node: { url: this.api.$host, name: this.selectedNodeName } };\n }\n\n override async selectNode(name: string): Promise<void> {\n super.selectNode(name);\n const networkId = await this.api.getNetworkId();\n Array.from(this._clients.keys())\n .filter((clientId) => this._isRpcClientConnected(clientId))\n .map((clientId) => this._getClient(clientId))\n .forEach((client) => {\n client.rpc.notify(METHODS.updateNetwork, {\n networkId,\n ...(client.connectNode && this._getNode()),\n });\n });\n }\n\n _getClient(clientId: string): RpcClientsInfo {\n const client = this._clients.get(clientId);\n if (client == null) throw new UnknownRpcClientError(clientId);\n return client;\n }\n\n _isRpcClientConnected(clientId: string): boolean {\n return (\n RPC_STATUS.CONNECTED === this._getClient(clientId).status &&\n this._getClient(clientId).rpc.connection.isConnected()\n );\n }\n\n _disconnectRpcClient(clientId: string): void {\n const client = this._getClient(clientId);\n client.rpc.connection.disconnect();\n client.status = RPC_STATUS.DISCONNECTED;\n client.addressSubscription = new Set();\n }\n\n /**\n * Remove specific RpcClient by ID\n * @param id - Client ID\n */\n removeRpcClient(id: string): void {\n this._disconnectRpcClient(id);\n this._clients.delete(id);\n }\n\n /**\n * Add new client by AEPP connection\n * @param clientConnection - AEPP connection object\n * @returns Client ID\n */\n addRpcClient(clientConnection: BrowserConnection): string {\n // @TODO detect if aepp has some history based on origin????\n // if yes use this instance for connection\n const id = Buffer.from(nacl.randomBytes(8)).toString('base64');\n let disconnectParams: any;\n const client: RpcClientsInfo = {\n id,\n status: RPC_STATUS.WAITING_FOR_CONNECTION_REQUEST,\n addressSubscription: new Set(),\n connectNode: false,\n rpc: new RpcClient<AeppApi, WalletApi>(\n clientConnection,\n () => {\n this._clients.delete(id);\n this.onDisconnect(id, disconnectParams); // also related info\n },\n {\n [METHODS.closeConnection]: (params) => {\n disconnectParams = params;\n this._disconnectRpcClient(id);\n },\n // Store client info and prepare two fn for each client `connect` and `denyConnection`\n // which automatically prepare and send response for that client\n [METHODS.connect]: async ({ name, version, icons, connectNode }, origin) => {\n if (version !== RPC_VERSION) throw new RpcUnsupportedProtocolError();\n\n await this.onConnection(id, { name, icons, connectNode }, origin);\n client.status = RPC_STATUS.CONNECTED;\n client.connectNode = connectNode;\n return {\n ...(await this.getWalletInfo()),\n ...(connectNode && this._getNode()),\n };\n },\n [METHODS.subscribeAddress]: async ({ type, value }, origin) => {\n if (!this._isRpcClientConnected(id)) throw new RpcNotAuthorizeError();\n\n switch (type) {\n case SUBSCRIPTION_TYPES.subscribe:\n // TODO: remove `type` as it always subscribe\n await this.onSubscription(id, { type, value }, origin);\n client.addressSubscription.add(value);\n break;\n case SUBSCRIPTION_TYPES.unsubscribe:\n client.addressSubscription.delete(value);\n break;\n default:\n throw new InternalError(`Unknown subscription type: ${type}`);\n }\n\n return {\n subscription: Array.from(client.addressSubscription),\n address: this._getAccountsForClient(client),\n };\n },\n [METHODS.address]: async (params, origin) => {\n if (!this._isRpcClientConnected(id)) throw new RpcNotAuthorizeError();\n await this.onAskAccounts(id, params, origin);\n return this.addresses();\n },\n [METHODS.sign]: async (\n { tx, onAccount = this.address, returnSigned, innerTx },\n origin,\n ) => {\n if (!this._isRpcClientConnected(id)) throw new RpcNotAuthorizeError();\n if (!this.addresses().includes(onAccount)) {\n throw new RpcPermissionDenyError(onAccount);\n }\n\n const parameters = {\n onAccount,\n aeppOrigin: origin,\n aeppRpcClientId: id,\n innerTx,\n };\n if (returnSigned || innerTx === true) {\n return { signedTransaction: await this.signTransaction(tx, parameters) };\n }\n try {\n return jsonBig.parse(\n jsonBig.stringify({\n transactionHash: await this.sendTransaction(tx, { ...parameters, verify: false }),\n }),\n );\n } catch (error) {\n const validation = await verifyTransaction(tx, this.api);\n if (validation.length > 0) throw new RpcInvalidTransactionError(validation);\n throw error;\n }\n },\n [METHODS.signMessage]: async ({ message, onAccount = this.address }, origin) => {\n if (!this._isRpcClientConnected(id)) throw new RpcNotAuthorizeError();\n if (!this.addresses().includes(onAccount)) {\n throw new RpcPermissionDenyError(onAccount);\n }\n\n const parameters = { onAccount, aeppOrigin: origin, aeppRpcClientId: id };\n return {\n signature: Buffer.from(await this.signMessage(message, parameters)).toString('hex'),\n };\n },\n [METHODS.signTypedData]: async (\n { domain, aci, data, onAccount = this.address },\n origin,\n ) => {\n if (!this._isRpcClientConnected(id)) throw new RpcNotAuthorizeError();\n if (!this.addresses().includes(onAccount)) {\n throw new RpcPermissionDenyError(onAccount);\n }\n\n const parameters = {\n ...domain,\n onAccount,\n aeppOrigin: origin,\n aeppRpcClientId: id,\n };\n return {\n signature: await this.signTypedData(data, aci, parameters),\n };\n },\n [METHODS.unsafeSign]: async ({ data, onAccount = this.address }, origin) => {\n if (!this._isRpcClientConnected(id)) throw new RpcNotAuthorizeError();\n if (!this.addresses().includes(onAccount)) throw new RpcPermissionDenyError(onAccount);\n const parameters = { onAccount, aeppOrigin: origin, aeppRpcClientId: id };\n const signature = encode(await this.sign(decode(data), parameters), Encoding.Signature);\n return { signature };\n },\n [METHODS.signDelegation]: async ({ delegation, onAccount = this.address }, origin) => {\n if (!this._isRpcClientConnected(id)) throw new RpcNotAuthorizeError();\n if (!this.addresses().includes(onAccount)) throw new RpcPermissionDenyError(onAccount);\n const parameters = { onAccount, aeppOrigin: origin, aeppRpcClientId: id };\n const signature = await this.signDelegation(delegation, parameters);\n return { signature };\n },\n [METHODS.updateNetwork]: async (params, origin) => {\n if (!this._isRpcClientConnected(id)) throw new RpcNotAuthorizeError();\n await this.onAskToSelectNetwork(id, params, origin);\n return null;\n },\n },\n ),\n };\n this._clients.set(id, client);\n return id;\n }\n\n /**\n * Send shareWalletInfo message to notify AEPP about wallet\n * @param clientId - ID of RPC client send message to\n */\n async shareWalletInfo(clientId: string): Promise<void> {\n this._getClient(clientId).rpc.notify(METHODS.readyToConnect, await this.getWalletInfo());\n }\n\n /**\n * Get Wallet info object\n * @returns Object with wallet information\n */\n async getWalletInfo(): Promise<WalletInfo> {\n const { origin } = window.location;\n return {\n id: this.id,\n name: this.name,\n networkId: await this.api.getNetworkId(),\n origin: origin === 'file://' ? '*' : origin,\n type: this._type,\n };\n }\n\n /**\n * Get Wallet accounts\n * @returns Object with accounts information (\\{ connected: Object, current: Object \\})\n */\n getAccounts(): Accounts {\n return {\n current: this.selectedAddress != null ? { [this.selectedAddress]: {} } : {},\n connected: this.addresses()\n .filter((a) => a !== this.selectedAddress)\n .reduce((acc, a) => ({ ...acc, [a]: {} }), {}),\n };\n }\n}\n"],"mappings":";;AAAA,OAAOA,IAAI,MAAM,WAAW;AAC5B,OAAOC,KAAK,MAAM,YAAY;AAC9B,OAAOC,iBAAiB,MAAM,mBAAmB;AACjD,OAAOC,SAAS,MAAM,8CAA8C;AACpE,SACEC,OAAO,EACPC,UAAU,EACVC,kBAAkB,EAElBC,0BAA0B,EAC1BC,oBAAoB,EACpBC,sBAAsB,EACtBC,2BAA2B,QACtB,uCAAuC;AAC9C,SAASC,aAAa,EAAEC,qBAAqB,QAAQ,mBAAmB;AAGxE,SAKEC,WAAW,QAGN,0CAA0C;AACjD,SAAkBC,QAAQ,EAAEC,MAAM,EAAEC,MAAM,QAAQ,oBAAoB;AACtE,OAAOC,OAAO,MAAM,qBAAqB;AAiCzC;AACA;AACA;AACA;AACA,eAAe,MAAMC,WAAW,SAASjB,KAAK,CAAC;EAmB7C;AACF;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;EACEkB,WAAWA,CAAC;IACVC,IAAI;IACJC,EAAE;IACFC,IAAI;IACJC,YAAY;IACZC,cAAc;IACdC,YAAY;IACZC,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MAAMgH,eAAeA,CAACzF,QAAgB,EAAiB;IACrD,IAAI,CAACG,UAAU,CAACH,QAAQ,CAAC,CAACO,GAAG,CAACC,MAAM,CAAChD,OAAO,CAACkI,cAAc,EAAE,MAAM,IAAI,CAACxC,aAAa,CAAC,CAAC,CAAC;EAC1F;;EAEA;AACF;AACA;AACA;EACE,MAAMA,aAAaA,CAAA,EAAwB;IACzC,MAAM;MAAED;IAAO,CAAC,GAAG0C,MAAM,CAACC,QAAQ;IAClC,OAAO;MACLnH,EAAE,EAAE,IAAI,CAACA,EAAE;MACXD,IAAI,EAAE,IAAI,CAACA,IAAI;MACf8C,SAAS,EAAE,MAAM,IAAI,CAACJ,GAAG,CAACK,YAAY,CAAC,CAAC;MACxC0B,MAAM,EAAEA,MAAM,KAAK,SAAS,GAAG,GAAG,GAAGA,MAAM;MAC3CvE,IAAI,EAAE,IAAI,CAACS;IACb,CAAC;EACH;;EAEA;AACF;AACA;AACA;EACEK,WAAWA,CAAA,EAAa;IACtB,OAAO;MACLF,OAAO,EAAE,IAAI,CAACuG,eAAe,IAAI,IAAI,GAAG;QAAE,CAAC,IAAI,CAACA,eAAe,GAAG,CAAC;MAAE,CAAC,GAAG,CAAC,CAAC;MAC3EtG,SAAS,EAAE,IAAI,CAACkE,SAAS,CAAC,CAAC,CACxB1D,MAAM,CAAE+F,CAAC,IAAKA,CAAC,KAAK,IAAI,CAACD,eAAe,CAAC,CACzCE,MAAM,CAAC,CAACC,GAAG,EAAEF,CAAC,MAAM;QAAE,GAAGE,GAAG;QAAE,CAACF,CAAC,GAAG,CAAC;MAAE,CAAC,CAAC,EAAE,CAAC,CAAC;IACjD,CAAC;EACH;AACF","ignoreList":[]}
|
|
1
|
+
{"version":3,"file":"AeSdkWallet.js","names":["nacl","AeSdk","verifyTransaction","RpcClient","METHODS","RPC_STATUS","SUBSCRIPTION_TYPES","RpcInvalidTransactionError","RpcNotAuthorizeError","RpcPermissionDenyError","RpcUnsupportedProtocolError","InternalError","UnknownRpcClientError","RPC_VERSION","Encoding","encode","decode","jsonBig","AeSdkWallet","constructor","name","id","type","onConnection","onSubscription","onDisconnect","onAskAccounts","onAskToSelectNetwork","options","_defineProperty","Map","_type","_getAccountsForClient","addressSubscription","current","connected","getAccounts","has","_pushAccountsToApps","_clients","Array","from","keys","filter","clientId","_isRpcClientConnected","map","_getClient","client","size","forEach","rpc","notify","updateAddress","selectAccount","address","addAccount","account","_getNode","ensureNodeConnected","node","url","api","$host","selectedNodeName","selectNode","networkId","getNetworkId","updateNetwork","connectNode","get","CONNECTED","status","connection","isConnected","_disconnectRpcClient","disconnect","DISCONNECTED","Set","removeRpcClient","delete","addRpcClient","clientConnection","_Buffer","randomBytes","toString","disconnectParams","WAITING_FOR_CONNECTION_REQUEST","closeConnection","params","connect","version","icons","origin","getWalletInfo","subscribeAddress","value","subscribe","add","unsubscribe","subscription","addresses","sign","tx","onAccount","returnSigned","innerTx","includes","parameters","aeppOrigin","aeppRpcClientId","signedTransaction","signTransaction","parse","stringify","transactionHash","sendTransaction","verify","error","validation","length","signMessage","message","signature","signTypedData","domain","aci","data","unsafeSign","Signature","signDelegation","delegation","set","shareWalletInfo","readyToConnect","window","location","selectedAddress","a","reduce","acc"],"sources":["../src/AeSdkWallet.ts"],"sourcesContent":["import nacl from 'tweetnacl';\nimport AeSdk from './AeSdk.js';\nimport verifyTransaction from './tx/validator.js';\nimport RpcClient from './aepp-wallet-communication/rpc/RpcClient.js';\nimport {\n METHODS,\n RPC_STATUS,\n SUBSCRIPTION_TYPES,\n WALLET_TYPE,\n RpcInvalidTransactionError,\n RpcNotAuthorizeError,\n RpcPermissionDenyError,\n RpcUnsupportedProtocolError,\n} from './aepp-wallet-communication/schema.js';\nimport { InternalError, UnknownRpcClientError } from './utils/errors.js';\nimport AccountBase from './account/Base.js';\nimport BrowserConnection from './aepp-wallet-communication/connection/Browser.js';\nimport {\n Accounts,\n AeppApi,\n Network,\n NetworkToSelect,\n RPC_VERSION,\n WalletApi,\n WalletInfo,\n} from './aepp-wallet-communication/rpc/types.js';\nimport { Encoded, Encoding, encode, decode } from './utils/encoder.js';\nimport jsonBig from './utils/json-big.js';\n\ntype RpcClientWallet = RpcClient<AeppApi, WalletApi>;\n\ntype OnConnection = (\n clientId: string,\n params: Omit<Parameters<WalletApi[METHODS.connect]>[0], 'version'>,\n origin: string,\n) => void;\n\ntype OnSubscription = (\n clientId: string,\n params: Parameters<WalletApi[METHODS.subscribeAddress]>[0],\n origin: string,\n) => void;\n\ntype OnDisconnect = (\n clientId: string,\n params: Parameters<WalletApi[METHODS.closeConnection]>[0],\n) => void;\n\ntype OnAskAccounts = (clientId: string, params: undefined, origin: string) => void;\n\ntype OnAskToSelectNetwork = (clientId: string, params: NetworkToSelect, origin: string) => void;\n\ninterface RpcClientsInfo {\n id: string;\n status: RPC_STATUS;\n connectNode: boolean;\n addressSubscription: Set<'connected' | 'current'>;\n rpc: RpcClientWallet;\n}\n\n/**\n * Contain functionality for aepp interaction and managing multiple aepps\n * @category aepp wallet communication\n */\nexport default class AeSdkWallet extends AeSdk {\n id: string;\n\n _type: WALLET_TYPE;\n\n name: string;\n\n _clients = new Map<string, RpcClientsInfo>();\n\n onConnection: OnConnection;\n\n onSubscription: OnSubscription;\n\n onDisconnect: OnDisconnect;\n\n onAskAccounts: OnAskAccounts;\n\n onAskToSelectNetwork: OnAskToSelectNetwork;\n\n /**\n * @param options - Options\n * @param options.name - Wallet name\n * @param options.id - Wallet id\n * @param options.type - Wallet type\n * @param options.onConnection - Call-back function for incoming AEPP connection\n * @param options.onSubscription - Call-back function for incoming AEPP account subscription\n * @param options.onAskAccounts - Call-back function for incoming AEPP get address request\n * @param options.onAskToSelectNetwork - Call-back function for incoming AEPP select network\n * request. If the request is fine then this function should change the current network.\n * @param options.onDisconnect - Call-back function for disconnect event\n */\n constructor({\n name,\n id,\n type,\n onConnection,\n onSubscription,\n onDisconnect,\n onAskAccounts,\n onAskToSelectNetwork,\n ...options\n }: {\n id: string;\n type: WALLET_TYPE;\n name: string;\n onConnection: OnConnection;\n onSubscription: OnSubscription;\n onDisconnect: OnDisconnect;\n onAskAccounts: OnAskAccounts;\n onAskToSelectNetwork: OnAskToSelectNetwork;\n } & ConstructorParameters<typeof AeSdk>[0]) {\n super(options);\n this.onConnection = onConnection;\n this.onSubscription = onSubscription;\n this.onDisconnect = onDisconnect;\n this.onAskAccounts = onAskAccounts;\n this.onAskToSelectNetwork = onAskToSelectNetwork;\n this.name = name;\n this.id = id;\n this._type = type;\n }\n\n _getAccountsForClient({ addressSubscription }: RpcClientsInfo): Accounts {\n const { current, connected } = this.getAccounts();\n return {\n current:\n addressSubscription.has('current') || addressSubscription.has('connected') ? current : {},\n connected: addressSubscription.has('connected') ? connected : {},\n };\n }\n\n _pushAccountsToApps(): void {\n if (this._clients == null) return;\n Array.from(this._clients.keys())\n .filter((clientId) => this._isRpcClientConnected(clientId))\n .map((clientId) => this._getClient(clientId))\n .filter((client) => client.addressSubscription.size !== 0)\n .forEach((client) =>\n client.rpc.notify(METHODS.updateAddress, this._getAccountsForClient(client)),\n );\n }\n\n override selectAccount(address: Encoded.AccountAddress): void {\n super.selectAccount(address);\n this._pushAccountsToApps();\n }\n\n override addAccount(account: AccountBase, options?: Parameters<AeSdk['addAccount']>[1]): void {\n super.addAccount(account, options);\n this._pushAccountsToApps();\n }\n\n _getNode(): { node: Network['node'] } {\n this.ensureNodeConnected();\n return { node: { url: this.api.$host, name: this.selectedNodeName } };\n }\n\n override async selectNode(name: string): Promise<void> {\n super.selectNode(name);\n const networkId = await this.api.getNetworkId();\n Array.from(this._clients.keys())\n .filter((clientId) => this._isRpcClientConnected(clientId))\n .map((clientId) => this._getClient(clientId))\n .forEach((client) => {\n client.rpc.notify(METHODS.updateNetwork, {\n networkId,\n ...(client.connectNode && this._getNode()),\n });\n });\n }\n\n _getClient(clientId: string): RpcClientsInfo {\n const client = this._clients.get(clientId);\n if (client == null) throw new UnknownRpcClientError(clientId);\n return client;\n }\n\n _isRpcClientConnected(clientId: string): boolean {\n return (\n RPC_STATUS.CONNECTED === this._getClient(clientId).status &&\n this._getClient(clientId).rpc.connection.isConnected()\n );\n }\n\n _disconnectRpcClient(clientId: string): void {\n const client = this._getClient(clientId);\n client.rpc.connection.disconnect();\n client.status = RPC_STATUS.DISCONNECTED;\n client.addressSubscription = new Set();\n }\n\n /**\n * Remove specific RpcClient by ID\n * @param id - Client ID\n */\n removeRpcClient(id: string): void {\n this._disconnectRpcClient(id);\n this._clients.delete(id);\n }\n\n /**\n * Add new client by AEPP connection\n * @param clientConnection - AEPP connection object\n * @returns Client ID\n */\n addRpcClient(clientConnection: BrowserConnection): string {\n // @TODO detect if aepp has some history based on origin????\n // if yes use this instance for connection\n const id = Buffer.from(nacl.randomBytes(8)).toString('base64');\n let disconnectParams: any;\n const client: RpcClientsInfo = {\n id,\n status: RPC_STATUS.WAITING_FOR_CONNECTION_REQUEST,\n addressSubscription: new Set(),\n connectNode: false,\n rpc: new RpcClient<AeppApi, WalletApi>(\n clientConnection,\n () => {\n this._clients.delete(id);\n this.onDisconnect(id, disconnectParams); // also related info\n },\n {\n [METHODS.closeConnection]: (params) => {\n disconnectParams = params;\n this._disconnectRpcClient(id);\n },\n // Store client info and prepare two fn for each client `connect` and `denyConnection`\n // which automatically prepare and send response for that client\n [METHODS.connect]: async ({ name, version, icons, connectNode }, origin) => {\n if (version !== RPC_VERSION) throw new RpcUnsupportedProtocolError();\n\n await this.onConnection(id, { name, icons, connectNode }, origin);\n client.status = RPC_STATUS.CONNECTED;\n client.connectNode = connectNode;\n return {\n ...(await this.getWalletInfo()),\n ...(connectNode && this._getNode()),\n };\n },\n [METHODS.subscribeAddress]: async ({ type, value }, origin) => {\n if (!this._isRpcClientConnected(id)) throw new RpcNotAuthorizeError();\n\n switch (type) {\n case SUBSCRIPTION_TYPES.subscribe:\n // TODO: remove `type` as it always subscribe\n await this.onSubscription(id, { type, value }, origin);\n client.addressSubscription.add(value);\n break;\n case SUBSCRIPTION_TYPES.unsubscribe:\n client.addressSubscription.delete(value);\n break;\n default:\n throw new InternalError(`Unknown subscription type: ${type}`);\n }\n\n return {\n subscription: Array.from(client.addressSubscription),\n address: this._getAccountsForClient(client),\n };\n },\n [METHODS.address]: async (params, origin) => {\n if (!this._isRpcClientConnected(id)) throw new RpcNotAuthorizeError();\n await this.onAskAccounts(id, params, origin);\n return this.addresses();\n },\n [METHODS.sign]: async (\n { tx, onAccount = this.address, returnSigned, innerTx },\n origin,\n ) => {\n if (!this._isRpcClientConnected(id)) throw new RpcNotAuthorizeError();\n if (!this.addresses().includes(onAccount)) {\n throw new RpcPermissionDenyError(onAccount);\n }\n\n const parameters = {\n onAccount,\n aeppOrigin: origin,\n aeppRpcClientId: id,\n innerTx,\n };\n if (returnSigned || innerTx === true) {\n return { signedTransaction: await this.signTransaction(tx, parameters) };\n }\n try {\n return jsonBig.parse(\n jsonBig.stringify({\n transactionHash: await this.sendTransaction(tx, { ...parameters, verify: false }),\n }),\n );\n } catch (error) {\n const validation = await verifyTransaction(tx, this.api);\n if (validation.length > 0) throw new RpcInvalidTransactionError(validation);\n throw error;\n }\n },\n [METHODS.signMessage]: async ({ message, onAccount = this.address }, origin) => {\n if (!this._isRpcClientConnected(id)) throw new RpcNotAuthorizeError();\n if (!this.addresses().includes(onAccount)) {\n throw new RpcPermissionDenyError(onAccount);\n }\n\n const parameters = { onAccount, aeppOrigin: origin, aeppRpcClientId: id };\n return {\n signature: Buffer.from(await this.signMessage(message, parameters)).toString('hex'),\n };\n },\n [METHODS.signTypedData]: async (\n { domain, aci, data, onAccount = this.address },\n origin,\n ) => {\n if (!this._isRpcClientConnected(id)) throw new RpcNotAuthorizeError();\n if (!this.addresses().includes(onAccount)) {\n throw new RpcPermissionDenyError(onAccount);\n }\n\n const parameters = {\n ...domain,\n onAccount,\n aeppOrigin: origin,\n aeppRpcClientId: id,\n };\n return {\n signature: await this.signTypedData(data, aci, parameters),\n };\n },\n [METHODS.unsafeSign]: async ({ data, onAccount = this.address }, origin) => {\n if (!this._isRpcClientConnected(id)) throw new RpcNotAuthorizeError();\n if (!this.addresses().includes(onAccount)) throw new RpcPermissionDenyError(onAccount);\n const parameters = { onAccount, aeppOrigin: origin, aeppRpcClientId: id };\n const signature = encode(\n await this.unsafeSign(decode(data), parameters),\n Encoding.Signature,\n );\n return { signature };\n },\n [METHODS.signDelegation]: async ({ delegation, onAccount = this.address }, origin) => {\n if (!this._isRpcClientConnected(id)) throw new RpcNotAuthorizeError();\n if (!this.addresses().includes(onAccount)) throw new RpcPermissionDenyError(onAccount);\n const parameters = { onAccount, aeppOrigin: origin, aeppRpcClientId: id };\n const signature = await this.signDelegation(delegation, parameters);\n return { signature };\n },\n [METHODS.updateNetwork]: async (params, origin) => {\n if (!this._isRpcClientConnected(id)) throw new RpcNotAuthorizeError();\n await this.onAskToSelectNetwork(id, params, origin);\n return null;\n },\n },\n ),\n };\n this._clients.set(id, client);\n return id;\n }\n\n /**\n * Send shareWalletInfo message to notify AEPP about wallet\n * @param clientId - ID of RPC client send message to\n */\n async shareWalletInfo(clientId: string): Promise<void> {\n this._getClient(clientId).rpc.notify(METHODS.readyToConnect, await this.getWalletInfo());\n }\n\n /**\n * Get Wallet info object\n * @returns Object with wallet information\n */\n async getWalletInfo(): Promise<WalletInfo> {\n const { origin } = window.location;\n return {\n id: this.id,\n name: this.name,\n networkId: await this.api.getNetworkId(),\n origin: origin === 'file://' ? '*' : origin,\n type: this._type,\n };\n }\n\n /**\n * Get Wallet accounts\n * @returns Object with accounts information (\\{ connected: Object, current: Object \\})\n */\n getAccounts(): Accounts {\n return {\n current: this.selectedAddress != null ? { [this.selectedAddress]: {} } : {},\n connected: this.addresses()\n .filter((a) => a !== this.selectedAddress)\n .reduce((acc, a) => ({ ...acc, [a]: {} }), {}),\n };\n }\n}\n"],"mappings":";;AAAA,OAAOA,IAAI,MAAM,WAAW;AAC5B,OAAOC,KAAK,MAAM,YAAY;AAC9B,OAAOC,iBAAiB,MAAM,mBAAmB;AACjD,OAAOC,SAAS,M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CAAC,IAAI,CAACA,eAAe,GAAG,CAAC;MAAE,CAAC,GAAG,CAAC,CAAC;MAC3EtG,SAAS,EAAE,IAAI,CAACkE,SAAS,CAAC,CAAC,CACxB1D,MAAM,CAAE+F,CAAC,IAAKA,CAAC,KAAK,IAAI,CAACD,eAAe,CAAC,CACzCE,MAAM,CAAC,CAACC,GAAG,EAAEF,CAAC,MAAM;QAAE,GAAGE,GAAG;QAAE,CAACF,CAAC,GAAG,CAAC;MAAE,CAAC,CAAC,EAAE,CAAC,CAAC;IACjD,CAAC;EACH;AACF","ignoreList":[]}
|
package/es/Middleware.d.ts
CHANGED
|
@@ -1,10 +1,14 @@
|
|
|
1
1
|
import { OperationArguments, OperationSpec } from '@azure/core-client';
|
|
2
2
|
import { Middleware as MiddlewareApi, MiddlewareOptionalParams } from './apis/middleware/index.js';
|
|
3
|
+
/**
|
|
4
|
+
* @category middleware
|
|
5
|
+
*/
|
|
3
6
|
export default class Middleware extends MiddlewareApi {
|
|
4
7
|
/**
|
|
5
8
|
* @param url - Url for middleware API
|
|
6
9
|
* @param options - Options
|
|
7
|
-
* @param options.ignoreVersion -
|
|
10
|
+
* @param options.ignoreVersion - Print warning instead of throwing exception if middleware
|
|
11
|
+
* is not supported, use with caution
|
|
8
12
|
* @param options.retryCount - Amount of extra requests to do in case of failure
|
|
9
13
|
* @param options.retryOverallDelay - Time in ms to wait between all retries
|
|
10
14
|
*/
|
package/es/Middleware.js
CHANGED
|
@@ -4,11 +4,16 @@ import { Middleware as MiddlewareApi } from './apis/middleware/index.js';
|
|
|
4
4
|
import { operationSpecs } from './apis/middleware/middleware.js';
|
|
5
5
|
import { IllegalArgumentError, InternalError } from './utils/errors.js';
|
|
6
6
|
import { MiddlewarePage, isMiddlewareRawPage } from './utils/MiddlewarePage.js';
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* @category middleware
|
|
10
|
+
*/
|
|
7
11
|
export default class Middleware extends MiddlewareApi {
|
|
8
12
|
/**
|
|
9
13
|
* @param url - Url for middleware API
|
|
10
14
|
* @param options - Options
|
|
11
|
-
* @param options.ignoreVersion -
|
|
15
|
+
* @param options.ignoreVersion - Print warning instead of throwing exception if middleware
|
|
16
|
+
* is not supported, use with caution
|
|
12
17
|
* @param options.retryCount - Amount of extra requests to do in case of failure
|
|
13
18
|
* @param options.retryOverallDelay - Time in ms to wait between all retries
|
|
14
19
|
*/
|
|
@@ -28,7 +33,7 @@ export default class Middleware extends MiddlewareApi {
|
|
|
28
33
|
// eslint-disable-next-line constructor-super
|
|
29
34
|
super(url, {
|
|
30
35
|
allowInsecureConnection: true,
|
|
31
|
-
additionalPolicies: [
|
|
36
|
+
additionalPolicies: [genVersionCheckPolicy('middleware', getVersion, '1.81.0', '2.0.0', ignoreVersion), genRequestQueuesPolicy(), genCombineGetRequestsPolicy(), genRetryOnFailurePolicy(retryCount, retryOverallDelay), genErrorFormatterPolicy(body => ` ${body.error}`)],
|
|
32
37
|
...options
|
|
33
38
|
});
|
|
34
39
|
this.pipeline.addPolicy(parseBigIntPolicy, {
|
package/es/Middleware.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Middleware.js","names":["userAgentPolicyName","setClientRequestIdPolicyName","genRequestQueuesPolicy","genCombineGetRequestsPolicy","genErrorFormatterPolicy","parseBigIntPolicy","genVersionCheckPolicy","genRetryOnFailurePolicy","Middleware","MiddlewareApi","operationSpecs","IllegalArgumentError","InternalError","MiddlewarePage","isMiddlewareRawPage","constructor","url","ignoreVersion","retryCount","retryOverallDelay","options","version","getVersion","opts","getStatus","mdwVersion","allowInsecureConnection","additionalPolicies","body","error","pipeline","addPolicy","phase","removePolicy","name","requestByPath","pathWithQuery","queryPos","indexOf","path","slice","length","query","operationSpec","find","os","p","groups","replace","split","part","shift","startsWith","sendOperationRequest","urlParameters","filter","parameterPath","queryParameters","Array","from","URLSearchParams","map","key","value","mapper","defaultValue","toString","serializedName","type","operationArguments","response"],"sources":["../src/Middleware.ts"],"sourcesContent":["import { OperationArguments, OperationOptions, OperationSpec } from '@azure/core-client';\nimport { userAgentPolicyName, setClientRequestIdPolicyName } from '@azure/core-rest-pipeline';\nimport {\n genRequestQueuesPolicy,\n genCombineGetRequestsPolicy,\n genErrorFormatterPolicy,\n parseBigIntPolicy,\n genVersionCheckPolicy,\n genRetryOnFailurePolicy,\n} from './utils/autorest.js';\nimport {\n Middleware as MiddlewareApi,\n MiddlewareOptionalParams,\n ErrorResponse,\n} from './apis/middleware/index.js';\nimport { operationSpecs } from './apis/middleware/middleware.js';\nimport { IllegalArgumentError, InternalError } from './utils/errors.js';\nimport { MiddlewarePage, isMiddlewareRawPage } from './utils/MiddlewarePage.js';\n\nexport default class Middleware extends MiddlewareApi {\n /**\n * @param url - Url for middleware API\n * @param options - Options\n * @param options.ignoreVersion -
|
|
1
|
+
{"version":3,"file":"Middleware.js","names":["userAgentPolicyName","setClientRequestIdPolicyName","genRequestQueuesPolicy","genCombineGetRequestsPolicy","genErrorFormatterPolicy","parseBigIntPolicy","genVersionCheckPolicy","genRetryOnFailurePolicy","Middleware","MiddlewareApi","operationSpecs","IllegalArgumentError","InternalError","MiddlewarePage","isMiddlewareRawPage","constructor","url","ignoreVersion","retryCount","retryOverallDelay","options","version","getVersion","opts","getStatus","mdwVersion","allowInsecureConnection","additionalPolicies","body","error","pipeline","addPolicy","phase","removePolicy","name","requestByPath","pathWithQuery","queryPos","indexOf","path","slice","length","query","operationSpec","find","os","p","groups","replace","split","part","shift","startsWith","sendOperationRequest","urlParameters","filter","parameterPath","queryParameters","Array","from","URLSearchParams","map","key","value","mapper","defaultValue","toString","serializedName","type","operationArguments","response"],"sources":["../src/Middleware.ts"],"sourcesContent":["import { OperationArguments, OperationOptions, OperationSpec } from '@azure/core-client';\nimport { userAgentPolicyName, setClientRequestIdPolicyName } from '@azure/core-rest-pipeline';\nimport {\n genRequestQueuesPolicy,\n genCombineGetRequestsPolicy,\n genErrorFormatterPolicy,\n parseBigIntPolicy,\n genVersionCheckPolicy,\n genRetryOnFailurePolicy,\n} from './utils/autorest.js';\nimport {\n Middleware as MiddlewareApi,\n MiddlewareOptionalParams,\n ErrorResponse,\n} from './apis/middleware/index.js';\nimport { operationSpecs } from './apis/middleware/middleware.js';\nimport { IllegalArgumentError, InternalError } from './utils/errors.js';\nimport { MiddlewarePage, isMiddlewareRawPage } from './utils/MiddlewarePage.js';\n\n/**\n * @category middleware\n */\nexport default class Middleware extends MiddlewareApi {\n /**\n * @param url - Url for middleware API\n * @param options - Options\n * @param options.ignoreVersion - Print warning instead of throwing exception if middleware\n * is not supported, use with caution\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,\n retryCount = 3,\n retryOverallDelay = 800,\n ...options\n }: MiddlewareOptionalParams & {\n ignoreVersion?: boolean;\n retryCount?: number;\n retryOverallDelay?: number;\n } = {},\n ) {\n let version: string | undefined;\n const getVersion = async (opts: OperationOptions): Promise<string> => {\n if (version != null) return version;\n version = (await this.getStatus(opts)).mdwVersion;\n return version;\n };\n\n // eslint-disable-next-line constructor-super\n super(url, {\n allowInsecureConnection: true,\n additionalPolicies: [\n genVersionCheckPolicy('middleware', getVersion, '1.81.0', '2.0.0', ignoreVersion),\n genRequestQueuesPolicy(),\n genCombineGetRequestsPolicy(),\n genRetryOnFailurePolicy(retryCount, retryOverallDelay),\n genErrorFormatterPolicy((body: ErrorResponse) => ` ${body.error}`),\n ],\n ...options,\n });\n this.pipeline.addPolicy(parseBigIntPolicy, { phase: 'Deserialize' });\n this.pipeline.removePolicy({ name: userAgentPolicyName });\n this.pipeline.removePolicy({ name: setClientRequestIdPolicyName });\n // TODO: use instead our retry policy\n this.pipeline.removePolicy({ name: 'defaultRetryPolicy' });\n }\n\n /**\n * Get a middleware response by path instead of a method name and arguments.\n * @param pathWithQuery - a path to request starting with `/v3/`\n */\n async requestByPath<Response = unknown>(pathWithQuery: string): Promise<Response> {\n const queryPos = pathWithQuery.indexOf('?');\n const path = pathWithQuery.slice(0, queryPos === -1 ? pathWithQuery.length : queryPos);\n const query = pathWithQuery.slice(queryPos === -1 ? pathWithQuery.length : queryPos + 1);\n\n const operationSpec = operationSpecs.find((os) => {\n let p = path;\n if (os.path == null) return false;\n const groups = os.path.replace(/{\\w+}/g, '{param}').split('{param}');\n while (groups.length > 0) {\n const part = groups.shift();\n if (part == null) throw new InternalError(`Unexpected operation spec path: ${os.path}`);\n if (!p.startsWith(part)) return false;\n p = p.replace(part, '');\n if (groups.length > 0) p = p.replace(/^[\\w.]+/, '');\n }\n return p === '';\n });\n if (operationSpec == null) {\n throw new IllegalArgumentError(`Can't find operation spec corresponding to ${path}`);\n }\n\n return this.sendOperationRequest(\n {},\n {\n ...operationSpec,\n path,\n urlParameters: operationSpec.urlParameters?.filter(\n ({ parameterPath }) => parameterPath === '$host',\n ),\n queryParameters: Array.from(new URLSearchParams(query)).map(([key, value]) => ({\n parameterPath: ['options', key],\n mapper: {\n defaultValue: value.toString(),\n serializedName: key,\n type: {\n name: 'String',\n },\n },\n })),\n },\n );\n }\n\n override async sendOperationRequest<T>(\n operationArguments: OperationArguments,\n operationSpec: OperationSpec,\n ): Promise<T> {\n const response = await super.sendOperationRequest(operationArguments, operationSpec);\n if (!isMiddlewareRawPage(response)) return response as T;\n return new MiddlewarePage(response, this) as T;\n }\n}\n"],"mappings":"AACA,SAASA,mBAAmB,EAAEC,4BAA4B,QAAQ,2BAA2B;AAC7F,SACEC,sBAAsB,EACtBC,2BAA2B,EAC3BC,uBAAuB,EACvBC,iBAAiB,EACjBC,qBAAqB,EACrBC,uBAAuB,QAClB,qBAAqB;AAC5B,SACEC,UAAU,IAAIC,aAAa,QAGtB,4BAA4B;AACnC,SAASC,cAAc,QAAQ,iCAAiC;AAChE,SAASC,oBAAoB,EAAEC,aAAa,QAAQ,mBAAmB;AACvE,SAASC,cAAc,EAAEC,mBAAmB,QAAQ,2BAA2B;;AAE/E;AACA;AACA;AACA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C,oBAAoB,CAAC,8CAA8C4B,IAAI,EAAE,CAAC;IACtF;IAEA,OAAO,IAAI,CAACc,oBAAoB,CAC9B,CAAC,CAAC,EACF;MACE,GAAGV,aAAa;MAChBJ,IAAI;MACJe,aAAa,EAAEX,aAAa,CAACW,aAAa,EAAEC,MAAM,CAChD,CAAC;QAAEC;MAAc,CAAC,KAAKA,aAAa,KAAK,OAC3C,CAAC;MACDC,eAAe,EAAEC,KAAK,CAACC,IAAI,CAAC,IAAIC,eAAe,CAAClB,KAAK,CAAC,CAAC,CAACmB,GAAG,CAAC,CAAC,CAACC,GAAG,EAAEC,KAAK,CAAC,MAAM;QAC7EP,aAAa,EAAE,CAAC,SAAS,EAAEM,GAAG,CAAC;QAC/BE,MAAM,EAAE;UACNC,YAAY,EAAEF,KAAK,CAACG,QAAQ,CAAC,CAAC;UAC9BC,cAAc,EAAEL,GAAG;UACnBM,IAAI,EAAE;YACJlC,IAAI,EAAE;UACR;QACF;MACF,CAAC,CAAC;IACJ,CACF,CAAC;EACH;EAEA,MAAemB,oBAAoBA,CACjCgB,kBAAsC,EACtC1B,aAA4B,EAChB;IACZ,MAAM2B,QAAQ,GAAG,MAAM,KAAK,CAACjB,oBAAoB,CAACgB,kBAAkB,EAAE1B,aAAa,CAAC;IACpF,IAAI,CAAC7B,mBAAmB,CAACwD,QAAQ,CAAC,EAAE,OAAOA,QAAQ;IACnD,OAAO,IAAIzD,cAAc,CAACyD,QAAQ,EAAE,IAAI,CAAC;EAC3C;AACF","ignoreList":[]}
|
|
@@ -8,6 +8,9 @@ export declare class MiddlewareSubscriberDisconnected extends MiddlewareSubscrib
|
|
|
8
8
|
readonly closeEvent: WebSocket.CloseEvent;
|
|
9
9
|
constructor(closeEvent: WebSocket.CloseEvent);
|
|
10
10
|
}
|
|
11
|
+
/**
|
|
12
|
+
* @category middleware
|
|
13
|
+
*/
|
|
11
14
|
export default class MiddlewareSubscriber {
|
|
12
15
|
#private;
|
|
13
16
|
readonly url: string;
|
|
@@ -27,6 +27,10 @@ export class MiddlewareSubscriberDisconnected extends MiddlewareSubscriberError
|
|
|
27
27
|
this.name = 'MiddlewareSubscriberDisconnected';
|
|
28
28
|
}
|
|
29
29
|
}
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* @category middleware
|
|
33
|
+
*/
|
|
30
34
|
var _subscriptions = /*#__PURE__*/new WeakMap();
|
|
31
35
|
var _requestQueue = /*#__PURE__*/new WeakMap();
|
|
32
36
|
var _webSocket = /*#__PURE__*/new WeakMap();
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"MiddlewareSubscriber.js","names":["WebSocket","BaseError","UnexpectedTsError","InternalError","Source","MiddlewareSubscriberError","constructor","message","name","MiddlewareSubscriberDisconnected","closeEvent","_subscriptions","WeakMap","_requestQueue","_webSocket","_MiddlewareSubscriber_brand","WeakSet","MiddlewareSubscriber","webSocket","_classPrivateFieldGet","url","_classPrivateMethodInitSpec","_classPrivateFieldInitSpec","reconnect","_assertClassBrand","_disconnect","call","_classPrivateFieldSet","Promise","resolve","Object","assign","onopen","onerror","errorEvent","_emit","undefined","error","onmessage","event","data","_messageHandler","JSON","parse","onclose","all","_classPrivateGetter","_get_targets","map","target","_sendSubscribe","subscribeKeyBlocks","cb","_subscribe","Middleware","subscribeKeyBlocksNode","Node","subscribeKeyBlocksAll","All","subscribeMicroBlocks","subscribeMicroBlocksNode","subscribeMicroBlocksAll","subscribeTransactions","subscribeTransactionsNode","subscribeTransactionsAll","subscribeObject","subscribeObjectNode","subscribeObjectAll","_this","Set","_sendMessage","send","stringify","isSubscribe","payload","includes","op","push","condition","p","e","filter","source","forEach","onlyReset","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.js';\nimport { Encoded } from './utils/encoder.js';\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<readonly [target: string, s: Source, cb: (p?: Object, e?: Error) => void]> =\n [];\n\n readonly #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\n : '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 #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(\n `Expected ${target} to be${isSubscribe ? '' : ' not'} included into ${message}`,\n );\n }\n if (error != null) this.#emit((t) => target === t, undefined, error);\n return;\n }\n this.#emit(\n (target, source) =>\n (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:\n | Encoded.KeyBlockHash\n | Encoded.Channel\n | Encoded.ContractAddress\n | Encoded.OracleAddress\n | Encoded.OracleQueryId\n | Encoded.AccountAddress\n | Encoded.Name\n | `${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:\n | Encoded.KeyBlockHash\n | Encoded.Channel\n | Encoded.ContractAddress\n | Encoded.OracleAddress\n | Encoded.OracleQueryId\n | Encoded.AccountAddress\n | Encoded.Name\n | `${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:\n | Encoded.KeyBlockHash\n | Encoded.Channel\n | Encoded.ContractAddress\n | Encoded.OracleAddress\n | Encoded.OracleQueryId\n | Encoded.AccountAddress\n | Encoded.Name\n | `${string}.chain`,\n cb: (p?: any, e?: Error) => void,\n ): () => void {\n return this.#subscribe(target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2BAAA,MAAI,EAACgC,YAAO,CAAC,CAAC8C,GAAG,CAAC5C,MAAM,CAAC,EAAEzB,iBAAA,CAAAT,2BAAA,MAAI,EAACmC,cAAa,CAAC,CAAAxB,IAAA,CAAnB,IAAI,EAAgB,KAAK,EAAEuB,MAAM;IACjE,IAAIH,mBAAA,CAAA/B,2BAAA,MAAI,EAACgC,YAAO,CAAC,CAAC6C,IAAI,KAAK,CAAC,EAAEpE,iBAAA,CAAAT,2BAAA,MAAI,EAACU,WAAU,CAAC,CAAAC,IAAA,CAAhB,IAAI;EACpC,CAAC;AACH","ignoreList":[]}
|
|
1
|
+
{"version":3,"file":"MiddlewareSubscriber.js","names":["WebSocket","BaseError","UnexpectedTsError","InternalError","Source","MiddlewareSubscriberError","constructor","message","name","MiddlewareSubscriberDisconnected","closeEvent","_subscriptions","WeakMap","_requestQueue","_webSocket","_MiddlewareSubscriber_brand","WeakSet","MiddlewareSubscriber","webSocket","_classPrivateFieldGet","url","_classPrivateMethodInitSpec","_classPrivateFieldInitSpec","reconnect","_assertClassBrand","_disconnect","call","_classPrivateFieldSet","Promise","resolve","Object","assign","onopen","onerror","errorEvent","_emit","undefined","error","onmessage","event","data","_messageHandler","JSON","parse","onclose","all","_classPrivateGetter","_get_targets","map","target","_sendSubscribe","subscribeKeyBlocks","cb","_subscribe","Middleware","subscribeKeyBlocksNode","Node","subscribeKeyBlocksAll","All","subscribeMicroBlocks","subscribeMicroBlocksNode","subscribeMicroBlocksAll","subscribeTransactions","subscribeTransactionsNode","subscribeTransactionsAll","subscribeObject","subscribeObjectNode","subscribeObjectAll","_this","Set","_sendMessage","send","stringify","isSubscribe","payload","includes","op","push","condition","p","e","filter","source","forEach","onlyReset","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.js';\nimport { Encoded } from './utils/encoder.js';\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\n/**\n * @category middleware\n */\nexport default class MiddlewareSubscriber {\n #subscriptions: Array<readonly [target: string, s: Source, cb: (p?: Object, e?: Error) => void]> =\n [];\n\n readonly #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\n : '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 #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(\n `Expected ${target} to be${isSubscribe ? '' : ' not'} included into ${message}`,\n );\n }\n if (error != null) this.#emit((t) => target === t, undefined, error);\n return;\n }\n this.#emit(\n (target, source) =>\n (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:\n | Encoded.KeyBlockHash\n | Encoded.Channel\n | Encoded.ContractAddress\n | Encoded.OracleAddress\n | Encoded.OracleQueryId\n | Encoded.AccountAddress\n | Encoded.Name\n | `${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:\n | Encoded.KeyBlockHash\n | Encoded.Channel\n | Encoded.ContractAddress\n | Encoded.OracleAddress\n | Encoded.OracleQueryId\n | Encoded.AccountAddress\n | Encoded.Name\n | `${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:\n | Encoded.KeyBlockHash\n | Encoded.Channel\n | Encoded.ContractAddress\n | Encoded.OracleAddress\n | Encoded.OracleQueryId\n | Encoded.AccountAddress\n | Encoded.Name\n | `${string}.chain`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AAI,KAAKH,YAAY,CAA9D,CAAC;IACnB,IAAI,CAAC7C,mBAAA,CAAA/B,2BAAA,MAAI,EAACgC,YAAO,CAAC,CAAC8C,GAAG,CAAC5C,MAAM,CAAC,EAAEzB,iBAAA,CAAAT,2BAAA,MAAI,EAACmC,cAAa,CAAC,CAAAxB,IAAA,CAAnB,IAAI,EAAgB,KAAK,EAAEuB,MAAM;IACjE,IAAIH,mBAAA,CAAA/B,2BAAA,MAAI,EAACgC,YAAO,CAAC,CAAC6C,IAAI,KAAK,CAAC,EAAEpE,iBAAA,CAAAT,2BAAA,MAAI,EAACU,WAAU,CAAC,CAAAC,IAAA,CAAhB,IAAI;EACpC,CAAC;AACH","ignoreList":[]}
|
package/es/Node.d.ts
CHANGED
|
@@ -7,12 +7,16 @@ interface NodeInfo {
|
|
|
7
7
|
version: string;
|
|
8
8
|
consensusProtocolVersion: ConsensusProtocolVersion;
|
|
9
9
|
}
|
|
10
|
+
/**
|
|
11
|
+
* @category chain
|
|
12
|
+
*/
|
|
10
13
|
export default class Node extends NodeApi {
|
|
11
14
|
#private;
|
|
12
15
|
/**
|
|
13
16
|
* @param url - Url for node API
|
|
14
17
|
* @param options - Options
|
|
15
|
-
* @param options.ignoreVersion -
|
|
18
|
+
* @param options.ignoreVersion - Print warning instead of throwing exception if node
|
|
19
|
+
* or consensus protocol version is not supported, use with caution
|
|
16
20
|
* @param options.retryCount - Amount of extra requests to do in case of failure
|
|
17
21
|
* @param options.retryOverallDelay - Time in ms to wait between all retries
|
|
18
22
|
*/
|
|
@@ -23,6 +27,7 @@ export default class Node extends NodeApi {
|
|
|
23
27
|
});
|
|
24
28
|
_getCachedStatus(options?: OperationOptions): ReturnType<NodeApi['getStatus']>;
|
|
25
29
|
getStatus(...args: Parameters<NodeApi['getStatus']>): ReturnType<NodeApi['getStatus']>;
|
|
30
|
+
_isHyperchain(): Promise<boolean>;
|
|
26
31
|
/**
|
|
27
32
|
* Returns network ID provided by node.
|
|
28
33
|
* This method won't do extra requests on subsequent calls.
|