UNPKG

6.49 kBJavaScriptView Raw
1"use strict";
2
3Object.defineProperty(exports, "__esModule", {
4 value: true
5});
6exports.ApiPromise = void 0;
7
8var _util = require("@polkadot/util");
9
10var _base = require("../base");
11
12var _Combinator = require("./Combinator");
13
14var _decorateMethod = require("./decorateMethod");
15
16// Copyright 2017-2022 @polkadot/api authors & contributors
17// SPDX-License-Identifier: Apache-2.0
18
19/**
20 * # @polkadot/api/promise
21 *
22 * ## Overview
23 *
24 * @name ApiPromise
25 * @description
26 * 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 `(value) => {}` callbacks to pass through the latest values.
27 *
28 * 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.
29 *
30 * @see [[ApiRx]]
31 *
32 * ## Usage
33 *
34 * Making rpc calls -
35 * <BR>
36 *
37 * ```javascript
38 * import ApiPromise from '@polkadot/api/promise';
39 *
40 * // initialise via static create
41 * const api = await ApiPromise.create();
42 *
43 * // make a subscription to the network head
44 * api.rpc.chain.subscribeNewHeads((header) => {
45 * console.log(`Chain is at #${header.number}`);
46 * });
47 * ```
48 * <BR>
49 *
50 * Subscribing to chain state -
51 * <BR>
52 *
53 * ```javascript
54 * import { ApiPromise, WsProvider } from '@polkadot/api';
55 *
56 * // initialise a provider with a specific endpoint
57 * const provider = new WsProvider('wss://example.com:9944')
58 *
59 * // initialise via isReady & new with specific provider
60 * const api = await new ApiPromise({ provider }).isReady;
61 *
62 * // retrieve the block target time
63 * const blockPeriod = await api.query.timestamp.blockPeriod().toNumber();
64 * let last = 0;
65 *
66 * // subscribe to the current block timestamp, updates automatically (callback provided)
67 * api.query.timestamp.now((timestamp) => {
68 * const elapsed = last
69 * ? `, ${timestamp.toNumber() - last}s since last`
70 * : '';
71 *
72 * last = timestamp.toNumber();
73 * console.log(`timestamp ${timestamp}${elapsed} (${blockPeriod}s target)`);
74 * });
75 * ```
76 * <BR>
77 *
78 * Submitting a transaction -
79 * <BR>
80 *
81 * ```javascript
82 * import ApiPromise from '@polkadot/api/promise';
83 *
84 * ApiPromise.create().then((api) => {
85 * const [nonce] = await api.query.system.account(keyring.alice.address);
86 *
87 * api.tx.balances
88 * // create transfer
89 * transfer(keyring.bob.address, 12345)
90 * // sign the transcation
91 * .sign(keyring.alice, { nonce })
92 * // send the transaction (optional status callback)
93 * .send((status) => {
94 * console.log(`current status ${status.type}`);
95 * })
96 * // retrieve the submitted extrinsic hash
97 * .then((hash) => {
98 * console.log(`submitted with hash ${hash}`);
99 * });
100 * });
101 * ```
102 */
103class ApiPromise extends _base.ApiBase {
104 #isReadyPromise;
105 #isReadyOrErrorPromise;
106 /**
107 * @description Creates an instance of the ApiPromise class
108 * @param options Options to create an instance. This can be either [[ApiOptions]] or
109 * an [[WsProvider]].
110 * @example
111 * <BR>
112 *
113 * ```javascript
114 * import Api from '@polkadot/api/promise';
115 *
116 * new Api().isReady.then((api) => {
117 * api.rpc.subscribeNewHeads((header) => {
118 * console.log(`new block #${header.number.toNumber()}`);
119 * });
120 * });
121 * ```
122 */
123
124 constructor(options) {
125 super(options, 'promise', _decorateMethod.toPromiseMethod);
126 this.#isReadyPromise = new Promise(resolve => {
127 super.once('ready', () => resolve(this));
128 });
129 this.#isReadyOrErrorPromise = new Promise((resolve, reject) => {
130 const tracker = (0, _decorateMethod.promiseTracker)(resolve, reject);
131 super.once('ready', () => tracker.resolve(this));
132 super.once('error', error => tracker.reject(error));
133 });
134 }
135 /**
136 * @description Creates an ApiPromise instance using the supplied provider. Returns an Promise containing the actual Api instance.
137 * @param options options that is passed to the class contructor. Can be either [[ApiOptions]] or a
138 * provider (see the constructor arguments)
139 * @example
140 * <BR>
141 *
142 * ```javascript
143 * import Api from '@polkadot/api/promise';
144 *
145 * Api.create().then(async (api) => {
146 * const timestamp = await api.query.timestamp.now();
147 *
148 * console.log(`lastest block timestamp ${timestamp}`);
149 * });
150 * ```
151 */
152
153
154 static create(options) {
155 const instance = new ApiPromise(options);
156
157 if (options && options.throwOnConnect) {
158 return instance.isReadyOrError;
159 } // Swallow any rejections on isReadyOrError
160 // (in Node 15.x this creates issues, when not being looked at)
161
162
163 instance.isReadyOrError.catch(() => {// ignore
164 });
165 return instance.isReady;
166 }
167 /**
168 * @description Promise that resolves the first time we are connected and loaded
169 */
170
171
172 get isReady() {
173 return this.#isReadyPromise;
174 }
175 /**
176 * @description Promise that resolves if we can connect, or reject if there is an error
177 */
178
179
180 get isReadyOrError() {
181 return this.#isReadyOrErrorPromise;
182 }
183 /**
184 * @description Returns a clone of this ApiPromise instance (new underlying provider connection)
185 */
186
187
188 clone() {
189 return new ApiPromise((0, _util.objectSpread)({}, this._options, {
190 source: this
191 }));
192 }
193 /**
194 * @description Creates a combinator that can be used to combine the latest results from multiple subscriptions
195 * @param fns An array of function to combine, each in the form of `(cb: (value: void)) => void`
196 * @param callback A callback that will return an Array of all the values this combinator has been applied to
197 * @example
198 * <BR>
199 *
200 * ```javascript
201 * const address = '5DTestUPts3kjeXSTMyerHihn1uwMfLj8vU8sqF7qYrFacT7';
202 *
203 * // combines values from balance & nonce as it updates
204 * api.combineLatest([
205 * api.rpc.chain.subscribeNewHeads,
206 * (cb) => api.query.system.account(address, cb)
207 * ], ([head, [balance, nonce]]) => {
208 * console.log(`#${head.number}: You have ${balance.free} units, with ${nonce} transactions sent`);
209 * });
210 * ```
211 */
212 // eslint-disable-next-line @typescript-eslint/require-await
213
214
215 async combineLatest(fns, callback) {
216 const combinator = new _Combinator.Combinator(fns, callback);
217 return () => {
218 combinator.unsubscribe();
219 };
220 }
221
222}
223
224exports.ApiPromise = ApiPromise;
\No newline at end of file