Compare commits
36 Commits
main
...
developmen
| Author | SHA1 | Date | |
|---|---|---|---|
| 1f648fa576 | |||
| b125916ee5 | |||
| 3c68811b85 | |||
| 5b8e34e8d0 | |||
| 5587b163f8 | |||
| 55988858d9 | |||
| 852d3c86ce | |||
| a78b583be3 | |||
| fc043af3e5 | |||
| b675da56d2 | |||
| ce7c973929 | |||
| 8b6a47d196 | |||
| 582b22aded | |||
| 2cc5695aae | |||
| 12f668130d | |||
| 3b2dd422fa | |||
| feb3c34455 | |||
| 12b943abf8 | |||
| c89da3c744 | |||
| 096256794f | |||
| e19c856403 | |||
| 03400023f3 | |||
| 62cd599250 | |||
| 7d4085f226 | |||
| b65ab19873 | |||
| d183478e6b | |||
| 190933cc9c | |||
| 094904c163 | |||
| b7823f19dd | |||
| 4de736ea08 | |||
| ce6e316feb | |||
| e42f5db893 | |||
| b09c6b82f7 | |||
| 42d5f82040 | |||
| 132bd0986b | |||
| 314abe1aba |
3
.papi/descriptors/.gitignore
vendored
Normal file
3
.papi/descriptors/.gitignore
vendored
Normal file
@ -0,0 +1,3 @@
|
||||
*
|
||||
!.gitignore
|
||||
!package.json
|
||||
25
.papi/descriptors/package.json
Normal file
25
.papi/descriptors/package.json
Normal file
@ -0,0 +1,25 @@
|
||||
{
|
||||
"version": "0.1.0-autogenerated.17780546383012228608",
|
||||
"name": "@polkadot-api/descriptors",
|
||||
"files": [
|
||||
"dist"
|
||||
],
|
||||
"type": "module",
|
||||
"exports": {
|
||||
".": {
|
||||
"types": "./dist/index.d.ts",
|
||||
"module": "./dist/index.js",
|
||||
"import": "./dist/index.js",
|
||||
"default": "./dist/index.js"
|
||||
},
|
||||
"./package.json": "./package.json"
|
||||
},
|
||||
"main": "./dist/index.js",
|
||||
"module": "./dist/index.js",
|
||||
"browser": "./dist/index.js",
|
||||
"types": "./dist/index.d.ts",
|
||||
"sideEffects": false,
|
||||
"peerDependencies": {
|
||||
"polkadot-api": ">=2.0.0"
|
||||
}
|
||||
}
|
||||
9
.papi/polkadot-api.json
Normal file
9
.papi/polkadot-api.json
Normal file
@ -0,0 +1,9 @@
|
||||
{
|
||||
"version": 0,
|
||||
"descriptorPath": ".papi\\descriptors",
|
||||
"entries": {
|
||||
"casper": {
|
||||
"metadata": "casper-metadata.scale"
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -2,7 +2,7 @@
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<link rel="icon" href="https://ipfs.io/ipfs/QmRgJ2UbzpM58te1R91bC2neWsS28F2QatBtzerM1JekyC" type="image/png" />
|
||||
<link rel="icon" href="https://ghostchain.io/wp-content/uploads/2026/06/ghost-favicon.ico" type="image/ico" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<link rel="stylesheet" type="text/css" href="https://fonts.googleapis.com/css?family=Ubuntu:regular,bold&subset=Latin">
|
||||
<link href="https://fonts.googleapis.com/css2?family=Ubuntu:wght@400;700&display=swap" rel="stylesheet">
|
||||
|
||||
BIN
metadatas/casper-metadata.scale
Normal file
BIN
metadatas/casper-metadata.scale
Normal file
Binary file not shown.
12
package.json
12
package.json
@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "ghost-dao-interface",
|
||||
"private": true,
|
||||
"version": "0.7.58",
|
||||
"version": "0.8.34",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
@ -30,6 +30,8 @@
|
||||
"@tanstack/react-query": "^5.67.2",
|
||||
"@tanstack/react-query-devtools": "^5.67.2",
|
||||
"@wagmi/core": "^2.17.3",
|
||||
"polkadot-api": "^3.3.0",
|
||||
"@polkadot-api/descriptors": "file:.papi/descriptors",
|
||||
"react": "^19.0.0",
|
||||
"react-dom": "^19.0.0",
|
||||
"react-ga4": "^2.1.0",
|
||||
@ -55,5 +57,11 @@
|
||||
"sass-embedded": "^1.85.1",
|
||||
"vite": "^6.2.0",
|
||||
"vite-plugin-svgr": "^4.3.0"
|
||||
}
|
||||
},
|
||||
"pnpm": {
|
||||
"overrides": {
|
||||
"@polkadot-api/json-rpc-provider": "0.2.0"
|
||||
}
|
||||
},
|
||||
"packageManager": "pnpm@9.6.0+sha512.38dc6fba8dba35b39340b9700112c2fe1e12f10b17134715a4aa98ccf7bb035e76fd981cf0bb384dfa98f8d6af5481c2bef2f4266a24bfa20c34eb7147ce0b5e"
|
||||
}
|
||||
|
||||
1420
pnpm-lock.yaml
1420
pnpm-lock.yaml
File diff suppressed because it is too large
Load Diff
18
src/App.jsx
18
src/App.jsx
@ -36,11 +36,14 @@ const BondModalContainer = lazy(() => import("./containers/Bond/BondModal"));
|
||||
const StakeContainer = lazy(() => import("./containers/Stake/StakeContainer"));
|
||||
const TreasuryDashboard = lazy(() => import("./containers/TreasuryDashboard/TreasuryDashboard"));
|
||||
const Dex = lazy(() => import("./containers/Dex/Dex"));
|
||||
const Bridge = lazy(() => import("./containers/Bridge/Bridge"));
|
||||
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"));
|
||||
const NewProposal = lazy(() => import("./containers/Governance/NewProposal"));
|
||||
const History = lazy(() => import("./containers/History/History"));
|
||||
const Exodus = lazy(() => import("./containers/Exodus/Exodus"));
|
||||
|
||||
const PREFIX = "App";
|
||||
|
||||
@ -182,9 +185,9 @@ function App() {
|
||||
/>
|
||||
<nav className={classes.drawer}>
|
||||
{isSmallerScreen ? (
|
||||
<NavDrawer chainId={chainId} addressChainId={addressChainId} mobileOpen={mobileOpen} handleDrawerToggle={handleDrawerToggle} />
|
||||
<NavDrawer address={address} chainId={chainId} addressChainId={addressChainId} mobileOpen={mobileOpen} handleDrawerToggle={handleDrawerToggle} />
|
||||
) : (
|
||||
<Sidebar chainId={chainId} addressChainId={addressChainId} />
|
||||
<Sidebar address={address} chainId={chainId} addressChainId={addressChainId} />
|
||||
)}
|
||||
</nav>
|
||||
|
||||
@ -195,15 +198,18 @@ function App() {
|
||||
<Route path="/" element={<Navigate to={chainExists ? `/${chains.at(0).name.toLowerCase()}/dashboard` : "/empty"} />} />
|
||||
{chainExists &&
|
||||
<Route path="/:network" element={<AvailableNetworkGuard allowedNetworks={chains.map(chain => chain.name.toLowerCase())} /> }>
|
||||
<Route path="dashboard" element={<TreasuryDashboard chainId={addressChainId ? addressChainId : chainId} />} />
|
||||
<Route path="bonds" element={<Bonds connect={tryConnectInjected} address={address} chainId={addressChainId ? addressChainId : chainId} />} />
|
||||
<Route path="dashboard" element={<TreasuryDashboard config={config} chainId={addressChainId ? addressChainId : chainId} />} />
|
||||
<Route path="bonds" element={<Bonds config={config} connect={tryConnectInjected} address={address} chainId={addressChainId ? addressChainId : chainId} />} />
|
||||
<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" element={<Bridge 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} />} />
|
||||
<Route path="governance/create" element={<NewProposal config={config} connect={tryConnectInjected} address={address} chainId={addressChainId ? addressChainId : chainId} />} />
|
||||
<Route path="history" element={<History config={config} connect={tryConnectInjected} address={address} chainId={addressChainId ? addressChainId : chainId} />} />
|
||||
<Route path="exodus" element={<Exodus config={config} connect={tryConnectInjected} address={address} chainId={addressChainId ? addressChainId : chainId} />} />
|
||||
</Route>
|
||||
}
|
||||
<Route path="/empty" element={<NotFound
|
||||
|
||||
File diff suppressed because one or more lines are too long
@ -1 +1 @@
|
||||
{"abi":[{"inputs":[{"internalType":"address","name":"_ftso","type":"address"}],"stateMutability":"nonpayable","type":"constructor"},{"inputs":[],"name":"InvalidPair","type":"error"},{"inputs":[{"internalType":"address","name":"pair","type":"address"}],"name":"getKValue","outputs":[{"internalType":"uint256","name":"k","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"pair","type":"address"}],"name":"getTotalValue","outputs":[{"internalType":"uint256","name":"value","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"pair","type":"address"}],"name":"markdown","outputs":[{"internalType":"uint256","name":"reserve","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"pair","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"valuation","outputs":[{"internalType":"uint256","name":"value","type":"uint256"}],"stateMutability":"view","type":"function"}]}
|
||||
{"abi":[{"inputs":[{"internalType":"address","name":"_ftso","type":"address"},{"internalType":"uint256","name":"_numerator","type":"uint256"},{"internalType":"uint256","name":"_denominator","type":"uint256"}],"stateMutability":"nonpayable","type":"constructor"},{"inputs":[],"name":"InvalidPair","type":"error"},{"inputs":[],"name":"fraction","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"pair","type":"address"},{"internalType":"bool","name":"isCoefficient","type":"bool"}],"name":"getKValue","outputs":[{"internalType":"uint256","name":"k","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"pair","type":"address"},{"internalType":"bool","name":"isCoefficient","type":"bool"}],"name":"getTotalValue","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"pair","type":"address"}],"name":"markdown","outputs":[{"internalType":"uint256","name":"reserve","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"pair","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"valuation","outputs":[{"internalType":"uint256","name":"value","type":"uint256"}],"stateMutability":"view","type":"function"}]}
|
||||
|
||||
File diff suppressed because one or more lines are too long
1
src/abi/GhostStorageHistory.json
Normal file
1
src/abi/GhostStorageHistory.json
Normal file
@ -0,0 +1 @@
|
||||
{"abi":[{"inputs":[],"stateMutability":"nonpayable","type":"constructor"},{"inputs":[],"name":"AlreadyExecuted","type":"error"},{"inputs":[],"name":"BridgeOutImpossible","type":"error"},{"inputs":[],"name":"NotDeployer","type":"error"},{"inputs":[],"name":"NotOwner","type":"error"},{"inputs":[],"name":"bridgeImbalance","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"deploymentSnapshot","outputs":[{"components":[{"internalType":"uint48","name":"deployedAt","type":"uint48"},{"internalType":"uint104","name":"amountIn","type":"uint104"},{"internalType":"uint104","name":"amountOut","type":"uint104"}],"internalType":"struct IStorageHistory.DeploymentSnapshot","name":"","type":"tuple"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"increaseBridgeIn","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"session","type":"uint256"}],"name":"isTransactionExecuted","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"newOwner","type":"address"}],"name":"setOwner","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"tryIncreaseBridgeOut","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"session","type":"uint256"}],"name":"trySetTransactionExecuted","outputs":[],"stateMutability":"nonpayable","type":"function"}]}
|
||||
File diff suppressed because one or more lines are too long
@ -150,7 +150,8 @@ const NavItem = ({
|
||||
component={ArrowUpIcon}
|
||||
/>}
|
||||
</Box>
|
||||
{chip && <Chip size="small" label={chip} template={chipColor} />}
|
||||
|
||||
{chip && <Box pr="6px"><Chip p="18px" size="small" label={chip} template={chipColor} /></Box>}
|
||||
</Box>
|
||||
</Link>
|
||||
);
|
||||
|
||||
@ -1,4 +1,6 @@
|
||||
import { useMemo, useEffect } from "react";
|
||||
import useSWR from "swr";
|
||||
import toast from "react-hot-toast";
|
||||
import { useMemo, useEffect, useState } from "react";
|
||||
|
||||
import "./Sidebar.scss";
|
||||
|
||||
@ -15,7 +17,7 @@ import {
|
||||
AccordionDetails,
|
||||
} from "@mui/material";
|
||||
import { styled } from "@mui/material/styles";
|
||||
import { NavLink } from "react-router-dom";
|
||||
import { NavLink, useLocation } from "react-router-dom";
|
||||
import { useSwitchChain } from "wagmi";
|
||||
|
||||
import ExpandMoreIcon from '@mui/icons-material/ExpandMore';
|
||||
@ -27,10 +29,14 @@ import HubIcon from '@mui/icons-material/Hub';
|
||||
import PublicIcon from '@mui/icons-material/Public';
|
||||
import ForkRightIcon from '@mui/icons-material/ForkRight';
|
||||
import GavelIcon from '@mui/icons-material/Gavel';
|
||||
import HistoryIcon from '@mui/icons-material/History';
|
||||
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 RampLeftIcon from '@mui/icons-material/RampLeft';
|
||||
import RouteIcon from '@mui/icons-material/Route';
|
||||
|
||||
import GhostIcon from "../../assets/icons/ghost-nav-header.svg?react";
|
||||
import NavItem from "../NavItem/NavItem";
|
||||
@ -40,9 +46,8 @@ import BondIcon from "../Icon/BondIcon";
|
||||
import StakeIcon from "../Icon/StakeIcon";
|
||||
import WrapIcon from "../Icon/WrapIcon";
|
||||
|
||||
import { isNetworkAvailable } from "../../constants";
|
||||
import { isNetworkAvailable, negativeBridgeNumbers, bridgeNumbers } from "../../constants";
|
||||
import { AVAILABLE_DEXES } from "../../constants/dexes";
|
||||
import { GATEKEEPER_ADDRESSES } from "../../constants/addresses";
|
||||
import { ECOSYSTEM } from "../../constants/ecosystem";
|
||||
import { DecimalBigNumber } from "../../helpers/DecimalBigNumber";
|
||||
import { sortBondsByDiscount, formatCurrency } from "../../helpers";
|
||||
@ -55,6 +60,8 @@ import WifiProtectedSetupIcon from '@mui/icons-material/WifiProtectedSetup';
|
||||
|
||||
import { useTokenSymbol } from "../../hooks/tokens";
|
||||
import { useLiveBonds } from "../../hooks/bonds/index";
|
||||
import { useLocalStorage } from "../../hooks/localstorage";
|
||||
import { useUnstableProvider } from "../../hooks/ghost";
|
||||
import pckg from "../../../package.json"
|
||||
|
||||
const PREFIX = "NavContent";
|
||||
@ -69,22 +76,63 @@ const StyledBox = styled(Box)(({ theme }) => ({
|
||||
},
|
||||
}));
|
||||
|
||||
const NavContent = ({ chainId, addressChainId }) => {
|
||||
const NavContent = ({ chainId, addressChainId, address }) => {
|
||||
const location = useLocation();
|
||||
const { chains } = useSwitchChain();
|
||||
|
||||
const chainName = useMemo(() => {
|
||||
return chains.find(chain => chain.id === chainId).name.toLowerCase();
|
||||
}, [chains, chainId, addressChainId])
|
||||
}, [chains, chainId, addressChainId]);
|
||||
|
||||
const [pendingExoduses, setPendingExoduses] = useState(0);
|
||||
const [signedExoduses, setSignedExoduses] = useState(0);
|
||||
|
||||
const { useStorageValue, CONSTANTS } = useLocalStorage();
|
||||
const { casperApi } = useUnstableProvider();
|
||||
|
||||
const { liveBonds: ghostBonds } = useLiveBonds(chainId);
|
||||
const { symbol: ftsoSymbol } = useTokenSymbol(chainId, "FTSO");
|
||||
const { symbol: ghstSymbol } = useTokenSymbol(chainId, "GHST");
|
||||
|
||||
const { data: pendingHistory } = useStorageValue(chainId, address, CONSTANTS.pendingHistoryPrefix, {})
|
||||
|
||||
const pendingTransactions = useMemo(() => {
|
||||
if (!pendingHistory) return null;
|
||||
const count = Object.values(pendingHistory).reduce((sum, count) => sum + count, 0);
|
||||
return count > 0 ? count: null;
|
||||
}, [pendingHistory]);
|
||||
|
||||
const sortedGhostBonds = useMemo(() => sortBondsByDiscount(ghostBonds), [ghostBonds]);
|
||||
const bridgeNumbers = useMemo(() => {
|
||||
const connectedNetworks = Object.keys(GATEKEEPER_ADDRESSES).length;
|
||||
const number = 1 + connectedNetworks * 3;
|
||||
return `(${number}, ${number})`;
|
||||
}, [chainId]);
|
||||
|
||||
const { data: counterForExodusRequest } = useSWR(
|
||||
casperApi ? ["counterForExodusRequest", casperApi] : null,
|
||||
([_, api]) => api.query.GhostExodus.CounterForExodusRequests.getValue(),
|
||||
{ fallbackData: 0, refetchInterval: 12000 },
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
if (pendingExoduses === counterForExodusRequest) return
|
||||
else if (pendingExoduses > counterForExodusRequest) {
|
||||
const newlySigned = pendingExoduses - counterForExodusRequest;
|
||||
setSignedExoduses((prev) => prev + newlySigned);
|
||||
setPendingExoduses(counterForExodusRequest);
|
||||
} else {
|
||||
const newlyQueued = counterForExodusRequest - pendingExoduses;
|
||||
const message =
|
||||
newlyQueued === 1
|
||||
? "GHOST Exodus request is signing now. Get ready to verify it and earn rewards!"
|
||||
: `${newlyQueued} GHOST Exodus requests are signing now. Get ready to verify them and earn rewards!`;
|
||||
|
||||
|
||||
toast.success(message, { autoClose: 5000 });
|
||||
setPendingExoduses(counterForExodusRequest);
|
||||
}
|
||||
}, [counterForExodusRequest, pendingExoduses]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!location.pathname.endsWith("exodus")) return
|
||||
setSignedExoduses(0);
|
||||
}, [location]);
|
||||
|
||||
return (
|
||||
<Paper className="dapp-sidebar">
|
||||
@ -98,7 +146,7 @@ const NavContent = ({ chainId, addressChainId }) => {
|
||||
component={GhostIcon}
|
||||
style={{ width: "150px", height: "150px" }}
|
||||
/>
|
||||
<Box mb="10px" mt="-40px" fontSize="12px" fontWeight="500" lineHeight={"15px"}>
|
||||
<Box mb="10px" mt="-40px" fontSize="12px" fontWeight="500" lineHeight={"15px"}>
|
||||
Version {pckg.version}
|
||||
</Box>
|
||||
</Link>
|
||||
@ -137,7 +185,7 @@ const NavContent = ({ chainId, addressChainId }) => {
|
||||
</AccordionDetails>
|
||||
}
|
||||
/>
|
||||
<NavItem icon={StakeIcon} label={`(3, 3) Stake`} to={`/${chainName}/stake`} />
|
||||
<NavItem icon={StakeIcon} label={<span>(3, 3) Stake<sup>1</sup></span>} to={`/${chainName}/stake`} />
|
||||
<NavItem
|
||||
defaultExpanded
|
||||
icon={BondIcon}
|
||||
@ -145,9 +193,6 @@ const NavContent = ({ chainId, addressChainId }) => {
|
||||
to={`/${chainName}/bonds`}
|
||||
children={
|
||||
<AccordionDetails style={{ margin: "0 0 -20px", display: "flex", flexDirection: "column", gap: "10px" }}>
|
||||
{sortedGhostBonds.length > 0 && <Box width="180px" mb="10px" ml="auto">
|
||||
<Typography component="span" variant="body2">Bond Discounts</Typography>
|
||||
</Box>}
|
||||
{sortedGhostBonds.map((bond, index) => {
|
||||
return (
|
||||
<Link
|
||||
@ -170,7 +215,7 @@ const NavContent = ({ chainId, addressChainId }) => {
|
||||
>
|
||||
{bond.displayName}
|
||||
{bond.isSoldOut
|
||||
? <Chip label="Sold Out" template="darkGray" />
|
||||
? <Chip label="Sold Out" template="gray" />
|
||||
: <BondDiscount discount={bond.discount} />
|
||||
}
|
||||
</Typography>
|
||||
@ -181,8 +226,12 @@ const NavContent = ({ chainId, addressChainId }) => {
|
||||
</AccordionDetails>
|
||||
}
|
||||
/>
|
||||
<NavItem icon={ForkRightIcon} label={`${bridgeNumbers} Stake\u00B2`} to={`/${chainName}/bridge`} />
|
||||
<NavItem icon={GavelIcon} label={`Governance`} to={`/${chainName}/governance`} />
|
||||
<NavItem icon={ForkRightIcon} label={`${bridgeNumbers()} Bridge-In`} to={`/${chainName}/bridge-in`} />
|
||||
<NavItem icon={RampLeftIcon} label={`${negativeBridgeNumbers()} Bridge-Out`} to={`/${chainName}/bridge-out`} />
|
||||
<NavItem icon={RouteIcon} chipColor="warning" chip={signedExoduses > 0 ? signedExoduses : null} label="(1, 1) Exodus" to={`/${chainName}/exodus`} />
|
||||
<NavItem icon={HistoryIcon} chipColor="warning" chip={pendingTransactions} label="Transaction History" to={`/${chainName}/history`} />
|
||||
{/* <NavItem icon={GavelIcon} label={`Governance`} to={`/${chainName}/governance`} /> */}
|
||||
|
||||
<Box className="menu-divider">
|
||||
<Divider />
|
||||
</Box>
|
||||
@ -193,8 +242,7 @@ const NavContent = ({ chainId, addressChainId }) => {
|
||||
</div>
|
||||
|
||||
<Box>
|
||||
<NavItem href="https://ghostchain.io/game-theory-3-3" icon={CasinoIcon} label={`${bridgeNumbers} Game Theory`} />
|
||||
<NavItem href="http://ecosystem.ghostchain.io" icon={PublicIcon} label={`Ecosystem`} />
|
||||
<NavItem href="https://ghostchain.io/game-theory-3-3" icon={CasinoIcon} label={`${bridgeNumbers()} Game Theory`} />
|
||||
<NavItem href="https://docs.ghostchain.io/" icon={BookIcon} label={`Documentation`} />
|
||||
<StyledBox display="flex" justifyContent="space-around" paddingY="24px">
|
||||
<Link href="https://git.ghostchain.io/ghostchain/ghost-dao-contracts" target="_blank" rel="noopener noreferrer">
|
||||
|
||||
@ -27,7 +27,7 @@ const StyledSwipeableDrawer = styled(SwipeableDrawer)(({ theme }) => ({
|
||||
|
||||
const drawerWidth = 280;
|
||||
|
||||
const NavDrawer = ({ chainId, addressChainId, mobileOpen, handleDrawerToggle }) => {
|
||||
const NavDrawer = ({ chainId, address, addressChainId, mobileOpen, handleDrawerToggle }) => {
|
||||
const location = useLocation();
|
||||
const isIOS = /iPad|iPhone|iPod/.test(navigator.userAgent);
|
||||
|
||||
@ -53,7 +53,7 @@ const NavDrawer = ({ chainId, addressChainId, mobileOpen, handleDrawerToggle })
|
||||
disableBackdropTransition={!isIOS}
|
||||
disableDiscovery={isIOS}
|
||||
>
|
||||
<NavContent addressChainId={addressChainId} chainId={chainId} />
|
||||
<NavContent address={address} addressChainId={addressChainId} chainId={chainId} />
|
||||
</StyledSwipeableDrawer>
|
||||
);
|
||||
};
|
||||
|
||||
@ -4,10 +4,10 @@ import { Drawer } from "@mui/material";
|
||||
import React from "react";
|
||||
import NavContent from "./NavContent";
|
||||
|
||||
const Sidebar = ({ chainId, addressChainId }) => (
|
||||
const Sidebar = ({ chainId, addressChainId, address }) => (
|
||||
<div className="sidebar" id="sidebarContent">
|
||||
<Drawer variant="permanent" anchor="left">
|
||||
<NavContent addressChainId={addressChainId} chainId={chainId} />
|
||||
<NavContent address={address} addressChainId={addressChainId} chainId={chainId} />
|
||||
</Drawer>
|
||||
</div>
|
||||
);
|
||||
|
||||
@ -1,3 +1,4 @@
|
||||
import useSWR from 'swr';
|
||||
import { useMemo } from "react";
|
||||
import {
|
||||
Box,
|
||||
@ -25,7 +26,7 @@ import ArrowUpIcon from "../../../assets/icons/arrow-up.svg?react";
|
||||
import { formatCurrency, shorten } from "../../../helpers";
|
||||
import { DecimalBigNumber } from "../../../helpers/DecimalBigNumber";
|
||||
import { RESERVE_ADDRESSES, FTSO_ADDRESSES } from "../../../constants/addresses";
|
||||
import { useUnstableProvider, useSystemAccount, useChainSpec } from "../../../hooks/ghost"
|
||||
import { useUnstableProvider } from "../../../hooks/ghost"
|
||||
|
||||
import { useAccount, useDisconnect, useSwitchChain } from "wagmi";
|
||||
|
||||
@ -113,28 +114,44 @@ function InitialWalletView({ isWalletOpen, address, chainId, onClose }) {
|
||||
const location = useLocation();
|
||||
const tokens = useWallet(chainId, address);
|
||||
|
||||
const [currency, setCurrency] = useState("USD");
|
||||
const { account, isExtensionMissing } = useUnstableProvider();
|
||||
const { client, casperApi, account, isExtensionMissing } = useUnstableProvider();
|
||||
const { chains } = useSwitchChain();
|
||||
|
||||
const [currency, setCurrency] = useState("USD");
|
||||
const [accountIndex, setAccountIndex] = useState(0);
|
||||
|
||||
const chainName = useMemo(() => {
|
||||
const chain = chains.find(chain => chain.id === chainId)
|
||||
if (!chain) return null
|
||||
return chain.name.toLowerCase()
|
||||
}, [chains, chainId])
|
||||
}, [chains, chainId]);
|
||||
|
||||
const chainSpec = useChainSpec();
|
||||
const accountBalanceRaw = useSystemAccount({ account });
|
||||
const { data: chainProperties } = useSWR(
|
||||
client ? ['chainProperties', client] : null,
|
||||
() => client.getChainSpecData(),
|
||||
{
|
||||
revalidateOnFocus: false
|
||||
}
|
||||
);
|
||||
|
||||
const { data: accountBalanceRaw, error } = useSWR(
|
||||
casperApi && account?.address ? ['accountBalance', account.address] : null,
|
||||
() => casperApi.query.System.Account.getValue(account.address),
|
||||
{
|
||||
refreshInterval: 12000,
|
||||
revalidateOnFocus: true
|
||||
}
|
||||
);
|
||||
|
||||
const accountBalance = useMemo(() => {
|
||||
const decimals = chainSpec ? chainSpec.properties.tokenDecimals : 18;
|
||||
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, chainSpec])
|
||||
}, [accountBalanceRaw, chainProperties]);
|
||||
|
||||
const nativeGhst = useMemo(() => {
|
||||
return {
|
||||
@ -201,8 +218,8 @@ function InitialWalletView({ isWalletOpen, address, chainId, onClose }) {
|
||||
<WalletTotalValue
|
||||
currency={currency}
|
||||
setCurrency={setCurrency}
|
||||
chainName={chainSpec?.chainName ?? ""}
|
||||
address={account ?? "...wait"}
|
||||
chainName={chainProperties?.name ?? ""}
|
||||
address={account?.address ?? "...wait"}
|
||||
tokens={nativeGhst}
|
||||
/>
|
||||
<NativeToken {...nativeGhst} />
|
||||
|
||||
@ -1,45 +1,46 @@
|
||||
import { defineChain } from 'viem'
|
||||
import { http, fallback, createConfig } from 'wagmi'
|
||||
import { sepolia, hoodi } from 'wagmi/chains'
|
||||
import { hoodi } from 'wagmi/chains'
|
||||
|
||||
const mordor = defineChain({
|
||||
id: 63,
|
||||
name: 'Mordor',
|
||||
nativeCurrency: {
|
||||
decimals: 18,
|
||||
name: 'METC',
|
||||
symbol: 'mETC',
|
||||
},
|
||||
rpcUrls: {
|
||||
default: { http: ['https://rpc.mordor.etccooperative.org'] },
|
||||
},
|
||||
blockExplorers: {
|
||||
default: {
|
||||
name: 'Blockscout',
|
||||
url: 'https://etc-mordor.blockscout.com/'
|
||||
},
|
||||
},
|
||||
})
|
||||
// const mordor = defineChain({
|
||||
// id: 63,
|
||||
// name: 'Mordor',
|
||||
// nativeCurrency: {
|
||||
// decimals: 18,
|
||||
// name: 'METC',
|
||||
// symbol: 'mETC',
|
||||
// },
|
||||
// rpcUrls: {
|
||||
// default: { http: ['https://rpc.mordor.etccooperative.org'] },
|
||||
// },
|
||||
// blockExplorers: {
|
||||
// default: {
|
||||
// name: 'Blockscout',
|
||||
// url: 'https://etc-mordor.blockscout.com/'
|
||||
// },
|
||||
// },
|
||||
// })
|
||||
|
||||
export const config = createConfig({
|
||||
chains: [sepolia, hoodi, mordor],
|
||||
chains: [hoodi],
|
||||
transports: {
|
||||
[sepolia.id]: fallback([
|
||||
http('https://ethereum-sepolia-rpc.publicnode.com'),
|
||||
http('https://1rpc.io/sepolia'),
|
||||
http('https://eth-sepolia.public.blastapi.io'),
|
||||
http('https://0xrpc.io/sep'),
|
||||
http('https://api.zan.top/eth-sepolia'),
|
||||
http('https://eth-sepolia.api.onfinality.io/public'),
|
||||
http('https://sepolia.drpc.org')
|
||||
]),
|
||||
// [sepolia.id]: fallback([
|
||||
// http('https://ethereum-sepolia-rpc.publicnode.com'),
|
||||
// http('https://1rpc.io/sepolia'),
|
||||
// http('https://eth-sepolia.public.blastapi.io'),
|
||||
// http('https://0xrpc.io/sep'),
|
||||
// http('https://api.zan.top/eth-sepolia'),
|
||||
// http('https://eth-sepolia.api.onfinality.io/public'),
|
||||
// http('https://sepolia.drpc.org')
|
||||
// ]),
|
||||
[hoodi.id]: fallback([
|
||||
http('https://rpc.hoodi.ethpandaops.io'),
|
||||
http('https://rpc.sentio.xyz/hoodi'),
|
||||
http('https://0xrpc.io/hoodi'),
|
||||
]),
|
||||
[mordor.id]: fallback([
|
||||
http('https://rpc.mordor.etccooperative.org'),
|
||||
http('https://geth-mordor.etc-network.info'),
|
||||
])
|
||||
// [mordor.id]: fallback([
|
||||
// http('https://rpc.mordor.etccooperative.org'),
|
||||
// http('https://geth-mordor.etc-network.info'),
|
||||
// ])
|
||||
},
|
||||
})
|
||||
|
||||
@ -1,3 +1,5 @@
|
||||
const CONNECTED_NETWORKS = 1;
|
||||
|
||||
export enum NetworkId {
|
||||
TESTNET_SEPOLIA = 11155111,
|
||||
TESTNET_HOODI = 560048,
|
||||
@ -24,18 +26,7 @@ export const isNetworkAvailable = (chainId, addressChainId) => {
|
||||
}
|
||||
|
||||
export const isNetworkLegacy = (chainId) => {
|
||||
let isLegacy = false;
|
||||
switch (chainId) {
|
||||
case 11155111:
|
||||
isLegacy = true
|
||||
break;
|
||||
case 63:
|
||||
isLegacy = true
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
return isLegacy;
|
||||
return false;
|
||||
}
|
||||
|
||||
export const isNetworkLegacyType = (chainId) => {
|
||||
@ -67,3 +58,13 @@ export const networkAvgBlockSpeed = (chainId) => {
|
||||
}
|
||||
return blockSpeed
|
||||
}
|
||||
|
||||
export const bridgeNumbers = () => {
|
||||
const number = 1 + CONNECTED_NETWORKS * 3;
|
||||
return `(${number}, ${number})`;
|
||||
}
|
||||
|
||||
export const negativeBridgeNumbers = () => {
|
||||
const number = 1 + CONNECTED_NETWORKS * 3;
|
||||
return `(-${number}, -${number})`;
|
||||
}
|
||||
|
||||
@ -4,25 +4,25 @@ export const EMPTY_ADDRESS = "0x0000000000000000000000000000000000000000";
|
||||
|
||||
export const STAKING_ADDRESSES = {
|
||||
[NetworkId.TESTNET_SEPOLIA]: "0xC2C579631Bf6daA93252154080fecfd68c6aa506",
|
||||
[NetworkId.TESTNET_HOODI]: "0xC2C579631Bf6daA93252154080fecfd68c6aa506",
|
||||
[NetworkId.TESTNET_HOODI]: "0x5d659FDEFc9c1552A3a53f661Cf4F52b0d7dDb40",
|
||||
[NetworkId.TESTNET_MORDOR]: "0xC2C579631Bf6daA93252154080fecfd68c6aa506",
|
||||
};
|
||||
|
||||
export const BOND_DEPOSITORY_ADDRESSES = {
|
||||
[NetworkId.TESTNET_SEPOLIA]: "0x46BF6F7c3e96351eab7542f2B14c9f2ac6d08dF0",
|
||||
[NetworkId.TESTNET_HOODI]: "0x46BF6F7c3e96351eab7542f2B14c9f2ac6d08dF0",
|
||||
[NetworkId.TESTNET_HOODI]: "0x4105D6b48f0fEfA8033b8B01d89972c2CBd787bD",
|
||||
[NetworkId.TESTNET_MORDOR]: "0x46BF6F7c3e96351eab7542f2B14c9f2ac6d08dF0",
|
||||
};
|
||||
|
||||
export const DAO_TREASURY_ADDRESSES = {
|
||||
[NetworkId.TESTNET_SEPOLIA]: "0x05D797f9F34844594C956da58f1785997397f02E",
|
||||
[NetworkId.TESTNET_HOODI]: "0x05D797f9F34844594C956da58f1785997397f02E",
|
||||
[NetworkId.TESTNET_HOODI]: "0xeA5113bF7e0af48B6D0Cf1a4B1e4dD0184708a09",
|
||||
[NetworkId.TESTNET_MORDOR]: "0x05D797f9F34844594C956da58f1785997397f02E",
|
||||
};
|
||||
|
||||
export const FTSO_DAI_LP_ADDRESSES = {
|
||||
export const FTSO_RESERVE_LP_ADDRESSES = {
|
||||
[NetworkId.TESTNET_SEPOLIA]: "0xCd1505E5d169525e0241c177aF5929A92E02276D",
|
||||
[NetworkId.TESTNET_HOODI]: "0x32388605b5E83Ea79CDdC479AA9939DBCF98f59D",
|
||||
[NetworkId.TESTNET_HOODI]: "0xf3F2cc4DaB20F09eee0d07d8456924927ceA1847",
|
||||
[NetworkId.TESTNET_MORDOR]: "0x53B13C4722081c405ce25c7A7629fC326A49a469",
|
||||
};
|
||||
|
||||
@ -46,43 +46,43 @@ export const WETH_ADDRESSES = {
|
||||
|
||||
export const GHST_ADDRESSES = {
|
||||
[NetworkId.TESTNET_SEPOLIA]: "0x1eCee8BfceC44e535B3Ee92Aca70507668781392",
|
||||
[NetworkId.TESTNET_HOODI]: "0x1eCee8BfceC44e535B3Ee92Aca70507668781392",
|
||||
[NetworkId.TESTNET_HOODI]: "0x594a5CD093859B3FD48aA901d86F71a7D537834a",
|
||||
[NetworkId.TESTNET_MORDOR]: "0x1eCee8BfceC44e535B3Ee92Aca70507668781392",
|
||||
};
|
||||
|
||||
export const STNK_ADDRESSES = {
|
||||
[NetworkId.TESTNET_SEPOLIA]: "0xa31cf59baC26Dd8A8b422b999eB1Ba541C941EA7",
|
||||
[NetworkId.TESTNET_HOODI]: "0xa31cf59baC26Dd8A8b422b999eB1Ba541C941EA7",
|
||||
[NetworkId.TESTNET_HOODI]: "0x7a7d0F214b8C03bD962B88AC0a7F543085aB817B",
|
||||
[NetworkId.TESTNET_MORDOR]: "0xa31cf59baC26Dd8A8b422b999eB1Ba541C941EA7",
|
||||
};
|
||||
|
||||
export const FTSO_ADDRESSES = {
|
||||
[NetworkId.TESTNET_SEPOLIA]: "0x7ebd1224D36d64eA09312073e60f352d1383801A",
|
||||
[NetworkId.TESTNET_HOODI]: "0x7ebd1224D36d64eA09312073e60f352d1383801A",
|
||||
[NetworkId.TESTNET_HOODI]: "0x07427B220934B3421223969eA61a247bFA37cF03",
|
||||
[NetworkId.TESTNET_MORDOR]: "0x7ebd1224D36d64eA09312073e60f352d1383801A",
|
||||
};
|
||||
|
||||
export const DISTRIBUTOR_ADDRESSES = {
|
||||
[NetworkId.TESTNET_SEPOLIA]: "0xfa524772eec78FAeD0db2cF8A831FDDa9F5B0544",
|
||||
[NetworkId.TESTNET_HOODI]: "0xfa524772eec78FAeD0db2cF8A831FDDa9F5B0544",
|
||||
[NetworkId.TESTNET_HOODI]: "0xe503d65C9574bD3C18c8d725cD346eCBFAE24b4d",
|
||||
[NetworkId.TESTNET_MORDOR]: "0xfa524772eec78FAeD0db2cF8A831FDDa9F5B0544",
|
||||
};
|
||||
|
||||
export const GHOST_GOVERNANCE_ADDRESSES = {
|
||||
[NetworkId.TESTNET_SEPOLIA]: "0xaf7Ad1b83C47405BB9aa96868bCFbb6D65e4C2a1",
|
||||
[NetworkId.TESTNET_HOODI]: "0xF950101af53733Ccf9309Ef4CC374B300dd43010",
|
||||
[NetworkId.TESTNET_HOODI]: "0x0000000000000000000000000000000000000000",
|
||||
[NetworkId.TESTNET_MORDOR]: "0xF950101af53733Ccf9309Ef4CC374B300dd43010",
|
||||
};
|
||||
|
||||
export const BONDING_CALCULATOR_ADDRESSES = {
|
||||
[NetworkId.TESTNET_SEPOLIA]: "0xfA821181de76D3EAdb404dDe971A6d28289F22b3",
|
||||
[NetworkId.TESTNET_HOODI]: "0xfA821181de76D3EAdb404dDe971A6d28289F22b3",
|
||||
[NetworkId.TESTNET_HOODI]: "0xf13A5319aD8071e4dcE7776728Ef9Cc221A5c098",
|
||||
[NetworkId.TESTNET_MORDOR]: "0xfA821181de76D3EAdb404dDe971A6d28289F22b3",
|
||||
}
|
||||
|
||||
export const GATEKEEPER_ADDRESSES = {
|
||||
[NetworkId.TESTNET_SEPOLIA]: "0xd735cA07984a16911222c08411A80e24EB38869B",
|
||||
[NetworkId.TESTNET_HOODI]: "0x4823F1DC785D721eAdD2bD218E1eeD63aF67fBF4",
|
||||
[NetworkId.TESTNET_HOODI]: "0xc9D5f50e17eeEAF39E0D0cDbbcF4B04FA4A4Bbd6",
|
||||
[NetworkId.TESTNET_MORDOR]: "0x4823F1DC785D721eAdD2bD218E1eeD63aF67fBF4",
|
||||
}
|
||||
|
||||
|
||||
@ -1,13 +1,15 @@
|
||||
import { ArrowBack } from "@mui/icons-material";
|
||||
import { Box, Link, Skeleton, Typography } from "@mui/material";
|
||||
import { Box, Container, Skeleton, Typography, useMediaQuery } from "@mui/material";
|
||||
import { useEffect, useState, useMemo, useCallback } from "react";
|
||||
import { Link as RouterLink, useLocation, useParams, useNavigate } from "react-router-dom";
|
||||
import { useLocation, useParams, useNavigate } from "react-router-dom";
|
||||
import { useAccount, useSwitchChain } from "wagmi";
|
||||
import { isAddress } from "viem";
|
||||
import ReactGA from "react-ga4";
|
||||
|
||||
import Countdown from "../../components/Countdown/Countdown";
|
||||
import Paper from "../../components/Paper/Paper";
|
||||
import PageTitle from "../../components/PageTitle/PageTitle";
|
||||
import Metric from "../../components/Metric/Metric";
|
||||
import MetricCollection from "../../components/Metric/MetricCollection";
|
||||
import TokenStack from "../../components/TokenStack/TokenStack";
|
||||
|
||||
import BondPrice from "./components/BondPrice";
|
||||
@ -18,12 +20,18 @@ import BondSettingsModal from "./components/BondSettingsModal";
|
||||
import NotFound from "../NotFound/NotFound";
|
||||
|
||||
import { DecimalBigNumber } from "../../helpers/DecimalBigNumber";
|
||||
import { WETH_ADDRESSES } from "../../constants/addresses";
|
||||
import { isNetworkLegacy } from "../../constants";
|
||||
import { formatCurrency } from "../../helpers";
|
||||
|
||||
import { useLocalStorage } from "../../hooks/localstorage";
|
||||
import { useLiveBonds } from "../../hooks/bonds";
|
||||
import { useFtsoPrice } from "../../hooks/prices";
|
||||
import { useTokenSymbol } from "../../hooks/tokens";
|
||||
|
||||
const SLIPPAGE_PREFIX = "bond-slippage";
|
||||
const DECIMALS_PREFIX = "bond-decimals";
|
||||
const RECIPIENT_PREFIX = "bond-recipient";
|
||||
|
||||
const BondModalContainer = ({ chainId, address, config, connect }) => {
|
||||
const { id, network } = useParams();
|
||||
@ -40,36 +48,38 @@ export const BondModal = ({ bond, chainId, address, config, connect }) => {
|
||||
const { network } = useParams();
|
||||
const { pathname } = useLocation();
|
||||
|
||||
const [isSettingsOpen, setSettingsOpen] = useState(false);
|
||||
const { getStorageValue, setStorageValue } = useLocalStorage();
|
||||
const isSmallScreen = useMediaQuery("(max-width: 650px)");
|
||||
const isVerySmallScreen = useMediaQuery("(max-width: 379px)");
|
||||
|
||||
const [slippage, setSlippage] = useState(() => getStorageValue(chainId, address, "bond-slippage", "10"));
|
||||
const [formatDecimals, setFormatDecimals] = useState(() => getStorageValue(chainId, address, "bond-decimals", "5"));
|
||||
const [recipientAddress, setRecipientAddressInner] = useState(() => getStorageValue(chainId, address, "bond-recipient", address));
|
||||
const [isSettingsOpen, setSettingsOpen] = useState(false);
|
||||
const { useStorageValue, setStorageValue } = useLocalStorage();
|
||||
|
||||
const { symbol } = useTokenSymbol(chainId, "FTSO");
|
||||
|
||||
const { data: slippage } = useStorageValue(chainId, address, SLIPPAGE_PREFIX, "10");
|
||||
const { data: formatDecimals } = useStorageValue(chainId, address, DECIMALS_PREFIX, "5");
|
||||
const { data: recipientAddress } = useStorageValue(chainId, address, RECIPIENT_PREFIX, address);
|
||||
|
||||
useEffect(() => {
|
||||
ReactGA.send({ hitType: "pageview", page: pathname });
|
||||
}, [pathname])
|
||||
|
||||
const setRecipientAddress = useCallback((value) => {
|
||||
setRecipientAddressInner(value);
|
||||
if (isAddress(value)) {
|
||||
setStorageValue(chainId, address, "bond-recipient", value);
|
||||
setStorageValue(chainId, address, RECIPIENT_PREFIX, value);
|
||||
}
|
||||
}, [chainId, address]);
|
||||
|
||||
const setSlippageInner = useCallback((value) => {
|
||||
const setSlippage = useCallback((value) => {
|
||||
const maybeValue = parseFloat(value);
|
||||
if (!maybeValue || parseFloat(value) <= 100) {
|
||||
setSlippage(value);
|
||||
setStorageValue(chainId, address, "bond-slippage", value);
|
||||
if (!maybeValue || parseFloat(value) >= 0) {
|
||||
setStorageValue(chainId, address, SLIPPAGE_PREFIX, value);
|
||||
}
|
||||
}, [chainId, address]);
|
||||
|
||||
const setFormatDecimalsInner = useCallback((value) => {
|
||||
const setFormatDecimals = useCallback((value) => {
|
||||
if (Number(value) <= 17) {
|
||||
setFormatDecimals(value);
|
||||
setStorageValue(chainId, address, "bond-decimals", value);
|
||||
setStorageValue(chainId, address, DECIMALS_PREFIX, value);
|
||||
}
|
||||
}, [chainId, address]);
|
||||
|
||||
@ -81,38 +91,30 @@ export const BondModal = ({ bond, chainId, address, config, connect }) => {
|
||||
return () => window.removeEventListener("keydown", handleKeyDown);
|
||||
}, [network, navigate, isSettingsOpen]);
|
||||
|
||||
const chainSymbol = useMemo(() => {
|
||||
const chainSymbol = config?.getClient()?.chain?.nativeCurrency?.symbol;
|
||||
if (chainSymbol) return chainSymbol;
|
||||
return "WTF";
|
||||
}, [config]);
|
||||
const chain = useMemo(() => {
|
||||
const client = config?.getClient();
|
||||
return {
|
||||
symbol: client?.chain?.nativeCurrency?.symbol,
|
||||
name: client?.chain?.name,
|
||||
}
|
||||
}, [config, chainId]);
|
||||
|
||||
const preparedQuoteToken = useMemo(() => {
|
||||
if (isNetworkLegacy(chainId)) {
|
||||
return {
|
||||
address: bond.quoteToken.quoteTokenAddress,
|
||||
chainNames: bond.quoteToken.chainNames,
|
||||
icons: bond.quoteToken.icons,
|
||||
name: bond.quoteToken.name,
|
||||
}
|
||||
return {
|
||||
address: bond.quoteToken.quoteTokenAddress,
|
||||
chainNames: bond.quoteToken.chainNames,
|
||||
icons: bond.quoteToken.icons,
|
||||
name: bond.quoteToken.name,
|
||||
isNative: bond.quoteToken.quoteTokenAddress.toLowerCase() === WETH_ADDRESSES[chainId]?.toLowerCase(),
|
||||
}
|
||||
return { address: undefined, icons: [chainSymbol], name: chainSymbol };
|
||||
}, [bond, chainSymbol, chainId])
|
||||
}, [bond, chain, chainId]);
|
||||
|
||||
return (
|
||||
<Box>
|
||||
<PageTitle
|
||||
subtitle={`(1, 1) Buy ${symbol} at a treasury-backed discount.`}
|
||||
name={
|
||||
<Box display="flex" flexDirection="row" alignItems="center">
|
||||
<Link component={RouterLink} to={`/${network}/bonds`}>
|
||||
<Box display="flex" flexDirection="row">
|
||||
<ArrowBack />
|
||||
<Typography fontWeight="500" marginLeft="9.5px" marginRight="18px">
|
||||
Back
|
||||
</Typography>
|
||||
</Box>
|
||||
</Link>
|
||||
|
||||
<TokenStack
|
||||
chainTokenNames={preparedQuoteToken.chainNames}
|
||||
tokens={preparedQuoteToken.icons}
|
||||
@ -120,7 +122,7 @@ export const BondModal = ({ bond, chainId, address, config, connect }) => {
|
||||
/>
|
||||
<Box display="flex" flexDirection="column" ml={1} justifyContent="center" alignItems="center">
|
||||
<Typography variant="h4" fontWeight={500}>
|
||||
{preparedQuoteToken.name}
|
||||
{preparedQuoteToken.name} Bond
|
||||
</Typography>
|
||||
</Box>
|
||||
</Box>
|
||||
@ -135,38 +137,54 @@ export const BondModal = ({ bond, chainId, address, config, connect }) => {
|
||||
recipientAddress={recipientAddress}
|
||||
formatDecimals={formatDecimals}
|
||||
onRecipientAddressChange={event => setRecipientAddress(event.currentTarget.value)}
|
||||
onSlippageChange={event => setSlippageInner(event.currentTarget.value)}
|
||||
onDecimalsChange={event => setFormatDecimalsInner(event.currentTarget.value)}
|
||||
onSlippageChange={event => setSlippage(event.currentTarget.value)}
|
||||
onDecimalsChange={event => setFormatDecimals(event.currentTarget.value)}
|
||||
/>
|
||||
|
||||
<Box display="flex" flexDirection="row" justifyContent="space-between" width={["100%", "70%"]} mt="24px">
|
||||
<Metric
|
||||
label={`Bond Price`}
|
||||
metric={
|
||||
bond.isSoldOut ? (
|
||||
"--"
|
||||
) : (
|
||||
<BondPrice
|
||||
price={bond.price.inUsd}
|
||||
/>
|
||||
)
|
||||
<Container
|
||||
style={{
|
||||
marginTop: "15px",
|
||||
paddingLeft: isSmallScreen || isVerySmallScreen ? "0" : "3.3rem",
|
||||
paddingRight: isSmallScreen || isVerySmallScreen ? "0" : "3.3rem",
|
||||
}}
|
||||
>
|
||||
<Paper
|
||||
fullWidth
|
||||
enableBackground
|
||||
headerContent={
|
||||
<Box display="flex" alignItems="center" flexDirection="row" gap="5px">
|
||||
<Typography variant="h6">
|
||||
Bond Expires
|
||||
<Countdown otherwise="[EXPIRED]" targetTime={bond.duration * 1000} />
|
||||
</Typography>
|
||||
</Box>
|
||||
}
|
||||
/>
|
||||
<Metric
|
||||
label="Market Price"
|
||||
metric={<TokenPrice priceInUsd={bond.price.marketPriceInUsd} />}
|
||||
/>
|
||||
<Metric
|
||||
label="Discount"
|
||||
metric={<BondDiscount discount={bond.discount} textOnly />}
|
||||
/>
|
||||
</Box>
|
||||
>
|
||||
<MetricCollection>
|
||||
<Metric
|
||||
label={`Bond Price`}
|
||||
tooltip={`Current discounted price at which ${symbol} can be acquired directly from the protocol on ${chain.name}.`}
|
||||
metric={bond.isSoldOut ? ( "--" ) : ( <BondPrice price={bond.price.inUsd} /> )}
|
||||
/>
|
||||
<Metric
|
||||
label={`${symbol} Price`}
|
||||
tooltip={`Weighted price of 1 ${symbol} across DEXs on ${chain.name}, excluding prices from other EVMs.`}
|
||||
metric={<TokenPrice priceInUsd={bond.price.marketPriceInUsd} />}
|
||||
/>
|
||||
<Metric
|
||||
label="Bond Discount"
|
||||
tooltip={`Discount rate at which the protocol offers ${symbol}. The discount dynamically increases through on-chain Dutch Auction mechanics.`}
|
||||
metric={<BondDiscount discount={bond.discount} textOnly />}
|
||||
/>
|
||||
</MetricCollection>
|
||||
</Paper>
|
||||
</Container>
|
||||
|
||||
<Box width="100%" mt="24px">
|
||||
<Box width="100%" display="flex" justifyContent="center" alignItems="center">
|
||||
<BondInputArea
|
||||
chainId={chainId}
|
||||
bond={bond}
|
||||
config={config}
|
||||
chain={chain}
|
||||
connect={connect}
|
||||
address={address}
|
||||
slippage={slippage}
|
||||
|
||||
@ -1,5 +1,5 @@
|
||||
import { Box, Tab, Tabs, Typography, Container, useMediaQuery } from "@mui/material";
|
||||
import { useEffect, useState } from "react";
|
||||
import { useEffect, useState, useMemo } from "react";
|
||||
import { useParams, useLocation } from "react-router-dom";
|
||||
import ReactGA from "react-ga4";
|
||||
|
||||
@ -19,7 +19,7 @@ import { useTotalReserves } from "../../hooks/treasury";
|
||||
import { useFtsoPrice } from "../../hooks/prices";
|
||||
import { useTokenSymbol } from "../../hooks/tokens";
|
||||
|
||||
const Bonds = ({ chainId, address, connect }) => {
|
||||
const Bonds = ({ chainId, config, address, connect }) => {
|
||||
const location = useLocation();
|
||||
const { network } = useParams();
|
||||
|
||||
@ -29,6 +29,14 @@ const Bonds = ({ chainId, address, connect }) => {
|
||||
const isSmallScreen = useMediaQuery("(max-width: 650px)");
|
||||
const isVerySmallScreen = useMediaQuery("(max-width: 379px)");
|
||||
|
||||
const chain = useMemo(() => {
|
||||
const client = config?.getClient();
|
||||
return {
|
||||
symbol: client?.chain?.nativeCurrency?.symbol,
|
||||
name: client?.chain?.name,
|
||||
}
|
||||
}, [config, chainId]);
|
||||
|
||||
useEffect(() => {
|
||||
ReactGA.send({ hitType: "pageview", page: location.pathname });
|
||||
}, [location]);
|
||||
@ -74,13 +82,15 @@ const Bonds = ({ chainId, address, connect }) => {
|
||||
>
|
||||
<MetricCollection>
|
||||
<Metric
|
||||
label={`Treasury Balance`}
|
||||
label={`Treasury Backing`}
|
||||
metric={formatCurrency(totalReserves, 2)}
|
||||
tooltip={`Total intrinsic treasury backing from pure Web3, non-freezable assets on ${chain.name} (wrapped ${chain.symbol} and Uni-V2 LP tokens), calculated as if ${ftsoSymbol} price fell to its ${chain.symbol}-denominated floor of $1 set at launch.`}
|
||||
isLoading={false}
|
||||
/>
|
||||
<Metric
|
||||
label={`${ftsoSymbol} price`}
|
||||
label={`${ftsoSymbol} Price`}
|
||||
metric={formatCurrency(ftsoPrice, 2)}
|
||||
tooltip={`Weighted price of 1 ${ftsoSymbol} across DEXs on ${chain.name}, excluding prices from other EVMs.`}
|
||||
isLoading={false}
|
||||
/>
|
||||
</MetricCollection>
|
||||
|
||||
@ -17,6 +17,9 @@ import BondDiscount from "./BondDiscount";
|
||||
import BondVesting from "./BondVesting";
|
||||
import BondSlippage from "./BondSlippage";
|
||||
|
||||
import { DecimalBigNumber } from "../../../helpers/DecimalBigNumber";
|
||||
import { formatNumber } from "../../../helpers";
|
||||
import { useLocalStorage } from "../../../hooks/localstorage";
|
||||
import { purchaseBond } from "../../../hooks/bonds";
|
||||
import { useWarmupLength } from "../../../hooks/staking";
|
||||
|
||||
@ -28,7 +31,33 @@ const StyledBox = styled(Box, {
|
||||
};
|
||||
});
|
||||
|
||||
const BondConfirmModal = ({
|
||||
export const DiscountConfirmModal = ({ isOpen, isPending, onSubmit, handleConfirmClose, discount }) => {
|
||||
const theme = useTheme();
|
||||
|
||||
return (
|
||||
<Modal
|
||||
maxWidth="380px"
|
||||
minHeight="200px"
|
||||
open={isOpen}
|
||||
headerContent={<Typography variant="h4">Confirm Bond Purchase</Typography>}
|
||||
onClose={!isPending && handleConfirmClose}
|
||||
>
|
||||
<Box display="flex" flexDirection="column" justifyContent="space-between" alignItems="center" gap="10px">
|
||||
<Typography>I confirm the bond purchase with a negative discount</Typography>
|
||||
|
||||
<Box display="flex" flexDirection="row" alignItems="center" justifyContent="center">
|
||||
<Typography color={theme.colors.feedback.error} variant="h6">{discount}%</Typography>
|
||||
</Box>
|
||||
|
||||
<PrimaryButton fullWidth onClick={onSubmit} disabled={isPending} loading={isPending}>
|
||||
Confirm
|
||||
</PrimaryButton>
|
||||
</Box>
|
||||
</Modal>
|
||||
)
|
||||
}
|
||||
|
||||
export const BondConfirmModal = ({
|
||||
chainId,
|
||||
bond,
|
||||
slippage,
|
||||
@ -37,22 +66,51 @@ const BondConfirmModal = ({
|
||||
spendAmount,
|
||||
receiveAmount,
|
||||
sender,
|
||||
handleSettingsOpen,
|
||||
isOpen,
|
||||
isNative,
|
||||
bondQuoteTokenName,
|
||||
bondQuoteTokenIcons,
|
||||
bondQuoteTokenChainNames,
|
||||
handleConfirmClose
|
||||
handleConfirmClose,
|
||||
discount,
|
||||
}) => {
|
||||
const theme = useTheme();
|
||||
|
||||
const needsNegativeRoiCheck = new DecimalBigNumber("0").lt(bond.discount);
|
||||
const { warmupLength, warmupExists: needsWarmup } = useWarmupLength(chainId);
|
||||
|
||||
const [acknowledgedNegativeDiscount, setAcknowledgedNegativeDiscount] = useState(needsNegativeRoiCheck);
|
||||
const [acknowledgedWarmup, setAcknowledgedWarmup] = useState(false);
|
||||
const [isPending, setIsPending] = useState(false);
|
||||
|
||||
const { tryStoreInHistory, CONSTANTS } = useLocalStorage();
|
||||
|
||||
useEffect(() => setAcknowledgedWarmup(acknowledgedWarmup || !needsWarmup), [acknowledgedWarmup, needsWarmup]);
|
||||
|
||||
const AcknowledgeNegativeDiscountCheckbox = () => {
|
||||
if (needsNegativeRoiCheck) return <></>;
|
||||
return (
|
||||
<Box sx={{ marginBottom: "1rem" }}>
|
||||
<FormControlLabel
|
||||
control={
|
||||
<Checkbox
|
||||
data-testid="acknowledge-bond-negative-discount"
|
||||
checked={acknowledgedNegativeDiscount}
|
||||
onChange={event => setAcknowledgedNegativeDiscount(event.target.checked)}
|
||||
icon={<CheckBoxOutlineBlank viewBox="0 0 24 24" />}
|
||||
checkedIcon={<CheckBoxOutlined viewBox="0 0 24 24" />}
|
||||
/>
|
||||
}
|
||||
label={
|
||||
<Typography variant="body2">
|
||||
I understand this bond has a negative ROI, meaning I will receive less than market value upon vesting.
|
||||
</Typography>
|
||||
}
|
||||
/>
|
||||
</Box>
|
||||
);
|
||||
};
|
||||
|
||||
const AcknowledgeWarmupCheckbox = () => {
|
||||
if (!needsWarmup) return <></>;
|
||||
return (
|
||||
@ -94,6 +152,7 @@ const BondConfirmModal = ({
|
||||
|
||||
const handleConfirmCloseMaster = () => {
|
||||
setAcknowledgedWarmup(false);
|
||||
setAcknowledgedNegativeDiscount(needsNegativeRoiCheck);
|
||||
handleConfirmClose()
|
||||
}
|
||||
|
||||
@ -104,40 +163,31 @@ const BondConfirmModal = ({
|
||||
const one = BigInt(shares * 100);
|
||||
const floatSlippage = slippage === "" ? 0 : parseFloat(slippage);
|
||||
const bigIntSlippage = one + BigInt(Math.round(floatSlippage * shares));
|
||||
|
||||
const maxPrice = bond.price.inBaseToken._value * bigIntSlippage / one;
|
||||
const referral = import.meta.env.VITE_APP_REFERRAL_ADDRESS;
|
||||
|
||||
await purchaseBond({
|
||||
const txHash = await purchaseBond({
|
||||
chainId,
|
||||
bondId: bond.id,
|
||||
amount: spendAmountValue._value.toBigInt(),
|
||||
maxPrice,
|
||||
user: recipientAddress,
|
||||
sender,
|
||||
referral,
|
||||
isNative
|
||||
});
|
||||
|
||||
if (txHash) tryStoreInHistory(chainId, sender, CONSTANTS.bond.key, txHash, CONSTANTS.bond.bond);
|
||||
|
||||
setIsPending(false);
|
||||
handleConfirmCloseMaster();
|
||||
}
|
||||
|
||||
return (
|
||||
<Modal
|
||||
maxWidth="476px"
|
||||
maxWidth="426px"
|
||||
minHeight="200px"
|
||||
open={isOpen}
|
||||
headerContent={<Typography variant="h4">{bondQuoteTokenName} Bond</Typography>}
|
||||
onClose={!isPending && handleConfirmCloseMaster}
|
||||
topRight={
|
||||
<GhostStyledIcon
|
||||
viewBox="0 0 23 23"
|
||||
component={SettingsIcon}
|
||||
style={{ cursor: "pointer" }}
|
||||
onClick={handleSettingsOpen}
|
||||
/>
|
||||
}
|
||||
>
|
||||
<>
|
||||
<Box display="flex" flexDirection="row" justifyContent="space-between" alignItems="center">
|
||||
@ -201,16 +251,16 @@ const BondConfirmModal = ({
|
||||
<DataRow title="ROI" balance={<BondDiscount discount={bond.discount} textOnly />} />
|
||||
<DataRow title="Bond Slippage" balance={<BondSlippage slippage={slippage} textOnly />} />
|
||||
<DataRow title="Vesting Term" balance={<BondVesting vesting={bond.vesting} />} />
|
||||
{!acknowledgedWarmup && <Box>
|
||||
{(!acknowledgedWarmup || !acknowledgedNegativeDiscount) && <Box>
|
||||
<Box mt="21px" mb="21px" borderTop={`1px solid ${theme.colors.gray[500]}`}></Box>
|
||||
<NeedsWarmupDetails />
|
||||
{!acknowledgedWarmup && <NeedsWarmupDetails />}
|
||||
{!acknowledgedNegativeDiscount && <AcknowledgeNegativeDiscountCheckbox />}
|
||||
</Box>}
|
||||
{acknowledgedWarmup && <PrimaryButton fullWidth onClick={onSubmit} disabled={isPending} loading={isPending}>
|
||||
|
||||
{acknowledgedNegativeDiscount && acknowledgedWarmup && <PrimaryButton fullWidth onClick={onSubmit} disabled={isPending} loading={isPending}>
|
||||
{isPending ? "Bonding..." : "Confirm Bond Purchase"}
|
||||
</PrimaryButton>}
|
||||
</>
|
||||
</Modal>
|
||||
);
|
||||
};
|
||||
|
||||
export default BondConfirmModal;
|
||||
|
||||
@ -1,7 +1,8 @@
|
||||
import { CheckBoxOutlineBlank, CheckBoxOutlined } from "@mui/icons-material";
|
||||
import { Box, Checkbox, FormControlLabel, useMediaQuery } from "@mui/material";
|
||||
import { useState, useMemo, useCallback } from "react";
|
||||
import { Box, Container, Checkbox, FormControlLabel, Typography, useMediaQuery } from "@mui/material";
|
||||
import { useState, useMemo, useEffect, useCallback } from "react";
|
||||
import { useLocation } from "react-router-dom";
|
||||
import SettingsIcon from '@mui/icons-material/Settings';
|
||||
|
||||
import { BOND_DEPOSITORY_ADDRESSES } from "../../../constants/addresses";
|
||||
import { shorten, formatNumber, formatCurrency } from "../../../helpers";
|
||||
@ -9,10 +10,11 @@ import { DecimalBigNumber } from "../../../helpers/DecimalBigNumber";
|
||||
|
||||
import BondDiscount from "./BondDiscount";
|
||||
import BondVesting from "./BondVesting";
|
||||
import BondConfirmModal from "./BondConfirmModal";
|
||||
import { BondConfirmModal, DiscountConfirmModal } from "./BondConfirmModal";
|
||||
|
||||
import { TokenAllowanceGuard } from "../../../components/TokenAllowanceGuard/TokenAllowanceGuard";
|
||||
import { PrimaryButton } from "../../../components/Button";
|
||||
import GhostStyledIcon from "../../../components/Icon/GhostIcon";
|
||||
import SwapCard from "../../../components/Swap/SwapCard";
|
||||
import SwapCollection from "../../../components/Swap/SwapCollection";
|
||||
import TokenStack from "../../../components/TokenStack/TokenStack";
|
||||
@ -24,6 +26,7 @@ import { useBalance, useTokenSymbol } from "../../../hooks/tokens";
|
||||
|
||||
const BondInputArea = ({
|
||||
bond,
|
||||
chain,
|
||||
chainId,
|
||||
slippage,
|
||||
recipientAddress,
|
||||
@ -33,20 +36,47 @@ const BondInputArea = ({
|
||||
preparedQuoteToken,
|
||||
connect
|
||||
}) => {
|
||||
const isSmallScreen = useMediaQuery("(max-width: 650px)");
|
||||
const isSemiSmallScreen = useMediaQuery("(max-width: 480px)");
|
||||
const isVerySmallScreen = useMediaQuery("(max-width: 379px)");
|
||||
|
||||
const { pathname } = useLocation();
|
||||
const [previousPathname, setPreviousPathname] = useState(pathname);
|
||||
|
||||
const [wethOption, setWethOpen] = useState(false);
|
||||
const [isWrappedToken, setIsWrappedToken] = useState(false);
|
||||
|
||||
const selectedQuoteToken = (preparedQuoteToken?.isNative && !isWrappedToken)
|
||||
? undefined
|
||||
: preparedQuoteToken?.address;
|
||||
|
||||
const toggleWethOpen = () => {
|
||||
if (!preparedQuoteToken.isNative) return;
|
||||
setWethOpen((opened) => !opened)
|
||||
}
|
||||
|
||||
const toggleQuoteToken = () => {
|
||||
if (!preparedQuoteToken.isNative) return;
|
||||
setIsWrappedToken((prev) => !prev);
|
||||
}
|
||||
|
||||
const { currentIndex } = useCurrentIndex(chainId);
|
||||
const { balance, refetch } = useBalance(chainId, preparedQuoteToken.address, address);
|
||||
const { balance, refetch } = useBalance(chainId, selectedQuoteToken, address);
|
||||
|
||||
const { symbol: ftsoSymbol } = useTokenSymbol(chainId, "FTSO");
|
||||
const { symbol: ghstSymbol } = useTokenSymbol(chainId, "GHST");
|
||||
const { balance: ftsoBalance } = useBalance(chainId, "FTSO", address);
|
||||
|
||||
const [amount, setAmount] = useState("");
|
||||
const [checked, setChecked] = useState(false);
|
||||
const [confirmOpen, setConfirmOpen] = useState(false);
|
||||
|
||||
if (pathname !== previousPathname) {
|
||||
setAmount("");
|
||||
setWethOpen(false);
|
||||
setIsWrappedToken(false);
|
||||
setPreviousPathname(pathname);
|
||||
}
|
||||
|
||||
const parsedAmount = useMemo(() => {
|
||||
return new DecimalBigNumber(amount, bond.quoteToken.decimals);
|
||||
}, [bond, amount])
|
||||
@ -56,10 +86,6 @@ const BondInputArea = ({
|
||||
return new DecimalBigNumber(0n, 0);
|
||||
}, [parsedAmount]);
|
||||
|
||||
const showDisclaimer = useMemo(() => {
|
||||
return new DecimalBigNumber("0").gt(bond.discount);
|
||||
}, [bond]);
|
||||
|
||||
const handleConfirmClose = () => {
|
||||
setAmount("");
|
||||
setConfirmOpen(false);
|
||||
@ -72,15 +98,15 @@ const BondInputArea = ({
|
||||
if (bond.capacity.inQuoteToken.lt(bond.maxPayout.inQuoteToken)) {
|
||||
return setAmount(
|
||||
bond.capacity.inQuoteToken.lt(balance)
|
||||
? bond.capacity.inQuoteToken.toString() // Capacity is the smallest
|
||||
: balance.toString(),
|
||||
? bond.capacity.inQuoteToken.toString() // Capacity is the smallest
|
||||
: balance.toString(),
|
||||
);
|
||||
}
|
||||
|
||||
setAmount(
|
||||
bond.maxPayout.inQuoteToken.lt(balance)
|
||||
? bond.maxPayout.inQuoteToken.toString() // Payout is the smallest
|
||||
: balance.toString(),
|
||||
? bond.maxPayout.inQuoteToken.toString() // Payout is the smallest
|
||||
: balance.toString(),
|
||||
);
|
||||
}, [bond, balance]);
|
||||
|
||||
@ -91,147 +117,30 @@ const BondInputArea = ({
|
||||
|
||||
const incorrectInputAmount = useMemo(() => {
|
||||
if (!balance) return false;
|
||||
return balance.lt(parsedAmount) || baseTokenString.lt(amountInBaseToken);
|
||||
const zero = new DecimalBigNumber(0n, 0);
|
||||
return parsedAmount.eq(zero)
|
||||
|| amountInBaseToken.eq(zero)
|
||||
|| balance.lt(parsedAmount)
|
||||
|| baseTokenString.lt(amountInBaseToken);
|
||||
}, [amountInBaseToken, baseTokenString, balance, parsedAmount]);
|
||||
|
||||
return (
|
||||
<Box minHeight="calc(100vh - 210px)" display="flex" flexDirection="column" justifyContent="center">
|
||||
<Box display="flex" flexDirection="row" width="100%" justifyContent="center" mt="10px">
|
||||
<Box display="flex" flexDirection="column" width="100%" maxWidth="476px">
|
||||
<Box mb="21px">
|
||||
<SwapCollection
|
||||
iconNotNeeded
|
||||
UpperSwapCard={
|
||||
<SwapCard
|
||||
maxWidth="476px"
|
||||
inputWidth={isVerySmallScreen ? "100px" : isSemiSmallScreen ? "180px" : "250px"}
|
||||
id="from"
|
||||
token={
|
||||
<TokenStack
|
||||
chainTokenNames={bond.quoteToken.chainNames}
|
||||
tokens={bond.quoteToken.icons}
|
||||
sx={{ fontSize: "25px", height: "30px" }}
|
||||
/>
|
||||
}
|
||||
tokenName={preparedQuoteToken.name}
|
||||
info={formatCurrency(balance, formatDecimals, preparedQuoteToken.name)}
|
||||
endString="Max"
|
||||
endStringOnClick={setMax}
|
||||
value={amount}
|
||||
onChange={event => setAmount(event.currentTarget.value)}
|
||||
inputProps={{ "data-testid": "fromInput" }}
|
||||
/>}
|
||||
LowerSwapCard={
|
||||
<SwapCard
|
||||
maxWidth="476px"
|
||||
inputWidth={isVerySmallScreen ? "100px" : isSemiSmallScreen ? "180px" : "250px"}
|
||||
id="to"
|
||||
token={
|
||||
<TokenStack
|
||||
chainTokenNames={bond.baseToken.chainNames}
|
||||
tokens={bond.baseToken.icons}
|
||||
sx={{ fontSize: "25px", height: "30px" }}
|
||||
/>
|
||||
}
|
||||
tokenName={bond.baseToken.name}
|
||||
value={amountInBaseToken.toString({ decimals: 9 })}
|
||||
inputProps={{ "data-testid": "toInput" }}
|
||||
/>
|
||||
}
|
||||
/>
|
||||
</Box>
|
||||
|
||||
<TokenAllowanceGuard
|
||||
spendAmount={parsedAmount}
|
||||
tokenName={bond.quoteToken.quoteTokenAddress}
|
||||
owner={address}
|
||||
spender={BOND_DEPOSITORY_ADDRESSES[chainId]}
|
||||
decimals={parsedAmount._decimals}
|
||||
approvalText={`Approve ${bond.quoteToken.name} to Bond`}
|
||||
approvalPendingText={"Approving..."}
|
||||
connect={connect}
|
||||
width="100%"
|
||||
height="60px"
|
||||
isNative={preparedQuoteToken.address === undefined}
|
||||
isVertical
|
||||
message={
|
||||
<>
|
||||
First time bonding <b>{bond.quoteToken.name}</b>? <br /> Please approve ghostDAO to use your{" "}
|
||||
<b>{bond.quoteToken.name}</b> for bonding.
|
||||
</>
|
||||
}
|
||||
>
|
||||
{showDisclaimer && (
|
||||
<FormControlLabel
|
||||
control={
|
||||
<Checkbox
|
||||
checked={checked}
|
||||
onChange={event => setChecked(event.target.checked)}
|
||||
icon={<CheckBoxOutlineBlank viewBox="0 0 24 24" />}
|
||||
checkedIcon={<CheckBoxOutlined viewBox="0 0 24 24" />}
|
||||
/>
|
||||
}
|
||||
label="I understand that I'm buying a negative discount bond"
|
||||
/>
|
||||
)}
|
||||
<PrimaryButton
|
||||
fullWidth
|
||||
disabled={incorrectInputAmount || bond.isSoldOut || (showDisclaimer && !checked)}
|
||||
onClick={() => setConfirmOpen(true)}
|
||||
>
|
||||
Bond
|
||||
</PrimaryButton>
|
||||
</TokenAllowanceGuard>
|
||||
|
||||
<Paper style={{ marginBottom: "7px", marginTop: "21px" }} fullWidth enableBackground>
|
||||
<Box mt="24px">
|
||||
<DataRow
|
||||
title={"You Will Get"}
|
||||
balance={
|
||||
<span>
|
||||
{formatCurrency(amountInBaseToken, formatDecimals, ftsoSymbol)}
|
||||
{" "}
|
||||
{!!currentIndex && (
|
||||
<span>
|
||||
(≈{formatCurrency(amountInBaseToken.div(currentIndex), formatDecimals, ghstSymbol)})
|
||||
</span>
|
||||
)}
|
||||
</span>
|
||||
}
|
||||
tooltip={`Total amount of ${ftsoSymbol} you will receive from this bond purchase`}
|
||||
/>
|
||||
|
||||
<DataRow
|
||||
title="Max You Can Buy"
|
||||
tooltip={`Maximum ${ftsoSymbol} that can be purchased in a single transaction. Prevents whales from buying entire bond supply at once.`}
|
||||
balance={
|
||||
<span>
|
||||
{bond.baseToken.tokenAddress.toUpperCase() === bond.quoteToken.quoteTokenAddress.toUpperCase()
|
||||
? `${formatCurrency(baseTokenString, formatDecimals, ftsoSymbol)}`
|
||||
: `${formatCurrency(baseTokenString, formatDecimals, ftsoSymbol)} (≈${formatCurrency(baseTokenString.div(currentIndex), formatDecimals, ghstSymbol)})`}
|
||||
</span>
|
||||
}
|
||||
/>
|
||||
|
||||
<DataRow
|
||||
title="Discount"
|
||||
balance={<BondDiscount discount={bond.discount} textOnly />}
|
||||
tooltip={`The discount (or premium) between ${ftsoSymbol} market price and bond price. Higher discount = better deal for bond buyers.`}
|
||||
/>
|
||||
|
||||
<DataRow
|
||||
title={`Vesting Term`}
|
||||
balance={<BondVesting vesting={bond.vesting} />}
|
||||
tooltip={"Time until bond fully vests and becomes claimable. Vesting period aligns bond buyer with the protocol by encouraging longer-term holding."}
|
||||
/>
|
||||
|
||||
{recipientAddress !== address && (
|
||||
<DataRow title={`Recipient`} balance={shorten(recipientAddress)} />
|
||||
)}
|
||||
</Box>
|
||||
</Paper>
|
||||
</Box>
|
||||
</Box>
|
||||
<Box sx={{ 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={handleSettingsOpen}
|
||||
/>
|
||||
}
|
||||
headerContent={
|
||||
<Typography variant="h6">Bond</Typography>
|
||||
}
|
||||
>
|
||||
<BondConfirmModal
|
||||
chainId={chainId}
|
||||
bond={bond}
|
||||
@ -240,17 +149,156 @@ const BondInputArea = ({
|
||||
spendAmountValue={parsedAmount}
|
||||
spendAmount={formatNumber(parsedAmount, formatDecimals)}
|
||||
receiveAmount={formatNumber(amountInBaseToken, formatDecimals)}
|
||||
bondQuoteTokenName={preparedQuoteToken.name}
|
||||
bondQuoteTokenName={selectedQuoteToken ? preparedQuoteToken.name : chain.symbol}
|
||||
bondQuoteTokenIcons={preparedQuoteToken.icons}
|
||||
bondQuoteTokenChainNames={preparedQuoteToken.chainNames}
|
||||
isNative={preparedQuoteToken.address === undefined}
|
||||
isNative={selectedQuoteToken === undefined}
|
||||
handleSettingsOpen={handleSettingsOpen}
|
||||
isOpen={confirmOpen}
|
||||
sender={address}
|
||||
handleConfirmClose={() => handleConfirmClose()}
|
||||
handleConfirmClose={handleConfirmClose}
|
||||
/>
|
||||
</Box>
|
||||
);
|
||||
};
|
||||
|
||||
<Box maxWidth="390px" display="flex" flexDirection="column" justifyContent="center" gap="15px">
|
||||
<SwapCollection
|
||||
iconNotNeeded
|
||||
UpperSwapCard={
|
||||
<SwapCard
|
||||
id="from"
|
||||
token={
|
||||
<TokenStack
|
||||
chainTokenNames={bond.quoteToken.chainNames}
|
||||
tokens={bond.quoteToken.icons}
|
||||
sx={{ fontSize: "25px", height: "30px" }}
|
||||
/>
|
||||
}
|
||||
tokenOnClick={preparedQuoteToken.isNative ? toggleQuoteToken : undefined}
|
||||
tokenName={selectedQuoteToken ? preparedQuoteToken.name : chain.symbol}
|
||||
info={
|
||||
(!isSemiSmallScreen ? "Balance: " : "") +
|
||||
formatCurrency(
|
||||
balance,
|
||||
formatDecimals,
|
||||
selectedQuoteToken ? preparedQuoteToken.name : chain.symbol
|
||||
)
|
||||
}
|
||||
endString="Max"
|
||||
endStringOnClick={setMax}
|
||||
value={amount}
|
||||
onChange={event => setAmount(event.currentTarget.value)}
|
||||
inputProps={{ "data-testid": "fromInput" }}
|
||||
/>}
|
||||
LowerSwapCard={
|
||||
<SwapCard
|
||||
id="to"
|
||||
token={
|
||||
<TokenStack
|
||||
chainTokenNames={bond.baseToken.chainNames}
|
||||
tokens={bond.baseToken.icons}
|
||||
sx={{ fontSize: "25px", height: "30px" }}
|
||||
/>
|
||||
}
|
||||
info={
|
||||
(!isSemiSmallScreen ? "Balance: " : "") +
|
||||
formatCurrency(ftsoBalance, formatDecimals, ftsoSymbol)
|
||||
}
|
||||
tokenName={bond.baseToken.name}
|
||||
value={amountInBaseToken.toString({ decimals: 9 })}
|
||||
inputProps={{ "data-testid": "toInput" }}
|
||||
/>
|
||||
}
|
||||
/>
|
||||
|
||||
<Box
|
||||
display="flex"
|
||||
flexDirection="column"
|
||||
sx={{
|
||||
"& .DataRow-root": {
|
||||
margin: "0px !important",
|
||||
},
|
||||
"& .MuiTypography-root": {
|
||||
fontSize: "13px !important",
|
||||
},
|
||||
"& span": {
|
||||
fontSize: "13px !important",
|
||||
}
|
||||
}}
|
||||
>
|
||||
<DataRow
|
||||
title={"Bond Payout"}
|
||||
balance={
|
||||
<span>
|
||||
{formatCurrency(amountInBaseToken, formatDecimals, ftsoSymbol)}
|
||||
{" "}
|
||||
{!!currentIndex && (
|
||||
<span>
|
||||
(≈{formatCurrency(amountInBaseToken.div(currentIndex), formatDecimals, ghstSymbol)})
|
||||
</span>
|
||||
)}
|
||||
</span>
|
||||
}
|
||||
tooltip={`Total amount of ${ftsoSymbol} you will receive from this bond purchase`}
|
||||
/>
|
||||
|
||||
<DataRow
|
||||
title="Max Payout"
|
||||
tooltip={`Maximum ${ftsoSymbol} that can be purchased in a single transaction. Prevents whales from buying entire bond supply at once.`}
|
||||
balance={
|
||||
<span>
|
||||
{bond.baseToken.tokenAddress.toUpperCase() === bond.quoteToken.quoteTokenAddress.toUpperCase()
|
||||
? `${formatCurrency(baseTokenString, formatDecimals, ftsoSymbol)}`
|
||||
: `${formatCurrency(baseTokenString, formatDecimals, ftsoSymbol)} (≈${formatCurrency(baseTokenString.div(currentIndex), formatDecimals, ghstSymbol)})`}
|
||||
</span>
|
||||
}
|
||||
/>
|
||||
|
||||
<DataRow
|
||||
title={`Vesting Term`}
|
||||
balance={<span><BondVesting vesting={bond.vesting} /></span>}
|
||||
tooltip={"Time until bond fully vests and becomes claimable. Vesting period aligns bond buyer with the protocol by encouraging longer-term holding."}
|
||||
/>
|
||||
|
||||
{recipientAddress !== address && (
|
||||
<DataRow
|
||||
title={`Recipient`}
|
||||
balance={<span>{shorten(recipientAddress)}</span>}
|
||||
tooltip="The address that will receive the bond. To change it from your connected account, update the settings via the gear icon."
|
||||
/>
|
||||
)}
|
||||
</Box>
|
||||
|
||||
<TokenAllowanceGuard
|
||||
spendAmount={parsedAmount}
|
||||
tokenName={bond.quoteToken.quoteTokenAddress}
|
||||
owner={address}
|
||||
spender={BOND_DEPOSITORY_ADDRESSES[chainId]}
|
||||
decimals={parsedAmount._decimals}
|
||||
approvalText={`Approve ${bond.quoteToken.name} to Bond`}
|
||||
approvalPendingText={"Approving..."}
|
||||
connect={connect}
|
||||
width="100%"
|
||||
height="60px"
|
||||
isNative={selectedQuoteToken === undefined}
|
||||
isVertical
|
||||
message={
|
||||
<>
|
||||
First time bonding <b>{bond.quoteToken.name}</b>? <br /> Please approve ghostDAO to use your{" "}
|
||||
<b>{bond.quoteToken.name}</b> for bonding.
|
||||
</>
|
||||
}
|
||||
>
|
||||
<PrimaryButton
|
||||
fullWidth
|
||||
disabled={incorrectInputAmount || bond.isSoldOut}
|
||||
onClick={() => setConfirmOpen(true)}
|
||||
>
|
||||
Bond
|
||||
</PrimaryButton>
|
||||
</TokenAllowanceGuard>
|
||||
</Box>
|
||||
</Paper>
|
||||
</Box>
|
||||
)
|
||||
};
|
||||
|
||||
export default BondInputArea;
|
||||
|
||||
@ -53,7 +53,7 @@ const BondSettingsModal = props => {
|
||||
</Box>
|
||||
|
||||
<Box mt="32px">
|
||||
<InputLabel htmlFor="recipient">Recipient Address</InputLabel>
|
||||
<InputLabel htmlFor="recipient">Custom destination address</InputLabel>
|
||||
<Box mt="8px">
|
||||
<FormControl variant="outlined" color="primary" fullWidth>
|
||||
<OutlinedInput
|
||||
@ -67,7 +67,7 @@ const BondSettingsModal = props => {
|
||||
</Box>
|
||||
<Box mt="8px">
|
||||
<Typography variant="body2" color="textSecondary">
|
||||
Choose recipient address. By default, this is your currently connected address
|
||||
Recipient address of bonded assets
|
||||
</Typography>
|
||||
</Box>
|
||||
</Box>
|
||||
|
||||
@ -13,11 +13,11 @@ const BondSlippage = ({ slippage, textOnly }) => {
|
||||
color: isSlippageBig ? theme.colors.feedback.error : theme.colors.feedback.pnlGain,
|
||||
}}
|
||||
>
|
||||
{slippage}%
|
||||
{formatNumber(slippage, 2)}%
|
||||
</Box>
|
||||
) : (
|
||||
<Chip
|
||||
label={`${slippage}%`}
|
||||
label={`${formatNumber(slippage, 2)}%`}
|
||||
template={isSlippageBig ? "error" : "success"}
|
||||
/>
|
||||
);
|
||||
|
||||
@ -1,7 +1,7 @@
|
||||
import { prettifySecondsInDays } from "../../../helpers/timeUtil";
|
||||
|
||||
const BondVesting = ({ vesting }) => {
|
||||
return <>{vesting > 0 ? prettifySecondsInDays(vesting) : "Instant"}</>;
|
||||
return <>{vesting > 0 ? prettifySecondsInDays(vesting) : "Infinity"}</>;
|
||||
};
|
||||
|
||||
export default BondVesting;
|
||||
|
||||
@ -23,6 +23,7 @@ import { useNotes, redeem, forceRedeem } from "../../../hooks/bonds";
|
||||
import { useTokenSymbol } from "../../../hooks/tokens";
|
||||
import { useGhstPrice } from "../../../hooks/prices";
|
||||
import { useBreakoutModal } from "../../../hooks/breakoutModal";
|
||||
import { useLocalStorage } from "../../../hooks/localstorage";
|
||||
|
||||
export const ClaimBonds = ({ chainId, address, secondsTo }) => {
|
||||
const isSmallScreen = useScreenSize("md");
|
||||
@ -33,6 +34,7 @@ export const ClaimBonds = ({ chainId, address, secondsTo }) => {
|
||||
const [isPayoutGhst, _] = useState(true);
|
||||
|
||||
const ghstPrice = useGhstPrice(chainId);
|
||||
const { tryStoreInHistory, CONSTANTS } = useLocalStorage();
|
||||
const { breakoutFromBonding } = useBreakoutModal();
|
||||
const { epoch } = useEpoch(chainId);
|
||||
const { warmupExists } = useWarmupLength(chainId);
|
||||
@ -59,8 +61,9 @@ export const ClaimBonds = ({ chainId, address, secondsTo }) => {
|
||||
setPendingIndexes(indexes);
|
||||
|
||||
const defaultFunction = async () => {
|
||||
await redeem({ chainId, user: address, isGhst: isPayoutGhst, indexes });
|
||||
await notesRefetch();
|
||||
const txHash = await redeem({ chainId, user: address, isGhst: isPayoutGhst, indexes });
|
||||
if (txHash) tryStoreInHistory(chainId, address, CONSTANTS.bond.key, txHash, CONSTANTS.bond.claim);
|
||||
return txHash;
|
||||
};
|
||||
|
||||
if (isNetworkLegacy(chainId)) {
|
||||
@ -79,11 +82,14 @@ export const ClaimBonds = ({ chainId, address, secondsTo }) => {
|
||||
|
||||
const toExecute = async (receiver) => {
|
||||
const txHash = await forceRedeem({ chainId, user: address, receiver, indexes });
|
||||
if (txHash) tryStoreInHistory(chainId, address, CONSTANTS.bridgeIn.key, txHash, CONSTANTS.bridgeIn.name);
|
||||
return txHash;
|
||||
}
|
||||
|
||||
breakoutFromBonding({ defaultFunction, toExecute, amount, warmupLeft })
|
||||
}
|
||||
|
||||
await notesRefetch();
|
||||
setPendingIndexes([]);
|
||||
setIsPending(false);
|
||||
}
|
||||
@ -143,7 +149,10 @@ export const ClaimBonds = ({ chainId, address, secondsTo }) => {
|
||||
{notes.map((note, index) => (
|
||||
<Box key={index} mt="32px">
|
||||
<Box display="flex" alignItems="center">
|
||||
<TokenStack chainTokenNames={note.quoteToken.chainNames} tokens={note.quoteToken.icons} />
|
||||
<TokenStack
|
||||
chainTokenNames={note.quoteToken.chainNames}
|
||||
tokens={note.quoteToken.icons}
|
||||
/>
|
||||
<Box ml="8px">
|
||||
<Typography>{note.quoteToken.name}</Typography>
|
||||
</Box>
|
||||
@ -205,7 +214,10 @@ export const ClaimBonds = ({ chainId, address, secondsTo }) => {
|
||||
<TableRow key={index}>
|
||||
<TableCell style={{ padding: "8px 0" }}>
|
||||
<Box display="flex" alignItems="center">
|
||||
<TokenStack chainTokenNames={note.quoteToken.chainNames} tokens={note.quoteToken.icons} />
|
||||
<TokenStack
|
||||
chainTokenNames={note.quoteToken.chainNames}
|
||||
tokens={note.quoteToken.icons}
|
||||
/>
|
||||
<Box display="flex" flexDirection="column" ml="16px">
|
||||
<Typography>{note.quoteToken.name}</Typography>
|
||||
</Box>
|
||||
|
||||
@ -1,6 +1,6 @@
|
||||
import useSWR from 'swr';
|
||||
import { useMemo, useState, useCallback, useEffect } from "react";
|
||||
import { Box, Typography, Link, Checkbox, FormControlLabel, useTheme } from "@mui/material";
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { Box, Typography, Link, Checkbox, FormControlLabel, Skeleton, useTheme } from "@mui/material";
|
||||
import { getBlockNumber } from "@wagmi/core";
|
||||
import { useConfig } from "wagmi";
|
||||
import { ss58Decode } from "@polkadot-labs/hdkd-helpers";
|
||||
@ -10,33 +10,64 @@ import CancelIcon from '@mui/icons-material/Cancel';
|
||||
import ArrowDropDownIcon from '@mui/icons-material/ArrowDropDown';
|
||||
import { CheckBoxOutlineBlank, CheckBoxOutlined } from "@mui/icons-material";
|
||||
|
||||
import { BridgeGhostAddressCard } from "../Bridge/BridgeGhostAddress";
|
||||
import Metric from "../../components/Metric/Metric";
|
||||
import Modal from "../../components/Modal/Modal";
|
||||
import SwapCard from "../../components/Swap/SwapCard";
|
||||
import Token from "../../components/Token/Token";
|
||||
import GhostStyledIcon from "../../components/Icon/GhostIcon";
|
||||
import { PrimaryButton, SecondaryButton } from "../../components/Button";
|
||||
import { GATEKEEPER_ADDRESSES, EMPTY_ADDRESS } from "../../constants/addresses";
|
||||
import { GHOST_CONNECT } from "../../constants/ecosystem";
|
||||
import { networkAvgBlockSpeed, bridgeNumbers } from "../../constants";
|
||||
|
||||
import { useLocalStorage } from "../../hooks/localstorage";
|
||||
import { useBreakoutModal } from "../../hooks/breakoutModal";
|
||||
import { useTokenSymbol } from "../../hooks/tokens";
|
||||
import { useEpoch, useGatekeeperApy, useGatekeeperAddress } from "../../hooks/staking";
|
||||
import { useEpoch, useGatekeeperApy, useGatekeeperMinimum, useGatekeeperAddress } from "../../hooks/staking";
|
||||
import { useEvmNetwork, useCurrentIndex, useUnstableProvider } from "../../hooks/ghost";
|
||||
import { formatNumber, shorten } from "../../helpers";
|
||||
import { prettifySecondsInDays } from "../../helpers/timeUtil";
|
||||
import { DecimalBigNumber } from "../../helpers/DecimalBigNumber";
|
||||
|
||||
const BreakoutModal = ({ chainId, address }) => {
|
||||
const { casperApi, account } = useUnstableProvider();
|
||||
|
||||
const [step, setStep] = useState(0);
|
||||
const [receiver, setReceiver] = useState("");
|
||||
const [isPending, setIsPending] = useState(false);
|
||||
const [receiver, setReceiver] = useState(account ?.address);
|
||||
const [convertedReceiver, setConvertedReceiver] = useState(undefined);
|
||||
|
||||
const [prevAddress, setPrevAddress] = useState(account?.address);
|
||||
|
||||
if (account?.address !== prevAddress) {
|
||||
setPrevAddress(account?.address);
|
||||
if (account?.address && !receiver) setReceiver(account.address);
|
||||
}
|
||||
|
||||
const { symbol: ghstSymbol } = useTokenSymbol(chainId, "GHST");
|
||||
const { symbol: ftsoSymbol } = useTokenSymbol(chainId, "FTSO");
|
||||
|
||||
const evmNetwork = useEvmNetwork({ evmChainId: chainId });
|
||||
const { gatekeeperAddress } = useGatekeeperAddress(chainId);
|
||||
|
||||
const { data: networkData, isLoading: isNetworkDataLoading } = useSWR(
|
||||
casperApi ? ['networkData', casperApi, chainId] : null,
|
||||
async () => {
|
||||
const key = BigInt(chainId);
|
||||
const res = await casperApi.query.GhostNetworks.Networks.getValue(key);
|
||||
return res;
|
||||
},
|
||||
);
|
||||
|
||||
const incomingFee = useMemo(() => {
|
||||
const hundredPercent = 10000000;
|
||||
const incomingShare = networkData ? networkData.incoming_share : 0;
|
||||
return incomingShare / hundredPercent;
|
||||
}, [networkData]);
|
||||
|
||||
const gatekeepersMatch = useMemo(() => {
|
||||
if (!networkData) return false;
|
||||
return gatekeeperAddress.toUpperCase() == toHex(networkData.gatekeeper).toUpperCase();
|
||||
}, [gatekeeperAddress, networkData]);
|
||||
|
||||
const {
|
||||
isOpened,
|
||||
@ -44,28 +75,22 @@ const BreakoutModal = ({ chainId, address }) => {
|
||||
isStakingOpened,
|
||||
isClaimBondOpened,
|
||||
warmupPeriod,
|
||||
setActiveTxIndex,
|
||||
defaultFunction,
|
||||
executableFunction,
|
||||
estimatedAmount
|
||||
} = useBreakoutModal();
|
||||
|
||||
const incomingFee = useMemo(() => {
|
||||
return new DecimalBigNumber(
|
||||
evmNetwork ? evmNetwork.incoming_fee : 100000000,
|
||||
7
|
||||
);
|
||||
}, [evmNetwork]);
|
||||
|
||||
const closeModal = () => {
|
||||
setActiveTxIndex(-1);
|
||||
closeModalPure();
|
||||
}
|
||||
|
||||
const closeModalPure = () => {
|
||||
setStep(0);
|
||||
setReceiver("");
|
||||
closeModalInner();
|
||||
if (!isPending) {
|
||||
setStep(0);
|
||||
setReceiver(account?.address ?? "");
|
||||
setPrevAddress(undefined);
|
||||
closeModalInner();
|
||||
}
|
||||
}
|
||||
|
||||
const header = useMemo(() => {
|
||||
@ -75,12 +100,6 @@ const BreakoutModal = ({ chainId, address }) => {
|
||||
if (isClaimBondOpened && warmupPeriod > 0) return "Bond in Warm-up"
|
||||
}, [isStakingOpened, isClaimBondOpened, warmupPeriod]);
|
||||
|
||||
const bridgeNumbers = useMemo(() => {
|
||||
const connectedNetworks = Object.keys(GATEKEEPER_ADDRESSES).length;
|
||||
const number = 1 + connectedNetworks * 3;
|
||||
return `(${number}, ${number})`;
|
||||
}, [chainId]);
|
||||
|
||||
useEffect(() => {
|
||||
try {
|
||||
const [publicKey, prefix] = ss58Decode(receiver);
|
||||
@ -97,7 +116,12 @@ const BreakoutModal = ({ chainId, address }) => {
|
||||
<Modal
|
||||
headerContent={
|
||||
<Box display="flex" justifyContent="center" alignItems="center" gap="15px">
|
||||
<Typography variant="h4">{step === 0 ? header : step === 1 ? `Start ${bridgeNumbers} ${"Stake\u00B2"}` : "Bridge Confirmation"}</Typography>
|
||||
<Typography variant="h4">
|
||||
{step === 0 ? header : step === 1
|
||||
? `Start ${bridgeNumbers()} ${"Stake\u00B2"}`
|
||||
: "Bridge Confirmation"
|
||||
}
|
||||
</Typography>
|
||||
</Box>
|
||||
}
|
||||
open={isOpened}
|
||||
@ -110,42 +134,51 @@ const BreakoutModal = ({ chainId, address }) => {
|
||||
? <WelcomeView
|
||||
isStakingOpened={isStakingOpened}
|
||||
chainId={chainId}
|
||||
isPending={isPending}
|
||||
setIsPending={setIsPending}
|
||||
warmupPeriod={warmupPeriod}
|
||||
ghstSymbol={ghstSymbol}
|
||||
ftsoSymbol={ftsoSymbol}
|
||||
bridgeNumbers={bridgeNumbers}
|
||||
defaultFunction={defaultFunction}
|
||||
goNext={() => setStep(1)}
|
||||
closeModal={closeModal}
|
||||
incomingFee={incomingFee}
|
||||
estimatedAmount={estimatedAmount}
|
||||
gatekeepersMatch={gatekeepersMatch}
|
||||
isNetworkDataLoading={isNetworkDataLoading}
|
||||
/>
|
||||
: step === 1
|
||||
? <BridgeView
|
||||
receiver={receiver}
|
||||
setReceiver={setReceiver}
|
||||
chainId={chainId}
|
||||
bridgeNumbers={bridgeNumbers}
|
||||
bridgeNumbers={bridgeNumbers()}
|
||||
ghstSymbol={ghstSymbol}
|
||||
estimatedAmount={estimatedAmount}
|
||||
incomingFee={incomingFee}
|
||||
goNext={() => setStep(2)}
|
||||
convertedReceiver={convertedReceiver}
|
||||
setConvertedReceiver={setConvertedReceiver}
|
||||
incomingFee={incomingFee}
|
||||
networkData={networkData}
|
||||
gatekeepersMatch={gatekeepersMatch}
|
||||
gatekeeperAddress={gatekeeperAddress}
|
||||
|
||||
/>
|
||||
: <ConfirmStep
|
||||
chainId={chainId}
|
||||
address={address}
|
||||
receiver={receiver}
|
||||
isPending={isPending}
|
||||
setIsPending={setIsPending}
|
||||
executableFunction={executableFunction}
|
||||
isStakingOpened={isStakingOpened}
|
||||
bridgeNumbers={bridgeNumbers}
|
||||
incomingFee={incomingFee}
|
||||
estimatedAmount={estimatedAmount}
|
||||
ghstSymbol={ghstSymbol}
|
||||
setActiveTxIndex={setActiveTxIndex}
|
||||
closeModal={closeModalPure}
|
||||
evmNetwork={evmNetwork}
|
||||
convertedReceiver={convertedReceiver}
|
||||
networkData={networkData}
|
||||
gatekeepersMatch={gatekeepersMatch}
|
||||
incomingFee={incomingFee}
|
||||
/>
|
||||
}
|
||||
</Box>
|
||||
@ -153,121 +186,25 @@ const BreakoutModal = ({ chainId, address }) => {
|
||||
)
|
||||
}
|
||||
|
||||
const BridgeView = ({
|
||||
chainId,
|
||||
receiver,
|
||||
setReceiver,
|
||||
convertedReceiver,
|
||||
setConvertedReceiver,
|
||||
bridgeNumbers,
|
||||
ghstSymbol,
|
||||
estimatedAmount,
|
||||
goNext,
|
||||
incomingFee
|
||||
}) => {
|
||||
const theme = useTheme();
|
||||
const [inputFocused, setInputFocused] = useState(false);
|
||||
|
||||
const config = useConfig();
|
||||
const { gatekeeperAddress } = useGatekeeperAddress(chainId);
|
||||
|
||||
const chainExplorerUrl = useMemo(() => {
|
||||
const client = config?.getClient();
|
||||
return client?.chain?.blockExplorers?.default?.url;
|
||||
}, [config]);
|
||||
|
||||
return (
|
||||
<>
|
||||
<Typography>Bridge to start earning {bridgeNumbers} {"Stake\u00B2"} on your {ghstSymbol} balance:</Typography>
|
||||
|
||||
<Box display="flex" justifyContent="center">
|
||||
<Typography variant="h5">{formatNumber(estimatedAmount, 5)} {ghstSymbol}</Typography>
|
||||
</Box>
|
||||
|
||||
<Typography>
|
||||
Generate a unique address for per tx with <Link underline="hover" href={GHOST_CONNECT} color={theme.colors.primary[300]}>GHOST Connect</Link> for privacy.
|
||||
</Typography>
|
||||
|
||||
<SwapCard
|
||||
id={`bridge-token-receiver`}
|
||||
inputWidth={"100%"}
|
||||
onBlur={() => setInputFocused(true)}
|
||||
onFocus={() => setInputFocused(false)}
|
||||
onChange={event => setReceiver(event.currentTarget.value)}
|
||||
placeholder={convertedReceiver ? shorten(receiver, 15, -10) : "GHOST address (sf prefixed)"}
|
||||
value={convertedReceiver ? "" : receiver}
|
||||
inputProps={{ "data-testid": "fromInput" }}
|
||||
endString={convertedReceiver
|
||||
? <GhostStyledIcon color="success" viewBox="0 0 25 25" component={CheckIcon} />
|
||||
: inputFocused && receiver !== ""
|
||||
? <GhostStyledIcon color="error" viewBox="0 0 25 25" component={CancelIcon} />
|
||||
: undefined
|
||||
}
|
||||
type="text"
|
||||
maxWidth="100%"
|
||||
/>
|
||||
|
||||
<Box display="flex" justifyContent="center" flexDirection="column" alignItems="center">
|
||||
<Box width="100%" display="flex" flexDirection="row" justifyContent="space-between">
|
||||
<Typography variant="body2">Gatekeeper</Typography>
|
||||
<Link
|
||||
fontSize="12px"
|
||||
lineHeight="15px"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
href={`${chainExplorerUrl}/token/${gatekeeperAddress}`}
|
||||
>
|
||||
<Typography variant="body2">
|
||||
{shorten(gatekeeperAddress, 10, -8)}
|
||||
</Typography>
|
||||
</Link>
|
||||
</Box>
|
||||
<Box width="100%" display="flex" flexDirection="row" justifyContent="space-between">
|
||||
<Typography variant="body2">Bridge Fee</Typography>
|
||||
<Typography variant="body2">{formatNumber(incomingFee, 4)}%</Typography>
|
||||
</Box>
|
||||
<Box width="100%" display="flex" flexDirection="row" justifyContent="space-between">
|
||||
<Typography variant="body2">Est. Time</Typography>
|
||||
<Typography variant="body2">20 mins</Typography>
|
||||
</Box>
|
||||
</Box>
|
||||
|
||||
<PrimaryButton
|
||||
onClick={goNext}
|
||||
disabled={convertedReceiver === undefined}
|
||||
fullWidth
|
||||
>
|
||||
Proceed
|
||||
</PrimaryButton>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
const WelcomeView = ({
|
||||
bridgeNumbers,
|
||||
goNext,
|
||||
isStakingOpened,
|
||||
chainId,
|
||||
isPending,
|
||||
setIsPending,
|
||||
warmupPeriod,
|
||||
ghstSymbol,
|
||||
ftsoSymbol,
|
||||
estimatedAmount,
|
||||
defaultFunction,
|
||||
closeModal
|
||||
closeModal,
|
||||
incomingFee,
|
||||
gatekeepersMatch,
|
||||
isNetworkDataLoading
|
||||
}) => {
|
||||
const [refreshNeeded, setRefreshNeeded] = useState(false);
|
||||
const [isPending, setIsPending] = useState(false);
|
||||
|
||||
const { epoch } = useEpoch(chainId);
|
||||
const { gatekeeperAddress } = useGatekeeperAddress(chainId);
|
||||
const { gatekeepedApy, apyInner } = useGatekeeperApy(chainId);
|
||||
|
||||
const { isExtensionMissing } = useUnstableProvider();
|
||||
|
||||
const refreshPage = () => window.location.reload();
|
||||
const getConnect = () => {
|
||||
setRefreshNeeded(true)
|
||||
window.open(GHOST_CONNECT, '_blank', 'noopener,noreferrer');
|
||||
}
|
||||
const { existentialDeposit } = useGatekeeperMinimum(chainId);
|
||||
|
||||
const callDefaultFunction = useCallback(async () => {
|
||||
setIsPending(true);
|
||||
@ -295,7 +232,7 @@ const WelcomeView = ({
|
||||
>
|
||||
{warmupPeriod > 0
|
||||
? `Warm-up ends in ${prettifySecondsInDays(epoch.length * warmupPeriod)}`
|
||||
: `${isPending ? "Claiming..." : "Claim"} ${isStakingOpened ? "(3, 3) Stake" : "(1, 1) Bond"}`
|
||||
: `${isPending ? "Claiming..." : `Claim ${isStakingOpened ? "(3, 3) Stake" : "(1, 1) Bond"}`}`
|
||||
}
|
||||
</SecondaryButton>
|
||||
|
||||
@ -307,24 +244,150 @@ const WelcomeView = ({
|
||||
|
||||
<Box display="flex" flexDirection="column" justifyContent="space-between" gap="10px">
|
||||
<Typography fontWeight="bold">Skip the Warm-up Now!</Typography>
|
||||
<Typography>{`Bridge your ${ghstSymbol} to GHOST Chain and start ${bridgeNumbers} ${"Stake\u00B2"} at:`}</Typography>
|
||||
<Typography>
|
||||
Bridge your {ghstSymbol} to GHOST Chain and start{" "}
|
||||
<Box component="span" sx={{ whiteSpace: "nowrap" }}>{bridgeNumbers()}</Box>{" "}
|
||||
{"Stake\u00B2"} at:
|
||||
</Typography>
|
||||
</Box>
|
||||
|
||||
<Box display="flex" justifyContent="center" flexDirection="column" alignItems="center">
|
||||
<Typography variant="h5">{formatNumber(gatekeepedApy, 2)}% APY</Typography>
|
||||
<Typography variant="h5" display="flex" alignItems="center">
|
||||
{formatNumber(gatekeepedApy, 2)}% APY
|
||||
</Typography>
|
||||
</Box>
|
||||
|
||||
<PrimaryButton
|
||||
disabled={isPending || gatekeeperAddress === EMPTY_ADDRESS}
|
||||
onClick={isExtensionMissing
|
||||
? (refreshNeeded ? refreshPage : getConnect)
|
||||
: goNext
|
||||
}
|
||||
disabled={isPending || !gatekeepersMatch || estimatedAmount.lt(existentialDeposit)}
|
||||
onClick={goNext}
|
||||
fullWidth
|
||||
>
|
||||
{isExtensionMissing
|
||||
? (refreshNeeded ? "Refresh Page" : "Get GHOST Connect")
|
||||
: `Start ${bridgeNumbers} ${"Stake\u00B2"}`}
|
||||
{gatekeepersMatch
|
||||
? estimatedAmount.lt(existentialDeposit) ? "Below Existential Deposit" : `Start ${bridgeNumbers()} ${"Stake\u00B2"}`
|
||||
: isNetworkDataLoading ? "Syncing with Gatekeeper..." : "Gatekeeper Outdated"
|
||||
}
|
||||
</PrimaryButton>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
const BridgeView = ({
|
||||
chainId,
|
||||
receiver,
|
||||
setReceiver,
|
||||
convertedReceiver,
|
||||
setConvertedReceiver,
|
||||
bridgeNumbers,
|
||||
ghstSymbol,
|
||||
estimatedAmount,
|
||||
goNext,
|
||||
incomingFee,
|
||||
networkData,
|
||||
gatekeepersMatch,
|
||||
gatekeeperAddress
|
||||
}) => {
|
||||
const theme = useTheme();
|
||||
const config = useConfig();
|
||||
|
||||
const { account } = useUnstableProvider();
|
||||
const [inputFocused, setInputFocused] = useState(false);
|
||||
|
||||
const blockDelayMetric = useMemo(() => {
|
||||
if (!networkData) return null;
|
||||
const blockSpeed = networkAvgBlockSpeed(chainId);
|
||||
const finalityDelay = networkData.finality_delay;
|
||||
const estimatedMins = (blockSpeed * finalityDelay) / 60n;
|
||||
return { finalityDelay, text: `~${estimatedMins} mins` }
|
||||
}, [chainId, networkData]);
|
||||
|
||||
const chainExplorerUrl = useMemo(() => {
|
||||
const client = config?.getClient();
|
||||
return client?.chain?.blockExplorers?.default?.url;
|
||||
}, [config]);
|
||||
|
||||
return (
|
||||
<>
|
||||
<Typography>
|
||||
Bridge to start earning {bridgeNumbers} {"Stake\u00B2"} on your {ghstSymbol} balance:
|
||||
</Typography>
|
||||
|
||||
<Box display="flex" justifyContent="center">
|
||||
<Typography variant="h5">{formatNumber(estimatedAmount, 5)} {ghstSymbol}</Typography>
|
||||
</Box>
|
||||
|
||||
<Typography>
|
||||
Generate a unique address for per tx with {" "}
|
||||
<Link
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
underline="hover"
|
||||
href={GHOST_CONNECT}
|
||||
color={theme.colors.primary[300]}
|
||||
>
|
||||
GHOST Connect
|
||||
</Link>
|
||||
{" "}for your privacy
|
||||
{account ? (
|
||||
<>
|
||||
, or{" "}
|
||||
<Link
|
||||
component="button"
|
||||
type="button"
|
||||
variant="body1"
|
||||
underline="hover"
|
||||
onClick={() => setReceiver(account ? account.address : "")}
|
||||
sx={{
|
||||
color: theme.colors.primary[300],
|
||||
verticalAlign: "baseline",
|
||||
}}
|
||||
>
|
||||
click here
|
||||
</Link>{" "}
|
||||
to use connected one.
|
||||
</>
|
||||
) : (".")}
|
||||
</Typography>
|
||||
|
||||
<BridgeGhostAddressCard
|
||||
isCard
|
||||
receiver={receiver}
|
||||
setReceiver={setReceiver}
|
||||
/>
|
||||
|
||||
<Box display="flex" justifyContent="center" flexDirection="column" alignItems="center">
|
||||
<Box width="100%" display="flex" flexDirection="row" justifyContent="space-between">
|
||||
<Typography variant="body2">Gatekeeper</Typography>
|
||||
<Link
|
||||
fontSize="12px"
|
||||
lineHeight="15px"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
href={`${chainExplorerUrl}/token/${gatekeeperAddress}`}
|
||||
>
|
||||
<Typography variant="body2">
|
||||
{shorten(gatekeeperAddress, 10, -8)}
|
||||
</Typography>
|
||||
</Link>
|
||||
</Box>
|
||||
<Box width="100%" display="flex" flexDirection="row" justifyContent="space-between">
|
||||
<Typography variant="body2">Bridge Fee</Typography>
|
||||
<Typography variant="body2">{formatNumber(incomingFee, 5)}%</Typography>
|
||||
</Box>
|
||||
<Box width="100%" display="flex" flexDirection="row" justifyContent="space-between">
|
||||
<Typography variant="body2">Est. Time</Typography>
|
||||
{blockDelayMetric
|
||||
? <Typography variant="body2">{blockDelayMetric.text}</Typography>
|
||||
: <Skeleton width="120px" />
|
||||
}
|
||||
</Box>
|
||||
</Box>
|
||||
|
||||
<PrimaryButton
|
||||
onClick={goNext}
|
||||
disabled={!gatekeepersMatch || convertedReceiver === undefined}
|
||||
fullWidth
|
||||
>
|
||||
{gatekeepersMatch ? "Proceed" : "Gatekeeper Outdated"}
|
||||
</PrimaryButton>
|
||||
</>
|
||||
)
|
||||
@ -334,84 +397,45 @@ const ConfirmStep = ({
|
||||
chainId,
|
||||
address,
|
||||
receiver,
|
||||
isPending,
|
||||
setIsPending,
|
||||
convertedReceiver,
|
||||
executableFunction,
|
||||
ghstSymbol,
|
||||
bridgeNumbers,
|
||||
estimatedAmount,
|
||||
bridgingRisk,
|
||||
incomingFee,
|
||||
setActiveTxIndex,
|
||||
closeModal,
|
||||
evmNetwork
|
||||
networkData,
|
||||
gatekeepersMatch,
|
||||
incomingFee
|
||||
}) => {
|
||||
const config = useConfig();
|
||||
const navigate = useNavigate();
|
||||
|
||||
const currentSession = useCurrentIndex();
|
||||
const { getStorageValue, setStorageValue } = useLocalStorage();
|
||||
|
||||
const [blockNumber, setBlockNumber] = useState(0n);
|
||||
const [isPending, setIsPending] = useState(false);
|
||||
const [acknowledgeBridgingRisk, setAcknowledgeBridgingRisk] = useState(false);
|
||||
const [acknowledgeWalletCustody, setAcknowledgeWalletCustody] = useState(false);
|
||||
|
||||
getBlockNumber(config).then(block => setBlockNumber(block));
|
||||
|
||||
const nativeSymbol = useMemo(() => config?.getClient()?.chain?.nativeCurrency?.symbol, [config]);
|
||||
const networkName= useMemo(() => config?.getClient()?.chain?.name.toLowerCase(), [config]);
|
||||
|
||||
const receivedEstimation = useMemo(() => {
|
||||
const decimals = incomingFee._decimals + 2;
|
||||
const afterFee = new DecimalBigNumber(
|
||||
BigInt(Math.pow(10, decimals) - incomingFee._value),
|
||||
decimals
|
||||
incomingFee ? BigInt((100 - incomingFee) * 100) : 0n,
|
||||
4
|
||||
);
|
||||
|
||||
return estimatedAmount.mul(afterFee);
|
||||
}, [incomingFee, estimatedAmount]);
|
||||
|
||||
const execute = useCallback(async () => {
|
||||
setIsPending(true);
|
||||
try {
|
||||
const txHash = await executableFunction()(convertedReceiver);
|
||||
if (txHash) {
|
||||
const expectedSessionIndex = (currentSession ?? 0) + (evmNetwork
|
||||
? Number((evmNetwork.avg_block_speed * evmNetwork.finality_delay) / (1000n * 14400n))
|
||||
: 0);
|
||||
|
||||
const transaction = {
|
||||
receiverAddress: receiver,
|
||||
amount: estimatedAmount._value.toString(),
|
||||
sessionIndex: expectedSessionIndex,
|
||||
transactionHash: txHash,
|
||||
blockNumber: Number(blockNumber),
|
||||
chainId: chainId,
|
||||
bridgeStability: 69, // TODO: avoid stability
|
||||
timestamp: Date.now()
|
||||
}
|
||||
|
||||
const storedTransactions = getStorageValue(chainId, address, "bridge-txs", []);
|
||||
const newStoredTransactions = [transaction, ...storedTransactions];
|
||||
setStorageValue(chainId, address, "bridge-txs", newStoredTransactions);
|
||||
|
||||
setActiveTxIndex(0);
|
||||
navigate(`${networkName}/bridge`);
|
||||
}
|
||||
await executableFunction()(convertedReceiver);
|
||||
} finally {
|
||||
setIsPending(false);
|
||||
closeModal();
|
||||
}
|
||||
}, [
|
||||
executableFunction,
|
||||
convertedReceiver,
|
||||
receiver,
|
||||
networkName,
|
||||
chainId,
|
||||
address,
|
||||
blockNumber,
|
||||
evmNetwork,
|
||||
currentSession,
|
||||
]);
|
||||
}, [executableFunction, convertedReceiver]);
|
||||
|
||||
return (
|
||||
<>
|
||||
@ -433,7 +457,7 @@ const ConfirmStep = ({
|
||||
</Box>
|
||||
</Box>
|
||||
|
||||
<Typography>{`You are bridging to GHOST Chain now to claim ${bridgeNumbers} ${"Stake\u00B2"} rewards.`}</Typography>
|
||||
<Typography>{`You are bridging to GHOST Chain now to claim ${bridgeNumbers()} ${"Stake\u00B2"} rewards.`}</Typography>
|
||||
|
||||
<hr style={{ width: "100%" }} />
|
||||
|
||||
|
||||
348
src/containers/Bridge/BridgeConfirmationModal.jsx
Normal file
348
src/containers/Bridge/BridgeConfirmationModal.jsx
Normal 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>
|
||||
)
|
||||
}
|
||||
86
src/containers/Bridge/BridgeGhostAddress.jsx
Normal file
86
src/containers/Bridge/BridgeGhostAddress.jsx
Normal file
@ -0,0 +1,86 @@
|
||||
import { useState, useEffect } from "react";
|
||||
import { isAddress } from 'viem';
|
||||
import { ss58Decode } from "@polkadot-labs/hdkd-helpers";
|
||||
import { FormControl, OutlinedInput } from "@mui/material";
|
||||
|
||||
import CheckIcon from '@mui/icons-material/CheckCircle';
|
||||
import CancelIcon from '@mui/icons-material/Cancel';
|
||||
|
||||
import SwapCard from "../../components/Swap/SwapCard";
|
||||
import GhostStyledIcon from "../../components/Icon/GhostIcon";
|
||||
|
||||
import { shorten } from "../../helpers";
|
||||
|
||||
export const BridgeGhostAddressCard = ({ receiver, setReceiver, isCard, isEvm = false, readOnly = false }) => {
|
||||
const [inputFocused, setInputFocused] = useState(false);
|
||||
const [innerReceiver, setInnerReceiver] = useState(receiver);
|
||||
|
||||
useEffect(() => {
|
||||
try {
|
||||
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, isEvm]);
|
||||
|
||||
if (isCard) {
|
||||
return (
|
||||
<SwapCard
|
||||
readOnly={readOnly}
|
||||
id={`bridge-token-receiver-card`}
|
||||
inputWidth={"100%"}
|
||||
onBlur={() => setInputFocused(true)}
|
||||
onFocus={() => setInputFocused(false)}
|
||||
onMouseLeave={() => setInputFocused(true)}
|
||||
onMouseEnter={() => setInputFocused(false)}
|
||||
onChange={event => setInnerReceiver(event.currentTarget.value)}
|
||||
placeholder={receiver
|
||||
? shorten(receiver, 15, -10)
|
||||
: isEvm ? "EVM address (0x prefixed)" : "GHOST address (sf prefixed)"
|
||||
}
|
||||
value={receiver ? "" : innerReceiver}
|
||||
inputProps={{ "data-testid": "fromInput" }}
|
||||
endString={receiver
|
||||
? <GhostStyledIcon color="success" viewBox="0 0 25 25" component={CheckIcon} />
|
||||
: inputFocused && !receiver
|
||||
? <GhostStyledIcon color="error" viewBox="0 0 25 25" component={CancelIcon} />
|
||||
: undefined
|
||||
}
|
||||
type="text"
|
||||
maxWidth="100%"
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<FormControl variant="outlined" color="primary" fullWidth>
|
||||
<OutlinedInput
|
||||
readOnly={readOnly}
|
||||
inputProps={{ "data-testid": "custom-destination-input" }}
|
||||
id="custom-destination-input"
|
||||
onBlur={() => setInputFocused(true)}
|
||||
onFocus={() => setInputFocused(false)}
|
||||
onMouseLeave={() => setInputFocused(true)}
|
||||
onMouseEnter={() => setInputFocused(false)}
|
||||
onChange={event => setInnerReceiver(event.currentTarget.value)}
|
||||
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} />
|
||||
: inputFocused && !receiver
|
||||
? <GhostStyledIcon color="error" viewBox="0 0 25 25" component={CancelIcon} />
|
||||
: undefined
|
||||
}
|
||||
/>
|
||||
</FormControl>
|
||||
)
|
||||
}
|
||||
567
src/containers/Bridge/BridgeIn.jsx
Normal file
567
src/containers/Bridge/BridgeIn.jsx
Normal file
@ -0,0 +1,567 @@
|
||||
import { useEffect, useState, useMemo, useCallback } from "react";
|
||||
import { useLocation } from "react-router-dom";
|
||||
import { ss58Decode } from "@polkadot-labs/hdkd-helpers";
|
||||
import { toHex } from "@polkadot-api/utils";
|
||||
import ReactGA from "react-ga4";
|
||||
import useSWR from 'swr';
|
||||
|
||||
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 PageTitle from "../../components/PageTitle/PageTitle";
|
||||
import GhostStyledIcon from "../../components/Icon/GhostIcon";
|
||||
import MetricCollection from "../../components/Metric/MetricCollection";
|
||||
import LinearProgressBar from "../../components/Progress/LinearProgressBar";
|
||||
import SwapCard from "../../components/Swap/SwapCard";
|
||||
import SwapCollection from "../../components/Swap/SwapCollection";
|
||||
import TokenStack from "../../components/TokenStack/TokenStack";
|
||||
import DataRow from "../../components/DataRow/DataRow";
|
||||
import { PrimaryButton } from "../../components/Button";
|
||||
|
||||
import { BridgeInSettingsModal } from "./BridgeSettingsModal";
|
||||
import { BridgeInConfirmationModal } from "./BridgeConfirmationModal";
|
||||
|
||||
import {
|
||||
ghost,
|
||||
useGatekeeperApy,
|
||||
useGatekeeperAddress,
|
||||
useGatekeeperMinimum,
|
||||
} from "../../hooks/staking";
|
||||
|
||||
import { useTokenSymbol, useBalance } from "../../hooks/tokens";
|
||||
import { useUnstableProvider } from "../../hooks/ghost";
|
||||
import { useLocalStorage } from "../../hooks/localstorage";
|
||||
import { prettifySeconds } from "../../helpers/timeUtil";
|
||||
import { DecimalBigNumber } from "../../helpers/DecimalBigNumber";
|
||||
import { formatNumber, formatCurrency } from "../../helpers";
|
||||
import { GATEKEEPER_ADDRESSES } from "../../constants/addresses";
|
||||
import { networkAvgBlockSpeed, bridgeNumbers } from "../../constants";
|
||||
|
||||
const DECIMALS_PREFIX = "bridge-in-decimals";
|
||||
|
||||
const BridgeStatusCard = ({ progressPercent, totalValidators, pendingValidators, tapestryDraft }) => {
|
||||
const theme = useTheme();
|
||||
|
||||
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">
|
||||
{tapestryDraft
|
||||
? <Box display="flex" flexDirection="row" gap="5px">
|
||||
<Typography variant="caption" sx={{ fontWeight: "700" }}>Round 2:</Typography>
|
||||
<Typography variant="caption">Merkle Root Verification</Typography>
|
||||
</Box>
|
||||
: <Box display="flex" flexDirection="row" gap="5px">
|
||||
<Typography variant="caption" sx={{ fontWeight: "700" }}>Round 1:</Typography>
|
||||
<Typography variant="caption">Block Consensus</Typography>
|
||||
</Box>
|
||||
}
|
||||
</Typography>
|
||||
<Typography variant="caption">
|
||||
{tapestryDraft
|
||||
? <Box display="flex" flexDirection="row" gap="5px">
|
||||
<Typography variant="caption" sx={{ fontWeight: "700" }}>Block:</Typography>
|
||||
<Typography variant="caption">{`${formatNumber(tapestryDraft.median)} (${pendingValidators} out of ${totalValidators} validators)`}</Typography>
|
||||
</Box>
|
||||
: <Box display="flex" flexDirection="row" gap="5px">
|
||||
<Typography variant="caption" sx={{ fontWeight: "700" }}>Blocks:</Typography>
|
||||
<Typography variant="caption">{`Pending... (${pendingValidators} out of ${totalValidators} validators)`}</Typography>
|
||||
</Box>
|
||||
}
|
||||
</Typography>
|
||||
</Box>
|
||||
|
||||
<LinearProgressBar
|
||||
variant={typeof progressPercent === "number" ? "determinate" : "indeterminate"}
|
||||
value={progressPercent ? progressPercent : 0}
|
||||
height={6}
|
||||
barColor={theme.colors.feedback.success}
|
||||
/>
|
||||
</Box>
|
||||
);
|
||||
};
|
||||
|
||||
const BridgeIn = ({ chainId, address, config, connect }) => {
|
||||
const location = useLocation();
|
||||
const { useStorageValue, setStorageValue, tryStoreInHistory, CONSTANTS } = useLocalStorage();
|
||||
|
||||
const isSmallScreen = useMediaQuery("(max-width: 650px)");
|
||||
const isSemiSmallScreen = useMediaQuery("(max-width: 480px)");
|
||||
const isVerySmallScreen = useMediaQuery("(max-width: 379px)");
|
||||
|
||||
const { casperApi, client, account } = useUnstableProvider();
|
||||
const { gatekeepedApy } = useGatekeeperApy(chainId);
|
||||
|
||||
const [msSinceLastBlock, setMsSinceLastBlock] = useState(0);
|
||||
const [nextEraIn, setNextEraIn] = useState(null);
|
||||
const [settingsOpen, setSettingsOpen] = useState(false);
|
||||
const [confirmOpen, setConfirmOpen] = useState(false);
|
||||
const [amount, setAmount] = useState("");
|
||||
const [receiver, setReceiver] = useState(account ? account.address : "");
|
||||
const [customReceiver, setCustomReceiver] = useState(account ? account.address : "");
|
||||
|
||||
const { symbol: ghstSymbol } = useTokenSymbol(chainId, "GHST");
|
||||
const { symbol: ftsoSymbol } = useTokenSymbol(chainId, "FTSO");
|
||||
const { balance: ghstBalance, refetch: ghstBalanceRefetch } = useBalance(chainId, "GHST", address);
|
||||
const { gatekeeperAddress } = useGatekeeperAddress(chainId);
|
||||
const { existentialDeposit } = useGatekeeperMinimum(chainId);
|
||||
|
||||
const { data: formatDecimals } = useStorageValue(chainId, address, DECIMALS_PREFIX, "5");
|
||||
|
||||
useEffect(() => {
|
||||
ReactGA.send({ hitType: "pageview", page: location.pathname });
|
||||
}, [location]);
|
||||
|
||||
const { data: chainProperties } = useSWR(
|
||||
client ? ['chainProperties', client] : null,
|
||||
() => client.getChainSpecData(),
|
||||
);
|
||||
|
||||
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: activeEraStart } = useSWR(
|
||||
casperApi ? ['activeEra', casperApi] : null,
|
||||
() => casperApi.query.Staking.ActiveEra.getValue(),
|
||||
{
|
||||
refreshInterval: 12000,
|
||||
revalidateOnFocus: true
|
||||
}
|
||||
);
|
||||
|
||||
const { data: weaverAuthorities } = useSWR(
|
||||
casperApi ? ['weaverAuthorities', casperApi] : null,
|
||||
() => casperApi.query.GhostWeaver.Authorities.getValue(),
|
||||
{
|
||||
revalidateOnFocus: true
|
||||
}
|
||||
);
|
||||
|
||||
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: 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);
|
||||
},
|
||||
{
|
||||
revalidateOnFocus: true
|
||||
}
|
||||
);
|
||||
|
||||
const { data: attestationDelay } = useSWR(
|
||||
casperApi ? ['attestationDelay', casperApi] : null,
|
||||
() => casperApi.constants.GhostWeaver.AttestationDelay(),
|
||||
);
|
||||
|
||||
const { data: weavingDelay } = useSWR(
|
||||
casperApi ? ['weavingDelay', casperApi] : null,
|
||||
() => casperApi.constants.GhostWeaver.WeavingDelay(),
|
||||
);
|
||||
|
||||
const { data: currentBlockNumber } = useSWR(
|
||||
casperApi ? ['currentBlockNumber', casperApi] : null,
|
||||
() => casperApi.query.System.Number.getValue(),
|
||||
{
|
||||
refreshInterval: 12000,
|
||||
revalidateOnFocus: true
|
||||
}
|
||||
);
|
||||
|
||||
const { data: nextConsensusAttempt, error } = useSWR(
|
||||
casperApi ? ['nextConsensusAttempt', casperApi] : null,
|
||||
async () => {
|
||||
const key = BigInt(chainId);
|
||||
const res = await casperApi.query.GhostWeaver.NextConsensusAttemptBlocks.getValue(key);
|
||||
return res;
|
||||
},
|
||||
{
|
||||
refreshInterval: 12000,
|
||||
revalidateOnFocus: true
|
||||
}
|
||||
);
|
||||
|
||||
const { data: networkAttestations } = useSWR(
|
||||
casperApi ? ['networkAttestations', casperApi, chainId] : null,
|
||||
async () => {
|
||||
const key = BigInt(chainId);
|
||||
const res = await casperApi.query.GhostWeaver.NetworkAttestations.getValue(key);
|
||||
return res;
|
||||
},
|
||||
{
|
||||
refreshInterval: 12000,
|
||||
revalidateOnFocus: true
|
||||
}
|
||||
);
|
||||
|
||||
const { data: tapestryDraft } = useSWR(
|
||||
casperApi ? ['tapestryDraft', casperApi, chainId] : null,
|
||||
async () => {
|
||||
const key = BigInt(chainId);
|
||||
const res = await casperApi.query.GhostWeaver.TapestryDrafts.getValue(key);
|
||||
return res;
|
||||
},
|
||||
{
|
||||
refreshInterval: 12000,
|
||||
revalidateOnFocus: true
|
||||
}
|
||||
);
|
||||
|
||||
const { data: tapestryStrand } = useSWR(
|
||||
casperApi ? ['tapestryStrand', casperApi, chainId] : null,
|
||||
async () => {
|
||||
const key = BigInt(chainId);
|
||||
const res = await casperApi.query.GhostWeaver.TapestryStrands.getValue(key);
|
||||
return res;
|
||||
},
|
||||
{
|
||||
refreshInterval: 12000,
|
||||
revalidateOnFocus: true
|
||||
}
|
||||
);
|
||||
|
||||
const tapestryParticipants = useMemo(() => {
|
||||
if (!tapestryStrand) return { element: "", onesCount: 0 };
|
||||
|
||||
let maxOnesCount = 0;
|
||||
let bestElement = null;
|
||||
|
||||
tapestryStrand.forEach(item => {
|
||||
const dataArray = item[1]?.data || [];
|
||||
const totalOnes = dataArray.reduce((sum, num) => {
|
||||
const onesInNumber = num.toString(2).split('1').length - 1;
|
||||
return sum + onesInNumber;
|
||||
}, 0);
|
||||
|
||||
if (totalOnes > maxOnesCount) {
|
||||
maxOnesCount = totalOnes;
|
||||
bestElement = item[0];
|
||||
}
|
||||
});
|
||||
|
||||
return {
|
||||
element: bestElement,
|
||||
onesCount: maxOnesCount
|
||||
};
|
||||
}, [tapestryStrand]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!activeEraStart || !activeEraStart.start) return;
|
||||
|
||||
const calculateTime = () => {
|
||||
const nowMs = Date.now();
|
||||
const diffMs = nowMs - Number(activeEraStart.start);
|
||||
return prettifySeconds(Math.max(0, diffMs / 1000));
|
||||
};
|
||||
|
||||
setNextEraIn(calculateTime());
|
||||
|
||||
const intervalId = setInterval(() => {
|
||||
setNextEraIn(calculateTime());
|
||||
}, 1000);
|
||||
|
||||
return () => clearInterval(intervalId);
|
||||
}, [activeEraStart]);
|
||||
|
||||
const blockDelayMetric = useMemo(() => {
|
||||
if (!networkData) return null;
|
||||
const blockSpeed = networkAvgBlockSpeed(chainId);
|
||||
const finalityDelay = networkData.finality_delay;
|
||||
const estimatedMins = (blockSpeed * finalityDelay) / 60n;
|
||||
return { finalityDelay, text: `~${estimatedMins} mins` }
|
||||
}, [chainId, networkData]);
|
||||
|
||||
const chain = useMemo(() => {
|
||||
const client = config?.getClient();
|
||||
return {
|
||||
symbol: client?.chain?.nativeCurrency?.symbol,
|
||||
name: client?.chain?.name,
|
||||
}
|
||||
}, [config, chainId]);
|
||||
|
||||
const estimatedOutAmount = useMemo(() => {
|
||||
const hundredPercent = 1000000000;
|
||||
const incomingShare = networkData ? networkData.incoming_share : 0;
|
||||
const result = hundredPercent - incomingShare;
|
||||
|
||||
return amount * result / hundredPercent
|
||||
}, [amount, networkData]);
|
||||
|
||||
const gatekeepersMatch = useMemo(() => {
|
||||
if (!networkData) return false;
|
||||
return gatekeeperAddress.toUpperCase() == toHex(networkData.gatekeeper).toUpperCase();
|
||||
}, [gatekeeperAddress, networkData]);
|
||||
|
||||
const preparedAmount = useMemo(() => {
|
||||
return new DecimalBigNumber(amount, ghstBalance._decimals);
|
||||
}, [amount, ghstBalance]);
|
||||
|
||||
const receiverHex = useMemo(() => {
|
||||
const finalReceiver = customReceiver ? customReceiver : receiver;
|
||||
try {
|
||||
const [publicKey, prefix] = ss58Decode(finalReceiver);
|
||||
if (prefix !== 1995 && prefix !== 1996) return undefined;
|
||||
return toHex(publicKey);
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}, [receiver, customReceiver]);
|
||||
|
||||
const actionDisabled = useMemo(() => {
|
||||
if (!networkData) return true;
|
||||
const differentGatekeepers = gatekeeperAddress.toUpperCase() !== toHex(networkData.gatekeeper).toUpperCase();
|
||||
const smallAmount = existentialDeposit.gt(preparedAmount);
|
||||
const insufficientAmount = preparedAmount.gt(ghstBalance);
|
||||
|
||||
return differentGatekeepers || smallAmount || insufficientAmount || !receiverHex
|
||||
}, [networkData, gatekeeperAddress, existentialDeposit, preparedAmount, ghstBalance, receiverHex]);
|
||||
|
||||
const setFormatDecimals = useCallback((value) => {
|
||||
if (Number(value) <= 17) {
|
||||
setStorageValue(chainId, address, DECIMALS_PREFIX, value);
|
||||
}
|
||||
}, [chainId, address]);
|
||||
|
||||
const startGhostBridge = async () => {
|
||||
try {
|
||||
const txHash = await ghost(chainId, address, receiverHex, preparedAmount._value);
|
||||
if (txHash) {
|
||||
tryStoreInHistory(chainId, address, CONSTANTS.bridgeIn.key, txHash, CONSTANTS.bridgeIn.name);
|
||||
}
|
||||
} finally {
|
||||
await ghstBalanceRefetch();
|
||||
setAmount("");
|
||||
}
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
setMsSinceLastBlock(0);
|
||||
|
||||
const startTime = Date.now();
|
||||
const interval = setInterval(() => {
|
||||
setMsSinceLastBlock(Date.now() - startTime);
|
||||
}, 500);
|
||||
|
||||
return () => clearInterval(interval);
|
||||
}, [currentBlockNumber]);
|
||||
|
||||
const progressPercent = useMemo(() => {
|
||||
if (!nextConsensusAttempt || !attestationDelay || !weavingDelay) return null;
|
||||
|
||||
const total = tapestryDraft ? weavingDelay : attestationDelay;
|
||||
const end = tapestryDraft ? tapestryDraft.until : nextConsensusAttempt;
|
||||
|
||||
const remaining = end - currentBlockNumber;
|
||||
const passed = Number(total) - remaining;
|
||||
const progress = passed * 100 / Number(total);
|
||||
|
||||
const virtualBlocksPassed = Math.min(msSinceLastBlock / 12000, 1);
|
||||
const smoothBlocksPassed = passed + virtualBlocksPassed;
|
||||
const smoothProgress = (smoothBlocksPassed * 100) / Number(total);
|
||||
|
||||
return Math.min(Math.max(smoothProgress, 3), 100);
|
||||
}, [currentBlockNumber, tapestryDraft, nextConsensusAttempt, msSinceLastBlock, attestationDelay, weavingDelay]);
|
||||
|
||||
return (
|
||||
<Box minHeight="calc(100vh - 43px)">
|
||||
<PageTitle name="GHOST Bridge-In" subtitle={`${bridgeNumbers()} Bridge-In to ${bridgeNumbers()} Stake\u00B2`} />
|
||||
<Container
|
||||
style={{
|
||||
paddingLeft: isSmallScreen || isVerySmallScreen ? "0" : "3.3rem",
|
||||
paddingRight: isSmallScreen || isVerySmallScreen ? "0" : "3.3rem",
|
||||
}}
|
||||
>
|
||||
<BridgeInConfirmationModal
|
||||
isOpen={confirmOpen}
|
||||
onClose={() => setConfirmOpen(false)}
|
||||
preparedAmount={preparedAmount}
|
||||
estimatedOutAmount={estimatedOutAmount}
|
||||
formatDecimals={formatDecimals}
|
||||
ghstSymbol={ghstSymbol}
|
||||
nativeSymbol={chain.symbol}
|
||||
externalSymbol={chainProperties ? chainProperties.properties.tokenSymbol : "CSPR"}
|
||||
receiver={customReceiver ? customReceiver : receiver}
|
||||
sender={address}
|
||||
startGhostBridge={startGhostBridge}
|
||||
/>
|
||||
<BridgeInSettingsModal
|
||||
isOpen={settingsOpen}
|
||||
onClose={() => setSettingsOpen(false)}
|
||||
decimals={formatDecimals}
|
||||
setDecimals={setFormatDecimals}
|
||||
receiver={customReceiver}
|
||||
setReceiver={setCustomReceiver}
|
||||
/>
|
||||
<Box mt="15px" display="flex" flexDirection="column" justifyContent="space-between" alignItems="center">
|
||||
<Paper
|
||||
fullWidth
|
||||
enableBackground
|
||||
headerContent={
|
||||
<Box display="flex" gap="5px">
|
||||
<Typography variant="h6">Next Era in</Typography>
|
||||
{nextEraIn
|
||||
? <Typography sx={{ fontWeight: "700" }} variant="h6">{nextEraIn}</Typography>
|
||||
: <Skeleton width="120px" />
|
||||
}
|
||||
</Box>
|
||||
}
|
||||
>
|
||||
<MetricCollection>
|
||||
<Metric
|
||||
metric={`${formatNumber(gatekeepedApy, 2)}%`}
|
||||
label={`Stake\u00B2 APY`}
|
||||
tooltip={`Gross annualized ${ftsoSymbol} (4, 4) Stake² yield, funded by GHOST Chain revenue. Includes (3, 3) Stake¹ APY.`}
|
||||
/>
|
||||
|
||||
<Metric
|
||||
metric={`${formatNumber(totalStaked ? totalStaked.toString() : "0", 2)} ${chainProperties ? chainProperties.properties.tokenSymbol : "CSPR"}`}
|
||||
isLoading={!totalStaked}
|
||||
label="Bridge Security Stake"
|
||||
tooltip={`Total ${chainProperties ? chainProperties.properties.tokenSymbol : ""} securing the bridge, including validator, nominator, and pool stakes across the active validator set of ${chainProperties ? chainProperties.name : ""}.`}
|
||||
/>
|
||||
|
||||
<Metric
|
||||
label="Block Delay"
|
||||
tooltip={`Difference between the ${chain.name} block reported by your local RPC and the latest median ${chain.name} block agreed on by the active validator set of ${chainProperties ? chainProperties.name : ""}.`}
|
||||
isLoading={!blockDelayMetric}
|
||||
metric={blockDelayMetric?.text}
|
||||
/>
|
||||
</MetricCollection>
|
||||
|
||||
<BridgeStatusCard
|
||||
progressPercent={progressPercent}
|
||||
tapestryDraft={tapestryDraft}
|
||||
totalValidators={weaverAuthorities ? weaverAuthorities.length : 0}
|
||||
pendingValidators={
|
||||
tapestryDraft
|
||||
? tapestryParticipants.onesCount
|
||||
: networkAttestations ? networkAttestations.filter(v => v !== undefined).length : 0
|
||||
}
|
||||
/>
|
||||
</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-In</Typography>
|
||||
}
|
||||
>
|
||||
<Box maxWidth="390px" display="flex" flexDirection="column" justifyContent="center" gap="3px">
|
||||
<SwapCollection
|
||||
iconNotNeeded
|
||||
UpperSwapCard={
|
||||
<SwapCard
|
||||
id="from"
|
||||
token={
|
||||
<TokenStack
|
||||
chainTokenNames={[chain.symbol]}
|
||||
tokens={[ghstSymbol]}
|
||||
sx={{ fontSize: "25px", height: "30px" }}
|
||||
/>
|
||||
}
|
||||
tokenName={ghstSymbol}
|
||||
info={(!isSemiSmallScreen ? "Balance: " : "") + formatCurrency(ghstBalance.toString(), formatDecimals, ghstSymbol)}
|
||||
endString="Max"
|
||||
value={amount}
|
||||
endStringOnClick={() => setAmount(ghstBalance.toString())}
|
||||
onChange={event => setAmount(event.currentTarget.value)}
|
||||
inputProps={{ "data-testid": "fromInput" }}
|
||||
/>}
|
||||
LowerSwapCard={
|
||||
<SwapCard
|
||||
id="to"
|
||||
token={
|
||||
<TokenStack
|
||||
tokens={[chainProperties ? chainProperties.properties.tokenSymbol : "CSPR"]}
|
||||
sx={{ fontSize: "25px", height: "30px" }}
|
||||
/>
|
||||
}
|
||||
info={
|
||||
(!isSemiSmallScreen ? "Balance: " : "") +
|
||||
formatCurrency(
|
||||
accountBalance.toString(),
|
||||
formatDecimals,
|
||||
chainProperties ? chainProperties.properties.tokenSymbol : "CSPR",
|
||||
)
|
||||
}
|
||||
tokenName={chainProperties ? chainProperties.properties.tokenSymbol : "CSPR"}
|
||||
value={estimatedOutAmount}
|
||||
inputProps={{ "data-testid": "toInput" }}
|
||||
/>
|
||||
}
|
||||
/>
|
||||
|
||||
<DataRow
|
||||
title={<Typography variant="caption">Min Bridge-In</Typography>}
|
||||
tooltip="Minimum amount that could be handled by the bridge to avoid dust balances."
|
||||
balance={
|
||||
<Typography variant="caption">
|
||||
{formatCurrency(existentialDeposit.toString(), formatDecimals, ghstSymbol)}
|
||||
</Typography>
|
||||
}
|
||||
/>
|
||||
|
||||
<PrimaryButton
|
||||
fullWidth
|
||||
disabled={!gatekeepersMatch || actionDisabled}
|
||||
onClick={() => setConfirmOpen(true)}
|
||||
>
|
||||
Bridge-In
|
||||
</PrimaryButton>
|
||||
</Box>
|
||||
</Paper>
|
||||
</Box>
|
||||
</Box>
|
||||
</Container>
|
||||
</Box>
|
||||
)
|
||||
}
|
||||
|
||||
export default BridgeIn;
|
||||
@ -25,6 +25,7 @@ import { formatCurrency } from "../../helpers";
|
||||
import { DecimalBigNumber } from "../../helpers/DecimalBigNumber";
|
||||
import { GATEKEEPER_ADDRESSES } from "../../constants/addresses";
|
||||
import { GHOST_CONNECT } from "../../constants/ecosystem";
|
||||
import { bridgeNumbers } from "../../constants";
|
||||
|
||||
export const BridgeModal = ({
|
||||
providerDetail,
|
||||
@ -52,12 +53,6 @@ export const BridgeModal = ({
|
||||
});
|
||||
};
|
||||
|
||||
const bridgeNumbers = () => {
|
||||
const connectedNetworks = Object.keys(GATEKEEPER_ADDRESSES).length;
|
||||
const number = 1 + connectedNetworks * 3;
|
||||
return `(${number}, ${number})`;
|
||||
};
|
||||
|
||||
return (
|
||||
<Modal
|
||||
data-testid="transaction-details-modal"
|
||||
|
||||
727
src/containers/Bridge/BridgeOut.jsx
Normal file
727
src/containers/Bridge/BridgeOut.jsx
Normal file
@ -0,0 +1,727 @@
|
||||
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 { executePapiSignedTransaction } from "../../hooks/helpers";
|
||||
import { countBitmapOnes, 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
|
||||
? dkgPhaseType === "Finalized" ? 100 : 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: ftsoSymbol } = useTokenSymbol(chainId, "FTSO");
|
||||
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 chain = useMemo(() => {
|
||||
const client = config?.getClient();
|
||||
return {
|
||||
symbol: client?.chain?.nativeCurrency?.symbol,
|
||||
name: client?.chain?.name,
|
||||
}
|
||||
}, [config, chainId]);
|
||||
|
||||
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(
|
||||
casperApi && account?.address ? ['accountBalance', account.address] : null,
|
||||
() => casperApi.query.System.Account.getValue(account.address),
|
||||
{
|
||||
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, error } = useSWR(
|
||||
casperApi ? ['qualificationAuthorities', casperApi] : null,
|
||||
() => casperApi.query.GhostExodus.QualificationAuthorities.getValue({ type: "Secp256k1" }),
|
||||
);
|
||||
|
||||
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: activeDkgAuthorities } = useSWR(
|
||||
casperApi ? ['activeDkgAuthorities', 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 scoreSession = (entry, threshold) => {
|
||||
const sessionId = Number(entry.keyArgs?.[1] ?? 0);
|
||||
const state = entry.value;
|
||||
const status = typeof state.status === 'string' ? state.status : state.status?.type;
|
||||
|
||||
if (status === 'PartialSignatures') {
|
||||
const count = countBitmapOnes(state.partial_signers);
|
||||
return 3000 + (count >= threshold ? 500 : 0) + sessionId * 50 + count;
|
||||
}
|
||||
if (status === 'GroupCommitments') {
|
||||
return 2000 + sessionId * 50 + countBitmapOnes(state.group_committers);
|
||||
}
|
||||
return 1000 + sessionId * 50 + countBitmapOnes(state.nonce_committers);
|
||||
};
|
||||
|
||||
const { data: participants } = useSWR(
|
||||
casperApi && qualificationDkgState && qualificationAuthorities ? ['dkgRoundProgress'] : null,
|
||||
async () => {
|
||||
const dkgIndex = qualificationDkgState.dkg_state.dkg_index;
|
||||
const dkgPhase = qualificationDkgState.dkg_state.dkg_phase.type;
|
||||
const authorities = qualificationDkgState.authorities_indexes;
|
||||
let total = qualificationAuthorities.length;
|
||||
|
||||
let participated = 0;
|
||||
|
||||
switch (dkgPhase) {
|
||||
case 'Round0': {
|
||||
participated = countBitmapOnes(authorities);
|
||||
break;
|
||||
}
|
||||
case 'Round1': {
|
||||
const bitmap = await casperApi.query.GhostExodus.Round1Packages.getValue({ type: "Secp256k1" });
|
||||
participated = countBitmapOnes(bitmap);
|
||||
break;
|
||||
}
|
||||
case 'Round2': {
|
||||
const bitmap = await casperApi.query.GhostExodus.Round2Packages.getValue({ type: "Secp256k1" });
|
||||
participated = countBitmapOnes(bitmap);
|
||||
break;
|
||||
}
|
||||
case 'Round3': {
|
||||
const entries = await casperApi.query.GhostExodus.Complaints.getValue({ type: "Secp256k1" });
|
||||
participated = entries?.length ?? 0;
|
||||
break;
|
||||
}
|
||||
case 'Round4': {
|
||||
const entries = await casperApi.query.GhostExodus.Justifications.getValue({ type: "Secp256k1" });
|
||||
participated = entries?.length ?? 0;
|
||||
break;
|
||||
}
|
||||
case 'Round5': {
|
||||
const consensus = await casperApi.query.GhostExodus.VerifyingKeyConsensus.getValue(
|
||||
{ type: "Secp256k1" },
|
||||
dkgIndex
|
||||
);
|
||||
participated = countBitmapOnes(consensus?.state?.participants);
|
||||
break;
|
||||
}
|
||||
case 'Round6': {
|
||||
const shares = await casperApi.query.GhostExodus.VerifyingSharesParticipants.getValue(
|
||||
{ type: "Secp256k1" },
|
||||
dkgIndex
|
||||
);
|
||||
participated = countBitmapOnes(shares);
|
||||
break;
|
||||
}
|
||||
case 'Round7': {
|
||||
const activeCount = countBitmapOnes(activeDkgAuthorities?.authorities_indexes);
|
||||
const threshold = Math.floor((activeCount * 2) / 3) + 1;
|
||||
|
||||
const rotationContext = qualificationDkgState.rotations?.[0];
|
||||
if (!rotationContext) {
|
||||
total = threshold;
|
||||
participated = threshold;
|
||||
break;
|
||||
}
|
||||
|
||||
const entries = await casperApi.query.Exodus.RoastSessionStates.getEntries(rotationContext);
|
||||
if (!entries || entries.length === 0) {
|
||||
total = threshold;
|
||||
participated = 0;
|
||||
break;
|
||||
}
|
||||
|
||||
const best = entries.reduce((top, curr) =>
|
||||
scoreSession(curr) > scoreSession(top) ? curr : top
|
||||
);
|
||||
const state = best.value;
|
||||
const status = typeof state.status === 'string' ? state.status : state.status?.type;
|
||||
|
||||
if (status === 'PartialSignatures') {
|
||||
total = threshold;
|
||||
participated = countBitmapOnes(state.partial_signers);
|
||||
} else if (status === 'GroupCommitments') {
|
||||
total = Math.ceil(threshold / 2);
|
||||
participated = countBitmapOnes(state.group_committers);
|
||||
} else {
|
||||
total = threshold;
|
||||
participated = countBitmapOnes(state.nonce_committers);
|
||||
}
|
||||
break;
|
||||
}
|
||||
case 'Finalized': {
|
||||
participated = total;
|
||||
break;
|
||||
}
|
||||
default: {
|
||||
participated = 0;
|
||||
}
|
||||
}
|
||||
|
||||
return { total, participated };
|
||||
},
|
||||
{
|
||||
refreshInterval: 12000,
|
||||
revalidateOnFocus: true,
|
||||
keepPreviousData: true,
|
||||
fallbackData: { total: 0, participated: 0 },
|
||||
}
|
||||
);
|
||||
|
||||
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]);
|
||||
|
||||
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 isDkgQualificationPending = useMemo(() => {
|
||||
return qualificationDkgState
|
||||
? qualificationDkgState.dkg_state.dkg_phase.type !== "Finalized"
|
||||
: true
|
||||
}, [qualificationDkgState]);
|
||||
|
||||
const startGhostExodus = async () => {
|
||||
try {
|
||||
const dkgIndex = activeDkgAuthorities?.dkg_state.dkg_index;
|
||||
if (!dkgIndex) throw new Error("unknown dkg index");
|
||||
|
||||
const clampedBounty = Math.min(100, Math.max(0, Number(allocation) || 0));
|
||||
const allocationBounty = Math.round(clampedBounty * 10000000);
|
||||
|
||||
const txArgs = {
|
||||
network_id: BigInt(chainId),
|
||||
amount: BigInt(preparedAmount._value._hex),
|
||||
bounty: allocationBounty,
|
||||
receiver: customReceiver ? customReceiver : receiver,
|
||||
};
|
||||
|
||||
const tx = casperApi.tx.GhostExodus.register_evm_bridge_out_exodus(txArgs);
|
||||
|
||||
const receipt = await executePapiSignedTransaction({
|
||||
tx,
|
||||
signer: account.txCreator,
|
||||
messages: {
|
||||
loadingMsg: "Waiting for wallet signature of bridge-out transaction...",
|
||||
inBlockMsg: "Bridge-out transaction included in block, finalizing...",
|
||||
successMsg: "Bridge-out transaction confirmed and finalized!",
|
||||
errorMsg: "Bridge-out transaction failed.",
|
||||
}
|
||||
});
|
||||
|
||||
const bridgeEvent = receipt?.events.find(
|
||||
ev => ev.type === "GhostExodus" && ev.value.type === "EvmBridgeOutRegistered"
|
||||
);
|
||||
|
||||
if (bridgeEvent) {
|
||||
const exodusSession = Number(bridgeEvent.value.value.exodus_session);
|
||||
|
||||
const value = {
|
||||
txHash: receipt.txHash,
|
||||
blockHash: receipt.blockHash,
|
||||
share: networkData.outgoing_share,
|
||||
dkgIndex,
|
||||
exodusSession,
|
||||
};
|
||||
tryStoreInHistory(chainId, receiver, CONSTANTS.bridgeOut.key, value, CONSTANTS.bridgeOut.name);
|
||||
}
|
||||
} finally {
|
||||
setAmount("");
|
||||
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 ? account.address : ""}
|
||||
startGhostExodus={startGhostExodus}
|
||||
allocation={allocation}
|
||||
nativeSymbol={chain.symbol}
|
||||
/>
|
||||
<BridgeOutSettingsModal
|
||||
isOpen={settingsOpen}
|
||||
onClose={() => setSettingsOpen(false)}
|
||||
decimals={formatDecimals}
|
||||
setDecimals={setFormatDecimals}
|
||||
receiver={customReceiver}
|
||||
setReceiver={setCustomReceiver}
|
||||
allocation={allocation}
|
||||
setAllocation={setAllocation}
|
||||
nativeSymbol={chain.symbol}
|
||||
/>
|
||||
|
||||
<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={`Gross annualized ${ftsoSymbol} ${bridgeNumbers()} Stake² yield, funded by ${chainProperties ? chainProperties.name : ""} revenue. Includes (3, 3) Stake¹ APY.`}
|
||||
/>
|
||||
|
||||
<Metric
|
||||
metric={`${formatNumber(totalStaked ? totalStaked.toString() : "0", 2)} ${chainProperties ? chainProperties.properties.tokenSymbol : "CSPR"}`}
|
||||
isLoading={!totalStaked}
|
||||
label="Bridge Security Stake"
|
||||
tooltip={`Total ${ghstSymbol} securing the bridge, including validator, nominator, and pool stakes across the active validator set of ${chainProperties ? chainProperties.name : ""}.`}
|
||||
/>
|
||||
|
||||
<Metric
|
||||
label="Bridge-Out Queue"
|
||||
tooltip={`Number of ${negativeBridgeNumbers()} Bridge-Out transactions currently queued and scheduled for processing by the active validator set of ${chainProperties ? chainProperties.name : ""}.`}
|
||||
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={[chain.symbol]}
|
||||
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={false || isDkgQualificationPending}
|
||||
onClick={() => setConfirmOpen(true)}
|
||||
>
|
||||
{isDkgQualificationPending ? "DKG Ongoing" : "Bridge-Out"}
|
||||
</PrimaryButton>
|
||||
</Box>
|
||||
</Paper>
|
||||
</Box>
|
||||
</Box>
|
||||
</Container>
|
||||
</Box>
|
||||
)
|
||||
}
|
||||
|
||||
export default BridgeOut;
|
||||
127
src/containers/Bridge/BridgeSettingsModal.jsx
Normal file
127
src/containers/Bridge/BridgeSettingsModal.jsx
Normal file
@ -0,0 +1,127 @@
|
||||
import { useState, useEffect } from "react";
|
||||
import { Box, Typography, FormControl, OutlinedInput, InputLabel } from "@mui/material";
|
||||
import { BridgeGhostAddressCard } from "./BridgeGhostAddress";
|
||||
import Modal from "../../components/Modal/Modal";
|
||||
|
||||
export const BridgeInSettingsModal = ({ isOpen, onClose, decimals, setDecimals, receiver, setReceiver }) => {
|
||||
return (
|
||||
<Modal
|
||||
data-testid="bridge-in-settings-modal"
|
||||
maxWidth="476px"
|
||||
headerContent={<Typography variant="h6">Bridge-In Settings</Typography>}
|
||||
open={isOpen}
|
||||
onClose={onClose}
|
||||
minHeight={"100px"}
|
||||
>
|
||||
<Box>
|
||||
<InputLabel htmlFor="recipient">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="32px">
|
||||
<InputLabel htmlFor="recipient">Destination address</InputLabel>
|
||||
<Box mt="8px">
|
||||
<BridgeGhostAddressCard receiver={receiver} setReceiver={setReceiver} />
|
||||
<Typography mt="8px" variant="body2" color="textSecondary">
|
||||
Custom recipient address of bridged assets
|
||||
</Typography>
|
||||
</Box>
|
||||
</Box>
|
||||
</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">Custom destination address</InputLabel>
|
||||
<Box mt="8px">
|
||||
<BridgeGhostAddressCard isEvm receiver={receiver} setReceiver={setReceiver} />
|
||||
<Typography mt="8px" variant="body2" color="textSecondary">
|
||||
Recipient address of bridged-out assets
|
||||
</Typography>
|
||||
</Box>
|
||||
</Box>
|
||||
</Box>
|
||||
</Modal>
|
||||
)
|
||||
}
|
||||
@ -41,12 +41,17 @@ import PoolContainer from "./PoolContainer";
|
||||
import SwapContainer from "./SwapContainer";
|
||||
import TokenModal from "./TokenModal";
|
||||
|
||||
const DEADLINE_PREFIX = "dex-deadline";
|
||||
const SLIPPAGE_PREFIX = "dex-slippage";
|
||||
const DECIMALS_PREFIX = "dex-decimals";
|
||||
const DESTINATION_PREFIX = "dex-destination";
|
||||
|
||||
const Dex = ({ chainId, address, connect, config }) => {
|
||||
const location = useLocation();
|
||||
const pathname = useParams();
|
||||
|
||||
const theme = useTheme();
|
||||
const { getStorageValue, setStorageValue } = useLocalStorage();
|
||||
const { useStorageValue, setStorageValue, CONSTANTS } = useLocalStorage();
|
||||
|
||||
const isSmallScreen = useMediaQuery("(max-width: 650px)");
|
||||
const isVerySmallScreen = useMediaQuery("(max-width: 379px)");
|
||||
@ -59,12 +64,12 @@ const Dex = ({ chainId, address, connect, config }) => {
|
||||
const [topTokenListOpen, setTopTokenListOpen] = useState(false);
|
||||
const [bottomTokenListOpen, setBottomTokenListOpen] = useState(false);
|
||||
|
||||
const [secondsToWait, setSecondsToWait] = useState(() => getStorageValue(chainId, address, "dex-deadline", "60"));
|
||||
const [slippage, setSlippage] = useState(() => getStorageValue(chainId, address, "dex-slippage", "5"));
|
||||
const [formatDecimals, setFormatDecimals] = useState(() => getStorageValue(chainId, address, "dex-decimals", "5"));
|
||||
const [actualDestinationAddress, setActualDestinationAddress] = useState(() => getStorageValue(chainId, address, "dex-destination", address));
|
||||
const [destinationAddress, setDestinationAddress] = useState(actualDestinationAddress);
|
||||
const { data: secondsToWait } = useStorageValue(chainId, address, DEADLINE_PREFIX, "60");
|
||||
const { data: slippage } = useStorageValue(chainId, address, SLIPPAGE_PREFIX, "5");
|
||||
const { data: formatDecimals } = useStorageValue(chainId, address, DECIMALS_PREFIX, "5");
|
||||
const { data: actualDestinationAddress } = useStorageValue(chainId, address, DESTINATION_PREFIX, address);
|
||||
|
||||
const [destinationAddress, setDestinationAddress] = useState(actualDestinationAddress);
|
||||
const [tokenAddressTop, setTokenAddressTop] = useState(EMPTY_ADDRESS);
|
||||
const [tokenAddressBottom, setTokenAddressBottom] = useState(FTSO_ADDRESSES[chainId]);
|
||||
|
||||
@ -192,23 +197,20 @@ const Dex = ({ chainId, address, connect, config }) => {
|
||||
return dexInfo ? dexInfo.isFork : false;
|
||||
}, [chainId, pathname])
|
||||
|
||||
const setSlippageInner = useCallback((value) => {
|
||||
const setSlippage = useCallback((value) => {
|
||||
const maybeValue = parseFloat(value);
|
||||
if (!maybeValue || parseFloat(value) <= 100) {
|
||||
setSlippage(value);
|
||||
setStorageValue(chainId, address, "dex-slippage", value);
|
||||
setStorageValue(chainId, address, SLIPPAGE_PREFIX, value);
|
||||
}
|
||||
}, [chainId, address]);
|
||||
|
||||
const setSecondsToWaitInner = useCallback((value) => {
|
||||
setSecondsToWait(value);
|
||||
setStorageValue(chainId, address, "dex-deadline", value);
|
||||
const setSecondsToWait = useCallback((value) => {
|
||||
setStorageValue(chainId, address, DEADLINE_PREFIX, value);
|
||||
}, [chainId, address]);
|
||||
|
||||
const setFormatDecimalsInner = useCallback((value) => {
|
||||
const setFormatDecimals = useCallback((value) => {
|
||||
if (Number(value) <= 17) {
|
||||
setFormatDecimals(value);
|
||||
setStorageValue(chainId, address, "dex-decimals", value);
|
||||
setStorageValue(chainId, address, DECIMALS_PREFIX, value);
|
||||
}
|
||||
}, [chainId, address]);
|
||||
|
||||
@ -216,8 +218,7 @@ const Dex = ({ chainId, address, connect, config }) => {
|
||||
const cleanedValue = value.trim();
|
||||
setDestinationAddress(value);
|
||||
if (isAddress(cleanedValue)) {
|
||||
setActualDestinationAddress(value);
|
||||
setStorageValue(chainId, address, "dex-destination", value);
|
||||
setStorageValue(chainId, address, DECIMALS_PREFIX, value);
|
||||
}
|
||||
}, [chainId, address]);
|
||||
|
||||
@ -278,7 +279,7 @@ const Dex = ({ chainId, address, connect, config }) => {
|
||||
type="text"
|
||||
id="slippage-dex"
|
||||
value={slippage}
|
||||
onChange={event => setSlippageInner(event.currentTarget.value)}
|
||||
onChange={event => setSlippage(event.currentTarget.value)}
|
||||
endAdornment="%"
|
||||
/>
|
||||
</FormControl>
|
||||
@ -291,7 +292,7 @@ const Dex = ({ chainId, address, connect, config }) => {
|
||||
</Box>
|
||||
|
||||
<Box mt="32px">
|
||||
<InputLabel htmlFor="recipient">Transaction deadline</InputLabel>
|
||||
<InputLabel htmlFor="dex-deadline">Transaction deadline</InputLabel>
|
||||
<Box mt="8px">
|
||||
<FormControl variant="outlined" color="primary" fullWidth>
|
||||
<OutlinedInput
|
||||
@ -299,7 +300,7 @@ const Dex = ({ chainId, address, connect, config }) => {
|
||||
type="number"
|
||||
id="seconds-to-wait"
|
||||
value={secondsToWait}
|
||||
onChange={event => setSecondsToWaitInner(event.currentTarget.value)}
|
||||
onChange={event => setSecondsToWait(event.currentTarget.value)}
|
||||
endAdornment="seconds"
|
||||
/>
|
||||
</FormControl>
|
||||
@ -312,7 +313,7 @@ const Dex = ({ chainId, address, connect, config }) => {
|
||||
</Box>
|
||||
|
||||
<Box mt="32px">
|
||||
<InputLabel htmlFor="recipient">Decimal representation</InputLabel>
|
||||
<InputLabel htmlFor="dex-decimals">Decimal representation</InputLabel>
|
||||
<Box mt="8px">
|
||||
<FormControl variant="outlined" color="primary" fullWidth>
|
||||
<OutlinedInput
|
||||
@ -320,7 +321,7 @@ const Dex = ({ chainId, address, connect, config }) => {
|
||||
type="number"
|
||||
id="decimals-to-wait"
|
||||
value={formatDecimals}
|
||||
onChange={event => setFormatDecimalsInner(event.currentTarget.value)}
|
||||
onChange={event => setFormatDecimals(event.currentTarget.value)}
|
||||
endAdornment="decimals"
|
||||
/>
|
||||
</FormControl>
|
||||
@ -333,7 +334,7 @@ const Dex = ({ chainId, address, connect, config }) => {
|
||||
</Box>
|
||||
|
||||
<Box mt="32px">
|
||||
<InputLabel htmlFor="recipient">
|
||||
<InputLabel htmlFor="dex-recipient">
|
||||
{`${actualDestinationAddress ? "Custom" : "Default"} destination address`}
|
||||
</InputLabel>
|
||||
<Box mt="8px">
|
||||
|
||||
@ -18,6 +18,7 @@ import {
|
||||
addLiquidity,
|
||||
addLiquidityETH,
|
||||
} from "../../hooks/uniswapv2";
|
||||
import { useLocalStorage } from "../../hooks/localstorage";
|
||||
|
||||
const PoolContainer = ({
|
||||
chainSymbol,
|
||||
@ -37,6 +38,7 @@ const PoolContainer = ({
|
||||
}) => {
|
||||
const theme = useTheme();
|
||||
const isSmallScreen = useMediaQuery("(max-width: 456px)");
|
||||
const { tryStoreInHistory, CONSTANTS } = useLocalStorage();
|
||||
|
||||
const [isPending, setIsPending] = useState(false);
|
||||
const [amountTop, setAmountTop] = useState("");
|
||||
@ -165,7 +167,12 @@ const PoolContainer = ({
|
||||
const addLiquidityInner = async () => {
|
||||
setIsPending(true);
|
||||
|
||||
const deadline = Math.floor(Date.now() / 1000) + secondsToWait;
|
||||
const numericSecondsToWait = parseInt(secondsToWait, 10);
|
||||
const safeSecondsToWait = (!isNaN(numericSecondsToWait) && numericSecondsToWait > 0)
|
||||
? numericSecondsToWait
|
||||
: 0;
|
||||
|
||||
const deadline = Math.floor(Date.now() / 1000) + safeSecondsToWait;
|
||||
const shares = 100000;
|
||||
const one = BigInt(shares * 100);
|
||||
const floatSlippage = slippage === "" ? 0 : parseFloat(slippage);
|
||||
@ -191,12 +198,16 @@ const PoolContainer = ({
|
||||
deadline,
|
||||
}
|
||||
|
||||
let txHash;
|
||||
|
||||
if (topIsNative || bottomIsNative) {
|
||||
await addLiquidityETH(params)
|
||||
txHash = await addLiquidityETH(params)
|
||||
} else {
|
||||
await addLiquidity(params);
|
||||
txHash = await addLiquidity(params);
|
||||
}
|
||||
|
||||
if (txHash) tryStoreInHistory(chainId, address, CONSTANTS.dex.key, txHash, CONSTANTS.dex.add);
|
||||
|
||||
await balanceRefetchTop();
|
||||
await balanceRefetchBottom();
|
||||
await pairAddressRefetch();
|
||||
@ -215,7 +226,7 @@ const PoolContainer = ({
|
||||
}, [pairAddress])
|
||||
|
||||
return (
|
||||
<Box maxWidth="356px" display="flex" flexDirection="column" justifyContent="space-between" height="100%">
|
||||
<Box maxWidth="390px" display="flex" flexDirection="column" justifyContent="space-between" height="100%">
|
||||
<SwapCollection
|
||||
UpperSwapCard={
|
||||
<SwapCard
|
||||
@ -256,7 +267,7 @@ const PoolContainer = ({
|
||||
justifyContent="space-between"
|
||||
alignItems="center"
|
||||
gap="0px"
|
||||
maxWidth="356px"
|
||||
maxWidth="390px"
|
||||
style={{ fontSize: "12px", color: theme.colors.gray[40] }}
|
||||
>
|
||||
<Box width="100%" display="flex" justifyContent="space-between">
|
||||
|
||||
@ -21,6 +21,7 @@ import {
|
||||
swapExactETHForTokens,
|
||||
swapExactTokensForETH,
|
||||
} from "../../hooks/uniswapv2";
|
||||
import { useLocalStorage } from "../../hooks/localstorage";
|
||||
|
||||
import { EMPTY_ADDRESS } from "../../constants/addresses";
|
||||
|
||||
@ -45,6 +46,7 @@ const SwapContainer = ({
|
||||
}) => {
|
||||
const theme = useTheme();
|
||||
const isSmallScreen = useMediaQuery("(max-width: 456px)");
|
||||
const { tryStoreInHistory, CONSTANTS } = useLocalStorage();
|
||||
|
||||
const [isPending, setIsPending] = useState(false);
|
||||
const [amountBottom, setAmountBottom] = useState("");
|
||||
@ -161,7 +163,12 @@ const SwapContainer = ({
|
||||
const swapTokens = async () => {
|
||||
setIsPending(true);
|
||||
|
||||
const deadline = Math.floor(Date.now() / 1000) + secondsToWait;
|
||||
const numericSecondsToWait = parseInt(secondsToWait, 10);
|
||||
const safeSecondsToWait = (!isNaN(numericSecondsToWait) && numericSecondsToWait > 0)
|
||||
? numericSecondsToWait
|
||||
: 0;
|
||||
|
||||
const deadline = Math.floor(Date.now() / 1000) + safeSecondsToWait;
|
||||
const shares = 100000;
|
||||
const one = BigInt(shares * 100);
|
||||
const floatSlippage = slippage === "" ? 0 : parseFloat(slippage);
|
||||
@ -173,10 +180,12 @@ const SwapContainer = ({
|
||||
const amountBDesired = BigInt(Math.round(parseFloat(amountBottom) * Math.pow(10, balanceBottom._decimals)));
|
||||
const amountBMin = amountBDesired * bigIntSlippage / one;
|
||||
|
||||
let txHash;
|
||||
|
||||
if (isWrapping) {
|
||||
await depositNative(chainId, address, amountADesired);
|
||||
txHash = await depositNative(chainId, address, amountADesired);
|
||||
} else if (isUnwrapping) {
|
||||
await withdrawWeth(chainId, address, amountADesired);
|
||||
txHash = await withdrawWeth(chainId, address, amountADesired);
|
||||
} else {
|
||||
const params = {
|
||||
chainId,
|
||||
@ -190,14 +199,16 @@ const SwapContainer = ({
|
||||
};
|
||||
|
||||
if (topIsNative) {
|
||||
await swapExactETHForTokens(params)
|
||||
txHash = await swapExactETHForTokens(params)
|
||||
} else if (bottomIsNative) {
|
||||
await swapExactTokensForETH(params)
|
||||
txHash = await swapExactTokensForETH(params)
|
||||
} else {
|
||||
await swapExactTokensForTokens(params);
|
||||
txHash = await swapExactTokensForTokens(params);
|
||||
}
|
||||
}
|
||||
|
||||
if (txHash) tryStoreInHistory(chainId, address, CONSTANTS.dex.key, txHash, CONSTANTS.dex.swap);
|
||||
|
||||
await balanceRefetchTop();
|
||||
await balanceRefetchBottom();
|
||||
await pairReservesRefetch();
|
||||
@ -207,11 +218,11 @@ const SwapContainer = ({
|
||||
}
|
||||
|
||||
return (
|
||||
<Box maxWidth="356px" display="flex" flexDirection="column" justifyContent="space-between" height="100%">
|
||||
<Box maxWidth="390px" display="flex" flexDirection="column" justifyContent="space-between" height="100%">
|
||||
<SwapCollection
|
||||
UpperSwapCard={
|
||||
<SwapCard
|
||||
maxWidth="356px"
|
||||
maxWidth="390px"
|
||||
id="from"
|
||||
token={tokenNameTop}
|
||||
chainTokenName={tokenNameTop !== chainSymbol && chainSymbol}
|
||||
@ -230,7 +241,7 @@ const SwapContainer = ({
|
||||
}
|
||||
LowerSwapCard={
|
||||
<SwapCard
|
||||
maxWidth="356px"
|
||||
maxWidth="390px"
|
||||
id="to"
|
||||
token={tokenNameBottom}
|
||||
chainTokenName={tokenNameBottom !== chainSymbol && chainSymbol}
|
||||
@ -252,7 +263,7 @@ const SwapContainer = ({
|
||||
justifyContent="space-between"
|
||||
alignItems="center"
|
||||
gap="0px"
|
||||
maxWidth="356px"
|
||||
maxWidth="390px"
|
||||
style={{ fontSize: "12px", color: theme.colors.gray[40] }}
|
||||
>
|
||||
<Box width="100%" display="flex" justifyContent="space-between">
|
||||
|
||||
394
src/containers/Exodus/Exodus.jsx
Normal file
394
src/containers/Exodus/Exodus.jsx
Normal file
@ -0,0 +1,394 @@
|
||||
import useSWR from "swr";
|
||||
import { useMemo, useState, useCallback, useEffect } from "react";
|
||||
import { getGasPrice } from "@wagmi/core";
|
||||
import { keccak256, hexToBytes, getAddress, toHex } from 'viem';
|
||||
|
||||
import {
|
||||
Box,
|
||||
Divider,
|
||||
CircularProgress,
|
||||
Container,
|
||||
Typography,
|
||||
Skeleton,
|
||||
TableContainer,
|
||||
TableCell,
|
||||
Table,
|
||||
TableHead,
|
||||
TableRow,
|
||||
TableBody,
|
||||
useMediaQuery,
|
||||
useTheme,
|
||||
} from "@mui/material";
|
||||
|
||||
import ArrowBackIosNewIcon from '@mui/icons-material/ArrowBackIosNew';
|
||||
import ArrowForwardIosIcon from '@mui/icons-material/ArrowForwardIos';
|
||||
|
||||
import Paper from "../../components/Paper/Paper";
|
||||
import Metric from "../../components/Metric/Metric";
|
||||
import { Tab, Tabs } from "../../components/Tabs/Tabs";
|
||||
import PageTitle from "../../components/PageTitle/PageTitle";
|
||||
import GhostStyledIcon from "../../components/Icon/GhostIcon";
|
||||
import MetricCollection from "../../components/Metric/MetricCollection";
|
||||
import { PrimaryButton } from "../../components/Button";
|
||||
|
||||
import { useCapturedPriceSnapshots } from "../../hooks/treasury";
|
||||
import { useCurrentGasPrice, useIsTransactionExecuted } from "../../hooks/staking";
|
||||
import { useFtsoPrice, useReservePrice } from "../../hooks/prices";
|
||||
import { useTokenSymbol } from "../../hooks/tokens";
|
||||
import { useUniswapV2Pair } from "../../hooks/uniswapv2";
|
||||
import { useUnstableProvider } from "../../hooks/ghost";
|
||||
import { getTokenAddress, getTokenDecimals } from "../../hooks/helpers";
|
||||
|
||||
import { formatCurrency, formatNumber, shorten } from "../../helpers";
|
||||
import { DecimalBigNumber } from "../../helpers/DecimalBigNumber";
|
||||
import { UNISWAP_V2_FACTORY } from "../../constants/addresses";
|
||||
|
||||
import { ExodusVerifyModal } from "./ExodusModal";
|
||||
import ExodusStatusCard from "./ExodusStatusCard";
|
||||
import ExodusList from "./ExodusList";
|
||||
|
||||
export const KEY_ROTATION = "Key Rotation";
|
||||
export const BRIDGE_OUT = "Bridge-Out";
|
||||
|
||||
const GAS_USED = {
|
||||
[KEY_ROTATION]: 166000n + 21000n + 5969n + 67585n,
|
||||
[BRIDGE_OUT]: 300000n,
|
||||
}
|
||||
|
||||
const Exodus = ({ chainId, address, config }) => {
|
||||
const theme = useTheme();
|
||||
|
||||
const isSmallScreen = useMediaQuery("(max-width: 650px)");
|
||||
const isSemiSmallScreen = useMediaQuery("(max-width: 850px)");
|
||||
const isVerySmallScreen = useMediaQuery("(max-width: 379px)");
|
||||
|
||||
const [gasPrice, setGasPrice] = useState(0n);
|
||||
const [dkgHistory, setDkgHistory] = useState([]);
|
||||
const [searchOpen, setSearchOpen] = useState(false);
|
||||
const [verifiedItem, setVerifiedItem] = useState(null);
|
||||
|
||||
useEffect(() => {
|
||||
let isMounted = true;
|
||||
|
||||
const fetchBlock = async () => {
|
||||
try {
|
||||
const evmGasPrice = await getGasPrice(config, { chainId });
|
||||
if (isMounted) setGasPrice(evmGasPrice);
|
||||
} catch (err) {
|
||||
console.error('Error fetching EVM gas price:', err);
|
||||
}
|
||||
};
|
||||
|
||||
fetchBlock();
|
||||
const intervalId = setInterval(fetchBlock, 5000);
|
||||
|
||||
return () => {
|
||||
isMounted = false;
|
||||
clearInterval(intervalId);
|
||||
};
|
||||
}, [chainId, config]);
|
||||
|
||||
const { casperApi, client } = useUnstableProvider();
|
||||
|
||||
const nativeMetadata = useMemo(() => {
|
||||
const client = config?.getClient();
|
||||
return {
|
||||
name: client?.chain.name,
|
||||
url: client?.chain?.blockExplorers?.default?.url,
|
||||
symbol: client?.chain?.nativeCurrency?.symbol,
|
||||
decimals: client?.chain?.nativeCurrency?.decimals,
|
||||
}
|
||||
}, [config, chainId]);
|
||||
|
||||
const ftsoPrice = useFtsoPrice(chainId);
|
||||
const reservePrice = useReservePrice(chainId);
|
||||
const { symbol: ftsoSymbol } = useTokenSymbol(chainId, "FTSO");
|
||||
const { currentGasPrice, maxGasPrice } = useCurrentGasPrice(chainId);
|
||||
|
||||
const { pairAddress } = useUniswapV2Pair(
|
||||
chainId,
|
||||
UNISWAP_V2_FACTORY[chainId],
|
||||
getTokenAddress(chainId, "WETH"),
|
||||
getTokenAddress(chainId, "FTSO")
|
||||
);
|
||||
|
||||
const { capturedPriceSnapshots } = useCapturedPriceSnapshots(chainId, pairAddress);
|
||||
|
||||
const currentTwapPrice = useCallback((gasUsed) => {
|
||||
const value = ((capturedPriceSnapshots ? capturedPriceSnapshots._value : 0n) * gasUsed) >> 112n;
|
||||
return (new DecimalBigNumber(value, getTokenDecimals("FTSO")));
|
||||
}, [capturedPriceSnapshots]);
|
||||
|
||||
const executionDiscount = useMemo(() => {
|
||||
const oneNative = 10n ** BigInt(nativeMetadata.decimals);
|
||||
const zero = new DecimalBigNumber(0n, 0);
|
||||
const oneHundred = new DecimalBigNumber(100n, 0);
|
||||
const actualGasPerUnit = new DecimalBigNumber(gasPrice ? gasPrice * oneNative : 0n, 18);
|
||||
|
||||
const currentGasPriceCost = currentTwapPrice(currentGasPrice._value * oneNative).mul(ftsoPrice);
|
||||
const actualGasPerUnitCost = actualGasPerUnit.mul(reservePrice);
|
||||
|
||||
if (currentGasPriceCost.eq(zero)) return zero;
|
||||
|
||||
return currentGasPriceCost
|
||||
.sub(actualGasPerUnitCost)
|
||||
.mul(oneHundred.add(zero))
|
||||
.div(currentGasPriceCost);
|
||||
}, [currentTwapPrice, reservePrice, ftsoPrice, nativeMetadata, gasPrice, currentGasPrice]);
|
||||
|
||||
const { data: activeDkgAuthorities, isLoading: activeDkgAuthoritiesLoading } = useSWR(
|
||||
casperApi ? ['activeDkgAuthorities', casperApi] : null,
|
||||
() => casperApi.query.GhostExodus.ActiveDkgAuthorities.getValue({ type: "Secp256k1" }),
|
||||
{
|
||||
revalidateOnFocus: true
|
||||
}
|
||||
);
|
||||
|
||||
const currentDkgIndex = useMemo(() => {
|
||||
if (!activeDkgAuthorities) return null;
|
||||
return dkgHistory.length > 0
|
||||
? dkgHistory[dkgHistory.length - 1].dkgIndex
|
||||
: activeDkgAuthorities.dkg_index;
|
||||
}, [dkgHistory, activeDkgAuthorities]);
|
||||
|
||||
const { data: signedExodusRotations, isLoading: signedExodusRotationsLoading, } = useSWR(
|
||||
casperApi && currentDkgIndex ? ['signedExodusRotations', casperApi, currentDkgIndex] : null,
|
||||
async ([_, api, index]) => {
|
||||
const startIndex = Number(index) - 1;
|
||||
if (startIndex < 0) return null;
|
||||
|
||||
for (let idx = startIndex; idx >= 0; idx--) {
|
||||
const entry = await casperApi.query.GhostExodus.ExodusSignedRotations.getValue(
|
||||
idx,
|
||||
{ type: 'Evm', value: undefined }
|
||||
);
|
||||
|
||||
if (entry) {
|
||||
const [exodusContext, signedMessage] = entry;
|
||||
|
||||
if (chainId != null && exodusContext.network_id !== BigInt(chainId)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
return {
|
||||
type: KEY_ROTATION,
|
||||
gasUsed: GAS_USED[KEY_ROTATION],
|
||||
exodusContext: entry.at(0),
|
||||
signedMessage: entry.at(1),
|
||||
dkgIndex: idx,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
},
|
||||
{ revalidateOnFocus: true }
|
||||
);
|
||||
|
||||
const currentDkgSession = useMemo(() => {
|
||||
if (!activeDkgAuthorities) return null;
|
||||
return dkgHistory.length > 0
|
||||
? dkgHistory[dkgHistory.length - 1].session
|
||||
: signedExodusRotations?.exodusContext.session;
|
||||
}, [dkgHistory, activeDkgAuthorities]);
|
||||
|
||||
const {
|
||||
isTransactionExecuted: currentDkgVerified,
|
||||
isTransactionExecutedLoading: currentDkgVerifiedLoading,
|
||||
refetchTransactionExecuted: currentDkgVerifiedMutate,
|
||||
} = useIsTransactionExecuted(
|
||||
Number(signedExodusRotations
|
||||
? signedExodusRotations.exodusContext.network_id
|
||||
: chainId
|
||||
),
|
||||
currentDkgSession,
|
||||
);
|
||||
|
||||
const {
|
||||
isTransactionExecuted: previousDkgVerified,
|
||||
isTransactionExecutedLoading: previousDkgVerifiedLoading
|
||||
} = useIsTransactionExecuted(
|
||||
Number(signedExodusRotations?.exodusContext.network_id),
|
||||
signedExodusRotations?.exodusContext.session
|
||||
);
|
||||
|
||||
const { data: signedBridges, isLoading: signedBridgesLoading } = useSWR(
|
||||
casperApi && currentDkgIndex ? ['signedBridges', currentDkgIndex] : null,
|
||||
async ([_, idx]) => {
|
||||
const entires = await casperApi.query.GhostExodus.ExodusSignedBridges.getEntries(idx);
|
||||
return entires
|
||||
?.filter((e) => e.keyArgs.at(1).network_id === BigInt(chainId))
|
||||
.map((e) => ({
|
||||
type: BRIDGE_OUT,
|
||||
gasUsed: GAS_USED[BRIDGE_OUT],
|
||||
dkgIndex: e.keyArgs[0],
|
||||
exodusContext: e.keyArgs[1]
|
||||
}));
|
||||
},
|
||||
{ revalidateOnFocus: true }
|
||||
);
|
||||
|
||||
return (
|
||||
<Box minHeight="calc(100vh - 43px)">
|
||||
<PageTitle name="Exodus" subtitle="(1, 1) Verify Exodus for a treasury-backed reward" />
|
||||
<Container
|
||||
style={{
|
||||
paddingLeft: isSmallScreen || isVerySmallScreen ? "0" : "3.3rem",
|
||||
paddingRight: isSmallScreen || isVerySmallScreen ? "0" : "3.3rem",
|
||||
}}
|
||||
>
|
||||
<ExodusVerifyModal
|
||||
address={address}
|
||||
isOpen={!!verifiedItem}
|
||||
casperApi={casperApi}
|
||||
item={verifiedItem}
|
||||
nativeMetadata={nativeMetadata}
|
||||
ftsoSymbol={ftsoSymbol}
|
||||
gasPrice={gasPrice}
|
||||
currentTwapPrice={currentTwapPrice}
|
||||
onClose={() => setVerifiedItem(null)}
|
||||
gasUsed={GAS_USED[verifiedItem?.type]}
|
||||
/>
|
||||
|
||||
<Box mt="15px" display="flex" flexDirection="column" justifyContent="space-between" alignItems="center">
|
||||
<Paper
|
||||
fullWidth
|
||||
enableBackground
|
||||
headerContent={<Typography pr="5px" variant="h6">Exodus Metrics</Typography>}
|
||||
>
|
||||
<MetricCollection>
|
||||
<Metric
|
||||
metric={formatCurrency(currentTwapPrice(10n ** BigInt(nativeMetadata.decimals)).mul(ftsoPrice), 2)}
|
||||
label="Exodus Price"
|
||||
tooltip={`Current discounted price at which ${ftsoSymbol} can be acquired directly from the protocol on ${nativeMetadata.name} for verifying (1, 1) Exodus transactions.`}
|
||||
/>
|
||||
|
||||
<Metric
|
||||
metric={formatCurrency(ftsoPrice, 2)}
|
||||
label={`${ftsoSymbol} Price`}
|
||||
tooltip={`Weighted price of 1 ${ftsoSymbol} across DEXs on ${nativeMetadata.name}, excluding prices from other EVMs.`}
|
||||
/>
|
||||
|
||||
<Metric
|
||||
metric={
|
||||
<Typography variant="h5" fontWeight="bold" sx={{
|
||||
color: Number(executionDiscount) > 0
|
||||
? theme.colors.feedback.success
|
||||
: theme.colors.feedback.error
|
||||
}}>
|
||||
{formatNumber(executionDiscount, 2)}%
|
||||
</Typography>
|
||||
}
|
||||
label="Exodus Discount"
|
||||
tooltip={`Discount rate at which the protocol offers ${ftsoSymbol} in exchange for verifying (1, 1) Exodus transactions. The discount dynamically increases through on-chain Dutch Auction mechanics.`}
|
||||
/>
|
||||
</MetricCollection>
|
||||
|
||||
<ExodusStatusCard
|
||||
executionDiscount={executionDiscount}
|
||||
currentGasPrice={currentGasPrice}
|
||||
maxGasPrice={maxGasPrice}
|
||||
/>
|
||||
</Paper>
|
||||
|
||||
<Paper
|
||||
fullWidth
|
||||
enableBackground
|
||||
topRight={
|
||||
<GhostStyledIcon
|
||||
component={ArrowForwardIosIcon}
|
||||
viewBox="0 0 23 23"
|
||||
style={dkgHistory.length > 0
|
||||
? { cursor: "pointer" }
|
||||
: { opacity: "50%" }
|
||||
}
|
||||
onClick={() => {
|
||||
if (dkgHistory.length === 0) return;
|
||||
setDkgHistory((prev) => prev.slice(0, -1));
|
||||
}}
|
||||
/>
|
||||
}
|
||||
topLeft={
|
||||
<GhostStyledIcon
|
||||
component={ArrowBackIosNewIcon}
|
||||
viewBox="0 0 23 23"
|
||||
style={signedExodusRotations ? { cursor: "pointer" } : { opacity: "50%" }}
|
||||
onClick={() => {
|
||||
if (!signedExodusRotations) return;
|
||||
const entry = {
|
||||
dkgIndex: signedExodusRotations.dkgIndex,
|
||||
session: signedExodusRotations.exodusContext.session,
|
||||
}
|
||||
setDkgHistory((prev) => [...prev, entry]);
|
||||
}}
|
||||
/>
|
||||
}
|
||||
headerContent={
|
||||
<Box
|
||||
width="100%"
|
||||
display="flex"
|
||||
flexDirection="column"
|
||||
justifyContent="space-between"
|
||||
alignItems="center"
|
||||
gap="15px"
|
||||
>
|
||||
<Box display="flex" gap="8px">
|
||||
<Typography variant="h2">Ghost Exodus</Typography>
|
||||
{currentDkgIndex
|
||||
? <Typography variant="h2">#{formatNumber(currentDkgIndex)}</Typography>
|
||||
: <Skeleton width="120px" />
|
||||
}
|
||||
</Box>
|
||||
<Box width="100%" maxWidth="350px">
|
||||
<PrimaryButton
|
||||
fullWidth
|
||||
disabled={
|
||||
currentDkgVerified ||
|
||||
!currentDkgIndex ||
|
||||
!currentDkgSession ||
|
||||
!previousDkgVerified ||
|
||||
!signedExodusRotations ||
|
||||
signedExodusRotationsLoading ||
|
||||
currentDkgVerifiedLoading
|
||||
}
|
||||
onClick={() => {
|
||||
setVerifiedItem({
|
||||
type: KEY_ROTATION,
|
||||
gasUsed: GAS_USED[KEY_ROTATION],
|
||||
dkgIndex: currentDkgIndex,
|
||||
mutate: currentDkgVerifiedMutate,
|
||||
exodusContext: {
|
||||
session: currentDkgSession,
|
||||
network_id: signedExodusRotations
|
||||
? signedExodusRotations.exodusContext.network_id
|
||||
: BigInt(chainId),
|
||||
},
|
||||
});
|
||||
}}
|
||||
>
|
||||
{currentDkgVerified
|
||||
? "DKG Already Verified"
|
||||
: previousDkgVerified ? "Verify DKG" : "Previous Verification Missed"
|
||||
}
|
||||
</PrimaryButton>
|
||||
</Box>
|
||||
</Box>}
|
||||
>
|
||||
<ExodusList
|
||||
disabled={!currentDkgVerified}
|
||||
ftsoSymbol={ftsoSymbol}
|
||||
gasPrice={gasPrice}
|
||||
setVerifiedItem={setVerifiedItem}
|
||||
nativeMetadata={nativeMetadata}
|
||||
currentTwapPrice={currentTwapPrice}
|
||||
signedMessages={signedBridges}
|
||||
isLoading={signedBridgesLoading || activeDkgAuthoritiesLoading}
|
||||
/>
|
||||
</Paper>
|
||||
</Box>
|
||||
</Container>
|
||||
</Box>
|
||||
)
|
||||
}
|
||||
|
||||
export default Exodus;
|
||||
273
src/containers/Exodus/ExodusList.jsx
Normal file
273
src/containers/Exodus/ExodusList.jsx
Normal file
@ -0,0 +1,273 @@
|
||||
import { useMemo } from "react";
|
||||
import {
|
||||
Box,
|
||||
Link,
|
||||
CircularProgress,
|
||||
Container,
|
||||
Typography,
|
||||
TableContainer,
|
||||
TableCell,
|
||||
Table,
|
||||
TableHead,
|
||||
TableRow,
|
||||
TableBody,
|
||||
useMediaQuery,
|
||||
useTheme,
|
||||
} from "@mui/material";
|
||||
|
||||
import Chip from "../../components/Chip/Chip";
|
||||
import { TertiaryButton } from "../../components/Button";
|
||||
import TokenStack from "../../components/TokenStack/TokenStack";
|
||||
|
||||
import { useIsTransactionExecuted } from "../../hooks/staking";
|
||||
|
||||
import { formatCurrency } from "../../helpers";
|
||||
import { DecimalBigNumber } from "../../helpers/DecimalBigNumber";
|
||||
|
||||
const ExodusItem = ({
|
||||
item,
|
||||
gasPrice,
|
||||
ftsoSymbol,
|
||||
disabled,
|
||||
isLoading,
|
||||
nativeMetadata,
|
||||
setVerifiedItem,
|
||||
isSmallScreen,
|
||||
currentTwapPrice
|
||||
}) => {
|
||||
const theme = useTheme();
|
||||
const isVerySmallScreen = useMediaQuery("(max-width: 450px)");
|
||||
|
||||
const {
|
||||
isTransactionExecuted,
|
||||
isTransactionExecutedLoading,
|
||||
refetchTransactionExecuted
|
||||
} = useIsTransactionExecuted(Number(item.exodusContext.network_id), Number(item.exodusContext.session));
|
||||
|
||||
const chipStatus = useMemo(() => {
|
||||
const width = isVerySmallScreen ? "21px" : "100px";
|
||||
|
||||
if (isTransactionExecuted && !isTransactionExecutedLoading) {
|
||||
return <Chip
|
||||
sx={{ width: width }}
|
||||
template={"gray"}
|
||||
label={isVerySmallScreen ? "" : isTransactionExecutedLoading ? "Checking..." : "Executed"}
|
||||
/>
|
||||
}
|
||||
|
||||
return <Chip sx={{ width: width }} label={isVerySmallScreen ? "" : "Ready"} template={"success"} />
|
||||
}, [isTransactionExecutedLoading, isTransactionExecuted]);
|
||||
|
||||
if (isSmallScreen || isVerySmallScreen) {
|
||||
return (
|
||||
<>
|
||||
<Box display="flex" flexDirection="column" gap="10px">
|
||||
<Box
|
||||
display="flex"
|
||||
alignItems="center"
|
||||
justifyContent="space-between"
|
||||
flexDirection={isVerySmallScreen ? "row" : "row"}
|
||||
>
|
||||
<Box display="flex" gap="20px" p="10px 0">
|
||||
<TokenStack chainTokenNames={[nativeMetadata.symbol]} tokens={[ftsoSymbol]} />
|
||||
<Box display="flex" flexDirection="column">
|
||||
<Typography>{item.type}</Typography>
|
||||
<Link
|
||||
href={`${nativeMetadata.url}`}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
>
|
||||
<Typography>{"Something here"}</Typography>
|
||||
</Link>
|
||||
</Box>
|
||||
</Box>
|
||||
|
||||
<Box display="flex" flexDirection="column" alignItems="flex-end">
|
||||
{chipStatus}
|
||||
</Box>
|
||||
</Box>
|
||||
|
||||
<Box width="100%" display="flex" flexDirection="row" justifyContent="space-between">
|
||||
<Box display="flex" flexDirection="column">
|
||||
<Typography>{nativeMetadata.symbol} Cost</Typography>
|
||||
<Typography>{
|
||||
formatCurrency(
|
||||
new DecimalBigNumber(gasPrice * item.gasUsed, 18),
|
||||
5,
|
||||
nativeMetadata.symbol
|
||||
)
|
||||
}</Typography>
|
||||
</Box>
|
||||
|
||||
<Box display="flex" flexDirection="column">
|
||||
<Typography>Reward</Typography>
|
||||
<Typography>{
|
||||
formatCurrency(
|
||||
currentTwapPrice(gasPrice * item.gasUsed).toString(),
|
||||
5,
|
||||
ftsoSymbol
|
||||
)
|
||||
}</Typography>
|
||||
</Box>
|
||||
</Box>
|
||||
|
||||
<Box display="flex" flexDirection="row" gap="20px">
|
||||
<TertiaryButton
|
||||
fullWidth
|
||||
disabled={disabled || isLoading || isTransactionExecuted || isTransactionExecutedLoading}
|
||||
onClick={() => setVerifiedItem({
|
||||
exodusContext: item.exodusContext,
|
||||
dkgIndex: item.dkgIndex,
|
||||
type: item.type,
|
||||
mutate: refetchTransactionExecuted,
|
||||
})}
|
||||
>
|
||||
{isTransactionExecuted ? "Verified" : "Verify"}
|
||||
</TertiaryButton>
|
||||
</Box>
|
||||
</Box>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<TableRow>
|
||||
<TableCell sx={{ padding: "10px 0" }}>
|
||||
<Box display="flex" alignItems="center">
|
||||
<TokenStack chainTokenNames={[nativeMetadata.symbol]} tokens={[ftsoSymbol]} />
|
||||
<Box ml="10px" display="flex" flexDirection="column" alignItems="flex-start">
|
||||
<Typography>{item.type}</Typography>
|
||||
<Link
|
||||
href={`${nativeMetadata.url}`}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
>
|
||||
<Typography>{"Something here"}</Typography>
|
||||
</Link>
|
||||
</Box>
|
||||
</Box>
|
||||
</TableCell>
|
||||
|
||||
<TableCell align="center" sx={{ padding: "10px 0" }}>
|
||||
{chipStatus}
|
||||
</TableCell>
|
||||
|
||||
<TableCell align="center" sx={{ padding: "10px 0" }}>
|
||||
{formatCurrency(
|
||||
new DecimalBigNumber(gasPrice * item.gasUsed, 18),
|
||||
5,
|
||||
nativeMetadata.symbol
|
||||
)}
|
||||
</TableCell>
|
||||
|
||||
<TableCell align="center" sx={{ padding: "10px 0" }}>
|
||||
<Typography>{
|
||||
formatCurrency(
|
||||
currentTwapPrice(gasPrice * item.gasUsed).toString(),
|
||||
5,
|
||||
ftsoSymbol
|
||||
)
|
||||
}</Typography>
|
||||
</TableCell>
|
||||
|
||||
<TableCell sx={{ padding: "10px 0" }}>
|
||||
<Box p="0 30px" display="flex" justifyContent="center" alignItems="center">
|
||||
<TertiaryButton
|
||||
fullWidth
|
||||
disabled={disabled || isLoading || isTransactionExecuted || isTransactionExecutedLoading}
|
||||
onClick={() => setVerifiedItem({
|
||||
exodusContext: item.exodusContext,
|
||||
dkgIndex: item.dkgIndex,
|
||||
type: item.type,
|
||||
mutate: refetchTransactionExecuted,
|
||||
})}
|
||||
>
|
||||
{isTransactionExecuted ? "Verified" : "Verify"}
|
||||
</TertiaryButton>
|
||||
</Box>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
)
|
||||
}
|
||||
|
||||
const ExodusList = ({
|
||||
nativeMetadata,
|
||||
setVerifiedItem,
|
||||
ftsoSymbol,
|
||||
gasPrice,
|
||||
disabled,
|
||||
currentTwapPrice,
|
||||
signedMessages,
|
||||
isLoading,
|
||||
signedExodusRotations,
|
||||
}) => {
|
||||
const isSmallScreen = useMediaQuery("(max-width: 900px)");
|
||||
|
||||
if (isLoading) {
|
||||
return (
|
||||
<Box my="20px" display="flex" flexDirection="column" justifyContent="center" alignItems="center" gap="50px">
|
||||
<CircularProgress color="primary" />
|
||||
<Typography>Loading Signed Messages...</Typography>
|
||||
</Box>
|
||||
)
|
||||
}
|
||||
|
||||
if (isSmallScreen) {
|
||||
return (
|
||||
<Box display="flex" flexDirection="column" gap="50px">
|
||||
{signedMessages?.map((item, i) => {
|
||||
return (
|
||||
<ExodusItem
|
||||
key={i}
|
||||
item={item}
|
||||
gasPrice={gasPrice}
|
||||
disabled={disabled}
|
||||
isLoading={isLoading}
|
||||
ftsoSymbol={ftsoSymbol}
|
||||
setVerifiedItem={setVerifiedItem}
|
||||
currentTwapPrice={currentTwapPrice}
|
||||
nativeMetadata={nativeMetadata}
|
||||
isSmallScreen={isSmallScreen}
|
||||
/>
|
||||
)
|
||||
})}
|
||||
</Box>
|
||||
)
|
||||
} else {
|
||||
return (
|
||||
<TableContainer>
|
||||
<Table aria-label="Available bonds" style={{ tableLayout: "fixed" }}>
|
||||
<TableHead>
|
||||
<TableRow>
|
||||
<TableCell style={{ padding: "8px 0" }}>Exodus</TableCell>
|
||||
<TableCell style={{ padding: "8px 0" }} align="center">Status</TableCell>
|
||||
<TableCell style={{ padding: "8px 0" }} align="center">{nativeMetadata.symbol} Cost</TableCell>
|
||||
<TableCell style={{ padding: "8px 0" }} align="center">Reward</TableCell>
|
||||
<TableCell style={{ padding: "8px 0" }}></TableCell>
|
||||
</TableRow>
|
||||
</TableHead>
|
||||
<TableBody>
|
||||
{signedMessages?.map((item, i) => {
|
||||
return (
|
||||
<ExodusItem
|
||||
key={i}
|
||||
item={item}
|
||||
disabled={disabled}
|
||||
isLoading={isLoading}
|
||||
gasPrice={gasPrice}
|
||||
ftsoSymbol={ftsoSymbol}
|
||||
setVerifiedItem={setVerifiedItem}
|
||||
nativeMetadata={nativeMetadata}
|
||||
currentTwapPrice={currentTwapPrice}
|
||||
isSmallScreen={isSmallScreen}
|
||||
/>
|
||||
)
|
||||
})}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</TableContainer>
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
export default ExodusList;
|
||||
263
src/containers/Exodus/ExodusModal.jsx
Normal file
263
src/containers/Exodus/ExodusModal.jsx
Normal file
@ -0,0 +1,263 @@
|
||||
import useSWR from "swr";
|
||||
import { useState, useMemo } from "react";
|
||||
import { Box, Divider, Link, Skeleton, Typography } from "@mui/material";
|
||||
import { keccak256, hexToBytes, getAddress, toHex, hexToBigInt } from 'viem';
|
||||
|
||||
import CloseIcon from '@mui/icons-material/Close';
|
||||
import CheckIcon from '@mui/icons-material/Check';
|
||||
import ContentPasteIcon from '@mui/icons-material/ContentPaste';
|
||||
|
||||
import Modal from "../../components/Modal/Modal";
|
||||
import DataRow from "../../components/DataRow/DataRow";
|
||||
import GhostStyledIcon from "../../components/Icon/GhostIcon";
|
||||
import { PrimaryButton } from "../../components/Button";
|
||||
|
||||
import { DecimalBigNumber } from "../../helpers/DecimalBigNumber";
|
||||
import { formatCurrency, shorten } from "../../helpers";
|
||||
import { verifySignature, useGatekeeperAddress } from "../../hooks/staking";
|
||||
import { useUnstableProvider } from "../../hooks/ghost";
|
||||
import { useTokenSymbol } from "../../hooks/tokens";
|
||||
import { useLocalStorage } from "../../hooks/localstorage";
|
||||
|
||||
import { BRIDGE_OUT, KEY_ROTATION } from "./Exodus";
|
||||
|
||||
export const ExodusVerifyModal = ({
|
||||
chainId,
|
||||
isOpen,
|
||||
onClose,
|
||||
nativeMetadata,
|
||||
address,
|
||||
casperApi,
|
||||
item,
|
||||
ftsoSymbol,
|
||||
gasPrice,
|
||||
gasUsed,
|
||||
currentTwapPrice,
|
||||
}) => {
|
||||
const [isPending, setIsPending] = useState(false);
|
||||
const [copiedIndex, setCopiedIndex] = useState(null);
|
||||
|
||||
const { tryStoreInHistory, CONSTANTS } = useLocalStorage();
|
||||
const { client } = useUnstableProvider();
|
||||
|
||||
const copyToClipboard = (text, index) => {
|
||||
navigator.clipboard.writeText(text).then(() => {
|
||||
setCopiedIndex(index);
|
||||
setTimeout(() => setCopiedIndex(null) , 800);
|
||||
});
|
||||
};
|
||||
|
||||
const { symbol: ghstSymbol } = useTokenSymbol(Number(item?.exodusContext.network_id), "GHST");
|
||||
|
||||
const {
|
||||
gatekeeperAddress,
|
||||
gatekeeperIsEmpty
|
||||
} = useGatekeeperAddress(Number(item?.exodusContext.network_id));
|
||||
|
||||
const { data: evmMessageMetadata, isLoading: evmMessageMetadataLoading, error } = useSWR(
|
||||
client && item ? ['evmMessage', client, item] : null,
|
||||
async ([_, client, it]) => {
|
||||
switch (it.type) {
|
||||
case BRIDGE_OUT:
|
||||
return client.getUnsafeApi().apis.ExodusApi.get_evm_bridge_metadata(
|
||||
BigInt(it.dkgIndex),
|
||||
BigInt(it.exodusContext.network_id),
|
||||
BigInt(it.exodusContext.session),
|
||||
)
|
||||
case KEY_ROTATION:
|
||||
return client.getUnsafeApi().apis.ExodusApi.get_evm_rotation_metadata(
|
||||
BigInt(it.dkgIndex),
|
||||
{ type: "Evm" }
|
||||
)
|
||||
default:
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
const upcomingGroupKey = useMemo(() => {
|
||||
if (!evmMessageMetadata) return null;
|
||||
|
||||
const callHex = toHex(evmMessageMetadata.at(0));
|
||||
const extractedPxHex = `0x${callHex.slice(74, 138)}`;
|
||||
|
||||
const cleanHex = extractedPxHex.startsWith('0x04') && extractedPxHex.length === 130
|
||||
? `0x${extractedPxHex.slice(4)}`
|
||||
: extractedPxHex.startsWith('0x')
|
||||
? extractedPxHex
|
||||
: `0x${extractedPxHex}`;
|
||||
|
||||
const hash = keccak256(cleanHex);
|
||||
|
||||
return getAddress(`0x${hash.slice(-40)}`);
|
||||
}, [evmMessageMetadata]);
|
||||
|
||||
const bridgeAmount = useMemo(() => {
|
||||
if (!evmMessageMetadata) return null;
|
||||
|
||||
const callHex = toHex(evmMessageMetadata.at(0));
|
||||
const rawAmountHex = `0x${callHex.slice(74, 138)}`;
|
||||
|
||||
const amountWei = hexToBigInt(rawAmountHex);
|
||||
return new DecimalBigNumber(amountWei, 18);
|
||||
}, [evmMessageMetadata]);
|
||||
|
||||
const verifySignatureModal = async () => {
|
||||
setIsPending(true);
|
||||
|
||||
try {
|
||||
const txHash = await verifySignature({
|
||||
account: address,
|
||||
gatekeeper: gatekeeperAddress,
|
||||
chainId: Number(item.exodusContext.network_id),
|
||||
calldata: toHex(evmMessageMetadata.at(0)),
|
||||
nonce: toHex(evmMessageMetadata.at(1)),
|
||||
signature: toHex(evmMessageMetadata.at(2)),
|
||||
});
|
||||
|
||||
if (txHash) tryStoreInHistory(
|
||||
Number(item.exodusContext.network_id),
|
||||
address,
|
||||
CONSTANTS.bond.key,
|
||||
txHash,
|
||||
CONSTANTS.bond.exodus
|
||||
);
|
||||
|
||||
await item.mutate();
|
||||
|
||||
onClose();
|
||||
} finally {
|
||||
setIsPending(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Modal
|
||||
maxWidth="426px"
|
||||
minHeight="200px"
|
||||
open={isOpen}
|
||||
headerContent={<Typography variant="h4">Verify {item ? item.type : ""}</Typography>}
|
||||
onClose={!isPending && onClose}
|
||||
topRight={
|
||||
<GhostStyledIcon
|
||||
viewBox="0 0 23 23"
|
||||
component={CloseIcon}
|
||||
onClick={onClose}
|
||||
/>
|
||||
}
|
||||
>
|
||||
<Box display="flex" flexDirection="column">
|
||||
<Box mb="15px" display="flex" flexDirection="column" gap="1px" sx={{ "& .DataRow-root": { margin: "0 !important" } }}>
|
||||
{item?.type === KEY_ROTATION
|
||||
? <DataRow
|
||||
title={<Typography variant="caption">New Group Key</Typography>}
|
||||
tooltip="Some cool description here."
|
||||
balance={<Link
|
||||
href={`${nativeMetadata.url}/address/${upcomingGroupKey}`}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
>
|
||||
<Typography variant="caption">{
|
||||
upcomingGroupKey ? shorten(upcomingGroupKey, 12, -8) : ""
|
||||
}</Typography>
|
||||
</Link>}
|
||||
/>
|
||||
: <DataRow
|
||||
title={<Typography variant="caption">Bridging Amount</Typography>}
|
||||
tooltip="Some cool description here."
|
||||
balance={
|
||||
<Typography variant="caption">{
|
||||
bridgeAmount ? formatCurrency(bridgeAmount, 5, ghstSymbol) : ""
|
||||
}</Typography>
|
||||
} />
|
||||
}
|
||||
|
||||
<DataRow
|
||||
title={<Typography variant="caption">Verification Reward</Typography>}
|
||||
tooltip="Some cool description here."
|
||||
balance={<Typography variant="caption">{
|
||||
formatCurrency(
|
||||
currentTwapPrice((gasPrice ? gasPrice : 0n) * (gasUsed ? gasUsed : 0n)).toString(),
|
||||
5,
|
||||
ftsoSymbol
|
||||
)
|
||||
}</Typography>}
|
||||
/>
|
||||
|
||||
<Divider sx={{ my: "15px", width: "100%" }} />
|
||||
|
||||
<DataRow
|
||||
title={<Typography variant="caption">Raw Message</Typography>}
|
||||
tooltip="Some cool description here."
|
||||
balance={evmMessageMetadata?.at(0)
|
||||
? <Link
|
||||
style={{ display: "flex", flexDirection: "row", justifyContent: "center", alignItems: "center" }}
|
||||
onClick={() => copyToClipboard(toHex(evmMessageMetadata.at(0)), 0)}
|
||||
>
|
||||
<Typography variant="caption">
|
||||
{shorten(toHex(evmMessageMetadata.at(0)), 12, -10)}
|
||||
</Typography>
|
||||
<GhostStyledIcon
|
||||
sx={{ marginLeft: "5px", width: "12px", height: "12px" }}
|
||||
viewBox="0 0 25 25"
|
||||
component={copiedIndex === 0 ? CheckIcon : ContentPasteIcon}
|
||||
/>
|
||||
</Link>
|
||||
: <Skeleton width="185px" />
|
||||
}
|
||||
/>
|
||||
|
||||
<DataRow
|
||||
title={<Typography variant="caption">Nonce</Typography>}
|
||||
tooltip="Some cool description here."
|
||||
balance={evmMessageMetadata?.at(1)
|
||||
? <Link
|
||||
style={{ display: "flex", flexDirection: "row", justifyContent: "center", alignItems: "center" }}
|
||||
onClick={() => copyToClipboard(toHex(evmMessageMetadata.at(1)), 1)}
|
||||
>
|
||||
<Typography variant="caption">
|
||||
{shorten(toHex(evmMessageMetadata.at(1)), 12, -10)}
|
||||
</Typography>
|
||||
<GhostStyledIcon
|
||||
sx={{ marginLeft: "5px", width: "12px", height: "12px" }}
|
||||
viewBox="0 0 25 25"
|
||||
component={copiedIndex === 1 ? CheckIcon : ContentPasteIcon}
|
||||
/>
|
||||
</Link>
|
||||
: <Skeleton width="185px" />
|
||||
}
|
||||
/>
|
||||
|
||||
<DataRow
|
||||
title={<Typography variant="caption">Signture</Typography>}
|
||||
tooltip="Some cool description here."
|
||||
balance={evmMessageMetadata?.at(2)
|
||||
? <Link
|
||||
style={{ display: "flex", flexDirection: "row", justifyContent: "center", alignItems: "center" }}
|
||||
onClick={() => copyToClipboard(toHex(evmMessageMetadata.at(2)), 2)}
|
||||
>
|
||||
<Typography variant="caption">
|
||||
{shorten(toHex(evmMessageMetadata.at(2)), 12, -10)}
|
||||
</Typography>
|
||||
<GhostStyledIcon
|
||||
sx={{ marginLeft: "5px", width: "12px", height: "12px" }}
|
||||
viewBox="0 0 25 25"
|
||||
component={copiedIndex === 2 ? CheckIcon : ContentPasteIcon}
|
||||
/>
|
||||
</Link>
|
||||
: <Skeleton width="185px" />
|
||||
}
|
||||
/>
|
||||
</Box>
|
||||
|
||||
<PrimaryButton
|
||||
fullWidth
|
||||
disabled={isPending || gatekeeperIsEmpty || evmMessageMetadataLoading || !evmMessageMetadata}
|
||||
onClick={verifySignatureModal}
|
||||
>
|
||||
{isPending ? "Pending..." : "Verify"}
|
||||
</PrimaryButton>
|
||||
</Box>
|
||||
</Modal>
|
||||
)
|
||||
}
|
||||
50
src/containers/Exodus/ExodusStatusCard.jsx
Normal file
50
src/containers/Exodus/ExodusStatusCard.jsx
Normal file
@ -0,0 +1,50 @@
|
||||
import { Box, Typography, useTheme } from "@mui/material";
|
||||
import { formatNumber } from "../../helpers";
|
||||
import LinearProgressBar from "../../components/Progress/LinearProgressBar";
|
||||
|
||||
const ExodusStatusCard = ({ executionDiscount, currentGasPrice, maxGasPrice }) => {
|
||||
const theme = useTheme();
|
||||
|
||||
const getGasLabel = (pct) => {
|
||||
if (pct >= 100) return "Peak Bounty";
|
||||
if (pct >= 85) return "Surge Bounty";
|
||||
if (pct >= 70) return "High Incentive";
|
||||
if (pct >= 50) return "Boosted Bounty";
|
||||
if (pct >= 35) return "Rising Bounty";
|
||||
if (pct >= 15) return "Growing Bounty";
|
||||
if (pct > 0) return "Base Bounty";
|
||||
return "Awaiting Start";
|
||||
};
|
||||
|
||||
return (
|
||||
<Box mt="30px" sx={{ mb: { xs: "0px", md: "-30px" }}}>
|
||||
<Box display="flex" justifyContent="space-between" alignItems="center" mt="2px">
|
||||
<Box display="flex" alignItems="center" gap="5px">
|
||||
<Typography variant="caption" fontWeight="bold">Bounty Escalation: </Typography>
|
||||
<Typography variant="caption" fontWeight="bold" sx={{
|
||||
color: Number(executionDiscount) > 0
|
||||
? theme.colors.feedback.success
|
||||
: theme.colors.feedback.error
|
||||
}}>
|
||||
{getGasLabel(Math.min(100, Number(currentGasPrice.div(maxGasPrice).toString()) * 100))}
|
||||
</Typography>
|
||||
</Box>
|
||||
<Typography variant="caption">
|
||||
<Box display="flex" flexDirection="row" gap="5px">
|
||||
<Typography variant="caption" sx={{ fontWeight: "700" }}>Multiplier:</Typography>
|
||||
<Typography variant="caption">{`${formatNumber(currentGasPrice, 5)} / ${formatNumber(maxGasPrice, 5)}`}</Typography>
|
||||
</Box>
|
||||
</Typography>
|
||||
</Box>
|
||||
|
||||
<LinearProgressBar
|
||||
variant={"determinate"}
|
||||
value={Math.min(100, Number(currentGasPrice.div(maxGasPrice).toString()) * 100)}
|
||||
height={6}
|
||||
barColor={theme.colors.feedback.success}
|
||||
/>
|
||||
</Box>
|
||||
);
|
||||
};
|
||||
|
||||
export default ExodusStatusCard;
|
||||
@ -12,7 +12,7 @@ import { ArgumentsWrapper, BooleanTrigger, ArgumentInput, ParsedCell } from "./i
|
||||
|
||||
import {
|
||||
RESERVE_ADDRESSES,
|
||||
FTSO_DAI_LP_ADDRESSES,
|
||||
FTSO_RESERVE_LP_ADDRESSES,
|
||||
BOND_DEPOSITORY_ADDRESSES,
|
||||
} from "../../../../constants/addresses";
|
||||
import { abi as DepositoryAbi } from "../../../../abi/GhostBondDepository.json";
|
||||
@ -114,7 +114,7 @@ export const CreateBondSteps = ({ nativeCurrency, ftsoSymbol, chainId, toInitial
|
||||
}, [step, tokenAddress, capacity, initialPrice, debtBuffer, depositInterval, tuneInterval]);
|
||||
|
||||
const possibleTokens = [
|
||||
{ value: FTSO_DAI_LP_ADDRESSES[chainId], symbol: `${ftsoSymbol}-${reserveSymbol} LP`, label: `${ftsoSymbol}-${reserveSymbol} LP: ${shorten(FTSO_DAI_LP_ADDRESSES[chainId])}` },
|
||||
{ value: FTSO_RESERVE_LP_ADDRESSES[chainId], symbol: `${ftsoSymbol}-${reserveSymbol} LP`, label: `${ftsoSymbol}-${reserveSymbol} LP: ${shorten(FTSO_RESERVE_LP_ADDRESSES[chainId])}` },
|
||||
{ value: RESERVE_ADDRESSES[chainId], symbol: reserveSymbol, label: `${reserveSymbol}: ${shorten(RESERVE_ADDRESSES[chainId])}` },
|
||||
];
|
||||
|
||||
|
||||
197
src/containers/History/AddRecordModal.jsx
Normal file
197
src/containers/History/AddRecordModal.jsx
Normal file
@ -0,0 +1,197 @@
|
||||
import { isHash, hexToNumber, decodeEventLog, decodeFunctionData } from 'viem';
|
||||
import { useTransactionReceipt, useBlockNumber, useTransaction } from 'wagmi';
|
||||
import { useState, useMemo } from "react";
|
||||
import { Box, Typography, FormControl, OutlinedInput } from "@mui/material";
|
||||
|
||||
import Modal from "../../components/Modal/Modal";
|
||||
import GhostStyledIcon from "../../components/Icon/GhostIcon";
|
||||
import { PrimaryButton } from "../../components/Button";
|
||||
|
||||
import { shorten } from "../../helpers";
|
||||
import { useLocalStorage } from "../../hooks/localstorage";
|
||||
|
||||
import CheckIcon from '@mui/icons-material/CheckCircle';
|
||||
import PendingIcon from '@mui/icons-material/Pending';
|
||||
import CancelIcon from '@mui/icons-material/Cancel';
|
||||
|
||||
import {
|
||||
STAKING_ADDRESSES,
|
||||
BOND_DEPOSITORY_ADDRESSES,
|
||||
UNISWAP_V2_ROUTER
|
||||
} from "../../constants/addresses";
|
||||
|
||||
import { abi as UniswapV2RouterAbi } from "../../abi/UniswapV2Router.json";
|
||||
import { abi as GhostStakingAbi } from "../../abi/GhostStaking.json"
|
||||
import { abi as GatekeeperAbi } from "../../abi/GhostGatekeeper.json";
|
||||
import { abi as UniswapV2PairAbi } from "../../abi/UniswapV2Pair.json";
|
||||
import { abi as GhostBondDepositoryAbi } from "../../abi/GhostBondDepository.json";
|
||||
import { abi as ERC20TokenAbi } from "../../abi/ERC20.json";
|
||||
|
||||
const ABIS = [GatekeeperAbi, UniswapV2PairAbi, GhostBondDepositoryAbi, ERC20TokenAbi, GhostStakingAbi, UniswapV2RouterAbi]
|
||||
|
||||
const AddRecordModal = ({ chainId, address, isOpen, close }) => {
|
||||
const [txHash, setTxHash] = useState("");
|
||||
const isValidTxHash = isHash(txHash);
|
||||
|
||||
const { tryStoreInHistory, CONSTANTS } = useLocalStorage();
|
||||
|
||||
const { data: txData } = useTransaction({
|
||||
chainId,
|
||||
hash: isValidTxHash ? txHash : null,
|
||||
});
|
||||
|
||||
const { data: receipt } = useTransactionReceipt({
|
||||
hash: isValidTxHash ? txHash : null,
|
||||
query: {
|
||||
enabled: isValidTxHash
|
||||
}
|
||||
});
|
||||
|
||||
const functionCall = useMemo(() => {
|
||||
let functionCall = null;
|
||||
for (const abi of ABIS) {
|
||||
try {
|
||||
const decodedFunction = decodeFunctionData({ abi, data: txData.input });
|
||||
functionCall = {
|
||||
name: decodedFunction.functionName,
|
||||
args: decodedFunction.args,
|
||||
address: txData?.to?.toLowerCase(),
|
||||
};
|
||||
break;
|
||||
} catch (e) {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
return functionCall;
|
||||
}, [receipt, txData]);
|
||||
|
||||
const transactionType = useMemo(() => {
|
||||
switch (functionCall?.name) {
|
||||
case "forceRedeem":
|
||||
if (functionCall?.address !== BOND_DEPOSITORY_ADDRESSES[chainId]?.toLowerCase()) return null;
|
||||
return { key: CONSTANTS.bridgeIn.key, name: CONSTANTS.bridgeIn.name };
|
||||
case "ghost":
|
||||
if (functionCall?.address !== STAKING_ADDRESSES[chainId]?.toLowerCase()) return null;
|
||||
return { key: CONSTANTS.bridgeIn.key, name: CONSTANTS.bridgeIn.name };
|
||||
case "redeem":
|
||||
if (functionCall?.address !== BOND_DEPOSITORY_ADDRESSES[chainId]?.toLowerCase()) return null;
|
||||
return { key: CONSTANTS.bond.key, name: CONSTANTS.bond.claim };
|
||||
case "deposit":
|
||||
if (functionCall?.address !== BOND_DEPOSITORY_ADDRESSES[chainId]?.toLowerCase()) return null;
|
||||
return { key: CONSTANTS.bond.key, name: CONSTANTS.bond.bond };
|
||||
case "stake":
|
||||
if (functionCall?.address !== STAKING_ADDRESSES[chainId]?.toLowerCase()) return null;
|
||||
return { key: CONSTANTS.stake.key, name: CONSTANTS.stake.stake };
|
||||
case "unstake":
|
||||
if (functionCall?.address !== STAKING_ADDRESSES[chainId]?.toLowerCase()) return null;
|
||||
return { key: CONSTANTS.stake.key, name: CONSTANTS.stake.unstake };
|
||||
case "wrap":
|
||||
if (functionCall?.address !== STAKING_ADDRESSES[chainId]?.toLowerCase()) return null;
|
||||
return { key: CONSTANTS.stake.key, name: CONSTANTS.stake.wrap };
|
||||
case "unwrap":
|
||||
if (functionCall?.address !== STAKING_ADDRESSES[chainId]?.toLowerCase()) return null;
|
||||
return { key: CONSTANTS.stake.key, name: CONSTANTS.stake.unwrap };
|
||||
|
||||
case "swapExactETHForTokens":
|
||||
case "swapExactTokensForTokens":
|
||||
case "swapTokensForExactTokens":
|
||||
case "swapTokensForExactETH":
|
||||
case "swapExactTokensForETH":
|
||||
case "swapETHForExactTokens":
|
||||
case "swapExactTokensForTokensSupportingFeeOnTransferTokens":
|
||||
case "swapExactETHForTokensSupportingFeeOnTransferTokens":
|
||||
case "swapExactTokensForETHSupportingFeeOnTransferTokens":
|
||||
if (functionCall?.address !== UNISWAP_V2_ROUTER[chainId]?.toLowerCase()) return null;
|
||||
return { key: CONSTANTS.dex.key, name: CONSTANTS.dex.swap };
|
||||
|
||||
case "addLiquidity":
|
||||
case "addLiquidityETH":
|
||||
if (functionCall?.address !== UNISWAP_V2_ROUTER[chainId]?.toLowerCase()) return null;
|
||||
return { key: CONSTANTS.dex.key, name: CONSTANTS.dex.add };
|
||||
|
||||
case "removeLiquidity":
|
||||
case "removeLiquidityETH":
|
||||
case "removeLiquidityWithPermit":
|
||||
case "removeLiquidityETHWithPermit":
|
||||
case "removeLiquidityETHSupportingFeeOnTransferTokens":
|
||||
case "removeLiquidityETHWithPermitSupportingFeeOnTransferTokens":
|
||||
if (functionCall?.address !== UNISWAP_V2_ROUTER[chainId]?.toLowerCase()) return null;
|
||||
return { key: CONSTANTS.dex.key, name: CONSTANTS.dex.remove };
|
||||
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
}, [functionCall]);
|
||||
|
||||
const submitted = useMemo(() => {
|
||||
if (!txData) return Date.now();
|
||||
const seconds = hexToNumber(txData?.blockTimestamp);
|
||||
const jsTimestamp = seconds * 1000;
|
||||
return new Date(jsTimestamp);
|
||||
}, [txData]);
|
||||
|
||||
const storeRecord = () => {
|
||||
tryStoreInHistory(chainId, address, transactionType.key, txHash, transactionType.name, true);
|
||||
close()
|
||||
}
|
||||
|
||||
return (
|
||||
<Modal
|
||||
key="AddRecordModal"
|
||||
maxWidth="380px"
|
||||
minHeight="200px"
|
||||
open={isOpen}
|
||||
headerText="Add Record"
|
||||
onClose={() => close()}
|
||||
>
|
||||
<Box display="flex" flexDirection="column" justifyContent="space-between" gap="20px">
|
||||
<Box display="flex" flexDirection="column" gap="5px">
|
||||
<Typography>Transaction hash to be used in history</Typography>
|
||||
<FormControl variant="outlined" color="primary" fullWidth>
|
||||
<OutlinedInput
|
||||
inputProps={{ "data-testid": "add-record-tx-hash" }}
|
||||
id="add-record-tx-hash"
|
||||
onChange={event => setTxHash(event.currentTarget.value)}
|
||||
placeholder={isValidTxHash ? shorten(txHash, 17, -14) : "Transaction hash (0x prefixed)"}
|
||||
value={isValidTxHash ? "" : txHash}
|
||||
/>
|
||||
</FormControl>
|
||||
</Box>
|
||||
|
||||
{txData && transactionType &&
|
||||
<>
|
||||
<Box display="flex" flexDirection="column" gap="5px">
|
||||
<Typography>Block Submission Timestamp</Typography>
|
||||
<FormControl variant="outlined" color="primary" fullWidth>
|
||||
<OutlinedInput
|
||||
readOnly
|
||||
inputProps={{ "data-testid": "add-record-submitted" }}
|
||||
id="add-record-submitted"
|
||||
value={submitted.toLocaleString()}
|
||||
/>
|
||||
</FormControl>
|
||||
</Box>
|
||||
|
||||
<Box display="flex" flexDirection="column" gap="5px">
|
||||
<Typography>Transaction Type</Typography>
|
||||
<FormControl variant="outlined" color="primary" fullWidth>
|
||||
<OutlinedInput
|
||||
readOnly
|
||||
inputProps={{ "data-testid": "add-record-submitted" }}
|
||||
id="add-record-submitted"
|
||||
value={`${transactionType.name} / ${transactionType.name}`}
|
||||
/>
|
||||
</FormControl>
|
||||
</Box>
|
||||
</>
|
||||
}
|
||||
|
||||
<PrimaryButton disabled={!txData || !transactionType} fullWidth onClick={storeRecord}>
|
||||
{transactionType ? "Add Record" : "Unknown Transaction"}
|
||||
</PrimaryButton>
|
||||
</Box>
|
||||
</Modal>
|
||||
)
|
||||
}
|
||||
|
||||
export default AddRecordModal;
|
||||
41
src/containers/History/BondModal.jsx
Normal file
41
src/containers/History/BondModal.jsx
Normal file
@ -0,0 +1,41 @@
|
||||
import { useLocalStorage } from "../../hooks/localstorage";
|
||||
|
||||
import BondModalClaim from "./BondModals/BondModalClaim";
|
||||
import BondModalBond from "./BondModals/BondModalBond";
|
||||
import BondModalExodus from "./BondModals/BondModalExodus";
|
||||
|
||||
const BondModal = ({ chainId, isOpen, close, config, historyRecord, address }) => {
|
||||
const { CONSTANTS } = useLocalStorage();
|
||||
|
||||
switch (historyRecord.name) {
|
||||
case CONSTANTS.bond.bond:
|
||||
return <BondModalBond
|
||||
chainId={chainId}
|
||||
isOpen={isOpen}
|
||||
close={close}
|
||||
config={config}
|
||||
historyRecord={historyRecord}
|
||||
/>
|
||||
case CONSTANTS.bond.claim:
|
||||
return <BondModalClaim
|
||||
chainId={chainId}
|
||||
isOpen={isOpen}
|
||||
close={close}
|
||||
config={config}
|
||||
historyRecord={historyRecord}
|
||||
/>
|
||||
case CONSTANTS.bond.exodus:
|
||||
return <BondModalExodus
|
||||
chainId={chainId}
|
||||
isOpen={isOpen}
|
||||
close={close}
|
||||
config={config}
|
||||
address={address}
|
||||
historyRecord={historyRecord}
|
||||
/>
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export default BondModal;
|
||||
231
src/containers/History/BondModals/BondModalBond.jsx
Normal file
231
src/containers/History/BondModals/BondModalBond.jsx
Normal file
@ -0,0 +1,231 @@
|
||||
import { useTransactionReceipt, useTransaction, useToken } from 'wagmi';
|
||||
import { decodeEventLog, decodeFunctionData } from 'viem';
|
||||
import { useMemo, useCallback, useState } from "react";
|
||||
import { useParams } from "react-router-dom";
|
||||
|
||||
import { Box, Typography, Link } from "@mui/material";
|
||||
import ArrowRightIcon from '@mui/icons-material/ArrowRight';
|
||||
|
||||
import GhostStyledIcon from "../../../components/Icon/GhostIcon";
|
||||
import Modal from "../../../components/Modal/Modal";
|
||||
import Token from "../../../components/Token/Token";
|
||||
import { PrimaryButton } from "../../../components/Button";
|
||||
|
||||
import { useBondInfo } from "../../../hooks/bonds";
|
||||
import { getTokenDecimals } from "../../../hooks/helpers";
|
||||
import { useLocalStorage } from "../../../hooks/localstorage";
|
||||
import { formatNumber, formatCurrency, shorten } from "../../../helpers";
|
||||
import { DecimalBigNumber } from "../../../helpers/DecimalBigNumber";
|
||||
|
||||
import { abi as GhostBondDepository } from "../../../abi/GhostBondDepository.json";
|
||||
import { abi as GhostGatekeeper } from "../../../abi/GhostGatekeeper.json";
|
||||
import { abi as ERC20Token } from "../../../abi/ERC20.json";
|
||||
import TokenBox from "../TokenBox";
|
||||
|
||||
const BondModalBond = ({ chainId, isOpen, close, config, historyRecord }) => {
|
||||
if (historyRecord === null) return null;
|
||||
const { network } = useParams();
|
||||
const { CONSTANTS } = useLocalStorage();
|
||||
|
||||
const [copiedIndex, setCopiedIndex] = useState(null);
|
||||
|
||||
const copyToClipboard = (text, index) => {
|
||||
navigator.clipboard.writeText(text).then(() => {
|
||||
setCopiedIndex(index);
|
||||
setTimeout(() => setCopiedIndex(null) , 800);
|
||||
});
|
||||
};
|
||||
|
||||
const chainInfo = useMemo(() => {
|
||||
const client = config?.getClient();
|
||||
|
||||
return {
|
||||
url: client?.chain?.blockExplorers?.default?.url,
|
||||
symbol: client?.chain?.nativeCurrency?.symbol,
|
||||
};
|
||||
}, [config]);
|
||||
|
||||
const { data: receipt, isLoading, error } = useTransactionReceipt({
|
||||
hash: historyRecord?.txHash,
|
||||
query: {
|
||||
enabled: !!historyRecord?.txHash && isOpen,
|
||||
}
|
||||
});
|
||||
|
||||
const { data: txData } = useTransaction({
|
||||
chainId,
|
||||
hash: historyRecord.txHash,
|
||||
});
|
||||
|
||||
const functionArgs = useMemo(() => {
|
||||
if (!txData) return null;
|
||||
|
||||
try {
|
||||
const decoded = decodeFunctionData({
|
||||
abi: GhostBondDepository,
|
||||
data: txData.input
|
||||
});
|
||||
|
||||
return {
|
||||
bondId: decoded.args.at(0),
|
||||
amount: decoded.args.at(1),
|
||||
maxPrice: decoded.args.at(2),
|
||||
receiver: decoded.args.at(3),
|
||||
}
|
||||
} catch {}
|
||||
|
||||
try {
|
||||
const decoded = decodeFunctionData({
|
||||
abi: GhostGatekeeper,
|
||||
data: txData.input,
|
||||
});
|
||||
|
||||
return {
|
||||
bondId: 0,
|
||||
amount: 0n,
|
||||
maxPrice: 0n,
|
||||
receiver: "0x0000000000000000000000000000000000000000",
|
||||
}
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}, [txData]);
|
||||
|
||||
const allDecodedLogs = useMemo(() => {
|
||||
if (!receipt?.logs) return [];
|
||||
|
||||
return receipt.logs.map((log) => {
|
||||
try {
|
||||
const decoded = decodeEventLog({
|
||||
abi: GhostBondDepository,
|
||||
data: log.data,
|
||||
topics: log.topics,
|
||||
});
|
||||
|
||||
return {
|
||||
eventName: decoded.eventName,
|
||||
args: decoded.args,
|
||||
address: log.address
|
||||
};
|
||||
} catch (e) {
|
||||
return null;
|
||||
}
|
||||
}).filter(Boolean);
|
||||
}, [receipt]);
|
||||
|
||||
const { bonds } = useBondInfo(chainId, network, functionArgs ? [functionArgs.bondId] : []);
|
||||
|
||||
const bondPurchasePrice = useMemo(() => {
|
||||
const log = allDecodedLogs.find(l => l.eventName === 'Bond');
|
||||
if (!log) return 1n;
|
||||
|
||||
return log.args.price;
|
||||
}, [allDecodedLogs]);
|
||||
|
||||
const { data: baseToken } = useToken({
|
||||
address: bonds?.at(0)?.baseToken.tokenAddress,
|
||||
scopeKey: `baseToken-${functionArgs ? functionArgs.bondId : null}-${chainId}`,
|
||||
chainId
|
||||
});
|
||||
|
||||
const { data: quoteToken } = useToken({
|
||||
address: bonds?.at(0)?.quoteToken.quoteTokenAddress,
|
||||
scopeKey: `quoteToken-${functionArgs ? functionArgs.bondId : null}-${chainId}`,
|
||||
chainId
|
||||
});
|
||||
|
||||
const estimatedPayout = useMemo(() => {
|
||||
const spentAmount = functionArgs ? functionArgs.amount : 0n;
|
||||
const bondPrice = bondPurchasePrice ? bondPurchasePrice : 1n;
|
||||
const quoteTokenDecimals = quoteToken ? quoteToken.decimals : 18;
|
||||
|
||||
const mulDivResult = spentAmount * (10n ** 18n) / bondPrice;
|
||||
return mulDivResult / (10n ** BigInt(quoteTokenDecimals));
|
||||
}, [bondPurchasePrice, functionArgs?.amount, baseToken, quoteToken]);
|
||||
|
||||
const convertedAmount = useCallback((value) => {
|
||||
const decimals = baseToken ? baseToken.decimals : 9;
|
||||
const symbol = quoteToken ? quoteToken.symbol : "Unknown";
|
||||
|
||||
const convertedValue = new DecimalBigNumber(value ? value : 0n, decimals);
|
||||
return formatCurrency(convertedValue.toString(), 5, symbol);
|
||||
}, [quoteToken, baseToken]);
|
||||
|
||||
return (
|
||||
<Modal
|
||||
maxWidth="420px"
|
||||
minHeight="200px"
|
||||
open={isOpen}
|
||||
headerText={
|
||||
<>
|
||||
{(bonds && functionArgs && bondPurchasePrice) &&
|
||||
functionArgs.receiver !== "0x0000000000000000000000000000000000000000"
|
||||
? "Bond Purchase" : "Voluntary Verification"}
|
||||
{(!bonds || !functionArgs || !bondPurchasePrice) && "Parsing Transaction Hash"}
|
||||
</>
|
||||
}
|
||||
onClose={() => close()}
|
||||
>
|
||||
{bonds && functionArgs && bondPurchasePrice && <Box display="flex" flexDirection="column" gap="15px">
|
||||
<Box width="100%" gap="20px" display="flex" flexDirection="column" justifyContent="space-between" alignItems="flex-start">
|
||||
<Box width="100%" display="flex" flexDirection="row" justifyContent="space-around" alignItems="center">
|
||||
<TokenBox
|
||||
tokenAmount={functionArgs.amount}
|
||||
decimals={quoteToken ? quoteToken.decimals : 18}
|
||||
tokenSymbol={bonds.at(0) ? bonds.at(0).quoteToken.name : "Unknown"}
|
||||
chainTokenSymbol={bonds.at(0) ? bonds.at(0).quoteToken.chainNames.at(0) : chainInfo.symbol}
|
||||
/>
|
||||
|
||||
<GhostStyledIcon sx={{ fontSize: '24px' }} component={ArrowRightIcon} />
|
||||
|
||||
<TokenBox
|
||||
tokenAmount={estimatedPayout}
|
||||
decimals={baseToken ? baseToken.decimals : 9}
|
||||
tokenSymbol={bonds.at(0) ? bonds.at(0).baseToken.name : "Unknown"}
|
||||
chainTokenSymbol={bonds.at(0) ? bonds.at(0).baseToken.chainNames.at(0) : chainInfo.symbol}
|
||||
/>
|
||||
</Box>
|
||||
|
||||
<Box display="flex" flexDirection="column" justifyContent="space-between" width="100%">
|
||||
<Box display="flex" justifyContent="space-between" width="100%">
|
||||
{functionArgs.receiver !== "0x0000000000000000000000000000000000000000" &&
|
||||
<>
|
||||
<Typography>Receiver</Typography>
|
||||
<Link
|
||||
href={`${chainInfo.url}/address/${functionArgs.receiver}`}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
>
|
||||
<Typography>{shorten(functionArgs.receiver, 12, -10)}</Typography>
|
||||
</Link>
|
||||
</>
|
||||
}
|
||||
</Box>
|
||||
|
||||
<Box display="flex" justifyContent="space-between" width="100%">
|
||||
<Typography>Max Price Set</Typography>
|
||||
<Typography>{convertedAmount(functionArgs.maxPrice)}</Typography>
|
||||
</Box>
|
||||
|
||||
<Box display="flex" justifyContent="space-between" width="100%">
|
||||
<Typography>Effective Price</Typography>
|
||||
<Typography>{convertedAmount(bondPurchasePrice)}</Typography>
|
||||
</Box>
|
||||
</Box>
|
||||
|
||||
<PrimaryButton
|
||||
fullWidth
|
||||
component="a"
|
||||
href={`${chainInfo.url}/tx/${historyRecord.txHash}`}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
>
|
||||
View Transaction Details
|
||||
</PrimaryButton>
|
||||
</Box>
|
||||
</Box>}
|
||||
</Modal>
|
||||
)
|
||||
}
|
||||
|
||||
export default BondModalBond;
|
||||
174
src/containers/History/BondModals/BondModalClaim.jsx
Normal file
174
src/containers/History/BondModals/BondModalClaim.jsx
Normal file
@ -0,0 +1,174 @@
|
||||
import { useTransactionReceipt, useTransaction, useToken } from 'wagmi';
|
||||
import { decodeEventLog, decodeFunctionData } from 'viem';
|
||||
import { useMemo, useCallback } from "react";
|
||||
import { useParams } from "react-router-dom";
|
||||
|
||||
import { Box, Typography, Link } from "@mui/material";
|
||||
import ArrowRightIcon from '@mui/icons-material/ArrowRight';
|
||||
|
||||
import GhostStyledIcon from "../../../components/Icon/GhostIcon";
|
||||
import Modal from "../../../components/Modal/Modal";
|
||||
import Token from "../../../components/Token/Token";
|
||||
import { PrimaryButton } from "../../../components/Button";
|
||||
|
||||
import { useBondInfo } from "../../../hooks/bonds";
|
||||
import { getTokenDecimals } from "../../../hooks/helpers";
|
||||
import { useLocalStorage } from "../../../hooks/localstorage";
|
||||
import { formatNumber, formatCurrency, shorten } from "../../../helpers";
|
||||
import { DecimalBigNumber } from "../../../helpers/DecimalBigNumber";
|
||||
|
||||
import { abi as GhostBondDepository } from "../../../abi/GhostBondDepository.json";
|
||||
import { abi as GhostGatekeeper } from "../../../abi/GhostGatekeeper.json";
|
||||
import { abi as ERC20Token } from "../../../abi/ERC20.json";
|
||||
import TokenBox from "../TokenBox";
|
||||
|
||||
const BondModalClaim = ({ chainId, isOpen, close, config, historyRecord }) => {
|
||||
if (historyRecord === null) return null;
|
||||
const { network } = useParams();
|
||||
|
||||
const chainInfo = useMemo(() => {
|
||||
const client = config?.getClient();
|
||||
|
||||
return {
|
||||
url: client?.chain?.blockExplorers?.default?.url,
|
||||
symbol: client?.chain?.nativeCurrency?.symbol,
|
||||
};
|
||||
}, [config]);
|
||||
|
||||
const { data: receipt, isLoading, error } = useTransactionReceipt({
|
||||
hash: historyRecord?.txHash,
|
||||
query: {
|
||||
enabled: !!historyRecord?.txHash && isOpen,
|
||||
}
|
||||
});
|
||||
|
||||
const { data: txData } = useTransaction({
|
||||
chainId,
|
||||
hash: historyRecord.txHash,
|
||||
});
|
||||
|
||||
const functionArgs = useMemo(() => {
|
||||
if (!txData) return null;
|
||||
const decoded = decodeFunctionData({ abi: GhostBondDepository, data: txData.input });
|
||||
if (!decoded) return null;
|
||||
|
||||
return {
|
||||
receiver: decoded.args.at(0),
|
||||
isGhst: decoded.args.at(1),
|
||||
bondIds: decoded.args.at(2),
|
||||
}
|
||||
}, [txData]);
|
||||
|
||||
const allDecodedLogs = useMemo(() => {
|
||||
if (!receipt?.logs) return [];
|
||||
|
||||
return receipt.logs.map((log) => {
|
||||
try {
|
||||
const decoded = decodeEventLog({
|
||||
abi: ERC20Token,
|
||||
data: log.data,
|
||||
topics: log.topics,
|
||||
});
|
||||
|
||||
return {
|
||||
eventName: decoded.eventName,
|
||||
args: decoded.args,
|
||||
address: log.address
|
||||
};
|
||||
} catch (e) {
|
||||
return null;
|
||||
}
|
||||
}).filter(Boolean);
|
||||
}, [receipt]);
|
||||
|
||||
const claimedAmount = useMemo(() => {
|
||||
return allDecodedLogs?.reduce((sum, item) => sum + item.args.value, 0n);
|
||||
}, [allDecodedLogs]);
|
||||
|
||||
return (
|
||||
<Modal
|
||||
maxWidth="420px"
|
||||
minHeight="200px"
|
||||
open={isOpen}
|
||||
headerText={
|
||||
<>
|
||||
{functionArgs && "Bond Claim"}
|
||||
{(!functionArgs) && "Parsing Transaction Hash"}
|
||||
</>
|
||||
}
|
||||
onClose={() => close()}
|
||||
>
|
||||
{functionArgs && <Box display="flex" flexDirection="column" gap="15px">
|
||||
<Box width="100%" gap="20px" display="flex" flexDirection="column" justifyContent="space-between" alignItems="flex-start">
|
||||
<Box display="flex" flexDirection="row" justifyContent="space-between" alignItems="center" width="100%" gap="25px">
|
||||
<Box
|
||||
display="flex"
|
||||
alignItems="center"
|
||||
justifyContent="center"
|
||||
flexShrink={0}
|
||||
sx={{ width: "60px", height: "60px" }}
|
||||
>
|
||||
<Token
|
||||
parentSx={{
|
||||
display: "flex",
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
"& svg:nth-of-type(2)": {
|
||||
transform: "translate(50%, -50%)",
|
||||
zIndex: 100,
|
||||
}
|
||||
}}
|
||||
sx={{ transform: "scale(1.65)" }}
|
||||
chainTokenName={chainInfo.symbol}
|
||||
name={functionArgs.isGhst ? "GHST" : "STNK"}
|
||||
/>
|
||||
</Box>
|
||||
|
||||
<Box display="flex" flexDirection="column" justifyContent="space-between" width="100%">
|
||||
<Box display="flex" justifyContent="space-between" width="100%">
|
||||
<Typography>Receiver</Typography>
|
||||
<Link
|
||||
href={`${chainInfo.url}/address/${functionArgs.receiver}`}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
>
|
||||
<Typography>{shorten(functionArgs.receiver, 10, -8)}</Typography>
|
||||
</Link>
|
||||
</Box>
|
||||
|
||||
<Box display="flex" justifyContent="space-between" width="100%">
|
||||
<Typography>Claimed</Typography>
|
||||
<Typography>
|
||||
{formatCurrency(
|
||||
new DecimalBigNumber(claimedAmount ?? 0n, getTokenDecimals(functionArgs.isGhst ? "GHST" : "STNK")),
|
||||
5,
|
||||
functionArgs.isGhst ? "GHST" : "STNK"
|
||||
)}
|
||||
</Typography>
|
||||
</Box>
|
||||
|
||||
<Box display="flex" justifyContent="space-between" width="100%">
|
||||
<Typography>Bond Indexes</Typography>
|
||||
<Typography width="160px" textAlign="right">
|
||||
{functionArgs.bondIds.map((bond) => formatNumber(bond)).join(", ")}
|
||||
</Typography>
|
||||
</Box>
|
||||
</Box>
|
||||
</Box>
|
||||
|
||||
<PrimaryButton
|
||||
fullWidth
|
||||
component="a"
|
||||
href={`${chainInfo.url}/tx/${historyRecord.txHash}`}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
>
|
||||
View Transaction Details
|
||||
</PrimaryButton>
|
||||
</Box>
|
||||
</Box>}
|
||||
</Modal>
|
||||
)
|
||||
}
|
||||
|
||||
export default BondModalClaim;
|
||||
228
src/containers/History/BondModals/BondModalExodus.jsx
Normal file
228
src/containers/History/BondModals/BondModalExodus.jsx
Normal file
@ -0,0 +1,228 @@
|
||||
import { useTransactionReceipt, useTransaction, useToken } from 'wagmi';
|
||||
import { decodeEventLog, decodeFunctionData, toHex } from 'viem';
|
||||
import { useMemo, useCallback, useState } from "react";
|
||||
import { useParams } from "react-router-dom";
|
||||
|
||||
import { Box, Typography, Link, Skeleton } from "@mui/material";
|
||||
import CheckIcon from '@mui/icons-material/Check';
|
||||
import ContentPasteIcon from '@mui/icons-material/ContentPaste';
|
||||
|
||||
import GhostStyledIcon from "../../../components/Icon/GhostIcon";
|
||||
import Modal from "../../../components/Modal/Modal";
|
||||
import Token from "../../../components/Token/Token";
|
||||
import { PrimaryButton } from "../../../components/Button";
|
||||
|
||||
import { useBondInfo } from "../../../hooks/bonds";
|
||||
import { useTokenSymbol } from "../../../hooks/tokens";
|
||||
import { getTokenDecimals } from "../../../hooks/helpers";
|
||||
import { useLocalStorage } from "../../../hooks/localstorage";
|
||||
import { formatNumber, formatCurrency, shorten } from "../../../helpers";
|
||||
import { DecimalBigNumber } from "../../../helpers/DecimalBigNumber";
|
||||
|
||||
import { abi as GhostStaking } from "../../../abi/GhostStaking.json";
|
||||
import { abi as GhostGatekeeper } from "../../../abi/GhostGatekeeper.json";
|
||||
import { abi as ERC20Token } from "../../../abi/ERC20.json";
|
||||
import TokenBox from "../TokenBox";
|
||||
|
||||
const ClickableHex = ({ copyToClipboard, index, value, copiedIndex }) => {
|
||||
if (!value) return <Skeleton width="185px" />;
|
||||
|
||||
return (
|
||||
<Link
|
||||
style={{ display: "flex", flexDirection: "row", justifyContent: "center", alignItems: "center" }}
|
||||
onClick={() => copyToClipboard(value, index)}
|
||||
>
|
||||
<Typography>{shorten(value, 12, -10)}</Typography>
|
||||
<GhostStyledIcon
|
||||
sx={{ marginLeft: "5px", width: "12px", height: "12px" }}
|
||||
viewBox="0 0 25 25"
|
||||
component={copiedIndex === index ? CheckIcon : ContentPasteIcon}
|
||||
/>
|
||||
</Link>
|
||||
)
|
||||
}
|
||||
|
||||
const BondModalExodus = ({ chainId, address, isOpen, close, config, historyRecord }) => {
|
||||
if (historyRecord === null) return null;
|
||||
const { network } = useParams();
|
||||
const { CONSTANTS } = useLocalStorage();
|
||||
|
||||
const [copiedIndex, setCopiedIndex] = useState(null);
|
||||
|
||||
const copyToClipboard = (text, index) => {
|
||||
navigator.clipboard.writeText(text).then(() => {
|
||||
setCopiedIndex(index);
|
||||
setTimeout(() => setCopiedIndex(null) , 800);
|
||||
});
|
||||
};
|
||||
|
||||
const chainInfo = useMemo(() => {
|
||||
const client = config?.getClient();
|
||||
|
||||
return {
|
||||
url: client?.chain?.blockExplorers?.default?.url,
|
||||
symbol: client?.chain?.nativeCurrency?.symbol,
|
||||
};
|
||||
}, [config]);
|
||||
|
||||
const { symbol: ftsoSymbol } = useTokenSymbol(chainId, "FTSO");
|
||||
|
||||
const { data: receipt, isLoading, error } = useTransactionReceipt({
|
||||
hash: historyRecord?.txHash,
|
||||
query: {
|
||||
enabled: !!historyRecord?.txHash && isOpen,
|
||||
}
|
||||
});
|
||||
|
||||
const { data: txData } = useTransaction({
|
||||
chainId,
|
||||
hash: historyRecord.txHash,
|
||||
});
|
||||
|
||||
const functionArgs = useMemo(() => {
|
||||
if (!txData) return null;
|
||||
|
||||
try {
|
||||
const decoded = decodeFunctionData({
|
||||
abi: GhostGatekeeper,
|
||||
data: txData.input,
|
||||
});
|
||||
|
||||
return {
|
||||
message: decoded?.args.at(0),
|
||||
nonce: toHex(decoded?.args.at(1)),
|
||||
signature: toHex(decoded?.args.at(2)),
|
||||
}
|
||||
} catch (err) {
|
||||
return null;
|
||||
}
|
||||
}, [txData]);
|
||||
|
||||
const allDecodedLogs = useMemo(() => {
|
||||
if (!receipt?.logs) return [];
|
||||
|
||||
return receipt.logs.map((log) => {
|
||||
try {
|
||||
const decoded = decodeEventLog({
|
||||
abi: GhostGatekeeper,
|
||||
data: log.data,
|
||||
topics: log.topics,
|
||||
});
|
||||
|
||||
return {
|
||||
eventName: decoded.eventName,
|
||||
args: decoded.args,
|
||||
address: log.address
|
||||
};
|
||||
} catch (e) {}
|
||||
|
||||
try {
|
||||
const decoded = decodeEventLog({
|
||||
abi: GhostStaking,
|
||||
data: log.data,
|
||||
topics: log.topics,
|
||||
});
|
||||
|
||||
return {
|
||||
eventName: decoded.eventName,
|
||||
args: decoded.args,
|
||||
address: log.address
|
||||
};
|
||||
} catch (e) {
|
||||
return null;
|
||||
}
|
||||
}).filter(Boolean);
|
||||
}, [receipt]);
|
||||
|
||||
const voluntaryVerification = useMemo(() => {
|
||||
return !!allDecodedLogs.find(l => l.eventName === "VoluntaryVerification");
|
||||
}, [allDecodedLogs])
|
||||
|
||||
const stakedAmount = useMemo(() => {
|
||||
const log = allDecodedLogs.find(l => l.eventName === 'Staked');
|
||||
if (!log) return 1n;
|
||||
|
||||
return new DecimalBigNumber(log.args.amount, getTokenDecimals("FTSO"));
|
||||
}, [allDecodedLogs]);
|
||||
|
||||
return (
|
||||
<Modal
|
||||
maxWidth="420px"
|
||||
minHeight="200px"
|
||||
open={isOpen}
|
||||
headerText={
|
||||
<>
|
||||
{(functionArgs && allDecodedLogs) && voluntaryVerification
|
||||
? "Voluntary Verification" : "Exodus Verification"}
|
||||
{(!functionArgs || !allDecodedLogs) && "Parsing Transaction Hash"}
|
||||
</>
|
||||
}
|
||||
onClose={() => close()}
|
||||
>
|
||||
{<Box display="flex" flexDirection="column" gap="15px">
|
||||
<Box width="100%" gap="20px" display="flex" flexDirection="column" justifyContent="space-between" alignItems="flex-start">
|
||||
{!voluntaryVerification && <Box width="100%" display="flex" flexDirection="column" justifyContent="space-around" alignItems="center">
|
||||
<Box display="flex" justifyContent="space-between" width="100%">
|
||||
<Typography>Exodus Reward</Typography>
|
||||
<Typography>{formatCurrency(stakedAmount, 5, ftsoSymbol)}</Typography>
|
||||
</Box>
|
||||
|
||||
<Box display="flex" justifyContent="space-between" width="100%">
|
||||
<Typography>Receiver</Typography>
|
||||
<ClickableHex
|
||||
index={0}
|
||||
value={address}
|
||||
copiedIndex={copiedIndex}
|
||||
copyToClipboard={copyToClipboard}
|
||||
/>
|
||||
</Box>
|
||||
</Box>}
|
||||
|
||||
<Box display="flex" flexDirection="column" justifyContent="space-between" width="100%">
|
||||
<Box display="flex" justifyContent="space-between" width="100%">
|
||||
<Typography>Message</Typography>
|
||||
<ClickableHex
|
||||
index={1}
|
||||
copiedIndex={copiedIndex}
|
||||
copyToClipboard={copyToClipboard}
|
||||
value={functionArgs?.message}
|
||||
/>
|
||||
</Box>
|
||||
|
||||
<Box display="flex" justifyContent="space-between" width="100%">
|
||||
<Typography>Nonce</Typography>
|
||||
<ClickableHex
|
||||
index={2}
|
||||
copiedIndex={copiedIndex}
|
||||
copyToClipboard={copyToClipboard}
|
||||
value={functionArgs?.nonce}
|
||||
/>
|
||||
</Box>
|
||||
|
||||
<Box display="flex" justifyContent="space-between" width="100%">
|
||||
<Typography>Signature</Typography>
|
||||
<ClickableHex
|
||||
index={3}
|
||||
copiedIndex={copiedIndex}
|
||||
copyToClipboard={copyToClipboard}
|
||||
value={functionArgs?.signature}
|
||||
/>
|
||||
</Box>
|
||||
</Box>
|
||||
|
||||
<PrimaryButton
|
||||
fullWidth
|
||||
component="a"
|
||||
href={`${chainInfo.url}/tx/${historyRecord.txHash}`}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
>
|
||||
View Transaction Details
|
||||
</PrimaryButton>
|
||||
</Box>
|
||||
</Box>}
|
||||
</Modal>
|
||||
)
|
||||
}
|
||||
|
||||
export default BondModalExodus;
|
||||
742
src/containers/History/BridgeInModal.jsx
Normal file
742
src/containers/History/BridgeInModal.jsx
Normal file
@ -0,0 +1,742 @@
|
||||
import useSWR from 'swr';
|
||||
import { useMemo, useState, useEffect } from "react";
|
||||
import { useTransactionReceipt, useTransaction } from 'wagmi';
|
||||
import { getBlockNumber } from "@wagmi/core";
|
||||
import { decodeEventLog, decodeFunctionData } from 'viem';
|
||||
import { Box, Typography, Link, Skeleton, useTheme } from "@mui/material";
|
||||
import { ss58Encode } from "@polkadot-labs/hdkd-helpers";
|
||||
import { hexToBytes, bytesToHex } from "viem";
|
||||
import { blake2AsU8a } from "@polkadot/util-crypto";
|
||||
|
||||
import CheckIcon from '@mui/icons-material/Check';
|
||||
import SyncIcon from '@mui/icons-material/Sync';
|
||||
import FingerprintIcon from '@mui/icons-material/Fingerprint';
|
||||
import ContentPasteIcon from '@mui/icons-material/ContentPaste';
|
||||
import HourglassBottomIcon from '@mui/icons-material/HourglassBottom';
|
||||
import PendingIcon from '@mui/icons-material/Pending';
|
||||
import CheckCircleIcon from '@mui/icons-material/CheckCircle';
|
||||
|
||||
import Modal from "../../components/Modal/Modal";
|
||||
import DataRow from "../../components/DataRow/DataRow";
|
||||
import GhostStyledIcon from "../../components/Icon/GhostIcon";
|
||||
import { PrimaryButton } from "../../components/Button";
|
||||
import { abi as GatekeeperAbi } from "../../abi/GhostGatekeeper.json";
|
||||
import { abi as GhostBondDepositoryAbi } from "../../abi/GhostBondDepository.json";
|
||||
import { abi as ERC20TokenAbi } from "../../abi/ERC20.json";
|
||||
|
||||
import { executePapiBareTransaction } from "../../hooks/helpers";
|
||||
import { useWeaverRoot, useWeaverProof, useWeaverSlotValues, useWeaverMaximumSlots } from "../../hooks/staking"
|
||||
import { useUnstableProvider } from "../../hooks/ghost";
|
||||
import { DecimalBigNumber } from "../../helpers/DecimalBigNumber";
|
||||
import { shorten, formatNumber, formatCurrency } from "../../helpers";
|
||||
|
||||
const BridgeInModal = ({ chainId, isOpen, close, config, historyRecord }) => {
|
||||
if (historyRecord === null) return null;
|
||||
|
||||
const [isPending, setIsPending] = useState(false);
|
||||
const [blockNumber, setBlockNumber] = useState(0n);
|
||||
const [copiedIndex, setCopiedIndex] = useState(null);
|
||||
const { casperApi, client, account } = useUnstableProvider();
|
||||
|
||||
useEffect(() => {
|
||||
if (!isOpen || !historyRecord || !config) return;
|
||||
let isMounted = true;
|
||||
|
||||
const fetchBlock = async () => {
|
||||
try {
|
||||
const block = await getBlockNumber(config, { chainId });
|
||||
if (isMounted) setBlockNumber(block);
|
||||
} catch (err) {
|
||||
console.error('Error fetching block number:', err);
|
||||
}
|
||||
};
|
||||
|
||||
fetchBlock();
|
||||
const intervalId = setInterval(fetchBlock, 5000);
|
||||
|
||||
return () => {
|
||||
isMounted = false;
|
||||
clearInterval(intervalId);
|
||||
};
|
||||
}, [config, chainId, isOpen, historyRecord]);
|
||||
|
||||
const { data: txData } = useTransaction({
|
||||
chainId,
|
||||
hash: historyRecord.txHash,
|
||||
});
|
||||
|
||||
const copyToClipboard = (text, index) => {
|
||||
navigator.clipboard.writeText(text).then(() => {
|
||||
setCopiedIndex(index);
|
||||
setTimeout(() => setCopiedIndex(null) , 800);
|
||||
});
|
||||
};
|
||||
|
||||
const { data: chainProperties } = useSWR(
|
||||
client ? ['chainProperties', client] : null,
|
||||
() => client.getChainSpecData(),
|
||||
{
|
||||
revalidateOnFocus: true
|
||||
}
|
||||
);
|
||||
|
||||
const functionArgs = useMemo(() => {
|
||||
if (!txData || !chainProperties) return null;
|
||||
|
||||
try {
|
||||
const decoded = decodeFunctionData({ abi: GatekeeperAbi, data: txData.input });
|
||||
const prefix = chainProperties.properties.ss58Format;
|
||||
const receiverRaw = decoded?.args.at(0);
|
||||
const receiver = receiverRaw ? ss58Encode(receiverRaw, prefix) : null;
|
||||
return { receiver, amount: decoded?.args.at(1) };
|
||||
} catch (err) {}
|
||||
|
||||
try {
|
||||
const decoded = decodeFunctionData({ abi: GhostBondDepositoryAbi, data: txData.input });
|
||||
const prefix = chainProperties.properties.ss58Format;
|
||||
const receiverRaw = decoded?.args.at(0);
|
||||
const receiver = receiverRaw ? ss58Encode(receiverRaw, prefix) : null;
|
||||
return { receiver, amount: 1n, indexes: decoded?.args.at(1) };
|
||||
} catch (err) {
|
||||
return null;
|
||||
}
|
||||
}, [txData, chainProperties]);
|
||||
|
||||
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: loomState } = useSWR(
|
||||
casperApi ? ['loomState', casperApi, chainId] : null,
|
||||
async () => {
|
||||
const key = BigInt(chainId);
|
||||
const res = await casperApi.query.GhostWeaver.LoomStates.getValue(key, 0n);
|
||||
return res;
|
||||
},
|
||||
{
|
||||
refreshInterval: 12000,
|
||||
revalidateOnFocus: true
|
||||
}
|
||||
);
|
||||
|
||||
const chainInfo = useMemo(() => {
|
||||
const client = config?.getClient();
|
||||
return {
|
||||
url: client?.chain?.blockExplorers?.default?.url,
|
||||
symbol: client?.chain?.nativeCurrency?.symbol,
|
||||
};
|
||||
}, [config]);
|
||||
|
||||
const { data: receipt, isLoading, error } = useTransactionReceipt({
|
||||
hash: historyRecord?.txHash,
|
||||
query: {
|
||||
enabled: !!historyRecord?.txHash && isOpen,
|
||||
}
|
||||
});
|
||||
|
||||
const allDecodedLogs = useMemo(() => {
|
||||
if (!receipt?.logs) return [];
|
||||
|
||||
return receipt.logs.map((log) => {
|
||||
try {
|
||||
const decodedERC20 = decodeEventLog({
|
||||
abi: ERC20TokenAbi,
|
||||
data: log.data,
|
||||
topics: log.topics,
|
||||
});
|
||||
|
||||
return {
|
||||
eventName: decodedERC20.eventName,
|
||||
args: decodedERC20.args,
|
||||
address: log.address,
|
||||
};
|
||||
} catch (e) { }
|
||||
|
||||
try {
|
||||
const decodedGatekeeper = decodeEventLog({
|
||||
abi: GatekeeperAbi,
|
||||
data: log.data,
|
||||
topics: log.topics,
|
||||
});
|
||||
|
||||
return {
|
||||
eventName: decodedGatekeeper.eventName,
|
||||
args: decodedGatekeeper.args,
|
||||
address: log.address,
|
||||
};
|
||||
} catch (e) { }
|
||||
|
||||
return null;
|
||||
}).filter(Boolean);
|
||||
}, [receipt]);
|
||||
|
||||
const bridgeInInfo = useMemo(() => {
|
||||
return allDecodedLogs.find(l => l.eventName === 'ThreadInserted');
|
||||
}, [allDecodedLogs]);
|
||||
|
||||
const transferInfo = useMemo(() => {
|
||||
return allDecodedLogs.find(l => l.eventName === 'Transfer');
|
||||
}, [allDecodedLogs]);
|
||||
|
||||
const { maximumSlots } = useWeaverMaximumSlots(chainId);
|
||||
const { merkleRoot: evmMerkleRoot } = useWeaverRoot(chainId, loomState?.at_block, bridgeInInfo?.args);
|
||||
const { merkleProof } = useWeaverProof(chainId, loomState?.at_block, bridgeInInfo?.args);
|
||||
const { slotValues } = useWeaverSlotValues(chainId, loomState?.at_block, bridgeInInfo?.args);
|
||||
|
||||
const localString = new Date(historyRecord.submitted).toLocaleString();
|
||||
|
||||
const bridgedAmount = useMemo(() => {
|
||||
if (functionArgs && !Object.hasOwn(functionArgs, 'indexes')) {
|
||||
return new DecimalBigNumber(
|
||||
functionArgs.amount,
|
||||
chainProperties?.properties.tokenDecimals ?? 18
|
||||
)
|
||||
} else if (transferInfo) {
|
||||
return new DecimalBigNumber(
|
||||
transferInfo.args.value,
|
||||
chainProperties?.properties.tokenDecimals ?? 18
|
||||
)
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
}, [functionArgs, transferInfo, chainProperties]);
|
||||
|
||||
const estimatedReceived = useMemo(() => {
|
||||
if (!networkData || !chainProperties) return null;
|
||||
|
||||
const hundredPercent = 1000000000n;
|
||||
const incomingShare = networkData ? BigInt(networkData.incoming_share) : 0n;
|
||||
const result = hundredPercent - incomingShare
|
||||
|
||||
if (functionArgs && !Object.hasOwn(functionArgs, 'indexes')) {
|
||||
const value = functionArgs.amount * result / hundredPercent;
|
||||
return new DecimalBigNumber(value, chainProperties.properties.tokenDecimals)
|
||||
} else if (transferInfo) {
|
||||
const value = transferInfo.args.value * result / hundredPercent;
|
||||
return new DecimalBigNumber(value, chainProperties.properties.tokenDecimals)
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
}, [functionArgs, transferInfo, networkData, chainProperties]);
|
||||
|
||||
const estimatedReceiver = useMemo(() => {
|
||||
if (functionArgs) return functionArgs.receiver;
|
||||
if (transferInfo) return transferInfo.args.from;
|
||||
return null
|
||||
}, [functionArgs, transferInfo]);
|
||||
|
||||
const finalization = useMemo(() => {
|
||||
if (!receipt || !blockNumber || !networkData) return null;
|
||||
const finalityDelay = networkData.finality_delay;
|
||||
return Math.max(0, Number(finalityDelay + receipt.blockNumber - blockNumber));
|
||||
}, [receipt, blockNumber, networkData]);
|
||||
|
||||
const rootIncluded = useMemo(() => {
|
||||
if (!loomState || !receipt) return false;
|
||||
return evmMerkleRoot === loomState.root_hash && receipt.blockNumber <= loomState.at_block;
|
||||
}, [loomState, receipt, evmMerkleRoot]);
|
||||
|
||||
const weaverArgs = useMemo(() => {
|
||||
if (!bridgeInInfo) return null;
|
||||
return {
|
||||
sessionIndex: bridgeInInfo.args.session,
|
||||
slotIndex: bridgeInInfo.args.index % maximumSlots,
|
||||
valueIndex: bridgeInInfo.args.index / maximumSlots,
|
||||
};
|
||||
}, [maximumSlots, bridgeInInfo]);
|
||||
|
||||
const pulledThreadKey = useMemo(() => {
|
||||
if (!chainId || !weaverArgs) return "0x0000000000000000000000000000000000000000000000000000000000000000";
|
||||
|
||||
const padU64 = (val) => "0x" + BigInt(val).toString(16).padStart(64, "0");
|
||||
|
||||
const metadata = [
|
||||
padU64(weaverArgs.sessionIndex),
|
||||
padU64(weaverArgs.valueIndex),
|
||||
padU64(weaverArgs.slotIndex),
|
||||
padU64(chainId)
|
||||
].map(hexToBytes);
|
||||
|
||||
let currentHash = metadata[0];
|
||||
|
||||
for (let i = 1; i < metadata.length; i++) {
|
||||
const combined = new Uint8Array(64);
|
||||
combined.set(currentHash, 0);
|
||||
combined.set(metadata[i], 32);
|
||||
currentHash = blake2AsU8a(combined);
|
||||
}
|
||||
|
||||
return bytesToHex(currentHash);
|
||||
}, [chainId, weaverArgs]);
|
||||
|
||||
const { data: threadPulled, mutate: threadPulledMutate } = useSWR(
|
||||
casperApi ? ['threadPulled', casperApi, pulledThreadKey, chainId] : null,
|
||||
async () => {
|
||||
const key = BigInt(chainId);
|
||||
const res = await casperApi.query.GhostWeaver.PulledThreads.getValue(pulledThreadKey);
|
||||
return res;
|
||||
},
|
||||
{
|
||||
revalidateOnFocus: true
|
||||
}
|
||||
);
|
||||
|
||||
const pullCurrentThread = async () => {
|
||||
setIsPending(true);
|
||||
|
||||
try {
|
||||
const txArgs = {
|
||||
network_id: BigInt(chainId),
|
||||
session: weaverArgs.sessionIndex,
|
||||
thread_proof: {
|
||||
type: "EvmThreadProof",
|
||||
value: {
|
||||
slot_index: weaverArgs.valueIndex,
|
||||
proof_index: weaverArgs.slotIndex,
|
||||
receiver: functionArgs.receiver,
|
||||
amount: bridgedAmount._value,
|
||||
proof: merkleProof,
|
||||
slots: slotValues,
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const tx = casperApi.tx.GhostWeaver.pull_thread(txArgs);
|
||||
const bareTx = await tx.getBareTx();
|
||||
|
||||
await executePapiBareTransaction({ client, bareTx });
|
||||
await threadPulledMutate();
|
||||
} finally {
|
||||
setIsPending(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Modal
|
||||
maxWidth="420px"
|
||||
minHeight="200px"
|
||||
open={isOpen}
|
||||
headerContent={
|
||||
<Box display="flex" flexDirection="row">
|
||||
{bridgeInInfo
|
||||
? <Box display="flex" gap="10px">
|
||||
<Typography variant="h5">Bridge-In</Typography>
|
||||
<Link
|
||||
underline="always"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
href={`${chainInfo.url}/tx/${historyRecord.txHash}`}
|
||||
>
|
||||
<Typography variant="h5">
|
||||
{bridgeInInfo ? shorten(historyRecord.txHash, 7, -5) : ""}
|
||||
</Typography>
|
||||
</Link>
|
||||
</Box>
|
||||
: <Typography variant="h5">Parsing Transaction Hash</Typography>
|
||||
}
|
||||
</Box>
|
||||
}
|
||||
onClose={() => isPending ? {} : close()}
|
||||
>
|
||||
<Box display="flex" flexDirection="column">
|
||||
<Box width="100%" gap="5px" display="flex" flexDirection="column" justifyContent="space-between" alignItems="center">
|
||||
<BridgeInProgress
|
||||
submissionBlock={receipt ? receipt.blockNumber : 0}
|
||||
blockNumber={blockNumber}
|
||||
chainId={chainId}
|
||||
casperApi={casperApi}
|
||||
finalization={finalization}
|
||||
loomState={loomState}
|
||||
rootIncluded={rootIncluded}
|
||||
claimed={threadPulled === null}
|
||||
/>
|
||||
|
||||
<Box
|
||||
mt={2}
|
||||
width="100%"
|
||||
display="flex"
|
||||
flexDirection="column"
|
||||
sx={{
|
||||
'& .data-row': {
|
||||
margin: '0px !important',
|
||||
},
|
||||
'& .data-row .MuiTypography-root': {
|
||||
fontSize: '13px !important',
|
||||
}
|
||||
}}
|
||||
>
|
||||
<DataRow
|
||||
title="Submitted"
|
||||
balance={<Typography variant="body1">{localString}</Typography>}
|
||||
tooltip="some description to be added."
|
||||
/>
|
||||
|
||||
<DataRow
|
||||
title="Receiver"
|
||||
tooltip="some description to be added."
|
||||
balance={
|
||||
<Link
|
||||
style={{ display: "flex", flexDirection: "row", justifyContent: "center", alignItems: "center" }}
|
||||
onClick={() => estimatedReceiver ? copyToClipboard(estimatedReceiver, 0) : {}}
|
||||
>
|
||||
<Typography variant="body1">
|
||||
{estimatedReceiver ? shorten(estimatedReceiver, 11, -8) : <Skeleton width="120px" />}
|
||||
</Typography>
|
||||
<GhostStyledIcon
|
||||
sx={{ marginLeft: "5px", width: "12px", height: "12px" }}
|
||||
viewBox="0 0 25 25"
|
||||
component={copiedIndex === 0 ? CheckIcon : ContentPasteIcon}
|
||||
/>
|
||||
</Link>
|
||||
}
|
||||
/>
|
||||
|
||||
<DataRow
|
||||
title="Block Height"
|
||||
tooltip="some description to be added."
|
||||
balance={receipt
|
||||
? <Typography variant="body1">{formatNumber(receipt.blockNumber)}</Typography>
|
||||
: <Skeleton width="120px" />
|
||||
}
|
||||
/>
|
||||
</Box>
|
||||
|
||||
<hr style={{ width: "100%" }} />
|
||||
|
||||
<Box
|
||||
mb="10px"
|
||||
width="100%"
|
||||
display="flex"
|
||||
flexDirection="column"
|
||||
sx={{
|
||||
'& .data-row': {
|
||||
margin: '0px !important',
|
||||
},
|
||||
'& .data-row .MuiTypography-root': {
|
||||
fontSize: '13px !important',
|
||||
}
|
||||
}}
|
||||
>
|
||||
<DataRow
|
||||
title="Gross Bridged"
|
||||
tooltip="some description to be added."
|
||||
balance={bridgedAmount
|
||||
? <Typography variant="body1">
|
||||
{formatCurrency(bridgedAmount.toString(), 5, chainProperties?.properties.tokenSymbol ?? "")}
|
||||
</Typography>
|
||||
: <Skeleton width="120px" />
|
||||
}
|
||||
/>
|
||||
|
||||
<DataRow
|
||||
title="GHOST Fee (Est.)"
|
||||
tooltip="some description to be added."
|
||||
balance={bridgedAmount && estimatedReceived
|
||||
? <Typography variant="body1">
|
||||
{formatCurrency(bridgedAmount.sub(estimatedReceived), 5, chainProperties?.properties.tokenSymbol ?? "")}
|
||||
</Typography>
|
||||
: <Skeleton width="120px" />
|
||||
}
|
||||
/>
|
||||
|
||||
<DataRow
|
||||
title="Net Received"
|
||||
tooltip="some description to be added."
|
||||
balance={estimatedReceived
|
||||
? <Typography variant="body1">
|
||||
{formatCurrency(estimatedReceived.toString(), 5, chainProperties?.properties.tokenSymbol ?? "")}
|
||||
</Typography>
|
||||
: <Skeleton width="120px" />
|
||||
}
|
||||
/>
|
||||
</Box>
|
||||
|
||||
<PrimaryButton
|
||||
fullWidth
|
||||
disabled={
|
||||
(!functionArgs && !transferInfo) ||
|
||||
!rootIncluded ||
|
||||
isPending ||
|
||||
threadPulled === null
|
||||
}
|
||||
onClick={pullCurrentThread}
|
||||
>
|
||||
{isPending
|
||||
? "Pending..."
|
||||
: threadPulled === null ? "Transaction Claimed" : "Claim Bridge-In"
|
||||
}
|
||||
</PrimaryButton>
|
||||
</Box>
|
||||
</Box>
|
||||
</Modal>
|
||||
)
|
||||
}
|
||||
|
||||
const BridgeInProgress = ({ chainId, submissionBlock, claimed, casperApi, finalization, loomState, rootIncluded }) => {
|
||||
const theme = useTheme();
|
||||
|
||||
const { data: weaverAuthorities } = useSWR(
|
||||
casperApi ? ['weaverAuthorities', casperApi] : null,
|
||||
() => casperApi.query.GhostWeaver.Authorities.getValue(),
|
||||
{
|
||||
revalidateOnFocus: true
|
||||
}
|
||||
);
|
||||
|
||||
const { data: networkAttestations } = useSWR(
|
||||
casperApi ? ['networkAttestations', casperApi] : null,
|
||||
async () => {
|
||||
const key = BigInt(chainId);
|
||||
const res = await casperApi.query.GhostWeaver.NetworkAttestations.getValue(key);
|
||||
return res;
|
||||
},
|
||||
{
|
||||
refreshInterval: 12000,
|
||||
revalidateOnFocus: true
|
||||
}
|
||||
);
|
||||
|
||||
const { data: tapestryDraft } = useSWR(
|
||||
casperApi ? ['tapestryDraft', casperApi, chainId] : null,
|
||||
async () => {
|
||||
const key = BigInt(chainId);
|
||||
const res = await casperApi.query.GhostWeaver.TapestryDrafts.getValue(key);
|
||||
return res;
|
||||
},
|
||||
{
|
||||
refreshInterval: 12000,
|
||||
revalidateOnFocus: true
|
||||
}
|
||||
);
|
||||
|
||||
const { data: tapestryStrand } = useSWR(
|
||||
casperApi ? ['tapestryStrand', casperApi, chainId] : null,
|
||||
async () => {
|
||||
const key = BigInt(chainId);
|
||||
const res = await casperApi.query.GhostWeaver.TapestryStrands.getValue(key);
|
||||
return res;
|
||||
},
|
||||
{
|
||||
refreshInterval: 12000,
|
||||
revalidateOnFocus: true
|
||||
}
|
||||
);
|
||||
|
||||
return (
|
||||
<Box p="10px 0" width="100%" display="flex" justifyContent="space-between" alignItems="center">
|
||||
{finalization === null || finalization > 0
|
||||
? <BlockFinalization theme={theme} finalization={finalization} />
|
||||
: <SyncTarget
|
||||
theme={theme}
|
||||
weaverAuthorities={weaverAuthorities}
|
||||
networkAttestations={networkAttestations}
|
||||
rootIncluded={rootIncluded}
|
||||
submissionBlock={submissionBlock}
|
||||
loomState={loomState}
|
||||
tapestryDraft={tapestryDraft}
|
||||
/>
|
||||
}
|
||||
<RootVerification
|
||||
theme={theme}
|
||||
finalization={finalization}
|
||||
rootIncluded={rootIncluded}
|
||||
tapestryDraft={tapestryDraft}
|
||||
tapestryStrand={tapestryStrand}
|
||||
totalAuthorities={weaverAuthorities?.length ?? 0}
|
||||
/>
|
||||
<ProofSubmission claimed={claimed} theme={theme} rootIncluded={rootIncluded} />
|
||||
</Box>
|
||||
)
|
||||
}
|
||||
|
||||
const ProofSubmission = ({ theme, claimed, rootIncluded }) => {
|
||||
return (
|
||||
<Box
|
||||
sx={{
|
||||
transition: "all 0.8s ease",
|
||||
transform: (rootIncluded && !claimed) && "scale(1.2)",
|
||||
color: claimed && theme.colors.primary[300]
|
||||
}}
|
||||
maxWidth="120px"
|
||||
display="flex"
|
||||
flexDirection="column"
|
||||
justifyContent="start"
|
||||
alignItems="center"
|
||||
>
|
||||
<GhostStyledIcon
|
||||
sx={{
|
||||
width: "35px",
|
||||
height: "35px",
|
||||
transformOrigin: "center",
|
||||
animation: (rootIncluded && !claimed) && 'waitingForClaim 4s ease-in-out infinite',
|
||||
'@keyframes waitingForClaim': {
|
||||
'0%, 100%': { opacity: 0.4 },
|
||||
'50%': { opacity: 1 },
|
||||
},
|
||||
}}
|
||||
viewBox="0 0 25 25"
|
||||
component={claimed ? CheckCircleIcon : PendingIcon}
|
||||
/>
|
||||
<Typography variant="caption">Bridge Status</Typography>
|
||||
<Typography variant="caption">
|
||||
{rootIncluded
|
||||
? claimed ? "Success" : "Claim Ready"
|
||||
: "Claim Pending..."
|
||||
}
|
||||
</Typography>
|
||||
</Box>
|
||||
)
|
||||
}
|
||||
|
||||
const RootVerification = ({ theme, finalization, tapestryDraft, rootIncluded, totalAuthorities, tapestryStrand }) => {
|
||||
const finalizationPending = useMemo(() => finalization > 0, [finalization]);
|
||||
|
||||
const rootVerificationText = useMemo(() => {
|
||||
if (rootIncluded) return "Synced";
|
||||
if (!tapestryDraft || finalizationPending) return "Pending...";
|
||||
|
||||
let maxOnesCount = 0;
|
||||
tapestryStrand?.forEach(item => {
|
||||
const dataArray = item[1]?.data || [];
|
||||
const totalOnes = dataArray.reduce((sum, num) => {
|
||||
const onesInNumber = num.toString(2).split('1').length - 1;
|
||||
return sum + onesInNumber;
|
||||
}, 0);
|
||||
|
||||
if (totalOnes > maxOnesCount) {
|
||||
maxOnesCount = totalOnes;
|
||||
}
|
||||
});
|
||||
|
||||
return `${maxOnesCount} / ${totalAuthorities}`;
|
||||
}, [rootIncluded, tapestryDraft, tapestryStrand, totalAuthorities, finalizationPending]);
|
||||
|
||||
return (
|
||||
<Box
|
||||
sx={{
|
||||
transition: "all 0.8s ease",
|
||||
transform: !rootIncluded && !finalizationPending && tapestryDraft && "scale(1.2)",
|
||||
color: (rootIncluded || tapestryDraft) && !finalizationPending && theme.colors.primary[300]
|
||||
}}
|
||||
maxWidth="120px"
|
||||
display="flex"
|
||||
flexDirection="column"
|
||||
justifyContent="start"
|
||||
alignItems="center"
|
||||
>
|
||||
<GhostStyledIcon
|
||||
sx={{
|
||||
width: "35px",
|
||||
height: "35px",
|
||||
transformOrigin: "center",
|
||||
animation: !rootIncluded && tapestryDraft && 'scanFingerPrint 4s ease-in-out infinite',
|
||||
'@keyframes scanFingerPrint': {
|
||||
'0%, 100%': { opacity: 0.4 },
|
||||
'50%': { opacity: 1 },
|
||||
},
|
||||
}}
|
||||
viewBox="0 0 25 25"
|
||||
component={FingerprintIcon}
|
||||
/>
|
||||
<Typography variant="caption">Root Verification</Typography>
|
||||
<Typography variant="caption">{rootVerificationText}</Typography>
|
||||
</Box>
|
||||
)
|
||||
}
|
||||
|
||||
const SyncTarget = ({ weaverAuthorities, networkAttestations, tapestryDraft, submissionBlock, loomState, rootIncluded, theme }) => {
|
||||
const syncTargetText = useMemo(() => {
|
||||
if (rootIncluded) return "Synced";
|
||||
|
||||
if (!tapestryDraft || !tapestryDraft) {
|
||||
const total = weaverAuthorities ? weaverAuthorities.length : 0;
|
||||
const count = networkAttestations
|
||||
? networkAttestations.filter(v => v !== undefined).length
|
||||
: 0;
|
||||
return `${count} / ${total}`
|
||||
}
|
||||
|
||||
if (submissionBlock < tapestryDraft.median) return "Synced";
|
||||
|
||||
return `${formatNumber(Number(submissionBlock - tapestryDraft.median))} blocks behind`;
|
||||
}, [rootIncluded, tapestryDraft, loomState, weaverAuthorities, submissionBlock, networkAttestations]);
|
||||
|
||||
return (
|
||||
<Box
|
||||
sx={{
|
||||
transition: "all 0.8s ease",
|
||||
transform: !rootIncluded && !tapestryDraft && "scale(1.2)",
|
||||
color: (rootIncluded || !tapestryDraft) && theme.colors.primary[300]
|
||||
}}
|
||||
maxWidth="120px"
|
||||
display="flex"
|
||||
flexDirection="column"
|
||||
justifyContent="start"
|
||||
alignItems="center"
|
||||
>
|
||||
<GhostStyledIcon
|
||||
sx={{
|
||||
width: "35px",
|
||||
height: "35px",
|
||||
transformOrigin: "center",
|
||||
animation: !rootIncluded && !tapestryDraft && 'rotateSyncTarget 2s ease-in-out infinite',
|
||||
'@keyframes rotateSyncTarget': {
|
||||
'0%': { transform: 'rotate(0deg)' },
|
||||
'100%': { transform: 'rotate(-360deg)' },
|
||||
},
|
||||
}}
|
||||
viewBox="0 0 25 25"
|
||||
component={SyncIcon}
|
||||
/>
|
||||
<Typography variant="caption">Sync Target</Typography>
|
||||
<Typography variant="caption">{syncTargetText}</Typography>
|
||||
</Box>
|
||||
)
|
||||
}
|
||||
|
||||
const BlockFinalization = ({ finalization, theme }) => {
|
||||
return (
|
||||
<Box
|
||||
sx={{
|
||||
transition: "all 0.8s ease",
|
||||
transform: finalization && finalization > 0 && "scale(1.2)",
|
||||
color: finalization === 0 && theme.colors.primary[300]
|
||||
}}
|
||||
maxWidth="120px"
|
||||
display="flex"
|
||||
flexDirection="column"
|
||||
justifyContent="start"
|
||||
alignItems="center"
|
||||
>
|
||||
<GhostStyledIcon
|
||||
sx={{
|
||||
width: "35px",
|
||||
height: "35px",
|
||||
animation: finalization && finalization > 0 && 'rotateHourGlass 2s ease-in-out infinite',
|
||||
'@keyframes rotateHourGlass': {
|
||||
'0%': { transform: 'rotate(0deg)' },
|
||||
'15%': { transform: 'rotate(0deg)' },
|
||||
'85%': { transform: 'rotate(180deg)' },
|
||||
'100%': { transform: 'rotate(180deg)' },
|
||||
},
|
||||
}}
|
||||
viewBox="0 0 25 25"
|
||||
component={HourglassBottomIcon}
|
||||
/>
|
||||
<Typography variant="caption">Finalization</Typography>
|
||||
<Typography variant="caption">
|
||||
{(finalization ?? 0).toString()} blocks left
|
||||
</Typography>
|
||||
</Box>
|
||||
)
|
||||
}
|
||||
|
||||
export default BridgeInModal;
|
||||
601
src/containers/History/BridgeOutModal.jsx
Normal file
601
src/containers/History/BridgeOutModal.jsx
Normal file
@ -0,0 +1,601 @@
|
||||
import useSWR from "swr";
|
||||
import { getAddress } from 'viem';
|
||||
import { useMemo, useState } from "react";
|
||||
import { Box, Typography, Link, Skeleton, useTheme } from "@mui/material";
|
||||
import { useUnstableProvider } from "../../hooks/ghost";
|
||||
import { useLocalStorage } from "../../hooks/localstorage";
|
||||
|
||||
import { Binary } from "polkadot-api";
|
||||
import { blake2AsU8a } from '@polkadot/util-crypto';
|
||||
import { fromHex, toHex } from '@polkadot-api/utils';
|
||||
import { useParams, useNavigate } from "react-router-dom";
|
||||
|
||||
import CheckIcon from '@mui/icons-material/Check';
|
||||
import ContentPasteIcon from '@mui/icons-material/ContentPaste';
|
||||
import HandshakeIcon from '@mui/icons-material/Handshake';
|
||||
import GppGoodIcon from '@mui/icons-material/GppGood';
|
||||
import CasinoIcon from '@mui/icons-material/Casino';
|
||||
import AddModeratorIcon from '@mui/icons-material/AddModerator';
|
||||
|
||||
import Modal from "../../components/Modal/Modal";
|
||||
import DataRow from "../../components/DataRow/DataRow";
|
||||
import GhostStyledIcon from "../../components/Icon/GhostIcon";
|
||||
import InfoTooltip from "../../components/Tooltip/InfoTooltip";
|
||||
import { PrimaryButton } from "../../components/Button";
|
||||
|
||||
import { DecimalBigNumber } from "../../helpers/DecimalBigNumber";
|
||||
import { useIsTransactionExecuted, useGatekeeperAddress, verifySignature } from "../../hooks/staking";
|
||||
import { countBitmapOnes, shorten, formatNumber, formatCurrency } from "../../helpers";
|
||||
|
||||
const BridgeOutModal = ({ chainId, isOpen, close, config, address, historyRecord }) => {
|
||||
const navigate = useNavigate();
|
||||
const { network } = useParams();
|
||||
|
||||
const [isPending, setIsPending] = useState(false);
|
||||
const [copiedIndex, setCopiedIndex] = useState(null);
|
||||
|
||||
const { tryStoreInHistory, CONSTANTS } = useLocalStorage();
|
||||
const { casperApi, client, account } = useUnstableProvider();
|
||||
|
||||
const copyToClipboard = (text, index) => {
|
||||
navigator.clipboard.writeText(text).then(() => {
|
||||
setCopiedIndex(index);
|
||||
setTimeout(() => setCopiedIndex(null) , 800);
|
||||
});
|
||||
};
|
||||
|
||||
const {
|
||||
isTransactionExecuted,
|
||||
isTransactionExecutedLoading,
|
||||
refetchTransactionExecuted
|
||||
} = useIsTransactionExecuted(chainId, historyRecord.txHash.exodusSession);
|
||||
|
||||
const { gatekeeperAddress } = useGatekeeperAddress(chainId);
|
||||
|
||||
const localString = new Date(historyRecord.submitted).toLocaleString();
|
||||
|
||||
const { data: chainProperties } = useSWR(
|
||||
client ? ['chainProperties', client] : null,
|
||||
() => client.getChainSpecData(),
|
||||
{
|
||||
revalidateOnFocus: true
|
||||
}
|
||||
);
|
||||
|
||||
const { data: extrinsic } = useSWR(
|
||||
client && historyRecord?.txHash ? ["extrinsic", historyRecord.txHash] : null,
|
||||
async ([, txMetadata]) => {
|
||||
const { blockHash, txHash } = txMetadata;
|
||||
|
||||
const blockData = await client._request("chain_getBlock", [blockHash]);
|
||||
const extrinsics = blockData?.block?.extrinsics ?? [];
|
||||
|
||||
for (let i = 0; i < extrinsics.length; i++) {
|
||||
const computedHash = toHex(blake2AsU8a(fromHex(extrinsics[i]))).toLowerCase();
|
||||
if (computedHash === txHash.toLowerCase()) return extrinsics[i];
|
||||
}
|
||||
return null;
|
||||
},
|
||||
{
|
||||
revalidateOnFocus: false,
|
||||
shouldRetryOnError: false,
|
||||
},
|
||||
);
|
||||
|
||||
const skipCompact = (bytes, offset) => {
|
||||
const mode = bytes[offset] & 0x03;
|
||||
if (mode === 0) return offset + 1;
|
||||
if (mode === 1) return offset + 2;
|
||||
if (mode === 2) return offset + 4;
|
||||
return offset + 1 + (bytes[offset] >> 2);
|
||||
};
|
||||
|
||||
const extractCallData = (extrinsicHex) => {
|
||||
const bytes = fromHex(extrinsicHex);
|
||||
let offset = skipCompact(bytes, 0);
|
||||
const version = bytes[offset++];
|
||||
|
||||
if (version & 0x80) {
|
||||
offset += bytes[offset] === 0x00 ? 33 : 21;
|
||||
offset += bytes[offset] === 0x02 ? 66 : 65;
|
||||
offset += bytes[offset] === 0x00 ? 1 : 2;
|
||||
offset = skipCompact(bytes, offset);
|
||||
offset = skipCompact(bytes, offset);
|
||||
}
|
||||
|
||||
return bytes.slice(offset);
|
||||
};
|
||||
|
||||
const { data: decodedArgs, isLoading, error: decodeError } = useSWR(
|
||||
casperApi && extrinsic ? ["decodedArgs", extrinsic] : null,
|
||||
async ([, extHex]) => {
|
||||
const callDataBytes = extractCallData(extHex);
|
||||
const tx = await casperApi.txFromCallData(Binary.fromHex(toHex(callDataBytes)));
|
||||
|
||||
return {
|
||||
pallet: tx.decodedCall.type,
|
||||
call: tx.decodedCall.value.type,
|
||||
args: tx.decodedCall.value.value,
|
||||
};
|
||||
},
|
||||
{
|
||||
revalidateOnFocus: false,
|
||||
shouldRetryOnError: false,
|
||||
},
|
||||
);
|
||||
|
||||
const { data: signedBridge, error: signedBridgeError } = useSWR(
|
||||
casperApi && historyRecord && chainId ? ["signedBridge"] : null,
|
||||
() => casperApi.query.GhostExodus.ExodusSignedBridges.getValue(
|
||||
historyRecord.txHash.dkgIndex,
|
||||
{
|
||||
session: BigInt(historyRecord.txHash.exodusSession),
|
||||
network_id: BigInt(chainId)
|
||||
}
|
||||
),
|
||||
{
|
||||
refreshInterval: 12000,
|
||||
revalidateOnFocus: true,
|
||||
}
|
||||
);
|
||||
|
||||
const { data: roastSessionStates } = useSWR(
|
||||
casperApi && historyRecord && chainId ? ["roastSessionStates"] : null,
|
||||
() => casperApi.query.GhostExodus.RoastSessionStates.getEntries(
|
||||
{
|
||||
session: BigInt(historyRecord.txHash.exodusSession),
|
||||
network_id: BigInt(chainId)
|
||||
}
|
||||
),
|
||||
{
|
||||
refreshInterval: 12000,
|
||||
revalidateOnFocus: true,
|
||||
}
|
||||
);
|
||||
|
||||
const { data: previousDkgExodusSession, isLoading: previousDkgExodusSessionLoading } = useSWR(
|
||||
casperApi && historyRecord
|
||||
? ["previousDkgExodusSession", casperApi, historyRecord.txHash.dkgIndex]
|
||||
: null,
|
||||
async ([_, api, startIndex]) => {
|
||||
if (startIndex < 0) return null;
|
||||
|
||||
let previousDkgIndex = startIndex;
|
||||
for (let idx = startIndex; idx >= 0; idx--) {
|
||||
const entry = await casperApi.query.GhostExodus.ExodusSignedRotations.getValue(
|
||||
idx,
|
||||
{ type: 'Evm', value: undefined }
|
||||
);
|
||||
|
||||
if (entry) {
|
||||
const [exodusContext, signedMessage] = entry;
|
||||
if (chainId != null && exodusContext.network_id !== BigInt(chainId)) continue;
|
||||
if (exodusContext.session > BigInt(historyRecord.txHash.exodusSession)) {
|
||||
previousDkgIndex = idx;
|
||||
} else {
|
||||
return exodusContext.session;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return null
|
||||
}
|
||||
);
|
||||
|
||||
const { data: evmMessageMetadata, isLoading: evmMessageMetadataLoading, error } = useSWR(
|
||||
client && historyRecord?.txHash ? ['evmMessage', client, historyRecord.txHash] : null,
|
||||
async ([_, client, record]) =>
|
||||
client.getUnsafeApi().apis.ExodusApi.get_evm_bridge_metadata(
|
||||
BigInt(record.dkgIndex),
|
||||
BigInt(chainId),
|
||||
BigInt(record.exodusSession),
|
||||
)
|
||||
);
|
||||
|
||||
const {
|
||||
isTransactionExecuted: previousDkgExecuted,
|
||||
isTransactionExecutedLoading: previousDkgExecutedLoading
|
||||
} = useIsTransactionExecuted(chainId, previousDkgExodusSession);
|
||||
|
||||
const roastProgress = useMemo(() => {
|
||||
if (!roastSessionStates || roastSessionStates.length === 0) {
|
||||
return {
|
||||
tracksCount: 0,
|
||||
nonces: { total: 0, bestTrackIndex: 0, bestTrack: 0, isActive: true },
|
||||
commitment: { total: 0, bestTrackIndex: 0, bestTrack: 0, isActive: false },
|
||||
signature: { total: 0, bestTrackIndex: 0, bestTrack: 0, isActive: false },
|
||||
leadingPhase: 'NonceCommitments',
|
||||
};
|
||||
}
|
||||
|
||||
let noncesTotal = 0;
|
||||
let noncesBest = 0;
|
||||
|
||||
let commitTotal = 0;
|
||||
let commitBest = 0;
|
||||
|
||||
let signTotal = 0;
|
||||
let signBest = 0;
|
||||
|
||||
let noncesBestTrack = 0;
|
||||
let commitBestTrack = 0;
|
||||
let signBestTrack = 0;
|
||||
|
||||
let hasNoncePhase = false;
|
||||
let hasCommitPhase = false;
|
||||
let hasSignPhase = false;
|
||||
|
||||
for (const { keyArgs, value } of roastSessionStates) {
|
||||
const trackIndex = Number(keyArgs[1]);
|
||||
|
||||
const n = countBitmapOnes(value.nonce_committers);
|
||||
const c = countBitmapOnes(value.group_committers);
|
||||
const s = countBitmapOnes(value.partial_signers);
|
||||
|
||||
noncesTotal += n;
|
||||
if (n > noncesBest) { noncesBestTrack = trackIndex; noncesBest = n; }
|
||||
|
||||
commitTotal += c;
|
||||
if (c > commitBest) { commitBestTrack = trackIndex; commitBest = c; }
|
||||
|
||||
signTotal += s;
|
||||
if (s > signBest) { signBestTrack = trackIndex; signBest = s; }
|
||||
|
||||
const statusType = value.status?.type;
|
||||
if (statusType === 'NonceCommitments') hasNoncePhase = true;
|
||||
if (statusType === 'GroupCommitments') hasCommitPhase = true;
|
||||
if (statusType === 'PartialSignatures') hasSignPhase = true;
|
||||
}
|
||||
|
||||
const tracksCount = roastSessionStates.length;
|
||||
|
||||
return {
|
||||
tracksCount,
|
||||
nonces: {
|
||||
total: noncesTotal,
|
||||
bestTrack: noncesBest,
|
||||
bestTrackIndex: noncesBestTrack,
|
||||
isActive: hasNoncePhase,
|
||||
},
|
||||
commitment: {
|
||||
total: commitTotal,
|
||||
bestTrack: commitBest,
|
||||
bestTrackIndex: commitBestTrack,
|
||||
isActive: hasCommitPhase,
|
||||
},
|
||||
signature: {
|
||||
total: signTotal,
|
||||
bestTrack: signBest,
|
||||
bestTrackIndex: signBestTrack,
|
||||
isActive: hasSignPhase,
|
||||
},
|
||||
};
|
||||
}, [roastSessionStates]);
|
||||
|
||||
const amounts = useMemo(() => {
|
||||
const sentAmount = BigInt(decodedArgs?.args?.amount ?? 0n);
|
||||
const bridgeShare = BigInt(historyRecord?.txHash?.share ?? 69000000n);
|
||||
const shareAmount = (sentAmount * bridgeShare) / 1000000000n;
|
||||
const netAmount = sentAmount - shareAmount;
|
||||
|
||||
return {
|
||||
amount: new DecimalBigNumber(sentAmount, chainProperties?.properties.tokenDecimals ?? 18),
|
||||
netAmount: new DecimalBigNumber(netAmount, chainProperties?.properties.tokenDecimals ?? 18),
|
||||
bridgeShare: new DecimalBigNumber(bridgeShare, 7),
|
||||
}
|
||||
}, [decodedArgs, historyRecord, chainProperties]);
|
||||
|
||||
const verifyBridgeOut = async () => {
|
||||
setIsPending(true);
|
||||
|
||||
try {
|
||||
const txHash = await verifySignature({
|
||||
chainId,
|
||||
account: address,
|
||||
gatekeeper: gatekeeperAddress,
|
||||
calldata: toHex(evmMessageMetadata.at(0)),
|
||||
nonce: toHex(evmMessageMetadata.at(1)),
|
||||
signature: toHex(evmMessageMetadata.at(2)),
|
||||
});
|
||||
|
||||
if (txHash) {
|
||||
tryStoreInHistory(chainId, address, CONSTANTS.bond.key, txHash, CONSTANTS.bond.exodus);
|
||||
await refetchTransactionExecuted();
|
||||
}
|
||||
} finally {
|
||||
setIsPending(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Modal
|
||||
maxWidth="420px"
|
||||
minHeight="200px"
|
||||
open={isOpen}
|
||||
headerContent={
|
||||
<Box display="flex" flexDirection="row">
|
||||
{historyRecord && decodedArgs?.args
|
||||
? <Box display="flex" justifyContent="center" gap="0px">
|
||||
{signedBridge
|
||||
? <Typography variant="h5">Bridge-Out Signed</Typography>
|
||||
: <>
|
||||
<Typography variant="h5">
|
||||
Bridge-Out [{roastProgress.tracksCount} Track{roastProgress.tracksCount > 0 ? "s" : ""}]
|
||||
</Typography>
|
||||
<InfoTooltip
|
||||
variant="h5"
|
||||
message="Parallel ROAST signing tracks are racing to reach the validator threshold."
|
||||
/>
|
||||
</>
|
||||
}
|
||||
</Box>
|
||||
: <Typography variant="h5">Parsing Transaction Hash</Typography>
|
||||
}
|
||||
</Box>
|
||||
}
|
||||
onClose={() => !isPending ? close() : {}}
|
||||
>
|
||||
<Box display="flex" flexDirection="column">
|
||||
<Box width="100%" gap="5px" display="flex" flexDirection="column" justifyContent="space-between" alignItems="center">
|
||||
<BridgeOutProgress
|
||||
chainId={chainId}
|
||||
casperApi={casperApi}
|
||||
signedBridge={signedBridge}
|
||||
roastProgress={roastProgress}
|
||||
dkgIndex={historyRecord.txHash.dkgIndex}
|
||||
exodusSession={historyRecord.txHash.exodusSession}
|
||||
isExecuted={isTransactionExecuted && !isTransactionExecutedLoading}
|
||||
/>
|
||||
|
||||
<Box
|
||||
mt={2}
|
||||
width="100%"
|
||||
display="flex"
|
||||
flexDirection="column"
|
||||
sx={{
|
||||
'& .data-row': {
|
||||
margin: '0px !important',
|
||||
},
|
||||
'& .data-row .MuiTypography-root': {
|
||||
fontSize: '13px !important',
|
||||
}
|
||||
}}
|
||||
>
|
||||
<DataRow
|
||||
title="Submitted"
|
||||
balance={<Typography variant="body1">{localString}</Typography>}
|
||||
tooltip="some description to be added."
|
||||
/>
|
||||
|
||||
<DataRow
|
||||
title="Receiver"
|
||||
tooltip="some description to be added."
|
||||
balance={
|
||||
<Link
|
||||
style={{ display: "flex", flexDirection: "row", justifyContent: "center", alignItems: "center" }}
|
||||
onClick={() => decodedArgs?.args.receiver
|
||||
? copyToClipboard(getAddress(decodedArgs.args.receiver), 0)
|
||||
: {}
|
||||
}
|
||||
>
|
||||
<Typography variant="body1">
|
||||
{decodedArgs?.args.receiver
|
||||
? shorten(getAddress(decodedArgs.args.receiver), 11, -8)
|
||||
: <Skeleton width="120px" />
|
||||
}
|
||||
</Typography>
|
||||
<GhostStyledIcon
|
||||
sx={{ marginLeft: "5px", width: "12px", height: "12px" }}
|
||||
viewBox="0 0 25 25"
|
||||
component={copiedIndex === 0 ? CheckIcon : ContentPasteIcon}
|
||||
/>
|
||||
</Link>
|
||||
}
|
||||
/>
|
||||
|
||||
<DataRow
|
||||
title="Exodus Session"
|
||||
tooltip="some description to be added."
|
||||
balance={historyRecord?.txHash?.exodusSession
|
||||
? <Typography variant="body1">{formatNumber(historyRecord.txHash.exodusSession)}</Typography>
|
||||
: <Skeleton width="120px" />
|
||||
}
|
||||
/>
|
||||
</Box>
|
||||
|
||||
<hr style={{ width: "100%" }} />
|
||||
|
||||
<Box
|
||||
mb="10px"
|
||||
width="100%"
|
||||
display="flex"
|
||||
flexDirection="column"
|
||||
sx={{
|
||||
'& .data-row': {
|
||||
margin: '0px !important',
|
||||
},
|
||||
'& .data-row .MuiTypography-root': {
|
||||
fontSize: '13px !important',
|
||||
}
|
||||
}}
|
||||
>
|
||||
<DataRow
|
||||
title="Gross Bridged"
|
||||
tooltip="some description to be added."
|
||||
balance={formatCurrency(amounts.amount, 5, chainProperties?.properties.tokenSymbol ?? "")}
|
||||
/>
|
||||
|
||||
<DataRow
|
||||
title="GHOST Fee (Est.)"
|
||||
tooltip="some description to be added."
|
||||
balance={<Typography variant="body1">{formatNumber(amounts.bridgeShare, 2)}%</Typography>}
|
||||
/>
|
||||
|
||||
<DataRow
|
||||
title="Net Received"
|
||||
tooltip="some description to be added."
|
||||
balance={formatCurrency(amounts.netAmount.toString(), 5, chainProperties?.properties.tokenSymbol ?? "")}
|
||||
/>
|
||||
</Box>
|
||||
|
||||
<PrimaryButton
|
||||
fullWidth
|
||||
disabled={isPending || !decodedArgs || !previousDkgExecuted || isTransactionExecuted || !signedBridge}
|
||||
onClick={() => !previousDkgExecuted ? navigate(`/${network}/exodus`) : verifyBridgeOut() }
|
||||
>
|
||||
{isPending
|
||||
? "Pending..."
|
||||
: isTransactionExecuted
|
||||
? "Bridge-Out Finished"
|
||||
: previousDkgExecuted ? "Verify Bridge-Out" : "DKG Rotations Needed"
|
||||
}
|
||||
</PrimaryButton>
|
||||
</Box>
|
||||
</Box>
|
||||
</Modal>
|
||||
)
|
||||
}
|
||||
|
||||
const BridgeOutProgress = ({ isExecuted, roastProgress, signedBridge, dkgIndex, exodusSession, chainId }) => {
|
||||
const theme = useTheme();
|
||||
return (
|
||||
<Box
|
||||
p="10px 0"
|
||||
width="100%"
|
||||
display="flex"
|
||||
justifyContent={signedBridge ? "center" : "space-between"}
|
||||
alignItems="center"
|
||||
>
|
||||
{!signedBridge && <>
|
||||
<NonceCommitments roastProgress={roastProgress} theme={theme} />
|
||||
<GroupCommitments roastProgress={roastProgress} theme={theme} />
|
||||
</>}
|
||||
<SignatureShares
|
||||
isExecuted={isExecuted}
|
||||
signedBridge={signedBridge}
|
||||
roastProgress={roastProgress}
|
||||
theme={theme}
|
||||
/>
|
||||
</Box>
|
||||
)
|
||||
}
|
||||
|
||||
const NonceCommitments = ({ roastProgress, theme }) => {
|
||||
return (
|
||||
<Box
|
||||
sx={{
|
||||
transition: "all 0.8s ease",
|
||||
transform: roastProgress.nonces.isActive ?? "scale(1.2)",
|
||||
color: (roastProgress.commitment.isActive || roastProgress.signature.isActive) && theme.colors.primary[300]
|
||||
}}
|
||||
maxWidth="120px"
|
||||
display="flex"
|
||||
flexDirection="column"
|
||||
justifyContent="start"
|
||||
alignItems="center"
|
||||
>
|
||||
<GhostStyledIcon
|
||||
sx={{
|
||||
width: "35px",
|
||||
height: "35px",
|
||||
animation: roastProgress.nonces.isActive ?? 'rotateDice 2s ease-in-out infinite',
|
||||
'@keyframes rotateDice': {
|
||||
'0%': { transform: 'rotate(0deg)' },
|
||||
'50%': { transform: 'rotate(180deg)' },
|
||||
'100%': { transform: 'rotate(180deg)' },
|
||||
},
|
||||
}}
|
||||
viewBox="0 0 24 24"
|
||||
component={CasinoIcon}
|
||||
/>
|
||||
<Typography variant="caption">Nonces</Typography>
|
||||
<Typography variant="caption">
|
||||
{`${roastProgress.nonces.bestTrack} on Track #${roastProgress.nonces.bestTrackIndex}`}
|
||||
</Typography>
|
||||
</Box>
|
||||
)
|
||||
}
|
||||
|
||||
const GroupCommitments = ({ theme, roastProgress }) => {
|
||||
return (
|
||||
<Box
|
||||
sx={{
|
||||
transition: "all 0.8s ease",
|
||||
transform: roastProgress.commitment.isActive ?? "scale(1.2)",
|
||||
color: roastProgress.signature.isActive && theme.colors.primary[300]
|
||||
}}
|
||||
maxWidth="120px"
|
||||
display="flex"
|
||||
flexDirection="column"
|
||||
justifyContent="start"
|
||||
alignItems="center"
|
||||
>
|
||||
<GhostStyledIcon
|
||||
sx={{
|
||||
width: "35px",
|
||||
height: "35px",
|
||||
transformOrigin: "center",
|
||||
animation: roastProgress.commitment.isActive ?? 'shakeHands 2.2s ease-in-out infinite',
|
||||
'@keyframes shakeHands': {
|
||||
'0%, 100%': { transform: 'translateY(0) rotate(0deg)' },
|
||||
'20%': { transform: 'translateY(-3px) rotate(-6deg)' },
|
||||
'40%': { transform: 'translateY(2px) rotate(6deg)' },
|
||||
'60%': { transform: 'translateY(-2px) rotate(-4deg)' },
|
||||
'80%': { transform: 'translateY(0) rotate(0deg)' },
|
||||
},
|
||||
}}
|
||||
viewBox="0 0 25 25"
|
||||
component={HandshakeIcon}
|
||||
/>
|
||||
<Typography variant="caption">Commitment</Typography>
|
||||
<Typography variant="caption">
|
||||
{`${roastProgress.commitment.bestTrack} on Track #${roastProgress.commitment.bestTrackIndex}`}
|
||||
</Typography>
|
||||
</Box>
|
||||
)
|
||||
}
|
||||
|
||||
const SignatureShares = ({ signedBridge, theme, roastProgress, isExecuted }) => {
|
||||
return (
|
||||
<Box
|
||||
sx={{
|
||||
transition: "all 0.8s ease",
|
||||
transform: (roastProgress.signature.isActive || signedBridge) && "scale(1.2)",
|
||||
color: (roastProgress.signature.isActive || signedBridge) && theme.colors.primary[300]
|
||||
}}
|
||||
maxWidth={!signedBridge ? "120px" : "180px"}
|
||||
display="flex"
|
||||
flexDirection="column"
|
||||
justifyContent="start"
|
||||
alignItems="center"
|
||||
>
|
||||
<GhostStyledIcon
|
||||
sx={{
|
||||
width: signedBridge ? "60px" : "35px",
|
||||
height: signedBridge ? "60px" : "35px",
|
||||
transformOrigin: "center",
|
||||
animation: roastProgress.signature.isActive ?? 'pulseShield 2.4s ease-in-out infinite',
|
||||
'@keyframes pulseShield': {
|
||||
'0%, 100%': {
|
||||
transform: 'scale(1)',
|
||||
filter: 'drop-shadow(0 0 0px rgba(245, 208, 66, 0))',
|
||||
},
|
||||
'50%': {
|
||||
transform: 'scale(1.08)',
|
||||
filter: 'drop-shadow(0 0 8px rgba(245, 208, 66, 0.7))',
|
||||
},
|
||||
},
|
||||
}}
|
||||
viewBox="0 0 25 25"
|
||||
component={isExecuted ? GppGoodIcon : AddModeratorIcon }
|
||||
/>
|
||||
<Typography variant={signedBridge ? "body1" : "caption"}>Signature</Typography>
|
||||
<Typography variant={signedBridge ? "body1" : "caption"}>{!signedBridge
|
||||
? `${roastProgress.signature.bestTrack} on Track #${roastProgress.signature.bestTrackIndex}`
|
||||
: isExecuted ? "Already Verified" : "Ready for Verification"
|
||||
}</Typography>
|
||||
</Box>
|
||||
)
|
||||
}
|
||||
|
||||
export default BridgeOutModal;
|
||||
359
src/containers/History/DexViewModal.jsx
Normal file
359
src/containers/History/DexViewModal.jsx
Normal file
@ -0,0 +1,359 @@
|
||||
import { useTransactionReceipt, useToken } from 'wagmi';
|
||||
import { decodeEventLog } from 'viem';
|
||||
import { useMemo } from "react";
|
||||
|
||||
import ArrowRightIcon from '@mui/icons-material/ArrowRight';
|
||||
import { Box, Typography, Link } from "@mui/material";
|
||||
|
||||
import Modal from "../../components/Modal/Modal";
|
||||
import GhostStyledIcon from "../../components/Icon/GhostIcon";
|
||||
import { PrimaryButton } from "../../components/Button";
|
||||
|
||||
import { abi as UniswapV2PairAbi } from "../../abi/UniswapV2Pair.json";
|
||||
import { formatNumber, formatCurrency, shorten } from "../../helpers";
|
||||
import { DecimalBigNumber } from "../../helpers/DecimalBigNumber";
|
||||
import { useLocalStorage } from "../../hooks/localstorage";
|
||||
|
||||
import TokenBox from "./TokenBox";
|
||||
|
||||
const DexSwapViewModal = ({ chainId, isOpen, close, config, historyRecord }) => {
|
||||
if (historyRecord === null) return null;
|
||||
|
||||
const { data: receipt } = useTransactionReceipt({
|
||||
hash: historyRecord?.txHash,
|
||||
query: {
|
||||
enabled: !!historyRecord?.txHash && isOpen,
|
||||
}
|
||||
});
|
||||
|
||||
const allDecodedLogs = useMemo(() => {
|
||||
if (!receipt?.logs) return [];
|
||||
|
||||
return receipt.logs.map((log) => {
|
||||
try {
|
||||
const decoded = decodeEventLog({
|
||||
abi: UniswapV2PairAbi,
|
||||
data: log.data,
|
||||
topics: log.topics,
|
||||
});
|
||||
|
||||
return {
|
||||
eventName: decoded.eventName,
|
||||
args: decoded.args,
|
||||
address: log.address
|
||||
};
|
||||
} catch (e) {
|
||||
return null;
|
||||
}
|
||||
}).filter(Boolean);
|
||||
}, [receipt]);
|
||||
|
||||
const swapInfo = useMemo(() => {
|
||||
const swapEvent = allDecodedLogs.find(l => l.eventName === 'Swap');
|
||||
if (!swapEvent) return null;
|
||||
|
||||
const isZeroForOne = swapEvent.args.amount0In > 0n;
|
||||
|
||||
const transferLogs = allDecodedLogs.filter(l => l.eventName === 'Transfer');
|
||||
|
||||
const tokenInAddress = isZeroForOne
|
||||
? transferLogs.find(t => t.args.value === swapEvent.args.amount0In)?.address
|
||||
: transferLogs.find(t => t.args.value === swapEvent.args.amount1In)?.address;
|
||||
|
||||
const tokenOutAddress = isZeroForOne
|
||||
? transferLogs.find(t => t.args.value === swapEvent.args.amount1Out)?.address
|
||||
: transferLogs.find(t => t.args.value === swapEvent.args.amount0Out)?.address;
|
||||
|
||||
return {
|
||||
from: swapEvent.args.sender,
|
||||
to: swapEvent.args.to,
|
||||
tokenInAddress,
|
||||
tokenOutAddress,
|
||||
amountIn: isZeroForOne ? swapEvent.args.amount0In : swapEvent.args.amount1In,
|
||||
amountOut: isZeroForOne ? swapEvent.args.amount1Out : swapEvent.args.amount0Out,
|
||||
};
|
||||
}, [allDecodedLogs]);
|
||||
|
||||
const { data: tokenIn } = useToken({
|
||||
address: swapInfo?.tokenInAddress,
|
||||
scopeKey: `token-${swapInfo ? swapInfo.tokenInAddress : ""}-${chainId}`,
|
||||
chainId
|
||||
});
|
||||
|
||||
const { data: tokenOut } = useToken({
|
||||
address: swapInfo?.tokenOutAddress,
|
||||
scopeKey: `token-${swapInfo ? swapInfo.tokenOutAddress : ""}-${chainId}`,
|
||||
chainId
|
||||
});
|
||||
|
||||
const chainInfo = useMemo(() => {
|
||||
const client = config?.getClient();
|
||||
|
||||
return {
|
||||
url: client?.chain?.blockExplorers?.default?.url,
|
||||
symbol: client?.chain?.nativeCurrency?.symbol,
|
||||
};
|
||||
}, [config]);
|
||||
|
||||
return (
|
||||
<Modal
|
||||
maxWidth="420px"
|
||||
minHeight="200px"
|
||||
open={isOpen}
|
||||
headerText={
|
||||
<>
|
||||
{swapInfo && "DEX Swap"}
|
||||
{!swapInfo && "Parsing Transaction Hash"}
|
||||
</>
|
||||
}
|
||||
onClose={() => close()}
|
||||
>
|
||||
{swapInfo && <Box display="flex" flexDirection="column" gap="15px">
|
||||
<Box width="100%" display="flex" flexDirection="column" justifyContent="space-between" alignItems="flex-start">
|
||||
<Box display="flex" justifyContent="space-between" width="100%">
|
||||
<Typography>{tokenIn ? tokenIn.symbol : "Unknown"} Sender</Typography>
|
||||
<Link
|
||||
href={`${chainInfo.url}/address/${swapInfo ? swapInfo.from : ""}`}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
>
|
||||
<Typography>{swapInfo ? shorten(swapInfo.from, 12, -10) : ""}</Typography>
|
||||
</Link>
|
||||
</Box>
|
||||
|
||||
<Box display="flex" justifyContent="space-between" width="100%">
|
||||
<Typography>{tokenOut ? tokenOut.symbol : "Unknown"} Receiver</Typography>
|
||||
<Link
|
||||
href={`${chainInfo.url}/address/${swapInfo ? swapInfo.to : ""}`}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
>
|
||||
<Typography>{swapInfo ? shorten(swapInfo.to, 12, -10) : ""}</Typography>
|
||||
</Link>
|
||||
</Box>
|
||||
</Box>
|
||||
|
||||
<Box width="100%" display="flex" flexDirection="row" justifyContent="space-around" alignItems="center">
|
||||
<TokenBox
|
||||
tokenAmount={swapInfo ? swapInfo.amountIn : 0n}
|
||||
tokenSymbol={tokenIn ? tokenIn.symbol : "Unknown"}
|
||||
decimals={tokenIn ? tokenIn.decimals : 18}
|
||||
chainTokenSymbol={tokenIn?.symbol.toUpperCase() === "WETH" ? undefined : chainInfo.symbol}
|
||||
/>
|
||||
|
||||
<GhostStyledIcon sx={{ fontSize: '24px' }} component={ArrowRightIcon} />
|
||||
|
||||
<TokenBox
|
||||
tokenAmount={swapInfo ? swapInfo.amountOut : 0n}
|
||||
tokenSymbol={tokenOut ? tokenOut.symbol : "Unknown"}
|
||||
decimals={tokenOut ? tokenOut.decimals : 18}
|
||||
chainTokenSymbol={tokenOut?.symbol.toUpperCase() === "WETH" ? undefined : chainInfo.symbol}
|
||||
/>
|
||||
</Box>
|
||||
|
||||
<PrimaryButton
|
||||
fullWidth
|
||||
component="a"
|
||||
href={`${chainInfo.url}/tx/${historyRecord.txHash}`}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
>
|
||||
View Transaction Details
|
||||
</PrimaryButton>
|
||||
</Box>}
|
||||
</Modal>
|
||||
)
|
||||
}
|
||||
|
||||
const DexAddViewModal = ({ chainId, isOpen, close, config, historyRecord }) => {
|
||||
if (historyRecord === null) return null;
|
||||
|
||||
const { data: receipt } = useTransactionReceipt({
|
||||
hash: historyRecord?.txHash,
|
||||
query: {
|
||||
enabled: !!historyRecord?.txHash && isOpen,
|
||||
}
|
||||
});
|
||||
|
||||
const allDecodedLogs = useMemo(() => {
|
||||
if (!receipt?.logs) return [];
|
||||
|
||||
return receipt.logs.map((log) => {
|
||||
try {
|
||||
const decoded = decodeEventLog({
|
||||
abi: UniswapV2PairAbi,
|
||||
data: log.data,
|
||||
topics: log.topics,
|
||||
});
|
||||
|
||||
return {
|
||||
eventName: decoded.eventName,
|
||||
args: decoded.args,
|
||||
address: log.address
|
||||
};
|
||||
} catch (e) {
|
||||
return null;
|
||||
}
|
||||
}).filter(Boolean);
|
||||
}, [receipt]);
|
||||
|
||||
const mintInfo = useMemo(() => {
|
||||
const mintEvent = allDecodedLogs.find(l => l.eventName === 'Mint');
|
||||
if (!mintEvent) return null;
|
||||
|
||||
const tokenTransfers = allDecodedLogs.filter(
|
||||
l => l.eventName === 'Transfer' && l.address.toLowerCase() !== mintEvent.address.toLowerCase()
|
||||
);
|
||||
|
||||
const lpMintTransfer = allDecodedLogs.find(
|
||||
l =>
|
||||
l.eventName === 'Transfer' &&
|
||||
l.address.toLowerCase() === mintEvent.address.toLowerCase() &&
|
||||
l.args.from === "0x0000000000000000000000000000000000000000"
|
||||
);
|
||||
|
||||
const token0Log = tokenTransfers.find(t => t.args.value === mintEvent.args.amount0);
|
||||
const token1Log = tokenTransfers.find(
|
||||
t => t.args.value === mintEvent.args.amount1 && t !== token0Log
|
||||
);
|
||||
|
||||
return {
|
||||
pairAddress: mintEvent.address,
|
||||
sender: mintEvent.args.sender,
|
||||
recipient: lpMintTransfer?.args?.to || receipt?.from,
|
||||
token0Address: token0Log?.address,
|
||||
token1Address: token1Log?.address,
|
||||
amount0: mintEvent.args.amount0,
|
||||
amount1: mintEvent.args.amount1,
|
||||
lpAmount: lpMintTransfer?.args?.value ?? 0n,
|
||||
};
|
||||
}, [allDecodedLogs, receipt]);
|
||||
|
||||
const { data: token0 } = useToken({
|
||||
address: mintInfo?.token0Address,
|
||||
scopeKey: `token-${mintInfo ? mintInfo.token0Address : ""}-${chainId}`,
|
||||
chainId
|
||||
});
|
||||
|
||||
const { data: token1 } = useToken({
|
||||
address: mintInfo?.token1Address,
|
||||
scopeKey: `token-${mintInfo ? mintInfo.token1Address : ""}-${chainId}`,
|
||||
chainId
|
||||
});
|
||||
|
||||
const chainInfo = useMemo(() => {
|
||||
const client = config?.getClient();
|
||||
|
||||
return {
|
||||
url: client?.chain?.blockExplorers?.default?.url,
|
||||
symbol: client?.chain?.nativeCurrency?.symbol,
|
||||
};
|
||||
}, [config]);
|
||||
|
||||
return (
|
||||
<Modal
|
||||
maxWidth="420px"
|
||||
minHeight="200px"
|
||||
open={isOpen}
|
||||
headerText={
|
||||
<>
|
||||
{mintInfo && "DEX Add Liquidity"}
|
||||
{!mintInfo && "Parsing Transaction Hash"}
|
||||
</>
|
||||
}
|
||||
onClose={() => close()}
|
||||
>
|
||||
{mintInfo && (
|
||||
<Box display="flex" flexDirection="column" gap="15px">
|
||||
<Box width="100%" display="flex" flexDirection="column" justifyContent="space-between" alignItems="flex-start">
|
||||
<Box display="flex" justifyContent="space-between" width="100%">
|
||||
<Typography>Recipient</Typography>
|
||||
<Link
|
||||
href={`${chainInfo.url}/address/${mintInfo.recipient}`}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
>
|
||||
<Typography>{shorten(mintInfo.recipient, 12, -10)}</Typography>
|
||||
</Link>
|
||||
</Box>
|
||||
|
||||
<Box display="flex" justifyContent="space-between" width="100%">
|
||||
<Typography>Liquidity Pool</Typography>
|
||||
<Link
|
||||
href={`${chainInfo.url}/address/${mintInfo.pairAddress}`}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
>
|
||||
<Typography>{shorten(mintInfo.pairAddress, 12, -10)}</Typography>
|
||||
</Link>
|
||||
</Box>
|
||||
|
||||
<Box display="flex" justifyContent="space-between" width="100%">
|
||||
<Typography>Liquidity Amount</Typography>
|
||||
<Typography>{formatCurrency(new DecimalBigNumber(mintInfo.lpAmount, 18), 10, "LP")}</Typography>
|
||||
</Box>
|
||||
</Box>
|
||||
|
||||
<Box width="100%" display="flex" flexDirection="row" justifyContent="space-around" alignItems="center">
|
||||
<TokenBox
|
||||
tokenAmount={mintInfo.amount0}
|
||||
tokenSymbol={token0 ? token0.symbol : "Unknown"}
|
||||
decimals={token0 ? token0.decimals : 18}
|
||||
chainTokenSymbol={token0?.symbol?.toUpperCase() === "WETH" ? undefined : chainInfo.symbol}
|
||||
/>
|
||||
|
||||
<Typography variant="h6">+</Typography>
|
||||
|
||||
<TokenBox
|
||||
tokenAmount={mintInfo.amount1}
|
||||
tokenSymbol={token1 ? token1.symbol : "Unknown"}
|
||||
decimals={token1 ? token1.decimals : 18}
|
||||
chainTokenSymbol={token1?.symbol?.toUpperCase() === "WETH" ? undefined : chainInfo.symbol}
|
||||
/>
|
||||
</Box>
|
||||
|
||||
<PrimaryButton
|
||||
fullWidth
|
||||
component="a"
|
||||
href={`${chainInfo.url}/tx/${historyRecord.txHash}`}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
>
|
||||
View Transaction Details
|
||||
</PrimaryButton>
|
||||
</Box>
|
||||
)}
|
||||
</Modal>
|
||||
)
|
||||
}
|
||||
|
||||
const DexViewModal = ({ chainId, isOpen, close, config, historyRecord }) => {
|
||||
const { CONSTANTS } = useLocalStorage();
|
||||
|
||||
switch (historyRecord.name) {
|
||||
case CONSTANTS.dex.swap:
|
||||
return (
|
||||
<DexSwapViewModal
|
||||
chainId={chainId}
|
||||
isOpen={isOpen}
|
||||
close={close}
|
||||
config={config}
|
||||
historyRecord={historyRecord}
|
||||
/>
|
||||
);
|
||||
case CONSTANTS.dex.add:
|
||||
return (
|
||||
<DexAddViewModal
|
||||
chainId={chainId}
|
||||
isOpen={isOpen}
|
||||
close={close}
|
||||
config={config}
|
||||
historyRecord={historyRecord}
|
||||
/>
|
||||
);
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export default DexViewModal;
|
||||
23
src/containers/History/EraseModal.jsx
Normal file
23
src/containers/History/EraseModal.jsx
Normal file
@ -0,0 +1,23 @@
|
||||
import { Box, Typography } from "@mui/material";
|
||||
|
||||
import Modal from "../../components/Modal/Modal";
|
||||
import { PrimaryButton } from "../../components/Button";
|
||||
|
||||
const EraseModal = ({ isOpen, close, submit, isAll }) => {
|
||||
return (
|
||||
<Modal
|
||||
maxWidth="350px"
|
||||
minHeight="200px"
|
||||
open={isOpen}
|
||||
headerText={`Erase ${isAll ? "All Records" : "Record"}`}
|
||||
onClose={() => close()}
|
||||
>
|
||||
<Box display="flex" flexDirection="column" justifyContent="space-between" gap="20px">
|
||||
<Typography>{`Erasing ${isAll ? "all records" : "this record"} is permanent, and cannot be recovered.`}</Typography>
|
||||
<PrimaryButton fullWidth onClick={submit}>Erase {isAll ? "All Records" : ""}</PrimaryButton>
|
||||
</Box>
|
||||
</Modal>
|
||||
)
|
||||
}
|
||||
|
||||
export default EraseModal;
|
||||
536
src/containers/History/History.jsx
Normal file
536
src/containers/History/History.jsx
Normal file
@ -0,0 +1,536 @@
|
||||
import {
|
||||
Box,
|
||||
Table,
|
||||
TableBody,
|
||||
TableCell,
|
||||
TableContainer,
|
||||
TableHead,
|
||||
TableRow,
|
||||
Typography,
|
||||
Container,
|
||||
FormControlLabel,
|
||||
FormControl,
|
||||
Checkbox,
|
||||
Link,
|
||||
useMediaQuery,
|
||||
useTheme,
|
||||
} from "@mui/material";
|
||||
|
||||
import { useLocation } from "react-router-dom";
|
||||
import { useEffect, useState, useMemo, useCallback } from "react";
|
||||
import useSWR from 'swr';
|
||||
import ReactGA from "react-ga4";
|
||||
import SettingsIcon from '@mui/icons-material/Settings';
|
||||
|
||||
import Modal from "../../components/Modal/Modal";
|
||||
import Paper from "../../components/Paper/Paper";
|
||||
import PageTitle from "../../components/PageTitle/PageTitle";
|
||||
import TokenStack from "../../components/TokenStack/TokenStack";
|
||||
import GhostStyledIcon from "../../components/Icon/GhostIcon";
|
||||
import Chip from "../../components/Chip/Chip";
|
||||
|
||||
import { PrimaryButton, TertiaryButton } from "../../components/Button";
|
||||
import { Tab, Tabs } from "../../components/Tabs/Tabs";
|
||||
|
||||
import { useTokenSymbol } from "../../hooks/tokens";
|
||||
import { useLocalStorage } from "../../hooks/localstorage";
|
||||
import { useUnstableProvider } from "../../hooks/ghost";
|
||||
import { shorten } from "../../helpers";
|
||||
import { networkAvgBlockSpeed } from "../../constants";
|
||||
|
||||
import EraseModal from "./EraseModal";
|
||||
import SettingsModal from "./SettingsModal";
|
||||
import DexViewModal from "./DexViewModal";
|
||||
import StakingViewModal from "./StakingViewModal";
|
||||
import BridgeInModal from "./BridgeInModal";
|
||||
import BridgeOutModal from "./BridgeOutModal";
|
||||
import BondModal from "./BondModal";
|
||||
import AddRecordModal from "./AddRecordModal";
|
||||
|
||||
const HistoryItem = ({
|
||||
item,
|
||||
chainId,
|
||||
config,
|
||||
currentTime,
|
||||
eraseRecord,
|
||||
setViewModalOpen,
|
||||
isSmallScreen,
|
||||
finalityDelay
|
||||
}) => {
|
||||
const theme = useTheme();
|
||||
const isVerySmallScreen = useMediaQuery("(max-width: 450px)");
|
||||
|
||||
const localString = new Date(item.submitted).toLocaleString();
|
||||
const { symbol: ftsoSymbol } = useTokenSymbol(chainId, "FTSO");
|
||||
const { CONSTANTS } = useLocalStorage();
|
||||
|
||||
const chainInfo = useMemo(() => {
|
||||
const client = config?.getClient();
|
||||
return {
|
||||
url: client?.chain?.blockExplorers?.default?.url,
|
||||
symbol: client?.chain?.nativeCurrency?.symbol,
|
||||
};
|
||||
}, [config]);
|
||||
|
||||
const chipStatus = useMemo(() => {
|
||||
const delay = Number(finalityDelay * networkAvgBlockSpeed(chainId)) * 1000;
|
||||
const width = isVerySmallScreen ? "21px" : "100px";
|
||||
|
||||
if (item.submitted + delay > currentTime && item.name !== CONSTANTS.bridgeOut.key) {
|
||||
return <Chip sx={{ width: width }} label={isVerySmallScreen ? "" : "Pending"} template={"gray"} />
|
||||
}
|
||||
|
||||
return <Chip sx={{ width: width }} label={isVerySmallScreen ? "" : "Finalized"} template={"success"} />
|
||||
}, [item, currentTime, isVerySmallScreen, finalityDelay]);
|
||||
|
||||
const txHashMetadata = useMemo(() => {
|
||||
if (!item) return undefined;
|
||||
if (item.name === CONSTANTS.bridgeOut.key) {
|
||||
return {
|
||||
txUrl: `https://app.ghostportal.cc.cd/#/explorer/query/${item.txHash.blockHash}`,
|
||||
txHash: item.txHash.blockHash,
|
||||
}
|
||||
} else {
|
||||
return {
|
||||
txUrl: `${chainInfo.url}/tx/${item.txHash}`,
|
||||
txHash: item.txHash,
|
||||
}
|
||||
}
|
||||
}, [chainInfo, item]);
|
||||
|
||||
if (isSmallScreen || isVerySmallScreen) {
|
||||
return (
|
||||
<>
|
||||
<Box display="flex" flexDirection="column" gap="10px">
|
||||
<Box
|
||||
display="flex"
|
||||
alignItems="center"
|
||||
justifyContent="space-between"
|
||||
flexDirection={isVerySmallScreen ? "row" : "row"}
|
||||
>
|
||||
<Box display="flex" gap="20px" p="10px 0">
|
||||
<TokenStack chainTokenNames={[chainInfo.symbol]} tokens={[ftsoSymbol]} />
|
||||
<Box display="flex" flexDirection="column">
|
||||
<Typography>{localString}</Typography>
|
||||
<Link
|
||||
href={txHashMetadata.txUrl}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
>
|
||||
<Typography>{shorten(txHashMetadata.txHash)}</Typography>
|
||||
</Link>
|
||||
</Box>
|
||||
</Box>
|
||||
|
||||
<Box display="flex" flexDirection="column" alignItems="center">
|
||||
<Typography>{item?.name ?? "Unknown"}{item?.isCustom ? " (Custom)" : ""}</Typography>
|
||||
{chipStatus}
|
||||
</Box>
|
||||
</Box>
|
||||
|
||||
<Box display="flex" flexDirection="row" gap="20px">
|
||||
<TertiaryButton fullWidth onClick={eraseRecord}>Erase</TertiaryButton>
|
||||
<TertiaryButton fullWidth onClick={setViewModalOpen}>View</TertiaryButton>
|
||||
</Box>
|
||||
</Box>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<TableRow>
|
||||
<TableCell sx={{ padding: "10px 0" }}>
|
||||
<Box display="flex" alignItems="center">
|
||||
<TokenStack chainTokenNames={["ETH"]} tokens={[ftsoSymbol]} />
|
||||
<Box ml="10px" display="flex" flexDirection="column" alignItems="flex-start">
|
||||
<Typography>{item?.name ?? "Unknown"}{item?.isCustom ? " (Custom)" : ""}</Typography>
|
||||
<Link
|
||||
href={txHashMetadata.txUrl}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
>
|
||||
<Typography>{shorten(txHashMetadata.txHash, 7, -5)}</Typography>
|
||||
</Link>
|
||||
</Box>
|
||||
</Box>
|
||||
</TableCell>
|
||||
|
||||
<TableCell align="center" sx={{ padding: "10px 0" }}>
|
||||
{chipStatus}
|
||||
</TableCell>
|
||||
|
||||
<TableCell sx={{ padding: "10px 0" }}>
|
||||
<Typography>{localString}</Typography>
|
||||
</TableCell>
|
||||
|
||||
<TableCell sx={{ padding: "10px 0" }}>
|
||||
<Box display="flex" flexDirection="row" gap="20px">
|
||||
<TertiaryButton fullWidth onClick={eraseRecord}>Erase</TertiaryButton>
|
||||
<TertiaryButton fullWidth onClick={setViewModalOpen}>View</TertiaryButton>
|
||||
</Box>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
)
|
||||
}
|
||||
|
||||
const HistoryList = ({ chainId, address, storedTransactions, historyType, config, eraseRecord }) => {
|
||||
const isSmallScreen = useMediaQuery("(max-width: 900px)");
|
||||
|
||||
const [currentTime, setCurrentTime] = useState(Date.now());
|
||||
const [viewModalOpen, setViewModalOpen] = useState(null);
|
||||
|
||||
const { CONSTANTS } = useLocalStorage();
|
||||
const { casperApi } = useUnstableProvider();
|
||||
|
||||
const { data: networkData, error, isLoading } = 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 finalityDelay = useMemo(() => {
|
||||
return networkData ? networkData.finality_delay : 420n;
|
||||
}, [networkData]);
|
||||
|
||||
useEffect(() => {
|
||||
const intervalId = setInterval(() => {
|
||||
setCurrentTime(Date.now());
|
||||
}, 1000);
|
||||
return () => clearInterval(intervalId);
|
||||
}, []);
|
||||
|
||||
const historyContainer = useMemo(() => {
|
||||
if (isSmallScreen) {
|
||||
return (
|
||||
<Box display="flex" flexDirection="column" gap="50px">
|
||||
{storedTransactions?.map((item, i) => {
|
||||
return (
|
||||
<HistoryItem
|
||||
key={i}
|
||||
item={item}
|
||||
config={config}
|
||||
chainId={chainId}
|
||||
currentTime={currentTime}
|
||||
finalityDelay={finalityDelay}
|
||||
eraseRecord={() => eraseRecord(i)}
|
||||
setViewModalOpen={() => setViewModalOpen(i)}
|
||||
isSmallScreen={isSmallScreen}
|
||||
/>
|
||||
)
|
||||
})}
|
||||
</Box>
|
||||
)
|
||||
} else {
|
||||
return (
|
||||
<TableContainer>
|
||||
<Table aria-label="Available bonds" style={{ tableLayout: "fixed" }}>
|
||||
<TableHead>
|
||||
<TableRow>
|
||||
<TableCell style={{ padding: "8px 0" }}>Transaction</TableCell>
|
||||
<TableCell style={{ padding: "8px 0" }} align="center">Status</TableCell>
|
||||
<TableCell style={{ padding: "8px 0" }}>Submitted</TableCell>
|
||||
<TableCell style={{ padding: "8px 0" }}></TableCell>
|
||||
</TableRow>
|
||||
</TableHead>
|
||||
<TableBody>
|
||||
{storedTransactions?.map((item, i) => {
|
||||
return (
|
||||
<HistoryItem
|
||||
key={i}
|
||||
item={item}
|
||||
config={config}
|
||||
chainId={chainId}
|
||||
currentTime={currentTime}
|
||||
finalityDelay={finalityDelay}
|
||||
eraseRecord={() => eraseRecord(i)}
|
||||
setViewModalOpen={() => setViewModalOpen(i)}
|
||||
isSmallScreen={isSmallScreen}
|
||||
/>
|
||||
)
|
||||
})}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</TableContainer>
|
||||
)
|
||||
}
|
||||
}, [isSmallScreen, currentTime, storedTransactions, config]);
|
||||
|
||||
return (
|
||||
<>
|
||||
{viewModalOpen !== null && historyType === CONSTANTS.dex.key && (
|
||||
<DexViewModal
|
||||
chainId={chainId}
|
||||
config={config}
|
||||
close={() => setViewModalOpen(null)}
|
||||
isOpen={true}
|
||||
historyRecord={storedTransactions.at(viewModalOpen)}
|
||||
/>
|
||||
)}
|
||||
|
||||
{viewModalOpen !== null && historyType === CONSTANTS.stake.key && (
|
||||
<StakingViewModal
|
||||
chainId={chainId}
|
||||
config={config}
|
||||
close={() => setViewModalOpen(null)}
|
||||
isOpen={true}
|
||||
historyRecord={storedTransactions.at(viewModalOpen)}
|
||||
/>
|
||||
)}
|
||||
|
||||
{viewModalOpen !== null && historyType === CONSTANTS.bridgeIn.key && (
|
||||
<BridgeInModal
|
||||
chainId={chainId}
|
||||
config={config}
|
||||
close={() => setViewModalOpen(null)}
|
||||
isOpen={true}
|
||||
historyRecord={storedTransactions.at(viewModalOpen)}
|
||||
/>
|
||||
)}
|
||||
|
||||
{viewModalOpen !== null && historyType === CONSTANTS.bridgeOut.key && (
|
||||
<BridgeOutModal
|
||||
chainId={chainId}
|
||||
config={config}
|
||||
close={() => setViewModalOpen(null)}
|
||||
isOpen={true}
|
||||
address={address}
|
||||
historyRecord={storedTransactions.at(viewModalOpen)}
|
||||
/>
|
||||
)}
|
||||
|
||||
{viewModalOpen !== null && historyType === CONSTANTS.bond.key && (
|
||||
<BondModal
|
||||
chainId={chainId}
|
||||
config={config}
|
||||
address={address}
|
||||
close={() => setViewModalOpen(null)}
|
||||
isOpen={true}
|
||||
historyRecord={storedTransactions.at(viewModalOpen)}
|
||||
/>
|
||||
)}
|
||||
|
||||
{historyContainer}
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
const History = ({ chainId, config, tryConnectInjected, address }) => {
|
||||
const isSmallScreen = useMediaQuery("(max-width: 650px)");
|
||||
const isSemiSmallScreen = useMediaQuery("(max-width: 745px)");
|
||||
const isVerySmallScreen = useMediaQuery("(max-width: 379px)");
|
||||
|
||||
const [historyTypeIndex, setHistoryTypeIndex] = useState(0);
|
||||
const [erasingIndex, setErasingIndex] = useState(null);
|
||||
const [settingsOpen, setSettingsOpen] = useState(false);
|
||||
const [erasingOpen, setErasingOpen] = useState(false);
|
||||
const [addRecordOpen, setAddRecordOpen] = useState(false);
|
||||
|
||||
const location = useLocation();
|
||||
|
||||
useEffect(() => {
|
||||
ReactGA.send({ hitType: "pageview", page: location.pathname });
|
||||
}, [location]);
|
||||
|
||||
const {
|
||||
CONSTANTS,
|
||||
useStorageValue,
|
||||
setStorageValue,
|
||||
clearPendingHistory
|
||||
} = useLocalStorage();
|
||||
|
||||
const { data: storedHistoryTypes } = useStorageValue(chainId, address, CONSTANTS.historyPrefix, CONSTANTS.defaultHistoryTypes);
|
||||
const { data: storedTransactions, mutate: storedTransactionsMutate } = useStorageValue(
|
||||
chainId,
|
||||
address,
|
||||
storedHistoryTypes[historyTypeIndex],
|
||||
[]
|
||||
);
|
||||
|
||||
const { data: pendingHistory } = useStorageValue(chainId, address, CONSTANTS.pendingHistoryPrefix, {});
|
||||
|
||||
const handleHistoryTypesChange = useCallback((values) => {
|
||||
setStorageValue(chainId, address, CONSTANTS.historyPrefix, values);
|
||||
}, [chainId, address]);
|
||||
|
||||
const handleConfirmErase = useCallback(() => {
|
||||
if (erasingIndex !== null) {
|
||||
const updated = storedTransactions.filter((_, index) => index !== erasingIndex);
|
||||
setStorageValue(chainId, address, storedHistoryTypes[historyTypeIndex], updated);
|
||||
} else {
|
||||
setStorageValue(chainId, address, storedHistoryTypes[historyTypeIndex], []);
|
||||
}
|
||||
setErasingOpen(false);
|
||||
setErasingIndex(null);
|
||||
}, [storedTransactions, erasingIndex, chainId, address, historyTypeIndex]);
|
||||
|
||||
useEffect(() => {
|
||||
clearPendingHistory(chainId, address, storedHistoryTypes.at(historyTypeIndex));
|
||||
}, [storedHistoryTypes, historyTypeIndex]);
|
||||
|
||||
return (
|
||||
<Box minHeight="calc(100vh - 43px)">
|
||||
<PageTitle name="History" subtitle="Complete record of your ghostDAO activity" />
|
||||
<Container
|
||||
style={{
|
||||
paddingLeft: isSmallScreen || isVerySmallScreen ? "0" : "3.3rem",
|
||||
paddingRight: isSmallScreen || isVerySmallScreen ? "0" : "3.3rem",
|
||||
}}
|
||||
>
|
||||
<EraseModal
|
||||
key="EraseModal"
|
||||
isOpen={erasingOpen}
|
||||
close={() => {
|
||||
setErasingOpen(false);
|
||||
setErasingIndex(null);
|
||||
}}
|
||||
submit={handleConfirmErase}
|
||||
isAll={erasingIndex === null}
|
||||
/>
|
||||
|
||||
<AddRecordModal
|
||||
chainId={chainId}
|
||||
address={address}
|
||||
key="AddRecordModal"
|
||||
isOpen={addRecordOpen}
|
||||
close={() => {
|
||||
setAddRecordOpen(false);
|
||||
storedTransactionsMutate();
|
||||
clearPendingHistory(chainId, address, storedHistoryTypes.at(historyTypeIndex));
|
||||
}}
|
||||
/>
|
||||
|
||||
<SettingsModal
|
||||
key="SettingsModal"
|
||||
isOpen={settingsOpen}
|
||||
close={() => setSettingsOpen(false)}
|
||||
onChange={handleHistoryTypesChange}
|
||||
selectedValues={storedHistoryTypes}
|
||||
possibleValues={CONSTANTS.possibleHistoryTypes}
|
||||
/>
|
||||
|
||||
<Box mt="15px">
|
||||
<Paper
|
||||
fullWidth
|
||||
enableBackground
|
||||
topRight={
|
||||
<Box style={{ position: "absolute", top: "28px", right: "20px", zIndex: 10 }}>
|
||||
<GhostStyledIcon
|
||||
component={SettingsIcon}
|
||||
viewBox="0 0 23 23"
|
||||
style={{ display: "flex", cursor: "pointer" }}
|
||||
onClick={() => setSettingsOpen(true)}
|
||||
/>
|
||||
</Box>
|
||||
}
|
||||
headerContent={
|
||||
<Box
|
||||
width="100%"
|
||||
display="flex"
|
||||
flexDirection="column"
|
||||
justifyContent="space-between"
|
||||
alignItems="center"
|
||||
gap="15px"
|
||||
>
|
||||
<Tabs
|
||||
centered={!isSemiSmallScreen}
|
||||
orientation={isSemiSmallScreen ? "vertical" : "horizontal"}
|
||||
textColor="primary"
|
||||
indicatorColor="primary"
|
||||
value={storedHistoryTypes[historyTypeIndex]}
|
||||
aria-label="History menu"
|
||||
onChange={(_, selectedValue) => {
|
||||
const index = storedHistoryTypes.indexOf(selectedValue);
|
||||
if (index !== -1) setHistoryTypeIndex(index);
|
||||
}}
|
||||
TabIndicatorProps={{ style: { display: "none" } }}
|
||||
>
|
||||
{storedHistoryTypes.map((type, i) => {
|
||||
return (
|
||||
<Tab
|
||||
key={i}
|
||||
value={type}
|
||||
aria-label={`history-${i}-button`}
|
||||
style={{ fontSize: "1.2rem" }}
|
||||
label={
|
||||
<Box display="flex" alignItems="center" gap="5px">
|
||||
<Typography variant="h6">{type}</Typography>
|
||||
{pendingHistory && pendingHistory[type] > 0 && (
|
||||
<Chip
|
||||
template="warning"
|
||||
strong={true}
|
||||
style={{
|
||||
display: "inline-flex",
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
height: "16px",
|
||||
minWidth: "16px",
|
||||
width: "auto",
|
||||
fontSize: "8px",
|
||||
borderRadius: "100%"
|
||||
}}
|
||||
sx={{
|
||||
"& .MuiChip-label": {
|
||||
padding: 0,
|
||||
lineHeight: "16px",
|
||||
display: "block"
|
||||
}
|
||||
}}
|
||||
label={pendingHistory[type]}
|
||||
/>
|
||||
)}
|
||||
</Box>
|
||||
}
|
||||
/>
|
||||
)
|
||||
})}
|
||||
</Tabs>
|
||||
|
||||
<Box
|
||||
display="flex"
|
||||
justifyContent="center"
|
||||
gap={isSmallScreen ? "5px" : "20px"}
|
||||
width={isSmallScreen ? "100%" : "380px"}
|
||||
flexDirection={isSmallScreen ? "column" : "row"}
|
||||
>
|
||||
<TertiaryButton
|
||||
fullWidth
|
||||
onClick={() => setAddRecordOpen(true)}
|
||||
>
|
||||
Add Record
|
||||
</TertiaryButton>
|
||||
|
||||
<PrimaryButton
|
||||
fullWidth
|
||||
onClick={() => setErasingOpen(true)}
|
||||
>
|
||||
Erase All Records
|
||||
</PrimaryButton>
|
||||
</Box>
|
||||
</Box>
|
||||
}
|
||||
>
|
||||
<HistoryList
|
||||
chainId={chainId}
|
||||
config={config}
|
||||
address={address}
|
||||
eraseRecord={(index) => {
|
||||
setErasingIndex(index);
|
||||
setErasingOpen(true);
|
||||
}}
|
||||
historyType={storedHistoryTypes[historyTypeIndex]}
|
||||
storedTransactions={storedTransactions}
|
||||
/>
|
||||
</Paper>
|
||||
</Box>
|
||||
</Container>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
export default History;
|
||||
49
src/containers/History/SettingsModal.jsx
Normal file
49
src/containers/History/SettingsModal.jsx
Normal file
@ -0,0 +1,49 @@
|
||||
import { Box, FormControlLabel, Checkbox, Typography } from "@mui/material";
|
||||
|
||||
import Modal from "../../components/Modal/Modal";
|
||||
import { CheckBoxOutlineBlank, CheckBoxOutlined } from "@mui/icons-material";
|
||||
|
||||
const SettingsModal = ({ isOpen, close, submit, selectedValues, possibleValues, onChange }) => {
|
||||
const handleCheckboxChange = (type, isChecked) => {
|
||||
const updatedTypes = possibleValues.filter(v => {
|
||||
if (v === type) return isChecked
|
||||
return selectedValues.includes(v)
|
||||
})
|
||||
onChange(updatedTypes);
|
||||
};
|
||||
|
||||
return (
|
||||
<Modal
|
||||
key="SettingsModal"
|
||||
maxWidth="320px"
|
||||
minHeight="200px"
|
||||
open={isOpen}
|
||||
headerText="Settings"
|
||||
onClose={() => close()}
|
||||
>
|
||||
<Box display="flex" flexDirection="column" justifyContent="space-between" gap="5px">
|
||||
{possibleValues.map((type, i) => {
|
||||
const isChecked = selectedValues.includes(type);
|
||||
return (
|
||||
<FormControlLabel
|
||||
key={i}
|
||||
control={
|
||||
<Checkbox
|
||||
inputProps={{ "data-testid": `history-type-${type}` }}
|
||||
id={`history-type-${type}`}
|
||||
checked={isChecked}
|
||||
onChange={event => handleCheckboxChange(type, event.target.checked)}
|
||||
icon={<CheckBoxOutlineBlank viewBox="0 0 24 24" />}
|
||||
checkedIcon={<CheckBoxOutlined viewBox="0 0 24 24" />}
|
||||
/>
|
||||
}
|
||||
label={<Typography variant="body1">{type} History</Typography>}
|
||||
/>
|
||||
)
|
||||
})}
|
||||
</Box>
|
||||
</Modal>
|
||||
)
|
||||
}
|
||||
|
||||
export default SettingsModal;
|
||||
133
src/containers/History/StakingViewModal.jsx
Normal file
133
src/containers/History/StakingViewModal.jsx
Normal file
@ -0,0 +1,133 @@
|
||||
import { useTransactionReceipt } from 'wagmi';
|
||||
import { decodeEventLog } from 'viem';
|
||||
import { useMemo } from "react";
|
||||
|
||||
import ArrowRightIcon from '@mui/icons-material/ArrowRight';
|
||||
import { Box, Typography, Link } from "@mui/material";
|
||||
|
||||
import Token from "../../components/Token/Token";
|
||||
import Modal from "../../components/Modal/Modal";
|
||||
import GhostStyledIcon from "../../components/Icon/GhostIcon";
|
||||
import { PrimaryButton } from "../../components/Button";
|
||||
|
||||
import { abi as StakingAbi } from "../../abi/GhostStaking.json";
|
||||
import { DecimalBigNumber } from "../../helpers/DecimalBigNumber";
|
||||
import { formatNumber, shorten } from "../../helpers";
|
||||
|
||||
import { useTokenSymbol } from "../../hooks/tokens";
|
||||
import { getTokenDecimals } from "../../hooks/helpers";
|
||||
import TokenBox from "./TokenBox";
|
||||
|
||||
const StakingViewModal = ({ chainId, isOpen, close, config, historyRecord }) => {
|
||||
if (historyRecord === null) return null;
|
||||
|
||||
const { data: receipt, isLoading, error } = useTransactionReceipt({
|
||||
hash: historyRecord?.txHash,
|
||||
query: {
|
||||
enabled: !!historyRecord?.txHash && isOpen,
|
||||
}
|
||||
});
|
||||
|
||||
const allDecodedLogs = useMemo(() => {
|
||||
if (!receipt?.logs) return [];
|
||||
|
||||
return receipt.logs.map((log) => {
|
||||
try {
|
||||
const decoded = decodeEventLog({
|
||||
abi: StakingAbi,
|
||||
data: log.data,
|
||||
topics: log.topics,
|
||||
});
|
||||
|
||||
return {
|
||||
eventName: decoded.eventName,
|
||||
args: decoded.args,
|
||||
address: log.address
|
||||
};
|
||||
} catch (e) {
|
||||
return null;
|
||||
}
|
||||
}).filter(Boolean);
|
||||
}, [receipt]);
|
||||
|
||||
const stakeInfo = useMemo(() => {
|
||||
return allDecodedLogs.find(l => l.eventName === 'Staked' || l.eventName === 'Unstaked');
|
||||
}, [allDecodedLogs]);
|
||||
|
||||
const { symbol: ftsoSymbol } = useTokenSymbol(chainId, "FTSO");
|
||||
const ftsoDecimals = getTokenDecimals("FTSO");
|
||||
|
||||
const chainInfo = useMemo(() => {
|
||||
const client = config?.getClient();
|
||||
|
||||
return {
|
||||
url: client?.chain?.blockExplorers?.default?.url,
|
||||
symbol: client?.chain?.nativeCurrency?.symbol,
|
||||
};
|
||||
}, [config]);
|
||||
|
||||
return (
|
||||
<Modal
|
||||
maxWidth="420px"
|
||||
minHeight="200px"
|
||||
open={isOpen}
|
||||
headerText={
|
||||
<>
|
||||
{stakeInfo && historyRecord.name}
|
||||
{!stakeInfo && "Parsing Transaction Hash"}
|
||||
</>
|
||||
}
|
||||
onClose={() => close()}
|
||||
>
|
||||
{stakeInfo && <Box display="flex" flexDirection="column" gap="15px">
|
||||
<Box width="100%" display="flex" flexDirection="row" justifyContent="space-between" alignItems="center">
|
||||
<Token
|
||||
parentSx={{
|
||||
height: "80px",
|
||||
paddingLeft: "10px",
|
||||
"& svg:nth-of-type(2)": {
|
||||
transform: "translate(50%, -50%)",
|
||||
zIndex: 100,
|
||||
}
|
||||
}}
|
||||
sx={{ transform: "scale(1.65)", }}
|
||||
chainTokenName={chainInfo.symbol}
|
||||
name={ftsoSymbol ? ftsoSymbol : ""}
|
||||
/>
|
||||
|
||||
<Box flexBasis="75%" display="flex" flexDirection="column">
|
||||
<Box display="flex" justifyContent="space-between">
|
||||
<Typography>Receiver</Typography>
|
||||
<Link
|
||||
href={`${chainInfo.url}/address/${stakeInfo.args.receiver}`}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
>
|
||||
<Typography>{shorten(stakeInfo.args.receiver, 9, -7)}</Typography>
|
||||
</Link>
|
||||
</Box>
|
||||
<Box display="flex" justifyContent="space-between">
|
||||
<Typography>Amount</Typography>
|
||||
<Typography>{formatNumber(
|
||||
new DecimalBigNumber(stakeInfo ? stakeInfo.args.amount : 0n, ftsoDecimals),
|
||||
5
|
||||
)} {ftsoSymbol}</Typography>
|
||||
</Box>
|
||||
</Box>
|
||||
</Box>
|
||||
|
||||
<PrimaryButton
|
||||
fullWidth
|
||||
component="a"
|
||||
href={`${chainInfo.url}/tx/${historyRecord.txHash}`}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
>
|
||||
View Transaction Details
|
||||
</PrimaryButton>
|
||||
</Box>}
|
||||
</Modal>
|
||||
)
|
||||
}
|
||||
|
||||
export default StakingViewModal;
|
||||
33
src/containers/History/TokenBox.jsx
Normal file
33
src/containers/History/TokenBox.jsx
Normal file
@ -0,0 +1,33 @@
|
||||
import Token from "../../components/Token/Token";
|
||||
import { DecimalBigNumber } from "../../helpers/DecimalBigNumber";
|
||||
import { formatNumber } from "../../helpers";
|
||||
|
||||
import { Box, Typography } from "@mui/material";
|
||||
|
||||
const TokenBox = ({ tokenAmount, tokenSymbol, decimals, chainTokenSymbol }) => {
|
||||
return (
|
||||
<Box display="flex" flexDirection="column" width="70px">
|
||||
<Token
|
||||
parentSx={{
|
||||
height: "80px",
|
||||
"& svg:nth-of-type(2)": {
|
||||
transform: "translate(10%, -50%)",
|
||||
zIndex: 100,
|
||||
}
|
||||
}}
|
||||
sx={{ transform: "scale(1.65)", }}
|
||||
chainTokenName={chainTokenSymbol}
|
||||
name={tokenSymbol}
|
||||
/>
|
||||
|
||||
<Box display="flex" flexDirection="column" alignItems="center">
|
||||
<Typography>{formatNumber(
|
||||
new DecimalBigNumber(tokenAmount ? tokenAmount : 0n, decimals),
|
||||
5
|
||||
)}</Typography>
|
||||
</Box>
|
||||
</Box>
|
||||
)
|
||||
}
|
||||
|
||||
export default TokenBox;
|
||||
@ -32,10 +32,12 @@ export const StakeContainer = ({ chainId, address, config, connect }) => {
|
||||
|
||||
const { epoch, refetch: refetchEpoch } = useEpoch(chainId);
|
||||
|
||||
const chainSymbol = useMemo(() => {
|
||||
const chainSymbol = config?.getClient()?.chain?.nativeCurrency?.symbol;
|
||||
if (chainSymbol) return chainSymbol;
|
||||
return "WTF";
|
||||
const chain = useMemo(() => {
|
||||
const client = config?.getClient();
|
||||
return {
|
||||
symbol: client?.chain?.nativeCurrency?.symbol,
|
||||
name: client?.chain?.name,
|
||||
}
|
||||
}, [config, chainId])
|
||||
|
||||
useEffect(() => {
|
||||
@ -45,7 +47,7 @@ export const StakeContainer = ({ chainId, address, config, connect }) => {
|
||||
if (isModalOpened) {
|
||||
return (
|
||||
<Stake
|
||||
chainSymbol={chainSymbol}
|
||||
chainSymbol={chain.symbol}
|
||||
chainId={chainId}
|
||||
address={address}
|
||||
isOpened={isModalOpened}
|
||||
@ -57,7 +59,7 @@ export const StakeContainer = ({ chainId, address, config, connect }) => {
|
||||
|
||||
return (
|
||||
<Box>
|
||||
<PageTitle name="Protocol Staking" subtitle={`(3, 3) Stake ${ftsoSymbol} to earn rebase yields backed by protocol revenue`} />
|
||||
<PageTitle name="Protocol Staking" subtitle={`(3, 3) Stake¹ ${ftsoSymbol} to earn rebase yields backed by protocol revenue`} />
|
||||
<Container
|
||||
style={{
|
||||
paddingLeft: isSmallScreen || isVerySmallScreen ? "0" : "3.3rem",
|
||||
@ -78,13 +80,12 @@ export const StakeContainer = ({ chainId, address, config, connect }) => {
|
||||
Rebase
|
||||
<Countdown otherwise="Ready" targetTime={epoch.end * 1000} />
|
||||
</Typography>
|
||||
|
||||
</Box>
|
||||
}
|
||||
>
|
||||
<Grid container spacing={1}>
|
||||
<Grid item xs={isSmallScreen ? 12 : 4}>
|
||||
<Apy stnkSymbol={stnkSymbol} distribute={epoch.distribute} chainId={chainId} />
|
||||
<Apy chainName={chain.name} ftsoSymbol={ftsoSymbol} distribute={epoch.distribute} chainId={chainId} />
|
||||
</Grid>
|
||||
<Grid item xs={isSmallScreen ? 12 : 4}>
|
||||
<TotalDeposit stnkSymbol={stnkSymbol} chainId={chainId} />
|
||||
@ -95,7 +96,7 @@ export const StakeContainer = ({ chainId, address, config, connect }) => {
|
||||
</Grid>
|
||||
|
||||
<Divider sx={{ marginTop: "30px" }} />
|
||||
<ClaimsArea chainId={chainId} address={address} chainSymbol={chainSymbol} epoch={epoch} />
|
||||
<ClaimsArea chainId={chainId} address={address} chainSymbol={chain.symbol} epoch={epoch} />
|
||||
<Divider />
|
||||
|
||||
<Box mt="15px" display="flex" flexDirection="column" alignItems="center" justifyContent="center">
|
||||
@ -104,14 +105,14 @@ export const StakeContainer = ({ chainId, address, config, connect }) => {
|
||||
onClick={() => handleModal(true)}
|
||||
sx={{ maxWidth: isSemiSmallScreen ? "100%" : "350px" }}
|
||||
>
|
||||
Start staking
|
||||
Start (3, 3) Stake¹
|
||||
</PrimaryButton>
|
||||
<Box textAlign="center" mt="15px">
|
||||
<StakeInfoText />
|
||||
</Box>
|
||||
</Box>
|
||||
</Paper>
|
||||
<FarmPools chainId={chainId} chainSymbol={chainSymbol} />
|
||||
<FarmPools chainId={chainId} chainSymbol={chain.symbol} />
|
||||
</Box>
|
||||
</Container>
|
||||
</Box>
|
||||
|
||||
@ -1,5 +1,6 @@
|
||||
import Metric from "../../../components/Metric/Metric";
|
||||
import { formatCurrency, formatNumber } from "../../../helpers";
|
||||
import { bridgeNumbers } from "../../../constants";
|
||||
|
||||
import { useCurrentIndex } from "../../../hooks/staking";
|
||||
import { useCirculatingSupply } from "../../../hooks/tokens";
|
||||
@ -12,8 +13,8 @@ export const CurrentIndex = props => {
|
||||
|
||||
const _props = {
|
||||
...props,
|
||||
label: `Current Index`,
|
||||
tooltip: `The current index indicates the amount of ${props.ftsoSymbol} a holder would possess if they had staked and maintained 1 ${props.ftsoSymbol} since its launch.`,
|
||||
label: "Stake¹ Index",
|
||||
tooltip: `A cumulative multiplier showing how much 1 ${props.ftsoSymbol} would have compounded if staked in (3, 3) Stake¹ since protocol launch.`,
|
||||
};
|
||||
|
||||
if (currentIndex) _props.metric = `${formatNumber(currentIndex, 2)}`;
|
||||
@ -34,8 +35,8 @@ export const Apy = props => {
|
||||
|
||||
const _props = {
|
||||
...props,
|
||||
label: "APY",
|
||||
tooltip: `The annualized rate of return, accounting for compounding from ${props.stnkSymbol}’s exponential rebasing.`,
|
||||
label: "Stake¹ APY",
|
||||
tooltip: `Annualized (3, 3) Stake¹ yield for ${props.ftsoSymbol} based on the protocol's current rebase rate, funded by protocol revenue on ${props.chainName}.`
|
||||
};
|
||||
|
||||
if (apy) _props.metric = `${formatNumber(apy, 2)}${apy === Infinity ? "" : "%"}`;
|
||||
@ -51,8 +52,8 @@ export const TotalDeposit = props => {
|
||||
|
||||
const _props = {
|
||||
...props,
|
||||
label: "Total Deposit",
|
||||
tooltip: `Total reserves of native coins, LP tokens, and other assets in the ghostDAO treasury backing the entire circulating supply of ${props.stnkSymbol}.`,
|
||||
label: "Total Stake¹",
|
||||
tooltip: `Market value of all ${props.ftsoSymbol} staked into (3, 3) Stake¹ on ${props.chainName}, including tokens still in warmup or in ${bridgeNumbers()} Bridge-In.`
|
||||
};
|
||||
|
||||
if (deposit) _props.metric = `${formatCurrency(deposit, 2)}`;
|
||||
|
||||
@ -12,6 +12,7 @@ import Token from "../../../components/Token/Token";
|
||||
import { PrimaryButton, SecondaryButton } from "../../../components/Button";
|
||||
import { TokenAllowanceGuard } from "../../../components/TokenAllowanceGuard/TokenAllowanceGuard";
|
||||
|
||||
import { useLocalStorage } from "../../../hooks/localstorage";
|
||||
import { useWarmupLength, stake, unstake, wrap, unwrap } from "../../../hooks/staking";
|
||||
import { formatNumber } from "../../../helpers";
|
||||
|
||||
@ -22,6 +23,8 @@ const StakeConfirmationModal = (props) => {
|
||||
const [acknowledgedWarmup, setAcknowledgedWarmup] = useState(false);
|
||||
const [isPending, setIsPending] = useState(false);
|
||||
|
||||
const { tryStoreInHistory, CONSTANTS } = useLocalStorage();
|
||||
|
||||
useEffect(() => setAcknowledgedWarmup(acknowledgedWarmup || !needsWarmup), [acknowledgedWarmup, needsWarmup])
|
||||
|
||||
const AcknowledgeWarmupCheckbox = () => {
|
||||
@ -73,11 +76,13 @@ const StakeConfirmationModal = (props) => {
|
||||
setIsPending(true);
|
||||
const actionAmount = new DecimalBigNumber(props.amount, props.spendDecimals);
|
||||
let isRebase = false;
|
||||
let txHash = null;
|
||||
let txName = null;
|
||||
|
||||
switch (props.action.toUpperCase()) {
|
||||
case "STAKE":
|
||||
isRebase = props.bottomToken === props.stnkSymbol;
|
||||
await stake(
|
||||
txHash = await stake(
|
||||
props.chainId,
|
||||
props.address,
|
||||
actionAmount._value.toBigInt(),
|
||||
@ -87,10 +92,11 @@ const StakeConfirmationModal = (props) => {
|
||||
props.stnkSymbol,
|
||||
props.ghstSymbol
|
||||
);
|
||||
txName = CONSTANTS.stake.stake;
|
||||
break;
|
||||
case "UNSTAKE":
|
||||
isRebase = props.upperToken === props.stnkSymbol;
|
||||
await unstake(
|
||||
txHash = await unstake(
|
||||
props.chainId,
|
||||
props.address,
|
||||
actionAmount._value.toBigInt(),
|
||||
@ -100,27 +106,32 @@ const StakeConfirmationModal = (props) => {
|
||||
props.stnkSymbol,
|
||||
props.ghstSymbol
|
||||
);
|
||||
txName = CONSTANTS.stake.unstake;
|
||||
break;
|
||||
case "WRAP":
|
||||
await wrap(
|
||||
txHash = await wrap(
|
||||
props.chainId,
|
||||
props.address,
|
||||
actionAmount._value.toBigInt(),
|
||||
props.ghstSymbol
|
||||
);
|
||||
txName = CONSTANTS.stake.wrap;
|
||||
break;
|
||||
case "UNWRAP":
|
||||
await unwrap(
|
||||
txHash = await unwrap(
|
||||
props.chainId,
|
||||
props.address,
|
||||
actionAmount._value.toBigInt(),
|
||||
props.stnkSymbol
|
||||
);
|
||||
txName = CONSTANTS.stake.unwrap;
|
||||
break;
|
||||
default:
|
||||
console.log("Wrong action to be executed!");
|
||||
}
|
||||
|
||||
if (txHash && txName) tryStoreInHistory(props.chainId, props.address, CONSTANTS.stake.key, txHash, txName);
|
||||
|
||||
setIsPending(false);
|
||||
props.onClose();
|
||||
}
|
||||
@ -156,7 +167,7 @@ const StakeConfirmationModal = (props) => {
|
||||
chainTokenName={props.chainSymbol}
|
||||
name={props.upperToken}
|
||||
/>
|
||||
<Typography>{props.upperToken}</Typography>
|
||||
<Typography>{props.upperToken}</Typography>
|
||||
</Box>
|
||||
</Box>
|
||||
<GhostStyledIcon component={ArrowRightIcon} />
|
||||
|
||||
@ -67,6 +67,10 @@ const StyledBox = styled(Box)(({ theme }) => ({
|
||||
},
|
||||
}));
|
||||
|
||||
const DECIMALS_PREFIX = "stake-decimals";
|
||||
const IS_CLAIM_PREFIX = "stake-isClaim";
|
||||
const IS_TRIGGER_PREFIX = "stake-isTrigger";
|
||||
|
||||
export const StakeInputArea = ({
|
||||
chainSymbol,
|
||||
upperToken,
|
||||
@ -84,11 +88,11 @@ export const StakeInputArea = ({
|
||||
const [bottomTokenModalOpen, setBottomTokenModalOpen] = useState(false);
|
||||
const [confirmationModalOpen, setConfirmationModalOpen] = useState(false);
|
||||
|
||||
const { getStorageValue, setStorageValue } = useLocalStorage();
|
||||
const { useStorageValue, setStorageValue } = useLocalStorage();
|
||||
|
||||
const [formatDecimals, setFormatDecimals] = useState(() => getStorageValue(chainId, address, "stake-decimals", "5"));
|
||||
const [isClaim, setIsClaim] = useState(() => getStorageValue(chainId, address, "stake-isClaim", true));
|
||||
const [isTrigger, setIsTrigger] = useState(() => getStorageValue(chainId, address, "stake-isTrigger", true));
|
||||
const { data: formatDecimals } = useStorageValue(chainId, address, DECIMALS_PREFIX, "5");
|
||||
const { data: isClaim } = useStorageValue(chainId, address, IS_CLAIM_PREFIX, true);
|
||||
const { data: isTrigger } = useStorageValue(chainId, address, IS_TRIGGER_PREFIX, true);
|
||||
|
||||
const [amount, setAmount] = useState("");
|
||||
const [receiveAmount, setReceiveAmount] = useState("");
|
||||
@ -103,20 +107,17 @@ export const StakeInputArea = ({
|
||||
const { symbol: stnkSymbol } = useTokenSymbol(chainId, "STNK");
|
||||
const { symbol: ghstSymbol } = useTokenSymbol(chainId, "GHST");
|
||||
|
||||
const setIsClaimInner = useCallback((value) => {
|
||||
setIsClaim(value);
|
||||
setStorageValue(chainId, address, "stake-isClaim", value);
|
||||
const setIsClaim = useCallback((value) => {
|
||||
setStorageValue(chainId, address, IS_CLAIM_PREFIX, value);
|
||||
}, [chainId, address]);
|
||||
|
||||
const setIsTriggerInner = useCallback((value) => {
|
||||
setIsTrigger(value);
|
||||
setStorageValue(chainId, address, "stake-isTrigger", value);
|
||||
const setIsTrigger = useCallback((value) => {
|
||||
setStorageValue(chainId, address, IS_TRIGGER_PREFIX, value);
|
||||
}, [chainId, address]);
|
||||
|
||||
const setFormatDecimalsInner = useCallback((value) => {
|
||||
const setFormatDecimals = useCallback((value) => {
|
||||
if (Number(value) <= 17) {
|
||||
setFormatDecimals(value);
|
||||
setStorageValue(chainId, address, "stake-decimals", value);
|
||||
setStorageValue(chainId, address, DECIMALS_PREFIX, value);
|
||||
}
|
||||
}, [chainId, address]);
|
||||
|
||||
@ -251,11 +252,11 @@ export const StakeInputArea = ({
|
||||
open={settingsModalOpen}
|
||||
onClose={closeSettingModal}
|
||||
formatDecimals={formatDecimals}
|
||||
onFormatDecimalsChange={event => setFormatDecimalsInner(event.currentTarget.value)}
|
||||
onFormatDecimalsChange={event => setFormatDecimals(event.currentTarget.value)}
|
||||
isClaim={isClaim}
|
||||
onIsClaimChanged={setIsClaimInner}
|
||||
onIsClaimChanged={setIsClaim}
|
||||
isTrigger={isTrigger}
|
||||
onTriggerRebaseChange={setIsTriggerInner}
|
||||
onTriggerRebaseChange={setIsTrigger}
|
||||
/>
|
||||
<StakeConfirmationModal
|
||||
chainSymbol={chainSymbol}
|
||||
|
||||
@ -20,7 +20,7 @@ import SafariFooter from "../../components/SafariFooter/SafariFooter";
|
||||
|
||||
import { useTokenSymbol } from "../../hooks/tokens";
|
||||
|
||||
const MetricsDashboard = ({ chainId }) => {
|
||||
const MetricsDashboard = ({ chainId, nativeMetadata }) => {
|
||||
const theme = useTheme();
|
||||
const isMobileScreen = useMediaQuery("(max-width: 885px)");
|
||||
const isVeryMobileScreen = useMediaQuery("(max-width: 560px)");
|
||||
@ -40,22 +40,22 @@ const MetricsDashboard = ({ chainId }) => {
|
||||
<Paper fullWidth enableBackground>
|
||||
<Grid container spacing={2}>
|
||||
<Grid item xs={xsCalculator}>
|
||||
<TreasuryMarketCap ftsoSymbol={ftsoSymbol} chainId={chainId} />
|
||||
<TreasuryMarketCap nativeMetadata={nativeMetadata} ftsoSymbol={ftsoSymbol} chainId={chainId} />
|
||||
</Grid>
|
||||
<Grid item xs={xsCalculator}>
|
||||
<FatsoPrice ftsoSymbol={ftsoSymbol} chainId={chainId} />
|
||||
<FatsoPrice nativeMetadata={nativeMetadata} ftsoSymbol={ftsoSymbol} chainId={chainId} />
|
||||
</Grid>
|
||||
<Grid item xs={xsCalculator}>
|
||||
<GhostPrice ghstSymbol={ghstSymbol} ftsoSymbol={ftsoSymbol} chainId={chainId} />
|
||||
</Grid>
|
||||
<Grid item xs={xsCalculator}>
|
||||
<CirculatingSupply stnkSymbol={stnkSymbol} chainId={chainId} />
|
||||
<CirculatingSupply ftsoSymbol={ftsoSymbol} chainId={chainId} />
|
||||
</Grid>
|
||||
<Grid item xs={xsCalculator}>
|
||||
<FatsoBacking ftsoSymbol={ftsoSymbol} chainId={chainId} />
|
||||
<FatsoBacking nativeMetadata={nativeMetadata} ftsoSymbol={ftsoSymbol} chainId={chainId} />
|
||||
</Grid>
|
||||
<Grid item xs={xsCalculator}>
|
||||
<CurrentIndex ftsoSymbol={ftsoSymbol} chainId={chainId} />
|
||||
<CurrentIndex nativeMetadata={nativeMetadata} ftsoSymbol={ftsoSymbol} chainId={chainId} />
|
||||
</Grid>
|
||||
</Grid>
|
||||
</Paper>
|
||||
@ -70,7 +70,7 @@ const MetricsDashboard = ({ chainId }) => {
|
||||
);
|
||||
};
|
||||
|
||||
const TreasuryDashboard = ({ chainId }) => {
|
||||
const TreasuryDashboard = ({ chainId, config }) => {
|
||||
const isSmallScreen = useMediaQuery("(max-width: 650px)");
|
||||
const isVerySmallScreen = useMediaQuery("(max-width: 379px)");
|
||||
|
||||
@ -80,6 +80,16 @@ const TreasuryDashboard = ({ chainId }) => {
|
||||
ReactGA.send({ hitType: "pageview", page: location.pathname });
|
||||
}, [location]);
|
||||
|
||||
const nativeMetadata = useMemo(() => {
|
||||
const client = config?.getClient();
|
||||
return {
|
||||
chainName: client?.chain?.name,
|
||||
url: client?.chain?.blockExplorers?.default?.url,
|
||||
symbol: client?.chain?.nativeCurrency?.symbol,
|
||||
decimals: client?.chain?.nativeCurrency?.decimals,
|
||||
}
|
||||
}, [config]);
|
||||
|
||||
return (
|
||||
<>
|
||||
<PageTitle name="Protocol Overview" subtitle="Confirm protocol health by monitoring supply and reserves" />
|
||||
@ -90,7 +100,7 @@ const TreasuryDashboard = ({ chainId }) => {
|
||||
}}
|
||||
>
|
||||
<Box sx={{ mt: "15px" }}>
|
||||
<MetricsDashboard chainId={chainId} />
|
||||
<MetricsDashboard nativeMetadata={nativeMetadata} chainId={chainId} />
|
||||
</Box>
|
||||
</Container>
|
||||
</>
|
||||
|
||||
@ -14,8 +14,8 @@ export const CurrentIndex = props => {
|
||||
|
||||
const _props = {
|
||||
...props,
|
||||
label: `Current Index`,
|
||||
tooltip: `The current index indicates the amount of ${props.ftsoSymbol} a holder would possess if they had staked and maintained 1 ${props.ftsoSymbol} since its launch.`,
|
||||
label: "Stake¹ Index",
|
||||
tooltip: `Cumulative multiplier showing how much 1 ${props.ftsoSymbol} would have compounded through continuous (3, 3) Stake¹ since launch on ${props.nativeMetadata.chainName}.`,
|
||||
};
|
||||
|
||||
if (currentIndex) _props.metric = `${formatNumber(currentIndex, 2)} ${props.ftsoSymbol}`;
|
||||
@ -32,7 +32,7 @@ export const GhostPrice = props => {
|
||||
const _props = {
|
||||
...props,
|
||||
label: `${props.ghstSymbol} Price`,
|
||||
tooltip: `1 ${props.ghstSymbol} = 1 ${props.ftsoSymbol} x Current Index`,
|
||||
tooltip: `Synthetic price of 1 ${props.ghstSymbol}, derived by multiplying the price of 1 ${props.ftsoSymbol} by (3, 3) Stake¹ Index.`,
|
||||
};
|
||||
|
||||
if (ghstPrice) _props.metric = formatCurrency(ghstPrice, 2);
|
||||
@ -47,7 +47,7 @@ export const FatsoPrice = props => {
|
||||
const _props = {
|
||||
...props,
|
||||
label: `${props.ftsoSymbol} Price`,
|
||||
tooltip: `Weighted ${props.ftsoSymbol} Price Across V2 DEXs on the chosen EVM Chain`,
|
||||
tooltip: `Weighted price of 1 ${props.ftsoSymbol} across DEXs on ${props.nativeMetadata.chainName}, excluding prices from other EVMs.`,
|
||||
};
|
||||
|
||||
if (ftsoPrice) _props.metric = formatCurrency(ftsoPrice, 2);
|
||||
@ -62,8 +62,8 @@ export const CirculatingSupply = props => {
|
||||
|
||||
const _props = {
|
||||
...props,
|
||||
label: `Circulating / Total`,
|
||||
tooltip: `Circulating supply refers to the amount of ${props.stnkSymbol} in circulation, excluding those held by the protocol in its treasury. However, ${props.stnkSymbol} allocated to Protocol-Owned Liquidity is considered part of the circulating supply.`,
|
||||
label: `Stake¹ / Total`,
|
||||
tooltip: `(3, 3) Stake¹ supply is all staked ${props.ftsoSymbol}. Total supply is all ${props.ftsoSymbol} ever minted. The delta is unstaked ${props.ftsoSymbol} in user wallets and DEX liquidity pools, including Protocol Owned Liquidity (POL).`
|
||||
};
|
||||
|
||||
if (circulatingSupply && totalSupply) _props.metric = `${formatNumber(circulatingSupply, 0)}/${formatNumber(totalSupply, 0)}`;
|
||||
@ -84,7 +84,7 @@ export const FatsoBacking = props => {
|
||||
const _props = {
|
||||
...props,
|
||||
label: `Backing per ${props.ftsoSymbol}`,
|
||||
tooltip: `The total amount of native coins, LP tokens, and other assets held by the ghostDAO treasury to support the value of each ${props.ftsoSymbol} in circulation.`
|
||||
tooltip: `Intrinsic treasury backing per 1 ${props.ftsoSymbol} from pure Web3, non-freezable assets on ${props.nativeMetadata.chainName} (wrapped ${props.nativeMetadata.symbol} and Uni-V2 LP tokens), calculated as if ${props.ftsoSymbol} price fell to its ${props.nativeMetadata.symbol}-denominated floor of $1 set at launch.`,
|
||||
};
|
||||
|
||||
if (backing) _props.metric = formatCurrency(backing, 2);
|
||||
@ -101,7 +101,7 @@ export const TreasuryMarketCap = props => {
|
||||
const _props = {
|
||||
...props,
|
||||
label: `Market Cap`,
|
||||
tooltip: `Market Cap = ${props.ftsoSymbol} Price × ${props.ftsoSymbol} Total Supply`
|
||||
tooltip: `Market capitalization of ${props.ftsoSymbol} on ${props.nativeMetadata.chainName}, excluding market cap estimates from other EVMs.`
|
||||
};
|
||||
|
||||
if (marketCap) _props.metric = formatCurrency(marketCap, 2);
|
||||
|
||||
@ -11,6 +11,7 @@ import { SecondaryButton } from "../../../components/Button";
|
||||
import { DecimalBigNumber } from "../../../helpers/DecimalBigNumber";
|
||||
|
||||
import { GATEKEEPER_ADDRESSES, EMPTY_ADDRESS } from "../../../constants/addresses";
|
||||
import { bridgeNumbers } from "../../../constants";
|
||||
|
||||
const ProtocolDetail = ({ isMobileScreen, theme, name, sideName, url, urlParams, description }) => {
|
||||
const navigate = useNavigate();
|
||||
@ -80,12 +81,6 @@ const ProtocolDetails = ({ chainId, isMobileScreen, theme, }) => {
|
||||
return `Up to ${formatNumber(maxDiscount, 0)}% Discount`;
|
||||
}, [liveBonds]);
|
||||
|
||||
const bridgeNumbers = useMemo(() => {
|
||||
const connectedNetworks = Object.keys(GATEKEEPER_ADDRESSES).length;
|
||||
const number = 1 + connectedNetworks * 3;
|
||||
return `(${number}, ${number})`;
|
||||
}, [chainId]);
|
||||
|
||||
return (
|
||||
<Grid container spacing={0} justifyContent={"center"}>
|
||||
<Box display="flex" flexWrap="wrap" justifyContent="space-between" mt="10px" gap="25px">
|
||||
@ -115,18 +110,18 @@ const ProtocolDetails = ({ chainId, isMobileScreen, theme, }) => {
|
||||
isMobileScreen={isMobileScreen}
|
||||
theme={theme}
|
||||
url={`/${networkName.toLowerCase()}/stake`}
|
||||
name="(3, 3) Stake"
|
||||
name="(3, 3) Stake¹"
|
||||
sideName={`${formatNumber(apyInner, 2)}% APY`}
|
||||
description={`Staking enables (3, 3) coordination by aligning long-term incentives, sustainably backed by (1, 1) Bonds, LP fees, and Farming. Stake ${ftsoSymbol} to earn rewards and unlock ${bridgeNumbers} Stake\u00B2.`}
|
||||
description={`Staking enables (3, 3) coordination by aligning long-term incentives, sustainably backed by (1, 1) Bonds, LP fees, and Farming. Stake ${ftsoSymbol} to earn rewards and unlock ${bridgeNumbers()} Stake\u00B2.`}
|
||||
/>
|
||||
|
||||
<ProtocolDetail
|
||||
isMobileScreen={isMobileScreen}
|
||||
theme={theme}
|
||||
url={`/${networkName.toLowerCase()}/bridge`}
|
||||
name={`${bridgeNumbers} Stake\u00B2`}
|
||||
name={`${bridgeNumbers()} Stake\u00B2`}
|
||||
sideName={`${formatNumber(gatekeepedApy, 2)}% APY`}
|
||||
description={`Staking\u00B2 strategy further deepens long-term incentives powered by sustainable cross-chain bridging revenue. ${bridgeNumbers} Stake\u00B2 ${csprSymbol} to receive organic APY with no warmup and no dilution.`}
|
||||
description={`Staking\u00B2 strategy further deepens long-term incentives powered by sustainable cross-chain bridging revenue. ${bridgeNumbers()} Stake\u00B2 ${csprSymbol} to receive organic APY with no warmup and no dilution.`}
|
||||
/>
|
||||
</Box>
|
||||
</Grid>
|
||||
|
||||
@ -1,3 +1,18 @@
|
||||
export const countOnes32 = (n) => {
|
||||
let count = 0;
|
||||
let num = BigInt(n) & 0xffffffffn;
|
||||
while (num > 0n) {
|
||||
num &= num - 1n;
|
||||
count++;
|
||||
}
|
||||
return count;
|
||||
};
|
||||
|
||||
export const countBitmapOnes = (bitmap) => {
|
||||
if (!bitmap?.data) return 0;
|
||||
return bitmap.data.reduce((sum, word) => sum + countOnes32(word), 0);
|
||||
};
|
||||
|
||||
export function shorten(str, first = 6, second = -4) {
|
||||
if (str.length < 10) return str;
|
||||
return `${str.slice(0, first)}...${str.slice(second)}`;
|
||||
|
||||
@ -1,10 +1,12 @@
|
||||
import { useReadContract, useReadContracts } from "wagmi";
|
||||
import { useMemo } from "react";
|
||||
import toast from "react-hot-toast";
|
||||
|
||||
import {
|
||||
BOND_DEPOSITORY_ADDRESSES,
|
||||
DAO_TREASURY_ADDRESSES,
|
||||
BONDING_CALCULATOR_ADDRESSES,
|
||||
WETH_ADDRESSES,
|
||||
} from "../../constants/addresses";
|
||||
import { abi as BondAbi } from "../../abi/GhostBondDepository.json";
|
||||
import { abi as TreasuryAbi } from "../../abi/GhostTreasury.json";
|
||||
@ -26,12 +28,10 @@ import { DecimalBigNumber } from "../../helpers/DecimalBigNumber";
|
||||
import { shorten } from "../../helpers";
|
||||
import { tokenNameConverter } from "../../helpers/tokenConverter";
|
||||
|
||||
export const useLiveBonds = (chainId, chainName) => {
|
||||
const ftsoPrice = useFtsoPrice(chainId);
|
||||
const baseTokenPerUsd = useReservePrice(chainId);
|
||||
const originalCoefficient = useOrinalCoefficient(chainId);
|
||||
const LP_SYMBOLS = ["UNI-V2", "SLP", "CAKE-LP"];
|
||||
|
||||
const { data: liveIndexesRaw, refetch } = useReadContract({
|
||||
export const useLiveBonds = (chainId, chainName) => {
|
||||
const { data: liveIndexesRaw, refetch: refetchLiveMarkets } = useReadContract({
|
||||
abi: BondAbi,
|
||||
address: BOND_DEPOSITORY_ADDRESSES[chainId],
|
||||
functionName: "liveMarkets",
|
||||
@ -39,8 +39,18 @@ export const useLiveBonds = (chainId, chainName) => {
|
||||
chainId: chainId,
|
||||
});
|
||||
|
||||
const { bonds } = useBondInfo(chainId, chainName, liveIndexesRaw);
|
||||
|
||||
return { liveBonds: bonds, refetch: refetchLiveMarkets };
|
||||
}
|
||||
|
||||
export const useBondInfo = (chainId, chainName, indexes) => {
|
||||
const ftsoPrice = useFtsoPrice(chainId);
|
||||
const baseTokenPerUsd = useReservePrice(chainId);
|
||||
const originalCoefficient = useOrinalCoefficient(chainId);
|
||||
|
||||
const { data: markets } = useReadContracts({
|
||||
contracts: liveIndexesRaw?.map((id) => ({
|
||||
contracts: indexes?.map((id) => ({
|
||||
abi: BondAbi,
|
||||
address: BOND_DEPOSITORY_ADDRESSES[chainId],
|
||||
functionName: "markets",
|
||||
@ -51,7 +61,7 @@ export const useLiveBonds = (chainId, chainName) => {
|
||||
});
|
||||
|
||||
const { data: terms } = useReadContracts({
|
||||
contracts: liveIndexesRaw?.map((id) => ({
|
||||
contracts: indexes?.map((id) => ({
|
||||
abi: BondAbi,
|
||||
address: BOND_DEPOSITORY_ADDRESSES[chainId],
|
||||
functionName: "terms",
|
||||
@ -62,7 +72,7 @@ export const useLiveBonds = (chainId, chainName) => {
|
||||
});
|
||||
|
||||
const { data: metas } = useReadContracts({
|
||||
contracts: liveIndexesRaw?.map((id) => ({
|
||||
contracts: indexes?.map((id) => ({
|
||||
abi: BondAbi,
|
||||
address: BOND_DEPOSITORY_ADDRESSES[chainId],
|
||||
functionName: "metadatas",
|
||||
@ -73,7 +83,7 @@ export const useLiveBonds = (chainId, chainName) => {
|
||||
});
|
||||
|
||||
const { data: marketPrices } = useReadContracts({
|
||||
contracts: liveIndexesRaw?.map((id) => ({
|
||||
contracts: indexes?.map((id) => ({
|
||||
abi: BondAbi,
|
||||
address: BOND_DEPOSITORY_ADDRESSES[chainId],
|
||||
functionName: "marketPrice",
|
||||
@ -86,7 +96,7 @@ export const useLiveBonds = (chainId, chainName) => {
|
||||
const { data: quotePrices } = useReadContracts({
|
||||
contracts: markets?.map((_, index) => {
|
||||
const quoteTokenDecimals = metas?.at(index).result?.at(5) ? metas.at(index).result.at(5) : 18;
|
||||
const quoteTokenAddress = markets?.at(index).result?.at(1) ? markets.at(index).result.at(1) : "";
|
||||
const quoteTokenAddress = markets?.at(index).result?.at(3) ? markets.at(index).result.at(3) : "";
|
||||
const one = 10n ** BigInt(quoteTokenDecimals);
|
||||
|
||||
return {
|
||||
@ -102,7 +112,7 @@ export const useLiveBonds = (chainId, chainName) => {
|
||||
|
||||
const { data: markdowns } = useReadContracts({
|
||||
contracts: markets?.map((_, index) => {
|
||||
const quoteTokenAddress = markets?.at(index).result?.at(1) ? markets.at(index).result.at(1) : "";
|
||||
const quoteTokenAddress = markets?.at(index).result?.at(3) ? markets.at(index).result.at(3) : "";
|
||||
return {
|
||||
abi: BondingCalculatorAbi,
|
||||
address: BONDING_CALCULATOR_ADDRESSES[chainId],
|
||||
@ -114,18 +124,19 @@ export const useLiveBonds = (chainId, chainName) => {
|
||||
})
|
||||
});
|
||||
|
||||
const { symbols: quoteTokenSymbols } = useTokenSymbols(chainId, markets?.map(m => m.result?.at(1)));
|
||||
const { symbols: quoteTokenSymbols } = useTokenSymbols(chainId, markets?.map(m => m.result?.at(3)));
|
||||
const { symbol: baseTokenSymbol } = useTokenSymbol(chainId, "FTSO");
|
||||
|
||||
const liveBonds = liveIndexesRaw ? liveIndexesRaw.map((bondIndex, index) => {
|
||||
const bonds = indexes ? indexes.map((bondIndex, index) => {
|
||||
const id = Number(bondIndex);
|
||||
|
||||
const marketPrice = marketPrices?.at(index).result ? marketPrices.at(index).result : 0n;
|
||||
const marketCapacity = markets?.at(index).result?.at(0) ? markets.at(index).result.at(0) : 0n;
|
||||
const quoteTokenAddress = markets?.at(index).result?.at(1) ? markets.at(index).result.at(1) : "";
|
||||
const capacityInQuote = markets?.at(index).result?.at(2) ? markets.at(index).result.at(2) : 0n;
|
||||
const marketMaxPayout = markets?.at(index).result?.at(4) ? markets.at(index).result.at(4) : 0n;
|
||||
const quoteTokenAddress = markets?.at(index).result?.at(3) ? markets.at(index).result.at(3) : "";
|
||||
const capacityInQuote = markets?.at(index).result?.at(4) ? markets.at(index).result.at(4) : 0n;
|
||||
const marketMaxPayout = markets?.at(index).result?.at(6) ? markets.at(index).result.at(6) : 0n;
|
||||
const quoteTokenDecimals = metas?.at(index).result?.at(5) ? metas.at(index).result.at(5) : 18;
|
||||
|
||||
const quoteTokenPerUsd = quotePrices?.at(index).result
|
||||
? new DecimalBigNumber(quotePrices.at(index).result * (10n ** 9n), quoteTokenDecimals)
|
||||
: new DecimalBigNumber(0n, quoteTokenDecimals);
|
||||
@ -194,7 +205,8 @@ export const useLiveBonds = (chainId, chainName) => {
|
||||
},
|
||||
}
|
||||
}).sort((a, b) => (a.id > b.id ? -1 : 1)) : [];
|
||||
return { liveBonds, refetch };
|
||||
|
||||
return { bonds };
|
||||
}
|
||||
|
||||
export const useNotes = (chainId, address) => {
|
||||
@ -246,19 +258,38 @@ export const useNotes = (chainId, address) => {
|
||||
}),
|
||||
});
|
||||
|
||||
const { symbols: quoteTokenSymbols } = useTokenSymbols(chainId, markets?.map(m => m.result?.at(1)));
|
||||
const quoteTokenNames = useMemo(
|
||||
() => markets?.map((m) => {
|
||||
const address = m.result?.at(3);
|
||||
return address ? address : WETH_ADDRESSES[chainId];
|
||||
}),
|
||||
[markets]
|
||||
);
|
||||
|
||||
const { symbols: quoteTokenSymbols } = useTokenSymbols(chainId, quoteTokenNames);
|
||||
|
||||
const notes = indexesFor ? indexesFor.map((noteIndex, index) => {
|
||||
const id = Number(noteIndex);
|
||||
const quoteTokenAddress = markets?.at(index).result?.at(1) ? markets.at(index).result.at(1) : "";
|
||||
const quoteTokenSymbol = quoteTokenSymbols?.at(index).result ? quoteTokenSymbols.at(index).result : "";
|
||||
const quoteTokenAddress = quoteTokenNames?.at(index);
|
||||
const quoteTokenSymbol = quoteTokenSymbols?.at(index)?.result
|
||||
? quoteTokenSymbols.at(index).result
|
||||
: "";
|
||||
|
||||
const tokenIcos = getTokenIcons(chainId, quoteTokenAddress);
|
||||
const isEmptyIcon = tokenIcos.length === 1 && tokenIcos.at(0) === "";
|
||||
const isLpToken = LP_SYMBOLS.includes(quoteTokenSymbol);
|
||||
|
||||
const chainNames = isEmptyIcon ? [] : getChainTokenNames(chainId, quoteTokenAddress);
|
||||
const quoteTokenIcons = isEmptyIcon
|
||||
? (isLpToken ? ["WETH", "FTSO"] : ["WETH"])
|
||||
: tokenIcos;
|
||||
|
||||
return {
|
||||
id,
|
||||
quoteToken: {
|
||||
name: tokenNameConverter(chainId, quoteTokenSymbol),
|
||||
icons: getTokenIcons(chainId, quoteTokenAddress),
|
||||
chainNames: getChainTokenNames(chainId, quoteTokenAddress),
|
||||
chainNames,
|
||||
icons: quoteTokenIcons,
|
||||
name: tokenNameConverter(chainId, quoteTokenSymbol === '' ? 'WETH' : quoteTokenSymbol),
|
||||
},
|
||||
vesting: terms?.at(index).result?.at(2) ? terms.at(index).result.at(2) : 0,
|
||||
created: notesRaw?.at(index).result?.at(1) ? notesRaw.at(index).result.at(1) : 0,
|
||||
@ -273,24 +304,26 @@ export const useNotes = (chainId, address) => {
|
||||
return { notes, refetch };
|
||||
}
|
||||
|
||||
export const purchaseBond = async ({ chainId, bondId, amount, maxPrice, user, sender, referral, isNative }) => {
|
||||
const args = [bondId, amount, maxPrice, user, referral];
|
||||
export const purchaseBond = async ({ chainId, bondId, amount, maxPrice, user, sender, isNative }) => {
|
||||
const args = [bondId, amount, maxPrice, user];
|
||||
const messages = {
|
||||
replacedMsg: "Bond transaction was replaced. Wait for inclusion please.",
|
||||
successMsg: `Bond successfully purchased for ${shorten(user)}! Wait until it'll mature before claim.`,
|
||||
errorMsg: "Bond transaction failed. Check logs for error detalization.",
|
||||
};
|
||||
|
||||
await executeOnChainTransaction({
|
||||
const txHash = await executeOnChainTransaction({
|
||||
chainId,
|
||||
args,
|
||||
messages,
|
||||
abi: BondAbi,
|
||||
address: BOND_DEPOSITORY_ADDRESSES[chainId],
|
||||
functionName: "deposit",
|
||||
account: user,
|
||||
account: sender,
|
||||
value: isNative ? amount : undefined
|
||||
});
|
||||
|
||||
return txHash;
|
||||
}
|
||||
|
||||
export const redeem = async ({ chainId, user, isGhst, indexes }) => {
|
||||
@ -301,7 +334,7 @@ export const redeem = async ({ chainId, user, isGhst, indexes }) => {
|
||||
errorMsg: `Redeem of ${indexes.length} bonds failed. Check logs for error detalization.`,
|
||||
};
|
||||
|
||||
await executeOnChainTransaction({
|
||||
const txHash = await executeOnChainTransaction({
|
||||
chainId,
|
||||
args,
|
||||
messages,
|
||||
@ -310,6 +343,8 @@ export const redeem = async ({ chainId, user, isGhst, indexes }) => {
|
||||
functionName: "redeem",
|
||||
account: user,
|
||||
});
|
||||
|
||||
return txHash;
|
||||
}
|
||||
|
||||
export const forceRedeem = async ({ chainId, user, receiver, indexes }) => {
|
||||
|
||||
@ -1,5 +1,4 @@
|
||||
import { createContext, useContext, useState, useMemo } from "react";
|
||||
import { claim } from "../../hooks/staking";
|
||||
|
||||
const emptyFunction = () => {};
|
||||
const BreakoutModalContext = createContext();
|
||||
@ -8,7 +7,6 @@ export const useBreakoutModal = () => useContext(BreakoutModalContext);
|
||||
export const BreakoutModalProvider = ({ children }) => {
|
||||
const [isStakingOpened, setIsStakingOpened] = useState(false);
|
||||
const [isClaimBondOpened, setIsClaimBondOpened] = useState(false);
|
||||
const [activeTxIndex, setActiveTxIndex] = useState(-1);
|
||||
const [warmupPeriod, setWarmupPeriod] = useState(0);
|
||||
const [estimatedAmount, setEstimatedAmount] = useState(0);
|
||||
const [defaultFunction, setDefaultFunction] = useState(emptyFunction);
|
||||
@ -46,8 +44,6 @@ export const BreakoutModalProvider = ({ children }) => {
|
||||
<BreakoutModalContext.Provider value={{
|
||||
isStakingOpened,
|
||||
isClaimBondOpened,
|
||||
activeTxIndex,
|
||||
setActiveTxIndex,
|
||||
warmupPeriod,
|
||||
isOpened,
|
||||
closeModal,
|
||||
|
||||
@ -2,76 +2,116 @@ import { createContext, useEffect, useContext, useState, useMemo, useCallback, u
|
||||
import { Unstable } from "@substrate/connect-discovery"
|
||||
import { createClient } from "@polkadot-api/substrate-client"
|
||||
import { getObservableClient } from "@polkadot-api/observable-client"
|
||||
import { getInjectedExtensions, connectInjectedExtension } from "polkadot-api/pjs-signer";
|
||||
import useSWR from "swr"
|
||||
|
||||
import { createClient as createClientOther } from "polkadot-api";
|
||||
import { getSmProvider } from "polkadot-api/sm-provider"
|
||||
import { startFromWorker } from "polkadot-api/smoldot/from-worker"
|
||||
import SmWorker from "polkadot-api/smoldot/worker?worker"
|
||||
|
||||
import { casper as casperMetadata } from "@polkadot-api/descriptors";
|
||||
import { casperChainSpec } from "./chainSpecs";
|
||||
|
||||
const GHOST_CONNECT_EXTENSION = "GHOST Connect Browser Extension"
|
||||
const MAX_BLOCK_TIMEOUT = 15000
|
||||
const DEFAULT_CHAIN_ID = "0x475e48fab52f3d0587b6b03101d224560c549e984d1dee197b7d8b55830e7da3"
|
||||
const MAX_CONNECT_ATTEMPTS = 20;
|
||||
const DEFAULT_CHAIN_ID = "0xcaf9c5ddccc7ba6f96149a6b8a81c26a3641742795cd5e7e0aee79bf3f4e77b7"
|
||||
const UnstableProvider = createContext(null)
|
||||
export const useUnstableProvider = () => useContext(UnstableProvider)
|
||||
|
||||
export const UnstableProviderProvider = ({ children }) => {
|
||||
const [chainId, setChainId] = useState(DEFAULT_CHAIN_ID);
|
||||
const [providerIndex, setProviderIndex] = useState(0);
|
||||
const [client, setClient] = useState(undefined);
|
||||
const [status, setStatus] = useState("loading");
|
||||
|
||||
const { data: providerDetails } = useSWR("getGhostProviders", () =>
|
||||
Unstable.getSubstrateConnectExtensionProviders()
|
||||
);
|
||||
const [selectedExtension, setSelectedExtension] = useState(null);
|
||||
const [selectedAccountIndex, setSelectedAccountIndex] = useState(0);
|
||||
const [accounts, setAccounts] = useState([]);
|
||||
|
||||
const providerDetail = useMemo(() => providerDetails?.at(providerIndex), [providerDetails, providerIndex]);
|
||||
useEffect(() => {
|
||||
let isMounted = true;
|
||||
let provider = null;
|
||||
|
||||
const { data: provider } = useSWR(
|
||||
() => providerDetail ? `ghostProviderDetail.${providerDetail.info.uuid}.provider` : null,
|
||||
() => providerDetail ? providerDetail.provider : null
|
||||
);
|
||||
try {
|
||||
const smoldot = startFromWorker(new SmWorker());
|
||||
provider = createClientOther(
|
||||
getSmProvider(() => smoldot.addChain({ chainSpec: casperChainSpec })),
|
||||
)
|
||||
|
||||
const { data: accounts } = useSWR(
|
||||
() => providerDetail ? `providerDetail.${providerDetail.info.uuid}.provider.getAccounts(${chainId})` : null,
|
||||
async () => {
|
||||
if (!providerDetail) return []
|
||||
const activeProvider = await providerDetail.provider;
|
||||
return activeProvider.getAccounts(chainId);
|
||||
},
|
||||
)
|
||||
if (isMounted) {
|
||||
setClient(provider);
|
||||
setStatus("connected");
|
||||
}
|
||||
|
||||
const account = useMemo(() => {
|
||||
if (Array.isArray(accounts)) return accounts?.at(0)?.address;
|
||||
if (typeof accounts === 'string') return accounts?.address;
|
||||
return undefined
|
||||
}, [accounts])
|
||||
} catch (error) {
|
||||
console.error("Smoldot initialization failed:", error);
|
||||
if (isMounted) setStatus("error");
|
||||
}
|
||||
|
||||
const connectionState = useMemo(() => {
|
||||
if (!providerDetail) return 'no-extension';
|
||||
if (!provider) return 'loading';
|
||||
return () => {
|
||||
isMounted = false;
|
||||
if (provider) provider.destroy();
|
||||
};
|
||||
}, []);
|
||||
|
||||
const chains = provider.getChains();
|
||||
if (chains[chainId]) return 'connected';
|
||||
useEffect(() => {
|
||||
if (status !== "connected") return;
|
||||
let isMounted = true;
|
||||
|
||||
return 'wrong-network';
|
||||
}, [providerDetail, provider, chainId]);
|
||||
(async () => {
|
||||
let targetExt = null;
|
||||
let attempts = 0;
|
||||
|
||||
const client = useMemo(() => {
|
||||
if (!provider || !chainId) return undefined;
|
||||
while (attempts < MAX_CONNECT_ATTEMPTS && isMounted) {
|
||||
const extensions = getInjectedExtensions();
|
||||
targetExt = extensions.find(ext => ext === GHOST_CONNECT_EXTENSION);
|
||||
|
||||
const chain = provider.getChains()[chainId];
|
||||
if (!chain) return undefined;
|
||||
if (targetExt) break;
|
||||
|
||||
return createClient(chain.connect)
|
||||
}, [provider, chainId]);
|
||||
attempts += 1;
|
||||
await new Promise((r) => setTimeout(r, 300));
|
||||
}
|
||||
|
||||
const observableClient = useMemo(() => client ? getObservableClient(client) : undefined, [client]);
|
||||
const chainHead$ = useMemo(() => observableClient?.chainHead$(), [observableClient]);
|
||||
if (!targetExt) {
|
||||
console.warn(
|
||||
`[UnstableProvider] "${GHOST_CONNECT_EXTENSION}" not found after ${MAX_CONNECT_ATTEMPTS} attempts. Available:`,
|
||||
getInjectedExtensions()
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
const ext = await connectInjectedExtension(targetExt);
|
||||
if (isMounted) setSelectedExtension(ext);
|
||||
})();
|
||||
|
||||
return () => { isMounted = false; };
|
||||
}, [status]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!selectedExtension) return;
|
||||
|
||||
const extensionAccounts = selectedExtension.getAccounts();
|
||||
setAccounts(extensionAccounts)
|
||||
|
||||
const unsubscribe = selectedExtension.subscribe((updatedAccounts) => {
|
||||
setAccounts(updatedAccounts);
|
||||
});
|
||||
|
||||
return unsubscribe;
|
||||
}, [selectedExtension]);
|
||||
|
||||
const account = useMemo(() => accounts?.at(selectedAccountIndex), [accounts, selectedAccountIndex]);
|
||||
const casperApi = useMemo(() => client?.getTypedApi(casperMetadata), [client]);
|
||||
const finalizedBlock$ = useMemo(() => client?.finalizedBlock$, [client]);
|
||||
|
||||
const value = useMemo(() => ({
|
||||
isExtensionMissing: connectionState === "no-extension",
|
||||
providerDetails,
|
||||
providerDetail,
|
||||
connectProviderByIndex: setProviderIndex,
|
||||
chainId,
|
||||
account,
|
||||
status,
|
||||
client,
|
||||
setChainId,
|
||||
chainHead$
|
||||
}), [providerDetails, providerDetail, chainId, client, account, chainHead$]);
|
||||
account,
|
||||
accounts,
|
||||
casperApi,
|
||||
finalizedBlock$,
|
||||
}), [accounts, status, client, finalizedBlock$]);
|
||||
|
||||
return (
|
||||
<UnstableProvider.Provider value={value}>
|
||||
|
||||
36
src/hooks/ghost/chainSpecs.js
Normal file
36
src/hooks/ghost/chainSpecs.js
Normal file
@ -0,0 +1,36 @@
|
||||
export const casperChainSpec = `{
|
||||
"badBlocks": null,
|
||||
"bootNodes": [
|
||||
"/dns/bootnode007.ghostchain.io/tcp/30335/p2p/12D3KooWF9SWxz9dmy6vfndQhoxqCa7PESaoFWEiF8Jkqh4xKDRf",
|
||||
"/dns/bootnode007.ghostchain.io/tcp/30336/ws/p2p/12D3KooWF9SWxz9dmy6vfndQhoxqCa7PESaoFWEiF8Jkqh4xKDRf",
|
||||
"/dns/bootnode007.ghostchain.io/tcp/443/wss/p2p/12D3KooWF9SWxz9dmy6vfndQhoxqCa7PESaoFWEiF8Jkqh4xKDRf",
|
||||
"/dns/bootnode70.chain.ghostchain.io/tcp/30334/p2p/12D3KooWP3h5dSdqcpvsCr7fp1jyfqDj291QDZ68a4gY6VQ8T1nW",
|
||||
"/dns/bootnode70.chain.ghostchain.io/tcp/30335/ws/p2p/12D3KooWP3h5dSdqcpvsCr7fp1jyfqDj291QDZ68a4gY6VQ8T1nW",
|
||||
"/dns/bootnode70.chain.ghostchain.io/tcp/30336/wss/p2p/12D3KooWP3h5dSdqcpvsCr7fp1jyfqDj291QDZ68a4gY6VQ8T1nW"
|
||||
],
|
||||
"chainType": "Live",
|
||||
"forkBlocks": null,
|
||||
"genesis": {
|
||||
"stateRootHash": "0xb4784a3c8f2f29ba3f191d563f1166f08f4e0337e114679c0f24ef77d06e10e4"
|
||||
},
|
||||
"id": "casper_staging_testnet",
|
||||
"lightSyncState": {
|
||||
"babeEpochChanges": "0x042c315b655c7144df4bfdc41837eeacb84d80aee06eaba51f6941a0c7a26cb1bf5d090000015e9de408000000000ea2e40800000000049b2e88b8ce43a677c1ca90f62134800b7e510c0c353dad719cad82faf6136cfb0d0e0000010ea2e40800000000bea6e408000000000000082c315b655c7144df4bfdc41837eeacb84d80aee06eaba51f6941a0c7a26cb1bf5d0900000103000000000000005e9de40800000000b00400000000000014daaaaab6a6e574099e24ae9bb75b543610edef9d374fa85a378edb573b47615f010000000000000074fa7381a7a74b316afb6793a00387eed9d95d46a69866cbb316b5d9c918af0e0100000000000000e0f0a776ecc9fa5e1f22e2fa001fe3fba5aea52b9444bc894b45589d4213247501000000000000006c4dd88b43e2011cf9a6a73d53446336ac9e04cdd4ca23587df63187ac455e4901000000000000003c944c704cae203619b9e7a5a4b6742736da6a8e76c762291bebdc7652cfec2f01000000000000002ff7c765405e9c11a59525a08173bb1fa59e5e281090f8e4d1824469f513d0cc01000000000000000400000000000000029b2e88b8ce43a677c1ca90f62134800b7e510c0c353dad719cad82faf6136cfb0d0e00000104000000000000000ea2e40800000000b00400000000000014daaaaab6a6e574099e24ae9bb75b543610edef9d374fa85a378edb573b47615f010000000000000074fa7381a7a74b316afb6793a00387eed9d95d46a69866cbb316b5d9c918af0e0100000000000000e0f0a776ecc9fa5e1f22e2fa001fe3fba5aea52b9444bc894b45589d4213247501000000000000006c4dd88b43e2011cf9a6a73d53446336ac9e04cdd4ca23587df63187ac455e4901000000000000003c944c704cae203619b9e7a5a4b6742736da6a8e76c762291bebdc7652cfec2f0100000000000000dea465ff8bf16938cc9ead89bf9fdb5d9c495fad61fd952b2067ebdc51c4e1c10100000000000000040000000000000002",
|
||||
"babeFinalizedBlockWeight": 1039,
|
||||
"finalizedBlockHeader": "0x6ed6c2debc2e5fd4e7db0d14426d1b904e6c101f2c62a71b8e891c217ba79079f9433280c0257a860f793833bd6bed6b9f86094400aa8e5ea24a81752f0f046ff5ed560f7231760c622ae35d3968fbab033ed34d950b57a7937ae45c411d1d384748080642414245b50103000000004fa0e40800000000a2c7d71b4e1f94c0208c9730ab93955b08c8d7ac86d2fc6ec5f62cc3272a5f1ec0e28c798461372109ee3e12f03ff66ea5ad9cac5b1c37d7280d2333d0226f0865ea77a801bad79785a8ca83c87f0dbf1e36936a6f65cd7b125a41c52f38f80105424142450101caaa6fe5f9df57930e2ac08aef43b75d5477d410c73c3a8e6dea9d5503b9fd25eae1d12b6604194389e22f3f4265d581eb162d1dc5a9034247fe33765dddbe8c",
|
||||
"grandpaAuthoritySet": "0x1455446f9a7aa99ced06b317c80ce90d56b84e56526775683af2525969e8da0b640100000000000000236d2fa03f4ed8cb65de7e514d7540159b328f1c170dd402b094ad7fbf5472180100000000000000b63c5a0cf342b9b04931bc8ed74d7d0165ab99ab5f8a4514797d4b299a4501fe01000000000000008f9ea20bf4a807a8e710f7559dece86e94672b5b361de157bdaa5c1f37849f8d01000000000000000aa3a88f6b777c95c3dfe7e997b76798413f16aa325f34824cae0c9102b281d5010000000000000000000000000000000001fe1000000000"
|
||||
},
|
||||
"name": "Casper Staging Testnet",
|
||||
"properties": {
|
||||
"ss58Format": 1996,
|
||||
"tokenDecimals": 18,
|
||||
"tokenSymbol": "CSPR"
|
||||
},
|
||||
"protocolId": "cspr",
|
||||
"telemetryEndpoints": [
|
||||
[
|
||||
"/dns/telemetry.ghostchain.io/tcp/443/x-parity-wss/%2Fsubmit%2F",
|
||||
0
|
||||
]
|
||||
]
|
||||
}`;
|
||||
@ -1,12 +1,13 @@
|
||||
import toast from "react-hot-toast";
|
||||
import { simulateContract, writeContract, waitForTransactionReceipt } from "@wagmi/core";
|
||||
import { encodeFunctionData, BaseError, UserRejectedRequestError } from 'viem';
|
||||
import { estimateGas, simulateContract, writeContract, waitForTransactionReceipt } from "@wagmi/core";
|
||||
|
||||
import {
|
||||
RESERVE_ADDRESSES,
|
||||
FTSO_ADDRESSES,
|
||||
STNK_ADDRESSES,
|
||||
GHST_ADDRESSES,
|
||||
FTSO_DAI_LP_ADDRESSES,
|
||||
FTSO_RESERVE_LP_ADDRESSES,
|
||||
WETH_ADDRESSES,
|
||||
} from "../constants/addresses";
|
||||
import { config } from "../config";
|
||||
@ -134,10 +135,10 @@ export const getTokenAddress = (chainId, name) => {
|
||||
address = GHST_ADDRESSES[chainId];
|
||||
break;
|
||||
case "GDAI_FTSO":
|
||||
address = FTSO_DAI_LP_ADDRESSES[chainId];
|
||||
address = FTSO_RESERVE_LP_ADDRESSES[chainId];
|
||||
break;
|
||||
case "RESERVE_FTSO":
|
||||
address = FTSO_DAI_LP_ADDRESSES[chainId];
|
||||
address = FTSO_RESERVE_LP_ADDRESSES[chainId];
|
||||
break;
|
||||
case "WETH":
|
||||
address = WETH_ADDRESSES[chainId];
|
||||
@ -173,7 +174,7 @@ export const getTokenIcons = (chainId, address) => {
|
||||
case GHST_ADDRESSES[chainId]:
|
||||
icons = ["GHST"];
|
||||
break;
|
||||
case FTSO_DAI_LP_ADDRESSES[chainId]:
|
||||
case FTSO_RESERVE_LP_ADDRESSES[chainId]:
|
||||
icons = ["WETH", "FTSO"];
|
||||
break;
|
||||
default:
|
||||
@ -185,7 +186,7 @@ export const getTokenIcons = (chainId, address) => {
|
||||
export const getChainTokenNames = (chainId, address) => {
|
||||
let icons = [undefined];
|
||||
switch (address) {
|
||||
case FTSO_DAI_LP_ADDRESSES[chainId]:
|
||||
case FTSO_RESERVE_LP_ADDRESSES[chainId]:
|
||||
icons = [undefined, "WETH"];
|
||||
break;
|
||||
case RESERVE_ADDRESSES[chainId]:
|
||||
@ -199,7 +200,7 @@ export const getChainTokenNames = (chainId, address) => {
|
||||
|
||||
export const getBondNameDisplayName = (chainId, tokenAddress, baseTokenSymbol) => {
|
||||
let stringValue = tokenNameConverter(chainId, "WETH")
|
||||
if (tokenAddress.toUpperCase() === FTSO_DAI_LP_ADDRESSES[chainId].toUpperCase()) {
|
||||
if (tokenAddress.toUpperCase() === FTSO_RESERVE_LP_ADDRESSES[chainId].toUpperCase()) {
|
||||
stringValue = `${baseTokenSymbol}-${stringValue} LP`;
|
||||
}
|
||||
return stringValue;
|
||||
@ -209,13 +210,14 @@ export const getTokenPurchaseLink = (chainId, tokenAddress, chainName) => {
|
||||
let purchaseUrl = `https://app.dao.ghostchain.io/#/${chainName}/dex/uniswap`;
|
||||
switch (tokenAddress) {
|
||||
case RESERVE_ADDRESSES[chainId]:
|
||||
purchaseUrl = `https://app.dao.ghostchain.io/#/${chainName}/faucet`;
|
||||
if (chainId == 63) {
|
||||
purchaseUrl = `https://app.dao.ghostchain.io/#/${chainName}/wrapper`;
|
||||
}
|
||||
purchaseUrl = `https://ghostchain.io/faucet/`;
|
||||
break;
|
||||
case FTSO_DAI_LP_ADDRESSES[chainId]:
|
||||
purchaseUrl += `?pool=true&from=${RESERVE_ADDRESSES[chainId]}&to=${FTSO_ADDRESSES[chainId]}`;
|
||||
case FTSO_RESERVE_LP_ADDRESSES[chainId]:
|
||||
const reserve = RESERVE_ADDRESSES[chainId] === WETH_ADDRESSES[chainId]
|
||||
? "0x0000000000000000000000000000000000000000"
|
||||
: RESERVE_ADDRESSES[chainId];
|
||||
|
||||
purchaseUrl += `?pool=true&from=${reserve}&to=${FTSO_ADDRESSES[chainId]}`;
|
||||
break;
|
||||
}
|
||||
return purchaseUrl;
|
||||
@ -229,7 +231,8 @@ export const executeOnChainTransaction = async ({
|
||||
args,
|
||||
account,
|
||||
messages,
|
||||
value
|
||||
value,
|
||||
gasMultiplier = 100n, // 100%
|
||||
}) => {
|
||||
try {
|
||||
const { request } = await simulateContract(config, {
|
||||
@ -242,19 +245,169 @@ export const executeOnChainTransaction = async ({
|
||||
value,
|
||||
});
|
||||
|
||||
const txHash = await writeContract(config, request);
|
||||
const data = encodeFunctionData({ abi, functionName, args });
|
||||
const estimatedGas = await estimateGas(config, {
|
||||
account,
|
||||
to: address,
|
||||
data,
|
||||
value,
|
||||
chainId,
|
||||
});
|
||||
|
||||
const bufferedGas = (estimatedGas * BigInt(gasMultiplier)) / 100n;
|
||||
|
||||
const txHash = await writeContract(config, {
|
||||
...request,
|
||||
gas: bufferedGas,
|
||||
});
|
||||
|
||||
await waitForTransactionReceipt(config, {
|
||||
hash: txHash,
|
||||
onReplaced: () => toast(messages.replacedMsg),
|
||||
chainId
|
||||
});
|
||||
// TODO: onReplaced
|
||||
|
||||
toast.success(messages.successMsg);
|
||||
|
||||
return txHash;
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
toast.error(messages.errorMsg)
|
||||
return undefined;
|
||||
if (err instanceof BaseError) {
|
||||
const rejectionError = err.walk((e) => e instanceof UserRejectedRequestError);
|
||||
|
||||
if (rejectionError) {
|
||||
console.log("User rejected the transaction in their wallet.");
|
||||
return undefined;
|
||||
}
|
||||
} else {
|
||||
console.error(err)
|
||||
}
|
||||
|
||||
toast.error(messages.errorMsg)
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
export const executePapiBareTransaction = async ({
|
||||
client,
|
||||
bareTx,
|
||||
messages = {
|
||||
loadingMsg: "Broadcasting transaction to available peers...",
|
||||
inBlockMsg: "Transaction included in block, waiting for finality...",
|
||||
successMsg: "Transaction successfully finalized!",
|
||||
errorMsg: "Transaction failed.",
|
||||
},
|
||||
}) => {
|
||||
try {
|
||||
return await new Promise((resolve, reject) => {
|
||||
const subscription = client.submitAndWatch(bareTx).subscribe({
|
||||
next: (event) => {
|
||||
if (event.type === "broadcasted") {
|
||||
toast.success(messages.loadingMsg);
|
||||
} else if (event.type === "inBestBlock") {
|
||||
toast.success(messages.inBlockMsg);
|
||||
} else if (event.type === "finalized") {
|
||||
toast.success(messages.successMsg);
|
||||
subscription.unsubscribe();
|
||||
resolve(event);
|
||||
}
|
||||
},
|
||||
error: (err) => {
|
||||
toast.error(`${messages.errorMsg} ${err.message || err}`);
|
||||
subscription.unsubscribe();
|
||||
reject(err);
|
||||
},
|
||||
});
|
||||
});
|
||||
} catch (err) {
|
||||
console.error("Bare PAPI Transaction failed:", err);
|
||||
return undefined;
|
||||
}
|
||||
};
|
||||
|
||||
export const executePapiSignedTransaction = async ({
|
||||
tx,
|
||||
signer,
|
||||
messages = {
|
||||
loadingMsg: "Waiting for wallet signature...",
|
||||
inBlockMsg: "Transaction included in block, finalizing...",
|
||||
successMsg: "Transaction confirmed and finalized!",
|
||||
errorMsg: "Transaction failed.",
|
||||
}
|
||||
}) => {
|
||||
try {
|
||||
const toastId = toast.success(messages.loadingMsg, { duration: Infinity });
|
||||
|
||||
return await new Promise((resolve, reject) => {
|
||||
const subscription = tx.createSubmitAndWatch(signer).subscribe({
|
||||
next: (event) => {
|
||||
switch (event.type) {
|
||||
case "created":
|
||||
toast.success("Transaction signed, submitting to network...", {
|
||||
id: toastId,
|
||||
duration: Infinity,
|
||||
});
|
||||
break;
|
||||
case "broadcasted":
|
||||
toast.success("Transaction sent, waiting for block inclusion...", {
|
||||
id: toastId,
|
||||
duration: Infinity,
|
||||
});
|
||||
break;
|
||||
case "inBestBlock":
|
||||
if (event.ok) {
|
||||
toast.success(messages.inBlockMsg, {
|
||||
id: toastId,
|
||||
duration: Infinity,
|
||||
});
|
||||
} else {
|
||||
toast.error("Transaction reverted on-chain.", {
|
||||
id: toastId,
|
||||
duration: 2000,
|
||||
});
|
||||
subscription.unsubscribe();
|
||||
reject(new Error("Transaction failed on-chain"));
|
||||
}
|
||||
break;
|
||||
case "notInBestBlock":
|
||||
toast.success("Chain reorganized, waiting for re-inclusion...", {
|
||||
id: toastId,
|
||||
duration: Infinity,
|
||||
});
|
||||
break;
|
||||
case "finalized":
|
||||
const { txHash, block, events, ok } = event;
|
||||
|
||||
if (ok) {
|
||||
toast.success(messages.successMsg, {
|
||||
id: toastId,
|
||||
duration: 2000,
|
||||
});
|
||||
subscription.unsubscribe();
|
||||
resolve({ txHash, blockHash: block.hash, events });
|
||||
} else {
|
||||
toast.error("Transaction finalized with an on-chain error.", {
|
||||
id: toastId,
|
||||
duration: 5000,
|
||||
});
|
||||
subscription.unsubscribe();
|
||||
reject(new Error("Transaction failed on-chain"));
|
||||
}
|
||||
break;
|
||||
}
|
||||
},
|
||||
error: (err) => {
|
||||
toast.error(`${messages.errorMsg} ${err.message || err}`, {
|
||||
id: toastId,
|
||||
duration: 5000,
|
||||
});
|
||||
subscription.unsubscribe();
|
||||
reject(err);
|
||||
},
|
||||
});
|
||||
});
|
||||
} catch (err) {
|
||||
console.error("PAPI Signed Transaction failed:", err);
|
||||
return undefined;
|
||||
}
|
||||
};
|
||||
|
||||
@ -1,26 +1,127 @@
|
||||
import { createContext, useContext, useState, useEffect } from "react";
|
||||
import useSWR, { mutate } from "swr";
|
||||
|
||||
const BRIDGE_IN = "Bridge-In";
|
||||
const BRIDGE_OUT = "Bridge-Out";
|
||||
const DEX_ACTION = "DEX";
|
||||
const STAKE_ACTION = "Stake";
|
||||
const BOND_ACTION = "Bond";
|
||||
|
||||
const DEX_ACTION_SWAP = "Swap";
|
||||
const DEX_ACTION_ADD = "Add Liquidity";
|
||||
const DEX_ACTION_REMOVE = "Remove Liquidity";
|
||||
|
||||
const BOND_ACTION_BOND = "Bond";
|
||||
const BOND_ACTION_CLAIM = "Claim";
|
||||
const BOND_ACTION_EXODUS = "Exodus";
|
||||
|
||||
const STAKE_ACTION_STAKE = "Stake";
|
||||
const UNSTAKE_ACTION_STAKE = "Unstake";
|
||||
const WRAP_ACTION_STAKE = "Wrap";
|
||||
const UNWRAP_ACTION_STAKE = "Unwrap";
|
||||
|
||||
const POSSIBLE_HISTORY_TYPES = [BRIDGE_IN, BRIDGE_OUT, DEX_ACTION, STAKE_ACTION, BOND_ACTION];
|
||||
const DEFAULT_HISTORY_TYPES = [BRIDGE_IN, BRIDGE_OUT];
|
||||
|
||||
const HISTORY_PREFIX = "history";
|
||||
const PENDING_HISTORY_PREIFX = "pending";
|
||||
|
||||
const LocalStorageContext = createContext();
|
||||
export const useLocalStorage = () => useContext(LocalStorageContext);
|
||||
|
||||
const CONSTANTS = {
|
||||
possibleHistoryTypes: POSSIBLE_HISTORY_TYPES,
|
||||
defaultHistoryTypes: DEFAULT_HISTORY_TYPES,
|
||||
historyPrefix: HISTORY_PREFIX,
|
||||
pendingHistoryPrefix: PENDING_HISTORY_PREIFX,
|
||||
|
||||
bridgeIn: { key: BRIDGE_IN, name: BRIDGE_IN },
|
||||
bridgeOut: { key: BRIDGE_OUT, name: BRIDGE_OUT },
|
||||
dex: { key: DEX_ACTION, swap: DEX_ACTION_SWAP, add: DEX_ACTION_ADD, remove: DEX_ACTION_REMOVE },
|
||||
bond: {
|
||||
key: BOND_ACTION,
|
||||
bond: BOND_ACTION_BOND,
|
||||
claim: BOND_ACTION_CLAIM,
|
||||
exodus: BOND_ACTION_EXODUS,
|
||||
},
|
||||
stake: {
|
||||
key: STAKE_ACTION,
|
||||
stake: STAKE_ACTION_STAKE,
|
||||
unstake: UNSTAKE_ACTION_STAKE,
|
||||
wrap: WRAP_ACTION_STAKE,
|
||||
unwrap: UNWRAP_ACTION_STAKE,
|
||||
},
|
||||
};
|
||||
|
||||
export const LocalStorageProvider = ({ children }) => {
|
||||
const getStorageKey = (chainId, address, target) => {
|
||||
return `${chainId}:${address}:${target}`;
|
||||
}
|
||||
|
||||
const getStorageValue = (chainId, address, target, defaultValue) => {
|
||||
const key = getStorageKey(chainId, address, target);
|
||||
const stored = localStorage.getItem(key);
|
||||
return stored ? JSON.parse(stored) : defaultValue;
|
||||
}
|
||||
const useStorageValue = (chainId, address, target, defaultValue) => {
|
||||
return useSWR(
|
||||
chainId && address ? ["local", chainId, address, target] : null,
|
||||
([_, chainId, address, target]) => {
|
||||
const key = getStorageKey(chainId, address, target);
|
||||
const stored = localStorage.getItem(key);
|
||||
return stored ? JSON.parse(stored) : defaultValue;
|
||||
},
|
||||
{ revalidateOnFocus: false, fallbackData: defaultValue }
|
||||
);
|
||||
};
|
||||
|
||||
const setStorageValue = (chainId, address, target, value) => {
|
||||
const setStorageValue = async (chainId, address, target, value) => {
|
||||
const key = getStorageKey(chainId, address, target);
|
||||
localStorage.setItem(key, JSON.stringify(value));
|
||||
await mutate(["local", chainId, address, target]);
|
||||
}
|
||||
|
||||
const clearPendingHistory = async (chainId, address, target) => {
|
||||
const key = getStorageKey(chainId, address, PENDING_HISTORY_PREIFX);
|
||||
const stored = localStorage.getItem(key);
|
||||
if (!stored) return
|
||||
|
||||
const pendingValues = JSON.parse(stored);
|
||||
if (target in pendingValues) {
|
||||
delete pendingValues[target];
|
||||
localStorage.setItem(key, JSON.stringify(pendingValues));
|
||||
await mutate(["local", chainId, address, PENDING_HISTORY_PREIFX]);
|
||||
}
|
||||
}
|
||||
|
||||
const tryStoreInHistory = async (chainId, address, target, txHash, name, isCustom = false) => {
|
||||
const historyKey = getStorageKey(chainId, address, HISTORY_PREFIX);
|
||||
const storedHistoryTypes = localStorage.getItem(historyKey);
|
||||
const historyTypes = storedHistoryTypes ? JSON.parse(storedHistoryTypes) : DEFAULT_HISTORY_TYPES;
|
||||
if (!historyTypes.includes(target)) return;
|
||||
|
||||
const key = getStorageKey(chainId, address, target);
|
||||
const stored = localStorage.getItem(key);
|
||||
const values = stored ? JSON.parse(stored) : [];
|
||||
|
||||
const value = { name, txHash, submitted: Date.now(), isCustom };
|
||||
const newValues = [value, ...values];
|
||||
localStorage.setItem(key, JSON.stringify(newValues));
|
||||
|
||||
const pendingKey = getStorageKey(chainId, address, PENDING_HISTORY_PREIFX);
|
||||
const pendingItems = localStorage.getItem(pendingKey);
|
||||
const pendingValues = pendingItems ? JSON.parse(pendingItems) : {};
|
||||
|
||||
const currentCount = pendingValues[target] || 0;
|
||||
pendingValues[target] = currentCount + 1;
|
||||
localStorage.setItem(pendingKey, JSON.stringify(pendingValues));
|
||||
|
||||
await mutate(["local", chainId, address, PENDING_HISTORY_PREIFX]);
|
||||
}
|
||||
|
||||
return (
|
||||
<LocalStorageContext.Provider value={{ getStorageValue, setStorageValue }}>
|
||||
<LocalStorageContext.Provider value={{
|
||||
CONSTANTS,
|
||||
tryStoreInHistory,
|
||||
useStorageValue,
|
||||
clearPendingHistory,
|
||||
setStorageValue
|
||||
}}>
|
||||
{children}
|
||||
</LocalStorageContext.Provider>
|
||||
)
|
||||
|
||||
@ -5,7 +5,7 @@ import { useCurrentIndex, useGhostedSupply } from "../staking";
|
||||
import { useUniswapV2PairReserves } from "../uniswapv2";
|
||||
import { DecimalBigNumber } from "../../helpers/DecimalBigNumber";
|
||||
import {
|
||||
FTSO_DAI_LP_ADDRESSES,
|
||||
FTSO_RESERVE_LP_ADDRESSES,
|
||||
RESERVE_ADDRESSES,
|
||||
FTSO_ADDRESSES,
|
||||
CEX_TICKERS,
|
||||
@ -135,13 +135,13 @@ export const useReservePrice = (chainId) => {
|
||||
};
|
||||
|
||||
export const useFtsoPrice = (chainId) => {
|
||||
const { reserves, tokens, refetch } = useUniswapV2PairReserves(chainId, FTSO_DAI_LP_ADDRESSES[chainId]);
|
||||
const { reserves, tokens, refetch } = useUniswapV2PairReserves(chainId, FTSO_RESERVE_LP_ADDRESSES[chainId]);
|
||||
|
||||
const reservePrice = useReservePrice(chainId);
|
||||
const reserveAddress = RESERVE_ADDRESSES[chainId];
|
||||
const ftsoAddress = FTSO_ADDRESSES[chainId];
|
||||
if (!reserveAddress || !ftsoAddress) {
|
||||
return new DecimalBigNumber(0n, 9);
|
||||
return new DecimalBigNumber(1n, 9);
|
||||
}
|
||||
|
||||
const stableReserves = reserveAddress.toUpperCase() === tokens.token0.toUpperCase()
|
||||
|
||||
@ -1,4 +1,5 @@
|
||||
import { useReadContract } from "wagmi";
|
||||
import { readContract } from "@wagmi/core";
|
||||
import toast from "react-hot-toast";
|
||||
|
||||
import {
|
||||
@ -11,12 +12,177 @@ import {
|
||||
import { STAKING_ADDRESSES } from "../../constants/addresses";
|
||||
import { abi as StakingAbi } from "../../abi/GhostStaking.json";
|
||||
import { abi as GatekeeperAbi } from "../../abi/GhostGatekeeper.json";
|
||||
import { abi as GhostStorageHistoryAbi } from "../../abi/GhostStorageHistory.json";
|
||||
|
||||
import { shorten } from "../../helpers";
|
||||
import { DecimalBigNumber } from "../../helpers/DecimalBigNumber";
|
||||
import { executeOnChainTransaction } from "../helpers";
|
||||
import { executeOnChainTransaction, getTokenDecimals } from "../helpers";
|
||||
import { useCirculatingSupply } from "../tokens";
|
||||
|
||||
export const useRotationInfoAt = (chainId, session) => {
|
||||
const { gatekeeperAddress } = useGatekeeperAddress(chainId);
|
||||
|
||||
const { data: rotationInfoAt, isLoading: rotationInfoAtLoading } = useReadContract({
|
||||
abi: GatekeeperAbi,
|
||||
address: gatekeeperAddress,
|
||||
args: [session],
|
||||
functionName: "getRotationInfoAt",
|
||||
scopeKey: `getRotationInfoAt-${chainId}-${session}-${gatekeeperAddress}`,
|
||||
chainId: chainId,
|
||||
});
|
||||
|
||||
return { rotationInfoAt, rotationInfoAtLoading };
|
||||
}
|
||||
|
||||
export const useIsTransactionExecuted = (chainId, index) => {
|
||||
const { gatekeeperAddress } = useGatekeeperAddress(chainId);
|
||||
|
||||
const { data: storageHistory } = useReadContract({
|
||||
abi: GatekeeperAbi,
|
||||
address: gatekeeperAddress,
|
||||
functionName: "storageHistory",
|
||||
scopeKey: `storageHistory-${chainId}-${gatekeeperAddress}`,
|
||||
chainId: chainId,
|
||||
});
|
||||
|
||||
const {
|
||||
data: isTransactionExecuted,
|
||||
isLoading: isTransactionExecutedLoading,
|
||||
refetch: refetchTransactionExecuted
|
||||
} = useReadContract({
|
||||
abi: GhostStorageHistoryAbi,
|
||||
address: storageHistory,
|
||||
functionName: "isTransactionExecuted",
|
||||
args: [index],
|
||||
scopeKey: `isTransactionExecuted-${chainId}-${storageHistory}`,
|
||||
chainId: chainId,
|
||||
});
|
||||
|
||||
return { isTransactionExecuted, isTransactionExecutedLoading, refetchTransactionExecuted }
|
||||
}
|
||||
|
||||
export const useCurrentGasPrice = (chainId) => {
|
||||
const { gatekeeperAddress } = useGatekeeperAddress(chainId);
|
||||
|
||||
const { data: gasPrice } = useReadContract({
|
||||
abi: GatekeeperAbi,
|
||||
address: gatekeeperAddress,
|
||||
functionName: "getCurrentGasPrice",
|
||||
scopeKey: `currentGasPrice-${chainId}-${gatekeeperAddress}`,
|
||||
chainId: chainId,
|
||||
});
|
||||
|
||||
const { data } = useReadContract({
|
||||
abi: GatekeeperAbi,
|
||||
address: gatekeeperAddress,
|
||||
functionName: "MAX_ALLOWED_GAS_PRICE",
|
||||
scopeKey: `MAX_ALLOWED_GAS_PRICE-${chainId}-${gatekeeperAddress}`,
|
||||
chainId: chainId,
|
||||
});
|
||||
|
||||
const maxGasPrice = new DecimalBigNumber(data ? data : 1n, 9);
|
||||
const currentGasPrice = new DecimalBigNumber(gasPrice ? gasPrice : 1n, 9);
|
||||
|
||||
return { currentGasPrice, maxGasPrice };
|
||||
}
|
||||
|
||||
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 : 0n };
|
||||
}
|
||||
|
||||
export const useWeaverMaximumSlots = (chainId) => {
|
||||
const { gatekeeperAddress } = useGatekeeperAddress(chainId);
|
||||
|
||||
const { data } = useReadContract({
|
||||
abi: GatekeeperAbi,
|
||||
address: gatekeeperAddress,
|
||||
functionName: "SLOTS",
|
||||
scopeKey: `SLOTS-${chainId}-${gatekeeperAddress}`,
|
||||
chainId: chainId,
|
||||
});
|
||||
|
||||
return { maximumSlots: data ? data : 1n };
|
||||
}
|
||||
|
||||
export const useWeaverRoot = (chainId, blockNumber, context) => {
|
||||
const session = context?.session;
|
||||
const { gatekeeperAddress } = useGatekeeperAddress(chainId);
|
||||
|
||||
const { data } = useReadContract({
|
||||
abi: GatekeeperAbi,
|
||||
address: gatekeeperAddress,
|
||||
functionName: "getRoot",
|
||||
args: [session, blockNumber],
|
||||
scopeKey: `getRoot-${chainId}-${session}-${blockNumber}-${gatekeeperAddress}`,
|
||||
chainId: chainId,
|
||||
});
|
||||
|
||||
return { merkleRoot: data?.at(0), nextSession: data?.at(1) }
|
||||
}
|
||||
|
||||
export const useWeaverProof = (chainId, blockNumber, context) => {
|
||||
const index = context?.index;
|
||||
const session = context?.session;
|
||||
const { gatekeeperAddress } = useGatekeeperAddress(chainId);
|
||||
|
||||
const { data: merkleProofInner } = useReadContract({
|
||||
abi: GatekeeperAbi,
|
||||
address: gatekeeperAddress,
|
||||
functionName: "getProof",
|
||||
args: [index, session, blockNumber],
|
||||
scopeKey: `getProof-${chainId}-${session}-${index}-${blockNumber}-${gatekeeperAddress}`,
|
||||
chainId: chainId,
|
||||
});
|
||||
|
||||
return { merkleProof: merkleProofInner }
|
||||
}
|
||||
|
||||
export const useWeaverSlotValues = (chainId, blockNumber, context) => {
|
||||
const index = context?.index;
|
||||
const session = context?.session;
|
||||
const { gatekeeperAddress } = useGatekeeperAddress(chainId);
|
||||
|
||||
const { data: slotValuesInner } = useReadContract({
|
||||
abi: GatekeeperAbi,
|
||||
address: gatekeeperAddress,
|
||||
functionName: "getSlotValues",
|
||||
args: [index, session, blockNumber],
|
||||
scopeKey: `getSlotValues-${chainId}-${session}-${index}-${blockNumber}-${gatekeeperAddress}`,
|
||||
chainId: chainId,
|
||||
});
|
||||
|
||||
return { slotValues: slotValuesInner }
|
||||
}
|
||||
|
||||
export const useGatekeeperMinimum = (chainId) => {
|
||||
const { gatekeeperAddress } = useGatekeeperAddress(chainId);
|
||||
|
||||
const { data: minimum, error } = useReadContract({
|
||||
abi: GatekeeperAbi,
|
||||
address: gatekeeperAddress,
|
||||
functionName: "EXISTENTIAL_DEPOSIT",
|
||||
scopeKey: `existentialDeposit-${chainId}-${gatekeeperAddress}`,
|
||||
chainId: chainId,
|
||||
});
|
||||
|
||||
const existentialDeposit = new DecimalBigNumber(
|
||||
minimum ? minimum : 0n,
|
||||
getTokenDecimals("GHST"),
|
||||
);
|
||||
|
||||
return { existentialDeposit };
|
||||
}
|
||||
|
||||
export const useGatekeeperApy = (chainId) => {
|
||||
const circulatingSupply = useCirculatingSupply(chainId, "STNK");
|
||||
const { gatekeeperAddress } = useGatekeeperAddress(chainId);
|
||||
@ -32,11 +198,11 @@ export const useGatekeeperApy = (chainId) => {
|
||||
|
||||
const amountIn = new DecimalBigNumber(
|
||||
(metadata?.amountIn ?? 0n) + (amountInHistory[chainId] ?? 0n),
|
||||
18,
|
||||
getTokenDecimals("GHST"),
|
||||
);
|
||||
const amountOut = new DecimalBigNumber(
|
||||
(metadata?.amountOut ?? 0n) + (amountOutHistory[chainId] ?? 0n),
|
||||
18,
|
||||
getTokenDecimals("GHST"),
|
||||
);
|
||||
|
||||
const deployedAt = metadata?.deployedAt ?? 0;
|
||||
@ -154,7 +320,8 @@ export const useGatekeeperAddress = (chainId) => {
|
||||
});
|
||||
|
||||
const gatekeeperAddress = info ? info : "0x0000000000000000000000000000000000000000";
|
||||
return { gatekeeperAddress, refetch };
|
||||
const gatekeeperIsEmpty = gatekeeperAddress === "0x0000000000000000000000000000000000000000";
|
||||
return { gatekeeperAddress, gatekeeperIsEmpty, refetch };
|
||||
}
|
||||
|
||||
export const useGhostedSupply = (chainId) => {
|
||||
@ -181,7 +348,7 @@ export const stake = async (chainId, account, amount, isRebase, isClaim, ftsoSym
|
||||
successMsg: `${ftsoSymbol} tokens staked successfully! Wait for the warm-up period to claim your ${isRebase ? stnkSymbol : ghstSymbol}.`,
|
||||
errorMsg: "Staking transaction failed. Check logs for error detalization.",
|
||||
};
|
||||
await executeOnChainTransaction({
|
||||
const txHash = await executeOnChainTransaction({
|
||||
chainId,
|
||||
args,
|
||||
messages,
|
||||
@ -190,6 +357,7 @@ export const stake = async (chainId, account, amount, isRebase, isClaim, ftsoSym
|
||||
address: STAKING_ADDRESSES[chainId],
|
||||
functionName: "stake",
|
||||
});
|
||||
return txHash;
|
||||
}
|
||||
|
||||
export const unstake = async (chainId, account, amount, isTrigger, isRebase, ftsoSymbol, stnkSymbol, ghstSymbol) => {
|
||||
@ -199,7 +367,7 @@ export const unstake = async (chainId, account, amount, isTrigger, isRebase, fts
|
||||
successMsg: `${isRebase ? stnkSymbol : ghstSymbol} tokens unstaked successfully! Check your ${ftsoSymbol} balance on ${shorten(account)}.`,
|
||||
errorMsg: "Unstake transaction failed. Check logs for error detalization.",
|
||||
};
|
||||
await executeOnChainTransaction({
|
||||
const txHash = await executeOnChainTransaction({
|
||||
chainId,
|
||||
args,
|
||||
messages,
|
||||
@ -208,6 +376,7 @@ export const unstake = async (chainId, account, amount, isTrigger, isRebase, fts
|
||||
address: STAKING_ADDRESSES[chainId],
|
||||
functionName: "unstake",
|
||||
});
|
||||
return txHash;
|
||||
}
|
||||
|
||||
export const forfeit = async (chainId, account, ftsoSymbol) => {
|
||||
@ -216,7 +385,7 @@ export const forfeit = async (chainId, account, ftsoSymbol) => {
|
||||
successMsg: `Tokens forfeited successfully! Check your ${ftsoSymbol} balance on ${shorten(account)}.`,
|
||||
errorMsg: "Forfeit transaction failed. Check logs for error detalization.",
|
||||
};
|
||||
await executeOnChainTransaction({
|
||||
const txHash = await executeOnChainTransaction({
|
||||
chainId,
|
||||
messages,
|
||||
account,
|
||||
@ -225,6 +394,7 @@ export const forfeit = async (chainId, account, ftsoSymbol) => {
|
||||
address: STAKING_ADDRESSES[chainId],
|
||||
functionName: "forfeit",
|
||||
});
|
||||
return txHash;
|
||||
}
|
||||
|
||||
export const claim = async (chainId, account, isStnk, stnkSymbol, ghstSymbol) => {
|
||||
@ -234,7 +404,7 @@ export const claim = async (chainId, account, isStnk, stnkSymbol, ghstSymbol) =>
|
||||
successMsg: `${isStnk ? stnkSymbol : ghstSymbol} tokens claimed successfully to ${shorten(account)}.`,
|
||||
errorMsg: "Claim transaction failed. Check logs for error detalization.",
|
||||
};
|
||||
await executeOnChainTransaction({
|
||||
const txHash = await executeOnChainTransaction({
|
||||
chainId,
|
||||
args,
|
||||
messages,
|
||||
@ -243,6 +413,7 @@ export const claim = async (chainId, account, isStnk, stnkSymbol, ghstSymbol) =>
|
||||
address: STAKING_ADDRESSES[chainId],
|
||||
functionName: "claim",
|
||||
});
|
||||
return txHash;
|
||||
}
|
||||
|
||||
export const breakout = async (chainId, account, receiver, amount) => {
|
||||
@ -261,7 +432,6 @@ export const breakout = async (chainId, account, receiver, amount) => {
|
||||
address: STAKING_ADDRESSES[chainId],
|
||||
functionName: "breakout",
|
||||
});
|
||||
|
||||
return txHash;
|
||||
}
|
||||
|
||||
@ -269,7 +439,7 @@ export const unwrap = async (chainId, account, amount, stnkSymbol) => {
|
||||
const args = [account, amount];
|
||||
const messages = {
|
||||
replacedMsg: "Unwrap transaction was replaced. Wait for inclusion please.",
|
||||
successMsg: `Tokens unwrapped successfully! Check your ${stnkSymbol} balance on ${shorten(account)}.`,
|
||||
successMsg: `Tokens unwrapped succesfully! Check your ${stnkSymbol} balance on ${shorten(account)}.`,
|
||||
errorMsg: "Unwrap transaction failed. Check logs for error detalization.",
|
||||
};
|
||||
const txHash = await executeOnChainTransaction({
|
||||
@ -281,6 +451,7 @@ export const unwrap = async (chainId, account, amount, stnkSymbol) => {
|
||||
address: STAKING_ADDRESSES[chainId],
|
||||
functionName: "unwrap",
|
||||
});
|
||||
return txHash;
|
||||
}
|
||||
|
||||
export const wrap = async (chainId, account, amount, ghstSymbol) => {
|
||||
@ -299,13 +470,14 @@ export const wrap = async (chainId, account, amount, ghstSymbol) => {
|
||||
address: STAKING_ADDRESSES[chainId],
|
||||
functionName: "wrap",
|
||||
});
|
||||
return txHash;
|
||||
}
|
||||
|
||||
export const ghost = async (chainId, account, receiver, amount) => {
|
||||
const args = [receiver, amount];
|
||||
const messages = {
|
||||
replacedMsg: "Bridge transaction was replaced. Wait for inclusion please.",
|
||||
successMsg: `Amount successfully bridged! Check tx hash status or wait for slow clap finalization.`,
|
||||
successMsg: `Amount successfully bridged! Check Transaction History to trace the progress.`,
|
||||
errorMsg: "Bridge transaction failed. Check logs for error detalization.",
|
||||
};
|
||||
const txHash = await executeOnChainTransaction({
|
||||
@ -317,6 +489,27 @@ export const ghost = async (chainId, account, receiver, amount) => {
|
||||
address: STAKING_ADDRESSES[chainId],
|
||||
functionName: "ghost",
|
||||
});
|
||||
return txHash;
|
||||
}
|
||||
|
||||
export const verifySignature = async ({ chainId, account, gatekeeper, calldata, nonce, signature }) => {
|
||||
const args = [calldata, nonce, signature];
|
||||
const messages = {
|
||||
replacedMsg: "Verification transaction was replaced. Wait for inclusion please.",
|
||||
successMsg: `Verification succesfully passed! Check Transaction History to trace the progress.`,
|
||||
errorMsg: "Verification transaction failed. Check logs for error detalization.",
|
||||
};
|
||||
|
||||
const txHash = await executeOnChainTransaction({
|
||||
chainId,
|
||||
args,
|
||||
messages,
|
||||
account,
|
||||
abi: GatekeeperAbi,
|
||||
address: gatekeeper,
|
||||
functionName: "verify",
|
||||
gasMultiplier: 145n, // 45% more
|
||||
});
|
||||
|
||||
return txHash;
|
||||
}
|
||||
|
||||
@ -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);
|
||||
|
||||
@ -124,14 +141,14 @@ export const useTokenSymbol = (chainId, name) => {
|
||||
}
|
||||
|
||||
export const useTokenSymbols = (chainId, names) => {
|
||||
const { data: symbols } = useReadContracts({
|
||||
const { data: symbols, error } = useReadContracts({
|
||||
contracts: names?.map((name) => {
|
||||
const contractAddress = getTokenAddress(chainId, name);
|
||||
return {
|
||||
abi: getTokenAbi(name),
|
||||
address: contractAddress,
|
||||
functionName: "symbol",
|
||||
scopeKey: `symbol-${contractAddress}-${chainId}`,
|
||||
scopeKey: `symbol-${contractAddress}-${chainId}-${name}`,
|
||||
chainId: chainId,
|
||||
}
|
||||
})
|
||||
|
||||
@ -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";
|
||||
|
||||
@ -9,6 +10,21 @@ import { bigIntSqrt } from "../../helpers";
|
||||
import { DecimalBigNumber } from "../../helpers/DecimalBigNumber";
|
||||
import { getTokenAddress } from "../helpers";
|
||||
|
||||
export const useCapturedPriceSnapshots = (chainId, address) => {
|
||||
const { data } = useReadContract({
|
||||
abi: TreasuryAbi,
|
||||
address: DAO_TREASURY_ADDRESSES[chainId],
|
||||
functionName: "capturedPriceSnapshots",
|
||||
args: [address],
|
||||
scopeKey: `capturedPriceSnapshots-${address}-${chainId}`,
|
||||
chainId: chainId
|
||||
});
|
||||
|
||||
const capturedPriceSnapshots = new DecimalBigNumber(data ? data : 0n, 18);
|
||||
|
||||
return { capturedPriceSnapshots }
|
||||
}
|
||||
|
||||
export const useOrinalCoefficient = (chainId) => {
|
||||
const { data: original } = useReadContract({
|
||||
abi: TreasuryAbi,
|
||||
@ -21,6 +37,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,
|
||||
|
||||
@ -33,7 +33,7 @@ export const swapExactETHForTokens = async ({
|
||||
deadline
|
||||
];
|
||||
|
||||
await executeOnChainTransaction({
|
||||
const txHash = await executeOnChainTransaction({
|
||||
chainId,
|
||||
args,
|
||||
abi: RouterAbi,
|
||||
@ -43,6 +43,8 @@ export const swapExactETHForTokens = async ({
|
||||
messages: swapMessages,
|
||||
value: amountADesired,
|
||||
});
|
||||
|
||||
return txHash;
|
||||
}
|
||||
|
||||
export const swapExactTokensForETH = async ({
|
||||
@ -63,7 +65,7 @@ export const swapExactTokensForETH = async ({
|
||||
deadline
|
||||
];
|
||||
|
||||
await executeOnChainTransaction({
|
||||
const txHash = await executeOnChainTransaction({
|
||||
chainId,
|
||||
args,
|
||||
abi: RouterAbi,
|
||||
@ -72,6 +74,8 @@ export const swapExactTokensForETH = async ({
|
||||
account: address,
|
||||
messages: swapMessages,
|
||||
});
|
||||
|
||||
return txHash;
|
||||
}
|
||||
|
||||
export const swapExactTokensForTokens = async ({
|
||||
@ -92,7 +96,7 @@ export const swapExactTokensForTokens = async ({
|
||||
deadline
|
||||
];
|
||||
|
||||
await executeOnChainTransaction({
|
||||
const txHash = await executeOnChainTransaction({
|
||||
chainId,
|
||||
args,
|
||||
abi: RouterAbi,
|
||||
@ -101,6 +105,8 @@ export const swapExactTokensForTokens = async ({
|
||||
account: address,
|
||||
messages: swapMessages,
|
||||
});
|
||||
|
||||
return txHash;
|
||||
}
|
||||
|
||||
export const addLiquidity = async ({
|
||||
@ -126,7 +132,7 @@ export const addLiquidity = async ({
|
||||
deadline
|
||||
];
|
||||
|
||||
await executeOnChainTransaction({
|
||||
const txHash = await executeOnChainTransaction({
|
||||
chainId,
|
||||
args,
|
||||
abi: RouterAbi,
|
||||
@ -135,6 +141,8 @@ export const addLiquidity = async ({
|
||||
account: address,
|
||||
messages: addMessages,
|
||||
});
|
||||
|
||||
return txHash;
|
||||
}
|
||||
|
||||
export const addLiquidityETH = async ({
|
||||
@ -172,7 +180,7 @@ export const addLiquidityETH = async ({
|
||||
deadline
|
||||
];
|
||||
|
||||
await executeOnChainTransaction({
|
||||
const txHash = await executeOnChainTransaction({
|
||||
chainId,
|
||||
args,
|
||||
abi: RouterAbi,
|
||||
@ -182,4 +190,6 @@ export const addLiquidityETH = async ({
|
||||
messages: addMessages,
|
||||
value: amountETHDesired,
|
||||
});
|
||||
|
||||
return txHash;
|
||||
}
|
||||
|
||||
@ -18,12 +18,12 @@ export const darkPalette = {
|
||||
success: "#60C45B", // idk where this is - done
|
||||
userFeedback: "#49A1F2", // idk where this is
|
||||
error: "#F06F73", // red negative % - done
|
||||
warning: "#ed6c02", // idk where this is - done
|
||||
warning: "#F2E370", // idk where this is - done
|
||||
pnlGain: "#60C45B", // green positive % - done
|
||||
},
|
||||
bridgeProgress: {
|
||||
error: "#F06F73",
|
||||
warning: "#ed6c02",
|
||||
warning: "#F2E370",
|
||||
success: "#60C45B",
|
||||
},
|
||||
validatorsColor: {
|
||||
|
||||
Loading…
Reference in New Issue
Block a user