prepare breakout modal based on new localstorage logic

Signed-off-by: Uncle Fatso <uncle.fatso@ghostchain.io>
This commit is contained in:
Uncle Fatso 2026-11-10 19:34:53 +03:00
parent 094904c163
commit 190933cc9c
Signed by: f4ts0
GPG Key ID: 565F4F2860226EBB
11 changed files with 410 additions and 218 deletions

View File

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

View File

@ -26,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) => {

View File

@ -144,7 +144,7 @@ export const BondConfirmModal = ({
isNative
});
if (txHash) tryStoreInHistory(chainId, sender, CONSTANTS.bond.key, txHash, CONSTANTS.bond.name);
if (txHash) tryStoreInHistory(chainId, sender, CONSTANTS.bond.key, txHash, CONSTANTS.bond.bond);
setIsPending(false);
handleConfirmCloseMaster();

View File

@ -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,13 @@ 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 })
}
setPendingIndexes([]);
setIsPending(false);
}

View File

@ -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,34 +10,57 @@ 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 { bridgeNumbers } from "../../constants";
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);
const [convertedReceiver, setConvertedReceiver] = useState(undefined);
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,
@ -45,28 +68,21 @@ 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("");
closeModalInner();
}
}
const header = useMemo(() => {
@ -92,7 +108,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}
@ -105,13 +126,18 @@ 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
@ -121,26 +147,30 @@ const BreakoutModal = ({ chainId, address }) => {
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>
@ -148,121 +178,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);
@ -290,7 +224,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>
@ -304,26 +238,143 @@ const WelcomeView = ({
<Typography fontWeight="bold">Skip the Warm-up Now!</Typography>
<Typography>
Bridge your {ghstSymbol} to GHOST Chain and start{" "}
<Box component="span" sx={{ whiteSpace: "nowrap" }}>{bridgeNumbers}</Box>{" "}
<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, or{" "}
<Link
component="button"
type="button"
variant="body1"
underline="hover"
onClick={() => setReceiver(account)}
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>
</>
)
@ -333,84 +384,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 (
<>
@ -432,7 +444,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%" }} />

View File

@ -291,7 +291,7 @@ const BridgeIn = ({ chainId, address, config, connect }) => {
return amount * result / hundredPercent
}, [amount, networkData]);
const gatekeepersDifferent = useMemo(() => {
const gatekeepersMatch = useMemo(() => {
if (!networkData) return false;
return gatekeeperAddress.toUpperCase() == toHex(networkData.gatekeeper).toUpperCase();
}, [gatekeeperAddress, networkData]);
@ -541,7 +541,7 @@ const BridgeIn = ({ chainId, address, config, connect }) => {
<PrimaryButton
fullWidth
disabled={actionDisabled}
disabled={!gatekeepersMatch || actionDisabled}
onClick={startGhostBridge}
>
{isPending ? "Pending..." : "Bridge-In"}

View File

@ -8,16 +8,20 @@ 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 { formatCurrency, shorten } from "../../helpers";
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 ERC20Token } from "../../abi/ERC20.json";
import TokenBox from "./TokenBox";
const BondModal = ({ chainId, isOpen, close, config, historyRecord }) => {
const BondModalClaim = ({ chainId, isOpen, close, config, historyRecord }) => {
if (historyRecord === null) return null;
const { network } = useParams();
@ -42,6 +46,157 @@ const BondModal = ({ chainId, isOpen, close, config, historyRecord }) => {
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>
)
}
const BondModalBond = ({ chainId, isOpen, close, config, historyRecord }) => {
if (historyRecord === null) return null;
const { network } = useParams();
const { CONSTANTS } = useLocalStorage();
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 });
@ -186,4 +341,29 @@ const BondModal = ({ chainId, isOpen, close, config, historyRecord }) => {
)
}
const BondModal = ({ chainId, isOpen, close, config, historyRecord }) => {
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}
/>
default:
return null;
}
}
export default BondModal;

View File

@ -44,7 +44,7 @@ export const useBondInfo = (chainId, chainName, indexes) => {
const ftsoPrice = useFtsoPrice(chainId);
const baseTokenPerUsd = useReservePrice(chainId);
const originalCoefficient = useOrinalCoefficient(chainId);
const { data: markets } = useReadContracts({
contracts: indexes?.map((id) => ({
abi: BondAbi,
@ -311,7 +311,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,
@ -320,6 +320,8 @@ export const redeem = async ({ chainId, user, isGhst, indexes }) => {
functionName: "redeem",
account: user,
});
return txHash;
}
export const forceRedeem = async ({ chainId, user, receiver, indexes }) => {

View File

@ -7,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);
@ -45,8 +44,6 @@ export const BreakoutModalProvider = ({ children }) => {
<BreakoutModalContext.Provider value={{
isStakingOpened,
isClaimBondOpened,
activeTxIndex,
setActiveTxIndex,
warmupPeriod,
isOpened,
closeModal,

View File

@ -10,6 +10,9 @@ const BOND_ACTION = "Bond";
const DEX_ACTION_SWAP = "Swap";
const DEX_ACTION_ADD = "Add Liquidity";
const BOND_ACTION_BOND = "Bond";
const BOND_ACTION_CLAIM = "Claim";
const STAKE_ACTION_STAKE = "Stake";
const UNSTAKE_ACTION_STAKE = "Unstake";
const WRAP_ACTION_STAKE = "Wrap";
@ -33,7 +36,11 @@ const CONSTANTS = {
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 },
bond: { key: BOND_ACTION, name: BOND_ACTION },
bond: {
key: BOND_ACTION,
bond: BOND_ACTION_BOND,
claim: BOND_ACTION_CLAIM,
},
stake: {
key: STAKE_ACTION,
stake: STAKE_ACTION_STAKE,

View File

@ -97,7 +97,7 @@ export const useGatekeeperMinimum = (chainId) => {
getTokenDecimals("GHST"),
);
return { existentialDeposit};
return { existentialDeposit };
}
export const useGatekeeperApy = (chainId) => {