aboutsummaryrefslogtreecommitdiffstats
path: root/packages/website/ts/subproviders/redundant_rpc_subprovider.ts
blob: d540e6e7b468613cde55f71b933e7d38a7cff98f (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
import {promisify} from '@0xproject/utils';
import * as _ from 'lodash';
import {JSONRPCPayload} from 'ts/types';
import RpcSubprovider = require('web3-provider-engine/subproviders/rpc');
import Subprovider = require('web3-provider-engine/subproviders/subprovider');

export class RedundantRPCSubprovider extends Subprovider {
    private rpcs: RpcSubprovider[];
    private static async firstSuccessAsync(
        rpcs: RpcSubprovider[], payload: JSONRPCPayload, next: () => void,
    ): Promise<any> {
        let lastErr;
        for (const rpc of rpcs) {
            try {
                const data = await promisify(rpc.handleRequest.bind(rpc))(payload, next);
                return data;
            } catch (err) {
                lastErr = err;
                continue;
            }
        }
        throw Error(lastErr);
    }
    constructor(endpoints: string[]) {
        super();
        this.rpcs = _.map(endpoints, endpoint => {
            return new RpcSubprovider({
                rpcUrl: endpoint,
            });
        });
    }
    public async handleRequest(payload: JSONRPCPayload, next: () => void,
                               end: (err?: Error, data?: any) =>  void): Promise<void> {
        const rpcsCopy = this.rpcs.slice();
        try {
            const data = await RedundantRPCSubprovider.firstSuccessAsync(rpcsCopy, payload, next);
            end(null, data);
        } catch (err) {
            end(err);
        }

    }
}