-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathuseRecord.ts
71 lines (66 loc) · 1.97 KB
/
useRecord.ts
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
import type { ChainUniqueId } from "core/types/ChainUniqueId";
import { useCallback, useEffect, useMemo, useState } from "react";
import { useCoinService } from "./useCoinService";
import { RecordFilter } from "@/scripts/background/servers/IWalletServer";
import { chainUniqueIdToCoinType } from "core/helper/CoinType";
import { CoinType } from "core/types";
import { type RecordDetailWithSpent } from "core/coins/ALEO/types/SyncTask";
import { NATIVE_TOKEN_PROGRAM_ID } from "core/coins/ALEO/constants";
export const useRecords = ({
uniqueId,
address,
recordFilter = RecordFilter.UNSPENT,
programId = NATIVE_TOKEN_PROGRAM_ID,
}: {
uniqueId: ChainUniqueId;
address: string;
recordFilter?: RecordFilter;
programId?: string;
}) => {
const { coinService } = useCoinService(uniqueId);
const coinType = useMemo(() => {
return chainUniqueIdToCoinType(uniqueId);
}, [uniqueId]);
const [loading, setLoading] = useState(false);
const [records, setRecords] = useState<RecordDetailWithSpent[]>([]);
const fetchRecords = useCallback(async () => {
if (coinType !== CoinType.ALEO) {
return;
}
setLoading(true);
try {
const result = await coinService.getRecords(
address,
programId,
recordFilter,
);
const nonZeroRecords = result.filter((record) => {
return record.parsedContent?.microcredits !== 0n;
});
setRecords([...nonZeroRecords]);
} catch (err) {
console.log("===> fetch record error: ", err);
setRecords([]);
} finally {
setLoading(false);
}
}, [coinType, coinService, address, programId, recordFilter]);
useEffect(() => {
void fetchRecords();
}, [fetchRecords]);
const res = useMemo(() => {
if (coinType !== CoinType.ALEO) {
return {
loading: false,
records,
fetchRecords,
};
}
return {
loading,
records,
fetchRecords,
};
}, [coinType, loading, records, fetchRecords]);
return res;
};