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
1 change: 1 addition & 0 deletions apps/web/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@
},
"devDependencies": {
"@tanstack/eslint-config": "^0.3.0",
"@tanstack/react-query-devtools": "^5.100.9",
"@types/node": "^25.1.0",
"@types/react": "^19.2.10",
"@types/react-dom": "^19.2.3",
Expand Down
21 changes: 21 additions & 0 deletions apps/web/src/app/error-page.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
type Props = {
onReset?: () => void
}

export function ErrorPage({ onReset }: Props) {
return (
<main className="flex min-h-screen flex-col items-center justify-center gap-4 p-8 text-center">
<h1 className="text-2xl font-semibold text-foreground">Something went wrong</h1>
<p className="max-w-sm text-sm text-muted-foreground">
An unexpected error occurred. You can try reloading the page or contact support if the
problem persists.
</p>
<button
className="rounded-md bg-primary px-4 py-2 text-sm font-medium text-primary-foreground hover:bg-primary/90"
onClick={onReset ?? (() => window.location.reload())}
>
Reload
</button>
</main>
)
}
18 changes: 17 additions & 1 deletion apps/web/src/app/providers/QueryProvider.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,22 @@
import { QueryClient, QueryClientProvider } from "@tanstack/react-query"
import { QueryCache, QueryClient, QueryClientProvider } from "@tanstack/react-query"
import { ReactQueryDevtools } from "@tanstack/react-query-devtools"
import type { ReactNode } from "react"
import { toast } from "sonner"
import { parseSorobanError } from "@/lib/soroban/errors"

function isAuthError(error: unknown): boolean {
const text = String(error).toLowerCase()
return ["401", "403", "unauthorized", "unauthenticated"].some((token) => text.includes(token))
}

export const queryClient = new QueryClient({
queryCache: new QueryCache({
onError(error) {
if (isAuthError(error)) return
if (import.meta.env.DEV) console.error("[query error]", error)
toast.error(parseSorobanError(error))
},
}),
defaultOptions: {
queries: {
staleTime: 1000 * 30,
Expand All @@ -14,6 +29,7 @@ export function QueryProvider({ children }: { children: ReactNode }) {
return (
<QueryClientProvider client={queryClient}>
{children}
{import.meta.env.DEV && <ReactQueryDevtools initialIsOpen={false} />}
</QueryClientProvider>
)
}
38 changes: 31 additions & 7 deletions apps/web/src/app/providers/index.tsx
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
import { createContext, useCallback, useContext, useEffect, useRef } from "react"
import { Component, createContext, useCallback, useContext, useEffect, useRef } from "react"
import { QueryProvider } from "./QueryProvider"
import type { ReactNode } from "react"
import type { ErrorInfo, ReactNode } from "react"
import { useWalletStore } from "@/features/wallet/store/wallet-store"
import { NETWORK } from "@/app/config/network"
import { ThemeProvider } from "@/ui/theme-provider"
import { ErrorPage } from "@/app/error-page"

export type WalletStatus = "disconnected" | "connecting" | "connected" | "error"

Expand Down Expand Up @@ -97,12 +98,35 @@ export function WalletProvider({ children }: { children: ReactNode }) {
)
}

type ErrorBoundaryState = { hasError: boolean }

class ErrorBoundary extends Component<{ children: ReactNode }, ErrorBoundaryState> {
state: ErrorBoundaryState = { hasError: false }

static getDerivedStateFromError(): ErrorBoundaryState {
return { hasError: true }
}

componentDidCatch(error: Error, info: ErrorInfo) {
console.error("[ErrorBoundary]", error, info.componentStack)
}

render() {
if (this.state.hasError) {
return <ErrorPage onReset={() => this.setState({ hasError: false })} />
}
return this.props.children
}
}

export function AppProviders({ children }: { children: ReactNode }) {
return (
<QueryProvider>
<WalletProvider>
<ThemeProvider>{children}</ThemeProvider>
</WalletProvider>
</QueryProvider>
<ErrorBoundary>
<QueryProvider>
<WalletProvider>
<ThemeProvider>{children}</ThemeProvider>
</WalletProvider>
</QueryProvider>
</ErrorBoundary>
)
}
49 changes: 44 additions & 5 deletions apps/web/src/features/trade/components/positions/PositionsList.tsx
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
import { useState } from "react"
import { useEffect, useRef, useState } from "react"
import { useQueryClient } from "@tanstack/react-query"
import { Skeleton } from "@workspace/ui/components/skeleton"
import { Button } from "@workspace/ui/components/button"
import { Badge } from "@workspace/ui/components/badge"
import { usePositions } from "../../hooks/usePositions"
import { usePositions } from "../../hooks/usePositions"
import { useFundingRate } from "../../hooks/useFundingRate"
import { createDecreaseOrder } from "../../lib/stellar"
import type {Position} from "../../hooks/usePositions";
import type { Position } from "../../hooks/usePositions"
import { formatPct, formatUsd } from "@/shared/lib/format"
import { queryKeys } from "../../lib/query-keys"
import { useWalletStore } from "@/features/wallet/store/wallet-store"
Expand All @@ -14,8 +15,40 @@ type Props = {
onSelectPosition?: (position: Position) => void
}

function formatCountdown(ms: number): string {
if (ms <= 0) return "0m"
const totalSeconds = Math.floor(ms / 1000)
const h = Math.floor(totalSeconds / 3600)
const m = Math.floor((totalSeconds % 3600) / 60)
return h > 0 ? `${h}h ${m}m` : `${m}m`
}

function useFundingCountdown(nextEpochTs: number | undefined): string {
const [remaining, setRemaining] = useState<number>(0)
const intervalRef = useRef<ReturnType<typeof setInterval> | null>(null)

useEffect(() => {
if (nextEpochTs === undefined) return

function tick() {
setRemaining(Math.max(0, nextEpochTs! - Date.now()))
}

tick()
intervalRef.current = setInterval(tick, 1000)

return () => {
if (intervalRef.current !== null) clearInterval(intervalRef.current)
}
}, [nextEpochTs])

return formatCountdown(remaining)
}

export function PositionsList({ onSelectPosition }: Props) {
const { data: positions = [], isLoading } = usePositions()
const { data: fundingRate } = useFundingRate()
const countdown = useFundingCountdown(fundingRate?.nextEpochTs)
const account = useWalletStore((state) => state.address)
const queryClient = useQueryClient()
const [closing, setClosing] = useState<string | null>(null)
Expand All @@ -31,14 +64,16 @@ export function PositionsList({ onSelectPosition }: Props) {
marketAddress: position.marketAddress,
collateralToken: position.collateralToken,
collateralDeltaAmount: position.collateralAmount,
sizeDeltaUsd: position.sizeUsd, // full close
sizeDeltaUsd: position.sizeUsd, // full close
isLong: position.isLong,
acceptablePrice: position.markPrice,
orderType: "MarketDecrease",
receiveToken: position.collateralToken,
})
if (account) {
await queryClient.invalidateQueries({ queryKey: queryKeys.positions("stellar-mainnet", account) })
await queryClient.invalidateQueries({
queryKey: queryKeys.positions("stellar-mainnet", account),
})
}
} finally {
setClosing(null)
Expand Down Expand Up @@ -74,6 +109,7 @@ export function PositionsList({ onSelectPosition }: Props) {
<th className="px-4 py-2">Mark</th>
<th className="px-4 py-2">Liq.</th>
<th className="px-4 py-2">PnL</th>
<th className="px-4 py-2">Next Funding</th>
<th className="px-4 py-2" />
</tr>
</thead>
Expand Down Expand Up @@ -108,6 +144,9 @@ export function PositionsList({ onSelectPosition }: Props) {
{formatUsd(p.pnl)} ({formatPct(p.pnlPercent)})
</span>
</td>
<td className="px-4 py-2 font-mono tabular-nums text-muted-foreground">
{countdown}
</td>
<td className="px-4 py-2">
<Button
size="xs"
Expand Down
32 changes: 32 additions & 0 deletions apps/web/src/features/trade/hooks/useFundingRate.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import { useQuery } from "@tanstack/react-query"
import { queryKeys } from "../lib/query-keys"

const FUNDING_INTERVAL_MS = 8 * 60 * 60 * 1000 // 8-hour epochs

export type FundingRateInfo = {
ratePerHour: number
nextEpochTs: number // Unix ms timestamp of next funding settlement
}

function computeNextEpoch(): number {
const now = Date.now()
const elapsed = now % FUNDING_INTERVAL_MS
return now - elapsed + FUNDING_INTERVAL_MS
}

async function fetchFundingRate(): Promise<FundingRateInfo> {
// TODO: replace with on-chain DataStore read once contracts are deployed
return {
ratePerHour: 0.00005,
nextEpochTs: computeNextEpoch(),
}
}

export function useFundingRate() {
return useQuery<FundingRateInfo>({
queryKey: queryKeys.fundingRate("stellar-mainnet"),
queryFn: fetchFundingRate,
staleTime: 60_000,
refetchInterval: 60_000,
})
}
3 changes: 2 additions & 1 deletion apps/web/src/features/trade/hooks/usePositions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,7 @@ export function usePositions() {
queryFn: () => fetchPositions(account!),
enabled: !!account,
staleTime: 10_000,
refetchInterval: 15_000,
refetchInterval: 5_000,
refetchIntervalInBackground: false,
})
}
3 changes: 3 additions & 0 deletions apps/web/src/features/trade/lib/query-keys.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,4 +29,7 @@ export const queryKeys = {
// Trade history
tradeHistory: (chainId: string, account: string, page: number) =>
["tradeHistory", chainId, account, page] as const,

// Funding rate + next epoch timestamp
fundingRate: (chainId: string) => ["fundingRate", chainId] as const,
}
Loading