From f8db2788f42b72dc8d619a7ed4c2d0cc593b1a5a Mon Sep 17 00:00:00 2001 From: Kelvin Fichter Date: Tue, 10 May 2022 18:35:42 -0400 Subject: [PATCH] fix(sdk): bug causing error when no tx nonce given Fixes a bug in the SDK that would throw an error when the user did not provide a nonce along with the transaction (when estimating gas). If no nonce is provided, will try to find a reasonable nonce or use a default (large) nonce that will give a good upper bound for the L1 gas cost. --- .changeset/smart-readers-remember.md | 5 +++++ packages/sdk/src/l2-provider.ts | 25 +++++++++++++++++++++++-- 2 files changed, 28 insertions(+), 2 deletions(-) create mode 100644 .changeset/smart-readers-remember.md diff --git a/.changeset/smart-readers-remember.md b/.changeset/smart-readers-remember.md new file mode 100644 index 0000000000000..bd19d949e5391 --- /dev/null +++ b/.changeset/smart-readers-remember.md @@ -0,0 +1,5 @@ +--- +'@eth-optimism/sdk': patch +--- + +Fixes a bug in the SDK which would cause the SDK to throw if no tx nonce is provided diff --git a/packages/sdk/src/l2-provider.ts b/packages/sdk/src/l2-provider.ts index 5fa2b7a2f4ac9..9b41c7891c095 100644 --- a/packages/sdk/src/l2-provider.ts +++ b/packages/sdk/src/l2-provider.ts @@ -11,6 +11,27 @@ import { toProvider, toNumber, toBigNumber } from './utils' type ProviderTypeIsWrong = any +/** + * Gets a reasonable nonce for the transaction. + * + * @param provider Provider to get the nonce from. + * @param tx Requested transaction. + * @returns A reasonable nonce for the transaction. + */ +const getNonceForTx = async ( + provider: ProviderLike, + tx: TransactionRequest +): Promise => { + if (tx.nonce !== undefined) { + return toNumber(tx.nonce as NumberLike) + } else if (tx.from !== undefined) { + return toProvider(provider).getTransactionCount(tx.from) + } else { + // Large nonce with lots of non-zero bytes + return 0xffffffff + } +} + /** * Returns a Contract object for the GasPriceOracle. * @@ -57,7 +78,7 @@ export const estimateL1Gas = async ( gasPrice: tx.gasPrice, type: tx.type, gasLimit: tx.gasLimit, - nonce: toNumber(tx.nonce as NumberLike), + nonce: await getNonceForTx(l2Provider, tx), }) ) } @@ -81,7 +102,7 @@ export const estimateL1GasCost = async ( gasPrice: tx.gasPrice, type: tx.type, gasLimit: tx.gasLimit, - nonce: toNumber(tx.nonce as NumberLike), + nonce: await getNonceForTx(l2Provider, tx), }) ) }