on 368f024 help sign in
bridge/src/store/lib/useResidentsStore.ts
104 lines 2.9 kB history raw
1import { useState, useCallback } from 'react';
2import { Just, Nothing } from 'folktale/maybe';
4import { azimuth } from 'azimuth-js';
6import { useNetwork } from 'store/network';
8import * as need from 'lib/need';
9import { isPlanet } from 'lib/utils/point';
11const emptyCacheEntry = {
12 residentCount: Nothing(),
13 requestCount: Nothing(),
14 residents: Nothing(),
15 requests: Nothing(),
16};
18export default function useResidents() {
19 const [residentCache, _setResidentCache] = useState({});
21 const addToResidentCache = useCallback(
22 (point, entry) =>
23 _setResidentCache(cache => ({ ...cache, [point]: entry })),
24 [_setResidentCache]
25 );
27 const getResidents = useCallback(
28 point => residentCache[point] || emptyCacheEntry,
29 [residentCache]
30 );
32 const { contracts } = useNetwork();
33 const _contracts = need.contracts(contracts);
35 const syncResidentCount = useCallback(
36 async point => {
37 // Do nothing if we've already fetched in full
38 // or we aren't a sponsor
39 const pointSize = azimuth.getPointSize(point);
40 if (Just.hasInstance(getResidents(point).residents)) {
41 return;
42 }
43 if (pointSize === azimuth.PointSize.Planet) {
44 addToResidentCache(point, {
45 residentCount: Just(0),
46 requestCount: Just(0),
47 requests: Just([]),
48 residents: Just([]),
49 });
50 return;
51 }
53 const isGalaxy = pointSize === azimuth.PointSize.Galaxy;
54 const [residentCount, requestCount] = await Promise.all([
55 azimuth.getSponsoringCount(_contracts, point),
56 azimuth.getEscapeRequestsCount(_contracts, point),
57 ]);
59 // Galaxies sponsor themselves
60 const parsedCount = Number(residentCount);
61 const _residentCount = isGalaxy ? parsedCount - 1 : parsedCount;
63 addToResidentCache(point, {
64 residentCount: Just(_residentCount),
65 requestCount: Just(Number(requestCount)),
66 residents: Nothing(),
67 requests: Nothing(),
68 });
69 },
70 [addToResidentCache, _contracts, getResidents]
71 );
73 const syncResidents = useCallback(
74 async point => {
75 if (isPlanet(point)) {
76 addToResidentCache(point, {
77 residentCount: Just(0),
78 requestCount: Just(0),
79 requests: Just([]),
80 residents: Just([]),
81 });
83 return;
84 }
85 const [residents, requests] = await Promise.all([
86 azimuth.getSponsoring(_contracts, point),
87 azimuth.getEscapeRequests(_contracts, point),
88 ]);
90 // Galaxies sponsor themselves
91 const _residents = residents.filter(r => r !== point);
93 addToResidentCache(point, {
94 residentCount: Just(_residents.length),
95 requestCount: Just(requests.length),
96 residents: Just(_residents),
97 requests: Just(requests),
98 });
99 },
100 [addToResidentCache, _contracts]
101 );
103 return { getResidents, syncResidentCount, syncResidents };