Skip to content

Commit

Permalink
refactor: move invalid nonce logic to SafeTxProvider
Browse files Browse the repository at this point in the history
  • Loading branch information
schmanu committed Aug 14, 2023
1 parent 2360c6b commit 76d7e6f
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 10 deletions.
8 changes: 6 additions & 2 deletions src/components/tx-flow/SafeTxProvider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import type { SafeTransaction } from '@safe-global/safe-core-sdk-types'
import { createTx } from '@/services/tx/tx-sender'
import { useRecommendedNonce, useSafeTxGas } from '../tx/SignOrExecuteForm/hooks'
import { Errors, logError } from '@/services/exceptions'
import useSafeInfo from '@/hooks/useSafeInfo'

export const SafeTxContext = createContext<{
safeTx?: SafeTransaction
Expand Down Expand Up @@ -36,15 +37,18 @@ const SafeTxProvider = ({ children }: { children: ReactNode }): ReactElement =>
const [nonceNeeded, setNonceNeeded] = useState<boolean>(true)
const [safeTxGas, setSafeTxGas] = useState<number>()

const { safe } = useSafeInfo()

// Signed txs cannot be updated
const isSigned = safeTx && safeTx.signatures.size > 0

// Recommended nonce and safeTxGas
const recommendedNonce = useRecommendedNonce()
const recommendedSafeTxGas = useSafeTxGas(safeTx)

// Priority to external nonce, then to the recommended one
const finalNonce = isSigned ? safeTx?.data.nonce : nonce ?? recommendedNonce ?? safeTx?.data.nonce
// Priority to external nonce if valid, then to the recommended one
const isNonceValid = nonce !== undefined && nonce >= safe.nonce
const finalNonce = isSigned ? safeTx?.data.nonce : isNonceValid ? nonce : recommendedNonce ?? safeTx?.data.nonce
const finalSafeTxGas = isSigned ? safeTx?.data.safeTxGas : safeTxGas ?? recommendedSafeTxGas ?? safeTx?.data.safeTxGas

// Update the tx when the nonce or safeTxGas change
Expand Down
11 changes: 3 additions & 8 deletions src/components/tx-flow/common/TxNonce/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -109,15 +109,10 @@ const TxNonceForm = ({ nonce, recommendedNonce }: { nonce: string; recommendedNo
formMethods.setValue(TxNonceFormFieldNames.NONCE, recommendedNonce)
}

const currentFormNonce = formMethods.watch(TxNonceFormFieldNames.NONCE)
const isFormChanged = formMethods.formState.isDirty

// Update to recommended nonce if the current nonce is unchanged and invalid after update
// keep the formdata up-to-date when the actually used nonce updates
useEffect(() => {
if (!isFormChanged && Number(currentFormNonce) < safe.nonce) {
formMethods.setValue(TxNonceFormFieldNames.NONCE, safe.nonce.toString())
}
}, [safe.nonce, currentFormNonce, isFormChanged, formMethods])
formMethods.setValue(TxNonceFormFieldNames.NONCE, nonce)
}, [nonce, formMethods])

return (
<Controller
Expand Down

0 comments on commit 76d7e6f

Please sign in to comment.