forked from StellarSend/frontend
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuseBatchPayment.ts
More file actions
131 lines (115 loc) · 3.62 KB
/
Copy pathuseBatchPayment.ts
File metadata and controls
131 lines (115 loc) · 3.62 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
import { useMutation } from '@tanstack/react-query'
import { useCallback, useState } from 'react'
import { batchPaymentApi } from '@/lib/api'
import { buildBatchPaymentTransaction, submitTransaction } from '@/lib/stellar'
import { useWallet } from './useWallet'
import { useSupportedAssets } from './useSendPayment'
import { useInvalidateTransactions } from './useTransactions'
import type { BatchPaymentFormValues, BatchPaymentResult } from '@/types'
export type BatchPaymentStep =
| 'form'
| 'review'
| 'signing'
| 'submitting'
| 'success'
| 'error'
interface BatchPaymentState {
step: BatchPaymentStep
formValues: BatchPaymentFormValues | null
result: BatchPaymentResult | null
error: string | null
}
export function useBatchPayment() {
const { publicKey, network, signTransaction, isConnected, refreshAccount } = useWallet()
const invalidateTxs = useInvalidateTransactions()
const supportedAssets = useSupportedAssets()
const [state, setState] = useState<BatchPaymentState>({
step: 'form',
formValues: null,
result: null,
error: null,
})
const totalAmount = state.formValues
? state.formValues.recipients.reduce((sum, r) => sum + (parseFloat(r.amount) || 0), 0)
: 0
const mutation = useMutation<BatchPaymentResult, Error, void>({
mutationFn: async () => {
if (!publicKey || !state.formValues) {
throw new Error('Missing required data to send a batch payment')
}
const values = state.formValues
const asset =
supportedAssets.find((a) => a.code === values.assetCode) ?? supportedAssets[0]
setState((s) => ({ ...s, step: 'signing' }))
const xdr = await buildBatchPaymentTransaction({
sourcePublicKey: publicKey,
asset,
recipients: values.recipients,
network,
})
const signedXdr = await signTransaction(xdr)
setState((s) => ({ ...s, step: 'submitting' }))
try {
return await batchPaymentApi.send({
sourcePublicKey: publicKey,
assetCode: asset.code,
assetIssuer: asset.issuer,
recipients: values.recipients,
signedXdr,
})
} catch {
const { hash } = await submitTransaction(signedXdr, network)
return {
batchId: hash,
transactionHash: hash,
status: 'success',
recipientCount: values.recipients.length,
totalAmount: totalAmount.toFixed(7),
createdAt: new Date().toISOString(),
}
}
},
onSuccess: (result) => {
setState((s) => ({ ...s, step: 'success', result, error: null }))
invalidateTxs()
refreshAccount()
},
onError: (err) => {
setState((s) => ({
...s,
step: 'error',
error: err.message || 'Batch payment failed. Please try again.',
}))
},
})
const reviewBatch = useCallback(
(values: BatchPaymentFormValues) => {
if (!isConnected || !publicKey) {
setState((s) => ({ ...s, error: 'Please connect your wallet first' }))
return
}
setState((s) => ({ ...s, step: 'review', formValues: values, error: null }))
},
[isConnected, publicKey],
)
const confirmBatch = useCallback(() => {
mutation.mutate()
}, [mutation])
const goBack = useCallback(() => {
setState((s) => ({ ...s, step: 'form', error: null }))
}, [])
const reset = useCallback(() => {
setState({ step: 'form', formValues: null, result: null, error: null })
mutation.reset()
}, [mutation])
return {
state,
reviewBatch,
confirmBatch,
goBack,
reset,
isSending: mutation.isPending,
totalAmount,
supportedAssets,
}
}