on c19b2a8 help sign in
bridge/src/store/lib/useBirthdaysStore.js
59 lines 1.6 kB history raw
1import { useCallback, useState } from 'react';
2import { Just, Nothing } 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(point => birthdayCache[point] || Nothing(), [
21 birthdayCache,
22 ]);
24 const syncBirthday = useCallback(
25 async point => {
26 const _contracts = contracts.getOrElse(null);
27 const _web3 = web3.getOrElse(null);
28 if (!_contracts || !_web3) {
29 return;
30 }
32 // birthday will not change after being set, so bail if we already know
33 if (Just.hasInstance(getBirthday(point))) {
34 return;
35 }
37 const birthBlock = await azimuth.azimuth.getActivationBlock(
38 _contracts,
39 point
40 );
42 if (birthBlock > 0) {
43 const block = await _web3.eth.getBlock(birthBlock);
44 addToBirthdayCache({
45 [point]: Just(new Date(block.timestamp * 1000)),
46 });
47 } else {
48 // TODO: better encoding for "no birthday" state using Result.Ok/Error
49 // if there's no birthday, just use today
50 addToBirthdayCache({
51 [point]: Just(new Date()),
52 });
53 }
54 },
55 [contracts, web3, addToBirthdayCache, getBirthday]
56 );
58 return { getBirthday, syncBirthday };