forked from xch-dev/sage
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuseTokenState.ts
More file actions
218 lines (192 loc) · 5.56 KB
/
Copy pathuseTokenState.ts
File metadata and controls
218 lines (192 loc) · 5.56 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
207
208
209
210
211
212
213
214
215
216
217
218
import { useState, useEffect, useMemo } from 'react';
import { useErrors } from '@/hooks/useErrors';
import { useWalletState } from '@/state';
import { usePrices } from '@/hooks/usePrices';
import { toDecimal } from '@/lib/utils';
import { RowSelectionState } from '@tanstack/react-table';
import {
CatRecord,
CoinRecord,
commands,
events,
TransactionResponse,
CoinSortMode,
} from '../bindings';
// Extend the TransactionResponse type to include additionalData
interface EnhancedTransactionResponse extends TransactionResponse {
additionalData?: {
title: string;
content: {
type: 'split' | 'combine';
coins: CoinRecord[];
outputCount?: number;
ticker: string;
precision: number;
};
};
}
export function useTokenState(assetId: string | undefined) {
const walletState = useWalletState();
const { getBalanceInUsd } = usePrices();
const { addError } = useErrors();
const [asset, setAsset] = useState<CatRecord | null>(null);
const [coins, setCoins] = useState<CoinRecord[]>([]);
const [response, setResponse] = useState<EnhancedTransactionResponse | null>(
null,
);
const [selectedCoins, setSelectedCoins] = useState<RowSelectionState>({});
const { receive_address } = walletState.sync;
const [currentPage, setCurrentPage] = useState<number>(0);
const [totalCoins, setTotalCoins] = useState<number>(0);
const [sortMode, setSortMode] = useState<CoinSortMode>('created_height');
const [sortDirection, setSortDirection] = useState<boolean>(false); // false = descending, true = ascending
const [includeSpentCoins, setIncludeSpentCoins] = useState<boolean>(false);
const pageSize = 10;
const precision = useMemo(
() => (assetId === 'xch' ? walletState.sync.unit.decimals : 3),
[assetId, walletState.sync.unit.decimals],
);
const balanceInUsd = useMemo(() => {
if (!asset) return '0';
return getBalanceInUsd(asset.asset_id, toDecimal(asset.balance, precision));
}, [asset, precision, getBalanceInUsd]);
const updateCoins = useMemo(
() =>
(page: number = currentPage) => {
const offset = page * pageSize;
const getCoins =
assetId === 'xch'
? commands.getXchCoins({
offset,
limit: pageSize,
sort_mode: sortMode,
ascending: sortDirection,
include_spent_coins: includeSpentCoins,
})
: commands.getCatCoins({
asset_id: assetId!,
offset,
limit: pageSize,
sort_mode: sortMode,
ascending: sortDirection,
include_spent_coins: includeSpentCoins,
});
getCoins
.then((res) => {
setCoins(res.coins);
setTotalCoins(res.total);
})
.catch(addError);
},
[
assetId,
addError,
pageSize,
currentPage,
sortMode,
sortDirection,
includeSpentCoins,
],
);
const updateCat = useMemo(
() => () => {
if (assetId === 'xch') return;
commands
.getCat({ asset_id: assetId! })
.then((res) => setAsset(res.cat))
.catch(addError);
},
[assetId, addError],
);
useEffect(() => {
updateCoins();
const unlisten = events.syncEvent.listen((event) => {
const type = event.payload.type;
if (type === 'coin_state' || type === 'puzzle_batch_synced') {
updateCoins();
}
});
return () => {
unlisten.then((u) => u());
};
}, [updateCoins]);
useEffect(() => {
if (assetId === 'xch') {
setAsset({
asset_id: 'xch',
name: 'Chia',
description: 'The native token of the Chia blockchain.',
ticker: walletState.sync.unit.ticker,
balance: walletState.sync.balance,
icon_url: 'https://icons.dexie.space/xch.webp',
visible: true,
});
} else {
updateCat();
const unlisten = events.syncEvent.listen((event) => {
const type = event.payload.type;
if (
type === 'coin_state' ||
type === 'puzzle_batch_synced' ||
type === 'cat_info'
) {
updateCat();
}
});
return () => {
unlisten.then((u) => u());
};
}
}, [assetId, updateCat, walletState.sync]);
const redownload = () => {
if (!assetId || assetId === 'xch') return;
commands
.resyncCat({ asset_id: assetId })
.then(() => updateCat())
.catch(addError);
};
const setVisibility = (visible: boolean) => {
if (!asset || assetId === 'xch') return;
const updatedAsset = { ...asset, visible };
commands.updateCat({ record: updatedAsset }).catch(addError);
};
const updateCatDetails = async (updatedAsset: CatRecord) => {
return commands
.updateCat({ record: updatedAsset })
.then(() => updateCat())
.catch(addError);
};
// Add effect to update coins when page changes
useEffect(() => {
updateCoins(currentPage);
}, [currentPage, updateCoins]);
// Reset to page 0 when sort parameters change
useEffect(() => {
setCurrentPage(0);
}, [sortMode, sortDirection, includeSpentCoins]);
return {
asset,
coins,
precision,
balanceInUsd,
response,
selectedCoins,
receive_address,
currentPage,
totalCoins,
pageSize,
sortMode,
sortDirection,
includeSpentCoins,
setResponse,
setSelectedCoins,
setCurrentPage,
setSortMode,
setSortDirection,
setIncludeSpentCoins,
redownload,
setVisibility,
updateCatDetails,
updateCoins,
};
}