Skip to content

Commit

Permalink
fix: avoid nonce gap in nonceManager (wevm#3142)
Browse files Browse the repository at this point in the history
  • Loading branch information
0xrouss committed Dec 21, 2024
1 parent 1ffb683 commit ec689f7
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 21 deletions.
5 changes: 5 additions & 0 deletions .changeset/brave-cooks-carry.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"viem": patch
---

Fixed an issue that caused the nonce to increment prematurely in prepareTransactionRequest, resulting in possible nonce gaps. Now the nonce manager logic is arranged so that gas estimation is performed first, ensuring no wasted nonce if gas estimation fails
43 changes: 22 additions & 21 deletions src/actions/wallet/prepareTransactionRequest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -316,26 +316,6 @@ export async function prepareTransactionRequest<

if (parameters.includes('chainId')) request.chainId = await getChainId()

if (parameters.includes('nonce') && typeof nonce === 'undefined' && account) {
if (nonceManager) {
const chainId = await getChainId()
request.nonce = await nonceManager.consume({
address: account.address,
chainId,
client,
})
} else {
request.nonce = await getAction(
client,
getTransactionCount,
'getTransactionCount',
)({
address: account.address,
blockTag: 'pending',
})
}
}

if (
(parameters.includes('fees') || parameters.includes('type')) &&
typeof type === 'undefined'
Expand Down Expand Up @@ -403,7 +383,7 @@ export async function prepareTransactionRequest<
}
}

if (parameters.includes('gas') && typeof gas === 'undefined')
if (parameters.includes('gas') && typeof gas === 'undefined') {
request.gas = await getAction(
client,
estimateGas,
Expand All @@ -414,6 +394,27 @@ export async function prepareTransactionRequest<
? { address: account.address, type: 'json-rpc' }
: account,
} as EstimateGasParameters)
}

if (parameters.includes('nonce') && typeof nonce === 'undefined' && account) {
if (nonceManager) {
const chainId = await getChainId()
request.nonce = await nonceManager.consume({
address: account.address,
chainId,
client,
})
} else {
request.nonce = await getAction(
client,
getTransactionCount,
'getTransactionCount',
)({
address: account.address,
blockTag: 'pending',
})
}
}

assertRequest(request as AssertRequestParameters)

Expand Down

0 comments on commit ec689f7

Please sign in to comment.