on 30dcfcd help sign in
bridge/src/store/lib/useResidentsStore.js
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';
10const emptyCacheEntry = {
11 residentCount: Nothing(),
12 requestCount: Nothing(),
13 residents: Nothing(),
14 requests: Nothing(),
15};
17export default function useResidents() {
18 const [residentCache, _setResidentCache] = useState({});
20 const addToResidentCache = useCallback(
21 (point, entry) =>
22 _setResidentCache(cache => ({ ...cache, [point]: entry })),
23 [_setResidentCache]
24 );
26 const getResidents = useCallback(
27 point => residentCache[point] || emptyCacheEntry,
28 [residentCache]
29 );
31 const { contracts } = useNetwork();
32 const _contracts = need.contracts(contracts);
34 const syncResidentCount = useCallback(
35 async point => {
36 // Do nothing if we've already fetched in full
37 // or we aren't a sponsor
38 const pointSize = azimuth.getPointSize(point);
39 if (Just.hasInstance(getResidents(point).residents)) {
40 return;
41 }
42 if (pointSize === azimuth.PointSize.Planet) {
43 addToResidentCache(point, {
44 residentCount: Just(0),
45 requestCount: Just(0),
46 requests: Just([]),
47 residents: Just([]),
48 });
49 return;
50 }
52 const isGalaxy = pointSize === azimuth.PointSize.Galaxy;
53 const [residentCount, requestCount] = await Promise.all([
54 azimuth.getSponsoringCount(_contracts, point),
55 azimuth.getEscapeRequestsCount(_contracts, point),
56 ]);
58 // Galaxies sponsor themselves
59 const _residentCount = isGalaxy
60 ? residentCount.toNumber() - 1
61 : residentCount.toNumber();
63 addToResidentCache(point, {
64 residentCount: Just(_residentCount),
65 requestCount: Just(requestCount.toNumber()),
66 residents: Nothing(),
67 requests: Nothing(),
68 });
69 },
70 [addToResidentCache, _contracts, getResidents]
71 );
73 const syncResidents = useCallback(
74 async point => {
75 if (azimuth.getPointSize(point) === azimuth.PointSize.Planet) {
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 };