-
Notifications
You must be signed in to change notification settings - Fork 4.9k
/
web3_request_manager.ts
497 lines (441 loc) · 14.7 KB
/
web3_request_manager.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
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
/*
This file is part of web3.js.
web3.js is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
web3.js is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with web3.js. If not, see <http://www.gnu.org/licenses/>.
*/
import {
ContractExecutionError,
InvalidResponseError,
ProviderError,
ResponseError,
rpcErrorsMap,
RpcError,
} from 'web3-errors';
import HttpProvider from 'web3-providers-http';
import WSProvider from 'web3-providers-ws';
import {
EthExecutionAPI,
JsonRpcBatchRequest,
JsonRpcBatchResponse,
JsonRpcPayload,
JsonRpcResponse,
JsonRpcError,
JsonRpcResponseWithResult,
JsonRpcResponseWithError,
SupportedProviders,
Web3APIMethod,
Web3APIPayload,
Web3APIRequest,
Web3APIReturnType,
Web3APISpec,
Web3BaseProvider,
Web3BaseProviderConstructor,
JsonRpcRequest
} from 'web3-types';
import { isNullish, isPromise, jsonRpc, isResponseRpcError } from 'web3-utils';
import {
isEIP1193Provider,
isLegacyRequestProvider,
isLegacySendAsyncProvider,
isLegacySendProvider,
isWeb3Provider,
isMetaMaskProvider,
} from './utils.js';
import { Web3EventEmitter } from './web3_event_emitter.js';
export enum Web3RequestManagerEvent {
PROVIDER_CHANGED = 'PROVIDER_CHANGED',
BEFORE_PROVIDER_CHANGE = 'BEFORE_PROVIDER_CHANGE',
}
const availableProviders: {
HttpProvider: Web3BaseProviderConstructor;
WebsocketProvider: Web3BaseProviderConstructor;
} = {
HttpProvider: HttpProvider as Web3BaseProviderConstructor,
WebsocketProvider: WSProvider as Web3BaseProviderConstructor,
};
// if input was provided in params, change to data due to metamask only accepting data
const metamaskPayload = (payload: JsonRpcRequest) => {
if(Array.isArray(payload.params)) {
const params = payload.params[0] as Record<string, unknown>
if (params.input && !params.data) {
return {...payload,
params: [{...params,
data: params.data ?? params.input}]
}
}
}
return payload;
}
export class Web3RequestManager<
API extends Web3APISpec = EthExecutionAPI,
> extends Web3EventEmitter<{
[key in Web3RequestManagerEvent]: SupportedProviders<API> | undefined;
}> {
private _provider?: SupportedProviders<API>;
private readonly useRpcCallSpecification?: boolean;
public constructor(
provider?: SupportedProviders<API> | string,
useRpcCallSpecification?: boolean,
) {
super();
if (!isNullish(provider)) {
this.setProvider(provider);
}
this.useRpcCallSpecification = useRpcCallSpecification;
}
/**
* Will return all available providers
*/
public static get providers() {
return availableProviders;
}
/**
* Will return the current provider.
*
* @returns Returns the current provider
*/
public get provider() {
return this._provider;
}
/**
* Will return all available providers
*/
// eslint-disable-next-line class-methods-use-this
public get providers() {
return availableProviders;
}
/**
* Use to set provider. Provider can be a provider instance or a string.
*
* @param provider - The provider to set
*/
public setProvider(provider?: SupportedProviders<API> | string): boolean {
let newProvider: SupportedProviders<API> | undefined;
// autodetect provider
if (provider && typeof provider === 'string' && this.providers) {
// HTTP
if (/^http(s)?:\/\//i.test(provider)) {
newProvider = new this.providers.HttpProvider<API>(provider);
// WS
} else if (/^ws(s)?:\/\//i.test(provider)) {
newProvider = new this.providers.WebsocketProvider<API>(provider);
} else {
throw new ProviderError(`Can't autodetect provider for "${provider}"`);
}
} else if (isNullish(provider)) {
// In case want to unset the provider
newProvider = undefined;
} else {
newProvider = provider as SupportedProviders<API>;
}
this.emit(Web3RequestManagerEvent.BEFORE_PROVIDER_CHANGE, this._provider);
this._provider = newProvider;
this.emit(Web3RequestManagerEvent.PROVIDER_CHANGED, this._provider);
return true;
}
/**
*
* Will execute a request
*
* @param request - {@link Web3APIRequest} The request to send
*
* @returns The response of the request {@link ResponseType}. If there is error
* in the response, will throw an error
*/
public async send<
Method extends Web3APIMethod<API>,
ResponseType = Web3APIReturnType<API, Method>,
>(request: Web3APIRequest<API, Method>): Promise<ResponseType> {
const response = await this._sendRequest<Method, ResponseType>(request);
if (jsonRpc.isResponseWithResult(response)) {
return response.result;
}
throw new ResponseError(response);
}
/**
* Same as send, but, will execute a batch of requests
*
* @param request {@link JsonRpcBatchRequest} The batch request to send
*/
public async sendBatch(request: JsonRpcBatchRequest): Promise<JsonRpcBatchResponse<unknown>> {
const response = await this._sendRequest<never, never>(request);
return response as JsonRpcBatchResponse<unknown>;
}
private async _sendRequest<
Method extends Web3APIMethod<API>,
ResponseType = Web3APIReturnType<API, Method>,
>(
request: Web3APIRequest<API, Method> | JsonRpcBatchRequest,
): Promise<JsonRpcResponse<ResponseType>> {
const { provider } = this;
if (isNullish(provider)) {
throw new ProviderError(
'Provider not available. Use `.setProvider` or `.provider=` to initialize the provider.',
);
}
let payload = jsonRpc.isBatchRequest(request)
? jsonRpc.toBatchPayload(request)
: jsonRpc.toPayload(request);
if(isMetaMaskProvider(provider)){ // metamask send_transaction accepts data and not input, so we change it
if ((payload as JsonRpcRequest<ResponseType>).method === 'eth_sendTransaction'){
if(!jsonRpc.isBatchRequest(payload)){
payload = metamaskPayload(payload as JsonRpcRequest)
} else {
payload = payload.map(p => metamaskPayload(p as JsonRpcRequest))
}
}
}
if (isWeb3Provider(provider)) {
let response;
try {
response = await provider.request<Method, ResponseType>(
payload as Web3APIPayload<API, Method>,
);
} catch (error) {
// Check if the provider throw an error instead of reject with error
response = error as JsonRpcResponse<ResponseType>;
}
return this._processJsonRpcResponse(payload, response, { legacy: false, error: false });
}
if (isEIP1193Provider(provider)) {
return (provider as Web3BaseProvider<API>)
.request<Method, ResponseType>(payload as Web3APIPayload<API, Method>)
.then(
res =>
this._processJsonRpcResponse(payload, res, {
legacy: true,
error: false,
}) as JsonRpcResponseWithResult<ResponseType>,
)
.catch(error =>
this._processJsonRpcResponse(
payload,
error as JsonRpcResponse<ResponseType, unknown>,
{ legacy: true, error: true },
),
);
}
// TODO: This could be deprecated and removed.
if (isLegacyRequestProvider(provider)) {
return new Promise<JsonRpcResponse<ResponseType>>((resolve, reject) => {
const rejectWithError = (err: unknown) =>
reject(
this._processJsonRpcResponse(
payload,
err as JsonRpcResponse<ResponseType>,
{
legacy: true,
error: true,
},
),
);
const resolveWithResponse = (response: JsonRpcResponse<ResponseType>) =>
resolve(
this._processJsonRpcResponse(payload, response, {
legacy: true,
error: false,
}),
);
const result = provider.request<ResponseType>(
payload,
// a callback that is expected to be called after getting the response:
(err, response) => {
if (err) {
return rejectWithError(err);
}
return resolveWithResponse(response);
},
);
// Some providers, that follow a previous drafted version of EIP1193, has a `request` function
// that is not defined as `async`, but it returns a promise.
// Such providers would not be picked with if(isEIP1193Provider(provider)) above
// because the `request` function was not defined with `async` and so the function definition is not `AsyncFunction`.
// Like this provider: https://github.dev/NomicFoundation/hardhat/blob/62bea2600785595ba36f2105564076cf5cdf0fd8/packages/hardhat-core/src/internal/core/providers/backwards-compatibility.ts#L19
// So check if the returned result is a Promise, and resolve with it accordingly.
// Note: in this case we expect the callback provided above to never be called.
if (isPromise(result)) {
const responsePromise = result as unknown as Promise<
JsonRpcResponse<ResponseType>
>;
responsePromise.then(resolveWithResponse).catch(rejectWithError);
}
});
}
// TODO: This could be deprecated and removed.
if (isLegacySendProvider(provider)) {
return new Promise<JsonRpcResponse<ResponseType>>((resolve, reject): void => {
provider.send<ResponseType>(payload, (err, response) => {
if (err) {
return reject(
this._processJsonRpcResponse(
payload,
err as unknown as JsonRpcResponse<ResponseType>,
{
legacy: true,
error: true,
},
),
);
}
if (isNullish(response)) {
throw new ResponseError(
'' as never,
'Got a "nullish" response from provider.',
);
}
return resolve(
this._processJsonRpcResponse(payload, response, {
legacy: true,
error: false,
}),
);
});
});
}
// TODO: This could be deprecated and removed.
if (isLegacySendAsyncProvider(provider)) {
return provider
.sendAsync<ResponseType>(payload)
.then(response =>
this._processJsonRpcResponse(payload, response, { legacy: true, error: false }),
)
.catch(error =>
this._processJsonRpcResponse(payload, error as JsonRpcResponse<ResponseType>, {
legacy: true,
error: true,
}),
);
}
throw new ProviderError('Provider does not have a request or send method to use.');
}
// eslint-disable-next-line class-methods-use-this
private _processJsonRpcResponse<ResultType, ErrorType, RequestType>(
payload: JsonRpcPayload<RequestType>,
response: JsonRpcResponse<ResultType, ErrorType>,
{ legacy, error }: { legacy: boolean; error: boolean },
): JsonRpcResponse<ResultType> | never {
if (isNullish(response)) {
return this._buildResponse(
payload,
// Some providers uses "null" as valid empty response
// eslint-disable-next-line no-null/no-null
null as unknown as JsonRpcResponse<ResultType, ErrorType>,
error,
);
}
// This is the majority of the cases so check these first
// A valid JSON-RPC response with error object
if (jsonRpc.isResponseWithError<ErrorType>(response)) {
// check if its an rpc error
if (
this.useRpcCallSpecification &&
isResponseRpcError(response as JsonRpcResponseWithError)
) {
const rpcErrorResponse = response as JsonRpcResponseWithError;
// check if rpc error flag is on and response error code match an EIP-1474 or a standard rpc error code
if (rpcErrorsMap.get(rpcErrorResponse.error.code)) {
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
const Err = rpcErrorsMap.get(rpcErrorResponse.error.code)!.error;
throw new Err(rpcErrorResponse);
} else {
throw new RpcError(rpcErrorResponse);
}
} else if (!Web3RequestManager._isReverted(response)) {
throw new InvalidResponseError<ErrorType, RequestType>(response, payload);
}
}
// This is the majority of the cases so check these first
// A valid JSON-RPC response with result object
if (jsonRpc.isResponseWithResult<ResultType>(response)) {
return response;
}
if ((response as unknown) instanceof Error) {
Web3RequestManager._isReverted(response);
throw response;
}
if (!legacy && jsonRpc.isBatchRequest(payload) && jsonRpc.isBatchResponse(response)) {
return response as JsonRpcBatchResponse<ResultType>;
}
if (legacy && !error && jsonRpc.isBatchRequest(payload)) {
return response as JsonRpcBatchResponse<ResultType>;
}
if (legacy && error && jsonRpc.isBatchRequest(payload)) {
// In case of error batch response we don't want to throw Invalid response
throw response;
}
if (
legacy &&
!jsonRpc.isResponseWithError(response) &&
!jsonRpc.isResponseWithResult(response)
) {
return this._buildResponse(payload, response, error);
}
if (jsonRpc.isBatchRequest(payload) && !Array.isArray(response)) {
throw new ResponseError(response, 'Got normal response for a batch request.');
}
if (!jsonRpc.isBatchRequest(payload) && Array.isArray(response)) {
throw new ResponseError(response, 'Got batch response for a normal request.');
}
if (
(jsonRpc.isResponseWithError(response) || jsonRpc.isResponseWithResult(response)) &&
!jsonRpc.isBatchRequest(payload)
) {
if (response.id && payload.id !== response.id) {
throw new InvalidResponseError<ErrorType>(response);
}
}
throw new ResponseError(response, 'Invalid response');
}
private static _isReverted<ResultType, ErrorType>(
response: JsonRpcResponse<ResultType, ErrorType>,
): boolean {
let error: JsonRpcError | undefined;
if (jsonRpc.isResponseWithError<ErrorType>(response)) {
error = (response as JsonRpcResponseWithError).error;
} else if ((response as unknown) instanceof Error) {
error = response as unknown as JsonRpcError;
}
// This message means that there was an error while executing the code of the smart contract
// However, more processing will happen at a higher level to decode the error data,
// according to the Error ABI, if it was available as of EIP-838.
if (error?.message.includes('revert')) throw new ContractExecutionError(error);
return false;
}
// Need to use same types as _processJsonRpcResponse so have to declare as instance method
// eslint-disable-next-line class-methods-use-this
private _buildResponse<ResultType, ErrorType, RequestType>(
payload: JsonRpcPayload<RequestType>,
response: JsonRpcResponse<ResultType, ErrorType>,
error: boolean,
): JsonRpcResponse<ResultType> {
const res = {
jsonrpc: '2.0',
// eslint-disable-next-line no-nested-ternary
id: jsonRpc.isBatchRequest(payload)
? payload[0].id
: 'id' in payload
? payload.id
: // Have to use the null here explicitly
// eslint-disable-next-line no-null/no-null
null,
};
if (error) {
return {
...res,
error: response as unknown,
} as JsonRpcResponse<ResultType>;
}
return {
...res,
result: response as unknown,
} as JsonRpcResponse<ResultType>;
}
}