From 21d0622f84114b1826fd91dbb791176ec2082ca8 Mon Sep 17 00:00:00 2001 From: Jaco Greeff Date: Mon, 9 Nov 2020 19:41:29 +0100 Subject: [PATCH] Bump common (#2832) * Bump common * Update for new common non-default exports * Don't export createSubmittable * Adjust exports * default export adjustments * Some additional non-default exports --- packages/api-contract/package.json | 2 +- packages/api-contract/src/Abi.spec.ts | 2 +- packages/api-contract/src/Abi.ts | 4 +- .../api-contract/src/MetaRegistry.spec.ts | 2 +- packages/api-contract/src/MetaRegistry.ts | 2 +- packages/api-contract/src/base/Base.ts | 4 +- packages/api-contract/src/base/Blueprint.ts | 8 +- packages/api-contract/src/base/Code.ts | 8 +- packages/api-contract/src/base/Contract.ts | 6 +- packages/api-contract/src/base/index.ts | 6 +- packages/api-contract/src/index.ts | 2 +- .../api-contract/src/promise/Blueprint.ts | 6 +- packages/api-contract/src/promise/Code.ts | 6 +- packages/api-contract/src/promise/Contract.ts | 6 +- packages/api-contract/src/promise/index.ts | 6 +- packages/api-contract/src/rx/Blueprint.ts | 6 +- packages/api-contract/src/rx/Code.ts | 6 +- packages/api-contract/src/rx/Contract.ts | 6 +- packages/api-contract/src/rx/index.ts | 6 +- packages/api-contract/src/types.ts | 2 +- packages/api-derive/package.json | 6 +- packages/api-derive/src/index.spec.ts | 2 +- packages/api-derive/src/index.ts | 2 +- packages/api/package.json | 6 +- packages/api/src/base/Decorate.ts | 8 +- packages/api/src/checkTypes.manual.ts | 4 +- packages/api/src/index.ts | 9 +- packages/api/src/promise/Api.ts | 304 ------------ packages/api/src/promise/Combinator.ts | 2 +- packages/api/src/promise/Combinators.spec.ts | 2 +- .../promise/{Api.spec.ts => index.spec.ts} | 8 +- packages/api/src/promise/index.ts | 303 +++++++++++- packages/api/src/rx/Api.ts | 191 ------- .../api/src/rx/{Api.spec.ts => index.spec.ts} | 6 +- packages/api/src/rx/index.ts | 190 ++++++- packages/api/src/submittable/Result.ts | 2 +- packages/api/src/submittable/createClass.ts | 4 +- .../api/src/submittable/createSubmittable.ts | 4 +- packages/api/src/submittable/index.ts | 4 +- packages/api/src/util/validate.spec.ts | 2 +- packages/metadata/package.json | 6 +- packages/metadata/src/MagicNumber.spec.ts | 2 +- packages/metadata/src/MagicNumber.ts | 2 +- packages/metadata/src/Metadata.spec.ts | 2 +- packages/metadata/src/Metadata.ts | 4 +- packages/metadata/src/MetadataVersioned.ts | 4 +- .../src/decorate/consts/fromMetadata.spec.ts | 4 +- .../src/decorate/consts/fromMetadata.ts | 4 +- .../decorate/extrinsics/fromMetadata.spec.ts | 4 +- .../src/decorate/extrinsics/fromMetadata.ts | 2 +- .../src/decorate/extrinsics/index.spec.ts | 8 +- packages/metadata/src/decorate/index.spec.ts | 2 +- packages/metadata/src/decorate/index.ts | 10 +- .../src/decorate/storage/fromMetadata.spec.ts | 6 +- .../src/decorate/storage/fromMetadata.ts | 4 +- packages/metadata/src/index.ts | 8 +- packages/metadata/src/util/testUtil.ts | 2 +- .../metadata/src/util/toCallsOnly.spec.ts | 2 +- packages/rpc-core/README.md | 2 +- packages/rpc-core/package.json | 4 +- packages/rpc-core/src/cached.spec.ts | 10 +- packages/rpc-core/src/index.spec.ts | 6 +- packages/rpc-core/src/index.ts | 4 +- packages/rpc-core/src/methodSend.spec.ts | 6 +- packages/rpc-core/src/replay.spec.ts | 6 +- packages/rpc-provider/README.md | 2 +- packages/rpc-provider/package.json | 10 +- packages/rpc-provider/src/http/index.spec.ts | 12 +- packages/rpc-provider/src/http/index.ts | 2 +- packages/rpc-provider/src/http/send.spec.ts | 6 +- packages/rpc-provider/src/index.ts | 4 +- packages/rpc-provider/src/mock/index.ts | 6 +- packages/rpc-provider/src/ws/Provider.ts | 468 ------------------ packages/rpc-provider/src/ws/connect.spec.ts | 2 +- packages/rpc-provider/src/ws/index.spec.ts | 2 +- packages/rpc-provider/src/ws/index.ts | 466 ++++++++++++++++- packages/rpc-provider/src/ws/onOpen.spec.ts | 2 +- packages/rpc-provider/src/ws/send.spec.ts | 2 +- packages/rpc-provider/src/ws/state.spec.ts | 2 +- .../rpc-provider/src/ws/subscribe.spec.ts | 2 +- .../rpc-provider/src/ws/unsubscribe.spec.ts | 2 +- packages/typegen/package.json | 2 +- packages/typegen/src/generate/consts.ts | 2 +- packages/typegen/src/generate/query.ts | 2 +- packages/typegen/src/generate/tx.ts | 2 +- packages/typegen/src/metadataMd.ts | 2 +- packages/types-known/package.json | 2 +- packages/types/package.json | 6 +- packages/types/src/codec/Compact.ts | 2 +- packages/types/src/codec/Map.ts | 4 +- packages/types/src/codec/Tuple.spec.ts | 2 +- packages/types/src/codec/Vec.spec.ts | 2 +- .../src/codec/utils/compareArray.spec.ts | 2 +- .../types/src/codec/utils/compareArray.ts | 2 +- .../types/src/codec/utils/compareMap.spec.ts | 2 +- packages/types/src/codec/utils/compareMap.ts | 2 +- packages/types/src/codec/utils/compareSet.ts | 2 +- packages/types/src/codec/utils/decodeU8a.ts | 2 +- packages/types/src/codec/utils/index.ts | 12 +- .../types/src/codec/utils/mapToTypeMap.ts | 4 +- .../src/codec/utils/typeToConstructor.ts | 2 +- packages/types/src/ethereum/AccountId.spec.ts | 2 +- packages/types/src/ethereum/AccountId.ts | 6 +- .../types/src/ethereum/LookupSource.spec.ts | 3 +- packages/types/src/ethereum/LookupSource.ts | 20 +- packages/types/src/ethereum/index.ts | 4 +- .../types/src/extrinsic/Extrinsic.spec.ts | 4 +- .../types/src/extrinsic/SignerPayload.spec.ts | 2 +- .../types/src/extrinsic/v4/Extrinsic.spec.ts | 6 +- packages/types/src/generic/Block.spec.ts | 2 +- packages/types/src/generic/Call.spec.ts | 2 +- packages/types/src/index.spec.ts | 2 +- packages/types/src/index.types.ts | 2 +- .../src/interfaces/system/EventRecord.spec.ts | 2 +- .../types/src/primitive/StorageKey.spec.ts | 2 +- yarn.lock | 139 +++--- 116 files changed, 1245 insertions(+), 1270 deletions(-) delete mode 100644 packages/api/src/promise/Api.ts rename packages/api/src/promise/{Api.spec.ts => index.spec.ts} (96%) delete mode 100644 packages/api/src/rx/Api.ts rename packages/api/src/rx/{Api.spec.ts => index.spec.ts} (93%) delete mode 100644 packages/rpc-provider/src/ws/Provider.ts diff --git a/packages/api-contract/package.json b/packages/api-contract/package.json index 49e85f67da..c1b7285ba8 100644 --- a/packages/api-contract/package.json +++ b/packages/api-contract/package.json @@ -31,7 +31,7 @@ "@babel/runtime": "^7.12.1", "@polkadot/api": "2.6.2-0", "@polkadot/types": "2.6.2-0", - "@polkadot/util": "^4.0.1", + "@polkadot/util": "^4.0.2-5", "bn.js": "^5.1.3", "rxjs": "^6.6.3" } diff --git a/packages/api-contract/src/Abi.spec.ts b/packages/api-contract/src/Abi.spec.ts index 03196cc6f0..51bd212caf 100644 --- a/packages/api-contract/src/Abi.spec.ts +++ b/packages/api-contract/src/Abi.spec.ts @@ -1,7 +1,7 @@ // Copyright 2017-2020 @polkadot/api-contract authors & contributors // SPDX-License-Identifier: Apache-2.0 -import Abi from './Abi'; +import { Abi } from '.'; import * as testContracts from '../test/contracts'; diff --git a/packages/api-contract/src/Abi.ts b/packages/api-contract/src/Abi.ts index 2b0acd9c20..a3a5ecc60a 100644 --- a/packages/api-contract/src/Abi.ts +++ b/packages/api-contract/src/Abi.ts @@ -7,7 +7,7 @@ import { AbiConstructor, AbiEvent, AbiMessage, AbiParam, DecodedEvent, DecodedMe import { assert, assertReturn, compactAddLength, compactStripLength, isNumber, isObject, isString, logger, stringCamelCase, u8aConcat, u8aToHex } from '@polkadot/util'; -import MetaRegistry from './MetaRegistry'; +import { MetaRegistry } from './MetaRegistry'; const l = logger('Abi'); @@ -21,7 +21,7 @@ function findMessage (list: T[], messageOrId: T | string return assertReturn(message, `Attempted to call an invalid contract interface, ${JSON.stringify(messageOrId)}`); } -export default class Abi { +export class Abi { readonly #events: AbiEvent[]; public readonly constructors: AbiConstructor[]; diff --git a/packages/api-contract/src/MetaRegistry.spec.ts b/packages/api-contract/src/MetaRegistry.spec.ts index 609dc49398..edf2c98e74 100644 --- a/packages/api-contract/src/MetaRegistry.spec.ts +++ b/packages/api-contract/src/MetaRegistry.spec.ts @@ -4,7 +4,7 @@ import fs from 'fs'; import path from 'path'; -import Abi from './Abi'; +import { Abi } from '.'; import * as testContracts from '../test/contracts'; diff --git a/packages/api-contract/src/MetaRegistry.ts b/packages/api-contract/src/MetaRegistry.ts index ce4e07b31f..aaf7cc94fe 100644 --- a/packages/api-contract/src/MetaRegistry.ts +++ b/packages/api-contract/src/MetaRegistry.ts @@ -24,7 +24,7 @@ const PRIMITIVE_ALIAS: Record = { const PRIMITIVE_ALWAYS = ['AccountId', 'AccountIndex', 'Address', 'Balance']; -export default class MetaRegistry extends TypeRegistry { +export class MetaRegistry extends TypeRegistry { public readonly metaTypeDefs: TypeDef[] = []; #siTypes: SiType[] = []; diff --git a/packages/api-contract/src/base/Base.ts b/packages/api-contract/src/base/Base.ts index 81e8501e25..aba9789fec 100644 --- a/packages/api-contract/src/base/Base.ts +++ b/packages/api-contract/src/base/Base.ts @@ -7,9 +7,9 @@ import { AnyJson, Registry } from '@polkadot/types/types'; import ApiBase from '@polkadot/api/base'; import { assert } from '@polkadot/util'; -import Abi from '../Abi'; +import { Abi } from '../Abi'; -export default abstract class Base { +export abstract class Base { public readonly abi: Abi; public readonly api: ApiBase; diff --git a/packages/api-contract/src/base/Blueprint.ts b/packages/api-contract/src/base/Blueprint.ts index a01545b18f..f0f6f8151c 100644 --- a/packages/api-contract/src/base/Blueprint.ts +++ b/packages/api-contract/src/base/Blueprint.ts @@ -13,10 +13,10 @@ import { SubmittableResult } from '@polkadot/api'; import ApiBase from '@polkadot/api/base'; import { isUndefined, stringCamelCase } from '@polkadot/util'; -import Abi from '../Abi'; +import { Abi } from '../Abi'; import { applyOnEvent } from '../util'; -import Base from './Base'; -import Contract from './Contract'; +import { Base } from './Base'; +import { Contract } from './Contract'; export class BlueprintSubmittableResult extends SubmittableResult { public readonly contract?: Contract; @@ -28,7 +28,7 @@ export class BlueprintSubmittableResult extends Submit } } -export default class Blueprint extends Base { +export class Blueprint extends Base { public readonly codeHash: Hash; readonly #tx: MapConstructorExec = {}; diff --git a/packages/api-contract/src/base/Code.ts b/packages/api-contract/src/base/Code.ts index ef61241f70..c11f5bc7db 100644 --- a/packages/api-contract/src/base/Code.ts +++ b/packages/api-contract/src/base/Code.ts @@ -10,10 +10,10 @@ import { SubmittableResult } from '@polkadot/api'; import ApiBase from '@polkadot/api/base'; import { compactAddLength, u8aToU8a } from '@polkadot/util'; -import Abi from '../Abi'; +import { Abi } from '../Abi'; import { applyOnEvent } from '../util'; -import Base from './Base'; -import Blueprint from './Blueprint'; +import { Base } from './Base'; +import { Blueprint } from './Blueprint'; export class CodeSubmittableResult extends SubmittableResult { public readonly blueprint?: Blueprint; @@ -25,7 +25,7 @@ export class CodeSubmittableResult extends Submittable } } -export default class Code extends Base { +export class Code extends Base { public readonly code: Uint8Array; constructor (api: ApiBase, abi: AnyJson | Abi, wasm: Uint8Array | string | Buffer, decorateMethod: DecorateMethod) { diff --git a/packages/api-contract/src/base/Contract.ts b/packages/api-contract/src/base/Contract.ts index b8e94cdaa2..8e1fae8685 100644 --- a/packages/api-contract/src/base/Contract.ts +++ b/packages/api-contract/src/base/Contract.ts @@ -14,9 +14,9 @@ import { SubmittableResult } from '@polkadot/api'; import ApiBase from '@polkadot/api/base'; import { assert, bnToBn, isFunction, isUndefined, logger, stringCamelCase } from '@polkadot/util'; -import Abi from '../Abi'; +import { Abi } from '../Abi'; import { applyOnEvent, formatData } from '../util'; -import Base from './Base'; +import { Base } from './Base'; // As per Rust, 5 * GAS_PER_SEC const MAX_CALL_GAS = new BN(5_000_000_000_000).subn(1); @@ -60,7 +60,7 @@ function mapExecResult (registry: Registry, json: Record): Cont return registry.createType('ContractExecResult', { result: { err: { other: 'unknown' } } }); } -export default class Contract extends Base { +export class Contract extends Base { public readonly address: AccountId; readonly #tx: MapMessageExec = {}; diff --git a/packages/api-contract/src/base/index.ts b/packages/api-contract/src/base/index.ts index f9cc67cce6..e831a207f5 100644 --- a/packages/api-contract/src/base/index.ts +++ b/packages/api-contract/src/base/index.ts @@ -1,6 +1,6 @@ // Copyright 2017-2020 @polkadot/api authors & contributors // SPDX-License-Identifier: Apache-2.0 -export { default as Blueprint, BlueprintSubmittableResult } from './Blueprint'; -export { default as Code, CodeSubmittableResult } from './Code'; -export { default as Contract } from './Contract'; +export { Blueprint, BlueprintSubmittableResult } from './Blueprint'; +export { Code, CodeSubmittableResult } from './Code'; +export { Contract } from './Contract'; diff --git a/packages/api-contract/src/index.ts b/packages/api-contract/src/index.ts index 956b802f7a..430349ccf2 100644 --- a/packages/api-contract/src/index.ts +++ b/packages/api-contract/src/index.ts @@ -1,7 +1,7 @@ // Copyright 2017-2020 @polkadot/api-contract authors & contributors // SPDX-License-Identifier: Apache-2.0 -export { default as Abi } from './Abi'; +export { Abi } from './Abi'; export { Blueprint as BlueprintRx, Code as CodeRx, Contract as ContractRx } from './rx'; export { Blueprint as BlueprintPromise, Code as CodePromise, Contract as ContractPromise } from './promise'; diff --git a/packages/api-contract/src/promise/Blueprint.ts b/packages/api-contract/src/promise/Blueprint.ts index 71fe877de3..b7b6d695d8 100644 --- a/packages/api-contract/src/promise/Blueprint.ts +++ b/packages/api-contract/src/promise/Blueprint.ts @@ -7,10 +7,10 @@ import { AnyJson } from '@polkadot/types/types'; import { ApiPromise } from '@polkadot/api'; import { decorateMethod } from '@polkadot/api/promise'; -import Abi from '../Abi'; -import BaseBlueprint from '../base/Blueprint'; +import { Abi } from '../Abi'; +import { Blueprint as BaseBlueprint } from '../base'; -export default class Blueprint extends BaseBlueprint<'promise'> { +export class Blueprint extends BaseBlueprint<'promise'> { constructor (api: ApiPromise, abi: AnyJson | Abi, codeHash: string | Hash) { super(api, abi, codeHash, decorateMethod); } diff --git a/packages/api-contract/src/promise/Code.ts b/packages/api-contract/src/promise/Code.ts index bf50ead297..dd64692964 100644 --- a/packages/api-contract/src/promise/Code.ts +++ b/packages/api-contract/src/promise/Code.ts @@ -5,10 +5,10 @@ import { ApiPromise } from '@polkadot/api'; import { decorateMethod } from '@polkadot/api/promise'; import { AnyJson } from '@polkadot/types/types'; -import Abi from '../Abi'; -import BaseCode from '../base/Code'; +import { Abi } from '../Abi'; +import { Code as BaseCode } from '../base'; -export default class Code extends BaseCode<'promise'> { +export class Code extends BaseCode<'promise'> { constructor (api: ApiPromise, abi: AnyJson | Abi, wasm: Uint8Array | string | Buffer) { super(api, abi, wasm, decorateMethod); } diff --git a/packages/api-contract/src/promise/Contract.ts b/packages/api-contract/src/promise/Contract.ts index fc828bcab8..bf7364fd73 100644 --- a/packages/api-contract/src/promise/Contract.ts +++ b/packages/api-contract/src/promise/Contract.ts @@ -7,10 +7,10 @@ import { AnyJson } from '@polkadot/types/types'; import { ApiPromise } from '@polkadot/api'; import { decorateMethod } from '@polkadot/api/promise'; -import Abi from '../Abi'; -import BaseContract from '../base/Contract'; +import { Abi } from '../Abi'; +import { Contract as BaseContract } from '../base'; -export default class Contract extends BaseContract<'promise'> { +export class Contract extends BaseContract<'promise'> { constructor (api: ApiPromise, abi: AnyJson | Abi, address: string | AccountId) { super(api, abi, address, decorateMethod); } diff --git a/packages/api-contract/src/promise/index.ts b/packages/api-contract/src/promise/index.ts index 63f12f1730..4cfbc6d0d6 100644 --- a/packages/api-contract/src/promise/index.ts +++ b/packages/api-contract/src/promise/index.ts @@ -1,6 +1,6 @@ // Copyright 2017-2020 @polkadot/api-contract authors & contributors // SPDX-License-Identifier: Apache-2.0 -export { default as Blueprint } from './Blueprint'; -export { default as Code } from './Code'; -export { default as Contract } from './Contract'; +export { Blueprint } from './Blueprint'; +export { Code } from './Code'; +export { Contract } from './Contract'; diff --git a/packages/api-contract/src/rx/Blueprint.ts b/packages/api-contract/src/rx/Blueprint.ts index 1a0e6a150e..a443c13d2e 100644 --- a/packages/api-contract/src/rx/Blueprint.ts +++ b/packages/api-contract/src/rx/Blueprint.ts @@ -7,10 +7,10 @@ import { AnyJson } from '@polkadot/types/types'; import { ApiRx } from '@polkadot/api'; import { decorateMethod } from '@polkadot/api/rx'; -import Abi from '../Abi'; -import BaseBlueprint from '../base/Blueprint'; +import { Abi } from '../Abi'; +import { Blueprint as BaseBlueprint } from '../base'; -export default class Blueprint extends BaseBlueprint<'rxjs'> { +export class Blueprint extends BaseBlueprint<'rxjs'> { constructor (api: ApiRx, abi: AnyJson | Abi, codeHash: string | Hash) { super(api, abi, codeHash, decorateMethod); } diff --git a/packages/api-contract/src/rx/Code.ts b/packages/api-contract/src/rx/Code.ts index f2ed6c7089..d18a260ad9 100644 --- a/packages/api-contract/src/rx/Code.ts +++ b/packages/api-contract/src/rx/Code.ts @@ -6,10 +6,10 @@ import { AnyJson } from '@polkadot/types/types'; import { ApiRx } from '@polkadot/api'; import { decorateMethod } from '@polkadot/api/rx'; -import Abi from '../Abi'; -import BaseCode from '../base/Code'; +import { Abi } from '../Abi'; +import { Code as BaseCode } from '../base'; -export default class Code extends BaseCode<'rxjs'> { +export class Code extends BaseCode<'rxjs'> { constructor (api: ApiRx, abi: AnyJson | Abi, wasm: Uint8Array | string | Buffer) { super(api, abi, wasm, decorateMethod); } diff --git a/packages/api-contract/src/rx/Contract.ts b/packages/api-contract/src/rx/Contract.ts index 90f5beebd4..bf959ec0bb 100644 --- a/packages/api-contract/src/rx/Contract.ts +++ b/packages/api-contract/src/rx/Contract.ts @@ -7,10 +7,10 @@ import { AnyJson } from '@polkadot/types/types'; import { ApiRx } from '@polkadot/api'; import { decorateMethod } from '@polkadot/api/rx'; -import Abi from '../Abi'; -import BaseContract from '../base/Contract'; +import { Abi } from '../Abi'; +import { Contract as BaseContract } from '../base'; -export default class Contract extends BaseContract<'rxjs'> { +export class Contract extends BaseContract<'rxjs'> { constructor (api: ApiRx, abi: AnyJson | Abi, address: string | AccountId) { super(api, abi, address, decorateMethod); } diff --git a/packages/api-contract/src/rx/index.ts b/packages/api-contract/src/rx/index.ts index 63f12f1730..4cfbc6d0d6 100644 --- a/packages/api-contract/src/rx/index.ts +++ b/packages/api-contract/src/rx/index.ts @@ -1,6 +1,6 @@ // Copyright 2017-2020 @polkadot/api-contract authors & contributors // SPDX-License-Identifier: Apache-2.0 -export { default as Blueprint } from './Blueprint'; -export { default as Code } from './Code'; -export { default as Contract } from './Contract'; +export { Blueprint } from './Blueprint'; +export { Code } from './Code'; +export { Contract } from './Contract'; diff --git a/packages/api-contract/src/types.ts b/packages/api-contract/src/types.ts index b72f6ee829..5a491c184d 100644 --- a/packages/api-contract/src/types.ts +++ b/packages/api-contract/src/types.ts @@ -8,7 +8,7 @@ import { Codec, CodecArg, TypeDef } from '@polkadot/types/types'; import ApiBase from '@polkadot/api/base'; import { Text, u64 } from '@polkadot/types'; -import Abi from './Abi'; +import { Abi } from '.'; export interface ContractBase { readonly abi: Abi; diff --git a/packages/api-derive/package.json b/packages/api-derive/package.json index ab874044e2..14f5a56ebd 100644 --- a/packages/api-derive/package.json +++ b/packages/api-derive/package.json @@ -33,14 +33,14 @@ "@polkadot/api": "2.6.2-0", "@polkadot/rpc-core": "2.6.2-0", "@polkadot/types": "2.6.2-0", - "@polkadot/util": "^4.0.1", - "@polkadot/util-crypto": "^4.0.1", + "@polkadot/util": "^4.0.2-5", + "@polkadot/util-crypto": "^4.0.2-5", "bn.js": "^5.1.3", "memoizee": "^0.4.14", "rxjs": "^6.6.3" }, "devDependencies": { - "@polkadot/keyring": "^4.0.1", + "@polkadot/keyring": "^4.0.2-5", "@polkadot/rpc-provider": "2.6.2-0" } } diff --git a/packages/api-derive/src/index.spec.ts b/packages/api-derive/src/index.spec.ts index 0609e99f71..63e30a2003 100644 --- a/packages/api-derive/src/index.spec.ts +++ b/packages/api-derive/src/index.spec.ts @@ -6,7 +6,7 @@ /* eslint-disable @typescript-eslint/restrict-template-expressions */ import { Observable, from } from 'rxjs'; -import ApiRx from '@polkadot/api/rx/Api'; +import { ApiRx } from '@polkadot/api/rx'; import MockProvider from '@polkadot/rpc-provider/mock'; import { TypeRegistry } from '@polkadot/types'; diff --git a/packages/api-derive/src/index.ts b/packages/api-derive/src/index.ts index 90d975d531..52c8abc67a 100644 --- a/packages/api-derive/src/index.ts +++ b/packages/api-derive/src/index.ts @@ -92,7 +92,7 @@ function injectFunctions (instanceId: string, api: ApiInterfaceRx, // FIXME The return type of this function should be {...ExactDerive, ...DeriveCustom} // For now we just drop the custom derive typings /** @internal */ -export default function decorateDerive (instanceId: string, api: ApiInterfaceRx, custom: DeriveCustom = {}): ExactDerive { +export function decorateDerive (instanceId: string, api: ApiInterfaceRx, custom: DeriveCustom = {}): ExactDerive { return { ...injectFunctions(instanceId, api, derive), ...injectFunctions(instanceId, api, custom) diff --git a/packages/api/package.json b/packages/api/package.json index f7f30539f3..7967cf7af1 100644 --- a/packages/api/package.json +++ b/packages/api/package.json @@ -30,14 +30,14 @@ "dependencies": { "@babel/runtime": "^7.12.1", "@polkadot/api-derive": "2.6.2-0", - "@polkadot/keyring": "^4.0.1", + "@polkadot/keyring": "^4.0.2-5", "@polkadot/metadata": "2.6.2-0", "@polkadot/rpc-core": "2.6.2-0", "@polkadot/rpc-provider": "2.6.2-0", "@polkadot/types": "2.6.2-0", "@polkadot/types-known": "2.6.2-0", - "@polkadot/util": "^4.0.1", - "@polkadot/util-crypto": "^4.0.1", + "@polkadot/util": "^4.0.2-5", + "@polkadot/util-crypto": "^4.0.2-5", "bn.js": "^5.1.3", "eventemitter3": "^4.0.7", "rxjs": "^6.6.3" diff --git a/packages/api/src/base/Decorate.ts b/packages/api/src/base/Decorate.ts index d52a11018d..452971cd8d 100644 --- a/packages/api/src/base/Decorate.ts +++ b/packages/api/src/base/Decorate.ts @@ -11,12 +11,12 @@ import { ApiInterfaceRx, ApiOptions, ApiTypes, DecorateMethod, DecoratedRpc, Dec import BN from 'bn.js'; import { BehaviorSubject, Observable, combineLatest, of } from 'rxjs'; import { map, switchMap, take, tap, toArray } from 'rxjs/operators'; -import decorateDerive, { ExactDerive } from '@polkadot/api-derive'; +import { ExactDerive, decorateDerive } from '@polkadot/api-derive'; import { memo } from '@polkadot/api-derive/util'; -import { expandMetadata } from '@polkadot/metadata'; -import RpcCore from '@polkadot/rpc-core'; +import { Metadata, expandMetadata } from '@polkadot/metadata'; +import { RpcCore } from '@polkadot/rpc-core'; import { WsProvider } from '@polkadot/rpc-provider'; -import { Metadata, Option, Raw, Text, TypeRegistry, u64 } from '@polkadot/types'; +import { Option, Raw, Text, TypeRegistry, u64 } from '@polkadot/types'; import { DEFAULT_VERSION as EXTRINSIC_DEFAULT_VERSION } from '@polkadot/types/extrinsic/constants'; import StorageKey, { StorageEntry, unwrapStorageType } from '@polkadot/types/primitive/StorageKey'; import { assert, compactStripLength, logger, u8aToHex } from '@polkadot/util'; diff --git a/packages/api/src/checkTypes.manual.ts b/packages/api/src/checkTypes.manual.ts index e3493010c5..2c46f4dfd8 100644 --- a/packages/api/src/checkTypes.manual.ts +++ b/packages/api/src/checkTypes.manual.ts @@ -8,7 +8,7 @@ import { IExtrinsic, IMethod } from '@polkadot/types/types'; import { ApiPromise } from '@polkadot/api'; import { HeaderExtended } from '@polkadot/api-derive'; -import testKeyring, { TestKeyringMap } from '@polkadot/keyring/testingPairs'; +import { TestKeyringMap, createTestPairs } from '@polkadot/keyring/testingPairs'; import { createTypeUnsafe, TypeRegistry } from '@polkadot/types'; import { SubmittableResult } from './'; @@ -183,7 +183,7 @@ async function tx (api: ApiPromise, keyring: TestKeyringMap): Promise { async function main (): Promise { const api = await ApiPromise.create(); - const keyring = testKeyring(); + const keyring = createTestPairs(); // eslint-disable-next-line @typescript-eslint/no-floating-promises Promise.all([ diff --git a/packages/api/src/index.ts b/packages/api/src/index.ts index f9f6d2d7dc..9f57ff1c9a 100644 --- a/packages/api/src/index.ts +++ b/packages/api/src/index.ts @@ -8,8 +8,9 @@ import { detectPackage } from '@polkadot/util'; detectPackage(require('./package.json'), typeof __dirname !== 'undefined' && __dirname); export { Keyring } from '@polkadot/keyring'; -export { default as WsProvider } from '@polkadot/rpc-provider/ws'; +export { WsProvider } from '@polkadot/rpc-provider/ws'; -export { default as ApiPromise } from './promise'; -export { default as ApiRx } from './rx'; -export * from './submittable'; +export { ApiPromise } from './promise'; +export { ApiRx } from './rx'; + +export { SubmittableResult } from './submittable'; diff --git a/packages/api/src/promise/Api.ts b/packages/api/src/promise/Api.ts deleted file mode 100644 index 1ab6f54c36..0000000000 --- a/packages/api/src/promise/Api.ts +++ /dev/null @@ -1,304 +0,0 @@ -// Copyright 2017-2020 @polkadot/api authors & contributors -// SPDX-License-Identifier: Apache-2.0 - -import { Callback, Codec } from '@polkadot/types/types'; -import { ApiOptions, DecorateFn, DecorateMethodOptions, ObsInnerType, StorageEntryPromiseOverloads, UnsubscribePromise, VoidFn } from '../types'; - -import { EMPTY, Observable, Subscription } from 'rxjs'; -import { catchError, tap } from 'rxjs/operators'; -import { isFunction, assert } from '@polkadot/util'; - -import ApiBase from '../base'; -import Combinator, { CombinatorCallback, CombinatorFunction } from './Combinator'; - -interface Tracker { - reject: (value: Error) => Observable; - resolve: (value: T) => void; -} - -// extract the arguments and callback params from a value array possibly containing a callback -function extractArgs (args: unknown[], needsCallback: boolean): [unknown[], Callback | undefined] { - let callback: Callback | undefined; - const actualArgs = args.slice(); - - // If the last arg is a function, we pop it, put it into callback. - // actualArgs will then hold the actual arguments to be passed to `method` - if (args.length && isFunction(args[args.length - 1])) { - callback = actualArgs.pop() as Callback; - } - - // When we need a subscription, ensure that a valid callback is actually passed - assert(!needsCallback || isFunction(callback), 'Expected a callback to be passed with subscriptions'); - - return [actualArgs, callback]; -} - -// a Promise completion tracker, wrapping an isComplete variable that ensures the promise only resolves once -function promiseTracker (resolve: (value: T) => void, reject: (value: Error) => void): Tracker { - let isCompleted = false; - - return { - reject: (error: Error): Observable => { - if (!isCompleted) { - isCompleted = true; - - reject(error); - } - - return EMPTY; - }, - resolve: (value: T): void => { - if (!isCompleted) { - isCompleted = true; - - resolve(value); - } - } - }; -} - -// Decorate a call for a single-shot result - retrieve and then immediate unsubscribe -function decorateCall>>> (method: Method, actualArgs: unknown[]): Promise>> { - return new Promise((resolve, reject): void => { - // single result tracker - either reject with Error or resolve with Codec result - const tracker = promiseTracker(resolve, reject); - - // encoding errors reject immediately, any result unsubscribes and resolves - const subscription: Subscription = method(...actualArgs).pipe( - catchError((error) => tracker.reject(error)) - ).subscribe((result): void => { - tracker.resolve(result); - setTimeout(() => subscription.unsubscribe(), 0); - }); - }); -} - -// Decorate a subscription where we have a result callback specified -function decorateSubscribe>>> (method: Method, actualArgs: unknown[], resultCb: Callback): UnsubscribePromise { - return new Promise((resolve, reject): void => { - // either reject with error or resolve with unsubscribe callback - const tracker = promiseTracker(resolve, reject); - - // errors reject immediately, the first result resolves with an unsubscribe promise, all results via callback - const subscription: Subscription = method(...actualArgs).pipe( - catchError((error) => tracker.reject(error)), - tap(() => tracker.resolve(() => subscription.unsubscribe())) - ).subscribe((result): void => { - // queue result (back of queue to clear current) - setTimeout(() => resultCb(result) as void, 0); - }); - }); -} - -/** - * @description Decorate method for ApiPromise, where the results are converted to the Promise equivalent - */ -export function decorateMethod>>> (method: Method, options?: DecorateMethodOptions): StorageEntryPromiseOverloads { - const needsCallback = options && options.methodName && options.methodName.includes('subscribe'); - - return function (...args: unknown[]): Promise>> | UnsubscribePromise { - const [actualArgs, resultCb] = extractArgs(args, !!needsCallback); - - return resultCb - ? decorateSubscribe(method, actualArgs, resultCb) - : decorateCall((options?.overrideNoSub as Method) || method, actualArgs); - } as StorageEntryPromiseOverloads; -} - -/** - * # @polkadot/api/promise - * - * ## Overview - * - * @name ApiPromise - * @description - * ApiPromise is a standard JavaScript wrapper around the RPC and interfaces on the Polkadot network. As a full Promise-based, all interface calls return Promises, including the static `.create(...)`. Subscription calls utilise `(value) => {}` callbacks to pass through the latest values. - * - * The API is well suited to real-time applications where either the single-shot state is needed or use is to be made of the subscription-based features of Polkadot (and Substrate) clients. - * - * @see [[ApiRx]] - * - * ## Usage - * - * Making rpc calls - - *
- * - * ```javascript - * import ApiPromise from '@polkadot/api/promise'; - * - * // initialise via static create - * const api = await ApiPromise.create(); - * - * // make a subscription to the network head - * api.rpc.chain.subscribeNewHeads((header) => { - * console.log(`Chain is at #${header.number}`); - * }); - * ``` - *
- * - * Subscribing to chain state - - *
- * - * ```javascript - * import { ApiPromise, WsProvider } from '@polkadot/api'; - * - * // initialise a provider with a specific endpoint - * const provider = new WsProvider('wss://example.com:9944') - * - * // initialise via isReady & new with specific provider - * const api = await new ApiPromise({ provider }).isReady; - * - * // retrieve the block target time - * const blockPeriod = await api.query.timestamp.blockPeriod().toNumber(); - * let last = 0; - * - * // subscribe to the current block timestamp, updates automatically (callback provided) - * api.query.timestamp.now((timestamp) => { - * const elapsed = last - * ? `, ${timestamp.toNumber() - last}s since last` - * : ''; - * - * last = timestamp.toNumber(); - * console.log(`timestamp ${timestamp}${elapsed} (${blockPeriod}s target)`); - * }); - * ``` - *
- * - * Submitting a transaction - - *
- * - * ```javascript - * import ApiPromise from '@polkadot/api/promise'; - * - * ApiPromise.create().then((api) => { - * const [nonce] = await api.query.system.account(keyring.alice.address); - * - * api.tx.balances - * // create transfer - * transfer(keyring.bob.address, 12345) - * // sign the transcation - * .sign(keyring.alice, { nonce }) - * // send the transaction (optional status callback) - * .send((status) => { - * console.log(`current status ${status.type}`); - * }) - * // retrieve the submitted extrinsic hash - * .then((hash) => { - * console.log(`submitted with hash ${hash}`); - * }); - * }); - * ``` - */ -export default class ApiPromise extends ApiBase<'promise'> { - #isReadyPromise: Promise; - #isReadyOrErrorPromise: Promise; - - /** - * @description Creates an ApiPromise instance using the supplied provider. Returns an Promise containing the actual Api instance. - * @param options options that is passed to the class contructor. Can be either [[ApiOptions]] or a - * provider (see the constructor arguments) - * @example - *
- * - * ```javascript - * import Api from '@polkadot/api/promise'; - * - * Api.create().then(async (api) => { - * const timestamp = await api.query.timestamp.now(); - * - * console.log(`lastest block timestamp ${timestamp}`); - * }); - * ``` - */ - public static create (options?: ApiOptions): Promise { - return new ApiPromise(options).isReady; - } - - /** - * @description Creates an instance of the ApiPromise class - * @param options Options to create an instance. This can be either [[ApiOptions]] or - * an [[WsProvider]]. - * @example - *
- * - * ```javascript - * import Api from '@polkadot/api/promise'; - * - * new Api().isReady.then((api) => { - * api.rpc.subscribeNewHeads((header) => { - * console.log(`new block #${header.number.toNumber()}`); - * }); - * }); - * ``` - */ - constructor (options?: ApiOptions) { - super(options, 'promise', decorateMethod); - - this.#isReadyPromise = new Promise((resolve): void => { - super.once('ready', (): void => { - resolve(this); - }); - }); - - this.#isReadyOrErrorPromise = new Promise((resolve, reject): void => { - super.once('ready', (): void => { - resolve(this); - }); - super.once('error', (e): void => { - reject(e); - }); - }); - } - - /** - * @description Promise that resolves the first time we are connected and loaded - */ - public get isReady (): Promise { - return this.#isReadyPromise; - } - - /** - * @description Promise that resolves if we can connect, or reject if there is an error - */ - public get isReadyOrError (): Promise { - return this.#isReadyOrErrorPromise; - } - - /** - * @description Returns a clone of this ApiPromise instance (new underlying provider connection) - */ - public clone (): ApiPromise { - return new ApiPromise({ - ...this._options, - source: this - }); - } - - /** - * @description Creates a combinator that can be used to combine the latest results from multiple subscriptions - * @param fns An array of function to combine, each in the form of `(cb: (value: void)) => void` - * @param callback A callback that will return an Array of all the values this combinator has been applied to - * @example - *
- * - * ```javascript - * const address = '5DTestUPts3kjeXSTMyerHihn1uwMfLj8vU8sqF7qYrFacT7'; - * - * // combines values from balance & nonce as it updates - * api.combineLatest([ - * api.rpc.chain.subscribeNewHeads, - * (cb) => api.query.system.account(address, cb) - * ], ([head, [balance, nonce]]) => { - * console.log(`#${head.number}: You have ${balance.free} units, with ${nonce} transactions sent`); - * }); - * ``` - */ - // eslint-disable-next-line @typescript-eslint/require-await - public async combineLatest (fns: (CombinatorFunction | [CombinatorFunction, ...any[]])[], callback: CombinatorCallback): UnsubscribePromise { - const combinator = new Combinator(fns, callback); - - return (): void => { - combinator.unsubscribe(); - }; - } -} diff --git a/packages/api/src/promise/Combinator.ts b/packages/api/src/promise/Combinator.ts index 8410cd33bd..a22b6a0845 100644 --- a/packages/api/src/promise/Combinator.ts +++ b/packages/api/src/promise/Combinator.ts @@ -12,7 +12,7 @@ export interface CombinatorFunction { (cb: Callback): UnsubscribePromise; } -export default class Combinator { +export class Combinator { #allHasFired = false; #callback: CombinatorCallback; diff --git a/packages/api/src/promise/Combinators.spec.ts b/packages/api/src/promise/Combinators.spec.ts index 59f6e538af..2d35593b91 100644 --- a/packages/api/src/promise/Combinators.spec.ts +++ b/packages/api/src/promise/Combinators.spec.ts @@ -2,7 +2,7 @@ // SPDX-License-Identifier: Apache-2.0 import { UnsubscribePromise } from '../types'; -import Combinator from './Combinator'; +import { Combinator } from './Combinator'; describe('Combinator', (): void => { let fns: ((value: any) => void)[] = []; diff --git a/packages/api/src/promise/Api.spec.ts b/packages/api/src/promise/index.spec.ts similarity index 96% rename from packages/api/src/promise/Api.spec.ts rename to packages/api/src/promise/index.spec.ts index 1403d9bcac..9a322c4e10 100644 --- a/packages/api/src/promise/Api.spec.ts +++ b/packages/api/src/promise/index.spec.ts @@ -3,20 +3,20 @@ import { ApiOptions, SubmittableExtrinsic } from '../types'; -import createPair from '@polkadot/keyring/pair'; -import testKeyring from '@polkadot/keyring/testing'; +import { createPair } from '@polkadot/keyring/pair'; +import { createTestKeyring } from '@polkadot/keyring/testing'; import Mock from '@polkadot/rpc-provider/mock/index'; import { TypeRegistry } from '@polkadot/types'; import { hexToU8a } from '@polkadot/util'; import { SingleAccountSigner } from '../../test/util'; -import ApiPromise from './Api'; +import { ApiPromise } from '.'; const TRANSFER_SIG = '0x7a10e5ed9a14284eca7bea53f81631981dddda5a3d2dee973b136475947264801465726e4829ae3994d9058df638d959d4e043c7f1924299546790dda1dea20a'; describe('ApiPromise', (): void => { const registry = new TypeRegistry(); - const keyring = testKeyring({ type: 'ed25519' }); + const keyring = createTestKeyring({ type: 'ed25519' }); const aliceEd = keyring.addPair( // eslint-disable-next-line @typescript-eslint/unbound-method createPair({ toSS58: keyring.encodeAddress, type: 'ed25519' }, { diff --git a/packages/api/src/promise/index.ts b/packages/api/src/promise/index.ts index 37bc831321..10b00b73d7 100644 --- a/packages/api/src/promise/index.ts +++ b/packages/api/src/promise/index.ts @@ -1,7 +1,304 @@ // Copyright 2017-2020 @polkadot/api authors & contributors // SPDX-License-Identifier: Apache-2.0 -import ApiPromise, { decorateMethod } from './Api'; +import { Callback, Codec } from '@polkadot/types/types'; +import { ApiOptions, DecorateFn, DecorateMethodOptions, ObsInnerType, StorageEntryPromiseOverloads, UnsubscribePromise, VoidFn } from '../types'; -export default ApiPromise; -export { decorateMethod }; +import { EMPTY, Observable, Subscription } from 'rxjs'; +import { catchError, tap } from 'rxjs/operators'; +import { isFunction, assert } from '@polkadot/util'; + +import ApiBase from '../base'; +import { Combinator, CombinatorCallback, CombinatorFunction } from './Combinator'; + +interface Tracker { + reject: (value: Error) => Observable; + resolve: (value: T) => void; +} + +// extract the arguments and callback params from a value array possibly containing a callback +function extractArgs (args: unknown[], needsCallback: boolean): [unknown[], Callback | undefined] { + let callback: Callback | undefined; + const actualArgs = args.slice(); + + // If the last arg is a function, we pop it, put it into callback. + // actualArgs will then hold the actual arguments to be passed to `method` + if (args.length && isFunction(args[args.length - 1])) { + callback = actualArgs.pop() as Callback; + } + + // When we need a subscription, ensure that a valid callback is actually passed + assert(!needsCallback || isFunction(callback), 'Expected a callback to be passed with subscriptions'); + + return [actualArgs, callback]; +} + +// a Promise completion tracker, wrapping an isComplete variable that ensures the promise only resolves once +function promiseTracker (resolve: (value: T) => void, reject: (value: Error) => void): Tracker { + let isCompleted = false; + + return { + reject: (error: Error): Observable => { + if (!isCompleted) { + isCompleted = true; + + reject(error); + } + + return EMPTY; + }, + resolve: (value: T): void => { + if (!isCompleted) { + isCompleted = true; + + resolve(value); + } + } + }; +} + +// Decorate a call for a single-shot result - retrieve and then immediate unsubscribe +function decorateCall>>> (method: Method, actualArgs: unknown[]): Promise>> { + return new Promise((resolve, reject): void => { + // single result tracker - either reject with Error or resolve with Codec result + const tracker = promiseTracker(resolve, reject); + + // encoding errors reject immediately, any result unsubscribes and resolves + const subscription: Subscription = method(...actualArgs).pipe( + catchError((error) => tracker.reject(error)) + ).subscribe((result): void => { + tracker.resolve(result); + setTimeout(() => subscription.unsubscribe(), 0); + }); + }); +} + +// Decorate a subscription where we have a result callback specified +function decorateSubscribe>>> (method: Method, actualArgs: unknown[], resultCb: Callback): UnsubscribePromise { + return new Promise((resolve, reject): void => { + // either reject with error or resolve with unsubscribe callback + const tracker = promiseTracker(resolve, reject); + + // errors reject immediately, the first result resolves with an unsubscribe promise, all results via callback + const subscription: Subscription = method(...actualArgs).pipe( + catchError((error) => tracker.reject(error)), + tap(() => tracker.resolve(() => subscription.unsubscribe())) + ).subscribe((result): void => { + // queue result (back of queue to clear current) + setTimeout(() => resultCb(result) as void, 0); + }); + }); +} + +/** + * @description Decorate method for ApiPromise, where the results are converted to the Promise equivalent + */ +export function decorateMethod>>> (method: Method, options?: DecorateMethodOptions): StorageEntryPromiseOverloads { + const needsCallback = options && options.methodName && options.methodName.includes('subscribe'); + + return function (...args: unknown[]): Promise>> | UnsubscribePromise { + const [actualArgs, resultCb] = extractArgs(args, !!needsCallback); + + return resultCb + ? decorateSubscribe(method, actualArgs, resultCb) + : decorateCall((options?.overrideNoSub as Method) || method, actualArgs); + } as StorageEntryPromiseOverloads; +} + +/** + * # @polkadot/api/promise + * + * ## Overview + * + * @name ApiPromise + * @description + * ApiPromise is a standard JavaScript wrapper around the RPC and interfaces on the Polkadot network. As a full Promise-based, all interface calls return Promises, including the static `.create(...)`. Subscription calls utilise `(value) => {}` callbacks to pass through the latest values. + * + * The API is well suited to real-time applications where either the single-shot state is needed or use is to be made of the subscription-based features of Polkadot (and Substrate) clients. + * + * @see [[ApiRx]] + * + * ## Usage + * + * Making rpc calls - + *
+ * + * ```javascript + * import ApiPromise from '@polkadot/api/promise'; + * + * // initialise via static create + * const api = await ApiPromise.create(); + * + * // make a subscription to the network head + * api.rpc.chain.subscribeNewHeads((header) => { + * console.log(`Chain is at #${header.number}`); + * }); + * ``` + *
+ * + * Subscribing to chain state - + *
+ * + * ```javascript + * import { ApiPromise, WsProvider } from '@polkadot/api'; + * + * // initialise a provider with a specific endpoint + * const provider = new WsProvider('wss://example.com:9944') + * + * // initialise via isReady & new with specific provider + * const api = await new ApiPromise({ provider }).isReady; + * + * // retrieve the block target time + * const blockPeriod = await api.query.timestamp.blockPeriod().toNumber(); + * let last = 0; + * + * // subscribe to the current block timestamp, updates automatically (callback provided) + * api.query.timestamp.now((timestamp) => { + * const elapsed = last + * ? `, ${timestamp.toNumber() - last}s since last` + * : ''; + * + * last = timestamp.toNumber(); + * console.log(`timestamp ${timestamp}${elapsed} (${blockPeriod}s target)`); + * }); + * ``` + *
+ * + * Submitting a transaction - + *
+ * + * ```javascript + * import ApiPromise from '@polkadot/api/promise'; + * + * ApiPromise.create().then((api) => { + * const [nonce] = await api.query.system.account(keyring.alice.address); + * + * api.tx.balances + * // create transfer + * transfer(keyring.bob.address, 12345) + * // sign the transcation + * .sign(keyring.alice, { nonce }) + * // send the transaction (optional status callback) + * .send((status) => { + * console.log(`current status ${status.type}`); + * }) + * // retrieve the submitted extrinsic hash + * .then((hash) => { + * console.log(`submitted with hash ${hash}`); + * }); + * }); + * ``` + */ +export class ApiPromise extends ApiBase<'promise'> { + #isReadyPromise: Promise; + #isReadyOrErrorPromise: Promise; + + /** + * @description Creates an ApiPromise instance using the supplied provider. Returns an Promise containing the actual Api instance. + * @param options options that is passed to the class contructor. Can be either [[ApiOptions]] or a + * provider (see the constructor arguments) + * @example + *
+ * + * ```javascript + * import Api from '@polkadot/api/promise'; + * + * Api.create().then(async (api) => { + * const timestamp = await api.query.timestamp.now(); + * + * console.log(`lastest block timestamp ${timestamp}`); + * }); + * ``` + */ + public static create (options?: ApiOptions): Promise { + return new ApiPromise(options).isReady; + } + + /** + * @description Creates an instance of the ApiPromise class + * @param options Options to create an instance. This can be either [[ApiOptions]] or + * an [[WsProvider]]. + * @example + *
+ * + * ```javascript + * import Api from '@polkadot/api/promise'; + * + * new Api().isReady.then((api) => { + * api.rpc.subscribeNewHeads((header) => { + * console.log(`new block #${header.number.toNumber()}`); + * }); + * }); + * ``` + */ + constructor (options?: ApiOptions) { + super(options, 'promise', decorateMethod); + + this.#isReadyPromise = new Promise((resolve): void => { + super.once('ready', (): void => { + resolve(this); + }); + }); + + this.#isReadyOrErrorPromise = new Promise((resolve, reject): void => { + super.once('ready', (): void => { + resolve(this); + }); + super.once('error', (e): void => { + reject(e); + }); + }); + } + + /** + * @description Promise that resolves the first time we are connected and loaded + */ + public get isReady (): Promise { + return this.#isReadyPromise; + } + + /** + * @description Promise that resolves if we can connect, or reject if there is an error + */ + public get isReadyOrError (): Promise { + return this.#isReadyOrErrorPromise; + } + + /** + * @description Returns a clone of this ApiPromise instance (new underlying provider connection) + */ + public clone (): ApiPromise { + return new ApiPromise({ + ...this._options, + source: this + }); + } + + /** + * @description Creates a combinator that can be used to combine the latest results from multiple subscriptions + * @param fns An array of function to combine, each in the form of `(cb: (value: void)) => void` + * @param callback A callback that will return an Array of all the values this combinator has been applied to + * @example + *
+ * + * ```javascript + * const address = '5DTestUPts3kjeXSTMyerHihn1uwMfLj8vU8sqF7qYrFacT7'; + * + * // combines values from balance & nonce as it updates + * api.combineLatest([ + * api.rpc.chain.subscribeNewHeads, + * (cb) => api.query.system.account(address, cb) + * ], ([head, [balance, nonce]]) => { + * console.log(`#${head.number}: You have ${balance.free} units, with ${nonce} transactions sent`); + * }); + * ``` + */ + // eslint-disable-next-line @typescript-eslint/require-await + public async combineLatest (fns: (CombinatorFunction | [CombinatorFunction, ...any[]])[], callback: CombinatorCallback): UnsubscribePromise { + const combinator = new Combinator(fns, callback); + + return (): void => { + combinator.unsubscribe(); + }; + } +} diff --git a/packages/api/src/rx/Api.ts b/packages/api/src/rx/Api.ts deleted file mode 100644 index e93bc7b2f3..0000000000 --- a/packages/api/src/rx/Api.ts +++ /dev/null @@ -1,191 +0,0 @@ -// Copyright 2017-2020 @polkadot/api authors & contributors -// SPDX-License-Identifier: Apache-2.0 - -import { Codec } from '@polkadot/types/types'; -import { ApiOptions, DecorateFn } from '../types'; - -import { from, Observable } from 'rxjs'; - -import ApiBase from '../base'; - -export function decorateMethod > (method: Method): Method { - return method; -} - -/** - * # @polkadot/api/rx - * - * ## Overview - * - * @name ApiRx - * - * @description - * ApiRx is a powerful RxJS Observable wrapper around the RPC and interfaces on the Polkadot network. As a full Observable API, all interface calls return RxJS Observables, including the static `.create(...)`. In the same fashion and subscription-based methods return long-running Observables that update with the latest values. - * - * The API is well suited to real-time applications where the latest state is needed, unlocking the subscription-based features of Polkadot (and Substrate) clients. Some familiarity with RxJS is a requirement to use the API, however just understanding `.subscribe` and `.pipe` on Observables will unlock full-scale use thereof. - * - * @see [[ApiPromise]] - * - * ## Usage - * - * Making rpc calls - - *
- * - * ```javascript - * import ApiRx from '@polkadot/api/rx'; - * - * // initialize via Promise & static create - * const api = await ApiRx.create().toPromise(); - * - * // make a call to retrieve the current network head - * api.rpc.chain.subscribeNewHeads().subscribe((header) => { - * console.log(`Chain is at #${header.number}`); - * }); - * ``` - *
- * - * Subscribing to chain state - - *
- * - * ```javascript - * import { combineLatest } from 'rxjs'; - * import { pairwise, switchMap } from 'rxjs/operators'; - * import { ApiRx, WsProvider } from '@polkadot/api'; - * - * - * // initialize a provider with a specific endpoint - * const provider = new WsProvider('wss://example.com:9944') - * - * // initialize via isReady & new with specific provider - * new ApiRx({ provider }) - * .isReady - * .pipe( - * switchMap((api) => - * combineLatest([ - * api.query.timestamp.blockPeriod(), - * api.query.timestamp.now().pipe(pairwise()) - * ]) - * ) - * ) - * .subscribe(([blockPeriod, timestamp]) => { - * const elapsed = timestamp[1].toNumber() - timestamp[0].toNumber(); - * console.log(`timestamp ${timestamp[1]} \nelapsed ${elapsed} \n(${blockPeriod}s target)`); - * }); - * ``` - *
- * - * Submitting a transaction - - *
- * - * ```javascript - * import { first, switchMap } from 'rxjs/operators'; - * import ApiRx from '@polkadot/api/rx'; - * - * // import the test keyring (already has dev keys for Alice, Bob, Charlie, Eve & Ferdie) - * import testingPairs from '@polkadot/keyring/testingPairs'; - * const keyring = testingPairs(); - * - * // get api via Promise - * const api = await ApiRx.create().toPromise(); - * - * // retrieve nonce for the account - * api.query.system - * .account(keyring.alice.address) - * .pipe( - * first(), - * // pipe nonce into transfer - * switchMap(([nonce]) => - * api.tx.balances - * // create transfer - * .transfer(keyring.bob.address, 12345) - * // sign the transaction - * .sign(keyring.alice, { nonce }) - * // send the transaction - * .send() - * ) - * ) - * // subscribe to overall result - * .subscribe(({ status }) => { - * if (status.isInBlock) { - * console.log('Completed at block hash', status.asFinalized.toHex()); - * } - * }); - * ``` - */ -export default class ApiRx extends ApiBase<'rxjs'> { - #isReadyRx: Observable; - - /** - * @description Creates an ApiRx instance using the supplied provider. Returns an Observable containing the actual Api instance. - * @param options options that is passed to the class constructor. Can be either [[ApiOptions]] or [[WsProvider]] - * @example - *
- * - * ```javascript - * import { switchMap } from 'rxjs/operators'; - * import Api from '@polkadot/api/rx'; - * - * Api.create() - * .pipe( - * switchMap((api) => - * api.rpc.chain.subscribeNewHeads() - * )) - * .subscribe((header) => { - * console.log(`new block #${header.number.toNumber()}`); - * }); - * ``` - */ - public static create (options?: ApiOptions): Observable { - return new ApiRx(options).isReady; - } - - /** - * @description Create an instance of the ApiRx class - * @param options Options to create an instance. Can be either [[ApiOptions]] or [[WsProvider]] - * @example - *
- * - * ```javascript - * import { switchMap } from 'rxjs/operators'; - * import Api from '@polkadot/api/rx'; - * - * new Api().isReady - * .pipe( - * switchMap((api) => - * api.rpc.chain.subscribeNewHeads() - * )) - * .subscribe((header) => { - * console.log(`new block #${header.number.toNumber()}`); - * }); - * ``` - */ - constructor (options?: ApiOptions) { - super(options, 'rxjs', decorateMethod); - - this.#isReadyRx = from>( - // You can create an observable from an event, however my mind groks this form better - new Promise((resolve): void => { - super.on('ready', (): void => { - resolve(this); - }); - }) - ); - } - - /** - * @description Observable that returns the first time we are connected and loaded - */ - public get isReady (): Observable { - return this.#isReadyRx; - } - - /** - * @description Returns a clone of this ApiRx instance (new underlying provider connection) - */ - public clone (): ApiRx { - return new ApiRx({ - ...this._options, - source: this - }); - } -} diff --git a/packages/api/src/rx/Api.spec.ts b/packages/api/src/rx/index.spec.ts similarity index 93% rename from packages/api/src/rx/Api.spec.ts rename to packages/api/src/rx/index.spec.ts index dc7438a843..528a415d9e 100644 --- a/packages/api/src/rx/Api.spec.ts +++ b/packages/api/src/rx/index.spec.ts @@ -5,16 +5,16 @@ import { SubmittableExtrinsic } from '../submittable/types'; import { Observable } from 'rxjs'; import { map, switchMap } from 'rxjs/operators'; -import testingPairs from '@polkadot/keyring/testingPairs'; +import { createTestPairs } from '@polkadot/keyring/testingPairs'; import Mock from '@polkadot/rpc-provider/mock/index'; import { TypeRegistry } from '@polkadot/types'; import { SingleAccountSigner } from '../../test/util'; -import ApiRx from './Api'; +import { ApiRx } from '.'; describe('ApiRx', (): void => { const registry = new TypeRegistry(); - const keyring = testingPairs({ type: 'ed25519' }); + const keyring = createTestPairs({ type: 'ed25519' }); let provider: Mock; beforeEach((): void => { diff --git a/packages/api/src/rx/index.ts b/packages/api/src/rx/index.ts index e6fc82b83c..0c88c17138 100644 --- a/packages/api/src/rx/index.ts +++ b/packages/api/src/rx/index.ts @@ -1,7 +1,191 @@ // Copyright 2017-2020 @polkadot/api authors & contributors // SPDX-License-Identifier: Apache-2.0 -import ApiRx, { decorateMethod } from './Api'; +import { Codec } from '@polkadot/types/types'; +import { ApiOptions, DecorateFn } from '../types'; -export default ApiRx; -export { decorateMethod }; +import { from, Observable } from 'rxjs'; + +import ApiBase from '../base'; + +export function decorateMethod > (method: Method): Method { + return method; +} + +/** + * # @polkadot/api/rx + * + * ## Overview + * + * @name ApiRx + * + * @description + * ApiRx is a powerful RxJS Observable wrapper around the RPC and interfaces on the Polkadot network. As a full Observable API, all interface calls return RxJS Observables, including the static `.create(...)`. In the same fashion and subscription-based methods return long-running Observables that update with the latest values. + * + * The API is well suited to real-time applications where the latest state is needed, unlocking the subscription-based features of Polkadot (and Substrate) clients. Some familiarity with RxJS is a requirement to use the API, however just understanding `.subscribe` and `.pipe` on Observables will unlock full-scale use thereof. + * + * @see [[ApiPromise]] + * + * ## Usage + * + * Making rpc calls - + *
+ * + * ```javascript + * import ApiRx from '@polkadot/api/rx'; + * + * // initialize via Promise & static create + * const api = await ApiRx.create().toPromise(); + * + * // make a call to retrieve the current network head + * api.rpc.chain.subscribeNewHeads().subscribe((header) => { + * console.log(`Chain is at #${header.number}`); + * }); + * ``` + *
+ * + * Subscribing to chain state - + *
+ * + * ```javascript + * import { combineLatest } from 'rxjs'; + * import { pairwise, switchMap } from 'rxjs/operators'; + * import { ApiRx, WsProvider } from '@polkadot/api'; + * + * + * // initialize a provider with a specific endpoint + * const provider = new WsProvider('wss://example.com:9944') + * + * // initialize via isReady & new with specific provider + * new ApiRx({ provider }) + * .isReady + * .pipe( + * switchMap((api) => + * combineLatest([ + * api.query.timestamp.blockPeriod(), + * api.query.timestamp.now().pipe(pairwise()) + * ]) + * ) + * ) + * .subscribe(([blockPeriod, timestamp]) => { + * const elapsed = timestamp[1].toNumber() - timestamp[0].toNumber(); + * console.log(`timestamp ${timestamp[1]} \nelapsed ${elapsed} \n(${blockPeriod}s target)`); + * }); + * ``` + *
+ * + * Submitting a transaction - + *
+ * + * ```javascript + * import { first, switchMap } from 'rxjs/operators'; + * import ApiRx from '@polkadot/api/rx'; + * + * // import the test keyring (already has dev keys for Alice, Bob, Charlie, Eve & Ferdie) + * import testingPairs from '@polkadot/keyring/testingPairs'; + * const keyring = testingPairs(); + * + * // get api via Promise + * const api = await ApiRx.create().toPromise(); + * + * // retrieve nonce for the account + * api.query.system + * .account(keyring.alice.address) + * .pipe( + * first(), + * // pipe nonce into transfer + * switchMap(([nonce]) => + * api.tx.balances + * // create transfer + * .transfer(keyring.bob.address, 12345) + * // sign the transaction + * .sign(keyring.alice, { nonce }) + * // send the transaction + * .send() + * ) + * ) + * // subscribe to overall result + * .subscribe(({ status }) => { + * if (status.isInBlock) { + * console.log('Completed at block hash', status.asFinalized.toHex()); + * } + * }); + * ``` + */ +export class ApiRx extends ApiBase<'rxjs'> { + #isReadyRx: Observable; + + /** + * @description Creates an ApiRx instance using the supplied provider. Returns an Observable containing the actual Api instance. + * @param options options that is passed to the class constructor. Can be either [[ApiOptions]] or [[WsProvider]] + * @example + *
+ * + * ```javascript + * import { switchMap } from 'rxjs/operators'; + * import Api from '@polkadot/api/rx'; + * + * Api.create() + * .pipe( + * switchMap((api) => + * api.rpc.chain.subscribeNewHeads() + * )) + * .subscribe((header) => { + * console.log(`new block #${header.number.toNumber()}`); + * }); + * ``` + */ + public static create (options?: ApiOptions): Observable { + return new ApiRx(options).isReady; + } + + /** + * @description Create an instance of the ApiRx class + * @param options Options to create an instance. Can be either [[ApiOptions]] or [[WsProvider]] + * @example + *
+ * + * ```javascript + * import { switchMap } from 'rxjs/operators'; + * import Api from '@polkadot/api/rx'; + * + * new Api().isReady + * .pipe( + * switchMap((api) => + * api.rpc.chain.subscribeNewHeads() + * )) + * .subscribe((header) => { + * console.log(`new block #${header.number.toNumber()}`); + * }); + * ``` + */ + constructor (options?: ApiOptions) { + super(options, 'rxjs', decorateMethod); + + this.#isReadyRx = from>( + // You can create an observable from an event, however my mind groks this form better + new Promise((resolve): void => { + super.on('ready', (): void => { + resolve(this); + }); + }) + ); + } + + /** + * @description Observable that returns the first time we are connected and loaded + */ + public get isReady (): Observable { + return this.#isReadyRx; + } + + /** + * @description Returns a clone of this ApiRx instance (new underlying provider connection) + */ + public clone (): ApiRx { + return new ApiRx({ + ...this._options, + source: this + }); + } +} diff --git a/packages/api/src/submittable/Result.ts b/packages/api/src/submittable/Result.ts index b2be3b0421..2e94e09cf9 100644 --- a/packages/api/src/submittable/Result.ts +++ b/packages/api/src/submittable/Result.ts @@ -27,7 +27,7 @@ function extractInfo (events: EventRecord[] = []): DispatchInfo | undefined { )[0]; } -export default class SubmittableResult implements ISubmittableResult { +export class SubmittableResult implements ISubmittableResult { public readonly dispatchError?: DispatchError; public readonly dispatchInfo?: DispatchInfo; diff --git a/packages/api/src/submittable/createClass.ts b/packages/api/src/submittable/createClass.ts index 0cb772e942..3a99724f11 100644 --- a/packages/api/src/submittable/createClass.ts +++ b/packages/api/src/submittable/createClass.ts @@ -14,7 +14,7 @@ import { assert, isBn, isFunction, isNumber, isString, isU8a } from '@polkadot/u import { filterEvents, isKeyringPair } from '../util'; import ApiBase from '../base'; -import SubmittableResult from './Result'; +import { SubmittableResult } from './Result'; interface SubmittableOptions { api: ApiInterfaceRx; @@ -24,7 +24,7 @@ interface SubmittableOptions { const identity = (input: T): T => input; -export default function createClass ({ api, apiType, decorateMethod }: SubmittableOptions): Constructor> { +export function createClass ({ api, apiType, decorateMethod }: SubmittableOptions): Constructor> { // an instance of the base extrinsic for us to extend const ExtrinsicBase = api.registry.createClass('Extrinsic'); diff --git a/packages/api/src/submittable/createSubmittable.ts b/packages/api/src/submittable/createSubmittable.ts index 9458012f56..edcb046163 100644 --- a/packages/api/src/submittable/createSubmittable.ts +++ b/packages/api/src/submittable/createSubmittable.ts @@ -6,11 +6,11 @@ import { ApiInterfaceRx, ApiTypes } from '../types'; import { SubmittableExtrinsic } from './types'; import ApiBase from '../base'; -import createClass from './createClass'; +import { createClass } from './createClass'; type Creator = (extrinsic: Call | Uint8Array | string) => SubmittableExtrinsic; -export default function createSubmittable (apiType: ApiTypes, api: ApiInterfaceRx, decorateMethod: ApiBase['_decorateMethod']): Creator { +export function createSubmittable (apiType: ApiTypes, api: ApiInterfaceRx, decorateMethod: ApiBase['_decorateMethod']): Creator { const Submittable = createClass({ api, apiType, decorateMethod }); return (extrinsic: Call | Extrinsic | Uint8Array | string): SubmittableExtrinsic => diff --git a/packages/api/src/submittable/index.ts b/packages/api/src/submittable/index.ts index 910b1cfff6..7d9ee9c658 100644 --- a/packages/api/src/submittable/index.ts +++ b/packages/api/src/submittable/index.ts @@ -1,5 +1,5 @@ // Copyright 2017-2020 @polkadot/api authors & contributors // SPDX-License-Identifier: Apache-2.0 -export { default as createSubmittable } from './createSubmittable'; -export { default as SubmittableResult } from './Result'; +export { createSubmittable } from './createSubmittable'; +export { SubmittableResult } from './Result'; diff --git a/packages/api/src/util/validate.spec.ts b/packages/api/src/util/validate.spec.ts index 135f6a4107..99c51033f5 100644 --- a/packages/api/src/util/validate.spec.ts +++ b/packages/api/src/util/validate.spec.ts @@ -3,7 +3,7 @@ import { Storage } from '@polkadot/metadata/decorate/types'; -import Metadata, { storageFromMeta } from '@polkadot/metadata'; +import { Metadata, storageFromMeta } from '@polkadot/metadata'; import metaStatic from '@polkadot/metadata/static'; import { TypeRegistry } from '@polkadot/types'; diff --git a/packages/metadata/package.json b/packages/metadata/package.json index 12e043b8b9..9585f114d6 100644 --- a/packages/metadata/package.json +++ b/packages/metadata/package.json @@ -31,11 +31,11 @@ "@babel/runtime": "^7.12.1", "@polkadot/types": "2.6.2-0", "@polkadot/types-known": "2.6.2-0", - "@polkadot/util": "^4.0.1", - "@polkadot/util-crypto": "^4.0.1", + "@polkadot/util": "^4.0.2-5", + "@polkadot/util-crypto": "^4.0.2-5", "bn.js": "^5.1.3" }, "devDependencies": { - "@polkadot/keyring": "^4.0.1" + "@polkadot/keyring": "^4.0.2-5" } } diff --git a/packages/metadata/src/MagicNumber.spec.ts b/packages/metadata/src/MagicNumber.spec.ts index 05fd6133be..3339b050b3 100644 --- a/packages/metadata/src/MagicNumber.spec.ts +++ b/packages/metadata/src/MagicNumber.spec.ts @@ -3,7 +3,7 @@ import { TypeRegistry } from '@polkadot/types'; -import MagicNumber, { MAGIC_NUMBER } from './MagicNumber'; +import { MagicNumber, MAGIC_NUMBER } from './MagicNumber'; describe('MagicNumber', (): void => { const registry = new TypeRegistry(); diff --git a/packages/metadata/src/MagicNumber.ts b/packages/metadata/src/MagicNumber.ts index fe7885b8ed..35fa71f175 100644 --- a/packages/metadata/src/MagicNumber.ts +++ b/packages/metadata/src/MagicNumber.ts @@ -9,7 +9,7 @@ import U32 from '@polkadot/types/primitive/U32'; export const MAGIC_NUMBER = 0x6174656d; // `meta`, reversed for Little Endian encoding -export default class MagicNumber extends U32 { +export class MagicNumber extends U32 { constructor (registry: Registry, value?: AnyNumber) { super(registry, value); diff --git a/packages/metadata/src/Metadata.spec.ts b/packages/metadata/src/Metadata.spec.ts index f2355247a2..a89d7f022b 100644 --- a/packages/metadata/src/Metadata.spec.ts +++ b/packages/metadata/src/Metadata.spec.ts @@ -4,7 +4,7 @@ import { TypeRegistry } from '@polkadot/types'; import substrateData from './static'; -import Metadata from './Metadata'; +import { Metadata } from './Metadata'; describe('Metadata', (): void => { it('allows creation from hex with JSON equivalence', (): void => { diff --git a/packages/metadata/src/Metadata.ts b/packages/metadata/src/Metadata.ts index b7a02126c3..79b246466c 100644 --- a/packages/metadata/src/Metadata.ts +++ b/packages/metadata/src/Metadata.ts @@ -5,7 +5,7 @@ import { Registry } from '@polkadot/types/types'; import { isString, u8aConcat, u8aToU8a } from '@polkadot/util'; -import MetadataVersioned from './MetadataVersioned'; +import { MetadataVersioned } from './MetadataVersioned'; // magic u32 preceding the version id const VERSION_IDX = 4; @@ -49,7 +49,7 @@ function decodeMetadata (registry: Registry, _value?: Uint8Array | string): Meta * @description * The versioned runtime metadata as a decoded structure */ -export default class Metadata extends MetadataVersioned { +export class Metadata extends MetadataVersioned { constructor (registry: Registry, value?: Uint8Array | string) { super(registry, decodeMetadata(registry, value)); } diff --git a/packages/metadata/src/MetadataVersioned.ts b/packages/metadata/src/MetadataVersioned.ts index e82eda35d0..cbf9873f5d 100644 --- a/packages/metadata/src/MetadataVersioned.ts +++ b/packages/metadata/src/MetadataVersioned.ts @@ -7,7 +7,7 @@ import { Registry } from '@polkadot/types/types'; import Struct from '@polkadot/types/codec/Struct'; import { assert } from '@polkadot/util'; -import MagicNumber from './MagicNumber'; +import { MagicNumber } from './MagicNumber'; import v9ToV10 from './v9/toV10'; import v10ToV11 from './v10/toV11'; import v11ToV12 from './v11/toV12'; @@ -23,7 +23,7 @@ type MetaAsX = 'asV9' | 'asV10' | 'asV11' | 'asV12'; * @description * The versioned runtime metadata as a decoded structure */ -export default class MetadataVersioned extends Struct { +export class MetadataVersioned extends Struct { readonly #converted = new Map(); constructor (registry: Registry, value?: unknown) { diff --git a/packages/metadata/src/decorate/consts/fromMetadata.spec.ts b/packages/metadata/src/decorate/consts/fromMetadata.spec.ts index fa61980c65..5af102e88d 100644 --- a/packages/metadata/src/decorate/consts/fromMetadata.spec.ts +++ b/packages/metadata/src/decorate/consts/fromMetadata.spec.ts @@ -7,7 +7,7 @@ import { Metadata, TypeRegistry } from '@polkadot/types'; import rpcMetadata from '../../static'; import rpcMetadataV10 from '../../v10/static'; -import fromMetadata from './fromMetadata'; +import { constantsFromMeta } from './fromMetadata'; function init (meta: string): [Constants, TypeRegistry] { const registry = new TypeRegistry(); @@ -15,7 +15,7 @@ function init (meta: string): [Constants, TypeRegistry] { registry.setMetadata(metadata); - return [fromMetadata(registry, metadata), registry]; + return [constantsFromMeta(registry, metadata), registry]; } describe('fromMetadata', (): void => { diff --git a/packages/metadata/src/decorate/consts/fromMetadata.ts b/packages/metadata/src/decorate/consts/fromMetadata.ts index 13bb09c4c1..f899fd5bd5 100644 --- a/packages/metadata/src/decorate/consts/fromMetadata.ts +++ b/packages/metadata/src/decorate/consts/fromMetadata.ts @@ -7,10 +7,10 @@ import { Constants, ConstantCodec, ModuleConstants } from '../types'; import { createTypeUnsafe } from '@polkadot/types/create'; import { hexToU8a, stringCamelCase } from '@polkadot/util'; -import Metadata from '../..'; +import { Metadata } from '../..'; /** @internal */ -export default function fromMetadata (registry: Registry, metadata: Metadata): Constants { +export function constantsFromMeta (registry: Registry, metadata: Metadata): Constants { return metadata.asLatest.modules.reduce((result: Constants, moduleMetadata): Constants => { if (moduleMetadata.constants.isEmpty) { return result; diff --git a/packages/metadata/src/decorate/extrinsics/fromMetadata.spec.ts b/packages/metadata/src/decorate/extrinsics/fromMetadata.spec.ts index 3f69b8b74c..509656d15b 100644 --- a/packages/metadata/src/decorate/extrinsics/fromMetadata.spec.ts +++ b/packages/metadata/src/decorate/extrinsics/fromMetadata.spec.ts @@ -4,7 +4,7 @@ import { Metadata, TypeRegistry } from '@polkadot/types'; import json from '../../static'; -import fromMetadata from './fromMetadata'; +import { extrinsicsFromMeta } from './fromMetadata'; // Use the pre-generated metadata const registry = new TypeRegistry(); @@ -12,7 +12,7 @@ const metadata = new Metadata(registry, json); registry.setMetadata(metadata); -const newExtrinsics = fromMetadata(registry, metadata); +const newExtrinsics = extrinsicsFromMeta(registry, metadata); describe('fromMetadata', (): void => { it('should throw if an incorrect number of args is supplied', (): void => { diff --git a/packages/metadata/src/decorate/extrinsics/fromMetadata.ts b/packages/metadata/src/decorate/extrinsics/fromMetadata.ts index d89ac27fbc..cb6bf0448a 100644 --- a/packages/metadata/src/decorate/extrinsics/fromMetadata.ts +++ b/packages/metadata/src/decorate/extrinsics/fromMetadata.ts @@ -9,7 +9,7 @@ import extrinsics from './'; import createUnchecked from './createUnchecked'; /** @internal */ -export default function fromMetadata (registry: Registry, metadata: RegistryMetadata): ModulesWithCalls { +export function extrinsicsFromMeta (registry: Registry, metadata: RegistryMetadata): ModulesWithCalls { const modules = metadata.asLatest.modules; const isIndexed = modules.some(({ index }) => !index.eqn(255)); diff --git a/packages/metadata/src/decorate/extrinsics/index.spec.ts b/packages/metadata/src/decorate/extrinsics/index.spec.ts index 3d06c3f5c0..d6deafbb11 100644 --- a/packages/metadata/src/decorate/extrinsics/index.spec.ts +++ b/packages/metadata/src/decorate/extrinsics/index.spec.ts @@ -2,19 +2,19 @@ // SPDX-License-Identifier: Apache-2.0 import BN from 'bn.js'; -import testingPairs from '@polkadot/keyring/testingPairs'; +import { createTestPairs } from '@polkadot/keyring/testingPairs'; import { Metadata, TypeRegistry } from '@polkadot/types'; import metadataStatic from '../../static'; -import fromMetadata from './fromMetadata'; +import { extrinsicsFromMeta } from './fromMetadata'; -const keyring = testingPairs({ type: 'ed25519' }, false); +const keyring = createTestPairs({ type: 'ed25519' }, false); const registry = new TypeRegistry(); const metadata = new Metadata(registry, metadataStatic); registry.setMetadata(metadata); -const extrinsics = fromMetadata(registry, metadata); +const extrinsics = extrinsicsFromMeta(registry, metadata); describe('extrinsics', (): void => { it('encodes an actual transfer (actual data)', (): void => { diff --git a/packages/metadata/src/decorate/index.spec.ts b/packages/metadata/src/decorate/index.spec.ts index 237057a353..f812fb3429 100644 --- a/packages/metadata/src/decorate/index.spec.ts +++ b/packages/metadata/src/decorate/index.spec.ts @@ -4,7 +4,7 @@ import { TypeRegistry } from '@polkadot/types/create'; import { u8aToHex } from '@polkadot/util'; -import Metadata from '..'; +import { Metadata } from '..'; import json from '../static'; import { constantsFromMeta, extrinsicsFromMeta, storageFromMeta } from './'; diff --git a/packages/metadata/src/decorate/index.ts b/packages/metadata/src/decorate/index.ts index edc4fb89a8..f535869ca0 100644 --- a/packages/metadata/src/decorate/index.ts +++ b/packages/metadata/src/decorate/index.ts @@ -6,15 +6,15 @@ import { DecoratedMeta } from './types'; import { assert } from '@polkadot/util'; -import Metadata from '..'; -import constantsFromMeta from './consts/fromMetadata'; -import extrinsicsFromMeta from './extrinsics/fromMetadata'; -import storageFromMeta from './storage/fromMetadata'; +import { Metadata } from '..'; +import { constantsFromMeta } from './consts/fromMetadata'; +import { extrinsicsFromMeta } from './extrinsics/fromMetadata'; +import { storageFromMeta } from './storage/fromMetadata'; /** * Expands the metadata by decoration int consts, query and tx sections */ -export default function expandMetadata (registry: Registry, value: Metadata): DecoratedMeta { +export function expandMetadata (registry: Registry, value: Metadata): DecoratedMeta { assert(value instanceof Metadata, 'You need to pass a valid Metadata instance to Decorated'); return { diff --git a/packages/metadata/src/decorate/storage/fromMetadata.spec.ts b/packages/metadata/src/decorate/storage/fromMetadata.spec.ts index 3cd4b565a8..58643d0671 100644 --- a/packages/metadata/src/decorate/storage/fromMetadata.spec.ts +++ b/packages/metadata/src/decorate/storage/fromMetadata.spec.ts @@ -1,15 +1,15 @@ // Copyright 2017-2020 @polkadot/metadata authors & contributors // SPDX-License-Identifier: Apache-2.0 -import testingPairs from '@polkadot/keyring/testingPairs'; +import { createTestPairs } from '@polkadot/keyring/testingPairs'; import { TypeRegistry } from '@polkadot/types'; import { u8aToHex } from '@polkadot/util'; -import Metadata from '../../'; +import { Metadata } from '../../'; import rpcMetadata from '../../static'; import { storageFromMeta } from '../'; -const keyring = testingPairs({ type: 'ed25519' }); +const keyring = createTestPairs({ type: 'ed25519' }); describe('fromMetadata', (): void => { describe('latest', (): void => { diff --git a/packages/metadata/src/decorate/storage/fromMetadata.ts b/packages/metadata/src/decorate/storage/fromMetadata.ts index 0f69ebec1c..152bdcec59 100644 --- a/packages/metadata/src/decorate/storage/fromMetadata.ts +++ b/packages/metadata/src/decorate/storage/fromMetadata.ts @@ -6,12 +6,12 @@ import { ModuleStorage, Storage } from '../types'; import { stringCamelCase, stringLowerFirst } from '@polkadot/util'; -import Metadata from '../../Metadata'; +import { Metadata } from '../../Metadata'; import createFunction from './createFunction'; import getStorage from './storage'; /** @internal */ -export default function fromMetadata (registry: Registry, metadata: Metadata): Storage { +export function storageFromMeta (registry: Registry, metadata: Metadata): Storage { return metadata.asLatest.modules.reduce((result: Storage, moduleMetadata): Storage => { if (moduleMetadata.storage.isNone) { return result; diff --git a/packages/metadata/src/index.ts b/packages/metadata/src/index.ts index ea108cc9a4..a25bd6480c 100644 --- a/packages/metadata/src/index.ts +++ b/packages/metadata/src/index.ts @@ -1,9 +1,5 @@ // Copyright 2017-2020 @polkadot/metadata authors & contributors // SPDX-License-Identifier: Apache-2.0 -import expandMetadata, { constantsFromMeta, extrinsicsFromMeta, storageFromMeta } from './decorate'; -import Metadata from './Metadata'; - -export default Metadata; - -export { constantsFromMeta, expandMetadata, extrinsicsFromMeta, storageFromMeta }; +export { Metadata } from './Metadata'; +export { constantsFromMeta, expandMetadata, extrinsicsFromMeta, storageFromMeta } from './decorate'; diff --git a/packages/metadata/src/util/testUtil.ts b/packages/metadata/src/util/testUtil.ts index c869911ee6..5195c2917a 100644 --- a/packages/metadata/src/util/testUtil.ts +++ b/packages/metadata/src/util/testUtil.ts @@ -7,7 +7,7 @@ import { MetadataInterface } from '../types'; import { unwrapStorageType } from '@polkadot/types/primitive/StorageKey'; import getUniqTypes from './getUniqTypes'; -import Metadata from '..'; +import { Metadata } from '..'; /** @internal */ export function decodeLatestSubstrate (registry: Registry, version: number, rpcData: string, staticSubstrate: Record): void { diff --git a/packages/metadata/src/util/toCallsOnly.spec.ts b/packages/metadata/src/util/toCallsOnly.spec.ts index 34e397a6a6..9dc552a523 100644 --- a/packages/metadata/src/util/toCallsOnly.spec.ts +++ b/packages/metadata/src/util/toCallsOnly.spec.ts @@ -4,7 +4,7 @@ import { TypeRegistry } from '@polkadot/types'; import staticData from '../static'; -import Metadata from '..'; +import { Metadata } from '..'; describe('toCallsOnly', (): void => { const registry = new TypeRegistry(); diff --git a/packages/rpc-core/README.md b/packages/rpc-core/README.md index ae2a6d8d7f..3da79ef22a 100644 --- a/packages/rpc-core/README.md +++ b/packages/rpc-core/README.md @@ -14,7 +14,7 @@ Initialization - ```js import Rpc from '@polkadot/rpc-core'; -import WsProvider from '@polkadot/rpc-provider/ws'; +import { WsProvider } from '@polkadot/rpc-provider/ws'; const provider = new WsProvider('http://127.0.0.1:9944'); const rpc = new Rpc(provider); diff --git a/packages/rpc-core/package.json b/packages/rpc-core/package.json index 25700abe3f..f14c61f415 100644 --- a/packages/rpc-core/package.json +++ b/packages/rpc-core/package.json @@ -32,11 +32,11 @@ "@polkadot/metadata": "2.6.2-0", "@polkadot/rpc-provider": "2.6.2-0", "@polkadot/types": "2.6.2-0", - "@polkadot/util": "^4.0.1", + "@polkadot/util": "^4.0.2-5", "memoizee": "^0.4.14", "rxjs": "^6.6.3" }, "devDependencies": { - "@polkadot/keyring": "^4.0.1" + "@polkadot/keyring": "^4.0.2-5" } } diff --git a/packages/rpc-core/src/cached.spec.ts b/packages/rpc-core/src/cached.spec.ts index 3108e93bf7..a2139eb71d 100644 --- a/packages/rpc-core/src/cached.spec.ts +++ b/packages/rpc-core/src/cached.spec.ts @@ -1,19 +1,19 @@ // Copyright 2017-2020 @polkadot/rpc-core authors & contributors // SPDX-License-Identifier: Apache-2.0 -import testingPairs from '@polkadot/keyring/testingPairs'; +import { createTestPairs } from '@polkadot/keyring/testingPairs'; import MockProvider from '@polkadot/rpc-provider/mock'; import { TypeRegistry } from '@polkadot/types'; -import Rpc from '.'; +import { RpcCore } from '.'; describe('Cached Observables', (): void => { const registry = new TypeRegistry(); - let rpc: Rpc; - const keyring = testingPairs(); + let rpc: RpcCore; + const keyring = createTestPairs(); beforeEach((): void => { - rpc = new Rpc('123', registry, new MockProvider(registry)); + rpc = new RpcCore('123', registry, new MockProvider(registry)); }); it('creates a single observable for subscriptions (multiple calls)', (): void => { diff --git a/packages/rpc-core/src/index.spec.ts b/packages/rpc-core/src/index.spec.ts index e68dab2dc7..18939b1ccd 100644 --- a/packages/rpc-core/src/index.spec.ts +++ b/packages/rpc-core/src/index.spec.ts @@ -5,19 +5,19 @@ import MockProvider from '@polkadot/rpc-provider/mock'; import { TypeRegistry } from '@polkadot/types'; import { isFunction } from '@polkadot/util'; -import Rpc from '.'; +import { RpcCore } from '.'; describe('Api', (): void => { const registry = new TypeRegistry(); it('requires a provider with a send method', (): void => { expect( - (): Rpc => new Rpc('234', registry, {} as any) + () => new RpcCore('234', registry, {} as any) ).toThrow(/Expected Provider/); }); it('allows for the definition of user RPCs', (): void => { - const rpc = new Rpc('567', registry, new MockProvider(registry), { + const rpc = new RpcCore('567', registry, new MockProvider(registry), { testing: { foo: { description: 'foo', diff --git a/packages/rpc-core/src/index.ts b/packages/rpc-core/src/index.ts index ff7655b92c..44c530853b 100644 --- a/packages/rpc-core/src/index.ts +++ b/packages/rpc-core/src/index.ts @@ -61,13 +61,13 @@ function logErrorMessage (method: string, { params, type }: DefinitionRpc, error * * ```javascript * import Rpc from '@polkadot/rpc-core'; - * import WsProvider from '@polkadot/rpc-provider/ws'; + * import { WsProvider } from '@polkadot/rpc-provider/ws'; * * const provider = new WsProvider('ws://127.0.0.1:9944'); * const rpc = new Rpc(provider); * ``` */ -export default class Rpc implements RpcInterface { +export class RpcCore implements RpcInterface { #instanceId: string; #registryDefault: Registry; diff --git a/packages/rpc-core/src/methodSend.spec.ts b/packages/rpc-core/src/methodSend.spec.ts index df4c7389da..20f011b535 100644 --- a/packages/rpc-core/src/methodSend.spec.ts +++ b/packages/rpc-core/src/methodSend.spec.ts @@ -5,11 +5,11 @@ import { DefinitionRpc } from '@polkadot/types/types'; import { TypeRegistry } from '@polkadot/types'; -import Rpc from '.'; +import { RpcCore } from '.'; describe('methodSend', (): void => { const registry = new TypeRegistry(); - let rpc: Rpc; + let rpc: RpcCore; let methods: Record; let provider: any; @@ -35,7 +35,7 @@ describe('methodSend', (): void => { }) }; - rpc = new Rpc('987', registry, provider); + rpc = new RpcCore('987', registry, provider); }); it('checks for mismatched parameters', (done): void => { diff --git a/packages/rpc-core/src/replay.spec.ts b/packages/rpc-core/src/replay.spec.ts index 46f3f01ab3..49d51c991c 100644 --- a/packages/rpc-core/src/replay.spec.ts +++ b/packages/rpc-core/src/replay.spec.ts @@ -5,14 +5,14 @@ import { Observable, of } from 'rxjs'; import MockProvider from '@polkadot/rpc-provider/mock'; import { TypeRegistry } from '@polkadot/types'; -import Rpc from '.'; +import { RpcCore } from '.'; describe('replay', (): void => { const registry = new TypeRegistry(); - let rpc: Rpc; + let rpc: RpcCore; beforeEach((): void => { - rpc = new Rpc('653', registry, new MockProvider(registry)); + rpc = new RpcCore('653', registry, new MockProvider(registry)); }); it('subscribes via the rpc section', (done): void => { diff --git a/packages/rpc-provider/README.md b/packages/rpc-provider/README.md index c26550f533..7f42a2748c 100644 --- a/packages/rpc-provider/README.md +++ b/packages/rpc-provider/README.md @@ -19,7 +19,7 @@ yarn add @polkadot/rpc-provider WebSocket Initialization - ```javascript -import WsProvider from '@polkadot/rpc-provider/ws'; +import { WsProvider } from '@polkadot/rpc-provider/ws'; // this is the actual default endpoint const provider = new WsProvider('ws://127.0.0.1:9944'); diff --git a/packages/rpc-provider/package.json b/packages/rpc-provider/package.json index 7ecb297292..f749c949f0 100644 --- a/packages/rpc-provider/package.json +++ b/packages/rpc-provider/package.json @@ -30,15 +30,15 @@ "dependencies": { "@babel/runtime": "^7.12.1", "@polkadot/types": "2.6.2-0", - "@polkadot/util": "^4.0.1", - "@polkadot/util-crypto": "^4.0.1", - "@polkadot/x-fetch": "^4.0.1", - "@polkadot/x-ws": "^4.0.1", + "@polkadot/util": "^4.0.2-5", + "@polkadot/util-crypto": "^4.0.2-5", + "@polkadot/x-fetch": "^4.0.2-5", + "@polkadot/x-ws": "^4.0.2-5", "bn.js": "^5.1.3", "eventemitter3": "^4.0.7" }, "devDependencies": { - "@polkadot/keyring": "^4.0.1", + "@polkadot/keyring": "^4.0.2-5", "@polkadot/metadata": "2.6.2-0", "mock-socket": "^9.0.3", "nock": "^13.0.4" diff --git a/packages/rpc-provider/src/http/index.spec.ts b/packages/rpc-provider/src/http/index.spec.ts index 6c076b8959..a376569a7e 100644 --- a/packages/rpc-provider/src/http/index.spec.ts +++ b/packages/rpc-provider/src/http/index.spec.ts @@ -2,30 +2,30 @@ // SPDX-License-Identifier: Apache-2.0 import { TEST_HTTP_URL } from '../../test/mockHttp'; -import Http from './'; +import { HttpProvider } from './'; describe('Http', (): void => { - let http: Http; + let http: HttpProvider; beforeEach((): void => { - http = new Http(TEST_HTTP_URL); + http = new HttpProvider(TEST_HTTP_URL); }); it('requires an http:// prefixed endpoint', (): void => { expect( - (): Http => new Http('ws://') + () => new HttpProvider('ws://') ).toThrow(/with 'http/); }); it('allows https:// endpoints', (): void => { expect( - (): Http => new Http('https://') + () => new HttpProvider('https://') ).not.toThrow(); }); it('allows custom headers', (): void => { expect( - (): Http => new Http('https://', { foo: 'bar' }) + () => new HttpProvider('https://', { foo: 'bar' }) ).not.toThrow(); }); diff --git a/packages/rpc-provider/src/http/index.ts b/packages/rpc-provider/src/http/index.ts index fd3d58f182..a11b5f617b 100644 --- a/packages/rpc-provider/src/http/index.ts +++ b/packages/rpc-provider/src/http/index.ts @@ -33,7 +33,7 @@ const l = logger('api-http'); * * @see [[WsProvider]] */ -export default class HttpProvider implements ProviderInterface { +export class HttpProvider implements ProviderInterface { readonly #coder: Coder; readonly #endpoint: string; diff --git a/packages/rpc-provider/src/http/send.spec.ts b/packages/rpc-provider/src/http/send.spec.ts index c7193f648b..e0c4e4fdb9 100644 --- a/packages/rpc-provider/src/http/send.spec.ts +++ b/packages/rpc-provider/src/http/send.spec.ts @@ -4,14 +4,14 @@ import { Mock } from './../mock/types'; import { mockHttp, TEST_HTTP_URL } from '../../test/mockHttp'; -import Http from './'; +import { HttpProvider } from './'; describe('send', (): void => { - let http: Http; + let http: HttpProvider; let mock: Mock; beforeEach((): void => { - http = new Http(TEST_HTTP_URL); + http = new HttpProvider(TEST_HTTP_URL); }); afterEach((): void => { diff --git a/packages/rpc-provider/src/index.ts b/packages/rpc-provider/src/index.ts index 3497f4f86f..dabf1ad54b 100644 --- a/packages/rpc-provider/src/index.ts +++ b/packages/rpc-provider/src/index.ts @@ -1,5 +1,5 @@ // Copyright 2017-2020 @polkadot/rpc-provider authors & contributors // SPDX-License-Identifier: Apache-2.0 -export { default as HttpProvider } from './http'; -export { default as WsProvider } from './ws'; +export { HttpProvider } from './http'; +export { WsProvider } from './ws'; diff --git a/packages/rpc-provider/src/mock/index.ts b/packages/rpc-provider/src/mock/index.ts index fcb97ef323..9d5780bb1a 100644 --- a/packages/rpc-provider/src/mock/index.ts +++ b/packages/rpc-provider/src/mock/index.ts @@ -10,10 +10,10 @@ import { MockStateSubscriptions, MockStateSubscriptionCallback, MockStateDb } fr import BN from 'bn.js'; import EventEmitter from 'eventemitter3'; -import Metadata, { storageFromMeta } from '@polkadot/metadata'; +import { Metadata, storageFromMeta } from '@polkadot/metadata'; import rpcMetadata from '@polkadot/metadata/static'; import jsonrpc from '@polkadot/types/interfaces/jsonrpc'; -import testKeyring from '@polkadot/keyring/testing'; +import { createTestKeyring } from '@polkadot/keyring/testing'; import rpcHeader from '@polkadot/types/json/Header.004.json'; import rpcSignedBlock from '@polkadot/types/json/SignedBlock.004.immortal.json'; import { assert, bnToU8a, logger, u8aToHex } from '@polkadot/util'; @@ -31,7 +31,7 @@ const SUBSCRIPTIONS: string[] = Array.prototype.concat.apply( ) ) as string[]; -const keyring = testKeyring({ type: 'ed25519' }); +const keyring = createTestKeyring({ type: 'ed25519' }); const l = logger('api-mock'); /** diff --git a/packages/rpc-provider/src/ws/Provider.ts b/packages/rpc-provider/src/ws/Provider.ts deleted file mode 100644 index 127a482134..0000000000 --- a/packages/rpc-provider/src/ws/Provider.ts +++ /dev/null @@ -1,468 +0,0 @@ -// Copyright 2017-2020 @polkadot/rpc-provider authors & contributors -// SPDX-License-Identifier: Apache-2.0 - -/* eslint-disable camelcase */ - -import { JsonRpcResponse, ProviderInterface, ProviderInterfaceCallback, ProviderInterfaceEmitted, ProviderInterfaceEmitCb } from '../types'; - -import EventEmitter from 'eventemitter3'; -import { assert, isChildClass, isNull, isUndefined, logger } from '@polkadot/util'; -import WS from '@polkadot/x-ws'; - -import Coder from '../coder'; -import defaults from '../defaults'; -import { getWSErrorString } from './errors'; - -interface SubscriptionHandler { - callback: ProviderInterfaceCallback; - type: string; -} - -interface WsStateAwaiting { - callback: ProviderInterfaceCallback; - method: string; - params: any[]; - subscription?: SubscriptionHandler; -} - -interface WsStateSubscription extends SubscriptionHandler { - method: string; - params: any[]; -} - -const ALIASSES: { [index: string]: string } = { - chain_finalisedHead: 'chain_finalizedHead', - chain_subscribeFinalisedHeads: 'chain_subscribeFinalizedHeads', - chain_unsubscribeFinalisedHeads: 'chain_unsubscribeFinalizedHeads' -}; - -const RETRY_DELAY = 1000; - -const l = logger('api-ws'); - -/** - * # @polkadot/rpc-provider/ws - * - * @name WsProvider - * - * @description The WebSocket Provider allows sending requests using WebSocket to a WebSocket RPC server TCP port. Unlike the [[HttpProvider]], it does support subscriptions and allows listening to events such as new blocks or balance changes. - * - * @example - *
- * - * ```javascript - * import Api from '@polkadot/api/promise'; - * import WsProvider from '@polkadot/rpc-provider/ws'; - * - * const provider = new WsProvider('ws://127.0.0.1:9944'); - * const api = new Api(provider); - * ``` - * - * @see [[HttpProvider]] - */ -export default class WsProvider implements ProviderInterface { - readonly #coder: Coder; - - readonly #endpoints: string[]; - - readonly #headers: Record; - - readonly #eventemitter: EventEmitter; - - readonly #handlers: Record = {}; - - readonly #queued: Record = {}; - - readonly #waitingForId: Record = {}; - - #autoConnectMs: number; - - #endpointIndex: number; - - #isConnected = false; - - #subscriptions: Record = {}; - - #websocket: WebSocket | null; - - /** - * @param {string | string[]} endpoint The endpoint url. Usually `ws://ip:9944` or `wss://ip:9944`, may provide an array of endpoint strings. - * @param {boolean} autoConnect Whether to connect automatically or not. - */ - constructor (endpoint: string | string[] = defaults.WS_URL, autoConnectMs: number | false = RETRY_DELAY, headers: Record = {}) { - const endpoints = Array.isArray(endpoint) - ? endpoint - : [endpoint]; - - assert(endpoints.length !== 0, 'WsProvider requires at least one Endpoint'); - - endpoints.forEach((endpoint) => { - assert(/^(wss|ws):\/\//.test(endpoint), `Endpoint should start with 'ws://', received '${endpoint}'`); - }); - - this.#eventemitter = new EventEmitter(); - this.#autoConnectMs = autoConnectMs || 0; - this.#coder = new Coder(); - this.#endpointIndex = -1; - this.#endpoints = endpoints; - this.#headers = headers; - this.#websocket = null; - - if (autoConnectMs > 0) { - this.connectWithRetry().catch((): void => { - // does not throw - }); - } - } - - /** - * @summary `true` when this provider supports subscriptions - */ - public get hasSubscriptions (): boolean { - return true; - } - - /** - * @summary Whether the node is connected or not. - * @return {boolean} true if connected - */ - public get isConnected (): boolean { - return this.#isConnected; - } - - /** - * @description Returns a clone of the object - */ - public clone (): WsProvider { - return new WsProvider(this.#endpoints); - } - - /** - * @summary Manually connect - * @description The [[WsProvider]] connects automatically by default, however if you decided otherwise, you may - * connect manually using this method. - */ - // eslint-disable-next-line @typescript-eslint/require-await - public async connect (): Promise { - try { - this.#endpointIndex = (this.#endpointIndex + 1) % this.#endpoints.length; - this.#websocket = typeof WebSocket !== 'undefined' && isChildClass(WebSocket, WS) - ? new WS(this.#endpoints[this.#endpointIndex]) - // eslint-disable-next-line @typescript-eslint/ban-ts-comment - // @ts-ignore - WS may be an instance of w3cwebsocket, which supports headers - : new WS(this.#endpoints[this.#endpointIndex], undefined, undefined, this.#headers, undefined, { - // default: true - fragmentOutgoingMessages: true, - // default: 16K - fragmentationThreshold: 256 * 1024 - }); - - this.#websocket.onclose = this.#onSocketClose; - this.#websocket.onerror = this.#onSocketError; - this.#websocket.onmessage = this.#onSocketMessage; - this.#websocket.onopen = this.#onSocketOpen; - } catch (error) { - l.error(error); - - this.#emit('error', error); - - throw error; - } - } - - /** - * @description Connect, never throwing an error, but rather forcing a retry - */ - public async connectWithRetry (): Promise { - try { - await this.connect(); - } catch (error) { - setTimeout((): void => { - this.connectWithRetry().catch((): void => { - // does not throw - }); - }, this.#autoConnectMs || RETRY_DELAY); - } - } - - /** - * @description Manually disconnect from the connection, clearing autoconnect logic - */ - // eslint-disable-next-line @typescript-eslint/require-await - public async disconnect (): Promise { - try { - assert(!isNull(this.#websocket), 'Cannot disconnect on a non-connected websocket'); - - // switch off autoConnect, we are in manual mode now - this.#autoConnectMs = 0; - - // 1000 - Normal closure; the connection successfully completed - this.#websocket.close(1000); - this.#websocket = null; - } catch (error) { - l.error(error); - - this.#emit('error', error); - - throw error; - } - } - - /** - * @summary Listens on events after having subscribed using the [[subscribe]] function. - * @param {ProviderInterfaceEmitted} type Event - * @param {ProviderInterfaceEmitCb} sub Callback - * @return unsubscribe function - */ - public on (type: ProviderInterfaceEmitted, sub: ProviderInterfaceEmitCb): () => void { - this.#eventemitter.on(type, sub); - - return (): void => { - this.#eventemitter.removeListener(type, sub); - }; - } - - /** - * @summary Send JSON data using WebSockets to configured HTTP Endpoint or queue. - * @param method The RPC methods to execute - * @param params Encoded paramaters as appliucable for the method - * @param subscription Subscription details (internally used) - */ - public send (method: string, params: any[], subscription?: SubscriptionHandler): Promise { - return new Promise((resolve, reject): void => { - try { - const json = this.#coder.encodeJson(method, params); - const id = this.#coder.getId(); - - const callback = (error?: Error | null, result?: any): void => { - error - ? reject(error) - : resolve(result); - }; - - l.debug((): string[] => ['calling', method, json]); - - this.#handlers[id] = { - callback, - method, - params, - subscription - }; - - if (this.isConnected && !isNull(this.#websocket)) { - this.#websocket.send(json); - } else { - this.#queued[id] = json; - } - } catch (error) { - reject(error); - } - }); - } - - /** - * @name subscribe - * @summary Allows subscribing to a specific event. - * @param {string} type Subscription type - * @param {string} method Subscription method - * @param {any[]} params Parameters - * @param {ProviderInterfaceCallback} callback Callback - * @return {Promise} Promise resolving to the dd of the subscription you can use with [[unsubscribe]]. - * - * @example - *
- * - * ```javascript - * const provider = new WsProvider('ws://127.0.0.1:9944'); - * const rpc = new Rpc(provider); - * - * rpc.state.subscribeStorage([[storage.system.account,
]], (_, values) => { - * console.log(values) - * }).then((subscriptionId) => { - * console.log('balance changes subscription id: ', subscriptionId) - * }) - * ``` - */ - public async subscribe (type: string, method: string, params: any[], callback: ProviderInterfaceCallback): Promise { - const id = await this.send(method, params, { callback, type }) as Promise; - - return id; - } - - /** - * @summary Allows unsubscribing to subscriptions made with [[subscribe]]. - */ - public async unsubscribe (type: string, method: string, id: number | string): Promise { - const subscription = `${type}::${id}`; - - // FIXME This now could happen with re-subscriptions. The issue is that with a re-sub - // the assigned id now does not match what the API user originally received. It has - // a slight complication in solving - since we cannot rely on the send id, but rather - // need to find the actual subscription id to map it - if (isUndefined(this.#subscriptions[subscription])) { - l.debug((): string => `Unable to find active subscription=${subscription}`); - - return false; - } - - delete this.#subscriptions[subscription]; - - const result = await this.send(method, [id]) as Promise; - - return result; - } - - #emit = (type: ProviderInterfaceEmitted, ...args: any[]): void => { - this.#eventemitter.emit(type, ...args); - } - - #onSocketClose = (event: CloseEvent): void => { - if (this.#autoConnectMs > 0) { - l.error(`disconnected from ${this.#endpoints[this.#endpointIndex]}: ${event.code}:: ${event.reason || getWSErrorString(event.code)}`); - } - - this.#isConnected = false; - this.#emit('disconnected'); - - if (this.#autoConnectMs > 0) { - setTimeout((): void => { - this.connectWithRetry().catch(() => { - // does not throw - }); - }, this.#autoConnectMs); - } - } - - #onSocketError = (error: Event): void => { - l.debug((): any => ['socket error', error]); - this.#emit('error', error); - } - - #onSocketMessage = (message: MessageEvent): void => { - // eslint-disable-next-line @typescript-eslint/no-unsafe-return - l.debug(() => ['received', message.data]); - - const response = JSON.parse(message.data as string) as JsonRpcResponse; - - return isUndefined(response.method) - ? this.#onSocketMessageResult(response) - : this.#onSocketMessageSubscribe(response); - } - - #onSocketMessageResult = (response: JsonRpcResponse): void => { - const handler = this.#handlers[response.id]; - - if (!handler) { - l.debug((): string => `Unable to find handler for id=${response.id}`); - - return; - } - - try { - const { method, params, subscription } = handler; - const result = this.#coder.decodeResponse(response) as string; - - // first send the result - in case of subs, we may have an update - // immediately if we have some queued results already - handler.callback(null, result); - - if (subscription) { - const subId = `${subscription.type}::${result}`; - - this.#subscriptions[subId] = { - ...subscription, - method, - params - }; - - // if we have a result waiting for this subscription already - if (this.#waitingForId[subId]) { - this.#onSocketMessageSubscribe(this.#waitingForId[subId]); - } - } - } catch (error) { - handler.callback(error, undefined); - } - - delete this.#handlers[response.id]; - } - - #onSocketMessageSubscribe = (response: JsonRpcResponse): void => { - const method = ALIASSES[response.method as string] || response.method || 'invalid'; - const subId = `${method}::${response.params.subscription}`; - const handler = this.#subscriptions[subId]; - - if (!handler) { - // store the JSON, we could have out-of-order subid coming in - this.#waitingForId[subId] = response; - - l.debug((): string => `Unable to find handler for subscription=${subId}`); - - return; - } - - // housekeeping - delete this.#waitingForId[subId]; - - try { - const result = this.#coder.decodeResponse(response); - - handler.callback(null, result); - } catch (error) { - handler.callback(error, undefined); - } - } - - #onSocketOpen = (): boolean => { - assert(!isNull(this.#websocket), 'WebSocket cannot be null in onOpen'); - - l.debug((): any[] => ['connected to', this.#endpoints[this.#endpointIndex]]); - - this.#isConnected = true; - - this.#emit('connected'); - this.#sendQueue(); - this.#resubscribe(); - - return true; - } - - #resubscribe = (): void => { - const subscriptions = this.#subscriptions; - - this.#subscriptions = {}; - - // eslint-disable-next-line @typescript-eslint/no-misused-promises - Object.keys(subscriptions).forEach(async (id): Promise => { - const { callback, method, params, type } = subscriptions[id]; - - // only re-create subscriptions which are not in author (only area where - // transactions are created, i.e. submissions such as 'author_submitAndWatchExtrinsic' - // are not included (and will not be re-broadcast) - if (type.startsWith('author_')) { - return; - } - - try { - await this.subscribe(type, method, params, callback); - } catch (error) { - l.error(error); - } - }); - } - - #sendQueue = (): void => { - Object.keys(this.#queued).forEach((id): void => { - try { - // we have done the websocket check in onSocketOpen, if an issue, will catch it - (this.#websocket as WebSocket).send( - this.#queued[id] - ); - - delete this.#queued[id]; - } catch (error) { - l.error(error); - } - }); - } -} diff --git a/packages/rpc-provider/src/ws/connect.spec.ts b/packages/rpc-provider/src/ws/connect.spec.ts index 688e71a73f..b59943d2a2 100644 --- a/packages/rpc-provider/src/ws/connect.spec.ts +++ b/packages/rpc-provider/src/ws/connect.spec.ts @@ -4,7 +4,7 @@ import { Mock } from './../mock/types'; import { mockWs, TEST_WS_URL } from '../../test/mockWs'; -import WsProvider from './'; +import { WsProvider } from './'; function sleepMs (ms = 0): Promise { return new Promise((resolve) => setTimeout(resolve, ms)); diff --git a/packages/rpc-provider/src/ws/index.spec.ts b/packages/rpc-provider/src/ws/index.spec.ts index 855cbc705d..bb0b41db8c 100644 --- a/packages/rpc-provider/src/ws/index.spec.ts +++ b/packages/rpc-provider/src/ws/index.spec.ts @@ -4,7 +4,7 @@ import { Mock } from './../mock/types'; import { mockWs, TEST_WS_URL } from '../../test/mockWs'; -import WsProvider from './'; +import { WsProvider } from './'; let ws: WsProvider; let mock: Mock; diff --git a/packages/rpc-provider/src/ws/index.ts b/packages/rpc-provider/src/ws/index.ts index 511b8e09c8..ab3dd9dc42 100644 --- a/packages/rpc-provider/src/ws/index.ts +++ b/packages/rpc-provider/src/ws/index.ts @@ -1,6 +1,468 @@ // Copyright 2017-2020 @polkadot/rpc-provider authors & contributors // SPDX-License-Identifier: Apache-2.0 -import WsProvider from './Provider'; +/* eslint-disable camelcase */ -export default WsProvider; +import { JsonRpcResponse, ProviderInterface, ProviderInterfaceCallback, ProviderInterfaceEmitted, ProviderInterfaceEmitCb } from '../types'; + +import EventEmitter from 'eventemitter3'; +import { assert, isChildClass, isNull, isUndefined, logger } from '@polkadot/util'; +import WS from '@polkadot/x-ws'; + +import Coder from '../coder'; +import defaults from '../defaults'; +import { getWSErrorString } from './errors'; + +interface SubscriptionHandler { + callback: ProviderInterfaceCallback; + type: string; +} + +interface WsStateAwaiting { + callback: ProviderInterfaceCallback; + method: string; + params: any[]; + subscription?: SubscriptionHandler; +} + +interface WsStateSubscription extends SubscriptionHandler { + method: string; + params: any[]; +} + +const ALIASSES: { [index: string]: string } = { + chain_finalisedHead: 'chain_finalizedHead', + chain_subscribeFinalisedHeads: 'chain_subscribeFinalizedHeads', + chain_unsubscribeFinalisedHeads: 'chain_unsubscribeFinalizedHeads' +}; + +const RETRY_DELAY = 1000; + +const l = logger('api-ws'); + +/** + * # @polkadot/rpc-provider/ws + * + * @name WsProvider + * + * @description The WebSocket Provider allows sending requests using WebSocket to a WebSocket RPC server TCP port. Unlike the [[HttpProvider]], it does support subscriptions and allows listening to events such as new blocks or balance changes. + * + * @example + *
+ * + * ```javascript + * import Api from '@polkadot/api/promise'; + * import { WsProvider } from '@polkadot/rpc-provider/ws'; + * + * const provider = new WsProvider('ws://127.0.0.1:9944'); + * const api = new Api(provider); + * ``` + * + * @see [[HttpProvider]] + */ +export class WsProvider implements ProviderInterface { + readonly #coder: Coder; + + readonly #endpoints: string[]; + + readonly #headers: Record; + + readonly #eventemitter: EventEmitter; + + readonly #handlers: Record = {}; + + readonly #queued: Record = {}; + + readonly #waitingForId: Record = {}; + + #autoConnectMs: number; + + #endpointIndex: number; + + #isConnected = false; + + #subscriptions: Record = {}; + + #websocket: WebSocket | null; + + /** + * @param {string | string[]} endpoint The endpoint url. Usually `ws://ip:9944` or `wss://ip:9944`, may provide an array of endpoint strings. + * @param {boolean} autoConnect Whether to connect automatically or not. + */ + constructor (endpoint: string | string[] = defaults.WS_URL, autoConnectMs: number | false = RETRY_DELAY, headers: Record = {}) { + const endpoints = Array.isArray(endpoint) + ? endpoint + : [endpoint]; + + assert(endpoints.length !== 0, 'WsProvider requires at least one Endpoint'); + + endpoints.forEach((endpoint) => { + assert(/^(wss|ws):\/\//.test(endpoint), `Endpoint should start with 'ws://', received '${endpoint}'`); + }); + + this.#eventemitter = new EventEmitter(); + this.#autoConnectMs = autoConnectMs || 0; + this.#coder = new Coder(); + this.#endpointIndex = -1; + this.#endpoints = endpoints; + this.#headers = headers; + this.#websocket = null; + + if (autoConnectMs > 0) { + this.connectWithRetry().catch((): void => { + // does not throw + }); + } + } + + /** + * @summary `true` when this provider supports subscriptions + */ + public get hasSubscriptions (): boolean { + return true; + } + + /** + * @summary Whether the node is connected or not. + * @return {boolean} true if connected + */ + public get isConnected (): boolean { + return this.#isConnected; + } + + /** + * @description Returns a clone of the object + */ + public clone (): WsProvider { + return new WsProvider(this.#endpoints); + } + + /** + * @summary Manually connect + * @description The [[WsProvider]] connects automatically by default, however if you decided otherwise, you may + * connect manually using this method. + */ + // eslint-disable-next-line @typescript-eslint/require-await + public async connect (): Promise { + try { + this.#endpointIndex = (this.#endpointIndex + 1) % this.#endpoints.length; + this.#websocket = typeof WebSocket !== 'undefined' && isChildClass(WebSocket, WS) + ? new WS(this.#endpoints[this.#endpointIndex]) + // eslint-disable-next-line @typescript-eslint/ban-ts-comment + // @ts-ignore - WS may be an instance of w3cwebsocket, which supports headers + : new WS(this.#endpoints[this.#endpointIndex], undefined, undefined, this.#headers, undefined, { + // default: true + fragmentOutgoingMessages: true, + // default: 16K + fragmentationThreshold: 256 * 1024 + }); + + this.#websocket.onclose = this.#onSocketClose; + this.#websocket.onerror = this.#onSocketError; + this.#websocket.onmessage = this.#onSocketMessage; + this.#websocket.onopen = this.#onSocketOpen; + } catch (error) { + l.error(error); + + this.#emit('error', error); + + throw error; + } + } + + /** + * @description Connect, never throwing an error, but rather forcing a retry + */ + public async connectWithRetry (): Promise { + try { + await this.connect(); + } catch (error) { + setTimeout((): void => { + this.connectWithRetry().catch((): void => { + // does not throw + }); + }, this.#autoConnectMs || RETRY_DELAY); + } + } + + /** + * @description Manually disconnect from the connection, clearing autoconnect logic + */ + // eslint-disable-next-line @typescript-eslint/require-await + public async disconnect (): Promise { + try { + assert(!isNull(this.#websocket), 'Cannot disconnect on a non-connected websocket'); + + // switch off autoConnect, we are in manual mode now + this.#autoConnectMs = 0; + + // 1000 - Normal closure; the connection successfully completed + this.#websocket.close(1000); + this.#websocket = null; + } catch (error) { + l.error(error); + + this.#emit('error', error); + + throw error; + } + } + + /** + * @summary Listens on events after having subscribed using the [[subscribe]] function. + * @param {ProviderInterfaceEmitted} type Event + * @param {ProviderInterfaceEmitCb} sub Callback + * @return unsubscribe function + */ + public on (type: ProviderInterfaceEmitted, sub: ProviderInterfaceEmitCb): () => void { + this.#eventemitter.on(type, sub); + + return (): void => { + this.#eventemitter.removeListener(type, sub); + }; + } + + /** + * @summary Send JSON data using WebSockets to configured HTTP Endpoint or queue. + * @param method The RPC methods to execute + * @param params Encoded paramaters as appliucable for the method + * @param subscription Subscription details (internally used) + */ + public send (method: string, params: any[], subscription?: SubscriptionHandler): Promise { + return new Promise((resolve, reject): void => { + try { + const json = this.#coder.encodeJson(method, params); + const id = this.#coder.getId(); + + const callback = (error?: Error | null, result?: any): void => { + error + ? reject(error) + : resolve(result); + }; + + l.debug((): string[] => ['calling', method, json]); + + this.#handlers[id] = { + callback, + method, + params, + subscription + }; + + if (this.isConnected && !isNull(this.#websocket)) { + this.#websocket.send(json); + } else { + this.#queued[id] = json; + } + } catch (error) { + reject(error); + } + }); + } + + /** + * @name subscribe + * @summary Allows subscribing to a specific event. + * @param {string} type Subscription type + * @param {string} method Subscription method + * @param {any[]} params Parameters + * @param {ProviderInterfaceCallback} callback Callback + * @return {Promise} Promise resolving to the dd of the subscription you can use with [[unsubscribe]]. + * + * @example + *
+ * + * ```javascript + * const provider = new WsProvider('ws://127.0.0.1:9944'); + * const rpc = new Rpc(provider); + * + * rpc.state.subscribeStorage([[storage.system.account,
]], (_, values) => { + * console.log(values) + * }).then((subscriptionId) => { + * console.log('balance changes subscription id: ', subscriptionId) + * }) + * ``` + */ + public async subscribe (type: string, method: string, params: any[], callback: ProviderInterfaceCallback): Promise { + const id = await this.send(method, params, { callback, type }) as Promise; + + return id; + } + + /** + * @summary Allows unsubscribing to subscriptions made with [[subscribe]]. + */ + public async unsubscribe (type: string, method: string, id: number | string): Promise { + const subscription = `${type}::${id}`; + + // FIXME This now could happen with re-subscriptions. The issue is that with a re-sub + // the assigned id now does not match what the API user originally received. It has + // a slight complication in solving - since we cannot rely on the send id, but rather + // need to find the actual subscription id to map it + if (isUndefined(this.#subscriptions[subscription])) { + l.debug((): string => `Unable to find active subscription=${subscription}`); + + return false; + } + + delete this.#subscriptions[subscription]; + + const result = await this.send(method, [id]) as Promise; + + return result; + } + + #emit = (type: ProviderInterfaceEmitted, ...args: any[]): void => { + this.#eventemitter.emit(type, ...args); + } + + #onSocketClose = (event: CloseEvent): void => { + if (this.#autoConnectMs > 0) { + l.error(`disconnected from ${this.#endpoints[this.#endpointIndex]}: ${event.code}:: ${event.reason || getWSErrorString(event.code)}`); + } + + this.#isConnected = false; + this.#emit('disconnected'); + + if (this.#autoConnectMs > 0) { + setTimeout((): void => { + this.connectWithRetry().catch(() => { + // does not throw + }); + }, this.#autoConnectMs); + } + } + + #onSocketError = (error: Event): void => { + l.debug((): any => ['socket error', error]); + this.#emit('error', error); + } + + #onSocketMessage = (message: MessageEvent): void => { + // eslint-disable-next-line @typescript-eslint/no-unsafe-return + l.debug(() => ['received', message.data]); + + const response = JSON.parse(message.data as string) as JsonRpcResponse; + + return isUndefined(response.method) + ? this.#onSocketMessageResult(response) + : this.#onSocketMessageSubscribe(response); + } + + #onSocketMessageResult = (response: JsonRpcResponse): void => { + const handler = this.#handlers[response.id]; + + if (!handler) { + l.debug((): string => `Unable to find handler for id=${response.id}`); + + return; + } + + try { + const { method, params, subscription } = handler; + const result = this.#coder.decodeResponse(response) as string; + + // first send the result - in case of subs, we may have an update + // immediately if we have some queued results already + handler.callback(null, result); + + if (subscription) { + const subId = `${subscription.type}::${result}`; + + this.#subscriptions[subId] = { + ...subscription, + method, + params + }; + + // if we have a result waiting for this subscription already + if (this.#waitingForId[subId]) { + this.#onSocketMessageSubscribe(this.#waitingForId[subId]); + } + } + } catch (error) { + handler.callback(error, undefined); + } + + delete this.#handlers[response.id]; + } + + #onSocketMessageSubscribe = (response: JsonRpcResponse): void => { + const method = ALIASSES[response.method as string] || response.method || 'invalid'; + const subId = `${method}::${response.params.subscription}`; + const handler = this.#subscriptions[subId]; + + if (!handler) { + // store the JSON, we could have out-of-order subid coming in + this.#waitingForId[subId] = response; + + l.debug((): string => `Unable to find handler for subscription=${subId}`); + + return; + } + + // housekeeping + delete this.#waitingForId[subId]; + + try { + const result = this.#coder.decodeResponse(response); + + handler.callback(null, result); + } catch (error) { + handler.callback(error, undefined); + } + } + + #onSocketOpen = (): boolean => { + assert(!isNull(this.#websocket), 'WebSocket cannot be null in onOpen'); + + l.debug((): any[] => ['connected to', this.#endpoints[this.#endpointIndex]]); + + this.#isConnected = true; + + this.#emit('connected'); + this.#sendQueue(); + this.#resubscribe(); + + return true; + } + + #resubscribe = (): void => { + const subscriptions = this.#subscriptions; + + this.#subscriptions = {}; + + // eslint-disable-next-line @typescript-eslint/no-misused-promises + Object.keys(subscriptions).forEach(async (id): Promise => { + const { callback, method, params, type } = subscriptions[id]; + + // only re-create subscriptions which are not in author (only area where + // transactions are created, i.e. submissions such as 'author_submitAndWatchExtrinsic' + // are not included (and will not be re-broadcast) + if (type.startsWith('author_')) { + return; + } + + try { + await this.subscribe(type, method, params, callback); + } catch (error) { + l.error(error); + } + }); + } + + #sendQueue = (): void => { + Object.keys(this.#queued).forEach((id): void => { + try { + // we have done the websocket check in onSocketOpen, if an issue, will catch it + (this.#websocket as WebSocket).send( + this.#queued[id] + ); + + delete this.#queued[id]; + } catch (error) { + l.error(error); + } + }); + } +} diff --git a/packages/rpc-provider/src/ws/onOpen.spec.ts b/packages/rpc-provider/src/ws/onOpen.spec.ts index 22fe008b55..f8e78cc716 100644 --- a/packages/rpc-provider/src/ws/onOpen.spec.ts +++ b/packages/rpc-provider/src/ws/onOpen.spec.ts @@ -4,7 +4,7 @@ import { Mock } from './../mock/types'; import { mockWs, TEST_WS_URL } from '../../test/mockWs'; -import WsProvider from './'; +import { WsProvider } from './'; let ws: WsProvider; let mock: Mock; diff --git a/packages/rpc-provider/src/ws/send.spec.ts b/packages/rpc-provider/src/ws/send.spec.ts index dbde3b4038..2eb8331d69 100644 --- a/packages/rpc-provider/src/ws/send.spec.ts +++ b/packages/rpc-provider/src/ws/send.spec.ts @@ -6,7 +6,7 @@ import { Constructor } from '@polkadot/types/types'; import { Global, Mock } from './../mock/types'; import { mockWs, TEST_WS_URL } from '../../test/mockWs'; -import WsProvider from './'; +import { WsProvider } from './'; declare const global: Global; diff --git a/packages/rpc-provider/src/ws/state.spec.ts b/packages/rpc-provider/src/ws/state.spec.ts index 97365ce5a0..ce4c5f1fbf 100644 --- a/packages/rpc-provider/src/ws/state.spec.ts +++ b/packages/rpc-provider/src/ws/state.spec.ts @@ -1,7 +1,7 @@ // Copyright 2017-2020 @polkadot/rpc-provider authors & contributors // SPDX-License-Identifier: Apache-2.0 -import WsProvider from './'; +import { WsProvider } from './'; describe('state', (): void => { it('requires an ws:// prefixed endpoint', (): void => { diff --git a/packages/rpc-provider/src/ws/subscribe.spec.ts b/packages/rpc-provider/src/ws/subscribe.spec.ts index 7036d2bbfa..fcb416dd05 100644 --- a/packages/rpc-provider/src/ws/subscribe.spec.ts +++ b/packages/rpc-provider/src/ws/subscribe.spec.ts @@ -6,7 +6,7 @@ import { Constructor } from '@polkadot/types/types'; import { Global, Mock } from './../mock/types'; import { mockWs, TEST_WS_URL } from '../../test/mockWs'; -import WsProvider from './'; +import { WsProvider } from './'; declare const global: Global; diff --git a/packages/rpc-provider/src/ws/unsubscribe.spec.ts b/packages/rpc-provider/src/ws/unsubscribe.spec.ts index 8abf9ade69..36d9d6374a 100644 --- a/packages/rpc-provider/src/ws/unsubscribe.spec.ts +++ b/packages/rpc-provider/src/ws/unsubscribe.spec.ts @@ -6,7 +6,7 @@ import { Constructor } from '@polkadot/types/types'; import { Global, Mock } from './../mock/types'; import { mockWs, TEST_WS_URL } from '../../test/mockWs'; -import WsProvider from './'; +import { WsProvider } from './'; declare const global: Global; diff --git a/packages/typegen/package.json b/packages/typegen/package.json index 58a427b4aa..ef195d440e 100644 --- a/packages/typegen/package.json +++ b/packages/typegen/package.json @@ -42,7 +42,7 @@ "@polkadot/metadata": "2.6.2-0", "@polkadot/rpc-provider": "2.6.2-0", "@polkadot/types": "2.6.2-0", - "@polkadot/util": "^4.0.1", + "@polkadot/util": "^4.0.2-5", "handlebars": "^4.7.6", "websocket": "^1.0.32", "yargs": "^16.1.0" diff --git a/packages/typegen/src/generate/consts.ts b/packages/typegen/src/generate/consts.ts index f39f31e4b1..acde9cd8b1 100644 --- a/packages/typegen/src/generate/consts.ts +++ b/packages/typegen/src/generate/consts.ts @@ -4,7 +4,7 @@ import Handlebars from 'handlebars'; import staticData from '@polkadot/metadata/static'; -import Metadata from '@polkadot/metadata'; +import { Metadata } from '@polkadot/metadata'; import { TypeRegistry } from '@polkadot/types/create'; import * as defaultDefs from '@polkadot/types/interfaces/definitions'; import { stringCamelCase } from '@polkadot/util'; diff --git a/packages/typegen/src/generate/query.ts b/packages/typegen/src/generate/query.ts index 75e3737988..e7be5112d1 100644 --- a/packages/typegen/src/generate/query.ts +++ b/packages/typegen/src/generate/query.ts @@ -7,7 +7,7 @@ import { StorageEntryMetadataLatest } from '@polkadot/types/interfaces/metadata' import { Registry } from '@polkadot/types/types'; import staticData from '@polkadot/metadata/static'; -import Metadata from '@polkadot/metadata'; +import { Metadata } from '@polkadot/metadata'; import * as defaultDefs from '@polkadot/types/interfaces/definitions'; import { unwrapStorageType } from '@polkadot/types/primitive/StorageKey'; import { TypeRegistry } from '@polkadot/types/create'; diff --git a/packages/typegen/src/generate/tx.ts b/packages/typegen/src/generate/tx.ts index fec4611fc5..bffd346542 100644 --- a/packages/typegen/src/generate/tx.ts +++ b/packages/typegen/src/generate/tx.ts @@ -6,7 +6,7 @@ import Handlebars from 'handlebars'; import { Registry } from '@polkadot/types/types'; import staticData from '@polkadot/metadata/static'; -import Metadata from '@polkadot/metadata'; +import { Metadata } from '@polkadot/metadata'; import * as defaultDefs from '@polkadot/types/interfaces/definitions'; import { Text } from '@polkadot/types/primitive'; import { TypeRegistry } from '@polkadot/types/create'; diff --git a/packages/typegen/src/metadataMd.ts b/packages/typegen/src/metadataMd.ts index 64f13d4cb2..c52dff9693 100644 --- a/packages/typegen/src/metadataMd.ts +++ b/packages/typegen/src/metadataMd.ts @@ -5,7 +5,7 @@ import { MetadataLatest } from '@polkadot/types/interfaces/metadata'; import { Codec, DefinitionRpcParam } from '@polkadot/types/types'; import fs from 'fs'; -import Metadata from '@polkadot/metadata'; +import { Metadata } from '@polkadot/metadata'; import rpcdata from '@polkadot/metadata/static'; import Call from '@polkadot/types/generic/Call'; import { unwrapStorageType } from '@polkadot/types/primitive/StorageKey'; diff --git a/packages/types-known/package.json b/packages/types-known/package.json index 60e6d2a04a..3c09cb6710 100644 --- a/packages/types-known/package.json +++ b/packages/types-known/package.json @@ -30,7 +30,7 @@ "dependencies": { "@babel/runtime": "^7.12.1", "@polkadot/types": "2.6.2-0", - "@polkadot/util": "^4.0.1", + "@polkadot/util": "^4.0.2-5", "bn.js": "^5.1.3" }, "devDependencies": { diff --git a/packages/types/package.json b/packages/types/package.json index 0f06165052..a9a65dac7c 100644 --- a/packages/types/package.json +++ b/packages/types/package.json @@ -30,15 +30,15 @@ "dependencies": { "@babel/runtime": "^7.12.1", "@polkadot/metadata": "2.6.2-0", - "@polkadot/util": "^4.0.1", - "@polkadot/util-crypto": "^4.0.1", + "@polkadot/util": "^4.0.2-5", + "@polkadot/util-crypto": "^4.0.2-5", "@types/bn.js": "^4.11.6", "bn.js": "^5.1.3", "memoizee": "^0.4.14", "rxjs": "^6.6.3" }, "devDependencies": { - "@polkadot/keyring": "^4.0.1", + "@polkadot/keyring": "^4.0.2-5", "@types/memoizee": "^0.4.4" } } diff --git a/packages/types/src/codec/Compact.ts b/packages/types/src/codec/Compact.ts index 5b59105bad..6361c3636b 100644 --- a/packages/types/src/codec/Compact.ts +++ b/packages/types/src/codec/Compact.ts @@ -8,7 +8,7 @@ import BN from 'bn.js'; import { compactAddLength, compactFromU8a, compactStripLength, compactToU8a, isBigInt, isBn, isNumber, isString } from '@polkadot/util'; import { DEFAULT_BITLENGTH } from '@polkadot/util/compact/defaults'; -import typeToConstructor from './utils/typeToConstructor'; +import { typeToConstructor } from './utils'; import { UIntBitLength } from './AbstractInt'; export interface CompactEncodable extends Codec { diff --git a/packages/types/src/codec/Map.ts b/packages/types/src/codec/Map.ts index c5b94c5662..f14dcaaf7c 100644 --- a/packages/types/src/codec/Map.ts +++ b/packages/types/src/codec/Map.ts @@ -7,9 +7,7 @@ import { AnyJson, Constructor, Codec, InterfaceTypes, Registry } from '../types' import { isHex, hexToU8a, isObject, isU8a, logger, u8aConcat, u8aToHex, u8aToU8a } from '@polkadot/util'; import Compact from './Compact'; -import compareMap from './utils/compareMap'; -import decodeU8a from './utils/decodeU8a'; -import typeToConstructor from './utils/typeToConstructor'; +import { compareMap, decodeU8a, typeToConstructor } from './utils'; const l = logger('Map'); diff --git a/packages/types/src/codec/Tuple.spec.ts b/packages/types/src/codec/Tuple.spec.ts index a8771d569e..509798533d 100644 --- a/packages/types/src/codec/Tuple.spec.ts +++ b/packages/types/src/codec/Tuple.spec.ts @@ -5,7 +5,7 @@ import { VoteThreshold } from '../interfaces/elections'; import { BlockNumber } from '../interfaces/runtime'; import { CodecTo } from '../types'; -import Metadata from '@polkadot/metadata'; +import { Metadata } from '@polkadot/metadata'; import rpcMetadata from '@polkadot/metadata/static'; import { TypeRegistry } from '../create'; diff --git a/packages/types/src/codec/Vec.spec.ts b/packages/types/src/codec/Vec.spec.ts index 8595080a9b..9c8d7df857 100644 --- a/packages/types/src/codec/Vec.spec.ts +++ b/packages/types/src/codec/Vec.spec.ts @@ -4,7 +4,7 @@ import { PropIndex } from '../interfaces/democracy'; import { Codec, CodecTo } from '../types'; -import Metadata from '@polkadot/metadata'; +import { Metadata } from '@polkadot/metadata'; import rpcMetadata from '@polkadot/metadata/static'; import { createTypeUnsafe, TypeRegistry } from '../create'; diff --git a/packages/types/src/codec/utils/compareArray.spec.ts b/packages/types/src/codec/utils/compareArray.spec.ts index 7905938de6..e28bbbbad8 100644 --- a/packages/types/src/codec/utils/compareArray.spec.ts +++ b/packages/types/src/codec/utils/compareArray.spec.ts @@ -3,7 +3,7 @@ import { TypeRegistry } from '../../create'; import U32 from '../../primitive/U32'; -import compareArray from './compareArray'; +import { compareArray } from '.'; describe('compareArray', (): void => { const registry = new TypeRegistry(); diff --git a/packages/types/src/codec/utils/compareArray.ts b/packages/types/src/codec/utils/compareArray.ts index d1061619f9..320ea59880 100644 --- a/packages/types/src/codec/utils/compareArray.ts +++ b/packages/types/src/codec/utils/compareArray.ts @@ -7,7 +7,7 @@ import { hasEq } from './util'; // NOTE These are used internally and when comparing objects, expects that // when the second is an Codec[] that the first has to be as well -export default function compareArray (a: unknown[], b?: unknown): boolean { +export function compareArray (a: unknown[], b?: unknown): boolean { if (Array.isArray(b)) { return (a.length === b.length) && isUndefined( a.find((value, index): boolean => diff --git a/packages/types/src/codec/utils/compareMap.spec.ts b/packages/types/src/codec/utils/compareMap.spec.ts index e4ef36eaf5..bde300a558 100644 --- a/packages/types/src/codec/utils/compareMap.spec.ts +++ b/packages/types/src/codec/utils/compareMap.spec.ts @@ -4,7 +4,7 @@ import { Codec } from '../../types'; import { TypeRegistry } from '../../create'; import U32 from '../../primitive/U32'; -import compareMap from './compareMap'; +import { compareMap } from '.'; describe('compareMap', (): void => { const registry = new TypeRegistry(); diff --git a/packages/types/src/codec/utils/compareMap.ts b/packages/types/src/codec/utils/compareMap.ts index eeb66d789a..03c8b40563 100644 --- a/packages/types/src/codec/utils/compareMap.ts +++ b/packages/types/src/codec/utils/compareMap.ts @@ -26,7 +26,7 @@ function compareMapArray (a: Map, b: [any, any][]): boolean { // NOTE These are used internally and when comparing objects, expects that // when the second is an Map that the first has to be as well -export default function compareMap (a: Map, b?: unknown): boolean { +export function compareMap (a: Map, b?: unknown): boolean { if (Array.isArray(b)) { return compareMapArray(a, b); } else if (b instanceof Map) { diff --git a/packages/types/src/codec/utils/compareSet.ts b/packages/types/src/codec/utils/compareSet.ts index 2e9b89eb22..452e32ecd9 100644 --- a/packages/types/src/codec/utils/compareSet.ts +++ b/packages/types/src/codec/utils/compareSet.ts @@ -10,7 +10,7 @@ function compareSetArray (a: Set, b: any[]): boolean { // NOTE These are used internally and when comparing objects, expects that // when the second is an Set that the first has to be as well -export default function compareSet (a: Set, b?: unknown): boolean { +export function compareSet (a: Set, b?: unknown): boolean { if (Array.isArray(b)) { return compareSetArray(a, b); } else if (b instanceof Set) { diff --git a/packages/types/src/codec/utils/decodeU8a.ts b/packages/types/src/codec/utils/decodeU8a.ts index f36d661526..2895c1f676 100644 --- a/packages/types/src/codec/utils/decodeU8a.ts +++ b/packages/types/src/codec/utils/decodeU8a.ts @@ -10,7 +10,7 @@ import { Codec, Constructor, Registry } from '../../types'; * @param u8a - The u8a to decode. * @param types - The array of Constructor to decode the U8a against. */ -export default function decodeU8a (registry: Registry, u8a: Uint8Array, _types: Constructor[] | { [index: string]: Constructor }): Codec[] { +export function decodeU8a (registry: Registry, u8a: Uint8Array, _types: Constructor[] | { [index: string]: Constructor }): Codec[] { const types = Array.isArray(_types) ? _types : Object.values(_types); diff --git a/packages/types/src/codec/utils/index.ts b/packages/types/src/codec/utils/index.ts index f62904e6bd..81165735c5 100644 --- a/packages/types/src/codec/utils/index.ts +++ b/packages/types/src/codec/utils/index.ts @@ -1,11 +1,11 @@ // Copyright 2017-2020 @polkadot/types authors & contributors // SPDX-License-Identifier: Apache-2.0 -export { default as compareArray } from './compareArray'; -export { default as compareMap } from './compareMap'; -export { default as compareSet } from './compareSet'; -export { default as decodeU8a } from './decodeU8a'; -export { default as mapToTypeMap } from './mapToTypeMap'; -export { default as typeToConstructor } from './typeToConstructor'; +export { compareArray } from './compareArray'; +export { compareMap } from './compareMap'; +export { compareSet } from './compareSet'; +export { decodeU8a } from './decodeU8a'; +export { mapToTypeMap } from './mapToTypeMap'; +export { typeToConstructor } from './typeToConstructor'; export * from './encodeTypes'; diff --git a/packages/types/src/codec/utils/mapToTypeMap.ts b/packages/types/src/codec/utils/mapToTypeMap.ts index 8356cfeed1..ddf5afec81 100644 --- a/packages/types/src/codec/utils/mapToTypeMap.ts +++ b/packages/types/src/codec/utils/mapToTypeMap.ts @@ -3,12 +3,12 @@ import { Constructor, InterfaceTypes, Registry } from '../../types'; -import typeToConstructor from './typeToConstructor'; +import { typeToConstructor } from './typeToConstructor'; /** * @description takes an input map of the form `{ [string]: string | Constructor }` and returns a map of `{ [string]: Constructor }` */ -export default function mapToTypeMap (registry: Registry, input: Record): Record { +export function mapToTypeMap (registry: Registry, input: Record): Record { return Object .entries(input) .reduce((output: Record, [key, type]): Record => { diff --git a/packages/types/src/codec/utils/typeToConstructor.ts b/packages/types/src/codec/utils/typeToConstructor.ts index 3b96a040c9..0e5631fb2d 100644 --- a/packages/types/src/codec/utils/typeToConstructor.ts +++ b/packages/types/src/codec/utils/typeToConstructor.ts @@ -5,7 +5,7 @@ import { Codec, Constructor, InterfaceTypes, Registry } from '../../types'; import { isString } from '@polkadot/util'; -export default function typeToConstructor (registry: Registry, type: keyof InterfaceTypes | Constructor): Constructor { +export function typeToConstructor (registry: Registry, type: keyof InterfaceTypes | Constructor): Constructor { return ( isString(type) ? registry.createClass(type) diff --git a/packages/types/src/ethereum/AccountId.spec.ts b/packages/types/src/ethereum/AccountId.spec.ts index 493ab38021..58bf6a1308 100644 --- a/packages/types/src/ethereum/AccountId.spec.ts +++ b/packages/types/src/ethereum/AccountId.spec.ts @@ -5,7 +5,7 @@ import { TypeRegistry } from '../create'; import Raw from '../codec/Raw'; -import AccountId from './AccountId'; +import { GenericEthereumAccountId as AccountId } from './AccountId'; describe('EthereumAccountId', (): void => { const registry = new TypeRegistry(); diff --git a/packages/types/src/ethereum/AccountId.ts b/packages/types/src/ethereum/AccountId.ts index 7780666a96..b212753dd0 100644 --- a/packages/types/src/ethereum/AccountId.ts +++ b/packages/types/src/ethereum/AccountId.ts @@ -22,13 +22,13 @@ function decodeAccountId (value: AnyU8a | AnyString): AnyU8a { } /** - * @name EthereumAccountId + * @name GenericEthereumAccountId * @description * A wrapper around an Ethereum-compatible AccountId. Since we are dealing with * underlying addresses (20 bytes in length), we extend from U8aFixed which is * just a Uint8Array wrapper with a fixed length. */ -export default class AccountId extends U8aFixed { +export class GenericEthereumAccountId extends U8aFixed { constructor (registry: Registry, value: AnyU8a = new Uint8Array()) { super(registry, decodeAccountId(value), 160); } @@ -62,7 +62,7 @@ export default class AccountId extends U8aFixed { * @description Returns the string representation of the value */ public toString (): string { - return AccountId.encode(this); + return GenericEthereumAccountId.encode(this); } /** diff --git a/packages/types/src/ethereum/LookupSource.spec.ts b/packages/types/src/ethereum/LookupSource.spec.ts index 44d436070c..3e2e5a51fb 100644 --- a/packages/types/src/ethereum/LookupSource.spec.ts +++ b/packages/types/src/ethereum/LookupSource.spec.ts @@ -3,8 +3,7 @@ import { TypeRegistry } from '../create'; import AccountIndex from '../generic/AccountIndex'; -import AccountId from './AccountId'; -import Address from './LookupSource'; +import { GenericEthereumAccountId as AccountId, GenericEthereumLookupSource as Address } from '.'; describe('EthereumLookupSource', (): void => { const registry = new TypeRegistry(); diff --git a/packages/types/src/ethereum/LookupSource.ts b/packages/types/src/ethereum/LookupSource.ts index 93c176f870..7e946e7cf9 100644 --- a/packages/types/src/ethereum/LookupSource.ts +++ b/packages/types/src/ethereum/LookupSource.ts @@ -9,15 +9,15 @@ import { decodeAddress } from '@polkadot/util-crypto'; import Base from '../codec/Base'; import AccountIndex from '../generic/AccountIndex'; -import EthereumAccountId from './AccountId'; +import { GenericEthereumAccountId } from './AccountId'; // eslint-disable-next-line no-use-before-define -type AnyAddress = BigInt | BN | LookupSource | EthereumAccountId | AccountIndex | number[] | Uint8Array | number | string; +type AnyAddress = BigInt | BN | GenericEthereumLookupSource | GenericEthereumAccountId | AccountIndex | number[] | Uint8Array | number | string; export const ACCOUNT_ID_PREFIX = new Uint8Array([0xff]); /** @internal */ -function decodeString (registry: Registry, value: string): EthereumAccountId | AccountIndex { +function decodeString (registry: Registry, value: string): GenericEthereumAccountId | AccountIndex { const decoded = decodeAddress(value); return decoded.length === 20 @@ -26,7 +26,7 @@ function decodeString (registry: Registry, value: string): EthereumAccountId | A } /** @internal */ -function decodeU8a (registry: Registry, value: Uint8Array): EthereumAccountId | AccountIndex { +function decodeU8a (registry: Registry, value: Uint8Array): GenericEthereumAccountId | AccountIndex { // This allows us to instantiate an address with a raw publicKey. Do this first before // we checking the first byte, otherwise we may split an already-existent valid address if (value.length === 20) { @@ -41,23 +41,23 @@ function decodeU8a (registry: Registry, value: Uint8Array): EthereumAccountId | } /** - * @name LookupSource + * @name GenericEthereumLookupSource * @description * A wrapper around an EthereumAccountId and/or AccountIndex that is encoded with a prefix. * Since we are dealing with underlying publicKeys (or shorter encoded addresses), * we extend from Base with an AccountId/AccountIndex wrapper. Basically the Address * is encoded as `[ , ...publicKey/...bytes ]` as per spec */ -export default class LookupSource extends Base { +export class GenericEthereumLookupSource extends Base { constructor (registry: Registry, value: AnyAddress = new Uint8Array()) { - super(registry, LookupSource._decodeAddress(registry, value)); + super(registry, GenericEthereumLookupSource._decodeAddress(registry, value)); } /** @internal */ - private static _decodeAddress (registry: Registry, value: AnyAddress): EthereumAccountId | AccountIndex { - return value instanceof LookupSource + private static _decodeAddress (registry: Registry, value: AnyAddress): GenericEthereumAccountId | AccountIndex { + return value instanceof GenericEthereumLookupSource ? value._raw - : value instanceof EthereumAccountId || value instanceof AccountIndex + : value instanceof GenericEthereumAccountId || value instanceof AccountIndex ? value : isBn(value) || isNumber(value) || isBigInt(value) ? registry.createType('AccountIndex', value) diff --git a/packages/types/src/ethereum/index.ts b/packages/types/src/ethereum/index.ts index c59cae9be6..472f6f8f97 100644 --- a/packages/types/src/ethereum/index.ts +++ b/packages/types/src/ethereum/index.ts @@ -1,5 +1,5 @@ // Copyright 2017-2020 @polkadot/types authors & contributors // SPDX-License-Identifier: Apache-2.0 -export { default as GenericEthereumAccountId } from './AccountId'; -export { default as GenericEthereumLookupSource } from './LookupSource'; +export { GenericEthereumAccountId } from './AccountId'; +export { GenericEthereumLookupSource } from './LookupSource'; diff --git a/packages/types/src/extrinsic/Extrinsic.spec.ts b/packages/types/src/extrinsic/Extrinsic.spec.ts index d98d560568..778beb5ae9 100644 --- a/packages/types/src/extrinsic/Extrinsic.spec.ts +++ b/packages/types/src/extrinsic/Extrinsic.spec.ts @@ -1,11 +1,11 @@ // Copyright 2017-2020 @polkadot/types authors & contributors // SPDX-License-Identifier: Apache-2.0 -import Metadata from '@polkadot/metadata'; +import { Metadata } from '@polkadot/metadata'; import rpcMetadata from '@polkadot/metadata/static'; import { TypeRegistry } from '../create'; -import Extrinsic from './Extrinsic'; +import { GenericExtrinsic as Extrinsic } from '.'; const registry = new TypeRegistry(); const metadata = new Metadata(registry, rpcMetadata); diff --git a/packages/types/src/extrinsic/SignerPayload.spec.ts b/packages/types/src/extrinsic/SignerPayload.spec.ts index f318dc7d4d..63c65ab848 100644 --- a/packages/types/src/extrinsic/SignerPayload.spec.ts +++ b/packages/types/src/extrinsic/SignerPayload.spec.ts @@ -1,7 +1,7 @@ // Copyright 2017-2020 @polkadot/types authors & contributors // SPDX-License-Identifier: Apache-2.0 -import Metadata from '@polkadot/metadata'; +import { Metadata } from '@polkadot/metadata'; import rpcMetadata from '@polkadot/metadata/static'; import { TypeRegistry } from '../create'; diff --git a/packages/types/src/extrinsic/v4/Extrinsic.spec.ts b/packages/types/src/extrinsic/v4/Extrinsic.spec.ts index 304e8f1c36..1ed25042a2 100644 --- a/packages/types/src/extrinsic/v4/Extrinsic.spec.ts +++ b/packages/types/src/extrinsic/v4/Extrinsic.spec.ts @@ -2,8 +2,8 @@ // SPDX-License-Identifier: Apache-2.0 import BN from 'bn.js'; -import testingPairs from '@polkadot/keyring/testingPairs'; -import Metadata, { extrinsicsFromMeta } from '@polkadot/metadata'; +import { createTestPairs } from '@polkadot/keyring/testingPairs'; +import { Metadata, extrinsicsFromMeta } from '@polkadot/metadata'; import rpcMetadata from '@polkadot/metadata/static'; import { TypeRegistry } from '../../create'; @@ -11,7 +11,7 @@ import Extrinsic from './Extrinsic'; const registry = new TypeRegistry(); const metadata = new Metadata(registry, rpcMetadata); -const keyring = testingPairs({ type: 'ed25519' }, false); +const keyring = createTestPairs({ type: 'ed25519' }, false); registry.setMetadata(metadata); diff --git a/packages/types/src/generic/Block.spec.ts b/packages/types/src/generic/Block.spec.ts index 471a84201b..786aa05ee1 100644 --- a/packages/types/src/generic/Block.spec.ts +++ b/packages/types/src/generic/Block.spec.ts @@ -4,7 +4,7 @@ /* eslint-disable sort-keys */ /* eslint-disable @typescript-eslint/no-unsafe-member-access */ -import Metadata from '@polkadot/metadata'; +import { Metadata } from '@polkadot/metadata'; import metadataStatic from '@polkadot/metadata/static'; import { TypeRegistry } from '../create'; diff --git a/packages/types/src/generic/Call.spec.ts b/packages/types/src/generic/Call.spec.ts index 69663faf99..3f7c298fce 100644 --- a/packages/types/src/generic/Call.spec.ts +++ b/packages/types/src/generic/Call.spec.ts @@ -1,7 +1,7 @@ // Copyright 2017-2020 @polkadot/metadata authors & contributors // SPDX-License-Identifier: Apache-2.0 -import Metadata from '@polkadot/metadata'; +import { Metadata } from '@polkadot/metadata'; import metadataStatic from '@polkadot/metadata/static'; import { TypeRegistry } from '../create'; diff --git a/packages/types/src/index.spec.ts b/packages/types/src/index.spec.ts index 4d63feb87f..b07d10556e 100644 --- a/packages/types/src/index.spec.ts +++ b/packages/types/src/index.spec.ts @@ -1,7 +1,7 @@ // Copyright 2017-2020 @polkadot/types authors & contributors // SPDX-License-Identifier: Apache-2.0 -import Metadata from '@polkadot/metadata'; +import { Metadata } from '@polkadot/metadata'; import metadataStatic from '@polkadot/metadata/static'; import { createTypeUnsafe, TypeRegistry } from './create'; diff --git a/packages/types/src/index.types.ts b/packages/types/src/index.types.ts index 492a66b993..0e2c845813 100644 --- a/packages/types/src/index.types.ts +++ b/packages/types/src/index.types.ts @@ -1,7 +1,7 @@ // Copyright 2017-2020 @polkadot/types authors & contributors // SPDX-License-Identifier: Apache-2.0 -export { default as Metadata } from '@polkadot/metadata'; +export { Metadata } from '@polkadot/metadata'; export * from './extrinsic'; export * from './generic'; diff --git a/packages/types/src/interfaces/system/EventRecord.spec.ts b/packages/types/src/interfaces/system/EventRecord.spec.ts index 52c988201a..384613ca18 100644 --- a/packages/types/src/interfaces/system/EventRecord.spec.ts +++ b/packages/types/src/interfaces/system/EventRecord.spec.ts @@ -4,7 +4,7 @@ /* eslint-disable @typescript-eslint/no-unsafe-assignment */ /* eslint-disable @typescript-eslint/no-unsafe-member-access */ -import Metadata from '@polkadot/metadata'; +import { Metadata } from '@polkadot/metadata'; import rpcMetadata from '@polkadot/metadata/static'; import { TypeRegistry } from '../../create'; diff --git a/packages/types/src/primitive/StorageKey.spec.ts b/packages/types/src/primitive/StorageKey.spec.ts index c607982ef1..7ec4ded492 100644 --- a/packages/types/src/primitive/StorageKey.spec.ts +++ b/packages/types/src/primitive/StorageKey.spec.ts @@ -1,7 +1,7 @@ // Copyright 2017-2020 @polkadot/types authors & contributors // SPDX-License-Identifier: Apache-2.0 -import Metadata, { storageFromMeta } from '@polkadot/metadata'; +import { Metadata, storageFromMeta } from '@polkadot/metadata'; import rpcDataV11 from '@polkadot/metadata/v11/static'; import { TypeRegistry } from '../create'; diff --git a/yarn.lock b/yarn.lock index 731e9a3585..f1cafdc8fc 100644 --- a/yarn.lock +++ b/yarn.lock @@ -1753,7 +1753,7 @@ __metadata: "@babel/runtime": ^7.12.1 "@polkadot/api": 2.6.2-0 "@polkadot/types": 2.6.2-0 - "@polkadot/util": ^4.0.1 + "@polkadot/util": ^4.0.2-5 bn.js: ^5.1.3 rxjs: ^6.6.3 languageName: unknown @@ -1765,12 +1765,12 @@ __metadata: dependencies: "@babel/runtime": ^7.12.1 "@polkadot/api": 2.6.2-0 - "@polkadot/keyring": ^4.0.1 + "@polkadot/keyring": ^4.0.2-5 "@polkadot/rpc-core": 2.6.2-0 "@polkadot/rpc-provider": 2.6.2-0 "@polkadot/types": 2.6.2-0 - "@polkadot/util": ^4.0.1 - "@polkadot/util-crypto": ^4.0.1 + "@polkadot/util": ^4.0.2-5 + "@polkadot/util-crypto": ^4.0.2-5 bn.js: ^5.1.3 memoizee: ^0.4.14 rxjs: ^6.6.3 @@ -1783,14 +1783,14 @@ __metadata: dependencies: "@babel/runtime": ^7.12.1 "@polkadot/api-derive": 2.6.2-0 - "@polkadot/keyring": ^4.0.1 + "@polkadot/keyring": ^4.0.2-5 "@polkadot/metadata": 2.6.2-0 "@polkadot/rpc-core": 2.6.2-0 "@polkadot/rpc-provider": 2.6.2-0 "@polkadot/types": 2.6.2-0 "@polkadot/types-known": 2.6.2-0 - "@polkadot/util": ^4.0.1 - "@polkadot/util-crypto": ^4.0.1 + "@polkadot/util": ^4.0.2-5 + "@polkadot/util-crypto": ^4.0.2-5 bn.js: ^5.1.3 eventemitter3: ^4.0.7 rxjs: ^6.6.3 @@ -1889,17 +1889,17 @@ __metadata: languageName: node linkType: hard -"@polkadot/keyring@npm:^4.0.1": - version: 4.0.1 - resolution: "@polkadot/keyring@npm:4.0.1" +"@polkadot/keyring@npm:^4.0.2-5": + version: 4.0.2-5 + resolution: "@polkadot/keyring@npm:4.0.2-5" dependencies: "@babel/runtime": ^7.12.1 - "@polkadot/util": 4.0.1 - "@polkadot/util-crypto": 4.0.1 + "@polkadot/util": 4.0.2-5 + "@polkadot/util-crypto": 4.0.2-5 peerDependencies: - "@polkadot/util": 4.0.1 - "@polkadot/util-crypto": 4.0.1 - checksum: 2fc0c101b6c24ca60dd6cad59084ab79a7d308bb4e078012f8c31489789de53c198f73fb2f6ab09d712a332d31c28497906f01cd7d4847e8140cc38f5e310d5d + "@polkadot/util": 4.0.2-5 + "@polkadot/util-crypto": 4.0.2-5 + checksum: 2bb9a76f28f582f410ca5703430be43e99b01c7384a3ddc7511020506fb2a7440739534d804e4a3bedaaf3ce89969670a12398ffe8e6ec8c74cb1a65219870f5 languageName: node linkType: hard @@ -1908,21 +1908,21 @@ __metadata: resolution: "@polkadot/metadata@workspace:packages/metadata" dependencies: "@babel/runtime": ^7.12.1 - "@polkadot/keyring": ^4.0.1 + "@polkadot/keyring": ^4.0.2-5 "@polkadot/types": 2.6.2-0 "@polkadot/types-known": 2.6.2-0 - "@polkadot/util": ^4.0.1 - "@polkadot/util-crypto": ^4.0.1 + "@polkadot/util": ^4.0.2-5 + "@polkadot/util-crypto": ^4.0.2-5 bn.js: ^5.1.3 languageName: unknown linkType: soft -"@polkadot/networks@npm:4.0.1": - version: 4.0.1 - resolution: "@polkadot/networks@npm:4.0.1" +"@polkadot/networks@npm:4.0.2-5": + version: 4.0.2-5 + resolution: "@polkadot/networks@npm:4.0.2-5" dependencies: "@babel/runtime": ^7.12.1 - checksum: 46f0bdba3a9a6a7649645944dbac4c0e88e5b15c3d25cc13a71a91440bba179c3233cdbb99b3359fe230ff396666315d50aab6248f851748491c77ebc0568e97 + checksum: 80bcdd6983e74e507bab734a78323b3706ebf470fc56109dcaf248dc9a13797818320d985ce4cf6cd91edcba086e55e2f6671163112ae899dd9b010859713ecd languageName: node linkType: hard @@ -1931,11 +1931,11 @@ __metadata: resolution: "@polkadot/rpc-core@workspace:packages/rpc-core" dependencies: "@babel/runtime": ^7.12.1 - "@polkadot/keyring": ^4.0.1 + "@polkadot/keyring": ^4.0.2-5 "@polkadot/metadata": 2.6.2-0 "@polkadot/rpc-provider": 2.6.2-0 "@polkadot/types": 2.6.2-0 - "@polkadot/util": ^4.0.1 + "@polkadot/util": ^4.0.2-5 memoizee: ^0.4.14 rxjs: ^6.6.3 languageName: unknown @@ -1946,13 +1946,13 @@ __metadata: resolution: "@polkadot/rpc-provider@workspace:packages/rpc-provider" dependencies: "@babel/runtime": ^7.12.1 - "@polkadot/keyring": ^4.0.1 + "@polkadot/keyring": ^4.0.2-5 "@polkadot/metadata": 2.6.2-0 "@polkadot/types": 2.6.2-0 - "@polkadot/util": ^4.0.1 - "@polkadot/util-crypto": ^4.0.1 - "@polkadot/x-fetch": ^4.0.1 - "@polkadot/x-ws": ^4.0.1 + "@polkadot/util": ^4.0.2-5 + "@polkadot/util-crypto": ^4.0.2-5 + "@polkadot/x-fetch": ^4.0.2-5 + "@polkadot/x-ws": ^4.0.2-5 bn.js: ^5.1.3 eventemitter3: ^4.0.7 mock-socket: ^9.0.3 @@ -1980,7 +1980,7 @@ __metadata: "@polkadot/metadata": 2.6.2-0 "@polkadot/rpc-provider": 2.6.2-0 "@polkadot/types": 2.6.2-0 - "@polkadot/util": ^4.0.1 + "@polkadot/util": ^4.0.2-5 "@types/websocket": ^1.0.1 "@types/yargs": ^15.0.9 handlebars: ^4.7.6 @@ -2001,7 +2001,7 @@ __metadata: dependencies: "@babel/runtime": ^7.12.1 "@polkadot/types": 2.6.2-0 - "@polkadot/util": ^4.0.1 + "@polkadot/util": ^4.0.2-5 "@types/bn.js": ^4.11.6 bn.js: ^5.1.3 languageName: unknown @@ -2012,10 +2012,10 @@ __metadata: resolution: "@polkadot/types@workspace:packages/types" dependencies: "@babel/runtime": ^7.12.1 - "@polkadot/keyring": ^4.0.1 + "@polkadot/keyring": ^4.0.2-5 "@polkadot/metadata": 2.6.2-0 - "@polkadot/util": ^4.0.1 - "@polkadot/util-crypto": ^4.0.1 + "@polkadot/util": ^4.0.2-5 + "@polkadot/util-crypto": ^4.0.2-5 "@types/bn.js": ^4.11.6 "@types/memoizee": ^0.4.4 bn.js: ^5.1.3 @@ -2024,43 +2024,44 @@ __metadata: languageName: unknown linkType: soft -"@polkadot/util-crypto@npm:4.0.1, @polkadot/util-crypto@npm:^4.0.1": - version: 4.0.1 - resolution: "@polkadot/util-crypto@npm:4.0.1" +"@polkadot/util-crypto@npm:4.0.2-5, @polkadot/util-crypto@npm:^4.0.2-5": + version: 4.0.2-5 + resolution: "@polkadot/util-crypto@npm:4.0.2-5" dependencies: "@babel/runtime": ^7.12.1 - "@polkadot/networks": 4.0.1 - "@polkadot/util": 4.0.1 + "@polkadot/networks": 4.0.2-5 + "@polkadot/util": 4.0.2-5 "@polkadot/wasm-crypto": ^2.0.1 - "@polkadot/x-randomvalues": 4.0.1 + "@polkadot/x-randomvalues": 4.0.2-5 base-x: ^3.0.8 blakejs: ^1.1.0 bn.js: ^5.1.3 create-hash: ^1.2.0 elliptic: ^6.5.3 + hash.js: ^1.1.7 js-sha3: ^0.8.0 pbkdf2: ^3.1.1 scryptsy: ^2.1.0 tweetnacl: ^1.0.3 xxhashjs: ^0.2.2 peerDependencies: - "@polkadot/util": 4.0.1 - checksum: 8bb2f44d73e920a1a16eb7c3939c6fd6fb7d33a34844d9600a7b4e58ee67f0ac869b8877e262cec55063207fd0cf7754e49cdabe8c88c0c241ff3129fe315c35 + "@polkadot/util": 4.0.2-5 + checksum: 376ee7f9d1bd7daa5964b89b7b2b0f301feaee6d169302e405e15beefc6e2499f502425466ead1d8271bdb6e91522cf5330f7cd29390ddfeaf89d01acab34a63 languageName: node linkType: hard -"@polkadot/util@npm:4.0.1, @polkadot/util@npm:^4.0.1": - version: 4.0.1 - resolution: "@polkadot/util@npm:4.0.1" +"@polkadot/util@npm:4.0.2-5, @polkadot/util@npm:^4.0.2-5": + version: 4.0.2-5 + resolution: "@polkadot/util@npm:4.0.2-5" dependencies: "@babel/runtime": ^7.12.1 - "@polkadot/x-textdecoder": 4.0.1 - "@polkadot/x-textencoder": 4.0.1 + "@polkadot/x-textdecoder": 4.0.2-5 + "@polkadot/x-textencoder": 4.0.2-5 "@types/bn.js": ^4.11.6 bn.js: ^5.1.3 camelcase: ^5.3.1 ip-regex: ^4.2.0 - checksum: 316db22e9d63dd25f11e4339a769acb9f594dd134adb32d89805c576764a0b0d03e52467b61de410886308f14b819bd25034d2f6ca08f3abf53ba871e229d726 + checksum: be10c8f4c1a3953aaf432d96ad5f0117028bdb48ccd1eb4c3784f0cb24266de632ca8089644f066f37c1f3906845f58f7e7ddc6af6f3c15dfbcea961988f3bd8 languageName: node linkType: hard @@ -2074,52 +2075,52 @@ __metadata: languageName: node linkType: hard -"@polkadot/x-fetch@npm:^4.0.1": - version: 4.0.1 - resolution: "@polkadot/x-fetch@npm:4.0.1" +"@polkadot/x-fetch@npm:^4.0.2-5": + version: 4.0.2-5 + resolution: "@polkadot/x-fetch@npm:4.0.2-5" dependencies: "@babel/runtime": ^7.12.1 "@types/node-fetch": ^2.5.7 node-fetch: ^2.6.1 - checksum: d1aa6ede4df491c71af8fccbff032b80df27bbefff407aeea9db7bbf842012a75e2e66ceb57ea2ec733397f6188544a19fed509f693680cfb220fcdccb372ac6 + checksum: b2fdbd5acdf1dce705a083220cedd266457efa0bdc8a1bf49704fce9ca7e4f02738c76f3d7f25e3c453641bd7006c6eea5ce5d0e57a8a57cb560f6feef480eb9 languageName: node linkType: hard -"@polkadot/x-randomvalues@npm:4.0.1": - version: 4.0.1 - resolution: "@polkadot/x-randomvalues@npm:4.0.1" +"@polkadot/x-randomvalues@npm:4.0.2-5": + version: 4.0.2-5 + resolution: "@polkadot/x-randomvalues@npm:4.0.2-5" dependencies: "@babel/runtime": ^7.12.1 - checksum: 819d8fcb30ada53a588adf4fbb947ec76ce6a72d2ea5b67d85f7ece105dc3734a0afa345e963af80c8c08f91f3248a807e7229f4649179be88e6717d49f14056 + checksum: ec895fc243bafd913818caa5f205c0a644d23ddfb1716296454869f6dc5859ab52b4d3af46fe45c0d92be7f19f21a7533e961109a2f5b18b3d345a07c5282d53 languageName: node linkType: hard -"@polkadot/x-textdecoder@npm:4.0.1": - version: 4.0.1 - resolution: "@polkadot/x-textdecoder@npm:4.0.1" +"@polkadot/x-textdecoder@npm:4.0.2-5": + version: 4.0.2-5 + resolution: "@polkadot/x-textdecoder@npm:4.0.2-5" dependencies: "@babel/runtime": ^7.12.1 - checksum: f12ef770f02756600ced9e35cd8c239f5ffef231f71b39b4f12854f0a64cc154e55dd344ddcbcfca0fb587c24bc0920bfb0288c8dabf27f2a5d317c67eee3eeb + checksum: 2d9b4192338b1dd1a7b64c9b3a64302dd22039bd5245434c8dd8ba64332ffcc8ae833431791127644c2911d5c9397d361db488642898c1f033719924c8b022ec languageName: node linkType: hard -"@polkadot/x-textencoder@npm:4.0.1": - version: 4.0.1 - resolution: "@polkadot/x-textencoder@npm:4.0.1" +"@polkadot/x-textencoder@npm:4.0.2-5": + version: 4.0.2-5 + resolution: "@polkadot/x-textencoder@npm:4.0.2-5" dependencies: "@babel/runtime": ^7.12.1 - checksum: 045f1b2b8671c9b75a0144dd373714c12d386fa66c490de5ebd1abfd195b162972db63149376a8838f8626d55aeebd8b2f71c5795157e4009d6be1854cf6c226 + checksum: fda2c245f7f5413df6f48fb052f6b36484c0942837017707047891959600d327041abb997067fe009d88891541ceabe3a63a9c0076957e2efbc69446a45b87e9 languageName: node linkType: hard -"@polkadot/x-ws@npm:^4.0.1": - version: 4.0.1 - resolution: "@polkadot/x-ws@npm:4.0.1" +"@polkadot/x-ws@npm:^4.0.2-5": + version: 4.0.2-5 + resolution: "@polkadot/x-ws@npm:4.0.2-5" dependencies: "@babel/runtime": ^7.12.1 "@types/websocket": ^1.0.1 websocket: ^1.0.32 - checksum: f48b366856625a450d13a9bffeba53d2ab592efc939249a223cb68a45c7ae2d50490f6b28501be87e2d35933c9890ba2e2a3510188c9b5916b43ca5c2baa8b65 + checksum: 2be445d505d4d7f79734d64248b202d58c9f8ffd2e21f0360094d3f2026721eec8566e6c8e6cb166ef135ae461c5bb2bcf195c76b1fa503d460d5a94085f18aa languageName: node linkType: hard @@ -5808,7 +5809,7 @@ fsevents@^1.2.7: languageName: node linkType: hard -"hash.js@npm:^1.0.0, hash.js@npm:^1.0.3": +"hash.js@npm:^1.0.0, hash.js@npm:^1.0.3, hash.js@npm:^1.1.7": version: 1.1.7 resolution: "hash.js@npm:1.1.7" dependencies: