@@ -5,36 +5,106 @@ import React, {
55 useContext,
66 useState,
77} from 'react';
8+import Maybe from 'folktale/maybe';
89import * as azimuth from 'azimuth-js';
910
1011import { useNetwork } from './network';
1112
1213export const PointCacheContext = createContext(null);
1314
15+// the default value of a point's invites
16+const kEmptyInvites = {
17+ availableInvites: Maybe.Nothing(),
18+ sentInvites: Maybe.Nothing(),
19+ acceptedInvites: Maybe.Nothing(),
20+};
21+
1422function _usePointCache() {
15− const { contracts } = useNetwork();
23+ const { contracts, web3 } = useNetwork();
1624 const [pointCache, _setPointCache] = useState({});
25+ const [birthdayCache, _setBirthdayCache] = useState({});
26+ const [invitesCache, _setInvitesCache] = useState({});
1727
1828 const addToPointCache = useCallback(
1929 entry => _setPointCache(cache => ({ ...cache, ...entry })),
2030 [_setPointCache]
2131 );
2232
33+ const addToBirthdayCache = useCallback(
34+ entry => _setBirthdayCache(cache => ({ ...cache, ...entry })),
35+ [_setBirthdayCache]
36+ );
37+
38+ const addToInvitesCache = useCallback(
39+ entry => _setInvitesCache(cache => ({ ...cache, ...entry })),
40+ [_setInvitesCache]
41+ );
42+
43+ // TODO: refactor pointCache access to use accessor like bithday
44+ const getBirthday = useCallback(
45+ point => birthdayCache[point] || Maybe.Nothing(),
46+ [birthdayCache]
47+ );
48+ const getInvites = useCallback(
49+ point => invitesCache[point] || kEmptyInvites,
50+ [invitesCache]
51+ );
52+
2353 const fetchPoint = useCallback(
2454 async point => {
2555 const _contracts = contracts.getOrElse(null);
26− if (!_contracts) {
56+ const _web3 = web3.getOrElse(null);
57+ if (!_contracts || !_web3) {
2758 return;
2859 }
2960
61+ // fetch point details
3062 const details = await azimuth.azimuth.getPoint(_contracts, point);
3163 addToPointCache({ [point]: details });
64+
65+ // fetch invites
66+ const count = await azimuth.delegatedSending.getTotalUsableInvites(
67+ _contracts,
68+ point
69+ );
70+ addToInvitesCache({
71+ [point]: {
72+ availableInvites: Maybe.Just(count),
73+ // TODO: look up sent/accepted on-chain
74+ sentInvites: Maybe.Just(6),
75+ acceptedInvites: Maybe.Just(5),
76+ },
77+ });
78+
79+ // fetch birthday (if not already known — will not change after being set)
80+ if (Maybe.Nothing.hasInstance(getBirthday(point))) {
81+ const birthBlock = await azimuth.azimuth.getActivationBlock(
82+ _contracts,
83+ point
84+ );
85+
86+ if (birthBlock > 0) {
87+ const block = await _web3.eth.getBlock(birthBlock);
88+ addToBirthdayCache({
89+ [point]: Maybe.Just(new Date(block.timestamp * 1000)),
90+ });
91+ }
92+ }
3293 },
33− [contracts, addToPointCache]
94+ [
95+ contracts,
96+ web3,
97+ addToPointCache,
98+ addToBirthdayCache,
99+ getBirthday,
100+ addToInvitesCache,
101+ ]
34102 );
35103
36104 return {
37105 pointCache,
106+ getBirthday,
107+ getInvites,
38108 addToPointCache,
39109 fetchPoint,
40110 };