73 lines
2.5 KiB
Markdown
73 lines
2.5 KiB
Markdown
|
|
[](https://polkadot.js.org)  [](https://github.com/Flet/semistandard) [](https://www.npmjs.com/package/@polkadot/api) [](https://travis-ci.org/polkadot-js/api) [](https://codeclimate.com/github/polkadot-js/api/maintainability) [](https://coveralls.io/github/polkadot-js/api?branch=master) [](https://david-dm.org/polkadot-js/api?path=package/rpc-core) [](https://david-dm.org/polkadot-js/api?path=package/rpc-core#info=devDependencies)
|
|
|
|
@polkadot/api
|
|
=============
|
|
|
|
This library provides a clean wrapper around all the methods exposed by a Polkadot network client.
|
|
|
|
Usage
|
|
-----
|
|
|
|
Installation -
|
|
|
|
```
|
|
npm install --save @polkadot/rpc-core
|
|
```
|
|
|
|
Initialisation -
|
|
|
|
```js
|
|
import Api from '@polkadot/rpc-core';
|
|
import WsProvider from '@polkadot/rpc-provider/ws';
|
|
|
|
const provider = new WsProvider('http://127.0.0.1:9944');
|
|
const api = new Api(provider);
|
|
```
|
|
|
|
Making calls -
|
|
|
|
```js
|
|
api.chain
|
|
.getHeader('0x1234567890')
|
|
.then((header) => console.log(header))
|
|
.catch((error) => console.error(error));
|
|
```
|
|
|
|
Retrieving the best block (once-off) -
|
|
|
|
```js
|
|
api.chain
|
|
.getHead()
|
|
.then((headerHash) => {
|
|
return api.chain.getHeader(headerHash);
|
|
})
|
|
.then((header) => {
|
|
console.log(`best #${header.number.toString()}`);
|
|
})
|
|
.catch((error) => {
|
|
console.error('error:', error);
|
|
});
|
|
```
|
|
|
|
Retrieving best header via subscription -
|
|
|
|
```js
|
|
api.chain
|
|
.newHead((error, header) => {
|
|
if (error) {
|
|
console.error('error:', error);
|
|
}
|
|
|
|
console.log(`best #${header.number.toString()}`);
|
|
})
|
|
.then((subscriptionId) => {
|
|
// id for the subscription, can unsubscribe via
|
|
// api.chain.newHead.unsubscribe(subscriptionId)
|
|
})
|
|
.catch((error) => {
|
|
console.error('error subscribing:', error);
|
|
});
|
|
```
|
|
|