aboutsummaryrefslogtreecommitdiffstats
path: root/packages/subproviders/src/subproviders/injected_web3.ts
blob: 6d4e2b27b2942300ef5247f8c5ccb01e0f408d62 (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
import * as _ from 'lodash';
import * as Web3 from 'web3';

import { Subprovider } from './subprovider';

/*
 * This class implements the web3-provider-engine subprovider interface and forwards
 * requests involving user accounts (getAccounts, sendTransaction, etc...) to the injected
 * provider instance in their browser.
 * Source: https://github.com/MetaMask/provider-engine/blob/master/subproviders/subprovider.js
 */
export class InjectedWeb3Subprovider extends Subprovider {
    private _injectedWeb3: Web3;
    constructor(subprovider: Web3.Provider) {
        super();
        this._injectedWeb3 = new Web3(subprovider);
    }
    public handleRequest(
        payload: Web3.JSONRPCRequestPayload,
        next: () => void,
        end: (err: Error | null, result: any) => void,
    ) {
        switch (payload.method) {
            case 'web3_clientVersion':
                this._injectedWeb3.version.getNode(end);
                return;
            case 'eth_accounts':
                this._injectedWeb3.eth.getAccounts(end);
                return;

            case 'eth_sendTransaction':
                const [txParams] = payload.params;
                this._injectedWeb3.eth.sendTransaction(txParams, end);
                return;

            case 'eth_sign':
                const [address, message] = payload.params;
                this._injectedWeb3.eth.sign(address, message, end);
                return;

            default:
                next();
                return;
        }
    }
}