ghost-dao-interface/src/containers/Bridge/BridgeOut.jsx
Uncle Fatso e19c856403
first take on the exodus page
Signed-off-by: Uncle Fatso <uncle.fatso@ghostchain.io>
2026-11-13 19:00:03 +03:00

562 lines
25 KiB
JavaScript

import ReactGA from "react-ga4";
import useSWR from 'swr';
import { isAddress } from "viem";
import { toHex } from "@polkadot-api/utils";
import { useEffect, useMemo, useState, useCallback } from "react";
import { negativeBridgeNumbers, bridgeNumbers } from "../../constants";
import {
Box,
Container,
Typography,
Skeleton,
useMediaQuery,
useTheme,
} from "@mui/material";
import SettingsIcon from '@mui/icons-material/Settings';
import Paper from "../../components/Paper/Paper";
import Metric from "../../components/Metric/Metric";
import SwapCard from "../../components/Swap/SwapCard";
import DataRow from "../../components/DataRow/DataRow";
import PageTitle from "../../components/PageTitle/PageTitle";
import GhostStyledIcon from "../../components/Icon/GhostIcon";
import TokenStack from "../../components/TokenStack/TokenStack";
import SwapCollection from "../../components/Swap/SwapCollection";
import MetricCollection from "../../components/Metric/MetricCollection";
import LinearProgressBar from "../../components/Progress/LinearProgressBar";
import { PrimaryButton } from "../../components/Button";
import { DecimalBigNumber } from "../../helpers/DecimalBigNumber";
import { useUnstableProvider } from "../../hooks/ghost";
import { useGatekeeperApy, useGatekeeperAddress, useGhostedSupply } from "../../hooks/staking";
import { useLocalStorage } from "../../hooks/localstorage";
import { useTokenSymbol, useBalance } from "../../hooks/tokens";
import { formatNumber, formatCurrency } from "../../helpers";
import { BridgeOutSettingsModal } from "./BridgeSettingsModal";
import { BridgeOutConfirmationModal } from "./BridgeConfirmationModal"
const DECIMALS_PREFIX = "bridge-out-decimals";
const ROUNDS_TEXT_MAP = {
Vacant: "Preparing DKG Session",
Round0: "Commitment Hash",
Round1: "Polynomial Commitments",
Round2: "Encrypted Secret Shares",
Round3: "Complaints Review",
Round4: "Complaint Justifications",
Round5: "Group Key Consensus",
Round6: "Verifying Share Registration",
Round7: "Signing Rotation Transaction",
Finalized: "DKG Completed",
};
const BridgeStatusCard = ({ progressPercent, totalValidators, pendingValidators, dkgPhaseType }) => {
const theme = useTheme();
const roundText = ROUNDS_TEXT_MAP[dkgPhaseType];
return (
<Box mt="30px" sx={{ mb: { xs: "0px", md: "-30px" }}}>
<Box display="flex" justifyContent="space-between" alignItems="center" mt="2px">
<Typography variant="caption" fontWeight="bold">
<Box display="flex" flexDirection="row" gap="5px">
<Typography variant="caption" sx={{ fontWeight: "700" }}>
{dkgPhaseType
? <Typography variant="caption">{`${dkgPhaseType}:`}</Typography>
: <Skeleton width="120px" />
}
</Typography>
{roundText
? <Typography variant="caption">{roundText}</Typography>
: <Skeleton width="120px" />
}
</Box>
</Typography>
<Typography variant="caption">
{`Participated ${pendingValidators} out of ${totalValidators} validators`}
</Typography>
</Box>
<LinearProgressBar
variant={typeof progressPercent === "number" ? "determinate" : "indeterminate"}
value={progressPercent ? progressPercent : 0}
height={6}
barColor={theme.colors.feedback.success}
/>
</Box>
);
};
const BridgeOut = ({ chainId, address, config, connect }) => {
const isSmallScreen = useMediaQuery("(max-width: 650px)");
const isSemiSmallScreen = useMediaQuery("(max-width: 480px)");
const isVerySmallScreen = useMediaQuery("(max-width: 379px)");
const [amount, setAmount] = useState("");
const [receiver, setReceiver] = useState(address);
const [allocation, setAllocationInner] = useState(0);
const [confirmOpen, setConfirmOpen] = useState(false);
const [settingsOpen, setSettingsOpen] = useState(false);
const [msSinceLastBlock, setMsSinceLastBlock] = useState(0);
const [customReceiver, setCustomReceiver] = useState(address);
const { useStorageValue, setStorageValue, tryStoreInHistory, CONSTANTS } = useLocalStorage();
const { casperApi, client, account } = useUnstableProvider();
const { gatekeepedApy } = useGatekeeperApy(chainId);
const { symbol: ghstSymbol } = useTokenSymbol(chainId, "GHST");
const { balance: ghstBalance } = useBalance(chainId, "GHST", address);
const { gatekeeperAddress } = useGatekeeperAddress(chainId);
const ghostedSupply = useGhostedSupply(chainId);
const { data: formatDecimals } = useStorageValue(chainId, address, DECIMALS_PREFIX, "5");
const nativeSymbol = useMemo(() => {
const client = config?.getClient();
return client?.chain?.nativeCurrency?.symbol;
}, [config]);
const setFormatDecimals = useCallback((value) => {
const valueNumber = Number(value);
if (valueNumber <= 17 && valueNumber >= 0) {
setStorageValue(chainId, address, DECIMALS_PREFIX, value);
}
}, [chainId, address]);
const setAllocation = (value) => {
const valueNumber = Number(value);
if (valueNumber <= 100 && valueNumber >= 0) {
setAllocationInner(value);
}
}
useEffect(() => {
ReactGA.send({ hitType: "pageview", page: location.pathname });
}, [location]);
const { data: chainProperties } = useSWR(
client ? ['chainProperties', client] : null,
() => client.getChainSpecData(),
);
const { data: dkgRoundPeriod } = useSWR(
casperApi ? ['dkgRoundPeriod', casperApi] : null,
() => casperApi.constants.GhostExodus.DkgRoundPeriod(),
);
const { data: baseEvmAmount } = useSWR(
casperApi ? ['baseEvmAmount', casperApi] : null,
() => casperApi.constants.GhostExodus.BaseEvmAmount(),
);
const { data: existentialDeposit } = useSWR(
casperApi ? ['existentialDeposit', casperApi] : null,
() => casperApi.constants.Balances.ExistentialDeposit(),
);
const { data: currentBlockNumber } = useSWR(
casperApi ? ['currentBlockNumber', casperApi] : null,
() => casperApi.query.System.Number.getValue(),
{
refreshInterval: 12000,
revalidateOnFocus: true
}
);
const { data: accountBalanceRaw } = useSWR(
client ? ['accountBalance', client] : null,
() => casperApi.query.System.Account.getValue(account),
{
refreshInterval: 12000,
revalidateOnFocus: true
}
);
const accountBalance = useMemo(() => {
const decimals = chainProperties ? chainProperties.properties.tokenDecimals : 18;
if (!accountBalanceRaw) return new DecimalBigNumber(0n, decimals);
const balance = accountBalanceRaw.data.free
+ accountBalanceRaw.data.frozen
+ accountBalanceRaw.data.reserved;
return new DecimalBigNumber(balance, decimals);
}, [accountBalanceRaw, chainProperties]);
const { data: qualificationAuthorities } = useSWR(
casperApi ? ['qualificationAuthorities', casperApi] : null,
() => casperApi.query.GhostExodus.QualificationAuthorities.getValue(),
);
const { data: activeEraStart } = useSWR(
casperApi ? ['activeEra', casperApi] : null,
() => casperApi.query.Staking.ActiveEra.getValue(),
);
const { data: totalStaked } = useSWR(
casperApi && activeEraStart && chainProperties ? ['erasTotalStake', casperApi, activeEraStart, chainProperties] : null,
async () => {
const decimals = chainProperties.properties.tokenDecimals;
const total = await casperApi.query.Staking.ErasTotalStake.getValue(activeEraStart.index);
return new DecimalBigNumber(total, decimals);
},
);
const { data: qualificationDkgState } = useSWR(
casperApi ? ['qualificationDkgState', casperApi] : null,
() => casperApi.query.GhostExodus.QualificationDkgState.getValue({ type: "Secp256k1" }),
{
refreshInterval: 12000,
revalidateOnFocus: true
}
);
const { data: counterForExodusRequests } = useSWR(
casperApi ? ['counterForExodusRequests', casperApi] : null,
() => casperApi.query.GhostExodus.CounterForExodusRequests.getValue(),
{
refreshInterval: 12000,
revalidateOnFocus: true
}
);
const minimumBridgeOut = useMemo(() => {
if (counterForExodusRequests === undefined || baseEvmAmount === undefined) return null;
if (counterForExodusRequests > 32) return null;
const scale = 1n << BigInt(counterForExodusRequests);
const scaledMinBalance = existentialDeposit * scale;
return scaledMinBalance + baseEvmAmount;
}, [existentialDeposit, counterForExodusRequests]);
const { data: networkData } = useSWR(
casperApi ? ['networkData', casperApi, chainId] : null,
async () => {
const key = BigInt(chainId);
const res = await casperApi.query.GhostNetworks.Networks.getValue(key);
return res;
},
{
revalidateOnFocus: true
}
);
const { data: networkGatekeeperAmount } = useSWR(
casperApi ? ['networkGatekeeperAmount', casperApi, chainId] : null,
async () => {
const key = BigInt(chainId);
const res = await casperApi.query.GhostNetworks.GatekeeperAmounts.getValue(key);
return res;
},
{
refreshInterval: 12000,
revalidateOnFocus: true
}
);
const gatekeepedAmount = useMemo(() => {
const gatekeeperAmount = new DecimalBigNumber(
networkGatekeeperAmount ? networkGatekeeperAmount : 0n,
chainProperties ? chainProperties.properties.tokenDecimals : 18,
);
if (ghostedSupply.lt(gatekeeperAmount)) return ghostedSupply;
else return gatekeeperAmount;
}, [ghostedSupply, networkGatekeeperAmount, chainProperties]);
const participants = useMemo(() => {
if (!qualificationDkgState) return { total: 0, participated: 0 }
const countOnes32 = (n) => {
let count = 0;
let num = n >>> 0;
while (num > 0) {
num &= num - 1;
count++;
}
return count;
}
const authorities = qualificationDkgState.authorities_indexes
const totalParticipants = authorities.active_bits_count;
const particpatedCount = authorities.data.reduce((sum, word) => sum + countOnes32(word), 0);
return { total: totalParticipants, participated: particpatedCount };
}, [qualificationDkgState]);
useEffect(() => {
setMsSinceLastBlock(0);
const startTime = Date.now();
const interval = setInterval(() => {
setMsSinceLastBlock(Date.now() - startTime);
}, 500);
return () => clearInterval(interval);
}, [currentBlockNumber]);
const progressPercent = useMemo(() => {
if (!currentBlockNumber || !qualificationDkgState || !dkgRoundPeriod) return null;
const total = Number(dkgRoundPeriod);
const end = qualificationDkgState.dkg_state.release_block;
const remaining = end - currentBlockNumber;
const passed = total - remaining;
const progress = passed * 100 / total;
const virtualBlocksPassed = Math.min(msSinceLastBlock / 12000, 1);
const smoothBlocksPassed = passed + virtualBlocksPassed;
const smoothProgress = (smoothBlocksPassed * 100) / total;
return Math.min(Math.max(smoothProgress, 3), 100);
}, [currentBlockNumber, qualificationDkgState, dkgRoundPeriod, msSinceLastBlock]);
const preparedAmount = useMemo(() => {
const decimals = chainProperties ? chainProperties.properties.tokenDecimals : 18;
return new DecimalBigNumber(amount, decimals);
}, [amount, chainProperties]);
const estimatedOutAmount = useMemo(() => {
const decimals = preparedAmount._decimals;
const zero = new DecimalBigNumber(0n, decimals);
const rawAmount = BigInt(preparedAmount._value?.toString() ?? "0");
if (!chainProperties || !networkData || rawAmount <= 0n) {
return { netReceive: zero, allocated: zero };
}
const HUNDRED_PERCENT = 1000000000n;
const outgoingShare = BigInt(networkData?.outgoing_share ?? 0);
const netShare = outgoingShare >= HUNDRED_PERCENT ? 0n : HUNDRED_PERCENT - outgoingShare;
const clampedAllocation = Math.min(100, Math.max(0, Number(allocation) || 0));
const allocationPerbill = BigInt(Math.round(clampedAllocation * 10000000));
const userShare = HUNDRED_PERCENT - allocationPerbill;
const totalNetRaw = (rawAmount * netShare) / HUNDRED_PERCENT;
const netReceiveRaw = (rawAmount * netShare * userShare) / (HUNDRED_PERCENT * HUNDRED_PERCENT);
const allocatedRaw = totalNetRaw - netReceiveRaw;
return {
netReceive: new DecimalBigNumber(netReceiveRaw, decimals),
allocated: new DecimalBigNumber(allocatedRaw, decimals),
};
}, [preparedAmount, allocation, chainProperties, networkData]);
const actionDisabled = useMemo(() => {
if (!networkData) return true;
const differentGatekeepers = gatekeeperAddress.toUpperCase() !== toHex(networkData.gatekeeper).toUpperCase();
const insufficientAmount = preparedAmount.gt(accountBalance);
const bigMinimumBridgeOut = new DecimalBigNumber(
minimumBridgeOut ? minimumBridgeOut: 0n,
chainProperties ? chainProperties.properties.tokenDecimals : 18
);
const notEnoughGatekeeped = gatekeepedAmount.lt(preparedAmount);
const smallAmount = bigMinimumBridgeOut.gt(preparedAmount);
const validReceiver = isAddress(customReceiver ? customReceiver : receiver);
return notEnoughGatekeeped || differentGatekeepers || smallAmount || insufficientAmount || !validReceiver;
}, [gatekeepedAmount, networkData, gatekeeperAddress, minimumBridgeOut, preparedAmount, accountBalance, customReceiver, receiver]);
const startGhostExodus = async () => {
alert("not ready yet");
setConfirmOpen(false);
}
return (
<Box minHeight="calc(100vh - 43px)">
<PageTitle name="GHOST Bridge-Out" subtitle={`${negativeBridgeNumbers()} Bridge-Out from ${bridgeNumbers()} Stake\u00B2`} />
<Container
style={{
paddingLeft: isSmallScreen || isVerySmallScreen ? "0" : "3.3rem",
paddingRight: isSmallScreen || isVerySmallScreen ? "0" : "3.3rem",
}}
>
<BridgeOutConfirmationModal
chainId={chainId}
isOpen={confirmOpen}
onClose={() => setConfirmOpen(false)}
preparedAmount={preparedAmount}
estimatedOutAmount={estimatedOutAmount}
formatDecimals={formatDecimals}
ghstSymbol={ghstSymbol}
externalSymbol={chainProperties ? chainProperties.properties.tokenSymbol : "CSPR"}
receiver={customReceiver ? customReceiver : receiver}
sender={account}
startGhostExodus={startGhostExodus}
allocation={allocation}
nativeSymbol={nativeSymbol}
/>
<BridgeOutSettingsModal
isOpen={settingsOpen}
onClose={() => setSettingsOpen(false)}
decimals={formatDecimals}
setDecimals={setFormatDecimals}
receiver={customReceiver}
setReceiver={setCustomReceiver}
allocation={allocation}
setAllocation={setAllocation}
nativeSymbol={nativeSymbol}
/>
<Box mt="15px" display="flex" flexDirection="column" justifyContent="space-between" alignItems="center">
<Paper
fullWidth
enableBackground
headerContent={
<Box display="flex" gap="5px">
<Typography variant="h6">DKG</Typography>
{qualificationDkgState
? <Typography sx={{ fontWeight: "700" }} variant="h6">{
qualificationDkgState.dkg_state.dkg_phase.type === "Finalized"
? "Finalized"
: "In-Progress"
}</Typography>
: <Skeleton width="120px" />
}
</Box>
}
>
<MetricCollection>
<Metric
metric={`${formatNumber(gatekeepedApy, 2)}%`}
label={`Stake\u00B2 APY`}
tooltip="some description to be added"
/>
<Metric
metric={`${formatNumber(totalStaked ? totalStaked.toString() : "0", 2)} ${chainProperties ? chainProperties.properties.tokenSymbol : "CSPR"}`}
isLoading={!totalStaked}
label="Bridge Security Stake"
tooltip="some description to be added"
/>
<Metric
label="Bridge-Out Queue"
tooltip="some description to be added"
isLoading={!Number.isFinite(counterForExodusRequests)}
metric={`${formatNumber(counterForExodusRequests)} (~10 mins)`}
/>
</MetricCollection>
<BridgeStatusCard
progressPercent={progressPercent}
totalValidators={participants.total}
pendingValidators={participants.participated}
dkgPhaseType={qualificationDkgState?.dkg_state.dkg_phase.type}
/>
</Paper>
<Box width="100%" maxWidth="420px" mt="15px">
<Paper
fullWidth
enableBackground
topRight={
<GhostStyledIcon
component={SettingsIcon}
viewBox="0 0 23 23"
style={{ display: "flex", alignItems: "center", cursor: "pointer" }}
onClick={() => setSettingsOpen(true)}
/>
}
headerContent={
<Typography variant="h6">Bridge-Out</Typography>
}
>
<Box maxWidth="390px" display="flex" flexDirection="column" justifyContent="center" gap="3px">
<SwapCollection
iconNotNeeded
UpperSwapCard={
<SwapCard
id="from"
token={
<TokenStack
tokens={[chainProperties ? chainProperties.properties.tokenSymbol : "CSPR"]}
sx={{ fontSize: "25px", height: "30px" }}
/>
}
tokenName={ghstSymbol}
info={
(!isSemiSmallScreen ? "Balance: " : "") +
formatCurrency(
accountBalance.toString(),
formatDecimals,
chainProperties ? chainProperties.properties.tokenSymbol : "CSPR",
)
}
endString="Max"
value={amount}
endStringOnClick={() => setAmount(accountBalance.toString())}
onChange={event => setAmount(event.currentTarget.value)}
inputProps={{ "data-testid": "fromInput" }}
/>}
LowerSwapCard={
<SwapCard
id="to"
token={
<TokenStack
chainTokenNames={[nativeSymbol]}
tokens={[ghstSymbol]}
sx={{ fontSize: "25px", height: "30px" }}
/>
}
info={(!isSemiSmallScreen ? "Balance: " : "") + formatCurrency(ghstBalance.toString(), formatDecimals, ghstSymbol)}
tokenName={ghstSymbol}
value={estimatedOutAmount.netReceive}
inputProps={{ "data-testid": "toInput" }}
/>
}
/>
<Box m="15px 0" display="flex" flexDirection="column" gap="1px" sx={{ "& .DataRow-root": { margin: "0 !important" } }}>
<DataRow
title={<Typography variant="caption">Min Bridge-Out</Typography>}
tooltip="Minimum amount that could be handled by the bridge to avoid dust balances."
balance={<Typography variant="caption">{
formatCurrency(
new DecimalBigNumber(
minimumBridgeOut ? minimumBridgeOut : 0n,
chainProperties ? chainProperties.properties.tokenDecimals : 18,
),
formatDecimals,
ghstSymbol
)
}</Typography>}
/>
<DataRow
title={<Typography variant="caption">Gatekeeped Amount</Typography>}
tooltip="Minimum amount that could be handled by the bridge to avoid dust balances."
balance={<Typography variant="caption">{
formatCurrency(gatekeepedAmount, formatDecimals, ghstSymbol)
}</Typography>}
/>
</Box>
<PrimaryButton
fullWidth
disabled={actionDisabled}
onClick={() => setConfirmOpen(true)}
>
Bridge-Out
</PrimaryButton>
</Box>
</Paper>
</Box>
</Box>
</Container>
</Box>
)
}
export default BridgeOut;