on ec040ad help sign in
bridge/src/store/lib/useControlledPointsStore.js
82 lines 2.1 kB history raw
1import { useState, useEffect, useCallback } from 'react';
2import { Just, Nothing } from 'folktale/maybe';
3import Result from 'folktale/result';
5import { useNetwork } from '../network';
6import { useWallet } from 'store/wallet';
7import useRoller from 'lib/useRoller';
9export default function useControlledPointsStore() {
10 const { contracts } = useNetwork();
11 const { wallet } = useWallet();
12 const { getPoints } = useRoller();
14 const [controlledPoints, _setControlledPoints] = useState(Nothing());
16 const syncControlledPoints = useCallback(async () => {
17 const _contracts = contracts.getOrElse(null);
18 const _wallet = wallet.getOrElse(null);
19 if (!_contracts || !_wallet) {
20 return;
21 }
23 _setControlledPoints(Nothing());
25 const address = _wallet.address;
27 try {
28 const [
29 ownedPoints,
30 incomingPoints,
31 managingPoints,
32 votingPoints,
33 spawningPoints,
34 ] = await Promise.all([
35 getPoints('own', address),
36 getPoints('transfer', address),
37 getPoints('manage', address),
38 getPoints('vote', address),
39 getPoints('spawn', address),
40 ]);
42 console.log(ownedPoints)
44 if (
45 ownedPoints === null &&
46 incomingPoints === null &&
47 managingPoints === null &&
48 votingPoints === null &&
49 spawningPoints === null
50 ) {
51 _setControlledPoints(
52 Just(Result.Error('Failed to read the blockchain.'))
53 );
54 } else {
55 _setControlledPoints(
56 Just(
57 Result.Ok({
58 ownedPoints,
59 incomingPoints,
60 managingPoints,
61 votingPoints,
62 spawningPoints,
63 })
64 )
65 );
66 }
67 } catch (error) {
68 console.error('failed to fetch controlled points', error);
69 _setControlledPoints(Just(Result.Error(error)));
70 }
71 }, [contracts, wallet, getPoints]);
73 // sync controlled points whenever wallet or contracts changes
74 useEffect(() => {
75 syncControlledPoints();
76 }, [syncControlledPoints]);
78 return {
79 controlledPoints,
80 syncControlledPoints,
81 };