-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrequestsManager.ts
250 lines (218 loc) · 7.49 KB
/
requestsManager.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
246
247
248
249
250
import { emitSnapKeyringEvent, KeyringEvent } from '@metamask/keyring-api';
import type { Json } from '@metamask/snaps-sdk';
import { renderErrorMessage } from './features/error-message/render';
import { TransactionHelper } from './lib/helpers/transaction';
import type { ICustodianApi } from './lib/types';
import type {
CustodialSnapRequest,
KeyringState,
SignedMessageRequest,
TransactionRequest,
} from './lib/types/CustodialKeyring';
import type { CustodialKeyringAccount } from './lib/types/CustodialKeyringAccount';
import type { EthSignTransactionRequest } from './lib/types/EthSignTransactionRequest';
import logger from './logger';
import { saveState } from './stateManagement';
type KeyringFacade = {
getCustodianApiForAddress: (address: string) => Promise<ICustodianApi>;
getAccount: (accountId: string) => Promise<CustodialKeyringAccount>;
};
export class RequestManager {
#state: KeyringState;
#keyringFacade: KeyringFacade;
constructor(state: KeyringState, keyringFacade: KeyringFacade) {
this.#state = state;
this.#keyringFacade = keyringFacade;
}
listRequests(): CustodialSnapRequest<
SignedMessageRequest | TransactionRequest
>[] {
return Object.values(this.#state.requests);
}
async addPendingRequest(
request: CustodialSnapRequest<SignedMessageRequest | TransactionRequest>,
): Promise<void> {
this.#state.requests[request.keyringRequest.id] = request;
await saveState(this.#state);
}
async removePendingRequest(id: string): Promise<void> {
delete this.#state.requests[id];
await saveState(this.#state);
}
async getChainIdFromPendingRequest(id: string): Promise<string> {
const transactionRequest = this.getRequestParams(id);
if (!transactionRequest.chainId) {
throw new Error(`Request ${id} has no chainId`);
}
return transactionRequest.chainId;
}
getRequestParams(id: string): EthSignTransactionRequest {
if (!this.#state.requests[id]) {
throw new Error(`Request ${id} not found`);
}
const requestParams =
this.#state.requests[id]?.keyringRequest.request.params;
if (!Array.isArray(requestParams) || requestParams.length === 0) {
throw new Error(`Request ${id} has invalid params`);
}
return requestParams[0] as EthSignTransactionRequest;
}
async clearAllRequests(): Promise<void> {
this.#state.requests = {};
await saveState(this.#state);
}
async poll(): Promise<void> {
const pendingRequests = this.listRequests().filter(
(request) => !request.fulfilled,
);
for (const request of pendingRequests) {
if (request.type === 'message') {
try {
await this.pollSignedMessage(
request.keyringRequest.id,
request as CustodialSnapRequest<SignedMessageRequest>,
);
} catch (error: any) {
logger.info(
`Error polling signed message request ${request.keyringRequest.id}`,
);
logger.error(error);
}
} else if (request.type === 'transaction') {
try {
await this.pollTransaction(
request.keyringRequest.id,
request as CustodialSnapRequest<TransactionRequest>,
);
} catch (error: any) {
logger.info(
`Error polling transaction request ${request.keyringRequest.id}`,
);
console.error(error);
logger.error(error);
}
}
}
}
async pollTransaction(
requestId: string,
request: CustodialSnapRequest<TransactionRequest>,
): Promise<void> {
const { account } = request.keyringRequest;
const { address } = await this.#keyringFacade.getAccount(account);
const custodianApi = await this.#keyringFacade.getCustodianApiForAddress(
address,
);
const { custodianTransactionId } = request.transaction;
const transactionResponse = await custodianApi.getTransaction(
address,
custodianTransactionId,
);
if (
transactionResponse?.transactionStatus.finished &&
!transactionResponse.transactionStatus.success
) {
await this.emitRejectedEvent(requestId);
await this.removePendingRequest(requestId);
return;
}
if (
(transactionResponse?.transactionStatus.finished &&
transactionResponse.transactionStatus.success) ||
transactionResponse?.signedRawTransaction
) {
const chainId = await this.getChainIdFromPendingRequest(requestId);
const signature = await TransactionHelper.getTransactionSignature(
transactionResponse,
chainId,
);
const validationResult = TransactionHelper.validateTransaction(
this.getRequestParams(requestId),
transactionResponse,
);
if (!validationResult.isValid) {
// First show a dialog with the error message
if (validationResult.error) {
const errorMessage = `Transaction ${custodianTransactionId} was signed by custodian but failed validation: ${validationResult.error}`;
await renderErrorMessage(errorMessage);
}
await this.emitRejectedEvent(requestId);
await this.removePendingRequest(requestId);
return;
}
const updatedTransaction = {
...request,
fulfilled: true,
result: signature,
};
Object.assign(request, updatedTransaction);
await this.emitApprovedEvent(requestId, signature);
await this.removePendingRequest(requestId);
}
}
async pollSignedMessage(
requestId: string,
request: CustodialSnapRequest<SignedMessageRequest>,
): Promise<void> {
const { account } = request.keyringRequest;
const { address } = await this.#keyringFacade.getAccount(account);
const custodianApi = await this.#keyringFacade.getCustodianApiForAddress(
address,
);
const signedMessageResponse = await custodianApi.getSignedMessage(
address,
request.message.id,
);
if (signedMessageResponse?.status?.finished) {
if (signedMessageResponse.status.success) {
const updatedSignedMessage = {
...request,
fulfilled: true,
result: signedMessageResponse.signature,
};
Object.assign(request, updatedSignedMessage);
await this.emitApprovedEvent(
requestId,
signedMessageResponse.signature,
);
} else {
await this.emitRejectedEvent(requestId);
}
await this.removePendingRequest(requestId);
}
}
async emitApprovedEvent(id: string, result: Json): Promise<void> {
try {
await emitSnapKeyringEvent(snap, KeyringEvent.RequestApproved, {
id,
result,
});
} catch (error: any) {
/*
* we are looking for Request '${id}' not found, that means the request
* was removed from the snap keyring before we could emit the event
* So we should remove the request from the state and not throw an error
*/
if (error.message.includes(`Request '${id}' not found`)) {
logger.info(`Request '${id}' not found, removing from state`);
await this.removePendingRequest(id);
} else {
throw error;
}
}
}
async emitRejectedEvent(id: string): Promise<void> {
try {
await emitSnapKeyringEvent(snap, KeyringEvent.RequestRejected, {
id,
});
} catch (error: any) {
if (error.message.includes(`Request '${id}' not found`)) {
logger.info(`Request '${id}' not found, removing from state`);
await this.removePendingRequest(id);
} else {
throw error;
}
}
}
}