From e9b0ead596e63c2ea19e9f5f58815e643a94fd84 Mon Sep 17 00:00:00 2001 From: Jaco Greeff Date: Sat, 10 Aug 2019 11:01:30 +0200 Subject: [PATCH 01/11] Lazily create registry types (also solves resolution order) --- packages/api/src/Base.ts | 8 ++++ packages/types/src/codec/TypeRegistry.spec.ts | 7 ++- packages/types/src/codec/createType.ts | 8 ++-- packages/types/src/codec/typeRegistry.ts | 46 ++++++++++++------- packages/types/src/index.types.ts | 3 -- packages/types/src/injector.ts | 14 ++++-- 6 files changed, 55 insertions(+), 31 deletions(-) diff --git a/packages/api/src/Base.ts b/packages/api/src/Base.ts index b4f1747c35aa..c98863731bbd 100644 --- a/packages/api/src/Base.ts +++ b/packages/api/src/Base.ts @@ -582,6 +582,14 @@ export default abstract class ApiBase { getTypeRegistry().register({ Keys: 'SessionKeysPolkadot' }); } + // FIXME This is absolutely NOT the right place and the check is not 100% - + // however, I need to get this working, today. So basically, when we detect + // a v1 extrinsic, we assume that we are dealing win an ancient 1.x chain, so + // setup the overrides. TL;DR This is an even bigger HACK than the NOTE above + if (this._extrinsicType === 1) { + getTypeRegistry().register({ EventRecord: 'EventRecord0to76' }); + } + this._rx.extrinsicType = this._extrinsicType; this._rx.genesisHash = this._genesisHash; this._rx.runtimeVersion = this._runtimeVersion; diff --git a/packages/types/src/codec/TypeRegistry.spec.ts b/packages/types/src/codec/TypeRegistry.spec.ts index fe73d53b20a4..22dbff5c6ec5 100644 --- a/packages/types/src/codec/TypeRegistry.spec.ts +++ b/packages/types/src/codec/TypeRegistry.spec.ts @@ -2,6 +2,8 @@ // This software may be modified and distributed under the terms // of the Apache-2.0 license. See the LICENSE file for details. +import '../injector'; + import { TypeRegistry } from './typeRegistry'; import Struct from '../codec/Struct'; import Text from '../primitive/Text'; @@ -42,7 +44,10 @@ describe('TypeRegistry', (): void => { registry.register({ U32Renamed: 'u32' }); - expect(registry.get('U32Renamed')).toBe(U32); + + const Type = registry.getOrThrow('U32Renamed'); + + expect(new Type() instanceof U32).toBe(true); }); it('can create structs via definition', (): void => { diff --git a/packages/types/src/codec/createType.ts b/packages/types/src/codec/createType.ts index 40e7f2f820ec..499715415b49 100644 --- a/packages/types/src/codec/createType.ts +++ b/packages/types/src/codec/createType.ts @@ -22,7 +22,7 @@ import U8aFixed, { BitLength as U8aFixedBitLength } from './U8aFixed'; import UInt from './UInt'; import Vec from './Vec'; import VecFixed from './VecFixed'; -import getRegistry from './typeRegistry'; +import getTypeRegistry from './typeRegistry'; // Type which says: if `K` is in the InterfaceRegistry, then return InterfaceRegistry[K], else fallback to T type FromReg = K extends keyof InterfaceRegistry ? InterfaceRegistry[K] : T @@ -181,9 +181,7 @@ const memoizedCreateClass = memoizee(> => { // eslint-disable-next-line @typescript-eslint/no-use-before-define - return getTypeClass>( - getTypeDef(type) - ); + return getTypeClass>(getTypeDef(type)); }, { length: 1 }); export function createClass ( @@ -216,7 +214,7 @@ export function getTypeClassMap (defs: TypeDef[]): { [index: string]: Constructo // Returns the type Class for construction export function getTypeClass (value: TypeDef, Fallback?: Constructor): Constructor { - const Type = getRegistry().get(value.type); + const Type = getTypeRegistry().get(value.type); if (Type) { return Type; diff --git a/packages/types/src/codec/typeRegistry.ts b/packages/types/src/codec/typeRegistry.ts index a9ea91a5d9b6..236dfe1da157 100644 --- a/packages/types/src/codec/typeRegistry.ts +++ b/packages/types/src/codec/typeRegistry.ts @@ -2,14 +2,17 @@ // This software may be modified and distributed under the terms // of the Apache-2.0 license. See the LICENSE file for details. +import { Codec, Constructor, RegistryTypes } from '../types'; + import { isFunction, isString, isUndefined } from '@polkadot/util'; -import { Codec, Constructor, RegistryTypes } from '../types'; import { createClass } from './createType'; export class TypeRegistry { public static readonly defaultRegistry: TypeRegistry = new TypeRegistry(); + private _definitions: Map = new Map(); + private _registry: Map = new Map(); public register (type: Constructor | RegistryTypes): void; @@ -37,20 +40,39 @@ export class TypeRegistry { private registerObject (obj: RegistryTypes, overwrite: boolean = true): void { Object.entries(obj).forEach(([name, type]): void => { if (overwrite || !this.get(name)) { - if (isString(type)) { - this._registry.set(name, createClass(type)); - } else if (isFunction(type)) { + if (isFunction(type)) { // This _looks_ a bit funny, but `typeof Clazz === 'function' this._registry.set(name, type); } else { - this._registry.set(name, createClass(JSON.stringify(type))); + // we want to lazy create this one lazily + this._definitions.set(name, ( + isString(type) + ? type + : JSON.stringify(type) + )); } } }); } public get (name: string): Constructor | undefined { - return this._registry.get(name) as unknown as Constructor; + let Type = this._registry.get(name); + + // we have not already created the type, attempt it + if (!Type) { + const definition = this._definitions.get(name); + + // we have a definition, so create the class now (lazily) + if (definition) { + // NOTE If we didn't extend here, we would have strange artifacts. An example is + // Balance, with this, new Balance() instanceof u128 is true, but Balance !== u128 + Type = class extends createClass(definition) {}; + + this._registry.set(name, Type); + } + } + + return Type as Constructor; } public getOrThrow (name: string, msg?: string): Constructor { @@ -64,16 +86,6 @@ export class TypeRegistry { } } -let defaultRegistry: TypeRegistry; - export default function getDefaultRegistry (): TypeRegistry { - if (!defaultRegistry) { - // eslint-disable-next-line @typescript-eslint/no-var-requires - const defaultTypes = require('../index.types'); - - defaultRegistry = new TypeRegistry(); - defaultRegistry.register({ ...defaultTypes }); - } - - return defaultRegistry; + return TypeRegistry.defaultRegistry; } diff --git a/packages/types/src/index.types.ts b/packages/types/src/index.types.ts index 2e10ea86a677..eb3c8196791c 100644 --- a/packages/types/src/index.types.ts +++ b/packages/types/src/index.types.ts @@ -2,9 +2,6 @@ // This software may be modified and distributed under the terms // of the Apache-2.0 license. See the LICENSE file for details. -// NOTE When adding any types here, we need to update the coumentation links as -// well - /docs/SUMMARY.md as well as ../README.md - /** * @summary Type definitions that are used in the system */ diff --git a/packages/types/src/injector.ts b/packages/types/src/injector.ts index 09217dd1254d..fb21aa76d115 100644 --- a/packages/types/src/injector.ts +++ b/packages/types/src/injector.ts @@ -2,22 +2,26 @@ // This software may be modified and distributed under the terms // of the Apache-2.0 license. See the LICENSE file for details. -import { ClassOf } from './codec/createType'; +// import { ClassOf } from './codec/createType'; import getTypeRegistry from './codec/typeRegistry'; import * as definitions from './interfaces/definitions'; +import * as baseTypes from './index.types'; /** * @description A utility method that injects all the srml definitions into the type registry */ -export function injectDefinitions (): void { +export function injectTypes (): void { const registry = getTypeRegistry(); + registry.register({ ...baseTypes }); + Object.values(definitions).forEach(({ types }): void => registry.register(types) ); - // Here we setup the fallbacks - ClassOf('EventRecord').Fallback = ClassOf('EventRecord0to76'); + // FIXME Here we setup the fallbacks, well, rather we HAD them here. So these have + // been moved to API base since types are now created lazily + // ClassOf('EventRecord').Fallback = ClassOf('EventRecord0to76'); } -injectDefinitions(); +injectTypes(); From 02647c44305e31dcfb7e28fa2cd20bc2be59e32a Mon Sep 17 00:00:00 2001 From: Jaco Greeff Date: Sat, 10 Aug 2019 11:04:56 +0200 Subject: [PATCH 02/11] Typo in comment --- packages/types/src/codec/typeRegistry.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/types/src/codec/typeRegistry.ts b/packages/types/src/codec/typeRegistry.ts index 236dfe1da157..91e244d4e3eb 100644 --- a/packages/types/src/codec/typeRegistry.ts +++ b/packages/types/src/codec/typeRegistry.ts @@ -44,7 +44,7 @@ export class TypeRegistry { // This _looks_ a bit funny, but `typeof Clazz === 'function' this._registry.set(name, type); } else { - // we want to lazy create this one lazily + // We only create types on-demand, so just register the definition this._definitions.set(name, ( isString(type) ? type From b4ca714ef527ed517d0f64ae5a505945140ebffd Mon Sep 17 00:00:00 2001 From: Jaco Greeff Date: Sat, 10 Aug 2019 11:27:15 +0200 Subject: [PATCH 03/11] Alphabetical definitions (ordering detected) --- packages/types/src/injector.ts | 7 +- packages/types/src/interfaceRegistry.ts | 384 +++++++++--------- .../types/src/interfaces/babe/definitions.ts | 4 +- .../src/interfaces/balances/definitions.ts | 12 +- .../src/interfaces/claims/definitions.ts | 2 +- packages/types/src/interfaces/claims/types.ts | 6 +- .../src/interfaces/contracts/definitions.ts | 10 +- packages/types/src/interfaces/definitions.ts | 30 +- .../interfaces/genericAsset/definitions.ts | 10 +- .../src/interfaces/imOnline/definitions.ts | 12 +- .../src/interfaces/parachains/definitions.ts | 58 +-- .../src/interfaces/runtime/definitions.ts | 53 ++- .../src/interfaces/session/definitions.ts | 4 +- .../src/interfaces/staking/definitions.ts | 16 +- .../src/interfaces/system/definitions.ts | 21 +- packages/types/src/interfaces/types.ts | 12 +- 16 files changed, 309 insertions(+), 332 deletions(-) diff --git a/packages/types/src/injector.ts b/packages/types/src/injector.ts index fb21aa76d115..6a2fc91255d8 100644 --- a/packages/types/src/injector.ts +++ b/packages/types/src/injector.ts @@ -2,7 +2,6 @@ // This software may be modified and distributed under the terms // of the Apache-2.0 license. See the LICENSE file for details. -// import { ClassOf } from './codec/createType'; import getTypeRegistry from './codec/typeRegistry'; import * as definitions from './interfaces/definitions'; import * as baseTypes from './index.types'; @@ -13,15 +12,13 @@ import * as baseTypes from './index.types'; export function injectTypes (): void { const registry = getTypeRegistry(); + // since these are classes, the are active immediately registry.register({ ...baseTypes }); + // since these are definitions, they would only get created when needed Object.values(definitions).forEach(({ types }): void => registry.register(types) ); - - // FIXME Here we setup the fallbacks, well, rather we HAD them here. So these have - // been moved to API base since types are now created lazily - // ClassOf('EventRecord').Fallback = ClassOf('EventRecord0to76'); } injectTypes(); diff --git a/packages/types/src/interfaceRegistry.ts b/packages/types/src/interfaceRegistry.ts index 9aede2f8c621..5e7b05fcb116 100644 --- a/packages/types/src/interfaceRegistry.ts +++ b/packages/types/src/interfaceRegistry.ts @@ -4,27 +4,27 @@ import { Compact, Option, Vec } from './codec'; import { Bytes, Data, Fixed64, H160, H256, H512, Null, StorageData, StorageHasher, StorageKey, Text, Type, bool, i128, i16, i256, i32, i64, i8, u128, u16, u256, u32, u64, u8, usize } from './primitive'; import { AccountId, AccountIdOf, AccountIndex, Address, AssetId, Balance, BalanceOf, Block, BlockNumber, Call, Consensus, ConsensusEngineId, Digest, DigestItem, Ed25519Signature, Extrinsic, ExtrinsicEra, ExtrinsicPayload, Hash, Header, ImmortalEra, Index, Justification, KeyTypeId, KeyValue, LockIdentifier, Moment, MortalEra, Origin, Perbill, Permill, Phantom, PhantomData, PreRuntime, Seal, SealV0, Signature, SignedBlock, Sr25519Signature, ValidatorId, Weight, WeightMultiplier } from './interfaces/runtime'; -import { AuthorityId } from './interfaces/consensus'; -import { Keys, SessionIndex, SessionKeysPolkadot, SessionKeysSubstrate } from './interfaces/session'; -import { AuthorityWeight, NextAuthority, PendingPause, PendingResume, StoredPendingChange, StoredState } from './interfaces/grandpa'; -import { ApprovalFlag, SetIndex, Vote, VoteIndex, VoteThreshold, VoterInfo } from './interfaces/elections'; +import { RawAuraBorosPreDigest } from './interfaces/abrs'; import { InclusionHeight, Uncle, UncleEntryItem } from './interfaces/authorship'; import { RawAuraPreDigest } from './interfaces/aura'; import { BabeWeight, RawBabePreDigest, SlotNumber } from './interfaces/babe'; -import { RawAuraBorosPreDigest } from './interfaces/abrs'; import { BalanceLock, VestingSchedule, WithdrawReasons } from './interfaces/balances'; import { MemberCount, ProposalIndex, Votes } from './interfaces/collective'; +import { AuthorityId } from './interfaces/consensus'; import { AliveContractInfo, CodeHash, ContractInfo, ContractStorageKey, Gas, PrefabWasmModule, PrefabWasmModuleReserved, Schedule, SeedOf, TombstoneContractInfo, TrieId } from './interfaces/contracts'; import { Conviction, PropIndex, Proposal, ReferendumIndex, ReferendumInfo } from './interfaces/democracy'; import { AccountInfo, Amount, AssetOf, InherentOfflineReport, LockPeriods, NewAccountOutcome, OpaqueKey, SessionKey } from './interfaces/deprecated'; +import { ApprovalFlag, SetIndex, Vote, VoteIndex, VoteThreshold, VoterInfo } from './interfaces/elections'; import { AssetOptions, Owner, PermissionLatest, PermissionVersions, PermissionsV1 } from './interfaces/genericAsset'; +import { AuthorityWeight, NextAuthority, PendingPause, PendingResume, StoredPendingChange, StoredState } from './interfaces/grandpa'; import { AuthIndex, AuthoritySignature, Heartbeat, OpaqueMultiaddr, OpaqueNetworkState, OpaquePeerId } from './interfaces/imOnline'; +import { Keys, SessionIndex, SessionKeysPolkadot, SessionKeysSubstrate } from './interfaces/session'; import { EraIndex, EraRewards, Exposure, IndividualExposure, MomentOf, RewardDestination, StakingLedger, UnlockChunk, ValidatorPrefs } from './interfaces/staking'; import { DigestOf, Event, EventId, EventIndex, EventRecord, EventRecord0to76, Key, Phase } from './interfaces/system'; import { TreasuryProposal } from './interfaces/treasury'; +import { BlockAttestations, IncludedBlocks, MoreAttestations } from './interfaces/attestations'; import { EcdsaSignature, EthereumAddress } from './interfaces/claims'; import { AttestedCandidate, AuctionIndex, BalanceUpload, Bidder, CandidateReceipt, CollatorSignature, EgressQueueRoot, HeadData, IncomingParachain, IncomingParachainDeploy, IncomingParachainFixed, LeasePeriod, LeasePeriodOf, NewBidder, ParaId, ParaIdOf, ParachainDispatchOrigin, SlotRange, SubId, UpwardMessage, ValidatorIndex, ValidityAttestation, ValidityVote, WinningData, WinningDataEntry } from './interfaces/parachains'; -import { BlockAttestations, IncludedBlocks, MoreAttestations } from './interfaces/attestations'; import { ApiId, ChainProperties, ExtrinsicOrHash, ExtrinsicStatus, Health, KeyValueOption, NetworkState, PeerInfo, RuntimeVersion, RuntimeVersionApi, StorageChangeSet } from './interfaces/rpc'; export interface InterfaceRegistry { @@ -137,17 +137,51 @@ export interface InterfaceRegistry { BalanceOf: BalanceOf; 'Option': Option; 'Vec': Vec; + Block: Block; + 'Option': Option; + 'Vec': Vec; BlockNumber: BlockNumber; 'Compact': Compact; 'Option': Option; 'Vec': Vec; + Call: Call; + 'Option': Option; + 'Vec': Vec; + ConsensusEngineId: ConsensusEngineId; + 'Compact': Compact; + 'Option': Option; + 'Vec': Vec; + Digest: Digest; + 'Option': Option; + 'Vec': Vec; + DigestItem: DigestItem; + 'Option': Option; + 'Vec': Vec; + Extrinsic: Extrinsic; + 'Option': Option; + 'Vec': Vec; + ExtrinsicEra: ExtrinsicEra; + 'Option': Option; + 'Vec': Vec; + ExtrinsicPayload: ExtrinsicPayload; + 'Option': Option; + 'Vec': Vec; Hash: Hash; 'Option': Option; 'Vec': Vec; + Header: Header; + 'Option
': Option
; + 'Vec
': Vec
; Index: Index; 'Compact': Compact; 'Option': Option; 'Vec': Vec; + Justification: Justification; + 'Option': Option; + 'Vec': Vec; + KeyValue: KeyValue; + 'Option': Option; + 'Vec': Vec; KeyTypeId: KeyTypeId; 'Compact': Compact; 'Option': Option; @@ -159,6 +193,9 @@ export interface InterfaceRegistry { 'Compact': Compact; 'Option': Option; 'Vec': Vec; + Origin: Origin; + 'Option': Option; + 'Vec': Vec; Perbill: Perbill; 'Compact': Compact; 'Option': Option; @@ -173,6 +210,12 @@ export interface InterfaceRegistry { PhantomData: PhantomData; 'Option': Option; 'Vec': Vec; + Signature: Signature; + 'Option': Option; + 'Vec': Vec; + SignedBlock: SignedBlock; + 'Option': Option; + 'Vec': Vec; ValidatorId: ValidatorId; 'Option': Option; 'Vec': Vec; @@ -183,43 +226,18 @@ export interface InterfaceRegistry { WeightMultiplier: WeightMultiplier; 'Option': Option; 'Vec': Vec; - KeyValue: KeyValue; - 'Option': Option; - 'Vec': Vec; - Signature: Signature; - 'Option': Option; - 'Vec': Vec; Ed25519Signature: Ed25519Signature; 'Option': Option; 'Vec': Vec; Sr25519Signature: Sr25519Signature; 'Option': Option; 'Vec': Vec; - Call: Call; - 'Option': Option; - 'Vec': Vec; - Origin: Origin; - 'Option': Option; - 'Vec': Vec; ImmortalEra: ImmortalEra; 'Option': Option; 'Vec': Vec; MortalEra: MortalEra; 'Option': Option; 'Vec': Vec; - ExtrinsicEra: ExtrinsicEra; - 'Option': Option; - 'Vec': Vec; - ExtrinsicPayload: ExtrinsicPayload; - 'Option': Option; - 'Vec': Vec; - Extrinsic: Extrinsic; - 'Option': Option; - 'Vec': Vec; - ConsensusEngineId: ConsensusEngineId; - 'Compact': Compact; - 'Option': Option; - 'Vec': Vec; PreRuntime: PreRuntime; 'Option': Option; 'Vec': Vec; @@ -232,80 +250,9 @@ export interface InterfaceRegistry { Consensus: Consensus; 'Option': Option; 'Vec': Vec; - DigestItem: DigestItem; - 'Option': Option; - 'Vec': Vec; - Digest: Digest; - 'Option': Option; - 'Vec': Vec; - Header: Header; - 'Option
': Option
; - 'Vec
': Vec
; - Justification: Justification; - 'Option': Option; - 'Vec': Vec; - Block: Block; - 'Option': Option; - 'Vec': Vec; - SignedBlock: SignedBlock; - 'Option': Option; - 'Vec': Vec; - AuthorityId: AuthorityId; - 'Option': Option; - 'Vec': Vec; - SessionIndex: SessionIndex; - 'Compact': Compact; - 'Option': Option; - 'Vec': Vec; - SessionKeysSubstrate: SessionKeysSubstrate; - 'Option': Option; - 'Vec': Vec; - SessionKeysPolkadot: SessionKeysPolkadot; - 'Option': Option; - 'Vec': Vec; - Keys: Keys; - 'Option': Option; - 'Vec': Vec; - AuthorityWeight: AuthorityWeight; - 'Compact': Compact; - 'Option': Option; - 'Vec': Vec; - NextAuthority: NextAuthority; - 'Option': Option; - 'Vec': Vec; - PendingPause: PendingPause; - 'Option': Option; - 'Vec': Vec; - PendingResume: PendingResume; - 'Option': Option; - 'Vec': Vec; - StoredPendingChange: StoredPendingChange; - 'Option': Option; - 'Vec': Vec; - StoredState: StoredState; - 'Option': Option; - 'Vec': Vec; - ApprovalFlag: ApprovalFlag; - 'Compact': Compact; - 'Option': Option; - 'Vec': Vec; - SetIndex: SetIndex; - 'Compact': Compact; - 'Option': Option; - 'Vec': Vec; - Vote: Vote; - 'Option': Option; - 'Vec': Vec; - VoteIndex: VoteIndex; - 'Compact': Compact; - 'Option': Option; - 'Vec': Vec; - VoterInfo: VoterInfo; - 'Option': Option; - 'Vec': Vec; - VoteThreshold: VoteThreshold; - 'Option': Option; - 'Vec': Vec; + RawAuraBorosPreDigest: RawAuraBorosPreDigest; + 'Option': Option; + 'Vec': Vec; InclusionHeight: InclusionHeight; 'Option': Option; 'Vec': Vec; @@ -322,25 +269,22 @@ export interface InterfaceRegistry { 'Compact': Compact; 'Option': Option; 'Vec': Vec; + RawBabePreDigest: RawBabePreDigest; + 'Option': Option; + 'Vec': Vec; SlotNumber: SlotNumber; 'Compact': Compact; 'Option': Option; 'Vec': Vec; - RawBabePreDigest: RawBabePreDigest; - 'Option': Option; - 'Vec': Vec; - RawAuraBorosPreDigest: RawAuraBorosPreDigest; - 'Option': Option; - 'Vec': Vec; + BalanceLock: BalanceLock; + 'Option': Option; + 'Vec': Vec; VestingSchedule: VestingSchedule; 'Option': Option; 'Vec': Vec; WithdrawReasons: WithdrawReasons; 'Option': Option; 'Vec': Vec; - BalanceLock: BalanceLock; - 'Option': Option; - 'Vec': Vec; MemberCount: MemberCount; 'Compact': Compact; 'Option': Option; @@ -352,18 +296,15 @@ export interface InterfaceRegistry { Votes: Votes; 'Option': Option; 'Vec': Vec; - CodeHash: CodeHash; - 'Option': Option; - 'Vec': Vec; - TrieId: TrieId; - 'Option': Option; - 'Vec': Vec; + AuthorityId: AuthorityId; + 'Option': Option; + 'Vec': Vec; AliveContractInfo: AliveContractInfo; 'Option': Option; 'Vec': Vec; - TombstoneContractInfo: TombstoneContractInfo; - 'Option': Option; - 'Vec': Vec; + CodeHash: CodeHash; + 'Option': Option; + 'Vec': Vec; ContractInfo: ContractInfo; 'Option': Option; 'Vec': Vec; @@ -374,18 +315,24 @@ export interface InterfaceRegistry { 'Compact': Compact; 'Option': Option; 'Vec': Vec; - PrefabWasmModuleReserved: PrefabWasmModuleReserved; - 'Option': Option; - 'Vec': Vec; PrefabWasmModule: PrefabWasmModule; 'Option': Option; 'Vec': Vec; + PrefabWasmModuleReserved: PrefabWasmModuleReserved; + 'Option': Option; + 'Vec': Vec; Schedule: Schedule; 'Option': Option; 'Vec': Vec; SeedOf: SeedOf; 'Option': Option; 'Vec': Vec; + TombstoneContractInfo: TombstoneContractInfo; + 'Option': Option; + 'Vec': Vec; + TrieId: TrieId; + 'Option': Option; + 'Vec': Vec; Conviction: Conviction; 'Option': Option; 'Vec': Vec; @@ -428,6 +375,30 @@ export interface InterfaceRegistry { OpaqueKey: OpaqueKey; 'Option': Option; 'Vec': Vec; + ApprovalFlag: ApprovalFlag; + 'Compact': Compact; + 'Option': Option; + 'Vec': Vec; + SetIndex: SetIndex; + 'Compact': Compact; + 'Option': Option; + 'Vec': Vec; + Vote: Vote; + 'Option': Option; + 'Vec': Vec; + VoteIndex: VoteIndex; + 'Compact': Compact; + 'Option': Option; + 'Vec': Vec; + VoterInfo: VoterInfo; + 'Option': Option; + 'Vec': Vec; + VoteThreshold: VoteThreshold; + 'Option': Option; + 'Vec': Vec; + AssetOptions: AssetOptions; + 'Option': Option; + 'Vec': Vec; Owner: Owner; 'Option': Option; 'Vec': Vec; @@ -440,9 +411,25 @@ export interface InterfaceRegistry { PermissionLatest: PermissionLatest; 'Option': Option; 'Vec': Vec; - AssetOptions: AssetOptions; - 'Option': Option; - 'Vec': Vec; + AuthorityWeight: AuthorityWeight; + 'Compact': Compact; + 'Option': Option; + 'Vec': Vec; + NextAuthority: NextAuthority; + 'Option': Option; + 'Vec': Vec; + PendingPause: PendingPause; + 'Option': Option; + 'Vec': Vec; + PendingResume: PendingResume; + 'Option': Option; + 'Vec': Vec; + StoredPendingChange: StoredPendingChange; + 'Option': Option; + 'Vec': Vec; + StoredState: StoredState; + 'Option': Option; + 'Vec': Vec; AuthIndex: AuthIndex; 'Compact': Compact; 'Option': Option; @@ -450,6 +437,9 @@ export interface InterfaceRegistry { AuthoritySignature: AuthoritySignature; 'Option': Option; 'Vec': Vec; + Heartbeat: Heartbeat; + 'Option': Option; + 'Vec': Vec; OpaqueMultiaddr: OpaqueMultiaddr; 'Option': Option; 'Vec': Vec; @@ -459,9 +449,19 @@ export interface InterfaceRegistry { OpaqueNetworkState: OpaqueNetworkState; 'Option': Option; 'Vec': Vec; - Heartbeat: Heartbeat; - 'Option': Option; - 'Vec': Vec; + SessionIndex: SessionIndex; + 'Compact': Compact; + 'Option': Option; + 'Vec': Vec; + Keys: Keys; + 'Option': Option; + 'Vec': Vec; + SessionKeysSubstrate: SessionKeysSubstrate; + 'Option': Option; + 'Vec': Vec; + SessionKeysPolkadot: SessionKeysPolkadot; + 'Option': Option; + 'Vec': Vec; EraIndex: EraIndex; 'Compact': Compact; 'Option': Option; @@ -469,30 +469,33 @@ export interface InterfaceRegistry { EraRewards: EraRewards; 'Option': Option; 'Vec': Vec; - IndividualExposure: IndividualExposure; - 'Option': Option; - 'Vec': Vec; Exposure: Exposure; 'Option': Option; 'Vec': Vec; + IndividualExposure: IndividualExposure; + 'Option': Option; + 'Vec': Vec; MomentOf: MomentOf; 'Option': Option; 'Vec': Vec; RewardDestination: RewardDestination; 'Option': Option; 'Vec': Vec; - UnlockChunk: UnlockChunk; - 'Option': Option; - 'Vec': Vec; StakingLedger: StakingLedger; 'Option': Option; 'Vec': Vec; + UnlockChunk: UnlockChunk; + 'Option': Option; + 'Vec': Vec; ValidatorPrefs: ValidatorPrefs; 'Option': Option; 'Vec': Vec; DigestOf: DigestOf; 'Option': Option; 'Vec': Vec; + Event: Event; + 'Option': Option; + 'Vec': Vec; EventId: EventId; 'Option': Option; 'Vec': Vec; @@ -500,79 +503,61 @@ export interface InterfaceRegistry { 'Compact': Compact; 'Option': Option; 'Vec': Vec; + EventRecord: EventRecord; + 'Option': Option; + 'Vec': Vec; + EventRecord0to76: EventRecord0to76; + 'Option': Option; + 'Vec': Vec; Key: Key; 'Option': Option; 'Vec': Vec; Phase: Phase; 'Option': Option; 'Vec': Vec; - Event: Event; - 'Option': Option; - 'Vec': Vec; - EventRecord0to76: EventRecord0to76; - 'Option': Option; - 'Vec': Vec; - EventRecord: EventRecord; - 'Option': Option; - 'Vec': Vec; TreasuryProposal: TreasuryProposal; 'Option': Option; 'Vec': Vec; + BlockAttestations: BlockAttestations; + 'Option': Option; + 'Vec': Vec; + IncludedBlocks: IncludedBlocks; + 'Option': Option; + 'Vec': Vec; + MoreAttestations: MoreAttestations; + 'Option': Option; + 'Vec': Vec; EcdsaSignature: EcdsaSignature; 'Option': Option; 'Vec': Vec; EthereumAddress: EthereumAddress; 'Option': Option; 'Vec': Vec; + AttestedCandidate: AttestedCandidate; + 'Option': Option; + 'Vec': Vec; AuctionIndex: AuctionIndex; 'Compact': Compact; 'Option': Option; 'Vec': Vec; - CollatorSignature: CollatorSignature; - 'Option': Option; - 'Vec': Vec; - ValidityAttestation: ValidityAttestation; - 'Option': Option; - 'Vec': Vec; - ParaId: ParaId; - 'Compact': Compact; - 'Option': Option; - 'Vec': Vec; - ParaIdOf: ParaIdOf; - 'Option': Option; - 'Vec': Vec; - ValidatorIndex: ValidatorIndex; - 'Compact': Compact; - 'Option': Option; - 'Vec': Vec; - ValidityVote: ValidityVote; - 'Option': Option; - 'Vec': Vec; BalanceUpload: BalanceUpload; 'Option': Option; 'Vec': Vec; + Bidder: Bidder; + 'Option': Option; + 'Vec': Vec; + CandidateReceipt: CandidateReceipt; + 'Option': Option; + 'Vec': Vec; + CollatorSignature: CollatorSignature; + 'Option': Option; + 'Vec': Vec; EgressQueueRoot: EgressQueueRoot; 'Option': Option; 'Vec': Vec; HeadData: HeadData; 'Option': Option; 'Vec': Vec; - CandidateReceipt: CandidateReceipt; - 'Option': Option; - 'Vec': Vec; - AttestedCandidate: AttestedCandidate; - 'Option': Option; - 'Vec': Vec; - SubId: SubId; - 'Compact': Compact; - 'Option': Option; - 'Vec': Vec; - NewBidder: NewBidder; - 'Option': Option; - 'Vec': Vec; - Bidder: Bidder; - 'Option': Option; - 'Vec': Vec; IncomingParachainDeploy: IncomingParachainDeploy; 'Option': Option; 'Vec': Vec; @@ -588,30 +573,45 @@ export interface InterfaceRegistry { LeasePeriodOf: LeasePeriodOf; 'Option': Option; 'Vec': Vec; + NewBidder: NewBidder; + 'Option': Option; + 'Vec': Vec; + ParaId: ParaId; + 'Compact': Compact; + 'Option': Option; + 'Vec': Vec; + ParaIdOf: ParaIdOf; + 'Option': Option; + 'Vec': Vec; ParachainDispatchOrigin: ParachainDispatchOrigin; 'Option': Option; 'Vec': Vec; SlotRange: SlotRange; 'Option': Option; 'Vec': Vec; + SubId: SubId; + 'Compact': Compact; + 'Option': Option; + 'Vec': Vec; UpwardMessage: UpwardMessage; 'Option': Option; 'Vec': Vec; + ValidityAttestation: ValidityAttestation; + 'Option': Option; + 'Vec': Vec; + ValidatorIndex: ValidatorIndex; + 'Compact': Compact; + 'Option': Option; + 'Vec': Vec; + ValidityVote: ValidityVote; + 'Option': Option; + 'Vec': Vec; WinningDataEntry: WinningDataEntry; 'Option': Option; 'Vec': Vec; WinningData: WinningData; 'Option': Option; 'Vec': Vec; - BlockAttestations: BlockAttestations; - 'Option': Option; - 'Vec': Vec; - IncludedBlocks: IncludedBlocks; - 'Option': Option; - 'Vec': Vec; - MoreAttestations: MoreAttestations; - 'Option': Option; - 'Vec': Vec; ApiId: ApiId; 'Option': Option; 'Vec': Vec; diff --git a/packages/types/src/interfaces/babe/definitions.ts b/packages/types/src/interfaces/babe/definitions.ts index 96b7a6757eb9..abda332c03b4 100644 --- a/packages/types/src/interfaces/babe/definitions.ts +++ b/packages/types/src/interfaces/babe/definitions.ts @@ -5,12 +5,12 @@ export default { types: { BabeWeight: 'u64', - SlotNumber: 'u64', RawBabePreDigest: { slotNumber: 'SlotNumber', authorityIndex: 'u32', // AuthorityIndex (also in aura, not same size there) vrfOutput: 'H256', // should be '[u8; 32]' (generator support lacking here) vrfProof: 'H256' // should be '[u8; 32]' - } + }, + SlotNumber: 'u64' } }; diff --git a/packages/types/src/interfaces/balances/definitions.ts b/packages/types/src/interfaces/balances/definitions.ts index ffa19008726d..bcf2d93a860a 100644 --- a/packages/types/src/interfaces/balances/definitions.ts +++ b/packages/types/src/interfaces/balances/definitions.ts @@ -4,6 +4,12 @@ export default { types: { + BalanceLock: { + id: 'LockIdentifier', + amount: 'Balance', + until: 'BlockNumber', + reasons: 'WithdrawReasons' + }, VestingSchedule: { offset: 'Balance', perBlock: 'Balance', @@ -16,12 +22,6 @@ export default { Reserve: 0b00000100, Fee: 0b00001000 } - }, - BalanceLock: { - id: 'LockIdentifier', - amount: 'Balance', - until: 'BlockNumber', - reasons: 'WithdrawReasons' } } }; diff --git a/packages/types/src/interfaces/claims/definitions.ts b/packages/types/src/interfaces/claims/definitions.ts index 4b91924ad0b1..53313bc0571c 100644 --- a/packages/types/src/interfaces/claims/definitions.ts +++ b/packages/types/src/interfaces/claims/definitions.ts @@ -4,7 +4,7 @@ export default { types: { - EcdsaSignature: '[u8; 65]', + EcdsaSignature: '(H256, H256, i8)', EthereumAddress: 'H160' } }; diff --git a/packages/types/src/interfaces/claims/types.ts b/packages/types/src/interfaces/claims/types.ts index a556a3fcc7fa..da021b119e6d 100644 --- a/packages/types/src/interfaces/claims/types.ts +++ b/packages/types/src/interfaces/claims/types.ts @@ -2,10 +2,10 @@ /* eslint-disable @typescript-eslint/no-empty-interface */ import { Codec } from '../../types'; -import { H160 } from '../../primitive'; +import { H160, H256, i8 } from '../../primitive'; -/** Uint8Array & Codec */ -export type EcdsaSignature = Uint8Array & Codec; +/** [H256, H256, i8] & Codec */ +export type EcdsaSignature = [H256, H256, i8] & Codec; /** H160 */ export type EthereumAddress = H160; diff --git a/packages/types/src/interfaces/contracts/definitions.ts b/packages/types/src/interfaces/contracts/definitions.ts index acb660864811..844f9f66646b 100644 --- a/packages/types/src/interfaces/contracts/definitions.ts +++ b/packages/types/src/interfaces/contracts/definitions.ts @@ -4,8 +4,6 @@ export default { types: { - CodeHash: 'Hash', - TrieId: 'Bytes', AliveContractInfo: { trieId: 'TrieId', storageSize: 'u32', @@ -14,7 +12,7 @@ export default { deductBlock: 'BlockNumber', lastWrite: 'Option' }, - TombstoneContractInfo: 'Hash', + CodeHash: 'Hash', ContractInfo: { _enum: { Alive: 'AliveContractInfo', @@ -23,7 +21,6 @@ export default { }, ContractStorageKey: '[u8; 32]', Gas: 'u64', - PrefabWasmModuleReserved: 'Option', PrefabWasmModule: { scheduleVersion: 'Compact', initial: 'Compact', @@ -31,6 +28,7 @@ export default { _reserved: 'PrefabWasmModuleReserved', code: 'Bytes' }, + PrefabWasmModuleReserved: 'Option', Schedule: { version: 'u32', putCodePerByteCost: 'Gas', @@ -48,6 +46,8 @@ export default { enablePrintln: 'bool', maxSubjectLen: 'u32' }, - SeedOf: 'Hash' + SeedOf: 'Hash', + TombstoneContractInfo: 'Hash', + TrieId: 'Bytes' } }; diff --git a/packages/types/src/interfaces/definitions.ts b/packages/types/src/interfaces/definitions.ts index ecc8bc3d59c2..faa0dbebabe7 100644 --- a/packages/types/src/interfaces/definitions.ts +++ b/packages/types/src/interfaces/definitions.ts @@ -2,47 +2,33 @@ // This software may be modified and distributed under the terms // of the Apache-2.0 license. See the LICENSE file for details. -// NOTE The order here is NOT alphabetical, rather it is setup so that lower -// layers can re-use types from higher layers as this is being injected. The -// injection order is critical. - -// runtime before everything else, these are base definitions +// technically runtime can go below, but since it is the base, do it first export { default as runtime } from './runtime/definitions'; -// consensus before grandpa, imOnline -export { default as consensus } from './consensus/definitions'; - -// session before imOnline -export { default as session } from './session/definitions'; - -// grandpa before parachains -export { default as grandpa } from './grandpa/definitions'; - -// elections before democracy -export { default as elections } from './elections/definitions'; - -// authoring, abra uses babe & aura +// substrate types +export { default as abrs } from './abrs/definitions'; export { default as authorship } from './authorship/definitions'; export { default as aura } from './aura/definitions'; export { default as babe } from './babe/definitions'; -export { default as abrs } from './abrs/definitions'; - -// remaining, alphabetical odering export { default as balances } from './balances/definitions'; export { default as collective } from './collective/definitions'; +export { default as consensus } from './consensus/definitions'; export { default as contracts } from './contracts/definitions'; export { default as democracy } from './democracy/definitions'; export { default as deprecated } from './deprecated/definitions'; +export { default as elections } from './elections/definitions'; export { default as genericAsset } from './genericAsset/definitions'; +export { default as grandpa } from './grandpa/definitions'; export { default as imOnline } from './imOnline/definitions'; +export { default as session } from './session/definitions'; export { default as staking } from './staking/definitions'; export { default as system } from './system/definitions'; export { default as treasury } from './treasury/definitions'; // polkadot-specific types +export { default as attestations } from './attestations/definitions'; export { default as claims } from './claims/definitions'; export { default as parachains } from './parachains/definitions'; -export { default as attestations } from './attestations/definitions'; // pull in rpc last, assuming that is uses info from above export { default as rpc } from './rpc/definitions'; diff --git a/packages/types/src/interfaces/genericAsset/definitions.ts b/packages/types/src/interfaces/genericAsset/definitions.ts index 21c128ba7a56..de17899638b1 100644 --- a/packages/types/src/interfaces/genericAsset/definitions.ts +++ b/packages/types/src/interfaces/genericAsset/definitions.ts @@ -4,6 +4,10 @@ export default { types: { + AssetOptions: { + initalIssuance: 'Balance', + permissions: 'PermissionLatest' + }, Owner: { _enum: { None: 'Null', @@ -20,10 +24,6 @@ export default { V1: 'PermissionsV1' } }, - PermissionLatest: 'PermissionsV1', - AssetOptions: { - initalIssuance: 'Balance', - permissions: 'PermissionLatest' - } + PermissionLatest: 'PermissionsV1' } }; diff --git a/packages/types/src/interfaces/imOnline/definitions.ts b/packages/types/src/interfaces/imOnline/definitions.ts index 84fbe05a303a..f94bc8d3d27b 100644 --- a/packages/types/src/interfaces/imOnline/definitions.ts +++ b/packages/types/src/interfaces/imOnline/definitions.ts @@ -6,6 +6,12 @@ export default { types: { AuthIndex: 'u32', AuthoritySignature: 'Signature', + Heartbeat: { + blockNumber: 'BlockNumber', + networkState: 'OpaqueNetworkState', + sessionIndex: 'SessionIndex', + authorityId: 'AuthorityId' + }, OpaqueMultiaddr: 'Bytes', OpaquePeerId: 'Bytes', OpaqueNetworkState: { @@ -13,12 +19,6 @@ export default { peerId: 'OpaquePeerId', /// List of addresses the node knows it can be reached as. externalAddresses: 'Vec' - }, - Heartbeat: { - blockNumber: 'BlockNumber', - networkState: 'OpaqueNetworkState', - sessionIndex: 'SessionIndex', - authorityId: 'AuthorityId' } } }; diff --git a/packages/types/src/interfaces/parachains/definitions.ts b/packages/types/src/interfaces/parachains/definitions.ts index 0d4d18dbd75b..55844e267f4f 100644 --- a/packages/types/src/interfaces/parachains/definitions.ts +++ b/packages/types/src/interfaces/parachains/definitions.ts @@ -4,24 +4,18 @@ export default { types: { + AttestedCandidate: { + candidate: 'CandidateReceipt', + validityVotes: 'Vec' + }, AuctionIndex: 'u32', - CollatorSignature: 'Signature', - ValidityAttestation: { + BalanceUpload: '(AccountId, u64)', + Bidder: { _enum: { - // This Null is not in the original, however indexes start at 1, so add a - // placeholder in the first position (which is basically non-valid) - None: 'Null', - Implicit: 'CollatorSignature', // 1 - Explicit: 'CollatorSignature' // 2 + New: 'NewBidder', + Existing: 'ParaId' } }, - ParaId: 'u32', - ParaIdOf: 'ParaId', - ValidatorIndex: 'u32', - ValidityVote: '(ValidatorIndex, ValidityAttestation)', - BalanceUpload: '(AccountId, u64)', - EgressQueueRoot: '(ParaId, Hash)', - HeadData: 'Bytes', CandidateReceipt: { parachainIndex: 'ParaId', collator: 'AccountId', @@ -32,21 +26,9 @@ export default { fees: 'u64', blockDataHash: 'Hash' }, - AttestedCandidate: { - candidate: 'CandidateReceipt', - validityVotes: 'Vec' - }, - SubId: 'u32', - NewBidder: { - who: 'AccountId', - sub: 'SubId' - }, - Bidder: { - _enum: { - New: 'NewBidder', - Existing: 'ParaId' - } - }, + CollatorSignature: 'Signature', + EgressQueueRoot: '(ParaId, Hash)', + HeadData: 'Bytes', IncomingParachainDeploy: { code: 'Bytes', initialHeadData: 'Bytes' @@ -64,6 +46,12 @@ export default { }, LeasePeriod: 'BlockNumber', LeasePeriodOf: 'LeasePeriod', + NewBidder: { + who: 'AccountId', + sub: 'SubId' + }, + ParaId: 'u32', + ParaIdOf: 'ParaId', ParachainDispatchOrigin: { _enum: [ 'Signed', @@ -84,10 +72,22 @@ export default { 'ThreeThree' // 9 ] }, + SubId: 'u32', UpwardMessage: { origin: 'ParachainDispatchOrigin', data: 'Bytes' }, + ValidityAttestation: { + _enum: { + // This Null is not in the original, however indexes start at 1, so add a + // placeholder in the first position (which is basically non-valid) + None: 'Null', + Implicit: 'CollatorSignature', // 1 + Explicit: 'CollatorSignature' // 2 + } + }, + ValidatorIndex: 'u32', + ValidityVote: '(ValidatorIndex, ValidityAttestation)', WinningDataEntry: '(AccountId, ParaIdOf, BalanceOf)', WinningData: '[WinningDataEntry; 10]' } diff --git a/packages/types/src/interfaces/runtime/definitions.ts b/packages/types/src/interfaces/runtime/definitions.ts index 28b5a02d2eae..abbbfb713528 100644 --- a/packages/types/src/interfaces/runtime/definitions.ts +++ b/packages/types/src/interfaces/runtime/definitions.ts @@ -11,60 +11,55 @@ export default { AssetId: 'u32', Balance: 'u128', BalanceOf: 'Balance', + Block: 'GenericBlock', BlockNumber: 'u64', + Call: 'GenericCall', + ConsensusEngineId: 'GenericConsensusEngineId', + Digest: 'GenericDigest', + DigestItem: 'GenericDigestItem', + Extrinsic: 'GenericExtrinsic', + ExtrinsicEra: 'GenericExtrinsicEra', + ExtrinsicPayload: 'GenericExtrinsicPayload', Hash: 'H256', + Header: { + parentHash: 'Hash', + number: 'Compact', + stateRoot: 'Hash', + extrinsicsRoot: 'Hash', + digest: 'Digest' + }, Index: 'u64', + Justification: 'Bytes', + KeyValue: '(StorageKey, StorageData)', KeyTypeId: 'u32', LockIdentifier: '[u8; 8]', Moment: 'u64', + Origin: 'GenericOrigin', Perbill: 'u32', Permill: 'u32', Phantom: 'Null', PhantomData: 'Null', + Signature: 'H512', + SignedBlock: { + block: 'Block', + justification: 'Justification' + }, ValidatorId: 'AccountId', Weight: 'u32', WeightMultiplier: 'Fixed64', - // storage helpers - KeyValue: '(StorageKey, StorageData)', - // signatures (used in block & extrinsics) - Signature: 'H512', Ed25519Signature: 'Signature', Sr25519Signature: 'Signature', // extrinsic definition - Call: 'GenericCall', - Origin: 'GenericOrigin', ImmortalEra: 'GenericImmortalEra', MortalEra: 'GenericMortalEra', - ExtrinsicEra: 'GenericExtrinsicEra', - ExtrinsicPayload: 'GenericExtrinsicPayload', - Extrinsic: 'GenericExtrinsic', - // block definition // :: digest - ConsensusEngineId: 'GenericConsensusEngineId', PreRuntime: '(ConsensusEngineId, Bytes)', SealV0: '(u64, Signature)', Seal: '(ConsensusEngineId, Bytes)', - Consensus: '(ConsensusEngineId, Bytes)', - DigestItem: 'GenericDigestItem', - Digest: 'GenericDigest', - // :: parts - Header: { - parentHash: 'Hash', - number: 'Compact', - stateRoot: 'Hash', - extrinsicsRoot: 'Hash', - digest: 'Digest' - }, - Justification: 'Bytes', - // :: definitions - Block: 'GenericBlock', - SignedBlock: { - block: 'Block', - justification: 'Justification' - } + Consensus: '(ConsensusEngineId, Bytes)' } }; diff --git a/packages/types/src/interfaces/session/definitions.ts b/packages/types/src/interfaces/session/definitions.ts index a109f04ebe36..a317266cb4c8 100644 --- a/packages/types/src/interfaces/session/definitions.ts +++ b/packages/types/src/interfaces/session/definitions.ts @@ -11,10 +11,10 @@ export default { // impl_opaque_keys! { // pub struct SessionKeys { // Here we revert to tuples to keep the interfaces "opaque", as per the use + Keys: 'SessionKeysSubstrate', // For substrate: Grandpa, Babe, ImOnline SessionKeysSubstrate: '(AccountId, AccountId, AccountId)', // For polkadot: Grandpa, Babe, ImOnline, Parachains - SessionKeysPolkadot: '(AccountId, AccountId, AccountId, AccountId)', - Keys: 'SessionKeysSubstrate' + SessionKeysPolkadot: '(AccountId, AccountId, AccountId, AccountId)' } }; diff --git a/packages/types/src/interfaces/staking/definitions.ts b/packages/types/src/interfaces/staking/definitions.ts index bb5cd3dd77ed..3f84400d5513 100644 --- a/packages/types/src/interfaces/staking/definitions.ts +++ b/packages/types/src/interfaces/staking/definitions.ts @@ -9,15 +9,15 @@ export default { total: 'u32', rewards: 'Vec' }, - IndividualExposure: { - who: 'AccountId', - value: 'Compact' - }, Exposure: { total: 'Compact', own: 'Compact', others: 'Vec' }, + IndividualExposure: { + who: 'AccountId', + value: 'Compact' + }, MomentOf: 'Moment', RewardDestination: { _enum: [ @@ -26,16 +26,16 @@ export default { 'Controller' ] }, - UnlockChunk: { - value: 'Compact', - era: 'Compact' - }, StakingLedger: { stash: 'AccountId', total: 'Compact', active: 'Compact', unlocking: 'Vec' }, + UnlockChunk: { + value: 'Compact', + era: 'Compact' + }, ValidatorPrefs: { unstakeThreshold: 'Compact', validatorPayment: 'Compact' diff --git a/packages/types/src/interfaces/system/definitions.ts b/packages/types/src/interfaces/system/definitions.ts index 78c7d6a204ed..5b9ac90337f2 100644 --- a/packages/types/src/interfaces/system/definitions.ts +++ b/packages/types/src/interfaces/system/definitions.ts @@ -5,25 +5,24 @@ export default { types: { DigestOf: 'Digest', + Event: 'GenericEvent', EventId: '[u8; 2]', EventIndex: 'u32', + EventRecord: { + phase: 'Phase', + event: 'Event', + topics: 'Vec' + }, + EventRecord0to76: { + phase: 'Phase', + event: 'Event' + }, Key: 'Bytes', Phase: { _enum: { ApplyExtrinsic: 'u32', Finalization: 'Null' } - }, - Event: 'GenericEvent', - EventRecord0to76: { - phase: 'Phase', - event: 'Event' - }, - // Fallback in injectDefinitions - EventRecord: { - phase: 'Phase', - event: 'Event', - topics: 'Vec' } } }; diff --git a/packages/types/src/interfaces/types.ts b/packages/types/src/interfaces/types.ts index f4ba05b41469..82cd9b0791ed 100644 --- a/packages/types/src/interfaces/types.ts +++ b/packages/types/src/interfaces/types.ts @@ -2,25 +2,25 @@ /* eslint-disable @typescript-eslint/no-empty-interface */ export * from './runtime/types'; -export * from './consensus/types'; -export * from './session/types'; -export * from './grandpa/types'; -export * from './elections/types'; +export * from './abrs/types'; export * from './authorship/types'; export * from './aura/types'; export * from './babe/types'; -export * from './abrs/types'; export * from './balances/types'; export * from './collective/types'; +export * from './consensus/types'; export * from './contracts/types'; export * from './democracy/types'; export * from './deprecated/types'; +export * from './elections/types'; export * from './genericAsset/types'; +export * from './grandpa/types'; export * from './imOnline/types'; +export * from './session/types'; export * from './staking/types'; export * from './system/types'; export * from './treasury/types'; +export * from './attestations/types'; export * from './claims/types'; export * from './parachains/types'; -export * from './attestations/types'; export * from './rpc/types'; From e48010b7605d9f9f4019fd5dbeb2fd8cddb4405a Mon Sep 17 00:00:00 2001 From: Jaco Greeff Date: Sat, 10 Aug 2019 12:27:15 +0200 Subject: [PATCH 04/11] Make fallback & SessionKeys work as expected --- packages/api/src/Base.ts | 23 +++++++---------------- packages/types/src/codec/typeRegistry.ts | 9 +++++++++ packages/types/src/injector.ts | 6 ++++++ 3 files changed, 22 insertions(+), 16 deletions(-) diff --git a/packages/api/src/Base.ts b/packages/api/src/Base.ts index c98863731bbd..1b9863d328de 100644 --- a/packages/api/src/Base.ts +++ b/packages/api/src/Base.ts @@ -538,6 +538,13 @@ export default abstract class ApiBase { this._rpcCore.chain.getRuntimeVersion().toPromise() ]); + // NOTE The SessionKeys definition for Polkadot and Substrate (OpaqueKeys + // implementation) are different. Detect Polkadot and inject the `Keys` + // definition as applicable. (3 keys in substrate vs 4 in Polkadot). + if (this._runtimeVersion.specName.eq('polkadot')) { + getTypeRegistry().register({ Keys: 'SessionKeysPolkadot' }); + } + const metadataKey = `${this._genesisHash}-${(this._runtimeVersion as RuntimeVersion).specVersion}`; if (metadataKey in metadata) { @@ -574,22 +581,6 @@ export default abstract class ApiBase { this._query = this.decorateStorage(storage, this.decorateMethod); this._consts = constants; - // NOTE The SessionKeys definition for Polkadot and Substrate (OpaqueKeys - // implementation) are different. Detect Polkadot and inject the `Keys` - // definition as applicable. (3 keys in substrate vs 4 in Polkadot). If - // we have reflected metadata, this override becomes unneeded - if (this._query.parachains) { - getTypeRegistry().register({ Keys: 'SessionKeysPolkadot' }); - } - - // FIXME This is absolutely NOT the right place and the check is not 100% - - // however, I need to get this working, today. So basically, when we detect - // a v1 extrinsic, we assume that we are dealing win an ancient 1.x chain, so - // setup the overrides. TL;DR This is an even bigger HACK than the NOTE above - if (this._extrinsicType === 1) { - getTypeRegistry().register({ EventRecord: 'EventRecord0to76' }); - } - this._rx.extrinsicType = this._extrinsicType; this._rx.genesisHash = this._genesisHash; this._rx.runtimeVersion = this._runtimeVersion; diff --git a/packages/types/src/codec/typeRegistry.ts b/packages/types/src/codec/typeRegistry.ts index 91e244d4e3eb..e879e93098e4 100644 --- a/packages/types/src/codec/typeRegistry.ts +++ b/packages/types/src/codec/typeRegistry.ts @@ -44,6 +44,11 @@ export class TypeRegistry { // This _looks_ a bit funny, but `typeof Clazz === 'function' this._registry.set(name, type); } else { + // when registering, remove the old value + if (this._registry.has(name)) { + this._registry.delete(name); + } + // We only create types on-demand, so just register the definition this._definitions.set(name, ( isString(type) @@ -75,6 +80,10 @@ export class TypeRegistry { return Type as Constructor; } + public getDefinition (name: string): string | undefined { + return this._definitions.get(name); + } + public getOrThrow (name: string, msg?: string): Constructor { const type = this.get(name); diff --git a/packages/types/src/injector.ts b/packages/types/src/injector.ts index 6a2fc91255d8..7b81a47b45e7 100644 --- a/packages/types/src/injector.ts +++ b/packages/types/src/injector.ts @@ -2,6 +2,7 @@ // This software may be modified and distributed under the terms // of the Apache-2.0 license. See the LICENSE file for details. +import { ClassOf } from './codec/createType'; import getTypeRegistry from './codec/typeRegistry'; import * as definitions from './interfaces/definitions'; import * as baseTypes from './index.types'; @@ -19,6 +20,11 @@ export function injectTypes (): void { Object.values(definitions).forEach(({ types }): void => registry.register(types) ); + + // FIXME Register the fallbacks. The issue with this atm is that it forcibly + // creates the actual classes here, which is something we don't really want, + // we want it do be done on-demand. Def. an issue if it expands in-use + ClassOf('EventRecord').Fallback = ClassOf('EventRecord0to76'); } injectTypes(); From 9ad95c172b480c2419d9f2c09a0b6b3b41a3802d Mon Sep 17 00:00:00 2001 From: Jaco Greeff Date: Sat, 10 Aug 2019 12:52:12 +0200 Subject: [PATCH 05/11] Cleanup registration, user-types takes priority --- packages/api/src/Base.ts | 19 +++++++------------ packages/types/src/codec/typeRegistry.ts | 7 ++++++- packages/types/src/injector.ts | 4 ++-- 3 files changed, 15 insertions(+), 15 deletions(-) diff --git a/packages/api/src/Base.ts b/packages/api/src/Base.ts index 1b9863d328de..99988cd89647 100644 --- a/packages/api/src/Base.ts +++ b/packages/api/src/Base.ts @@ -22,7 +22,6 @@ import { WsProvider } from '@polkadot/rpc-provider'; import { getTypeRegistry, GenericCall, GenericEvent, Metadata, Null, u64 } from '@polkadot/types'; import Linkage, { LinkageResult } from '@polkadot/types/codec/Linkage'; import { DEFAULT_VERSION as EXTRINSIC_DEFAULT_VERSION } from '@polkadot/types/primitive/Extrinsic/constants'; -import * as interfacesTypes from '@polkadot/types/interfaces/definitions'; import { StorageEntry } from '@polkadot/types/primitive/StorageKey'; import { assert, compactStripLength, isFunction, isObject, isString, isUndefined, logger, u8aToHex, u8aToU8a } from '@polkadot/util'; import { cryptoWaitReady } from '@polkadot/util-crypto'; @@ -125,6 +124,13 @@ export default abstract class ApiBase { ? options.source._rpcCore.provider.clone() : (options.provider || new WsProvider()); + // We only register the types (global) if this is not a cloned instance. + // Do right up-front, so we get in the user types before we are actually + // doing anything on-chain, this ensures we have the overrides in-place + if (!options.source && options.types) { + this.registerTypes(options.types); + } + this._options = options; this._type = type; this._eventemitter = new EventEmitter(); @@ -139,17 +145,6 @@ export default abstract class ApiBase { this._rx.queryMulti = this.decorateMulti(rxDecorateMethod); this._rx.signer = options.signer; - // we only re-register the types (global) if this is not a cloned instance - if (!options.source) { - // first register the definitions we have, i.e. those where there are no type classes - Object.values(interfacesTypes).forEach(({ types }): void => - this.registerTypes(types) - ); - - // next register all the user types - this.registerTypes(options.types); - } - this.init(); } diff --git a/packages/types/src/codec/typeRegistry.ts b/packages/types/src/codec/typeRegistry.ts index e879e93098e4..8615662215ef 100644 --- a/packages/types/src/codec/typeRegistry.ts +++ b/packages/types/src/codec/typeRegistry.ts @@ -69,9 +69,14 @@ export class TypeRegistry { // we have a definition, so create the class now (lazily) if (definition) { + const BaseType = createClass(definition); + // NOTE If we didn't extend here, we would have strange artifacts. An example is // Balance, with this, new Balance() instanceof u128 is true, but Balance !== u128 - Type = class extends createClass(definition) {}; + Type = class extends BaseType { + // ensure we carry through any fallbacks identified - since there are now lower + public static Fallback = BaseType.Fallback; + }; this._registry.set(name, Type); } diff --git a/packages/types/src/injector.ts b/packages/types/src/injector.ts index 7b81a47b45e7..e7ea54145edb 100644 --- a/packages/types/src/injector.ts +++ b/packages/types/src/injector.ts @@ -23,8 +23,8 @@ export function injectTypes (): void { // FIXME Register the fallbacks. The issue with this atm is that it forcibly // creates the actual classes here, which is something we don't really want, - // we want it do be done on-demand. Def. an issue if it expands in-use - ClassOf('EventRecord').Fallback = ClassOf('EventRecord0to76'); + // we want it do be done on-demand, not up-front. + ClassOf('Vec').Fallback = ClassOf('Vec'); } injectTypes(); From 0cb8a17a1ed33149861c59f4d628a7ef5ea24669 Mon Sep 17 00:00:00 2001 From: Jaco Greeff Date: Sat, 10 Aug 2019 12:53:46 +0200 Subject: [PATCH 06/11] typo --- packages/types/src/codec/typeRegistry.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/types/src/codec/typeRegistry.ts b/packages/types/src/codec/typeRegistry.ts index 8615662215ef..1e9d2d922863 100644 --- a/packages/types/src/codec/typeRegistry.ts +++ b/packages/types/src/codec/typeRegistry.ts @@ -74,7 +74,7 @@ export class TypeRegistry { // NOTE If we didn't extend here, we would have strange artifacts. An example is // Balance, with this, new Balance() instanceof u128 is true, but Balance !== u128 Type = class extends BaseType { - // ensure we carry through any fallbacks identified - since there are now lower + // ensure we carry through any fallbacks identified - since they are now lower public static Fallback = BaseType.Fallback; }; From 8725d00732acaca7a5f6ea344f0aa15286beca3f Mon Sep 17 00:00:00 2001 From: Jaco Greeff Date: Sat, 10 Aug 2019 13:08:31 +0200 Subject: [PATCH 07/11] Api constructors only take options --- CHANGELOG.md | 1 + docs/examples/promise/01_simple_connect/index.js | 2 +- docs/examples/promise/10_upgrade_chain/index.js | 2 +- docs/examples/rx/01_simple_connect/index.js | 2 +- docs/examples/rx/10_upgrade_chain/index.js | 2 +- packages/api-derive/src/index.spec.ts | 2 +- packages/api/src/Base.ts | 8 ++------ packages/api/src/promise/Api.ts | 7 +++---- packages/api/src/rx/Api.ts | 9 ++++----- packages/api/test/e2e/api-derive/promise-dev.spec.ts | 2 +- packages/api/test/e2e/api-derive/promise.spec.ts | 2 +- packages/api/test/e2e/api-derive/rx.spec.ts | 2 +- packages/api/test/e2e/api/promise-alex-archive.spec.ts | 2 +- packages/api/test/e2e/api/promise-alex.spec.ts | 2 +- packages/api/test/e2e/api/promise-consts.spec.ts | 2 +- packages/api/test/e2e/api/promise-contract.spec.ts | 2 +- packages/api/test/e2e/api/promise-queries-dev.spec.ts | 2 +- .../api/test/e2e/api/promise-queries-doubleMap.spec.ts | 2 +- packages/api/test/e2e/api/promise-queries.spec.ts | 2 +- packages/api/test/e2e/api/promise-tx-chained.spec.ts | 2 +- packages/api/test/e2e/api/promise-tx-eras.spec.ts | 2 +- packages/api/test/e2e/api/promise-tx-signer.spec.ts | 2 +- packages/api/test/e2e/api/promise-tx.spec.ts | 2 +- packages/api/test/e2e/api/rx-queries-dev.spec.ts | 2 +- packages/api/test/e2e/api/rx-queries.spec.ts | 2 +- packages/api/test/e2e/api/rx-tx.spec.ts | 2 +- packages/api/test/e2e/rpc-core/child-storage.spec.ts | 4 ++-- 27 files changed, 34 insertions(+), 39 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2fa7ad67876c..7377a89c4622 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,7 @@ If you are upgrading form an older version, use the CHANGELOG hand-in-hand with the [migration guide](UPGRADING.md). +- **Breaking change** `Api.create` now only takes an options Object, so if you passed thr provider directly previously, you need to do `Api.create({ provider: ... })` - Support substrate v7 metadata - The `Method.findFunction(callIndex)` (allowing decoding of raw data), is now available on `api.findCall(callIndex)`. To keep backwards compatibility, it is still available on `GenericCall.findMethod` but the `api.findCall` is recommended and suggested. - Runtime types have been extended and moved to definitions instead of classes diff --git a/docs/examples/promise/01_simple_connect/index.js b/docs/examples/promise/01_simple_connect/index.js index 4dff56ac9c5a..a9e37448bf17 100755 --- a/docs/examples/promise/01_simple_connect/index.js +++ b/docs/examples/promise/01_simple_connect/index.js @@ -7,7 +7,7 @@ async function main () { const provider = new WsProvider('ws://127.0.0.1:9944'); // Create the API and wait until ready - const api = await ApiPromise.create(provider); + const api = await ApiPromise.create({ provider }); // Retrieve the chain & node information information via rpc calls const [chain, nodeName, nodeVersion] = await Promise.all([ diff --git a/docs/examples/promise/10_upgrade_chain/index.js b/docs/examples/promise/10_upgrade_chain/index.js index b75864bb35cb..48eb2d7409ff 100755 --- a/docs/examples/promise/10_upgrade_chain/index.js +++ b/docs/examples/promise/10_upgrade_chain/index.js @@ -12,7 +12,7 @@ async function main () { const provider = new WsProvider('ws://127.0.0.1:9944'); // Create the API and wait until ready (optional provider passed through) - const api = await ApiPromise.create(provider); + const api = await ApiPromise.create({ provider }); // retrieve the upgrade key from the chain state const adminId = await api.query.sudo.key(); diff --git a/docs/examples/rx/01_simple_connect/index.js b/docs/examples/rx/01_simple_connect/index.js index 4110d40f2788..2e48f2474dfd 100644 --- a/docs/examples/rx/01_simple_connect/index.js +++ b/docs/examples/rx/01_simple_connect/index.js @@ -9,7 +9,7 @@ function main () { const provider = new WsProvider('ws://127.0.0.1:9944'); // Create the API and wait until ready - const api = await ApiRx.create(provider).toPromise(); + const api = await ApiRx.create({ provider }).toPromise(); // We're using RxJs 'zip()' combination operator to get the emitted values // of multiple observables as an array diff --git a/docs/examples/rx/10_upgrade_chain/index.js b/docs/examples/rx/10_upgrade_chain/index.js index ab10ee720de6..f88f31185618 100644 --- a/docs/examples/rx/10_upgrade_chain/index.js +++ b/docs/examples/rx/10_upgrade_chain/index.js @@ -10,7 +10,7 @@ async function main () { const provider = new WsProvider('ws://127.0.0.1:9944'); // Create the API and wait until ready (optional provider passed through) - const api = await ApiRx.create(provider).toPromise(); + const api = await ApiRx.create({ provider }).toPromise(); // retrieve the upgrade key from the chain state const adminId = await api.query.sudo.key().toPromise(); diff --git a/packages/api-derive/src/index.spec.ts b/packages/api-derive/src/index.spec.ts index f7121084df4c..f273f51cf735 100644 --- a/packages/api-derive/src/index.spec.ts +++ b/packages/api-derive/src/index.spec.ts @@ -27,7 +27,7 @@ const testFunction = (api: ApiRx): any => { describe('derive', (): void => { describe('builtin', (): void => { - const api = new ApiRx(new MockProvider()); + const api = new ApiRx({ provider: new MockProvider() }); beforeAll((done): void => { api.isReady.subscribe((): void => done()); diff --git a/packages/api/src/Base.ts b/packages/api/src/Base.ts index 99988cd89647..3db2fdd550a2 100644 --- a/packages/api/src/Base.ts +++ b/packages/api/src/Base.ts @@ -3,7 +3,6 @@ // of the Apache-2.0 license. See the LICENSE file for details. import { RpcInterface } from '@polkadot/rpc-core/jsonrpc.types'; -import { ProviderInterface } from '@polkadot/rpc-provider/types'; import { Hash, RuntimeVersion, SignedBlock } from '@polkadot/types/interfaces'; import { AnyFunction, CallFunction, Codec, CodecArg, ModulesWithCalls, RegistryTypes } from '@polkadot/types/types'; import { ApiInterfaceRx, ApiInterfaceEvents, ApiOptions, ApiTypes, DecorateMethodOptions, DecoratedRpc, DecoratedRpcSection, QueryableModuleStorage, QueryableStorage, QueryableStorageEntry, QueryableStorageMulti, QueryableStorageMultiArg, QueryableStorageMultiArgs, SignerPayloadRawBase, SubmittableExtrinsicFunction, SubmittableExtrinsics, SubmittableModuleExtrinsics, Signer } from './types'; @@ -23,7 +22,7 @@ import { getTypeRegistry, GenericCall, GenericEvent, Metadata, Null, u64 } from import Linkage, { LinkageResult } from '@polkadot/types/codec/Linkage'; import { DEFAULT_VERSION as EXTRINSIC_DEFAULT_VERSION } from '@polkadot/types/primitive/Extrinsic/constants'; import { StorageEntry } from '@polkadot/types/primitive/StorageKey'; -import { assert, compactStripLength, isFunction, isObject, isString, isUndefined, logger, u8aToHex, u8aToU8a } from '@polkadot/util'; +import { assert, compactStripLength, isString, isUndefined, logger, u8aToHex, u8aToU8a } from '@polkadot/util'; import { cryptoWaitReady } from '@polkadot/util-crypto'; import createSubmittable, { SubmittableExtrinsic } from './SubmittableExtrinsic'; @@ -116,10 +115,7 @@ export default abstract class ApiBase { * }); * ``` */ - public constructor (provider: ApiOptions | ProviderInterface = {}, type: ApiTypes) { - const options = isObject(provider) && isFunction((provider as ProviderInterface).send) - ? { provider } as unknown as ApiOptions - : provider as ApiOptions; + public constructor (options: ApiOptions = {}, type: ApiTypes) { const thisProvider = options.source ? options.source._rpcCore.provider.clone() : (options.provider || new WsProvider()); diff --git a/packages/api/src/promise/Api.ts b/packages/api/src/promise/Api.ts index 5c2a592600dc..8dde2d576ae7 100644 --- a/packages/api/src/promise/Api.ts +++ b/packages/api/src/promise/Api.ts @@ -2,7 +2,6 @@ // This software may be modified and distributed under the terms // of the Apache-2.0 license. See the LICENSE file for details. -import { ProviderInterface } from '@polkadot/rpc-provider/types'; import { AnyFunction, Callback, Codec } from '@polkadot/types/types'; import { ApiOptions, DecorateMethodOptions, ObsInnerType, StorageEntryPromiseOverloads, UnsubscribePromise } from '../types'; @@ -55,7 +54,7 @@ import Combinator, { CombinatorCallback, CombinatorFunction } from './Combinator * const provider = new WsProvider('wss://example.com:9944') * * // initialise via isReady & new with specific provider - * const api = await new ApiPromise(provider).isReady; + * const api = await new ApiPromise({ provider }).isReady; * * // retrieve the block target time * const blockPeriod = await api.query.timestamp.blockPeriod().toNumber(); @@ -120,7 +119,7 @@ export default class ApiPromise extends ApiBase<'promise'> { * }); * ``` */ - public static create (options: ApiOptions | ProviderInterface = {}): Promise { + public static create (options?: ApiOptions): Promise { return new ApiPromise(options).isReady; } @@ -143,7 +142,7 @@ export default class ApiPromise extends ApiBase<'promise'> { * }); * ``` */ - public constructor (options?: ApiOptions | ProviderInterface) { + public constructor (options?: ApiOptions) { super(options, 'promise'); this._isReadyPromise = new Promise((resolve): void => { diff --git a/packages/api/src/rx/Api.ts b/packages/api/src/rx/Api.ts index fe67b3854b38..c9ee5c39be12 100644 --- a/packages/api/src/rx/Api.ts +++ b/packages/api/src/rx/Api.ts @@ -2,7 +2,6 @@ // This software may be modified and distributed under the terms // of the Apache-2.0 license. See the LICENSE file for details. -import { ProviderInterface } from '@polkadot/rpc-provider/types'; import { AnyFunction } from '@polkadot/types/types'; import { ApiOptions } from '../types'; @@ -55,7 +54,7 @@ import ApiBase from '../Base'; * const provider = new WsProvider('wss://example.com:9944') * * // initialise via isReady & new with specific provider - * new ApiRx(provider) + * new ApiRx({ provider }) * .isReady * .pipe( * switchMap((api) => @@ -135,7 +134,7 @@ export default class ApiRx extends ApiBase<'rxjs'> { * }); * ``` */ - public static create (options?: ApiOptions | ProviderInterface): Observable { + public static create (options?: ApiOptions): Observable { return new ApiRx(options).isReady; } @@ -161,8 +160,8 @@ export default class ApiRx extends ApiBase<'rxjs'> { * }); * ``` */ - public constructor (provider?: ApiOptions | ProviderInterface) { - super(provider, 'rxjs'); + public constructor (options?: ApiOptions) { + super(options, 'rxjs'); this._isReadyRx = from( // convinced you can observable from an event, however my mind groks this form better diff --git a/packages/api/test/e2e/api-derive/promise-dev.spec.ts b/packages/api/test/e2e/api-derive/promise-dev.spec.ts index ee6bcaae115b..dfad66ac4877 100644 --- a/packages/api/test/e2e/api-derive/promise-dev.spec.ts +++ b/packages/api/test/e2e/api-derive/promise-dev.spec.ts @@ -21,7 +21,7 @@ describeE2E({ let api: ApiPromise; beforeEach(async (done): Promise => { - api = await ApiPromise.create(new WsProvider(wsUrl)); + api = await ApiPromise.create({ provider: new WsProvider(wsUrl) }); done(); }); diff --git a/packages/api/test/e2e/api-derive/promise.spec.ts b/packages/api/test/e2e/api-derive/promise.spec.ts index c4127e0c807c..245a2b0a6b2c 100644 --- a/packages/api/test/e2e/api-derive/promise.spec.ts +++ b/packages/api/test/e2e/api-derive/promise.spec.ts @@ -13,7 +13,7 @@ describeE2E()('Derive Promise e2e', (wsUrl: string): void => { let api: ApiPromise; beforeEach(async (done): Promise => { - api = await ApiPromise.create(new WsProvider(wsUrl)); + api = await ApiPromise.create({ provider: new WsProvider(wsUrl) }); done(); }); diff --git a/packages/api/test/e2e/api-derive/rx.spec.ts b/packages/api/test/e2e/api-derive/rx.spec.ts index b6acb11f43e3..a9bfc417f759 100644 --- a/packages/api/test/e2e/api-derive/rx.spec.ts +++ b/packages/api/test/e2e/api-derive/rx.spec.ts @@ -31,7 +31,7 @@ describeE2E({ }); beforeEach(async (done): Promise => { - api = await ApiRx.create(new WsProvider(wsUrl)).toPromise(); + api = await ApiRx.create({ provider: new WsProvider(wsUrl) }).toPromise(); done(); }); diff --git a/packages/api/test/e2e/api/promise-alex-archive.spec.ts b/packages/api/test/e2e/api/promise-alex-archive.spec.ts index e9c6c7a952f0..aa49bccf2058 100644 --- a/packages/api/test/e2e/api/promise-alex-archive.spec.ts +++ b/packages/api/test/e2e/api/promise-alex-archive.spec.ts @@ -15,7 +15,7 @@ describeE2E({ let api: ApiPromise; beforeEach(async (done): Promise => { - api = await ApiPromise.create(new WsProvider(wsUrl)); + api = await ApiPromise.create({ provider: new WsProvider(wsUrl) }); done(); }); diff --git a/packages/api/test/e2e/api/promise-alex.spec.ts b/packages/api/test/e2e/api/promise-alex.spec.ts index 6b1b82bf639c..79dd9f8032a8 100644 --- a/packages/api/test/e2e/api/promise-alex.spec.ts +++ b/packages/api/test/e2e/api/promise-alex.spec.ts @@ -16,7 +16,7 @@ describeE2E({ let api: ApiPromise; beforeEach(async (done): Promise => { - api = await ApiPromise.create(new WsProvider(wsUrl)); + api = await ApiPromise.create({ provider: new WsProvider(wsUrl) }); done(); }); diff --git a/packages/api/test/e2e/api/promise-consts.spec.ts b/packages/api/test/e2e/api/promise-consts.spec.ts index fab1e1a9f73b..8556e3700110 100644 --- a/packages/api/test/e2e/api/promise-consts.spec.ts +++ b/packages/api/test/e2e/api/promise-consts.spec.ts @@ -19,7 +19,7 @@ describeE2E({ let api: ApiPromise; beforeEach(async (done): Promise => { - api = await ApiPromise.create(new WsProvider(wsUrl)); + api = await ApiPromise.create({ provider: new WsProvider(wsUrl) }); done(); }); diff --git a/packages/api/test/e2e/api/promise-contract.spec.ts b/packages/api/test/e2e/api/promise-contract.spec.ts index 48d7c53474a4..ae98419b680d 100644 --- a/packages/api/test/e2e/api/promise-contract.spec.ts +++ b/packages/api/test/e2e/api/promise-contract.spec.ts @@ -37,7 +37,7 @@ describeE2E({ let CREATION_FEE: number; beforeEach(async (done): Promise => { - api = await ApiPromise.create(new WsProvider(wsUrl)); + api = await ApiPromise.create({ provider: new WsProvider(wsUrl) }); CREATION_FEE = 123456789123456; done(); diff --git a/packages/api/test/e2e/api/promise-queries-dev.spec.ts b/packages/api/test/e2e/api/promise-queries-dev.spec.ts index 88d3d0a70d01..b6e5ef5e52f5 100644 --- a/packages/api/test/e2e/api/promise-queries-dev.spec.ts +++ b/packages/api/test/e2e/api/promise-queries-dev.spec.ts @@ -26,7 +26,7 @@ describeE2E({ let api: ApiPromise; beforeEach(async (done): Promise => { - api = await ApiPromise.create(new WsProvider(wsUrl)); + api = await ApiPromise.create({ provider: new WsProvider(wsUrl) }); done(); }); diff --git a/packages/api/test/e2e/api/promise-queries-doubleMap.spec.ts b/packages/api/test/e2e/api/promise-queries-doubleMap.spec.ts index 1e4c960f1a13..d27028d6b13d 100644 --- a/packages/api/test/e2e/api/promise-queries-doubleMap.spec.ts +++ b/packages/api/test/e2e/api/promise-queries-doubleMap.spec.ts @@ -25,7 +25,7 @@ describeE2E({ const keyring = testingPairs({ type: 'ed25519' }); beforeEach(async (done): Promise => { - api = await ApiPromise.create(new WsProvider(wsUrl)); + api = await ApiPromise.create({ provider: new WsProvider(wsUrl) }); done(); }); diff --git a/packages/api/test/e2e/api/promise-queries.spec.ts b/packages/api/test/e2e/api/promise-queries.spec.ts index e06e3a6874a2..4b0e7a66ede3 100644 --- a/packages/api/test/e2e/api/promise-queries.spec.ts +++ b/packages/api/test/e2e/api/promise-queries.spec.ts @@ -16,7 +16,7 @@ describeE2E()('Promise e2e queries', (wsUrl: string): void => { let api: ApiPromise; beforeEach(async (done): Promise => { - api = await ApiPromise.create(new WsProvider(wsUrl)); + api = await ApiPromise.create({ provider: new WsProvider(wsUrl) }); done(); }); diff --git a/packages/api/test/e2e/api/promise-tx-chained.spec.ts b/packages/api/test/e2e/api/promise-tx-chained.spec.ts index 1f3bf7b42bcd..f693d124adc2 100644 --- a/packages/api/test/e2e/api/promise-tx-chained.spec.ts +++ b/packages/api/test/e2e/api/promise-tx-chained.spec.ts @@ -37,7 +37,7 @@ describeE2E({ let api: ApiPromise; beforeEach(async (done): Promise => { - api = await ApiPromise.create(new WsProvider(wsUrl)); + api = await ApiPromise.create({ provider: new WsProvider(wsUrl) }); done(); }); diff --git a/packages/api/test/e2e/api/promise-tx-eras.spec.ts b/packages/api/test/e2e/api/promise-tx-eras.spec.ts index 11f935c72912..22c996b78dc4 100644 --- a/packages/api/test/e2e/api/promise-tx-eras.spec.ts +++ b/packages/api/test/e2e/api/promise-tx-eras.spec.ts @@ -43,7 +43,7 @@ describeE2E({ let api: ApiPromise; beforeEach(async (done): Promise => { - api = await ApiPromise.create(new WsProvider(wsUrl)); + api = await ApiPromise.create({ provider: new WsProvider(wsUrl) }); done(); }); diff --git a/packages/api/test/e2e/api/promise-tx-signer.spec.ts b/packages/api/test/e2e/api/promise-tx-signer.spec.ts index f502be55005d..0eb43800708a 100644 --- a/packages/api/test/e2e/api/promise-tx-signer.spec.ts +++ b/packages/api/test/e2e/api/promise-tx-signer.spec.ts @@ -37,7 +37,7 @@ describeE2E({ let api: ApiPromise; beforeEach(async (done): Promise => { - api = await ApiPromise.create(new WsProvider(wsUrl)); + api = await ApiPromise.create({ provider: new WsProvider(wsUrl) }); done(); }); diff --git a/packages/api/test/e2e/api/promise-tx.spec.ts b/packages/api/test/e2e/api/promise-tx.spec.ts index 1d8b56b85aa3..eccb3b505dfd 100644 --- a/packages/api/test/e2e/api/promise-tx.spec.ts +++ b/packages/api/test/e2e/api/promise-tx.spec.ts @@ -40,7 +40,7 @@ describeE2E({ let api: ApiPromise; beforeEach(async (done): Promise => { - api = await ApiPromise.create(new WsProvider(wsUrl)); + api = await ApiPromise.create({ provider: new WsProvider(wsUrl) }); done(); }); diff --git a/packages/api/test/e2e/api/rx-queries-dev.spec.ts b/packages/api/test/e2e/api/rx-queries-dev.spec.ts index 7128bb4f240a..63f3d5a4f1f4 100644 --- a/packages/api/test/e2e/api/rx-queries-dev.spec.ts +++ b/packages/api/test/e2e/api/rx-queries-dev.spec.ts @@ -21,7 +21,7 @@ describeE2E({ let api: ApiRx; beforeEach(async (done): Promise => { - api = await ApiRx.create(new WsProvider(wsUrl)).toPromise(); + api = await ApiRx.create({ provider: new WsProvider(wsUrl) }).toPromise(); done(); }); diff --git a/packages/api/test/e2e/api/rx-queries.spec.ts b/packages/api/test/e2e/api/rx-queries.spec.ts index f6a0108a6de3..13e273aa81d8 100644 --- a/packages/api/test/e2e/api/rx-queries.spec.ts +++ b/packages/api/test/e2e/api/rx-queries.spec.ts @@ -15,7 +15,7 @@ describeE2E()('Rx e2e queries', (wsUrl: string): void => { let api: ApiRx; beforeEach(async (done): Promise => { - api = await ApiRx.create(new WsProvider(wsUrl)).toPromise(); + api = await ApiRx.create({ provider: new WsProvider(wsUrl) }).toPromise(); done(); }); diff --git a/packages/api/test/e2e/api/rx-tx.spec.ts b/packages/api/test/e2e/api/rx-tx.spec.ts index 273823e03539..9595f6580005 100644 --- a/packages/api/test/e2e/api/rx-tx.spec.ts +++ b/packages/api/test/e2e/api/rx-tx.spec.ts @@ -21,7 +21,7 @@ describeE2E()('Rx e2e transactions', (wsUrl: string): void => { let api: ApiRx; beforeEach(async (done): Promise => { - api = await ApiRx.create(new WsProvider(wsUrl)).toPromise(); + api = await ApiRx.create({ provider: new WsProvider(wsUrl) }).toPromise(); done(); }); diff --git a/packages/api/test/e2e/rpc-core/child-storage.spec.ts b/packages/api/test/e2e/rpc-core/child-storage.spec.ts index f8350170bc5a..fa9a7075019e 100644 --- a/packages/api/test/e2e/rpc-core/child-storage.spec.ts +++ b/packages/api/test/e2e/rpc-core/child-storage.spec.ts @@ -46,7 +46,7 @@ describeE2E({ beforeAll(async (done): Promise<() => void> => { abi = new Abi(incrementerAbi); - api = await ApiPromise.create(new WsProvider(wsUrl)); + api = await ApiPromise.create({ provider: new WsProvider(wsUrl) }); return ( api.tx.contracts .putCode(MAX_GAS, `0x${incrementerCode}`) @@ -73,7 +73,7 @@ describeE2E({ describe('e2e state child methods', (): void => { beforeAll(async (done): Promise<() => void> => { abi = new Abi(incrementerAbi); - api = await ApiPromise.create(new WsProvider(wsUrl)); + api = await ApiPromise.create({ provider: new WsProvider(wsUrl) }); // An instance of a contract can only be deployed once by one specific account. // That's why we need a random starting point for our incrementer contract to be // able to run this test multiple times without the need of pruning the database From 00df244ed00f59e0bbe4df0aafa4395050d17278 Mon Sep 17 00:00:00 2001 From: Jaco Greeff Date: Sat, 10 Aug 2019 13:10:00 +0200 Subject: [PATCH 08/11] Cleanup typos --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 7377a89c4622..e88a722fdcc1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,7 +2,7 @@ If you are upgrading form an older version, use the CHANGELOG hand-in-hand with the [migration guide](UPGRADING.md). -- **Breaking change** `Api.create` now only takes an options Object, so if you passed thr provider directly previously, you need to do `Api.create({ provider: ... })` +- **Breaking change** `Api.create(...)` and `new Api(...)` now only takes an options Object, so if you passed the provider directly previously, you need to swap the use to `Api.create({ provider: ... })` - Support substrate v7 metadata - The `Method.findFunction(callIndex)` (allowing decoding of raw data), is now available on `api.findCall(callIndex)`. To keep backwards compatibility, it is still available on `GenericCall.findMethod` but the `api.findCall` is recommended and suggested. - Runtime types have been extended and moved to definitions instead of classes From 3deb380976c3ca1e469346592cab38e3d35ea1c7 Mon Sep 17 00:00:00 2001 From: Jaco Greeff Date: Sat, 10 Aug 2019 13:39:22 +0200 Subject: [PATCH 09/11] Don't create classes while validating metadata --- .../types/src/Metadata/util/validateTypes.ts | 4 +--- packages/types/src/codec/typeRegistry.ts | 22 +++++++++++-------- 2 files changed, 14 insertions(+), 12 deletions(-) diff --git a/packages/types/src/Metadata/util/validateTypes.ts b/packages/types/src/Metadata/util/validateTypes.ts index 06cc44dd874d..1d11ed620d65 100644 --- a/packages/types/src/Metadata/util/validateTypes.ts +++ b/packages/types/src/Metadata/util/validateTypes.ts @@ -4,8 +4,6 @@ import { TypeDef, TypeDefInfo, TypeDefExtVecFixed } from '../../codec/types'; -import { isUndefined } from '@polkadot/util'; - import { getTypeDef } from '../../codec/createType'; import flattenUniq from './flattenUniq'; import { getTypeRegistry } from '../../codec'; @@ -40,7 +38,7 @@ export default function validateTypes (types: string[], throwError: boolean): vo const typeRegistry = getTypeRegistry(); const missing = flattenUniq(extractTypes(types)).filter((type): boolean => - isUndefined(typeRegistry.get(type)) + !typeRegistry.hasType(type) ); if (missing.length !== 0) { diff --git a/packages/types/src/codec/typeRegistry.ts b/packages/types/src/codec/typeRegistry.ts index 1e9d2d922863..15503510989b 100644 --- a/packages/types/src/codec/typeRegistry.ts +++ b/packages/types/src/codec/typeRegistry.ts @@ -11,9 +11,9 @@ import { createClass } from './createType'; export class TypeRegistry { public static readonly defaultRegistry: TypeRegistry = new TypeRegistry(); - private _definitions: Map = new Map(); + private _classes: Map = new Map(); - private _registry: Map = new Map(); + private _definitions: Map = new Map(); public register (type: Constructor | RegistryTypes): void; @@ -26,12 +26,12 @@ export class TypeRegistry { const name = arg1; const type = arg2!; - this._registry.set(name, type); + this._classes.set(name, type); } else if (isFunction(arg1)) { const name = arg1.name; const type = arg1; - this._registry.set(name, type); + this._classes.set(name, type); } else { this.registerObject(arg1); } @@ -42,11 +42,11 @@ export class TypeRegistry { if (overwrite || !this.get(name)) { if (isFunction(type)) { // This _looks_ a bit funny, but `typeof Clazz === 'function' - this._registry.set(name, type); + this._classes.set(name, type); } else { // when registering, remove the old value - if (this._registry.has(name)) { - this._registry.delete(name); + if (this._classes.has(name)) { + this._classes.delete(name); } // We only create types on-demand, so just register the definition @@ -61,7 +61,7 @@ export class TypeRegistry { } public get (name: string): Constructor | undefined { - let Type = this._registry.get(name); + let Type = this._classes.get(name); // we have not already created the type, attempt it if (!Type) { @@ -78,7 +78,7 @@ export class TypeRegistry { public static Fallback = BaseType.Fallback; }; - this._registry.set(name, Type); + this._classes.set(name, Type); } } @@ -98,6 +98,10 @@ export class TypeRegistry { return type; } + + public hasType (name: string): boolean { + return this._classes.has(name) || this._definitions.has(name); + } } export default function getDefaultRegistry (): TypeRegistry { From 466a56f34f1101ab2a9705a1e933a54a02f1309f Mon Sep 17 00:00:00 2001 From: Jaco Greeff Date: Sat, 10 Aug 2019 13:57:50 +0200 Subject: [PATCH 10/11] Adjust badges... well, waiting for CI, so... --- README.md | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/README.md b/README.md index e1f25155a129..8939909e733b 100644 --- a/README.md +++ b/README.md @@ -1,12 +1,12 @@ -[![polkadotjs](https://img.shields.io/badge/polkadot-js-orange.svg?style=flat-square)](https://polkadot.js.org) -![license](https://img.shields.io/badge/License-Apache%202.0-blue.svg?style=flat-square) -[![npm](https://img.shields.io/npm/v/@polkadot/api.svg?style=flat-square)](https://www.npmjs.com/package/@polkadot/api) -[![beta](https://img.shields.io/npm/v/@polkadot/api/beta?label=beta&style=flat-square)](https://www.npmjs.com/package/@polkadot/api) -[![travisci](https://img.shields.io/travis/com/polkadot-js/api?label=travisci&style=flat-square)](https://travis-ci.com/polkadot-js/api) -[![circleci](https://img.shields.io/circleci/build/github/polkadot-js/api/master?label=circleci&style=flat-square)](https://circleci.com/gh/polkadot-js/api) -[![maintainability](https://img.shields.io/codeclimate/maintainability/polkadot-js/api.svg?style=flat-square)](https://codeclimate.com/github/polkadot-js/api) -[![coverage](https://img.shields.io/codeclimate/coverage/polkadot-js/api.svg?style=flat-square)](https://codeclimate.com/github/polkadot-js/api) -[![greenkeeper](https://img.shields.io/badge/greenkeeper-enabled-brightgreen.svg?style=flat-square)](https://greenkeeper.io/) +[![polkadotjs](https://img.shields.io/badge/polkadot-js-orange?style=for-the-badge)](https://polkadot.js.org) +![license](https://img.shields.io/badge/License-Apache%202.0-blue?label=&logo=apache&style=for-the-badge) +[![npm](https://img.shields.io/npm/v/@polkadot/api?label=&logo=npm&style=for-the-badge)](https://www.npmjs.com/package/@polkadot/api) +[![beta](https://img.shields.io/npm/v/@polkadot/api/beta?label=&logo=npm&&style=for-the-badge)](https://www.npmjs.com/package/@polkadot/api) +[![travisci](https://img.shields.io/travis/com/polkadot-js/api?label=&logo=travis&style=for-the-badge)](https://travis-ci.com/polkadot-js/api) +[![circleci](https://img.shields.io/circleci/build/github/polkadot-js/api/master?label=&logo=circleci&style=for-the-badge)](https://circleci.com/gh/polkadot-js/api) +[![maintainability](https://img.shields.io/codeclimate/maintainability/polkadot-js/api?label=&logo=code-climate&style=for-the-badge)](https://codeclimate.com/github/polkadot-js/api) +[![coverage](https://img.shields.io/codeclimate/coverage/polkadot-js/api?label=&logo=code-climatestyle=for-the-badge)](https://codeclimate.com/github/polkadot-js/api) +[![greenkeeper](https://img.shields.io/badge/greenkeeper-enabled-brightgreen?label=&logo=greenkeeper&style=for-the-badge)](https://greenkeeper.io/) # @polkadot/api From 724d10961b2d5a8078409dafe624780e59685847 Mon Sep 17 00:00:00 2001 From: Jaco Greeff Date: Sat, 10 Aug 2019 13:58:45 +0200 Subject: [PATCH 11/11] typo --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 8939909e733b..cab33552fb19 100644 --- a/README.md +++ b/README.md @@ -5,7 +5,7 @@ [![travisci](https://img.shields.io/travis/com/polkadot-js/api?label=&logo=travis&style=for-the-badge)](https://travis-ci.com/polkadot-js/api) [![circleci](https://img.shields.io/circleci/build/github/polkadot-js/api/master?label=&logo=circleci&style=for-the-badge)](https://circleci.com/gh/polkadot-js/api) [![maintainability](https://img.shields.io/codeclimate/maintainability/polkadot-js/api?label=&logo=code-climate&style=for-the-badge)](https://codeclimate.com/github/polkadot-js/api) -[![coverage](https://img.shields.io/codeclimate/coverage/polkadot-js/api?label=&logo=code-climatestyle=for-the-badge)](https://codeclimate.com/github/polkadot-js/api) +[![coverage](https://img.shields.io/codeclimate/coverage/polkadot-js/api?label=&logo=code-climate&style=for-the-badge)](https://codeclimate.com/github/polkadot-js/api) [![greenkeeper](https://img.shields.io/badge/greenkeeper-enabled-brightgreen?label=&logo=greenkeeper&style=for-the-badge)](https://greenkeeper.io/) # @polkadot/api