diff --git a/src/analytics/index.tsx b/src/analytics/index.tsx deleted file mode 100644 index 35bcfaa7286..00000000000 --- a/src/analytics/index.tsx +++ /dev/null @@ -1,59 +0,0 @@ -import { - sendAnalyticsEvent as sendAnalyticsTraceEvent, - Trace as AnalyticsTrace, - TraceEvent as AnalyticsEvent, -} from '@uniswap/analytics' -import { atomWithStorage, useAtomValue } from 'jotai/utils' -import { memo } from 'react' - -export { - type ITraceContext, - getDeviceId, - initializeAnalytics, - OriginApplication, - user, - useTrace, -} from '@uniswap/analytics' - -const allowAnalyticsAtomKey = 'allow_analytics' -export const allowAnalyticsAtom = atomWithStorage(allowAnalyticsAtomKey, true) - -export const Trace = memo((props: React.ComponentProps) => { - const allowAnalytics = useAtomValue(allowAnalyticsAtom) - const shouldLogImpression = allowAnalytics ? props.shouldLogImpression : false - - return -}) - -Trace.displayName = 'Trace' - -export const TraceEvent = memo((props: React.ComponentProps) => { - const allowAnalytics = useAtomValue(allowAnalyticsAtom) - const shouldLogImpression = allowAnalytics ? props.shouldLogImpression : false - - return -}) - -TraceEvent.displayName = 'TraceEvent' - -export const sendAnalyticsEvent: typeof sendAnalyticsTraceEvent = (event, properties) => { - let allowAnalytics = true - - try { - const value = localStorage.getItem(allowAnalyticsAtomKey) - - if (typeof value === 'string') { - allowAnalytics = JSON.parse(value) - } - // eslint-disable-next-line no-empty - } catch {} - - if (allowAnalytics) { - sendAnalyticsTraceEvent(event, properties) - } -} - -// This is only used for initial page load so we can get the user's country -export const sendInitializationEvent: typeof sendAnalyticsTraceEvent = (event, properties) => { - sendAnalyticsTraceEvent(event, properties) -} diff --git a/src/components/About/AboutFooter.tsx b/src/components/About/AboutFooter.tsx index 3d1cdae2a92..d7277600637 100644 --- a/src/components/About/AboutFooter.tsx +++ b/src/components/About/AboutFooter.tsx @@ -1,5 +1,3 @@ -import { BrowserEvent, InterfaceElementName, SharedEventName } from '@uniswap/analytics-events' -import { TraceEvent } from 'analytics' import { useDisableNFTRoutes } from 'hooks/useDisableNFTRoutes' import styled from 'styled-components' import { BREAKPOINTS } from 'theme' @@ -120,15 +118,9 @@ const LogoSectionContent = () => { - - - - - + + + @@ -162,43 +154,19 @@ export const AboutFooter = () => { Company - - Careers - - - Blog - + Careers + Blog Get Help - - - Contact Us - - - - Help Center - + Contact Us + + Help Center diff --git a/src/components/About/Card.tsx b/src/components/About/Card.tsx index 4cab78f63cb..886751ed244 100644 --- a/src/components/About/Card.tsx +++ b/src/components/About/Card.tsx @@ -1,5 +1,3 @@ -import { BrowserEvent, SharedEventName } from '@uniswap/analytics-events' -import { TraceEvent } from 'analytics' import { Link } from 'react-router-dom' import styled, { DefaultTheme } from 'styled-components' import { BREAKPOINTS } from 'theme' @@ -106,7 +104,6 @@ const Card = ({ external, backgroundImgSrc, icon, - elementName, }: { type?: CardType title: string @@ -116,31 +113,28 @@ const Card = ({ external?: boolean backgroundImgSrc?: string icon?: React.ReactNode - elementName?: string }) => { const isDarkMode = useIsDarkMode() return ( - - - - {title} - {icon} - - - {description} - {cta} - - - + + + {title} + {icon} + + + {description} + {cta} + + ) } diff --git a/src/components/About/constants.tsx b/src/components/About/constants.tsx index dd679ee2525..cbe5c95359d 100644 --- a/src/components/About/constants.tsx +++ b/src/components/About/constants.tsx @@ -1,4 +1,3 @@ -import { InterfaceElementName } from '@uniswap/analytics-events' import { DollarSign, Terminal } from 'react-feather' import styled from 'styled-components' import { lightTheme } from 'theme/colors' @@ -18,7 +17,6 @@ export const MAIN_CARDS = [ cta: 'Trade Tokens', darkBackgroundImgSrc: swapCardImgSrc, lightBackgroundImgSrc: swapCardImgSrc, - elementName: InterfaceElementName.ABOUT_PAGE_SWAP_CARD, }, { to: '/nfts', @@ -27,7 +25,6 @@ export const MAIN_CARDS = [ cta: 'Explore NFTs', darkBackgroundImgSrc: nftCardImgSrc, lightBackgroundImgSrc: nftCardImgSrc, - elementName: InterfaceElementName.ABOUT_PAGE_NFTS_CARD, }, ] @@ -47,7 +44,6 @@ export const MORE_CARDS = [ lightIcon: , darkIcon: , cta: 'Buy now', - elementName: InterfaceElementName.ABOUT_PAGE_BUY_CRYPTO_CARD, }, { to: '/pools', @@ -56,7 +52,6 @@ export const MORE_CARDS = [ lightIcon: , darkIcon: , cta: 'Provide liquidity', - elementName: InterfaceElementName.ABOUT_PAGE_EARN_CARD, }, { to: 'https://docs.uniswap.org', @@ -66,6 +61,5 @@ export const MORE_CARDS = [ lightIcon: , darkIcon: , cta: 'Developer docs', - elementName: InterfaceElementName.ABOUT_PAGE_DEV_DOCS_CARD, }, ] diff --git a/src/components/AccountDrawer/AnalyticsToggle.tsx b/src/components/AccountDrawer/AnalyticsToggle.tsx deleted file mode 100644 index de616d8e652..00000000000 --- a/src/components/AccountDrawer/AnalyticsToggle.tsx +++ /dev/null @@ -1,18 +0,0 @@ -import { t } from '@lingui/macro' -import { allowAnalyticsAtom } from 'analytics' -import { useAtom } from 'jotai' - -import { SettingsToggle } from './SettingsToggle' - -export function AnalyticsToggle() { - const [allowAnalytics, updateAllowAnalytics] = useAtom(allowAnalyticsAtom) - - return ( - void updateAllowAnalytics((value) => !value)} - /> - ) -} diff --git a/src/components/AccountDrawer/AuthenticatedHeader.tsx b/src/components/AccountDrawer/AuthenticatedHeader.tsx index db9c25f308b..ae8de05792c 100644 --- a/src/components/AccountDrawer/AuthenticatedHeader.tsx +++ b/src/components/AccountDrawer/AuthenticatedHeader.tsx @@ -1,8 +1,6 @@ import { Trans } from '@lingui/macro' -import { BrowserEvent, InterfaceElementName, InterfaceEventName, SharedEventName } from '@uniswap/analytics-events' import { CurrencyAmount, Token } from '@uniswap/sdk-core' import { useWeb3React } from '@web3-react/core' -import { sendAnalyticsEvent, TraceEvent } from 'analytics' import { ButtonEmphasis, ButtonSize, LoadingButtonSpinner, ThemeButton } from 'components/Button' import Column from 'components/Column' import { Power } from 'components/Icons/Power' @@ -192,7 +190,6 @@ export default function AuthenticatedHeader({ account, openSettings }: { account const openFiatOnrampModal = useOpenModal(ApplicationModal.FIAT_ONRAMP) const openFoRModalWithAnalytics = useCallback(() => { toggleWalletDrawer() - sendAnalyticsEvent(InterfaceEventName.FIAT_ONRAMP_WIDGET_OPENED) openFiatOnrampModal() }, [openFiatOnrampModal, toggleWalletDrawer]) @@ -251,20 +248,14 @@ export default function AuthenticatedHeader({ account, openSettings }: { account onClick={openSettings} Icon={Settings} /> - - - + diff --git a/src/components/AccountDrawer/DownloadButton.tsx b/src/components/AccountDrawer/DownloadButton.tsx index cc7ff243f6e..d833ffff717 100644 --- a/src/components/AccountDrawer/DownloadButton.tsx +++ b/src/components/AccountDrawer/DownloadButton.tsx @@ -1,4 +1,3 @@ -import { InterfaceElementName } from '@uniswap/analytics-events' import { PropsWithChildren, useCallback } from 'react' import styled from 'styled-components' import { ClickableStyle } from 'theme/components' @@ -32,20 +31,12 @@ function BaseButton({ onClick, branded, children }: PropsWithChildren<{ onClick? } // Launches App Store if on an iOS device, else navigates to Uniswap Wallet microsite -export function DownloadButton({ - onClick, - text = 'Download', - element, -}: { - onClick?: () => void - text?: string - element: InterfaceElementName -}) { +export function DownloadButton({ onClick, text = 'Download' }: { onClick?: () => void; text?: string }) { const onButtonClick = useCallback(() => { // handles any actions required by the parent, i.e. cancelling wallet connection attempt or dismissing an ad onClick?.() - openDownloadApp({ element }) - }, [element, onClick]) + openDownloadApp() + }, [onClick]) return ( diff --git a/src/components/AccountDrawer/MiniPortfolio/Activity/ActivityRow.tsx b/src/components/AccountDrawer/MiniPortfolio/Activity/ActivityRow.tsx index ed479980d17..e4842851594 100644 --- a/src/components/AccountDrawer/MiniPortfolio/Activity/ActivityRow.tsx +++ b/src/components/AccountDrawer/MiniPortfolio/Activity/ActivityRow.tsx @@ -1,5 +1,3 @@ -import { BrowserEvent, InterfaceElementName, SharedEventName } from '@uniswap/analytics-events' -import { TraceEvent } from 'analytics' import Column from 'components/Column' import AlertTriangleFilled from 'components/Icons/AlertTriangleFilled' import { LoaderV2 } from 'components/Icons/LoadingSpinner' @@ -48,8 +46,6 @@ export function ActivityRow({ activity }: { activity: Activity }) { const openOffchainActivityModal = useOpenOffchainActivityModal() const { ENSName } = useENSName(otherAccount) - const explorerUrl = getExplorerLink(chainId, hash, ExplorerDataType.TRANSACTION) - const onClick = useCallback(() => { if (offchainOrderStatus) { openOffchainActivityModal({ orderHash: hash, status: offchainOrderStatus }) @@ -60,33 +56,26 @@ export function ActivityRow({ activity }: { activity: Activity }) { }, [offchainOrderStatus, chainId, hash, openOffchainActivityModal]) return ( - - - - - } - title={ - - {prefixIconSrc && } - {title} - - } - descriptor={ - - {descriptor} - {ENSName ?? shortenAddress(otherAccount)} - - } - right={} - onClick={onClick} - /> - + + + + } + title={ + + {prefixIconSrc && } + {title} + + } + descriptor={ + + {descriptor} + {ENSName ?? shortenAddress(otherAccount)} + + } + right={} + onClick={onClick} + /> ) } diff --git a/src/components/AccountDrawer/MiniPortfolio/NFTs/NFTItem.tsx b/src/components/AccountDrawer/MiniPortfolio/NFTs/NFTItem.tsx index c9a5658fe39..daf0598fc36 100644 --- a/src/components/AccountDrawer/MiniPortfolio/NFTs/NFTItem.tsx +++ b/src/components/AccountDrawer/MiniPortfolio/NFTs/NFTItem.tsx @@ -1,5 +1,3 @@ -import { InterfaceElementName, SharedEventName } from '@uniswap/analytics-events' -import { sendAnalyticsEvent, useTrace } from 'analytics' import { useToggleAccountDrawer } from 'components/AccountDrawer' import Column from 'components/Column' import Row from 'components/Row' @@ -48,7 +46,6 @@ export function NFT({ }) { const toggleWalletDrawer = useToggleAccountDrawer() const navigate = useNavigate() - const trace = useTrace() const navigateToNFTDetails = () => { toggleWalletDrawer() @@ -64,15 +61,6 @@ export function NFT({ isSelected={false} isDisabled={false} onCardClick={navigateToNFTDetails} - sendAnalyticsEvent={() => - sendAnalyticsEvent(SharedEventName.ELEMENT_CLICKED, { - element: InterfaceElementName.MINI_PORTFOLIO_NFT_ITEM, - collection_name: asset.collection?.name, - collection_address: asset.collection?.address, - token_id: asset.tokenId, - ...trace, - }) - } mediaShouldBePlaying={mediaShouldBePlaying} setCurrentTokenPlayingMedia={setCurrentTokenPlayingMedia} testId="mini-portfolio-nft" diff --git a/src/components/AccountDrawer/MiniPortfolio/Pools/index.tsx b/src/components/AccountDrawer/MiniPortfolio/Pools/index.tsx index f47a018bc6c..bd4b37efecb 100644 --- a/src/components/AccountDrawer/MiniPortfolio/Pools/index.tsx +++ b/src/components/AccountDrawer/MiniPortfolio/Pools/index.tsx @@ -1,8 +1,6 @@ import { t } from '@lingui/macro' -import { BrowserEvent, InterfaceElementName, SharedEventName } from '@uniswap/analytics-events' import { Position } from '@uniswap/v3-sdk' import { useWeb3React } from '@web3-react/core' -import { TraceEvent } from 'analytics' import { useToggleAccountDrawer } from 'components/AccountDrawer' import Row from 'components/Row' import { MouseoverTooltip } from 'components/Tooltip' @@ -134,68 +132,51 @@ function PositionListItem({ positionInfo }: { positionInfo: PositionInfo }) { toggleWalletDrawer() navigate('/pool/' + details.tokenId) }, [walletChainId, chainId, switchChain, connector, toggleWalletDrawer, navigate, details.tokenId]) - const analyticsEventProperties = useMemo( - () => ({ - chain_id: chainId, - pool_token_0_symbol: pool.token0.symbol, - pool_token_1_symbol: pool.token1.symbol, - pool_token_0_address: pool.token0.address, - pool_token_1_address: pool.token1.address, - }), - [chainId, pool.token0.address, pool.token0.symbol, pool.token1.address, pool.token1.symbol] - ) return ( - - } - title={ - + } + title={ + + + {pool.token0.symbol} / {pool.token1?.symbol} + + + } + descriptor={{`${pool.fee / 10000}%`}} + right={ + <> + + {`${formatNumber({ + input: liquidityValue, + type: NumberType.PortfolioBalance, + })} (liquidity) + ${formatNumber({ + input: feeValue, + type: NumberType.PortfolioBalance, + })} (fees)`} + + } + > - {pool.token0.symbol} / {pool.token1?.symbol} + {formatNumber({ + input: (liquidityValue ?? 0) + (feeValue ?? 0), + type: NumberType.PortfolioBalance, + })} + + + + + {closed ? t`Closed` : inRange ? t`In range` : t`Out of range`} + + - } - descriptor={{`${pool.fee / 10000}%`}} - right={ - <> - - {`${formatNumber({ - input: liquidityValue, - type: NumberType.PortfolioBalance, - })} (liquidity) + ${formatNumber({ - input: feeValue, - type: NumberType.PortfolioBalance, - })} (fees)`} - - } - > - - {formatNumber({ - input: (liquidityValue ?? 0) + (feeValue ?? 0), - type: NumberType.PortfolioBalance, - })} - - - - - - {closed ? t`Closed` : inRange ? t`In range` : t`Out of range`} - - - - - } - /> - + + } + /> ) } diff --git a/src/components/AccountDrawer/MiniPortfolio/Tokens/index.tsx b/src/components/AccountDrawer/MiniPortfolio/Tokens/index.tsx index 3f09e733295..e20296f056c 100644 --- a/src/components/AccountDrawer/MiniPortfolio/Tokens/index.tsx +++ b/src/components/AccountDrawer/MiniPortfolio/Tokens/index.tsx @@ -1,5 +1,3 @@ -import { BrowserEvent, InterfaceElementName, SharedEventName } from '@uniswap/analytics-events' -import { TraceEvent } from 'analytics' import { useCachedPortfolioBalancesQuery } from 'components/PrefetchBalancesWrapper/PrefetchBalancesWrapper' import Row from 'components/Row' import { DeltaArrow } from 'components/Tokens/TokenDetails/Delta' @@ -91,42 +89,35 @@ function TokenRow({ token, quantity, denominatedValue, tokenProjectMarket }: Tok return null } return ( - - } - title={{token?.name}} - descriptor={ - - {formatNumber({ - input: quantity, - type: NumberType.TokenNonTx, - })}{' '} - {token?.symbol} - - } - onClick={navigateToTokenDetails} - right={ - denominatedValue && ( - <> - - {formatNumber({ - input: denominatedValue?.value, - type: NumberType.PortfolioBalance, - })} - - - - {formatPercent(percentChange)} - - - ) - } - /> - + } + title={{token?.name}} + descriptor={ + + {formatNumber({ + input: quantity, + type: NumberType.TokenNonTx, + })}{' '} + {token?.symbol} + + } + onClick={navigateToTokenDetails} + right={ + denominatedValue && ( + <> + + {formatNumber({ + input: denominatedValue?.value, + type: NumberType.PortfolioBalance, + })} + + + + {formatPercent(percentChange)} + + + ) + } + /> ) } diff --git a/src/components/AccountDrawer/MiniPortfolio/index.tsx b/src/components/AccountDrawer/MiniPortfolio/index.tsx index c875a1a4a67..e07d09e3e85 100644 --- a/src/components/AccountDrawer/MiniPortfolio/index.tsx +++ b/src/components/AccountDrawer/MiniPortfolio/index.tsx @@ -1,6 +1,4 @@ import { Trans } from '@lingui/macro' -import { BrowserEvent, InterfaceElementName, InterfaceSectionName, SharedEventName } from '@uniswap/analytics-events' -import { Trace, TraceEvent } from 'analytics' import Column from 'components/Column' import { LoaderV2 } from 'components/Icons/LoadingSpinner' import { AutoRow } from 'components/Row' @@ -65,7 +63,6 @@ interface Page { title: React.ReactNode key: string component: ({ account }: { account: string }) => JSX.Element - loggingElementName: string } const Pages: Array = [ @@ -73,25 +70,21 @@ const Pages: Array = [ title: Tokens, key: 'tokens', component: Tokens, - loggingElementName: InterfaceElementName.MINI_PORTFOLIO_TOKENS_TAB, }, { title: NFTs, key: 'nfts', component: NFTs, - loggingElementName: InterfaceElementName.MINI_PORTFOLIO_NFT_TAB, }, { title: Pools, key: 'pools', component: Pools, - loggingElementName: InterfaceElementName.MINI_PORTFOLIO_POOLS_TAB, }, { title: Activity, key: 'activity', component: ActivityTab, - loggingElementName: InterfaceElementName.MINI_PORTFOLIO_ACTIVITY_TAB, }, ] @@ -111,47 +104,38 @@ export default function MiniPortfolio({ account }: { account: string }) { }, [currentKey, hasPendingActivity]) return ( - - - + + + + ) } diff --git a/src/components/AccountDrawer/SettingsMenu.tsx b/src/components/AccountDrawer/SettingsMenu.tsx index f3acce8c645..f8c305b1c15 100644 --- a/src/components/AccountDrawer/SettingsMenu.tsx +++ b/src/components/AccountDrawer/SettingsMenu.tsx @@ -11,7 +11,6 @@ import styled from 'styled-components' import { ClickableStyle, ThemedText } from 'theme/components' import ThemeToggle from 'theme/components/ThemeToggle' -import { AnalyticsToggle } from './AnalyticsToggle' import { GitVersionRow } from './GitVersionRow' import { LanguageMenuItems } from './LanguageMenu' import { SlideOutMenu } from './SlideOutMenu' @@ -91,7 +90,6 @@ export default function SettingsMenu({ - {!currencyConversionEnabled && ( diff --git a/src/components/AccountDrawer/UniwalletModal.tsx b/src/components/AccountDrawer/UniwalletModal.tsx index c85484c40ff..f7165a7c8b8 100644 --- a/src/components/AccountDrawer/UniwalletModal.tsx +++ b/src/components/AccountDrawer/UniwalletModal.tsx @@ -1,7 +1,5 @@ import { Trans } from '@lingui/macro' -import { InterfaceElementName } from '@uniswap/analytics-events' import { WalletConnect as WalletConnectv2 } from '@web3-react/walletconnect-v2' -import { sendAnalyticsEvent } from 'analytics' import Column, { AutoColumn } from 'components/Column' import Modal from 'components/Modal' import { RowBetween } from 'components/Row' @@ -56,10 +54,6 @@ export default function UniwalletModal() { }) }, []) - useEffect(() => { - if (open) sendAnalyticsEvent('Uniswap wallet modal opened') - }, [open]) - const theme = useTheme() return ( @@ -115,7 +109,7 @@ function InfoSection() { - + ) diff --git a/src/components/AccountDrawer/index.tsx b/src/components/AccountDrawer/index.tsx index e357444d03f..fbcf7d255e9 100644 --- a/src/components/AccountDrawer/index.tsx +++ b/src/components/AccountDrawer/index.tsx @@ -1,5 +1,3 @@ -import { BrowserEvent, InterfaceEventName } from '@uniswap/analytics-events' -import { TraceEvent } from 'analytics' import { ScrollBarStyles } from 'components/Common' import useDisableScrolling from 'hooks/useDisableScrolling' import usePrevious from 'hooks/usePrevious' @@ -243,15 +241,9 @@ function AccountDrawer() { return ( {walletDrawerOpen && ( - - - - - + + + )} openDownloadApp({ - element: InterfaceElementName.UNISWAP_WALLET_BANNER_DOWNLOAD_BUTTON, appStoreParams: 'pt=123625782&ct=base-app-banner&mt=8', }) } diff --git a/src/components/CurrencyInputPanel/SwapCurrencyInputPanel.tsx b/src/components/CurrencyInputPanel/SwapCurrencyInputPanel.tsx index a9de21dc517..a41c6151e81 100644 --- a/src/components/CurrencyInputPanel/SwapCurrencyInputPanel.tsx +++ b/src/components/CurrencyInputPanel/SwapCurrencyInputPanel.tsx @@ -1,9 +1,7 @@ import { Trans } from '@lingui/macro' -import { BrowserEvent, InterfaceElementName, SwapEventName } from '@uniswap/analytics-events' import { Currency, CurrencyAmount, Percent } from '@uniswap/sdk-core' import { Pair } from '@uniswap/v2-sdk' import { useWeb3React } from '@web3-react/core' -import { TraceEvent } from 'analytics' import { AutoColumn } from 'components/Column' import { LoadingOpacityContainer, loadingOpacityMixin } from 'components/Loader/styled' import CurrencyLogo from 'components/Logo/CurrencyLogo' @@ -229,7 +227,6 @@ interface SwapCurrencyInputPanelProps { otherCurrency?: Currency | null fiatValue?: { data?: number; isLoading: boolean } priceImpact?: Percent - id: string showCommonBases?: boolean showCurrencyAmount?: boolean disableNonToken?: boolean @@ -254,7 +251,6 @@ const SwapCurrencyInputPanel = forwardRef setTooltipVisible(false), [currency]) return ( - + {locked && ( @@ -321,7 +317,6 @@ const SwapCurrencyInputPanel = forwardRef @@ -408,15 +403,9 @@ const SwapCurrencyInputPanel = forwardRef {showMaxButton && selectedCurrencyBalance ? ( - - - Max - - + + Max + ) : null} ) : ( diff --git a/src/components/CurrencyInputPanel/index.tsx b/src/components/CurrencyInputPanel/index.tsx index f28bfcdd32e..5f9d0c1f275 100644 --- a/src/components/CurrencyInputPanel/index.tsx +++ b/src/components/CurrencyInputPanel/index.tsx @@ -1,9 +1,7 @@ import { Trans } from '@lingui/macro' -import { BrowserEvent, InterfaceElementName, SwapEventName } from '@uniswap/analytics-events' import { Currency, CurrencyAmount } from '@uniswap/sdk-core' import { Pair } from '@uniswap/v2-sdk' import { useWeb3React } from '@web3-react/core' -import { TraceEvent } from 'analytics' import { LoadingOpacityContainer, loadingOpacityMixin } from 'components/Loader/styled' import PrefetchBalancesWrapper from 'components/PrefetchBalancesWrapper/PrefetchBalancesWrapper' import { isSupportedChain } from 'constants/chains' @@ -301,15 +299,9 @@ export default function CurrencyInputPanel({ ))} {Boolean(showMaxButton && selectedCurrencyBalance) && ( - - - MAX - - + + MAX + )} )} diff --git a/src/components/FeeSelector/index.tsx b/src/components/FeeSelector/index.tsx index 1ef77a041f3..cb36305d6e8 100644 --- a/src/components/FeeSelector/index.tsx +++ b/src/components/FeeSelector/index.tsx @@ -1,9 +1,7 @@ import { Trans } from '@lingui/macro' -import { FeePoolSelectAction, LiquidityEventName } from '@uniswap/analytics-events' import { Currency } from '@uniswap/sdk-core' import { FeeAmount } from '@uniswap/v3-sdk' import { useWeb3React } from '@web3-react/core' -import { sendAnalyticsEvent, useTrace } from 'analytics' import { ButtonGray } from 'components/Button' import Card from 'components/Card' import { AutoColumn } from 'components/Column' @@ -61,7 +59,6 @@ export default function FeeSelector({ currencyB?: Currency }) { const { chainId } = useWeb3React() - const trace = useTrace() const { isLoading, isError, largestUsageFeeTier, distributions } = useFeeTierDistribution(currencyA, currencyB) @@ -103,13 +100,9 @@ export default function FeeSelector({ const handleFeePoolSelectWithEvent = useCallback( (fee: FeeAmount) => { - sendAnalyticsEvent(LiquidityEventName.SELECT_LIQUIDITY_POOL_FEE_TIER, { - action: FeePoolSelectAction.MANUAL, - ...trace, - }) handleFeePoolSelect(fee) }, - [handleFeePoolSelect, trace] + [handleFeePoolSelect] ) useEffect(() => { @@ -124,14 +117,10 @@ export default function FeeSelector({ setShowOptions(false) recommended.current = true - sendAnalyticsEvent(LiquidityEventName.SELECT_LIQUIDITY_POOL_FEE_TIER, { - action: FeePoolSelectAction.RECOMMENDED, - ...trace, - }) handleFeePoolSelect(largestUsageFeeTier) } - }, [feeAmount, isLoading, isError, largestUsageFeeTier, handleFeePoolSelect, trace]) + }, [feeAmount, isLoading, isError, largestUsageFeeTier, handleFeePoolSelect]) useEffect(() => { setShowOptions(isError) diff --git a/src/components/NavBar/ChainSelectorRow.tsx b/src/components/NavBar/ChainSelectorRow.tsx index 2b14f3004a1..0276df7b34e 100644 --- a/src/components/NavBar/ChainSelectorRow.tsx +++ b/src/components/NavBar/ChainSelectorRow.tsx @@ -1,8 +1,6 @@ import { Trans } from '@lingui/macro' -import { BrowserEvent, SharedEventName } from '@uniswap/analytics-events' import { ChainId } from '@uniswap/sdk-core' import { useWeb3React } from '@web3-react/core' -import { TraceEvent } from 'analytics' import Loader from 'components/Icons/LoadingSpinner' import { getChainInfo } from 'constants/chainInfo' import { CheckMarkIcon } from 'nft/components/icons' @@ -80,31 +78,29 @@ export default function ChainSelectorRow({ disabled, targetChain, onSelectChain, const theme = useTheme() return ( - - { - if (!disabled) onSelectChain(targetChain) - }} - > - {logoUrl && } - {label && } - {disabled && ( - - Unsupported by your wallet - - )} - {isPending && ( - - Approve in wallet - - )} - - {active && } - {!active && isPending && } - - - + { + if (!disabled) onSelectChain(targetChain) + }} + > + {logoUrl && } + {label && } + {disabled && ( + + Unsupported by your wallet + + )} + {isPending && ( + + Approve in wallet + + )} + + {active && } + {!active && isPending && } + + ) } diff --git a/src/components/NavBar/MenuDropdown.tsx b/src/components/NavBar/MenuDropdown.tsx index c9e9531161d..1167ca03acd 100644 --- a/src/components/NavBar/MenuDropdown.tsx +++ b/src/components/NavBar/MenuDropdown.tsx @@ -1,5 +1,4 @@ import { t, Trans } from '@lingui/macro' -import { InterfaceElementName } from '@uniswap/analytics-events' import FeatureFlagModal from 'components/FeatureFlagModal/FeatureFlagModal' import { useOnClickOutside } from 'hooks/useOnClickOutside' import { Box } from 'nft/components/Box' @@ -123,7 +122,6 @@ const Icon = ({ href, children }: { href?: string; children: ReactNode }) => { export const MenuDropdown = () => { const theme = useTheme() const [isOpen, toggleOpen] = useReducer((s) => !s, false) - const togglePrivacyPolicy = useToggleModal(ApplicationModal.PRIVACY_POLICY) const openFeatureFlagsModal = useToggleModal(ApplicationModal.FEATURE_FLAGS) const ref = useRef(null) useOnClickOutside(ref, isOpen ? toggleOpen : undefined) @@ -149,13 +147,7 @@ export const MenuDropdown = () => { - - openDownloadApp({ - element: InterfaceElementName.UNISWAP_WALLET_MODAL_DOWNLOAD_BUTTON, - }) - } - > + openDownloadApp()}> diff --git a/src/components/NavBar/SearchBar.tsx b/src/components/NavBar/SearchBar.tsx index b3b4fbcf7a2..53334690ffd 100644 --- a/src/components/NavBar/SearchBar.tsx +++ b/src/components/NavBar/SearchBar.tsx @@ -1,9 +1,7 @@ // eslint-disable-next-line no-restricted-imports import { t } from '@lingui/macro' import { useLingui } from '@lingui/react' -import { BrowserEvent, InterfaceElementName, InterfaceEventName, InterfaceSectionName } from '@uniswap/analytics-events' import { useWeb3React } from '@web3-react/core' -import { sendAnalyticsEvent, Trace, TraceEvent, useTrace } from 'analytics' import clsx from 'clsx' import { Search } from 'components/Icons/Search' import { useCollectionSearch } from 'graphql/data/nft/CollectionSearch' @@ -98,14 +96,6 @@ export const SearchBar = () => { const isMobileOrTablet = isMobile || isTablet || !isNavSearchInputVisible - const trace = useTrace({ section: InterfaceSectionName.NAVBAR_SEARCH }) - - const navbarSearchEventProperties = { - navbar_search_input_text: debouncedSearchValue, - hasInput: debouncedSearchValue && debouncedSearchValue.length > 0, - ...trace, - } - const { i18n } = useLingui() // subscribe to locale changes const placeholderText = isMobileOrTablet ? t(i18n)`Search` @@ -139,7 +129,7 @@ export const SearchBar = () => { }, [handleKeyPress, inputRef]) return ( - + <> { - - ) => { - !isOpen && toggleOpen() - setSearchValue(event.target.value) - }} - onBlur={() => sendAnalyticsEvent(InterfaceEventName.NAVBAR_SEARCH_EXITED, navbarSearchEventProperties)} - className={`${styles.searchBarInput} ${styles.searchContentLeftAlign}`} - value={searchValue} - ref={inputRef} - width="full" - /> - + ) => { + !isOpen && toggleOpen() + setSearchValue(event.target.value) + }} + className={`${styles.searchBarInput} ${styles.searchContentLeftAlign}`} + value={searchValue} + ref={inputRef} + width="full" + /> {!isOpen && /} @@ -208,7 +190,6 @@ export const SearchBar = () => { toggleOpen={toggleOpen} tokens={reducedTokens} collections={reducedCollections} - queryText={debouncedSearchValue} hasInput={debouncedSearchValue.length > 0} isLoading={tokensAreLoading || collectionsAreLoading} /> @@ -220,6 +201,6 @@ export const SearchBar = () => { )} - + ) } diff --git a/src/components/NavBar/SearchBarDropdown.tsx b/src/components/NavBar/SearchBarDropdown.tsx index 4ff6f9e52a3..c1e1b0a7ee9 100644 --- a/src/components/NavBar/SearchBarDropdown.tsx +++ b/src/components/NavBar/SearchBarDropdown.tsx @@ -1,8 +1,6 @@ import { Trans } from '@lingui/macro' -import { InterfaceSectionName, NavBarSearchTypes } from '@uniswap/analytics-events' import { ChainId } from '@uniswap/sdk-core' import { useWeb3React } from '@web3-react/core' -import { useTrace } from 'analytics' import clsx from 'clsx' import Badge from 'components/Badge' import { getChainInfo } from 'constants/chainInfo' @@ -42,7 +40,6 @@ interface SearchBarDropdownSectionProps { startingIndex: number setHoveredIndex: (index: number | undefined) => void isLoading?: boolean - eventProperties: Record } const SearchBarDropdownSection = ({ @@ -54,7 +51,6 @@ const SearchBarDropdownSection = ({ startingIndex, setHoveredIndex, isLoading, - eventProperties, }: SearchBarDropdownSectionProps) => { return ( @@ -74,12 +70,6 @@ const SearchBarDropdownSection = ({ setHoveredIndex={setHoveredIndex} toggleOpen={toggleOpen} index={index + startingIndex} - eventProperties={{ - position: index + startingIndex, - selected_search_result_name: suggestion.name, - selected_search_result_address: suggestion.address, - ...eventProperties, - }} /> ) : ( ) )} @@ -129,7 +113,6 @@ interface SearchBarDropdownProps { toggleOpen: () => void tokens: SearchToken[] collections: GenieCollection[] - queryText: string hasInput: boolean isLoading: boolean } @@ -161,13 +144,7 @@ export const SearchBarDropdown = (props: SearchBarDropdownProps) => { ) } -function SearchBarDropdownContents({ - toggleOpen, - tokens, - collections, - queryText, - hasInput, -}: SearchBarDropdownProps): JSX.Element { +function SearchBarDropdownContents({ toggleOpen, tokens, collections, hasInput }: SearchBarDropdownProps): JSX.Element { const [hoveredIndex, setHoveredIndex] = useState(0) const { data: searchHistory } = useRecentlySearchedAssets() const shortenedHistory = useMemo(() => searchHistory?.slice(0, 2) ?? [...Array(2)], [searchHistory]) @@ -244,14 +221,6 @@ function SearchBarDropdownContents({ const showCollectionsFirst = (isNFTPage && (hasVerifiedCollection || !hasKnownToken)) || (!isNFTPage && !hasKnownToken && hasVerifiedCollection) - const trace = JSON.stringify(useTrace({ section: InterfaceSectionName.NAVBAR_SEARCH })) - - const eventProperties = { - total_suggestions: totalSuggestions, - query_text: queryText, - ...JSON.parse(trace), - } - const tokenSearchResults = tokens.length > 0 ? ( Tokens} /> ) : ( @@ -280,10 +245,6 @@ function SearchBarDropdownContents({ setHoveredIndex={setHoveredIndex} toggleOpen={toggleOpen} suggestions={collections} - eventProperties={{ - suggestion_type: NavBarSearchTypes.COLLECTION_SUGGESTION, - ...eventProperties, - }} header={NFT collections} /> ) : ( @@ -315,10 +276,6 @@ function SearchBarDropdownContents({ setHoveredIndex={setHoveredIndex} toggleOpen={toggleOpen} suggestions={shortenedHistory} - eventProperties={{ - suggestion_type: NavBarSearchTypes.RECENT_SEARCH, - ...eventProperties, - }} header={Recent searches} headerIcon={} isLoading={!searchHistory} @@ -331,10 +288,6 @@ function SearchBarDropdownContents({ setHoveredIndex={setHoveredIndex} toggleOpen={toggleOpen} suggestions={trendingTokens} - eventProperties={{ - suggestion_type: NavBarSearchTypes.TOKEN_TRENDING, - ...eventProperties, - }} header={Popular tokens} headerIcon={} isLoading={!trendingTokenData} @@ -347,10 +300,6 @@ function SearchBarDropdownContents({ setHoveredIndex={setHoveredIndex} toggleOpen={toggleOpen} suggestions={formattedTrendingCollections as unknown as GenieCollection[]} - eventProperties={{ - suggestion_type: NavBarSearchTypes.COLLECTION_TRENDING, - ...eventProperties, - }} header={Popular NFT collections} headerIcon={} isLoading={trendingCollectionsAreLoading} diff --git a/src/components/NavBar/SuggestionRow.tsx b/src/components/NavBar/SuggestionRow.tsx index c8fdc95aa1f..b948bebe092 100644 --- a/src/components/NavBar/SuggestionRow.tsx +++ b/src/components/NavBar/SuggestionRow.tsx @@ -1,5 +1,3 @@ -import { InterfaceEventName } from '@uniswap/analytics-events' -import { sendAnalyticsEvent } from 'analytics' import clsx from 'clsx' import QueryTokenLogo from 'components/Logo/QueryTokenLogo' import TokenSafetyIcon from 'components/TokenSafety/TokenSafetyIcon' @@ -37,17 +35,9 @@ interface CollectionRowProps { setHoveredIndex: (index: number | undefined) => void toggleOpen: () => void index: number - eventProperties: Record } -export const CollectionRow = ({ - collection, - isHovered, - setHoveredIndex, - toggleOpen, - index, - eventProperties, -}: CollectionRowProps) => { +export const CollectionRow = ({ collection, isHovered, setHoveredIndex, toggleOpen, index }: CollectionRowProps) => { const [brokenImage, setBrokenImage] = useState(false) const [loaded, setLoaded] = useState(false) @@ -57,8 +47,7 @@ export const CollectionRow = ({ const handleClick = useCallback(() => { addRecentlySearchedAsset({ ...collection, isNft: true, chain: Chain.Ethereum }) toggleOpen() - sendAnalyticsEvent(InterfaceEventName.NAVBAR_RESULT_SELECTED, { ...eventProperties }) - }, [addRecentlySearchedAsset, collection, toggleOpen, eventProperties]) + }, [addRecentlySearchedAsset, collection, toggleOpen]) useEffect(() => { const keyDownHandler = (event: KeyboardEvent) => { @@ -122,10 +111,9 @@ interface TokenRowProps { setHoveredIndex: (index: number | undefined) => void toggleOpen: () => void index: number - eventProperties: Record } -export const TokenRow = ({ token, isHovered, setHoveredIndex, toggleOpen, index, eventProperties }: TokenRowProps) => { +export const TokenRow = ({ token, isHovered, setHoveredIndex, toggleOpen, index }: TokenRowProps) => { const addRecentlySearchedAsset = useAddRecentlySearchedAsset() const navigate = useNavigate() const { formatFiatPrice, formatPercent } = useFormatter() @@ -135,8 +123,7 @@ export const TokenRow = ({ token, isHovered, setHoveredIndex, toggleOpen, index, address && addRecentlySearchedAsset({ address, chain: token.chain }) toggleOpen() - sendAnalyticsEvent(InterfaceEventName.NAVBAR_RESULT_SELECTED, { ...eventProperties }) - }, [addRecentlySearchedAsset, token, toggleOpen, eventProperties]) + }, [addRecentlySearchedAsset, token, toggleOpen]) const tokenDetailsPath = getTokenDetailsURL(token) // Close the modal on escape diff --git a/src/components/SearchModal/CommonBases.test.tsx b/src/components/SearchModal/CommonBases.test.tsx index 76af44c5349..086d1542cff 100644 --- a/src/components/SearchModal/CommonBases.test.tsx +++ b/src/components/SearchModal/CommonBases.test.tsx @@ -7,16 +7,12 @@ const mockOnSelect = jest.fn() describe('CommonBases', () => { it('renders without crashing', () => { - const { container } = render( - - ) + const { container } = render() expect(container).toMatchSnapshot() }) it('renders correct number of common bases', () => { - const { getAllByTestId } = render( - - ) + const { getAllByTestId } = render() const items = getAllByTestId(/common-base-/) expect(items.length).toBe(6) }) @@ -24,9 +20,7 @@ describe('CommonBases', () => { it('renders common bases on mobile', () => { window.innerWidth = 400 window.dispatchEvent(new Event('resize')) - const { getAllByTestId } = render( - - ) + const { getAllByTestId } = render() const items = getAllByTestId(/common-base-/) expect(items.length).toBe(6) }) diff --git a/src/components/SearchModal/CommonBases.tsx b/src/components/SearchModal/CommonBases.tsx index 715323ee378..cb0473b2149 100644 --- a/src/components/SearchModal/CommonBases.tsx +++ b/src/components/SearchModal/CommonBases.tsx @@ -1,11 +1,8 @@ -import { BrowserEvent, InterfaceElementName, InterfaceEventName } from '@uniswap/analytics-events' import { Currency } from '@uniswap/sdk-core' -import { TraceEvent } from 'analytics' import CurrencyLogo from 'components/Logo/CurrencyLogo' import { AutoRow } from 'components/Row' import { COMMON_BASES } from 'constants/routing' import { useTokenInfoFromActiveList } from 'hooks/useTokenInfoFromActiveList' -import { getTokenAddress } from 'lib/utils/analytics' import { Text } from 'rebass' import styled from 'styled-components' import { currencyId } from 'utils/currencyId' @@ -30,30 +27,14 @@ const BaseWrapper = styled.div<{ disable?: boolean }>` background-color: ${({ theme, disable }) => disable && theme.surface3}; ` -const formatAnalyticsEventProperties = (currency: Currency, searchQuery: string, isAddressSearch: string | false) => ({ - token_symbol: currency?.symbol, - token_chain_id: currency?.chainId, - token_address: getTokenAddress(currency), - is_suggested_token: true, - is_selected_from_list: false, - is_imported_by_user: false, - ...(isAddressSearch === false - ? { search_token_symbol_input: searchQuery } - : { search_token_address_input: isAddressSearch }), -}) - export default function CommonBases({ chainId, onSelect, selectedCurrency, - searchQuery, - isAddressSearch, }: { chainId?: number selectedCurrency?: Currency | null onSelect: (currency: Currency) => void - searchQuery: string - isAddressSearch: string | false }) { const bases = chainId !== undefined ? COMMON_BASES[chainId] ?? [] : [] @@ -63,27 +44,19 @@ export default function CommonBases({ const isSelected = selectedCurrency?.equals(currency) return ( - !isSelected && e.key === 'Enter' && onSelect(currency)} + onClick={() => !isSelected && onSelect(currency)} + disable={isSelected} key={currencyId(currency)} + data-testid={`common-base-${currency.symbol}`} > - !isSelected && e.key === 'Enter' && onSelect(currency)} - onClick={() => !isSelected && onSelect(currency)} - disable={isSelected} - key={currencyId(currency)} - data-testid={`common-base-${currency.symbol}`} - > - - - {currency.symbol} - - - + + + {currency.symbol} + + ) })} diff --git a/src/components/SearchModal/CurrencyList/index.test.tsx b/src/components/SearchModal/CurrencyList/index.test.tsx index 06caf8b4026..abc798693f3 100644 --- a/src/components/SearchModal/CurrencyList/index.test.tsx +++ b/src/components/SearchModal/CurrencyList/index.test.tsx @@ -42,8 +42,6 @@ it('renders loading rows when isLoading is true', () => { selectedCurrency={null} onCurrencySelect={noOp} isLoading={true} - searchQuery="" - isAddressSearch="" balances={{}} /> ) @@ -62,8 +60,6 @@ it('renders currency rows correctly when currencies list is non-empty', () => { selectedCurrency={null} onCurrencySelect={noOp} isLoading={false} - searchQuery="" - isAddressSearch="" balances={{}} /> ) @@ -85,8 +81,6 @@ it('renders currency rows correctly with balances', () => { selectedCurrency={null} onCurrencySelect={noOp} isLoading={false} - searchQuery="" - isAddressSearch="" showCurrencyAmount balances={{ [DAI.address.toLowerCase()]: { usdValue: 2, balance: 2 }, diff --git a/src/components/SearchModal/CurrencyList/index.tsx b/src/components/SearchModal/CurrencyList/index.tsx index 6f5fa078882..5ed30b60eb7 100644 --- a/src/components/SearchModal/CurrencyList/index.tsx +++ b/src/components/SearchModal/CurrencyList/index.tsx @@ -1,7 +1,5 @@ -import { BrowserEvent, InterfaceElementName, InterfaceEventName } from '@uniswap/analytics-events' -import { Currency, CurrencyAmount, Token } from '@uniswap/sdk-core' +import { Currency, CurrencyAmount } from '@uniswap/sdk-core' import { useWeb3React } from '@web3-react/core' -import { TraceEvent } from 'analytics' import Loader from 'components/Icons/LoadingSpinner' import TokenSafetyIcon from 'components/TokenSafety/TokenSafetyIcon' import { checkWarning } from 'constants/tokenSafety' @@ -14,7 +12,6 @@ import { Text } from 'rebass' import styled from 'styled-components' import { ThemedText } from 'theme/components' -import { useIsUserAddedToken } from '../../../hooks/Tokens' import { WrappedTokenInfo } from '../../../state/lists/wrappedTokenInfo' import Column, { AutoColumn } from '../../Column' import CurrencyLogo from '../../Logo/CurrencyLogo' @@ -110,7 +107,6 @@ export function CurrencyRow({ otherSelected, style, showCurrencyAmount, - eventProperties, balance, }: { currency: Currency @@ -119,69 +115,56 @@ export function CurrencyRow({ otherSelected: boolean style?: CSSProperties showCurrencyAmount?: boolean - eventProperties: Record balance?: CurrencyAmount }) { const { account } = useWeb3React() const key = currencyKey(currency) - const customAdded = useIsUserAddedToken(currency) const warning = currency.isNative ? null : checkWarning(currency.address) const isBlockedToken = !!warning && !warning.canProceed const blockedTokenOpacity = '0.6' // only show add or remove buttons if not on selected list return ( - (!isSelected && e.key === 'Enter' ? onSelect(!!warning) : null)} + onClick={() => (isSelected ? null : onSelect(!!warning))} + disabled={isSelected} + selected={otherSelected} + dim={isBlockedToken} > - (!isSelected && e.key === 'Enter' ? onSelect(!!warning) : null)} - onClick={() => (isSelected ? null : onSelect(!!warning))} - disabled={isSelected} - selected={otherSelected} - dim={isBlockedToken} - > - - - - - - {currency.name} - - - - - {currency.symbol} - - - - - - - {showCurrencyAmount ? ( + + + + + + {currency.name} + + + + + {currency.symbol} + + + + + + + {showCurrencyAmount ? ( + + {account ? balance ? : : null} + {isSelected && } + + ) : ( + isSelected && ( - {account ? balance ? : : null} - {isSelected && } + - ) : ( - isSelected && ( - - - - ) - )} - - + ) + )} + ) } @@ -191,25 +174,6 @@ interface TokenRowProps { style: CSSProperties } -export const formatAnalyticsEventProperties = ( - token: Token, - index: number, - data: any[], - searchQuery: string, - isAddressSearch: string | false -) => ({ - token_symbol: token?.symbol, - token_address: token?.address, - is_suggested_token: false, - is_selected_from_list: true, - scroll_position: '', - token_list_index: index, - token_list_length: data.length, - ...(isAddressSearch === false - ? { search_token_symbol_input: searchQuery } - : { search_token_address_input: isAddressSearch }), -}) - const LoadingRow = () => (
@@ -228,8 +192,6 @@ export default function CurrencyList({ fixedListRef, showCurrencyAmount, isLoading, - searchQuery, - isAddressSearch, balances, }: { height: number @@ -241,8 +203,6 @@ export default function CurrencyList({ fixedListRef?: MutableRefObject showCurrencyAmount?: boolean isLoading: boolean - searchQuery: string - isAddressSearch: string | false balances: TokenBalances }) { const itemData: Currency[] = useMemo(() => { @@ -268,8 +228,6 @@ export default function CurrencyList({ const otherSelected = Boolean(currency && otherCurrency && otherCurrency.equals(currency)) const handleSelect = (hasWarning: boolean) => currency && onCurrencySelect(currency, hasWarning) - const token = currency?.wrapped - if (isLoading) { return LoadingRow() } else if (currency) { @@ -281,7 +239,6 @@ export default function CurrencyList({ onSelect={handleSelect} otherSelected={otherSelected} showCurrencyAmount={showCurrencyAmount} - eventProperties={formatAnalyticsEventProperties(token, index, data, searchQuery, isAddressSearch)} balance={balance} /> ) @@ -289,16 +246,7 @@ export default function CurrencyList({ return null } }, - [ - selectedCurrency, - otherCurrency, - isLoading, - onCurrencySelect, - showCurrencyAmount, - searchQuery, - isAddressSearch, - balances, - ] + [selectedCurrency, otherCurrency, isLoading, onCurrencySelect, showCurrencyAmount, balances] ) const itemKey = useCallback((index: number, data: typeof itemData) => { diff --git a/src/components/SearchModal/CurrencySearch.tsx b/src/components/SearchModal/CurrencySearch.tsx index 2df87730817..dc97637def0 100644 --- a/src/components/SearchModal/CurrencySearch.tsx +++ b/src/components/SearchModal/CurrencySearch.tsx @@ -1,9 +1,7 @@ // eslint-disable-next-line no-restricted-imports import { t, Trans } from '@lingui/macro' -import { InterfaceEventName, InterfaceModalName } from '@uniswap/analytics-events' import { Currency, Token } from '@uniswap/sdk-core' import { useWeb3React } from '@web3-react/core' -import { Trace } from 'analytics' import { useCachedPortfolioBalancesQuery } from 'components/PrefetchBalancesWrapper/PrefetchBalancesWrapper' import { supportedChainIdFromGQLChain } from 'graphql/data/util' import useDebounce from 'hooks/useDebounce' @@ -25,7 +23,7 @@ import { isAddress } from '../../utils' import Column from '../Column' import Row, { RowBetween } from '../Row' import CommonBases from './CommonBases' -import { CurrencyRow, formatAnalyticsEventProperties } from './CurrencyList' +import { CurrencyRow } from './CurrencyList' import CurrencyList from './CurrencyList' import { PaddedColumn, SearchInput, Separator } from './styled' @@ -220,88 +218,67 @@ export function CurrencySearch({ return ( - - - - - Select a token - - - - - } - onChange={handleInput} - onKeyDown={handleEnter} - /> - - {showCommonBases && ( - - )} - - - {searchToken && !searchTokenIsAdded ? ( - - searchToken && handleCurrencySelect(searchToken, hasWarning)} - otherSelected={Boolean(searchToken && otherSelectedCurrency && otherSelectedCurrency.equals(searchToken))} - showCurrencyAmount={showCurrencyAmount} - eventProperties={formatAnalyticsEventProperties( - searchToken, - 0, - [searchToken], - searchQuery, - isAddressSearch - )} - /> - - ) : searchCurrencies?.length > 0 || filteredInactiveTokens?.length > 0 || isLoading ? ( -
- - {({ height }) => ( - - )} - -
- ) : ( - - - No results found. - - + + + + Select a token + + + + + } + onChange={handleInput} + onKeyDown={handleEnter} + /> + + {showCommonBases && ( + )} -
+ + + {searchToken && !searchTokenIsAdded ? ( + + searchToken && handleCurrencySelect(searchToken, hasWarning)} + otherSelected={Boolean(searchToken && otherSelectedCurrency && otherSelectedCurrency.equals(searchToken))} + showCurrencyAmount={showCurrencyAmount} + /> + + ) : searchCurrencies?.length > 0 || filteredInactiveTokens?.length > 0 || isLoading ? ( +
+ + {({ height }) => ( + + )} + +
+ ) : ( + + + No results found. + + + )}
) } diff --git a/src/components/Tokens/TokenDetails/index.tsx b/src/components/Tokens/TokenDetails/index.tsx index c5b73daf7d0..9287545af88 100644 --- a/src/components/Tokens/TokenDetails/index.tsx +++ b/src/components/Tokens/TokenDetails/index.tsx @@ -1,7 +1,5 @@ import { Trans } from '@lingui/macro' -import { InterfacePageName } from '@uniswap/analytics-events' import { useWeb3React } from '@web3-react/core' -import { Trace } from 'analytics' import CurrencyLogo from 'components/Logo/CurrencyLogo' import { AboutSection } from 'components/Tokens/TokenDetails/About' import AddressSection from 'components/Tokens/TokenDetails/AddressSection' @@ -199,79 +197,73 @@ export default function TokenDetails({ return } return ( - - - {detailedToken && !isPending ? ( - - - Tokens - - - - - - {detailedToken.name ?? Name not found} - {detailedToken.symbol ?? Symbol not found} - - - - - - - + + {detailedToken && !isPending ? ( + + + Tokens + + + + + + {detailedToken.name ?? Name not found} + {detailedToken.symbol ?? Symbol not found} + + + + + + + - -
- - {!detailedToken.isNative && } -
- ) : ( - - )} + +
+ + {!detailedToken.isNative && } +
+ ) : ( + + )} - isBlockedToken && setOpenTokenSafetyModal(true)}> -
- -
- {tokenWarning && } - {!isInfoTDPEnabled && detailedToken && } -
- {!isInfoTDPEnabled && detailedToken && } + isBlockedToken && setOpenTokenSafetyModal(true)}> +
+ +
+ {tokenWarning && } + {!isInfoTDPEnabled && detailedToken && } +
+ {!isInfoTDPEnabled && detailedToken && } - onResolveSwap(true)} - onBlocked={() => { - setOpenTokenSafetyModal(false) - }} - onCancel={() => onResolveSwap(false)} - showCancel={true} - /> -
-
+ onResolveSwap(true)} + onBlocked={() => { + setOpenTokenSafetyModal(false) + }} + onCancel={() => onResolveSwap(false)} + showCancel={true} + /> + ) } diff --git a/src/components/Tokens/TokenTable/SearchBar.tsx b/src/components/Tokens/TokenTable/SearchBar.tsx index 62087ec9919..6c404a0ff1c 100644 --- a/src/components/Tokens/TokenTable/SearchBar.tsx +++ b/src/components/Tokens/TokenTable/SearchBar.tsx @@ -1,6 +1,4 @@ import { Trans } from '@lingui/macro' -import { BrowserEvent, InterfaceElementName, InterfaceEventName } from '@uniswap/analytics-events' -import { TraceEvent } from 'analytics' import searchIcon from 'assets/svg/search.svg' import xIcon from 'assets/svg/x.svg' import useDebounce from 'hooks/useDebounce' @@ -80,21 +78,15 @@ export default function SearchBar() { ( - - setLocalFilterString(value)} - /> - + setLocalFilterString(value)} + /> )} > Filter tokens diff --git a/src/components/Tokens/TokenTable/TokenRow.tsx b/src/components/Tokens/TokenTable/TokenRow.tsx index 88706f1dece..f8c0d931376 100644 --- a/src/components/Tokens/TokenTable/TokenRow.tsx +++ b/src/components/Tokens/TokenTable/TokenRow.tsx @@ -1,7 +1,5 @@ import { Trans } from '@lingui/macro' -import { InterfaceEventName } from '@uniswap/analytics-events' import { ParentSize } from '@visx/responsive' -import { sendAnalyticsEvent } from 'analytics' import SparklineChart from 'components/Charts/SparklineChart' import { ArrowChangeDown } from 'components/Icons/ArrowChangeDown' import { ArrowChangeUp } from 'components/Icons/ArrowChangeUp' @@ -9,11 +7,11 @@ import { Info } from 'components/Icons/Info' import QueryTokenLogo from 'components/Logo/QueryTokenLogo' import { MouseoverTooltip } from 'components/Tooltip' import { SparklineMap, TopToken } from 'graphql/data/TopTokens' -import { getTokenDetailsURL, supportedChainIdFromGQLChain, validateUrlChainParam } from 'graphql/data/util' +import { getTokenDetailsURL } from 'graphql/data/util' import { useAtomValue } from 'jotai/utils' import { ForwardedRef, forwardRef } from 'react' import { CSSProperties, ReactNode } from 'react' -import { Link, useParams } from 'react-router-dom' +import { Link } from 'react-router-dom' import styled, { css, useTheme } from 'styled-components' import { BREAKPOINTS } from 'theme' import { ClickableStyle } from 'theme/components' @@ -26,14 +24,7 @@ import { SMALL_MEDIA_BREAKPOINT, } from '../constants' import { LoadingBubble } from '../loading' -import { - filterStringAtom, - filterTimeAtom, - sortAscendingAtom, - sortMethodAtom, - TokenSortMethod, - useSetSortMethod, -} from '../state' +import { sortAscendingAtom, sortMethodAtom, TokenSortMethod, useSetSortMethod } from '../state' import { DeltaArrow, DeltaText } from '../TokenDetails/Delta' const Cell = styled.div` @@ -444,37 +435,16 @@ export const LoadedRow = forwardRef((props: LoadedRowProps, ref: ForwardedRef().chainName?.toUpperCase()) - const chainId = supportedChainIdFromGQLChain(filterNetwork) - const timePeriod = useAtomValue(filterTimeAtom) const delta = token.market?.pricePercentChange?.value const formattedDelta = formatPercent(delta) - const exploreTokenSelectedEventProperties = { - chain_id: chainId, - token_address: token.address, - token_symbol: token.symbol, - token_list_index: tokenListIndex, - token_list_rank: sortRank, - token_list_length: tokenListLength, - time_frame: timePeriod, - search_token_address_input: filterString, - } - // A simple 0 price indicates the price is not currently available from the api const price = token.market?.price?.value === 0 ? '-' : formatFiatPrice({ price: token.market?.price?.value }) // TODO: currency logo sizing mobile (32px) vs. desktop (24px) return (
- - sendAnalyticsEvent(InterfaceEventName.EXPLORE_TOKEN_ROW_CLICKED, exploreTokenSelectedEventProperties) - } - > + - - - - - {connection.getName()} - - {connection.getName()} - - {isCurrentOptionPending && } - - + + + {connection.getName()} + + {connection.getName()} + + {isCurrentOptionPending && } + ) } diff --git a/src/components/Web3Provider/index.test.tsx b/src/components/Web3Provider/index.test.tsx index bfa7c400dac..5262bd4afc9 100644 --- a/src/components/Web3Provider/index.test.tsx +++ b/src/components/Web3Provider/index.test.tsx @@ -1,14 +1,9 @@ import { act, render } from '@testing-library/react' -import { InterfaceEventName, WalletConnectionResult } from '@uniswap/analytics-events' -import { MockEIP1193Provider } from '@web3-react/core' import { Provider as EIP1193Provider } from '@web3-react/types' -import { sendAnalyticsEvent, user } from 'analytics' -import { connections, getConnection } from 'connection' import { Connection, ConnectionType } from 'connection/types' import { Provider } from 'react-redux' import { HashRouter } from 'react-router-dom' import store from 'state' -import { mocked } from 'test-utils/mocked' import Web3Provider from '.' @@ -36,14 +31,6 @@ jest.mock('connection', () => { jest.unmock('@web3-react/core') -function first(array: T[]): T { - return array[0] -} - -function last(array: T[]): T { - return array[array.length - 1] -} - const UI = ( @@ -60,75 +47,4 @@ describe('Web3Provider', () => { }) expect(result).toBeTruthy() }) - - describe('analytics', () => { - let mockProvider: MockEIP1193Provider - - beforeEach(() => { - const mockConnection = connections[0] - mockProvider = mockConnection.connector.provider as MockEIP1193Provider - mocked(getConnection).mockReturnValue(mockConnection) - jest.spyOn(console, 'warn').mockImplementation() - }) - - it('sends event when the active account changes', async () => { - // Arrange - const result = render(UI) - await act(async () => { - await result - }) - - // Act - act(() => { - mockProvider.emitConnect('0x1') - mockProvider.emitAccountsChanged(['0x0000000000000000000000000000000000000000']) - }) - - // Assert - expect(sendAnalyticsEvent).toHaveBeenCalledTimes(1) - expect(sendAnalyticsEvent).toHaveBeenCalledWith(InterfaceEventName.WALLET_CONNECTED, { - result: WalletConnectionResult.SUCCEEDED, - wallet_address: '0x0000000000000000000000000000000000000000', - wallet_type: 'test', - is_reconnect: false, - peer_wallet_agent: '(Injected)', - }) - expect(first(mocked(sendAnalyticsEvent).mock.invocationCallOrder)).toBeGreaterThan( - last(mocked(user.set).mock.invocationCallOrder) - ) - expect(first(mocked(sendAnalyticsEvent).mock.invocationCallOrder)).toBeGreaterThan( - last(mocked(user.postInsert).mock.invocationCallOrder) - ) - }) - - it('sends event with is_reconnect when a previous account reconnects', async () => { - // Arrange - const result = render(UI) - await act(async () => { - await result - }) - - // Act - act(() => { - mockProvider.emitConnect('0x1') - mockProvider.emitAccountsChanged(['0x0000000000000000000000000000000000000000']) - }) - act(() => { - mockProvider.emitAccountsChanged(['0x0000000000000000000000000000000000000001']) - }) - act(() => { - mockProvider.emitAccountsChanged(['0x0000000000000000000000000000000000000000']) - }) - - // Assert - expect(sendAnalyticsEvent).toHaveBeenCalledTimes(3) - expect(sendAnalyticsEvent).toHaveBeenCalledWith(InterfaceEventName.WALLET_CONNECTED, { - result: WalletConnectionResult.SUCCEEDED, - wallet_address: '0x0000000000000000000000000000000000000000', - wallet_type: 'test', - is_reconnect: true, - peer_wallet_agent: '(Injected)', - }) - }) - }) }) diff --git a/src/components/Web3Provider/index.tsx b/src/components/Web3Provider/index.tsx index 965c280e240..d3395ea4ee8 100644 --- a/src/components/Web3Provider/index.tsx +++ b/src/components/Web3Provider/index.tsx @@ -1,7 +1,5 @@ -import { CustomUserProperties, InterfaceEventName, WalletConnectionResult } from '@uniswap/analytics-events' import { useWeb3React, Web3ReactHooks, Web3ReactProvider } from '@web3-react/core' import { Connector } from '@web3-react/types' -import { sendAnalyticsEvent, user, useTrace } from 'analytics' import { connections, getConnection } from 'connection' import { isSupportedChain } from 'constants/chains' import { DEPRECATED_RPC_PROVIDERS, RPC_PROVIDERS } from 'constants/providers' @@ -12,7 +10,6 @@ import { ReactNode, useEffect } from 'react' import { useLocation } from 'react-router-dom' import { useConnectedWallets } from 'state/wallets/hooks' import { getCurrentPageFromLocation } from 'utils/urlRoutes' -import { getWalletMeta } from 'utils/walletMeta' export default function Web3Provider({ children }: { children: ReactNode }) { const connectors = connections.map<[Connector, Web3ReactHooks]>(({ hooks, connector }) => [connector, hooks]) @@ -30,7 +27,6 @@ function Updater() { const { account, chainId, connector, provider } = useWeb3React() const { pathname } = useLocation() const currentPage = getCurrentPageFromLocation(pathname) - const analyticsContext = useTrace() const providers = useFallbackProviderEnabled() ? RPC_PROVIDERS : DEPRECATED_RPC_PROVIDERS @@ -48,22 +44,7 @@ function Updater() { provider?.off('debug', trace) networkProvider?.off('debug', trace) } - }, [analyticsContext, networkProvider, provider, shouldTrace]) - - const previousConnectedChainId = usePrevious(chainId) - useEffect(() => { - const chainChanged = previousConnectedChainId && previousConnectedChainId !== chainId - if (chainChanged) { - sendAnalyticsEvent(InterfaceEventName.CHAIN_CHANGED, { - result: WalletConnectionResult.SUCCEEDED, - wallet_address: account, - wallet_type: getConnection(connector).getName(), - chain_id: chainId, - previousConnectedChainId, - page: currentPage, - }) - } - }, [account, chainId, connector, currentPage, previousConnectedChainId]) + }, [networkProvider, provider, shouldTrace]) // Send analytics events when the active account changes. const previousAccount = usePrevious(account) @@ -71,41 +52,6 @@ function Updater() { useEffect(() => { if (account && account !== previousAccount) { const walletType = getConnection(connector).getName() - const peerWalletAgent = provider ? getWalletMeta(provider)?.agent : undefined - const isReconnect = connectedWallets.some( - (wallet) => wallet.account === account && wallet.walletType === walletType - ) - - provider - ?.send('web3_clientVersion', []) - .then((clientVersion) => { - user.set(CustomUserProperties.WALLET_VERSION, clientVersion) - }) - .catch((error) => { - console.warn('Failed to get client version', error) - }) - - // User properties *must* be set before sending corresponding event properties, - // so that the event contains the correct and up-to-date user properties. - user.set(CustomUserProperties.WALLET_ADDRESS, account) - user.postInsert(CustomUserProperties.ALL_WALLET_ADDRESSES_CONNECTED, account) - - user.set(CustomUserProperties.WALLET_TYPE, walletType) - user.set(CustomUserProperties.PEER_WALLET_AGENT, peerWalletAgent ?? '') - if (chainId) { - user.set(CustomUserProperties.CHAIN_ID, chainId) - user.postInsert(CustomUserProperties.ALL_WALLET_CHAIN_IDS, chainId) - } - - sendAnalyticsEvent(InterfaceEventName.WALLET_CONNECTED, { - result: WalletConnectionResult.SUCCEEDED, - wallet_address: account, - wallet_type: walletType, - is_reconnect: isReconnect, - peer_wallet_agent: peerWalletAgent, - page: currentPage, - }) - addConnectedWallet({ account, walletType }) } }, [account, addConnectedWallet, currentPage, chainId, connectedWallets, connector, previousAccount, provider]) diff --git a/src/components/Web3Status/index.tsx b/src/components/Web3Status/index.tsx index 278429ff6c5..6164edaea94 100644 --- a/src/components/Web3Status/index.tsx +++ b/src/components/Web3Status/index.tsx @@ -1,7 +1,5 @@ import { Trans } from '@lingui/macro' -import { BrowserEvent, InterfaceElementName, InterfaceEventName } from '@uniswap/analytics-events' import { useWeb3React } from '@web3-react/core' -import { sendAnalyticsEvent, TraceEvent } from 'analytics' import PortfolioDrawer, { useAccountDrawer } from 'components/AccountDrawer' import { usePendingActivity } from 'components/AccountDrawer/MiniPortfolio/Activity/hooks' import Loader, { LoaderV3 } from 'components/Icons/LoadingSpinner' @@ -146,7 +144,6 @@ function Web3StatusInner() { const [, toggleAccountDrawer] = useAccountDrawer() const handleWalletDropdownClick = useCallback(() => { - sendAnalyticsEvent(InterfaceEventName.ACCOUNT_DROPDOWN_BUTTON_CLICKED) toggleAccountDrawer() }, [toggleAccountDrawer]) const isClaimAvailable = useIsNftClaimAvailable((state) => state.isClaimAvailable) @@ -197,53 +194,41 @@ function Web3StatusInner() { if (account) { return ( - - - {!hasPendingActivity && ( - - )} - {hasPendingActivity ? ( - - - {pendingActivityCount} Pending - {' '} - - - ) : ( - - {ENSName ?? shortenAddress(account)} - - )} - - + {!hasPendingActivity && ( + + )} + {hasPendingActivity ? ( + + + {pendingActivityCount} Pending + {' '} + + + ) : ( + + {ENSName ?? shortenAddress(account)} + + )} + ) } else { return ( - e.key === 'Enter' && handleWalletDropdownClick()} + onClick={handleWalletDropdownClick} > - e.key === 'Enter' && handleWalletDropdownClick()} - onClick={handleWalletDropdownClick} - > - - Connect - - - + + Connect + + ) } } diff --git a/src/components/analytics/index.ts b/src/components/analytics/index.ts deleted file mode 100644 index 95558297690..00000000000 --- a/src/components/analytics/index.ts +++ /dev/null @@ -1,8 +0,0 @@ -import { InterfaceEventName } from '@uniswap/analytics-events' -import { sendAnalyticsEvent } from 'analytics' - -export function outboundLink({ label }: { label: string }) { - sendAnalyticsEvent(InterfaceEventName.EXTERNAL_LINK_CLICK, { - label, - }) -} diff --git a/src/components/swap/ConfirmSwapModal.tsx b/src/components/swap/ConfirmSwapModal.tsx index d8ab028cbfb..f083707b805 100644 --- a/src/components/swap/ConfirmSwapModal.tsx +++ b/src/components/swap/ConfirmSwapModal.tsx @@ -1,25 +1,16 @@ import { Trans } from '@lingui/macro' -import { - InterfaceEventName, - InterfaceModalName, - SwapEventName, - SwapPriceUpdateUserResponse, -} from '@uniswap/analytics-events' import { Currency, Percent } from '@uniswap/sdk-core' import { useWeb3React } from '@web3-react/core' -import { sendAnalyticsEvent, Trace, useTrace } from 'analytics' import Badge from 'components/Badge' import Modal, { MODAL_TRANSITION_DURATION } from 'components/Modal' import { RowFixed } from 'components/Row' import { getChainInfo } from 'constants/chainInfo' import { TransactionStatus } from 'graphql/data/__generated__/types-and-hooks' -import { useMaxAmountIn } from 'hooks/useMaxAmountIn' import { Allowance, AllowanceState } from 'hooks/usePermit2Allowance' import usePrevious from 'hooks/usePrevious' import { SwapResult } from 'hooks/useSwapCallback' import useWrapCallback from 'hooks/useWrapCallback' import useNativeCurrency from 'lib/hooks/useNativeCurrency' -import { getPriceUpdateBasisPoints } from 'lib/utils/analytics' import { useCallback, useEffect, useState } from 'react' import { InterfaceTrade, TradeFillType } from 'state/routing/types' import { isPreviewTrade } from 'state/routing/utils' @@ -31,7 +22,6 @@ import invariant from 'tiny-invariant' import { isL2ChainId } from 'utils/chains' import { SignatureExpiredError } from 'utils/errors' import { NumberType, useFormatter } from 'utils/formatNumbers' -import { formatSwapPriceUpdatedEventProperties } from 'utils/loggingFormatters' import { didUserReject } from 'utils/swapErrorToUserReadableMessage' import { tradeMeaningfullyDiffers } from 'utils/tradeMeaningFullyDiffer' @@ -70,7 +60,6 @@ function isInApprovalPhase(confirmModalState: ConfirmModalState) { function useConfirmModalState({ trade, - allowedSlippage, onSwap, allowance, doesTradeDiffer, @@ -115,8 +104,6 @@ function useConfirmModalState({ }, [allowance, trade]) const { chainId } = useWeb3React() - const trace = useTrace() - const maximumAmountIn = useMaxAmountIn(trade, allowedSlippage) const nativeCurrency = useNativeCurrency(chainId) @@ -149,13 +136,6 @@ function useConfirmModalState({ // After the wrap has succeeded, reset the input currency to be WETH // because the trade will be on WETH -> token onCurrencySelection(Field.INPUT, trade.inputAmount.currency) - sendAnalyticsEvent(InterfaceEventName.WRAP_TOKEN_TXN_SUBMITTED, { - chain_id: chainId, - token_symbol: maximumAmountIn?.currency.symbol, - token_address: maximumAmountIn?.currency.address, - ...trade, - ...trace, - }) }) .catch((e) => catchUserReject(e, PendingModalError.WRAP_ERROR)) break @@ -187,17 +167,7 @@ function useConfirmModalState({ break } }, - [ - allowance, - chainId, - maximumAmountIn?.currency.address, - maximumAmountIn?.currency.symbol, - onSwap, - onWrap, - trace, - trade, - onCurrencySelection, - ] + [allowance, onSwap, onWrap, trade, onCurrencySelection] ) const startSwapFlow = useCallback(() => { @@ -326,28 +296,19 @@ export default function ConfirmSwapModal({ ) const [lastExecutionPrice, setLastExecutionPrice] = useState(trade?.executionPrice) - const [priceUpdate, setPriceUpdate] = useState() useEffect(() => { if (lastExecutionPrice && !trade.executionPrice.equalTo(lastExecutionPrice)) { - setPriceUpdate(getPriceUpdateBasisPoints(lastExecutionPrice, trade.executionPrice)) setLastExecutionPrice(trade.executionPrice) } }, [lastExecutionPrice, setLastExecutionPrice, trade]) const onModalDismiss = useCallback(() => { - if (showAcceptChanges) { - // If the user dismissed the modal while showing the price update, log the event as rejected. - sendAnalyticsEvent( - SwapEventName.SWAP_PRICE_UPDATE_ACKNOWLEDGED, - formatSwapPriceUpdatedEventProperties(trade, priceUpdate, SwapPriceUpdateUserResponse.REJECTED) - ) - } onDismiss() setTimeout(() => { // Reset local state after the modal dismiss animation finishes, to avoid UI flicker as it dismisses onCancel() }, MODAL_TRANSITION_DURATION) - }, [onCancel, onDismiss, priceUpdate, showAcceptChanges, trade]) + }, [onCancel, onDismiss]) const modalHeader = useCallback(() => { if (confirmModalState !== ConfirmModalState.REVIEWING && !showAcceptChanges) { @@ -431,20 +392,18 @@ export default function ConfirmSwapModal({ const errorType = getErrorType() return ( - - - {errorType ? ( - - ) : ( - Review swap : undefined} - onDismiss={onModalDismiss} - topContent={modalHeader} - bottomContent={modalBottom} - headerContent={l2Badge} - /> - )} - - + + {errorType ? ( + + ) : ( + Review swap : undefined} + onDismiss={onModalDismiss} + topContent={modalHeader} + bottomContent={modalBottom} + headerContent={l2Badge} + /> + )} + ) } diff --git a/src/components/swap/GasEstimateTooltip.tsx b/src/components/swap/GasEstimateTooltip.tsx index f253dd97eb1..c003cae297c 100644 --- a/src/components/swap/GasEstimateTooltip.tsx +++ b/src/components/swap/GasEstimateTooltip.tsx @@ -1,6 +1,4 @@ -import { InterfaceElementName, SwapEventName } from '@uniswap/analytics-events' import { useWeb3React } from '@web3-react/core' -import { sendAnalyticsEvent } from 'analytics' import { Gas } from 'components/Icons/Gas' import { LoadingOpacityContainer } from 'components/Loader/styled' import { UniswapXRouterIcon } from 'components/RouterLabel/UniswapXRouterLabel' @@ -33,16 +31,7 @@ export default function GasEstimateTooltip({ trade, loading }: { trade?: Submitt } return ( - } - onOpen={() => { - sendAnalyticsEvent(SwapEventName.SWAP_AUTOROUTER_VISUALIZATION_EXPANDED, { - element: InterfaceElementName.AUTOROUTER_VISUALIZATION_ROW, - }) - }} - placement="right" - > + } placement="right"> {isUniswapXTrade(trade) ? : } diff --git a/src/components/swap/SwapBuyFiatButton.tsx b/src/components/swap/SwapBuyFiatButton.tsx index 6100ab42564..9e104fc5e1c 100644 --- a/src/components/swap/SwapBuyFiatButton.tsx +++ b/src/components/swap/SwapBuyFiatButton.tsx @@ -1,7 +1,5 @@ import { Trans } from '@lingui/macro' -import { BrowserEvent, InterfaceElementName, SharedEventName } from '@uniswap/analytics-events' import { useWeb3React } from '@web3-react/core' -import { TraceEvent } from 'analytics' import { useAccountDrawer } from 'components/AccountDrawer' import { ButtonText } from 'components/Button' import { MouseoverTooltip } from 'components/Tooltip' @@ -110,30 +108,17 @@ export default function SwapBuyFiatButton() { text={
Crypto purchases are not available in your region. - - - Learn more - - + + Learn more +
} placement="bottom" disabled={fiatOnRampsUnavailableTooltipDisabled} > - - - Buy - - + + Buy +
) } diff --git a/src/components/swap/SwapDetailsDropdown.tsx b/src/components/swap/SwapDetailsDropdown.tsx index 6e412449a6d..c339c0a0167 100644 --- a/src/components/swap/SwapDetailsDropdown.tsx +++ b/src/components/swap/SwapDetailsDropdown.tsx @@ -1,12 +1,9 @@ import { Trans } from '@lingui/macro' -import { BrowserEvent, InterfaceElementName, SwapEventName } from '@uniswap/analytics-events' import { Percent } from '@uniswap/sdk-core' -import { TraceEvent, useTrace } from 'analytics' import AnimatedDropdown from 'components/AnimatedDropdown' import Column from 'components/Column' import { LoadingOpacityContainer } from 'components/Loader/styled' import { RowBetween, RowFixed } from 'components/Row' -import { formatCommonPropertiesForTrade } from 'lib/utils/analytics' import { useState } from 'react' import { ChevronDown } from 'react-feather' import { InterfaceTrade } from 'state/routing/types' @@ -48,48 +45,36 @@ interface SwapDetailsProps { } export default function SwapDetailsDropdown(props: SwapDetailsProps) { - const { trade, syncing, loading, allowedSlippage } = props + const { trade, syncing, loading } = props const theme = useTheme() const [showDetails, setShowDetails] = useState(false) - const trace = useTrace() return ( - setShowDetails(!showDetails)} + disabled={!trade} + open={showDetails} > - setShowDetails(!showDetails)} - disabled={!trade} - open={showDetails} - > - - {trade ? ( - - - - ) : loading || syncing ? ( - - Fetching best price... - - ) : null} - - - {!showDetails && isSubmittableTrade(trade) && ( - - )} - - - - + + {trade ? ( + + + + ) : loading || syncing ? ( + + Fetching best price... + + ) : null} + + + {!showDetails && isSubmittableTrade(trade) && ( + + )} + + + ) diff --git a/src/components/swap/SwapModalFooter.tsx b/src/components/swap/SwapModalFooter.tsx index 86f5155c9df..45da42b5346 100644 --- a/src/components/swap/SwapModalFooter.tsx +++ b/src/components/swap/SwapModalFooter.tsx @@ -1,20 +1,13 @@ import { Trans } from '@lingui/macro' -import { BrowserEvent, InterfaceElementName, SwapEventName } from '@uniswap/analytics-events' import { Percent } from '@uniswap/sdk-core' -import { TraceEvent } from 'analytics' import Column from 'components/Column' import SpinningLoader from 'components/Loader/SpinningLoader' import { SwapResult } from 'hooks/useSwapCallback' -import useTransactionDeadline from 'hooks/useTransactionDeadline' import { ReactNode } from 'react' import { AlertTriangle } from 'react-feather' -import { InterfaceTrade, RouterPreference } from 'state/routing/types' -import { isClassicTrade } from 'state/routing/utils' -import { useRouterPreference, useUserSlippageTolerance } from 'state/user/hooks' +import { InterfaceTrade } from 'state/routing/types' import styled, { useTheme } from 'styled-components' import { ThemedText } from 'theme/components' -import getRoutingDiagramEntries from 'utils/getRoutingDiagramEntries' -import { formatSwapButtonClickEventProperties } from 'utils/loggingFormatters' import { ButtonError, SmallButtonPrimary } from '../Button' import Row, { AutoRow, RowBetween, RowFixed } from '../Row' @@ -39,12 +32,9 @@ const ConfirmButton = styled(ButtonError)` export default function SwapModalFooter({ trade, allowedSlippage, - swapResult, onConfirm, swapErrorMessage, disabledConfirm, - fiatValueInput, - fiatValueOutput, showAcceptChanges, onAcceptChanges, isLoading, @@ -61,10 +51,6 @@ export default function SwapModalFooter({ onAcceptChanges: () => void isLoading: boolean }) { - const transactionDeadlineSecondsSinceEpoch = useTransactionDeadline()?.toNumber() // in seconds since epoch - const isAutoSlippage = useUserSlippageTolerance()[0] === 'auto' - const [routerPreference] = useRouterPreference() - const routes = isClassicTrade(trade) ? getRoutingDiagramEntries(trade) : undefined const theme = useTheme() const lineItemProps = { trade, allowedSlippage, syncing: false } @@ -97,43 +83,25 @@ export default function SwapModalFooter({ ) : ( - - - {isLoading ? ( - - - - Finalizing quote... - - - ) : ( - - Confirm swap - - )} - - + {isLoading ? ( + + + + Finalizing quote... + + + ) : ( + + Confirm swap + + )} + {swapErrorMessage ? : null} diff --git a/src/connection/WalletConnectV2.ts b/src/connection/WalletConnectV2.ts index 02d4a64d178..c72c146bdbf 100644 --- a/src/connection/WalletConnectV2.ts +++ b/src/connection/WalletConnectV2.ts @@ -1,6 +1,5 @@ import { ChainId } from '@uniswap/sdk-core' import { URI_AVAILABLE, WalletConnect, WalletConnectConstructorArgs } from '@web3-react/walletconnect-v2' -import { sendAnalyticsEvent } from 'analytics' import { L1_CHAIN_IDS, L2_CHAIN_IDS } from 'constants/chains' import { Z_INDEX } from 'theme/zIndex' import { isIOS } from 'utils/userAgent' @@ -58,7 +57,6 @@ export class WalletConnectV2 extends WalletConnect { } activate(chainId?: number) { - sendAnalyticsEvent(this.ANALYTICS_EVENT) return super.activate(chainId) } } diff --git a/src/connection/activate.ts b/src/connection/activate.ts index d41b02cf2f5..18880d3d6bd 100644 --- a/src/connection/activate.ts +++ b/src/connection/activate.ts @@ -1,14 +1,10 @@ -import { InterfaceEventName, WalletConnectionResult } from '@uniswap/analytics-events' import { ChainId } from '@uniswap/sdk-core' -import { sendAnalyticsEvent } from 'analytics' import { Connection } from 'connection/types' import { atom } from 'jotai' import { useAtomValue, useUpdateAtom } from 'jotai/utils' import { useCallback } from 'react' -import { useLocation } from 'react-router-dom' import { useAppDispatch } from 'state/hooks' import { updateSelectedWallet } from 'state/user/reducer' -import { getCurrentPageFromLocation } from 'utils/urlRoutes' import { didUserReject } from './utils' @@ -28,8 +24,6 @@ const activationStateAtom = atom(IDLE_ACTIVATION_STATE) function useTryActivation() { const dispatch = useAppDispatch() const setActivationState = useUpdateAtom(activationStateAtom) - const { pathname } = useLocation() - const currentPage = getCurrentPageFromLocation(pathname) return useCallback( async (connection: Connection, onSuccess: () => void, chainId?: ChainId) => { @@ -62,17 +56,10 @@ function useTryActivation() { console.debug(`Connection failed: ${connection.getName()}`) console.error(error) - // Failed Connection events are logged here, while successful ones are logged by Web3Provider - sendAnalyticsEvent(InterfaceEventName.WALLET_CONNECTED, { - result: WalletConnectionResult.FAILED, - wallet_type: connection.getName(), - page: currentPage, - error: error.message, - }) setActivationState({ status: ActivationStatus.ERROR, connection, error }) } }, - [currentPage, dispatch, setActivationState] + [dispatch, setActivationState] ) } diff --git a/src/hooks/useContract.ts b/src/hooks/useContract.ts index 77de1a6e9d3..1c8ee303f7f 100644 --- a/src/hooks/useContract.ts +++ b/src/hooks/useContract.ts @@ -1,5 +1,4 @@ import { Contract } from '@ethersproject/contracts' -import { InterfaceEventName } from '@uniswap/analytics-events' import { ARGENT_WALLET_DETECTOR_ADDRESS, ChainId, @@ -27,11 +26,10 @@ import ERC721_ABI from 'abis/erc721.json' import ERC1155_ABI from 'abis/erc1155.json' import { ArgentWalletDetector, EnsPublicResolver, EnsRegistrar, Erc20, Erc721, Erc1155, Weth } from 'abis/types' import WETH_ABI from 'abis/weth.json' -import { sendAnalyticsEvent } from 'analytics' import { DEPRECATED_RPC_PROVIDERS, RPC_PROVIDERS } from 'constants/providers' import { WRAPPED_NATIVE_CURRENCY } from 'constants/tokens' import { useFallbackProviderEnabled } from 'featureFlags/flags/fallbackProvider' -import { useEffect, useMemo } from 'react' +import { useMemo } from 'react' import { NonfungiblePositionManager, TickLens, UniswapInterfaceMulticall } from 'types/v3' import { V3Migrator } from 'types/v3/V3Migrator' import { getContract } from 'utils' @@ -150,20 +148,11 @@ export function useMainnetInterfaceMulticall() { } export function useV3NFTPositionManagerContract(withSignerIfPossible?: boolean): NonfungiblePositionManager | null { - const { account } = useWeb3React() const contract = useContract( NONFUNGIBLE_POSITION_MANAGER_ADDRESSES, NFTPositionManagerABI, withSignerIfPossible ) - useEffect(() => { - if (contract && account) { - sendAnalyticsEvent(InterfaceEventName.WALLET_PROVIDER_USED, { - source: 'useV3NFTPositionManagerContract', - contract, - }) - } - }, [account, contract]) return contract } diff --git a/src/hooks/useLocalCurrencyLinkProps.ts b/src/hooks/useLocalCurrencyLinkProps.ts index e1467cf3bfc..22ba9d5cb25 100644 --- a/src/hooks/useLocalCurrencyLinkProps.ts +++ b/src/hooks/useLocalCurrencyLinkProps.ts @@ -1,4 +1,3 @@ -import { sendAnalyticsEvent } from 'analytics' import { SupportedLocalCurrency } from 'constants/localCurrencies' import useParsedQueryString from 'hooks/useParsedQueryString' import { useAtom } from 'jotai' @@ -7,7 +6,7 @@ import { useMemo } from 'react' import type { To } from 'react-router-dom' import { useLocation } from 'react-router-dom' -import { activeLocalCurrencyAtom, useActiveLocalCurrency } from './useActiveLocalCurrency' +import { activeLocalCurrencyAtom } from './useActiveLocalCurrency' export function useLocalCurrencyLinkProps(localCurrency?: SupportedLocalCurrency): { to?: To @@ -15,7 +14,6 @@ export function useLocalCurrencyLinkProps(localCurrency?: SupportedLocalCurrency } { const location = useLocation() const qs = useParsedQueryString() - const activeLocalCurrency = useActiveLocalCurrency() const [, updateActiveLocalCurrency] = useAtom(activeLocalCurrencyAtom) return useMemo( @@ -29,12 +27,8 @@ export function useLocalCurrencyLinkProps(localCurrency?: SupportedLocalCurrency }, onClick: () => { updateActiveLocalCurrency(localCurrency) - sendAnalyticsEvent('Local Currency Selected', { - previous_local_currency: activeLocalCurrency, - new_local_currency: localCurrency, - }) }, }, - [localCurrency, location, qs, updateActiveLocalCurrency, activeLocalCurrency] + [localCurrency, location, qs, updateActiveLocalCurrency] ) } diff --git a/src/hooks/useSwapCallback.tsx b/src/hooks/useSwapCallback.tsx index 6da00627b97..4a8e9eb8b4d 100644 --- a/src/hooks/useSwapCallback.tsx +++ b/src/hooks/useSwapCallback.tsx @@ -40,15 +40,11 @@ export function useSwapCallback( fiatValues, }) - const universalRouterSwapCallback = useUniversalRouterSwapCallback( - isClassicTrade(trade) ? trade : undefined, - fiatValues, - { - slippageTolerance: allowedSlippage, - deadline, - permit: permitSignature, - } - ) + const universalRouterSwapCallback = useUniversalRouterSwapCallback(isClassicTrade(trade) ? trade : undefined, { + slippageTolerance: allowedSlippage, + deadline, + permit: permitSignature, + }) const swapCallback = isUniswapXTrade(trade) ? uniswapXSwapCallback : universalRouterSwapCallback diff --git a/src/hooks/useSwapTaxes.ts b/src/hooks/useSwapTaxes.ts index 426b161062f..805dd48234a 100644 --- a/src/hooks/useSwapTaxes.ts +++ b/src/hooks/useSwapTaxes.ts @@ -1,10 +1,8 @@ -import { InterfaceEventName } from '@uniswap/analytics-events' import { ChainId, Percent } from '@uniswap/sdk-core' import { WETH_ADDRESS as getWethAddress } from '@uniswap/universal-router-sdk' import { useWeb3React } from '@web3-react/core' import FOT_DETECTOR_ABI from 'abis/fee-on-transfer-detector.json' import { FeeOnTransferDetector } from 'abis/types' -import { sendAnalyticsEvent } from 'analytics' import { ZERO_PERCENT } from 'constants/misc' import { useEffect, useState } from 'react' @@ -13,18 +11,7 @@ import { useContract } from './useContract' const FEE_ON_TRANSFER_DETECTOR_ADDRESS = '0x19C97dc2a25845C7f9d1d519c8C2d4809c58b43f' function useFeeOnTransferDetectorContract(): FeeOnTransferDetector | null { - const { account } = useWeb3React() - const contract = useContract(FEE_ON_TRANSFER_DETECTOR_ADDRESS, FOT_DETECTOR_ABI) - - useEffect(() => { - if (contract && account) { - sendAnalyticsEvent(InterfaceEventName.WALLET_PROVIDER_USED, { - source: 'useFeeOnTransferDetectorContract', - contract, - }) - } - }, [account, contract]) - return contract + return useContract(FEE_ON_TRANSFER_DETECTOR_ADDRESS, FOT_DETECTOR_ABI) } // TODO(WEB-2787): add tax-fetching for other chains diff --git a/src/hooks/useTokenAllowance.ts b/src/hooks/useTokenAllowance.ts index 4bde759588a..b8a4d37d7ab 100644 --- a/src/hooks/useTokenAllowance.ts +++ b/src/hooks/useTokenAllowance.ts @@ -1,7 +1,5 @@ import { ContractTransaction } from '@ethersproject/contracts' -import { InterfaceEventName } from '@uniswap/analytics-events' import { CurrencyAmount, MaxUint256, Token } from '@uniswap/sdk-core' -import { sendAnalyticsEvent, useTrace } from 'analytics' import { useTokenContract } from 'hooks/useContract' import { useSingleCallResult } from 'lib/hooks/multicall' import { useCallback, useEffect, useMemo, useState } from 'react' @@ -45,7 +43,6 @@ export function useUpdateTokenAllowance( spender: string ): () => Promise<{ response: ContractTransaction; info: ApproveTransactionInfo }> { const contract = useTokenContract(amount?.currency.address) - const trace = useTrace() return useCallback(async () => { try { @@ -55,12 +52,6 @@ export function useUpdateTokenAllowance( const allowance = amount.equalTo(0) ? '0' : MAX_ALLOWANCE const response = await contract.approve(spender, allowance) - sendAnalyticsEvent(InterfaceEventName.APPROVE_TOKEN_TXN_SUBMITTED, { - chain_id: amount.currency.chainId, - token_symbol: amount.currency.symbol, - token_address: amount.currency.address, - ...trace, - }) return { response, info: { @@ -77,7 +68,7 @@ export function useUpdateTokenAllowance( } throw new Error(`${symbol} token allowance failed: ${e instanceof Error ? e.message : e}`) } - }, [amount, contract, spender, trace]) + }, [amount, contract, spender]) } export function useRevokeTokenAllowance( diff --git a/src/hooks/useUniswapXSwapCallback.ts b/src/hooks/useUniswapXSwapCallback.ts index 044dfcd7677..07eb67d965a 100644 --- a/src/hooks/useUniswapXSwapCallback.ts +++ b/src/hooks/useUniswapXSwapCallback.ts @@ -1,11 +1,8 @@ import { BigNumber } from '@ethersproject/bignumber' import * as Sentry from '@sentry/react' -import { SwapEventName } from '@uniswap/analytics-events' import { Percent } from '@uniswap/sdk-core' import { DutchOrder, DutchOrderBuilder } from '@uniswap/uniswapx-sdk' import { useWeb3React } from '@web3-react/core' -import { sendAnalyticsEvent, useTrace } from 'analytics' -import { formatSwapSignedAnalyticsEventProperties } from 'lib/utils/analytics' import { useCallback } from 'react' import { DutchOrderTrade, TradeFillType } from 'state/routing/types' import { trace } from 'tracing/trace' @@ -46,15 +43,12 @@ async function getUpdatedNonce(swapper: string, chainId: number): Promise @@ -106,19 +100,8 @@ export function useUniswapXSwapCallback({ } } - const beforeSign = Date.now() const { signature, updatedOrder } = await signDutchOrder() - sendAnalyticsEvent(SwapEventName.SWAP_SIGNED, { - ...formatSwapSignedAnalyticsEventProperties({ - trade, - allowedSlippage, - fiatValues, - timeToSignSinceRequestMs: Date.now() - beforeSign, - }), - ...analyticsContext, - }) - const res = await fetch(`${UNISWAP_API_URL}/order`, { method: 'POST', body: JSON.stringify({ @@ -134,16 +117,6 @@ export function useUniswapXSwapCallback({ // TODO(UniswapX): For now, `errorCode` is not always present in the response, so we have to fallback // check for status code and perform this type narrowing. if (isErrorResponse(res, body)) { - sendAnalyticsEvent('UniswapX Order Post Error', { - ...formatSwapSignedAnalyticsEventProperties({ - trade, - allowedSlippage, - fiatValues, - }), - ...analyticsContext, - errorCode: body.errorCode, - detail: body.detail, - }) // TODO(UniswapX): Provide a similar utility to `swapErrorToUserReadableMessage` once // backend team provides a list of error codes and potential messages throw new Error(`${body.errorCode ?? body.detail ?? 'Unknown error'}`) @@ -154,6 +127,6 @@ export function useUniswapXSwapCallback({ response: { orderHash: body.hash, deadline: updatedOrder.info.deadline }, } }), - [account, provider, trade, allowedSlippage, fiatValues, analyticsContext] + [account, provider, trade] ) } diff --git a/src/hooks/useUniversalRouter.ts b/src/hooks/useUniversalRouter.ts index 3ba976a34f1..c993e37f0f8 100644 --- a/src/hooks/useUniversalRouter.ts +++ b/src/hooks/useUniversalRouter.ts @@ -1,16 +1,11 @@ import { BigNumber } from '@ethersproject/bignumber' import { t } from '@lingui/macro' -import { SwapEventName } from '@uniswap/analytics-events' import { Percent } from '@uniswap/sdk-core' import { SwapRouter, UNIVERSAL_ROUTER_ADDRESS } from '@uniswap/universal-router-sdk' import { FeeOptions, toHex } from '@uniswap/v3-sdk' import { useWeb3React } from '@web3-react/core' -import { sendAnalyticsEvent, useTrace } from 'analytics' -import useBlockNumber from 'lib/hooks/useBlockNumber' -import { formatCommonPropertiesForTrade, formatSwapSignedAnalyticsEventProperties } from 'lib/utils/analytics' import { useCallback } from 'react' import { ClassicTrade, TradeFillType } from 'state/routing/types' -import { useUserSlippageTolerance } from 'state/user/hooks' import { trace } from 'tracing/trace' import { calculateGasMargin } from 'utils/calculateGasMargin' import { UserRejectedRequestError, WrongChainError } from 'utils/errors' @@ -45,15 +40,8 @@ interface SwapOptions { feeOptions?: FeeOptions } -export function useUniversalRouterSwapCallback( - trade: ClassicTrade | undefined, - fiatValues: { amountIn?: number; amountOut?: number }, - options: SwapOptions -) { +export function useUniversalRouterSwapCallback(trade: ClassicTrade | undefined, options: SwapOptions) { const { account, chainId, provider } = useWeb3React() - const analyticsContext = useTrace() - const blockNumber = useBlockNumber() - const isAutoSlippage = useUserSlippageTolerance()[0] === 'auto' return useCallback(async () => { return trace('swap.send', async ({ setTraceData, setTraceStatus, setTraceError }) => { @@ -92,40 +80,16 @@ export function useUniversalRouterSwapCallback( } catch (gasError) { setTraceStatus('failed_precondition') setTraceError(gasError) - sendAnalyticsEvent(SwapEventName.SWAP_ESTIMATE_GAS_CALL_FAILED, { - ...formatCommonPropertiesForTrade(trade, options.slippageTolerance), - ...analyticsContext, - client_block_number: blockNumber, - tx, - error: gasError, - isAutoSlippage, - }) console.warn(gasError) throw new GasEstimationError() } const gasLimit = calculateGasMargin(gasEstimate) setTraceData('gasLimit', gasLimit.toNumber()) - const beforeSign = Date.now() const response = await provider .getSigner() .sendTransaction({ ...tx, gasLimit }) .then((response) => { - sendAnalyticsEvent(SwapEventName.SWAP_SIGNED, { - ...formatSwapSignedAnalyticsEventProperties({ - trade, - timeToSignSinceRequestMs: Date.now() - beforeSign, - allowedSlippage: options.slippageTolerance, - fiatValues, - txHash: response.hash, - }), - ...analyticsContext, - }) if (tx.data !== response.data) { - sendAnalyticsEvent(SwapEventName.SWAP_MODIFIED_IN_WALLET, { - txHash: response.hash, - ...analyticsContext, - }) - if (!response.data || response.data.length === 0 || response.data === '0x') { throw new ModifiedSwapError() } @@ -154,16 +118,12 @@ export function useUniversalRouterSwapCallback( }) }, [ account, - analyticsContext, - blockNumber, chainId, - fiatValues, options.deadline, options.feeOptions, options.permit, options.slippageTolerance, provider, trade, - isAutoSlippage, ]) } diff --git a/src/hooks/useWrapCallback.tsx b/src/hooks/useWrapCallback.tsx index e5a0b8a16d7..392cca03115 100644 --- a/src/hooks/useWrapCallback.tsx +++ b/src/hooks/useWrapCallback.tsx @@ -1,10 +1,7 @@ import { Trans } from '@lingui/macro' -import { InterfaceEventName } from '@uniswap/analytics-events' import { Currency } from '@uniswap/sdk-core' import { useWeb3React } from '@web3-react/core' -import { sendAnalyticsEvent } from 'analytics' import useNativeCurrency from 'lib/hooks/useNativeCurrency' -import { formatToDecimal, getTokenAddress } from 'lib/utils/analytics' import tryParseCurrencyAmount from 'lib/utils/tryParseCurrencyAmount' import { useMemo, useState } from 'react' @@ -84,15 +81,6 @@ export default function useWrapCallback( const hasInputAmount = Boolean(inputAmount?.greaterThan('0')) const sufficientBalance = inputAmount && balance && !balance.lessThan(inputAmount) - const eventProperties = { - token_in_address: getTokenAddress(inputCurrency), - token_out_address: getTokenAddress(outputCurrency), - token_in_symbol: inputCurrency.symbol, - token_out_symbol: outputCurrency.symbol, - chain_id: inputCurrency.chainId, - amount: inputAmount ? formatToDecimal(inputAmount, inputAmount?.currency.decimals) : undefined, - } - if (inputCurrency.isNative && weth.equals(outputCurrency)) { return { wrapType: WrapType.WRAP, @@ -104,12 +92,6 @@ export default function useWrapCallback( network.chainId !== chainId || wethContract.address !== WRAPPED_NATIVE_CURRENCY[network.chainId]?.address ) { - sendAnalyticsEvent(InterfaceEventName.WRAP_TOKEN_TXN_INVALIDATED, { - ...eventProperties, - contract_address: wethContract.address, - contract_chain_id: network.chainId, - type: WrapType.WRAP, - }) const error = new Error(`Invalid WETH contract Please file a bug detailing how this happened - https://github.com/Uniswap/interface/issues/new?labels=bug&template=bug-report.md&title=Invalid%20WETH%20contract`) setError(error) @@ -122,10 +104,6 @@ Please file a bug detailing how this happened - https://github.com/Uniswap/inter currencyAmountRaw: inputAmount?.quotient.toString(), chainId, }) - sendAnalyticsEvent(InterfaceEventName.WRAP_TOKEN_TXN_SUBMITTED, { - ...eventProperties, - type: WrapType.WRAP, - }) return txReceipt.hash } : undefined, @@ -149,10 +127,6 @@ Please file a bug detailing how this happened - https://github.com/Uniswap/inter currencyAmountRaw: inputAmount?.quotient.toString(), chainId, }) - sendAnalyticsEvent(InterfaceEventName.WRAP_TOKEN_TXN_SUBMITTED, { - ...eventProperties, - type: WrapType.UNWRAP, - }) return txReceipt.hash } catch (error) { console.error('Could not withdraw', error) diff --git a/src/lib/hooks/useApproval.ts b/src/lib/hooks/useApproval.ts index 95ed9fff2a3..0c69bc8c2f8 100644 --- a/src/lib/hooks/useApproval.ts +++ b/src/lib/hooks/useApproval.ts @@ -1,12 +1,9 @@ import { MaxUint256 } from '@ethersproject/constants' import type { TransactionResponse } from '@ethersproject/providers' -import { InterfaceEventName } from '@uniswap/analytics-events' import { Currency, CurrencyAmount, Token } from '@uniswap/sdk-core' import { useWeb3React } from '@web3-react/core' -import { sendAnalyticsEvent } from 'analytics' import { useTokenContract } from 'hooks/useContract' import { useTokenAllowance } from 'hooks/useTokenAllowance' -import { getTokenAddress } from 'lib/utils/analytics' import { useCallback, useMemo } from 'react' import { calculateGasMargin } from 'utils/calculateGasMargin' @@ -95,12 +92,6 @@ export function useApproval( gasLimit: calculateGasMargin(estimatedGas), }) .then((response) => { - const eventProperties = { - chain_id: chainId, - token_symbol: token?.symbol, - token_address: getTokenAddress(token), - } - sendAnalyticsEvent(InterfaceEventName.APPROVE_TOKEN_TXN_SUBMITTED, eventProperties) return { response, tokenAddress: token.address, diff --git a/src/lib/hooks/useCurrency.ts b/src/lib/hooks/useCurrency.ts index acdb9480d78..0f943fdfc94 100644 --- a/src/lib/hooks/useCurrency.ts +++ b/src/lib/hooks/useCurrency.ts @@ -1,14 +1,12 @@ import { arrayify } from '@ethersproject/bytes' import { parseBytes32String } from '@ethersproject/strings' -import { InterfaceEventName } from '@uniswap/analytics-events' import { ChainId, Currency, Token } from '@uniswap/sdk-core' import { useWeb3React } from '@web3-react/core' -import { sendAnalyticsEvent } from 'analytics' import { asSupportedChain, isSupportedChain } from 'constants/chains' import { useBytes32TokenContract, useTokenContract } from 'hooks/useContract' import { NEVER_RELOAD, useSingleCallResult } from 'lib/hooks/multicall' import useNativeCurrency from 'lib/hooks/useNativeCurrency' -import { useEffect, useMemo } from 'react' +import { useMemo } from 'react' import { DEFAULT_ERC20_DECIMALS } from '../../constants/tokens' import { TOKEN_SHORTHANDS } from '../../constants/tokens' @@ -84,16 +82,6 @@ export function useTokenFromMapOrNetwork(tokens: TokenMap, tokenAddress?: string const address = isAddress(tokenAddress) const token: Token | undefined = address ? tokens[address] : undefined const tokenFromNetwork = useTokenFromActiveNetwork(token ? undefined : address ? address : undefined) - - useEffect(() => { - if (tokenFromNetwork) { - sendAnalyticsEvent(InterfaceEventName.WALLET_PROVIDER_USED, { - source: 'useTokenFromActiveNetwork', - token: tokenFromNetwork, - }) - } - }, [tokenFromNetwork]) - return tokenFromNetwork ?? token } diff --git a/src/nft/components/bag/Bag.tsx b/src/nft/components/bag/Bag.tsx index 18323e2589f..7c99f7a7b2d 100644 --- a/src/nft/components/bag/Bag.tsx +++ b/src/nft/components/bag/Bag.tsx @@ -1,6 +1,4 @@ import { Trans } from '@lingui/macro' -import { NFTEventName } from '@uniswap/analytics-events' -import { sendAnalyticsEvent } from 'analytics' import { useIsNftDetailsPage, useIsNftPage, useIsNftProfilePage } from 'hooks/useIsNftPage' import { BagFooter } from 'nft/components/bag/BagFooter' import { Box } from 'nft/components/Box' @@ -9,7 +7,7 @@ import { Column } from 'nft/components/Flex' import { Overlay } from 'nft/components/modals/Overlay' import { useBag, useIsMobile, useProfilePageState, useSellAsset, useSubscribeScrollState } from 'nft/hooks' import { BagStatus, ProfilePageStateType } from 'nft/types' -import { formatAssetEventProperties, recalculateBagUsingPooledAssets } from 'nft/utils' +import { recalculateBagUsingPooledAssets } from 'nft/utils' import { useCallback, useEffect, useMemo, useState } from 'react' import styled from 'styled-components' import { Z_INDEX } from 'theme/zIndex' @@ -137,13 +135,6 @@ const Bag = () => { (!isProfilePage && !isBuyingAssets && bagStatus === BagStatus.ADDING_TO_BAG) || (isProfilePage && !isSellingAssets) ) - const eventProperties = useMemo( - () => ({ - ...formatAssetEventProperties(itemsInBag.map((item) => item.asset)), - }), - [itemsInBag] - ) - if (!bagExpanded || !isNFTPage) { return null } @@ -162,19 +153,12 @@ const Bag = () => { {isProfilePage ? : } - {hasAssetsToShow && !isProfilePage && ( - - )} + {hasAssetsToShow && !isProfilePage && } {isSellingAssets && isProfilePage && ( { toggleBag() setProfilePageState(ProfilePageStateType.LISTING) - sendAnalyticsEvent(NFTEventName.NFT_PROFILE_PAGE_START_SELL, { - list_quantity: sellAssets.length, - collection_addresses: sellAssets.map((asset) => asset.asset_contract.address), - token_ids: sellAssets.map((asset) => asset.tokenId), - }) }} > Continue diff --git a/src/nft/components/bag/BagContent.tsx b/src/nft/components/bag/BagContent.tsx index 9cdc57815bc..3d6262ee4a8 100644 --- a/src/nft/components/bag/BagContent.tsx +++ b/src/nft/components/bag/BagContent.tsx @@ -1,10 +1,8 @@ -import { NFTEventName } from '@uniswap/analytics-events' -import { sendAnalyticsEvent, Trace } from 'analytics' import { BagRow, PriceChangeBagRow, UnavailableAssetsHeaderRow } from 'nft/components/bag/BagRow' import { Column } from 'nft/components/Flex' import { useBag, useIsMobile, useNativeUsdPrice } from 'nft/hooks' import { BagItemStatus, BagStatus } from 'nft/types' -import { formatAssetEventProperties, recalculateBagUsingPooledAssets } from 'nft/utils' +import { recalculateBagUsingPooledAssets } from 'nft/utils' import { useEffect, useMemo } from 'react' export const BagContent = () => { @@ -44,13 +42,6 @@ export const BagContent = () => { const hasAssetsInReview = priceChangedAssets.length > 0 const hasAssets = itemsInBag.length > 0 - if (hasAssetsInReview) - sendAnalyticsEvent(NFTEventName.NFT_BUY_BAG_CHANGED, { - usd_value: ethUsdPrice, - bag_quantity: itemsInBag, - ...formatAssetEventProperties(priceChangedAssets), - }) - if (bagStatus === BagStatus.IN_REVIEW && !hasAssetsInReview) { if (hasAssets) setBagStatus(BagStatus.CONFIRM_REVIEW) else setBagStatus(BagStatus.ADDING_TO_BAG) @@ -65,24 +56,14 @@ export const BagContent = () => { <> 0 || unavailableAssets.length > 0 ? 'flex' : 'none'}> {unavailableAssets.length > 0 && ( - - setItemsInBag(availableItems)} - didOpenUnavailableAssets={didOpenUnavailableAssets} - setDidOpenUnavailableAssets={setDidOpenUnavailableAssets} - isMobile={isMobile} - /> - + setItemsInBag(availableItems)} + didOpenUnavailableAssets={didOpenUnavailableAssets} + setDidOpenUnavailableAssets={setDidOpenUnavailableAssets} + isMobile={isMobile} + /> )} {priceChangedAssets.map((asset, index) => ( void - eventProperties: Record } -export const BagFooter = ({ setModalIsOpen, eventProperties }: BagFooterProps) => { +export const BagFooter = ({ setModalIsOpen }: BagFooterProps) => { const toggleWalletDrawer = useToggleAccountDrawer() const theme = useTheme() const { account, chainId, connector } = useWeb3React() @@ -446,12 +443,6 @@ export const BagFooter = ({ setModalIsOpen, eventProperties }: BagFooterProps) = setBagExpanded, ]) - const traceEventProperties = { - usd_value: usdcValue?.toExact(), - using_erc20: !!inputCurrency, - ...eventProperties, - } - return (
@@ -467,7 +458,6 @@ export const BagFooter = ({ setModalIsOpen, eventProperties }: BagFooterProps) = onClick={() => { if (!bagIsLocked) { setTokenSelectorOpen(true) - sendAnalyticsEvent(NFTEventName.NFT_BUY_TOKEN_SELECTOR_CLICKED) } }} > @@ -500,38 +490,24 @@ export const BagFooter = ({ setModalIsOpen, eventProperties }: BagFooterProps) = usingPayWithAnyToken={usingPayWithAnyToken} /> - {warningText} + {helperText} + - {warningText} - {helperText} - - {isPending && } - {buttonText} - - + {isPending && } + {buttonText} +
setTokenSelectorOpen(false)} onCurrencySelect={(currency: Currency) => { setInputCurrency(currency.isNative ? undefined : currency) - if (currency.isToken) { - sendAnalyticsEvent(NFTEventName.NFT_BUY_TOKEN_SELECTED, { - token_address: currency.address, - token_symbol: currency.symbol, - }) - } }} selectedCurrency={activeCurrency ?? undefined} onlyShowCurrenciesWithBalance={true} diff --git a/src/nft/components/card/index.tsx b/src/nft/components/card/index.tsx index 8b8bb25fa26..b57e52b9748 100644 --- a/src/nft/components/card/index.tsx +++ b/src/nft/components/card/index.tsx @@ -52,7 +52,6 @@ export const NftCard = ({ isDisabled, onButtonClick, onCardClick, - sendAnalyticsEvent, mediaShouldBePlaying, uniformAspectRatio = UniformAspectRatios.square, setUniformAspectRatio, @@ -90,7 +89,6 @@ export const NftCard = ({ onClick={() => { if (bagExpanded) setBagExpanded({ bagExpanded: false }) onCardClick?.() - sendAnalyticsEvent?.() }} > diff --git a/src/nft/components/collection/ActivityCells.tsx b/src/nft/components/collection/ActivityCells.tsx index 48f0557c2c4..23608400ef2 100644 --- a/src/nft/components/collection/ActivityCells.tsx +++ b/src/nft/components/collection/ActivityCells.tsx @@ -1,7 +1,5 @@ import { Trans } from '@lingui/macro' -import { InterfacePageName, NFTEventName } from '@uniswap/analytics-events' import { ChainId } from '@uniswap/sdk-core' -import { sendAnalyticsEvent, useTrace } from 'analytics' import { MouseoverTooltip } from 'components/Tooltip' import { NftActivityType, NftMarketplace, OrderStatus } from 'graphql/data/__generated__/types-and-hooks' import { Box } from 'nft/components/Box' @@ -118,13 +116,6 @@ export const BuyCell = ({ }, [asset, itemsInBag]) const orderIsPurchasable = isPurchasableOrder(event.orderStatus, event.marketplace) - const trace = useTrace({ page: InterfacePageName.NFT_COLLECTION_PAGE }) - const eventProperties = { - collection_address: asset.address, - token_id: asset.tokenId, - token_type: asset.tokenType, - ...trace, - } return ( @@ -136,7 +127,6 @@ export const BuyCell = ({ e.preventDefault() isSelected ? removeAsset([asset]) : selectAsset([asset]) !isSelected && !cartExpanded && !isMobile && toggleCart() - !isSelected && sendAnalyticsEvent(NFTEventName.NFT_BUY_ADDED, { eventProperties }) }} disabled={!orderIsPurchasable} > diff --git a/src/nft/components/collection/ActivitySwitcher.tsx b/src/nft/components/collection/ActivitySwitcher.tsx index 8a021b6e050..c6710f02e67 100644 --- a/src/nft/components/collection/ActivitySwitcher.tsx +++ b/src/nft/components/collection/ActivitySwitcher.tsx @@ -1,5 +1,3 @@ -import { BrowserEvent, InterfaceElementName, NFTEventName } from '@uniswap/analytics-events' -import { TraceEvent } from 'analytics' import { Box } from 'nft/components/Box' import { Row } from 'nft/components/Flex' import { useIsCollectionLoading } from 'nft/hooks' @@ -39,20 +37,14 @@ export const ActivitySwitcher = ({ > Items - !showActivity && toggleActivity()} + data-testid="nft-activity" > - !showActivity && toggleActivity()} - data-testid="nft-activity" - > - Activity - - + Activity + )} diff --git a/src/nft/components/collection/CollectionAsset.tsx b/src/nft/components/collection/CollectionAsset.tsx index f911909e358..8765fda5b58 100644 --- a/src/nft/components/collection/CollectionAsset.tsx +++ b/src/nft/components/collection/CollectionAsset.tsx @@ -1,7 +1,5 @@ import { BigNumber } from '@ethersproject/bignumber' import { Trans } from '@lingui/macro' -import { InterfacePageName, NFTEventName } from '@uniswap/analytics-events' -import { sendAnalyticsEvent, useTrace } from 'analytics' import { NftCard, NftCardDisplayProps } from 'nft/components/card' import { Ranking as RankingContainer, Suspicious as SuspiciousContainer } from 'nft/components/card/icons' import { useBag } from 'nft/hooks' @@ -37,7 +35,6 @@ export const CollectionAsset = ({ const itemsInBag = useBag((state) => state.itemsInBag) const bagExpanded = useBag((state) => state.bagExpanded) const setBagExpanded = useBag((state) => state.setBagExpanded) - const trace = useTrace({ page: InterfacePageName.NFT_COLLECTION_PAGE }) const { isSelected } = useMemo(() => { const matchingItems = itemsInBag.filter( @@ -58,14 +55,8 @@ export const CollectionAsset = ({ if (!bagExpanded && !isMobile && !bagManuallyClosed) { setBagExpanded({ bagExpanded: true }) } - sendAnalyticsEvent(NFTEventName.NFT_BUY_ADDED, { - collection_address: asset.address, - token_id: asset.tokenId, - token_type: asset.tokenType, - ...trace, - }) } - }, [addAssetsToBag, asset, bagExpanded, bagManuallyClosed, isMobile, setBagExpanded, trace]) + }, [addAssetsToBag, asset, bagExpanded, bagManuallyClosed, isMobile, setBagExpanded]) const handleRemoveAssetFromBag = useCallback(() => { removeAssetsFromBag([asset]) diff --git a/src/nft/components/collection/CollectionNfts.tsx b/src/nft/components/collection/CollectionNfts.tsx index 2d7ecb11f18..22e76b21f12 100644 --- a/src/nft/components/collection/CollectionNfts.tsx +++ b/src/nft/components/collection/CollectionNfts.tsx @@ -1,8 +1,5 @@ import { BigNumber } from '@ethersproject/bignumber' import { parseEther } from '@ethersproject/units' -import { BrowserEvent, InterfaceElementName, NFTEventName } from '@uniswap/analytics-events' -import { useWeb3React } from '@web3-react/core' -import { TraceEvent } from 'analytics' import clsx from 'clsx' import { OpacityHoverState } from 'components/Common' import { NftAssetTraitInput, NftMarketplace, NftStandard } from 'graphql/data/__generated__/types-and-hooks' @@ -220,7 +217,6 @@ export const getSortDropdownOptions = (setSortBy: (sortBy: SortBy) => void, hasR } export const CollectionNfts = ({ contractAddress, collectionStats, rarityVerified }: CollectionNftsProps) => { - const { chainId } = useWeb3React() const traits = useCollectionFilters((state) => state.traits) const minPrice = useCollectionFilters((state) => state.minPrice) const maxPrice = useCollectionFilters((state) => state.maxPrice) @@ -492,23 +488,15 @@ export const CollectionNfts = ({ contractAddress, collectionStats, rarityVerifie > - - { - if (bagExpanded && !screenSize['xl']) toggleBag() - setFiltersExpanded(!isFiltersExpanded) - }} - /> - + { + if (bagExpanded && !screenSize['xl']) toggleBag() + setFiltersExpanded(!isFiltersExpanded) + }} + /> diff --git a/src/nft/components/collection/MarketplaceSelect.tsx b/src/nft/components/collection/MarketplaceSelect.tsx index b8eab41c561..d2559a86354 100644 --- a/src/nft/components/collection/MarketplaceSelect.tsx +++ b/src/nft/components/collection/MarketplaceSelect.tsx @@ -1,5 +1,3 @@ -import { NFTEventName, NFTFilterTypes } from '@uniswap/analytics-events' -import { sendAnalyticsEvent } from 'analytics' import clsx from 'clsx' import { Box } from 'nft/components/Box' import * as styles from 'nft/components/collection/Filters.css' @@ -86,7 +84,6 @@ const MarketplaceItem = ({ removeMarket(value) setCheckboxSelected(false) } - sendAnalyticsEvent(NFTEventName.NFT_FILTER_SELECTED, { filter_type: NFTFilterTypes.MARKETPLACE }) } const checkbox = ( diff --git a/src/nft/components/collection/PriceRange.tsx b/src/nft/components/collection/PriceRange.tsx index 12ea4c60977..15b1855e177 100644 --- a/src/nft/components/collection/PriceRange.tsx +++ b/src/nft/components/collection/PriceRange.tsx @@ -1,7 +1,5 @@ import 'rc-slider/assets/index.css' -import { NFTEventName, NFTFilterTypes } from '@uniswap/analytics-events' -import { sendAnalyticsEvent } from 'analytics' import { Box } from 'nft/components/Box' import { Row } from 'nft/components/Flex' import { NumericInput } from 'nft/components/layout/Input' @@ -54,8 +52,6 @@ export const PriceRange = () => { const handleBlur: FocusEventHandler = (e) => { e.currentTarget.placeholder = placeholderText setPlaceholderText('') - if (minPrice || maxPrice) - sendAnalyticsEvent(NFTEventName.NFT_FILTER_SELECTED, { filter_type: NFTFilterTypes.PRICE_RANGE }) } const updateMinPriceRange = (v: FormEvent) => { diff --git a/src/nft/components/collection/TraitSelect.tsx b/src/nft/components/collection/TraitSelect.tsx index 30c20e92f65..c1d2f5e1e49 100644 --- a/src/nft/components/collection/TraitSelect.tsx +++ b/src/nft/components/collection/TraitSelect.tsx @@ -1,5 +1,3 @@ -import { NFTEventName, NFTFilterTypes } from '@uniswap/analytics-events' -import { sendAnalyticsEvent } from 'analytics' import useDebounce from 'hooks/useDebounce' import { Box } from 'nft/components/Box' import { Column, Row } from 'nft/components/Flex' @@ -61,7 +59,6 @@ const TraitItem = ({ removeTrait(trait) setCheckboxSelected(false) } - sendAnalyticsEvent(NFTEventName.NFT_FILTER_SELECTED, { filter_type: NFTFilterTypes.TRAIT }) } const showFullTraitName = shouldShow && trait_type === trait.trait_type && trait_value === trait.trait_value diff --git a/src/nft/components/collection/TransactionCompleteModal.tsx b/src/nft/components/collection/TransactionCompleteModal.tsx index cc8b8fb56d4..dea9e30977b 100644 --- a/src/nft/components/collection/TransactionCompleteModal.tsx +++ b/src/nft/components/collection/TransactionCompleteModal.tsx @@ -1,7 +1,4 @@ -import { formatEther } from '@ethersproject/units' import { Trans } from '@lingui/macro' -import { InterfaceModalName, NFTEventName } from '@uniswap/analytics-events' -import { Trace, useTrace } from 'analytics' import clsx from 'clsx' import { OpacityHoverState } from 'components/Common' import { Box } from 'nft/components/Box' @@ -20,7 +17,6 @@ import { getSuccessfulImageSize, parseTransactionResponse, } from 'nft/utils' -import { formatAssetEventProperties } from 'nft/utils/formatEventProperties' import { useEffect, useMemo, useRef, useState } from 'react' import styled from 'styled-components' import { ExplorerDataType, getExplorerLink } from 'utils/getExplorerLink' @@ -49,7 +45,6 @@ const TxCompleteModal = () => { const ethUsdPrice = useNativeUsdPrice() const [showUnavailable, setShowUnavailable] = useState(false) const txHash = useSendTransaction((state) => state.txHash) - const purchasedWithErc20 = useSendTransaction((state) => state.purchasedWithErc20) const setTxState = useSendTransaction((state) => state.setState) const txState = useSendTransaction((state) => state.state) const transactionStateRef = useRef(txState) @@ -58,7 +53,6 @@ const TxCompleteModal = () => { const isMobile = useIsMobile() const txHashUrl = getExplorerLink(1, txHash, ExplorerDataType.TRANSACTION) const shouldShowModal = (txState === TxStateType.Success || txState === TxStateType.Failed) && txState - const trace = useTrace({ modal: InterfaceModalName.NFT_TX_COMPLETE }) const { nftsPurchased, nftsNotPurchased, @@ -103,268 +97,232 @@ const TxCompleteModal = () => { {/* Successfully purchased NFTs */} {showPurchasedModal && ( - - - - -

- Complete! -

-

- Uniswap has granted your wish! -

-
- - - - 32 ? (isMobile ? '172px' : '292px') : 'min-content', - }} - > - {[...nftsPurchased].map((nft, index) => ( - 1 && styles.successAssetImageGrid - )} - style={{ - maxHeight: `${getSuccessfulImageSize(nftsPurchased.length, isMobile)}px`, - maxWidth: `${getSuccessfulImageSize(nftsPurchased.length, isMobile)}px`, - }} - src={nft.imageUrl} - alt={nft.name} - key={index} - /> - ))} - - {nftsPurchased.length > 32 && } - - - - {nftsPurchased.length} NFT{nftsPurchased.length === 1 ? '' : 's'} - - {formatEthPrice(totalPurchaseValue.toString())} ETH - - - - View on Etherscan - - - + + + +

+ Complete! +

+

+ Uniswap has granted your wish! +

-
+ + + + 32 ? (isMobile ? '172px' : '292px') : 'min-content', + }} + > + {[...nftsPurchased].map((nft, index) => ( + 1 && styles.successAssetImageGrid + )} + style={{ + maxHeight: `${getSuccessfulImageSize(nftsPurchased.length, isMobile)}px`, + maxWidth: `${getSuccessfulImageSize(nftsPurchased.length, isMobile)}px`, + }} + src={nft.imageUrl} + alt={nft.name} + key={index} + /> + ))} + + {nftsPurchased.length > 32 && } + + + + {nftsPurchased.length} NFT{nftsPurchased.length === 1 ? '' : 's'} + + {formatEthPrice(totalPurchaseValue.toString())} ETH + + + + View on Etherscan + + + + )} {/* NFTs that were not purchased ie Refunds */} {showRefundModal && /* Showing both purchases & refunds */ (showPurchasedModal ? ( - - + + + +

Instant Refund

+

+ Uniswap returned{' '} + {formatEthPrice(totalRefundValue.toString())} ETH back + to your wallet for unavailable items. +

- -

Instant Refund

-

- Uniswap returned{' '} - {formatEthPrice(totalRefundValue.toString())} ETH{' '} - back to your wallet for unavailable items. +

+ {formatEthPrice(totalRefundValue.toString())} ETH +

+

{formatUSDPriceWithCommas(totalUSDRefund)}

+

+ for {nftsNotPurchased.length} unavailable item + {nftsNotPurchased.length === 1 ? '' : 's'}.

-

- {formatEthPrice(totalRefundValue.toString())} ETH -

-

{formatUSDPriceWithCommas(totalUSDRefund)}

-

- for {nftsNotPurchased.length} unavailable item - {nftsNotPurchased.length === 1 ? '' : 's'}. -

- - - - View on Etherscan - - - + + + View on Etherscan + +
- - {nftsNotPurchased.map((nft, index) => ( - - {nft.name} - - ))} - - -
+ + {nftsNotPurchased.map((nft, index) => ( + + {nft.name} + + ))} + + + ) : ( // Only showing when all assets are unavailable - - - - {txState === TxStateType.Success ? ( - <> - -

Instant Refund

- - ) : ( -

Failed Transaction

- )} -
-

- {txState === TxStateType.Success && - `Selected item${ - nftsPurchased.length === 1 ? ' is' : 's are' - } no longer available. Uniswap instantly refunded you for this incomplete transaction. `} - {formatUsdPrice(txFeeFiat)} was used for gas in attempt to complete this transaction. For support, - please visit our Discord -

- - {nftsNotPurchased.length >= 3 && ( - toggleShowUnavailable()}> - {!showUnavailable && ( - - {nftsNotPurchased.slice(0, 3).map((asset, index) => ( - {asset.name} - ))} - - )} - - Unavailable - - {nftsNotPurchased.length} item{nftsNotPurchased.length === 1 ? '' : 's'} - + + + {txState === TxStateType.Success ? ( + <> + +

Instant Refund

+ + ) : ( +

Failed Transaction

+ )} +
+

+ {txState === TxStateType.Success && + `Selected item${ + nftsPurchased.length === 1 ? ' is' : 's are' + } no longer available. Uniswap instantly refunded you for this incomplete transaction. `} + {formatUsdPrice(txFeeFiat)} was used for gas in attempt to complete this transaction. For support, + please visit our Discord +

+ + {nftsNotPurchased.length >= 3 && ( + toggleShowUnavailable()}> + {!showUnavailable && ( + + {nftsNotPurchased.slice(0, 3).map((asset, index) => ( + {asset.name} + ))} + + )} + + Unavailable + + {nftsNotPurchased.length} item{nftsNotPurchased.length === 1 ? '' : 's'} - - )} - {(showUnavailable || nftsNotPurchased.length < 3) && - nftsNotPurchased.map((asset, index) => ( - - - {asset.name} + + + )} + {(showUnavailable || nftsNotPurchased.length < 3) && + nftsNotPurchased.map((asset, index) => ( + + + {asset.name} + + + +

+ {formatEthPrice( + asset.updatedPriceInfo ? asset.updatedPriceInfo.ETHPrice : asset.priceInfo.ETHPrice + )}{' '} + ETH +

- - -

- {formatEthPrice( - asset.updatedPriceInfo ? asset.updatedPriceInfo.ETHPrice : asset.priceInfo.ETHPrice - )}{' '} - ETH -

-
- - {txState === TxStateType.Success ? 'Refunded' : asset.name} - + + {txState === TxStateType.Success ? 'Refunded' : asset.name}
- ))} -
- {showUnavailable && } -

- {formatEthPrice(totalRefundValue.toString())} ETH -

-

{formatUSDPriceWithCommas(totalUSDRefund)}

- - - View on Etherscan - - -

- for {nftsNotPurchased.length} unavailable item - {nftsNotPurchased.length === 1 ? '' : 's'}. -

- closeTxCompleteScreen()} - > - - Return to Marketplace - +
+ ))} +
+ {showUnavailable && } +

+ {formatEthPrice(totalRefundValue.toString())} ETH +

+

{formatUSDPriceWithCommas(totalUSDRefund)}

+ + + View on Etherscan + -
+

+ for {nftsNotPurchased.length} unavailable item + {nftsNotPurchased.length === 1 ? '' : 's'}. +

+ closeTxCompleteScreen()} + > + + Return to Marketplace + +
))} diff --git a/src/nft/components/details/AssetPriceDetails.tsx b/src/nft/components/details/AssetPriceDetails.tsx index 6dc5ed21c43..e01d5fcb159 100644 --- a/src/nft/components/details/AssetPriceDetails.tsx +++ b/src/nft/components/details/AssetPriceDetails.tsx @@ -1,6 +1,4 @@ -import { NFTEventName } from '@uniswap/analytics-events' import { useWeb3React } from '@web3-react/core' -import { sendAnalyticsEvent, useTrace } from 'analytics' import { OpacityHoverState } from 'components/Common' import { Share } from 'components/Icons/Share' import { useNftBalance } from 'graphql/data/nft/NftBalance' @@ -221,17 +219,11 @@ const OwnerContainer = ({ asset }: { asset: WalletAsset }) => { () => (ethUsdPrice && asset.floor_sell_order_price ? ethUsdPrice * asset.floor_sell_order_price : undefined), [ethUsdPrice, asset.floor_sell_order_price] ) - const trace = useTrace() const goToListPage = () => { resetSellAssets() navigate('/nfts/profile') selectSellAsset(asset) - sendAnalyticsEvent(NFTEventName.NFT_SELL_ITEM_ADDED, { - collection_address: asset.asset_contract.address, - token_id: asset.tokenId, - ...trace, - }) setSellPageState(ProfilePageStateType.LISTING) } diff --git a/src/nft/components/explore/Table.tsx b/src/nft/components/explore/Table.tsx index f72687f4d3b..ff25d1a93c6 100644 --- a/src/nft/components/explore/Table.tsx +++ b/src/nft/components/explore/Table.tsx @@ -1,6 +1,3 @@ -import { BrowserEvent, InterfaceElementName, NFTEventName } from '@uniswap/analytics-events' -import { useWeb3React } from '@web3-react/core' -import { TraceEvent } from 'analytics' import { ArrowChangeDown } from 'components/Icons/ArrowChangeDown' import { ArrowChangeUp } from 'components/Icons/ArrowChangeUp' import { LoadingBubble } from 'components/Tokens/loading' @@ -103,7 +100,6 @@ export function Table>({ ...props }: TableProps) { const theme = useTheme() - const { chainId } = useWeb3React() const { width } = useWindowSize() const isMobile = useIsMobile() @@ -187,46 +183,38 @@ export function Table>({ prepareRow(row) return ( - navigate(`/nfts/collection/${row.original.collection.address}`)} + data-testid="nft-trending-collection" > - navigate(`/nfts/collection/${row.original.collection.address}`)} - data-testid="nft-trending-collection" - > - {row.cells.map((cell, cellIndex) => { - return ( - - {cellIndex === 0 ? ( - - {!isMobile && ( - - {i + 1} - - )} - {cell.render('Cell')} - - ) : ( - cell.render('Cell') - )} - - ) - })} - - + {row.cells.map((cell, cellIndex) => { + return ( + + {cellIndex === 0 ? ( + + {!isMobile && ( + + {i + 1} + + )} + {cell.render('Cell')} + + ) : ( + cell.render('Cell') + )} + + ) + })} + ) })} diff --git a/src/nft/components/profile/list/ListPage.tsx b/src/nft/components/profile/list/ListPage.tsx index 2436a75d3fe..ab1e6bca04a 100644 --- a/src/nft/components/profile/list/ListPage.tsx +++ b/src/nft/components/profile/list/ListPage.tsx @@ -1,7 +1,5 @@ import { Trans } from '@lingui/macro' -import { InterfaceModalName, NFTEventName } from '@uniswap/analytics-events' import { useWeb3React } from '@web3-react/core' -import { sendAnalyticsEvent, useTrace } from 'analytics' import Column from 'components/Column' import Row from 'components/Row' import { useStablecoinValue } from 'hooks/useStablecoinPrice' @@ -186,7 +184,6 @@ export const ListPage = () => { const { setProfilePageState: setSellPageState } = useProfilePageState() const { provider, chainId } = useWeb3React() const isMobile = useIsMobile() - const trace = useTrace({ modal: InterfaceModalName.NFT_LISTING }) const { formatCurrencyAmount } = useFormatter() const { setGlobalMarketplaces, sellAssets, issues } = useSellAsset( ({ setGlobalMarketplaces, sellAssets, issues }) => ({ @@ -195,9 +192,8 @@ export const ListPage = () => { issues, }) ) - const { listings, collectionsRequiringApproval, setLooksRareNonce, setCollectionStatusAndCallback } = useNFTList( - ({ listings, collectionsRequiringApproval, setLooksRareNonce, setCollectionStatusAndCallback }) => ({ - listings, + const { collectionsRequiringApproval, setLooksRareNonce, setCollectionStatusAndCallback } = useNFTList( + ({ collectionsRequiringApproval, setLooksRareNonce, setCollectionStatusAndCallback }) => ({ collectionsRequiringApproval, setLooksRareNonce, setCollectionStatusAndCallback, @@ -223,18 +219,8 @@ export const ListPage = () => { setGlobalMarketplaces(selectedMarkets) }, [selectedMarkets, setGlobalMarketplaces]) - const startListingEventProperties = { - collection_addresses: sellAssets.map((asset) => asset.asset_contract.address), - token_ids: sellAssets.map((asset) => asset.tokenId), - marketplaces: Array.from(new Set(listings.map((asset) => asset.marketplace.name))), - list_quantity: listings.length, - usd_value: usdcAmount, - ...trace, - } - const startListingFlow = async () => { if (!signer) return - sendAnalyticsEvent(NFTEventName.NFT_SELL_START_LISTING, { ...startListingEventProperties }) const signerAddress = await signer.getAddress() const nonce = await looksRareNonceFetcher(signerAddress) setLooksRareNonce(nonce ?? 0) diff --git a/src/nft/components/profile/list/Modal/ListModal.tsx b/src/nft/components/profile/list/Modal/ListModal.tsx index 4975162bc5a..5a2d590cf0c 100644 --- a/src/nft/components/profile/list/Modal/ListModal.tsx +++ b/src/nft/components/profile/list/Modal/ListModal.tsx @@ -1,14 +1,9 @@ import { Trans } from '@lingui/macro' -import { InterfaceModalName, NFTEventName } from '@uniswap/analytics-events' import { useWeb3React } from '@web3-react/core' -import { sendAnalyticsEvent, Trace, useTrace } from 'analytics' -import { useStablecoinValue } from 'hooks/useStablecoinPrice' -import useNativeCurrency from 'lib/hooks/useNativeCurrency' -import tryParseCurrencyAmount from 'lib/utils/tryParseCurrencyAmount' import { Portal } from 'nft/components/common/Portal' import { Overlay } from 'nft/components/modals/Overlay' -import { getTotalEthValue, signListingRow } from 'nft/components/profile/list/utils' -import { useNFTList, useSellAsset } from 'nft/hooks' +import { signListingRow } from 'nft/components/profile/list/utils' +import { useNFTList } from 'nft/hooks' import { ListingStatus } from 'nft/types' import { useCallback, useEffect, useMemo, useReducer } from 'react' import { X } from 'react-feather' @@ -16,7 +11,6 @@ import styled from 'styled-components' import { BREAKPOINTS } from 'theme' import { ThemedText } from 'theme/components' import { Z_INDEX } from 'theme/zIndex' -import { NumberType, useFormatter } from 'utils/formatNumbers' import { TitleRow } from '../shared' import { ListModalSection, Section } from './ListModalSection' @@ -45,11 +39,8 @@ const ListModalWrapper = styled.div` ` export const ListModal = ({ overlayClick }: { overlayClick: () => void }) => { - const { provider, chainId } = useWeb3React() + const { provider } = useWeb3React() const signer = provider?.getSigner() - const trace = useTrace({ modal: InterfaceModalName.NFT_LISTING }) - const { formatCurrencyAmount } = useFormatter() - const sellAssets = useSellAsset((state) => state.sellAssets) const { setListingStatusAndCallback, setLooksRareNonce, getLooksRareNonce, collectionsRequiringApproval, listings } = useNFTList( ({ @@ -67,19 +58,10 @@ export const ListModal = ({ overlayClick }: { overlayClick: () => void }) => { }) ) - const totalEthListingValue = useMemo(() => getTotalEthValue(sellAssets), [sellAssets]) const [openSection, toggleOpenSection] = useReducer( (s) => (s === Section.APPROVE ? Section.SIGN : Section.APPROVE), Section.APPROVE ) - const nativeCurrency = useNativeCurrency(chainId) - const parsedAmount = tryParseCurrencyAmount(totalEthListingValue.toString(), nativeCurrency) - const usdcValue = useStablecoinValue(parsedAmount) - const usdcAmount = formatCurrencyAmount({ - amount: usdcValue, - type: NumberType.FiatTokenPrice, - }) - const allCollectionsApproved = useMemo( () => collectionsRequiringApproval.every((collection) => collection.status === ListingStatus.APPROVED), [collectionsRequiringApproval] @@ -96,13 +78,6 @@ export const ListModal = ({ overlayClick }: { overlayClick: () => void }) => { for (const listing of listings) { await signListingRow(listing, signer, provider, getLooksRareNonce, setLooksRareNonce, setListingStatusAndCallback) } - - sendAnalyticsEvent(NFTEventName.NFT_LISTING_COMPLETED, { - signatures_approved: listings.filter((asset) => asset.status === ListingStatus.APPROVED), - list_quantity: listings.length, - usd_value: usdcAmount, - ...trace, - }) } // Once all collections have been approved, go to next section and start signing listings @@ -125,34 +100,32 @@ export const ListModal = ({ overlayClick }: { overlayClick: () => void }) => { return ( - - - {allListingsApproved ? ( - - ) : ( - <> - - - List NFTs - - - - - - - )} - - + + {allListingsApproved ? ( + + ) : ( + <> + + + List NFTs + + + + + + + )} + ) diff --git a/src/nft/components/profile/view/ViewMyNftsAsset.tsx b/src/nft/components/profile/view/ViewMyNftsAsset.tsx index c77763cf04a..2009ff7ae96 100644 --- a/src/nft/components/profile/view/ViewMyNftsAsset.tsx +++ b/src/nft/components/profile/view/ViewMyNftsAsset.tsx @@ -1,6 +1,4 @@ import { Trans } from '@lingui/macro' -import { NFTEventName } from '@uniswap/analytics-events' -import { sendAnalyticsEvent, useTrace } from 'analytics' import { NftCard, NftCardDisplayProps } from 'nft/components/card' import { detailsHref } from 'nft/components/card/utils' import { VerifiedIcon } from 'nft/components/icons' @@ -36,7 +34,6 @@ export const ViewMyNftsAsset = ({ ) }, [asset, sellAssets]) - const trace = useTrace() const toggleSelect = () => handleSelect(isSelected) const handleSelect = (removeAsset: boolean) => { @@ -44,11 +41,6 @@ export const ViewMyNftsAsset = ({ removeSellAsset(asset) } else { selectSellAsset(asset) - sendAnalyticsEvent(NFTEventName.NFT_SELL_ITEM_ADDED, { - collection_address: asset.asset_contract.address, - token_id: asset.tokenId, - ...trace, - }) } if ( !cartExpanded && diff --git a/src/nft/hooks/useSendTransaction.ts b/src/nft/hooks/useSendTransaction.ts index 136a61c7784..d813a4dc666 100644 --- a/src/nft/hooks/useSendTransaction.ts +++ b/src/nft/hooks/useSendTransaction.ts @@ -3,8 +3,6 @@ import { BigNumber } from '@ethersproject/bignumber' import { hexStripZeros } from '@ethersproject/bytes' import { ContractReceipt } from '@ethersproject/contracts' import type { JsonRpcSigner } from '@ethersproject/providers' -import { NFTEventName } from '@uniswap/analytics-events' -import { sendAnalyticsEvent } from 'analytics' import { create } from 'zustand' import { devtools } from 'zustand/middleware' @@ -54,7 +52,6 @@ export const useSendTransaction = create()( set({ state: TxStateType.Confirming }) set({ txHash: res.hash }) set({ purchasedWithErc20 }) - sendAnalyticsEvent(NFTEventName.NFT_BUY_BAG_SIGNED, { transaction_hash: res.hash }) const txReceipt = await res.wait() diff --git a/src/nft/pages/asset/Asset.tsx b/src/nft/pages/asset/Asset.tsx index 30619ebccf6..b1683a4f9cf 100644 --- a/src/nft/pages/asset/Asset.tsx +++ b/src/nft/pages/asset/Asset.tsx @@ -1,5 +1,3 @@ -import { InterfacePageName } from '@uniswap/analytics-events' -import { Trace } from 'analytics' import { useNftAssetDetails } from 'graphql/data/nft/Details' import { AssetDetails } from 'nft/components/details/AssetDetails' import { AssetDetailsLoading } from 'nft/components/details/AssetDetailsLoading' @@ -43,20 +41,14 @@ const AssetPage = () => { if (loading) return return ( <> - - {!!asset && !!collection ? ( - - - - - - - ) : null} - + {!!asset && !!collection ? ( + + + + + + + ) : null} ) } diff --git a/src/nft/pages/collection/index.tsx b/src/nft/pages/collection/index.tsx index 750607f5eb0..7e70c673117 100644 --- a/src/nft/pages/collection/index.tsx +++ b/src/nft/pages/collection/index.tsx @@ -1,6 +1,4 @@ -import { InterfacePageName } from '@uniswap/analytics-events' import { useWeb3React } from '@web3-react/core' -import { Trace } from 'analytics' import Column from 'components/Column' import { OpacityHoverState } from 'components/Common' import Row from 'components/Row' @@ -181,87 +179,79 @@ const Collection = () => { return ( <> - `calc(100% - ${x as number}px)`), + }} > - `calc(100% - ${x as number}px)`), - }} - > - {contractAddress && !blocklistedCollections.includes(contractAddress) ? ( - <> - - - - - {collectionStats && } -
- { - isFiltersExpanded && setFiltersExpanded(false) - toggleActivity() - }} - /> - - - - {isFiltersExpanded && ( - <> - {isMobile && ( - - Filter - setFiltersExpanded(false)}> - - - - )} - - - )} - + {contractAddress && !blocklistedCollections.includes(contractAddress) ? ( + <> + + + + + {collectionStats && } +
+ { + isFiltersExpanded && setFiltersExpanded(false) + toggleActivity() + }} + /> + + + + {isFiltersExpanded && ( + <> + {isMobile && ( + + Filter + setFiltersExpanded(false)}> + + + + )} + + + )} + - `translate(${x as number}px)`), - width: gridWidthOffset.to((x) => `calc(100% - ${x as number}px)`), - }} - > - {isActivityToggled - ? contractAddress && ( - `translate(${x as number}px)`), + width: gridWidthOffset.to((x) => `calc(100% - ${x as number}px)`), + }} + > + {isActivityToggled + ? contractAddress && ( + + ) + : contractAddress && + collectionStats && ( + }> + - ) - : contractAddress && - collectionStats && ( - }> - - - )} - - - - ) : ( - - )} - - + + )} + + + + ) : ( + + )} + ) diff --git a/src/nft/pages/explore/index.tsx b/src/nft/pages/explore/index.tsx index e51314f316f..c1e08858167 100644 --- a/src/nft/pages/explore/index.tsx +++ b/src/nft/pages/explore/index.tsx @@ -1,5 +1,3 @@ -import { InterfacePageName } from '@uniswap/analytics-events' -import { Trace } from 'analytics' import Banner from 'nft/components/explore/Banner' import TrendingCollections from 'nft/components/explore/TrendingCollections' import { useBag } from 'nft/hooks' @@ -30,12 +28,10 @@ const NftExplore = () => { return ( <> - - - - - - + + + + ) } diff --git a/src/nft/pages/profile/index.tsx b/src/nft/pages/profile/index.tsx index 950f1831127..c1b7d6b66ff 100644 --- a/src/nft/pages/profile/index.tsx +++ b/src/nft/pages/profile/index.tsx @@ -1,7 +1,5 @@ import { Trans } from '@lingui/macro' -import { InterfacePageName } from '@uniswap/analytics-events' import { useWeb3React } from '@web3-react/core' -import { Trace } from 'analytics' import { useToggleAccountDrawer } from 'components/AccountDrawer' import { ButtonPrimary } from 'components/Button' import { XXXL_BAG_WIDTH } from 'nft/components/bag/Bag' @@ -81,25 +79,23 @@ export default function Profile() { const isListingNfts = sellPageState === ProfilePageStateType.LISTING return ( - - - {account ? ( - - {!isListingNfts ? : } - - ) : ( -
- - No items to display - - - - Connect wallet - - -
- )} -
-
+ + {account ? ( + + {!isListingNfts ? : } + + ) : ( +
+ + No items to display + + + + Connect wallet + + +
+ )} +
) } diff --git a/src/pages/AddLiquidity/index.tsx b/src/pages/AddLiquidity/index.tsx index 0af60b354af..daad6a8577f 100644 --- a/src/pages/AddLiquidity/index.tsx +++ b/src/pages/AddLiquidity/index.tsx @@ -1,11 +1,9 @@ import { BigNumber } from '@ethersproject/bignumber' import type { TransactionResponse } from '@ethersproject/providers' import { Trans } from '@lingui/macro' -import { BrowserEvent, InterfaceElementName, InterfaceEventName, LiquidityEventName } from '@uniswap/analytics-events' import { Currency, CurrencyAmount, NONFUNGIBLE_POSITION_MANAGER_ADDRESSES, Percent } from '@uniswap/sdk-core' import { FeeAmount, NonfungiblePositionManager } from '@uniswap/v3-sdk' import { useWeb3React } from '@web3-react/core' -import { sendAnalyticsEvent, TraceEvent, useTrace } from 'analytics' import { useToggleAccountDrawer } from 'components/AccountDrawer' import OwnershipWarning from 'components/addLiquidity/OwnershipWarning' import UnsupportedCurrencyFooter from 'components/swap/UnsupportedCurrencyFooter' @@ -98,7 +96,6 @@ function AddLiquidity() { }>() const { account, chainId, provider } = useWeb3React() const theme = useTheme() - const trace = useTrace() const toggleWalletDrawer = useToggleAccountDrawer() // toggle wallet when disconnected const addTransaction = useTransactionAdder() @@ -301,11 +298,6 @@ function AddLiquidity() { } addTransaction(response, transactionInfo) setTxHash(response.hash) - sendAnalyticsEvent(LiquidityEventName.ADD_LIQUIDITY_SUBMITTED, { - label: [currencies[Field.CURRENCY_A]?.symbol, currencies[Field.CURRENCY_B]?.symbol].join('/'), - ...trace, - ...transactionInfo, - }) }) }) .catch((error) => { @@ -476,16 +468,9 @@ function AddLiquidity() { ) : !account ? ( - - - Connect wallet - - + + Connect wallet + ) : ( {(approvalA === ApprovalState.NOT_APPROVED || diff --git a/src/pages/AddLiquidityV2/index.tsx b/src/pages/AddLiquidityV2/index.tsx index 0c3ff98ffec..7b392ba810f 100644 --- a/src/pages/AddLiquidityV2/index.tsx +++ b/src/pages/AddLiquidityV2/index.tsx @@ -1,10 +1,8 @@ import { BigNumber } from '@ethersproject/bignumber' import type { TransactionResponse } from '@ethersproject/providers' import { Trans } from '@lingui/macro' -import { BrowserEvent, InterfaceElementName, InterfaceEventName, LiquidityEventName } from '@uniswap/analytics-events' import { Currency, CurrencyAmount, Percent } from '@uniswap/sdk-core' import { useWeb3React } from '@web3-react/core' -import { sendAnalyticsEvent, TraceEvent, useTrace } from 'analytics' import { useToggleAccountDrawer } from 'components/AccountDrawer' import UnsupportedCurrencyFooter from 'components/swap/UnsupportedCurrencyFooter' import { SwitchLocaleLink } from 'components/SwitchLocaleLink' @@ -61,7 +59,6 @@ export default function AddLiquidity() { const { account, chainId, provider } = useWeb3React() const theme = useTheme() - const trace = useTrace() const currencyA = useCurrency(currencyIdA) const currencyB = useCurrency(currencyIdB) @@ -207,12 +204,6 @@ export default function AddLiquidity() { addTransaction(response, transactionInfo) setTxHash(response.hash) - - sendAnalyticsEvent(LiquidityEventName.ADD_LIQUIDITY_SUBMITTED, { - label: [currencies[Field.CURRENCY_A]?.symbol, currencies[Field.CURRENCY_B]?.symbol].join('/'), - ...trace, - ...transactionInfo, - }) }) ) .catch((error) => { @@ -447,16 +438,9 @@ export default function AddLiquidity() { ) : !account ? ( - - - Connect wallet - - + + Connect wallet + ) : ( {(approvalA === ApprovalState.NOT_APPROVED || diff --git a/src/pages/App.tsx b/src/pages/App.tsx index f61b1bd0481..e882caae0cf 100644 --- a/src/pages/App.tsx +++ b/src/pages/App.tsx @@ -1,12 +1,9 @@ -import { CustomUserProperties, getBrowser, SharedEventName } from '@uniswap/analytics-events' import { useWeb3React } from '@web3-react/core' -import { getDeviceId, sendAnalyticsEvent, sendInitializationEvent, Trace, user } from 'analytics' import ErrorBoundary from 'components/ErrorBoundary' import Loader from 'components/Icons/LoadingSpinner' import NavBar, { PageTabs } from 'components/NavBar' import { UK_BANNER_HEIGHT, UK_BANNER_HEIGHT_MD, UK_BANNER_HEIGHT_SM, UkBanner } from 'components/NavBar/UkBanner' -import { FeatureFlag, useFeatureFlagsIsLoaded } from 'featureFlags' -import { useUniswapXDefaultEnabled } from 'featureFlags/flags/uniswapXDefault' +import { useFeatureFlagsIsLoaded } from 'featureFlags' import { useAtom } from 'jotai' import { useBag } from 'nft/hooks/useBag' import { lazy, Suspense, useEffect, useLayoutEffect, useMemo, useState } from 'react' @@ -14,19 +11,14 @@ import { Navigate, Route, Routes, useLocation, useSearchParams } from 'react-rou import { shouldDisableNFTRoutesAtom } from 'state/application/atoms' import { useAppSelector } from 'state/hooks' import { AppState } from 'state/reducer' -import { RouterPreference } from 'state/routing/types' -import { useRouterPreference, useUserOptedOutOfUniswapX } from 'state/user/hooks' -import { StatsigProvider, StatsigUser, useGate } from 'statsig-react' +import { StatsigProvider, StatsigUser } from 'statsig-react' import styled from 'styled-components' import DarkModeQueryParamReader from 'theme/components/DarkModeQueryParamReader' -import { useIsDarkMode } from 'theme/components/ThemeToggle' import { flexRowNoWrap } from 'theme/styles' import { Z_INDEX } from 'theme/zIndex' import { STATSIG_DUMMY_KEY } from 'tracing' import { getEnvName } from 'utils/env' import { getDownloadAppLink } from 'utils/openDownloadApp' -import { getCurrentPageFromLocation } from 'utils/urlRoutes' -import { getCLS, getFCP, getFID, getLCP, Metric } from 'web-vitals' import { RouteDefinition, routes, useRouterConfig } from './RouteDefinitions' @@ -96,7 +88,6 @@ export default function App() { const location = useLocation() const { pathname } = location - const currentPage = getCurrentPageFromLocation(pathname) const [scrollY, setScrollY] = useState(0) const scrolledState = scrollY > 0 const routerConfig = useRouterConfig() @@ -132,7 +123,6 @@ export default function App() { const { account } = useWeb3React() const statsigUser: StatsigUser = useMemo( () => ({ - userID: getDeviceId(), customIDs: { address: account ?? '' }, }), [account] @@ -159,109 +149,46 @@ export default function App() { return ( - - - - {renderUkBannner && } - - - - - - - - }> - {isLoaded ? ( - - {routes.map((route: RouteDefinition) => - route.enabled(routerConfig) ? ( - - {route.nestedPaths.map((nestedPath) => ( - - ))} - - ) : null - )} - - ) : ( - - )} - - - - - - - + + {renderUkBannner && } + + + + + + + + }> + {isLoaded ? ( + + {routes.map((route: RouteDefinition) => + route.enabled(routerConfig) ? ( + + {route.nestedPaths.map((nestedPath) => ( + + ))} + + ) : null + )} + + ) : ( + + )} + + + + + + ) } - -function UserPropertyUpdater() { - const isDarkMode = useIsDarkMode() - - const [routerPreference] = useRouterPreference() - const userOptedOutOfUniswapX = useUserOptedOutOfUniswapX() - const isUniswapXDefaultEnabled = useUniswapXDefaultEnabled() - const { isLoading: isUniswapXDefaultLoading } = useGate(FeatureFlag.uniswapXDefaultEnabled) - const rehydrated = useAppSelector((state) => state._persist.rehydrated) - - useEffect(() => { - // User properties *must* be set before sending corresponding event properties, - // so that the event contains the correct and up-to-date user properties. - user.set(CustomUserProperties.USER_AGENT, navigator.userAgent) - user.set(CustomUserProperties.BROWSER, getBrowser()) - user.set(CustomUserProperties.SCREEN_RESOLUTION_HEIGHT, window.screen.height) - user.set(CustomUserProperties.SCREEN_RESOLUTION_WIDTH, window.screen.width) - user.set(CustomUserProperties.GIT_COMMIT_HASH, process.env.REACT_APP_GIT_COMMIT_HASH ?? 'unknown') - - // Service Worker analytics - const isServiceWorkerInstalled = Boolean(window.navigator.serviceWorker?.controller) - const isServiceWorkerHit = Boolean((window as any).__isDocumentCached) - const serviceWorkerProperty = isServiceWorkerInstalled ? (isServiceWorkerHit ? 'hit' : 'miss') : 'uninstalled' - - const pageLoadProperties = { service_worker: serviceWorkerProperty } - sendInitializationEvent(SharedEventName.APP_LOADED, pageLoadProperties) - const sendWebVital = - (metric: string) => - ({ delta }: Metric) => - sendAnalyticsEvent(SharedEventName.WEB_VITALS, { ...pageLoadProperties, [metric]: delta }) - getCLS(sendWebVital('cumulative_layout_shift')) - getFCP(sendWebVital('first_contentful_paint_ms')) - getFID(sendWebVital('first_input_delay_ms')) - getLCP(sendWebVital('largest_contentful_paint_ms')) - }, []) - - useEffect(() => { - user.set(CustomUserProperties.DARK_MODE, isDarkMode) - }, [isDarkMode]) - - useEffect(() => { - if (isUniswapXDefaultLoading || !rehydrated) return - - // If we're not in the transition period to UniswapX opt-out, set the router preference to whatever is specified. - if (!isUniswapXDefaultEnabled) { - user.set(CustomUserProperties.ROUTER_PREFERENCE, routerPreference) - return - } - - // In the transition period, override the stored API preference to UniswapX if the user hasn't opted out. - if (routerPreference === RouterPreference.API && !userOptedOutOfUniswapX) { - user.set(CustomUserProperties.ROUTER_PREFERENCE, RouterPreference.X) - return - } - - // Otherwise, the user has opted out or their preference is UniswapX/client, so set the preference to whatever is specified. - user.set(CustomUserProperties.ROUTER_PREFERENCE, routerPreference) - }, [routerPreference, isUniswapXDefaultEnabled, userOptedOutOfUniswapX, isUniswapXDefaultLoading, rehydrated]) - return null -} diff --git a/src/pages/CreateProposal/index.tsx b/src/pages/CreateProposal/index.tsx index 3f81da00d58..eb4e0b5a9e9 100644 --- a/src/pages/CreateProposal/index.tsx +++ b/src/pages/CreateProposal/index.tsx @@ -1,10 +1,8 @@ import { defaultAbiCoder } from '@ethersproject/abi' import { getAddress, isAddress } from '@ethersproject/address' import { Trans } from '@lingui/macro' -import { InterfacePageName } from '@uniswap/analytics-events' import { Currency, CurrencyAmount, Token } from '@uniswap/sdk-core' import { useWeb3React } from '@web3-react/core' -import { Trace } from 'analytics' import { ButtonError } from 'components/Button' import { BlueCard } from 'components/Card' import { AutoColumn } from 'components/Column' @@ -257,71 +255,69 @@ ${bodyValue} } return ( - - - - - - - - - - Tip: Select an action and describe your proposal for the community. The proposal - cannot be modified after submission, so please verify all information before submitting. The voting - period will begin immediately and last for 7 days. To propose a custom action,{' '} - - read the docs - - . - - - - - - - - - - {!hasEnoughVote ? ( - - Don’t have 2.5M votes? Anyone can create an autonomous proposal using{' '} - fish.vote - - ) : null} - - handleActionChange(proposalAction)} + + + + + + + + + Tip: Select an action and describe your proposal for the community. The proposal + cannot be modified after submission, so please verify all information before submitting. The voting + period will begin immediately and last for 7 days. To propose a custom action,{' '} + + read the docs + + . + + + + + + + - - - - + + + {!hasEnoughVote ? ( + + Don’t have 2.5M votes? Anyone can create an autonomous proposal using{' '} + fish.vote + + ) : null} + + handleActionChange(proposalAction)} + /> + + + ) } diff --git a/src/pages/Landing/index.tsx b/src/pages/Landing/index.tsx index fd408f676bb..9f65e00328e 100644 --- a/src/pages/Landing/index.tsx +++ b/src/pages/Landing/index.tsx @@ -1,6 +1,4 @@ import { Trans } from '@lingui/macro' -import { BrowserEvent, InterfaceElementName, InterfacePageName, SharedEventName } from '@uniswap/analytics-events' -import { Trace, TraceEvent } from 'analytics' import { AboutFooter } from 'components/About/AboutFooter' import Card, { CardType } from 'components/About/Card' import { MAIN_CARDS, MORE_CARDS } from 'components/About/constants' @@ -412,82 +410,68 @@ export default function Landing() { } return ( - - - - - - - - - - - - - - - - {titles.header} - - - {titles.subHeader} - - - - - - Get started - - - - - { - cardsRef?.current?.scrollIntoView({ behavior: 'smooth' }) - }} - > - Learn more - - - - - - Download the Uniswap Wallet for iOS - - - - - {cards.map(({ darkBackgroundImgSrc, lightBackgroundImgSrc, ...card }) => ( - - ))} - - - {extraCards.map(({ darkIcon, lightIcon, ...card }) => ( - - ))} - - - - - - + + + + + + + + + + + + + {titles.header} + + + {titles.subHeader} + + + + + Get started + + + + { + cardsRef?.current?.scrollIntoView({ behavior: 'smooth' }) + }} + > + Learn more + + + + + + Download the Uniswap Wallet for iOS + + + + + {cards.map(({ darkBackgroundImgSrc, lightBackgroundImgSrc, ...card }) => ( + + ))} + + + {extraCards.map(({ darkIcon, lightIcon, ...card }) => ( + + ))} + + + + + ) } diff --git a/src/pages/MigrateV2/MigrateV2Pair.tsx b/src/pages/MigrateV2/MigrateV2Pair.tsx index de4e5193f97..d3da2f93952 100644 --- a/src/pages/MigrateV2/MigrateV2Pair.tsx +++ b/src/pages/MigrateV2/MigrateV2Pair.tsx @@ -1,11 +1,9 @@ import { Contract } from '@ethersproject/contracts' import type { TransactionResponse } from '@ethersproject/providers' import { Trans } from '@lingui/macro' -import { LiquidityEventName, LiquiditySource } from '@uniswap/analytics-events' import { CurrencyAmount, Fraction, Percent, Price, Token, V2_FACTORY_ADDRESSES } from '@uniswap/sdk-core' import { FeeAmount, Pool, Position, priceToClosestTick, TickMath } from '@uniswap/v3-sdk' import { useWeb3React } from '@web3-react/core' -import { sendAnalyticsEvent, useTrace } from 'analytics' import Badge, { BadgeVariant } from 'components/Badge' import { ButtonConfirmed } from 'components/Button' import { BlueCard, DarkGrayCard, LightCard, YellowCard } from 'components/Card' @@ -129,7 +127,6 @@ function V2PairMigration({ const { chainId, account } = useWeb3React() const theme = useTheme() const v2FactoryAddress = chainId ? V2_FACTORY_ADDRESSES[chainId] : undefined - const trace = useTrace() const pairFactory = useSingleCallResult(pair, 'factory') const isNotUniswap = pairFactory.result?.[0] && pairFactory.result[0] !== v2FactoryAddress @@ -342,12 +339,6 @@ function V2PairMigration({ return migrator .multicall(data, { gasLimit: calculateGasMargin(gasEstimate) }) .then((response: TransactionResponse) => { - sendAnalyticsEvent(LiquidityEventName.MIGRATE_LIQUIDITY_SUBMITTED, { - action: `${isNotUniswap ? LiquiditySource.SUSHISWAP : LiquiditySource.V2}->${LiquiditySource.V3}`, - label: `${currency0.symbol}/${currency1.symbol}`, - ...trace, - }) - addTransaction(response, { type: TransactionType.MIGRATE_LIQUIDITY_V3, baseCurrencyId: currencyId(currency0), @@ -382,7 +373,6 @@ function V2PairMigration({ isNotUniswap, currency0, currency1, - trace, addTransaction, ]) diff --git a/src/pages/NotFound/index.tsx b/src/pages/NotFound/index.tsx index 27b58517681..f9365bf2f85 100644 --- a/src/pages/NotFound/index.tsx +++ b/src/pages/NotFound/index.tsx @@ -1,6 +1,4 @@ import { Trans } from '@lingui/macro' -import { InterfacePageName } from '@uniswap/analytics-events' -import { Trace } from 'analytics' import { SmallButtonPrimary } from 'components/Button' import { useIsMobile } from 'nft/hooks' import { Link } from 'react-router-dom' @@ -47,20 +45,18 @@ export default function NotFound() { return ( - -
- - 404 - - Page not found! - - - Liluni -
- - Oops, take me back to Swap - -
+
+ + 404 + + Page not found! + + + Liluni +
+ + Oops, take me back to Swap +
) } diff --git a/src/pages/Pool/PositionPage.tsx b/src/pages/Pool/PositionPage.tsx index 62254ac4bb2..69e251cf5a2 100644 --- a/src/pages/Pool/PositionPage.tsx +++ b/src/pages/Pool/PositionPage.tsx @@ -1,11 +1,9 @@ import { BigNumber } from '@ethersproject/bignumber' import type { TransactionResponse } from '@ethersproject/providers' import { Trans } from '@lingui/macro' -import { InterfacePageName, LiquidityEventName, LiquiditySource } from '@uniswap/analytics-events' import { Currency, CurrencyAmount, Fraction, Percent, Price, Token } from '@uniswap/sdk-core' import { NonfungiblePositionManager, Pool, Position } from '@uniswap/v3-sdk' import { useWeb3React } from '@web3-react/core' -import { sendAnalyticsEvent, Trace } from 'analytics' import Badge from 'components/Badge' import { ButtonConfirmed, ButtonGray, ButtonPrimary } from 'components/Button' import { DarkCard, LightCard } from 'components/Card' @@ -550,12 +548,6 @@ function PositionPageContent() { .then((response: TransactionResponse) => { setCollectMigrationHash(response.hash) setCollecting(false) - - sendAnalyticsEvent(LiquidityEventName.COLLECT_LIQUIDITY_SUBMITTED, { - source: LiquiditySource.V3, - label: [currency0ForFeeCollectionPurposes.symbol, currency1ForFeeCollectionPurposes.symbol].join('/'), - }) - addTransaction(response, { type: TransactionType.COLLECT_FEES, currencyId0: currencyId(currency0ForFeeCollectionPurposes), @@ -661,367 +653,364 @@ function PositionPageContent() {
) : ( - - <> - - setShowConfirm(false)} - attemptingTxn={collecting} - hash={collectMigrationHash ?? ''} - reviewContent={() => ( - Claim fees} - onDismiss={() => setShowConfirm(false)} - topContent={modalHeader} - /> - )} - pendingText={Collecting fees} - /> - - - - - ← Back to Pools - - - - - - -  {currencyQuote?.symbol} / {currencyBase?.symbol} - - - - {new Percent(feeAmount, 1_000_000).toSignificant()}% - - - - - {ownsNFT && ( - - {currency0 && currency1 && feeAmount && tokenId ? ( - - Increase liquidity - - ) : null} - {tokenId && !removed ? ( - - Remove liquidity - - ) : null} - - )} - - - - - {'result' in metadata ? ( - - - {typeof chainId === 'number' && owner && !ownsNFT ? ( - - Owner - - ) : null} - - ) : ( - - - - )} - - - - - - - {fiatValueOfLiquidity?.greaterThan(new Fraction(1, 100)) ? ( - - ${fiatValueOfLiquidity.toFixed(2, { groupSeparator: ',' })} - - ) : ( - - $- - - )} - - - - - - - - {inverted ? position?.amount0.toSignificant(4) : position?.amount1.toSignificant(4)} - - {typeof ratio === 'number' && !removed ? ( - - - {inverted ? ratio : 100 - ratio}% - - - ) : null} - - - - - - - {inverted ? position?.amount1.toSignificant(4) : position?.amount0.toSignificant(4)} - - {typeof ratio === 'number' && !removed ? ( - - - {inverted ? 100 - ratio : ratio}% - - - ) : null} - - - - - + <> + + setShowConfirm(false)} + attemptingTxn={collecting} + hash={collectMigrationHash ?? ''} + reviewContent={() => ( + Claim fees} + onDismiss={() => setShowConfirm(false)} + topContent={modalHeader} + /> + )} + pendingText={Collecting fees} + /> + + + + + ← Back to Pools + + + + + + +  {currencyQuote?.symbol} / {currencyBase?.symbol} + + + + {new Percent(feeAmount, 1_000_000).toSignificant()}% + + + + + {ownsNFT && ( + + {currency0 && currency1 && feeAmount && tokenId ? ( + + Increase liquidity + + ) : null} + {tokenId && !removed ? ( + + Remove liquidity + + ) : null} + + )} + + + + + {'result' in metadata ? ( + + + {typeof chainId === 'number' && owner && !ownsNFT ? ( + + Owner + + ) : null} + + ) : ( + + - - + )} + + + + + + + {fiatValueOfLiquidity?.greaterThan(new Fraction(1, 100)) ? ( + + ${fiatValueOfLiquidity.toFixed(2, { groupSeparator: ',' })} + + ) : ( + + $- + + )} + + - - - - {fiatValueOfFees?.greaterThan(new Fraction(1, 100)) ? ( - - ${fiatValueOfFees.toFixed(2, { groupSeparator: ',' })} - - ) : ( - - $- - - )} - - {ownsNFT && - (feeValue0?.greaterThan(0) || feeValue1?.greaterThan(0) || !!collectMigrationHash) ? ( - setShowConfirm(true)} - > - {!!collectMigrationHash && !isCollectPending ? ( - - Collected - - ) : isCollectPending || collecting ? ( - - {' '} - - Collecting - - - ) : ( - <> - - Collect fees - - - )} - - ) : null} + + + + + {inverted ? position?.amount0.toSignificant(4) : position?.amount1.toSignificant(4)} + + {typeof ratio === 'number' && !removed ? ( + + + {inverted ? ratio : 100 - ratio}% + + + ) : null} + + + + + + + {inverted ? position?.amount1.toSignificant(4) : position?.amount0.toSignificant(4)} + + {typeof ratio === 'number' && !removed ? ( + + + {inverted ? 100 - ratio : ratio}% + + + ) : null} + - + + + + + + + - - - - {feeValueUpper?.currency?.symbol} - - - - {feeValueUpper ? formatCurrencyAmount(feeValueUpper, 4) : '-'} + + {fiatValueOfFees?.greaterThan(new Fraction(1, 100)) ? ( + + ${fiatValueOfFees.toFixed(2, { groupSeparator: ',' })} + + ) : ( + + $- + + )} + + {ownsNFT && (feeValue0?.greaterThan(0) || feeValue1?.greaterThan(0) || !!collectMigrationHash) ? ( + setShowConfirm(true)} + > + {!!collectMigrationHash && !isCollectPending ? ( + + Collected - - - - - - {feeValueLower?.currency?.symbol} - - - - {feeValueLower ? formatCurrencyAmount(feeValueLower, 4) : '-'} + ) : isCollectPending || collecting ? ( + + {' '} + + Collecting + - - - - - {showCollectAsWeth && ( - - + ) : ( + <> + + Collect fees + + + )} + + ) : null} + + + + + + + + {feeValueUpper?.currency?.symbol} + + - Collect as {nativeWrappedSymbol} + {feeValueUpper ? formatCurrencyAmount(feeValueUpper, 4) : '-'} - setReceiveWETH((receiveWETH) => !receiveWETH)} + + + + + - - - )} - - - - - - - - - - - <> - - - - - - - {currencyBase && currencyQuote && ( - setManuallyInverted(!manuallyInverted)} - /> - )} - - - - - - - - Min price - - - {formatTickPrice({ - price: priceLower, - atLimit: tickAtLimit, - direction: Bound.LOWER, - numberType: NumberType.TokenTx, - })} - - - {' '} - - {currencyQuote?.symbol} per {currencyBase?.symbol} - - - - {inRange && ( - - Your position will be 100% {currencyBase?.symbol} at this price. - - )} + {feeValueLower?.currency?.symbol} + + + + {feeValueLower ? formatCurrencyAmount(feeValueLower, 4) : '-'} + + + - - - - - - Max price - - - {formatTickPrice({ - price: priceUpper, - atLimit: tickAtLimit, - direction: Bound.UPPER, - numberType: NumberType.TokenTx, - })} - - - {' '} - - {currencyQuote?.symbol} per {currencyBase?.symbol} - - - - {inRange && ( - - Your position will be 100% {currencyQuote?.symbol} at this price. - - )} + {showCollectAsWeth && ( + + + + Collect as {nativeWrappedSymbol} + + setReceiveWETH((receiveWETH) => !receiveWETH)} + /> + - - - - - - - - - - + )} + + + + + + + + + + + <> + + + + + + + {currencyBase && currencyQuote && ( + setManuallyInverted(!manuallyInverted)} + /> + )} + + + + + + + + Min price + + + {formatTickPrice({ + price: priceLower, + atLimit: tickAtLimit, + direction: Bound.LOWER, + numberType: NumberType.TokenTx, + })} + + + {' '} + + {currencyQuote?.symbol} per {currencyBase?.symbol} + + + + {inRange && ( + + Your position will be 100% {currencyBase?.symbol} at this price. + + )} + + + + + + + + Max price + + + {formatTickPrice({ + price: priceUpper, + atLimit: tickAtLimit, + direction: Bound.UPPER, + numberType: NumberType.TokenTx, + })} + + + {' '} + + {currencyQuote?.symbol} per {currencyBase?.symbol} + + + + {inRange && ( + + Your position will be 100% {currencyQuote?.symbol} at this price. + + )} + + + + + + + + + + ) } diff --git a/src/pages/Pool/index.tsx b/src/pages/Pool/index.tsx index 0a1e4ff29aa..6c709fd548e 100644 --- a/src/pages/Pool/index.tsx +++ b/src/pages/Pool/index.tsx @@ -1,7 +1,5 @@ import { Trans } from '@lingui/macro' -import { BrowserEvent, InterfaceElementName, InterfaceEventName, InterfacePageName } from '@uniswap/analytics-events' import { useWeb3React } from '@web3-react/core' -import { Trace, TraceEvent } from 'analytics' import { useToggleAccountDrawer } from 'components/AccountDrawer' import { ButtonGray, ButtonPrimary, ButtonText } from 'components/Button' import { AutoColumn } from 'components/Column' @@ -252,7 +250,7 @@ export default function Pool() { ] return ( - + <> @@ -307,19 +305,12 @@ export default function Pool() { )} {showConnectAWallet && ( - - - Connect a wallet - - + Connect a wallet + )} )} @@ -331,6 +322,6 @@ export default function Pool() { - + ) } diff --git a/src/pages/Pool/v2.tsx b/src/pages/Pool/v2.tsx index 8f9408419b7..6c2d3c9d27f 100644 --- a/src/pages/Pool/v2.tsx +++ b/src/pages/Pool/v2.tsx @@ -1,8 +1,6 @@ import { Trans } from '@lingui/macro' -import { InterfacePageName } from '@uniswap/analytics-events' import { Pair } from '@uniswap/v2-sdk' import { useWeb3React } from '@web3-react/core' -import { Trace } from 'analytics' import { V2Unsupported } from 'components/V2Unsupported' import { useNetworkSupportsV2 } from 'hooks/useNetworkSupportsV2' import JSBI from 'jsbi' @@ -140,140 +138,138 @@ export default function Pool() { }) return ( - - <> - - - - - - - - - Liquidity provider rewards - - - - - - Liquidity providers earn a 0.3% fee on all trades proportional to their share of the pool. Fees - are added to the pool, accrue in real time and can be claimed by withdrawing your liquidity. - - - - - - Read more about providing liquidity - - - - - - - + <> + + + + + + + + + Liquidity provider rewards + + + + + + Liquidity providers earn a 0.3% fee on all trades proportional to their share of the pool. Fees are + added to the pool, accrue in real time and can be claimed by withdrawing your liquidity. + + + + + + Read more about providing liquidity + + + + + + + - {!networkSupportsV2 ? ( - - ) : ( - - - - - - Your V2 liquidity - - - - - Create a pair - - - - Import pool - - - - - Add V2 liquidity - - - - + {!networkSupportsV2 ? ( + + ) : ( + + + + + + Your V2 liquidity + + + + + Create a pair + + + + Import pool + + + + + Add V2 liquidity + + + + - {!account ? ( - - - Connect to a wallet to view your liquidity. - - - ) : v2IsLoading ? ( - - - - Loading - - - - ) : allV2PairsWithLiquidity?.length > 0 || stakingPairs?.length > 0 ? ( - <> - - - - - Account analytics and accrued fees - - - - - - {v2PairsWithoutStakedAmount.map((v2Pair) => ( - - ))} - {stakingPairs.map( - (stakingPair, i) => - stakingPair[1] && ( // skip pairs that arent loaded - - ) - )} - - - - Migrate liquidity to V3 - - - - ) : ( - - - No liquidity found. - - - )} - + {!account ? ( + + + Connect to a wallet to view your liquidity. + + + ) : v2IsLoading ? ( + + + + Loading + + + + ) : allV2PairsWithLiquidity?.length > 0 || stakingPairs?.length > 0 ? ( + <> + + + + + Account analytics and accrued fees + + + + + + {v2PairsWithoutStakedAmount.map((v2Pair) => ( + + ))} + {stakingPairs.map( + (stakingPair, i) => + stakingPair[1] && ( // skip pairs that arent loaded + + ) + )} + + + + Migrate liquidity to V3 + + + + ) : ( + + + No liquidity found. + + + )} - )} - - - - + + )} + + + ) } diff --git a/src/pages/PoolFinder/index.tsx b/src/pages/PoolFinder/index.tsx index 42d8b3be4c8..7a2b41b3779 100644 --- a/src/pages/PoolFinder/index.tsx +++ b/src/pages/PoolFinder/index.tsx @@ -1,8 +1,6 @@ import { Trans } from '@lingui/macro' -import { InterfacePageName } from '@uniswap/analytics-events' import { Currency, CurrencyAmount, Token } from '@uniswap/sdk-core' import { useWeb3React } from '@web3-react/core' -import { Trace } from 'analytics' import { V2Unsupported } from 'components/V2Unsupported' import { useNetworkSupportsV2 } from 'hooks/useNetworkSupportsV2' import JSBI from 'jsbi' @@ -102,141 +100,139 @@ export default function PoolFinder() { if (!networkSupportsV2) return return ( - - <> - - - - - - - - Tip: Use this tool to find v2 pools that don't automatically appear in the interface. - - - - - { - setShowSearch(true) - setActiveField(Fields.TOKEN0) - }} - > - {currency0 ? ( - - - - {currency0.symbol} - - - ) : ( + <> + + + + + + + + Tip: Use this tool to find v2 pools that don't automatically appear in the interface. + + + + + { + setShowSearch(true) + setActiveField(Fields.TOKEN0) + }} + > + {currency0 ? ( + + - Select a token + {currency0.symbol} - )} - - - - - - - { - setShowSearch(true) - setActiveField(Fields.TOKEN1) - }} - > - {currency1 ? ( - - - - {currency1.symbol} - - - ) : ( + + ) : ( + + Select a token + + )} + + + + + + + { + setShowSearch(true) + setActiveField(Fields.TOKEN1) + }} + > + {currency1 ? ( + + - Select a token + {currency1.symbol} - )} - - - {hasPosition && ( - - - Pool found! - - - - Manage this pool. - - - + + ) : ( + + Select a token + )} + - {currency0 && currency1 ? ( - pairState === PairState.EXISTS ? ( - hasPosition && pair ? ( - - ) : ( - - - - You don’t have liquidity in this pool yet. - - - - Add liquidity. - - - - - ) - ) : validPairNoLiquidity ? ( + {hasPosition && ( + + + Pool found! + + + + Manage this pool. + + + + )} + + {currency0 && currency1 ? ( + pairState === PairState.EXISTS ? ( + hasPosition && pair ? ( + + ) : ( - No pool found. + You don’t have liquidity in this pool yet. - Create pool. + + Add liquidity. + - ) : pairState === PairState.INVALID ? ( - - - - Invalid pair. - - - - ) : pairState === PairState.LOADING ? ( - - - - Loading - - - - - ) : null - ) : ( - prerequisiteMessage - )} - - - - - - - + ) + ) : validPairNoLiquidity ? ( + + + + No pool found. + + + Create pool. + + + + ) : pairState === PairState.INVALID ? ( + + + + Invalid pair. + + + + ) : pairState === PairState.LOADING ? ( + + + + Loading + + + + + ) : null + ) : ( + prerequisiteMessage + )} + + + + + + ) } diff --git a/src/pages/RemoveLiquidity/V3.tsx b/src/pages/RemoveLiquidity/V3.tsx index 6021f524390..8c2eceec266 100644 --- a/src/pages/RemoveLiquidity/V3.tsx +++ b/src/pages/RemoveLiquidity/V3.tsx @@ -1,11 +1,9 @@ import { BigNumber } from '@ethersproject/bignumber' import type { TransactionResponse } from '@ethersproject/providers' import { Trans } from '@lingui/macro' -import { LiquidityEventName, LiquiditySource } from '@uniswap/analytics-events' import { CurrencyAmount, Percent } from '@uniswap/sdk-core' import { NonfungiblePositionManager } from '@uniswap/v3-sdk' import { useWeb3React } from '@web3-react/core' -import { sendAnalyticsEvent, useTrace } from 'analytics' import RangeBadge from 'components/Badge/RangeBadge' import { ButtonConfirmed, ButtonPrimary } from 'components/Button' import { LightCard } from 'components/Card' @@ -73,7 +71,6 @@ function Remove({ tokenId }: { tokenId: BigNumber }) { const { position } = useV3PositionFromTokenId(tokenId) const theme = useTheme() const { account, chainId, provider } = useWeb3React() - const trace = useTrace() // flag for receiving WETH const [receiveWETH, setReceiveWETH] = useState(false) @@ -159,11 +156,6 @@ function Remove({ tokenId }: { tokenId: BigNumber }) { .getSigner() .sendTransaction(newTxn) .then((response: TransactionResponse) => { - sendAnalyticsEvent(LiquidityEventName.REMOVE_LIQUIDITY_SUBMITTED, { - source: LiquiditySource.V3, - label: [liquidityValue0.currency.symbol, liquidityValue1.currency.symbol].join('/'), - ...trace, - }) setTxnHash(response.hash) setAttemptingTxn(false) addTransaction(response, { @@ -193,7 +185,6 @@ function Remove({ tokenId }: { tokenId: BigNumber }) { allowedSlippage, feeValue0, feeValue1, - trace, addTransaction, ]) diff --git a/src/pages/RemoveLiquidity/index.tsx b/src/pages/RemoveLiquidity/index.tsx index 9098529c20a..6afc05285a4 100644 --- a/src/pages/RemoveLiquidity/index.tsx +++ b/src/pages/RemoveLiquidity/index.tsx @@ -2,10 +2,8 @@ import { BigNumber } from '@ethersproject/bignumber' import { Contract } from '@ethersproject/contracts' import type { TransactionResponse } from '@ethersproject/providers' import { Trans } from '@lingui/macro' -import { BrowserEvent, InterfaceElementName, InterfaceEventName, LiquidityEventName } from '@uniswap/analytics-events' import { Currency, Percent } from '@uniswap/sdk-core' import { useWeb3React } from '@web3-react/core' -import { sendAnalyticsEvent, TraceEvent, useTrace } from 'analytics' import { useToggleAccountDrawer } from 'components/AccountDrawer' import { V2Unsupported } from 'components/V2Unsupported' import { isSupportedChain } from 'constants/chains' @@ -69,7 +67,6 @@ function RemoveLiquidity() { const [tokenA, tokenB] = useMemo(() => [currencyA?.wrapped, currencyB?.wrapped], [currencyA, currencyB]) const theme = useTheme() - const trace = useTrace() // toggle wallet when disconnected const toggleWalletDrawer = useToggleAccountDrawer() @@ -292,11 +289,6 @@ function RemoveLiquidity() { }) setTxHash(response.hash) - - sendAnalyticsEvent(LiquidityEventName.REMOVE_LIQUIDITY_SUBMITTED, { - label: [currencyA.symbol, currencyB.symbol].join('/'), - ...trace, - }) }) .catch((error: Error) => { setAttemptingTxn(false) @@ -644,16 +636,9 @@ function RemoveLiquidity() { )}
{!account ? ( - - - Connect wallet - - + + Connect wallet + ) : ( { const { trade: { trade }, - allowedSlippage, } = props.swapInfo const userDisabledUniswapX = useUserDisabledUniswapX() const isOnClassic = Boolean(trade && isClassicTrade(trade) && trade.isUniswapXBetter && !userDisabledUniswapX) @@ -45,15 +42,7 @@ export const UniswapXOptIn = (props: { swapInfo: SwapInfo; isSmall: boolean }) = return null } - return ( - - - - ) + return } const OptInContents = ({ @@ -67,7 +56,6 @@ const OptInContents = ({ }) => { const { trade: { trade }, - allowedSlippage, } = swapInfo const [, setRouterPreference] = useRouterPreference() const dispatch = useAppDispatch() @@ -99,10 +87,6 @@ const OptInContents = ({ }, 200) if (!trade) return - sendAnalyticsEvent('UniswapX Opt In Toggled', { - ...formatCommonPropertiesForTrade(trade, allowedSlippage), - new_preference: RouterPreference.X, - }) setRouterPreference(RouterPreference.X) }} style={{ @@ -143,10 +127,6 @@ const OptInContents = ({ size={18} onClick={() => { if (!trade) return - sendAnalyticsEvent('UniswapX Opt In Toggled', { - ...formatCommonPropertiesForTrade(trade, allowedSlippage), - new_preference: RouterPreference.API, - }) setRouterPreference(RouterPreference.API) dispatch(updateDisabledUniswapX({ disabledUniswapX: true })) }} diff --git a/src/pages/Swap/index.tsx b/src/pages/Swap/index.tsx index 213986b1537..da8647cabd0 100644 --- a/src/pages/Swap/index.tsx +++ b/src/pages/Swap/index.tsx @@ -1,17 +1,7 @@ import { Trans } from '@lingui/macro' -import { - BrowserEvent, - InterfaceElementName, - InterfaceEventName, - InterfacePageName, - InterfaceSectionName, - SharedEventName, - SwapEventName, -} from '@uniswap/analytics-events' import { ChainId, Currency, CurrencyAmount, Percent, Token } from '@uniswap/sdk-core' import { UNIVERSAL_ROUTER_ADDRESS } from '@uniswap/universal-router-sdk' import { useWeb3React } from '@web3-react/core' -import { sendAnalyticsEvent, Trace, TraceEvent, useTrace } from 'analytics' import { useToggleAccountDrawer } from 'components/AccountDrawer' import AddressInputPanel from 'components/AddressInputPanel' import { ButtonError, ButtonLight, ButtonPrimary } from 'components/Button' @@ -44,7 +34,6 @@ import { useSwitchChain } from 'hooks/useSwitchChain' import { useUSDPrice } from 'hooks/useUSDPrice' import useWrapCallback, { WrapErrorText, WrapType } from 'hooks/useWrapCallback' import JSBI from 'jsbi' -import { formatSwapQuoteReceivedEventProperties } from 'lib/utils/analytics' import { ReactNode, useCallback, useEffect, useMemo, useReducer, useRef, useState } from 'react' import { ArrowDown } from 'react-feather' import { useLocation, useNavigate } from 'react-router-dom' @@ -57,7 +46,6 @@ import { useDefaultsFromURLSearch, useDerivedSwapInfo, useSwapActionHandlers } f import swapReducer, { initialState as initialSwapState, SwapState } from 'state/swap/reducer' import styled, { useTheme } from 'styled-components' import { LinkStyledButton, ThemedText } from 'theme/components' -import { maybeLogFirstSwapAction } from 'tracing/swapFlowLoggers' import { computeFiatValuePriceImpact } from 'utils/computeFiatValuePriceImpact' import { NumberType, useFormatter } from 'utils/formatNumbers' import { maxAmountSpend } from 'utils/maxAmountSpend' @@ -150,7 +138,7 @@ export default function SwapPage({ className }: { className?: string }) { const supportedChainId = asSupportedChain(connectedChainId) return ( - + <> {location.pathname === '/swap' && } - + ) } @@ -190,7 +178,6 @@ export function Swap({ }) { const connectionReady = useConnectionReady() const { account, chainId: connectedChainId, connector } = useWeb3React() - const trace = useTrace() // token warning stuff const prefilledInputCurrency = useCurrency(initialInputCurrencyId) @@ -372,16 +359,14 @@ export function Swap({ const handleTypeInput = useCallback( (value: string) => { onUserInput(Field.INPUT, value) - maybeLogFirstSwapAction(trace) }, - [onUserInput, trace] + [onUserInput] ) const handleTypeOutput = useCallback( (value: string) => { onUserInput(Field.OUTPUT, value) - maybeLogFirstSwapAction(trace) }, - [onUserInput, trace] + [onUserInput] ) const navigate = useNavigate() @@ -504,13 +489,6 @@ export function Swap({ })) onUserInput(Field.INPUT, '') } catch (error) { - if (!didUserReject(error)) { - sendAnalyticsEvent(SwapEventName.SWAP_ERROR, { - wrapType, - input: currencies[Field.INPUT], - output: currencies[Field.OUTPUT], - }) - } console.error('Could not wrap/unwrap', error) setSwapState((currentState) => ({ ...currentState, @@ -518,7 +496,7 @@ export function Swap({ txHash: undefined, })) } - }, [currencies, onUserInput, onWrap, wrapType]) + }, [onUserInput, onWrap]) // warnings on the greater of fiat value price impact and execution price impact const { priceImpactSeverity, largerPriceImpact } = useMemo(() => { @@ -552,16 +530,14 @@ export function Swap({ }, [Field.OUTPUT]: state[Field.OUTPUT], }) - maybeLogFirstSwapAction(trace) }, - [onCurrencyChange, onCurrencySelection, state, trace] + [onCurrencyChange, onCurrencySelection, state] ) const inputCurrencyNumericalInputRef = useRef(null) const handleMaxInput = useCallback(() => { maxInputAmount && onUserInput(Field.INPUT, maxInputAmount.toExact()) - maybeLogFirstSwapAction(trace) - }, [maxInputAmount, onUserInput, trace]) + }, [maxInputAmount, onUserInput]) const handleOutputSelect = useCallback( (outputCurrency: Currency) => { @@ -572,9 +548,8 @@ export function Swap({ currencyId: getSwapCurrencyId(outputCurrency), }, }) - maybeLogFirstSwapAction(trace) }, - [onCurrencyChange, onCurrencySelection, state, trace] + [onCurrencyChange, onCurrencySelection, state] ) const showPriceImpactWarning = isClassicTrade(trade) && largerPriceImpact && priceImpactSeverity > 3 @@ -582,12 +557,7 @@ export function Swap({ const prevTrade = usePrevious(trade) useEffect(() => { if (!trade || prevTrade === trade) return // no new swap quote to log - - sendAnalyticsEvent(SwapEventName.SWAP_QUOTE_RECEIVED, { - ...formatSwapQuoteReceivedEventProperties(trade, allowedSlippage, swapQuoteLatency, inputTax, outputTax), - ...trace, - }) - }, [prevTrade, trade, trace, allowedSlippage, swapQuoteLatency, inputTax, outputTax]) + }, [prevTrade, trade, allowedSlippage, swapQuoteLatency, inputTax, outputTax]) const showDetailsDropdown = Boolean( !showWrap && userHasSpecifiedInputOutput && (trade || routeIsLoading || routeIsSyncing) @@ -642,73 +612,60 @@ export function Swap({
- - You pay} - disabled={disableTokenInputs} - value={formattedAmounts[Field.INPUT]} - showMaxButton={showMaxButton} - currency={currencies[Field.INPUT] ?? null} - onUserInput={handleTypeInput} - onMax={handleMaxInput} - fiatValue={showFiatValueInput ? fiatValueInput : undefined} - onCurrencySelect={handleInputSelect} - otherCurrency={currencies[Field.OUTPUT]} - showCommonBases - id={InterfaceSectionName.CURRENCY_INPUT_PANEL} - loading={independentField === Field.OUTPUT && routeIsSyncing} - ref={inputCurrencyNumericalInputRef} - /> - + You pay} + disabled={disableTokenInputs} + value={formattedAmounts[Field.INPUT]} + showMaxButton={showMaxButton} + currency={currencies[Field.INPUT] ?? null} + onUserInput={handleTypeInput} + onMax={handleMaxInput} + fiatValue={showFiatValueInput ? fiatValueInput : undefined} + onCurrencySelect={handleInputSelect} + otherCurrency={currencies[Field.OUTPUT]} + showCommonBases + loading={independentField === Field.OUTPUT && routeIsSyncing} + ref={inputCurrencyNumericalInputRef} + /> - { + if (disableTokenInputs) return + onSwitchTokens(inputTokenHasTax, formattedAmounts[dependentField]) + }} + color={theme.neutral1} > - { - if (disableTokenInputs) return - onSwitchTokens(inputTokenHasTax, formattedAmounts[dependentField]) - maybeLogFirstSwapAction(trace) - }} - color={theme.neutral1} - > - - - + +
- - You receive} - showMaxButton={false} - hideBalance={false} - fiatValue={showFiatValueOutput ? fiatValueOutput : undefined} - priceImpact={stablecoinPriceImpact} - currency={currencies[Field.OUTPUT] ?? null} - onCurrencySelect={handleOutputSelect} - otherCurrency={currencies[Field.INPUT]} - showCommonBases - id={InterfaceSectionName.CURRENCY_OUTPUT_PANEL} - loading={independentField === Field.INPUT && routeIsSyncing} - numericalInputSettings={{ - // We disable numerical input here if the selected token has tax, since we cannot guarantee exact_outputs for FOT tokens - disabled: outputTokenHasTax, - // Focus the input currency panel if the user tries to type into the disabled output currency panel - onDisabledClick: () => inputCurrencyNumericalInputRef.current?.focus(), - disabledTooltipBody: , - }} - /> - + You receive} + showMaxButton={false} + hideBalance={false} + fiatValue={showFiatValueOutput ? fiatValueOutput : undefined} + priceImpact={stablecoinPriceImpact} + currency={currencies[Field.OUTPUT] ?? null} + onCurrencySelect={handleOutputSelect} + otherCurrency={currencies[Field.INPUT]} + showCommonBases + loading={independentField === Field.INPUT && routeIsSyncing} + numericalInputSettings={{ + // We disable numerical input here if the selected token has tax, since we cannot guarantee exact_outputs for FOT tokens + disabled: outputTokenHasTax, + // Focus the input currency panel if the user tries to type into the disabled output currency panel + onDisabledClick: () => inputCurrencyNumericalInputRef.current?.focus(), + disabledTooltipBody: , + }} + /> {recipient !== null && !showWrap ? ( <> @@ -745,16 +702,9 @@ export function Swap({ Connecting to {getChainInfo(switchingChain)?.label} ) : connectionReady && !account ? ( - - - Connect wallet - - + + Connect wallet + ) : chainId && chainId !== connectedChainId ? ( ) : ( - { + showPriceImpactWarning ? setShowPriceImpactModal(true) : handleContinueToReview() + }} + id="swap-button" + data-testid="swap-button" + disabled={!getIsReviewableQuote(trade, tradeState, swapInputError)} + error={!swapInputError && priceImpactSeverity > 2 && allowance.state === AllowanceState.ALLOWED} > - { - showPriceImpactWarning ? setShowPriceImpactModal(true) : handleContinueToReview() - }} - id="swap-button" - data-testid="swap-button" - disabled={!getIsReviewableQuote(trade, tradeState, swapInputError)} - error={!swapInputError && priceImpactSeverity > 2 && allowance.state === AllowanceState.ALLOWED} - > - - {swapInputError ? ( - swapInputError - ) : routeIsSyncing || routeIsLoading ? ( - Swap - ) : priceImpactSeverity > 2 ? ( - Swap anyway - ) : ( - Swap - )} - - - + + {swapInputError ? ( + swapInputError + ) : routeIsSyncing || routeIsLoading ? ( + Swap + ) : priceImpactSeverity > 2 ? ( + Swap anyway + ) : ( + Swap + )} + + )}
diff --git a/src/pages/Tokens/index.tsx b/src/pages/Tokens/index.tsx index 91496edbf5c..6465e64babc 100644 --- a/src/pages/Tokens/index.tsx +++ b/src/pages/Tokens/index.tsx @@ -1,6 +1,4 @@ import { Trans } from '@lingui/macro' -import { InterfacePageName } from '@uniswap/analytics-events' -import { Trace } from 'analytics' import { MAX_WIDTH_MEDIA_BREAKPOINT, MEDIUM_MEDIA_BREAKPOINT } from 'components/Tokens/constants' import { filterStringAtom } from 'components/Tokens/state' import NetworkFilter from 'components/Tokens/TokenTable/NetworkFilter' @@ -75,30 +73,28 @@ const Tokens = () => { }, [location, resetFilterString]) return ( - - - - This table contains the top tokens by Uniswap volume, sorted based on your input.} - placement="bottom" - > - - Top tokens on Uniswap - - - - - - - - - - - - - - - + + + This table contains the top tokens by Uniswap volume, sorted based on your input.} + placement="bottom" + > + + Top tokens on Uniswap + + + + + + + + + + + + + + ) } diff --git a/src/pages/Vote/Landing.tsx b/src/pages/Vote/Landing.tsx index f41ed5e4c43..df4ffa05c1d 100644 --- a/src/pages/Vote/Landing.tsx +++ b/src/pages/Vote/Landing.tsx @@ -1,8 +1,6 @@ import { Trans } from '@lingui/macro' -import { InterfacePageName } from '@uniswap/analytics-events' import { CurrencyAmount, Token } from '@uniswap/sdk-core' import { useWeb3React } from '@web3-react/core' -import { Trace } from 'analytics' import { ButtonPrimary } from 'components/Button' import { AutoColumn } from 'components/Column' import { CardBGImage, CardNoise, CardSection, DataCard } from 'components/earn/styled' @@ -145,159 +143,154 @@ export default function Landing() { ) return ( <> - - - Unlock votes : Update delegation} - /> - - - - - - - - - Uniswap governance - - - - - - UNI tokens represent voting shares in Uniswap governance. You can vote on each proposal yourself - or delegate your votes to a third party. - - - - - - Read more about Uniswap governance - - - - - - - - - - - - Proposals - - - {loadingProposals || loadingAvailableVotes ? : null} - {showUnlockVoting ? ( - - Unlock voting - - ) : availableVotes && JSBI.notEqual(JSBI.BigInt(0), availableVotes?.quotient) ? ( - - - Votes - - - ) : uniBalance && - userDelegatee && - userDelegatee !== ZERO_ADDRESS && - JSBI.notEqual(JSBI.BigInt(0), uniBalance?.quotient) ? ( - + + Unlock votes : Update delegation} + /> + + + + + + + + + Uniswap governance + + + + - Votes + UNI tokens represent voting shares in Uniswap governance. You can vote on each proposal yourself + or delegate your votes to a third party. - - ) : ( - '' - )} + +
+ + + Read more about Uniswap governance + + + + + + + + + + + + Proposals + + + {loadingProposals || loadingAvailableVotes ? : null} + {showUnlockVoting ? ( - Create proposal + Unlock voting - - - {!showUnlockVoting && ( - -
- {userDelegatee && userDelegatee !== ZERO_ADDRESS ? ( - - - Delegated to: - - - - {userDelegatee === account ? Self : shortenAddress(userDelegatee)} - - - (edit) - - - - ) : ( - '' - )} - - )} + ) : availableVotes && JSBI.notEqual(JSBI.BigInt(0), availableVotes?.quotient) ? ( + + + Votes + + + ) : uniBalance && + userDelegatee && + userDelegatee !== ZERO_ADDRESS && + JSBI.notEqual(JSBI.BigInt(0), uniBalance?.quotient) ? ( + + + Votes + + + ) : ( + '' + )} + + Create proposal + + + + {!showUnlockVoting && ( + +
+ {userDelegatee && userDelegatee !== ZERO_ADDRESS ? ( + + + Delegated to: + + + + {userDelegatee === account ? Self : shortenAddress(userDelegatee)} + + + (edit) + + + + ) : ( + '' + )} + + )} - {allProposals?.length === 0 && } + {allProposals?.length === 0 && } - {allProposals?.length > 0 && ( - - - - - Show cancelled - - setHideCancelled((hideCancelled) => !hideCancelled)} - /> - - - )} + {allProposals?.length > 0 && ( + + + + + Show cancelled + + setHideCancelled((hideCancelled) => !hideCancelled)} /> + + + )} - {allProposals - ?.slice(0) - ?.reverse() - ?.filter((p: ProposalData) => (hideCancelled ? p.status !== ProposalState.CANCELED : true)) - ?.map((p: ProposalData) => { - return ( - - - {p.governorIndex}.{p.id} - - {p.title} - - - ) - })} - + {allProposals + ?.slice(0) + ?.reverse() + ?.filter((p: ProposalData) => (hideCancelled ? p.status !== ProposalState.CANCELED : true)) + ?.map((p: ProposalData) => { + return ( + + + {p.governorIndex}.{p.id} + + {p.title} + + + ) + })} + - - A minimum threshold of 0.25% of the total UNI supply is required to submit proposals - - - + + A minimum threshold of 0.25% of the total UNI supply is required to submit proposals + + ) diff --git a/src/pages/Vote/VotePage.tsx b/src/pages/Vote/VotePage.tsx index c59f3ad5d8e..e890535fbde 100644 --- a/src/pages/Vote/VotePage.tsx +++ b/src/pages/Vote/VotePage.tsx @@ -1,9 +1,7 @@ import { BigNumber } from '@ethersproject/bignumber' import { Trans } from '@lingui/macro' -import { InterfacePageName } from '@uniswap/analytics-events' import { CurrencyAmount, Fraction, Token } from '@uniswap/sdk-core' import { useWeb3React } from '@web3-react/core' -import { Trace } from 'analytics' import ExecuteModal from 'components/vote/ExecuteModal' import QueueModal from 'components/vote/QueueModal' import { useActiveLocale } from 'hooks/useActiveLocale' @@ -271,239 +269,233 @@ export default function VotePage() { } return ( - - <> - - - Unlock votes} - /> - - - - - - - All Proposals - - - {proposalData && } + <> + + + Unlock votes} /> + + + + + + + All Proposals + + + {proposalData && } + + + + {proposalData?.title} + + + + {startDate && startDate > now ? ( + Voting starts approximately {startDate.toLocaleString(locale, dateFormat)} + ) : null} + - - - {proposalData?.title} - - - - {startDate && startDate > now ? ( - Voting starts approximately {startDate.toLocaleString(locale, dateFormat)} - ) : null} - - - - - {endDate && - (endDate < now ? ( - Voting ended {endDate.toLocaleString(locale, dateFormat)} - ) : ( - Voting ends approximately {endDate.toLocaleString(locale, dateFormat)} - ))} - - - {proposalData && proposalData.status === ProposalState.ACTIVE && !showVotingButtons && ( - + + + {endDate && + (endDate < now ? ( + Voting ended {endDate.toLocaleString(locale, dateFormat)} + ) : ( + Voting ends approximately {endDate.toLocaleString(locale, dateFormat)} + ))} + + + {proposalData && proposalData.status === ProposalState.ACTIVE && !showVotingButtons && ( + + + + Only UNI votes that were self delegated or delegated to another address before block{' '} + {proposalData.startBlock} are eligible for voting. + {' '} + {showLinkForUnlock && ( + + + Unlock voting to prepare for the next + proposal. + + + )} + + + )} + + {showVotingButtons && ( + + { + setVoteOption(VoteOption.For) + toggleVoteModal() + }} + > + Vote for + + { + setVoteOption(VoteOption.Against) + toggleVoteModal() + }} + > + Vote against + + + )} + {showQueueButton && ( + + { + toggleQueueModal() + }} + > + Queue + + + )} + {showExecuteButton && ( + <> + {eta && ( + - - Only UNI votes that were self delegated or delegated to another address before block{' '} - {proposalData.startBlock} are eligible for voting. - {' '} - {showLinkForUnlock && ( - - - Unlock voting to prepare for the next - proposal. - - - )} + This proposal may be executed after {eta.toLocaleString(locale, dateFormat)}. - + )} - - {showVotingButtons && ( - - { - setVoteOption(VoteOption.For) - toggleVoteModal() - }} - > - Vote for - - { - setVoteOption(VoteOption.Against) - toggleVoteModal() - }} - > - Vote against - - - )} - {showQueueButton && ( { - toggleQueueModal() + toggleExecuteModal() }} + // can't execute until the eta has arrived + disabled={!currentTimestamp || !proposalData?.eta || currentTimestamp.lt(proposalData.eta)} > - Queue + Execute - )} - {showExecuteButton && ( - <> - {eta && ( - - - This proposal may be executed after {eta.toLocaleString(locale, dateFormat)}. + + )} + + + + + + + For - - )} - - { - toggleExecuteModal() - }} - // can't execute until the eta has arrived - disabled={!currentTimestamp || !proposalData?.eta || currentTimestamp.lt(proposalData.eta)} - > - Execute - - - - )} - - - - - + {proposalData && ( - For + {proposalData.forCount.toFixed(0, { groupSeparator: ',' })} + {quorumAmount && ( + {` / ${quorumAmount.toExact({ + groupSeparator: ',', + })}`} + )} - {proposalData && ( - - {proposalData.forCount.toFixed(0, { groupSeparator: ',' })} - {quorumAmount && ( - {` / ${quorumAmount.toExact({ - groupSeparator: ',', - })}`} - )} - - )} - - - - - - - - - - - + )} + + + + + + + + + + + + + Against + + {proposalData && ( - Against + {proposalData.againstCount.toFixed(0, { groupSeparator: ',' })} - {proposalData && ( - - {proposalData.againstCount.toFixed(0, { groupSeparator: ',' })} - - )} - - - - - - - - - - - Details - - {proposalData?.details?.map((d, i) => { - return ( - - {i + 1}: {linkIfAddress(d.target)}.{d.functionSig}( - {d.callData.split(',').map((content, i) => { - return ( - - {linkIfAddress(content)} - {d.callData.split(',').length - 1 === i ? '' : ','} - - ) - })} + )} + + + + + + + + + + + Details + + {proposalData?.details?.map((d, i) => { + return ( + + {i + 1}: {linkIfAddress(d.target)}.{d.functionSig}( + {d.callData.split(',').map((content, i) => { + return ( + + {linkIfAddress(content)} + {d.callData.split(',').length - 1 === i ? '' : ','} + ) - - ) - })} - - - - Description - - - - - - - - Proposer - - - - - - - - - - + })} + ) + + ) + })} + + + + Description + + + + + + + + Proposer + + + + + + + + + ) } diff --git a/src/state/application/hooks.ts b/src/state/application/hooks.ts index a4123bfbddd..53fb5be273b 100644 --- a/src/state/application/hooks.ts +++ b/src/state/application/hooks.ts @@ -1,5 +1,3 @@ -import { MoonpayEventName } from '@uniswap/analytics-events' -import { sendAnalyticsEvent } from 'analytics' import { DEFAULT_TXN_DISMISS_MS } from 'constants/misc' import { useCallback, useEffect, useMemo, useState } from 'react' import { useAppDispatch, useAppSelector } from 'state/hooks' @@ -53,7 +51,6 @@ export function useFiatOnrampAvailability(shouldCheck: boolean, callback?: () => setLoading(true) try { const result = await getMoonpayAvailability() - sendAnalyticsEvent(MoonpayEventName.MOONPAY_GEOCHECK_COMPLETED, { success: result }) if (stale) return dispatch(setFiatOnrampAvailability(result)) if (result && callback) { @@ -142,10 +139,6 @@ export function useToggleExecuteModal(): () => void { return useToggleModal(ApplicationModal.EXECUTE) } -export function useTogglePrivacyPolicy(): () => void { - return useToggleModal(ApplicationModal.PRIVACY_POLICY) -} - export function useToggleFeatureFlags(): () => void { return useToggleModal(ApplicationModal.FEATURE_FLAGS) } diff --git a/src/state/routing/quickRouteSlice.ts b/src/state/routing/quickRouteSlice.ts index c1cc173b34c..d143ba5e491 100644 --- a/src/state/routing/quickRouteSlice.ts +++ b/src/state/routing/quickRouteSlice.ts @@ -1,10 +1,8 @@ import { createApi, fetchBaseQuery, FetchBaseQueryError } from '@reduxjs/toolkit/query/react' -import { sendAnalyticsEvent } from 'analytics' import ms from 'ms' -import { logSwapQuoteRequest } from 'tracing/swapFlowLoggers' import { trace } from 'tracing/trace' -import { GetQuickQuoteArgs, PreviewTradeResult, QuickRouteResponse, QuoteState, RouterPreference } from './types' +import { GetQuickQuoteArgs, PreviewTradeResult, QuickRouteResponse, QuoteState } from './types' import { isExactInput, transformQuickRouteToTrade } from './utils' const UNISWAP_API_URL = process.env.REACT_APP_UNISWAP_API_URL @@ -50,7 +48,6 @@ export const quickRouteApi = createApi({ ) }, async queryFn(args, _api, _extraOptions, fetch) { - logSwapQuoteRequest(args.tokenInChainId, RouterPreference.API, true) const quoteStartMark = performance.mark(`quickroute-fetch-start-${Date.now()}`) const { tokenInAddress, tokenInChainId, tokenOutAddress, tokenOutChainId, amount, tradeType } = args const type = isExactInput(tradeType) ? 'EXACT_IN' : 'EXACT_OUT' diff --git a/src/state/routing/slice.ts b/src/state/routing/slice.ts index edcb3136000..81825e1f418 100644 --- a/src/state/routing/slice.ts +++ b/src/state/routing/slice.ts @@ -1,10 +1,8 @@ import { createApi, fetchBaseQuery, FetchBaseQueryError } from '@reduxjs/toolkit/query/react' import { Protocol } from '@uniswap/router-sdk' import { TradeType } from '@uniswap/sdk-core' -import { sendAnalyticsEvent } from 'analytics' import { isUniswapXSupportedChain } from 'constants/chains' import ms from 'ms' -import { logSwapQuoteRequest } from 'tracing/swapFlowLoggers' import { trace } from 'tracing/trace' import { @@ -122,7 +120,6 @@ export const routingApi = createApi({ }, async queryFn(args, _api, _extraOptions, fetch) { let fellBack = false - logSwapQuoteRequest(args.tokenInChainId, args.routerPreference, false) const quoteStartMark = performance.mark(`quote-fetch-start-${Date.now()}`) if (shouldUseAPIRouter(args)) { fellBack = true @@ -156,11 +153,6 @@ export const routingApi = createApi({ typeof errorData === 'object' && (errorData?.errorCode === 'NO_ROUTE' || errorData?.detail === 'No quotes available') ) { - sendAnalyticsEvent('No quote received from routing API', { - requestBody, - response, - routerPreference: args.routerPreference, - }) return { data: { state: QuoteState.NOT_FOUND, latencyMs: getQuoteLatencyMeasure(quoteStartMark).duration }, } diff --git a/src/state/transactions/updater.tsx b/src/state/transactions/updater.tsx index a156aa4d9a1..4389ddff80d 100644 --- a/src/state/transactions/updater.tsx +++ b/src/state/transactions/updater.tsx @@ -1,18 +1,16 @@ import { TransactionReceipt } from '@ethersproject/abstract-provider' import { useWeb3React } from '@web3-react/core' -import { useTrace } from 'analytics' import { DEFAULT_TXN_DISMISS_MS, L2_TXN_DISMISS_MS } from 'constants/misc' import LibUpdater from 'lib/hooks/transactions/updater' import { useCallback, useMemo } from 'react' import { PopupType } from 'state/application/reducer' import { useAppDispatch, useAppSelector } from 'state/hooks' -import { logSwapSuccess } from 'tracing/swapFlowLoggers' import { L2_CHAIN_IDS } from '../../constants/chains' import { useAddPopup } from '../application/hooks' import { isPendingTx } from './hooks' import { checkedTransaction, finalizeTransaction } from './reducer' -import { SerializableTransactionReceipt, TransactionDetails, TransactionType } from './types' +import { SerializableTransactionReceipt, TransactionDetails } from './types' export function toSerializableReceipt(receipt: TransactionReceipt): SerializableTransactionReceipt { return { @@ -28,7 +26,6 @@ export function toSerializableReceipt(receipt: TransactionReceipt): Serializable } export default function Updater() { - const analyticsContext = useTrace() const { chainId } = useWeb3React() const addPopup = useAddPopup() // speed up popup dismisall time if on L2 @@ -58,10 +55,6 @@ export default function Updater() { }) ) - if (pendingTransactions[hash] && pendingTransactions[hash].info?.type === TransactionType.SWAP) { - logSwapSuccess(hash, chainId, analyticsContext) - } - addPopup( { type: PopupType.Transaction, @@ -71,7 +64,7 @@ export default function Updater() { isL2 ? L2_TXN_DISMISS_MS : DEFAULT_TXN_DISMISS_MS ) }, - [addPopup, analyticsContext, dispatch, isL2, pendingTransactions] + [addPopup, dispatch, isL2] ) return diff --git a/src/theme/components/index.tsx b/src/theme/components/index.tsx index 0323f45380d..c5125b7b55a 100644 --- a/src/theme/components/index.tsx +++ b/src/theme/components/index.tsx @@ -1,5 +1,4 @@ import { Trans } from '@lingui/macro' -import { outboundLink } from 'components/analytics' import { MOBILE_MEDIA_BREAKPOINT } from 'components/Tokens/constants' import useCopyClipboard from 'hooks/useCopyClipboard' import React, { @@ -18,7 +17,6 @@ import styled, { css, keyframes } from 'styled-components' import { Z_INDEX } from 'theme/zIndex' import { ReactComponent as TooltipTriangle } from '../../assets/svg/tooltip_triangle.svg' -import { anonymizeLink } from '../../utils/anonymizeLink' // TODO: Break this file into a components folder @@ -135,17 +133,11 @@ export const UniTokenAnimated = styled.img` ` function handleClickExternalLink(event: React.MouseEvent) { - const { target, href } = event.currentTarget - - const anonymizedHref = anonymizeLink(href) + const { target } = event.currentTarget // don't prevent default, don't redirect if it's a new tab - if (target === '_blank' || event.ctrlKey || event.metaKey) { - outboundLink({ label: anonymizedHref }) - } else { + if (!(target === '_blank' || event.ctrlKey || event.metaKey)) { event.preventDefault() - // send a ReactGA event and then trigger a location change - outboundLink({ label: anonymizedHref }) } } diff --git a/src/tracing/index.ts b/src/tracing/index.ts index d37c0d20f2b..8de3c61ada0 100644 --- a/src/tracing/index.ts +++ b/src/tracing/index.ts @@ -1,10 +1,6 @@ import * as Sentry from '@sentry/react' import { BrowserTracing } from '@sentry/tracing' -import { SharedEventName } from '@uniswap/analytics-events' -import { initializeAnalytics, OriginApplication } from 'analytics' -import store from 'state' -import { setOriginCountry } from 'state/user/reducer' -import { isDevelopmentEnv, isProductionEnv, isSentryEnabled } from 'utils/env' +import { isSentryEnabled } from 'utils/env' import { getEnvName } from 'utils/env' import { v4 as uuidv4 } from 'uuid' @@ -17,7 +13,6 @@ window.GIT_COMMIT_HASH = process.env.REACT_APP_GIT_COMMIT_HASH const SENTRY_USER_ID_KEY = 'sentry-user-id' // Actual KEYs are set by proxy servers. -const AMPLITUDE_DUMMY_KEY = '00000000000000000000000000000000' export const STATSIG_DUMMY_KEY = 'client-0000000000000000000000000000000000000000000' Sentry.init({ @@ -40,12 +35,3 @@ if (!sentryUserId) { localStorage.setItem(SENTRY_USER_ID_KEY, (sentryUserId = uuidv4())) } Sentry.setUser({ id: sentryUserId }) - -initializeAnalytics(AMPLITUDE_DUMMY_KEY, OriginApplication.INTERFACE, { - proxyUrl: process.env.REACT_APP_AMPLITUDE_PROXY_URL, - defaultEventName: SharedEventName.PAGE_VIEWED, - commitHash: process.env.REACT_APP_GIT_COMMIT_HASH, - isProductionEnv: isProductionEnv(), - debug: isDevelopmentEnv(), - reportOriginCountry: (country: string) => store.dispatch(setOriginCountry(country)), -}) diff --git a/src/tracing/swapFlowLoggers.test.ts b/src/tracing/swapFlowLoggers.test.ts deleted file mode 100644 index e8167d6c522..00000000000 --- a/src/tracing/swapFlowLoggers.test.ts +++ /dev/null @@ -1,82 +0,0 @@ -import { SwapEventName } from '@uniswap/analytics-events' -import { sendAnalyticsEvent } from 'analytics' - -jest.mock('analytics', () => ({ - sendAnalyticsEvent: jest.fn(), -})) - -jest.mock('./SwapEventTimestampTracker', () => ({ - SwapEventType: { - FIRST_SWAP_ACTION: 'FIRST_SWAP_ACTION', - FIRST_QUOTE_FETCH_STARTED: 'FIRST_QUOTE_FETCH_STARTED', - FIRST_SWAP_SIGNATURE_REQUESTED: 'FIRST_SWAP_SIGNATURE_REQUESTED', - FIRST_SWAP_SIGNATURE_COMPLETED: 'FIRST_SWAP_SIGNATURE_COMPLETED', - FIRST_SWAP_SUCCESS: 'FIRST_SWAP_SUCCESS', - }, - timestampTracker: { - hasTimestamp: () => false, - setElapsedTime: () => 100, - getElapsedTime: () => 100, - }, -})) - -import { INTERNAL_ROUTER_PREFERENCE_PRICE, RouterPreference } from 'state/routing/types' - -import { logSwapQuoteRequest, logSwapSuccess, maybeLogFirstSwapAction } from './swapFlowLoggers' - -describe('swapFlowLoggers', () => { - beforeEach(() => { - jest.clearAllMocks() - }) - - it('logSwapSuccess calls sendAnalyticsEvent with correct parameters', () => { - const mockHash = 'mockHash' - const mockChainId = 1 - const mockAnalyticsContext = { page: 'mockContext' } - - logSwapSuccess(mockHash, mockChainId, mockAnalyticsContext) - - expect(sendAnalyticsEvent).toHaveBeenCalledWith(SwapEventName.SWAP_TRANSACTION_COMPLETED, { - time_to_swap: 100, - time_to_swap_since_first_input: 100, - hash: mockHash, - chainId: mockChainId, - ...mockAnalyticsContext, - }) - }) - - it('maybeLogFirstSwapAction calls sendAnalyticsEvent with correct parameters', () => { - const mockAnalyticsContext = { page: 'mockContext' } - - maybeLogFirstSwapAction(mockAnalyticsContext) - - expect(sendAnalyticsEvent).toHaveBeenCalledWith(SwapEventName.SWAP_FIRST_ACTION, { - time_to_first_swap_action: 100, - ...mockAnalyticsContext, - }) - }) - - it('logSwapQuoteRequest calls sendAnalyticsEvent with correct parameters', () => { - const mockChainId = 1 - - logSwapQuoteRequest(mockChainId, RouterPreference.X) - - expect(sendAnalyticsEvent).toHaveBeenCalledWith(SwapEventName.SWAP_QUOTE_FETCH, { - chainId: mockChainId, - isQuickRoute: false, - time_to_first_quote_request: 100, - time_to_first_quote_request_since_first_input: 100, - }) - }) - - it('logSwapQuoteRequest excludes perf metrics for price quotes', () => { - const mockChainId = 1 - - logSwapQuoteRequest(mockChainId, INTERNAL_ROUTER_PREFERENCE_PRICE) - - expect(sendAnalyticsEvent).toHaveBeenCalledWith(SwapEventName.SWAP_QUOTE_FETCH, { - chainId: mockChainId, - isQuickRoute: false, - }) - }) -}) diff --git a/src/tracing/swapFlowLoggers.ts b/src/tracing/swapFlowLoggers.ts deleted file mode 100644 index 96a4861ac2a..00000000000 --- a/src/tracing/swapFlowLoggers.ts +++ /dev/null @@ -1,57 +0,0 @@ -import { SwapEventName } from '@uniswap/analytics-events' -import { ITraceContext } from 'analytics' -import { sendAnalyticsEvent } from 'analytics' -import { INTERNAL_ROUTER_PREFERENCE_PRICE, RouterPreference } from 'state/routing/types' - -import { SwapEventType, timestampTracker } from './SwapEventTimestampTracker' - -export function logSwapSuccess(hash: string, chainId: number, analyticsContext: ITraceContext) { - const hasSetSwapSuccess = timestampTracker.hasTimestamp(SwapEventType.FIRST_SWAP_SUCCESS) - const elapsedTime = timestampTracker.setElapsedTime(SwapEventType.FIRST_SWAP_SUCCESS) - sendAnalyticsEvent(SwapEventName.SWAP_TRANSACTION_COMPLETED, { - // We only log the time-to-swap metric for the first swap of a session, - // so if it was previously set we log undefined here. - time_to_swap: hasSetSwapSuccess ? undefined : elapsedTime, - time_to_swap_since_first_input: hasSetSwapSuccess - ? undefined - : timestampTracker.getElapsedTime(SwapEventType.FIRST_SWAP_SUCCESS, SwapEventType.FIRST_SWAP_ACTION), - hash, - chainId, - ...analyticsContext, - }) -} - -// We only log the time-to-first-swap-input metric for the first swap input of a session. -export function maybeLogFirstSwapAction(analyticsContext: ITraceContext) { - if (!timestampTracker.hasTimestamp(SwapEventType.FIRST_SWAP_ACTION)) { - const elapsedTime = timestampTracker.setElapsedTime(SwapEventType.FIRST_SWAP_ACTION) - sendAnalyticsEvent(SwapEventName.SWAP_FIRST_ACTION, { - time_to_first_swap_action: elapsedTime, - ...analyticsContext, - }) - } -} - -export function logSwapQuoteRequest( - chainId: number, - routerPreference: RouterPreference | typeof INTERNAL_ROUTER_PREFERENCE_PRICE, - isQuickRoute?: boolean -) { - let performanceMetrics = {} - if (routerPreference !== INTERNAL_ROUTER_PREFERENCE_PRICE) { - const hasSetSwapQuote = timestampTracker.hasTimestamp(SwapEventType.FIRST_QUOTE_FETCH_STARTED) - const elapsedTime = timestampTracker.setElapsedTime(SwapEventType.FIRST_QUOTE_FETCH_STARTED) - performanceMetrics = { - // We only log the time_to_first_quote_request metric for the first quote request of a session. - time_to_first_quote_request: hasSetSwapQuote ? undefined : elapsedTime, - time_to_first_quote_request_since_first_input: hasSetSwapQuote - ? undefined - : timestampTracker.getElapsedTime(SwapEventType.FIRST_QUOTE_FETCH_STARTED, SwapEventType.FIRST_SWAP_ACTION), - } - } - sendAnalyticsEvent(SwapEventName.SWAP_QUOTE_FETCH, { - chainId, - isQuickRoute: isQuickRoute ?? false, - ...performanceMetrics, - }) -} diff --git a/src/utils/loggingFormatters.ts b/src/utils/loggingFormatters.ts deleted file mode 100644 index f44d58abdb6..00000000000 --- a/src/utils/loggingFormatters.ts +++ /dev/null @@ -1,108 +0,0 @@ -import { SwapPriceUpdateUserResponse } from '@uniswap/analytics-events' -import { Percent } from '@uniswap/sdk-core' -import { SwapResult } from 'hooks/useSwapCallback' -import { - formatPercentInBasisPointsNumber, - formatPercentNumber, - formatToDecimal, - getDurationUntilTimestampSeconds, - getTokenAddress, -} from 'lib/utils/analytics' -import { InterfaceTrade, TradeFillType } from 'state/routing/types' -import { isClassicTrade } from 'state/routing/utils' - -import { RoutingDiagramEntry } from './getRoutingDiagramEntries' -import { computeRealizedPriceImpact } from './prices' - -const formatRoutesEventProperties = (routes?: RoutingDiagramEntry[]) => { - if (!routes) return {} - - const routesEventProperties: Record = { - routes_percentages: [], - routes_protocols: [], - } - - routes.forEach((route, index) => { - routesEventProperties['routes_percentages'].push(formatPercentNumber(route.percent)) - routesEventProperties['routes_protocols'].push(route.protocol) - routesEventProperties[`route_${index}_input_currency_symbols`] = route.path.map( - (pathStep) => pathStep[0].symbol ?? '' - ) - routesEventProperties[`route_${index}_output_currency_symbols`] = route.path.map( - (pathStep) => pathStep[1].symbol ?? '' - ) - routesEventProperties[`route_${index}_input_currency_addresses`] = route.path.map((pathStep) => - getTokenAddress(pathStep[0]) - ) - routesEventProperties[`route_${index}_output_currency_addresses`] = route.path.map((pathStep) => - getTokenAddress(pathStep[1]) - ) - routesEventProperties[`route_${index}_fee_amounts_hundredths_of_bps`] = route.path.map((pathStep) => pathStep[2]) - }) - - return routesEventProperties -} - -export const formatSwapPriceUpdatedEventProperties = ( - trade: InterfaceTrade, - priceUpdate: number | undefined, - response: SwapPriceUpdateUserResponse -) => ({ - chain_id: - trade.inputAmount.currency.chainId === trade.outputAmount.currency.chainId - ? trade.inputAmount.currency.chainId - : undefined, - response, - token_in_symbol: trade.inputAmount.currency.symbol, - token_out_symbol: trade.outputAmount.currency.symbol, - price_update_basis_points: priceUpdate, -}) - -interface AnalyticsEventProps { - trade: InterfaceTrade - swapResult?: SwapResult - allowedSlippage: Percent - transactionDeadlineSecondsSinceEpoch?: number - isAutoSlippage: boolean - isAutoRouterApi: boolean - routes?: RoutingDiagramEntry[] - fiatValueInput?: number - fiatValueOutput?: number -} - -export const formatSwapButtonClickEventProperties = ({ - trade, - swapResult, - allowedSlippage, - transactionDeadlineSecondsSinceEpoch, - isAutoSlippage, - isAutoRouterApi, - routes, - fiatValueInput, - fiatValueOutput, -}: AnalyticsEventProps) => ({ - estimated_network_fee_usd: isClassicTrade(trade) ? trade.gasUseEstimateUSD : undefined, - transaction_hash: swapResult?.type === TradeFillType.Classic ? swapResult.response.hash : undefined, - order_hash: swapResult?.type === TradeFillType.UniswapX ? swapResult.response.orderHash : undefined, - transaction_deadline_seconds: getDurationUntilTimestampSeconds(transactionDeadlineSecondsSinceEpoch), - token_in_address: trade ? getTokenAddress(trade.inputAmount.currency) : undefined, - token_out_address: trade ? getTokenAddress(trade.outputAmount.currency) : undefined, - token_in_symbol: trade.inputAmount.currency.symbol, - token_out_symbol: trade.outputAmount.currency.symbol, - token_in_amount: trade ? formatToDecimal(trade.inputAmount, trade.inputAmount.currency.decimals) : undefined, - token_out_amount: trade ? formatToDecimal(trade.outputAmount, trade.outputAmount.currency.decimals) : undefined, - token_in_amount_usd: fiatValueInput, - token_out_amount_usd: fiatValueOutput, - price_impact_basis_points: isClassicTrade(trade) - ? formatPercentInBasisPointsNumber(computeRealizedPriceImpact(trade)) - : undefined, - allowed_slippage_basis_points: formatPercentInBasisPointsNumber(allowedSlippage), - is_auto_router_api: isAutoRouterApi, - is_auto_slippage: isAutoSlippage, - chain_id: - trade.inputAmount.currency.chainId === trade.outputAmount.currency.chainId - ? trade.inputAmount.currency.chainId - : undefined, - swap_quote_block_number: isClassicTrade(trade) ? trade.blockNumber : undefined, - ...formatRoutesEventProperties(routes), -}) diff --git a/src/utils/openDownloadApp.ts b/src/utils/openDownloadApp.ts index 2eb8a686a2f..c68d6d1a14f 100644 --- a/src/utils/openDownloadApp.ts +++ b/src/utils/openDownloadApp.ts @@ -1,12 +1,9 @@ -import { InterfaceElementName, InterfaceEventName } from '@uniswap/analytics-events' -import { sendAnalyticsEvent } from 'analytics' import { isIOS } from 'utils/userAgent' const APP_STORE_LINK = 'https://apps.apple.com/app/apple-store/id6443944476' const MICROSITE_LINK = 'https://wallet.uniswap.org/' type OpenDownloadAppOptions = { - element?: InterfaceElementName appStoreParams?: string microSiteParams?: string } @@ -29,9 +26,9 @@ const defaultDownloadAppOptions = { export function openDownloadApp(options: OpenDownloadAppOptions = defaultDownloadAppOptions) { if (isIOS) { - openAppStore({ element: options?.element, urlParamString: options?.appStoreParams }) + openAppStore({ urlParamString: options?.appStoreParams }) } else { - openWalletMicrosite({ element: options?.element, urlParamString: options?.microSiteParams }) + openWalletMicrosite({ urlParamString: options?.microSiteParams }) } } @@ -52,17 +49,14 @@ export const getDownloadAppLinkProps = (options: OpenDownloadAppOptions = defaul } type AnalyticsLinkOptions = { - element?: InterfaceElementName urlParamString?: string } const openAppStore = (options?: AnalyticsLinkOptions) => { - sendAnalyticsEvent(InterfaceEventName.UNISWAP_WALLET_APP_DOWNLOAD_OPENED, { element: options?.element }) window.open(linkWithParams(APP_STORE_LINK, options?.urlParamString), /* target = */ 'uniswap_wallet_appstore') } export const openWalletMicrosite = (options?: AnalyticsLinkOptions) => { - sendAnalyticsEvent(InterfaceEventName.UNISWAP_WALLET_MICROSITE_OPENED, { element: options?.element }) window.open(linkWithParams(MICROSITE_LINK, options?.urlParamString), /* target = */ 'uniswap_wallet_microsite') } diff --git a/src/utils/urlRoutes.test.ts b/src/utils/urlRoutes.test.ts index e82ff309420..df3764b046a 100644 --- a/src/utils/urlRoutes.test.ts +++ b/src/utils/urlRoutes.test.ts @@ -1,49 +1,47 @@ -import { InterfacePageName } from '@uniswap/analytics-events' - import { getCurrentPageFromLocation } from './urlRoutes' describe('getCurrentPageFromLocation', () => { it('should return SWAP_PAGE when location pathname starts with "/swap"', () => { const result = getCurrentPageFromLocation('/swap/123') - expect(result).toBe(InterfacePageName.SWAP_PAGE) + expect(result).toBe('SWAP_PAGE') }) it('should return VOTE_PAGE when location pathname starts with "/vote"', () => { const result = getCurrentPageFromLocation('/vote/456') - expect(result).toBe(InterfacePageName.VOTE_PAGE) + expect(result).toBe('VOTE_PAGE') }) it('should return POOL_PAGE when location pathname starts with "/pools" or "/pool"', () => { let result = getCurrentPageFromLocation('/pools/789') - expect(result).toBe(InterfacePageName.POOL_PAGE) + expect(result).toBe('POOL_PAGE') result = getCurrentPageFromLocation('/pool/abc') - expect(result).toBe(InterfacePageName.POOL_PAGE) + expect(result).toBe('POOL_PAGE') }) it('should return TOKENS_PAGE when location pathname starts with "/tokens"', () => { const result = getCurrentPageFromLocation('/tokens/xyz') - expect(result).toBe(InterfacePageName.TOKENS_PAGE) + expect(result).toBe('TOKENS_PAGE') }) it('should return NFT_PROFILE_PAGE when location pathname starts with "/nfts/profile"', () => { const result = getCurrentPageFromLocation('/nfts/profile/def') - expect(result).toBe(InterfacePageName.NFT_PROFILE_PAGE) + expect(result).toBe('NFT_PROFILE_PAGE') }) it('should return NFT_DETAILS_PAGE when location pathname starts with "/nfts/asset"', () => { const result = getCurrentPageFromLocation('/nfts/asset/ghi') - expect(result).toBe(InterfacePageName.NFT_DETAILS_PAGE) + expect(result).toBe('NFT_DETAILS_PAGE') }) it('should return NFT_COLLECTION_PAGE when location pathname starts with "/nfts/collection"', () => { const result = getCurrentPageFromLocation('/nfts/collection/jkl') - expect(result).toBe(InterfacePageName.NFT_COLLECTION_PAGE) + expect(result).toBe('NFT_COLLECTION_PAGE') }) it('should return NFT_EXPLORE_PAGE when location pathname starts with "/nfts"', () => { const result = getCurrentPageFromLocation('/nfts/mno') - expect(result).toBe(InterfacePageName.NFT_EXPLORE_PAGE) + expect(result).toBe('NFT_EXPLORE_PAGE') }) it('should return undefined for unknown location pathnames', () => { diff --git a/src/utils/urlRoutes.ts b/src/utils/urlRoutes.ts index dca550d0b85..c4801740e1c 100644 --- a/src/utils/urlRoutes.ts +++ b/src/utils/urlRoutes.ts @@ -1,24 +1,22 @@ -import { InterfacePageName } from '@uniswap/analytics-events' - -export function getCurrentPageFromLocation(locationPathname: string): InterfacePageName | undefined { +export function getCurrentPageFromLocation(locationPathname: string) { switch (true) { case locationPathname.startsWith('/swap'): - return InterfacePageName.SWAP_PAGE + return 'SWAP_PAGE' case locationPathname.startsWith('/vote'): - return InterfacePageName.VOTE_PAGE + return 'VOTE_PAGE' case locationPathname.startsWith('/pools'): case locationPathname.startsWith('/pool'): - return InterfacePageName.POOL_PAGE + return 'POOL_PAGE' case locationPathname.startsWith('/tokens'): - return InterfacePageName.TOKENS_PAGE + return 'TOKENS_PAGE' case locationPathname.startsWith('/nfts/profile'): - return InterfacePageName.NFT_PROFILE_PAGE + return 'NFT_PROFILE_PAGE' case locationPathname.startsWith('/nfts/asset'): - return InterfacePageName.NFT_DETAILS_PAGE + return 'NFT_DETAILS_PAGE' case locationPathname.startsWith('/nfts/collection'): - return InterfacePageName.NFT_COLLECTION_PAGE + return 'NFT_COLLECTION_PAGE' case locationPathname.startsWith('/nfts'): - return InterfacePageName.NFT_EXPLORE_PAGE + return 'NFT_EXPLORE_PAGE' default: return undefined } diff --git a/yarn.lock b/yarn.lock index 97c884f6725..781ec16c208 100644 --- a/yarn.lock +++ b/yarn.lock @@ -47,52 +47,6 @@ resolved "https://registry.yarnpkg.com/@alloc/quick-lru/-/quick-lru-5.2.0.tgz#7bf68b20c0a350f936915fcae06f58e32007ce30" integrity sha512-UrcABB+4bUrFABwbluTIBErXwvbsU/V7TZWfmbgJfbkwiBuziS9gxdODUyuiecfdGQ85jglMW6juS3+z5TsKLw== -"@amplitude/analytics-browser@^1.5.8": - version "1.6.1" - resolved "https://registry.yarnpkg.com/@amplitude/analytics-browser/-/analytics-browser-1.6.1.tgz#1b67f117643e3c3acba71a915e11d1e280a853eb" - integrity sha512-i9Mt3p6ikZm7zu6QRMIziSzNwWW3F2zEIKoOoBbMxy97hSliM93/VoLBLOzwMhusHK3Xy5OwcIgYVUHdXbmigw== - dependencies: - "@amplitude/analytics-client-common" "^0.4.0" - "@amplitude/analytics-core" "^0.10.0" - "@amplitude/analytics-types" "^0.12.0" - "@amplitude/ua-parser-js" "^0.7.31" - tslib "^2.3.1" - -"@amplitude/analytics-client-common@^0.4.0": - version "0.4.0" - resolved "https://registry.yarnpkg.com/@amplitude/analytics-client-common/-/analytics-client-common-0.4.0.tgz#5ba53af7d447a992d006f263dd9040c87e07ec6b" - integrity sha512-I3cy6AYCiVUqXAD6yU+tm3qBZdEyrdruDaUS/vVPoi+MvHIkZIXw7xaQjmkBRURWCgdcxu5LioU8r1ld1widtA== - dependencies: - "@amplitude/analytics-connector" "^1.4.5" - "@amplitude/analytics-core" "^0.10.0" - "@amplitude/analytics-types" "^0.12.0" - tslib "^2.3.1" - -"@amplitude/analytics-connector@^1.4.5": - version "1.4.6" - resolved "https://registry.yarnpkg.com/@amplitude/analytics-connector/-/analytics-connector-1.4.6.tgz#60a66eaf0bcdcd17db4f414ff340c69e63116a72" - integrity sha512-6jD2pOosRD4y8DT8StUCz7yTd5ZDkdOU9/AWnlWKM5qk90Mz7sdZrdZ9H7sA/L3yOJEpQOYZgQplQdWWUzyWug== - dependencies: - "@amplitude/ua-parser-js" "0.7.31" - -"@amplitude/analytics-core@^0.10.0": - version "0.10.0" - resolved "https://registry.yarnpkg.com/@amplitude/analytics-core/-/analytics-core-0.10.0.tgz#0d68cede53fecaadfef9c36455eb271454b6ccee" - integrity sha512-D/6U9SzyDmcNWnT/lFnBKfYl4ASicLlwD1tqu4RZoYS3SwHd/PNST+LbnL3yBTEIJIY//qjth9lLBh/RRzePfg== - dependencies: - "@amplitude/analytics-types" "^0.12.0" - tslib "^2.3.1" - -"@amplitude/analytics-types@^0.12.0": - version "0.12.0" - resolved "https://registry.yarnpkg.com/@amplitude/analytics-types/-/analytics-types-0.12.0.tgz#aeec6f204758637603937f05393bdf89fa8e7a5b" - integrity sha512-XwySEhnCdU8fNWUNaB38JS7bwOt4GOUG8OqgzuXtR8HvGnpCvuT7C6H+BIGA7MfctNQBAzR+6IBgDD+8r1/OEQ== - -"@amplitude/ua-parser-js@0.7.31", "@amplitude/ua-parser-js@^0.7.31": - version "0.7.31" - resolved "https://registry.yarnpkg.com/@amplitude/ua-parser-js/-/ua-parser-js-0.7.31.tgz#749bf7cb633cfcc7ff3c10805bad7c5f6fbdbc61" - integrity sha512-+z8UGRaj13Pt5NDzOnkTBy49HE2CX64jeL0ArB86HAtilpnfkPB7oqkigN7Lf2LxscMg4QhFD7mmCfedh3rqTg== - "@ampproject/remapping@^2.2.0": version "2.2.1" resolved "https://registry.yarnpkg.com/@ampproject/remapping/-/remapping-2.2.1.tgz#99e8e11851128b8702cd57c33684f1d0f260b630" @@ -6052,20 +6006,6 @@ "@typescript-eslint/types" "5.59.1" eslint-visitor-keys "^3.3.0" -"@uniswap/analytics-events@^2.24.0": - version "2.24.0" - resolved "https://registry.yarnpkg.com/@uniswap/analytics-events/-/analytics-events-2.24.0.tgz#c81d0c24da4f052b7f6b2663ff42bfa787be91b5" - integrity sha512-MhX9L95Y7i28a3KxRFJnpmNxNHAgownBVPyhT+mu4PnCXiPEuSovml+uJr277tysKSqxRYqLnCeAw4LocTBIfg== - -"@uniswap/analytics@1.5.0": - version "1.5.0" - resolved "https://registry.yarnpkg.com/@uniswap/analytics/-/analytics-1.5.0.tgz#44e9febf773778c74516896c2555d6f95b2c6d62" - integrity sha512-4Hj7uMlU8j/FbKoXxMFmx2pClgOywq+dKy26gwP7696m5GPY2ZFH14XvBrg/ZMJ/Q5tm6nlMDvtxV6xMUK8ung== - dependencies: - "@amplitude/analytics-browser" "^1.5.8" - react "^18.2.0" - react-dom "^18.2.0" - "@uniswap/default-token-list@^11.2.0": version "11.2.0" resolved "https://registry.yarnpkg.com/@uniswap/default-token-list/-/default-token-list-11.2.0.tgz#f7babd37b8f2f1d5c724bd4689be93c4aedd9205"