From 2b88a8f43ce88456a9ddf0165142e03f6b6b8011 Mon Sep 17 00:00:00 2001 From: Jaco Greeff Date: Thu, 11 Oct 2018 20:56:42 +0200 Subject: [PATCH] Expand API documentation (#259) * Expand API documentation * Cleanups * Structuring * Checks & cleanups --- docs/SUMMARY.md | 4 --- packages/api/README.md | 18 ++++++++---- packages/api/src/Base.ts | 28 ++++++++++++++++-- packages/api/src/promise/index.ts | 24 ++++++++++----- packages/api/src/rx/index.ts | 25 +++++++++++----- packages/rpc-core/src/index.ts | 4 +-- packages/rpc-provider/README.md | 29 +++++++++++++++---- .../src/defaults.ts | 4 ++- packages/rpc-provider/src/http/index.ts | 9 ++++-- packages/rpc-provider/src/ws/index.ts | 9 ++++-- 10 files changed, 111 insertions(+), 43 deletions(-) rename packages/{rpc-core => rpc-provider}/src/defaults.ts (60%) diff --git a/docs/SUMMARY.md b/docs/SUMMARY.md index c81f0a663d..b433e832f0 100644 --- a/docs/SUMMARY.md +++ b/docs/SUMMARY.md @@ -6,10 +6,6 @@ - [rpc-provider](rpc-provider/README.md) - [HttpProvider](rpc-provider/classes/_http_index_.httpprovider.md) - [WsProvider](rpc-provider/classes/_ws_index_.wsprovider.md) -- [rpc-core](rpc-core/README.md) - - [Rpc](rpc-core/classes/_index_.rpc.md) -- [rpc-rx](rpc-rx/README.md) - - [RpcRx](rpc-rx/classes/_index_.rpcrx.md) ## Examples diff --git a/packages/api/README.md b/packages/api/README.md index 6ab3aef0eb..e6275bd653 100644 --- a/packages/api/README.md +++ b/packages/api/README.md @@ -6,23 +6,29 @@ The API wrappers provide a standard interface for use - - A static `.create()` that returns an API istance when connected, decorated and ready-to use - The above is just a wrapper for `new Api() `, exposing the `isReady` getter -- `api.rpc.*` provides access to actual RPC calls, be it for queries, submission or retrieving chain information -- `api.st.*` provides access to chain state queries. These are dynamically populated based on what the runtime provides -- `api.tx.*` provides the ability to create transaction, like chain state, this list is populated from a runtime query +- `api.rpc.
.` provides access to actual RPC calls, be it for queries, submission or retrieving chain information +- `api.st.
.` provides access to chain state queries. These are dynamically populated based on what the runtime provides +- `api.tx.
.` provides the ability to create transaction, like chain state, this list is populated from a runtime query ## API Selection There are two flavours of the API provided, one allowing a standard interface via JavaScript Promises and the second provides an Observable wrapper using [RxJS](https://github.com/ReactiveX/rxjs). Depending on your use-case and familiarity, you can choose either (or even both) for your application. -- [ApiPromise](promise/) All interface calls returns Promises, including the static `.create(...)`. Additionally any subscription method use standard JavaScript `(error, value) => {}` callbacks. -- [ApiRx](rx/) All interface calls return RxJS Observables, including the static `.create(...)`. In the same fashion and subscription-based methods return long-running Observables that update with the latest values. +- [[ApiPromise]] All interface calls returns Promises, including the static `.create(...)`. Additionally any subscription method use standard JavaScript `(error, value) => {}` callbacks. +- [[ApiRx]] All interface calls return RxJS Observables, including the static `.create(...)`. In the same fashion and subscription-based methods return long-running Observables that update with the latest values. + +## Dynamic by default + +Subtrate (on which Polkadot is built) used on-chain on-chain WASM runtimes, allowing for upgradability. Each runtime defining the actual chain extrinsics (submitted transactions and block intrinsics) as well as available entries in the chain state. Due to this, the API endpoints for queries and transactions are dynamically populated from the running chain. + +Due to this dynamic nature, this API departs from traditional APIs which only has fixed endpoints, driving use by what is available by the runtime. As a start, this generic nature has a learning curve, although the provided documentation, examples and linked documentation tries to make that experience as seamless as possible. ## Installation & import Installation - ``` -npm install --save @polkadot/api/rx +npm install --save @polkadot/api ``` Subscribing to blocks via Promise-based API - diff --git a/packages/api/src/Base.ts b/packages/api/src/Base.ts index da2ddb9b2f..f69ad6cbdb 100644 --- a/packages/api/src/Base.ts +++ b/packages/api/src/Base.ts @@ -40,7 +40,8 @@ export default abstract class ApiBase implements ApiBaseInterface * @@ -90,7 +91,10 @@ export default abstract class ApiBase implements ApiBaseInterface * @@ -108,6 +112,9 @@ export default abstract class ApiBase implements ApiBaseInterface)` (retrieving the associated nonce for an account), takes the `AccountId` as a parameter. + * * @example *
* @@ -127,6 +134,7 @@ export default abstract class ApiBase implements ApiBaseInterface * @@ -146,6 +154,22 @@ export default abstract class ApiBase implements ApiBaseInterface + * + * ```javascript + * * api.on('disconnected', () => { + * console.log('API has been connected to the endpoint'); + * }); + * + * api.on('disconnected', () => { + * console.log('API has been disconnected from the endpoint'); + * }); + * ``` + */ on (type: ApiInterface$Events, handler: (...args: Array) => any): void { this._eventemitter.on(type, handler); } diff --git a/packages/api/src/promise/index.ts b/packages/api/src/promise/index.ts index dbf3c4e4c3..83ec32f5ae 100644 --- a/packages/api/src/promise/index.ts +++ b/packages/api/src/promise/index.ts @@ -16,13 +16,18 @@ import SubmittableExtrinsic from './SubmittableExtrinsic'; import { StorageFunction } from '@polkadot/types/StorageKey'; /** + * # @polkadot/api/promise + * + * ## Overview + * + * @name ApiPromise * @description * ApiPromise is a standard JavaScript wrapper around the RPC and interfaces on the Polkadot network. As a full Promise-based, all interface calls return Promises, including the static `.create(...)`. Subscription calls utilise standard JavaScript-convention `(error, value)` callbacks. * - * The API is well suited to real-time applications where either the single-shot state is needed or use is to be made of athe subscription-based features of Polkadot (and Substrate) clients. + * The API is well suited to real-time applications where either the single-shot state is needed or use is to be made of the subscription-based features of Polkadot (and Substrate) clients. + * @see [[ApiRx]] * - * @example - *
+ * ## Usage * * Making rpc calls - *
@@ -47,14 +52,17 @@ import { StorageFunction } from '@polkadot/types/StorageKey'; * import { ApiPromise } from '@polkadot/api'; * import WsProvider from '@polkadot/rpc-provider/ws'; * - * // initialise via isReady & new with specific non-local endpoint - * const api = await new ApiPromise(new WsProvider('wss://example.com:9944')).isReady; + * // initialise a provider with a specific endpoint + * const provider = new WsProvider('wss://example.com:9944') + * + * // initialise via isReady & new with specific provider + * const api = await new ApiPromise(provider).isReady; * * // retrieve the block target time * const blockPeriod = await api.st.timestamp.blockPeriod().toNumber(); * let last = 0; * - * // subscribe to the current block timestamp, updates automatically + * // subscribe to the current block timestamp, updates automatically (callback provided) * api.st.timestamp.now((error, timestamp) => { * const elapsed = last * ? `, ${timestamp.toNumber() - last}s since last` @@ -94,7 +102,7 @@ export default class ApiPromise extends ApiBase * @@ -113,7 +121,7 @@ export default class ApiPromise extends ApiBase * diff --git a/packages/api/src/rx/index.ts b/packages/api/src/rx/index.ts index 0962153dc6..19c339af40 100644 --- a/packages/api/src/rx/index.ts +++ b/packages/api/src/rx/index.ts @@ -21,13 +21,18 @@ import { StorageFunction } from '@polkadot/types/StorageKey'; const l = logger('api-rx'); /** + * # @polkadot/api/rx + * + * ## Overview + * + * @name ApiRx * @description * ApiRx is a powerfull RxJS Observable wrapper around the RPC and interfaces on the Polkadot network. As a full Observable API, all interface calls return RxJS Observables, including the static `.create(...)`. In the same fashion and subscription-based methods return long-running Observables that update with the latest values. * * The API is well suited to real-time applications where the latest state is needed, unlocking the subscription-based features of Polkadot (and Substrate) clients. Some familiarity with RxJS is a requirement to use the API, however just understanding `.subscribe` and `.pipe` on Observables will unlock full-scale use thereof. + * @see [[ApiPromise]] * - * @example - *
+ * ## Usage * * Making rpc calls - *
@@ -49,14 +54,18 @@ const l = logger('api-rx'); *
* * ```javascript - * import { ApiRx } from '@polkadot/api'; - * import WsProvider from '@polkadot/rpc-provider/ws'; * import { combineLatest } from 'rxjs'; + * import { ApiRx } from '@polkadot/api'; + * import { WsProvider } from '@polkadot/rpc-provider'; * + * // last block timestamp * let last = 0; * - * // initialise via isReady & new with specific non-local endpoint - * new ApiRx(new WsProvider('wss://example.com:9944')) + * // initialise a provider with a specific endpoint + * const provider = new WsProvider('wss://example.com:9944') + * + * // initialise via isReady & new with specific provider + * new ApiRx(provider) * .isReady * .pipe( * switchMap((api) => @@ -111,7 +120,7 @@ export default class ApiRx extends ApiBase * @@ -130,7 +139,7 @@ export default class ApiRx extends ApiBase * diff --git a/packages/rpc-core/src/index.ts b/packages/rpc-core/src/index.ts index 926243de4f..dca9d68f74 100644 --- a/packages/rpc-core/src/index.ts +++ b/packages/rpc-core/src/index.ts @@ -14,8 +14,6 @@ import assert from '@polkadot/util/assert'; import ExtError from '@polkadot/util/ext/error'; import isFunction from '@polkadot/util/is/function'; -import defaults from './defaults'; - /** * @name Rpc * @summary The API may use a HTTP or WebSockets provider. @@ -51,7 +49,7 @@ export default class Rpc implements RpcInterface { * Default constructor for the Api Object * @param {ProviderInterface} provider An API provider using HTTP or WebSocket */ - constructor (provider: ProviderInterface = new WsProvider(defaults.WS_URL)) { + constructor (provider: ProviderInterface = new WsProvider()) { assert(provider && isFunction(provider.send), 'Expected Provider to API create'); this._provider = provider; diff --git a/packages/rpc-provider/README.md b/packages/rpc-provider/README.md index a74aa73425..932c694953 100644 --- a/packages/rpc-provider/README.md +++ b/packages/rpc-provider/README.md @@ -1,6 +1,12 @@ # @polkadot/rpc-provider -Generic transport providers to handle the transport of method calls to and from Polkadot clients from applications interacting with it. Generally, unless you are operating at a low-level and taking care of encoding and decoding of parameters/results, it won't be directly used. API interfaces building on top these providers can support various transports with the same underlying interfaces. +Generic transport providers to handle the transport of method calls to and from Polkadot clients from applications interacting with it. It provides an interface to making RPC class and is generally, unless you are operating at a low-level and taking care of encoding and decoding of parameters/results, it won't be directly used, rather only passed to a higher-level interface. + +## Provider Selection + +There are two flavours of the providers provided, one allowing for using HTTP as a transport machanism, the other using WebSockets. It is generally recommended to use the [[WsProvider]] since in addition to standard calls, it allows for subscriptions where all changes to state can be pushed from the node to the client. + +Both providers are usable (as is the API), in both browser-based and Node.js environments. Polyfills for unsupported functionality are automatically applied based on feature-detection. ## Usage @@ -10,13 +16,26 @@ Installation - yarn add @polkadot/rpc-provider ``` -Initialisation - +WebSocket Initialisation - -```js +```javascript import WsProvider from '@polkadot/rpc-provider/ws'; -const provider = new WsProvider('http://127.0.0.1:9944'); +// this is the actual default endpoint +const provider = new WsProvider('ws://127.0.0.1:9944'); const version = await provider.send('client_version', []); -console.log('clientVersion', version); +console.log('client version', version); +``` + +HTTP Initialisation - + +```javascript +import { HttpProvider } from '@polkadot/rpc-provider'; + +// this is the actual default endpoint +const provider = new HttpProvider('http://127.0.0.1:9933'); +const version = await provider.send('chain_getBlockHash', []); + +console.log('latest block Hash', hash); ``` diff --git a/packages/rpc-core/src/defaults.ts b/packages/rpc-provider/src/defaults.ts similarity index 60% rename from packages/rpc-core/src/defaults.ts rename to packages/rpc-provider/src/defaults.ts index b9e7f61ec1..722a5fa01d 100644 --- a/packages/rpc-core/src/defaults.ts +++ b/packages/rpc-provider/src/defaults.ts @@ -1,9 +1,11 @@ -// Copyright 2017-2018 @polkadot/rpc-core authors & contributors +// Copyright 2017-2018 @polkadot/rpc-provider authors & contributors // This software may be modified and distributed under the terms // of the ISC license. See the LICENSE file for details. +const HTTP_URL = 'http://127.0.0.1:9933'; const WS_URL = 'ws://127.0.0.1:9944'; export default { + HTTP_URL, WS_URL }; diff --git a/packages/rpc-provider/src/http/index.ts b/packages/rpc-provider/src/http/index.ts index 7fd45d7593..56bec12ebb 100644 --- a/packages/rpc-provider/src/http/index.ts +++ b/packages/rpc-provider/src/http/index.ts @@ -12,10 +12,13 @@ import assert from '@polkadot/util/assert'; import logger from '@polkadot/util/logger'; import coder from '../coder/json'; +import defaults from '../defaults'; const ERROR_SUBSCRIBE = 'HTTP Provider does not have subscriptions, use WebSockets instead'; /** + * # @polkadot/rpc-provider/https + * * @name HttpProvider * @summary The HTTP Provider allows sending requests using HTTP to a HTTP RPC server TCP port. * @description It does not support subscriptions so you won't be able to listen to events @@ -25,11 +28,11 @@ const ERROR_SUBSCRIBE = 'HTTP Provider does not have subscriptions, use WebSocke *
* * ```javascript - * import Rpc from '@polkadot/rpc-core'; + * import Api from '@polkadot/api/promise'; * import HttpProvider from '@polkadot/rpc-provider/http'; * * const provider = new HttpProvider('http://127.0.0.1:9933'); - * const api = new Rpc(provider); + * const api = new Api(provider); * ``` * * @see [[WsProvider]] @@ -42,7 +45,7 @@ export default class HttpProvider implements ProviderInterface { /** * @param {string} endpoint The endpoint url starting with http:// */ - constructor (endpoint: string) { + constructor (endpoint: string = defaults.HTTP_URL) { assert(/^(https|http):\/\//.test(endpoint), `Endpoint should start with 'http://', received '${endpoint}'`); this.coder = coder(); diff --git a/packages/rpc-provider/src/ws/index.ts b/packages/rpc-provider/src/ws/index.ts index bea6a111dd..f95c44acdb 100644 --- a/packages/rpc-provider/src/ws/index.ts +++ b/packages/rpc-provider/src/ws/index.ts @@ -15,6 +15,7 @@ import isUndefined from '@polkadot/util/is/undefined'; import logger from '@polkadot/util/logger'; import coder from '../coder/json'; +import defaults from '../defaults'; type SubscriptionHandler = { callback: ProviderInterface$Callback, @@ -38,6 +39,8 @@ interface WSProviderInterface extends ProviderInterface { } /** + * # @polkadot/rpc-provider/ws + * * @name WsProvider * @summary The WebSocket Provider allows sending requests using WebSocket to a WebSocket RPC server TCP port. * @description Unlike the [[HttpProvider]], it does support subscriptions and allows @@ -46,11 +49,11 @@ interface WSProviderInterface extends ProviderInterface { *
* * ```javascript - * import Rpc from '@polkadot/rpc-core'; + * import Api from '@polkadot/api/promise'; * import WsProvider from '@polkadot/rpc-provider/ws'; * * const provider = new WsProvider('ws://127.0.0.1:9944'); - * const api = new Rpc(provider); + * const api = new Api(provider); * ``` * * @see [[HttpProvider]] @@ -77,7 +80,7 @@ export default class WsProvider implements WSProviderInterface { * @param {string} endpoint The endpoint url. Usually `ws://ip:9944` or `wss://ip:9944` * @param {boolean} autoConnect Whether to connect automatically or not. */ - constructor (endpoint: string, autoConnect: boolean = true) { + constructor (endpoint: string = defaults.WS_URL, autoConnect: boolean = true) { assert(/^(wss|ws):\/\//.test(endpoint), `Endpoint should start with 'ws://', received '${endpoint}'`); this._eventemitter = new EventEmitter();