-
Notifications
You must be signed in to change notification settings - Fork 250
/
Copy pathjson-rpc-provider.ts
396 lines (362 loc) · 16 KB
/
json-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
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
/**
* This module contains the {@link JsonRpcProvider} client class
* which can be used to interact with the NEAR RPC API.
* @see {@link providers/provider} for a list of request and response types
*/
import depd from 'depd';
import {
AccessKeyWithPublicKey,
Provider,
FinalExecutionOutcome,
NodeStatusResult,
BlockId,
BlockReference,
BlockResult,
BlockChangeResult,
ChangeResult,
ChunkId,
ChunkResult,
EpochValidatorInfo,
NearProtocolConfig,
LightClientProof,
LightClientProofRequest,
GasPrice,
QueryResponseKind
} from './provider';
import { ConnectionInfo, fetchJson } from '../utils/web';
import { TypedError, ErrorContext } from '../utils/errors';
import { baseEncode } from 'borsh';
import exponentialBackoff from '../utils/exponential-backoff';
import { parseRpcError, getErrorTypeFromErrorMessage } from '../utils/rpc_errors';
import { SignedTransaction } from '../transaction';
/** @hidden */
export { TypedError, ErrorContext };
// Default number of retries before giving up on a request.
const REQUEST_RETRY_NUMBER = 12;
// Default wait until next retry in millis.
const REQUEST_RETRY_WAIT = 500;
// Exponential back off for waiting to retry.
const REQUEST_RETRY_WAIT_BACKOFF = 1.5;
/// Keep ids unique across all connections.
let _nextId = 123;
/**
* Client class to interact with the NEAR RPC API.
* @see {@link https://github.com/near/nearcore/tree/master/chain/jsonrpc}
*/
export class JsonRpcProvider extends Provider {
/** @hidden */
readonly connection: ConnectionInfo;
/**
* @param url RPC API endpoint URL
*/
constructor(url?: string) {
super();
this.connection = { url };
}
/**
* Gets the RPC's status
* @see {@link https://docs.near.org/docs/develop/front-end/rpc#general-validator-status}
*/
async status(): Promise<NodeStatusResult> {
return this.sendJsonRpc('status', []);
}
/**
* Sends a signed transaction to the RPC and waits until transaction is fully complete
* @see {@link https://docs.near.org/docs/develop/front-end/rpc#send-transaction-await}
*
* @param signedTransaction The signed transaction being sent
*/
async sendTransaction(signedTransaction: SignedTransaction): Promise<FinalExecutionOutcome> {
const bytes = signedTransaction.encode();
return this.sendJsonRpc('broadcast_tx_commit', [Buffer.from(bytes).toString('base64')]);
}
/**
* 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> {
const bytes = signedTransaction.encode();
return this.sendJsonRpc('broadcast_tx_async', [Buffer.from(bytes).toString('base64')]);
}
/**
* Gets a transaction's status from the RPC
* @see {@link https://docs.near.org/docs/develop/front-end/rpc#transaction-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): Promise<FinalExecutionOutcome> {
if(typeof txHash === 'string') {
return this.txStatusString(txHash, accountId);
} else {
return this.txStatusUint8Array(txHash, accountId);
}
}
private async txStatusUint8Array(txHash: Uint8Array, accountId: string): Promise<FinalExecutionOutcome> {
return this.sendJsonRpc('tx', [baseEncode(txHash), accountId]);
}
private async txStatusString(txHash: string, accountId: string): Promise<FinalExecutionOutcome> {
return this.sendJsonRpc('tx', [txHash, accountId]);
}
/**
* 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, accountId: string): Promise<FinalExecutionOutcome> {
return this.sendJsonRpc('EXPERIMENTAL_tx_status', [baseEncode(txHash), accountId]);
}
/**
* Query the RPC as [shown in the docs](https://docs.near.org/docs/develop/front-end/rpc#accounts--contracts)
* Query the RPC by passing an {@link RpcQueryRequest}
* @see {@link https://docs.near.org/docs/develop/front-end/rpc#accounts--contracts}
*
* @typeParam T the shape of the returned query response
*/
async query<T extends QueryResponseKind>(...args: any[]): Promise<T> {
let result;
if (args.length === 1) {
result = await this.sendJsonRpc<T>('query', args[0]);
} else {
const [path, data] = args;
result = await this.sendJsonRpc<T>('query', [path, data]);
}
if (result && result.error) {
throw new TypedError(
`Querying ${args} failed: ${result.error}.\n${JSON.stringify(result, null, 2)}`,
getErrorTypeFromErrorMessage(result.error));
}
return result;
}
/**
* Query for block info from the RPC
* pass block_id OR finality as blockQuery, not both
* @see {@link https://docs.near.org/docs/interaction/rpc#block}
*
* @param blockQuery {@link BlockReference} (passing a {@link BlockId} is deprecated)
*/
async block(blockQuery: BlockId | BlockReference): Promise<BlockResult> {
const { finality } = blockQuery as any;
let { blockId } = blockQuery as any;
if (typeof blockQuery !== 'object') {
const deprecate = depd('JsonRpcProvider.block(blockId)');
deprecate('use `block({ blockId })` or `block({ finality })` instead');
blockId = blockQuery;
}
return this.sendJsonRpc('block', { block_id: blockId, finality });
}
/**
* Query changes in block from the RPC
* pass block_id OR finality as blockQuery, not both
* See [docs for more info](https://docs.near.org/docs/develop/front-end/rpc#block-details)
*/
async blockChanges(blockQuery: BlockReference): Promise<BlockChangeResult> {
const { finality } = blockQuery as any;
const { blockId } = blockQuery as any;
return this.sendJsonRpc('EXPERIMENTAL_changes_in_block', { block_id: blockId, finality });
}
/**
* Queries for details about a specific chunk appending details of receipts and transactions to the same chunk data provided by a block
* @see {@link https://docs.near.org/docs/interaction/rpc#chunk}
*
* @param chunkId Hash of a chunk ID or shard ID
*/
async chunk(chunkId: ChunkId): Promise<ChunkResult> {
return this.sendJsonRpc('chunk', [chunkId]);
}
/**
* Query validators of the epoch defined by the given block id.
* @see {@link https://docs.near.org/docs/develop/front-end/rpc#detailed-validator-status}
*
* @param blockId Block hash or height, or null for latest.
*/
async validators(blockId: BlockId | null): Promise<EpochValidatorInfo> {
return this.sendJsonRpc('validators', [blockId]);
}
/**
* @deprecated
* Gets the genesis config from RPC
* @see {@link https://docs.near.org/docs/develop/front-end/rpc#genesis-config}
*/
async experimental_genesisConfig(): Promise<NearProtocolConfig> {
const deprecate = depd('JsonRpcProvider.experimental_protocolConfig()');
deprecate('use `experimental_protocolConfig({ sync_checkpoint: \'genesis\' })` to fetch the up-to-date or genesis protocol config explicitly');
return await this.sendJsonRpc('EXPERIMENTAL_protocol_config', { sync_checkpoint: 'genesis' });
}
/**
* Gets the protocol config at a block from RPC
* @see {@link }
*
* @param blockReference specifies the block to get the protocol config for
*/
async experimental_protocolConfig(blockReference: BlockReference | { sync_checkpoint: 'genesis' }): Promise<NearProtocolConfig> {
return await this.sendJsonRpc('EXPERIMENTAL_protocol_config', blockReference);
}
/**
* @deprecated Use {@link lightClientProof} instead
*/
async experimental_lightClientProof(request: LightClientProofRequest): Promise<LightClientProof> {
const deprecate = depd('JsonRpcProvider.experimental_lightClientProof(request)');
deprecate('use `lightClientProof` instead');
return await this.lightClientProof(request);
}
/**
* Gets a light client execution proof for verifying execution outcomes
* @see {@link https://github.com/nearprotocol/NEPs/blob/master/specs/ChainSpec/LightClient.md#light-client-proof}
*/
async lightClientProof(request: LightClientProofRequest): Promise<LightClientProof> {
return await this.sendJsonRpc('EXPERIMENTAL_light_client_proof', 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> {
const { finality } = blockQuery as any;
const { blockId } = blockQuery as any;
return this.sendJsonRpc('EXPERIMENTAL_changes', {
changes_type: 'all_access_key_changes',
account_ids: accountIdArray,
block_id: blockId,
finality
});
}
/**
* 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> {
const { finality } = blockQuery as any;
const { blockId } = blockQuery as any;
return this.sendJsonRpc('EXPERIMENTAL_changes', {
changes_type: 'single_access_key_changes',
keys: accessKeyArray,
block_id: blockId,
finality
});
}
/**
* 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> {
const { finality } = blockQuery as any;
const { blockId } = blockQuery as any;
return this.sendJsonRpc('EXPERIMENTAL_changes', {
changes_type: 'account_changes',
account_ids: accountIdArray,
block_id: blockId,
finality
});
}
/**
* 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> {
const { finality } = blockQuery as any;
const { blockId } = blockQuery as any;
return this.sendJsonRpc('EXPERIMENTAL_changes', {
changes_type: 'data_changes',
account_ids: accountIdArray,
key_prefix_base64: keyPrefix,
block_id: blockId,
finality
});
}
/**
* 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> {
const {finality} = blockQuery as any;
const {blockId} = blockQuery as any;
return this.sendJsonRpc('EXPERIMENTAL_changes', {
changes_type: 'contract_code_changes',
account_ids: accountIdArray,
block_id: blockId,
finality
});
}
/**
* Returns gas price for a specific block_height or block_hash.
* @see {@link https://docs.near.org/docs/develop/front-end/rpc#gas-price}
*
* @param blockId Block hash or height, or null for latest.
*/
async gasPrice(blockId: BlockId | null): Promise<GasPrice> {
return await this.sendJsonRpc('gas_price', [blockId]);
}
/**
* Directly call the RPC specifying the method and params
*
* @param method RPC method
* @param params Parameters to the method
*/
async sendJsonRpc<T>(method: string, params: object): Promise<T> {
const response = await exponentialBackoff(REQUEST_RETRY_WAIT, REQUEST_RETRY_NUMBER, REQUEST_RETRY_WAIT_BACKOFF, async () => {
try {
const request = {
method,
params,
id: (_nextId++),
jsonrpc: '2.0'
};
const response = await fetchJson(this.connection, JSON.stringify(request));
if (response.error) {
if (typeof response.error.data === 'object') {
if (typeof response.error.data.error_message === 'string' && typeof response.error.data.error_type === 'string') {
// if error data has error_message and error_type properties, we consider that node returned an error in the old format
throw new TypedError(response.error.data.error_message, response.error.data.error_type);
}
throw parseRpcError(response.error.data);
} else {
const errorMessage = `[${response.error.code}] ${response.error.message}: ${response.error.data}`;
// NOTE: All this hackery is happening because structured errors not implemented
// TODO: Fix when https://github.com/nearprotocol/nearcore/issues/1839 gets resolved
if (response.error.data === 'Timeout' || errorMessage.includes('Timeout error')
|| errorMessage.includes('query has timed out')) {
throw new TypedError(errorMessage, 'TimeoutError');
}
throw new TypedError(errorMessage, getErrorTypeFromErrorMessage(response.error.data));
}
}
// Success when response.error is not exist
return response;
} catch (error) {
if (error.type === 'TimeoutError') {
if (!process.env['NEAR_NO_LOGS']){
console.warn(`Retrying request to ${method} as it has timed out`, params);
}
return null;
}
throw error;
}
});
const { result } = response;
// From jsonrpc spec:
// result
// This member is REQUIRED on success.
// This member MUST NOT exist if there was an error invoking the method.
if (typeof result === 'undefined') {
throw new TypedError(
`Exceeded ${REQUEST_RETRY_NUMBER} attempts for request to ${method}.`, 'RetriesExceeded');
}
return result;
}
}