on df0c310 help sign in
bridge/src/store/lib/useDetailsStore.ts
76 lines 2.0 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 const _contracts = contracts.getOrElse(null);
37 if (!_contracts) {
38 return;
39 }
41 // fetch point details
42 try {
43 const l2Point = await api.getPoint(point);
44 const details =
45 l2Point && (l2Point.dominion === 'l2' || l2Point.dominion === 'spawn')
46 ? toL1Details(l2Point)
47 : await azimuth.azimuth.getPoint(_contracts, point);
48 addToDetails({
49 [point]: details,
50 });
51 } catch (error) {
52 if (isDevelopment) {
53 console.warn(error);
54 }
56 try {
57 const details = await azimuth.azimuth.getPoint(_contracts, point);
58 addToDetails({
59 [point]: details,
60 });
61 } catch (e) {
62 console.warn(e);
63 }
64 }
65 },
66 [api, contracts, addToDetails]
67 );
69 return {
70 // TODO: refactor accessors to use getDetails instead of
71 // touching the cache directly
72 pointCache: detailsCache,
73 getDetails,
74 syncDetails,
75 };