-
-
Notifications
You must be signed in to change notification settings - Fork 1.9k
/
web3-provider.ts
94 lines (74 loc) · 2.72 KB
/
web3-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
'use strict';
import { JsonRpcProvider } from './json-rpc-provider';
import { defineReadOnly } from '../utils/properties';
// Imported Types
import { Networkish } from '../utils/networks';
import * as errors from '../errors';
// Exported Types
export type AsyncSendable = {
isMetaMask?: boolean;
host?: string;
path?: string;
sendAsync?: (request: any, callback: (error: any, response: any) => void) => void
send?: (request: any, callback: (error: any, response: any) => void) => void
}
/*
@TODO
utils.defineProperty(Web3Signer, 'onchange', {
});
*/
export class Web3Provider extends JsonRpcProvider {
readonly _web3Provider: AsyncSendable;
private _sendAsync: (request: any, callback: (error: any, response: any) => void) => void;
constructor(web3Provider: AsyncSendable, network?: Networkish) {
// HTTP has a host; IPC has a path.
super(web3Provider.host || web3Provider.path || '', network);
errors.checkNew(this, Web3Provider);
if (web3Provider) {
if (web3Provider.sendAsync) {
this._sendAsync = web3Provider.sendAsync.bind(web3Provider);
} else if (web3Provider.send) {
this._sendAsync = web3Provider.send.bind(web3Provider);
}
}
if (!web3Provider || !this._sendAsync) {
errors.throwError(
'invalid web3Provider',
errors.INVALID_ARGUMENT,
{ arg: 'web3Provider', value: web3Provider }
);
}
defineReadOnly(this, '_web3Provider', web3Provider);
}
send(method: string, params: any): Promise<any> {
// Metamask complains about eth_sign (and on some versions hangs)
if (method == 'eth_sign' && this._web3Provider.isMetaMask) {
// https://github.com/ethereum/go-ethereum/wiki/Management-APIs#personal_sign
method = 'personal_sign';
params = [ params[1], params[0] ];
}
return new Promise((resolve, reject) => {
var request = {
method: method,
params: params,
id: 42,
jsonrpc: "2.0"
};
this._sendAsync(request, function(error, result) {
if (error) {
reject(error);
return;
}
if (result.error) {
// @TODO: not any
var error: any = new Error(result.error.message);
error.code = result.error.code;
error.data = result.error.data;
reject(error);
return;
}
resolve(result.result);
});
});
}
}