Add rpc.raw interface, convert RPC to Augmented wrappers (#1990)

* Add rpc.raw interface, convert RPC to Augmented

* Augmentaton attempt...

* Failing test

* Fix augmentation

* Cleanup linting

* Expose .raw on decorated RPCs

* .raw into CHANGELOG

* Stray eslint overrides
This commit is contained in:
Jaco Greeff
2020-03-03 08:49:24 +01:00
committed by GitHub
parent e07636675f
commit 0e297c6779
10 changed files with 110 additions and 59 deletions
+1
View File
@@ -4,6 +4,7 @@
- Fix storage parsing not resulting in rejected Promises (Fix from https://github.com/aniiantt applied)
- Type generation will now handle the same sub-module name across packages, i.e. `@polkadot/types/interfaces/runtime` & `@mine/interfaces/runtime`)
- Add `.range([from, to]: [Hash, Hash?], ...args: any[]): [Hash, Codec][]` on all storage entries
- Add `.raw(...args: any[]): Promise<Uint8Array & Codec>` to all RPC calls, returning the un-encoded result
- Allow pre-module type aliasing with `typesAlias: { <moduleName>: { <meta-type>: <alias-type> } }`on API construction options
- Allow `BTreeMap` to be initialized with a `Record<string, any>` object (in addition to `Map`)
- Allow for `HashMap<KeyType, ValueType>` definitions
+41 -41
View File
@@ -17,175 +17,175 @@ declare module '@polkadot/rpc-core/types.jsonrpc' {
/**
* Retrieves the next accountIndex as available on the node
**/
nextIndex(accountId: AccountId | string | Uint8Array): Observable<Index>;
nextIndex: AugmentedRpc<(accountId: AccountId | string | Uint8Array) => Observable<Index>>;
};
author: {
/**
* Returns true if the keystore has private keys for the given public key and key type.
**/
hasKey(publicKey: Bytes | string | Uint8Array, keyType: Text | string): Observable<bool>;
hasKey: AugmentedRpc<(publicKey: Bytes | string | Uint8Array, keyType: Text | string) => Observable<bool>>;
/**
* Returns true if the keystore has private keys for the given session public keys.
**/
hasSessionKeys(sessionKeys: Bytes | string | Uint8Array): Observable<bool>;
hasSessionKeys: AugmentedRpc<(sessionKeys: Bytes | string | Uint8Array) => Observable<bool>>;
/**
* Insert a key into the keystore.
**/
insertKey(keyType: Text | string, suri: Text | string, publicKey: Bytes | string | Uint8Array): Observable<Bytes>;
insertKey: AugmentedRpc<(keyType: Text | string, suri: Text | string, publicKey: Bytes | string | Uint8Array) => Observable<Bytes>>;
/**
* Returns all pending extrinsics, potentially grouped by sender
**/
pendingExtrinsics(): Observable<Vec<Extrinsic>>;
pendingExtrinsics: AugmentedRpc<() => Observable<Vec<Extrinsic>>>;
/**
* Remove given extrinsic from the pool and temporarily ban it to prevent reimporting
**/
removeExtrinsic(bytesOrHash: Vec<ExtrinsicOrHash> | (ExtrinsicOrHash | { hash: any } | { extrinsic: any } | string | Uint8Array)[]): Observable<Vec<Hash>>;
removeExtrinsic: AugmentedRpc<(bytesOrHash: Vec<ExtrinsicOrHash> | (ExtrinsicOrHash | { hash: any } | { extrinsic: any } | string | Uint8Array)[]) => Observable<Vec<Hash>>>;
/**
* Generate new session keys and returns the corresponding public keys
**/
rotateKeys(): Observable<Bytes>;
rotateKeys: AugmentedRpc<() => Observable<Bytes>>;
/**
* Submit and subscribe to watch an extrinsic until unsubscribed
**/
submitAndWatchExtrinsic(extrinsic: IExtrinsic): Observable<ExtrinsicStatus>;
submitAndWatchExtrinsic: AugmentedRpc<(extrinsic: IExtrinsic) => Observable<ExtrinsicStatus>>;
/**
* Submit a fully formatted extrinsic for block inclusion
**/
submitExtrinsic(extrinsic: IExtrinsic): Observable<Hash>;
submitExtrinsic: AugmentedRpc<(extrinsic: IExtrinsic) => Observable<Hash>>;
};
chain: {
/**
* Get header and body of a relay chain block
**/
getBlock(hash?: BlockHash | string | Uint8Array): Observable<SignedBlock>;
getBlock: AugmentedRpc<(hash?: BlockHash | string | Uint8Array) => Observable<SignedBlock>>;
/**
* Get the block hash for a specific block
**/
getBlockHash(blockNumber?: BlockNumber | AnyNumber | Uint8Array): Observable<BlockHash>;
getBlockHash: AugmentedRpc<(blockNumber?: BlockNumber | AnyNumber | Uint8Array) => Observable<BlockHash>>;
/**
* Get hash of the last finalized block in the canon chain
**/
getFinalizedHead(): Observable<BlockHash>;
getFinalizedHead: AugmentedRpc<() => Observable<BlockHash>>;
/**
* Retrieves the header for a specific block
**/
getHeader(hash?: BlockHash | string | Uint8Array): Observable<Header>;
getHeader: AugmentedRpc<(hash?: BlockHash | string | Uint8Array) => Observable<Header>>;
/**
* Retrieves the newest header via subscription
**/
subscribeAllHeads(): Observable<Header>;
subscribeAllHeads: AugmentedRpc<() => Observable<Header>>;
/**
* Retrieves the best finalized header via subscription
**/
subscribeFinalizedHeads(): Observable<Header>;
subscribeFinalizedHeads: AugmentedRpc<() => Observable<Header>>;
/**
* Retrieves the best header via subscription
**/
subscribeNewHeads(): Observable<Header>;
subscribeNewHeads: AugmentedRpc<() => Observable<Header>>;
};
contracts: {
/**
* Executes a call to a contract
**/
call(callRequest: ContractCallRequest | { origin?: any; dest?: any; value?: any; gasLimit?: any; inputData?: any } | string | Uint8Array, at?: BlockHash | string | Uint8Array): Observable<ContractExecResult>;
call: AugmentedRpc<(callRequest: ContractCallRequest | { origin?: any; dest?: any; value?: any; gasLimit?: any; inputData?: any } | string | Uint8Array, at?: BlockHash | string | Uint8Array) => Observable<ContractExecResult>>;
/**
* Returns the value under a specified storage key in a contract
**/
getStorage(address: AccountId | string | Uint8Array, key: H256 | string | Uint8Array, at?: BlockHash | string | Uint8Array): Observable<Option<Bytes>>;
getStorage: AugmentedRpc<(address: AccountId | string | Uint8Array, key: H256 | string | Uint8Array, at?: BlockHash | string | Uint8Array) => Observable<Option<Bytes>>>;
};
payment: {
/**
* Retrieves the fee information for an encoded extrinsic
**/
queryInfo(extrinsic: Bytes | string | Uint8Array, at?: BlockHash | string | Uint8Array): Observable<RuntimeDispatchInfo>;
queryInfo: AugmentedRpc<(extrinsic: Bytes | string | Uint8Array, at?: BlockHash | string | Uint8Array) => Observable<RuntimeDispatchInfo>>;
};
rpc: {
/**
* Retrieves the list of RPC methods that are exposed by the node
**/
methods(): Observable<RpcMethods>;
methods: AugmentedRpc<() => Observable<RpcMethods>>;
};
state: {
/**
* Perform a call to a builtin on the chain
**/
call(method: Text | string, data: Bytes | string | Uint8Array, at?: BlockHash | string | Uint8Array): Observable<Bytes>;
call: AugmentedRpc<(method: Text | string, data: Bytes | string | Uint8Array, at?: BlockHash | string | Uint8Array) => Observable<Bytes>>;
/**
* Retrieves the keys with prefix of a specific child storage
**/
getChildKeys(childStorageKey: StorageKey | string | Uint8Array | any, childDefinition: StorageKey | string | Uint8Array | any, childType: u32 | AnyNumber | Uint8Array, key: StorageKey | string | Uint8Array | any, at?: BlockHash | string | Uint8Array): Observable<Vec<StorageKey>>;
getChildKeys: AugmentedRpc<(childStorageKey: StorageKey | string | Uint8Array | any, childDefinition: StorageKey | string | Uint8Array | any, childType: u32 | AnyNumber | Uint8Array, key: StorageKey | string | Uint8Array | any, at?: BlockHash | string | Uint8Array) => Observable<Vec<StorageKey>>>;
/**
* Retrieves the child storage for a key
**/
getChildStorage(childStorageKey: StorageKey | string | Uint8Array | any, childDefinition: StorageKey | string | Uint8Array | any, childType: u32 | AnyNumber | Uint8Array, key: StorageKey | string | Uint8Array | any, at?: BlockHash | string | Uint8Array): Observable<StorageData>;
getChildStorage: AugmentedRpc<(childStorageKey: StorageKey | string | Uint8Array | any, childDefinition: StorageKey | string | Uint8Array | any, childType: u32 | AnyNumber | Uint8Array, key: StorageKey | string | Uint8Array | any, at?: BlockHash | string | Uint8Array) => Observable<StorageData>>;
/**
* Retrieves the child storage hash
**/
getChildStorageHash(childStorageKey: StorageKey | string | Uint8Array | any, childDefinition: StorageKey | string | Uint8Array | any, childType: u32 | AnyNumber | Uint8Array, key: StorageKey | string | Uint8Array | any, at?: BlockHash | string | Uint8Array): Observable<Hash>;
getChildStorageHash: AugmentedRpc<(childStorageKey: StorageKey | string | Uint8Array | any, childDefinition: StorageKey | string | Uint8Array | any, childType: u32 | AnyNumber | Uint8Array, key: StorageKey | string | Uint8Array | any, at?: BlockHash | string | Uint8Array) => Observable<Hash>>;
/**
* Retrieves the child storage size
**/
getChildStorageSize(childStorageKey: StorageKey | string | Uint8Array | any, childDefinition: StorageKey | string | Uint8Array | any, childType: u32 | AnyNumber | Uint8Array, key: StorageKey | string | Uint8Array | any, at?: BlockHash | string | Uint8Array): Observable<u64>;
getChildStorageSize: AugmentedRpc<(childStorageKey: StorageKey | string | Uint8Array | any, childDefinition: StorageKey | string | Uint8Array | any, childType: u32 | AnyNumber | Uint8Array, key: StorageKey | string | Uint8Array | any, at?: BlockHash | string | Uint8Array) => Observable<u64>>;
/**
* Retrieves the keys with a certain prefix
**/
getKeys(key: StorageKey | string | Uint8Array | any, at?: BlockHash | string | Uint8Array): Observable<Vec<StorageKey>>;
getKeys: AugmentedRpc<(key: StorageKey | string | Uint8Array | any, at?: BlockHash | string | Uint8Array) => Observable<Vec<StorageKey>>>;
/**
* Returns the runtime metadata
**/
getMetadata(at?: BlockHash | string | Uint8Array): Observable<Metadata>;
getMetadata: AugmentedRpc<(at?: BlockHash | string | Uint8Array) => Observable<Metadata>>;
/**
* Get the runtime version
**/
getRuntimeVersion(at?: BlockHash | string | Uint8Array): Observable<RuntimeVersion>;
getStorage<T = Codec>(key: any, block?: Hash | Uint8Array | string): Observable<T>;
getRuntimeVersion: AugmentedRpc<(at?: BlockHash | string | Uint8Array) => Observable<RuntimeVersion>>;
getStorage: AugmentedRpc<<T = Codec>(key: any, block?: Hash | Uint8Array | string) => Observable<T>>;
/**
* Retrieves the storage hash
**/
getStorageHash(key: StorageKey | string | Uint8Array | any, at?: BlockHash | string | Uint8Array): Observable<Hash>;
getStorageHash: AugmentedRpc<(key: StorageKey | string | Uint8Array | any, at?: BlockHash | string | Uint8Array) => Observable<Hash>>;
/**
* Retrieves the storage size
**/
getStorageSize(key: StorageKey | string | Uint8Array | any, at?: BlockHash | string | Uint8Array): Observable<u64>;
getStorageSize: AugmentedRpc<(key: StorageKey | string | Uint8Array | any, at?: BlockHash | string | Uint8Array) => Observable<u64>>;
/**
* Query historical storage entries (by key) starting from a start block
**/
queryStorage(keys: Vec<StorageKey> | (StorageKey | string | Uint8Array | any)[], startBlock: Hash | string | Uint8Array, at?: BlockHash | string | Uint8Array): Observable<Vec<StorageChangeSet>>;
queryStorage: AugmentedRpc<(keys: Vec<StorageKey> | (StorageKey | string | Uint8Array | any)[], startBlock: Hash | string | Uint8Array, at?: BlockHash | string | Uint8Array) => Observable<Vec<StorageChangeSet>>>;
/**
* Retrieves the runtime version via subscription
**/
subscribeRuntimeVersion(): Observable<RuntimeVersion>;
subscribeStorage<T = Codec[]>(keys: any[]): Observable<T>;
subscribeRuntimeVersion: AugmentedRpc<() => Observable<RuntimeVersion>>;
subscribeStorage: AugmentedRpc<<T = Codec[]>(keys: any[]) => Observable<T>>;
};
system: {
/**
* Retrieves the chain
**/
chain(): Observable<Text>;
chain: AugmentedRpc<() => Observable<Text>>;
/**
* Return health status of the node
**/
health(): Observable<Health>;
health: AugmentedRpc<() => Observable<Health>>;
/**
* Retrieves the node name
**/
name(): Observable<Text>;
name: AugmentedRpc<() => Observable<Text>>;
/**
* Returns current state of the network
**/
networkState(): Observable<NetworkState>;
networkState: AugmentedRpc<() => Observable<NetworkState>>;
/**
* Returns the currently connected peers
**/
peers(): Observable<Vec<PeerInfo>>;
peers: AugmentedRpc<() => Observable<Vec<PeerInfo>>>;
/**
* Get a custom set of properties as a JSON object, defined in the chain spec
**/
properties(): Observable<ChainProperties>;
properties: AugmentedRpc<() => Observable<ChainProperties>>;
/**
* Retrieves the version of the node
**/
version(): Observable<Text>;
version: AugmentedRpc<() => Observable<Text>>;
};
}
}
+1
View File
@@ -236,6 +236,7 @@ export default abstract class Decorate<ApiType extends ApiTypes> extends Events
// skip subscriptions where we have a non-subscribe interface
if (this.hasSubscriptions || !(methodName.startsWith('subscribe') || methodName.startsWith('unsubscribe'))) {
(section as any)[methodName] = decorateMethod(method, { methodName });
(section as any)[methodName].raw = decorateMethod(method.raw, { methodName });
}
return section;
+12 -2
View File
@@ -79,13 +79,23 @@ async function query (api: ApiPromise, keyring: TestKeyringMap): Promise<void> {
}
async function rpc (api: ApiPromise): Promise<void> {
await api.rpc.chain.subscribeNewHeads((header: Header): void => {
console.log('current header:', header);
// defaults
await api.rpc.chain.subscribeNewHeads((header): void => {
console.log('current header #', header.number.toNumber());
});
// with generic params
await api.rpc.state.subscribeStorage<[Balance]>(['my_balance_key'], ([balance]): void => {
console.log('current balance:', balance.toString());
});
// using raw
await api.rpc.chain.getBlock.raw('0x123456');
// using raw subs
api.rpc.chain.subscribeNewHeads.raw((result: Uint8Array): void => {
console.log(result);
});
}
function types (api: ApiPromise): void {
+3 -2
View File
@@ -7,7 +7,7 @@ import { AnyFunction, Callback, Codec } from '@polkadot/types/types';
// Prepend an element V onto the beginning of a tuple T.
// Cons<1, [2,3,4]> is [1,2,3,4]
type Cons<V, T extends any[]> = ((v: V, ...t: T) => void) extends ((...r: infer R) => void)
export type Cons<V, T extends any[]> = ((v: V, ...t: T) => void) extends ((...r: infer R) => void)
? R
: never;
@@ -15,7 +15,7 @@ type Cons<V, T extends any[]> = ((v: V, ...t: T) => void) extends ((...r: infer
// Push<[1,2,3],4> is [1,2,3,4]
// note that this DOES NOT PRESERVE optionality/readonly in tuples.
// So unfortunately Push<[1, 2?, 3?], 4> is [1,2|undefined,3|undefined,4]
type Push<T extends any[], V> = (
export type Push<T extends any[], V> = (
(
Cons<any, Required<T>> extends infer R
? { [K in keyof R]: K extends keyof T ? T[K] : V }
@@ -49,6 +49,7 @@ export interface RxResult<F extends AnyFunction> {
(...args: Parameters<F>): Observable<ObsInnerType<ReturnType<F>>>;
<T>(...args: Parameters<F>): Observable<T>;
}
export interface PromiseResult<F extends AnyFunction> {
(...args: Parameters<F>): Promise<ObsInnerType<ReturnType<F>>>;
(...args: Push<Parameters<F>, Callback<ObsInnerType<ReturnType<F>>>>): UnsubscribePromise;
+19 -3
View File
@@ -2,13 +2,29 @@
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { AnyFunction } from '@polkadot/types/types';
import { AnyFunction, Callback, Codec } from '@polkadot/types/types';
import { ApiTypes, MethodResult } from './base';
import { Observable } from 'rxjs';
import { ApiTypes, Push, PromiseResult, RxResult, UnsubscribePromise } from './base';
export interface RpcRxResult<F extends AnyFunction> extends RxResult<F> {
raw (...args: Parameters<F>): Observable<Uint8Array & Codec>;
}
export interface RpcPromiseResult<F extends AnyFunction> extends PromiseResult<F> {
raw (...args: Parameters<F>): Promise<Uint8Array & Codec>;
raw (...args: Push<Parameters<F>, Callback<Uint8Array & Codec>>): UnsubscribePromise;
}
// FIXME The day TS has higher-kinded types, we can remove this hardcoded stuff
export type RpcMethodResult<ApiType extends ApiTypes, F extends AnyFunction> = ApiType extends 'rxjs'
? RpcRxResult<F>
: RpcPromiseResult<F>;
export type DecoratedRpcSection<ApiType extends ApiTypes, Section> = {
[Method in keyof Section]: Section[Method] extends AnyFunction
? MethodResult<ApiType, Section[Method]>
? RpcMethodResult<ApiType, Section[Method]>
: never
}
+22 -8
View File
@@ -173,10 +173,17 @@ export default class Rpc implements RpcInterface {
}, {} as RpcInterface[Section]);
}
private createMethodWithRaw (creator: (isRaw: boolean) => (...values: any[]) => Observable<any>): RpcInterfaceMethod {
const call = creator(false) as Partial<RpcInterfaceMethod>;
call.raw = creator(true);
return call as RpcInterfaceMethod;
}
private createMethodSend (method: RpcMethod): RpcInterfaceMethod {
const rpcName = `${method.section}_${method.method}`;
const call = (...values: any[]): Observable<any> => {
const creator = (isRaw: boolean) => (...values: any[]): Observable<any> => {
// TODO Warn on deprecated methods
// Here, logically, it should be `of(this.formatInputs(method, values))`.
@@ -193,7 +200,11 @@ export default class Rpc implements RpcInterface {
from(this.provider.send(rpcName, params.map((param): AnyJson => param.toJSON())))
])
),
map(([params, result]): any => this.formatOutput(method, params, result)),
map(([params, result]): any =>
isRaw
? this.registry.createType('Raw', result)
: this.formatOutput(method, params, result)
),
catchError((error): any => {
const message = createErrorMessage(method, error);
@@ -210,7 +221,7 @@ export default class Rpc implements RpcInterface {
// We voluntarily don't cache the "one-shot" RPC calls. For example,
// `getStorage('123')` returns the current value, but this value can change
// over time, so we wouldn't want to cache the Observable.
return call as RpcInterfaceMethod;
return this.createMethodWithRaw(creator);
}
// create a subscriptor, it subscribes once and resolves with the id as subscribe
@@ -231,8 +242,7 @@ export default class Rpc implements RpcInterface {
const subName = `${method.section}_${subMethod}`;
const unsubName = `${method.section}_${unsubMethod}`;
const subType = `${method.section}_${updateType}`;
const call = (...values: any[]): Observable<any> => {
const creator = (isRaw: boolean) => (...values: any[]): Observable<any> => {
return new Observable((observer: Observer<any>): VoidCallback => {
// Have at least an empty promise, as used in the unsubscribe
let subscriptionPromise: Promise<number | void> = Promise.resolve();
@@ -254,7 +264,11 @@ export default class Rpc implements RpcInterface {
}
try {
observer.next(this.formatOutput(method, params, result));
observer.next(
isRaw
? this.registry.createType('Raw', result)
: this.formatOutput(method, params, result)
);
} catch (error) {
observer.error(error);
}
@@ -291,7 +305,7 @@ export default class Rpc implements RpcInterface {
}).pipe(drr());
};
const memoized = memoizee(call, {
const memoized = memoizee(this.createMethodWithRaw(creator), {
// Dynamic length for argument
length: false,
// Normalize args so that different args that should be cached
+6
View File
@@ -2,5 +2,11 @@
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
// FIXME, this whole file needs to move to API
import { AnyFunction } from '@polkadot/types/types';
// eslint-disable-next-line @typescript-eslint/no-empty-interface
export interface RpcInterface {}
export type AugmentedRpc<F extends AnyFunction> = F;
+1
View File
@@ -8,6 +8,7 @@ export * from './types.jsonrpc';
export interface RpcInterfaceMethod {
(...params: any[]): Observable<any>;
raw (...params: any[]): Observable<any>;
}
export interface UserRpcMethod {
+4 -3
View File
@@ -27,9 +27,10 @@ export default function generateRpcTypes (dest = 'packages/api/src/augment/rpc.t
if (section === 'state') {
if (method.method === 'getStorage') {
setImports(allDefs, imports, ['Codec']);
return ' getStorage<T = Codec>(key: any, block?: Hash | Uint8Array | string): Observable<T>;';
return indent(6)('getStorage: AugmentedRpc<<T = Codec>(key: any, block?: Hash | Uint8Array | string) => Observable<T>>;');
} else if (method.method === 'subscribeStorage') {
return ' subscribeStorage<T = Codec[]>(keys: any[]): Observable<T>;';
return indent(6)('subscribeStorage: AugmentedRpc<<T = Codec[]>(keys: any[]) => Observable<T>>;');
}
}
@@ -41,7 +42,7 @@ export default function generateRpcTypes (dest = 'packages/api/src/augment/rpc.t
return `${param.name}${param.isOptional ? '?' : ''}: ${similarTypes.join(' | ')}`;
});
return createDocComments(6, [method.description]) + indent(6)(`${method.method}(${args.join(', ')}): Observable<${method.type}>;`);
return createDocComments(6, [method.description]) + indent(6)(`${method.method}: AugmentedRpc<(${args.join(', ')}) => Observable<${method.type}>>;`);
});
return allSections.concat(