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

wallet connection #70

Merged
merged 4 commits into from
Jan 24, 2024
Merged
Show file tree
Hide file tree
Changes from all 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
23 changes: 0 additions & 23 deletions src/components/Web3Provider/index.tsx
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
import { useWeb3React, Web3ReactHooks, Web3ReactProvider } from '@web3-react/core'
import { Connector } from '@web3-react/types'
import { connections, getConnection } from 'connection'
import { isSupportedChain } from 'constants/chains'
import { RPC_PROVIDERS } from 'constants/providers'
import usePrevious from 'hooks/usePrevious'
import { ReactNode, useEffect } from 'react'
import { useLocation } from 'react-router-dom'
Expand All @@ -11,7 +9,6 @@ import { getCurrentPageFromLocation } from 'utils/urlRoutes'

export default function Web3Provider({ children }: { children: ReactNode }) {
const connectors = connections.map<[Connector, Web3ReactHooks]>(({ hooks, connector }) => [connector, hooks])

return (
<Web3ReactProvider connectors={connectors}>
<Updater />
Expand All @@ -26,18 +23,6 @@ function Updater() {
const { pathname } = useLocation()
const currentPage = getCurrentPageFromLocation(pathname)

const providers = RPC_PROVIDERS

// Trace RPC calls (for debugging).
const networkProvider = isSupportedChain(chainId) ? providers[chainId] : undefined
useEffect(() => {
return () => {
provider?.off('debug', trace)
networkProvider?.off('debug', trace)
}
}, [networkProvider, provider])

// Send analytics events when the active account changes.
const previousAccount = usePrevious(account)
const [connectedWallets, addConnectedWallet] = useConnectedWallets()
useEffect(() => {
Expand All @@ -49,11 +34,3 @@ function Updater() {

return null
}

function trace(event: any) {
if (!event?.request) return
const { method, id, params } = event.request
console.groupCollapsed(method, id)
console.debug(params)
console.groupEnd()
}
41 changes: 20 additions & 21 deletions src/connection/eagerlyConnect.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { Connector } from '@web3-react/types'
import { useSyncExternalStore } from 'react'

import { deprecatedNetworkConnection, getConnection, gnosisSafeConnection } from './index'
import { getConnection, gnosisSafeConnection, networkConnection } from './index'
import { deletePersistedConnectionMeta, getPersistedConnectionMeta } from './meta'
import { ConnectionType } from './types'

Expand Down Expand Up @@ -43,27 +43,26 @@ async function connect(connector: Connector, type: ConnectionType) {
if (window !== window.parent) {
connect(gnosisSafeConnection.connector, ConnectionType.GNOSIS_SAFE)
}
connect(deprecatedNetworkConnection.connector, ConnectionType.DEPRECATED_NETWORK)

connect(networkConnection.connector, ConnectionType.NETWORK)

// Get the persisted wallet type from the last session.
const meta = getPersistedConnectionMeta()
if (meta?.type) {
const selectedConnection = getConnection(meta.type)
if (selectedConnection) {
connectionReady = connect(selectedConnection.connector, meta.type)
.then((connected) => {
if (!connected) throw new FailedToConnect()
})
.catch((error) => {
// Clear the persisted wallet type if it failed to connect.
deletePersistedConnectionMeta()
// Log it if it threw an unknown error.
if (!(error instanceof FailedToConnect)) {
console.error(error)
}
})
.finally(() => {
connectionReady = true
})
}
const selectedConnection = meta?.type ? getConnection(meta.type) : undefined
if (selectedConnection && meta?.type) {
connectionReady = connect(selectedConnection.connector, meta.type)
.then((connected) => {
if (!connected) throw new FailedToConnect()
})
.catch((error) => {
// Clear the persisted wallet type if it failed to connect.
deletePersistedConnectionMeta()
// Log it if it threw an unknown error.
if (!(error instanceof FailedToConnect)) {
console.error(error)
}
})
.finally(() => {
connectionReady = true
})
}
23 changes: 2 additions & 21 deletions src/connection/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import COINBASE_ICON from 'assets/wallets/coinbase-icon.svg'
import { isMobile } from 'utils/userAgent'

import { RPC_URLS } from '../constants/networks'
import { DEPRECATED_RPC_PROVIDERS, RPC_PROVIDERS } from '../constants/providers'
import { RPC_PROVIDERS } from '../constants/providers'
import { Connection, ConnectionType } from './types'
import { getInjection, getIsCoinbaseWallet, getIsInjected, getIsMetaMaskWallet } from './utils'

Expand All @@ -30,17 +30,6 @@ export const networkConnection: Connection = {
shouldDisplay: () => false,
}

const [deprecatedWeb3Network, deprecatedWeb3NetworkHooks] = initializeConnector<Network>(
(actions) => new Network({ actions, urlMap: DEPRECATED_RPC_PROVIDERS, defaultChainId: 1 })
)
export const deprecatedNetworkConnection: Connection = {
getName: () => 'Network',
connector: deprecatedWeb3Network,
hooks: deprecatedWeb3NetworkHooks,
type: ConnectionType.NETWORK,
shouldDisplay: () => false,
}

const getIsCoinbaseWalletBrowser = () => isMobile && getIsCoinbaseWallet()
const getIsMetaMaskBrowser = () => isMobile && getIsMetaMaskWallet()
const getIsInjectedMobileBrowser = () => getIsCoinbaseWalletBrowser() || getIsMetaMaskBrowser()
Expand Down Expand Up @@ -108,13 +97,7 @@ const coinbaseWalletConnection: Connection = {
},
}

export const connections = [
gnosisSafeConnection,
injectedConnection,
coinbaseWalletConnection,
networkConnection,
deprecatedNetworkConnection,
]
export const connections = [gnosisSafeConnection, injectedConnection, coinbaseWalletConnection, networkConnection]

export function getConnection(c: Connector | ConnectionType) {
if (c instanceof Connector) {
Expand All @@ -131,8 +114,6 @@ export function getConnection(c: Connector | ConnectionType) {
return coinbaseWalletConnection
case ConnectionType.NETWORK:
return networkConnection
case ConnectionType.DEPRECATED_NETWORK:
return deprecatedNetworkConnection
case ConnectionType.GNOSIS_SAFE:
return gnosisSafeConnection
}
Expand Down
1 change: 0 additions & 1 deletion src/connection/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ export enum ConnectionType {
COINBASE_WALLET = 'COINBASE_WALLET',
NETWORK = 'NETWORK',
GNOSIS_SAFE = 'GNOSIS_SAFE',
DEPRECATED_NETWORK = 'DEPRECATED_NETWORK',
}

export function toConnectionType(value = ''): ConnectionType | undefined {
Expand Down
17 changes: 0 additions & 17 deletions src/constants/providers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,20 +31,3 @@ export const RPC_PROVIDERS: { [key in SupportedInterfaceChain]: StaticJsonRpcPro
[ChainId.AVALANCHE]: providerFactory(ChainId.AVALANCHE),
[ChainId.BASE]: providerFactory(ChainId.BASE),
}

export const DEPRECATED_RPC_PROVIDERS: { [key in SupportedInterfaceChain]: AppStaticJsonRpcProvider } = {
[ChainId.MAINNET]: providerFactory(ChainId.MAINNET),
[ChainId.GOERLI]: providerFactory(ChainId.GOERLI),
[ChainId.SEPOLIA]: providerFactory(ChainId.SEPOLIA),
[ChainId.OPTIMISM]: providerFactory(ChainId.OPTIMISM),
[ChainId.OPTIMISM_GOERLI]: providerFactory(ChainId.OPTIMISM_GOERLI),
[ChainId.ARBITRUM_ONE]: providerFactory(ChainId.ARBITRUM_ONE),
[ChainId.ARBITRUM_GOERLI]: providerFactory(ChainId.ARBITRUM_GOERLI),
[ChainId.POLYGON]: providerFactory(ChainId.POLYGON),
[ChainId.POLYGON_MUMBAI]: providerFactory(ChainId.POLYGON_MUMBAI),
[ChainId.CELO]: providerFactory(ChainId.CELO),
[ChainId.CELO_ALFAJORES]: providerFactory(ChainId.CELO_ALFAJORES),
[ChainId.BNB]: providerFactory(ChainId.BNB),
[ChainId.AVALANCHE]: providerFactory(ChainId.AVALANCHE),
[ChainId.BASE]: providerFactory(ChainId.BASE),
}
74 changes: 0 additions & 74 deletions src/hooks/useDebouncedTrade.test.ts

This file was deleted.

6 changes: 2 additions & 4 deletions src/hooks/useFetchListCallback.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,15 +11,13 @@ import { fetchTokenList } from '../state/lists/actions'

export function useFetchListCallback(): (listUrl: string, skipValidation?: boolean) => Promise<TokenList> {
const dispatch = useAppDispatch()
const providers = RPC_PROVIDERS

return useCallback(
async (listUrl: string, skipValidation?: boolean) => {
const requestId = nanoid()
dispatch(fetchTokenList.pending({ requestId, url: listUrl }))
return getTokenList(
listUrl,
(ensName: string) => resolveENSContentHash(ensName, providers[ChainId.MAINNET]),
(ensName: string) => resolveENSContentHash(ensName, RPC_PROVIDERS[ChainId.MAINNET]),

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we have this use built-in only if no wallet or wallet is not mainnet? That way if you are using Uniswap on Ethereum Mainnet it will use your wallet for ENS.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yeah we can, I just felt this PR was big enough not to add more stuff to it

skipValidation
)
.then((tokenList) => {
Expand All @@ -32,6 +30,6 @@ export function useFetchListCallback(): (listUrl: string, skipValidation?: boole
throw error
})
},
[dispatch, providers]
[dispatch]
)
}
4 changes: 2 additions & 2 deletions src/hooks/useSwitchChain.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { ChainId } from '@uniswap/sdk-core'
import { Connector } from '@web3-react/types'
import { deprecatedNetworkConnection, networkConnection } from 'connection'
import { networkConnection } from 'connection'
import { getChainInfo } from 'constants/chainInfo'
import { isSupportedChain, SupportedInterfaceChain } from 'constants/chains'
import { FALLBACK_URLS, RPC_URLS } from 'constants/networks'
Expand Down Expand Up @@ -32,7 +32,7 @@ export function useSwitchChain() {
} else {
dispatch(startSwitchingChain(chainId))
try {
if ([networkConnection.connector, deprecatedNetworkConnection.connector].includes(connector)) {
if ([networkConnection.connector].includes(connector)) {
await connector.activate(chainId)
} else {
const info = getChainInfo(chainId)
Expand Down
35 changes: 28 additions & 7 deletions src/lib/hooks/routing/clientSideSmartOrderRouter.ts
Original file line number Diff line number Diff line change
@@ -1,25 +1,46 @@
import type { Web3Provider } from '@ethersproject/providers'
import { BigintIsh, ChainId, CurrencyAmount, Token, TradeType } from '@uniswap/sdk-core'
// This file is lazy-loaded, so the import of smart-order-router is intentional.
// eslint-disable-next-line @typescript-eslint/no-restricted-imports
import { AlphaRouter, AlphaRouterConfig } from '@uniswap/smart-order-router'
import { asSupportedChain } from 'constants/chains'
import { DEPRECATED_RPC_PROVIDERS } from 'constants/providers'
import { RPC_PROVIDERS } from 'constants/providers'
import { nativeOnChain } from 'constants/tokens'
import JSBI from 'jsbi'
import AppStaticJsonRpcProvider from 'rpc/StaticJsonRpcProvider'
import { GetQuoteArgs, QuoteResult, QuoteState, SwapRouterNativeAssets } from 'state/routing/types'
import { transformSwapRouteToGetQuoteResult } from 'utils/transformSwapRouteToGetQuoteResult'

const routers = new Map<ChainId, AlphaRouter>()
export function getRouter(chainId: ChainId): AlphaRouter {
type RouterAndProvider = { router: AlphaRouter; provider: AppStaticJsonRpcProvider | Web3Provider }
let cachedProviderRouter: { chainId: number; routerProvider: RouterAndProvider } | undefined = undefined
const routers = new Map<ChainId, RouterAndProvider>()
export function getRouter(chainId: ChainId, web3Provider: Web3Provider | undefined): RouterAndProvider {
const providerChainId = web3Provider?.network.chainId
if (
cachedProviderRouter !== undefined &&
chainId === providerChainId &&
web3Provider === cachedProviderRouter.routerProvider.provider
) {
return cachedProviderRouter.routerProvider
} else {
cachedProviderRouter = undefined
}
if (providerChainId !== undefined && chainId === providerChainId && web3Provider !== undefined) {

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Last check is redundant. If providerChainId is defined then web3Provider will never be undefined. I'm a bit sad that TypeScript doesn't notice this.

Suggested change
if (providerChainId !== undefined && chainId === providerChainId && web3Provider !== undefined) {
if (providerChainId !== undefined && chainId === providerChainId) {

But maybe you need the check in order for TS to properly narrow?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

its needed for typescript

cachedProviderRouter = {
chainId,
routerProvider: { router: new AlphaRouter({ chainId, provider: web3Provider }), provider: web3Provider },
}
return cachedProviderRouter?.routerProvider
}
const router = routers.get(chainId)
if (router) return router

const supportedChainId = asSupportedChain(chainId)
if (supportedChainId) {
const provider = DEPRECATED_RPC_PROVIDERS[supportedChainId]
const router = new AlphaRouter({ chainId, provider })
routers.set(chainId, router)
return router
const provider = RPC_PROVIDERS[supportedChainId]
const routerProvider = { router: new AlphaRouter({ chainId, provider }), provider }
routers.set(chainId, routerProvider)
return routerProvider
}

throw new Error(`Router does not support this chain (chainId: ${chainId}).`)
Expand Down
10 changes: 4 additions & 6 deletions src/lib/hooks/useBlockNumber.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { ChainId } from '@uniswap/sdk-core'
import { useWeb3React } from '@web3-react/core'
import { DEPRECATED_RPC_PROVIDERS } from 'constants/providers'
import { RPC_PROVIDERS } from 'constants/providers'
import useIsWindowVisible from 'hooks/useIsWindowVisible'
import { createContext, ReactNode, useCallback, useContext, useEffect, useMemo, useState } from 'react'

Expand Down Expand Up @@ -92,19 +92,17 @@ export function BlockNumberProvider({ children }: { children: ReactNode }) {
return void 0
}, [activeChainId, provider, windowVisible, onChainBlock])

const networkProviders = DEPRECATED_RPC_PROVIDERS

useEffect(() => {
if (mainnetBlock === undefined) {
networkProviders[ChainId.MAINNET]
if (mainnetBlock === undefined && provider === undefined) {
RPC_PROVIDERS[ChainId.MAINNET]
.getBlockNumber()
.then((block) => {
onChainBlock(ChainId.MAINNET, block)
})
// swallow errors - it's ok if this fails, as we'll try again if we activate mainnet
.catch(() => undefined)
}
}, [mainnetBlock, networkProviders, onChainBlock])
}, [mainnetBlock, onChainBlock, provider])

const value = useMemo(
() => ({
Expand Down
Loading