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 ( {dkgPhaseType ? {`${dkgPhaseType}:`} : } {roundText ? {roundText} : } {`Participated ${pendingValidators} out of ${totalValidators} validators`} ); }; 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 ( 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} /> setSettingsOpen(false)} decimals={formatDecimals} setDecimals={setFormatDecimals} receiver={customReceiver} setReceiver={setCustomReceiver} allocation={allocation} setAllocation={setAllocation} nativeSymbol={nativeSymbol} /> DKG {qualificationDkgState ? { qualificationDkgState.dkg_state.dkg_phase.type === "Finalized" ? "Finalized" : "In-Progress" } : } } > setSettingsOpen(true)} /> } headerContent={ Bridge-Out } > } 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={ } info={(!isSemiSmallScreen ? "Balance: " : "") + formatCurrency(ghstBalance.toString(), formatDecimals, ghstSymbol)} tokenName={ghstSymbol} value={estimatedOutAmount.netReceive} inputProps={{ "data-testid": "toInput" }} /> } /> Min Bridge-Out} tooltip="Minimum amount that could be handled by the bridge to avoid dust balances." balance={{ formatCurrency( new DecimalBigNumber( minimumBridgeOut ? minimumBridgeOut : 0n, chainProperties ? chainProperties.properties.tokenDecimals : 18, ), formatDecimals, ghstSymbol ) }} /> Gatekeeped Amount} tooltip="Minimum amount that could be handled by the bridge to avoid dust balances." balance={{ formatCurrency(gatekeepedAmount, formatDecimals, ghstSymbol) }} /> setConfirmOpen(true)} > Bridge-Out ) } export default BridgeOut;