-
Notifications
You must be signed in to change notification settings - Fork 3
/
api.js
381 lines (329 loc) · 11.4 KB
/
api.js
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
// @flow
const config = require('config');
const fetch = require('node-fetch');
const utils = require('./utils');
const BigNumber = require('bignumber.js');
import type {
UtxoForAddressesInput,
UtxoForAddressesOutput,
UtxoSumForAddressesInput,
UtxoSumForAddressesOutput,
FilterUsedInput,
FilterUsedOutput,
TxBodiesInput,
HistoryInput,
HistoryOutput,
StatusOutput,
} from './types/wrapperApi';
import type {
HandlerFunction,
UtilEither,
UtilOK,
} from './types/utils';
import type {
getApiV0BlocksP1SuccessResponse,
getApiV0AddressesP1TransactionsSuccessResponse,
getApiV0AddressesP1TransactionsItem,
getApiV0BlocksSuccessResponse,
postApiV0TransactionsSendSuccessResponse,
postApiV0TransactionsSendRequest,
getApiV0TransactionsP1SuccessResponse,
getApiV0AddressesP1SuccessResponse,
} from './types/explorer';
const addressesRequestLimit = 50;
const apiResponseLimit = 50;
const askBlockNum = async (blockHash: ?string, txHash?: string): Promise<UtilEither<number>> => {
if (blockHash == undefined) return {kind:'ok', value: -1};
const resp = await fetch(
`${config.backend.explorer}/api/v0/blocks/${blockHash}`
);
if (resp.status !== 200) return {kind:'error', errMsg: 'block not found.'};
const r: getApiV0BlocksP1SuccessResponse = await resp.json();
if (txHash === "" || txHash == undefined) {
return {kind:'ok', value: r.block.header.height};
}
for(const tx of r.block.blockTransactions) {
if (tx.id === txHash) {
return {kind: 'ok', value: r.block.header.height};
}
}
return {kind:'error', errMsg: 'tx not found.'};
}
const askTransactionHistory = async (
limit: number
, addresses: string[]
, afterNum: number
, afterTxHash: ?string
, untilNum: number
) : Promise<UtilEither<Array<getApiV0AddressesP1TransactionsItem>>> => {
let output: Array<getApiV0AddressesP1TransactionsItem> = [];
const responses = await Promise.all(addresses.map((address) => (
fetch(`${config.backend.explorer}/api/v0/addresses/${address}/transactions`)
)));
const unfilteredResponses: Array<getApiV0AddressesP1TransactionsItem> = [];
for (const response of responses) {
if (response.status !== 200) return {kind:'error', errMsg: `error querying transactions for address`};
const json: getApiV0AddressesP1TransactionsSuccessResponse = await response.json();
unfilteredResponses.push(...json.items);
}
if (unfilteredResponses.length == 0) return {
kind: 'ok',
value: [],
};
for(const response of unfilteredResponses) {
// filter by limit after and until
const creationHeight = response.inclusionHeight;
if (creationHeight <= afterNum) {
continue;
}
if (creationHeight > untilNum) {
continue;
}
output.push(response);
}
if (afterTxHash != undefined) {
const index = output
.findIndex((tx) => (tx.id === afterTxHash))
if (index != undefined) {
output = output.slice(index + 1)
}
}
return {
kind: 'ok',
value: output,
};
}
const bestBlock: HandlerFunction = async function (req, _res) {
const resp = await fetch(
`${config.backend.explorer}/api/v0/blocks`
);
if (resp.status !== 200) {
return {status: 400, body: `error getting bestBlock`};
}
const r: getApiV0BlocksSuccessResponse = await resp.json();
const output = {
epoch: 0, // TODO
slot: 0, // TODO
hash: r.items[0].id,
height: r.items[0].height,
};
return { status: 200, body: output };
};
const signed: HandlerFunction = async function (req, _res) {
const body: postApiV0TransactionsSendRequest = req.body;
const resp = await fetch(
`${config.backend.explorer}/api/v0/transactions/send`,
{
method: 'post',
body,
})
if (resp.status !== 200) {
return { status: 400, body: `error sending transaction`};
}
const r: postApiV0TransactionsSendSuccessResponse = await resp.json();
return { status: 200, body: r };
};
async function getUtxoForAddress(address: string): Promise<UtilEither<UtxoForAddressesOutput>> {
const resp = await fetch(
`${config.backend.explorer}/api/v0/addresses/${address}/transactions`
);
if (resp.status !== 200) return {kind:'error', errMsg: `error querying utxos for address`};
const r: getApiV0AddressesP1TransactionsSuccessResponse = await resp.json();
// Get all outputs whose `address` matches input address and `spentTransactionId` is `null`.
const result = r.items.map(({ outputs }) => (
outputs
.map((output, index) => ({ output, index }))
.filter(({ output, index }) =>
output.address === address && output.spentTransactionId === null
)
))
.flat()
.map(({ output, index }) => ({
tx_hash: output.id,
tx_index: index,
utxo_id: output.id + index,
receiver: address,
amount: String(output.value)
}));
return {
kind: 'ok',
value: result,
};
}
const utxoForAddresses: HandlerFunction = async function (req, _res) {
const input: UtxoForAddressesInput = req.body;
const outputsForAddresses: Array<UtilEither<UtxoForAddressesOutput>> = (await Promise.all(
input.addresses.map(getUtxoForAddress)
));
const result: UtxoForAddressesOutput = [];
for (const outputsForAddress of outputsForAddresses) {
if (outputsForAddress.kind === 'error') {
return { status: 400, body: outputsForAddress.errMsg}
}
result.push(...outputsForAddress.value);
}
return { status: 200, body: result };
}
async function getBalanceForAddress(address: string): Promise<UtilEither<number>> {
const resp = await fetch(
`${config.backend.explorer}/api/v0/addresses/${address}`
);
if (resp.status !== 200) return {kind:'error', errMsg: `error querying utxos for address`};
const r: getApiV0AddressesP1SuccessResponse = await resp.json();
if (r.transactions && typeof r.transactions.confirmedBalance === 'number') {
return {
kind: 'ok',
value: r.transactions.confirmedBalance,
};
}
return {
kind: 'ok',
value: 0,
};
}
const utxoSumForAddresses: HandlerFunction = async function (req, _res) {
const input: UtxoSumForAddressesInput = req.body;
const balances = await Promise.all(
input.addresses.map(getBalanceForAddress)
);
let sum = new BigNumber(0);
for (const balance of balances) {
if (balance.kind === 'error') {
return {status: 400, body: balance.errMsg};
}
sum = sum.plus(balance.value);
}
const output: UtxoSumForAddressesOutput = { sum: sum.toString() };
return { status: 200, body: output };
}
async function isUsed(address: string): Promise<UtilEither<{| used: boolean, address: string |}>> {
const resp = await fetch(
`${config.backend.explorer}/api/v0/addresses/${address}`
);
if (resp.status !== 200) return {kind:'error', errMsg: `error querying address information`};
const r: getApiV0AddressesP1SuccessResponse = await resp.json();
return {
kind: 'ok',
value: {
used: r.transactions && r.transactions.totalReceived !== 0,
address,
},
};
}
const filterUsed: HandlerFunction = async function (req, _res) {
const input: FilterUsedInput = req.body;
const usedStatuses = await Promise.all(
input.addresses.map(isUsed)
);
const result: FilterUsedOutput = [];
for (const status of usedStatuses) {
if (status.kind === 'error') {
return {status: 400, body: status.errMsg};
}
if (status.value.used) {
result.push(status.value.address);
}
}
return { status: 200, body: result };
}
async function getTxBody(txHash: string): Promise<UtilEither<[string, getApiV0TransactionsP1SuccessResponse]>> {
const resp = await fetch(
`${config.backend.explorer}/api/v0/transactions/${txHash}`
);
if (resp.status !== 200) {
return { kind: 'error', errMsg: `error sending transaction`};
}
const txBody: getApiV0TransactionsP1SuccessResponse = await resp.json();
return {
kind: 'ok',
value: [ txHash, txBody ],
};
}
const txBodies: HandlerFunction = async function (req, _res) {
const input: TxBodiesInput = req.body;
const txBodyEntries = await Promise.all(
input.txHashes.map(getTxBody)
);
const result: {| [key: string]: getApiV0TransactionsP1SuccessResponse |} = {};
for (const entry of txBodyEntries) {
if (entry.kind === 'error') {
return {status: 400, body: entry.errMsg};
}
result[entry.value[0]] = entry.value[1];
}
return { status: 200, body: result };
}
const history: HandlerFunction = async function (req, _res) {
const input: HistoryInput = req.body;
console.log(input);
if(!req.body) {
const errMsg = "error, no body";
console.log(errMsg);
return { status: 400, body: errMsg}
}
const verifiedBody = utils.validateHistoryReq(addressesRequestLimit, apiResponseLimit, input);
switch (verifiedBody.kind) {
case "ok":
const body = verifiedBody.value;
const limit = apiResponseLimit;
const [referenceTx, referenceBlock] = (body.after && [body.after.tx, body.after.block]) || [undefined, undefined];
const referenceBestBlock = body.untilBlock;
const afterBlockNum = await askBlockNum(referenceBlock, referenceTx != undefined ? referenceTx : "");
const untilBlockNum = await askBlockNum(referenceBestBlock);
if (afterBlockNum.kind === 'error') {
if (afterBlockNum.errMsg.includes('tx')) {
throw new Error("REFERENCE_TX_NOT_FOUND");
}
if (afterBlockNum.errMsg.includes('block')) {
throw new Error("REFERENCE_BLOCK_MISMATCH");
}
return { status: 400, body: afterBlockNum.errMsg}
}
if (untilBlockNum.kind === 'error') {
throw new Error("REFERENCE_BEST_BLOCK_MISMATCH");
}
const unformattedTxs = await askTransactionHistory(limit, body.addresses, afterBlockNum.value, referenceTx, untilBlockNum.value);
if (unformattedTxs.kind === 'error') {
return { status: 400, body: unformattedTxs.errMsg}
}
const txs = unformattedTxs.value.map((tx) => {
const iso8601date = new Date(tx.timestamp).toISOString()
return {
hash: tx.id,
tx_state: 'Successful', // explorer doesn't handle pending transactions
block_num: tx.inclusionHeight,
block_hash: tx.headerId,
time: iso8601date,
epoch: 0, // TODO
slot: 0, // TODO
inputs: tx.inputs,
dataInputs: tx.dataInputs,
outputs: tx.outputs
}
});
return { status: 200, body: txs };
case "error":
console.log(verifiedBody.errMsg);
return { status: 400, body: verifiedBody.errMsg };
default: return utils.assertNever(verifiedBody);
}
}
const status: HandlerFunction = async function (req, _res) {
const resp = await fetch(
`${config.backend.explorer}/api/v0/info`
);
const output: StatusOutput = {
isServerOk: resp.status === 200,
};
return { status: 200, body: output };
}
exports.handlers = [
{ method: 'post', url: '/api/txs/utxoForAddresses', handler: utxoForAddresses },
{ method: 'post', url: '/api/txs/txBodies', handler: txBodies },
{ method: 'post', url: '/api/txs/utxoSumForAddresses', handler: utxoSumForAddresses },
{ method: 'post', url: '/api/v2/addresses/filterUsed', handler: filterUsed },
{ method: 'post', url: '/api/v2/txs/history', handler: history },
{ method: 'get', url: '/api/v2/bestblock', handler: bestBlock },
{ method: 'post', url: '/api/txs/signed', handler: signed },
{ method: 'get', url: '/api/status', handler: status },
];