From 50a3a40cfdd1661a83e109070f0e5111c24bf466 Mon Sep 17 00:00:00 2001 From: Jaco Greeff Date: Wed, 10 Jul 2019 16:55:25 +0200 Subject: [PATCH] Auto-generate TS definitions from types (#1077) * Basic ts generation from JSON (parachains) * Basic enum jsdoc comments * Add as enum getter * Register types * Expand with other Polkadot types * Readability cleanups * cc * Remove extra Null check * Combine Vector & VectorFixed * cc * Additional magic type comments * Tuple has actual indexed types * Tests for Enum asXyz and isXyz getters * Dep-dupe imports setup * Small textual adjustments * DRY up with getTypeClassMap --- package.json | 1 + packages/api/src/Base.ts | 7 + packages/types/README.md | 6 +- packages/types/src/Metadata/util/testUtil.ts | 15 ++ packages/types/src/codec/Compact.spec.ts | 2 +- packages/types/src/codec/EnumType.spec.ts | 14 ++ packages/types/src/codec/EnumType.ts | 24 +++ packages/types/src/codec/Struct.spec.ts | 2 +- packages/types/src/codec/createType.ts | 26 ++- packages/types/src/codec/typeRegistry.ts | 1 + .../types/src/{type => primitive}/Balance.ts | 2 +- .../src/{type => primitive}/Signature.ts | 2 +- packages/types/src/primitive/index.ts | 4 + packages/types/src/rpc/Digest.ts | 2 +- packages/types/src/scripts/srmlTS.ts | 162 ++++++++++++++++ .../SubId.ts => scripts/srmlTSWrapper.js} | 13 +- .../AuctionIndex.ts => srml/definitions.ts} | 10 +- .../types/src/srml/parachains/definitions.ts | 94 ++++++++++ packages/types/src/srml/parachains/types.ts | 173 ++++++++++++++++++ packages/types/src/type/Amount.ts | 2 +- packages/types/src/type/AssetOf.ts | 2 +- packages/types/src/type/AttestedCandidate.ts | 102 ----------- packages/types/src/type/BalanceLock.ts | 2 +- packages/types/src/type/Bft.ts | 2 +- packages/types/src/type/Bidder.ts | 37 ---- packages/types/src/type/ContractInfo.ts | 2 +- packages/types/src/type/Exposure.ts | 2 +- packages/types/src/type/ExtrinsicSignature.ts | 2 +- packages/types/src/type/IncomingParachain.ts | 24 --- packages/types/src/type/IndividualExposure.ts | 2 +- packages/types/src/type/ParaId.ts | 21 --- packages/types/src/type/SlotRange.ts | 37 ---- packages/types/src/type/StakingLedger.ts | 2 +- packages/types/src/type/TreasuryProposal.ts | 2 +- packages/types/src/type/UnlockChunk.ts | 2 +- packages/types/src/type/UpwardMessage.ts | 48 ----- packages/types/src/type/ValidatorPrefs.ts | 2 +- packages/types/src/type/VestingSchedule.ts | 2 +- packages/types/src/type/VoterInfo.ts | 2 +- packages/types/src/type/WinningData.ts | 24 --- packages/types/src/type/index.ts | 11 -- packages/types/src/types.ts | 2 +- 42 files changed, 540 insertions(+), 354 deletions(-) rename packages/types/src/{type => primitive}/Balance.ts (95%) rename packages/types/src/{type => primitive}/Signature.ts (95%) create mode 100644 packages/types/src/scripts/srmlTS.ts rename packages/types/src/{type/SubId.ts => scripts/srmlTSWrapper.js} (53%) rename packages/types/src/{type/AuctionIndex.ts => srml/definitions.ts} (50%) create mode 100644 packages/types/src/srml/parachains/definitions.ts create mode 100644 packages/types/src/srml/parachains/types.ts delete mode 100644 packages/types/src/type/AttestedCandidate.ts delete mode 100644 packages/types/src/type/Bidder.ts delete mode 100644 packages/types/src/type/IncomingParachain.ts delete mode 100644 packages/types/src/type/ParaId.ts delete mode 100644 packages/types/src/type/SlotRange.ts delete mode 100644 packages/types/src/type/UpwardMessage.ts delete mode 100644 packages/types/src/type/WinningData.ts diff --git a/package.json b/package.json index 9fe2bc7690..94561be0b1 100644 --- a/package.json +++ b/package.json @@ -15,6 +15,7 @@ "build": "polkadot-dev-build-ts && yarn run build:methodsdoc && polkadot-dev-build-docs", "build:htmldoc": "yarn clean && typedoc --theme default --out docs/html", "build:methodsdoc": "node packages/types/src/scripts/MetadataMdWrapper.js", + "build:srmlTs": "node packages/types/src/scripts/srmlTSWrapper.js", "check": "yarn lint", "lint": "tslint --project . && tsc --noEmit --pretty", "clean": "polkadot-dev-clean-build", diff --git a/packages/api/src/Base.ts b/packages/api/src/Base.ts index f70bcce884..d9edcf108e 100644 --- a/packages/api/src/Base.ts +++ b/packages/api/src/Base.ts @@ -25,6 +25,7 @@ import { WsProvider } from '@polkadot/rpc-provider'; import { Event, getTypeRegistry, Hash, Metadata, Method, RuntimeVersion, Null } from '@polkadot/types'; import Linkage, { LinkageResult } from '@polkadot/types/codec/Linkage'; import { MethodFunction, ModulesWithMethods } from '@polkadot/types/primitive/Method'; +import * as srmlTypes from '@polkadot/types/srml/definitions'; import { StorageEntry } from '@polkadot/types/primitive/StorageKey'; import { assert, compactStripLength, isFunction, isObject, isUndefined, logger, u8aToHex } from '@polkadot/util'; import { cryptoWaitReady } from '@polkadot/util-crypto'; @@ -123,6 +124,12 @@ export default abstract class ApiBase { // 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(srmlTypes).forEach(({ types }) => + this.registerTypes(types) + ); + + // next register all the user types this.registerTypes(options.types); } diff --git a/packages/types/README.md b/packages/types/README.md index 462e3c13d1..174cd6c0e2 100644 --- a/packages/types/README.md +++ b/packages/types/README.md @@ -56,6 +56,7 @@ These primitive types are available: | [[Moment]] | A wrapper around seconds/timestamps. Internally the representation only has second precicion (aligning with Rust) | | [[Null]] | Implements a type that does not contain anything (apart from `null`) | | [[Origin]] | Where Origin occurs, it should be ignored as an internal-only value | +| [[Signature]] | The default signature that is used accross the system | | [[StorageData]] | Data retrieved via Storage queries and data for key-value pairs | | [[StorageKey]] | A representation of a storage key (typically hashed) in the system | | [[Text]] | This is a string wrapper, along with the length. | @@ -78,7 +79,6 @@ These custom types implement specific types that are found as part of the Substr | [[Amount]] | The Substrate Amount representation as a [[Balance]] | | [[ApprovalFlag]] | Approval flag, implemented as a [[U32]] | | [[AssetOf]] | The Substrate AssetOf representation as a [[Balance]] | -| [[AttestedCandidate]] | An attested candidate | | [[AuthorityId]] | Wrapper for a AuthorityId. Same as an normal AccountId | | [[AuthoritiesChange]] | Log for Authories changed | | [[AuthorityWeight]] | The weight of an authority | @@ -135,7 +135,6 @@ These custom types implement specific types that are found as part of the Substr | [[SessionKey]] | Wrapper for a SessionKey. Same as an normal [[AuthorityId]], i.e. a wrapper around publicKey | | [[SessionKeys]] | Wrapper for the session and authority ids | | [[SetIndex]] | Set index, implemented as a [[U32]] | -| [[Signature]] | The default signature that is used accross the system | | [[SignaturePayload]] | A signing payload for an [[Extrinsic]]. For the final encoding, it is variable length based on the contents included | | [[SignaturePayloadRaw]] | A version of the [[SignaturePayload]] where it doesn't rely on [[Method]] with metadata, rather it treats the values as a raw byte stream | | [[StakingLedger]] | The ledger of a (bonded) stash | @@ -161,6 +160,7 @@ These types are only available in Polkadot chains - | **Types** | | | --- | --- | | [[AuctionIndex]] | A parachain auction index as a [[U32]] | +| [[AttestedCandidate]] | An attested candidate | | [[Bidder]] | The desired target of a bidder in an auction. | | [[LeasePeriod]] | The length of the lease for a parachain | | [[LeasePeriodOf]] | The length of the lease for a parachain | @@ -173,7 +173,7 @@ These types are only available in Polkadot chains - | [[SubId]] | A sub-bidder identifier. Used to distinguish between different logical bidders coming from the same account ID. | | [[UpwardMessage]] | A message from a parachain to its Relay Chain | | [[WinningData]] | Winning data type. This encodes the top bidders of each range together with their bid. | -| [[WinningDataentry]] | And entry in the [[WinningData]] fixed vector | +| [[WinningDataEntry]] | And entry in the [[WinningData]] fixed vector | ## RPC types diff --git a/packages/types/src/Metadata/util/testUtil.ts b/packages/types/src/Metadata/util/testUtil.ts index 0016af7bdc..1ad1def43b 100644 --- a/packages/types/src/Metadata/util/testUtil.ts +++ b/packages/types/src/Metadata/util/testUtil.ts @@ -3,6 +3,8 @@ // of the Apache-2.0 license. See the LICENSE file for details. import extrinsicsFromMeta from '@polkadot/api-metadata/extrinsics/fromMetadata'; +import { getTypeRegistry } from '@polkadot/types'; +import * as srmlTypes from '@polkadot/types/srml/definitions'; import createType from '../../codec/createType'; import Metadata from '../Metadata'; @@ -10,6 +12,12 @@ import Method from '../../primitive/Method'; import { MetadataInterface } from '../types'; import { Codec } from '../../types'; +function injectDefinitions () { + Object.values(srmlTypes).forEach(({ types }) => + getTypeRegistry().register(types) + ); +} + /** * Given the static `rpcData` and the `latestSubstrate` JSON file, Metadata * should decode `rpcData` and output `latestSubstrate`. @@ -20,6 +28,8 @@ export function decodeLatestSubstrate ( latestSubstrate: object ) { it('decodes latest substrate properly', () => { + injectDefinitions(); + const metadata = new Metadata(rpcData); console.error(JSON.stringify(metadata.toJSON())); @@ -36,6 +46,8 @@ export function decodeLatestSubstrate ( */ export function toV6 (version: number, rpcData: string) { it('converts to V6', () => { + injectDefinitions(); + const metadata = new Metadata(rpcData)[`asV${version}` as keyof Metadata]; const metadataV6 = new Metadata(rpcData).asV6; @@ -50,7 +62,10 @@ export function toV6 (version: number, rpcData: string) { */ export function defaultValues (rpcData: string) { describe('storage with default values', () => { + injectDefinitions(); + const metadata = new Metadata(rpcData); + Method.injectMethods(extrinsicsFromMeta(metadata)); metadata.asV6.modules diff --git a/packages/types/src/codec/Compact.spec.ts b/packages/types/src/codec/Compact.spec.ts index 08b9178c31..2904111feb 100644 --- a/packages/types/src/codec/Compact.spec.ts +++ b/packages/types/src/codec/Compact.spec.ts @@ -4,9 +4,9 @@ import BN from 'bn.js'; +import Balance from '../primitive/Balance'; import Moment from '../primitive/Moment'; import U32 from '../primitive/U32'; -import Balance from '../type/Balance'; import BlockNumber from '../type/BlockNumber'; import Compact from './Compact'; import UInt from './UInt'; diff --git a/packages/types/src/codec/EnumType.spec.ts b/packages/types/src/codec/EnumType.spec.ts index c7beb2276e..a766ad498c 100644 --- a/packages/types/src/codec/EnumType.spec.ts +++ b/packages/types/src/codec/EnumType.spec.ts @@ -63,6 +63,14 @@ describe('Enum', () => { ).toEqual('Null'); }); + it('has correct isXyz/asXyz (Enum.with)', () => { + const test = new (Enum.with({ First: Text, Second: U32, Third: U32 }))({ 'Second': 42 }) as any as { isSecond: boolean, asSecond: U32, asThird: never }; + + expect(test.isSecond).toEqual(true); + expect(test.asSecond.toNumber()).toEqual(42); + expect(() => test.asThird).toThrow(/Cannot convert Second via asThird/); + }); + it('stringifies with custom types', () => { class A extends Null { } class B extends Null { } @@ -185,6 +193,12 @@ describe('Enum', () => { ).toEqual(4); }); + it('has correct isXyz getters (Enum.with)', () => { + const test = new (Enum.with(['First', 'Second', 'Third']))('Second') as any as { isSecond: boolean, asSecond: never }; + + expect(test.isSecond).toEqual(true); + }); + describe('utils', () => { it('compares agains the index value', () => { expect( diff --git a/packages/types/src/codec/EnumType.ts b/packages/types/src/codec/EnumType.ts index d9189553dd..a906b45c6d 100644 --- a/packages/types/src/codec/EnumType.ts +++ b/packages/types/src/codec/EnumType.ts @@ -127,6 +127,30 @@ export default class Enum extends Base implements Codec { return class extends Enum { constructor (value?: any, index?: number) { super(Types, value, index); + + Object.keys(this._def).forEach((_key) => { + const askey = `as${_key}`; + const iskey = `is${_key}`; + + // do not clobber existing properties on the object + if (isUndefined((this as any)[iskey])) { + Object.defineProperty(this, iskey, { + enumerable: true, + get: () => this.type === _key + }); + } + + if (isUndefined((this as any)[askey])) { + Object.defineProperty(this, askey, { + enumerable: true, + get: () => { + assert((this as any)[iskey], `Cannot convert ${this.type} via ${askey}`); + + return this.value; + } + }); + } + }); } }; } diff --git a/packages/types/src/codec/Struct.spec.ts b/packages/types/src/codec/Struct.spec.ts index c000f2bf7f..28ec1db03d 100644 --- a/packages/types/src/codec/Struct.spec.ts +++ b/packages/types/src/codec/Struct.spec.ts @@ -3,9 +3,9 @@ // of the Apache-2.0 license. See the LICENSE file for details. import AccountId from '../primitive/AccountId'; +import Balance from '../primitive/Balance'; import Text from '../primitive/Text'; import U32 from '../primitive/U32'; -import Balance from '../type/Balance'; import BlockNumber from '../type/BlockNumber'; import { CodecTo } from '../types'; import Compact from './Compact'; diff --git a/packages/types/src/codec/createType.ts b/packages/types/src/codec/createType.ts index b7aedd791b..01ea230de2 100644 --- a/packages/types/src/codec/createType.ts +++ b/packages/types/src/codec/createType.ts @@ -174,6 +174,15 @@ export function getTypeDef (_type: Text | string, name?: string): TypeDef { return value; } +// create an array of constructors from the input +export function getTypeClassMap (defs: Array): { [index: string]: Constructor } { + return defs.reduce((result, sub) => { + result[sub.name as string] = getTypeClass(sub); + + return result; + }, {} as { [index: string]: Constructor }); +} + // Returns the type Class for construction export function getTypeClass (value: TypeDef, Fallback?: Constructor): Constructor { const Type = getRegistry().get(value.type); @@ -193,11 +202,7 @@ export function getTypeClass (value: TypeDef, Fallback?: Constructor): Construct assert(value.sub && Array.isArray(value.sub), 'Expected subtype for Enum'); return Enum.with( - (value.sub as Array).reduce((result, sub, index) => { - result[sub.name as string] = getTypeClass(sub); - - return result; - }, {} as { [index: string]: Constructor }) + getTypeClassMap(value.sub as Array) ); case TypeDefInfo.Option: assert(value.sub && !Array.isArray(value.sub), 'Expected subtype for Option'); @@ -209,11 +214,7 @@ export function getTypeClass (value: TypeDef, Fallback?: Constructor): Construct assert(Array.isArray(value.sub), 'Expected nested subtypes for Struct'); return Struct.with( - (value.sub as Array).reduce((result, sub) => { - result[sub.name as string] = getTypeClass(sub); - - return result; - }, {} as { [index: string]: Constructor }) + getTypeClassMap(value.sub as Array) ); case TypeDefInfo.Tuple: assert(Array.isArray(value.sub), 'Expected nested subtypes for Tuple'); @@ -262,6 +263,11 @@ export function createClass (type: Text | string): Constructor { ); } +// alias for createClass +export function ClassOf (name: string): Constructor { + return createClass(name); +} + function initType (Type: Constructor, value?: any, isPedantic?: boolean): Codec { try { const created = new Type(value); diff --git a/packages/types/src/codec/typeRegistry.ts b/packages/types/src/codec/typeRegistry.ts index 21301c497d..477b753b10 100644 --- a/packages/types/src/codec/typeRegistry.ts +++ b/packages/types/src/codec/typeRegistry.ts @@ -51,6 +51,7 @@ export class TypeRegistry { getOrThrow (name: string, msg?: string): Constructor { const type = this.get(name); + if (isUndefined(type)) { throw new Error(msg || `type ${name} not found`); } diff --git a/packages/types/src/type/Balance.ts b/packages/types/src/primitive/Balance.ts similarity index 95% rename from packages/types/src/type/Balance.ts rename to packages/types/src/primitive/Balance.ts index 04e29c15c0..c0b1fb090f 100644 --- a/packages/types/src/type/Balance.ts +++ b/packages/types/src/primitive/Balance.ts @@ -2,7 +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 U128 from '../primitive/U128'; +import U128 from './U128'; /** * @name Balance diff --git a/packages/types/src/type/Signature.ts b/packages/types/src/primitive/Signature.ts similarity index 95% rename from packages/types/src/type/Signature.ts rename to packages/types/src/primitive/Signature.ts index 7a5c560e2e..4b3509024e 100644 --- a/packages/types/src/type/Signature.ts +++ b/packages/types/src/primitive/Signature.ts @@ -2,7 +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 H512 from '../primitive/H512'; +import H512 from './H512'; /** * @name Signature diff --git a/packages/types/src/primitive/index.ts b/packages/types/src/primitive/index.ts index 98968b35b6..34039c6af4 100644 --- a/packages/types/src/primitive/index.ts +++ b/packages/types/src/primitive/index.ts @@ -14,6 +14,9 @@ export { default as AccountId, AccountIdOf } from './AccountId'; export { default as AccountIndex } from './AccountIndex'; export { default as AccountInfo } from './AccountInfo'; export { default as Address } from './Address'; +// Balance is technically not a primitive, however since it is used in a number of interfaces +// and actually is problematic/impossible to be overridden, it is included here as well +export { default as Balance, BalanceOf } from './Balance'; export { default as Event, EventIndex } from './Event'; export { default as EventRecord, EventRecord_0_76 } from './EventRecord'; export { default as Bool, default as bool } from './Bool'; @@ -33,6 +36,7 @@ export { default as Method } from './Method'; export { default as Moment, MomentOf } from './Moment'; export { default as Null } from './Null'; export { default as Origin } from './Origin'; +export { default as Signature, Ed25519Signature, Sr25519Signature } from './Signature'; export { default as StorageData } from './StorageData'; export { default as StorageHasher } from './StorageHasher'; export { default as StorageKey } from './StorageKey'; diff --git a/packages/types/src/rpc/Digest.ts b/packages/types/src/rpc/Digest.ts index b668a3df90..23702c6dec 100644 --- a/packages/types/src/rpc/Digest.ts +++ b/packages/types/src/rpc/Digest.ts @@ -11,10 +11,10 @@ import Tuple from '../codec/Tuple'; import Vector from '../codec/Vector'; import Bytes from '../primitive/Bytes'; import Hash from '../primitive/Hash'; +import Signature from '../primitive/Signature'; import U32 from '../primitive/U32'; import U64 from '../primitive/U64'; import AuthorityId from '../type/AuthorityId'; -import Signature from '../type/Signature'; const CID_AURA = 0x61727561; // 'aura' const CID_BABE = 0x65626162; // 'babe' diff --git a/packages/types/src/scripts/srmlTS.ts b/packages/types/src/scripts/srmlTS.ts new file mode 100644 index 0000000000..ec265d3060 --- /dev/null +++ b/packages/types/src/scripts/srmlTS.ts @@ -0,0 +1,162 @@ +// Copyright 2017-2019 @polkadot/types authors & contributors +// This software may be modified and distributed under the terms +// of the Apache-2.0 license. See the LICENSE file for details. + +import fs from 'fs'; +import { isString } from '@polkadot/util'; + +import { getTypeDef, TypeDef, TypeDefInfo, TypeDefExtVecFixed } from '../codec/createType'; +import * as definitions from '../srml/definitions'; + +// these map all the codec and primitive types for import, see the TypeImports below. If +// we have an unseen type, it is `undefined`/`false`, if we need to import it, it is `true` +type TypeExist = { + [index: string]: boolean +}; +type TypeImports = { + codecTypes: TypeExist, + otherTypes: TypeExist, + ownTypes: Array +}; + +const HEADER = '// Auto-generated, do not edit\n\n'; +const FOOTER = '\n'; + +// handlers are defined externally to use - this means that when we do a +// `generators[typedef.info](...)` TS will show any unhandled types. Rather +// we are being explicit in having no handlers where we do not support (yet) +const generators = { + [TypeDefInfo.Compact]: errorUnhandled, + [TypeDefInfo.DoubleMap]: errorUnhandled, + [TypeDefInfo.Enum]: tsEnum, + [TypeDefInfo.Linkage]: errorUnhandled, + [TypeDefInfo.Null]: errorUnhandled, + [TypeDefInfo.Option]: errorUnhandled, + [TypeDefInfo.Plain]: tsPlain, + [TypeDefInfo.Struct]: tsStruct, + [TypeDefInfo.Tuple]: tsTuple, + [TypeDefInfo.Vector]: tsVector, + [TypeDefInfo.VectorFixed]: tsVector +}; + +function setImports ({ codecTypes, otherTypes, ownTypes }: TypeImports, type: string | null, codecType: string | null): void { + if (type && !ownTypes.includes(type) && !otherTypes[type]) { + otherTypes[type] = true; + } + + if (codecType) { + codecTypes[codecType] = true; + } +} + +function errorUnhandled (def: TypeDef, imports: TypeImports): string { + throw new Error(`Generate: ${name}: Unhandled type ${TypeDefInfo[def.info]}`); +} + +function tsEnum ({ name: enumName, sub }: TypeDef, imports: TypeImports): string { + setImports(imports, null, 'Enum'); + + const keys = (sub as Array).map(({ info, name, type }, index) => { + const [enumType, asGetter] = type === 'Null' + ? ['', ''] + : [`(${type})`, ` readonly as${name}: ${type};\n`]; + + switch (info) { + case TypeDefInfo.Plain: + return ` /**\n * @description ${index}:: ${name}${enumType}\n */\n readonly is${name}: boolean;\n${asGetter}`; + + default: + throw new Error(`Enum: ${enumName}: Unhandled type ${TypeDefInfo[info]}`); + } + }); + + return `export interface ${enumName} extends Enum {\n${keys.join('')}}`; +} + +function tsPlain ({ name: plainName, type }: TypeDef, imports: TypeImports): string { + setImports(imports, type, null); + + return `export interface ${plainName} extends ${type} {}`; +} + +function _tsStructGetterType (structName: string | undefined, { info, sub, type }: TypeDef): [string, string] { + switch (info) { + case TypeDefInfo.Plain: + return [type, type]; + + case TypeDefInfo.Vector: + const _type = (sub as TypeDef).type; + + return [_type, `Vector<${_type}>`]; + + default: + throw new Error(`Struct: ${structName}: Unhandled type ${TypeDefInfo[info]}`); + } +} + +function tsStruct ({ name: structName, sub }: TypeDef, imports: TypeImports): string { + const keys = (sub as Array).map((typedef) => { + const [embedType, returnType] = _tsStructGetterType(structName, typedef); + + setImports(imports, embedType, 'Struct'); + + return ` readonly ${typedef.name}: ${returnType};\n`; + }); + + return `export interface ${structName} extends Struct {\n${keys.join('')}}`; +} + +function tsTuple ({ name: tupleName, sub }: TypeDef, imports: TypeImports): string { + const types = (sub as Array).map(({ type }) => { + setImports(imports, type, 'Tuple'); + + return type; + }); + + // TODO We need some way here of identifying the fields + return `type _${tupleName} = [${types.join(', ')}];\nexport interface ${tupleName} extends Codec, _${tupleName} {}`; +} + +function tsVector ({ ext, info, name: vectorName, sub }: TypeDef, imports: TypeImports): string { + const type = info === TypeDefInfo.VectorFixed + ? (ext as TypeDefExtVecFixed).type + : (sub as TypeDef).type; + + setImports(imports, type, 'Vector'); + + return `export interface ${vectorName} extends Vector<${type}> {}`; +} + +function generateTsDef (srmlName: string, { types }: { types: { [index: string]: any } }): void { + const codecTypes: TypeExist = {}; + const otherTypes: TypeExist = {}; + const ownTypes = Object.keys(types); + const interfaces = Object.entries(types).map(([name, type]) => { + const def = getTypeDef(isString(type) ? type.toString() : JSON.stringify(type), name); + + return [name, generators[def.info](def, { codecTypes, otherTypes, ownTypes })]; + }); + + let header = HEADER; + const codecImports = Object.keys(codecTypes).filter((name) => name !== 'Tuple').sort(); + const primitiveImports = Object.keys(otherTypes).filter((type) => otherTypes[type]).sort(); + const sortedDefs = interfaces.sort((a, b) => a[0].localeCompare(b[0])).map(([, definition]) => definition); + + if (codecTypes['Tuple']) { + header = header.concat(`import { Codec } from '../../types';\n`); + } + + if (codecImports.length) { + header = header.concat(`import { ${codecImports.join(', ')} } from '../../codec';\n`); + } + + if (primitiveImports.length) { + header = header.concat(`import { ${primitiveImports.join(', ')} } from '../../primitive';\n`); + } + + fs.writeFileSync(`packages/types/src/srml/${srmlName}/types.ts`, header.concat('\n').concat(sortedDefs.join('\n\n')).concat(FOOTER), { flag: 'w' }); +} + +Object.entries(definitions).forEach(([name, obj]) => + generateTsDef(name, obj) +); diff --git a/packages/types/src/type/SubId.ts b/packages/types/src/scripts/srmlTSWrapper.js similarity index 53% rename from packages/types/src/type/SubId.ts rename to packages/types/src/scripts/srmlTSWrapper.js index 64263aea12..2f47849748 100644 --- a/packages/types/src/type/SubId.ts +++ b/packages/types/src/scripts/srmlTSWrapper.js @@ -1,13 +1,10 @@ +#!/usr/bin/env node // Copyright 2017-2019 @polkadot/types authors & contributors // This software may be modified and distributed under the terms // of the Apache-2.0 license. See the LICENSE file for details. -import U32 from '../primitive/U32'; +require('@babel/register')({ + extensions: ['.js', '.ts'] +}); -/** - * @name SubId - * @description - * An auction index. We count auctions in this type. - */ -export default class SubId extends U32 { -} +require('./srmlTS.ts'); diff --git a/packages/types/src/type/AuctionIndex.ts b/packages/types/src/srml/definitions.ts similarity index 50% rename from packages/types/src/type/AuctionIndex.ts rename to packages/types/src/srml/definitions.ts index 5285124aea..c0d877145c 100644 --- a/packages/types/src/type/AuctionIndex.ts +++ b/packages/types/src/srml/definitions.ts @@ -2,12 +2,4 @@ // This software may be modified and distributed under the terms // of the Apache-2.0 license. See the LICENSE file for details. -import U32 from '../primitive/U32'; - -/** - * @name AuctionIndex - * @description - * An auction index. We count auctions in this type. - */ -export default class AuctionIndex extends U32 { -} +export { default as parachains } from './parachains/definitions'; diff --git a/packages/types/src/srml/parachains/definitions.ts b/packages/types/src/srml/parachains/definitions.ts new file mode 100644 index 0000000000..9e132d3571 --- /dev/null +++ b/packages/types/src/srml/parachains/definitions.ts @@ -0,0 +1,94 @@ +// Copyright 2017-2019 @polkadot/types authors & contributors +// This software may be modified and distributed under the terms +// of the Apache-2.0 license. See the LICENSE file for details. + +export default { + types: { + AuctionIndex: 'u32', + CollatorSignature: 'Signature', + // Until we are able to import the SessionKey from grandpa, define as AccountId + AvailabilityVote: '(AccountId, CollatorSignature)', // '(SessionKey, CollatorSignature)', + 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 + } + }, + ParaId: 'u32', + ParaIdOf: 'ParaId', + ValidityVote: '(AccountId, ValidityAttestation)', + BalanceUpload: '(AccountId, u64)', + EgressQueueRoot: '(ParaId, Hash)', + HeadData: 'Bytes', + CandidateReceipt: { + parachainIndex: 'ParaId', + collator: 'AccountId', + signature: 'CollatorSignature', + headData: 'HeadData', + balanceUploads: 'Vec', + egressQueueRoots: 'Vec', + fees: 'u64', + blockDataHash: 'Hash' + }, + AttestedCandidate: { + candidate: 'CandidateReceipt', + validityVotes: 'Vec', + availabilityVotes: 'Vec' + }, + SubId: 'u32', + NewBidder: { + who: 'AccountId', + sub: 'SubId' + }, + Bidder: { + _enum: { + New: 'NewBidder', + Existing: 'ParaId' + } + }, + IncomingParachainDeploy: { + code: 'Bytes', + initialHeadData: 'Bytes' + }, + IncomingParachainFixed: { + codeHash: 'Hash', + initialHeadData: 'Bytes' + }, + IncomingParachain: { + _enum: { + Unset: 'NewBidder', + Fixed: 'IncomingParachainFixed', + Deploy: 'IncomingParachainDeploy' + } + }, + ParachainDispatchOrigin: { + _enum: [ + 'Signed', + 'Parachain' + ] + }, + SlotRange: { + _enum: [ + 'ZeroZero', // 0 + 'ZeroOne', // 1, + 'ZeroTwo', // 2, + 'ZeroThree', // 3, + 'OneOne', // 4, + 'OneTwo', // 5, + 'OneThree', // 6, + 'TwoTwo', // 7, + 'TwoThree', // 8, + 'ThreeThree' // 9 + ] + }, + UpwardMessage: { + origin: 'ParachainDispatchOrigin', + data: 'Bytes' + }, + WinningDataEntry: '(AccountId, ParaIdOf, BalanceOf)', + WinningData: '[WinningDataEntry; 10]' + } +}; diff --git a/packages/types/src/srml/parachains/types.ts b/packages/types/src/srml/parachains/types.ts new file mode 100644 index 0000000000..b5b45daeb4 --- /dev/null +++ b/packages/types/src/srml/parachains/types.ts @@ -0,0 +1,173 @@ +// Auto-generated, do not edit + +import { Codec } from '../../types'; +import { Enum, Struct, Vector } from '../../codec'; +import { AccountId, BalanceOf, Bytes, Hash, Signature, u32, u64 } from '../../primitive'; + +export interface AttestedCandidate extends Struct { + readonly candidate: CandidateReceipt; + readonly validityVotes: Vector; + readonly availabilityVotes: Vector; +} + +export interface AuctionIndex extends u32 {} + +type _AvailabilityVote = [AccountId, CollatorSignature]; +export interface AvailabilityVote extends Codec, _AvailabilityVote {} + +type _BalanceUpload = [AccountId, u64]; +export interface BalanceUpload extends Codec, _BalanceUpload {} + +export interface Bidder extends Enum { + /** + * @description 0:: New(NewBidder) + */ + readonly isNew: boolean; + readonly asNew: NewBidder; + /** + * @description 1:: Existing(ParaId) + */ + readonly isExisting: boolean; + readonly asExisting: ParaId; +} + +export interface CandidateReceipt extends Struct { + readonly parachainIndex: ParaId; + readonly collator: AccountId; + readonly signature: CollatorSignature; + readonly headData: HeadData; + readonly balanceUploads: Vector; + readonly egressQueueRoots: Vector; + readonly fees: u64; + readonly blockDataHash: Hash; +} + +export interface CollatorSignature extends Signature {} + +type _EgressQueueRoot = [ParaId, Hash]; +export interface EgressQueueRoot extends Codec, _EgressQueueRoot {} + +export interface HeadData extends Bytes {} + +export interface IncomingParachain extends Enum { + /** + * @description 0:: Unset(NewBidder) + */ + readonly isUnset: boolean; + readonly asUnset: NewBidder; + /** + * @description 1:: Fixed(IncomingParachainFixed) + */ + readonly isFixed: boolean; + readonly asFixed: IncomingParachainFixed; + /** + * @description 2:: Deploy(IncomingParachainDeploy) + */ + readonly isDeploy: boolean; + readonly asDeploy: IncomingParachainDeploy; +} + +export interface IncomingParachainDeploy extends Struct { + readonly code: Bytes; + readonly initialHeadData: Bytes; +} + +export interface IncomingParachainFixed extends Struct { + readonly codeHash: Hash; + readonly initialHeadData: Bytes; +} + +export interface NewBidder extends Struct { + readonly who: AccountId; + readonly sub: SubId; +} + +export interface ParachainDispatchOrigin extends Enum { + /** + * @description 0:: Signed + */ + readonly isSigned: boolean; + /** + * @description 1:: Parachain + */ + readonly isParachain: boolean; +} + +export interface ParaId extends u32 {} + +export interface ParaIdOf extends ParaId {} + +export interface SlotRange extends Enum { + /** + * @description 0:: ZeroZero + */ + readonly isZeroZero: boolean; + /** + * @description 1:: ZeroOne + */ + readonly isZeroOne: boolean; + /** + * @description 2:: ZeroTwo + */ + readonly isZeroTwo: boolean; + /** + * @description 3:: ZeroThree + */ + readonly isZeroThree: boolean; + /** + * @description 4:: OneOne + */ + readonly isOneOne: boolean; + /** + * @description 5:: OneTwo + */ + readonly isOneTwo: boolean; + /** + * @description 6:: OneThree + */ + readonly isOneThree: boolean; + /** + * @description 7:: TwoTwo + */ + readonly isTwoTwo: boolean; + /** + * @description 8:: TwoThree + */ + readonly isTwoThree: boolean; + /** + * @description 9:: ThreeThree + */ + readonly isThreeThree: boolean; +} + +export interface SubId extends u32 {} + +export interface UpwardMessage extends Struct { + readonly origin: ParachainDispatchOrigin; + readonly data: Bytes; +} + +export interface ValidityAttestation extends Enum { + /** + * @description 0:: None + */ + readonly isNone: boolean; + /** + * @description 1:: Implicit(CollatorSignature) + */ + readonly isImplicit: boolean; + readonly asImplicit: CollatorSignature; + /** + * @description 2:: Explicit(CollatorSignature) + */ + readonly isExplicit: boolean; + readonly asExplicit: CollatorSignature; +} + +type _ValidityVote = [AccountId, ValidityAttestation]; +export interface ValidityVote extends Codec, _ValidityVote {} + +export interface WinningData extends Vector {} + +type _WinningDataEntry = [AccountId, ParaIdOf, BalanceOf]; +export interface WinningDataEntry extends Codec, _WinningDataEntry {} diff --git a/packages/types/src/type/Amount.ts b/packages/types/src/type/Amount.ts index 3c79d9b5f7..ab2f394231 100644 --- a/packages/types/src/type/Amount.ts +++ b/packages/types/src/type/Amount.ts @@ -2,7 +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 Balance from './Balance'; +import Balance from '../primitive/Balance'; /** * @name Amount diff --git a/packages/types/src/type/AssetOf.ts b/packages/types/src/type/AssetOf.ts index 69dca3bc93..6eb28b9923 100644 --- a/packages/types/src/type/AssetOf.ts +++ b/packages/types/src/type/AssetOf.ts @@ -2,7 +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 Balance from './Balance'; +import Balance from '../primitive/Balance'; /** * @name AssetOf diff --git a/packages/types/src/type/AttestedCandidate.ts b/packages/types/src/type/AttestedCandidate.ts deleted file mode 100644 index f03498faec..0000000000 --- a/packages/types/src/type/AttestedCandidate.ts +++ /dev/null @@ -1,102 +0,0 @@ -// Copyright 2017-2019 @polkadot/types authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -import { assert } from '@polkadot/util'; - -import Enum from '../codec/Enum'; -import Struct from '../codec/Struct'; -import Tuple from '../codec/Tuple'; -import Vector from '../codec/Vector'; -import AccountId from '../primitive/AccountId'; -import Bytes from '../primitive/Bytes'; -import Hash from '../primitive/Hash'; -import Null from '../primitive/Null'; -import U64 from '../primitive/U64'; -import ParaId from './ParaId'; -import Signature from './Signature'; -import SessionKey from './SessionKey'; - -export class CandidateSignature extends Signature { -} - -export class BalanceUpload extends Tuple.with({ AccountId, U64 }) { -} - -export class EgressQueueRoot extends Tuple.with({ ParaId, Hash }) { -} - -export class HeadData extends Bytes { -} - -export class CandidateReceipt extends Struct { - constructor (value?: any) { - super({ - parachainIndex: ParaId, - collator: AccountId, - signature: CandidateSignature, - headData: HeadData, - balanceUploads: Vector.with(BalanceUpload), - egressQueueRoots: Vector.with(EgressQueueRoot), - fees: U64, - blockDataHash: Hash - }, value); - } -} - -export class AvailabilityVote extends Tuple.with({ SessionKey, CandidateSignature }) { -} - -export class ExplicitCandidateSignature extends CandidateSignature { -} - -export class ImplicitCandidateSignature extends CandidateSignature { -} - -export class ValidityAttestation extends Enum { - constructor (value?: any) { - super({ - // 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) - Null, - ImplicitCandidateSignature, // 1 - ExplicitCandidateSignature // 2 - }, value); - } - - /** - * @description Returns the item as a [[ExplicitCandidateSignature]] - */ - get asExplicitCandidateSignature (): ExplicitCandidateSignature { - assert(this.toNumber() === 2, `Cannot convert '${this.type}' via asExplicitCandidateSignature`); - - return this.value as ExplicitCandidateSignature; - } - - /** - * @description Returns the item as a [[ImplicitCandidateSignature]] - */ - get asImplicitCandidateSignature (): ImplicitCandidateSignature { - assert(this.toNumber() === 1, `Cannot convert '${this.type}' via asImplicitCandidateSignature`); - - return this.value as ImplicitCandidateSignature; - } -} - -export class ValidityVote extends Tuple.with({ SessionKey, ValidityAttestation }) { -} - -/** - * @name AttestedCandidate - * @description - * An attested candidate - */ -export default class AttestedCandidate extends Struct { - constructor (value?: any) { - super({ - candidate: CandidateReceipt, - validityVotes: Vector.with(ValidityVote), - availabilityVotes: Vector.with(AvailabilityVote) - }, value); - } -} diff --git a/packages/types/src/type/BalanceLock.ts b/packages/types/src/type/BalanceLock.ts index 46089dcefe..fbbfd5445f 100644 --- a/packages/types/src/type/BalanceLock.ts +++ b/packages/types/src/type/BalanceLock.ts @@ -3,7 +3,7 @@ // of the Apache-2.0 license. See the LICENSE file for details. import Struct from '../codec/Struct'; -import Balance from './Balance'; +import Balance from '../primitive/Balance'; import BlockNumber from './BlockNumber'; import LockIdentifier from './LockIdentifier'; import WithdrawReasons from './WithdrawReasons'; diff --git a/packages/types/src/type/Bft.ts b/packages/types/src/type/Bft.ts index 3f9364e1a2..3e35eca815 100644 --- a/packages/types/src/type/Bft.ts +++ b/packages/types/src/type/Bft.ts @@ -6,8 +6,8 @@ import { AnyU8a } from '../types'; import Tuple from '../codec/Tuple'; import Hash from '../primitive/Hash'; +import Signature from '../primitive/Signature'; import AuthorityId from './AuthorityId'; -import Signature from './Signature'; export type BftAuthoritySignatureValue = [AnyU8a, AnyU8a]; diff --git a/packages/types/src/type/Bidder.ts b/packages/types/src/type/Bidder.ts deleted file mode 100644 index 7919d104b1..0000000000 --- a/packages/types/src/type/Bidder.ts +++ /dev/null @@ -1,37 +0,0 @@ -// Copyright 2017-2019 @polkadot/types authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -import Enum from '../codec/Enum'; -import Struct from '../codec/Struct'; -import AccountId from '../primitive/AccountId'; -import ParaId from './ParaId'; -import SubId from './SubId'; - -/** - * @name NewBidder - * @description - * A bidder identifier, which is just the combination of an account ID and a sub-bidder ID. This is called `NewBidder` in order to distinguish between bidders that would deploy a *new* parachain and pre-existing parachains bidding to renew themselves. - */ -export class NewBidder extends Struct { - constructor (value?: any) { - super({ - who: AccountId, - sub: SubId - }, value); - } -} - -/** - * @name Bidder - * @description - * The desired target of a bidder in an auction - */ -export default class Bidder extends Enum { - constructor (value?: any) { - super({ - New: NewBidder, - Existing: ParaId - }, value); - } -} diff --git a/packages/types/src/type/ContractInfo.ts b/packages/types/src/type/ContractInfo.ts index 4164d5ea22..74682eaba0 100644 --- a/packages/types/src/type/ContractInfo.ts +++ b/packages/types/src/type/ContractInfo.ts @@ -8,9 +8,9 @@ import Option from '../codec/Option'; import Bytes from '../primitive/Bytes'; import Enum from '../codec/Enum'; import Struct from '../codec/Struct'; +import Balance from '../primitive/Balance'; import Hash from '../primitive/Hash'; import U32 from '../primitive/U32'; -import Balance from './Balance'; import BlockNumber from './BlockNumber'; import CodeHash from './CodeHash'; diff --git a/packages/types/src/type/Exposure.ts b/packages/types/src/type/Exposure.ts index 96ca588877..989d7c4da9 100644 --- a/packages/types/src/type/Exposure.ts +++ b/packages/types/src/type/Exposure.ts @@ -5,7 +5,7 @@ import Compact from '../codec/Compact'; import Struct from '../codec/Struct'; import Vector from '../codec/Vector'; -import Balance from './Balance'; +import Balance from '../primitive/Balance'; import IndividualExposure from './IndividualExposure'; /** diff --git a/packages/types/src/type/ExtrinsicSignature.ts b/packages/types/src/type/ExtrinsicSignature.ts index e1d4a3ec84..d08abacae4 100644 --- a/packages/types/src/type/ExtrinsicSignature.ts +++ b/packages/types/src/type/ExtrinsicSignature.ts @@ -7,11 +7,11 @@ import { AnyNumber, IExtrinsicSignature, IKeyringPair, SignatureOptions } from ' import Struct from '../codec/Struct'; import Address from '../primitive/Address'; import Method from '../primitive/Method'; +import Signature from '../primitive/Signature'; import U8 from '../primitive/U8'; import RuntimeVersion from '../rpc/RuntimeVersion'; import ExtrinsicEra from './ExtrinsicEra'; import Nonce from './NonceCompact'; -import Signature from './Signature'; import SignaturePayload from './SignaturePayload'; export const IMMORTAL_ERA = new Uint8Array([0]); diff --git a/packages/types/src/type/IncomingParachain.ts b/packages/types/src/type/IncomingParachain.ts deleted file mode 100644 index e9e639640e..0000000000 --- a/packages/types/src/type/IncomingParachain.ts +++ /dev/null @@ -1,24 +0,0 @@ -// Copyright 2017-2019 @polkadot/types authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -import Enum from '../codec/Enum'; -import Struct from '../codec/Struct'; -import Bytes from '../primitive/Bytes'; -import Hash from '../primitive/Hash'; -import { NewBidder } from './Bidder'; - -/** - * @name IncomingParachain - * @description - * Information regarding a parachain that will be deployed. - */ -export default class Bidder extends Enum { - constructor (value?: any) { - super({ - Unset: NewBidder, - Fixed: Struct.with({ codeHash: Hash, initialHeadData: Bytes }), - Deploy: Struct.with({ code: Bytes, initialHeadData: Bytes }) - }, value); - } -} diff --git a/packages/types/src/type/IndividualExposure.ts b/packages/types/src/type/IndividualExposure.ts index ba040b4f49..27572c33ce 100644 --- a/packages/types/src/type/IndividualExposure.ts +++ b/packages/types/src/type/IndividualExposure.ts @@ -5,7 +5,7 @@ import Compact from '../codec/Compact'; import Struct from '../codec/Struct'; import AccountId from '../primitive/AccountId'; -import Balance from './Balance'; +import Balance from '../primitive/Balance'; /** * @name IndividualExposure diff --git a/packages/types/src/type/ParaId.ts b/packages/types/src/type/ParaId.ts deleted file mode 100644 index 7a8a8e894c..0000000000 --- a/packages/types/src/type/ParaId.ts +++ /dev/null @@ -1,21 +0,0 @@ -// Copyright 2017-2019 @polkadot/types authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -import U32 from '../primitive/U32'; - -/** - * @name ParaId - * @description - * Identifier for a deployed parachain implemented as a [[U32]] - */ -export default class ParaId extends U32 { -} - -/** - * @name ParaIdOf - * @description - * Identifier for a deployed parachain implemented as a [[U32]] - */ -export class ParaIdOf extends ParaId { -} diff --git a/packages/types/src/type/SlotRange.ts b/packages/types/src/type/SlotRange.ts deleted file mode 100644 index 09d398d6d0..0000000000 --- a/packages/types/src/type/SlotRange.ts +++ /dev/null @@ -1,37 +0,0 @@ -// Copyright 2017-2019 @polkadot/types authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -import Enum from '../codec/Enum'; - -/** - * @name SlotRange - * @description - * A compactly represented sub-range from the series (0, 1, 2, 3). - */ -export default class SlotRange extends Enum { - constructor (value?: any) { - super([ - /// Sub range from index 0 to index 0 inclusive. - 'ZeroZero', // 0 - /// Sub range from index 0 to index 1 inclusive. - 'ZeroOne', // 1, - /// Sub range from index 0 to index 2 inclusive. - 'ZeroTwo', // 2, - /// Sub range from index 0 to index 3 inclusive. - 'ZeroThree', // 3, - /// Sub range from index 1 to index 1 inclusive. - 'OneOne', // 4, - /// Sub range from index 1 to index 2 inclusive. - 'OneTwo', // 5, - /// Sub range from index 1 to index 3 inclusive. - 'OneThree', // 6, - /// Sub range from index 2 to index 2 inclusive. - 'TwoTwo', // 7, - /// Sub range from index 2 to index 3 inclusive. - 'TwoThree', // 8, - /// Sub range from index 3 to index 3 inclusive. - 'ThreeThree' // 9, // == SLOT_RANGE_COUNT - 1 - ], value); - } -} diff --git a/packages/types/src/type/StakingLedger.ts b/packages/types/src/type/StakingLedger.ts index ee07505580..37a839e1eb 100644 --- a/packages/types/src/type/StakingLedger.ts +++ b/packages/types/src/type/StakingLedger.ts @@ -6,7 +6,7 @@ import Compact from '../codec/Compact'; import Struct from '../codec/Struct'; import Vector from '../codec/Vector'; import AccountId from '../primitive/AccountId'; -import Balance from './Balance'; +import Balance from '../primitive/Balance'; import BlockNumber from './BlockNumber'; import UnlockChunk from './UnlockChunk'; diff --git a/packages/types/src/type/TreasuryProposal.ts b/packages/types/src/type/TreasuryProposal.ts index 0f33e0011c..0e8ca3bf94 100644 --- a/packages/types/src/type/TreasuryProposal.ts +++ b/packages/types/src/type/TreasuryProposal.ts @@ -4,7 +4,7 @@ import Struct from '../codec/Struct'; import AccountId from '../primitive/AccountId'; -import Balance from './Balance'; +import Balance from '../primitive/Balance'; /** * @name TreasuryProposal diff --git a/packages/types/src/type/UnlockChunk.ts b/packages/types/src/type/UnlockChunk.ts index 9b4ce821a7..e9491ec8a6 100644 --- a/packages/types/src/type/UnlockChunk.ts +++ b/packages/types/src/type/UnlockChunk.ts @@ -4,7 +4,7 @@ import Compact from '../codec/Compact'; import Struct from '../codec/Struct'; -import Balance from './Balance'; +import Balance from '../primitive/Balance'; import BlockNumber from './BlockNumber'; /** diff --git a/packages/types/src/type/UpwardMessage.ts b/packages/types/src/type/UpwardMessage.ts deleted file mode 100644 index 6e62c58cd0..0000000000 --- a/packages/types/src/type/UpwardMessage.ts +++ /dev/null @@ -1,48 +0,0 @@ -// Copyright 2017-2019 @polkadot/types authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -import Enum from '../codec/Enum'; -import Struct from '../codec/Struct'; -import Bytes from '../primitive/Bytes'; - -export class ParachainDispatchOrigin extends Enum { - constructor (value?: any) { - super([ - // As a simple `Origin::Signed`, using `ParaId::account_id` as its value. This is good when - // interacting with standard modules such as `balances`. - 'Signed', - // As the special `Origin::Parachain(ParaId)`. This is good when interacting with parachain- - // aware modules which need to succinctly verify that the origin is a parachain. - 'Parachain' - ], value); - } -} - -/** - * @name UpwardMessage - * @description - * A message from a parachain to its Relay Chain - */ -export default class UpwardMessage extends Struct { - constructor (value?: any) { - super({ - origin: ParachainDispatchOrigin, - data: Bytes - }, value); - } - - /** - * @description The total balance backing this validator - */ - get data (): Bytes { - return this.get('data') as Bytes; - } - - /** - * @description The validator's own stash that is exposed - */ - get origin (): ParachainDispatchOrigin { - return this.get('origin') as ParachainDispatchOrigin; - } -} diff --git a/packages/types/src/type/ValidatorPrefs.ts b/packages/types/src/type/ValidatorPrefs.ts index 070277bdc9..f0c788cdb8 100644 --- a/packages/types/src/type/ValidatorPrefs.ts +++ b/packages/types/src/type/ValidatorPrefs.ts @@ -6,8 +6,8 @@ import { AnyNumber } from '../types'; import Compact from '../codec/Compact'; import Struct from '../codec/Struct'; +import Balance from '../primitive/Balance'; import U32 from '../primitive/U32'; -import Balance from './Balance'; type ValidatorPrefsValue = { unstakeThreshold?: AnyNumber, diff --git a/packages/types/src/type/VestingSchedule.ts b/packages/types/src/type/VestingSchedule.ts index 4a6800db4f..8825184cbf 100644 --- a/packages/types/src/type/VestingSchedule.ts +++ b/packages/types/src/type/VestingSchedule.ts @@ -3,7 +3,7 @@ // of the Apache-2.0 license. See the LICENSE file for details. import Struct from '../codec/Struct'; -import Balance from './Balance'; +import Balance from '../primitive/Balance'; /** * @name VestingSchedule diff --git a/packages/types/src/type/VoterInfo.ts b/packages/types/src/type/VoterInfo.ts index fe2bb791ef..5d11f59980 100644 --- a/packages/types/src/type/VoterInfo.ts +++ b/packages/types/src/type/VoterInfo.ts @@ -3,7 +3,7 @@ // of the Apache-2.0 license. See the LICENSE file for details. import Struct from '../codec/Struct'; -import Balance from './Balance'; +import Balance from '../primitive/Balance'; import VoteIndex from './VoteIndex'; /** diff --git a/packages/types/src/type/WinningData.ts b/packages/types/src/type/WinningData.ts deleted file mode 100644 index db35c14f0f..0000000000 --- a/packages/types/src/type/WinningData.ts +++ /dev/null @@ -1,24 +0,0 @@ -// Copyright 2017-2019 @polkadot/types authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -import Tuple from '../codec/Tuple'; -import VectorFixed from '../codec/VectorFixed'; -import AccountId from '../primitive/AccountId'; -import { BalanceOf } from './Balance'; -import { ParaIdOf } from './ParaId'; - -const SLOT_RANGE_COUNT = 10; - -export class WinningDataEntry extends Tuple { - constructor (value?: any) { - super([AccountId, ParaIdOf, BalanceOf], value); - } -} -/** - * @name WinningData - * @description - * Winning data type. This encodes the top bidders of each range together with their bid. - */ -export default class WinningData extends VectorFixed.with(WinningDataEntry, SLOT_RANGE_COUNT) { -} diff --git a/packages/types/src/type/index.ts b/packages/types/src/type/index.ts index 676fd989c2..b4385d02d4 100644 --- a/packages/types/src/type/index.ts +++ b/packages/types/src/type/index.ts @@ -11,15 +11,11 @@ export { default as Amount } from './Amount'; export { default as ApprovalFlag } from './ApprovalFlag'; export { default as AssetOf } from './AssetOf'; -export { default as AttestedCandidate } from './AttestedCandidate'; -export { default as AuctionIndex } from './AuctionIndex'; export { default as AuthorityId } from './AuthorityId'; export { default as AuthorityWeight } from './AuthorityWeight'; -export { default as Balance, BalanceOf } from './Balance'; export { default as BalanceLock } from './BalanceLock'; // NOTE Bft items are only used in internal structures // export * from './Bft; -export { default as Bidder, NewBidder } from './Bidder'; export { default as BlockNumber } from './BlockNumber'; export { default as CodeHash } from './CodeHash'; export { default as Conviction } from './Conviction'; @@ -33,7 +29,6 @@ export { default as ExtrinsicSignature } from './ExtrinsicSignature'; // NOTE Only used internally, exported as PendingExtrinsics // export { default as Extrinsics } from './Extrinsics'; export { default as Gas } from './Gas'; -export { default as IncomingParachain } from './IncomingParachain'; export { default as IndividualExposure } from './IndividualExposure'; export { default as InherentOfflineReport } from './InherentOfflineReport'; export { default as Key } from './Key'; @@ -50,7 +45,6 @@ export { default as MemberCount } from './MemberCount'; export { default as MisbehaviorReport } from './MisbehaviorReport'; export { default as NewAccountOutcome } from './NewAccountOutcome'; export { default as OpaqueKey } from './OpaqueKey'; -export { default as ParaId, ParaIdOf } from './ParaId'; export { default as Permill } from './Permill'; export { default as Perbill } from './Perbill'; export { default as PrefabWasmModule } from './PrefabWasmModule'; @@ -66,16 +60,12 @@ export { default as SessionIndex } from './SessionIndex'; export { default as SessionKey } from './SessionKey'; export { default as SessionKeys } from './SessionKeys'; export { default as SetIndex } from './SetIndex'; -export { default as Signature, Ed25519Signature, Sr25519Signature } from './Signature'; export { default as SignaturePayload, SignaturePayloadRaw } from './SignaturePayload'; -export { default as SlotRange } from './SlotRange'; export { default as StakingLedger } from './StakingLedger'; export { default as StoredPendingChange } from './StoredPendingChange'; -export { default as SubId } from './SubId'; export { default as TreasuryProposal } from './TreasuryProposal'; export { default as UncleEntryItem } from './UncleEntryItem'; export { default as UnlockChunk } from './UnlockChunk'; -export { default as UpwardMessage, ParachainDispatchOrigin } from './UpwardMessage'; export { default as ValidatorId } from './ValidatorId'; export { default as ValidatorPrefs } from './ValidatorPrefs'; export { default as VestingSchedule } from './VestingSchedule'; @@ -84,5 +74,4 @@ export { default as Votes } from './Votes'; export { default as VoteThreshold } from './VoteThreshold'; export { default as VoteIndex } from './VoteIndex'; export { default as VoterInfo } from './VoterInfo'; -export { default as WinningData, WinningDataEntry } from './WinningData'; export { default as WithdrawReasons } from './WithdrawReasons'; diff --git a/packages/types/src/types.ts b/packages/types/src/types.ts index 3007abf38c..62246c65e6 100644 --- a/packages/types/src/types.ts +++ b/packages/types/src/types.ts @@ -99,7 +99,7 @@ export type ConstructorDef = { [index: string]: Constructor }; export type TypeDef = { [index: string]: Codec }; export type RegistryTypes = { - [name: string]: Constructor | string | { [name: string]: string } + [name: string]: Constructor | string | { [name: string]: string } | { _enum: Array | { [index: string]: string } } }; export interface RuntimeVersionInterface {