update app to use solana kit

This commit is contained in:
thesn10
2026-05-23 14:45:49 +02:00
parent c92e71fe81
commit 9b7391677c
13 changed files with 320 additions and 256 deletions

1
app/.gitignore vendored
View File

@@ -2,3 +2,4 @@
node_modules/
public/tamagui.generated.css
.env*.local
tsconfig.tsbuildinfo

View File

@@ -7,10 +7,9 @@
"start": "next start"
},
"dependencies": {
"@coral-xyz/anchor": "^0.32.1",
"@descro/sdk": "workspace:*",
"@solana/connector": "^0.2.4",
"@solana/web3.js": "^1.98.4",
"@solana/kit": "^6.0.0",
"@tamagui/config": "^2.0.0-rc.42",
"@tamagui/next-theme": "^2.0.0-rc.42",
"next": "^16.2.6",

View File

@@ -124,9 +124,9 @@ export default function PlaygroundPage() {
<YStack gap="$2">
{escrows.map((item) => (
<EscrowCard
key={item.pda.toBase58()}
key={item.pda}
item={item}
selected={selected?.pda.equals(item.pda) ?? false}
selected={selected?.pda === item.pda}
onSelect={() => setSelected(item)}
/>
))}

View File

@@ -1,21 +1,32 @@
'use client'
import { useState, useMemo } from 'react'
import { useState } from 'react'
import { YStack, XStack, Text, Button, Input, Spinner } from 'tamagui'
import { PublicKey, Transaction, Connection } from '@solana/web3.js'
import { AnchorProvider } from '@coral-xyz/anchor'
import { useTransactionSigner, useDisconnectWallet, useCluster } from '@solana/connector/react'
import { useWalletAdapterCompat } from '@solana/connector/compat'
import BN from 'bn.js'
import { EscrowClient } from '@descro/sdk'
import {
createSolanaRpc,
createSolanaRpcSubscriptions,
pipe,
createTransactionMessage,
setTransactionMessageFeePayerSigner,
setTransactionMessageLifetimeUsingBlockhash,
appendTransactionMessageInstructions,
signTransactionMessageWithSigners,
sendAndConfirmTransactionFactory,
assertIsTransactionWithBlockhashLifetime,
getSignatureFromTransaction,
address as kitAddress,
} from '@solana/kit'
import { useKitTransactionSigner, useWallet, useCluster } from '@solana/connector/react'
import { getCreateEscrowInstructionAsync } from '@descro/sdk'
import type { Address } from '@descro/sdk'
function getNextEscrowId(walletPubkey: string): BN {
const key = `descro_escrow_id_${walletPubkey}`
function getNextEscrowId(walletAddress: string): bigint {
const key = `descro_escrow_id_${walletAddress}`
const stored = localStorage.getItem(key)
const current = stored ? parseInt(stored, 10) : 0
const next = current + 1
localStorage.setItem(key, next.toString())
return new BN(next)
return BigInt(next)
}
interface CreateEscrowFormProps {
@@ -23,17 +34,10 @@ interface CreateEscrowFormProps {
}
export function CreateEscrowForm({ onCreated }: CreateEscrowFormProps) {
const { signer } = useTransactionSigner()
const { disconnect } = useDisconnectWallet()
const { signer } = useKitTransactionSigner()
const { account: address } = useWallet()
const { cluster } = useCluster()
const walletAdapter = useWalletAdapterCompat(signer, disconnect)
const connection = useMemo(
() => (cluster?.url ? new Connection(cluster.url, 'confirmed') : null),
[cluster?.url],
)
const publicKey = walletAdapter.publicKey ? new PublicKey(walletAdapter.publicKey.toString()) : null
const rpcUrl = cluster?.url ?? null
const [buyer, setBuyer] = useState('')
const [amountSol, setAmountSol] = useState('')
@@ -47,29 +51,30 @@ export function CreateEscrowForm({ onCreated }: CreateEscrowFormProps) {
setError(null)
setSuccess(null)
if (!publicKey || !connection) {
if (!signer || !address || !rpcUrl) {
setError('Connect your wallet first.')
return
}
let buyerPk: PublicKey
let buyerAddress: Address
try {
buyerPk = new PublicKey(buyer)
buyerAddress = kitAddress(buyer)
} catch {
setError('Invalid buyer public key.')
return
}
const amountLamports = parseFloat(amountSol)
if (isNaN(amountLamports) || amountLamports <= 0) {
const amountSolNum = parseFloat(amountSol)
if (isNaN(amountSolNum) || amountSolNum <= 0) {
setError('Invalid SOL amount.')
return
}
const amountLamports = BigInt(Math.round(amountSolNum * 1e9))
let resolverPk: PublicKey | null = null
let resolverAddress: Address | null = null
if (resolver.trim()) {
try {
resolverPk = new PublicKey(resolver.trim())
resolverAddress = kitAddress(resolver.trim())
} catch {
setError('Invalid resolver public key.')
return
@@ -78,29 +83,33 @@ export function CreateEscrowForm({ onCreated }: CreateEscrowFormProps) {
setLoading(true)
try {
const provider = new AnchorProvider(
connection,
{ publicKey, signTransaction: walletAdapter.signTransaction!.bind(walletAdapter) } as never,
{},
)
const client = new EscrowClient(provider)
const escrowId = getNextEscrowId(publicKey.toBase58())
const amount = new BN(Math.round(amountLamports * 1e9))
const rpc = createSolanaRpc(rpcUrl)
const rpcSubscriptions = createSolanaRpcSubscriptions(rpcUrl.replace('http', 'ws'))
const escrowId = getNextEscrowId(address)
const ix = await client.buildCreateEscrow({
seller: publicKey,
buyer: buyerPk,
amount,
disputeResolver: resolverPk,
const ix = await getCreateEscrowInstructionAsync({
seller: signer,
buyer: buyerAddress,
amount: amountLamports,
disputeResolver: resolverAddress,
escrowId,
})
const { blockhash, lastValidBlockHeight } = await connection.getLatestBlockhash()
const tx = new Transaction({ blockhash, lastValidBlockHeight, feePayer: publicKey }).add(ix)
const sig = await walletAdapter.sendTransaction(tx, connection)
await connection.confirmTransaction({ signature: sig, blockhash, lastValidBlockHeight }, 'confirmed')
const { value: latestBlockhash } = await rpc.getLatestBlockhash().send()
setSuccess(`Escrow #${escrowId.toString()} created! Tx: ${sig.slice(0, 16)}`)
const txMsg = pipe(
createTransactionMessage({ version: 0 }),
(tx) => setTransactionMessageFeePayerSigner(signer, tx),
(tx) => setTransactionMessageLifetimeUsingBlockhash(latestBlockhash, tx),
(tx) => appendTransactionMessageInstructions([ix as never], tx),
)
const signed = await signTransactionMessageWithSigners(txMsg)
assertIsTransactionWithBlockhashLifetime(signed)
await sendAndConfirmTransactionFactory({ rpc, rpcSubscriptions })(signed, { commitment: 'confirmed' })
const sig = getSignatureFromTransaction(signed)
setSuccess(`Escrow #${escrowId} created! Tx: ${sig.slice(0, 16)}`)
setBuyer('')
setAmountSol('')
setResolver('')
@@ -164,7 +173,7 @@ export function CreateEscrowForm({ onCreated }: CreateEscrowFormProps) {
<Button
theme="active"
onPress={handleSubmit as unknown as () => void}
disabled={loading || !publicKey}
disabled={loading || !address}
icon={loading ? <Spinner /> : undefined}
>
{loading ? 'Creating…' : 'Create Escrow'}

View File

@@ -4,11 +4,8 @@ import React from 'react'
import { YStack, XStack, Text } from 'tamagui'
import { StatusBadge } from './StatusBadge'
import type { EscrowAccountWithPda } from '@descro/sdk'
import { PublicKey } from '@solana/web3.js'
function truncPubkey(pk: PublicKey): string {
const s = pk.toBase58()
return `${s.slice(0, 4)}${s.slice(-4)}`
function truncAddr(addr: string): string {
return `${addr.slice(0, 4)}${addr.slice(-4)}`
}
interface EscrowCardProps {
@@ -47,16 +44,16 @@ export function EscrowCard({ item, selected, onSelect }: EscrowCardProps) {
<XStack gap="$4">
<YStack>
<Text fontSize={11} color="$color10">Seller</Text>
<Text fontSize={12} fontFamily="monospace">{truncPubkey(account.seller)}</Text>
<Text fontSize={12} fontFamily="monospace">{truncAddr(account.seller)}</Text>
</YStack>
<YStack>
<Text fontSize={11} color="$color10">Buyer</Text>
<Text fontSize={12} fontFamily="monospace">{truncPubkey(account.buyer)}</Text>
<Text fontSize={12} fontFamily="monospace">{truncAddr(account.buyer)}</Text>
</YStack>
</XStack>
<Text fontSize={11} color="$color10" fontFamily="monospace">
PDA: {truncPubkey(pda)}
PDA: {truncAddr(pda)}
</Text>
</YStack>
)

View File

@@ -1,13 +1,36 @@
'use client'
import { useState, useMemo } from 'react'
import { useState } from 'react'
import { YStack, XStack, Text, Button, Spinner, Separator } from 'tamagui'
import { PublicKey, Transaction, Connection } from '@solana/web3.js'
import { AnchorProvider } from '@coral-xyz/anchor'
import { useTransactionSigner, useDisconnectWallet, useCluster } from '@solana/connector/react'
import { useWalletAdapterCompat } from '@solana/connector/compat'
import {
createSolanaRpc,
createSolanaRpcSubscriptions,
pipe,
createTransactionMessage,
setTransactionMessageFeePayerSigner,
setTransactionMessageLifetimeUsingBlockhash,
appendTransactionMessageInstructions,
signTransactionMessageWithSigners,
sendAndConfirmTransactionFactory,
assertIsTransactionWithBlockhashLifetime,
getSignatureFromTransaction,
isSome,
} from '@solana/kit'
import { useKitTransactionSigner, useWallet, useCluster } from '@solana/connector/react'
import { StatusBadge } from './StatusBadge'
import { EscrowClient, isAwaitingDeposit, isActive, isDisputed } from '@descro/sdk'
import {
isAwaitingDeposit,
isActive,
isDisputed,
getDepositInstructionAsync,
getCancelInstruction,
getCompleteInstructionAsync,
getDisputeInstruction,
getResolveInstructionAsync,
findResolverEntryPda,
DESCRO_EXT_RESOLVERS_PROGRAM_ADDRESS,
Winner,
} from '@descro/sdk'
import type { EscrowAccountWithPda } from '@descro/sdk'
import { useEscrowDetail } from '@/hooks/useEscrowDetail'
@@ -16,41 +39,28 @@ interface EscrowDetailProps {
onAction?: () => void
}
function fullPubkey(pk: PublicKey): string {
return pk.toBase58()
}
export function EscrowDetail({ item, onAction }: EscrowDetailProps) {
const { pda } = item
const { account, loading: detailLoading } = useEscrowDetail(pda)
const escrow = account ?? item.account
const { signer } = useTransactionSigner()
const { disconnect } = useDisconnectWallet()
const { signer } = useKitTransactionSigner()
const { account: address } = useWallet()
const { cluster } = useCluster()
const walletAdapter = useWalletAdapterCompat(signer, disconnect)
const connection = useMemo(
() => (cluster?.url ? new Connection(cluster.url, 'confirmed') : null),
[cluster?.url],
)
const publicKey = walletAdapter.publicKey ? new PublicKey(walletAdapter.publicKey.toString()) : null
const rpcUrl = cluster?.url ?? null
const [loading, setLoading] = useState(false)
const [error, setError] = useState<string | null>(null)
const [success, setSuccess] = useState<string | null>(null)
const solAmount = (Number(escrow.amount.toString()) / 1e9).toFixed(4)
const isSeller = publicKey?.equals(escrow.seller) ?? false
const isBuyer = publicKey?.equals(escrow.buyer) ?? false
const isResolver =
escrow.disputeResolver != null && publicKey?.equals(escrow.disputeResolver) === true
const solAmount = (Number(escrow.amount) / 1e9).toFixed(4)
const isSeller = address != null && address === escrow.seller
const isBuyer = address != null && address === escrow.buyer
const resolverAddr = isSome(escrow.disputeResolver) ? escrow.disputeResolver.value : null
const isResolver = address != null && resolverAddr != null && address === resolverAddr
async function runTx(
buildFn: (client: EscrowClient) => Promise<import('@solana/web3.js').TransactionInstruction>,
) {
if (!publicKey || !connection || !walletAdapter.signTransaction) {
async function runTx(buildIx: () => Promise<unknown>) {
if (!signer || !address || !rpcUrl) {
setError('Connect your wallet first.')
return
}
@@ -58,17 +68,20 @@ export function EscrowDetail({ item, onAction }: EscrowDetailProps) {
setError(null)
setSuccess(null)
try {
const provider = new AnchorProvider(
connection,
{ publicKey, signTransaction: walletAdapter.signTransaction.bind(walletAdapter) } as never,
{},
const rpc = createSolanaRpc(rpcUrl)
const rpcSubscriptions = createSolanaRpcSubscriptions(rpcUrl.replace('http', 'ws'))
const ix = await buildIx()
const { value: latestBlockhash } = await rpc.getLatestBlockhash().send()
const txMsg = pipe(
createTransactionMessage({ version: 0 }),
(tx) => setTransactionMessageFeePayerSigner(signer, tx),
(tx) => setTransactionMessageLifetimeUsingBlockhash(latestBlockhash, tx),
(tx) => appendTransactionMessageInstructions([ix as never], tx),
)
const client = new EscrowClient(provider)
const ix = await buildFn(client)
const { blockhash, lastValidBlockHeight } = await connection.getLatestBlockhash()
const tx = new Transaction({ blockhash, lastValidBlockHeight, feePayer: publicKey }).add(ix)
const sig = await walletAdapter.sendTransaction(tx, connection)
await connection.confirmTransaction({ signature: sig, blockhash, lastValidBlockHeight }, 'confirmed')
const signed = await signTransactionMessageWithSigners(txMsg)
assertIsTransactionWithBlockhashLifetime(signed)
await sendAndConfirmTransactionFactory({ rpc, rpcSubscriptions })(signed, { commitment: 'confirmed' })
const sig = getSignatureFromTransaction(signed)
setSuccess(`Done! Tx: ${sig.slice(0, 20)}`)
onAction?.()
} catch (err: unknown) {
@@ -79,31 +92,33 @@ export function EscrowDetail({ item, onAction }: EscrowDetailProps) {
}
const handleDeposit = () =>
runTx((client) => client.buildDeposit({ buyer: publicKey!, escrowPda: pda }))
runTx(() => getDepositInstructionAsync({ buyer: signer!, escrowAccount: pda }))
const handleCancel = () =>
runTx((client) => client.buildCancel({ seller: publicKey!, escrowPda: pda }))
runTx(async () => getCancelInstruction({ seller: signer!, escrowAccount: pda }))
const handleComplete = () =>
runTx((client) =>
client.buildComplete({ buyer: publicKey!, seller: escrow.seller, escrowPda: pda }),
runTx(() =>
getCompleteInstructionAsync({ buyer: signer!, seller: escrow.seller, escrowAccount: pda }),
)
const handleDispute = () =>
runTx((client) => client.buildDispute({ initiator: publicKey!, escrowPda: pda }))
runTx(async () => getDisputeInstruction({ initiator: signer!, escrowAccount: pda }))
const handleResolve = (winner: 'buyer' | 'seller') => {
const winnerPubkey = winner === 'buyer' ? escrow.buyer : escrow.seller
runTx((client) =>
client.buildResolve({
resolver: publicKey!,
winner,
winnerPubkey,
if (!resolverAddr) return
runTx(async () => {
const [resolverEntryAddr] = await findResolverEntryPda({ authority: resolverAddr })
return getResolveInstructionAsync({
resolver: signer!,
winner: winner === 'buyer' ? escrow.buyer : escrow.seller,
seller: escrow.seller,
escrowPda: pda,
disputeResolver: escrow.disputeResolver,
}),
)
escrowAccount: pda,
resolverEntry: resolverEntryAddr,
registryProgram: DESCRO_EXT_RESOLVERS_PROGRAM_ADDRESS,
winnerArg: winner === 'buyer' ? Winner.Buyer : Winner.Seller,
})
})
}
void detailLoading
@@ -121,14 +136,14 @@ export function EscrowDetail({ item, onAction }: EscrowDetailProps) {
<YStack gap="$2">
<Row label="Amount" value={`${solAmount} SOL`} />
<Row label="Seller" value={fullPubkey(escrow.seller)} mono />
<Row label="Buyer" value={fullPubkey(escrow.buyer)} mono />
<Row label="Seller" value={escrow.seller} mono />
<Row label="Buyer" value={escrow.buyer} mono />
<Row
label="Resolver"
value={escrow.disputeResolver ? fullPubkey(escrow.disputeResolver) : 'None'}
mono={!!escrow.disputeResolver}
value={resolverAddr ?? 'None'}
mono={!!resolverAddr}
/>
<Row label="PDA" value={fullPubkey(pda)} mono />
<Row label="PDA" value={pda} mono />
</YStack>
<Separator />

View File

@@ -1,39 +1,47 @@
'use client'
import React, { useState, useEffect, useMemo } from 'react'
import React, { useState, useEffect } from 'react'
import { YStack, XStack, Text, Button, Input, Spinner, Separator } from 'tamagui'
import { PublicKey, Transaction, Connection } from '@solana/web3.js'
import { AnchorProvider } from '@coral-xyz/anchor'
import { useTransactionSigner, useDisconnectWallet, useCluster } from '@solana/connector/react'
import { useWalletAdapterCompat } from '@solana/connector/compat'
import { RegistryClient, resolverTypeLabel } from '@descro/sdk'
import type { ResolverEntryWithPda, ResolverType } from '@descro/sdk'
import {
createSolanaRpc,
createSolanaRpcSubscriptions,
pipe,
createTransactionMessage,
setTransactionMessageFeePayerSigner,
setTransactionMessageLifetimeUsingBlockhash,
appendTransactionMessageInstructions,
signTransactionMessageWithSigners,
sendAndConfirmTransactionFactory,
assertIsTransactionWithBlockhashLifetime,
getSignatureFromTransaction,
address as kitAddress,
} from '@solana/kit'
import { useKitTransactionSigner, useWallet, useCluster } from '@solana/connector/react'
import {
fetchAllResolvers,
getRegisterResolverInstructionAsync,
resolverTypeLabel,
ResolverType,
} from '@descro/sdk'
import type { ResolverEntryWithPda } from '@descro/sdk'
const RESOLVER_TYPE_OPTIONS: { label: string; value: ResolverType }[] = [
{ label: 'CentralAuthority', value: { centralAuthority: {} } },
{ label: 'JuryDAO', value: { juryDAO: {} } },
{ label: 'MAD', value: { mad: {} } },
{ label: 'Algorithmic', value: { algorithmic: {} } },
{ label: 'Multisig', value: { multisig: {} } },
{ label: 'CentralAuthority', value: ResolverType.CentralAuthority },
{ label: 'JuryDAO', value: ResolverType.JuryDAO },
{ label: 'MAD', value: ResolverType.MAD },
{ label: 'Algorithmic', value: ResolverType.Algorithmic },
{ label: 'Multisig', value: ResolverType.Multisig },
]
function truncPk(pk: PublicKey): string {
const s = pk.toBase58()
return `${s.slice(0, 4)}${s.slice(-4)}`
function truncAddr(addr: string): string {
return `${addr.slice(0, 4)}${addr.slice(-4)}`
}
export function ResolverPanel() {
const { signer } = useTransactionSigner()
const { disconnect } = useDisconnectWallet()
const { signer } = useKitTransactionSigner()
const { account: address } = useWallet()
const { cluster } = useCluster()
const walletAdapter = useWalletAdapterCompat(signer, disconnect)
const connection = useMemo(
() => (cluster?.url ? new Connection(cluster.url, 'confirmed') : null),
[cluster?.url],
)
const publicKey = walletAdapter.publicKey ? new PublicKey(walletAdapter.publicKey.toString()) : null
const rpcUrl = cluster?.url ?? null
const [resolvers, setResolvers] = useState<ResolverEntryWithPda[]>([])
const [resolversLoading, setResolversLoading] = useState(false)
@@ -50,12 +58,11 @@ export function ResolverPanel() {
const [success, setSuccess] = useState<string | null>(null)
async function loadResolvers() {
if (!connection) return
if (!rpcUrl) return
setResolversLoading(true)
try {
const provider = new AnchorProvider(connection, {} as never, {})
const client = new RegistryClient(provider)
const all = await client.fetchAllResolvers()
const rpc = createSolanaRpc(rpcUrl)
const all = await fetchAllResolvers(rpc)
setResolvers(all)
} catch (err) {
console.error('Failed to load resolvers', err)
@@ -67,22 +74,22 @@ export function ResolverPanel() {
useEffect(() => {
loadResolvers()
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [connection])
}, [rpcUrl])
async function handleRegister(e: React.FormEvent) {
e.preventDefault()
setError(null)
setSuccess(null)
if (!publicKey || !connection || !walletAdapter.signTransaction) {
if (!signer || !address || !rpcUrl) {
setError('Connect your wallet first.')
return
}
let recipientPk: PublicKey
const recipientStr = feeRecipient.trim() || publicKey.toBase58()
let recipientAddr
const recipientStr = feeRecipient.trim() || address
try {
recipientPk = new PublicKey(recipientStr)
recipientAddr = kitAddress(recipientStr)
} catch {
setError('Invalid fee recipient public key.')
return
@@ -101,28 +108,31 @@ export function ResolverPanel() {
setFormLoading(true)
try {
const provider = new AnchorProvider(
connection,
{ publicKey, signTransaction: walletAdapter.signTransaction.bind(walletAdapter) } as never,
{},
)
const client = new RegistryClient(provider)
const rpc = createSolanaRpc(rpcUrl)
const rpcSubscriptions = createSolanaRpcSubscriptions(rpcUrl.replace('http', 'ws'))
const resolverType = RESOLVER_TYPE_OPTIONS[resolverTypeIdx].value
const ix = await client.buildRegisterResolver({
authority: publicKey,
const ix = await getRegisterResolverInstructionAsync({
authority: signer,
resolverType,
name: name.trim(),
description: description.trim(),
feeBps: fee,
feeRecipient: recipientPk,
feeRecipient: recipientAddr,
metadataUri: metadataUri.trim(),
})
const { blockhash, lastValidBlockHeight } = await connection.getLatestBlockhash()
const tx = new Transaction({ blockhash, lastValidBlockHeight, feePayer: publicKey }).add(ix)
const sig = await walletAdapter.sendTransaction(tx, connection)
await connection.confirmTransaction({ signature: sig, blockhash, lastValidBlockHeight }, 'confirmed')
const { value: latestBlockhash } = await rpc.getLatestBlockhash().send()
const txMsg = pipe(
createTransactionMessage({ version: 0 }),
(tx) => setTransactionMessageFeePayerSigner(signer, tx),
(tx) => setTransactionMessageLifetimeUsingBlockhash(latestBlockhash, tx),
(tx) => appendTransactionMessageInstructions([ix as never], tx),
)
const signed = await signTransactionMessageWithSigners(txMsg)
assertIsTransactionWithBlockhashLifetime(signed)
await sendAndConfirmTransactionFactory({ rpc, rpcSubscriptions })(signed, { commitment: 'confirmed' })
const sig = getSignatureFromTransaction(signed)
setSuccess(`Registered! Tx: ${sig.slice(0, 20)}`)
setName('')
@@ -156,7 +166,7 @@ export function ResolverPanel() {
{resolvers.map(({ pda, account }) => (
<YStack
key={pda.toBase58()}
key={pda}
padding="$3"
borderRadius="$3"
borderWidth={1}
@@ -177,7 +187,7 @@ export function ResolverPanel() {
<Text fontSize={12} color="$orange9">S: {account.ruledForSeller.toString()}</Text>
</XStack>
<Text fontSize={11} color="$color10" style={{ fontFamily: 'monospace' }}>
{truncPk(account.authority)}
{truncAddr(account.authority)}
</Text>
</YStack>
))}
@@ -241,7 +251,7 @@ export function ResolverPanel() {
<Button
theme="active"
onPress={handleRegister as unknown as () => void}
disabled={formLoading || !publicKey}
disabled={formLoading || !address}
icon={formLoading ? <Spinner /> : undefined}
>
{formLoading ? 'Registering…' : 'Register'}

View File

@@ -1,40 +1,33 @@
'use client'
import { useState, useEffect, useRef, useMemo } from 'react'
import { PublicKey, Connection } from '@solana/web3.js'
import { useState, useEffect } from 'react'
import { createSolanaRpc, createSolanaRpcSubscriptions } from '@solana/kit'
import { useCluster } from '@solana/connector/react'
import { AnchorProvider } from '@coral-xyz/anchor'
import { EscrowClient, subscribeEscrow } from '@descro/sdk'
import type { EscrowAccount } from '@descro/sdk'
import { fetchMaybeEscrowAccount, subscribeEscrow } from '@descro/sdk'
import type { Address, EscrowAccount } from '@descro/sdk'
export function useEscrowDetail(pda: PublicKey | null) {
export function useEscrowDetail(pda: Address | null) {
const { cluster } = useCluster()
const connection = useMemo(
() => (cluster?.url ? new Connection(cluster.url) : null),
[cluster?.url],
)
const rpcUrl = cluster?.url ?? null
const [account, setAccount] = useState<EscrowAccount | null>(null)
const [loading, setLoading] = useState(false)
const [error, setError] = useState<string | null>(null)
const unsubRef = useRef<(() => void) | null>(null)
useEffect(() => {
if (!pda || !connection) {
if (!pda || !rpcUrl) {
setAccount(null)
return
}
let cancelled = false
setLoading(true)
const provider = new AnchorProvider(connection, {} as never, {})
const client = new EscrowClient(provider)
const rpc = createSolanaRpc(rpcUrl)
client
.fetchEscrow(pda)
.then((acc) => {
fetchMaybeEscrowAccount(rpc, pda)
.then((maybeAcc) => {
if (!cancelled) {
setAccount(acc)
setAccount(maybeAcc.exists ? maybeAcc.data : null)
setError(null)
}
})
@@ -45,17 +38,17 @@ export function useEscrowDetail(pda: PublicKey | null) {
if (!cancelled) setLoading(false)
})
const unsub = subscribeEscrow(connection, pda, (updated) => {
const wsUrl = rpcUrl.replace('http', 'ws')
const rpcSubscriptions = createSolanaRpcSubscriptions(wsUrl)
const unsub = subscribeEscrow(rpcSubscriptions, pda, (updated) => {
if (!cancelled) setAccount(updated)
})
unsubRef.current = unsub
return () => {
cancelled = true
unsub()
unsubRef.current = null
}
}, [pda?.toBase58(), connection])
}, [pda, rpcUrl])
return { account, loading, error }
}

View File

@@ -1,23 +1,17 @@
'use client'
import { useState, useEffect, useCallback, useRef, useMemo } from 'react'
import { Connection, PublicKey } from '@solana/web3.js'
import { useTransactionSigner, useCluster } from '@solana/connector/react'
import { AnchorProvider } from '@coral-xyz/anchor'
import { EscrowClient } from '@descro/sdk'
import { useState, useEffect, useCallback, useRef } from 'react'
import { createSolanaRpc } from '@solana/kit'
import { useWallet, useCluster } from '@solana/connector/react'
import { fetchEscrowsForWallet } from '@descro/sdk'
import type { EscrowAccountWithPda } from '@descro/sdk'
const POLL_INTERVAL_MS = 5000
export function useEscrows() {
const { address } = useTransactionSigner()
const { account: address } = useWallet()
const { cluster } = useCluster()
const publicKey = useMemo(() => (address ? new PublicKey(address) : null), [address])
const connection = useMemo(
() => (cluster?.url ? new Connection(cluster.url) : null),
[cluster?.url],
)
const rpcUrl = cluster?.url ?? null
const [escrows, setEscrows] = useState<EscrowAccountWithPda[]>([])
const [loading, setLoading] = useState(false)
@@ -25,23 +19,20 @@ export function useEscrows() {
const intervalRef = useRef<ReturnType<typeof setInterval> | null>(null)
const fetchEscrows = useCallback(async () => {
if (!publicKey || !connection) {
if (!address || !rpcUrl) {
setEscrows([])
return
}
try {
const provider = new AnchorProvider(connection, {} as never, {})
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()),
)
const rpc = createSolanaRpc(rpcUrl)
const results = await fetchEscrowsForWallet(rpc, address)
results.sort((a, b) => Number(b.account.escrowId - a.account.escrowId))
setEscrows(results)
setError(null)
} catch (err: unknown) {
setError(err instanceof Error ? err.message : String(err))
}
}, [publicKey, connection])
}, [address, rpcUrl])
useEffect(() => {
setLoading(true)

View File

@@ -1,6 +1,6 @@
{
"compilerOptions": {
"target": "ES2017",
"target": "ES2020",
"lib": [
"dom",
"dom.iterable",