Skip to content

Commit 7e171de

Browse files
committed
Merge remote-tracking branch 'origin/main' into ph/catchReadErrors
2 parents c0a2fa5 + a121730 commit 7e171de

File tree

5 files changed

+81
-94
lines changed

5 files changed

+81
-94
lines changed

src/server/middleware/error.ts

Lines changed: 21 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -53,7 +53,17 @@ const isZodError = (err: unknown): boolean => {
5353

5454
export const withErrorHandler = async (server: FastifyInstance) => {
5555
server.setErrorHandler(
56-
(error: Error | CustomError | ZodError, request, reply) => {
56+
(error: string | Error | CustomError | ZodError, request, reply) => {
57+
if (typeof error === "string") {
58+
return reply.status(StatusCodes.INTERNAL_SERVER_ERROR).send({
59+
error: {
60+
statusCode: 500,
61+
code: "INTERNAL_SERVER_ERROR",
62+
message: error || ReasonPhrases.INTERNAL_SERVER_ERROR,
63+
},
64+
});
65+
}
66+
5767
// Ethers Error Codes
5868
if (parseEthersError(error)) {
5969
return reply.status(StatusCodes.BAD_REQUEST).send({
@@ -103,25 +113,24 @@ export const withErrorHandler = async (server: FastifyInstance) => {
103113
StatusCodes.INTERNAL_SERVER_ERROR;
104114

105115
const message = error.message ?? ReasonPhrases.INTERNAL_SERVER_ERROR;
106-
reply.status(statusCode).send({
116+
return reply.status(statusCode).send({
107117
error: {
108118
code,
109119
message,
110120
statusCode,
111121
stack: env.NODE_ENV !== "production" ? error.stack : undefined,
112122
},
113123
});
114-
} else {
115-
// Handle non-custom errors
116-
reply.status(StatusCodes.INTERNAL_SERVER_ERROR).send({
117-
error: {
118-
statusCode: 500,
119-
code: "INTERNAL_SERVER_ERROR",
120-
message: error.message || ReasonPhrases.INTERNAL_SERVER_ERROR,
121-
stack: env.NODE_ENV !== "production" ? error.stack : undefined,
122-
},
123-
});
124124
}
125+
126+
reply.status(StatusCodes.INTERNAL_SERVER_ERROR).send({
127+
error: {
128+
statusCode: 500,
129+
code: "INTERNAL_SERVER_ERROR",
130+
message: error.message || ReasonPhrases.INTERNAL_SERVER_ERROR,
131+
stack: env.NODE_ENV !== "production" ? error.stack : undefined,
132+
},
133+
});
125134
},
126135
);
127136
};

src/server/routes/transaction/retry-failed.ts

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -69,10 +69,9 @@ export async function retryFailedTransaction(fastify: FastifyInstance) {
6969
);
7070
}
7171

72-
// temp do not handle userop
7372
if (transaction.isUserOp) {
7473
throw createCustomError(
75-
`Transaction cannot be retried because it is a userop`,
74+
"Transaction cannot be retried because it is a userop",
7675
StatusCodes.BAD_REQUEST,
7776
"TRANSACTION_CANNOT_BE_RETRIED",
7877
);

src/server/schemas/transaction/index.ts

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -292,7 +292,10 @@ export const toTransactionSchema = (
292292
toAddress: transaction.to ?? null,
293293
data: transaction.data ?? null,
294294
value: transaction.value.toString(),
295-
nonce: "nonce" in transaction ? transaction.nonce : null,
295+
nonce:
296+
"nonce" in transaction && transaction.nonce !== undefined
297+
? transaction.nonce
298+
: null,
296299
deployedContractAddress: transaction.deployedContractAddress ?? null,
297300
deployedContractType: transaction.deployedContractType ?? null,
298301
functionName: transaction.functionName ?? null,

src/worker/tasks/nonceResyncWorker.ts

Lines changed: 35 additions & 63 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ import {
88
} from "../../db/wallets/walletNonce";
99
import { getConfig } from "../../utils/cache/getConfig";
1010
import { getChain } from "../../utils/chain";
11+
import { prettifyError } from "../../utils/error";
1112
import { logger } from "../../utils/logger";
1213
import { redis } from "../../utils/redis/redis";
1314
import { thirdwebClient } from "../../utils/sdk";
@@ -40,78 +41,49 @@ export const initNonceResyncWorker = async () => {
4041
*/
4142
const handler: Processor<any, void, string> = async (job: Job<string>) => {
4243
const sentNoncesKeys = await redis.keys("nonce-sent*");
43-
job.log(`Found ${sentNoncesKeys.length} nonce-sent* keys`);
44+
if (sentNoncesKeys.length === 0) {
45+
job.log("No active wallets.");
46+
return;
47+
}
4448

4549
for (const sentNonceKey of sentNoncesKeys) {
46-
const { chainId, walletAddress } = splitSentNoncesKey(sentNonceKey);
47-
48-
const rpcRequest = getRpcClient({
49-
client: thirdwebClient,
50-
chain: await getChain(chainId),
51-
});
50+
try {
51+
const { chainId, walletAddress } = splitSentNoncesKey(sentNonceKey);
5252

53-
const [transactionCount, lastUsedNonceDb] = await Promise.all([
54-
eth_getTransactionCount(rpcRequest, {
55-
address: walletAddress,
56-
blockTag: "latest",
57-
}),
58-
inspectNonce(chainId, walletAddress),
59-
]);
60-
61-
if (Number.isNaN(transactionCount)) {
62-
job.log(
63-
`Received invalid onchain transaction count for ${walletAddress}: ${transactionCount}`,
64-
);
65-
logger({
66-
level: "error",
67-
message: `[nonceResyncWorker] Received invalid onchain transaction count for ${walletAddress}: ${transactionCount}`,
68-
service: "worker",
53+
const rpcRequest = getRpcClient({
54+
client: thirdwebClient,
55+
chain: await getChain(chainId),
6956
});
70-
continue;
71-
}
57+
const lastUsedNonceOnchain =
58+
(await eth_getTransactionCount(rpcRequest, {
59+
address: walletAddress,
60+
blockTag: "latest",
61+
})) - 1;
62+
const lastUsedNonceDb = await inspectNonce(chainId, walletAddress);
7263

73-
const lastUsedNonceOnchain = transactionCount - 1;
74-
75-
job.log(
76-
`${walletAddress} last used onchain nonce: ${lastUsedNonceOnchain} and last used db nonce: ${lastUsedNonceDb}`,
77-
);
78-
logger({
79-
level: "debug",
80-
message: `[nonceResyncWorker] last used onchain nonce: ${transactionCount} and last used db nonce: ${lastUsedNonceDb}`,
81-
service: "worker",
82-
});
83-
84-
// If the last used nonce onchain is the same as or ahead of the last used nonce in the db,
85-
// There is no need to resync the nonce.
86-
if (lastUsedNonceOnchain >= lastUsedNonceDb) {
87-
job.log(`No need to resync nonce for ${walletAddress}`);
88-
logger({
89-
level: "debug",
90-
message: `[nonceResyncWorker] No need to resync nonce for ${walletAddress}`,
91-
service: "worker",
92-
});
93-
continue;
94-
}
64+
// Recycle all nonces between (onchain nonce, db nonce] if they aren't in-flight ("sent nonce").
65+
const recycled: number[] = [];
66+
for (
67+
let nonce = lastUsedNonceOnchain + 1;
68+
nonce <= lastUsedNonceDb;
69+
nonce++
70+
) {
71+
const exists = await isSentNonce(chainId, walletAddress, nonce);
72+
if (!exists) {
73+
await recycleNonce(chainId, walletAddress, nonce);
74+
recycled.push(nonce);
75+
}
76+
}
9577

96-
// for each nonce between last used db nonce and last used onchain nonce
97-
// check if nonce exists in nonce-sent set
98-
// if it does not exist, recycle it
99-
for (
100-
let _nonce = lastUsedNonceOnchain + 1;
101-
_nonce < lastUsedNonceDb;
102-
_nonce++
103-
) {
104-
const exists = await isSentNonce(chainId, walletAddress, _nonce);
78+
const message = `wallet=${chainId}:${walletAddress} lastUsedNonceOnchain=${lastUsedNonceOnchain} lastUsedNonceDb=${lastUsedNonceDb}, recycled=${recycled.join(",")}`;
79+
job.log(message);
80+
logger({ level: "debug", service: "worker", message });
81+
} catch (error) {
10582
logger({
106-
level: "debug",
107-
message: `[nonceResyncWorker] nonce ${_nonce} exists in nonce-sent set: ${exists}`,
83+
level: "error",
84+
message: `[nonceResyncWorker] ${prettifyError(error)}`,
10885
service: "worker",
10986
});
110-
111-
// If nonce does not exist in nonce-sent set, recycle it
112-
if (!exists) {
113-
await recycleNonce(chainId, walletAddress, _nonce);
114-
}
11587
}
11688
}
11789
};

src/worker/tasks/sendTransactionWorker.ts

Lines changed: 20 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -78,17 +78,15 @@ const handler: Processor<string, void, string> = async (job: Job<string>) => {
7878
// For example, the developer retried all failed transactions during an RPC outage.
7979
// An errored queued transaction (resendCount = 0) is safe to retry: the transaction wasn't sent to RPC.
8080
if (transaction.status === "errored" && resendCount === 0) {
81+
const { errorMessage, ...omitted } = transaction;
8182
transaction = {
82-
...{
83-
...transaction,
84-
nonce: undefined,
85-
errorMessage: undefined,
86-
gas: undefined,
87-
gasPrice: undefined,
88-
maxFeePerGas: undefined,
89-
maxPriorityFeePerGas: undefined,
90-
},
83+
...omitted,
9184
status: "queued",
85+
resendCount: 0,
86+
queueId: transaction.queueId,
87+
queuedAt: transaction.queuedAt,
88+
value: transaction.value,
89+
data: transaction.data,
9290
manuallyResentAt: new Date(),
9391
} satisfies QueuedTransaction;
9492
}
@@ -246,11 +244,14 @@ const _sendUserOp = async (
246244
waitForDeployment: false,
247245
})) as UserOperation; // TODO support entrypoint v0.7 accounts
248246
} catch (error) {
249-
return {
247+
const errorMessage = wrapError(error, "Bundler").message;
248+
const erroredTransaction: ErroredTransaction = {
250249
...queuedTransaction,
251250
status: "errored",
252-
errorMessage: wrapError(error, "Bundler").message,
253-
} satisfies ErroredTransaction;
251+
errorMessage,
252+
};
253+
job.log(`Failed to populate transaction: ${errorMessage}`);
254+
return erroredTransaction;
254255
}
255256

256257
job.log(`Populated userOp: ${stringify(signedUserOp)}`);
@@ -322,12 +323,15 @@ const _sendTransaction = async (
322323
maxPriorityFeePerGas: overrides?.maxPriorityFeePerGas,
323324
},
324325
});
325-
} catch (e: unknown) {
326-
return {
326+
} catch (error: unknown) {
327+
const errorMessage = wrapError(error, "RPC").message;
328+
const erroredTransaction: ErroredTransaction = {
327329
...queuedTransaction,
328330
status: "errored",
329-
errorMessage: wrapError(e, "RPC").message,
330-
} satisfies ErroredTransaction;
331+
errorMessage,
332+
};
333+
job.log(`Failed to populate transaction: ${errorMessage}`);
334+
return erroredTransaction;
331335
}
332336

333337
// Handle if `maxFeePerGas` is overridden.

0 commit comments

Comments
 (0)