Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: Safe creation/batch execution gas estimation #2232

Merged
merged 3 commits into from
Jul 10, 2023
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 15 additions & 3 deletions src/components/new-safe/create/steps/ReviewStep/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -26,14 +26,15 @@ import { ExecutionMethodSelector, ExecutionMethod } from '@/components/tx/Execut
import { useLeastRemainingRelays } from '@/hooks/useRemainingRelays'
import classnames from 'classnames'
import { hasRemainingRelays } from '@/utils/relaying'
import { BigNumber } from 'ethers'

const ReviewStep = ({ data, onSubmit, onBack, setStep }: StepRenderProps<NewSafeFormData>) => {
const isWrongChain = useIsWrongChain()
useSyncSafeCreationStep(setStep)
const chain = useCurrentChain()
const wallet = useWallet()
const provider = useWeb3()
const { maxFeePerGas, maxPriorityFeePerGas } = useGasPrice()
const [gasPrice] = useGasPrice()
const saltNonce = useMemo(() => Date.now(), [])
const [_, setPendingSafe] = useLocalStorage<PendingSafeData | undefined>(SAFE_PENDING_CREATION_STORAGE_KEY)
const [executionMethod, setExecutionMethod] = useState(ExecutionMethod.RELAY)
Expand All @@ -55,9 +56,20 @@ const ReviewStep = ({ data, onSubmit, onBack, setStep }: StepRenderProps<NewSafe

const { gasLimit } = useEstimateSafeCreationGas(safeParams)

const maxFeePerGas = gasPrice?.maxFeePerGas
const maxPriorityFeePerGas = gasPrice?.maxPriorityFeePerGas

const totalFee =
gasLimit && maxFeePerGas && maxPriorityFeePerGas
? formatVisualAmount(maxFeePerGas.add(maxPriorityFeePerGas).mul(gasLimit), chain?.nativeCurrency.decimals)
gasLimit && maxFeePerGas
? formatVisualAmount(
maxFeePerGas
.add(
// maxPriorityFeePerGas is undefined if EIP-1559 disabled
maxPriorityFeePerGas || BigNumber.from(0),
)
.mul(gasLimit),
chain?.nativeCurrency.decimals,
)
: '> 0.001'

const handleBack = () => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@ import { waitFor } from '@testing-library/react'
import type Safe from '@safe-global/safe-core-sdk'
import { hexZeroPad } from 'ethers/lib/utils'
import type CompatibilityFallbackHandlerEthersContract from '@safe-global/safe-ethers-lib/dist/src/contracts/CompatibilityFallbackHandler/CompatibilityFallbackHandlerEthersContract'
import { FEATURES } from '@/utils/chains'
import * as gasPrice from '@/hooks/useGasPrice'

const mockSafeInfo = {
data: '0x',
Expand Down Expand Up @@ -45,6 +47,7 @@ describe('useSafeCreation', () => {

const mockChain = {
chainId: '4',
features: [],
} as unknown as ChainInfo

jest.spyOn(web3, 'useWeb3').mockImplementation(() => mockProvider)
Expand All @@ -56,15 +59,89 @@ describe('useSafeCreation', () => {
jest
.spyOn(contracts, 'getReadOnlyFallbackHandlerContract')
.mockReturnValue({ getAddress: () => hexZeroPad('0x123', 20) } as CompatibilityFallbackHandlerEthersContract)
jest
.spyOn(gasPrice, 'default')
.mockReturnValue([{ maxFeePerGas: BigNumber.from(123), maxPriorityFeePerGas: undefined }, undefined, false])
})

it('should create a safe with gas params if there is no txHash and status is AWAITING', async () => {
const createSafeSpy = jest.spyOn(logic, 'createNewSafe').mockReturnValue(Promise.resolve({} as Safe))

renderHook(() => useSafeCreation(mockPendingSafe, mockSetPendingSafe, mockStatus, mockSetStatus, false))

await waitFor(() => {
expect(createSafeSpy).toHaveBeenCalled()

const { gasPrice, maxFeePerGas, maxPriorityFeePerGas } = createSafeSpy.mock.calls[0][1].options || {}

expect(gasPrice).toBe('123')

expect(maxFeePerGas).toBeUndefined()
expect(maxPriorityFeePerGas).toBeUndefined()
})
})

it('should create a safe with EIP-1559 gas params if there is no txHash and status is AWAITING', async () => {
jest
.spyOn(gasPrice, 'default')
.mockReturnValue([
{ maxFeePerGas: BigNumber.from(123), maxPriorityFeePerGas: BigNumber.from(456) },
undefined,
false,
])

jest.spyOn(chain, 'useCurrentChain').mockImplementation(
() =>
({
chainId: '4',
features: [FEATURES.EIP1559],
} as unknown as ChainInfo),
)
const createSafeSpy = jest.spyOn(logic, 'createNewSafe').mockReturnValue(Promise.resolve({} as Safe))

renderHook(() => useSafeCreation(mockPendingSafe, mockSetPendingSafe, mockStatus, mockSetStatus, false))

await waitFor(() => {
expect(createSafeSpy).toHaveBeenCalled()

const { gasPrice, maxFeePerGas, maxPriorityFeePerGas } = createSafeSpy.mock.calls[0][1].options || {}

expect(maxFeePerGas).toBe('123')
expect(maxPriorityFeePerGas).toBe('456')

expect(gasPrice).toBeUndefined()
})
})

it('should create a safe if there is no txHash and status is AWAITING', async () => {
it('should create a safe with no gas params if the gas estimation threw, there is no txHash and status is AWAITING', async () => {
jest
.spyOn(gasPrice, 'default')
.mockReturnValue([{ maxFeePerGas: undefined, maxPriorityFeePerGas: undefined }, undefined, false])
iamacook marked this conversation as resolved.
Show resolved Hide resolved

const createSafeSpy = jest.spyOn(logic, 'createNewSafe').mockReturnValue(Promise.resolve({} as Safe))

renderHook(() => useSafeCreation(mockPendingSafe, mockSetPendingSafe, mockStatus, mockSetStatus, false))

await waitFor(() => {
expect(createSafeSpy).toHaveBeenCalled()

const { gasPrice, maxFeePerGas, maxPriorityFeePerGas } = createSafeSpy.mock.calls[0][1].options || {}

expect(gasPrice).toBeUndefined()
expect(maxFeePerGas).toBeUndefined()
expect(maxPriorityFeePerGas).toBeUndefined()
})
})

it('should not create a safe if there is no txHash, status is AWAITING but gas is loading', async () => {
jest.spyOn(gasPrice, 'default').mockReturnValue([undefined, undefined, true])

const createSafeSpy = jest.spyOn(logic, 'createNewSafe').mockReturnValue(Promise.resolve({} as Safe))

renderHook(() => useSafeCreation(mockPendingSafe, mockSetPendingSafe, mockStatus, mockSetStatus, false))

await waitFor(() => {
expect(createSafeSpy).not.toHaveBeenCalled()
})
})

Expand Down
25 changes: 23 additions & 2 deletions src/components/new-safe/create/steps/StatusStep/useSafeCreation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,10 @@ import { useAppDispatch } from '@/store'
import { closeByGroupKey } from '@/store/notificationsSlice'
import { CREATE_SAFE_EVENTS, trackEvent } from '@/services/analytics'
import { waitForCreateSafeTx } from '@/services/tx/txMonitor'
import useGasPrice from '@/hooks/useGasPrice'
import { hasFeature } from '@/utils/chains'
import { FEATURES } from '@safe-global/safe-gateway-typescript-sdk'
import type { DeploySafeProps } from '@safe-global/safe-core-sdk'

export enum SafeCreationStatus {
AWAITING,
Expand Down Expand Up @@ -48,6 +52,12 @@ export const useSafeCreation = (
const provider = useWeb3()
const web3ReadOnly = useWeb3ReadOnly()
const chain = useCurrentChain()
const [gasPrice, , gasPriceLoading] = useGasPrice()

const maxFeePerGas = gasPrice?.maxFeePerGas
const maxPriorityFeePerGas = gasPrice?.maxPriorityFeePerGas

const isEIP1559 = chain && hasFeature(chain, FEATURES.EIP1559)

const createSafeCallback = useCallback(
async (txHash: string, tx: PendingSafeTx) => {
Expand All @@ -59,7 +69,7 @@ export const useSafeCreation = (
)

const handleCreateSafe = useCallback(async () => {
if (!pendingSafe || !provider || !chain || !wallet || isCreating) return
if (!pendingSafe || !provider || !chain || !wallet || isCreating || gasPriceLoading) return

setIsCreating(true)
dispatch(closeByGroupKey({ groupKey: SAFE_CREATION_ERROR_KEY }))
Expand Down Expand Up @@ -87,7 +97,14 @@ export const useSafeCreation = (
chain.chainId,
)

await createNewSafe(provider, safeParams)
const options: DeploySafeProps['options'] = isEIP1559
? { maxFeePerGas: maxFeePerGas?.toString(), maxPriorityFeePerGas: maxPriorityFeePerGas?.toString() }
: { gasPrice: maxFeePerGas?.toString() }

await createNewSafe(provider, {
...safeParams,
options,
})
setStatus(SafeCreationStatus.SUCCESS)
}
} catch (err) {
Expand All @@ -106,7 +123,11 @@ export const useSafeCreation = (
chain,
createSafeCallback,
dispatch,
gasPriceLoading,
isCreating,
isEIP1559,
maxFeePerGas,
maxPriorityFeePerGas,
pendingSafe,
provider,
setPendingSafe,
Expand Down
8 changes: 4 additions & 4 deletions src/components/tx/AdvancedParams/useAdvancedParams.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,19 +9,19 @@ export const useAdvancedParams = ({
safeTxGas,
}: AdvancedParameters): [AdvancedParameters, (params: AdvancedParameters) => void] => {
const [manualParams, setManualParams] = useState<AdvancedParameters>()
const { maxFeePerGas, maxPriorityFeePerGas } = useGasPrice()
const [gasPrice] = useGasPrice()
const userNonce = useUserNonce()

const advancedParams: AdvancedParameters = useMemo(
() => ({
nonce: manualParams?.nonce ?? nonce,
userNonce: manualParams?.userNonce ?? userNonce,
gasLimit: manualParams?.gasLimit ?? gasLimit,
maxFeePerGas: manualParams?.maxFeePerGas ?? maxFeePerGas,
maxPriorityFeePerGas: manualParams?.maxPriorityFeePerGas ?? maxPriorityFeePerGas,
maxFeePerGas: manualParams?.maxFeePerGas ?? gasPrice?.maxFeePerGas,
maxPriorityFeePerGas: manualParams?.maxPriorityFeePerGas ?? gasPrice?.maxPriorityFeePerGas,
safeTxGas: manualParams?.safeTxGas ?? safeTxGas,
}),
[manualParams, nonce, userNonce, gasLimit, maxFeePerGas, maxPriorityFeePerGas, safeTxGas],
[manualParams, nonce, userNonce, gasLimit, gasPrice?.maxFeePerGas, gasPrice?.maxPriorityFeePerGas, safeTxGas],
)

return [advancedParams, setManualParams]
Expand Down
19 changes: 17 additions & 2 deletions src/components/tx/modals/BatchExecuteModal/ReviewBatchExecute.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import useAsync from '@/hooks/useAsync'
import { FEATURES } from '@safe-global/safe-gateway-typescript-sdk'
import type { TransactionDetails } from '@safe-global/safe-gateway-typescript-sdk'
import { getMultiSendCallOnlyContract } from '@/services/contracts/safeContracts'
import { useCurrentChain } from '@/hooks/useChains'
Expand All @@ -21,6 +22,9 @@ import useOnboard from '@/hooks/wallets/useOnboard'
import { WrongChainWarning } from '@/components/tx/WrongChainWarning'
import { useWeb3 } from '@/hooks/wallets/web3'
import { hasRemainingRelays } from '@/utils/relaying'
import useGasPrice from '@/hooks/useGasPrice'
import { hasFeature } from '@/utils/chains'
import type { PayableOverrides } from 'ethers'

const ReviewBatchExecute = ({ data, onSubmit }: { data: BatchExecuteData; onSubmit: (data: null) => void }) => {
const [isSubmittable, setIsSubmittable] = useState<boolean>(true)
Expand All @@ -29,6 +33,12 @@ const ReviewBatchExecute = ({ data, onSubmit }: { data: BatchExecuteData; onSubm
const chain = useCurrentChain()
const { safe } = useSafeInfo()
const [relays] = useRelaysBySafe()
const [gasPrice, , gasPriceLoading] = useGasPrice()

const maxFeePerGas = gasPrice?.maxFeePerGas
const maxPriorityFeePerGas = gasPrice?.maxPriorityFeePerGas

const isEIP1559 = chain && hasFeature(chain, FEATURES.EIP1559)

// Chain has relaying feature and available relays
const canRelay = hasRemainingRelays(relays)
Expand Down Expand Up @@ -58,7 +68,11 @@ const ReviewBatchExecute = ({ data, onSubmit }: { data: BatchExecuteData; onSubm
}, [txsWithDetails, multiSendTxs])

const onExecute = async () => {
if (!onboard || !multiSendTxData || !multiSendContract || !txsWithDetails) return
if (!onboard || !multiSendTxData || !multiSendContract || !txsWithDetails || gasPriceLoading) return

const overrides: PayableOverrides = isEIP1559
? { maxFeePerGas: maxFeePerGas?.toString(), maxPriorityFeePerGas: maxPriorityFeePerGas?.toString() }
: { gasPrice: maxFeePerGas?.toString() }

await dispatchBatchExecution(
txsWithDetails,
Expand All @@ -67,6 +81,7 @@ const ReviewBatchExecute = ({ data, onSubmit }: { data: BatchExecuteData; onSubm
onboard,
safe.chainId,
safe.address.value,
overrides,
)
onSubmit(null)
}
Expand Down Expand Up @@ -100,7 +115,7 @@ const ReviewBatchExecute = ({ data, onSubmit }: { data: BatchExecuteData; onSubm
}
}

const submitDisabled = loading || !isSubmittable
const submitDisabled = loading || !isSubmittable || gasPriceLoading

return (
<div>
Expand Down
Loading
Loading