bridge-out draft page added

Signed-off-by: Uncle Fatso <uncle.fatso@ghostchain.io>
This commit is contained in:
Uncle Fatso 2026-11-12 17:56:34 +03:00
parent b65ab19873
commit 7d4085f226
Signed by: f4ts0
GPG Key ID: 565F4F2860226EBB
13 changed files with 1064 additions and 189 deletions

View File

@ -1,7 +1,7 @@
{
"name": "ghost-dao-interface",
"private": true,
"version": "0.8.9",
"version": "0.8.10",
"type": "module",
"scripts": {
"dev": "vite",

View File

@ -37,6 +37,7 @@ const StakeContainer = lazy(() => import("./containers/Stake/StakeContainer"));
const TreasuryDashboard = lazy(() => import("./containers/TreasuryDashboard/TreasuryDashboard"));
const Dex = lazy(() => import("./containers/Dex/Dex"));
const BridgeIn = lazy(() => import("./containers/Bridge/BridgeIn"));
const BridgeOut = lazy(() => import("./containers/Bridge/BridgeOut"));
const NotFound = lazy(() => import("./containers/NotFound/NotFound"));
const Governance = lazy(() => import("./containers/Governance/Governance"));
const ProposalDetails = lazy(() => import("./containers/Governance/ProposalDetails"));
@ -201,6 +202,7 @@ function App() {
<Route path="bonds/:id" element={<BondModalContainer config={config} connect={tryConnectInjected} address={address} chainId={addressChainId ? addressChainId : chainId} />} />
<Route path="stake" element={<StakeContainer config={config} connect={tryConnectInjected} address={address} chainId={addressChainId ? addressChainId : chainId} />} />
<Route path="bridge-in" element={<BridgeIn config={config} connect={tryConnectInjected} address={address} chainId={addressChainId ? addressChainId : chainId} />} />
<Route path="bridge-out" element={<BridgeOut config={config} connect={tryConnectInjected} address={address} chainId={addressChainId ? addressChainId : chainId} />} />
<Route path="dex/:name" element={<Dex config={config} connect={tryConnectInjected} address={address} chainId={addressChainId ? addressChainId : chainId} />} />
<Route path="governance" element={<Governance config={config} connect={tryConnectInjected} address={address} chainId={addressChainId ? addressChainId : chainId} />} />
<Route path="governance/:id" element={<ProposalDetails config={config} connect={tryConnectInjected} address={address} chainId={addressChainId ? addressChainId : chainId} />} />

View File

@ -32,6 +32,7 @@ import CasinoIcon from '@mui/icons-material/Casino';
import ErrorOutlineIcon from '@mui/icons-material/ErrorOutline';
import BookIcon from '@mui/icons-material/Book';
import CurrencyExchangeIcon from '@mui/icons-material/CurrencyExchange';
import MergeIcon from '@mui/icons-material/Merge';
import GhostIcon from "../../assets/icons/ghost-nav-header.svg?react";
import NavItem from "../NavItem/NavItem";
@ -41,7 +42,7 @@ import BondIcon from "../Icon/BondIcon";
import StakeIcon from "../Icon/StakeIcon";
import WrapIcon from "../Icon/WrapIcon";
import { isNetworkAvailable, bridgeNumbers } from "../../constants";
import { isNetworkAvailable, negativeBridgeNumbers, bridgeNumbers } from "../../constants";
import { AVAILABLE_DEXES } from "../../constants/dexes";
import { ECOSYSTEM } from "../../constants/ecosystem";
import { DecimalBigNumber } from "../../helpers/DecimalBigNumber";
@ -185,6 +186,7 @@ const NavContent = ({ chainId, addressChainId, address }) => {
}
/>
<NavItem icon={ForkRightIcon} label={`${bridgeNumbers()} Bridge-In`} to={`/${chainName}/bridge-in`} />
<NavItem icon={MergeIcon} label={`${negativeBridgeNumbers()} Bridge-Out`} to={`/${chainName}/bridge-out`} />
{/* <NavItem icon={GavelIcon} label={`Governance`} to={`/${chainName}/governance`} /> */}
<NavItem icon={HistoryIcon} chipColor="warning" chip={pendingTransactions} label="Transaction History" to={`/${chainName}/history`} />

View File

@ -63,3 +63,8 @@ export const bridgeNumbers = () => {
const number = 1 + CONNECTED_NETWORKS * 3;
return `(${number}, ${number})`;
}
export const negativeBridgeNumbers = () => {
const number = 1 + CONNECTED_NETWORKS * 3;
return `(-${number}, -${number})`;
}

View File

@ -0,0 +1,348 @@
import { useState, useMemo } from "react";
import { Box, Typography, Link } from "@mui/material";
import CloseIcon from '@mui/icons-material/Close';
import CheckIcon from '@mui/icons-material/Check';
import ContentPasteIcon from '@mui/icons-material/ContentPaste';
import ArrowDropDownIcon from '@mui/icons-material/ArrowDropDown';
import GhostStyledIcon from "../../components/Icon/GhostIcon";
import Metric from "../../components/Metric/Metric";
import Modal from "../../components/Modal/Modal";
import TokenStack from "../../components/TokenStack/TokenStack";
import DataRow from "../../components/DataRow/DataRow";
import { PrimaryButton, SecondaryButton } from "../../components/Button";
import { formatNumber, formatCurrency, shorten } from "../../helpers";
import { useTotalSupply, useTokenDecimals } from "../../hooks/tokens";
import { useRegistryIndex, useCurrentIndex } from "../../hooks/staking";
import { useTotalReservesRaw, useRegisteredAt, useCalculatorFraction } from "../../hooks/treasury";
import { DecimalBigNumber } from "../../helpers/DecimalBigNumber";
import { BridgeGhostAddressCard } from "./BridgeGhostAddress";
export const BridgeInConfirmationModal = ({
isOpen,
onClose,
preparedAmount,
estimatedOutAmount,
formatDecimals,
externalSymbol,
ghstSymbol,
nativeSymbol,
receiver,
sender,
startGhostBridge
}) => {
const [isPending, setIsPending] = useState(false);
const [copiedIndex, setCopiedIndex] = useState(null);
const copyToClipboard = (text, index) => {
navigator.clipboard.writeText(text).then(() => {
setCopiedIndex(index);
setTimeout(() => setCopiedIndex(null) , 800);
});
};
const onSubmit = async () => {
setIsPending(true);
try {
await startGhostBridge();
} finally {
setIsPending(false);
}
}
return (
<Modal
maxWidth="426px"
minHeight="200px"
open={isOpen}
headerContent={<Typography variant="h4">Confirm Bridge-In</Typography>}
onClose={!isPending && onClose}
topRight={
<GhostStyledIcon
viewBox="0 0 23 23"
component={CloseIcon}
/>
}
>
<Box display="flex" flexDirection="column">
<Box display="flex" flexDirection="row" justifyContent="space-between" alignItems="center">
<Box display="flex" flexDirection="column">
<Metric
label="To Bridge"
metric={formatNumber(preparedAmount, formatDecimals)}
/>
<Box
sx={{ background: "" }}
height="120px"
display="flex"
flexDirection="column"
justifyContent="center"
alignItems="center"
>
<TokenStack
parentSx={{
height: "80px",
"& svg:nth-of-type(2)": {
transform: "translate(50%, -30%)",
zIndex: 100,
}
}}
sx={{ transform: "scale(1.65)", }}
tokens={[ghstSymbol]}
chainTokenNames={[nativeSymbol]}
/>
<Typography>{ghstSymbol}</Typography>
</Box>
</Box>
<GhostStyledIcon sx={{ transform: "rotate(-90deg)" }} component={ArrowDropDownIcon} />
<Box display="flex" flexDirection="column">
<Metric label="To Receive" metric={formatNumber(estimatedOutAmount, formatDecimals)} />
<Box
sx={{ background: "" }}
height="120px"
display="flex"
flexDirection="column"
justifyContent="center"
alignItems="center"
gap="0"
>
<TokenStack
parentSx={{
height: "80px",
"& svg:nth-of-type(2)": {
transform: "translate(50%, -30%)",
zIndex: 100,
}
}}
sx={{ transform: "scale(1.65)", }}
tokens={[externalSymbol]}
/>
<Typography>{externalSymbol}</Typography>
</Box>
</Box>
</Box>
<Box pb="20px" pt="20px" display="flex" flexDirection="column">
<Box display="flex" flexDirection="row" justifyContent="space-between">
<Typography variant="caption">Sender Address</Typography>
<Link
style={{ display: "flex", flexDirection: "row", justifyContent: "center", alignItems: "center" }}
onClick={() => copyToClipboard(sender, 0)}
>
<Typography variant="caption">{sender ? shorten(sender, 10, -8) : ""}</Typography>
<GhostStyledIcon
sx={{ marginLeft: "5px", width: "12px", height: "12px" }}
viewBox="0 0 25 25"
component={copiedIndex === 0 ? CheckIcon : ContentPasteIcon}
/>
</Link>
</Box>
<Box display="flex" flexDirection="row" justifyContent="space-between">
<Typography variant="caption">Destination Address</Typography>
<Link
style={{ display: "flex", flexDirection: "row", justifyContent: "center", alignItems: "center" }}
onClick={() => copyToClipboard(receiver, 1)}
>
<Typography variant="caption">{receiver ? shorten(receiver, 10, -8) : ""}</Typography>
<GhostStyledIcon
sx={{ marginLeft: "5px", width: "12px", height: "12px" }}
viewBox="0 0 25 25"
component={copiedIndex === 1 ? CheckIcon : ContentPasteIcon}
/>
</Link>
</Box>
</Box>
<PrimaryButton
fullWidth
disabled={isPending}
onClick={onSubmit}
>
{isPending ? "Pending..." : "Confirm"}
</PrimaryButton>
</Box>
</Modal>
)
}
export const BridgeOutConfirmationModal = ({
chainId,
isOpen,
onClose,
preparedAmount,
estimatedOutAmount,
formatDecimals,
externalSymbol,
ghstSymbol,
nativeSymbol,
receiver,
sender,
startGhostExodus,
allocation
}) => {
const [isPending, setIsPending] = useState(false);
const [copiedIndex, setCopiedIndex] = useState(null);
const { currentIndex } = useCurrentIndex(chainId);
const { totalSupply } = useTotalSupply(chainId, "FTSO");
const { registryIndex } = useRegistryIndex(chainId);
const totalReserves = useTotalReservesRaw(chainId);
const registeredAt = useRegisteredAt(chainId, registryIndex);
const calculatorFraction = useCalculatorFraction(chainId, registeredAt);
const allocationEstimation = useMemo(() => {
// uint256 totalSupply = IERC20(FTSO).totalSupply();
// uint256 reservesToSend = FullMath.mulDiv(amount, totalReserves, totalSupply);
// totalReserves = totalReserves - reservesToSend;
//
// value = FullMath.mulDiv(reservesToSend, 1e18, IBondingCalculator(bondCalculator[reserveToken]).fraction());
// value = FullMath.mulDiv(value, 10**IERC20Metadata(reserveToken).decimals(), 1e9);
const zero = new DecimalBigNumber(0n, 0);
if (calculatorFraction.eq(zero) || totalSupply.eq(zero)) return null;
const reservesToSend = estimatedOutAmount.allocated.mul(currentIndex).mul(totalReserves).div(totalSupply);
return reservesToSend.div(calculatorFraction);
}, [estimatedOutAmount, totalSupply, totalReserves, calculatorFraction]);
const copyToClipboard = (text, index) => {
navigator.clipboard.writeText(text).then(() => {
setCopiedIndex(index);
setTimeout(() => setCopiedIndex(null) , 800);
});
};
const onSubmit = async () => {
setIsPending(true);
try {
await startGhostExodus();
} finally {
setIsPending(false);
}
}
return (
<Modal
maxWidth="426px"
minHeight="200px"
open={isOpen}
headerContent={<Typography variant="h4">Confirm Bridge-Out</Typography>}
onClose={!isPending && onClose}
topRight={
<GhostStyledIcon
viewBox="0 0 23 23"
component={CloseIcon}
/>
}
>
<Box display="flex" flexDirection="column">
<Box display="flex" flexDirection="row" justifyContent="space-between" alignItems="center">
<Box display="flex" flexDirection="column">
<Metric
label="To Bridge"
metric={formatNumber(preparedAmount, formatDecimals)}
/>
<Box
sx={{ background: "" }}
height="120px"
display="flex"
flexDirection="column"
justifyContent="center"
alignItems="center"
>
<TokenStack
parentSx={{
height: "80px",
"& svg:nth-of-type(2)": {
transform: "translate(50%, -30%)",
zIndex: 100,
}
}}
sx={{ transform: "scale(1.65)", }}
tokens={[ghstSymbol]}
chainTokenNames={[nativeSymbol]}
/>
<Typography>{ghstSymbol}</Typography>
</Box>
</Box>
<GhostStyledIcon sx={{ transform: "rotate(-90deg)" }} component={ArrowDropDownIcon} />
<Box display="flex" flexDirection="column">
<Metric label="To Receive" metric={formatNumber(estimatedOutAmount.netReceive, formatDecimals)} />
<Box
sx={{ background: "" }}
height="120px"
display="flex"
flexDirection="column"
justifyContent="center"
alignItems="center"
gap="0"
>
<TokenStack
parentSx={{
height: "80px",
"& svg:nth-of-type(2)": {
transform: "translate(50%, -30%)",
zIndex: 100,
}
}}
sx={{ transform: "scale(1.65)", }}
tokens={[externalSymbol]}
/>
<Typography>{externalSymbol}</Typography>
</Box>
</Box>
</Box>
<Box pb="20px" pt="20px" display="flex" flexDirection="column">
<Box display="flex" flexDirection="row" justifyContent="space-between">
<Typography variant="caption">Sender Address</Typography>
<Link
style={{ display: "flex", flexDirection: "row", justifyContent: "center", alignItems: "center" }}
onClick={() => copyToClipboard(sender, 0)}
>
<Typography variant="caption">{sender ? shorten(sender, 10, -8) : ""}</Typography>
<GhostStyledIcon
sx={{ marginLeft: "5px", width: "12px", height: "12px" }}
viewBox="0 0 25 25"
component={copiedIndex === 0 ? CheckIcon : ContentPasteIcon}
/>
</Link>
</Box>
<Box display="flex" flexDirection="row" justifyContent="space-between">
<Typography variant="caption">Destination Address</Typography>
<Link
style={{ display: "flex", flexDirection: "row", justifyContent: "center", alignItems: "center" }}
onClick={() => copyToClipboard(receiver, 1)}
>
<Typography variant="caption">{receiver ? shorten(receiver, 10, -8) : ""}</Typography>
<GhostStyledIcon
sx={{ marginLeft: "5px", width: "12px", height: "12px" }}
viewBox="0 0 25 25"
component={copiedIndex === 1 ? CheckIcon : ContentPasteIcon}
/>
</Link>
</Box>
{allocation > 0 && <Box display="flex" flexDirection="row" justifyContent="space-between">
<Typography variant="caption">{nativeSymbol} Allocation</Typography>
<Typography variant="caption">
{formatNumber(allocation)}% (~{formatCurrency(allocationEstimation, formatDecimals, nativeSymbol)})
</Typography>
</Box>}
</Box>
<PrimaryButton
fullWidth
disabled={isPending}
onClick={onSubmit}
>
{isPending ? "Pending..." : "Confirm"}
</PrimaryButton>
</Box>
</Modal>
)
}

View File

@ -1,4 +1,5 @@
import { useState, useEffect } from "react";
import { isAddress } from 'viem';
import { ss58Decode } from "@polkadot-labs/hdkd-helpers";
import { FormControl, OutlinedInput } from "@mui/material";
@ -10,23 +11,23 @@ import GhostStyledIcon from "../../components/Icon/GhostIcon";
import { shorten } from "../../helpers";
export const BridgeGhostAddressCard = ({ receiver, setReceiver, isCard, readOnly = false }) => {
export const BridgeGhostAddressCard = ({ receiver, setReceiver, isCard, isEvm = false, readOnly = false }) => {
const [inputFocused, setInputFocused] = useState(false);
const [innerReceiver, setInnerReceiver] = useState(receiver);
useEffect(() => {
try {
const [publicKey, prefix] = ss58Decode(innerReceiver);
if (prefix !== 1995 && prefix !== 1996) {
throw new Error("bad prefix");
if (isEvm) {
if (!isAddress(innerReceiver)) throw new Error("bad evm address")
} else {
const [publicKey, prefix] = ss58Decode(innerReceiver);
if (prefix !== 1995 && prefix !== 1996) throw new Error("bad prefix");
}
setReceiver(innerReceiver);
} catch (err) {
setReceiver(undefined)
}
}, [innerReceiver]);
console.log(readOnly)
}, [innerReceiver, isEvm]);
if (isCard) {
return (
@ -39,7 +40,10 @@ export const BridgeGhostAddressCard = ({ receiver, setReceiver, isCard, readOnly
onMouseLeave={() => setInputFocused(true)}
onMouseEnter={() => setInputFocused(false)}
onChange={event => setInnerReceiver(event.currentTarget.value)}
placeholder={receiver ? shorten(receiver, 15, -10) : "GHOST address (sf prefixed)"}
placeholder={receiver
? shorten(receiver, 15, -10)
: isEvm ? "EVM address (0x prefixed)" : "GHOST address (sf prefixed)"
}
value={receiver ? "" : innerReceiver}
inputProps={{ "data-testid": "fromInput" }}
endString={receiver
@ -65,7 +69,10 @@ export const BridgeGhostAddressCard = ({ receiver, setReceiver, isCard, readOnly
onMouseLeave={() => setInputFocused(true)}
onMouseEnter={() => setInputFocused(false)}
onChange={event => setInnerReceiver(event.currentTarget.value)}
placeholder={receiver ? shorten(receiver, 15, -10) : "GHOST address (sf prefixed)"}
placeholder={receiver
? shorten(receiver, 15, -10)
: isEvm ? "EVM address (0x prefixed)" : "GHOST address (sf prefixed)"
}
value={receiver ? "" : innerReceiver}
endAdornment={receiver
? <GhostStyledIcon color="success" viewBox="0 0 25 25" component={CheckIcon} />

View File

@ -28,7 +28,7 @@ import DataRow from "../../components/DataRow/DataRow";
import { PrimaryButton } from "../../components/Button";
import { BridgeInSettingsModal } from "./BridgeSettingsModal";
import { BridgeInConfirmationModal } from "./BridgeInConfirmationModal";
import { BridgeInConfirmationModal } from "./BridgeConfirmationModal";
import {
ghost,
@ -84,10 +84,7 @@ const BridgeStatusCard = ({ progressPercent, totalValidators, pendingValidators,
variant={typeof progressPercent === "number" ? "determinate" : "indeterminate"}
value={progressPercent ? progressPercent : 0}
height={6}
barColor={tapestryDraft
? theme.colors.feedback.success
: theme.colors.feedback.error
}
barColor={theme.colors.feedback.success}
/>
</Box>
);
@ -126,9 +123,6 @@ const BridgeIn = ({ chainId, address, config, connect }) => {
const { data: chainProperties } = useSWR(
client ? ['chainProperties', client] : null,
() => client.getChainSpecData(),
{
revalidateOnFocus: true
}
);
const { data: accountBalanceRaw } = useSWR(
@ -521,8 +515,7 @@ const BridgeIn = ({ chainId, address, config, connect }) => {
id="to"
token={
<TokenStack
chainTokenNames={[nativeSymbol]}
tokens={["GHST"]}
tokens={[chainProperties ? chainProperties.properties.tokenSymbol : "CSPR"]}
sx={{ fontSize: "25px", height: "30px" }}
/>
}
@ -534,7 +527,7 @@ const BridgeIn = ({ chainId, address, config, connect }) => {
chainProperties ? chainProperties.properties.tokenSymbol : "CSPR",
)
}
tokenName={"GHST"}
tokenName={chainProperties ? chainProperties.properties.tokenSymbol : "CSPR"}
value={estimatedOutAmount}
inputProps={{ "data-testid": "toInput" }}
/>

View File

@ -1,165 +0,0 @@
import { useState } from "react";
import { Box, Typography, Link } from "@mui/material";
import CloseIcon from '@mui/icons-material/Close';
import CheckIcon from '@mui/icons-material/Check';
import ContentPasteIcon from '@mui/icons-material/ContentPaste';
import ArrowDropDownIcon from '@mui/icons-material/ArrowDropDown';
import GhostStyledIcon from "../../components/Icon/GhostIcon";
import Metric from "../../components/Metric/Metric";
import Modal from "../../components/Modal/Modal";
import TokenStack from "../../components/TokenStack/TokenStack";
import DataRow from "../../components/DataRow/DataRow";
import { PrimaryButton, SecondaryButton } from "../../components/Button";
import { formatNumber, shorten } from "../../helpers";
import { BridgeGhostAddressCard } from "./BridgeGhostAddress";
export const BridgeInConfirmationModal = ({
isOpen,
onClose,
preparedAmount,
estimatedOutAmount,
formatDecimals,
externalSymbol,
ghstSymbol,
nativeSymbol,
receiver,
sender,
startGhostBridge
}) => {
const [isPending, setIsPending] = useState(false);
const [copiedIndex, setCopiedIndex] = useState(null);
const copyToClipboard = (text, index) => {
navigator.clipboard.writeText(text).then(() => {
setCopiedIndex(index);
setTimeout(() => setCopiedIndex(null) , 800);
});
};
const onSubmit = async () => {
setIsPending(true);
try {
await startGhostBridge();
} finally {
setIsPending(false);
}
}
return (
<Modal
maxWidth="426px"
minHeight="200px"
open={isOpen}
headerContent={<Typography variant="h4">Confirm Bridge-In</Typography>}
onClose={!isPending && onClose}
topRight={
<GhostStyledIcon
viewBox="0 0 23 23"
component={CloseIcon}
/>
}
>
<Box display="flex" flexDirection="column">
<Box display="flex" flexDirection="row" justifyContent="space-between" alignItems="center">
<Box display="flex" flexDirection="column">
<Metric
label="To Bridge"
metric={formatNumber(preparedAmount, formatDecimals)}
/>
<Box
sx={{ background: "" }}
height="120px"
display="flex"
flexDirection="column"
justifyContent="center"
alignItems="center"
>
<TokenStack
parentSx={{
height: "80px",
"& svg:nth-of-type(2)": {
transform: "translate(50%, -30%)",
zIndex: 100,
}
}}
sx={{ transform: "scale(1.65)", }}
tokens={[ghstSymbol]}
chainTokenNames={[nativeSymbol]}
/>
<Typography>{ghstSymbol}</Typography>
</Box>
</Box>
<GhostStyledIcon sx={{ transform: "rotate(-90deg)" }} component={ArrowDropDownIcon} />
<Box display="flex" flexDirection="column">
<Metric label="To Receive" metric={formatNumber(estimatedOutAmount, formatDecimals)} />
<Box
sx={{ background: "" }}
height="120px"
display="flex"
flexDirection="column"
justifyContent="center"
alignItems="center"
gap="0"
>
<TokenStack
parentSx={{
height: "80px",
"& svg:nth-of-type(2)": {
transform: "translate(50%, -30%)",
zIndex: 100,
}
}}
sx={{ transform: "scale(1.65)", }}
tokens={[externalSymbol]}
/>
<Typography>{externalSymbol}</Typography>
</Box>
</Box>
</Box>
<Box pb="20px" pt="20px" display="flex" flexDirection="column">
<Box display="flex" flexDirection="row" justifyContent="space-between">
<Typography>Sender Address</Typography>
<Link
style={{ display: "flex", flexDirection: "row", justifyContent: "center", alignItems: "center" }}
onClick={() => copyToClipboard(sender, 0)}
>
<Typography>{sender ? shorten(sender, 10, -8) : ""}</Typography>
<GhostStyledIcon
sx={{ marginLeft: "5px", width: "12px", height: "12px" }}
viewBox="0 0 25 25"
component={copiedIndex === 0 ? CheckIcon : ContentPasteIcon}
/>
</Link>
</Box>
<Box display="flex" flexDirection="row" justifyContent="space-between">
<Typography>Destination Address</Typography>
<Link
style={{ display: "flex", flexDirection: "row", justifyContent: "center", alignItems: "center" }}
onClick={() => copyToClipboard(receiver, 1)}
>
<Typography>{receiver ? shorten(receiver, 10, -8) : ""}</Typography>
<GhostStyledIcon
sx={{ marginLeft: "5px", width: "12px", height: "12px" }}
viewBox="0 0 25 25"
component={copiedIndex === 1 ? CheckIcon : ContentPasteIcon}
/>
</Link>
</Box>
</Box>
<PrimaryButton
fullWidth
disabled={isPending}
onClick={onSubmit}
>
{isPending ? "Pending..." : "Confirm"}
</PrimaryButton>
</Box>
</Modal>
)
}

View File

@ -0,0 +1,526 @@
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 } 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 { 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 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 smallAmount = bigMinimumBridgeOut.gt(preparedAmount);
const validReceiver = isAddress(customReceiver ? customReceiver : receiver);
return differentGatekeepers || smallAmount || insufficientAmount || !validReceiver;
}, [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}
nativeSymbol={nativeSymbol}
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" }}
/>
}
/>
<DataRow
title={`Min Bridge-Out`}
tooltip="Minimum amount that could be handled by the bridge to avoid dust balances."
balance={<span>{
formatCurrency(
new DecimalBigNumber(
minimumBridgeOut ? minimumBridgeOut : 0n,
chainProperties ? chainProperties.properties.tokenDecimals : 18,
),
formatDecimals,
ghstSymbol
)
}</span>}
/>
<PrimaryButton
fullWidth
disabled={actionDisabled}
onClick={() => setConfirmOpen(true)}
>
Bridge-Out
</PrimaryButton>
</Box>
</Paper>
</Box>
</Box>
</Container>
</Box>
)
}
export default BridgeOut;

View File

@ -36,9 +36,9 @@ export const BridgeInSettingsModal = ({ isOpen, onClose, decimals, setDecimals,
<Box mt="32px">
<InputLabel htmlFor="recipient">Destination address</InputLabel>
<BridgeGhostAddressCard receiver={receiver} setReceiver={setReceiver} />
<Box mt="8px">
<Typography variant="body2" color="textSecondary">
<BridgeGhostAddressCard receiver={receiver} setReceiver={setReceiver} />
<Typography mt="8px" variant="body2" color="textSecondary">
Custom recipient address of bridged assets
</Typography>
</Box>
@ -46,3 +46,82 @@ export const BridgeInSettingsModal = ({ isOpen, onClose, decimals, setDecimals,
</Modal>
)
}
export const BridgeOutSettingsModal = ({
isOpen,
onClose,
decimals,
setDecimals,
receiver,
setReceiver,
allocation,
setAllocation,
nativeSymbol
}) => {
return (
<Modal
data-testid="bridge-in-settings-modal"
maxWidth="476px"
headerContent={<Typography variant="h6">Bridge-Out Settings</Typography>}
open={isOpen}
onClose={onClose}
minHeight={"100px"}
>
<Box display="flex" flexDirection="column" gap="15px">
<Box mt="8px">
<InputLabel htmlFor="allocation">{nativeSymbol} allocation</InputLabel>
<Box mt="8px">
<FormControl variant="outlined" color="primary" fullWidth>
<OutlinedInput
inputProps={{ "data-testid": "allocation-to-native" }}
type="number"
id="allocation-to-native"
value={allocation}
onChange={event => setAllocation(event.currentTarget.value)}
endAdornment="%"
/>
</FormControl>
</Box>
<Box mt="8px">
<Typography variant="body2" color="textSecondary">
Bridge-Out share converted to {nativeSymbol}
</Typography>
</Box>
</Box>
<Box mt="8px">
<InputLabel htmlFor="decimals">Decimal representation</InputLabel>
<Box mt="8px">
<FormControl variant="outlined" color="primary" fullWidth>
<OutlinedInput
inputProps={{ "data-testid": "decimals-to-wait" }}
type="number"
id="decimals-to-wait"
value={decimals}
onChange={event => setDecimals(event.currentTarget.value)}
endAdornment="decimals"
/>
</FormControl>
</Box>
<Box mt="8px">
<Typography variant="body2" color="textSecondary">
Number of decimals to be shown in token balances
</Typography>
</Box>
</Box>
<Box mt="8px">
<InputLabel htmlFor="recipient">Destination address</InputLabel>
<Box mt="8px">
<BridgeGhostAddressCard isEvm receiver={receiver} setReceiver={setReceiver} />
<Typography mt="8px" variant="body2" color="textSecondary">
Custom recipient address of bridged assets
</Typography>
</Box>
</Box>
</Box>
</Modal>
)
}

View File

@ -17,6 +17,20 @@ import { DecimalBigNumber } from "../../helpers/DecimalBigNumber";
import { executeOnChainTransaction, getTokenDecimals } from "../helpers";
import { useCirculatingSupply } from "../tokens";
export const useRegistryIndex = (chainId) => {
const { gatekeeperAddress } = useGatekeeperAddress(chainId);
const { data, isLoading } = useReadContract({
abi: GatekeeperAbi,
address: gatekeeperAddress,
functionName: "REGISTRY_INDEX",
scopeKey: `REGISTRY_INDEX-${chainId}-${gatekeeperAddress}`,
chainId: chainId,
});
return { registryIndex: !isLoading ? data : 69n };
}
export const useWeaverMaximumSlots = (chainId) => {
const { gatekeeperAddress } = useGatekeeperAddress(chainId);

View File

@ -106,6 +106,23 @@ export const useAllowance = (chainId, name, owner, spender, decimals) => {
return { allowance, refetch };
}
export const useTokenDecimals = (chainId, name) => {
const contractAddress = getTokenAddress(chainId, name);
const { data, refetch } = useReadContract({
abi: getTokenAbi(name),
address: contractAddress,
functionName: "decimals",
scopeKey: `decimals-${contractAddress}-${chainId}`,
chainId: chainId,
});
let decimals = data ? data : "";
return { decimals, refetch };
}
export const useTokenSymbol = (chainId, name) => {
const contractAddress = getTokenAddress(chainId, name);

View File

@ -2,6 +2,7 @@ import { useReadContract } from "wagmi";
import { DAO_TREASURY_ADDRESSES } from "../../constants/addresses";
import { abi as TreasuryAbi } from "../../abi/GhostTreasury.json";
import { abi as CalculatorAbi } from "../../abi/GhostBondingCalculator.json"
import { useReservePrice } from "../prices/index";
@ -21,6 +22,52 @@ export const useOrinalCoefficient = (chainId) => {
return new DecimalBigNumber(original ? original : 1000000000000000000n, 18);
}
export const useRegisteredAt = (chainId, registryIndex) => {
const { data: registeredAt } = useReadContract({
abi: TreasuryAbi,
address: DAO_TREASURY_ADDRESSES[chainId],
functionName: "registeredAt",
args: [1, registryIndex],
scopeKey: `registeredAt-${chainId}`,
chainId: chainId,
});
return registeredAt ? registeredAt : "0x0000000000000000000000000000000000000000";
}
export const useCalculatorFraction = (chainId, registryAddress) => {
const { data: bondCalculator } = useReadContract({
abi: TreasuryAbi,
address: DAO_TREASURY_ADDRESSES[chainId],
functionName: "bondCalculator",
args: [registryAddress],
scopeKey: `bondCalculator-${chainId}`,
chainId: chainId,
});
const { data: fraction } = useReadContract({
abi: CalculatorAbi,
address: bondCalculator,
functionName: "fraction",
scopeKey: `fraction-${chainId}`,
chainId: chainId,
});
return new DecimalBigNumber(fraction ? fraction : 0n, 18);
}
export const useTotalReservesRaw = (chainId) => {
const { data: totalReservesRaw } = useReadContract({
abi: TreasuryAbi,
address: DAO_TREASURY_ADDRESSES[chainId],
functionName: "totalReserves",
scopeKey: `totalReserves-${chainId}`,
chainId: chainId,
});
return new DecimalBigNumber(totalReservesRaw ? totalReservesRaw : 0n, 9);
}
export const useTotalReserves = (chainId) => {
const { data: totalReservesRaw } = useReadContract({
abi: TreasuryAbi,