51 lines
1.6 KiB
TypeScript
51 lines
1.6 KiB
TypeScript
'use client'
|
|
|
|
import { useState, useEffect, useCallback, useRef } from 'react'
|
|
import { useWallet, useConnection } from '@solana/wallet-adapter-react'
|
|
import { AnchorProvider } from '@coral-xyz/anchor'
|
|
import { EscrowClient } from '@descro/sdk'
|
|
import type { EscrowAccountWithPda } from '@descro/sdk'
|
|
|
|
const POLL_INTERVAL_MS = 5000
|
|
|
|
export function useEscrows() {
|
|
const { publicKey } = useWallet()
|
|
const { connection } = useConnection()
|
|
const [escrows, setEscrows] = useState<EscrowAccountWithPda[]>([])
|
|
const [loading, setLoading] = useState(false)
|
|
const [error, setError] = useState<string | null>(null)
|
|
const intervalRef = useRef<ReturnType<typeof setInterval> | null>(null)
|
|
|
|
const fetchEscrows = useCallback(async () => {
|
|
if (!publicKey) {
|
|
setEscrows([])
|
|
return
|
|
}
|
|
try {
|
|
const provider = new AnchorProvider(connection, {} as any, {})
|
|
const client = new EscrowClient(provider)
|
|
const results = await client.fetchEscrowsForWallet(publicKey)
|
|
results.sort((a, b) =>
|
|
Number(b.account.escrowId.toString()) - Number(a.account.escrowId.toString())
|
|
)
|
|
setEscrows(results)
|
|
setError(null)
|
|
} catch (err: unknown) {
|
|
setError(err instanceof Error ? err.message : String(err))
|
|
}
|
|
}, [publicKey, connection])
|
|
|
|
useEffect(() => {
|
|
setLoading(true)
|
|
fetchEscrows().finally(() => setLoading(false))
|
|
|
|
intervalRef.current = setInterval(fetchEscrows, POLL_INTERVAL_MS)
|
|
|
|
return () => {
|
|
if (intervalRef.current !== null) clearInterval(intervalRef.current)
|
|
}
|
|
}, [fetchEscrows])
|
|
|
|
return { escrows, loading, error, refresh: fetchEscrows }
|
|
}
|