Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions src/components/pages/portfolio/activity.helpers.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -135,6 +135,12 @@ describe('portfolio activity helpers', () => {
expect(entry?.action).toBe('deposit')
})

it('marks failed local notifications as failed activity', () => {
const entry = toLocalActivityEntry(createNotification({ status: 'error' }))

expect(entry?.transactionStatus).toBe('failed')
})

it('does not map local notifications without any timestamp', () => {
const entry = toLocalActivityEntry(
createNotification({
Expand Down
3 changes: 2 additions & 1 deletion src/components/pages/portfolio/activity.helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -192,7 +192,8 @@ export function toLocalActivityEntry(
outputTokenAmountFormatted: isZap && isExitAction ? assetAmountFormatted : null,
shareAmount,
shareAmountFormatted,
status: 'ok'
status: 'ok',
...(notification.status === 'error' ? { transactionStatus: 'failed' as const } : {})
}
}

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import type { TNotification } from '@shared/types/notifications'
import { describe, expect, it } from 'vitest'
import {
getLocalActivityTransactionKey,
getReceiptValidatedLocalActivityNotifications
} from './useLocalActivityReceiptStatuses'

const FAILED_HASH = '0xca2ea76c57d927d9d3637b8132031291d67f3977eba90d936a0647eb4487b651'

function createNotification(overrides: Partial<TNotification> = {}): TNotification {
return {
address: '0xdf0259238271427c469abc18a2cb3047d5c12466',
type: 'deposit',
amount: '1',
chainId: 1,
status: 'success',
txHash: FAILED_HASH,
timeFinished: 1,
...overrides
}
}

describe('local activity receipt validation', () => {
it('converts a cached success into a failed notification when its receipt reverted', () => {
const notification = createNotification()
const transactionKey = getLocalActivityTransactionKey(notification)
const statuses = new Map([[transactionKey!, 'reverted' as const]])

expect(getReceiptValidatedLocalActivityNotifications([notification], statuses)[0]?.status).toBe('error')
})

it('does not present an unverified cached success as completed', () => {
expect(getReceiptValidatedLocalActivityNotifications([createNotification()], new Map())).toEqual([])
})

it('keeps receipt-confirmed successes and existing errors', () => {
const success = createNotification()
const error = createNotification({ txHash: `0x${'f'.repeat(64)}`, status: 'error' })
const transactionKey = getLocalActivityTransactionKey(success)
const statuses = new Map([[transactionKey!, 'success' as const]])

expect(getReceiptValidatedLocalActivityNotifications([success, error], statuses)).toEqual([success, error])
})
})
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
import type { TNotification } from '@shared/types/notifications'
import { retrieveConfig } from '@shared/utils/wagmi'
import { useQueries } from '@tanstack/react-query'
import { useMemo } from 'react'
import { getTransactionReceipt } from 'wagmi/actions'

export type TLocalActivityReceiptStatus = 'success' | 'reverted'

export function getLocalActivityTransactionKey(notification: Pick<TNotification, 'chainId' | 'txHash'>): string | null {
return notification.txHash ? `${notification.chainId}:${notification.txHash.toLowerCase()}` : null
}

export function getReceiptValidatedLocalActivityNotifications(
notifications: TNotification[],
receiptStatuses: ReadonlyMap<string, TLocalActivityReceiptStatus>
): TNotification[] {
return notifications.flatMap((notification) => {
if (notification.status !== 'success') {
return [notification]
}

const transactionKey = getLocalActivityTransactionKey(notification)
const receiptStatus = transactionKey ? receiptStatuses.get(transactionKey) : undefined

if (receiptStatus === 'reverted') {
return [{ ...notification, status: 'error' as const }]
}

return receiptStatus === 'success' ? [notification] : []
})
}

export function useLocalActivityReceiptStatuses(
notifications: TNotification[],
enabled: boolean
): ReadonlyMap<string, TLocalActivityReceiptStatus> {
const candidates = useMemo(
() => notifications.filter((notification) => notification.status === 'success' && notification.txHash),
[notifications]
)
const queries = useQueries({
queries: candidates.map((notification) => ({
queryKey: ['portfolio', 'local-activity-receipt', notification.chainId, notification.txHash],
queryFn: () =>
getTransactionReceipt(retrieveConfig(), {
chainId: notification.chainId,
hash: notification.txHash!
}),
enabled,
staleTime: Number.POSITIVE_INFINITY,
retry: 1
}))
})

return useMemo(
() =>
candidates.reduce<Map<string, TLocalActivityReceiptStatus>>((statuses, notification, index) => {
const transactionKey = getLocalActivityTransactionKey(notification)
const receiptStatus = queries[index]?.data?.status

if (transactionKey && receiptStatus) {
statuses.set(transactionKey, receiptStatus)
}

return statuses
}, new Map()),
[candidates, queries]
)
}
25 changes: 21 additions & 4 deletions src/components/pages/portfolio/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,7 @@ import Image from '/src/components/Image'
import {
doesActivityEntryMatchSearch,
doesLocalActivityMatchFilters,
getNotificationActivityAction,
isRecentLocalActivityEntry,
isZapNotification,
toLocalActivityEntry
Expand All @@ -96,6 +97,10 @@ import {
resolvePortfolioGrowthDisplayMode
} from './components/PortfolioHistoryChart'
import type { TPortfolioVaultGrowthChartMode } from './components/PortfolioVaultGrowthChart'
import {
getReceiptValidatedLocalActivityNotifications,
useLocalActivityReceiptStatuses
} from './hooks/useLocalActivityReceiptStatuses'
import { usePortfolioActivity } from './hooks/usePortfolioActivity'
import { usePortfolioHistory } from './hooks/usePortfolioHistory'
import { usePortfolioProtocolReturnHistory } from './hooks/usePortfolioProtocolReturnHistory'
Expand Down Expand Up @@ -1216,6 +1221,7 @@ function IndexedActivityRow({
: 'ASSET RECEIVED:'
: 'VAULT SHARES RECEIVED:'
const metadataStatus = entry.status === 'ok' ? 'Indexed' : 'Limited metadata'
const isFailedTransaction = entry.transactionStatus === 'failed'
const hoverRoundedClass =
isFirstRow && isLastRow ? 'rounded-lg' : isFirstRow ? 'rounded-t-lg' : isLastRow ? 'rounded-b-lg' : ''
const handleRowToggle = (): void => {
Expand Down Expand Up @@ -1309,6 +1315,7 @@ function IndexedActivityRow({
time={formattedTime}
/>
{metadataStatus !== 'Indexed' ? <VaultsListChip label={metadataStatus} /> : null}
{isFailedTransaction ? <VaultsListChip label="Failed" /> : null}
{isZap ? (
<VaultsListChip
label="Zap"
Expand Down Expand Up @@ -1339,6 +1346,7 @@ function IndexedActivityRow({
time={formattedTime}
/>
{metadataStatus !== 'Indexed' ? <VaultsListChip label={metadataStatus} /> : null}
{isFailedTransaction ? <VaultsListChip label="Failed" /> : null}
{isZap ? (
<VaultsListChip
label="Zap"
Expand Down Expand Up @@ -1713,6 +1721,15 @@ function PortfolioActivitySection({ isActive, openLoginModal }: TPortfolioActivi
const { allVaults } = useYearn()
const { getToken } = useTokenList()
const { cachedEntries, isLoading: notificationsLoading, error: notificationsError } = useNotifications()
const localActivityNotifications = useMemo(
() => cachedEntries.filter((entry) => Boolean(getNotificationActivityAction(entry))),
[cachedEntries]
)
const localActivityReceiptStatuses = useLocalActivityReceiptStatuses(localActivityNotifications, isActive)
const receiptValidatedCachedEntries = useMemo(
() => getReceiptValidatedLocalActivityNotifications(localActivityNotifications, localActivityReceiptStatuses),
[localActivityNotifications, localActivityReceiptStatuses]
)
const [activityFilters, setActivityFilters] = useState<TActivityModalFilters>(DEFAULT_ACTIVITY_MODAL_FILTERS)
const [activityDateRangeDraftFilters, setActivityDateRangeDraftFilters] =
useState<TActivityModalFilters>(DEFAULT_ACTIVITY_MODAL_FILTERS)
Expand Down Expand Up @@ -1791,7 +1808,7 @@ function PortfolioActivitySection({ isActive, openLoginModal }: TPortfolioActivi
)
const unresolvedLocalActivityEntries = useMemo(
() =>
cachedEntries
receiptValidatedCachedEntries
.filter((entry) => entry.status !== 'success')
.filter((entry) =>
doesLocalActivityMatchFilters({
Expand All @@ -1813,7 +1830,7 @@ function PortfolioActivitySection({ isActive, openLoginModal }: TPortfolioActivi
activitySearch,
activityStartTimestamp,
allVaults,
cachedEntries,
receiptValidatedCachedEntries,
isActivityZapFilterActive
]
)
Expand All @@ -1823,7 +1840,7 @@ function PortfolioActivitySection({ isActive, openLoginModal }: TPortfolioActivi
)
const recentLocalEntries = useMemo(
() =>
cachedEntries
receiptValidatedCachedEntries
.filter((entry) => isRecentLocalActivityEntry(entry, indexedTxHashes))
.filter((entry) =>
doesLocalActivityMatchFilters({
Expand All @@ -1841,7 +1858,7 @@ function PortfolioActivitySection({ isActive, openLoginModal }: TPortfolioActivi
activityEndTimestamp,
activityFilters,
activityStartTimestamp,
cachedEntries,
receiptValidatedCachedEntries,
indexedTxHashes,
isActivityZapFilterActive
]
Expand Down
3 changes: 2 additions & 1 deletion src/components/pages/portfolio/types/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -144,7 +144,8 @@ const portfolioActivityEntrySchema = z.object({
outputTokenAmountFormatted: z.number().nullable().optional().default(null),
shareAmount: z.string(),
shareAmountFormatted: z.number().nullable(),
status: z.enum(['ok', 'missing_metadata'])
status: z.enum(['ok', 'missing_metadata']),
transactionStatus: z.literal('failed').optional()
})

export const portfolioActivityResponseSchema = z.object({
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import { useAccount, useCallsStatus, useWriteContract } from 'wagmi'
import { isConnectedToExecutionChain, resolveExecutionChainId } from '@/config/tenderly'
import { InfoOverlay } from '../shared/InfoOverlay'
import { AnimatedCheckmark, ErrorIcon, Spinner } from '../shared/TransactionStateIndicators'
import { resolveExecutionTrackingHash } from '../shared/transactionOverlay.helpers'
import { resolveExecutionTrackingHash, resolveTransactionReceiptOutcome } from '../shared/transactionOverlay.helpers'
import {
resolveApprovalOverlayActionDisabledState,
resolveApprovalOverlayConnectedChainId,
Expand Down Expand Up @@ -84,6 +84,11 @@ export const ApprovalOverlay: FC<ApprovalOverlayProps> = ({
callsReceiptTxHash: safeCallsStatus.data?.receipts?.[0]?.transactionHash
})
const receipt = useWaitForTransactionReceipt({ hash: executionTrackingHash, chainId })
const receiptOutcome = resolveTransactionReceiptOutcome({
isSuccess: receipt.isSuccess,
isError: receipt.isError,
status: receipt.data?.status
})

// Reset state when overlay closes
useEffect(() => {
Expand All @@ -97,11 +102,11 @@ export const ApprovalOverlay: FC<ApprovalOverlayProps> = ({

// Handle transaction success
useEffect(() => {
if (receipt.isSuccess && (txState === 'pending' || txState === 'submitted')) {
if (receiptOutcome === 'success' && (txState === 'pending' || txState === 'submitted')) {
setTxState('success')
reset()
}
}, [receipt.isSuccess, txState, reset])
}, [receiptOutcome, txState, reset])

useEffect(() => {
const nextTxState = resolveApprovalOverlayPendingSafeState({
Expand Down Expand Up @@ -133,12 +138,12 @@ export const ApprovalOverlay: FC<ApprovalOverlayProps> = ({

// Handle transaction error
useEffect(() => {
if (receipt.isError && (txState === 'pending' || txState === 'submitted')) {
if (receiptOutcome === 'error' && (txState === 'pending' || txState === 'submitted')) {
setTxState('error')
setErrorMessage('Transaction failed')
reset()
}
}, [receipt.isError, txState, reset])
}, [receiptOutcome, txState, reset])

const handleDone = useCallback(async () => {
if (isDoneRefreshing) return
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ import {
resolveExecutionTrackingHash,
resolveOverlayConnectedChainId,
resolvePendingSafeOverlayState,
resolveTransactionReceiptOutcome,
shouldAutoContinueFromSuccessState,
shouldAutoContinuePermitSuccess,
shouldRefetchNextStepAfterReceipt,
Expand Down Expand Up @@ -252,6 +253,11 @@ export const TransactionOverlay: FC<TransactionOverlayProps> = ({
callsReceiptTxHash: safeCallsStatus.data?.receipts?.[0]?.transactionHash
})
const receipt = useWaitForTransactionReceipt({ hash: executionTrackingHash, chainId: explorerChainId, confirmations })
const receiptOutcome = resolveTransactionReceiptOutcome({
isSuccess: receipt.isSuccess,
isError: receipt.isError,
status: receipt.data?.status
})
const blockExplorer = getNetwork(explorerChainId ?? currentChainId).defaultBlockExplorer
const explorerTxUrl = executionTrackingHash && blockExplorer ? `${blockExplorer}/tx/${executionTrackingHash}` : ''

Expand Down Expand Up @@ -816,7 +822,7 @@ export const TransactionOverlay: FC<TransactionOverlayProps> = ({
const executedStepCompletesFlow = successStep?.completesFlow ?? wasLastStepRef.current
const isTerminalSuccess = overlayState === 'success' && (hasCompletedFlow || executedStepCompletesFlow)
const isPreparingNextStep =
overlayState === 'pending' && receipt.isSuccess && !wasLastStepRef.current && executedStepAutoContinues
overlayState === 'pending' && receiptOutcome === 'success' && !wasLastStepRef.current && executedStepAutoContinues
const isSuccessButtonBusy = !isTerminalSuccess && (!isStepReady || isAutoContinuing)
const successButtonLabel = getSuccessButtonLabel({
isCrossChainNotification: successStep?.notification?.type === 'crosschain zap',
Expand Down Expand Up @@ -911,8 +917,8 @@ export const TransactionOverlay: FC<TransactionOverlayProps> = ({
const receiptHash = receipt.data?.transactionHash
const isUnhandledReceipt = Boolean(receiptHash && handledSuccessReceiptRef.current !== receiptHash)

if (receipt.isSuccess && receiptHash && (overlayState === 'pending' || overlayState === 'submitted')) {
executedStepBlockRef.current = receipt.data.blockNumber
if (receiptOutcome === 'success' && receiptHash && (overlayState === 'pending' || overlayState === 'submitted')) {
executedStepBlockRef.current = receipt.data?.blockNumber
const executedStepLabel = executedStepRef.current?.label
if (!hasReportedStepSuccessRef.current && executedStepLabel) {
hasReportedStepSuccessRef.current = true
Expand All @@ -923,7 +929,7 @@ export const TransactionOverlay: FC<TransactionOverlayProps> = ({
const isNextStepReady = step?.label !== executedStepRef.current?.label && isStepReady
const canShowSuccess = wasLastStepRef.current || isNextStepReady
if (
receipt.isSuccess &&
receiptOutcome === 'success' &&
receiptHash &&
isUnhandledReceipt &&
(overlayState === 'pending' || overlayState === 'submitted') &&
Expand Down Expand Up @@ -1014,7 +1020,7 @@ export const TransactionOverlay: FC<TransactionOverlayProps> = ({
}
}
}, [
receipt.isSuccess,
receiptOutcome,
receipt.data?.transactionHash,
overlayState,
requestConfetti,
Expand Down Expand Up @@ -1065,7 +1071,7 @@ export const TransactionOverlay: FC<TransactionOverlayProps> = ({

// Handle transaction error
useEffect(() => {
if (receipt.isError && receipt.error && (overlayState === 'pending' || overlayState === 'submitted')) {
if (receiptOutcome === 'error' && (overlayState === 'pending' || overlayState === 'submitted')) {
setOverlayState('error')
setErrorMessage('Transaction failed. Please try again.')
resetTxState()
Expand All @@ -1074,7 +1080,7 @@ export const TransactionOverlay: FC<TransactionOverlayProps> = ({
handleUpdateNotification({ status: 'error' })
setNotificationId(undefined)
}
}, [receipt.isError, receipt.error, overlayState, handleUpdateNotification, resetTxState])
}, [receiptOutcome, overlayState, handleUpdateNotification, resetTxState])

// When step 1 succeeds in a multi-step flow, the next step simulation may need a refetch
// to pick up post-transaction state (e.g. unstake -> withdraw).
Expand Down
Loading