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

329 handle intermediate states #412

Draft
wants to merge 2 commits into
base: main
Choose a base branch
from
Draft
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
10 changes: 10 additions & 0 deletions src/app/components/Staking/Staking.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@ import {
} from "@/app/hooks/services/useTransactionService";
import { useHealthCheck } from "@/app/hooks/useHealthCheck";
import { useAppState } from "@/app/state";
import { useDelegationV2State } from "@/app/state/DelegationV2State";
import { DelegationV2StakingState } from "@/app/types/delegationsV2";
import { ErrorHandlerParam, ErrorState } from "@/app/types/errors";
import {
FinalityProvider,
Expand Down Expand Up @@ -74,6 +76,7 @@ export const Staking = () => {
useLocalStorage<boolean>("bbn-staking-cancelFeedbackModalOpened ", false);

const { createDelegationEoi, estimateStakingFee } = useTransactionService();
const { addDelegation } = useDelegationV2State();
const { networkInfo } = useAppState();
const latestParam = networkInfo?.params.bbnStakingParams?.latestParam;
const stakingStatus = networkInfo?.stakingStatus;
Expand Down Expand Up @@ -226,6 +229,13 @@ export const Staking = () => {
signingCallback,
);

addDelegation({
stakingAmount: stakingAmountSat,
stakingTxHashHex,
startHeight: 0,
state: DelegationV2StakingState.INTERMEDIATE_PENDING_VERIFICATION,
});

setStakingTxHashHex(stakingTxHashHex);
setPendingVerificationOpen(true);
} catch (error: Error | any) {
Expand Down
10 changes: 10 additions & 0 deletions src/app/constants.ts
Original file line number Diff line number Diff line change
@@ -1,2 +1,12 @@
export const ONE_SECOND = 1000;
export const ONE_MINUTE = 60 * ONE_SECOND;

export const DELEGATION_ACTIONS = {
STAKE: "STAKE",
UNBOUND: "UNBOUND",
WITHDRAW_ON_EARLY_UNBOUNDING: "WITHDRAW_ON_EARLY_UNBOUNDING",
WITHDRAW_ON_TIMELOCK: "WITHDRAW_ON_TIMELOCK",
WITHDRAW_ON_TIMELOCK_SLASHING: "WITHDRAW_ON_TIMELOCK_SLASHING",
WITHDRAW_ON_EARLY_UNBOUNDING_SLASHING:
"WITHDRAW_ON_EARLY_UNBOUNDING_SLASHING",
} as const;
209 changes: 209 additions & 0 deletions src/app/hooks/services/useDelegationService.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,209 @@
import { useCallback, useMemo } from "react";

import { DELEGATION_ACTIONS as ACTIONS } from "@/app/constants";
import { useDelegationV2State } from "@/app/state/DelegationV2State";
import type { DelegationV2StakingState } from "@/app/types/delegationsV2";

import { useTransactionService } from "./useTransactionService";

export type ActionType = keyof typeof ACTIONS;

interface TxProps {
stakingTxHashHex: string;
stakingTxHex: string;
finalityProviderPk: string;
stakingAmount: number;
paramsVersion: number;
stakingTime: number;
unbondingTxHex: string;
covenantUnbondingSignatures?: {
covenantBtcPkHex: string;
signatureHex: string;
}[];
state: DelegationV2StakingState;
stakingInput: {
finalityProviderPkNoCoordHex: string;
stakingAmountSat: number;
stakingTimeBlocks: number;
};
slashingTxHex: string;
unbondingSlashingTxHex: string;
}

type DelegationCommand = (props: TxProps) => Promise<void>;

export function useDelegationService() {
const {
delegations = [],
fetchMoreDelegations,
hasMoreDelegations,
isLoading,
findDelegationByTxHash,
addDelegation,
} = useDelegationV2State();

const {
submitStakingTx,
submitUnbondingTx,
submitEarlyUnbondedWithdrawalTx,
submitTimelockUnbondedWithdrawalTx,
createDelegationEoi,
} = useTransactionService();

const COMMANDS: Record<ActionType, DelegationCommand> = useMemo(
() => ({
[ACTIONS.STAKE]: ({
stakingInput,
paramsVersion,
stakingTxHashHex,
stakingTxHex,
}: TxProps) =>
submitStakingTx(
stakingInput,
paramsVersion,
stakingTxHashHex,
stakingTxHex,
),

[ACTIONS.UNBOUND]: async ({
stakingInput,
paramsVersion,
stakingTxHex,
unbondingTxHex,
covenantUnbondingSignatures,
}: TxProps) => {
if (!covenantUnbondingSignatures) {
throw new Error("Covenant unbonding signatures not found");
}

await submitUnbondingTx(
stakingInput,
paramsVersion,
stakingTxHex,
unbondingTxHex,
covenantUnbondingSignatures.map((sig) => ({
btcPkHex: sig.covenantBtcPkHex,
sigHex: sig.signatureHex,
})),
);
},

[ACTIONS.WITHDRAW_ON_EARLY_UNBOUNDING]: ({
stakingInput,
paramsVersion,
unbondingTxHex,
}: TxProps) =>
submitEarlyUnbondedWithdrawalTx(
stakingInput,
paramsVersion,
unbondingTxHex,
),

[ACTIONS.WITHDRAW_ON_TIMELOCK]: async ({
stakingInput,
paramsVersion,
stakingTxHex,
}: TxProps) =>
submitTimelockUnbondedWithdrawalTx(
stakingInput,
paramsVersion,
stakingTxHex,
),

[ACTIONS.WITHDRAW_ON_EARLY_UNBOUNDING_SLASHING]: async ({
stakingInput,
paramsVersion,
unbondingSlashingTxHex,
}) => {
if (!unbondingSlashingTxHex) {
throw new Error(
"Unbonding slashing tx not found, can't submit withdrawal",
);
}
await submitEarlyUnbondedWithdrawalTx(
stakingInput,
paramsVersion,
unbondingSlashingTxHex,
);
},

[ACTIONS.WITHDRAW_ON_TIMELOCK_SLASHING]: async ({
stakingInput,
paramsVersion,
slashingTxHex,
}) => {
if (!slashingTxHex) {
throw new Error("Slashing tx not found, can't submit withdrawal");
}
await submitEarlyUnbondedWithdrawalTx(
stakingInput,
paramsVersion,
slashingTxHex,
);
},
}),
[
submitStakingTx,
submitUnbondingTx,
submitEarlyUnbondedWithdrawalTx,
submitTimelockUnbondedWithdrawalTx,
],
);

const executeDelegationAction = useCallback(
async (action: string, txHash: string) => {
const d = findDelegationByTxHash(txHash);

if (!d) {
throw new Error("Delegation not found: " + txHash);
}

const {
stakingTxHashHex,
stakingTxHex,
finalityProviderBtcPksHex,
stakingAmount,
paramsVersion,
stakingTime,
unbondingTxHex,
covenantUnbondingSignatures,
state,
slashingTxHex,
unbondingSlashingTxHex,
} = d;

const finalityProviderPk = finalityProviderBtcPksHex[0];
const stakingInput = {
finalityProviderPkNoCoordHex: finalityProviderPk,
stakingAmountSat: stakingAmount,
stakingTimeBlocks: stakingTime,
};

const execute = COMMANDS[action as ActionType];

await execute?.({
stakingTxHashHex,
stakingTxHex,
stakingAmount,
paramsVersion,
stakingTime,
unbondingTxHex,
covenantUnbondingSignatures,
finalityProviderPk,
state,
stakingInput,
slashingTxHex,
unbondingSlashingTxHex,
});
},
[COMMANDS, findDelegationByTxHash],
);

return {
isLoading,
delegations,
hasMoreDelegations,
fetchMoreDelegations,
executeDelegationAction,
};
}
130 changes: 130 additions & 0 deletions src/app/hooks/storage/useDelegationStorage.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,130 @@
import { useCallback, useEffect, useMemo } from "react";
import { useLocalStorage } from "usehooks-ts";

import {
DELEGATION_STATUSES,
DelegationLike,
DelegationV2,
DelegationV2StakingState as State,
} from "@/app/types/delegationsV2";

export function useDelegationStorage(
key: string,
delegations?: DelegationV2[],
) {
const [pendingDelegations = {}, setPendingDelegations] = useLocalStorage<
Record<string, DelegationLike>
>(`${key}_pending`, {});
const [delegationStatuses = {}, setDelegationStatuses] = useLocalStorage<
Record<string, State>
>(`${key}_statuses`, {});

const delegationMap = useMemo(() => {
return (delegations ?? []).reduce(
(acc, delegation) => ({
...acc,
[delegation.stakingTxHashHex]: delegation,
}),
{} as Record<string, DelegationV2>,
);
}, [delegations]);

const formattedDelegations = useMemo(() => {
const pendingDelegationArr = Object.values(pendingDelegations).map(
(d) =>
({
...d,
stakingTxHex: "",
paramsVersion: 0,
finalityProviderBtcPksHex: [],
stakerBtcPkHex: "",
stakingTime: 0,
endHeight: 0,
unbondingTime: 0,
unbondingTxHex: "",
stakingSlashingTxHex: "",
bbnInceptionHeight: 0,
bbnInceptionTime: 0,
slashingTxHex: "",
unbondingSlashingTxHex: "",
}) as DelegationV2,
);

return pendingDelegationArr.concat(
(delegations ?? [])
.filter((d) => !pendingDelegations[d.stakingTxHashHex])
.map((d) => ({
...d,
state: delegationStatuses[d.stakingTxHashHex] ?? d.state,
})),
);
}, [delegations, pendingDelegations, delegationStatuses]);

useEffect(
function syncPendingDelegations() {
if (!key) return;

setPendingDelegations((delegations) => {
const result = Object.values(delegations)
.filter((d) => !delegationMap[d.stakingTxHashHex])
.reduce(
(acc, d) => ({ ...acc, [d.stakingTxHashHex]: d }),
{} as Record<string, DelegationLike>,
);

return result;
});
},
[key, delegationMap, setPendingDelegations],
);

useEffect(
function syncDelegationStatuses() {
if (!key) return;

setDelegationStatuses((statuses) =>
Object.entries(statuses)
.filter(
([hash, status]) =>
DELEGATION_STATUSES[status] <
DELEGATION_STATUSES[delegationMap[hash].state],
)
.reduce(
(acc, [hash, status]) => ({ ...acc, [hash]: status }),
{} as Record<string, State>,
),
);
},
[key, delegationMap, setDelegationStatuses],
);

const addPendingDelegation = useCallback(
(delegation: DelegationLike) => {
if (!key) return;

setPendingDelegations((delegations) => ({
...delegations,
[delegation.stakingTxHashHex]: {
...delegation,
state: State.INTERMEDIATE_PENDING_VERIFICATION,
},
}));
},
[key, setPendingDelegations],
);

const updateDelegationStatus = useCallback(
(id: string, status: State) => {
if (!key) return;

setDelegationStatuses((statuses) => ({ ...statuses, [id]: status }));
},
[key, setDelegationStatuses],
);

return {
delegations: formattedDelegations,
addPendingDelegation,
updateDelegationStatus,
};
}
Loading