-
-
Notifications
You must be signed in to change notification settings - Fork 283
/
Copy pathindex.ts
367 lines (310 loc) · 11 KB
/
index.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
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
import { CustomError } from '@trezor/blockchain-link-types/src/constants/errors';
import { MESSAGES, RESPONSES } from '@trezor/blockchain-link-types/src/constants';
import {
transformUtxos,
transformAccountInfo,
transformTransaction,
} from '@trezor/blockchain-link-utils/src/blockfrost';
import type { SubscriptionAccountInfo } from '@trezor/blockchain-link-types/src/common';
import type { Response } from '@trezor/blockchain-link-types';
import type {
BlockfrostTransaction,
BlockContent,
} from '@trezor/blockchain-link-types/src/blockfrost';
import type * as MessageTypes from '@trezor/blockchain-link-types/src/messages';
import { BlockfrostAPI } from './websocket';
import { BaseWorker, CONTEXT, ContextType } from '../baseWorker';
type Context = ContextType<BlockfrostAPI>;
type Request<T> = T & Context;
const getInfo = async (request: Request<MessageTypes.GetInfo>) => {
const api = await request.connect();
const info = await api.getServerInfo();
return {
type: RESPONSES.GET_INFO,
payload: {
url: api.options.url,
...info,
},
} as const;
};
const getBlockHash = async (request: Request<MessageTypes.GetBlockHash>) => {
const api = await request.connect();
const blockMessage = await api.getBlockHash(request.payload);
return {
type: RESPONSES.GET_BLOCK_HASH,
payload: blockMessage.hash,
} as const;
};
const getAccountBalanceHistory = async (
request: Request<MessageTypes.GetAccountBalanceHistory>,
) => {
const socket = await request.connect();
const history = await socket.getAccountBalanceHistory(request.payload);
return {
type: RESPONSES.GET_ACCOUNT_BALANCE_HISTORY,
payload: history,
} as const;
};
const getTransaction = async (request: Request<MessageTypes.GetTransaction>) => {
const api = await request.connect();
const txData = await api.getTransaction(request.payload);
const tx = transformTransaction({ txData });
return {
type: RESPONSES.GET_TRANSACTION,
payload: tx,
} as const;
};
const estimateFee = async (request: Request<MessageTypes.EstimateFee>) => {
const api = await request.connect();
const resp = await api.estimateFee(request.payload);
const feeOptions: { feePerUnit: string }[] = [];
feeOptions.push({ feePerUnit: resp.lovelacePerByte.toString() });
return {
type: RESPONSES.ESTIMATE_FEE,
payload: feeOptions,
} as const;
};
const pushTransaction = async (request: Request<MessageTypes.PushTransaction>) => {
const api = await request.connect();
const payload = await api.pushTransaction(request.payload);
return {
type: RESPONSES.PUSH_TRANSACTION,
payload,
} as const;
};
const getAccountInfo = async (request: Request<MessageTypes.GetAccountInfo>) => {
const api = await request.connect();
const info = await api.getAccountInfo(request.payload);
return {
type: RESPONSES.GET_ACCOUNT_INFO,
payload: transformAccountInfo(info),
} as const;
};
const getAccountUtxo = async (request: Request<MessageTypes.GetAccountUtxo>) => {
const api = await request.connect();
const utxos = await api.getAccountUtxo(request.payload);
return {
type: RESPONSES.GET_ACCOUNT_UTXO,
payload: transformUtxos(utxos),
} as const;
};
const onNewBlock = ({ post }: Context, event: BlockContent) => {
post({
id: -1,
type: RESPONSES.NOTIFICATION,
payload: {
type: 'block',
payload: {
blockHeight: event.height || 0,
blockHash: event.hash,
},
},
});
};
const onTransaction = ({ state, post }: Context, event: BlockfrostTransaction) => {
const descriptor = event.address;
const account = state.getAccount(descriptor);
post({
id: -1,
type: RESPONSES.NOTIFICATION,
payload: {
type: 'notification',
payload: {
descriptor: account ? account.descriptor : descriptor,
tx: account
? transformTransaction(event, account.addresses ?? account.descriptor)
: transformTransaction(event, descriptor),
},
},
});
};
const subscribeBlock = async (ctx: Context) => {
if (ctx.state.getSubscription('block')) return { subscribed: true };
const api = await ctx.connect();
ctx.state.addSubscription('block');
api.on('block', ev => onNewBlock(ctx, ev));
return api.subscribeBlock();
};
const subscribeAccounts = async (ctx: Context, accounts: SubscriptionAccountInfo[]) => {
const api = await ctx.connect();
const { state } = ctx;
state.addAccounts(accounts);
if (!state.getSubscription('notification')) {
api.on('notification', ev => onTransaction(ctx, ev));
state.addSubscription('notification');
}
return api.subscribeAddresses(state.getAddresses());
};
const subscribeAddresses = async (ctx: Context, addresses: string[]) => {
const api = await ctx.connect();
const { state } = ctx;
state.addAddresses(addresses);
if (!state.getSubscription('notification')) {
api.on('notification', ev => onTransaction(ctx, ev));
state.addSubscription('notification');
}
return api.subscribeAddresses(state.getAddresses());
};
const subscribe = async (request: Request<MessageTypes.Subscribe>) => {
const { payload } = request;
let response: { subscribed: boolean };
if (payload.type === 'accounts') {
response = await subscribeAccounts(request, payload.accounts);
} else if (payload.type === 'addresses') {
response = await subscribeAddresses(request, payload.addresses);
} else if (payload.type === 'block') {
response = await subscribeBlock(request);
} else {
throw new CustomError('invalid_param', '+type');
}
return {
type: RESPONSES.SUBSCRIBE,
payload: response,
} as const;
};
const unsubscribeBlock = async ({ state, connect }: Context) => {
if (!state.getSubscription('block')) return { subscribed: false };
const api = await connect();
api.removeAllListeners('block');
state.removeSubscription('block');
return api.unsubscribeBlock();
};
const unsubscribeAccounts = async (
{ state, connect }: Context,
accounts?: SubscriptionAccountInfo[],
) => {
state.removeAccounts(accounts || state.getAccounts());
const api = await connect();
const subscribed = state.getAddresses();
if (subscribed.length < 1) {
// there are no subscribed addresses left
// remove listeners
api.removeAllListeners('notification');
state.removeSubscription('notification');
return api.unsubscribeAddresses();
}
// subscribe remained addresses
return api.subscribeAddresses(subscribed);
};
const unsubscribeAddresses = async ({ state, connect }: Context, addresses?: string[]) => {
const socket = await connect();
// remove accounts
if (!addresses) {
state.removeAccounts(state.getAccounts());
}
const subscribed = state.removeAddresses(addresses || state.getAddresses());
if (subscribed.length < 1) {
// there are no subscribed addresses left
// remove listeners
socket.removeAllListeners('notification');
state.removeSubscription('notification');
return socket.unsubscribeAddresses();
}
// subscribe remained addresses
return socket.subscribeAddresses(subscribed);
};
const unsubscribe = async (request: Request<MessageTypes.Unsubscribe>) => {
const { payload } = request;
let response: { subscribed: boolean };
if (payload.type === 'accounts') {
response = await unsubscribeAccounts(request, payload.accounts);
} else if (payload.type === 'addresses') {
response = await unsubscribeAddresses(request, payload.addresses);
} else if (payload.type === 'block') {
response = await unsubscribeBlock(request);
} else {
throw new CustomError('invalid_param', '+type');
}
return {
type: RESPONSES.UNSUBSCRIBE,
payload: response,
} as const;
};
const onRequest = (request: Request<MessageTypes.Message>) => {
switch (request.type) {
case MESSAGES.GET_INFO:
return getInfo(request);
case MESSAGES.GET_BLOCK_HASH:
return getBlockHash(request);
case MESSAGES.GET_ACCOUNT_BALANCE_HISTORY:
return getAccountBalanceHistory(request);
case MESSAGES.GET_ACCOUNT_INFO:
return getAccountInfo(request);
case MESSAGES.GET_ACCOUNT_UTXO:
return getAccountUtxo(request);
case MESSAGES.GET_TRANSACTION:
return getTransaction(request);
case MESSAGES.ESTIMATE_FEE:
return estimateFee(request);
case MESSAGES.PUSH_TRANSACTION:
return pushTransaction(request);
case MESSAGES.SUBSCRIBE:
return subscribe(request);
case MESSAGES.UNSUBSCRIBE:
return unsubscribe(request);
default:
throw new CustomError('worker_unknown_request', `+${request.type}`);
}
};
class BlockfrostWorker extends BaseWorker<BlockfrostAPI> {
cleanup() {
if (this.api) {
this.api.dispose();
this.api.removeAllListeners();
}
super.cleanup();
}
protected isConnected(api: BlockfrostAPI | undefined): api is BlockfrostAPI {
return api?.isConnected() ?? false;
}
async tryConnect(url: string): Promise<BlockfrostAPI> {
const { timeout, pingTimeout, keepAlive } = this.settings;
const api = new BlockfrostAPI({
url,
timeout,
pingTimeout,
keepAlive,
agent: this.proxyAgent,
});
await api.connect();
api.on('disconnected', () => {
this.post({ id: -1, type: RESPONSES.DISCONNECTED, payload: true });
this.cleanup();
});
this.post({
id: -1,
type: RESPONSES.CONNECTED,
});
return api;
}
disconnect() {
if (this.api) {
this.api.disconnect();
}
}
async messageHandler(event: { data: MessageTypes.Message }) {
try {
// skip processed messages
if (await super.messageHandler(event)) return true;
const request: Request<MessageTypes.Message> = {
...event.data,
connect: () => this.connect(),
post: (data: Response) => this.post(data),
state: this.state,
};
const response = await onRequest(request);
this.post({ id: event.data.id, ...response });
} catch (error) {
this.errorResponse(event.data.id, error);
}
}
}
// export worker factory used in src/index
export default function Blockfrost() {
return new BlockfrostWorker();
}
if (CONTEXT === 'worker') {
// Initialize module if script is running in worker context
const module = new BlockfrostWorker();
onmessage = module.messageHandler.bind(module);
}