on 2dd6efa help sign in
bridge/src/store/lib/useBirthdaysStore.js
60 lines 1.6 kB history raw
1import { useCallback, useState } from 'react';
2import Maybe from 'folktale/maybe';
3import * as azimuth from 'azimuth-js';
5import { useNetwork } from '../network';
7export default function useBirthdayStore() {
8 const { contracts, web3 } = useNetwork();
9 const [birthdayCache, _setBirthdayCache] = useState({});
11 const addToBirthdayCache = useCallback(
12 entry =>
13 _setBirthdayCache(cache => ({
14 ...cache,
15 ...entry,
16 })),
17 [_setBirthdayCache]
18 );
20 const getBirthday = useCallback(
21 point => birthdayCache[point] || Maybe.Nothing(),
22 [birthdayCache]
23 );
25 const syncBirthday = useCallback(
26 async point => {
27 const _contracts = contracts.getOrElse(null);
28 const _web3 = web3.getOrElse(null);
29 if (!_contracts || !web3) {
30 return;
31 }
33 // birthday will not change after being set, so bail if we already know
34 if (Maybe.Just.hasInstance(getBirthday(point))) {
35 return;
36 }
38 const birthBlock = await azimuth.azimuth.getActivationBlock(
39 _contracts,
40 point
41 );
43 if (birthBlock > 0) {
44 const block = await _web3.eth.getBlock(birthBlock);
45 addToBirthdayCache({
46 [point]: Maybe.Just(new Date(block.timestamp * 1000)),
47 });
48 } else {
49 // TODO: better encoding for "no birthday" state?
50 // if there's no birthday, just use today
51 addToBirthdayCache({
52 [point]: Maybe.Just(new Date()),
53 });
54 }
55 },
56 [contracts, web3, addToBirthdayCache, getBirthday]
57 );
59 return { getBirthday, syncBirthday };