forked from FlowwStar/FlowStar
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuse-batch-create.ts
More file actions
206 lines (172 loc) · 5.55 KB
/
Copy pathuse-batch-create.ts
File metadata and controls
206 lines (172 loc) · 5.55 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
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
'use client'
import { useState, useCallback, useRef, useEffect } from 'react'
import { createStreamsBatch as createStreamsBatchCall } from '@/lib/contract'
import { invalidateStreams } from '@/hooks/use-streams'
import { useWallet } from '@/hooks/use-wallet'
import { useNetwork } from '@/components/providers/network-provider'
import type { CreateStreamInput, TokenInfo } from '@/types/stream'
export interface BatchStreamInput {
recipient: string
token: TokenInfo
totalAmount: bigint
startTime: bigint
endTime: bigint
cliffTime: bigint
cliffAmount: bigint
}
export interface BatchCreateProgress {
total: number
completed: number
failed: number
current: number
successIds: string[]
errors: Map<number, string>
isRunning: boolean
}
const DEFAULT_BATCH_DELAY = 2000 // 2 seconds between streams to avoid rate limiting
export function useBatchCreate() {
const { address, isConnected } = useWallet()
const { network } = useNetwork()
const [progress, setProgress] = useState<BatchCreateProgress>({
total: 0,
completed: 0,
failed: 0,
current: 0,
successIds: [],
errors: new Map(),
isRunning: false,
})
const abortRef = useRef(false)
const createBatch = useCallback(
async (
streams: BatchStreamInput[],
options?: { batchDelay?: number; onProgress?: (p: BatchCreateProgress) => void },
): Promise<BatchCreateProgress> => {
if (!isConnected || !address) {
throw new Error('Wallet not connected')
}
if (streams.length === 0) {
throw new Error('No streams to create')
}
if (streams.length > 100) {
throw new Error('Batch size exceeds maximum of 100 streams')
}
const { batchDelay = DEFAULT_BATCH_DELAY, onProgress } = options ?? {}
abortRef.current = false
const newProgress: BatchCreateProgress = {
total: streams.length,
completed: 0,
failed: 0,
current: 0,
successIds: [],
errors: new Map(),
isRunning: true,
}
setProgress(newProgress)
try {
const batchIds = await createStreamsBatchCall(
streams.map((stream) => ({
recipient: stream.recipient,
token: stream.token,
totalAmount: stream.totalAmount,
startTime: stream.startTime,
endTime: stream.endTime,
cliffTime: stream.cliffTime,
cliffAmount: stream.cliffAmount,
})),
address,
network,
)
newProgress.successIds.push(...batchIds)
newProgress.completed = streams.length
newProgress.failed = 0
} catch (err) {
const message = err instanceof Error ? err.message : 'Unknown error'
streams.forEach((_, index) => {
newProgress.errors.set(index, message)
})
newProgress.failed = streams.length
}
setProgress({ ...newProgress })
onProgress?.({ ...newProgress })
newProgress.isRunning = false
setProgress(newProgress)
onProgress?.(newProgress)
// Invalidate streams to refresh UI
invalidateStreams()
return newProgress
},
[address, isConnected],
)
const retryFailed = useCallback(
async (
streams: BatchStreamInput[],
failedIndices: number[],
options?: { batchDelay?: number; onProgress?: (p: BatchCreateProgress) => void },
): Promise<BatchCreateProgress> => {
if (!isConnected || !address) {
throw new Error('Wallet not connected')
}
const { batchDelay = DEFAULT_BATCH_DELAY, onProgress } = options ?? {}
abortRef.current = false
const newProgress: BatchCreateProgress = {
total: failedIndices.length,
completed: 0,
failed: 0,
current: 0,
successIds: [],
errors: new Map(),
isRunning: true,
}
setProgress(newProgress)
const retryStreams = failedIndices.map((index) => streams[index])
try {
const batchIds = await createStreamsBatchCall(
retryStreams.map((stream) => ({
recipient: stream.recipient,
token: stream.token,
totalAmount: stream.totalAmount,
startTime: stream.startTime,
endTime: stream.endTime,
cliffTime: stream.cliffTime,
cliffAmount: stream.cliffAmount,
})),
address,
network,
)
newProgress.successIds.push(...batchIds)
newProgress.completed = retryStreams.length
newProgress.failed = 0
retryStreams.forEach((_, index) => {
newProgress.errors.delete(failedIndices[index])
})
} catch (err) {
const message = err instanceof Error ? err.message : 'Unknown error'
failedIndices.forEach((index) => {
newProgress.errors.set(index, message)
})
newProgress.failed = failedIndices.length
}
setProgress({ ...newProgress })
onProgress?.({ ...newProgress })
newProgress.isRunning = false
setProgress(newProgress)
onProgress?.(newProgress)
invalidateStreams()
return newProgress
},
[address, isConnected],
)
const cancel = useCallback(() => {
abortRef.current = true
}, [])
// Automatically abort the running batch when the component unmounts so that
// in-progress state updates are not posted to an unmounted component.
// The cancel callback is stable (empty deps) so this effect runs only once.
useEffect(() => {
return () => {
abortRef.current = true
}
}, [])
return { progress, createBatch, retryFailed, cancel }
}