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
4 changes: 4 additions & 0 deletions src/features/position-detail/components/overview-tab.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,8 @@ const PERIOD_LABELS: Record<EarningsPeriod, string> = {
day: '24h',
week: '7d',
month: '30d',
sixmonth: '6mo',
all: 'All time',
};

export function OverviewTab({
Expand All @@ -42,10 +44,12 @@ export function OverviewTab({
<YieldAnalysisDistribution
markets={groupedPosition.markets}
periodLabel={periodLabel}
isLoading={isEarningsLoading}
/>
<YieldAnalysisYieldBreakdown
markets={groupedPosition.markets}
periodLabel={periodLabel}
isLoading={isEarningsLoading}
/>
</div>
<MarketsBreakdownTable
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@ const PERIOD_OPTIONS: { value: EarningsPeriod; label: string }[] = [
{ value: 'day', label: '24h' },
{ value: 'week', label: '7 days' },
{ value: 'month', label: '30 days' },
{ value: 'sixmonth', label: '6 months' },
{ value: 'all', label: 'All time' },
];

export function PositionPeriodSelector({ period, onPeriodChange, className, contentClassName }: PositionPeriodSelectorProps) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import { useMemo } from 'react';
import { PieChart, Pie, Cell, ResponsiveContainer, Tooltip as RechartsTooltip } from 'recharts';
import { PulseLoader } from 'react-spinners';
import { Card } from '@/components/ui/card';
import { useChartColors } from '@/constants/chartColors';
import { getColorByIndex, OTHER_COLOR } from '@/features/positions/utils/colors';
Expand All @@ -11,6 +12,7 @@ import type { MarketPositionWithEarnings } from '@/utils/types';
type YieldAnalysisDistributionProps = {
markets: MarketPositionWithEarnings[];
periodLabel: string;
isLoading?: boolean;
};

type PieEntry = {
Expand All @@ -25,7 +27,7 @@ type PieEntry = {

const MAX_PIE_ITEMS = 6;

export function YieldAnalysisDistribution({ markets, periodLabel }: YieldAnalysisDistributionProps) {
export function YieldAnalysisDistribution({ markets, periodLabel, isLoading = false }: YieldAnalysisDistributionProps) {
const chartColors = useChartColors();

const pieData = useMemo((): PieEntry[] => {
Expand Down Expand Up @@ -107,7 +109,16 @@ export function YieldAnalysisDistribution({ markets, periodLabel }: YieldAnalysi
</div>
<div className="flex flex-col sm:flex-row items-stretch">
<div className="flex-1 min-h-[220px] px-4 py-4">
{pieData.length === 0 ? (
{isLoading ? (
<div className="flex h-[220px] flex-col items-center justify-center gap-2 text-sm text-secondary">
<PulseLoader
size={4}
color="#f45f2d"
margin={3}
/>
<span>Calculating...</span>
</div>
) : pieData.length === 0 ? (
<div className="flex h-[220px] items-center justify-center text-sm text-secondary">No activity in selected period.</div>
) : (
<ResponsiveContainer
Expand Down Expand Up @@ -149,7 +160,15 @@ export function YieldAnalysisDistribution({ markets, periodLabel }: YieldAnalysi
)}
</div>
<div className="w-full border-t border-border/40 px-4 py-4 sm:w-[280px] sm:border-l sm:border-t-0">
{pieData.length === 0 ? (
{isLoading ? (
<div className="flex h-[220px] items-center justify-center">
<PulseLoader
size={4}
color="#f45f2d"
margin={3}
/>
</div>
) : pieData.length === 0 ? (
<div className="text-xs text-secondary">No weighted exposure to display.</div>
) : (
<div className="max-h-[220px] space-y-2 overflow-auto pr-2">
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import { useMemo } from 'react';
import { PieChart, Pie, Cell, ResponsiveContainer, Tooltip as RechartsTooltip } from 'recharts';
import { PulseLoader } from 'react-spinners';
import { Card } from '@/components/ui/card';
import { useChartColors } from '@/constants/chartColors';
import { getColorByIndex, OTHER_COLOR } from '@/features/positions/utils/colors';
Expand All @@ -11,6 +12,7 @@ import type { MarketPositionWithEarnings } from '@/utils/types';
type YieldAnalysisYieldBreakdownProps = {
markets: MarketPositionWithEarnings[];
periodLabel: string;
isLoading?: boolean;
};

type PieEntry = {
Expand All @@ -24,7 +26,7 @@ type PieEntry = {

const MAX_PIE_ITEMS = 6;

export function YieldAnalysisYieldBreakdown({ markets, periodLabel }: YieldAnalysisYieldBreakdownProps) {
export function YieldAnalysisYieldBreakdown({ markets, periodLabel, isLoading = false }: YieldAnalysisYieldBreakdownProps) {
const chartColors = useChartColors();

const pieData = useMemo((): PieEntry[] => {
Expand Down Expand Up @@ -99,7 +101,16 @@ export function YieldAnalysisYieldBreakdown({ markets, periodLabel }: YieldAnaly
</div>
<div className="flex flex-col sm:flex-row items-stretch">
<div className="flex-1 min-h-[220px] px-4 py-4">
{pieData.length === 0 ? (
{isLoading ? (
<div className="flex h-[220px] flex-col items-center justify-center gap-2 text-sm text-secondary">
<PulseLoader
size={4}
color="#f45f2d"
margin={3}
/>
<span>Calculating...</span>
</div>
) : pieData.length === 0 ? (
<div className="flex h-[220px] items-center justify-center text-sm text-secondary">No yield generated in period.</div>
) : (
<ResponsiveContainer
Expand Down Expand Up @@ -141,7 +152,15 @@ export function YieldAnalysisYieldBreakdown({ markets, periodLabel }: YieldAnaly
)}
</div>
<div className="w-full border-t border-border/40 px-4 py-4 sm:w-[280px] sm:border-l sm:border-t-0">
{pieData.length === 0 ? (
{isLoading ? (
<div className="flex h-[220px] items-center justify-center">
<PulseLoader
size={4}
color="#f45f2d"
margin={3}
/>
</div>
) : pieData.length === 0 ? (
<div className="text-xs text-secondary">No yield breakdown to display.</div>
) : (
<div className="max-h-[220px] space-y-2 overflow-auto pr-2">
Expand Down
2 changes: 2 additions & 0 deletions src/features/position-detail/position-view.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,8 @@ const PERIOD_LABELS: Record<EarningsPeriod, string> = {
day: '24h',
week: '7d',
month: '30d',
sixmonth: '6mo',
all: 'All time',
};

type PositionDetailTab = 'analysis' | 'history';
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -70,11 +70,13 @@ export function SuppliedMorphoBlueGroupedTable({ account }: SuppliedMorphoBlueGr
return account === address;
}, [account, address]);

const periodLabels = {
const periodLabels: Record<EarningsPeriod, string> = {
day: '1D',
week: '7D',
month: '30D',
} as const;
sixmonth: '6M',
all: 'All',
};

const groupedPositions = useMemo(() => groupPositionsByLoanAsset(marketPositions), [marketPositions]);

Expand Down
6 changes: 4 additions & 2 deletions src/features/positions/components/user-vaults-table.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -23,11 +23,13 @@ import { VaultAllocationDetail } from './vault-allocation-detail';
import { CollateralIconsDisplay } from './collateral-icons-display';
import { VaultActionsDropdown } from './vault-actions-dropdown';

const periodLabels = {
const periodLabels: Record<EarningsPeriod, string> = {
day: '1D',
week: '7D',
month: '30D',
} as const;
sixmonth: '6M',
all: 'All',
};

const formatRate = (rate: number | null | undefined, isApr: boolean): string => {
if (rate === null || rate === undefined) return '-';
Expand Down
2 changes: 1 addition & 1 deletion src/hooks/useMarketData.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ export const useMarketData = (uniqueKey: string | undefined, network: SupportedN
console.log(`Attempting fetchMarketSnapshot for market ${uniqueKey}`);
let snapshot = null;
try {
snapshot = await fetchMarketSnapshot(uniqueKey, network, publicClient, 0);
snapshot = await fetchMarketSnapshot(uniqueKey, network, publicClient);
console.log(`Market state (from RPC) result for ${uniqueKey}:`, snapshot ? 'Exists' : 'Null');
} catch (snapshotError) {
console.error(`Error fetching market snapshot for ${uniqueKey}:`, snapshotError);
Expand Down
4 changes: 4 additions & 0 deletions src/hooks/usePositionsWithEarnings.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,10 @@ export const getPeriodTimestamp = (period: EarningsPeriod): number => {
return now - 7 * 86_400;
case 'month':
return now - 30 * 86_400;
case 'sixmonth':
return now - 180 * 86_400;
case 'all':
return 0;
default:
return now - 86_400;
}
Expand Down
2 changes: 1 addition & 1 deletion src/hooks/useUserPosition.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ const useUserPosition = (user: string | undefined, chainId: SupportedNetworks |
console.log(`Attempting fetchPositionSnapshot for ${user} on market ${marketKey}`);
let snapshot = null;
try {
snapshot = await fetchPositionSnapshot(marketKey, user as Address, chainId, 0, publicClient);
snapshot = await fetchPositionSnapshot(marketKey, user as Address, chainId, undefined, publicClient);
console.log(`Snapshot result for ${marketKey}:`, snapshot ? 'Exists' : 'Null');
} catch (snapshotError) {
console.error(`Error fetching position snapshot for ${user} on market ${marketKey}:`, snapshotError);
Expand Down
2 changes: 1 addition & 1 deletion src/hooks/useUserPositions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -187,7 +187,7 @@ const useUserPositions = (user: string | undefined, showEmpty = false, chainIds?
}

const marketIds = markets.map((m) => m.marketUniqueKey);
const snapshots = await fetchPositionsSnapshots(marketIds, user as Address, chainId, 0, publicClient);
const snapshots = await fetchPositionsSnapshots(marketIds, user as Address, chainId, undefined, publicClient);

// Merge into allSnapshots
snapshots.forEach((snapshot, marketId) => {
Expand Down
26 changes: 22 additions & 4 deletions src/hooks/useUserPositionsSummaryData.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,11 +40,19 @@ const useUserPositionsSummaryData = (user: string | undefined, period: EarningsP
return blocks;
}, [period, uniqueChainIds, currentBlocks]);

const { data: actualBlockData } = useBlockTimestamps(snapshotBlocks);
const {
data: actualBlockData,
isLoading: isLoadingBlockTimestamps,
isFetching: isFetchingBlockTimestamps,
} = useBlockTimestamps(snapshotBlocks);

const endTimestamp = useMemo(() => Math.floor(Date.now() / 1000), []);

const { data: txData, isLoading: isLoadingTransactions } = useUserTransactionsQuery({
const {
data: txData,
isLoading: isLoadingTransactions,
isFetching: isFetchingTransactions,
} = useUserTransactionsQuery({
filters: {
userAddress: user ? [user] : [],
marketUniqueKeys: positions?.map((p) => p.market.uniqueKey) ?? [],
Expand All @@ -54,7 +62,11 @@ const useUserPositionsSummaryData = (user: string | undefined, period: EarningsP
enabled: !!positions && !!user,
});

const { data: allSnapshots, isLoading: isLoadingSnapshots } = usePositionSnapshots({
const {
data: allSnapshots,
isLoading: isLoadingSnapshots,
isFetching: isFetchingSnapshots,
} = usePositionSnapshots({
positions,
user,
snapshotBlocks,
Expand Down Expand Up @@ -95,7 +107,13 @@ const useUserPositionsSummaryData = (user: string | undefined, period: EarningsP
}
};

const isEarningsLoading = isLoadingSnapshots || isLoadingTransactions || !actualBlockData;
const isEarningsLoading =
isLoadingSnapshots ||
isFetchingSnapshots ||
isLoadingTransactions ||
isFetchingTransactions ||
isLoadingBlockTimestamps ||
isFetchingBlockTimestamps;
Comment on lines +110 to +116
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor

isFetching in loading indicator will flash spinners on background refetches.

isLoading is true only on first fetch (no cached data). isFetching is true on every fetch, including background refetches. Including isFetching here means any stale-time expiry or window refocus (even though refetchOnWindowFocus: false is set on individual queries, invalidateQueries in refetch() will trigger it) will flip the UI back to a loading state.

If that's intentional — fine. If not, drop the isFetching checks and rely on isLoading alone to avoid flicker.

🤖 Prompt for AI Agents
In `@src/hooks/useUserPositionsSummaryData.ts` around lines 110 - 116, The
isEarningsLoading aggregate currently includes isFetching flags which cause UI
spinners to flash on background refetches; update useUserPositionsSummaryData to
remove all isFetching* checks and only use the isLoading variants
(isLoadingSnapshots, isLoadingTransactions, isLoadingBlockTimestamps) when
computing isEarningsLoading so the loading indicator shows only on the initial
load and not on background refetches.


const loadingStates = {
positions: positionsLoading,
Expand Down
3 changes: 1 addition & 2 deletions src/stores/usePositionsFilters.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,8 @@ import { persist } from 'zustand/middleware';

/**
* Earnings calculation periods for the positions summary page.
* Removed 'all' to optimize for speed - use report page for comprehensive analysis.
*/
export type EarningsPeriod = 'day' | 'week' | 'month';
export type EarningsPeriod = 'day' | 'week' | 'month' | 'sixmonth' | 'all';

type PositionsFiltersState = {
/** Currently selected earnings period */
Expand Down
22 changes: 11 additions & 11 deletions src/utils/positions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,15 +68,15 @@ function convertSharesToAssets(shares: bigint, totalAssets: bigint, totalShares:
* @param marketIds - Array of market unique IDs
* @param userAddress - The user's address
* @param chainId - The chain ID of the network
* @param blockNumber - The block number to fetch positions at (0 for latest)
* @param blockNumber - The block number to fetch positions at (undefined for latest)
* @param client - The viem PublicClient to use for the request
* @returns Map of marketId to PositionSnapshot
*/
export async function fetchPositionsSnapshots(
marketIds: string[],
userAddress: Address,
chainId: number,
blockNumber: number,
blockNumber: number | undefined,
client: PublicClient,
): Promise<Map<string, PositionSnapshot>> {
const result = new Map<string, PositionSnapshot>();
Expand All @@ -86,7 +86,7 @@ export async function fetchPositionsSnapshots(
}

try {
const isNow = blockNumber === 0;
const isLatest = blockNumber === undefined;
const morphoAddress = getMorphoAddress(chainId as SupportedNetworks);

// Step 1: Multicall to get all position data
Expand All @@ -100,7 +100,7 @@ export async function fetchPositionsSnapshots(
const positionResults = await client.multicall({
contracts: positionContracts,
allowFailure: true,
blockNumber: isNow ? undefined : BigInt(blockNumber),
blockNumber: isLatest ? undefined : BigInt(blockNumber),
});

// Process position results and identify which markets need market data
Expand Down Expand Up @@ -143,7 +143,7 @@ export async function fetchPositionsSnapshots(
const marketResults = await client.multicall({
contracts: marketContracts,
allowFailure: true,
blockNumber: isNow ? undefined : BigInt(blockNumber),
blockNumber: isLatest ? undefined : BigInt(blockNumber),
});

// Process market results and create final snapshots
Expand Down Expand Up @@ -192,15 +192,15 @@ export async function fetchPositionsSnapshots(
* @param marketId - The unique ID of the market
* @param userAddress - The user's address
* @param chainId - The chain ID of the network
* @param blockNumber - The block number to fetch the position at (0 for latest)
* @param blockNumber - The block number to fetch the position at (undefined for latest)
* @param client - The viem PublicClient to use for the request
* @returns The position snapshot or null if there was an error
*/
export async function fetchPositionSnapshot(
marketId: string,
userAddress: Address,
chainId: number,
blockNumber: number,
blockNumber: number | undefined,
client: PublicClient,
): Promise<PositionSnapshot | null> {
const snapshots = await fetchPositionsSnapshots([marketId], userAddress, chainId, blockNumber, client);
Expand All @@ -212,26 +212,26 @@ export async function fetchPositionSnapshot(
*
* @param marketId - The unique ID of the market
* @param chainId - The chain ID of the network
* @param blockNumber - The block number to fetch the market at (0 for latest)
* @param blockNumber - The block number to fetch the market at (undefined for latest)
* @param client - The viem PublicClient to use for the request
* @returns The market snapshot or null if there was an error
*/
export async function fetchMarketSnapshot(
marketId: string,
chainId: number,
client: PublicClient,
blockNumber = 0,
blockNumber?: number,
): Promise<MarketSnapshot | null> {
try {
const isNow = !blockNumber || blockNumber === 0;
const isLatest = blockNumber === undefined;

// Get the market data
const marketArray = (await client.readContract({
address: getMorphoAddress(chainId as SupportedNetworks),
abi: morphoABI,
functionName: 'market',
args: [marketId as `0x${string}`],
blockNumber: isNow ? undefined : BigInt(blockNumber!),
blockNumber: isLatest ? undefined : BigInt(blockNumber),
})) as readonly bigint[];

// Convert array to market object
Expand Down