-
Notifications
You must be signed in to change notification settings - Fork 458
/
Copy pathPopUpService.ts
245 lines (208 loc) · 6.88 KB
/
PopUpService.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
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
import { MessageTypes, POPUP_SCRIPT_NAME } from '@fuel-wallet/types';
import type { ResponseMessage, UIEventMessage } from '@fuel-wallet/types';
import type { JSONRPCRequest } from 'json-rpc-2.0';
import { JSONRPCClient } from 'json-rpc-2.0';
import { CRXPages } from '~/systems/Core/types';
import type { DeferPromise } from '~/systems/Core/utils/promise';
import { deferPromise } from '~/systems/Core/utils/promise';
import { uniqueId } from '~/systems/Core/utils/string';
import {
closePopUp,
createPopUp,
getTabFromSender,
showPopUp,
} from '../../utils';
import { ReportErrorService } from '~/systems/Error/services/ReportErrorService';
import type { CommunicationProtocol } from './CommunicationProtocol';
import type { MessageInputs, PopUpServiceInputs } from './types';
const popups = new Map<string, PopUpService>();
export class PopUpService {
openingPromise: DeferPromise<PopUpService> | undefined;
session: string | null = null;
tabId: number | null = null;
windowId: number | null = null;
tab: chrome.tabs.Tab | null = null;
eventId?: string;
client: JSONRPCClient;
readonly communicationProtocol: CommunicationProtocol;
private timeoutId: NodeJS.Timeout | null = null;
private origin: string;
constructor(communicationProtocol: CommunicationProtocol, origin: string) {
// Bind methods to ensure correct `this` context
this.onUIEvent = this.onUIEvent.bind(this);
this.onResponse = this.onResponse.bind(this);
this.rejectOpeningPromise = this.rejectOpeningPromise.bind(this);
this.resolveOpeningPromise = this.resolveOpeningPromise.bind(this);
this.origin = origin;
this.communicationProtocol = communicationProtocol;
this.openingPromise = deferPromise<PopUpService>();
this.setTimeout();
this.client = new JSONRPCClient(this.sendRequest);
this.setupUIListeners();
}
rejectOpeningPromise(message = 'PopUp not opened!') {
if (this.openingPromise) {
this.clearTimeout();
this.openingPromise?.reject(new Error(message));
this.openingPromise = undefined;
closePopUp(this.tabId!);
}
}
resolveOpeningPromise<T extends PopUpService>(resolver: T) {
if (this.openingPromise) {
this.clearTimeout();
this.openingPromise?.resolve(resolver);
this.openingPromise = undefined;
}
}
setTimeout(delay = 5000) {
this.timeoutId = setTimeout(() => {
this.rejectOpeningPromise('PopUp timed out waiting for event');
}, delay);
}
clearTimeout() {
if (this.timeoutId) {
clearTimeout(this.timeoutId);
this.timeoutId = null;
}
}
rejectAllRequests = (id: string) => {
if (id === this.eventId) {
// Close popup on rejecting connection
closePopUp(this.tabId);
// Reject all pending requests
this.client.rejectAllPendingRequests(
'Request cancelled without user response!'
);
}
};
sendRequest = async (rpcRequest: JSONRPCRequest) => {
if (this.eventId) {
this.communicationProtocol.postMessage({
type: MessageTypes.request,
target: POPUP_SCRIPT_NAME,
id: this.eventId,
request: rpcRequest,
});
} else {
throw new Error('UI not connected!');
}
};
onResponse = (cEvent: ResponseMessage) => {
if (cEvent.id === this.eventId && cEvent.response) {
this.client.receive(cEvent.response);
}
};
setupUIListeners() {
this.communicationProtocol.once(MessageTypes.uiEvent, this.onUIEvent);
this.communicationProtocol.on(MessageTypes.response, this.onResponse);
this.communicationProtocol.on(
MessageTypes.removeConnection,
this.rejectAllRequests
);
}
removeUIListeners() {
this.communicationProtocol.off(MessageTypes.uiEvent, this.onUIEvent);
this.communicationProtocol.off(MessageTypes.response, this.onResponse);
this.communicationProtocol.off(
MessageTypes.removeConnection,
this.rejectAllRequests
);
}
onUIEvent = (message: UIEventMessage) => {
if (this.session === message.session && message.ready && message.sender) {
const tab = getTabFromSender(message.sender);
this.tab = tab!;
this.tabId = tab?.id!;
this.eventId = message.id;
this.resolveOpeningPromise(this);
}
};
static async getCurrent(origin: string) {
const currentService = popups.get(origin);
if (currentService) {
const showPopupId = await showPopUp({
tabId: currentService.tabId!,
windowId: currentService.windowId!,
});
if (showPopupId) return currentService;
}
return null;
}
static create = async (
origin: string,
pathname: string,
communicationProtocol: CommunicationProtocol
) => {
const session = uniqueId(4);
const popupService = new PopUpService(communicationProtocol, origin);
// Set current instance to memory to avoid
// Multiple instances
popups.set(origin, popupService);
const windowId = await createPopUp(
`${CRXPages.popup}?s=${session}#${pathname}`
);
popupService.session = session;
popupService.windowId = windowId!;
return popupService;
};
static open = async (
origin: string,
pathname: string,
communicationProtocol: CommunicationProtocol
) => {
let popupService = await this.getCurrent(origin);
if (!popupService) {
popupService = await PopUpService.create(
origin,
pathname,
communicationProtocol
);
}
if (!popupService.openingPromise?.promise) {
throw new Error('PopUp has no opening promise');
}
return popupService.openingPromise.promise;
};
// UI exposed methods
async requestConnection(input: MessageInputs['requestConnection']) {
return this.client.request('requestConnection', input);
}
async signMessage(input: MessageInputs['signMessage']) {
return this.client.request('signMessage', input);
}
async sendTransaction(input: MessageInputs['sendTransaction']) {
console.log('sendTransaction', input);
return this.client.request('sendTransaction', input);
}
async addAssets(input: MessageInputs['addAssets']) {
return this.client.request('addAssets', input);
}
async selectNetwork(input: PopUpServiceInputs['selectNetwork']) {
return this.client.request('selectNetwork', input);
}
async addNetwork(input: PopUpServiceInputs['addNetwork']) {
return this.client.request('addNetwork', input);
}
// Forward to extension side
async captureError(error: Error) {
try {
await this.client.request('saveError', { error });
} catch (_) {
// If forwarding fails, save error directly
await ReportErrorService.saveError(error);
}
}
destroy() {
this.clearTimeout();
this.removeUIListeners();
this.client.rejectAllPendingRequests('Service is being cleaned up');
popups.delete(this.origin);
closePopUp(this.tabId!);
}
static destroyAll() {
for (const popup of popups.values()) {
popup.destroy();
}
}
}