on master help sign in
bridge/src/store/lib/useDetailsStore.ts
74 lines 1.9 kB history raw
1import { useState, useCallback } from 'react';
2import { Just, Nothing } from 'folktale/maybe';
3import * as azimuth from 'azimuth-js';
5import { isDevelopment } from 'lib/flags';
6import { toL1Details } from 'lib/utils/point';
7import useRoller from 'lib/useRoller';
8import { useNetwork } from '../network';
9import { L1Point } from 'lib/types/L1Point';
11export default function useDetailsStore() {
12 const { contracts }: any = useNetwork();
13 const { api } = useRoller();
14 const [detailsCache, _setDetailsCache] = useState<Record<number, L1Point>>(
15 {}
16 );
18 const addToDetails = useCallback(
19 entry =>
20 _setDetailsCache(cache => ({
21 ...cache,
22 ...entry,
23 })),
24 [_setDetailsCache]
25 );
27 // TODO: refactor detailsCache access to use accessor like bithday
28 // Maybe<{}>
29 const getDetails = useCallback(
30 point => (point in detailsCache ? Just(detailsCache[point]) : Nothing()),
31 [detailsCache]
32 );
34 const syncDetails = useCallback(
35 async point => {
36 // fetch point details
37 try {
38 const _point = await api.getPoint(point);
39 const details = toL1Details(_point);
40 addToDetails({
41 [point]: details,
42 });
43 } catch (error) {
44 if (isDevelopment) {
45 console.warn(error);
46 }
48 // Try getting the details from L1
49 try {
50 const _contracts = contracts.getOrElse(null);
51 if (!_contracts) {
52 return;
53 }
55 const details = await azimuth.azimuth.getPoint(_contracts, point);
56 addToDetails({
57 [point]: details,
58 });
59 } catch (e) {
60 console.warn(e);
61 }
62 }
63 },
64 [api, contracts, addToDetails]
65 );
67 return {
68 // TODO: refactor accessors to use getDetails instead of
69 // touching the cache directly
70 pointCache: detailsCache,
71 getDetails,
72 syncDetails,
73 };