-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathIframeEthereumProvider.ts
More file actions
397 lines (325 loc) · 10.4 KB
/
IframeEthereumProvider.ts
File metadata and controls
397 lines (325 loc) · 10.4 KB
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
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
import {ethers} from "ethers";
// By default post to any origin
const DEFAULT_TARGET_ORIGIN = '*';
// By default timeout is 60 seconds
const DEFAULT_TIMEOUT_MILLISECONDS = 120000;
const JSON_RPC_VERSION = '2.0';
// The interface for the source of the events, typically the window.
export interface MinimalEventSourceInterface {
addEventListener(
eventType: 'message',
handler: (message: MessageEvent) => void
): void;
}
// The interface for the target of our events, typically the parent window.
export interface MinimalEventTargetInterface {
postMessage(message: any, targetOrigin?: string): void;
}
/**
* Options for constructing the iframe ethereum provider.
*/
interface IFrameEthereumProviderOptions {
// The origin to communicate with. Default '*'
targetOrigin?: string;
// How long to time out waiting for responses. Default 60 seconds.
timeoutMilliseconds?: number;
// The event source. By default we use the window. This can be mocked for tests, or it can wrap
// a different interface, e.g. workers.
eventSource?: MinimalEventSourceInterface;
// The event target. By default we use the window parent. This can be mocked for tests, or it can wrap
// a different interface, e.g. workers.
eventTarget?: MinimalEventTargetInterface;
}
/**
* This is what we store in the state to keep track of pending promises.
*/
interface PromiseCompleter<TResult, TErrorData> {
// A response was received (either error or result response).
resolve(
result:
| JsonRpcSucessfulResponseMessage<TResult>
| JsonRpcErrorResponseMessage<TErrorData>
): void;
// An error with executing the request was encountered.
reject(error: Error): void;
}
type MessageId = number | string | null;
interface JsonRpcRequestMessage<TParams = any> {
jsonrpc: '2.0';
// Optional in the request.
id?: MessageId;
method: string;
params?: TParams;
}
interface BaseJsonRpcResponseMessage {
// Required but null if not identified in request
id: MessageId;
jsonrpc: '2.0';
}
interface JsonRpcSucessfulResponseMessage<TResult = any>
extends BaseJsonRpcResponseMessage {
result: TResult;
}
interface JsonRpcError<TData = any> {
code: number;
message: string;
data?: TData;
}
interface JsonRpcErrorResponseMessage<TErrorData = any>
extends BaseJsonRpcResponseMessage {
error: JsonRpcError<TErrorData>;
}
type ReceivedMessageType =
| JsonRpcRequestMessage
| JsonRpcErrorResponseMessage
| JsonRpcSucessfulResponseMessage;
/**
* We return a random number between the 0 and the maximum safe integer so that we always generate a unique identifier,
* across all communication channels.
*/
function getUniqueId(): number {
return Math.floor(Math.random() * Number.MAX_SAFE_INTEGER);
}
export type IFrameEthereumProviderEventTypes =
| 'connect'
| 'close'
| 'notification'
| 'chainChanged'
| 'networkChanged'
| 'accountsChanged';
/**
* Export the type information about the different events that are emitted.
*/
export interface IFrameEthereumProvider {
on(event: 'connect', handler: () => void): this;
on(event: 'close', handler: (code: number, reason: string) => void): this;
on(event: 'notification', handler: (result: any) => void): this;
on(event: 'chainChanged', handler: (chainId: string) => void): this;
on(event: 'networkChanged', handler: (networkId: string) => void): this;
on(event: 'accountsChanged', handler: (accounts: string[]) => void): this;
}
/**
* Represents an error in an RPC returned from the event source. Always contains a code and a reason. The message
* is constructed from both.
*/
class RpcError extends Error implements JsonRpcError {
public readonly isRpcError: true = true;
public readonly code: number;
public readonly data: any;
constructor(props: JsonRpcError) {
super(props.message);
this.code = props.code;
this.data = props.data;
}
}
/**
* This is the primary artifact of this library.
*/
export class IFrameEthereumProvider implements ethers.Eip1193Provider {
_isSigner = true;
/**
* Differentiate this provider from other providers by providing an isIFrame property that always returns true.
*/
public get isIFrame(): true {
return true;
}
/**
* Always return this for currentProvider.
*/
public get currentProvider(): IFrameEthereumProvider {
return this;
}
private readonly targetOrigin: string;
private readonly timeoutMilliseconds: number;
private readonly eventSource: MinimalEventSourceInterface;
private readonly eventTarget: MinimalEventTargetInterface;
private readonly completers: {
[id: string]: PromiseCompleter<any, any>;
} = {};
private gaCurrentWallet = null;
public constructor({
targetOrigin = DEFAULT_TARGET_ORIGIN,
timeoutMilliseconds = DEFAULT_TIMEOUT_MILLISECONDS,
eventSource = window,
eventTarget = window.opener ?? window.parent,
}: IFrameEthereumProviderOptions = {}) {
// Call super for `this` to be defined
//super();
this.targetOrigin = targetOrigin;
this.timeoutMilliseconds = timeoutMilliseconds;
this.eventSource = eventSource;
this.eventTarget = eventTarget;
// Listen for messages from the event source.
this.eventSource.addEventListener('message', this.handleEventSourceMessage);
}
/**
* Helper method that handles transport and request wrapping
* @param method method to execute
* @param params params to pass the method
*/
private async execute<TParams, TResult, TErrorData>(
method: string,
params?: TParams
): Promise<
| JsonRpcSucessfulResponseMessage<TResult>
| JsonRpcErrorResponseMessage<TErrorData>
> {
const id = getUniqueId();
const payload: JsonRpcRequestMessage = {
jsonrpc: JSON_RPC_VERSION,
id,
method,
...(typeof params === 'undefined' ? null : { params }),
};
const promise = new Promise<
| JsonRpcSucessfulResponseMessage<TResult>
| JsonRpcErrorResponseMessage<TErrorData>
>((resolve, reject) => (this.completers[id] = { resolve, reject }));
// Send the JSON RPC to the event source.
this.eventTarget.postMessage(payload, this.targetOrigin);
console.log("[IFRAME_RPC] request: ", payload);
// Delete the completer within the timeout and reject the promise.
setTimeout(() => {
if (this.completers[id]) {
this.completers[id].reject(
new Error(
`RPC ID "${id}" timed out after ${this.timeoutMilliseconds} milliseconds`
)
);
delete this.completers[id];
}
}, this.timeoutMilliseconds);
return promise;
}
/**
* Send the JSON RPC and return the result.
* @param request
* @param callback
*/
public send(request: {method: string, params?: Array<any>}, callback: (error: any, response: any) => void) {
this.execute(request.method, request.params).then(response => {
if ('error' in response) {
callback(response.error.code + ": " + response.error.message, null);
} else {
callback(null, response.result);
}
});
}
/**
* Backwards compatibility method for web3.
* @param request payload to send to the provider
* @param callback callback to be called when the provider resolves
*/
public async sendAsync(
request: {method: string, params?: Array<any>}, callback: (error: any, response: any) => void
) {
try {
const result = await this.execute(request.method, request.params);
callback(null, result);
} catch (error) {
callback(error.code + ": " + error.message, null);
}
}
/**
* Handle a message on the event source.
* @param event message event that will be processed by the provider
*/
private handleEventSourceMessage = (event: MessageEvent) => {
if (this.targetOrigin !== "*" && event.origin.indexOf(this.targetOrigin) !== 0)
return;
const data = event.data;
// No data to parse, skip.
if (!data) {
return;
}
const message = data as ReceivedMessageType;
// Always expect jsonrpc to be set to '2.0'
if (message.jsonrpc !== JSON_RPC_VERSION) {
return;
}
console.log("[IFRAME_RPC] response received: ", data);
// If the message has an ID, it is possibly a response message
if (typeof message.id !== 'undefined' && message.id !== null) {
const completer = this.completers['' + message.id];
// True if we haven't timed out and this is a response to a message we sent.
if (completer) {
// Handle pending promise
if ('error' in message || 'result' in message) {
if (
window.gtag &&
'result' in message &&
'method' in message &&
message.method === "eth_accounts"
) {
if (message.result?.[0] && message.result?.[0] != this.gaCurrentWallet){
this.gaCurrentWallet = message.result?.[0];
window.gtag('set', {
'wallet_address2': "evm:" + this.gaCurrentWallet,
'wallet_name': "iframe-provider"
});
window.gtag('event', 'wallet_connected', {
'wallet_address2': "evm:" + this.gaCurrentWallet,
'wallet_name': "iframe-provider"
});
}
}
completer.resolve(message);
} else {
completer.reject(
new Error('Response from provider did not have error or result key')
);
}
delete this.completers[message.id];
}
}
// If the method is a request from the parent window, it is likely a subscription.
/*if ('method' in message) {
switch (message.method) {
case 'notification':
this.emitNotification(message.params);
break;
case 'connect':
this.emitConnect();
break;
case 'close':
this.emitClose(message.params[0], message.params[1]);
break;
case 'chainChanged':
this.emitChainChanged(message.params[0]);
break;
case 'networkChanged':
this.emitNetworkChanged(message.params[0]);
break;
case 'accountsChanged':
this.emitAccountsChanged(message.params[0]);
break;
}
}*/
};
async request(request: { method: string; params?: Array<any> | Record<string, any> }): Promise<any> {
const response = await this.execute(request.method, request.params);
if ("error" in response) {
throw new RpcError(response.error);
}
return response.result;
}
/*private emitNotification(result: any) {
this.emit('notification', result);
}
private emitConnect() {
this.emit('connect');
}
private emitClose(code: number, reason: string) {
this.emit('close', code, reason);
}
private emitChainChanged(chainId: string) {
this.emit('chainChanged', chainId);
}
private emitNetworkChanged(networkId: string) {
this.emit('networkChanged', networkId);
}
private emitAccountsChanged(accounts: string[]) {
this.enabled = Promise.resolve(accounts);
this.emit('accountsChanged', accounts);
}*/
}