File tree Expand file tree Collapse file tree 1 file changed +13
-5
lines changed Expand file tree Collapse file tree 1 file changed +13
-5
lines changed Original file line number Diff line number Diff line change 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
1011const globalNonceManager = new Map < string , number > ( ) ;
1112
1213async 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}
You can’t perform that action at this time.
0 commit comments