Skip to content

Commit

Permalink
Merge b5ffa73 into 83f63e5
Browse files Browse the repository at this point in the history
  • Loading branch information
jacogr committed Oct 11, 2018
2 parents 83f63e5 + b5ffa73 commit 67e84c9
Show file tree
Hide file tree
Showing 4 changed files with 63 additions and 26 deletions.
18 changes: 12 additions & 6 deletions packages/api/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,23 +6,29 @@ The API wrappers provide a standard interface for use -

- A static `.create(<optional WsProvider>)` that returns an API istance when connected, decorated and ready-to use
- The above is just a wrapper for `new Api(<optional WsProvider>) `, 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.<section>.<method>` provides access to actual RPC calls, be it for queries, submission or retrieving chain information
- `api.st.<section>.<method>` provides access to chain state queries. These are dynamically populated based on what the runtime provides
- `api.tx.<section>.<method>` 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 -
Expand Down
28 changes: 26 additions & 2 deletions packages/api/src/Base.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,8 @@ export default abstract class ApiBase<R, S, E> implements ApiBaseInterface<R, S,
protected _runtimeVersion?: RuntimeVersion;

/**
* @param wsProvider An optional WebSocket provider from rpc-provider/ws. If not specified, it will default to connecting to the localhost with the default port
* @param wsProvider A WebSocket provider from rpc-provider/ws. If not specified, it will default to connecting to the localhost with the default port
*
* @example
* <BR>
*
Expand Down Expand Up @@ -90,7 +91,10 @@ export default abstract class ApiBase<R, S, E> implements ApiBaseInterface<R, S,
}

/**
* @description Contains all the raw rpc sections and their subsequent methods in the API as defined by the jsonrpc interface definitions.
* @description Contains all the raw rpc sections and their subsequent methods in the API as defined by the jsonrpc interface definitions. Unlike the dynamic `api.st` and `api.tx` sections, these methods are fixed (although extensible with node upgrades) and not determined by the runtime.
*
* RPC endpoints available here allow for the query of chain, node and system information, in addition to providing interfaces for the raw queries of state (usine known keys) and the submission of transactions.
*
* @example
* <BR>
*
Expand All @@ -108,6 +112,9 @@ export default abstract class ApiBase<R, S, E> implements ApiBaseInterface<R, S,

/**
* @description Contains all the chain state modules and their subsequent methods in the API. These are attached dynamically from the runtime metadata.
*
* All calls inside the namespace, is denoted by `section`.`method` and may take an optional query parameter. As an example, `api.st.timestamp.now()` (current block timestamp) does not take parameters, while `api.st.system.accountNonce(<accountId>)` (retrieving the associated nonce for an account), takes the `AccountId` as a parameter.
*
* @example
* <BR>
*
Expand All @@ -127,6 +134,7 @@ export default abstract class ApiBase<R, S, E> implements ApiBaseInterface<R, S,

/**
* @description Contains all the extrinsic modules and their subsequent methods in the API. It allows for the construction of transactions and the submission thereof. These are attached dynamically from the runtime metadata.
*
* @example
* <BR>
*
Expand All @@ -146,6 +154,22 @@ export default abstract class ApiBase<R, S, E> implements ApiBaseInterface<R, S,
return this._extrinsics as E;
}

/**
* @description
* @param type The type of event to listen to. Availble events are `connected`, `disconnected` and `ready`
* @param handler The callback to be called when the event fires. Depending on the event type, it could fire with additional arguments.
* @example<BR>
*
* ```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>) => any): void {
this._eventemitter.on(type, handler);
}
Expand Down
21 changes: 12 additions & 9 deletions packages/api/src/promise/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,13 +16,13 @@ import SubmittableExtrinsic from './SubmittableExtrinsic';
import { StorageFunction } from '@polkadot/types/StorageKey';

/**
* @description
* # @polkadot/api/promise
*
* 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.
*
* @example
* <BR>
* ## Usage
*
* Making rpc calls -
* <BR>
Expand All @@ -47,14 +47,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`
Expand Down Expand Up @@ -94,7 +97,7 @@ export default class ApiPromise extends ApiBase<Rpc, QueryableStorage, Submittab

/**
* @description Creates an ApiPromise instance using the supplied provider. Returns an Promise containing the actual Api instance.
* @param wsProvider Optional WebSocket provider that is passed to the class contructor
* @param wsProvider WebSocket provider that is passed to the class contructor
* @example
* <BR>
*
Expand All @@ -113,7 +116,7 @@ export default class ApiPromise extends ApiBase<Rpc, QueryableStorage, Submittab
}

/**
* @param wsProvider An optional WebSocket provider from rpc-provider/ws. If not specified, it will default to connecting to the localhost with the default port
* @param wsProvider WebSocket provider from rpc-provider/ws. If not specified, it will default to connecting to the localhost with the default port, i.e. `ws://127.0.0.1:9944`
* @example
* <BR>
*
Expand Down
22 changes: 13 additions & 9 deletions packages/api/src/rx/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,13 +21,13 @@ import { StorageFunction } from '@polkadot/types/StorageKey';
const l = logger('api-rx');

/**
* @description
* # @polkadot/api/rx
*
* 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.
*
* @example
* <BR>
* ## Usage
*
* Making rpc calls -
* <BR>
Expand All @@ -49,14 +49,18 @@ const l = logger('api-rx');
* <BR>
*
* ```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) =>
Expand Down Expand Up @@ -111,7 +115,7 @@ export default class ApiRx extends ApiBase<RpcRx, QueryableStorage, SubmittableE

/**
* @description Creates an ApiRx instance using the supplied provider. Returns an Observable containing the actual Api instance.
* @param wsProvider Optional WebSocket provider that is passed to the class contructor
* @param wsProvider WebSocket provider that is passed to the class contructor
* @example
* <BR>
*
Expand All @@ -130,7 +134,7 @@ export default class ApiRx extends ApiBase<RpcRx, QueryableStorage, SubmittableE
}

/**
* @param wsProvider An optional WebSocket provider from rpc-provider/ws. If not specified, it will default to connecting to the localhost with the default port
* @param wsProvider A WebSocket provider from rpc-provider/ws. If not specified, it will default to connecting to the localhost with the default port, i.e. `ws://127.0.0.1:9944`
* @example
* <BR>
*
Expand Down

0 comments on commit 67e84c9

Please sign in to comment.