on fd7895b help sign in
bridge/src/store/lib/useInvitesStore.js
71 lines 2.0 kB history raw
1import { useCallback } from 'react';
2import { Just, Nothing } from 'folktale/maybe';
3import * as azimuth from 'azimuth-js';
4import { chain } from 'lodash';
6import { useNetwork } from '../network';
7import useSetState from 'lib/useSetState';
9// the default value of a point's invites
10const EMPTY_INVITES = {
11 availableInvites: Nothing(),
12 sentInvites: Nothing(),
13 acceptedInvites: Nothing(),
14 acceptedPoints: Nothing(),
15 pendingPoints: Nothing(),
16};
18export default function useInvitesStore() {
19 const { contracts } = useNetwork();
20 const [invitesCache, addToInvitesCache] = useSetState({});
22 const getInvites = useCallback(
23 point => invitesCache[point] || EMPTY_INVITES,
24 [invitesCache]
25 );
27 const syncInvites = useCallback(
28 async point => {
29 const _contracts = contracts.getOrElse(null);
30 if (!_contracts) {
31 return;
32 }
34 const [availableInvites, invitedPoints] = await Promise.all([
35 azimuth.delegatedSending.getTotalUsableInvites(_contracts, point),
36 azimuth.delegatedSending.getInvited(_contracts, point),
37 ]);
39 const activity = await Promise.all(
40 invitedPoints.map(invitedPoint =>
41 azimuth.azimuth.isActive(_contracts, invitedPoint)
42 )
43 );
45 const sentInvites = invitedPoints.length;
46 const acceptedInvites = activity.filter(i => !!i).length;
48 const [acceptedPoints, pendingPoints] = chain(invitedPoints)
49 .zipWith(activity, (point, active) => ({
50 point,
51 active: !!active,
52 }))
53 .partition('active')
54 .map(arr => arr.map(x => x.point))
55 .value();
57 addToInvitesCache({
58 [point]: {
59 availableInvites: Just(availableInvites),
60 sentInvites: Just(sentInvites),
61 acceptedInvites: Just(acceptedInvites),
62 pendingPoints: Just(pendingPoints),
63 acceptedPoints: Just(acceptedPoints),
64 },
65 });
66 },
67 [contracts, addToInvitesCache]
68 );
70 return { getInvites, syncInvites };