Skip to content

Commit

Permalink
chore: fix async loading of stats
Browse files Browse the repository at this point in the history
  • Loading branch information
shibatales committed Jan 2, 2024
1 parent 84c91f4 commit 8297057
Show file tree
Hide file tree
Showing 5 changed files with 56 additions and 86 deletions.
66 changes: 25 additions & 41 deletions src/components/DaoList.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,6 @@ const DaoList = (props: DaoListProps) => {

const handleViewDetails = (mini: boolean, children?: JSX.Element) => {
if (!mini || !children) return;
console.log('handleViewDetails', mini, children);
setOpenModal({
name: modalName.VIEW_DETAILS,
metadata: { children },
Expand Down Expand Up @@ -93,6 +92,28 @@ const DaoList = (props: DaoListProps) => {
}
};

const loadTotalUserStaked = async () => {
if (!selectedAccount) return;

const coreInfoResults: { [key: number]: Partial<CoreEraStakeInfoType> | undefined; } = {};
const totalUserStakedResults: { [key: number]: BigNumber | undefined; } = {};

for (const core of stakingCores) {
const coreInfo = getCoreInfo(coreEraStakeInfo, core);
const totalUserStaked = getTotalUserStaked(userStakedInfo, core);

if (typeof coreInfo !== 'undefined') {
coreInfoResults[core.key] = coreInfo;
}

if (typeof totalUserStaked !== 'undefined') {
totalUserStakedResults[core.key] = totalUserStaked;
}
}

setTotalUserStakedData(prevState => ({ ...prevState, ...totalUserStakedResults }));
};

const loadAccountInfo = async (selectedAccount: InjectedAccountWithMeta) => {
const account = await api.query.system.account(selectedAccount.address);
const balance = account.toPrimitive() as BalanceType;
Expand Down Expand Up @@ -170,7 +191,6 @@ const DaoList = (props: DaoListProps) => {
const coreEraStake = coreEraStakeInfo.find(info => info.coreId === stakingCore.key);

if (coreEraStake) {
console.log('coreEraStake', coreEraStake);
coreEraStakeInfoMap.set(stakingCore.key, {
...coreEraStake,
});
Expand Down Expand Up @@ -220,44 +240,8 @@ const DaoList = (props: DaoListProps) => {
}, [selectedAccount, stakingCores, totalUserStakedData, api]);

useEffect(() => {
let isMounted = true;

(async () => {
const coreInfoResults: { [key: number]: Partial<CoreEraStakeInfoType> | undefined; } = {};
const totalUserStakedResults: { [key: number]: BigNumber | undefined; } = {};

for (const core of stakingCores) {
if (!isMounted) {
break;
}

const coreInfo = getCoreInfo(coreEraStakeInfo, core);
const totalUserStaked = getTotalUserStaked(userStakedInfo, core);

if (typeof coreInfo !== 'undefined') {
coreInfoResults[core.key] = coreInfo;
}

if (typeof totalUserStaked !== 'undefined') {
totalUserStakedResults[core.key] = totalUserStaked;
}
}

if (isMounted) {
setTotalUserStakedData(prevState => {
const newState = { ...prevState, ...totalUserStakedResults };
if (JSON.stringify(newState) !== JSON.stringify(prevState)) {
return newState;
}
return prevState;
});
}
})();

return () => {
isMounted = false;
};
}, [stakingCores, coreEraStakeInfo, userStakedInfo]);
loadTotalUserStaked();
}, [selectedAccount, stakingCores, coreEraStakeInfo, userStakedInfo]);

useEffect(() => {
if (!rewardsCoreClaimedQuery.data?.cores?.length || !selectedAccount) return;
Expand All @@ -268,7 +252,7 @@ const DaoList = (props: DaoListProps) => {
});

setCoreEraStakeInfo(Array.from(coreEraStakeInfoMap.values()));
}, [stakingCores, rewardsCoreClaimedQuery]);
}, [selectedAccount, stakingCores, rewardsCoreClaimedQuery]);

useEffect(() => {
let unsubs: UnsubscribePromise[] = [];
Expand Down
53 changes: 13 additions & 40 deletions src/components/ProjectCard.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import { RefObject, useEffect, useState } from 'react';
import { BigNumber } from 'bignumber.js';
import { LockClosedIcon } from '@heroicons/react/24/outline';
import { formatBalance } from '@polkadot/util';
import toast from 'react-hot-toast';
import { StakingCore, CoreEraStakeInfoType, ChainPropertiesType } from '../routes/staking';
import { InjectedAccountWithMeta } from '@polkadot/extension-inject/types';
Expand Down Expand Up @@ -38,7 +37,7 @@ const STAT_UNDERLINE = 'pb-2 border-b border-b-[#2B2C30]';
const ProjectCard = (props: ProjectCardProps) => {
const {
core,
totalUserStaked,
totalUserStaked: totalStaked,
coreInfo,
chainProperties,
availableBalance,
Expand All @@ -55,6 +54,7 @@ const ProjectCard = (props: ProjectCardProps) => {
const [aggregateStaked, setAggregateStaked] = useState<BigNumber>(new BigNumber("0"));
const [minStakeReward, setMinStakeReward] = useState<BigNumber>(new BigNumber("0"));
const [minSupportMet, setMinSupportMet] = useState<boolean>(false);
const [totalUserStaked, setTotalUserStaked] = useState<BigNumber>(new BigNumber("0"));
const api = useApi();

const handleReadMore = () => {
Expand Down Expand Up @@ -113,6 +113,12 @@ const ProjectCard = (props: ProjectCardProps) => {
calcMinSupportMet();
}, [minStakeReward, coreInfo?.totalStaked]);

useEffect(() => {
if (totalStaked) {
setTotalUserStaked(totalStaked);
}
}, [totalStaked]);

return (
<div
key={core.account}
Expand Down Expand Up @@ -183,14 +189,7 @@ const ProjectCard = (props: ProjectCardProps) => {
</div>
<div className="font-normal text-white text-[12px] text-right tracking-[0] leading-[normal] truncate">
{coreInfo?.totalStaked
? `${ formatBalance(
coreInfo?.totalStaked.toString(),
{
decimals: 12,
withUnit: false,
forceUnit: "-",
}
).slice(0, -2) } TNKR`
? `${ formatNumberShorthand(parseFloat(coreInfo?.totalStaked.toString()) / Math.pow(10, 12)) } TNKR`
: '--'}
</div>
</div> : null}
Expand All @@ -207,14 +206,7 @@ const ProjectCard = (props: ProjectCardProps) => {
</div>
<div className="font-normal text-white text-[12px] text-right tracking-[0] leading-[normal] truncate">
{totalUserStaked
? `${ formatBalance(
totalUserStaked.toString(),
{
decimals: 12,
withUnit: false,
forceUnit: "-",
}
).slice(0, -2) } TNKR`
? `${ formatNumberShorthand(parseFloat(totalUserStaked.toString()) / Math.pow(10, 12)) } TNKR`
: '--'}
</div>
</div>
Expand All @@ -231,14 +223,7 @@ const ProjectCard = (props: ProjectCardProps) => {
</div>
<div className="font-normal text-white text-[12px] text-right tracking-[0] leading-[normal] truncate">
{coreInfo?.totalRewards
? `${ formatBalance(
coreInfo?.totalRewards.toString(),
{
decimals: 12,
withUnit: false,
forceUnit: "-",
}
).slice(0, -2) } TNKR`
? `${ formatNumberShorthand(parseFloat(coreInfo?.totalRewards.toString()) / Math.pow(10, 12)) } TNKR`
: '--'}
</div>
</div> : null}
Expand All @@ -255,14 +240,7 @@ const ProjectCard = (props: ProjectCardProps) => {
</div>
<div className="font-normal text-white text-[12px] text-right tracking-[0] leading-[normal] truncate">
{coreInfo?.totalUnclaimed
? `${ formatBalance(
coreInfo?.totalUnclaimed.toString(),
{
decimals: 12,
withUnit: false,
forceUnit: "-",
}
).slice(0, -2) } TNKR`
? `${ formatNumberShorthand(parseFloat(coreInfo?.totalUnclaimed.toString()) / Math.pow(10, 12)) } TNKR`
: '--'}
</div>
</div> : null}
Expand Down Expand Up @@ -297,12 +275,7 @@ const ProjectCard = (props: ProjectCardProps) => {
<div className="text-white font-normal text-[12px] text-right tracking-[0] leading-[normal] truncate">
<span className={`${ minSupportMet ? 'text-green-400' : 'text-red-400' }`}>
{coreInfo?.totalStaked && minStakeReward
? `${ formatNumberShorthand(parseFloat(coreInfo?.totalStaked.toString()) / Math.pow(10, 12)) }/${ formatBalance(minStakeReward.toString(), {
decimals: 12,
withUnit: false,
forceUnit: '-',
withZero: false
}) }`
? `${ minSupportMet ? '25K' : formatNumberShorthand(parseFloat(coreInfo?.totalStaked.toString()) / Math.pow(10, 12)) }/${ formatNumberShorthand(parseFloat(minStakeReward.toString()) / Math.pow(10, 12)) }`
: '--'}
</span> TNKR
</div>
Expand Down
2 changes: 0 additions & 2 deletions src/modals/ViewDetails.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -34,8 +34,6 @@ const ViewDetails = (props: ViewDetailsProps) => {
};
}, [metadata]);

console.log('localMetadata', metadata, localMetadata);

if (!localMetadata) return null;

const { children } = localMetadata;
Expand Down
5 changes: 5 additions & 0 deletions src/stores/modals.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,11 @@ const useModal = createWithEqualityFn<ModalState>()((set) => ({
},
closeCurrentModal: () => {
set((state) => {
if (!state.openModals || state.openModals.length === 0) {
console.log('No open modals to close');
return state;
}

const newOpenModals = [...state.openModals];
newOpenModals.pop();
return { openModals: newOpenModals };
Expand Down
16 changes: 13 additions & 3 deletions src/utils/formatNumber.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,19 @@
export const formatNumberShorthand = (num: number) => {
if (num > 999 && num <= 999999) {
return (num / 1000).toFixed(1) + 'K';
const formattedNum = (num / 1000).toFixed(1);
// Remove decimal if the 1000th place is a zero
return formattedNum.endsWith('.0') ? `${ formattedNum.slice(0, -2) }K` : `${ formattedNum }K`;
} else if (num > 999999) {
return (num / 1000000).toFixed(1) + 'M';
const formattedNum = (num / 1000000).toFixed(1);
// Remove decimal if the millionth place is a zero
return formattedNum.endsWith('.0') ? `${ formattedNum.slice(0, -2) }M` : `${ formattedNum }M`;
} else {
return num.toString();
let formattedNum = num.toString();
const decimalIndex = formattedNum.indexOf('.');
// If the number has more than two decimal places, remove the extra ones
if (decimalIndex !== -1 && formattedNum.length > decimalIndex + 3) {
formattedNum = formattedNum.slice(0, decimalIndex + 3);
}
return formattedNum;
}
};

0 comments on commit 8297057

Please sign in to comment.