-
Notifications
You must be signed in to change notification settings - Fork 12
/
index.ts
420 lines (387 loc) · 12.2 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
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
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
import config from "config";
import http from "http";
import express from "express";
import * as websockets from "ws";
import { Request, Response } from "express";
import { Pool } from "pg";
// eslint-disable-next-line
const semverCompare = require("semver-compare");
import { connectionHandler } from "./ws-server";
import {
applyMiddleware,
applyRoutes,
Route,
UtilEither,
errMsgs,
} from "./utils";
import * as utils from "./utils";
import * as middleware from "./middleware";
import { askBestBlock } from "./services/bestblock";
import { utxoForAddresses } from "./services/utxoForAddress";
import {
askBlockNumByHash,
askBlockNumByTxHash,
askTransactionHistory,
} from "./services/transactionHistory";
import type { BlockNumByTxHashFrag } from "./services/transactionHistory";
import { filterUsedAddresses } from "./services/filterUsedAddress";
import { askUtxoSumForAddresses } from "./services/utxoSumForAddress";
import { handleSignedTx } from "./services/signedTransaction";
import { handlePoolInfo } from "./services/poolInfo";
import { handleGetAccountState } from "./services/accountState";
import { handleGetRegHistory } from "./services/regHistory";
import { handleGetRewardHistory } from "./services/rewardHistory";
import { handleGetMultiAssetSupply } from "./services/multiAssetSupply";
import { handleGetMultiAssetTxMintMetadata } from "./services/multiAssetTxMint";
import { handleTxStatus } from "./services/txStatus";
import { handleGetTxIO } from "./services/txIO";
import { handleTipStatusGet, handleTipStatusPost } from "./services/tipStatus";
import { handleGetTransactions } from "./services/transactions";
import { handlePolicyIdExists } from "./services/policyIdExists";
import { HealthChecker } from "./HealthChecker";
import { createCertificatesView } from "./Transactions/certificates";
import { createTransactionOutputView } from "./Transactions/output";
import { createValidUtxosView } from "./Transactions/valid_utxos_view";
import { createTransactionUtilityFunctions } from "./Transactions/userDefinedFunctions";
import { poolDelegationHistory } from "./services/poolHistory";
import { handleGetCardanoWalletPools } from "./services/cardanoWallet";
import { handleMessageBoard } from "./services/messageBoard";
import { handleMessageDirect } from "./services/messageDirect";
import { handleOracleDatapoint } from "./services/oracleDatapoint";
import { handleOracleTicker } from "./services/oracleTicker";
import { mapTransactionFragsToResponse } from "./utils/mappers";
const pool = new Pool({
user: config.get("db.user"),
host: config.get("db.host"),
database: config.get("db.database"),
password: config.get("db.password"),
port: config.get("db.port"),
});
createCertificatesView(pool);
createValidUtxosView(pool);
createTransactionOutputView(pool);
createTransactionUtilityFunctions(pool);
const healthChecker = new HealthChecker(() => askBestBlock(pool));
const router = express();
const middlewares = [
middleware.handleCors,
middleware.handleBodyRequestParsing,
middleware.handleCompression,
];
applyMiddleware(middlewares, router);
const port: number = config.get("server.port");
const addressesRequestLimit: number = config.get("server.addressRequestLimit");
const apiResponseLimit: number = config.get("server.apiResponseLimit");
const bestBlock = (pool: Pool) => async (_req: Request, res: Response) => {
const result = await askBestBlock(pool);
switch (result.kind) {
case "ok": {
const cardano = result.value;
res.send(cardano);
return;
}
case "error":
throw new Error(result.errMsg);
default:
return utils.assertNever(result);
}
};
const utxoSumForAddresses = async (req: Request, res: Response) => {
if (!req.body || !req.body.addresses) {
throw new Error("error, no addresses.");
}
const verifiedAddresses = utils.validateAddressesReq(
addressesRequestLimit,
req.body.addresses
);
switch (verifiedAddresses.kind) {
case "ok": {
const result = await askUtxoSumForAddresses(
pool,
verifiedAddresses.value
);
switch (result.kind) {
case "ok":
res.send(result.value);
return;
case "error":
throw new Error(result.errMsg);
default:
return utils.assertNever(result);
}
}
case "error":
throw new Error(verifiedAddresses.errMsg);
default:
return utils.assertNever(verifiedAddresses);
}
};
const getOrDefaultAfterParam = (
result: UtilEither<BlockNumByTxHashFrag>
): {
blockNumber: number;
txIndex: number;
} => {
if (result.kind !== "ok") {
if (result.errMsg === errMsgs.noValue) {
// default value since this is an optional field
return {
blockNumber: -1,
txIndex: -1,
};
}
throw new Error(result.errMsg);
}
return {
blockNumber: result.value.block.number,
txIndex: result.value.blockIndex,
};
};
const txHistory = async (req: Request, res: Response) => {
if (!req.body) {
throw new Error("error, no body");
}
const verifiedBody = utils.validateHistoryReq(
addressesRequestLimit,
apiResponseLimit,
req.body
);
switch (verifiedBody.kind) {
case "ok": {
const body = verifiedBody.value;
const limit = body.limit || apiResponseLimit;
const [referenceTx, referenceBlock] =
(body.after && [body.after.tx, body.after.block]) || [];
const referenceBestBlock = body.untilBlock;
const untilBlockNum = await askBlockNumByHash(pool, referenceBestBlock);
const afterBlockInfo = await askBlockNumByTxHash(pool, referenceTx);
if (
untilBlockNum.kind === "error" &&
untilBlockNum.errMsg === utils.errMsgs.noValue
) {
throw new Error("REFERENCE_BEST_BLOCK_MISMATCH");
}
if (
afterBlockInfo.kind === "error" &&
typeof referenceTx !== "undefined"
) {
throw new Error("REFERENCE_TX_NOT_FOUND");
}
if (
afterBlockInfo.kind === "ok" &&
afterBlockInfo.value.block.hash !== referenceBlock
) {
throw new Error("REFERENCE_BLOCK_MISMATCH");
}
// when things are running smoothly, we would never hit this case case
if (untilBlockNum.kind !== "ok") {
throw new Error(untilBlockNum.errMsg);
}
const afterInfo = getOrDefaultAfterParam(afterBlockInfo);
const maybeTxs = await askTransactionHistory(
pool,
limit,
body.addresses,
afterInfo,
untilBlockNum.value
);
switch (maybeTxs.kind) {
case "ok": {
const txs = mapTransactionFragsToResponse(maybeTxs.value);
res.send(txs);
return;
}
case "error":
throw new Error(maybeTxs.errMsg);
default:
return utils.assertNever(maybeTxs);
}
}
case "error":
throw new Error(verifiedBody.errMsg);
default:
return utils.assertNever(verifiedBody);
}
};
const getStatus = async (req: Request, res: Response) => {
const mobilePlatformVersionPrefixes = ["android / ", "ios / ", "- /"];
const desktopPlatformVersionPrefixes = ["firefox / ", "chrome / "];
const clientVersionHeader = "yoroi-version";
const minMobileVersion = "2.2.4";
const minDesktopVersion = "1.10.4";
if (clientVersionHeader in req.headers) {
const rawVerString: string | string[] | undefined =
req.headers[clientVersionHeader];
let verString = "none / 0.0.0";
if (typeof rawVerString === "string") verString = rawVerString;
if (Array.isArray(rawVerString)) verString = rawVerString[0];
for (const prefix of mobilePlatformVersionPrefixes) {
if (verString.includes(prefix)) {
const simVer = verString.split(" / ")[1];
if (semverCompare(simVer, minMobileVersion) < 0) {
res.send({ isServerOk: true, isMaintenance: true });
return;
}
}
}
for (const prefix of desktopPlatformVersionPrefixes) {
if (verString.includes(prefix)) {
const simVer = verString.split(" / ")[1];
if (semverCompare(simVer, minDesktopVersion) < 0) {
res.send({ isServerOk: true, isMaintenance: true });
return;
}
}
}
}
res.send({ isServerOk: true, isMaintenance: false, serverTime: Date.now() });
};
const getFundInfo = async (req: Request, res: Response) => {
res.send({
currentFund: {
id: 7,
registrationStart: "2021-11-18T11:00:00Z",
registrationEnd: "2022-01-13T11:00:00Z",
votingStart: "2022-01-13T11:00:00Z",
votingEnd: "2022-01-27T11:00:00Z",
votingPowerThreshold: "450",
},
});
};
const routes: Route[] = [
// deprecated endpoints
{
path: "/getAccountState",
method: "post",
handler: handleGetAccountState(pool),
},
{
path: "/getRegistrationHistory",
method: "post",
handler: handleGetRegHistory(pool),
},
{
path: "/getRewardHistory",
method: "post",
handler: handleGetRewardHistory(pool),
},
{ path: "/getPoolInfo", method: "post", handler: handlePoolInfo(pool) },
// replacement endpoints
{
path: "/account/state",
method: "post",
handler: handleGetAccountState(pool),
},
{
path: "/account/registrationHistory",
method: "post",
handler: handleGetRegHistory(pool),
},
{
path: "/account/rewardHistory",
method: "post",
handler: handleGetRewardHistory(pool),
},
{ path: "/pool/info", method: "post", handler: handlePoolInfo(pool) },
{
path: "/pool/delegationHistory",
method: "post",
handler: poolDelegationHistory(pool),
},
// regular endpoints
{ path: "/v2/bestblock", method: "get", handler: bestBlock(pool) },
{ path: "/v2/tipStatus", method: "get", handler: handleTipStatusGet(pool) },
{ path: "/v2/tipStatus", method: "post", handler: handleTipStatusPost(pool) },
{
path: "/v2/addresses/filterUsed",
method: "post",
handler: filterUsedAddresses(pool),
},
{
path: "/txs/utxoForAddresses",
method: "post",
handler: utxoForAddresses(pool),
},
{
path: "/txs/utxoSumForAddresses",
method: "post",
handler: utxoSumForAddresses,
},
{ path: "/v2/txs/history", method: "post", handler: txHistory },
{ path: "/txs/io/:tx_hash", method: "get", handler: handleGetTxIO(pool) },
{ path: "/v2/txs/get", method: "post", handler: handleGetTransactions(pool) },
{ path: "/txs/signed", method: "post", handler: handleSignedTx },
{
path: "/messages/getMessageBoard",
method: "post",
handler: handleMessageBoard(pool),
},
{
path: "/messages/getMessageDirect",
method: "post",
handler: handleMessageDirect(pool),
},
{
path: "/oracles/getDatapoints",
method: "post",
handler: handleOracleDatapoint(pool),
},
{
path: "/oracles/getTickers",
method: "post",
handler: handleOracleTicker(pool),
},
{
path: "/pool/cardanoWallet",
method: "get",
handler: handleGetCardanoWalletPools(pool),
},
{
path: "/multiAsset/supply",
method: "post",
handler: handleGetMultiAssetSupply(pool),
},
{
path: "/multiAsset/metadata",
method: "post",
handler: handleGetMultiAssetTxMintMetadata(pool),
},
{
path: "/tx/status",
method: "post",
handler: handleTxStatus(pool),
},
{
path: "/multiAsset/policyIdExists",
method: "post",
handler: handlePolicyIdExists(pool),
},
{
path: "/v2/importerhealthcheck",
method: "get",
handler: async (_req: Request, res: Response) => {
const status = healthChecker.getStatus();
if (status === "OK") res.send({ code: 200, message: "Importer is OK" });
else if (status === "BLOCK_IS_STALE")
res.send({
code: 200,
message:
"Importer seems OK. Not enough time has passed since last valid request.",
});
else throw new Error(status);
},
},
{ path: "/status", method: "get", handler: getStatus },
{
path: "/v0/catalyst/fundInfo",
method: "get",
handler: getFundInfo,
},
];
applyRoutes(routes, router);
router.use(middleware.logErrors);
router.use(middleware.errorHandler);
const server = http.createServer(router);
const wss = new websockets.Server({ server });
wss.on("connection", connectionHandler(pool));
server.listen(port, () => console.log(`listening on ${port}...`));