Auto-generate TS definitions from types (#1077)

* Basic ts generation from JSON (parachains)

* Basic enum jsdoc comments

* Add as<Type> 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
This commit is contained in:
Jaco Greeff
2019-07-10 16:55:25 +02:00
committed by GitHub
parent 618a622284
commit 50a3a40cfd
42 changed files with 540 additions and 354 deletions
@@ -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<Modules extends Codec> (
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<Modules extends Codec> (
*/
export function toV6<Modules extends Codec> (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<Modules extends Codec> (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
+1 -1
View File
@@ -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';
+14
View File
@@ -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(
+24
View File
@@ -127,6 +127,30 @@ export default class Enum extends Base<Codec> 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;
}
});
}
});
}
};
}
+1 -1
View File
@@ -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';
+16 -10
View File
@@ -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<TypeDef>): { [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<TypeDef>).reduce((result, sub, index) => {
result[sub.name as string] = getTypeClass(sub);
return result;
}, {} as { [index: string]: Constructor })
getTypeClassMap(value.sub as Array<TypeDef>)
);
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<TypeDef>).reduce((result, sub) => {
result[sub.name as string] = getTypeClass(sub);
return result;
}, {} as { [index: string]: Constructor })
getTypeClassMap(value.sub as Array<TypeDef>)
);
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);
+1
View File
@@ -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`);
}
@@ -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
@@ -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
+4
View File
@@ -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';
+1 -1
View File
@@ -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'
+162
View File
@@ -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<string>
};
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<TypeDef>).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<TypeDef>).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<TypeDef>).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)
);
@@ -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');
@@ -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';
@@ -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<BalanceUpload>',
egressQueueRoots: 'Vec<EgressQueueRoot>',
fees: 'u64',
blockDataHash: 'Hash'
},
AttestedCandidate: {
candidate: 'CandidateReceipt',
validityVotes: 'Vec<ValidityVote>',
availabilityVotes: 'Vec<AvailabilityVote>'
},
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]'
}
};
+173
View File
@@ -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<ValidityVote>;
readonly availabilityVotes: Vector<AvailabilityVote>;
}
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<BalanceUpload>;
readonly egressQueueRoots: Vector<EgressQueueRoot>;
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<WinningDataEntry> {}
type _WinningDataEntry = [AccountId, ParaIdOf, BalanceOf];
export interface WinningDataEntry extends Codec, _WinningDataEntry {}
+1 -1
View File
@@ -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
+1 -1
View File
@@ -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
@@ -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);
}
}
+1 -1
View File
@@ -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';
+1 -1
View File
@@ -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];
-37
View File
@@ -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);
}
}
+1 -1
View File
@@ -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';
+1 -1
View File
@@ -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';
/**
@@ -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]);
@@ -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);
}
}
@@ -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
-21
View File
@@ -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 {
}
-37
View File
@@ -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);
}
}
+1 -1
View File
@@ -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';
+1 -1
View File
@@ -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
+1 -1
View File
@@ -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';
/**
-48
View File
@@ -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;
}
}
+1 -1
View File
@@ -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,
+1 -1
View File
@@ -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
+1 -1
View File
@@ -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';
/**
-24
View File
@@ -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) {
}
-11
View File
@@ -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';
+1 -1
View File
@@ -99,7 +99,7 @@ export type ConstructorDef<T = Codec> = { [index: string]: Constructor<T> };
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<string> | { [index: string]: string } }
};
export interface RuntimeVersionInterface {