Skip to content

Commit 2a77c4b

Browse files
committed
lua script default to 0
1 parent 41c3f1f commit 2a77c4b

File tree

2 files changed

+9
-8
lines changed

2 files changed

+9
-8
lines changed

src/db/wallets/walletNonce.ts

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -194,7 +194,7 @@ export const deleteAllNonces = async () => {
194194
* @param chainId
195195
* @param walletAddress
196196
*/
197-
export const rebaseNonce = async (chainId: number, walletAddress: Address) => {
197+
export const resyncNonce = async (chainId: number, walletAddress: Address) => {
198198
const rpcRequest = getRpcClient({
199199
client: thirdwebClient,
200200
chain: await getChain(chainId),
@@ -205,10 +205,10 @@ export const rebaseNonce = async (chainId: number, walletAddress: Address) => {
205205
address: walletAddress,
206206
});
207207

208-
// Lua script to set nonce as max
208+
// Lua script to update the DB nonce only if the onchain nonce is higher.
209209
const script = `
210210
local transactionCount = tonumber(ARGV[1])
211-
local lastUsedNonce = tonumber(redis.call('get', KEYS[1]))
211+
local lastUsedNonce = tonumber(redis.call('get', KEYS[1])) or 0
212212
local nextNonce = math.max(transactionCount-1, lastUsedNonce)
213213
redis.call('set', KEYS[1], nextNonce)
214214
return nextNonce

src/worker/tasks/sendTransactionWorker.ts

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -10,8 +10,8 @@ import { TransactionDB } from "../../db/transactions/db";
1010
import {
1111
acquireNonce,
1212
addSentNonce,
13-
rebaseNonce,
1413
recycleNonce,
14+
resyncNonce,
1515
} from "../../db/wallets/walletNonce";
1616
import { getAccount } from "../../utils/account";
1717
import { getBlockNumberish } from "../../utils/block";
@@ -174,12 +174,13 @@ const _sendTransaction = async (
174174
transactionHash = sendTransactionResult.transactionHash;
175175
job.log(`Sent transaction: ${transactionHash}`);
176176
} catch (error: unknown) {
177-
// If NonceAlreadyUsedError, which can also manifest as a ReplacementGasFeeTooLowError,
178-
// recycle the nonce and retry the transaction.
177+
// If the nonce is already seen onchain (nonce too low) or in mempool (replacement underpriced),
178+
// correct the DB nonce.
179179
if (isNonceAlreadyUsedError(error) || isReplacementGasFeeTooLow(error)) {
180-
const resyncNonce = await rebaseNonce(chainId, from);
181-
job.log(`Resynced nonce to ${resyncNonce}.`);
180+
const result = await resyncNonce(chainId, from);
181+
job.log(`Resynced nonce to ${result}.`);
182182
} else {
183+
// Otherwise this nonce is not used yet. Recycle it to be used by a future transaction.
183184
job.log(`Recycling nonce: ${nonce}`);
184185
await recycleNonce(chainId, from, nonce);
185186
}

0 commit comments

Comments
 (0)