-
Notifications
You must be signed in to change notification settings - Fork 451
/
Copy pathindex.js
291 lines (261 loc) · 8.17 KB
/
index.js
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
// Copyright © 2017-2020 Trust Wallet.
//
// This file is part of Trust. The full Trust copyright notice, including
// terms governing use, modification, and redistribution, is contained in the
// file LICENSE at the root of the source code distribution tree.
"use strict";
import Web3 from "web3";
import RPCServer from "./rpc";
import ProviderRpcError from "./error";
import Utils from "./utils";
import IdMapping from "./id_mapping";
import { EventEmitter } from "events";
import isUtf8 from 'isutf8';
class TrustWeb3Provider extends EventEmitter {
constructor(config) {
super();
this.setConfig(config);
this.idMapping = new IdMapping();
this.callbacks = new Map;
this.wrapResults = new Map;
this.isTrust = true;
this.isDebug = false;
this.emitConnect(config.chainId);
}
setAddress(address) {
this.address = (address || "").toLowerCase();
this.ready = !!address;
}
setConfig(config) {
this.setAddress(config.address);
this.chainId = config.chainId;
this.rpc = new RPCServer(config.rpcUrl);
}
request(payload) {
// this points to window in methods like web3.eth.getAccounts()
var that = this;
if (!(this instanceof TrustWeb3Provider)) {
that = window.ethereum
}
return that._request(payload, false);
}
/**
* @deprecated Listen to "connect" event instead.
*/
isConnected() {
return true;
}
/**
* @deprecated Use request({method: "eth_requestAccounts"}) instead.
*/
enable() {
console.log('enable() is deprecated, please use window.ethereum.request({method: "eth_requestAccounts"}) instead.')
return this.request({ method: "eth_requestAccounts", params: [] });
}
/**
* @deprecated Use request() method instead.
*/
send(payload) {
let response = {jsonrpc: "2.0", id: payload.id};
switch(payload.method) {
case "eth_accounts":
response.result = this.eth_accounts();
break;
case "eth_coinbase":
response.result = this.eth_coinbase();
break;
case "net_version":
response.result = this.net_version();
break;
case "eth_chainId":
response.result = this.eth_chainId();
break;
default:
throw new ProviderRpcError(
4200,
`Trust does not support calling ${payload.method} synchronously without a callback. Please provide a callback parameter to call ${payload.method} asynchronously.`
);
}
return response;
}
/**
* @deprecated Use request() method instead.
*/
sendAsync(payload, callback) {
console.log('sendAsync(data, callback) is deprecated, please use window.ethereum.request(data) instead.')
// this points to window in methods like web3.eth.getAccounts()
var that = this;
if (!(this instanceof TrustWeb3Provider)) {
that = window.ethereum
}
if (Array.isArray(payload)) {
Promise.all(payload.map(that._request.bind(that)))
.then(data => callback(null, data))
.catch(error => callback(error, null));
} else {
that._request(payload)
.then(data => callback(null, data))
.catch(error => callback(error, null));
}
}
/**
* @private Internal rpc handler
*/
_request(payload, wrapResult = true) {
this.idMapping.tryIntifyId(payload);
if (this.isDebug) {
console.log(`==> _request payload ${JSON.stringify(payload)}`);
}
return new Promise((resolve, reject) => {
if (!payload.id) {
payload.id = Utils.genId();
}
this.callbacks.set(payload.id, (error, data) => {
if (error) {
reject(error);
} else {
resolve(data);
}
});
this.wrapResults.set(payload.id, wrapResult);
switch(payload.method) {
case "eth_accounts":
return this.sendResponse(payload.id, this.eth_accounts());
case "eth_coinbase":
return this.sendResponse(payload.id, this.eth_coinbase());
case "net_version":
return this.sendResponse(payload.id, this.net_version());
case "eth_chainId":
return this.sendResponse(payload.id, this.eth_chainId());
case "eth_sign":
return this.eth_sign(payload);
case "personal_sign":
return this.personal_sign(payload);
case "personal_ecRecover":
return this.personal_ecRecover(payload);
case "eth_signTypedData":
case "eth_signTypedData_v3":
return this.eth_signTypedData(payload);
case "eth_sendTransaction":
return this.eth_sendTransaction(payload);
case "eth_requestAccounts":
return this.eth_requestAccounts(payload);
case "eth_newFilter":
case "eth_newBlockFilter":
case "eth_newPendingTransactionFilter":
case "eth_uninstallFilter":
case "eth_subscribe":
throw new ProviderRpcError(
4200,
`Trust does not support calling ${payload.method}. Please use your own solution`
);
default:
// call upstream rpc
this.callbacks.delete(payload.id);
this.wrapResults.delete(payload.id);
return this.rpc.call(payload)
.then((response) => {
if (this.isDebug) {
console.log(`<== rpc response ${JSON.stringify(response)}`);
}
wrapResult ? resolve(response) : resolve(response.result);
})
.catch(reject);
}
});
}
emitConnect(chainId) {
this.emit("connect", {chainId: chainId});
}
eth_accounts() {
return this.address ? [this.address] : [];
}
eth_coinbase() {
return this.address;
}
net_version() {
return this.chainId.toString(10) || null;
}
eth_chainId() {
return "0x" + this.chainId.toString(16);
}
eth_sign(payload) {
const data = payload.params[1];
var buffer;
if ((typeof (data) === "string")) {
buffer = Utils.hexToBuffer(data);
} else {
buffer = Buffer.from(data);
}
const hex = buffer.toString('hex');
if (isUtf8(buffer)) {
this.postMessage("signPersonalMessage", payload.id, {data: hex});
} else {
this.postMessage("signMessage", payload.id, {data: hex});
}
}
personal_sign(payload) {
this.postMessage("signPersonalMessage", payload.id, {data: payload.params[0]});
}
personal_ecRecover(payload) {
this.postMessage("ecRecover", payload.id, {signature: payload.params[1], message: payload.params[0]});
}
eth_signTypedData(payload) {
this.postMessage("signTypedMessage", payload.id, {data: payload.params[1]});
}
eth_sendTransaction(payload) {
this.postMessage("signTransaction", payload.id, payload.params[0]);
}
eth_requestAccounts(payload) {
this.postMessage("requestAccounts", payload.id, {});
}
/**
* @private Internal js -> native message handler
*/
postMessage(handler, id, data) {
if (this.ready || handler === "requestAccounts") {
window.webkit.messageHandlers[handler].postMessage({
"name": handler,
"object": data,
"id": id
});
} else {
// don't forget to verify in the app
this.sendError(id, new ProviderRpcError(4100, "provider is not ready"));
}
}
/**
* @private Internal native result -> js
*/
sendResponse(id, result) {
let originId = this.idMapping.tryPopId(id) || id;
let callback = this.callbacks.get(id);
let wrapResult = this.wrapResults.get(id);
let data = {jsonrpc: "2.0", id: originId};
if (typeof result === "object" && result.jsonrpc && result.result) {
data.result = result.result;
} else {
data.result = result;
}
if (this.isDebug) {
console.log(`<== sendResponse id: ${id}, result: ${result}, data: ${JSON.stringify(data)}`);
}
if (callback) {
wrapResult ? callback(null, data) : callback(null, result);
this.callbacks.delete(id);
}
}
/**
* @private Internal native error -> js
*/
sendError(id, error) {
console.log(`<== ${id} sendError ${error}`);
let callback = this.callbacks.get(id);
if (callback) {
callback(error instanceof Error ? error : new Error(error), null);
this.callbacks.delete(id);
}
}
}
window.Trust = TrustWeb3Provider;
window.Web3 = Web3;