-
Notifications
You must be signed in to change notification settings - Fork 104
Expand file tree
/
Copy pathget-logs.ts
More file actions
274 lines (254 loc) · 8.62 KB
/
Copy pathget-logs.ts
File metadata and controls
274 lines (254 loc) · 8.62 KB
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
import { type Static, Type } from "@sinclair/typebox";
import type { FastifyInstance } from "fastify";
import { StatusCodes } from "http-status-codes";
import type { AbiEvent } from "ox";
import superjson from "superjson";
import {
type Hex,
eth_getTransactionReceipt,
getContract,
getRpcClient,
isHex,
parseEventLogs,
prepareEvent,
} from "thirdweb";
import { resolveContractAbi } from "thirdweb/contract";
import type { TransactionReceipt } from "thirdweb/transaction";
import { TransactionDB } from "../../../../shared/db/transactions/db";
import { getChain } from "../../../../shared/utils/chain";
import { env } from "../../../../shared/utils/env";
import { thirdwebClient } from "../../../../shared/utils/sdk";
import { createCustomError } from "../../../middleware/error";
import { AddressSchema, TransactionHashSchema } from "../../../schemas/address";
import { chainIdOrSlugSchema } from "../../../schemas/chain";
import { standardResponseSchema } from "../../../schemas/shared-api-schemas";
import { getChainIdFromChain } from "../../../utils/chain";
// INPUT
const requestQuerystringSchema = Type.Object({
chain: chainIdOrSlugSchema,
queueId: Type.Optional(
Type.String({
description: "The queue ID for a mined transaction.",
}),
),
transactionHash: Type.Optional({
...TransactionHashSchema,
description: "The transaction hash for a mined transaction.",
}),
parseLogs: Type.Optional(
Type.Boolean({
description:
"If true, parse the raw logs as events defined in the contract ABI. (Default: true)",
}),
),
});
// OUTPUT
const LogSchema = Type.Object({
address: AddressSchema,
topics: Type.Array(Type.String()),
data: Type.String(),
blockNumber: Type.String(),
transactionHash: TransactionHashSchema,
transactionIndex: Type.Integer(),
blockHash: Type.String(),
logIndex: Type.Integer(),
removed: Type.Boolean(),
// Additional properties only for parsed logs
eventName: Type.Optional(
Type.String({
description: "Event name, only returned when `parseLogs` is true",
}),
),
args: Type.Optional(
Type.Unknown({
description: "Event arguments. Only returned when `parseLogs` is true",
examples: [
{
from: "0xdeadbeeefdeadbeeefdeadbeeefdeadbeeefdead",
to: "0xdeadbeeefdeadbeeefdeadbeeefdeadbeeefdead",
value: "1000000000000000000n",
},
],
}),
),
});
// DO NOT USE type.union
// this is known to cause issues with the generated types
export const responseBodySchema = Type.Object({
result: Type.Array(LogSchema),
});
responseBodySchema.example = {
result: [
{
eventName: "Transfer",
args: {
from: "0x0000000000000000000000000000000000000000",
to: "0x71B6267b5b2b0B64EE058C3D27D58e4E14e7327f",
value: "1000000000000000000n",
},
address: "0x71b6267b5b2b0b64ee058c3d27d58e4e14e7327f",
topics: [
"0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef",
"0x0000000000000000000000000000000000000000000000000000000000000000",
"0x00000000000000000000000071b6267b5b2b0b64ee058c3d27d58e4e14e7327f",
],
data: "0x0000000000000000000000000000000000000000000000000de0b6b3a7640000",
blockNumber: "79326434",
transactionHash:
"0x568eb49d738f7c02ebb24aa329efcf10883d951b1e13aa000b0e073d54a0246e",
transactionIndex: 1,
blockHash:
"0xaffbcf3232a76152206de5f6999c549404efc76060a34f8826b90c95993464c3",
logIndex: 0,
removed: false,
},
],
};
export async function getTransactionLogs(fastify: FastifyInstance) {
fastify.route<{
Querystring: Static<typeof requestQuerystringSchema>;
Reply: Static<typeof responseBodySchema>;
}>({
method: "GET",
url: "/transaction/logs",
schema: {
summary: "Get transaction logs",
description:
"Get transaction logs for a mined transaction. A tranasction queue ID or hash must be provided. Set `parseLogs` to parse the event logs.",
tags: ["Transaction"],
operationId: "getTransactionLogs",
querystring: requestQuerystringSchema,
response: {
...standardResponseSchema,
[StatusCodes.OK]: responseBodySchema,
},
},
handler: async (request, reply) => {
const {
chain: inputChain,
queueId,
transactionHash,
parseLogs = true,
} = request.query;
const chainId = await getChainIdFromChain(inputChain);
const chain = await getChain(chainId);
const rpcRequest = getRpcClient({
client: thirdwebClient,
chain,
});
if (!queueId && !transactionHash) {
throw createCustomError(
"Either a queue ID or transaction hash must be provided.",
StatusCodes.BAD_REQUEST,
"MISSING_TRANSACTION_ID",
);
}
// Get the transaction hash from the provided input.
let hash: Hex | undefined;
if (queueId) {
// SPECIAL LOGIC FOR AMEX
// Backfill table takes priority — entries are intentional overrides for
// queue IDs that are stuck in Redis (e.g. orphaned "queued" transactions).
if (env.ENABLE_TX_BACKFILL_FALLBACK) {
const backfill = await TransactionDB.getBackfill(queueId);
if (backfill) {
// Backfill entry exists and is authoritative — only set hash if mined.
// If backfill is errored, hash stays undefined and we skip Redis lookup.
if (backfill.status === "mined" && backfill.transactionHash && isHex(backfill.transactionHash)) {
hash = backfill.transactionHash as Hex;
}
} else {
// No backfill entry — fall back to Redis.
const transaction = await TransactionDB.get(queueId);
if (transaction?.status === "mined") {
hash = transaction.transactionHash;
}
}
} else {
const transaction = await TransactionDB.get(queueId);
if (transaction?.status === "mined") {
hash = transaction.transactionHash;
}
}
} else if (transactionHash) {
hash = transactionHash as Hex;
}
if (!hash) {
throw createCustomError(
"Could not find transaction, or transaction is not mined.",
StatusCodes.BAD_REQUEST,
"TRANSACTION_NOT_MINED",
);
}
// Try to get the receipt.
let transactionReceipt: TransactionReceipt | undefined;
try {
transactionReceipt = await eth_getTransactionReceipt(rpcRequest, {
hash,
});
} catch {
throw createCustomError(
"Unable to get transaction receipt. The transaction may not have been mined yet.",
StatusCodes.BAD_REQUEST,
"TRANSACTION_NOT_MINED",
);
}
if (!parseLogs) {
return reply.status(StatusCodes.OK).send({
result: superjson.serialize(transactionReceipt.logs).json as Static<
typeof LogSchema
>[],
});
}
if (!transactionReceipt.to) {
throw createCustomError(
"Transaction logs are only supported for contract calls.",
StatusCodes.BAD_REQUEST,
"TRANSACTION_LOGS_UNAVAILABLE",
);
}
const contracts = new Set<string>();
contracts.add(transactionReceipt.to);
for (const log of transactionReceipt.logs) {
if (log.address) {
contracts.add(log.address);
}
}
const eventSignaturePromises = Array.from(contracts).map(
async (address) => {
const contract = getContract({
address,
chain,
client: thirdwebClient,
});
const abi: AbiEvent.AbiEvent[] = await resolveContractAbi(contract);
const eventSignatures = abi.filter((item) => item.type === "event");
return eventSignatures;
},
);
const combinedEventSignatures: AbiEvent.AbiEvent[] = (
await Promise.all(eventSignaturePromises)
).flat();
if (combinedEventSignatures.length === 0) {
throw createCustomError(
"No events found in contract or could not resolve contract ABI",
StatusCodes.BAD_REQUEST,
"NO_EVENTS_FOUND",
);
}
const preparedEvents = combinedEventSignatures.map((signature) =>
prepareEvent({ signature }),
);
const parsedLogs = parseEventLogs({
events: preparedEvents,
logs: transactionReceipt.logs,
strict: false,
});
reply.status(StatusCodes.OK).send({
result: superjson.serialize(parsedLogs).json as Static<
typeof LogSchema
>[],
});
},
});
}