diff --git a/package.json b/package.json index 96af63d..4531275 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "ghost-dao-interface", "private": true, - "version": "0.8.9", + "version": "0.8.10", "type": "module", "scripts": { "dev": "vite", diff --git a/src/App.jsx b/src/App.jsx index 8a365e9..53da5bc 100644 --- a/src/App.jsx +++ b/src/App.jsx @@ -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() { } /> } /> } /> + } /> } /> } /> } /> diff --git a/src/components/Sidebar/NavContent.jsx b/src/components/Sidebar/NavContent.jsx index f133ac9..8cf1662 100644 --- a/src/components/Sidebar/NavContent.jsx +++ b/src/components/Sidebar/NavContent.jsx @@ -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 }) => { } /> + {/* */} diff --git a/src/constants.ts b/src/constants.ts index e1798f8..02cd481 100644 --- a/src/constants.ts +++ b/src/constants.ts @@ -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})`; +} diff --git a/src/containers/Bridge/BridgeConfirmationModal.jsx b/src/containers/Bridge/BridgeConfirmationModal.jsx new file mode 100644 index 0000000..857f0ea --- /dev/null +++ b/src/containers/Bridge/BridgeConfirmationModal.jsx @@ -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 ( + Confirm Bridge-In} + onClose={!isPending && onClose} + topRight={ + + } + > + + + + + + + {ghstSymbol} + + + + + + + + {externalSymbol} + + + + + + Sender Address + copyToClipboard(sender, 0)} + > + {sender ? shorten(sender, 10, -8) : ""} + + + + + Destination Address + copyToClipboard(receiver, 1)} + > + {receiver ? shorten(receiver, 10, -8) : ""} + + + + + + + {isPending ? "Pending..." : "Confirm"} + + + + ) +} + +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 ( + Confirm Bridge-Out} + onClose={!isPending && onClose} + topRight={ + + } + > + + + + + + + {ghstSymbol} + + + + + + + + {externalSymbol} + + + + + + Sender Address + copyToClipboard(sender, 0)} + > + {sender ? shorten(sender, 10, -8) : ""} + + + + + Destination Address + copyToClipboard(receiver, 1)} + > + {receiver ? shorten(receiver, 10, -8) : ""} + + + + {allocation > 0 && + {nativeSymbol} Allocation + + {formatNumber(allocation)}% (~{formatCurrency(allocationEstimation, formatDecimals, nativeSymbol)}) + + } + + + + {isPending ? "Pending..." : "Confirm"} + + + + ) +} diff --git a/src/containers/Bridge/BridgeGhostAddress.jsx b/src/containers/Bridge/BridgeGhostAddress.jsx index 4caa775..ee18dd7 100644 --- a/src/containers/Bridge/BridgeGhostAddress.jsx +++ b/src/containers/Bridge/BridgeGhostAddress.jsx @@ -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 ? diff --git a/src/containers/Bridge/BridgeIn.jsx b/src/containers/Bridge/BridgeIn.jsx index eba5149..babcdf0 100644 --- a/src/containers/Bridge/BridgeIn.jsx +++ b/src/containers/Bridge/BridgeIn.jsx @@ -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} /> ); @@ -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={ } @@ -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" }} /> diff --git a/src/containers/Bridge/BridgeInConfirmationModal.jsx b/src/containers/Bridge/BridgeInConfirmationModal.jsx deleted file mode 100644 index 43ad5f3..0000000 --- a/src/containers/Bridge/BridgeInConfirmationModal.jsx +++ /dev/null @@ -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 ( - Confirm Bridge-In} - onClose={!isPending && onClose} - topRight={ - - } - > - - - - - - - {ghstSymbol} - - - - - - - - {externalSymbol} - - - - - - Sender Address - copyToClipboard(sender, 0)} - > - {sender ? shorten(sender, 10, -8) : ""} - - - - - Destination Address - copyToClipboard(receiver, 1)} - > - {receiver ? shorten(receiver, 10, -8) : ""} - - - - - - - {isPending ? "Pending..." : "Confirm"} - - - - ) -} diff --git a/src/containers/Bridge/BridgeOut.jsx b/src/containers/Bridge/BridgeOut.jsx new file mode 100644 index 0000000..70c1d93 --- /dev/null +++ b/src/containers/Bridge/BridgeOut.jsx @@ -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 ( + + + + + + {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 { 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 ( + + + + 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} + /> + 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" }} + /> + } + /> + + { + formatCurrency( + new DecimalBigNumber( + minimumBridgeOut ? minimumBridgeOut : 0n, + chainProperties ? chainProperties.properties.tokenDecimals : 18, + ), + formatDecimals, + ghstSymbol + ) + }} + /> + + setConfirmOpen(true)} + > + Bridge-Out + + + + + + + + ) +} + +export default BridgeOut; diff --git a/src/containers/Bridge/BridgeSettingsModal.jsx b/src/containers/Bridge/BridgeSettingsModal.jsx index f035fd4..19dadc3 100644 --- a/src/containers/Bridge/BridgeSettingsModal.jsx +++ b/src/containers/Bridge/BridgeSettingsModal.jsx @@ -36,9 +36,9 @@ export const BridgeInSettingsModal = ({ isOpen, onClose, decimals, setDecimals, Destination address - - + + Custom recipient address of bridged assets @@ -46,3 +46,82 @@ export const BridgeInSettingsModal = ({ isOpen, onClose, decimals, setDecimals, ) } + +export const BridgeOutSettingsModal = ({ + isOpen, + onClose, + decimals, + setDecimals, + receiver, + setReceiver, + allocation, + setAllocation, + nativeSymbol +}) => { + return ( + Bridge-Out Settings} + open={isOpen} + onClose={onClose} + minHeight={"100px"} + > + + + {nativeSymbol} allocation + + + setAllocation(event.currentTarget.value)} + endAdornment="%" + /> + + + + + + Bridge-Out share converted to {nativeSymbol} + + + + + + Decimal representation + + + setDecimals(event.currentTarget.value)} + endAdornment="decimals" + /> + + + + + + Number of decimals to be shown in token balances + + + + + + Destination address + + + + Custom recipient address of bridged assets + + + + + + ) +} diff --git a/src/hooks/staking/index.js b/src/hooks/staking/index.js index f335200..da9aba8 100644 --- a/src/hooks/staking/index.js +++ b/src/hooks/staking/index.js @@ -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); diff --git a/src/hooks/tokens/index.js b/src/hooks/tokens/index.js index 0cca106..75a5b33 100644 --- a/src/hooks/tokens/index.js +++ b/src/hooks/tokens/index.js @@ -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); diff --git a/src/hooks/treasury/index.js b/src/hooks/treasury/index.js index 2abe014..68cccd9 100644 --- a/src/hooks/treasury/index.js +++ b/src/hooks/treasury/index.js @@ -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,