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