on d8aa1ca help sign in
bridge/src/store/lib/useControlledPointsStore.js
112 lines 3.3 kB history raw
1import { useState, useEffect, useCallback } from 'react';
2import { Just, Nothing } from 'folktale/maybe';
3import Result from 'folktale/result';
4import * as azimuth from 'azimuth-js';
6import { useNetwork } from '../network';
7import { useWallet } from 'store/wallet';
8import useRoller from 'lib/useRoller';
10const onlyUnique = (value, index, self) => self.indexOf(value) === index;
12export default function useControlledPointsStore() {
13 const { contracts } = useNetwork();
14 const { wallet } = useWallet();
15 const { getPoints } = useRoller();
17 const [controlledPoints, _setControlledPoints] = useState(Nothing());
19 const syncControlledPoints = useCallback(async () => {
20 const _contracts = contracts.getOrElse(null);
21 const _wallet = wallet.getOrElse(null);
22 if (!_contracts || !_wallet) {
23 return;
24 }
26 _setControlledPoints(Nothing());
28 const address = _wallet.address;
30 try {
31 const [
32 ownedPoints,
33 incomingPoints,
34 managingPoints,
35 votingPoints,
36 spawningPoints,
37 ] = await Promise.all([
38 getPoints('own', address),
39 getPoints('transfer', address),
40 getPoints('manage', address),
41 getPoints('vote', address),
42 getPoints('spawn', address),
43 ]);
45 const [
46 ownedPointsL1,
47 incomingPointsL1,
48 managingPointsL1,
49 votingPointsL1,
50 spawningPointsL1,
51 ] = await Promise.all([
52 azimuth.azimuth.getOwnedPoints(_contracts, address),
53 azimuth.azimuth.getTransferringFor(_contracts, address),
54 azimuth.azimuth.getManagerFor(_contracts, address),
55 azimuth.azimuth.getVotingFor(_contracts, address),
56 azimuth.azimuth.getSpawningFor(_contracts, address),
57 ]);
59 if (
60 ownedPoints === null &&
61 incomingPoints === null &&
62 managingPoints === null &&
63 votingPoints === null &&
64 spawningPoints === null
65 ) {
66 _setControlledPoints(
67 Just(Result.Error('Failed to read the blockchain.'))
68 );
69 } else {
70 _setControlledPoints(
71 Just(
72 Result.Ok({
73 ownedPoints: ownedPoints
74 .concat(ownedPointsL1)
75 .map(Number)
76 .filter(onlyUnique),
77 incomingPoints: incomingPoints
78 .concat(incomingPointsL1)
79 .map(Number)
80 .filter(onlyUnique),
81 managingPoints: managingPoints
82 .concat(managingPointsL1)
83 .map(Number)
84 .filter(onlyUnique),
85 votingPoints: votingPoints
86 .concat(votingPointsL1)
87 .map(Number)
88 .filter(onlyUnique),
89 spawningPoints: spawningPoints
90 .concat(spawningPointsL1)
91 .map(Number)
92 .filter(onlyUnique),
93 })
94 )
95 );
96 }
97 } catch (error) {
98 console.error('failed to fetch controlled points', error);
99 _setControlledPoints(Just(Result.Error(error)));
100 }
101 }, [contracts, wallet, getPoints]);
103 // sync controlled points whenever wallet or contracts changes
104 useEffect(() => {
105 syncControlledPoints();
106 }, [syncControlledPoints]);
108 return {
109 controlledPoints,
110 syncControlledPoints,
111 };