Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

adjust restake logic #39

Merged
merged 3 commits into from
Jan 9, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion src/routes/claim.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import Button from "../components/Button";
import { calculateVestingSchedule, calculateVestingData, fetchSystemData } from "../utils/vestingServices";
import { loadProjectCores } from "../utils/stakingServices";
import { getSignAndSendCallbackWithPromise } from "../utils/getSignAndSendCallback";
import { CoreEraType } from "./staking";

export type SystemAccount = Struct & {
data: {
Expand Down Expand Up @@ -100,7 +101,7 @@ const Claim = () => {

if (selectedAccount && stakingCores) {
const userStakeInfo: { coreId: number; era: number; staked: BigNumber; }[] = [];
let unclaimedCores = { cores: [] as { coreId: number; earliestEra: number; }[], total: 0 };
let unclaimedCores = { cores: [] as CoreEraType[], total: 0 };

for (const core of stakingCores) {
const stakerInfo = await api.query.ocifStaking.generalStakerInfo(core.key, selectedAccount.address);
Expand Down
80 changes: 22 additions & 58 deletions src/routes/overview.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,10 @@ import useApi from "../hooks/useApi";
import useAccount from "../stores/account";
import { useQuery } from "urql";
import { AnyJson, Codec } from "@polkadot/types/types";
import { UnsubscribePromise } from "@polkadot/api/types";
import { StakesInfo, VestingData, VestingSchedule } from "./claim";
import MetricDashboard from "../components/MetricDashboard";
import { loadProjectCores } from '../utils/stakingServices';
import { StakingCore, CoreEraStakeInfoType, UserStakedInfoType, BalanceType, LockedType, TotalRewardsClaimedQuery, TotalRewardsCoreClaimedQuery } from "./staking";
import { StakingCore, CoreEraStakeInfoType, UserStakedInfoType, BalanceType, LockedType, TotalRewardsClaimedQuery, TotalRewardsCoreClaimedQuery, CoreEraType } from "./staking";
import { calculateVestingData, fetchSystemData } from "../utils/vestingServices";
import DaoList from "../components/DaoList";

Expand All @@ -27,7 +26,7 @@ const Overview = () => {
const [totalUserStaked, setTotalUserStaked] = useState<BigNumber>();
const [aggregateStaked, setAggregateStaked] = useState<BigNumber>();
const [unclaimedEras, setUnclaimedEras] = useState<{
cores: { coreId: number; earliestEra: number; }[];
cores: CoreEraType[];
total: number;
}>({ cores: [], total: 0 });
const [availableBalance, setAvailableBalance] = useState<BigNumber>();
Expand Down Expand Up @@ -56,43 +55,18 @@ const Overview = () => {
pause: !selectedAccount,
});

const setupSubscriptions = useCallback(({
selectedAccount,
}: {
selectedAccount: InjectedAccountWithMeta;
}) => {
// Current block subscription
const blocks = api.rpc.chain.subscribeNewHeads(() => { });

// Next era starting block subscription
const nextEraStartingBlock = api.query.ocifStaking.nextEraStartingBlock(() => { });

let generalEraInfo;

if (currentStakingEra > 0) {
generalEraInfo = api.query.ocifStaking.generalEraInfo(currentStakingEra);
}

// Staking current era subscription
const currentEra = api.query.ocifStaking.currentEra((era: Codec) => {
setCurrentStakingEra(era.toPrimitive() as number);
});

const account = api.query.system.account(selectedAccount.address);

const unsubs = [blocks, nextEraStartingBlock, currentEra, account];

if (generalEraInfo) {
unsubs.push(generalEraInfo);
}
const setupSubscriptions = useCallback(async () => {
if (!selectedAccount) {
throw new Error("selectedAccount is null");
};

const userStakedInfoMap: Map<
number, UserStakedInfoType
> = new Map();

if (coreEraStakeInfo && coreEraStakeInfo.length > 0) {
for (const stakingCore of stakingCores) {
api.query.ocifStaking.generalStakerInfo(
await api.query.ocifStaking.generalStakerInfo(
stakingCore.key,
selectedAccount.address,
(generalStakerInfo: Codec) => {
Expand Down Expand Up @@ -147,15 +121,12 @@ const Overview = () => {
const newTotalStaked = Array.from(
userStakedInfoMap.values()
).reduce((acc, cur) => acc.plus(cur.staked), new BigNumber(0));

setTotalUserStaked(newTotalStaked);
}
);
}
}

return Promise.resolve(unsubs as UnsubscribePromise[]);
}, [api, currentStakingEra, coreEraStakeInfo, stakingCores, unclaimedEras]);
}, [api, currentStakingEra, stakingCores, unclaimedEras, selectedAccount, coreEraStakeInfo]);

const loadAggregateStaked = useCallback(async () => {
const totalIssuance = (await api.query.balances.totalIssuance()).toPrimitive() as string;
Expand All @@ -181,6 +152,11 @@ const Overview = () => {
setLockedBalance(new BigNumber(balance.data.frozen));
}, [api]);

const loadCurrentEra = useCallback(async () => {
const currentStakingEra = (await api.query.ocifStaking.currentEra()).toPrimitive() as number;
setCurrentStakingEra(currentStakingEra);
}, [api]);

const loadVestingBalance = useCallback(async (selectedAccount: InjectedAccountWithMeta | null) => {
if (!selectedAccount) return;
try {
Expand All @@ -198,13 +174,15 @@ const Overview = () => {
}
}, [api]);


const initializeData = useCallback(async (selectedAccount: InjectedAccountWithMeta | null) => {
try {
toast.loading("Loading staking cores...");

if (selectedAccount) {
await Promise.all([
loadAccountInfo(selectedAccount),
loadCurrentEra(),
loadCores(),
loadAggregateStaked(),
loadVestingBalance(selectedAccount)
Expand All @@ -219,7 +197,7 @@ const Overview = () => {
setLoading(false);
setDataLoaded(true);
}
}, [loadAccountInfo, loadCores, loadAggregateStaked, loadVestingBalance]);
}, [loadAccountInfo, loadCores, loadAggregateStaked, loadVestingBalance, loadCurrentEra]);

useEffect(() => {
initializeData(selectedAccount);
Expand Down Expand Up @@ -258,26 +236,14 @@ const Overview = () => {
}, [selectedAccount, stakingCores, rewardsCoreClaimedQuery.data, rewardsCoreClaimedQuery.fetching]);

useEffect(() => {
let unsubs: UnsubscribePromise[] = [];
const setup = async () => {
if (selectedAccount) {
unsubs = await setupSubscriptions({ selectedAccount });
if (selectedAccount && typeof setupSubscriptions === 'function') {
await setupSubscriptions();
}
};
setup();

return () => {
unsubs.forEach((unsub: UnsubscribePromise) => {
if (unsub) {
unsub.then(unsubFunc => {
if (typeof unsubFunc === 'function') {
unsubFunc();
}
});
}
});
};
}, [setupSubscriptions, selectedAccount, api]);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [selectedAccount, stakingCores, coreEraStakeInfo]);

return (
<div className="mx-auto w-full flex max-w-7xl flex-col justify-between p-4 sm:px-6 lg:px-8 mt-14 md:mt-0 gap-3">
Expand All @@ -287,9 +253,7 @@ const Overview = () => {
<span>{isLoading || !isDataLoaded ? <LoadingSpinner /> : null}</span>
</h2>
</div>
{selectedAccount &&
currentStakingEra &&
unclaimedEras ? (
{selectedAccount ? (
<div>
<MetricDashboard
isOverview={true}
Expand Down Expand Up @@ -323,4 +287,4 @@ const Overview = () => {
);
};

export default Overview;
export default Overview;
Loading