-
Notifications
You must be signed in to change notification settings - Fork 2
/
api.ts
244 lines (220 loc) · 7.08 KB
/
api.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
import { Status } from "std/http/mod.ts";
import { ConsoleHandler } from "std/log/handlers.ts";
import { getLogger, setup as setupLog } from "std/log/mod.ts";
import {
Application as OakApplication,
type Context,
isHttpError,
Router,
} from "oak";
import { oakCors } from "https://deno.land/x/[email protected]/mod.ts";
import { Buffer } from "node:buffer";
import { stringify as losslessJsonStringify } from "npm:lossless-json";
import { getAddress, keccak256, toHex } from "viem";
import type { PrismaClient } from "./prisma/shim.ts";
import { validateEventRequest } from "./constants/apiSchema.ts";
import { serializeEventResponse } from "./messages/EventResponse.ts";
import { formatAbiItemPrototype } from "./utils/abiUtils.ts";
import {
ApiBehindReverseProxyEnvKey,
ApiUrlEnvKey,
combinedEnv,
} from "./utils/envUtils.ts";
import {
ApiLoggerName,
defaultLogFormatter,
getInternalLoggers,
getLoggingLevel,
} from "./utils/logUtils.ts";
import { runWithPrisma } from "./utils/runUtils.ts";
export function api(prisma: PrismaClient) {
const hexToBuffer = (hex: string): Buffer => {
return Buffer.from(hex.replace("0x", ""), "hex");
};
const getBlockNumberFromHash = async (blockHash?: string | number) => {
if (typeof blockHash !== "string") return blockHash;
return (await prisma.event.findFirst({
where: { blockHash: hexToBuffer(blockHash) },
}))
?.blockNumber;
};
const logger = getLogger(ApiLoggerName);
const abortController = new AbortController();
const router = new Router();
router.get("/", (ctx) => {
// TODO: show JSON Schema
ctx.response.body = "Not yet implemented";
ctx.response.status = Status.NotImplemented;
});
router.post("/", async (ctx) => {
const request = await ctx.request.body({ type: "json" }).value;
if (!validateEventRequest(request)) {
ctx.response.status = Status.BadRequest;
ctx.response.body = validateEventRequest.errors;
return;
}
const blockFrom = await getBlockNumberFromHash(request.blockFrom);
const blockTo = await getBlockNumberFromHash(request.blockTo);
ctx.response.body = losslessJsonStringify((await prisma.event.findMany({
where: {
blockHash: (request.blockHash && hexToBuffer(request.blockHash)) as
| Buffer
| undefined,
blockNumber: request.blockIndex ?? { gte: blockFrom, lte: blockTo },
logIndex: request.logIndex,
txHash:
(request.transactionHash && hexToBuffer(request.transactionHash)) as
| Buffer
| undefined,
sourceAddress:
(request.sourceAddress && hexToBuffer(request.sourceAddress)) as
| Buffer
| undefined,
abiHash: ((request.abiHash && hexToBuffer(request.abiHash)) ??
(request.abiSignature &&
Buffer.from(
keccak256(
new TextEncoder().encode(request.abiSignature),
"bytes",
),
))) as Buffer | undefined,
},
include: { Abi: true },
})).map((evt) =>
serializeEventResponse({
address: evt.sourceAddress,
sigHash: evt.abiHash,
abi: evt.Abi.json,
topics: [evt.topic3, evt.topic2, evt.topic1].reduce(
(acc, x) => x != undefined ? [x, ...acc] : [],
[] as Uint8Array[],
),
data: evt.data,
logIndex: BigInt(evt.logIndex),
blockNumber: BigInt(evt.blockNumber),
blockHash: evt.blockHash,
txHash: evt.txHash,
})
));
});
router.get("/sources", (ctx) => {
// TODO: show JSON Schema
ctx.response.body = "Not yet implemented";
ctx.response.status = Status.NotImplemented;
});
router.post("/sources", async (ctx) => {
// TODO: parameters
ctx.response.body = (
await prisma.eventSource.findMany({
include: { Abi: true },
})
).map((item) => ({
address: getAddress(toHex(item.address)),
abi: formatAbiItemPrototype(JSON.parse(item.Abi.json)),
abiHash: toHex(item.abiHash),
}));
});
router.get("/abi", (ctx) => {
// TODO: show JSON Schema
ctx.response.body = "Not yet implemented";
ctx.response.status = Status.NotImplemented;
});
router.post("/abi", async (ctx) => {
// TODO: parameters
ctx.response.body = (await prisma.eventAbi.findMany()).reduce(
(acc, item) => {
const abi = JSON.parse(item.json);
Object.assign(acc, {
[toHex(item.hash)]: {
signature: formatAbiItemPrototype(abi),
abi: abi,
},
});
return acc;
},
{},
);
});
router.post("/webhook", async (ctx) => {
// TODO: parameters
ctx.response.body = (await prisma.emitDestination.findMany())
.map((item) => ({
id: item.id,
sourceAddress: getAddress(toHex(item.sourceAddress)),
abiHash: toHex(item.abiHash),
webhookUrl: item.webhookUrl,
topic1: item.topic1 ? toHex(item.topic1) : undefined,
topic2: item.topic2 ? toHex(item.topic2) : undefined,
topic3: item.topic3 ? toHex(item.topic3) : undefined,
}));
});
const app = new OakApplication();
app.proxy = combinedEnv[ApiBehindReverseProxyEnvKey] === "true";
app.use(async (context, next) => {
function formatResponse(
ctx: Context<Record<string, unknown>, Record<string, unknown>>,
) {
return `${ctx.response.status} ${ctx.request.method} ${ctx.request.url.pathname} ${ctx.request.ip} ${
JSON.stringify(ctx.state["requestBody"])
}: ${
typeof ctx.response.body === "function"
? ctx.response.body()
: ctx.response.body
}`;
}
try {
context.state["requestBody"] = await context.request.body({
type: "json",
}).value;
await next();
logger.info(formatResponse(context));
} catch (err) {
if (isHttpError(err)) {
context.response.status = err.status;
} else {
context.response.status = 500;
}
context.response.body = { error: err.message };
context.response.type = "json";
logger.error(formatResponse(context));
} finally {
delete context.state["requestBody"];
}
});
app.use(oakCors());
app.use(router.routes());
app.use(router.allowedMethods());
const listenUrl = new URL(combinedEnv[ApiUrlEnvKey]);
logger.info(`API server listening on ${listenUrl}.`);
const runningPromise = app.listen({
port: Number(listenUrl.port) || 80,
hostname: listenUrl.hostname,
signal: abortController.signal,
});
async function cleanup() {
logger.warning("Stopping API server.");
abortController.abort();
return await runningPromise;
}
return { runningPromise, cleanup };
}
if (import.meta.main) {
setupLog({
handlers: {
console: new ConsoleHandler(getLoggingLevel(), {
formatter: defaultLogFormatter,
}),
},
loggers: {
...getInternalLoggers({
level: getLoggingLevel(),
handlers: ["console"],
}),
[ApiLoggerName]: {
level: getLoggingLevel(),
handlers: ["console"],
},
},
});
await runWithPrisma(api);
}