Correctly type api.query.*.* (#1406)

* v1, very wip

* Refactor file arch

* Clean some code

* Make it work for all methods

* Have correct typings!

* Add similar types

* Fix missing imports

* Move function order

* Put any for now

* Make api.queryMulti work

* Add override check

* Fix typings to make it better

* Uncomment code

* Fix lint

* Fix lint

* Put checkTypes into correct place in file

* Spaces...

* Add multi test

* Use interface instead of type alias

* Add comment

* Fix indentation

* Ignore query.types.ts
This commit is contained in:
Amaury Martiny
2019-09-23 16:46:35 +02:00
committed by GitHub
parent 84b9b8dc09
commit 00d86011a7
45 changed files with 1361 additions and 797 deletions
@@ -1,15 +1,15 @@
// Auto-generated via `yarn build:interfaces`, do not edit
/* eslint-disable @typescript-eslint/no-empty-interface */
import { Codec } from '../../types';
import { ITuple } from '../../types';
import { Enum, Option } from '../../codec';
import { AccountId, BlockNumber, Hash } from '../runtime';
/** BlockNumber */
export type InclusionHeight = BlockNumber;
export interface InclusionHeight extends BlockNumber {}
/** [Hash, Option<AccountId>] & Codec */
export type Uncle = [Hash, Option<AccountId>] & Codec;
/** ITuple<[Hash, Option<AccountId>]> */
export interface Uncle extends ITuple<[Hash, Option<AccountId>]> {}
/** Enum */
export interface UncleEntryItem extends Enum {
+4 -4
View File
@@ -5,13 +5,13 @@ import { Enum, Struct } from '../../codec';
import { H256, u32, u64 } from '../../primitive';
/** u64 */
export type BabeAuthorityWeight = u64;
export interface BabeAuthorityWeight extends u64 {}
/** u32 */
export type BabeBlockWeight = u32;
export interface BabeBlockWeight extends u32 {}
/** u64 */
export type BabeWeight = u64;
export interface BabeWeight extends u64 {}
/** Enum */
export interface RawBabePreDigest extends Enum {
@@ -50,4 +50,4 @@ export interface RawBabePreDigestSecondary extends Struct {
}
/** u64 */
export type SlotNumber = u64;
export interface SlotNumber extends u64 {}
@@ -4,8 +4,8 @@
import { Codec } from '../../types';
import { H160 } from '../../primitive';
/** Uint8Array & Codec */
export type EcdsaSignature = Uint8Array & Codec;
/** Uint8Array, Codec */
export interface EcdsaSignature extends Uint8Array, Codec {}
/** H160 */
export type EthereumAddress = H160;
export interface EthereumAddress extends H160 {}
@@ -6,10 +6,10 @@ import { u32 } from '../../primitive';
import { AccountId } from '../runtime';
/** u32 */
export type MemberCount = u32;
export interface MemberCount extends u32 {}
/** u32 */
export type ProposalIndex = u32;
export interface ProposalIndex extends u32 {}
/** Struct */
export interface Votes extends Struct {
@@ -4,4 +4,4 @@
import { AccountId } from '../runtime';
/** AccountId */
export type AuthorityId = AccountId;
export interface AuthorityId extends AccountId {}
@@ -23,7 +23,7 @@ export interface AliveContractInfo extends Struct {
}
/** Hash */
export type CodeHash = Hash;
export interface CodeHash extends Hash {}
/** Struct */
export interface ContractCallRequest extends Struct {
@@ -69,11 +69,11 @@ export interface ContractInfo extends Enum {
readonly asTombstone: TombstoneContractInfo;
}
/** Uint8Array & Codec */
export type ContractStorageKey = Uint8Array & Codec;
/** Uint8Array, Codec */
export interface ContractStorageKey extends Uint8Array, Codec {}
/** u64 */
export type Gas = u64;
export interface Gas extends u64 {}
/** Struct */
export interface PrefabWasmModule extends Struct {
@@ -90,7 +90,7 @@ export interface PrefabWasmModule extends Struct {
}
/** Option<Null> */
export type PrefabWasmModuleReserved = Option<Null>;
export interface PrefabWasmModuleReserved extends Option<Null> {}
/** Struct */
export interface Schedule extends Struct {
@@ -127,10 +127,10 @@ export interface Schedule extends Struct {
}
/** Hash */
export type SeedOf = Hash;
export interface SeedOf extends Hash {}
/** Hash */
export type TombstoneContractInfo = Hash;
export interface TombstoneContractInfo extends Hash {}
/** Bytes */
export type TrieId = Bytes;
export interface TrieId extends Bytes {}
@@ -23,13 +23,13 @@ export interface Conviction extends Enum {
}
/** u32 */
export type PropIndex = u32;
export interface PropIndex extends u32 {}
/** Call */
export type Proposal = Call;
export interface Proposal extends Call {}
/** u32 */
export type ReferendumIndex = u32;
export interface ReferendumIndex extends u32 {}
/** Struct */
export interface ReferendumInfo extends Struct {
@@ -14,16 +14,16 @@ export interface AccountInfo extends Struct {
}
/** Balance */
export type Amount = Balance;
export interface Amount extends Balance {}
/** u32 */
export type AssetOf = u32;
export interface AssetOf extends u32 {}
/** Null */
export type InherentOfflineReport = Null;
export interface InherentOfflineReport extends Null {}
/** i8 */
export type LockPeriods = i8;
export interface LockPeriods extends i8 {}
/** Enum */
export interface NewAccountOutcome extends Enum {
@@ -36,7 +36,7 @@ export interface NewAccountOutcome extends Enum {
}
/** Bytes */
export type OpaqueKey = Bytes;
export interface OpaqueKey extends Bytes {}
/** AccountId */
export type SessionKey = AccountId;
export interface SessionKey extends AccountId {}
@@ -6,16 +6,16 @@ import { GenericVote, u32 } from '../../primitive';
import { Balance } from '../runtime';
/** u32 */
export type ApprovalFlag = u32;
export interface ApprovalFlag extends u32 {}
/** u32 */
export type SetIndex = u32;
export interface SetIndex extends u32 {}
/** GenericVote */
export type Vote = GenericVote;
export interface Vote extends GenericVote {}
/** u32 */
export type VoteIndex = u32;
export interface VoteIndex extends u32 {}
/** Struct */
export interface VoterInfo extends Struct {
@@ -23,7 +23,7 @@ export interface Owner extends Enum {
}
/** PermissionsV1 */
export type PermissionLatest = PermissionsV1;
export interface PermissionLatest extends PermissionsV1 {}
/** Struct */
export interface PermissionsV1 extends Struct {
@@ -1,17 +1,17 @@
// Auto-generated via `yarn build:interfaces`, do not edit
/* eslint-disable @typescript-eslint/no-empty-interface */
import { Codec } from '../../types';
import { ITuple } from '../../types';
import { Enum, Struct, Vec } from '../../codec';
import { u64 } from '../../primitive';
import { BlockNumber } from '../runtime';
import { AuthorityId } from '../consensus';
/** u64 */
export type AuthorityWeight = u64;
export interface AuthorityWeight extends u64 {}
/** [AuthorityId, u64] & Codec */
export type NextAuthority = [AuthorityId, u64] & Codec;
/** ITuple<[AuthorityId, u64]> */
export interface NextAuthority extends ITuple<[AuthorityId, u64]> {}
/** Struct */
export interface PendingPause extends Struct {
@@ -30,7 +30,7 @@ export interface PendingResume extends Struct {
}
/** u64 */
export type SetId = u64;
export interface SetId extends u64 {}
/** Struct */
export interface StoredPendingChange extends Struct {
@@ -8,10 +8,10 @@ import { AuthorityId } from '../consensus';
import { SessionIndex } from '../session';
/** u32 */
export type AuthIndex = u32;
export interface AuthIndex extends u32 {}
/** Signature */
export type AuthoritySignature = Signature;
export interface AuthoritySignature extends Signature {}
/** Struct */
export interface Heartbeat extends Struct {
@@ -26,7 +26,7 @@ export interface Heartbeat extends Struct {
}
/** Bytes */
export type OpaqueMultiaddr = Bytes;
export interface OpaqueMultiaddr extends Bytes {}
/** Struct */
export interface OpaqueNetworkState extends Struct {
@@ -37,4 +37,4 @@ export interface OpaqueNetworkState extends Struct {
}
/** Bytes */
export type OpaquePeerId = Bytes;
export interface OpaquePeerId extends Bytes {}
+47 -47
View File
@@ -1,7 +1,7 @@
// Auto-generated via `yarn build:interfaces`, do not edit
/* eslint-disable @typescript-eslint/no-empty-interface */
import { Codec } from '../../types';
import { ITuple } from '../../types';
import { Enum, Option, Struct, Vec } from '../../codec';
import { Bytes, StorageHasher, Text, Type, bool, u16 } from '../../primitive';
@@ -54,10 +54,10 @@ export interface DoubleMapTypeV5 extends Struct {
}
/** DoubleMapTypeV5 */
export type DoubleMapTypeV6 = DoubleMapTypeV5;
export interface DoubleMapTypeV6 extends DoubleMapTypeV5 {}
/** DoubleMapTypeV6 */
export type DoubleMapTypeV7 = DoubleMapTypeV6;
export interface DoubleMapTypeV7 extends DoubleMapTypeV6 {}
/** Struct */
export interface EventMetadataV0 extends Struct {
@@ -70,25 +70,25 @@ export interface EventMetadataV0 extends Struct {
}
/** EventMetadataV0 */
export type EventMetadataV1 = EventMetadataV0;
export interface EventMetadataV1 extends EventMetadataV0 {}
/** EventMetadataV1 */
export type EventMetadataV2 = EventMetadataV1;
export interface EventMetadataV2 extends EventMetadataV1 {}
/** EventMetadataV2 */
export type EventMetadataV3 = EventMetadataV2;
export interface EventMetadataV3 extends EventMetadataV2 {}
/** EventMetadataV3 */
export type EventMetadataV4 = EventMetadataV3;
export interface EventMetadataV4 extends EventMetadataV3 {}
/** EventMetadataV4 */
export type EventMetadataV5 = EventMetadataV4;
export interface EventMetadataV5 extends EventMetadataV4 {}
/** EventMetadataV5 */
export type EventMetadataV6 = EventMetadataV5;
export interface EventMetadataV6 extends EventMetadataV5 {}
/** EventMetadataV6 */
export type EventMetadataV7 = EventMetadataV6;
export interface EventMetadataV7 extends EventMetadataV6 {}
/** Struct */
export interface FunctionArgumentMetadataV0 extends Struct {
@@ -99,25 +99,25 @@ export interface FunctionArgumentMetadataV0 extends Struct {
}
/** FunctionArgumentMetadataV0 */
export type FunctionArgumentMetadataV1 = FunctionArgumentMetadataV0;
export interface FunctionArgumentMetadataV1 extends FunctionArgumentMetadataV0 {}
/** FunctionArgumentMetadataV1 */
export type FunctionArgumentMetadataV2 = FunctionArgumentMetadataV1;
export interface FunctionArgumentMetadataV2 extends FunctionArgumentMetadataV1 {}
/** FunctionArgumentMetadataV2 */
export type FunctionArgumentMetadataV3 = FunctionArgumentMetadataV2;
export interface FunctionArgumentMetadataV3 extends FunctionArgumentMetadataV2 {}
/** FunctionArgumentMetadataV3 */
export type FunctionArgumentMetadataV4 = FunctionArgumentMetadataV3;
export interface FunctionArgumentMetadataV4 extends FunctionArgumentMetadataV3 {}
/** FunctionArgumentMetadataV4 */
export type FunctionArgumentMetadataV5 = FunctionArgumentMetadataV4;
export interface FunctionArgumentMetadataV5 extends FunctionArgumentMetadataV4 {}
/** FunctionArgumentMetadataV5 */
export type FunctionArgumentMetadataV6 = FunctionArgumentMetadataV5;
export interface FunctionArgumentMetadataV6 extends FunctionArgumentMetadataV5 {}
/** FunctionArgumentMetadataV6 */
export type FunctionArgumentMetadataV7 = FunctionArgumentMetadataV6;
export interface FunctionArgumentMetadataV7 extends FunctionArgumentMetadataV6 {}
/** Struct */
export interface FunctionMetadataV0 extends Struct {
@@ -142,22 +142,22 @@ export interface FunctionMetadataV1 extends Struct {
}
/** FunctionMetadataV1 */
export type FunctionMetadataV2 = FunctionMetadataV1;
export interface FunctionMetadataV2 extends FunctionMetadataV1 {}
/** FunctionMetadataV2 */
export type FunctionMetadataV3 = FunctionMetadataV2;
export interface FunctionMetadataV3 extends FunctionMetadataV2 {}
/** FunctionMetadataV3 */
export type FunctionMetadataV4 = FunctionMetadataV3;
export interface FunctionMetadataV4 extends FunctionMetadataV3 {}
/** FunctionMetadataV4 */
export type FunctionMetadataV5 = FunctionMetadataV4;
export interface FunctionMetadataV5 extends FunctionMetadataV4 {}
/** FunctionMetadataV5 */
export type FunctionMetadataV6 = FunctionMetadataV5;
export interface FunctionMetadataV6 extends FunctionMetadataV5 {}
/** FunctionMetadataV6 */
export type FunctionMetadataV7 = FunctionMetadataV6;
export interface FunctionMetadataV7 extends FunctionMetadataV6 {}
/** Struct */
export interface MapTypeV0 extends Struct {
@@ -178,7 +178,7 @@ export interface MapTypeV2 extends Struct {
}
/** MapTypeV2 */
export type MapTypeV3 = MapTypeV2;
export interface MapTypeV3 extends MapTypeV2 {}
/** Struct */
export interface MapTypeV4 extends Struct {
@@ -193,13 +193,13 @@ export interface MapTypeV4 extends Struct {
}
/** MapTypeV4 */
export type MapTypeV5 = MapTypeV4;
export interface MapTypeV5 extends MapTypeV4 {}
/** MapTypeV5 */
export type MapTypeV6 = MapTypeV5;
export interface MapTypeV6 extends MapTypeV5 {}
/** MapTypeV6 */
export type MapTypeV7 = MapTypeV6;
export interface MapTypeV7 extends MapTypeV6 {}
/** Struct */
export interface MetadataV0 extends Struct {
@@ -230,7 +230,7 @@ export interface ModuleConstantMetadataV6 extends Struct {
}
/** ModuleConstantMetadataV6 */
export type ModuleConstantMetadataV7 = ModuleConstantMetadataV6;
export interface ModuleConstantMetadataV7 extends ModuleConstantMetadataV6 {}
/** Struct */
export interface ModuleMetadataV0 extends Struct {
@@ -273,10 +273,10 @@ export interface OuterDispatchMetadataV0 extends Struct {
}
/** Vec<EventMetadataV0> */
export type OuterEventEventMetadataEventsV0 = Vec<EventMetadataV0>;
export interface OuterEventEventMetadataEventsV0 extends Vec<EventMetadataV0> {}
/** [Text, OuterEventEventMetadataEventsV0] & Codec */
export type OuterEventEventMetadataV0 = [Text, OuterEventEventMetadataEventsV0] & Codec;
/** ITuple<[Text, OuterEventEventMetadataEventsV0]> */
export interface OuterEventEventMetadataV0 extends ITuple<[Text, OuterEventEventMetadataEventsV0]> {}
/** Struct */
export interface OuterEventMetadataV0 extends Struct {
@@ -287,25 +287,25 @@ export interface OuterEventMetadataV0 extends Struct {
}
/** Type */
export type PlainTypeV0 = Type;
export interface PlainTypeV0 extends Type {}
/** Type */
export type PlainTypeV2 = Type;
export interface PlainTypeV2 extends Type {}
/** Type */
export type PlainTypeV3 = Type;
export interface PlainTypeV3 extends Type {}
/** Type */
export type PlainTypeV4 = Type;
export interface PlainTypeV4 extends Type {}
/** Type */
export type PlainTypeV5 = Type;
export interface PlainTypeV5 extends Type {}
/** Type */
export type PlainTypeV6 = Type;
export interface PlainTypeV6 extends Type {}
/** Type */
export type PlainTypeV7 = Type;
export interface PlainTypeV7 extends Type {}
/** Struct */
export interface RuntimeModuleMetadataV0 extends Struct {
@@ -318,10 +318,10 @@ export interface RuntimeModuleMetadataV0 extends Struct {
}
/** StorageFunctionModifierV5 */
export type StorageEntryModifierV6 = StorageFunctionModifierV5;
export interface StorageEntryModifierV6 extends StorageFunctionModifierV5 {}
/** StorageEntryModifierV6 */
export type StorageEntryModifierV7 = StorageEntryModifierV6;
export interface StorageEntryModifierV7 extends StorageEntryModifierV6 {}
/** Struct */
export interface StorageFunctionMetadataV0 extends Struct {
@@ -338,7 +338,7 @@ export interface StorageFunctionMetadataV0 extends Struct {
}
/** StorageFunctionMetadataV0 */
export type StorageFunctionMetadataV1 = StorageFunctionMetadataV0;
export interface StorageFunctionMetadataV1 extends StorageFunctionMetadataV0 {}
/** Enum */
export interface StorageFunctionModifierV0 extends Enum {
@@ -351,19 +351,19 @@ export interface StorageFunctionModifierV0 extends Enum {
}
/** StorageFunctionModifierV0 */
export type StorageFunctionModifierV1 = StorageFunctionModifierV0;
export interface StorageFunctionModifierV1 extends StorageFunctionModifierV0 {}
/** StorageFunctionModifierV1 */
export type StorageFunctionModifierV2 = StorageFunctionModifierV1;
export interface StorageFunctionModifierV2 extends StorageFunctionModifierV1 {}
/** StorageFunctionModifierV2 */
export type StorageFunctionModifierV3 = StorageFunctionModifierV2;
export interface StorageFunctionModifierV3 extends StorageFunctionModifierV2 {}
/** StorageFunctionModifierV3 */
export type StorageFunctionModifierV4 = StorageFunctionModifierV3;
export interface StorageFunctionModifierV4 extends StorageFunctionModifierV3 {}
/** StorageFunctionModifierV4 */
export type StorageFunctionModifierV5 = StorageFunctionModifierV4;
export interface StorageFunctionModifierV5 extends StorageFunctionModifierV4 {}
/** Enum */
export interface StorageFunctionTypeV0 extends Enum {
@@ -378,7 +378,7 @@ export interface StorageFunctionTypeV0 extends Enum {
}
/** StorageFunctionTypeV0 */
export type StorageFunctionTypeV1 = StorageFunctionTypeV0;
export interface StorageFunctionTypeV1 extends StorageFunctionTypeV0 {}
/** Struct */
export interface StorageMetadataV0 extends Struct {
@@ -7,8 +7,8 @@ import { Bytes } from '../../primitive';
import { AccountId, Hash } from '../runtime';
import { IdentificationTuple } from '../session';
/** Uint8Array & Codec */
export type Kind = Uint8Array & Codec;
/** Uint8Array, Codec */
export interface Kind extends Uint8Array, Codec {}
/** Struct */
export interface OffenceDetails extends Struct {
@@ -19,13 +19,13 @@ export interface OffenceDetails extends Struct {
}
/** IdentificationTuple */
export type Offender = IdentificationTuple;
export interface Offender extends IdentificationTuple {}
/** Bytes */
export type OpaqueTimeSlot = Bytes;
export interface OpaqueTimeSlot extends Bytes {}
/** AccountId */
export type Reporter = AccountId;
export interface Reporter extends AccountId {}
/** Hash */
export type ReportIdOf = Hash;
export interface ReportIdOf extends Hash {}
@@ -1,7 +1,7 @@
// Auto-generated via `yarn build:interfaces`, do not edit
/* eslint-disable @typescript-eslint/no-empty-interface */
import { Codec } from '../../types';
import { ITuple } from '../../types';
import { Enum, Struct, Vec } from '../../codec';
import { Bytes, u32, u64 } from '../../primitive';
import { AccountId, BalanceOf, BlockNumber, Hash, Signature } from '../runtime';
@@ -15,10 +15,10 @@ export interface AttestedCandidate extends Struct {
}
/** u32 */
export type AuctionIndex = u32;
export interface AuctionIndex extends u32 {}
/** [AccountId, u64] & Codec */
export type BalanceUpload = [AccountId, u64] & Codec;
/** ITuple<[AccountId, u64]> */
export interface BalanceUpload extends ITuple<[AccountId, u64]> {}
/** Enum */
export interface Bidder extends Enum {
@@ -53,13 +53,13 @@ export interface CandidateReceipt extends Struct {
}
/** Signature */
export type CollatorSignature = Signature;
export interface CollatorSignature extends Signature {}
/** [ParaId, Hash] & Codec */
export type EgressQueueRoot = [ParaId, Hash] & Codec;
/** ITuple<[ParaId, Hash]> */
export interface EgressQueueRoot extends ITuple<[ParaId, Hash]> {}
/** Bytes */
export type HeadData = Bytes;
export interface HeadData extends Bytes {}
/** Enum */
export interface IncomingParachain extends Enum {
@@ -94,10 +94,10 @@ export interface IncomingParachainFixed extends Struct {
}
/** BlockNumber */
export type LeasePeriod = BlockNumber;
export interface LeasePeriod extends BlockNumber {}
/** LeasePeriod */
export type LeasePeriodOf = LeasePeriod;
export interface LeasePeriodOf extends LeasePeriod {}
/** Struct */
export interface NewBidder extends Struct {
@@ -116,10 +116,10 @@ export interface ParachainDispatchOrigin extends Enum {
}
/** u32 */
export type ParaId = u32;
export interface ParaId extends u32 {}
/** ParaId */
export type ParaIdOf = ParaId;
export interface ParaIdOf extends ParaId {}
/** Enum */
export interface SlotRange extends Enum {
@@ -146,7 +146,7 @@ export interface SlotRange extends Enum {
}
/** u32 */
export type SubId = u32;
export interface SubId extends u32 {}
/** Struct */
export interface UpwardMessage extends Struct {
@@ -157,7 +157,7 @@ export interface UpwardMessage extends Struct {
}
/** u32 */
export type ValidatorIndex = u32;
export interface ValidatorIndex extends u32 {}
/** Enum */
export interface ValidityAttestation extends Enum {
@@ -173,11 +173,11 @@ export interface ValidityAttestation extends Enum {
readonly asExplicit: CollatorSignature;
}
/** [ValidatorIndex, ValidityAttestation] & Codec */
export type ValidityVote = [ValidatorIndex, ValidityAttestation] & Codec;
/** ITuple<[ValidatorIndex, ValidityAttestation]> */
export interface ValidityVote extends ITuple<[ValidatorIndex, ValidityAttestation]> {}
/** Vec<WinningDataEntry> */
export type WinningData = Vec<WinningDataEntry>;
export interface WinningData extends Vec<WinningDataEntry> {}
/** [AccountId, ParaIdOf, BalanceOf] & Codec */
export type WinningDataEntry = [AccountId, ParaIdOf, BalanceOf] & Codec;
/** ITuple<[AccountId, ParaIdOf, BalanceOf]> */
export interface WinningDataEntry extends ITuple<[AccountId, ParaIdOf, BalanceOf]> {}
+7 -7
View File
@@ -1,13 +1,13 @@
// Auto-generated via `yarn build:interfaces`, do not edit
/* eslint-disable @typescript-eslint/no-empty-interface */
import { Codec } from '../../types';
import { Codec, ITuple } from '../../types';
import { Enum, Option, Struct, Vec } from '../../codec';
import { Bytes, StorageData, StorageKey, Text, bool, u32, u64, u8 } from '../../primitive';
import { BlockNumber, Hash } from '../runtime';
/** Uint8Array & Codec */
export type ApiId = Uint8Array & Codec;
/** Uint8Array, Codec */
export interface ApiId extends Uint8Array, Codec {}
/** Struct */
export interface ChainProperties extends Struct {
@@ -65,8 +65,8 @@ export interface Health extends Struct {
readonly shouldHavePeers: bool;
}
/** [StorageKey, Option<StorageData>] & Codec */
export type KeyValueOption = [StorageKey, Option<StorageData>] & Codec;
/** ITuple<[StorageKey, Option<StorageData>]> */
export interface KeyValueOption extends ITuple<[StorageKey, Option<StorageData>]> {}
/** Struct */
export interface NetworkState extends Struct {
@@ -112,8 +112,8 @@ export interface RuntimeVersion extends Struct {
readonly apis: Vec<RuntimeVersionApi>;
}
/** [ApiId, u32] & Codec */
export type RuntimeVersionApi = [ApiId, u32] & Codec;
/** ITuple<[ApiId, u32]> */
export interface RuntimeVersionApi extends ITuple<[ApiId, u32]> {}
/** Struct */
export interface StorageChangeSet extends Struct {
+56 -56
View File
@@ -1,90 +1,90 @@
// Auto-generated via `yarn build:interfaces`, do not edit
/* eslint-disable @typescript-eslint/no-empty-interface */
import { Codec } from '../../types';
import { Codec, ITuple } from '../../types';
import { Compact, Struct } from '../../codec';
import { Bytes, Fixed64, GenericAccountId, GenericAccountIndex, GenericAddress, GenericBlock, GenericCall, GenericConsensusEngineId, GenericDigest, GenericDigestItem, GenericExtrinsic, GenericExtrinsicEra, GenericExtrinsicPayload, GenericExtrinsicPayloadUnknown, GenericExtrinsicPayloadV1, GenericExtrinsicPayloadV2, GenericExtrinsicPayloadV3, GenericExtrinsicUnknown, GenericExtrinsicV1, GenericExtrinsicV2, GenericExtrinsicV3, GenericImmortalEra, GenericMortalEra, GenericOrigin, GenericSignerPayload, H256, H512, Null, StorageData, StorageKey, u128, u32, u64 } from '../../primitive';
/** GenericAccountId */
export type AccountId = GenericAccountId;
export interface AccountId extends GenericAccountId {}
/** AccountId */
export type AccountIdOf = AccountId;
export interface AccountIdOf extends AccountId {}
/** GenericAccountIndex */
export type AccountIndex = GenericAccountIndex;
export interface AccountIndex extends GenericAccountIndex {}
/** GenericAddress */
export type Address = GenericAddress;
export interface Address extends GenericAddress {}
/** u32 */
export type AssetId = u32;
export interface AssetId extends u32 {}
/** u128 */
export type Balance = u128;
export interface Balance extends u128 {}
/** Balance */
export type BalanceOf = Balance;
export interface BalanceOf extends Balance {}
/** GenericBlock */
export type Block = GenericBlock;
export interface Block extends GenericBlock {}
/** u32 */
export type BlockNumber = u32;
export interface BlockNumber extends u32 {}
/** GenericCall */
export type Call = GenericCall;
export interface Call extends GenericCall {}
/** [ConsensusEngineId, Bytes] & Codec */
export type Consensus = [ConsensusEngineId, Bytes] & Codec;
/** ITuple<[ConsensusEngineId, Bytes]> */
export interface Consensus extends ITuple<[ConsensusEngineId, Bytes]> {}
/** GenericConsensusEngineId */
export type ConsensusEngineId = GenericConsensusEngineId;
export interface ConsensusEngineId extends GenericConsensusEngineId {}
/** GenericDigest */
export type Digest = GenericDigest;
export interface Digest extends GenericDigest {}
/** GenericDigestItem */
export type DigestItem = GenericDigestItem;
export interface DigestItem extends GenericDigestItem {}
/** Signature */
export type Ed25519Signature = Signature;
export interface Ed25519Signature extends Signature {}
/** GenericExtrinsic */
export type Extrinsic = GenericExtrinsic;
export interface Extrinsic extends GenericExtrinsic {}
/** GenericExtrinsicEra */
export type ExtrinsicEra = GenericExtrinsicEra;
export interface ExtrinsicEra extends GenericExtrinsicEra {}
/** GenericExtrinsicPayload */
export type ExtrinsicPayload = GenericExtrinsicPayload;
export interface ExtrinsicPayload extends GenericExtrinsicPayload {}
/** GenericExtrinsicPayloadUnknown */
export type ExtrinsicPayloadUnknown = GenericExtrinsicPayloadUnknown;
export interface ExtrinsicPayloadUnknown extends GenericExtrinsicPayloadUnknown {}
/** GenericExtrinsicPayloadV1 */
export type ExtrinsicPayloadV1 = GenericExtrinsicPayloadV1;
export interface ExtrinsicPayloadV1 extends GenericExtrinsicPayloadV1 {}
/** GenericExtrinsicPayloadV2 */
export type ExtrinsicPayloadV2 = GenericExtrinsicPayloadV2;
export interface ExtrinsicPayloadV2 extends GenericExtrinsicPayloadV2 {}
/** GenericExtrinsicPayloadV3 */
export type ExtrinsicPayloadV3 = GenericExtrinsicPayloadV3;
export interface ExtrinsicPayloadV3 extends GenericExtrinsicPayloadV3 {}
/** GenericExtrinsicUnknown */
export type ExtrinsicUnknown = GenericExtrinsicUnknown;
export interface ExtrinsicUnknown extends GenericExtrinsicUnknown {}
/** GenericExtrinsicV1 */
export type ExtrinsicV1 = GenericExtrinsicV1;
export interface ExtrinsicV1 extends GenericExtrinsicV1 {}
/** GenericExtrinsicV2 */
export type ExtrinsicV2 = GenericExtrinsicV2;
export interface ExtrinsicV2 extends GenericExtrinsicV2 {}
/** GenericExtrinsicV3 */
export type ExtrinsicV3 = GenericExtrinsicV3;
export interface ExtrinsicV3 extends GenericExtrinsicV3 {}
/** H256 */
export type Hash = H256;
export interface Hash extends H256 {}
/** Struct */
export interface Header extends Struct {
@@ -101,55 +101,55 @@ export interface Header extends Struct {
}
/** GenericImmortalEra */
export type ImmortalEra = GenericImmortalEra;
export interface ImmortalEra extends GenericImmortalEra {}
/** u32 */
export type Index = u32;
export interface Index extends u32 {}
/** Bytes */
export type Justification = Bytes;
export interface Justification extends Bytes {}
/** u32 */
export type KeyTypeId = u32;
export interface KeyTypeId extends u32 {}
/** [StorageKey, StorageData] & Codec */
export type KeyValue = [StorageKey, StorageData] & Codec;
/** ITuple<[StorageKey, StorageData]> */
export interface KeyValue extends ITuple<[StorageKey, StorageData]> {}
/** Uint8Array & Codec */
export type LockIdentifier = Uint8Array & Codec;
/** Uint8Array, Codec */
export interface LockIdentifier extends Uint8Array, Codec {}
/** u64 */
export type Moment = u64;
export interface Moment extends u64 {}
/** GenericMortalEra */
export type MortalEra = GenericMortalEra;
export interface MortalEra extends GenericMortalEra {}
/** GenericOrigin */
export type Origin = GenericOrigin;
export interface Origin extends GenericOrigin {}
/** u32 */
export type Perbill = u32;
export interface Perbill extends u32 {}
/** u32 */
export type Permill = u32;
export interface Permill extends u32 {}
/** Null */
export type Phantom = Null;
export interface Phantom extends Null {}
/** Null */
export type PhantomData = Null;
export interface PhantomData extends Null {}
/** [ConsensusEngineId, Bytes] & Codec */
export type PreRuntime = [ConsensusEngineId, Bytes] & Codec;
/** ITuple<[ConsensusEngineId, Bytes]> */
export interface PreRuntime extends ITuple<[ConsensusEngineId, Bytes]> {}
/** [ConsensusEngineId, Bytes] & Codec */
export type Seal = [ConsensusEngineId, Bytes] & Codec;
/** ITuple<[ConsensusEngineId, Bytes]> */
export interface Seal extends ITuple<[ConsensusEngineId, Bytes]> {}
/** [u64, Signature] & Codec */
export type SealV0 = [u64, Signature] & Codec;
/** ITuple<[u64, Signature]> */
export interface SealV0 extends ITuple<[u64, Signature]> {}
/** H512 */
export type Signature = H512;
export interface Signature extends H512 {}
/** Struct */
export interface SignedBlock extends Struct {
@@ -160,16 +160,16 @@ export interface SignedBlock extends Struct {
}
/** GenericSignerPayload */
export type SignerPayload = GenericSignerPayload;
export interface SignerPayload extends GenericSignerPayload {}
/** Signature */
export type Sr25519Signature = Signature;
export interface Sr25519Signature extends Signature {}
/** AccountId */
export type ValidatorId = AccountId;
export interface ValidatorId extends AccountId {}
/** u32 */
export type Weight = u32;
export interface Weight extends u32 {}
/** Fixed64 */
export type WeightMultiplier = Fixed64;
export interface WeightMultiplier extends Fixed64 {}
+10 -10
View File
@@ -1,25 +1,25 @@
// Auto-generated via `yarn build:interfaces`, do not edit
/* eslint-disable @typescript-eslint/no-empty-interface */
import { Codec } from '../../types';
import { ITuple } from '../../types';
import { u32 } from '../../primitive';
import { AccountId, ValidatorId } from '../runtime';
import { Exposure } from '../staking';
/** Exposure */
export type FullIdentification = Exposure;
export interface FullIdentification extends Exposure {}
/** [ValidatorId, FullIdentification] & Codec */
export type IdentificationTuple = [ValidatorId, FullIdentification] & Codec;
/** ITuple<[ValidatorId, FullIdentification]> */
export interface IdentificationTuple extends ITuple<[ValidatorId, FullIdentification]> {}
/** SessionKeysSubstrate */
export type Keys = SessionKeysSubstrate;
export interface Keys extends SessionKeysSubstrate {}
/** u32 */
export type SessionIndex = u32;
export interface SessionIndex extends u32 {}
/** [AccountId, AccountId, AccountId, AccountId] & Codec */
export type SessionKeysPolkadot = [AccountId, AccountId, AccountId, AccountId] & Codec;
/** ITuple<[AccountId, AccountId, AccountId, AccountId]> */
export interface SessionKeysPolkadot extends ITuple<[AccountId, AccountId, AccountId, AccountId]> {}
/** [AccountId, AccountId, AccountId] & Codec */
export type SessionKeysSubstrate = [AccountId, AccountId, AccountId] & Codec;
/** ITuple<[AccountId, AccountId, AccountId]> */
export interface SessionKeysSubstrate extends ITuple<[AccountId, AccountId, AccountId]> {}
@@ -6,7 +6,7 @@ import { u32 } from '../../primitive';
import { AccountId, Balance, BlockNumber, Moment } from '../runtime';
/** u32 */
export type EraIndex = u32;
export interface EraIndex extends u32 {}
/** Struct */
export interface EraPoints extends Struct {
@@ -53,10 +53,10 @@ export interface IndividualExposure extends Struct {
}
/** Moment */
export type MomentOf = Moment;
export interface MomentOf extends Moment {}
/** u32 */
export type Points = u32;
export interface Points extends u32 {}
/** Enum */
export interface RewardDestination extends Enum {
@@ -7,7 +7,7 @@ import { Bytes, GenericEvent, u32, u8 } from '../../primitive';
import { Digest, Hash } from '../runtime';
/** Digest */
export type DigestOf = Digest;
export interface DigestOf extends Digest {}
/** Struct */
export interface DispatchError extends Struct {
@@ -18,13 +18,13 @@ export interface DispatchError extends Struct {
}
/** GenericEvent */
export type Event = GenericEvent;
export interface Event extends GenericEvent {}
/** Uint8Array & Codec */
export type EventId = Uint8Array & Codec;
/** Uint8Array, Codec */
export interface EventId extends Uint8Array, Codec {}
/** u32 */
export type EventIndex = u32;
export interface EventIndex extends u32 {}
/** Struct */
export interface EventRecord extends Struct {
@@ -45,7 +45,7 @@ export interface EventRecord0to76 extends Struct {
}
/** Bytes */
export type Key = Bytes;
export interface Key extends Bytes {}
/** Enum */
export interface Phase extends Enum {
@@ -0,0 +1,71 @@
// 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 * as definitions from '../../interfaces/definitions';
import * as primitiveClasses from '../../primitive';
import {
createImportCode, createImports,
FOOTER,
getDerivedTypes,
HEADER,
indent,
setImports
} from '../util';
// Generate `packages/types/src/interfaceRegistry.ts`, the registry of all interfaces
export default function generateInterfaceRegistry (): void {
console.log('Writing interfaceRegistry.ts');
const imports = createImports();
const primitives = Object
.keys(primitiveClasses)
.filter((name): boolean => !!name.indexOf('Generic'))
.reduce((accumulator, primitiveName): string => {
setImports(imports, [primitiveName]);
return [
accumulator,
getDerivedTypes(primitiveName, primitiveName, imports).map(indent(2)).join('\n')
].join('\n');
}, '');
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const srml = Object.entries(definitions).reduce((accumulator, [_defName, { types }]): string => {
setImports(imports, Object.keys(types));
return [
accumulator,
...Object.keys(types).map((type): string =>
getDerivedTypes(type, (types as any)[type], imports).map(indent(2)).join('\n')
)
].join('\n');
}, '');
const header = createImportCode(HEADER, [
{
file: './codec',
types: Object.keys(imports.codecTypes).filter((name): boolean => name !== 'Tuple')
},
{
file: './primitive',
types: Object.keys(imports.primitiveTypes)
},
...Object.keys(imports.localTypes).map((moduleName): { file: string; types: string[] } => ({
file: `./interfaces/${moduleName}`,
types: Object.keys(imports.localTypes[moduleName])
}))
]);
const interfaceStart = 'export interface InterfaceRegistry {';
const interfaceEnd = '\n}';
fs.writeFileSync(
'packages/types/src/interfaceRegistry.ts',
header.concat(interfaceStart).concat(primitives).concat(srml).concat(interfaceEnd).concat(FOOTER)
, { flag: 'w' }
);
}
@@ -0,0 +1,144 @@
// 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 { stringLowerFirst } from '@polkadot/util';
import { Metadata } from '../..';
import { ModuleMetadataV7 } from '../../Metadata/v7/Metadata';
import { StorageEntryMetadata } from '../../Metadata/v7/Storage';
import staticData from '../../Metadata/v7/static';
import { createImportCode, createImports, FOOTER, formatType, getSimilarTypes, HEADER, indent, setImports, TypeImports } from '../util';
// From a storage entry metadata, we return [args, returnType]
function entrySignature (storageEntry: StorageEntryMetadata, imports: TypeImports): [string, string] {
if (storageEntry.type.isPlainType) {
setImports(imports, [storageEntry.type.asType.toString()]);
return ['', formatType(storageEntry.type.asType.toString(), imports)];
} else if (storageEntry.type.isMap) {
// Find similar types of the `key` type
const similarTypes = getSimilarTypes(storageEntry.type.asMap.key.toString(), imports);
setImports(imports, [
...similarTypes,
storageEntry.type.asMap.value.toString()
]);
return [
`arg: ${similarTypes.map((type) => formatType(type, imports)).join(' | ')}`,
formatType(storageEntry.type.asMap.value.toString(), imports)
];
} else if (storageEntry.type.isDoubleMap) {
// Find similartypes of `key1` and `key2` types
const similarTypes1 = getSimilarTypes(storageEntry.type.asDoubleMap.key1.toString(), imports);
const similarTypes2 = getSimilarTypes(storageEntry.type.asDoubleMap.key2.toString(), imports);
setImports(imports, [
...similarTypes1,
...similarTypes2,
storageEntry.type.asDoubleMap.value.toString()
]);
const key1Types = similarTypes1.map((type) => formatType(type, imports)).join(' | ');
const key2Types = similarTypes2.map((type) => formatType(type, imports)).join(' | ');
return [
`key1: ${key1Types}, key2: ${key2Types}`,
formatType(storageEntry.type.asDoubleMap.value.toString(), imports)
];
}
throw new Error(`entryArgs: Cannot parse args of entry ${storageEntry.name}`);
}
// Generate types for one storage entry in a module
function generateEntry (storageEntry: StorageEntryMetadata, imports: TypeImports): string[] {
const [args, returnType] = entrySignature(storageEntry, imports);
return [
`${stringLowerFirst(storageEntry.name.toString())}: StorageEntryExact<ApiType, (${args}) => Observable<${returnType}>> & QueryableStorageEntry<ApiType>;`
// `${stringLowerFirst(storageEntry.name.toString())}: QueryableStorageEntry<ApiType>;`
];
}
// Generate types for one module
function generateModule (modul: ModuleMetadataV7, imports: TypeImports): string[] {
if (modul.storage.isNone) {
return [];
}
return [indent(4)(`${stringLowerFirst(modul.name.toString())}: {`)]
.concat(indent(6)('[index: string]: QueryableStorageEntry<ApiType>;'))
.concat(
modul.storage.unwrap().items
.reduce((acc, storageEntry): string[] => {
return acc.concat(generateEntry(storageEntry, imports).map(indent(6)));
}, [] as string[])
.join('\n')
)
.concat([indent(4)('};')]);
}
// Generate `packages/types-jsonrpc/src/jsonrpc.types.ts` for a particular
// metadata
function generateForMeta (meta: Metadata): void {
console.log('Writing packages/api/src/query.types.ts');
// Inject all types so that metadata can use them
require('../../injector');
const imports = createImports(); // Will hold all needed imports
const body = meta.asLatest.modules.reduce((acc, modul): string[] => {
const storageEntries = generateModule(modul, imports);
return acc.concat(storageEntries);
}, [] as string[]);
const header = createImportCode(HEADER, [
{
file: 'rxjs',
types: ['Observable']
},
{
file: '@polkadot/types/codec',
types: Object.keys(imports.codecTypes).filter((name): boolean => name !== 'Tuple')
},
{
file: '@polkadot/types',
types: Object.keys(imports.primitiveTypes)
},
...Object.keys(imports.localTypes).map((moduleName): { file: string; types: string[] } => ({
file: `@polkadot/types/interfaces/${moduleName}`,
types: Object.keys(imports.localTypes[moduleName])
})),
{
file: '@polkadot/types/types',
types: Object.keys(imports.typesTypes)
}
]);
const interfaceStart =
[
"declare module './types' {",
indent(2)('export interface QueryableStorageExact<ApiType> {\n')
].join('\n');
const interfaceEnd = `\n${indent(2)('}')}\n}`;
fs.writeFileSync(
'packages/api/src/query.types.ts',
header
.concat(interfaceStart)
.concat(body.join('\n'))
.concat(interfaceEnd)
.concat(FOOTER)
, { flag: 'w' }
);
}
// Call `generateForMeta()` with current static metadata
export default function generateQuery (): void {
return generateForMeta(new Metadata(staticData));
}
@@ -0,0 +1,82 @@
// 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 interfaces from '../../../../type-jsonrpc/src';
import { createImportCode, createImports, FOOTER, getSimilarTypes, HEADER, setImports } from '../util';
// Generate `packages/types-jsonrpc/src/jsonrpc.types.ts`
export default function generateRpcTypes (): void {
console.log('Writing packages/rpc-core/jsonrpc.types.ts');
// Inject all types so that types-jsonrpc can use them
require('../../injector');
const imports = createImports();
const body = Object.keys(interfaces).sort().reduce<string[]>((allSections, section): string[] => {
const allMethods = Object.keys(interfaces[section].methods).sort().map((key): string => {
const method = interfaces[section].methods[key];
setImports(imports, [method.type]);
// FIXME These 2 are too hard to type, I give up
if (method.method === 'getStorage') {
setImports(imports, ['Codec']);
return ' getStorage<T = Codec>(key: any, block?: Hash | Uint8Array | string): Observable<T>;';
} else if (method.method === 'subscribeStorage') {
return ' subscribeStorage<T = Codec[]>(keys: any[]): Observable<T>;';
}
const args = method.params.map((param): string => {
const similarTypes = getSimilarTypes(param.type, imports);
setImports(imports, [param.type, ...similarTypes]);
return `${param.name}${param.isOptional ? '?' : ''}: ${similarTypes.join(' | ')}`;
});
return ` ${method.method}(${args.join(', ')}): Observable<${method.type}>;`;
});
return allSections.concat(
[
` ${section}: {`,
...allMethods,
' };'
].join('\n')
);
}, []).join('\n');
const header = createImportCode(HEADER, [
{
file: 'rxjs',
types: ['Observable']
},
{
file: '@polkadot/types/codec',
types: Object.keys(imports.codecTypes).filter((name): boolean => name !== 'Tuple')
},
{
file: '@polkadot/types',
types: Object.keys(imports.primitiveTypes)
},
...Object.keys(imports.localTypes).map((moduleName): { file: string; types: string[] } => ({
file: `@polkadot/types/interfaces/${moduleName}`,
types: Object.keys(imports.localTypes[moduleName])
})),
{
file: '@polkadot/types/types',
types: Object.keys(imports.typesTypes)
}
]);
const interfaceStart = 'export interface RpcInterface {\n';
const interfaceEnd = '\n}';
fs.writeFileSync(
'packages/rpc-core/src/jsonrpc.types.ts',
header.concat(interfaceStart).concat(body).concat(interfaceEnd).concat(FOOTER)
, { flag: 'w' }
);
}
@@ -0,0 +1,267 @@
// 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 { TypeDef, TypeDefInfo, TypeDefExtVecFixed } from '../../codec/types';
import fs from 'fs';
import { isString, stringCamelCase, stringUpperFirst } from '@polkadot/util';
import { getTypeDef } from '../../codec/create';
import * as definitions from '../../interfaces/definitions';
import {
createImportCode, createImports,
exportInterface, exportType,
formatCompact, formatOption, formatTuple, formatVec,
FOOTER, HEADER,
setImports, TypeImports
} from '../util';
interface Imports extends TypeImports {
interfaces: [string, string][];
}
// helper to generate a `readonly <Name>: <Type>;` getter
export function createGetter (name = '', type: string, imports: TypeImports, doc?: string): string {
setImports(imports, [type]);
return ` /** ${doc || type} */\n readonly ${name}: ${type};\n`;
}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
function errorUnhandled (def: TypeDef, imports: TypeImports): string {
throw new Error(`Generate: ${name}: Unhandled type ${TypeDefInfo[def.info]}`);
}
function tsCompact ({ name: compactName, sub }: TypeDef, imports: TypeImports): string {
const def = (sub as TypeDef);
setImports(imports, ['Compact']);
switch (def.info) {
case TypeDefInfo.Plain:
setImports(imports, [def.type]);
return exportType(compactName, formatCompact(def.type));
default:
throw new Error(`Enum: ${compactName}: Unhandled type ${TypeDefInfo[def.info]}`);
}
}
function tsEnum ({ name: enumName, sub }: TypeDef, imports: TypeImports): string {
setImports(imports, ['Enum']);
const keys = (sub as TypeDef[]).map(({ info, name = '', type }, index): string => {
const getter = stringUpperFirst(stringCamelCase(name.replace(' ', '_')));
const [enumType, asGetter] = type === 'Null'
? ['', '']
: [`(${type})`, createGetter(`as${getter}`, type, imports)];
const isGetter = createGetter(`is${getter}`, 'boolean', imports, `${index}:: ${name}${enumType}`);
switch (info) {
case TypeDefInfo.Plain:
case TypeDefInfo.Vec:
return `${isGetter}${asGetter}`;
default:
throw new Error(`Enum: ${enumName}: Unhandled type ${TypeDefInfo[info]}`);
}
});
return exportInterface(enumName, 'Enum', keys.join(''));
}
function tsOption ({ name: optionName, sub }: TypeDef, imports: TypeImports): string {
const def = (sub as TypeDef);
setImports(imports, ['Option']);
switch (def.info) {
case TypeDefInfo.Plain:
setImports(imports, [def.type]);
return exportType(optionName, formatOption(def.type));
default:
throw new Error(`Enum: ${optionName}: Unhandled type ${TypeDefInfo[def.info]}`);
}
}
function tsPlain ({ name: plainName, type }: TypeDef, imports: TypeImports): string {
setImports(imports, [type]);
return exportType(plainName, type);
}
function _tsStructGetterType (structName: string | undefined, { info, sub, type }: TypeDef, imports: TypeImports): [string, string] {
let _type;
switch (info) {
case TypeDefInfo.Compact:
_type = (sub as TypeDef).type;
setImports(imports, ['Compact']);
return [_type, formatCompact(_type)];
case TypeDefInfo.Option:
_type = (sub as TypeDef).type;
setImports(imports, ['Option']);
return [_type, formatOption(_type)];
case TypeDefInfo.Plain:
return [type, type];
case TypeDefInfo.Vec:
_type = (sub as TypeDef).type;
setImports(imports, ['Vec']);
return [_type, formatVec(_type)];
default:
throw new Error(`Struct: ${structName}: Unhandled type ${TypeDefInfo[info]}`);
}
}
function tsSet ({ name: setName, sub }: TypeDef, imports: TypeImports): string {
setImports(imports, ['Set']);
const types = (sub as TypeDef[]).map(({ name }): string =>
createGetter(`is${name}`, 'boolean', imports)
);
return exportInterface(setName, 'Set', types.join(''));
}
function tsStruct ({ name: structName, sub }: TypeDef, imports: TypeImports): string {
const keys = (sub as TypeDef[]).map((typedef): string => {
const [embedType, returnType] = _tsStructGetterType(structName, typedef, imports);
setImports(imports, ['Struct', embedType]);
return createGetter(typedef.name, returnType, imports);
});
return exportInterface(structName, 'Struct', keys.join(''));
}
function _tsTupleGetterType (tupleName: string | undefined, { info, sub, type }: TypeDef, imports: TypeImports): string {
switch (info) {
case TypeDefInfo.Option:
setImports(imports, ['Option', (sub as TypeDef).type]);
return type;
case TypeDefInfo.Plain:
setImports(imports, [type]);
return type;
default:
throw new Error(`Struct: ${tupleName}: Unhandled type ${TypeDefInfo[info]}`);
}
}
function tsTuple ({ name: tupleName, sub }: TypeDef, imports: TypeImports): string {
setImports(imports, ['ITuple']);
const types = (sub as TypeDef[]).map((typedef): string =>
_tsTupleGetterType(tupleName, typedef, imports)
);
return exportType(tupleName, formatTuple(types));
}
function tsVec ({ ext, info, name: vectorName, sub }: TypeDef, imports: TypeImports): string {
const type = info === TypeDefInfo.VecFixed
? (ext as TypeDefExtVecFixed).type
: (sub as TypeDef).type;
// FIXME This should be a VecFixed
// FIXME Technically Vec has length prefix, so for others this is not 100%
if (info === TypeDefInfo.VecFixed && type === 'u8') {
setImports(imports, ['Codec']);
return exportType(vectorName, 'Uint8Array, Codec');
}
setImports(imports, ['Vec', type]);
return exportType(vectorName, formatVec(type));
}
function generateInterfaces ({ types }: { types: Record<string, any> }, imports: Imports): [string, string][] {
// 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]: tsCompact,
[TypeDefInfo.DoubleMap]: errorUnhandled,
[TypeDefInfo.Enum]: tsEnum,
[TypeDefInfo.Linkage]: errorUnhandled,
[TypeDefInfo.Null]: errorUnhandled,
[TypeDefInfo.Option]: tsOption,
[TypeDefInfo.Plain]: tsPlain,
[TypeDefInfo.Set]: tsSet,
[TypeDefInfo.Struct]: tsStruct,
[TypeDefInfo.Tuple]: tsTuple,
[TypeDefInfo.Vec]: tsVec,
[TypeDefInfo.VecFixed]: tsVec
};
return Object.entries(types).map(([name, type]): [string, string] => {
const def = getTypeDef(isString(type) ? type.toString() : JSON.stringify(type), name);
return [name, generators[def.info](def, imports)];
});
}
function generateTsDefFor (defName: string, { types }: { types: Record<string, any> }): void {
const imports = { ...createImports({ types }), interfaces: [] } as Imports;
const interfaces = generateInterfaces({ types }, imports);
const sortedDefs = interfaces.sort((a, b): number => a[0].localeCompare(b[0])).map(([, definition]): string => definition).join('\n\n');
const header = createImportCode(HEADER, [
{
file: '../../types',
types: Object.keys(imports.typesTypes)
},
{
file: '../../codec',
types: Object.keys(imports.codecTypes).filter((name): boolean => name !== 'Tuple')
},
{
file: '../../primitive',
types: Object.keys(imports.primitiveTypes)
},
...Object.keys(imports.localTypes).map((moduleName): { file: string; types: string[] } => ({
file: `../${moduleName}`,
types: Object.keys(imports.localTypes[moduleName])
}))
]);
Object.entries(imports.localTypes).forEach(([moduleName, typeMap]): void => {
const types = Object.keys(typeMap).sort();
if (types.length) {
console.log(`\timport { ${types.join(', ')} } from '../${moduleName}'`);
}
});
fs.writeFileSync(`packages/types/src/interfaces/${defName}/types.ts`, header.concat(sortedDefs).concat(FOOTER), { flag: 'w' });
fs.writeFileSync(`packages/types/src/interfaces/${defName}/index.ts`, HEADER.concat('export * from \'./types\';').concat(FOOTER), { flag: 'w' });
}
export default function generateTsDef (): void {
Object.entries(definitions).forEach(([defName, obj]): void => {
console.log(`Extracting interfaces for ${defName}`);
generateTsDefFor(defName, obj);
});
console.log('Writing interfaces/types.ts');
fs.writeFileSync('packages/types/src/interfaces/types.ts', HEADER.concat(Object.keys(definitions).map((moduleName): string => `export * from './${moduleName}/types';`).join('\n')).concat(FOOTER), { flag: 'w' });
fs.writeFileSync('packages/types/src/interfaces/index.ts', HEADER.concat('export * from \'./types\';').concat(FOOTER), { flag: 'w' });
}
+6 -541
View File
@@ -2,551 +2,16 @@
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { TypeDef, TypeDefInfo, TypeDefExtVecFixed } from '../codec/types';
import { Constructor } from '../types';
import fs from 'fs';
import { isString, stringCamelCase, stringUpperFirst } from '@polkadot/util';
import interfaces from '../../../type-jsonrpc/src';
import { ClassOfUnsafe, getTypeDef } from '../codec/create';
import * as codecClasses from '../codec';
import AbstractInt from '../codec/AbstractInt';
import UInt from '../codec/UInt';
import Vec from '../codec/Vec';
import * as definitions from '../interfaces/definitions';
import * as primitiveClasses from '../primitive';
// 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 = Record<string, boolean>;
// local imports (between files), maps to this format
// { [moduleName]: { [typeName]: true } }
type LocalExist = Record<string, TypeExist>;
interface TypeImports {
codecTypes: TypeExist; // `import {} from '@polkadot/types/codec`
localTypes: LocalExist;
ownTypes: string[];
primitiveTypes: TypeExist; // `import {} from '@polkadot/types/primitive`
typesTypes: TypeExist; // `import {} from '@polkadot/types/types`
}
const HEADER = '// Auto-generated via `yarn build:interfaces`, do not edit\n/* eslint-disable @typescript-eslint/no-empty-interface */\n\n';
const FOOTER = '\n';
// Maps the types as found to the source location. This is used to generate the
// imports in the output file, dep-duped and sorted
function setImports ({ codecTypes, localTypes, ownTypes, primitiveTypes, typesTypes }: TypeImports, types: string[]): void {
types.forEach((type): void => {
if (ownTypes.includes(type)) {
// do nothing
} else if (['Codec', 'IExtrinsic'].includes(type)) {
typesTypes[type] = true;
} else if ((codecClasses as any)[type]) {
codecTypes[type] = true;
} else if ((primitiveClasses as any)[type] || type === 'Metadata') {
primitiveTypes[type] = true;
} else {
// find this module inside the exports from the rest
const [moduleName] = Object.entries(definitions).find(([, { types }]): boolean =>
Object.keys(types).includes(type)
) || [null];
if (moduleName) {
localTypes[moduleName][type] = true;
}
}
});
}
// See if a class is child of another class
// FIMXE This could go in util some day
function isChildClass (Parent: Constructor<any>, Child: Constructor<any>): boolean {
// https://stackoverflow.com/questions/30993434/check-if-a-constructor-inherits-another-in-es6/30993664
// eslint-disable-next-line no-prototype-builtins
return Parent === Child || Parent.isPrototypeOf(Child);
}
function isCompactEncodable (Child: Constructor<any>): boolean {
return isChildClass(UInt, Child);
}
// helper to generate a `export interface <Name> extends <Base> {<Body>}
function exportInterface (name = '', base: string, body = ''): string {
return `/** ${base} */\nexport interface ${name} extends ${base} {${body.length ? '\n' : ''}${body}}`;
}
// helper to create an `export <Name> = <Base>`
function exportType (name = '', base: string): string {
return `/** ${base} */\nexport type ${name} = ${base};`;
}
// helper to generate a `readonly <Name>: <Type>;` getter
function createGetter (name = '', type: string, imports: TypeImports, doc?: string): string {
setImports(imports, [type]);
return ` /** ${doc || type} */\n readonly ${name}: ${type};\n`;
}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
function errorUnhandled (def: TypeDef, imports: TypeImports): string {
throw new Error(`Generate: ${name}: Unhandled type ${TypeDefInfo[def.info]}`);
}
function tsCompact ({ name: compactName, sub }: TypeDef, imports: TypeImports): string {
const def = (sub as TypeDef);
setImports(imports, ['Compact']);
switch (def.info) {
case TypeDefInfo.Plain:
setImports(imports, [def.type]);
return exportType(compactName, `Compact<${def.type}>`);
default:
throw new Error(`Enum: ${compactName}: Unhandled type ${TypeDefInfo[def.info]}`);
}
}
function tsEnum ({ name: enumName, sub }: TypeDef, imports: TypeImports): string {
setImports(imports, ['Enum']);
const keys = (sub as TypeDef[]).map(({ info, name = '', type }, index): string => {
const getter = stringUpperFirst(stringCamelCase(name.replace(' ', '_')));
const [enumType, asGetter] = type === 'Null'
? ['', '']
: [`(${type})`, createGetter(`as${getter}`, type, imports)];
const isGetter = createGetter(`is${getter}`, 'boolean', imports, `${index}:: ${name}${enumType}`);
switch (info) {
case TypeDefInfo.Plain:
case TypeDefInfo.Vec:
return `${isGetter}${asGetter}`;
default:
throw new Error(`Enum: ${enumName}: Unhandled type ${TypeDefInfo[info]}`);
}
});
return exportInterface(enumName, 'Enum', keys.join(''));
}
function tsOption ({ name: optionName, sub }: TypeDef, imports: TypeImports): string {
const def = (sub as TypeDef);
setImports(imports, ['Option']);
switch (def.info) {
case TypeDefInfo.Plain:
setImports(imports, [def.type]);
return exportType(optionName, `Option<${def.type}>`);
default:
throw new Error(`Enum: ${optionName}: Unhandled type ${TypeDefInfo[def.info]}`);
}
}
function tsPlain ({ name: plainName, type }: TypeDef, imports: TypeImports): string {
setImports(imports, [type]);
return exportType(plainName, type);
}
function _tsStructGetterType (structName: string | undefined, { info, sub, type }: TypeDef, imports: TypeImports): [string, string] {
let _type;
switch (info) {
case TypeDefInfo.Compact:
_type = (sub as TypeDef).type;
setImports(imports, ['Compact']);
return [_type, `Compact<${_type}>`];
case TypeDefInfo.Option:
_type = (sub as TypeDef).type;
setImports(imports, ['Option']);
return [_type, `Option<${_type}>`];
case TypeDefInfo.Plain:
return [type, type];
case TypeDefInfo.Vec:
_type = (sub as TypeDef).type;
setImports(imports, ['Vec']);
return [_type, `Vec<${_type}>`];
default:
throw new Error(`Struct: ${structName}: Unhandled type ${TypeDefInfo[info]}`);
}
}
function tsSet ({ name: setName, sub }: TypeDef, imports: TypeImports): string {
setImports(imports, ['Set']);
const types = (sub as TypeDef[]).map(({ name }): string =>
createGetter(`is${name}`, 'boolean', imports)
);
return exportInterface(setName, 'Set', types.join(''));
}
function tsStruct ({ name: structName, sub }: TypeDef, imports: TypeImports): string {
const keys = (sub as TypeDef[]).map((typedef): string => {
const [embedType, returnType] = _tsStructGetterType(structName, typedef, imports);
setImports(imports, ['Struct', embedType]);
return createGetter(typedef.name, returnType, imports);
});
return exportInterface(structName, 'Struct', keys.join(''));
}
function _tsTupleGetterType (tupleName: string | undefined, { info, sub, type }: TypeDef, imports: TypeImports): string {
switch (info) {
case TypeDefInfo.Option:
setImports(imports, ['Option', (sub as TypeDef).type]);
return type;
case TypeDefInfo.Plain:
setImports(imports, [type]);
return type;
default:
throw new Error(`Struct: ${tupleName}: Unhandled type ${TypeDefInfo[info]}`);
}
}
function tsTuple ({ name: tupleName, sub }: TypeDef, imports: TypeImports): string {
setImports(imports, ['Codec', 'Tuple']);
const types = (sub as TypeDef[]).map((typedef): string =>
_tsTupleGetterType(tupleName, typedef, imports)
);
return exportType(tupleName, `[${types.join(', ')}] & Codec`);
}
function tsVec ({ ext, info, name: vectorName, sub }: TypeDef, imports: TypeImports): string {
const type = info === TypeDefInfo.VecFixed
? (ext as TypeDefExtVecFixed).type
: (sub as TypeDef).type;
// FIXME This should be a VecFixed
// FIXME Technically Vec has length prefix, so for others this is not 100%
if (info === TypeDefInfo.VecFixed && type === 'u8') {
setImports(imports, ['Codec']);
return exportType(vectorName, 'Uint8Array & Codec');
}
setImports(imports, ['Vec', type]);
return exportType(vectorName, `Vec<${type}>`);
}
// creates the import lines
function createImportCode (header: string, checks: { file: string; types: string[] }[]): string {
return checks.reduce((result, { file, types }): string => {
if (types.length) {
result += `import { ${types.sort().join(', ')} } from '${file}';\n`;
}
return result;
}, header) + '\n';
}
// From `T`, generate `Compact<T>, Option<T>, Vec<T>`
function getDerivedTypes (type: string, primitiveName: string, imports: TypeImports, indent = 2): string {
// `primitiveName` represents the actual primitive type our type is mapped to
const isCompact = isCompactEncodable((primitiveClasses as any)[primitiveName]);
setImports(imports, ['Option', 'Vec', isCompact ? 'Compact' : '']);
return [
`${type}: ${type};`,
isCompact
? `'Compact<${type}>': Compact<${type}>;`
: undefined,
`'Option<${type}>': Option<${type}>;`,
`'Vec<${type}>': Vec<${type}>;`
]
.filter((x): boolean => !!x)
.map((line): string => `${' '.repeat(indent)}${line}`) // Add indentation
.join('\n');
}
interface Imports extends TypeImports {
interfaces: [string, string][];
}
// Create an Imports object, prefilled with types (if necessary)
function createImports ({ types }: { types: Record<string, any> } = { types: {} }): Imports {
// 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]: tsCompact,
[TypeDefInfo.DoubleMap]: errorUnhandled,
[TypeDefInfo.Enum]: tsEnum,
[TypeDefInfo.Linkage]: errorUnhandled,
[TypeDefInfo.Null]: errorUnhandled,
[TypeDefInfo.Option]: tsOption,
[TypeDefInfo.Plain]: tsPlain,
[TypeDefInfo.Set]: tsSet,
[TypeDefInfo.Struct]: tsStruct,
[TypeDefInfo.Tuple]: tsTuple,
[TypeDefInfo.Vec]: tsVec,
[TypeDefInfo.VecFixed]: tsVec
};
const codecTypes: TypeExist = {};
const localTypes: LocalExist = Object.keys(definitions).reduce((localTypes: Record<string, TypeExist>, moduleName): Record<string, TypeExist> => {
localTypes[moduleName] = {};
return localTypes;
}, {});
const ownTypes = Object.keys(types);
const primitiveTypes: TypeExist = {};
const typesTypes: TypeExist = {};
const interfaces = Object.entries(types).map(([name, type]): [string, string] => {
const def = getTypeDef(isString(type) ? type.toString() : JSON.stringify(type), name);
return [name, generators[def.info](def, { codecTypes, localTypes, ownTypes, primitiveTypes, typesTypes })];
});
const imports = { codecTypes, localTypes, ownTypes, primitiveTypes, typesTypes, interfaces };
return imports;
}
function generateTsDef (defName: string, { types }: { types: Record<string, any> }): void {
const imports = createImports({ types });
const sortedDefs = imports.interfaces.sort((a, b): number => a[0].localeCompare(b[0])).map(([, definition]): string => definition).join('\n\n');
const header = createImportCode(HEADER, [
{
file: '../../types',
types: Object.keys(imports.typesTypes)
},
{
file: '../../codec',
types: Object.keys(imports.codecTypes).filter((name): boolean => name !== 'Tuple')
},
{
file: '../../primitive',
types: Object.keys(imports.primitiveTypes)
},
...Object.keys(imports.localTypes).map((moduleName): { file: string; types: string[] } => ({
file: `../${moduleName}`,
types: Object.keys(imports.localTypes[moduleName])
}))
]);
Object.entries(imports.localTypes).forEach(([moduleName, typeMap]): void => {
const types = Object.keys(typeMap).sort();
if (types.length) {
console.log(`\timport { ${types.join(', ')} } from '../${moduleName}'`);
}
});
fs.writeFileSync(`packages/types/src/interfaces/${defName}/types.ts`, header.concat(sortedDefs).concat(FOOTER), { flag: 'w' });
fs.writeFileSync(`packages/types/src/interfaces/${defName}/index.ts`, HEADER.concat('export * from \'./types\';').concat(FOOTER), { flag: 'w' });
}
// Generate `packages/types/src/interfaceRegistry.ts`, the registry of all interfaces
function generateInterfaceRegistry (): void {
const imports = createImports();
const primitives = Object
.keys(primitiveClasses)
.filter((name): boolean => !!name.indexOf('Generic'))
.reduce((accumulator, primitiveName): string => {
setImports(imports, [primitiveName]);
return [
accumulator,
getDerivedTypes(primitiveName, primitiveName, imports)
].join('\n');
}, '');
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const srml = Object.entries(definitions).reduce((accumulator, [_defName, { types }]): string => {
setImports(imports, Object.keys(types));
return [
accumulator,
...Object.keys(types).map((type): string =>
getDerivedTypes(type, (types as any)[type], imports, 2)
)
].join('\n');
}, '');
const header = createImportCode(HEADER, [
{
file: './codec',
types: Object.keys(imports.codecTypes).filter((name): boolean => name !== 'Tuple')
},
{
file: './primitive',
types: Object.keys(imports.primitiveTypes)
},
...Object.keys(imports.localTypes).map((moduleName): { file: string; types: string[] } => ({
file: `./interfaces/${moduleName}`,
types: Object.keys(imports.localTypes[moduleName])
}))
]);
const interfaceStart = 'export interface InterfaceRegistry {';
const interfaceEnd = '\n}';
fs.writeFileSync(
'packages/types/src/interfaceRegistry.ts',
header.concat(interfaceStart).concat(primitives).concat(srml).concat(interfaceEnd).concat(FOOTER)
, { flag: 'w' }
);
}
// Make types a little bit more flexible
// - if param instanceof AbstractInt, then param: u64 | Uint8array | string | number
// etc
function getSimilarTypes (imports: Imports, type: string): string[] {
const possibleTypes = [type];
if (type === 'Extrinsic') {
setImports(imports, ['IExtrinsic']);
return ['IExtrinsic'];
}
if (isChildClass(Vec, ClassOfUnsafe(type))) {
return [`(${getSimilarTypes(imports, ((getTypeDef(type).sub) as TypeDef).type).join(' | ')})[]`];
}
// FIXME This is a hack, it's hard to correctly type StorageKeys in the
// current state
if (type === 'StorageKey') {
return ['any'];
}
// Cannot get isChildClass of abstract class, but it works
if (isChildClass(AbstractInt as unknown as Constructor<any>, ClassOfUnsafe(type))) {
possibleTypes.push('Uint8Array', 'number', 'string');
} else if (isChildClass(Uint8Array, ClassOfUnsafe(type))) {
possibleTypes.push('Uint8Array', 'string');
} else if (isChildClass(String, ClassOfUnsafe(type))) {
possibleTypes.push('string');
}
return possibleTypes;
}
// Generate `packages/types-jsonrpc/src/jsonrpc.types.ts`
function generateRpcTypes (): void {
// Inject all types so that types-jsonrpc can use them
require('../injector');
// Get all imported types by types-jsonrpc
const allImportedTypes = Object.keys(interfaces).reduce<string[]>((allSections, section): string[] => {
return allSections.concat(
...Object.values(interfaces[section].methods).map((method): string[] =>
[...method.params.map(({ type }): string => type), method.type])
);
}, []);
const imports = createImports({ types: allImportedTypes });
const body = Object.keys(interfaces).sort().reduce<string[]>((allSections, section): string[] => {
const allMethods = Object.keys(interfaces[section].methods).sort().map((key): string => {
const method = interfaces[section].methods[key];
// FIXME These 2 are too hard to type, I give up
if (method.method === 'getStorage') {
setImports(imports, ['Codec']);
return ' getStorage<T = Codec>(key: any, block?: Hash | Uint8Array | string): Observable<T>;';
} else if (method.method === 'subscribeStorage') {
return ' subscribeStorage<T = Codec[]>(keys: any[]): Observable<T>;';
}
const args = method.params.map((param): string => {
const similarTypes = getSimilarTypes(imports, param.type);
setImports(imports, similarTypes);
return `${param.name}${param.isOptional ? '?' : ''}: ${similarTypes.join(' | ')}`;
});
return ` ${method.method}(${args.join(', ')}): Observable<${method.type}>;`;
});
return allSections.concat(
[
` ${section}: {`,
...allMethods,
' };'
].join('\n')
);
}, []).join('\n');
const header = createImportCode(HEADER, [
{
file: 'rxjs',
types: ['Observable']
},
{
file: '@polkadot/types/codec',
types: Object.keys(imports.codecTypes).filter((name): boolean => name !== 'Tuple')
},
{
file: '@polkadot/types',
types: Object.keys(imports.primitiveTypes)
},
...Object.keys(imports.localTypes).map((moduleName): { file: string; types: string[] } => ({
file: `@polkadot/types/interfaces/${moduleName}`,
types: Object.keys(imports.localTypes[moduleName])
})),
{
file: '@polkadot/types/types',
types: Object.keys(imports.typesTypes)
}
]);
const interfaceStart = 'export interface RpcInterface {\n';
const interfaceEnd = '\n}';
fs.writeFileSync(
'packages/rpc-core/src/jsonrpc.types.ts',
header.concat(interfaceStart).concat(body).concat(interfaceEnd).concat(FOOTER)
, { flag: 'w' }
);
}
import generateInterfaceRegistry from './generateTypes/interfaceRegistry';
import generateQueryTypes from './generateTypes/query';
import generateRpcTypes from './generateTypes/rpc';
import generateTsDef from './generateTypes/tsDef';
function main (): void {
Object.entries(definitions).forEach(([defName, obj]): void => {
console.log(`Extracting interfaces for ${defName}`);
generateTsDef(defName, obj);
});
console.log('Writing interfaces/types.ts');
fs.writeFileSync('packages/types/src/interfaces/types.ts', HEADER.concat(Object.keys(definitions).map((moduleName): string => `export * from './${moduleName}/types';`).join('\n')).concat(FOOTER), { flag: 'w' });
fs.writeFileSync('packages/types/src/interfaces/index.ts', HEADER.concat('export * from \'./types\';').concat(FOOTER), { flag: 'w' });
console.log('Writing interfaceRegistry.ts');
generateInterfaceRegistry();
console.log('Writing packages/rpc-core/jsonrpc.types.ts');
generateQueryTypes();
generateRpcTypes();
generateTsDef();
}
main();
+19
View File
@@ -0,0 +1,19 @@
// 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 { Constructor } from '../../types';
import UInt from '../../codec/UInt';
// See if a class is child of another class
// FIMXE This could go in util some day
export function isChildClass (Parent: Constructor<any>, Child: Constructor<any>): boolean {
// https://stackoverflow.com/questions/30993434/check-if-a-constructor-inherits-another-in-es6/30993664
// eslint-disable-next-line no-prototype-builtins
return Parent === Child || Parent.isPrototypeOf(Child);
}
export function isCompactEncodable (Child: Constructor<any>): boolean {
return isChildClass(UInt, Child);
}
@@ -0,0 +1,65 @@
// 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 { TypeDef } from '../../codec/types';
import { Constructor } from '../../types';
import { isChildClass, isCompactEncodable } from './class';
import { ClassOfUnsafe, getTypeDef } from '../../codec/create';
import AbstractInt from '../../codec/AbstractInt';
import Vec from '../../codec/Vec';
import { formatCompact, formatOption, formatVec } from './formatting';
import { setImports, TypeImports } from './imports';
import * as primitiveClasses from '../../primitive';
// From `T`, generate `Compact<T>, Option<T>, Vec<T>`
export function getDerivedTypes (type: string, primitiveName: string, imports: TypeImports): string[] {
// `primitiveName` represents the actual primitive type our type is mapped to
const isCompact = isCompactEncodable((primitiveClasses as any)[primitiveName]);
setImports(imports, ['Option', 'Vec', isCompact ? 'Compact' : '']);
return [
`${type}: ${type};`,
isCompact
? `'${formatCompact(type)}': ${formatCompact(type)};`
: '',
`'${formatOption(type)}': ${formatOption(type)};`,
`'${formatVec(type)}': ${formatVec(type)};`
]
.filter((x): boolean => !!x);
}
// Make types a little bit more flexible
// - if param instanceof AbstractInt, then param: u64 | Uint8array | string | number
// etc
export function getSimilarTypes (type: string, imports: TypeImports): string[] {
const possibleTypes = [type];
if (type === 'Extrinsic') {
setImports(imports, ['IExtrinsic']);
return ['IExtrinsic'];
}
if (isChildClass(Vec, ClassOfUnsafe(type))) {
return [`(${getSimilarTypes(((getTypeDef(type).sub) as TypeDef).type, imports).join(' | ')})[]`];
}
// FIXME This is a hack, it's hard to correctly type StorageKeys in the
// current state
if (type === 'StorageKey') {
return ['any'];
}
// Cannot get isChildClass of abstract class, but it works
if (isChildClass(AbstractInt as unknown as Constructor<any>, ClassOfUnsafe(type))) {
possibleTypes.push('Uint8Array', 'number', 'string');
} else if (isChildClass(Uint8Array, ClassOfUnsafe(type))) {
possibleTypes.push('Uint8Array', 'string');
} else if (isChildClass(String, ClassOfUnsafe(type))) {
possibleTypes.push('string');
}
return possibleTypes;
}
@@ -0,0 +1,11 @@
// 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 { indent } from './formatting';
describe('formatting', () => {
it('should indent correctly', () => {
expect(indent(2)('foo')).toBe(' foo');
});
});
@@ -0,0 +1,111 @@
// 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 { TypeDef, TypeDefInfo } from '../../codec/types';
import { getTypeDef } from '../../codec/create';
import { setImports, TypeImports } from './imports';
export const HEADER = '// Auto-generated via `yarn build:interfaces`, do not edit\n/* eslint-disable @typescript-eslint/no-empty-interface */\n\n';
export const FOOTER = '\n';
// creates the import lines
export function createImportCode (header: string, checks: { file: string; types: string[] }[]): string {
return checks.reduce((result, { file, types }): string => {
if (types.length) {
result += `import { ${types.sort().join(', ')} } from '${file}';\n`;
}
return result;
}, header) + '\n';
}
// helper to generate a `export interface <Name> extends <Base> {<Body>}
export function exportInterface (name = '', base: string, body = ''): string {
return `/** ${base} */\nexport interface ${name} extends ${base} {${body.length ? '\n' : ''}${body}}`;
}
// helper to create an `export type <Name> = <Base>`
// but since we don't want type alias (TS doesn't preserve names) we use
// interface here.
export function exportType (name = '', base: string): string {
return exportInterface(name, base);
}
/**
* Given the inner `T`, return a `Compact<T>` string
*/
export function formatCompact (inner: string): string {
return `Compact<${inner}>`;
}
/**
* Given the inner `T`, return a `Option<T>` string
*/
export function formatOption (inner: string): string {
return `Option<${inner}>`;
}
/**
* Given the inners `T[]`, return a `ITuple<...T>` string
*/
export function formatTuple (inners: string[]): string {
return `ITuple<[${inners.join(', ')}]>`;
}
/**
* Given the inner `T`, return a `Vec<T>` string
*/
export function formatVec (inner: string): string {
return `Vec<${inner}>`;
}
/**
* Correctly format a given type
*/
export function formatType (type: string, imports: TypeImports): string {
const typeDef = getTypeDef(type);
switch (typeDef.info) {
case TypeDefInfo.Compact: {
return formatCompact(formatType((typeDef.sub as TypeDef).type, imports));
}
case TypeDefInfo.Option: {
return formatOption(formatType((typeDef.sub as TypeDef).type, imports));
}
case TypeDefInfo.Plain: {
return type;
}
case TypeDefInfo.Vec: {
return formatVec(formatType((typeDef.sub as TypeDef).type, imports));
}
case TypeDefInfo.Tuple: {
setImports(imports, ['ITuple']);
// `(a,b)` gets transformed into `ITuple<[a, b]>`
return formatTuple(
((typeDef.sub as TypeDef[])
.map((sub): string => formatType(sub.type, imports)))
);
}
case TypeDefInfo.VecFixed: {
setImports(imports, ['U8a']);
// `[u8, 32]` gets transformed into U8a
return 'U8a';
}
default: {
throw new Error(`Cannot format ${type}.`);
}
}
}
/**
* Indent a string with `n` spaces before.
*/
export function indent (n: number, char = ' '): (str: string) => string {
return function (str: string): string {
return `${char.repeat(n)}${str}`;
};
}
@@ -0,0 +1,82 @@
// 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 * as codecClasses from '../../codec';
import { getTypeDef } from '../../codec/create';
import { TypeDefInfo } from '../../codec/types';
import * as definitions from '../../interfaces/definitions';
import * as primitiveClasses from '../../primitive';
// 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 = Record<string, boolean>;
// local and absolute imports map to this format
// { [moduleName]: { [typeName]: true } }
type TypeExistMap = Record<string, TypeExist>;
export interface TypeImports {
codecTypes: TypeExist; // `import {} from '@polkadot/types/codec`
localTypes: TypeExistMap; // `import {} from '../something'`
ignoredTypes: string[]; // No need to import these types
primitiveTypes: TypeExist; // `import {} from '@polkadot/types/primitive`
typesTypes: TypeExist; // `import {} from '@polkadot/types/types`
}
// Maps the types as found to the source location. This is used to generate the
// imports in the output file, dep-duped and sorted
export function setImports (imports: TypeImports, types: string[]): void {
const { codecTypes, localTypes, ignoredTypes, primitiveTypes, typesTypes } = imports;
types.forEach((type): void => {
if (ignoredTypes.includes(type)) {
// do nothing
} else if (['Codec', 'IExtrinsic', 'ITuple'].includes(type)) {
typesTypes[type] = true;
} else if ((codecClasses as any)[type]) {
codecTypes[type] = true;
} else if ((primitiveClasses as any)[type] || type === 'Metadata') {
primitiveTypes[type] = true;
} else if (type.includes('<') || type.includes('(') || type.includes('[')) {
// If the type is a bit special (tuple, fixed u8, nested type...), then we
// need to parse it with `getTypeDef`.
const typeDef = getTypeDef(type);
setImports(imports, [TypeDefInfo[typeDef.info]]);
// TypeDef.sub is a `TypeDef | TypeDef[]`
if (Array.isArray(typeDef.sub)) {
typeDef.sub.forEach((subType): void => setImports(imports, [subType.type]));
} else if (typeDef.sub) {
// typeDef.sub is a TypeDef in this case
setImports(imports, [typeDef.sub.type]);
}
} else {
// find this module inside the exports from the rest
const [moduleName] = Object.entries(definitions).find(([, { types }]): boolean =>
Object.keys(types).includes(type)
) || [null];
if (moduleName) {
localTypes[moduleName][type] = true;
}
}
});
}
// Create an Imports object, can be prefilled with `ignoredTypes`
export function createImports ({ types }: { types: Record<string, any> } = { types: {} }): TypeImports {
const codecTypes: TypeExist = {};
const localTypes: TypeExistMap = Object.keys(definitions).reduce((localTypes: Record<string, TypeExist>, moduleName): Record<string, TypeExist> => {
localTypes[moduleName] = {};
return localTypes;
}, {});
const ignoredTypes = Object.keys(types);
const primitiveTypes: TypeExist = {};
const typesTypes: TypeExist = {};
const imports = { codecTypes, localTypes, ignoredTypes, primitiveTypes, typesTypes };
return imports;
}
+7
View File
@@ -0,0 +1,7 @@
// 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 * from './derived';
export * from './formatting';
export * from './imports';
+5
View File
@@ -154,6 +154,11 @@ export interface SignatureOptions {
export type ArgsDef = Record<string, Constructor>;
// A type alias for [Type1, Type2] & Codec, representing a tuple (Type1, Type2)
// FIXME Implement this generic <Sub> on Tuple.ts itself.
// eslint-disable-next-line @typescript-eslint/interface-name-prefix
export type ITuple<Sub extends Codec[]> = Sub & Codec
// eslint-disable-next-line @typescript-eslint/interface-name-prefix
export interface IMethod extends Codec {
readonly args: Codec[];