syncState RPCs (#2797)

* syncState RPCs

* Use endpoint override as available

* Allow Json construction, update syncstate_get def
This commit is contained in:
Jaco Greeff
2020-10-28 13:26:37 +01:00
committed by GitHub
parent db3fe7d103
commit 9debb854f9
16 changed files with 87 additions and 14 deletions
+12 -2
View File
@@ -2,7 +2,7 @@
/* eslint-disable */
import { AnyNumber, Codec, IExtrinsic, Observable } from '@polkadot/types/types';
import { HashMap, Option, Vec } from '@polkadot/types/codec';
import { HashMap, Json, Option, Vec } from '@polkadot/types/codec';
import { Bytes, Null, StorageKey, Text, bool, u32, u64 } from '@polkadot/types/primitive';
import { Metadata } from '@polkadot/types';
import { ExtrinsicOrHash, ExtrinsicStatus } from '@polkadot/types/interfaces/author';
@@ -19,7 +19,7 @@ import { RuntimeDispatchInfo } from '@polkadot/types/interfaces/payment';
import { RpcMethods } from '@polkadot/types/interfaces/rpc';
import { AccountId, BlockNumber, H256, Hash, Header, Index, Justification, KeyValue, SignedBlock, StorageData } from '@polkadot/types/interfaces/runtime';
import { ReadProof, RuntimeVersion } from '@polkadot/types/interfaces/state';
import { ApplyExtrinsicResult, ChainProperties, ChainType, Health, NetworkState, NodeRole, PeerInfo } from '@polkadot/types/interfaces/system';
import { ApplyExtrinsicResult, ChainProperties, ChainType, Health, NetworkState, NodeRole, PeerInfo, SyncState } from '@polkadot/types/interfaces/system';
declare module '@polkadot/rpc-core/types.jsonrpc' {
export interface RpcInterface {
@@ -245,6 +245,12 @@ declare module '@polkadot/rpc-core/types.jsonrpc' {
**/
subscribeStorage: AugmentedRpc<<T = Codec[]>(keys?: Vec<StorageKey> | (StorageKey | string | Uint8Array | any)[]) => Observable<T>>;
};
syncstate: {
/**
* Returns the json-serialized chainspec running the node, with a sync state.
**/
genSyncSpec: AugmentedRpc<(raw: bool | boolean | Uint8Array) => Observable<Json>>;
};
system: {
/**
* Retrieves the next accountIndex as available on the node
@@ -302,6 +308,10 @@ declare module '@polkadot/rpc-core/types.jsonrpc' {
* Remove a reserved peer
**/
removeReservedPeer: AugmentedRpc<(peerId: Text | string) => Observable<Text>>;
/**
* Returns the state of the syncing of the node
**/
syncState: AugmentedRpc<() => Observable<SyncState>>;
/**
* Retrieves the version of the node
**/
+5 -1
View File
@@ -225,7 +225,7 @@ export default abstract class Decorate<ApiType extends ApiTypes> extends Events
protected _filterRpcMethods (exposed: string[]): void {
const hasResults = exposed.length !== 0;
const allKnown = [...this._rpcCore.mapping.entries()];
const allKeys = allKnown.reduce((allKeys: string[], [, { alias, method, pubsub, section }]): string[] => {
const allKeys = allKnown.reduce((allKeys: string[], [, { alias, endpoint, method, pubsub, section }]): string[] => {
allKeys.push(`${section}_${method}`);
if (pubsub) {
@@ -237,6 +237,10 @@ export default abstract class Decorate<ApiType extends ApiTypes> extends Events
allKeys.push(...alias);
}
if (endpoint) {
allKeys.push(endpoint);
}
return allKeys;
}, []);
const unknown = exposed.filter((key) => !allKeys.includes(key));
+8 -5
View File
@@ -106,6 +106,8 @@ export default class Rpc implements RpcInterface {
public readonly state!: RpcInterface['state'];
public readonly syncstate!: RpcInterface['syncstate'];
public readonly system!: RpcInterface['system'];
/**
@@ -186,13 +188,14 @@ export default class Rpc implements RpcInterface {
private _createInterface<Section extends keyof RpcInterface> (section: string, methods: Record<string, DefinitionRpc | DefinitionRpcSub>): RpcInterface[Section] {
return Object
.keys(methods)
.filter((method) => !this.mapping.has(`${section}_${method}`))
.reduce((exposed, method): RpcInterface[Section] => {
.entries(methods)
.filter(([method, { endpoint }]) => !this.mapping.has(endpoint || `${section}_${method}`))
.reduce((exposed, [method, { endpoint }]): RpcInterface[Section] => {
const def = methods[method];
const isSubscription = !!(def as DefinitionRpcSub).pubsub;
const jsonrpc = endpoint || `${section}_${method}`;
this.mapping.set(`${section}_${method}`, { ...def, isSubscription, jsonrpc: `${section}_${method}`, method, section });
this.mapping.set(jsonrpc, { ...def, isSubscription, jsonrpc, method, section });
// FIXME Remove any here
// To do so, remove `RpcInterfaceMethod` from './types.ts', and refactor
@@ -217,7 +220,7 @@ export default class Rpc implements RpcInterface {
}
private _createMethodSend (section: string, method: string, def: DefinitionRpc): RpcInterfaceMethod {
const rpcName = `${section}_${method}`;
const rpcName = def.endpoint || `${section}_${method}`;
const hashIndex = def.params.findIndex(({ isHistoric }) => isHistoric);
const cacheIndex = def.params.findIndex(({ isCached }) => isCached);
let memoized: null | RpcInterfaceMethod & memoizee.Memoized<RpcInterfaceMethod> = null;
+3 -3
View File
@@ -2,7 +2,7 @@
// SPDX-License-Identifier: Apache-2.0
import { MetadataLatest } from '@polkadot/types/interfaces/metadata';
import { Codec } from '@polkadot/types/types';
import { Codec, DefinitionRpcParam } from '@polkadot/types/types';
import fs from 'fs';
import Metadata from '@polkadot/metadata/Metadata';
@@ -120,7 +120,7 @@ function addRpc (): string {
.sort()
.map((methodName) => {
const method = section.rpc[methodName];
const args = method.params.map(({ isOptional, name, type }: any): string => {
const args = method.params.map(({ isOptional, name, type }: DefinitionRpcParam): string => {
// eslint-disable-next-line @typescript-eslint/restrict-plus-operands
return name + (isOptional ? '?' : '') + ': `' + type + '`';
}).join(', ');
@@ -128,7 +128,7 @@ function addRpc (): string {
return {
interface: '`' + `api.rpc.${sectionName}.${methodName}` + '`',
jsonrpc: '`' + `${sectionName}_${methodName}` + '`',
jsonrpc: '`' + (method.endpoint || `${sectionName}_${methodName}`) + '`',
name: `${methodName}(${args}): ${type}`,
...(method.description && { summary: method.description })
};
+4 -1
View File
@@ -44,7 +44,7 @@ import { Bid, BidKind, SocietyJudgement, SocietyVote, StrikeCount, VouchingStatu
import { ActiveEraInfo, CompactAssignments, CompactAssignmentsTo257, CompactScore, CompactScoreCompact, ElectionCompute, ElectionResult, ElectionScore, ElectionSize, ElectionStatus, EraIndex, EraPoints, EraRewardPoints, EraRewards, Exposure, Forcing, IndividualExposure, KeyType, MomentOf, Nominations, NominatorIndex, NominatorIndexCompact, OffchainAccuracy, OffchainAccuracyCompact, PhragmenScore, Points, RewardDestination, RewardDestinationTo257, RewardPoint, SlashJournalEntry, SlashingSpans, SlashingSpansTo204, SpanIndex, SpanRecord, StakingLedger, StakingLedgerTo223, StakingLedgerTo240, UnappliedSlash, UnappliedSlashOther, UnlockChunk, ValidatorIndex, ValidatorIndexCompact, ValidatorPrefs, ValidatorPrefsTo145, ValidatorPrefsTo196 } from '@polkadot/types/interfaces/staking';
import { ApiId, KeyValueOption, ReadProof, RuntimeVersion, RuntimeVersionApi, StorageChangeSet } from '@polkadot/types/interfaces/state';
import { WeightToFeeCoefficient } from '@polkadot/types/interfaces/support';
import { AccountInfo, ApplyExtrinsicResult, ChainProperties, ChainType, DigestOf, DispatchClass, DispatchError, DispatchErrorModule, DispatchErrorTo198, DispatchInfo, DispatchInfoTo190, DispatchInfoTo244, DispatchOutcome, DispatchResult, DispatchResultOf, DispatchResultTo198, Event, EventId, EventIndex, EventRecord, Health, InvalidTransaction, Key, LastRuntimeUpgradeInfo, NetworkState, NetworkStatePeerset, NetworkStatePeersetInfo, NodeRole, NotConnectedPeer, Peer, PeerEndpoint, PeerEndpointAddr, PeerInfo, PeerPing, Phase, RawOrigin, RefCount, RefCountTo259, SystemOrigin, TransactionValidityError, UnknownTransaction } from '@polkadot/types/interfaces/system';
import { AccountInfo, ApplyExtrinsicResult, ChainProperties, ChainType, DigestOf, DispatchClass, DispatchError, DispatchErrorModule, DispatchErrorTo198, DispatchInfo, DispatchInfoTo190, DispatchInfoTo244, DispatchOutcome, DispatchResult, DispatchResultOf, DispatchResultTo198, Event, EventId, EventIndex, EventRecord, Health, InvalidTransaction, Key, LastRuntimeUpgradeInfo, NetworkState, NetworkStatePeerset, NetworkStatePeersetInfo, NodeRole, NotConnectedPeer, Peer, PeerEndpoint, PeerEndpointAddr, PeerInfo, PeerPing, Phase, RawOrigin, RefCount, RefCountTo259, SyncState, SystemOrigin, TransactionValidityError, UnknownTransaction } from '@polkadot/types/interfaces/system';
import { Bounty, BountyIndex, BountyStatus, BountyStatusActive, BountyStatusCuratorProposed, BountyStatusPendingPayout, OpenTip, OpenTipFinderTo225, OpenTipTip, OpenTipTo225, TreasuryProposal } from '@polkadot/types/interfaces/treasury';
import { Multiplier } from '@polkadot/types/interfaces/txpayment';
import { Multisig, Timepoint } from '@polkadot/types/interfaces/utility';
@@ -1192,6 +1192,9 @@ declare module '@polkadot/types/types/registry' {
'Compact<RefCountTo259>': Compact<RefCountTo259>;
'Option<RefCountTo259>': Option<RefCountTo259>;
'Vec<RefCountTo259>': Vec<RefCountTo259>;
SyncState: SyncState;
'Option<SyncState>': Option<SyncState>;
'Vec<SyncState>': Vec<SyncState>;
SystemOrigin: SystemOrigin;
'Option<SystemOrigin>': Option<SystemOrigin>;
'Vec<SystemOrigin>': Vec<SystemOrigin>;
+1 -1
View File
@@ -13,12 +13,12 @@ export { default as Compact } from './Compact';
// export { default as Date } from './Date';
export { default as Enum } from './Enum';
export { default as HashMap } from './HashMap';
export { default as Json } from './Json';
export { default as Linkage } from './Linkage';
export { default as Option } from './Option';
export { default as Result } from './Result';
export { default as Set } from './Set';
export { default as Struct } from './Struct';
// export { default as StructAny } from './StructAny';
export { default as Tuple } from './Tuple';
export { default as Vec } from './Vec';
+2 -1
View File
@@ -10,6 +10,7 @@ import extrinsicsFromMeta from '@polkadot/metadata/Decorated/extrinsics/fromMeta
import { BN_ZERO, assert, formatBalance, isFunction, isString, isU8a, isUndefined, logger, stringCamelCase, u8aToHex } from '@polkadot/util';
import { blake2AsU8a } from '@polkadot/util-crypto';
import Json from '../codec/Json';
import Raw from '../codec/Raw';
import { defaultExtensions, expandExtensionTypes, findUnknownExtensions } from '../extrinsic/signedExtensions';
import { EventData } from '../generic/Event';
@@ -127,7 +128,7 @@ export class TypeRegistry implements Registry {
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
const definitions: Record<string, { types: RegistryTypes }> = require('../interfaces/definitions');
this.#knownDefaults = { Raw, ...baseTypes };
this.#knownDefaults = { Json, Raw, ...baseTypes };
this.#knownDefinitions = definitions;
this.init();
@@ -29,6 +29,7 @@ export { default as session } from './session/definitions';
export { default as society } from './society/definitions';
export { default as staking } from './staking/definitions';
export { default as support } from './support/definitions';
export { default as syncstate } from './syncstate/definitions';
export { default as system } from './system/definitions';
export { default as treasury } from './treasury/definitions';
export { default as txpayment } from './txpayment/definitions';
@@ -0,0 +1,24 @@
// Copyright 2017-2020 @polkadot/types authors & contributors
// SPDX-License-Identifier: Apache-2.0
// order important in structs... :)
/* eslint-disable sort-keys */
import { Definitions } from '../../types';
export default {
rpc: {
genSyncSpec: {
endpoint: 'sync_state_genSyncSpec',
description: 'Returns the json-serialized chainspec running the node, with a sync state.',
params: [
{
name: 'raw',
type: 'bool'
}
],
type: 'Json'
}
},
types: {}
} as Definitions;
@@ -0,0 +1,4 @@
// Auto-generated via `yarn polkadot-types-from-defs`, do not edit
/* eslint-disable */
export * from './types';
@@ -0,0 +1,4 @@
// Auto-generated via `yarn polkadot-types-from-defs`, do not edit
/* eslint-disable */
export type PHANTOM_SYNCSTATE = 'syncstate';
@@ -110,6 +110,11 @@ export default {
description: 'Returns the roles the node is running as',
params: [],
type: 'Vec<NodeRole>'
},
syncState: {
description: 'Returns the state of the syncing of the node',
params: [],
type: 'SyncState'
}
},
types: {
@@ -279,6 +284,11 @@ export default {
},
RefCount: 'u32',
RefCountTo259: 'u8',
SyncState: {
startingBlock: 'BlockNumber',
currentBlock: 'BlockNumber',
highestBlock: 'Option<BlockNumber>'
},
SystemOrigin: 'RawOrigin',
TransactionValidityError: {
_enum: {
@@ -262,6 +262,13 @@ export interface RefCount extends u32 {}
/** @name RefCountTo259 */
export interface RefCountTo259 extends u8 {}
/** @name SyncState */
export interface SyncState extends Struct {
readonly startingBlock: BlockNumber;
readonly currentBlock: BlockNumber;
readonly highestBlock: Option<BlockNumber>;
}
/** @name SystemOrigin */
export interface SystemOrigin extends RawOrigin {}
+1
View File
@@ -26,6 +26,7 @@ export * from './session/types';
export * from './society/types';
export * from './staking/types';
export * from './support/types';
export * from './syncstate/types';
export * from './system/types';
export * from './treasury/types';
export * from './txpayment/types';
+1
View File
@@ -22,6 +22,7 @@ export interface DefinitionRpcParam {
export interface DefinitionRpc {
alias?: string[];
description: string;
endpoint?: string;
params: DefinitionRpcParam[];
type: DefinitionTypeType;
}