-
Notifications
You must be signed in to change notification settings - Fork 237
/
failover-rpc-provider.ts
364 lines (329 loc) · 13.4 KB
/
failover-rpc-provider.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
/**
* @module
* @description
* This module contains the {@link FailoverRpcProvider} client class
* which can be used to interact with multiple [NEAR RPC APIs](https://docs.near.org/api/rpc/introduction).
* @see {@link "@near-js/types".provider | provider} for a list of request and response types
*/
import { Logger } from '@near-js/utils';
import {
AccessKeyWithPublicKey,
BlockId,
BlockReference,
BlockResult,
BlockChangeResult,
ChangeResult,
ChunkId,
ChunkResult,
EpochValidatorInfo,
FinalExecutionOutcome,
GasPrice,
LightClientProof,
LightClientProofRequest,
NextLightClientBlockRequest,
NextLightClientBlockResponse,
NearProtocolConfig,
NodeStatusResult,
QueryResponseKind,
TypedError,
RpcQueryRequest,
} from '@near-js/types';
import { SignedTransaction } from '@near-js/transactions';
import { Provider } from './provider';
import { TxExecutionStatus } from '@near-js/types/src/provider/protocol';
/**
* Client class to interact with the [NEAR RPC API](https://docs.near.org/api/rpc/introduction).
* @see [https://github.com/near/nearcore/tree/master/chain/jsonrpc](https://github.com/near/nearcore/tree/master/chain/jsonrpc)
*/
export class FailoverRpcProvider extends Provider {
/** @hidden */
readonly providers: Provider[];
private currentProviderIndex: number;
/**
* @param providers list of providers
*/
constructor(providers: Provider[]) {
super();
if (providers.length === 0) {
throw new Error('At least one provider must be specified');
}
this.providers = providers;
this.currentProviderIndex = 0;
}
private switchToNextProvider(): void {
if (this.providers.length === 1) return;
if (this.providers.length - 1 <= this.currentProviderIndex) {
this.currentProviderIndex = 0;
} else {
this.currentProviderIndex += 1;
}
Logger.debug(
`Switched to provider at the index ${this.currentProviderIndex}`
);
}
private get currentProvider(): Provider {
const provider = this.providers[this.currentProviderIndex];
if (!provider)
throw new Error(
`Provider wasn't found at index ${this.currentProviderIndex}`
);
return provider;
}
private async withBackoff(getResult: (provider: Provider) => Promise<any>) {
for (let i = 0; i < this.providers.length; i++) {
try {
// each provider implements own retry logic
const result = await getResult(this.currentProvider);
if (result) return result;
} catch {
this.switchToNextProvider();
}
}
throw new TypedError(
`Exceeded ${this.providers.length} providers to execute request`,
'RetriesExceeded'
);
}
/**
* Gets the RPC's status
* @see [https://docs.near.org/docs/develop/front-end/rpc#general-validator-status](https://docs.near.org/docs/develop/front-end/rpc#general-validator-status)
*/
async status(): Promise<NodeStatusResult> {
return this.withBackoff((currentProvider) => currentProvider.status());
}
async sendTransactionUntil(signedTransaction: SignedTransaction, waitUntil: TxExecutionStatus): Promise<FinalExecutionOutcome> {
return this.withBackoff((currentProvider) => currentProvider.sendTransactionUntil(signedTransaction, waitUntil));
}
/**
* Sends a signed transaction to the RPC and waits until transaction is fully complete
* @see [https://docs.near.org/docs/develop/front-end/rpc#send-transaction-await](https://docs.near.org/docs/develop/front-end/rpc#general-validator-status)
*
* @param signedTransaction The signed transaction being sent
*/
async sendTransaction(
signedTransaction: SignedTransaction
): Promise<FinalExecutionOutcome> {
return this.withBackoff((currentProvider) => currentProvider.sendTransaction(signedTransaction)
);
}
/**
* Sends a signed transaction to the RPC and immediately returns transaction hash
* See [docs for more info](https://docs.near.org/docs/develop/front-end/rpc#send-transaction-async)
* @param signedTransaction The signed transaction being sent
* @returns {Promise<FinalExecutionOutcome>}
*/
async sendTransactionAsync(
signedTransaction: SignedTransaction
): Promise<FinalExecutionOutcome> {
return this.withBackoff((currentProvider) => currentProvider.sendTransactionAsync(signedTransaction)
);
}
/**
* Gets a transaction's status from the RPC
* @see [https://docs.near.org/docs/develop/front-end/rpc#transaction-status](https://docs.near.org/docs/develop/front-end/rpc#general-validator-status)
*
* @param txHash A transaction hash as either a Uint8Array or a base58 encoded string
* @param accountId The NEAR account that signed the transaction
*/
async txStatus(
txHash: Uint8Array | string,
accountId: string,
waitUntil: TxExecutionStatus
): Promise<FinalExecutionOutcome> {
return this.withBackoff((currentProvider) => currentProvider.txStatus(txHash, accountId, waitUntil)
);
}
/**
* Gets a transaction's status from the RPC with receipts
* See [docs for more info](https://docs.near.org/docs/develop/front-end/rpc#transaction-status-with-receipts)
* @param txHash The hash of the transaction
* @param accountId The NEAR account that signed the transaction
* @returns {Promise<FinalExecutionOutcome>}
*/
async txStatusReceipts(
txHash: Uint8Array | string,
accountId: string,
waitUntil: TxExecutionStatus
): Promise<FinalExecutionOutcome> {
return this.withBackoff((currentProvider) => currentProvider.txStatusReceipts(txHash, accountId, waitUntil)
);
}
/**
* Query the RPC by passing an {@link "@near-js/types".provider/request.RpcQueryRequest | RpcQueryRequest }
* @see [https://docs.near.org/api/rpc/contracts](https://docs.near.org/api/rpc/contracts)
*
* @typeParam T the shape of the returned query response
*/
async query<T extends QueryResponseKind>(
params: RpcQueryRequest
): Promise<T>;
async query<T extends QueryResponseKind>(
path: string,
data: string
): Promise<T>;
async query<T extends QueryResponseKind>(
paramsOrPath: any,
data?: any
): Promise<T> {
if (data) {
return this.withBackoff((currentProvider) => currentProvider.query<T>(paramsOrPath, data)
);
}
return this.withBackoff((currentProvider) => currentProvider.query<T>(paramsOrPath)
);
}
/**
* Query for block info from the RPC
* pass block_id OR finality as blockQuery, not both
* @see [https://docs.near.org/api/rpc/block-chunk](https://docs.near.org/api/rpc/block-chunk)
*
* @param blockQuery {@link BlockReference} (passing a {@link BlockId} is deprecated)
*/
async block(blockQuery: BlockId | BlockReference): Promise<BlockResult> {
return this.withBackoff((currentProvider) => currentProvider.block(blockQuery));
}
/**
* Query changes in block from the RPC
* pass block_id OR finality as blockQuery, not both
* @see [https://docs.near.org/api/rpc/block-chunk](https://docs.near.org/api/rpc/block-chunk)
*/
async blockChanges(blockQuery: BlockReference): Promise<BlockChangeResult> {
return this.withBackoff((currentProvider) => currentProvider.blockChanges(blockQuery)
);
}
/**
* Queries for details about a specific chunk appending details of receipts and transactions to the same chunk data provided by a block
* @see [https://docs.near.org/api/rpc/block-chunk](https://docs.near.org/api/rpc/block-chunk)
*
* @param chunkId Hash of a chunk ID or shard ID
*/
async chunk(chunkId: ChunkId): Promise<ChunkResult> {
return this.withBackoff((currentProvider) => currentProvider.chunk(chunkId));
}
/**
* Query validators of the epoch defined by the given block id.
* @see [https://docs.near.org/api/rpc/network#validation-status](https://docs.near.org/api/rpc/network#validation-status)
*
* @param blockId Block hash or height, or null for latest.
*/
async validators(blockId: BlockId | null): Promise<EpochValidatorInfo> {
return this.withBackoff((currentProvider) => currentProvider.validators(blockId));
}
/**
* Gets the protocol config at a block from RPC
*
* @param blockReference specifies the block to get the protocol config for
*/
async experimental_protocolConfig(
blockReference: BlockReference | { sync_checkpoint: 'genesis' }
): Promise<NearProtocolConfig> {
return this.withBackoff((currentProvider) => currentProvider.experimental_protocolConfig(blockReference)
);
}
/**
* Gets a light client execution proof for verifying execution outcomes
* @see [https://github.com/nearprotocol/NEPs/blob/master/specs/ChainSpec/LightClient.md#light-client-proof](https://github.com/nearprotocol/NEPs/blob/master/specs/ChainSpec/LightClient.md#light-client-proof)
*/
async lightClientProof(
request: LightClientProofRequest
): Promise<LightClientProof> {
return this.withBackoff((currentProvider) => currentProvider.lightClientProof(request)
);
}
/**
* Returns the next light client block as far in the future as possible from the last known hash
* to still be able to validate from that hash. This will either return the last block of the
* next epoch, or the last final known block.
*
* @see [https://github.com/near/NEPs/blob/master/specs/ChainSpec/LightClient.md#light-client-block](https://github.com/near/NEPs/blob/master/specs/ChainSpec/LightClient.md#light-client-block)
*/
async nextLightClientBlock(
request: NextLightClientBlockRequest
): Promise<NextLightClientBlockResponse> {
return this.withBackoff((currentProvider) => currentProvider.nextLightClientBlock(request)
);
}
/**
* Gets access key changes for a given array of accountIds
* See [docs for more info](https://docs.near.org/docs/develop/front-end/rpc#view-access-key-changes-all)
* @returns {Promise<ChangeResult>}
*/
async accessKeyChanges(
accountIdArray: string[],
blockQuery: BlockReference
): Promise<ChangeResult> {
return this.withBackoff((currentProvider) => currentProvider.accessKeyChanges(accountIdArray, blockQuery)
);
}
/**
* Gets single access key changes for a given array of access keys
* pass block_id OR finality as blockQuery, not both
* See [docs for more info](https://docs.near.org/docs/develop/front-end/rpc#view-access-key-changes-single)
* @returns {Promise<ChangeResult>}
*/
async singleAccessKeyChanges(
accessKeyArray: AccessKeyWithPublicKey[],
blockQuery: BlockReference
): Promise<ChangeResult> {
return this.withBackoff((currentProvider) => currentProvider.singleAccessKeyChanges(
accessKeyArray,
blockQuery
)
);
}
/**
* Gets account changes for a given array of accountIds
* pass block_id OR finality as blockQuery, not both
* See [docs for more info](https://docs.near.org/docs/develop/front-end/rpc#view-account-changes)
* @returns {Promise<ChangeResult>}
*/
async accountChanges(
accountIdArray: string[],
blockQuery: BlockReference
): Promise<ChangeResult> {
return this.withBackoff((currentProvider) => currentProvider.accountChanges(accountIdArray, blockQuery)
);
}
/**
* Gets contract state changes for a given array of accountIds
* pass block_id OR finality as blockQuery, not both
* Note: If you pass a keyPrefix it must be base64 encoded
* See [docs for more info](https://docs.near.org/docs/develop/front-end/rpc#view-contract-state-changes)
* @returns {Promise<ChangeResult>}
*/
async contractStateChanges(
accountIdArray: string[],
blockQuery: BlockReference,
keyPrefix = ''
): Promise<ChangeResult> {
return this.withBackoff((currentProvider) => currentProvider.contractStateChanges(
accountIdArray,
blockQuery,
keyPrefix
)
);
}
/**
* Gets contract code changes for a given array of accountIds
* pass block_id OR finality as blockQuery, not both
* Note: Change is returned in a base64 encoded WASM file
* See [docs for more info](https://docs.near.org/docs/develop/front-end/rpc#view-contract-code-changes)
* @returns {Promise<ChangeResult>}
*/
async contractCodeChanges(
accountIdArray: string[],
blockQuery: BlockReference
): Promise<ChangeResult> {
return this.withBackoff((currentProvider) => currentProvider.contractCodeChanges(accountIdArray, blockQuery)
);
}
/**
* Returns gas price for a specific block_height or block_hash.
* @see [https://docs.near.org/api/rpc/gas](https://docs.near.org/api/rpc/gas)
*
* @param blockId Block hash or height, or null for latest.
*/
async gasPrice(blockId: BlockId | null): Promise<GasPrice> {
return this.withBackoff((currentProvider) => currentProvider.gasPrice(blockId));
}
}