Skip to content

Commit

Permalink
refactor: always use same provider
Browse files Browse the repository at this point in the history
  • Loading branch information
iamacook committed Jul 12, 2023
1 parent 35cb185 commit c6ca851
Show file tree
Hide file tree
Showing 37 changed files with 244 additions and 140 deletions.
4 changes: 2 additions & 2 deletions src/components/common/AddressInput/useNameResolver.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
import { useMemo } from 'react'
import { useWeb3ReadOnly } from '@/hooks/wallets/web3'
import { useWeb3 } from '@/hooks/wallets/web3'
import useAsync from '@/hooks/useAsync'
import { isDomain, resolveName } from '@/services/ens'
import useDebounce from '@/hooks/useDebounce'

const useNameResolver = (
value?: string,
): { address: string | undefined; resolverError?: Error; resolving: boolean } => {
const ethersProvider = useWeb3ReadOnly()
const ethersProvider = useWeb3()
const debouncedValue = useDebounce((value || '').trim(), 200)

// Fetch an ENS resolution for the current address
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ describe('useEstimateSafeCreationGas', () => {

it('should estimate gas', async () => {
const mockProvider = new JsonRpcProvider()
jest.spyOn(web3, 'useWeb3ReadOnly').mockReturnValue(mockProvider)
jest.spyOn(web3, 'useWeb3').mockReturnValue(mockProvider)
jest.spyOn(sender, 'estimateSafeCreationGas').mockReturnValue(Promise.resolve(BigNumber.from('123')))
jest.spyOn(wallet, 'default').mockReturnValue({
label: 'MetaMask',
Expand Down Expand Up @@ -69,7 +69,7 @@ describe('useEstimateSafeCreationGas', () => {
})

it('should not estimate gas if there is no provider', async () => {
jest.spyOn(web3, 'useWeb3ReadOnly').mockReturnValue(undefined)
jest.spyOn(web3, 'useWeb3').mockReturnValue(undefined)
const { result } = renderHook(() => useEstimateSafeCreationGas(mockProps))

await waitFor(() => {
Expand Down
2 changes: 1 addition & 1 deletion src/components/new-safe/create/logic/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ describe('checkSafeCreationTx', () => {
beforeEach(() => {
jest.resetAllMocks()

jest.spyOn(web3, 'getWeb3ReadOnly').mockImplementation(() => new Web3Provider(jest.fn()))
jest.spyOn(web3, '_getWeb3').mockImplementation(() => new Web3Provider(jest.fn()))

waitForTxSpy = jest.spyOn(provider, '_waitForTransaction')
jest.spyOn(provider, 'getBlockNumber').mockReturnValue(Promise.resolve(4))
Expand Down
4 changes: 2 additions & 2 deletions src/components/new-safe/create/steps/ReviewStep/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ import layoutCss from '@/components/new-safe/create/styles.module.css'
import { getReadOnlyFallbackHandlerContract } from '@/services/contracts/safeContracts'
import { computeNewSafeAddress } from '@/components/new-safe/create/logic'
import useWallet from '@/hooks/wallets/useWallet'
import { useWeb3 } from '@/hooks/wallets/web3'
import { isWeb3ReadOnly, useWeb3 } from '@/hooks/wallets/web3'
import useLocalStorage from '@/services/local-storage/useLocalStorage'
import { type PendingSafeData, SAFE_PENDING_CREATION_STORAGE_KEY } from '@/components/new-safe/create/steps/StatusStep'
import useSyncSafeCreationStep from '@/components/new-safe/create/useSyncSafeCreationStep'
Expand Down Expand Up @@ -77,7 +77,7 @@ const ReviewStep = ({ data, onSubmit, onBack, setStep }: StepRenderProps<NewSafe
}

const createSafe = async () => {
if (!wallet || !provider || !chain) return
if (!wallet || !provider || isWeb3ReadOnly(provider) || !chain) return

const readOnlyFallbackHandlerContract = getReadOnlyFallbackHandlerContract(chain.chainId)

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import * as wallet from '@/hooks/wallets/useWallet'
import * as logic from '@/components/new-safe/create/logic'
import * as contracts from '@/services/contracts/safeContracts'
import * as txMonitor from '@/services/tx/txMonitor'
import { JsonRpcProvider, Web3Provider } from '@ethersproject/providers'
import { Web3Provider } from '@ethersproject/providers'
import type { ConnectedWallet } from '@/hooks/wallets/useOnboard'
import type { ChainInfo } from '@safe-global/safe-gateway-typescript-sdk'
import { BigNumber } from '@ethersproject/bignumber'
Expand Down Expand Up @@ -40,7 +40,6 @@ describe('useSafeCreation', () => {
const mockStatus = SafeCreationStatus.AWAITING
const mockSetStatus = jest.fn()
const mockProvider: Web3Provider = new Web3Provider(jest.fn())
const mockReadOnlyProvider: JsonRpcProvider = new JsonRpcProvider()

beforeEach(() => {
jest.resetAllMocks()
Expand All @@ -51,8 +50,7 @@ describe('useSafeCreation', () => {
} as unknown as ChainInfo

jest.spyOn(web3, 'useWeb3').mockImplementation(() => mockProvider)
jest.spyOn(web3, 'getWeb3ReadOnly').mockImplementation(() => mockProvider)
jest.spyOn(web3, 'useWeb3ReadOnly').mockImplementation(() => mockReadOnlyProvider)
jest.spyOn(web3, '_getWeb3').mockImplementation(() => mockProvider)
jest.spyOn(chain, 'useCurrentChain').mockImplementation(() => mockChain)
jest.spyOn(wallet, 'default').mockReturnValue({} as ConnectedWallet)
jest.spyOn(logic, 'getSafeCreationTxInfo').mockReturnValue(Promise.resolve(mockSafeInfo))
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import type { Dispatch, SetStateAction } from 'react'
import { useCallback, useEffect, useState } from 'react'
import { useWeb3, useWeb3ReadOnly } from '@/hooks/wallets/web3'
import { isWeb3ReadOnly, useWeb3 } from '@/hooks/wallets/web3'
import { useCurrentChain } from '@/hooks/useChains'
import useWallet from '@/hooks/wallets/useWallet'
import type { EthersError } from '@/utils/ethers-utils'
Expand Down Expand Up @@ -50,7 +50,6 @@ export const useSafeCreation = (

const wallet = useWallet()
const provider = useWeb3()
const web3ReadOnly = useWeb3ReadOnly()
const chain = useCurrentChain()
const [gasPrice, , gasPriceLoading] = useGasPrice()

Expand All @@ -69,7 +68,8 @@ export const useSafeCreation = (
)

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

setIsCreating(true)
dispatch(closeByGroupKey({ groupKey: SAFE_CREATION_ERROR_KEY }))
Expand Down Expand Up @@ -137,15 +137,15 @@ export const useSafeCreation = (
])

const watchSafeTx = useCallback(async () => {
if (!pendingSafe?.tx || !pendingSafe?.txHash || !web3ReadOnly || isWatching) return
if (!pendingSafe?.tx || !pendingSafe?.txHash || !provider || isWatching) return

setStatus(SafeCreationStatus.PROCESSING)
setIsWatching(true)

const txStatus = await checkSafeCreationTx(web3ReadOnly, pendingSafe.tx, pendingSafe.txHash, dispatch)
const txStatus = await checkSafeCreationTx(provider, pendingSafe.tx, pendingSafe.txHash, dispatch)
setStatus(txStatus)
setIsWatching(false)
}, [isWatching, pendingSafe, web3ReadOnly, setStatus, dispatch])
}, [isWatching, pendingSafe, provider, setStatus, dispatch])

// Create or monitor Safe creation
useEffect(() => {
Expand Down
10 changes: 5 additions & 5 deletions src/components/new-safe/create/useEstimateSafeCreationGas.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import type { BigNumber } from 'ethers'
import { useWeb3ReadOnly } from '@/hooks/wallets/web3'
import { useWeb3 } from '@/hooks/wallets/web3'
import useWallet from '@/hooks/wallets/useWallet'
import useAsync from '@/hooks/useAsync'
import { useCurrentChain } from '@/hooks/useChains'
Expand All @@ -12,15 +12,15 @@ export const useEstimateSafeCreationGas = (
gasLimitError?: Error
gasLimitLoading: boolean
} => {
const web3ReadOnly = useWeb3ReadOnly()
const web3 = useWeb3()
const chain = useCurrentChain()
const wallet = useWallet()

const [gasLimit, gasLimitError, gasLimitLoading] = useAsync<BigNumber>(() => {
if (!wallet?.address || !chain || !web3ReadOnly) return
if (!wallet?.address || !chain || !web3) return

return estimateSafeCreationGas(chain, web3ReadOnly, wallet.address, safeParams)
}, [wallet, chain, web3ReadOnly, safeParams])
return estimateSafeCreationGas(chain, web3, wallet.address, safeParams)
}, [wallet, chain, web3, safeParams])

return { gasLimit, gasLimitError, gasLimitLoading }
}
16 changes: 4 additions & 12 deletions src/components/safe-apps/AppFrame/useAppCommunicator.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import type { MutableRefObject } from 'react'
import { useEffect, useMemo, useState } from 'react'
import { useEffect, useState } from 'react'
import { getAddress } from 'ethers/lib/utils'
import { BigNumber } from '@ethersproject/bignumber'
import type {
Expand Down Expand Up @@ -30,11 +30,9 @@ import { RPC_CALLS } from '@safe-global/safe-apps-sdk/dist/src/eth/constants'
import type { SafeSettings } from '@safe-global/safe-apps-sdk'
import AppCommunicator from '@/services/safe-apps/AppCommunicator'
import { Errors, logError } from '@/services/exceptions'
import { createSafeAppsWeb3Provider } from '@/hooks/wallets/web3'
import type { SafePermissionsRequest } from '@/hooks/safe-apps/permissions'
import { SAFE_APPS_EVENTS, trackSafeAppEvent } from '@/services/analytics'
import { useAppSelector } from '@/store'
import { selectRpc } from '@/store/settingsSlice'
import { useProvider } from '@/hooks/wallets/useProvider'

export enum CommunicatorMessages {
REJECT_TRANSACTION_MESSAGE = 'Transaction was rejected',
Expand Down Expand Up @@ -74,15 +72,9 @@ const useAppCommunicator = (
handlers: UseAppCommunicatorHandlers,
): AppCommunicator | undefined => {
const [communicator, setCommunicator] = useState<AppCommunicator | undefined>(undefined)
const customRpc = useAppSelector(selectRpc)

const safeAppWeb3Provider = useMemo(() => {
if (!chain) {
return
}

return createSafeAppsWeb3Provider(chain.rpcUri, customRpc?.[chain.chainId])
}, [chain, customRpc])
// Don't use `useWeb3` as we want Safe Apps provider when read only
const safeAppWeb3Provider = useProvider(true)

useEffect(() => {
let communicatorInstance: AppCommunicator
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import { SafeAppAccessPolicyTypes } from '@safe-global/safe-gateway-typescript-s

describe('SafeAppsSignMessageModal', () => {
test('can handle messages with EIP712Domain type in the JSON-RPC payload', () => {
jest.spyOn(web3, 'getWeb3ReadOnly').mockImplementation(() => new Web3Provider(jest.fn()))
jest.spyOn(web3, '_getWeb3').mockImplementation(() => new Web3Provider(jest.fn()))

render(
<SafeAppsSignMessageModal
Expand Down
2 changes: 1 addition & 1 deletion src/components/tx/TxSimulation/__tests__/utils.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ describe('simulation utils', () => {
.spyOn(safeContracts, 'getReadOnlyMultiSendCallOnlyContract')
.mockImplementation(() => multisendContractMock as any)

jest.spyOn(Web3, 'getWeb3ReadOnly').mockImplementation(
jest.spyOn(Web3, '_getWeb3').mockImplementation(
() =>
({
getBlock: () =>
Expand Down
6 changes: 3 additions & 3 deletions src/components/tx/TxSimulation/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import {
import { TENDERLY_SIMULATE_ENDPOINT_URL, TENDERLY_ORG_NAME, TENDERLY_PROJECT_NAME } from '@/config/constants'
import { FEATURES, hasFeature } from '@/utils/chains'
import type { StateObject, TenderlySimulatePayload, TenderlySimulation } from '@/components/tx/TxSimulation/types'
import { getWeb3ReadOnly } from '@/hooks/wallets/web3'
import { _getWeb3 } from '@/hooks/wallets/web3'
import { hexZeroPad } from 'ethers/lib/utils'
import { BigNumber } from 'ethers'
import type { EnvState } from '@/store/settingsSlice'
Expand Down Expand Up @@ -204,8 +204,8 @@ const getStateOverwrites = (params: SimulationTxParams) => {
}

const getLatestBlockGasLimit = async (): Promise<number> => {
const web3ReadOnly = getWeb3ReadOnly()
const latestBlock = await web3ReadOnly?.getBlock('latest')
const web3 = _getWeb3()
const latestBlock = await web3?.getBlock('latest')
if (!latestBlock) {
throw Error('Could not determine block gas limit')
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ import { ExecutionMethod, ExecutionMethodSelector } from '../../ExecutionMethodS
import { dispatchBatchExecution, dispatchBatchExecutionRelay } from '@/services/tx/tx-sender'
import useOnboard from '@/hooks/wallets/useOnboard'
import { WrongChainWarning } from '@/components/tx/WrongChainWarning'
import { useWeb3 } from '@/hooks/wallets/web3'
import { isWeb3ReadOnly, useWeb3 } from '@/hooks/wallets/web3'
import { hasRemainingRelays } from '@/utils/relaying'
import useGasPrice from '@/hooks/useGasPrice'
import { hasFeature } from '@/utils/chains'
Expand Down Expand Up @@ -53,7 +53,7 @@ const ReviewBatchExecute = ({ data, onSubmit }: { data: BatchExecuteData; onSubm
}, [data.txs, chain?.chainId])

const multiSendContract = useMemo(() => {
if (!chain?.chainId || !safe.version || !web3) return
if (!chain?.chainId || !safe.version || !web3 || isWeb3ReadOnly(web3)) return
return getMultiSendCallOnlyContract(chain.chainId, safe.version, web3)
}, [chain?.chainId, safe.version, web3])

Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import useChainId from '@/hooks/useChainId'
import { getSafeTokenAddress } from '@/components/common/SafeTokenWidget'
import { useWeb3ReadOnly } from '@/hooks/wallets/web3'
import { useWeb3 } from '@/hooks/wallets/web3'
import useAsync from '@/hooks/useAsync'
import { Contract } from 'ethers'
import { Interface } from '@ethersproject/abi'
Expand All @@ -10,7 +10,7 @@ const PAUSED_ABI = 'function paused() public view virtual returns (bool)'
// TODO: Remove this hook after the safe token has been unpaused
const useIsSafeTokenPaused = () => {
const chainId = useChainId()
const provider = useWeb3ReadOnly()
const provider = useWeb3()

const [isSafeTokenPaused] = useAsync<boolean>(async () => {
const safeTokenAddress = getSafeTokenAddress(chainId)
Expand Down
10 changes: 5 additions & 5 deletions src/components/tx/security/redefine/useRecipientModule.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import type { SafeTransaction } from '@safe-global/safe-core-sdk-types'
import useAddressBook from '@/hooks/useAddressBook'
import useAsync from '@/hooks/useAsync'
import useSafeInfo from '@/hooks/useSafeInfo'
import { useWeb3ReadOnly } from '@/hooks/wallets/web3'
import { useWeb3 } from '@/hooks/wallets/web3'
import { RecipientAddressModule } from '@/services/security/modules/RecipientAddressModule'
import type { RecipientAddressModuleResponse } from '@/services/security/modules/RecipientAddressModule'
import type { SecurityResponse } from '@/services/security/modules/types'
Expand All @@ -13,7 +13,7 @@ const RecipientAddressModuleInstance = new RecipientAddressModule()

export const useRecipientModule = (safeTransaction: SafeTransaction | undefined) => {
const { safe, safeLoaded } = useSafeInfo()
const web3ReadOnly = useWeb3ReadOnly()
const web3 = useWeb3()
const addressBook = useAddressBook()

const knownAddresses = useMemo(() => {
Expand All @@ -24,15 +24,15 @@ export const useRecipientModule = (safeTransaction: SafeTransaction | undefined)
}, [addressBook, safe.owners])

return useAsync<SecurityResponse<RecipientAddressModuleResponse>>(() => {
if (!safeTransaction || !web3ReadOnly || !safeLoaded) {
if (!safeTransaction || !web3 || !safeLoaded) {
return
}

return RecipientAddressModuleInstance.scanTransaction({
chainId: safe.chainId,
safeTransaction,
knownAddresses,
provider: web3ReadOnly,
provider: web3,
})
}, [safeTransaction, web3ReadOnly, safeLoaded, safe.chainId, knownAddresses, web3ReadOnly])
}, [safeTransaction, web3, safeLoaded, safe.chainId, knownAddresses, web3])
}
2 changes: 1 addition & 1 deletion src/hooks/__tests__/useAddressResolver.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ const mockProvider = new JsonRpcProvider()
describe('useAddressResolver', () => {
beforeEach(() => {
jest.resetAllMocks()
jest.spyOn(web3, 'useWeb3ReadOnly').mockImplementation(() => mockProvider)
jest.spyOn(web3, 'useWeb3').mockImplementation(() => mockProvider)
})

it('returns address book name if found, not resolving ENS domain', async () => {
Expand Down
4 changes: 2 additions & 2 deletions src/hooks/__tests__/useGasPrice.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { BigNumber } from 'ethers'
import { act, renderHook } from '@/tests/test-utils'
import useGasPrice from '@/hooks/useGasPrice'

// mock useWeb3Readonly
// mock useWeb3
jest.mock('../wallets/web3', () => {
const provider = {
getFeeData: jest.fn(() =>
Expand All @@ -14,7 +14,7 @@ jest.mock('../wallets/web3', () => {
),
}
return {
useWeb3ReadOnly: jest.fn(() => provider),
useWeb3: jest.fn(() => provider),
}
})

Expand Down
7 changes: 6 additions & 1 deletion src/hooks/__tests__/useIsValidExecution.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ import { JsonRpcProvider, Web3Provider } from '@ethersproject/providers'
import { type EIP1193Provider } from '@web3-onboard/core'
import * as contracts from '@/services/contracts/safeContracts'
import type GnosisSafeContractEthers from '@safe-global/safe-ethers-lib/dist/src/contracts/GnosisSafe/GnosisSafeContractEthers'
import * as useChains from '@/hooks/useChains'
import { type ChainInfo, RPC_AUTHENTICATION } from '@safe-global/safe-gateway-typescript-sdk'

const createSafeTx = (data = '0x'): SafeTransaction => {
return {
Expand Down Expand Up @@ -50,9 +52,12 @@ describe('useIsValidExecution', () => {
beforeEach(() => {
jest.resetAllMocks()

jest.spyOn(web3, 'useWeb3ReadOnly').mockImplementation(() => mockReadOnlyProvider)
jest
.spyOn(useChains, 'useCurrentChain')
.mockReturnValue({ rpcUri: { authentication: RPC_AUTHENTICATION.NO_AUTHENTICATION, value: '' } } as ChainInfo)
jest.spyOn(useWallet, 'default').mockReturnValue(mockWallet)
jest.spyOn(web3, 'createWeb3').mockImplementation(() => mockProvider)
jest.spyOn(web3, 'createWeb3ReadOnly').mockImplementation(() => mockReadOnlyProvider)
})

it('should append the error code description to the error thrown', async () => {
Expand Down
2 changes: 1 addition & 1 deletion src/hooks/__tests__/useLoadSpendingLimits.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -191,7 +191,7 @@ describe('getTokenAllowanceForDelegate', () => {
BigNumber.from(0),
])

jest.spyOn(web3, 'getWeb3ReadOnly').mockImplementation(
jest.spyOn(web3, '_getWeb3').mockImplementation(
() =>
({
call: (tx: { data: string; to: string }) => {
Expand Down
Loading

0 comments on commit c6ca851

Please sign in to comment.