Skip to content

Commit 3461d00

Browse files
committed
fix(e2e): improve nonce management logic to prevent concurrent collisions
1 parent 7e0de65 commit 3461d00

File tree

1 file changed

+13
-5
lines changed

1 file changed

+13
-5
lines changed

packages/e2e/src/helper/fundAccount.ts

Lines changed: 13 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ import {
77
} from 'viem';
88

99
// Global nonce manager to track nonces per account address
10+
// Tracks the next nonce to use per account to prevent concurrent collisions
1011
const globalNonceManager = new Map<string, number>();
1112

1213
async function getNextNonce(
@@ -19,14 +20,21 @@ async function getNextNonce(
1920
blockTag: 'pending',
2021
});
2122

22-
const localNonce = globalNonceManager.get(accountAddress) || 0;
23+
const cachedNextNonce = globalNonceManager.get(accountAddress);
2324

24-
// Use the higher of network nonce or local nonce + 1
25-
const nextNonce = Math.max(networkNonce, localNonce + 1);
26-
globalNonceManager.set(accountAddress, nextNonce);
25+
// If we have a cached value, ensure we never go backwards relative to the network
26+
const nextNonce =
27+
cachedNextNonce !== undefined
28+
? Math.max(cachedNextNonce, networkNonce)
29+
: networkNonce;
30+
31+
// Store the following nonce for the next caller
32+
globalNonceManager.set(accountAddress, nextNonce + 1);
2733

2834
console.log(
29-
`🔢 Using nonce ${nextNonce} for ${accountAddress} (network: ${networkNonce}, local: ${localNonce})`
35+
`🔢 Using nonce ${nextNonce} for ${accountAddress} (network: ${networkNonce}, cached: ${
36+
cachedNextNonce ?? 'unset'
37+
})`
3038
);
3139
return nextNonce;
3240
}

0 commit comments

Comments
 (0)