forked from FlowwStar/FlowStar
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuse-stream-history.ts
More file actions
190 lines (166 loc) · 4.53 KB
/
Copy pathuse-stream-history.ts
File metadata and controls
190 lines (166 loc) · 4.53 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
'use client'
import { useState, useEffect, useCallback } from 'react'
import { useNetwork } from '@/components/providers/network-provider'
export type TimelineEventType =
| 'created'
| 'withdrawal'
| 'topup'
| 'transfer'
| 'cancellation'
export interface TimelineEvent {
type: TimelineEventType
txHash: string
timestamp: number
ledger: number
description: string
amount?: string
from?: string
to?: string
}
function decodeEventType(topics: string[]): TimelineEventType | null {
const joined = topics.join(',').toLowerCase()
if (joined.includes('create') || joined.includes('stream_created')) return 'created'
if (joined.includes('withdraw')) return 'withdrawal'
if (joined.includes('topup') || joined.includes('top_up') || joined.includes('deposit')) return 'topup'
if (joined.includes('transfer')) return 'transfer'
if (joined.includes('cancel')) return 'cancellation'
return null
}
interface HorizonTransaction {
hash: string
ledger: number
created_at: string
envelope_xdr?: string
}
async function fetchHorizonTransactions(
horizonUrl: string,
contractId: string,
streamId: string,
): Promise<TimelineEvent[]> {
if (!contractId) return []
const events: TimelineEvent[] = []
try {
const res = await fetch(
`${horizonUrl}/accounts/${contractId}/transactions?limit=200&order=desc`,
{ headers: { Accept: 'application/json' } },
)
if (!res.ok) return []
const data = await res.json() as { _embedded?: { records?: HorizonTransaction[] } }
const records = data._embedded?.records ?? []
for (const tx of records) {
events.push({
type: 'created',
txHash: tx.hash,
timestamp: new Date(tx.created_at).getTime(),
ledger: tx.ledger,
description: `Transaction on stream #${streamId}`,
})
}
} catch {
// Horizon may not index Soroban contract accounts — fall back to empty
}
return events
}
async function fetchRpcEvents(
rpcUrl: string,
contractId: string,
streamId: string,
): Promise<TimelineEvent[]> {
if (!contractId) return []
try {
const res = await fetch(rpcUrl, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
jsonrpc: '2.0',
id: 1,
method: 'getEvents',
params: {
startLedger: 1,
filters: [
{
type: 'contract',
contractIds: [contractId],
},
],
pagination: { limit: 200 },
},
}),
})
const json = await res.json() as {
result?: {
events?: Array<{
type: string
ledger: number
ledgerClosedAt: string
txHash: string
topic: string[]
value: { xdr: string }
}>
}
}
const raw = json.result?.events ?? []
const events: TimelineEvent[] = []
for (const ev of raw) {
const eventType = decodeEventType(ev.topic ?? [])
if (!eventType) continue
const ts = ev.ledgerClosedAt
? new Date(ev.ledgerClosedAt).getTime()
: Date.now()
let description = ''
switch (eventType) {
case 'created':
description = 'Stream created'
break
case 'withdrawal':
description = 'Withdrawal from stream'
break
case 'topup':
description = 'Stream topped up'
break
case 'transfer':
description = 'Stream transferred to new recipient'
break
case 'cancellation':
description = 'Stream cancelled'
break
}
events.push({
type: eventType,
txHash: ev.txHash ?? '',
timestamp: ts,
ledger: ev.ledger,
description,
})
}
return events
} catch {
return []
}
}
export function useStreamHistory(streamId: string) {
const { config, network } = useNetwork()
const [events, setEvents] = useState<TimelineEvent[]>([])
const [loading, setLoading] = useState(false)
const load = useCallback(async () => {
if (!streamId) return
setLoading(true)
try {
const rpcEvents = await fetchRpcEvents(
config.rpcUrl,
config.streamContractId,
streamId,
)
const allEvents = rpcEvents.sort((a, b) => b.timestamp - a.timestamp)
setEvents(allEvents)
} catch {
setEvents([])
} finally {
setLoading(false)
}
}, [streamId, config.rpcUrl, config.streamContractId])
useEffect(() => {
load()
}, [load])
return { events, loading, refetch: load }
}