Skip to content

Commit

Permalink
Corrected Pools to not depend on chain sync+Added Action List
Browse files Browse the repository at this point in the history
  • Loading branch information
ehsan6sha committed Nov 20, 2024
1 parent d8eda36 commit 4695443
Show file tree
Hide file tree
Showing 6 changed files with 200 additions and 11 deletions.
141 changes: 141 additions & 0 deletions apps/box/src/components/Cards/TasksCard.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,141 @@
import React, { useEffect, useState } from 'react';
import {
FxBox,
FxCard,
FxText,
FxRadioButton,
FxRadioButtonWithLabel,
FxSpacer,
useFxTheme,
FxRefreshIcon,
} from '@functionland/component-library';
import { chainApi } from '@functionland/react-native-fula';
import { useNavigation } from '@react-navigation/native';
import { Pressable, ActivityIndicator } from 'react-native';

type ValueType = string | number;

type TaskListProps = {
pools: Array<{ joined: boolean; requested: boolean }>;
getPools: () => Promise<void>;
currentBloxPeerId: string;
accountId: string;
routes: any;
};

export type Task = {
id: ValueType;
title: string;
route: any;
};

export const TasksCard = ({
pools,
getPools,
currentBloxPeerId,
accountId,
routes,
}: TaskListProps) => {
const navigation = useNavigation();
const tasks: Task[] = [
{ id: 1, title: 'Join Testnet', route: routes.UsersTab },
{ id: 2, title: 'Join Closest Pool', route: routes.Pools },
];

const [completedTasks, setCompletedTasks] = useState<ValueType[]>([]);
const { colors } = useFxTheme();
const [refreshCard, setRefreshCard] = useState<boolean>(false);
const [loading, setLoading] = useState<boolean>(false);
const handleTaskPress = (route: string) => {
navigation.navigate(route, {
screen: route,
});
};

const checkTasks = async () => {
if (!loading) {
setLoading(true);
await checkTestnetTask();
await checkPoolTask();
setLoading(false);
}
};

const checkTestnetTask = async () => {
try {
const api = await chainApi.init();
const gasBalanceStr = await chainApi.checkAccountBalance(api, accountId);

if (gasBalanceStr && !gasBalanceStr.includes('Error')) {
console.log(gasBalanceStr);
const gasBalance = parseInt(gasBalanceStr, 10);
console.log(gasBalance);
if (gasBalance > 0) {
setCompletedTasks((prev) => (prev.includes(1) ? prev : [...prev, 1]));
} else {
setCompletedTasks((prev) => prev.filter((id) => id !== 1));
}
}
} catch (error) {
console.error('Error checking testnet balance:', error);
}
};

const checkPoolTask = async () => {
try {
const isPoolJoined =
pools.some((pool) => pool.joined || pool.requested) &&
currentBloxPeerId;

if (isPoolJoined) {
setCompletedTasks((prev) => (prev.includes(2) ? prev : [...prev, 2]));
} else {
setCompletedTasks((prev) => prev.filter((id) => id !== 2));
}
} catch (error) {
console.error('Error checking pool status:', error);
}
};

useEffect(() => {
getPools();
}, [currentBloxPeerId]);

useEffect(() => {
if (currentBloxPeerId && accountId) {
checkTasks();
}
}, [pools, currentBloxPeerId, accountId, refreshCard]);

return (
<FxCard>
<FxBox flexDirection="row" justifyContent="space-between">
<FxCard.Title marginBottom="16">Action List</FxCard.Title>
{loading ? (
<ActivityIndicator />
) : (
<FxRefreshIcon
fill={colors.content3}
onPress={() => setRefreshCard(!refreshCard)}
/>
)}
</FxBox>
<FxBox flexDirection="column">
<FxRadioButton.Group value={completedTasks} onValueChange={() => {}}>
{tasks.map((task, index) => (
<React.Fragment key={task.id}>
<Pressable onPress={() => handleTaskPress(task.route)}>
<FxRadioButtonWithLabel
disabled
value={task.id}
label={task.title}
/>
</Pressable>
{index < tasks.length - 1 && <FxSpacer height={4} />}
</React.Fragment>
))}
</FxRadioButton.Group>
</FxBox>
</FxCard>
);
};
2 changes: 1 addition & 1 deletion apps/box/src/components/WalletDetails.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -289,7 +289,7 @@ export const WalletDetails = ({
paddingHorizontal="32"
size="large"
>
{`PeerId:${appPeerId}`}
{`App PeerId:${appPeerId}`}
</FxButton>
</FxBox>
)}
Expand Down
57 changes: 51 additions & 6 deletions apps/box/src/screens/Blox/Blox.screen.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,25 +17,29 @@ import {
DeviceCard,
UsageBar,
} from '../../components';
import { UsersCard } from '../../components/Cards/UsersCard';
import { TasksCard } from '../../components/Cards/TasksCard';
import { EarningCard } from '../../components/Cards/EarningCard';
import { BloxHeader } from './components/BloxHeader';
import { BloxInteraction } from './components/BloxInteraction';
import { BloxInteractionModal } from './modals/BloxInteractionModal';
import { EDeviceStatus } from '../../api/hub';
import { EBloxInteractionType, TBloxInteraction } from '../../models';
import { ProfileBottomSheet } from '../../components/ProfileBottomSheet';
import { useUserProfileStore } from '../../stores/useUserProfileStore';
import {
ConnectionOptionsSheet,
ConnectionOptionsType,
} from '../../components/ConnectionOptionsSheet';
import { useLogger } from '../../hooks';
import { Routes } from '../../navigation/navigationConfig';
import { useNavigation } from '@react-navigation/native';
import { useBloxsStore } from '../../stores';
import {
useBloxsStore,
usePoolsStore,
useUserProfileStore,
} from '../../stores';
import { blockchain, fxblox } from '@functionland/react-native-fula';
import { Helper } from '../../utils';

const DEFAULT_DIVISION = 30;

export const BloxScreen = () => {
Expand All @@ -52,6 +56,7 @@ export const BloxScreen = () => {
const [resettingChain, setResettingChain] = useState(false);
const [loadingBloxSpace, setLoadingBloxSpace] = useState(false);
const [loadingFulaEarnings, setLoadingFulaEarnings] = useState(false);
const [bloxAccountId, setBloxAccountId] = useState('');

const [selectedMode, setSelectedMode] = useState<EBloxInteractionType>(
EBloxInteractionType.OfficeBloxUnit
Expand Down Expand Up @@ -87,9 +92,38 @@ export const BloxScreen = () => {
state.removeBlox,
state.update,
]);
useEffect(() => {
console.log('here');
}, [fulaIsReady]);

const [pools, getPools] = usePoolsStore((state) => [
state.pools,
state.getPools,
]);

const updateBloxAccount = async () => {
try {
if (fulaIsReady) {
const connectionStatus = await checkBloxConnection();
if (connectionStatus) {
const bloxAccount = await blockchain.getAccount();
setBloxAccountId(bloxAccount.account);
} else {
setBloxAccountId('Not Connected to blox');
}
} else {
setBloxAccountId('Fula is not ready');
}
} catch (e) {
console.error('Error updating blox account:', e);
const err = e.message || e.toString();
if (err.includes('failed to dial')) {
setBloxAccountId('Connection to Blox not established');
} else if (err.includes('blockchain call error')) {
setBloxAccountId('Error with blockchain.');
} else {
setBloxAccountId(e.message || e.toString());
}
}
};

const bloxInteractions = Object.values(bloxs || {}).map<TBloxInteraction>(
(blox) => ({
peerId: blox.peerId,
Expand All @@ -116,6 +150,7 @@ export const BloxScreen = () => {
updateBloxSpace();
updateFulaEarnings();
checkBloxConnection();
updateBloxAccount();
} else if (fulaIsReady && !bloxsConnectionStatus[currentBloxPeerId]) {
checkBloxConnection();
}
Expand Down Expand Up @@ -463,6 +498,16 @@ export const BloxScreen = () => {
totalCapacity={currentBloxSpaceInfo?.size || 1000}
/>
)}
{bloxAccountId && bloxAccountId.startsWith('5') && (
<TasksCard
pools={pools}
getPools={getPools}
currentBloxPeerId={currentBloxPeerId}
accountId={bloxAccountId} // Replace with actual account ID
routes={Routes}
/>
)}
<FxSpacer height={24} />
<DeviceCard
onRefreshPress={updateBloxSpace}
loading={loadingBloxSpace}
Expand Down
7 changes: 4 additions & 3 deletions apps/box/src/screens/Settings/Pools.screen.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ export const PoolsScreen = () => {

const wrappedJoinPool = async (poolID: number) => {
try {
if (syncProgress==0 || syncProgress > 90){
if (syncProgress==0 || syncProgress > 10){
setRefreshing(true);
await joinPool(poolID);
} else {
Expand Down Expand Up @@ -124,7 +124,8 @@ export const PoolsScreen = () => {
await getPools();
console.log('enableInteraction: ', enableInteraction);
setAllowJoin(
pools.filter((pool) => pool.joined || pool.requested).length === 0 && isChainSynced &&
pools.filter((pool) => pool.joined || pool.requested).length === 0 &&
syncProgress > 0 &&
enableInteraction
);
} catch (e) {
Expand Down Expand Up @@ -178,7 +179,7 @@ export const PoolsScreen = () => {
ListHeaderComponent={
<FxBox>
<FxBox flex={1}>
{ syncProgress > 0 && syncProgress < 99 &&
{ syncProgress > 0 && syncProgress < 10 &&
<FxBox
flexDirection="row"
alignItems='center'
Expand Down
2 changes: 1 addition & 1 deletion apps/box/src/screens/Users/UserHeader.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ export const UserHeader = ({ userData }: UserHeaderProps) => {
showDID={true}
showNetwork={false}
showPeerId={true}
showBloxPeerIds={false}
showBloxPeerIds={true}
/>
</FxBox>
{/* <FxBox width="100%">
Expand Down
2 changes: 2 additions & 0 deletions apps/box/src/stores/index.ts
Original file line number Diff line number Diff line change
@@ -1,2 +1,4 @@
export * from './useSettingsStore';
export * from './useBloxsStore';
export * from './usePoolsStore';
export * from './useUserProfileStore';

0 comments on commit 4695443

Please sign in to comment.