on 2b975ce help sign in
bridge/src/store/lib/useControlledPointsStore.js
78 lines 2.2 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';
9export default function useControlledPointsStore() {
10 const { contracts } = useNetwork();
11 const { wallet } = useWallet();
12 const [controlledPoints, _setControlledPoints] = useState(Nothing());
14 const syncControlledPoints = useCallback(async () => {
15 const _contracts = contracts.getOrElse(null);
16 const _wallet = wallet.getOrElse(null);
17 if (!_contracts || !_wallet) {
18 return;
19 }
21 _setControlledPoints(Nothing());
23 const address = _wallet.address;
25 try {
26 const [
27 ownedPoints,
28 incomingPoints,
29 managingPoints,
30 votingPoints,
31 spawningPoints,
32 ] = await Promise.all([
33 azimuth.azimuth.getOwnedPoints(_contracts, address),
34 azimuth.azimuth.getTransferringFor(_contracts, address),
35 azimuth.azimuth.getManagerFor(_contracts, address),
36 azimuth.azimuth.getVotingFor(_contracts, address),
37 azimuth.azimuth.getSpawningFor(_contracts, address),
38 ]);
40 if (
41 ownedPoints === null &&
42 incomingPoints === null &&
43 managingPoints === null &&
44 votingPoints === null &&
45 spawningPoints === null
46 ) {
47 _setControlledPoints(
48 Just(Result.Error('Failed to read the blockchain.'))
49 );
50 } else {
51 _setControlledPoints(
52 Just(
53 Result.Ok({
54 ownedPoints,
55 incomingPoints,
56 managingPoints,
57 votingPoints,
58 spawningPoints,
59 })
60 )
61 );
62 }
63 } catch (error) {
64 console.error('failed to fetch controlled points', error);
65 _setControlledPoints(Just(Result.Error(error)));
66 }
67 }, [contracts, wallet]);
69 // sync controlled points whenever wallet or contracts changes
70 useEffect(() => {
71 syncControlledPoints();
72 }, [syncControlledPoints]);
74 return {
75 controlledPoints,
76 syncControlledPoints,
77 };