blob: c51462f0786412774f69aa6eddfac6a8769732d5 (
plain) (
blame)
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
|
import { JSONRPCRequestPayload, JSONRPCResponsePayload } from '@0xproject/types';
import { promisify } from '@0xproject/utils';
import * as Web3 from 'web3';
import { JSONRPCRequestPayloadWithMethod } from '../types';
/**
* A altered version of the base class Subprovider found in [web3-provider-engine](https://github.com/MetaMask/provider-engine).
* This one has an async/await `emitPayloadAsync` and also defined types.
*/
export class Subprovider {
private _engine: any;
// Ported from: https://github.com/MetaMask/provider-engine/blob/master/util/random-id.js
private static _getRandomId() {
const extraDigits = 3;
// 13 time digits
const datePart = new Date().getTime() * Math.pow(10, extraDigits);
// 3 random digits
const extraPart = Math.floor(Math.random() * Math.pow(10, extraDigits));
// 16 digits
return datePart + extraPart;
}
private static _createFinalPayload(
payload: Partial<JSONRPCRequestPayloadWithMethod>,
): Partial<JSONRPCRequestPayloadWithMethod> {
const finalPayload = {
// defaults
id: Subprovider._getRandomId(),
jsonrpc: '2.0',
params: [],
...payload,
};
return finalPayload;
}
/**
* Emits a JSON RPC payload that will then be handled by the ProviderEngine instance
* this subprovider is a part of. The payload will cascade down the subprovider middleware
* stack until finding the responsible entity for handling the request.
* @param payload JSON RPC payload
* @returns JSON RPC response payload
*/
public async emitPayloadAsync(payload: Partial<JSONRPCRequestPayloadWithMethod>): Promise<JSONRPCResponsePayload> {
const finalPayload = Subprovider._createFinalPayload(payload);
const response = await promisify<JSONRPCResponsePayload>(this._engine.sendAsync, this._engine)(finalPayload);
return response;
}
/**
* Set's the subprovider's engine to the ProviderEngine it is added to.
* This is only called within the ProviderEngine source code, do not call
* directly.
*/
public setEngine(engine: any): void {
this._engine = engine;
}
}
|