From 0e297c6779be1167931d3485417180ed50e40827 Mon Sep 17 00:00:00 2001 From: Jaco Greeff Date: Tue, 3 Mar 2020 08:49:24 +0100 Subject: [PATCH] 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 --- CHANGELOG.md | 1 + packages/api/src/augment/rpc.ts | 82 +++++++++++++------------- packages/api/src/base/Decorate.ts | 1 + packages/api/src/checkTypes.manual.ts | 14 ++++- packages/api/src/types/base.ts | 5 +- packages/api/src/types/rpc.ts | 22 ++++++- packages/rpc-core/src/index.ts | 30 +++++++--- packages/rpc-core/src/types.jsonrpc.ts | 6 ++ packages/rpc-core/src/types.ts | 1 + packages/typegen/src/generate/rpc.ts | 7 ++- 10 files changed, 110 insertions(+), 59 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 88b1a2c51a..f922f1076c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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` to all RPC calls, returning the un-encoded result - Allow pre-module type aliasing with `typesAlias: { : { : } }`on API construction options - Allow `BTreeMap` to be initialized with a `Record` object (in addition to `Map`) - Allow for `HashMap` definitions diff --git a/packages/api/src/augment/rpc.ts b/packages/api/src/augment/rpc.ts index caf9effdf8..3b424e3507 100644 --- a/packages/api/src/augment/rpc.ts +++ b/packages/api/src/augment/rpc.ts @@ -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; + nextIndex: AugmentedRpc<(accountId: AccountId | string | Uint8Array) => Observable>; }; 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; + hasKey: AugmentedRpc<(publicKey: Bytes | string | Uint8Array, keyType: Text | string) => Observable>; /** * Returns true if the keystore has private keys for the given session public keys. **/ - hasSessionKeys(sessionKeys: Bytes | string | Uint8Array): Observable; + hasSessionKeys: AugmentedRpc<(sessionKeys: Bytes | string | Uint8Array) => Observable>; /** * Insert a key into the keystore. **/ - insertKey(keyType: Text | string, suri: Text | string, publicKey: Bytes | string | Uint8Array): Observable; + insertKey: AugmentedRpc<(keyType: Text | string, suri: Text | string, publicKey: Bytes | string | Uint8Array) => Observable>; /** * Returns all pending extrinsics, potentially grouped by sender **/ - pendingExtrinsics(): Observable>; + pendingExtrinsics: AugmentedRpc<() => Observable>>; /** * Remove given extrinsic from the pool and temporarily ban it to prevent reimporting **/ - removeExtrinsic(bytesOrHash: Vec | (ExtrinsicOrHash | { hash: any } | { extrinsic: any } | string | Uint8Array)[]): Observable>; + removeExtrinsic: AugmentedRpc<(bytesOrHash: Vec | (ExtrinsicOrHash | { hash: any } | { extrinsic: any } | string | Uint8Array)[]) => Observable>>; /** * Generate new session keys and returns the corresponding public keys **/ - rotateKeys(): Observable; + rotateKeys: AugmentedRpc<() => Observable>; /** * Submit and subscribe to watch an extrinsic until unsubscribed **/ - submitAndWatchExtrinsic(extrinsic: IExtrinsic): Observable; + submitAndWatchExtrinsic: AugmentedRpc<(extrinsic: IExtrinsic) => Observable>; /** * Submit a fully formatted extrinsic for block inclusion **/ - submitExtrinsic(extrinsic: IExtrinsic): Observable; + submitExtrinsic: AugmentedRpc<(extrinsic: IExtrinsic) => Observable>; }; chain: { /** * Get header and body of a relay chain block **/ - getBlock(hash?: BlockHash | string | Uint8Array): Observable; + getBlock: AugmentedRpc<(hash?: BlockHash | string | Uint8Array) => Observable>; /** * Get the block hash for a specific block **/ - getBlockHash(blockNumber?: BlockNumber | AnyNumber | Uint8Array): Observable; + getBlockHash: AugmentedRpc<(blockNumber?: BlockNumber | AnyNumber | Uint8Array) => Observable>; /** * Get hash of the last finalized block in the canon chain **/ - getFinalizedHead(): Observable; + getFinalizedHead: AugmentedRpc<() => Observable>; /** * Retrieves the header for a specific block **/ - getHeader(hash?: BlockHash | string | Uint8Array): Observable
; + getHeader: AugmentedRpc<(hash?: BlockHash | string | Uint8Array) => Observable
>; /** * Retrieves the newest header via subscription **/ - subscribeAllHeads(): Observable
; + subscribeAllHeads: AugmentedRpc<() => Observable
>; /** * Retrieves the best finalized header via subscription **/ - subscribeFinalizedHeads(): Observable
; + subscribeFinalizedHeads: AugmentedRpc<() => Observable
>; /** * Retrieves the best header via subscription **/ - subscribeNewHeads(): Observable
; + subscribeNewHeads: AugmentedRpc<() => Observable
>; }; 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; + call: AugmentedRpc<(callRequest: ContractCallRequest | { origin?: any; dest?: any; value?: any; gasLimit?: any; inputData?: any } | string | Uint8Array, at?: BlockHash | string | Uint8Array) => Observable>; /** * 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>; + getStorage: AugmentedRpc<(address: AccountId | string | Uint8Array, key: H256 | string | Uint8Array, at?: BlockHash | string | Uint8Array) => Observable>>; }; payment: { /** * Retrieves the fee information for an encoded extrinsic **/ - queryInfo(extrinsic: Bytes | string | Uint8Array, at?: BlockHash | string | Uint8Array): Observable; + queryInfo: AugmentedRpc<(extrinsic: Bytes | string | Uint8Array, at?: BlockHash | string | Uint8Array) => Observable>; }; rpc: { /** * Retrieves the list of RPC methods that are exposed by the node **/ - methods(): Observable; + methods: AugmentedRpc<() => Observable>; }; state: { /** * Perform a call to a builtin on the chain **/ - call(method: Text | string, data: Bytes | string | Uint8Array, at?: BlockHash | string | Uint8Array): Observable; + call: AugmentedRpc<(method: Text | string, data: Bytes | string | Uint8Array, at?: BlockHash | string | Uint8Array) => Observable>; /** * 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>; + 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>>; /** * 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; + 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>; /** * 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; + 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>; /** * 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; + 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>; /** * Retrieves the keys with a certain prefix **/ - getKeys(key: StorageKey | string | Uint8Array | any, at?: BlockHash | string | Uint8Array): Observable>; + getKeys: AugmentedRpc<(key: StorageKey | string | Uint8Array | any, at?: BlockHash | string | Uint8Array) => Observable>>; /** * Returns the runtime metadata **/ - getMetadata(at?: BlockHash | string | Uint8Array): Observable; + getMetadata: AugmentedRpc<(at?: BlockHash | string | Uint8Array) => Observable>; /** * Get the runtime version **/ - getRuntimeVersion(at?: BlockHash | string | Uint8Array): Observable; - getStorage(key: any, block?: Hash | Uint8Array | string): Observable; + getRuntimeVersion: AugmentedRpc<(at?: BlockHash | string | Uint8Array) => Observable>; + getStorage: AugmentedRpc<(key: any, block?: Hash | Uint8Array | string) => Observable>; /** * Retrieves the storage hash **/ - getStorageHash(key: StorageKey | string | Uint8Array | any, at?: BlockHash | string | Uint8Array): Observable; + getStorageHash: AugmentedRpc<(key: StorageKey | string | Uint8Array | any, at?: BlockHash | string | Uint8Array) => Observable>; /** * Retrieves the storage size **/ - getStorageSize(key: StorageKey | string | Uint8Array | any, at?: BlockHash | string | Uint8Array): Observable; + getStorageSize: AugmentedRpc<(key: StorageKey | string | Uint8Array | any, at?: BlockHash | string | Uint8Array) => Observable>; /** * Query historical storage entries (by key) starting from a start block **/ - queryStorage(keys: Vec | (StorageKey | string | Uint8Array | any)[], startBlock: Hash | string | Uint8Array, at?: BlockHash | string | Uint8Array): Observable>; + queryStorage: AugmentedRpc<(keys: Vec | (StorageKey | string | Uint8Array | any)[], startBlock: Hash | string | Uint8Array, at?: BlockHash | string | Uint8Array) => Observable>>; /** * Retrieves the runtime version via subscription **/ - subscribeRuntimeVersion(): Observable; - subscribeStorage(keys: any[]): Observable; + subscribeRuntimeVersion: AugmentedRpc<() => Observable>; + subscribeStorage: AugmentedRpc<(keys: any[]) => Observable>; }; system: { /** * Retrieves the chain **/ - chain(): Observable; + chain: AugmentedRpc<() => Observable>; /** * Return health status of the node **/ - health(): Observable; + health: AugmentedRpc<() => Observable>; /** * Retrieves the node name **/ - name(): Observable; + name: AugmentedRpc<() => Observable>; /** * Returns current state of the network **/ - networkState(): Observable; + networkState: AugmentedRpc<() => Observable>; /** * Returns the currently connected peers **/ - peers(): Observable>; + peers: AugmentedRpc<() => Observable>>; /** * Get a custom set of properties as a JSON object, defined in the chain spec **/ - properties(): Observable; + properties: AugmentedRpc<() => Observable>; /** * Retrieves the version of the node **/ - version(): Observable; + version: AugmentedRpc<() => Observable>; }; } } diff --git a/packages/api/src/base/Decorate.ts b/packages/api/src/base/Decorate.ts index 0f2255d83a..cb0d030005 100644 --- a/packages/api/src/base/Decorate.ts +++ b/packages/api/src/base/Decorate.ts @@ -236,6 +236,7 @@ export default abstract class Decorate 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; diff --git a/packages/api/src/checkTypes.manual.ts b/packages/api/src/checkTypes.manual.ts index b96f398426..be9bbe2605 100644 --- a/packages/api/src/checkTypes.manual.ts +++ b/packages/api/src/checkTypes.manual.ts @@ -79,13 +79,23 @@ async function query (api: ApiPromise, keyring: TestKeyringMap): Promise { } async function rpc (api: ApiPromise): Promise { - 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 { diff --git a/packages/api/src/types/base.ts b/packages/api/src/types/base.ts index b8e2e85d35..9db94fb551 100644 --- a/packages/api/src/types/base.ts +++ b/packages/api/src/types/base.ts @@ -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: V, ...t: T) => void) extends ((...r: infer R) => void) +export type Cons = ((v: V, ...t: T) => void) extends ((...r: infer R) => void) ? R : never; @@ -15,7 +15,7 @@ type Cons = ((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 = ( +export type Push = ( ( Cons> extends infer R ? { [K in keyof R]: K extends keyof T ? T[K] : V } @@ -49,6 +49,7 @@ export interface RxResult { (...args: Parameters): Observable>>; (...args: Parameters): Observable; } + export interface PromiseResult { (...args: Parameters): Promise>>; (...args: Push, Callback>>>): UnsubscribePromise; diff --git a/packages/api/src/types/rpc.ts b/packages/api/src/types/rpc.ts index 6e68c77548..de6477b873 100644 --- a/packages/api/src/types/rpc.ts +++ b/packages/api/src/types/rpc.ts @@ -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 extends RxResult { + raw (...args: Parameters): Observable; +} + +export interface RpcPromiseResult extends PromiseResult { + raw (...args: Parameters): Promise; + raw (...args: Push, Callback>): UnsubscribePromise; +} + +// FIXME The day TS has higher-kinded types, we can remove this hardcoded stuff +export type RpcMethodResult = ApiType extends 'rxjs' + ? RpcRxResult + : RpcPromiseResult; export type DecoratedRpcSection = { [Method in keyof Section]: Section[Method] extends AnyFunction - ? MethodResult + ? RpcMethodResult : never } diff --git a/packages/rpc-core/src/index.ts b/packages/rpc-core/src/index.ts index 0be738d754..39b7f9fbb0 100644 --- a/packages/rpc-core/src/index.ts +++ b/packages/rpc-core/src/index.ts @@ -173,10 +173,17 @@ export default class Rpc implements RpcInterface { }, {} as RpcInterface[Section]); } + private createMethodWithRaw (creator: (isRaw: boolean) => (...values: any[]) => Observable): RpcInterfaceMethod { + const call = creator(false) as Partial; + + call.raw = creator(true); + + return call as RpcInterfaceMethod; + } + private createMethodSend (method: RpcMethod): RpcInterfaceMethod { const rpcName = `${method.section}_${method.method}`; - - const call = (...values: any[]): Observable => { + const creator = (isRaw: boolean) => (...values: any[]): Observable => { // 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 => { + const creator = (isRaw: boolean) => (...values: any[]): Observable => { return new Observable((observer: Observer): VoidCallback => { // Have at least an empty promise, as used in the unsubscribe let subscriptionPromise: Promise = 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 diff --git a/packages/rpc-core/src/types.jsonrpc.ts b/packages/rpc-core/src/types.jsonrpc.ts index 3f668ae08d..77ca99cf52 100644 --- a/packages/rpc-core/src/types.jsonrpc.ts +++ b/packages/rpc-core/src/types.jsonrpc.ts @@ -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; diff --git a/packages/rpc-core/src/types.ts b/packages/rpc-core/src/types.ts index 9a4b67064c..7f9e598262 100644 --- a/packages/rpc-core/src/types.ts +++ b/packages/rpc-core/src/types.ts @@ -8,6 +8,7 @@ export * from './types.jsonrpc'; export interface RpcInterfaceMethod { (...params: any[]): Observable; + raw (...params: any[]): Observable; } export interface UserRpcMethod { diff --git a/packages/typegen/src/generate/rpc.ts b/packages/typegen/src/generate/rpc.ts index 936f19e8b3..f93f77f9a7 100644 --- a/packages/typegen/src/generate/rpc.ts +++ b/packages/typegen/src/generate/rpc.ts @@ -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(key: any, block?: Hash | Uint8Array | string): Observable;'; + + return indent(6)('getStorage: AugmentedRpc<(key: any, block?: Hash | Uint8Array | string) => Observable>;'); } else if (method.method === 'subscribeStorage') { - return ' subscribeStorage(keys: any[]): Observable;'; + return indent(6)('subscribeStorage: AugmentedRpc<(keys: any[]) => Observable>;'); } } @@ -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(