implement exodus page with verification for rotation messages
Signed-off-by: Uncle Fatso <uncle.fatso@ghostchain.io>
This commit is contained in:
parent
8b6a47d196
commit
ce7c973929
@ -1,5 +1,5 @@
|
||||
{
|
||||
"version": "0.1.0-autogenerated.3461409763779961730",
|
||||
"version": "0.1.0-autogenerated.17780546383012228608",
|
||||
"name": "@polkadot-api/descriptors",
|
||||
"files": [
|
||||
"dist"
|
||||
|
||||
@ -3,7 +3,7 @@
|
||||
"descriptorPath": ".papi\\descriptors",
|
||||
"entries": {
|
||||
"casper": {
|
||||
"metadata": "casper_runtime.scale"
|
||||
"metadata": "casper-metadata.scale"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Binary file not shown.
@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "ghost-dao-interface",
|
||||
"private": true,
|
||||
"version": "0.8.23",
|
||||
"version": "0.8.24",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
|
||||
@ -39,7 +39,7 @@ importers:
|
||||
specifier: ^6.4.6
|
||||
version: 6.4.6(@types/react@19.0.10)(react@19.0.0)
|
||||
'@polkadot-api/descriptors':
|
||||
specifier: file:./.papi/descriptors
|
||||
specifier: file:.papi/descriptors
|
||||
version: file:.papi/descriptors(polkadot-api@3.3.0(bufferutil@4.0.9)(esbuild@0.25.0)(rxjs@7.8.1)(utf-8-validate@5.0.10))
|
||||
'@polkadot-api/metadata-builders':
|
||||
specifier: 0.13.0
|
||||
|
||||
@ -219,7 +219,7 @@ function InitialWalletView({ isWalletOpen, address, chainId, onClose }) {
|
||||
currency={currency}
|
||||
setCurrency={setCurrency}
|
||||
chainName={chainProperties?.name ?? ""}
|
||||
address={account ?? "...wait"}
|
||||
address={account?.address ?? "...wait"}
|
||||
tokens={nativeGhst}
|
||||
/>
|
||||
<NativeToken {...nativeGhst} />
|
||||
|
||||
@ -106,8 +106,8 @@ const BridgeIn = ({ chainId, address, config, connect }) => {
|
||||
const [settingsOpen, setSettingsOpen] = useState(false);
|
||||
const [confirmOpen, setConfirmOpen] = useState(false);
|
||||
const [amount, setAmount] = useState("");
|
||||
const [receiver, setReceiver] = useState(account);
|
||||
const [customReceiver, setCustomReceiver] = useState(account);
|
||||
const [receiver, setReceiver] = useState(account ? account.address : "");
|
||||
const [customReceiver, setCustomReceiver] = useState(account ? account.address : "");
|
||||
|
||||
const { symbol: ghstSymbol } = useTokenSymbol(chainId, "GHST");
|
||||
const { balance: ghstBalance, refetch: ghstBalanceRefetch } = useBalance(chainId, "GHST", address);
|
||||
|
||||
@ -34,7 +34,8 @@ import { useUnstableProvider } from "../../hooks/ghost";
|
||||
import { useGatekeeperApy, useGatekeeperAddress, useGhostedSupply } from "../../hooks/staking";
|
||||
import { useLocalStorage } from "../../hooks/localstorage";
|
||||
import { useTokenSymbol, useBalance } from "../../hooks/tokens";
|
||||
import { formatNumber, formatCurrency } from "../../helpers";
|
||||
import { executePapiSignedTransaction } from "../../hooks/helpers";
|
||||
import { countBitmapOnes, formatNumber, formatCurrency } from "../../helpers";
|
||||
|
||||
import { BridgeOutSettingsModal } from "./BridgeSettingsModal";
|
||||
import { BridgeOutConfirmationModal } from "./BridgeConfirmationModal"
|
||||
@ -84,7 +85,9 @@ const BridgeStatusCard = ({ progressPercent, totalValidators, pendingValidators,
|
||||
|
||||
<LinearProgressBar
|
||||
variant={typeof progressPercent === "number" ? "determinate" : "indeterminate"}
|
||||
value={progressPercent ? progressPercent : 0}
|
||||
value={progressPercent
|
||||
? dkgPhaseType === "Finalized" ? 100 : progressPercent
|
||||
: 0}
|
||||
height={6}
|
||||
barColor={theme.colors.feedback.success}
|
||||
/>
|
||||
@ -170,8 +173,8 @@ const BridgeOut = ({ chainId, address, config, connect }) => {
|
||||
);
|
||||
|
||||
const { data: accountBalanceRaw } = useSWR(
|
||||
client ? ['accountBalance', client] : null,
|
||||
() => casperApi.query.System.Account.getValue(account),
|
||||
casperApi && account?.address ? ['accountBalance', account.address] : null,
|
||||
() => casperApi.query.System.Account.getValue(account.address),
|
||||
{
|
||||
refreshInterval: 12000,
|
||||
revalidateOnFocus: true
|
||||
@ -188,9 +191,9 @@ const BridgeOut = ({ chainId, address, config, connect }) => {
|
||||
return new DecimalBigNumber(balance, decimals);
|
||||
}, [accountBalanceRaw, chainProperties]);
|
||||
|
||||
const { data: qualificationAuthorities } = useSWR(
|
||||
const { data: qualificationAuthorities, error } = useSWR(
|
||||
casperApi ? ['qualificationAuthorities', casperApi] : null,
|
||||
() => casperApi.query.GhostExodus.QualificationAuthorities.getValue(),
|
||||
() => casperApi.query.GhostExodus.QualificationAuthorities.getValue({ type: "Secp256k1" }),
|
||||
);
|
||||
|
||||
const { data: activeEraStart } = useSWR(
|
||||
@ -216,6 +219,15 @@ const BridgeOut = ({ chainId, address, config, connect }) => {
|
||||
}
|
||||
);
|
||||
|
||||
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(),
|
||||
@ -258,6 +270,127 @@ const BridgeOut = ({ chainId, address, config, connect }) => {
|
||||
}
|
||||
);
|
||||
|
||||
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,
|
||||
@ -268,28 +401,6 @@ const BridgeOut = ({ chainId, address, config, connect }) => {
|
||||
else return gatekeeperAmount;
|
||||
}, [ghostedSupply, networkGatekeeperAmount, chainProperties]);
|
||||
|
||||
const participants = useMemo(() => {
|
||||
if (!qualificationDkgState) return { total: 0, participated: 0 }
|
||||
|
||||
const countOnes32 = (n) => {
|
||||
let count = 0;
|
||||
let num = n >>> 0;
|
||||
|
||||
while (num > 0) {
|
||||
num &= num - 1;
|
||||
count++;
|
||||
}
|
||||
|
||||
return count;
|
||||
}
|
||||
|
||||
const authorities = qualificationDkgState.authorities_indexes
|
||||
const totalParticipants = authorities.active_bits_count;
|
||||
const particpatedCount = authorities.data.reduce((sum, word) => sum + countOnes32(word), 0);
|
||||
|
||||
return { total: totalParticipants, participated: particpatedCount };
|
||||
}, [qualificationDkgState]);
|
||||
|
||||
useEffect(() => {
|
||||
setMsSinceLastBlock(0);
|
||||
|
||||
@ -367,9 +478,60 @@ const BridgeOut = ({ chainId, address, config, connect }) => {
|
||||
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 () => {
|
||||
alert("not ready yet");
|
||||
setConfirmOpen(false);
|
||||
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,
|
||||
};
|
||||
|
||||
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 (
|
||||
@ -391,7 +553,7 @@ const BridgeOut = ({ chainId, address, config, connect }) => {
|
||||
ghstSymbol={ghstSymbol}
|
||||
externalSymbol={chainProperties ? chainProperties.properties.tokenSymbol : "CSPR"}
|
||||
receiver={customReceiver ? customReceiver : receiver}
|
||||
sender={account}
|
||||
sender={account ? account.address : ""}
|
||||
startGhostExodus={startGhostExodus}
|
||||
allocation={allocation}
|
||||
nativeSymbol={nativeSymbol}
|
||||
@ -544,10 +706,10 @@ const BridgeOut = ({ chainId, address, config, connect }) => {
|
||||
|
||||
<PrimaryButton
|
||||
fullWidth
|
||||
disabled={actionDisabled}
|
||||
disabled={false || isDkgQualificationPending}
|
||||
onClick={() => setConfirmOpen(true)}
|
||||
>
|
||||
Bridge-Out
|
||||
{isDkgQualificationPending ? "DKG Ongoing" : "Bridge-Out"}
|
||||
</PrimaryButton>
|
||||
</Box>
|
||||
</Paper>
|
||||
|
||||
@ -20,7 +20,8 @@ import {
|
||||
useTheme,
|
||||
} from "@mui/material";
|
||||
|
||||
import SearchIcon from '@mui/icons-material/Search';
|
||||
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";
|
||||
@ -28,9 +29,10 @@ 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 { useTotalReserves, useCapturedPriceSnapshots } from "../../hooks/treasury";
|
||||
import { useCurrentGasPrice } from "../../hooks/staking";
|
||||
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";
|
||||
@ -47,9 +49,11 @@ import ExodusList from "./ExodusList";
|
||||
|
||||
const SELECTABLE_OPTIONS = ["All Exoduses", "Rotations", "Governance", "Bridge-Out"];
|
||||
const KEY_ROTATION = "Key Rotation";
|
||||
const BRIDGE_OUT = "Bridge-Out";
|
||||
|
||||
const GAS_USED = {
|
||||
[KEY_ROTATION]: 300000n,
|
||||
[KEY_ROTATION]: 166000n + 21000n + 5969n + 67585n,
|
||||
[BRIDGE_OUT]: 300000n,
|
||||
}
|
||||
|
||||
const Exodus = ({ chainId, address, config }) => {
|
||||
@ -59,12 +63,11 @@ const Exodus = ({ chainId, address, config }) => {
|
||||
const isSemiSmallScreen = useMediaQuery("(max-width: 850px)");
|
||||
const isVerySmallScreen = useMediaQuery("(max-width: 379px)");
|
||||
|
||||
const [dkgHistory, setDkgHistory] = useState([]);
|
||||
const [searchOpen, setSearchOpen] = useState(false);
|
||||
const [dkgDeviation, setDkgDeviation] = useState(3);
|
||||
const [verifiedItem, setVerifiedItem] = useState(null);
|
||||
const [selected, setSelected] = useState(0);
|
||||
|
||||
const { casperApi } = useUnstableProvider();
|
||||
const { casperApi, client } = useUnstableProvider();
|
||||
|
||||
const nativeMetadata = useMemo(() => {
|
||||
const client = config?.getClient();
|
||||
@ -78,7 +81,6 @@ const Exodus = ({ chainId, address, config }) => {
|
||||
const { data: gasPrice } = useGasPrice(chainId);
|
||||
const { symbol: ftsoSymbol } = useTokenSymbol(chainId, "FTSO");
|
||||
|
||||
const totalReserves = useTotalReserves(chainId);
|
||||
const ftsoPrice = useFtsoPrice(chainId);
|
||||
const reservePrice = useReservePrice(chainId);
|
||||
const { currentGasPrice, maxGasPrice } = useCurrentGasPrice(chainId);
|
||||
@ -98,11 +100,12 @@ const Exodus = ({ chainId, address, config }) => {
|
||||
}, [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 : 0n, 18);
|
||||
const actualGasPerUnit = new DecimalBigNumber(gasPrice ? gasPrice * oneNative : 0n, 18);
|
||||
|
||||
const currentGasPriceCost = currentTwapPrice(currentGasPrice._value).mul(ftsoPrice);
|
||||
const currentGasPriceCost = currentTwapPrice(currentGasPrice._value * oneNative).mul(ftsoPrice);
|
||||
const actualGasPerUnitCost = actualGasPerUnit.mul(reservePrice);
|
||||
|
||||
if (currentGasPriceCost.eq(zero)) return zero;
|
||||
@ -121,28 +124,91 @@ const Exodus = ({ chainId, address, config }) => {
|
||||
}
|
||||
);
|
||||
|
||||
const { data: signedExodusRotations, isLoading: signedExodusRotationsLoading } = useSWR(
|
||||
casperApi &&
|
||||
dkgDeviation &&
|
||||
(selected === 0 || selected === 1) &&
|
||||
activeDkgAuthorities
|
||||
? ['signedExodusRotations', casperApi, dkgDeviation]
|
||||
: null,
|
||||
async ([_, api, deviation]) => {
|
||||
const start = Math.max(0, activeDkgAuthorities.dkg_index - deviation);
|
||||
const length = activeDkgAuthorities.dkg_index - start;
|
||||
const currentDkgIndex = useMemo(() => {
|
||||
if (!activeDkgAuthorities) return null;
|
||||
return dkgHistory.length > 0
|
||||
? dkgHistory[dkgHistory.length - 1].dkgIndex
|
||||
: activeDkgAuthorities.dkg_index;
|
||||
}, [dkgHistory, activeDkgAuthorities]);
|
||||
|
||||
const promises = Array.from({ length }, (_, index) => start + index).map(index =>
|
||||
api.query.GhostExodus.ExodusSignedRotations.getValue(index, { type: "Evm" })
|
||||
.then(data => ({ dkgIndex: index, type: KEY_ROTATION, gasUsed: GAS_USED[KEY_ROTATION], data }))
|
||||
);
|
||||
const currentDkgSession = useMemo(() => {
|
||||
if (!activeDkgAuthorities) return null;
|
||||
return dkgHistory.length > 0
|
||||
? dkgHistory[dkgHistory.length - 1].session
|
||||
: undefined;
|
||||
}, [dkgHistory, activeDkgAuthorities]);
|
||||
|
||||
const results = await Promise.all(promises);
|
||||
return results.filter(item => item.data !== undefined);
|
||||
const { data: signedExodusRotations, isLoading: signedExodusRotationsLoading, error } = 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
|
||||
}
|
||||
{ revalidateOnFocus: true }
|
||||
);
|
||||
|
||||
const {
|
||||
isTransactionExecuted: currentDkgVerified,
|
||||
isTransactionExecutedLoading: currentDkgVerifiedLoading
|
||||
} = useIsTransactionExecuted(
|
||||
Number(signedExodusRotations
|
||||
? signedExodusRotations.exodusContext.network_id
|
||||
: chainId
|
||||
),
|
||||
currentDkgSession,
|
||||
);
|
||||
|
||||
const {
|
||||
isTransactionExecuted: previousDkgVerified,
|
||||
isTransactionExecutedLoading: previousDkgVerifiedLoading
|
||||
} = useIsTransactionExecuted(
|
||||
Number(signedExodusRotations?.exodusContext.network_id),
|
||||
signedExodusRotations?.exodusContext.session
|
||||
);
|
||||
|
||||
// console.log("status", signedExodusRotations?.dkgIndex, currentDkgIndex)
|
||||
// console.log(" ", previousDkgVerified, currentDkgVerified)
|
||||
// console.log(" ", signedExodusRotations?.exodusContext.session, currentDkgSession)
|
||||
|
||||
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 (
|
||||
@ -155,7 +221,6 @@ const Exodus = ({ chainId, address, config }) => {
|
||||
}}
|
||||
>
|
||||
<ExodusVerifyModal
|
||||
chainId={chainId}
|
||||
address={address}
|
||||
isOpen={!!verifiedItem}
|
||||
casperApi={casperApi}
|
||||
@ -175,21 +240,29 @@ const Exodus = ({ chainId, address, config }) => {
|
||||
headerContent={<Typography pr="5px" variant="h6">Exodus Metrics</Typography>}
|
||||
>
|
||||
<MetricCollection>
|
||||
<Metric
|
||||
metric={formatCurrency(totalReserves, 2)}
|
||||
label="Treasury Balance"
|
||||
tooltip="some description to be added"
|
||||
/>
|
||||
|
||||
<Metric
|
||||
metric={formatCurrency(currentTwapPrice(10n ** BigInt(nativeMetadata.decimals)).mul(ftsoPrice), 2)}
|
||||
label="Execution Price"
|
||||
label="Exodus Price"
|
||||
tooltip="some description to be added"
|
||||
/>
|
||||
|
||||
<Metric
|
||||
metric={formatCurrency(ftsoPrice, 2)}
|
||||
label="Market Price"
|
||||
label={`${ftsoSymbol} Price`}
|
||||
tooltip="some description to be added"
|
||||
/>
|
||||
|
||||
<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="Discount"
|
||||
tooltip="some description to be added"
|
||||
/>
|
||||
</MetricCollection>
|
||||
@ -205,14 +278,33 @@ const Exodus = ({ chainId, address, config }) => {
|
||||
fullWidth
|
||||
enableBackground
|
||||
topRight={
|
||||
<Box style={{ position: "absolute", top: "28px", right: "20px", zIndex: 10 }}>
|
||||
<GhostStyledIcon
|
||||
component={SearchIcon}
|
||||
viewBox="0 0 23 23"
|
||||
style={{ display: "flex", cursor: "pointer" }}
|
||||
onClick={() => alert("smart search for exodus will be here")}
|
||||
/>
|
||||
</Box>
|
||||
<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
|
||||
@ -223,42 +315,56 @@ const Exodus = ({ chainId, address, config }) => {
|
||||
alignItems="center"
|
||||
gap="15px"
|
||||
>
|
||||
<Tabs
|
||||
centered={!isSemiSmallScreen}
|
||||
orientation={isSemiSmallScreen ? "vertical" : "horizontal"}
|
||||
textColor="primary"
|
||||
indicatorColor="primary"
|
||||
value={SELECTABLE_OPTIONS[selected]}
|
||||
aria-label="Exodus menu"
|
||||
onChange={(_, selectedValue) => {
|
||||
const index = SELECTABLE_OPTIONS.indexOf(selectedValue);
|
||||
if (index !== -1) setSelected(index);
|
||||
}}
|
||||
TabIndicatorProps={{ style: { display: "none" } }}
|
||||
>
|
||||
{SELECTABLE_OPTIONS.map((option, i) => {
|
||||
return (
|
||||
<Tab
|
||||
key={i}
|
||||
value={option}
|
||||
aria-label={`exodus-${i}-button`}
|
||||
style={{ fontSize: "1.2rem" }}
|
||||
label={<Typography variant="h6">{option}</Typography>}
|
||||
/>
|
||||
)
|
||||
})}
|
||||
</Tabs>
|
||||
<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 ||
|
||||
!previousDkgVerified ||
|
||||
!signedExodusRotations ||
|
||||
signedExodusRotationsLoading ||
|
||||
currentDkgVerifiedLoading
|
||||
}
|
||||
onClick={() => {
|
||||
if (!currentDkgIndex || !currentDkgSession) return;
|
||||
|
||||
setVerifiedItem({
|
||||
type: KEY_ROTATION,
|
||||
gasUsed: GAS_USED[KEY_ROTATION],
|
||||
dkgIndex: currentDkgIndex,
|
||||
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
|
||||
chainId={chainId}
|
||||
disabled={!currentDkgVerified}
|
||||
ftsoSymbol={ftsoSymbol}
|
||||
gasPrice={gasPrice}
|
||||
setVerifiedItem={setVerifiedItem}
|
||||
nativeMetadata={nativeMetadata}
|
||||
currentTwapPrice={currentTwapPrice}
|
||||
signedExodusRotations={signedExodusRotations}
|
||||
signedExodusRotationsLoading={activeDkgAuthoritiesLoading || signedExodusRotationsLoading}
|
||||
signedMessages={signedBridges}
|
||||
isLoading={signedBridgesLoading || activeDkgAuthoritiesLoading}
|
||||
/>
|
||||
</Paper>
|
||||
</Box>
|
||||
|
||||
@ -26,9 +26,10 @@ import { DecimalBigNumber } from "../../helpers/DecimalBigNumber";
|
||||
|
||||
const ExodusItem = ({
|
||||
item,
|
||||
chainId,
|
||||
gasPrice,
|
||||
ftsoSymbol,
|
||||
disabled,
|
||||
isLoading,
|
||||
nativeMetadata,
|
||||
setVerifiedItem,
|
||||
isSmallScreen,
|
||||
@ -40,7 +41,7 @@ const ExodusItem = ({
|
||||
const {
|
||||
isTransactionExecuted,
|
||||
isTransactionExecutedLoading
|
||||
} = useIsTransactionExecuted(chainId, item.data.at(0)?.session);
|
||||
} = useIsTransactionExecuted(item.exodusContext.network_id, item.exodusContext.session);
|
||||
|
||||
const chipStatus = useMemo(() => {
|
||||
const width = isVerySmallScreen ? "21px" : "100px";
|
||||
@ -108,9 +109,9 @@ const ExodusItem = ({
|
||||
<Box display="flex" flexDirection="row" gap="20px">
|
||||
<TertiaryButton
|
||||
fullWidth
|
||||
disabled={isTransactionExecuted || isTransactionExecutedLoading}
|
||||
disabled={disabled || isLoading || isTransactionExecuted || isTransactionExecutedLoading}
|
||||
onClick={() => setVerifiedItem({
|
||||
exodusSession: item.data.at(0).session,
|
||||
exodusContext: item.exodusContext,
|
||||
dkgIndex: item.dkgIndex,
|
||||
type: item.type
|
||||
})}
|
||||
@ -167,9 +168,9 @@ const ExodusItem = ({
|
||||
<Box p="0 30px" display="flex" justifyContent="center" alignItems="center">
|
||||
<TertiaryButton
|
||||
fullWidth
|
||||
disabled={isTransactionExecuted || isTransactionExecutedLoading}
|
||||
disabled={disabled || isLoading || isTransactionExecuted || isTransactionExecutedLoading}
|
||||
onClick={() => setVerifiedItem({
|
||||
exodusSession: item.data.at(0).session,
|
||||
exodusContext: item.exodusContext,
|
||||
dkgIndex: item.dkgIndex,
|
||||
type: item.type
|
||||
})}
|
||||
@ -183,30 +184,23 @@ const ExodusItem = ({
|
||||
}
|
||||
|
||||
const ExodusList = ({
|
||||
chainId,
|
||||
nativeMetadata,
|
||||
setVerifiedItem,
|
||||
ftsoSymbol,
|
||||
gasPrice,
|
||||
disabled,
|
||||
currentTwapPrice,
|
||||
signedMessages,
|
||||
isLoading,
|
||||
signedExodusRotations,
|
||||
signedExodusRotationsLoading,
|
||||
}) => {
|
||||
const isSmallScreen = useMediaQuery("(max-width: 900px)");
|
||||
|
||||
const chainedExoduses = useMemo(() => {
|
||||
let chain = [];
|
||||
|
||||
if (Array.isArray(signedExodusRotations)) chain = [...chain, ...signedExodusRotations];
|
||||
|
||||
return chain;
|
||||
}, [signedExodusRotations]);
|
||||
|
||||
if (signedExodusRotationsLoading) {
|
||||
if (isLoading) {
|
||||
return (
|
||||
<Box my="20px" display="flex" flexDirection="column" justifyContent="center" alignItems="center" gap="50px">
|
||||
<CircularProgress color="primary" />
|
||||
<Typography>Loading Signed Rotations...</Typography>
|
||||
<Typography>Loading Signed Messages...</Typography>
|
||||
</Box>
|
||||
)
|
||||
}
|
||||
@ -214,13 +208,14 @@ const ExodusList = ({
|
||||
if (isSmallScreen) {
|
||||
return (
|
||||
<Box display="flex" flexDirection="column" gap="50px">
|
||||
{chainedExoduses.map((item, i) => {
|
||||
{signedMessages?.map((item, i) => {
|
||||
return (
|
||||
<ExodusItem
|
||||
key={i}
|
||||
item={item}
|
||||
chainId={chainId}
|
||||
gasPrice={gasPrice}
|
||||
disabled={disabled}
|
||||
isLoading={isLoading}
|
||||
ftsoSymbol={ftsoSymbol}
|
||||
setVerifiedItem={setVerifiedItem}
|
||||
currentTwapPrice={currentTwapPrice}
|
||||
@ -245,12 +240,13 @@ const ExodusList = ({
|
||||
</TableRow>
|
||||
</TableHead>
|
||||
<TableBody>
|
||||
{chainedExoduses.map((item, i) => {
|
||||
{signedMessages?.map((item, i) => {
|
||||
return (
|
||||
<ExodusItem
|
||||
key={i}
|
||||
item={item}
|
||||
chainId={chainId}
|
||||
disabled={disabled}
|
||||
isLoading={isLoading}
|
||||
gasPrice={gasPrice}
|
||||
ftsoSymbol={ftsoSymbol}
|
||||
setVerifiedItem={setVerifiedItem}
|
||||
|
||||
@ -13,7 +13,9 @@ import GhostStyledIcon from "../../components/Icon/GhostIcon";
|
||||
import { PrimaryButton } from "../../components/Button";
|
||||
|
||||
import { formatCurrency, shorten } from "../../helpers";
|
||||
import { verifySignature, useGatekeeperAddress } from "../../hooks/staking";
|
||||
import { useUnstableProvider } from "../../hooks/ghost";
|
||||
import { useLocalStorage } from "../../hooks/localstorage";
|
||||
|
||||
export const ExodusVerifyModal = ({
|
||||
chainId,
|
||||
@ -31,6 +33,7 @@ export const ExodusVerifyModal = ({
|
||||
const [isPending, setIsPending] = useState(false);
|
||||
const [copiedIndex, setCopiedIndex] = useState(null);
|
||||
|
||||
const { tryStoreInHistory, CONSTANTS } = useLocalStorage();
|
||||
const { client } = useUnstableProvider();
|
||||
|
||||
const copyToClipboard = (text, index) => {
|
||||
@ -40,10 +43,10 @@ export const ExodusVerifyModal = ({
|
||||
});
|
||||
};
|
||||
|
||||
const { data: signedExodusRotation } = useSWR(
|
||||
casperApi && item ? ['signedExodusRotations', casperApi, item] : null,
|
||||
async ([_, api, it]) => api.query.GhostExodus.ExodusSignedRotations.getValue(it.dkgIndex, { type: "Evm" }),
|
||||
);
|
||||
const {
|
||||
gatekeeperAddress,
|
||||
gatekeeperIsEmpty
|
||||
} = useGatekeeperAddress(Number(item?.exodusContext.network_id));
|
||||
|
||||
const { data: evmMessageMetadata, isLoading: evmMessageMetadataLoading } = useSWR(
|
||||
client && item ? ['evmMessage', client, item] : null,
|
||||
@ -55,21 +58,48 @@ export const ExodusVerifyModal = ({
|
||||
);
|
||||
|
||||
const upcomingGroupKey = useMemo(() => {
|
||||
if (!signedExodusRotation) return null;
|
||||
if (!evmMessageMetadata) return null;
|
||||
|
||||
const publicKey = signedExodusRotation?.at(1)["r#type"].value.public_key;
|
||||
if (!publicKey) return null;
|
||||
const callHex = toHex(evmMessageMetadata.at(0));
|
||||
const extractedPxHex = `0x${callHex.slice(74, 138)}`;
|
||||
|
||||
const cleanHex = publicKey.startsWith('0x04') && publicKey.length === 130
|
||||
? `0x${publicKey.slice(4)}`
|
||||
: publicKey.startsWith('0x')
|
||||
? publicKey
|
||||
: `0x${publicKey}`;
|
||||
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)}`);
|
||||
}, [signedExodusRotation]);
|
||||
}, [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.bond
|
||||
);
|
||||
|
||||
onClose();
|
||||
} finally {
|
||||
setIsPending(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Modal
|
||||
@ -182,13 +212,10 @@ export const ExodusVerifyModal = ({
|
||||
|
||||
<PrimaryButton
|
||||
fullWidth
|
||||
disabled={evmMessageMetadataLoading || !evmMessageMetadata}
|
||||
onClick={() => {
|
||||
alert("not ready for now");
|
||||
onClose();
|
||||
}}
|
||||
disabled={isPending || gatekeeperIsEmpty || evmMessageMetadataLoading || !evmMessageMetadata}
|
||||
onClick={verifySignatureModal}
|
||||
>
|
||||
Verify
|
||||
{isPending ? "Pending..." : "Verify"}
|
||||
</PrimaryButton>
|
||||
</Box>
|
||||
</Modal>
|
||||
|
||||
@ -2,33 +2,44 @@ import { Box, Typography, useTheme } from "@mui/material";
|
||||
import { formatNumber } from "../../helpers";
|
||||
import LinearProgressBar from "../../components/Progress/LinearProgressBar";
|
||||
|
||||
const ExodusStatusCard = ({ progressPercent, executionDiscount, currentGasPrice, maxGasPrice }) => {
|
||||
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">Execution Discount: </Typography>
|
||||
<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
|
||||
}}>
|
||||
{formatNumber(executionDiscount, 2)}%
|
||||
{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" }}>Gas Price:</Typography>
|
||||
<Typography variant="caption">{`${formatNumber(currentGasPrice, 5)} / ${formatNumber(maxGasPrice, 5)} gwei`}</Typography>
|
||||
<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.max(100, Number(currentGasPrice.div(maxGasPrice).toString()) * 100)}
|
||||
value={Math.min(100, Number(currentGasPrice.div(maxGasPrice).toString()) * 100)}
|
||||
height={6}
|
||||
barColor={theme.colors.feedback.success}
|
||||
/>
|
||||
|
||||
@ -18,6 +18,7 @@ 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";
|
||||
|
||||
@ -198,14 +199,35 @@ const BondModalBond = ({ chainId, isOpen, close, config, historyRecord }) => {
|
||||
|
||||
const functionArgs = useMemo(() => {
|
||||
if (!txData) return null;
|
||||
const decoded = decodeFunctionData({ abi: GhostBondDepository, data: txData.input });
|
||||
if (!decoded) return null;
|
||||
|
||||
return {
|
||||
bondId: decoded.args.at(0),
|
||||
amount: decoded.args.at(1),
|
||||
maxPrice: decoded.args.at(2),
|
||||
receiver: decoded.args.at(3),
|
||||
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]);
|
||||
|
||||
@ -235,7 +257,7 @@ const BondModalBond = ({ chainId, isOpen, close, config, historyRecord }) => {
|
||||
|
||||
const bondPurchasePrice = useMemo(() => {
|
||||
const log = allDecodedLogs.find(l => l.eventName === 'Bond');
|
||||
if (!log) return null;
|
||||
if (!log) return 1n;
|
||||
|
||||
return log.args.price;
|
||||
}, [allDecodedLogs]);
|
||||
@ -276,7 +298,9 @@ const BondModalBond = ({ chainId, isOpen, close, config, historyRecord }) => {
|
||||
open={isOpen}
|
||||
headerText={
|
||||
<>
|
||||
{bonds && functionArgs && bondPurchasePrice && "Bond Purchase"}
|
||||
{(bonds && functionArgs && bondPurchasePrice) &&
|
||||
functionArgs.receiver !== "0x0000000000000000000000000000000000000000"
|
||||
? "Bond Purchase" : "Voluntary Verification"}
|
||||
{(!bonds || !functionArgs || !bondPurchasePrice) && "Parsing Transaction Hash"}
|
||||
</>
|
||||
}
|
||||
@ -304,14 +328,18 @@ const BondModalBond = ({ chainId, isOpen, close, config, historyRecord }) => {
|
||||
|
||||
<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, 12, -10)}</Typography>
|
||||
</Link>
|
||||
{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%">
|
||||
|
||||
518
src/containers/History/BridgeOutModal.jsx
Normal file
518
src/containers/History/BridgeOutModal.jsx
Normal file
@ -0,0 +1,518 @@
|
||||
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 { 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 { useIsTransactionExecuted } from "../../hooks/staking";
|
||||
import { DecimalBigNumber } from "../../helpers/DecimalBigNumber";
|
||||
import { countBitmapOnes, shorten, formatNumber, formatCurrency } from "../../helpers";
|
||||
|
||||
const BridgeOutModal = ({ chainId, isOpen, close, config, historyRecord }) => {
|
||||
const navigate = useNavigate();
|
||||
const { network } = useParams();
|
||||
|
||||
const [copiedIndex, setCopiedIndex] = useState(null);
|
||||
const { casperApi, client, account } = useUnstableProvider();
|
||||
|
||||
const copyToClipboard = (text, index) => {
|
||||
navigator.clipboard.writeText(text).then(() => {
|
||||
setCopiedIndex(index);
|
||||
setTimeout(() => setCopiedIndex(null) , 800);
|
||||
});
|
||||
};
|
||||
|
||||
const {
|
||||
isTransactionExecuted,
|
||||
isTransactionExecutedLoading
|
||||
} = useIsTransactionExecuted(chainId, historyRecord.txHash.exodusSession);
|
||||
|
||||
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)
|
||||
}
|
||||
)
|
||||
);
|
||||
|
||||
const { data: roastSessionStates, error } = useSWR(
|
||||
casperApi && historyRecord && chainId ? ["roastSessionStates"] : null,
|
||||
() => casperApi.query.GhostExodus.RoastSessionStates.getEntries(
|
||||
{
|
||||
session: BigInt(historyRecord.txHash.exodusSession),
|
||||
network_id: BigInt(chainId)
|
||||
}
|
||||
)
|
||||
);
|
||||
|
||||
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]);
|
||||
|
||||
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={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={isTransactionExecuted || !signedBridge}
|
||||
onClick={() => {
|
||||
close();
|
||||
navigate(`/${network}/exodus`)
|
||||
}}
|
||||
>
|
||||
{isTransactionExecuted ? "Bridge-Out Finished" : "Verify Bridge-Out"}
|
||||
</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;
|
||||
@ -43,6 +43,7 @@ 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";
|
||||
|
||||
@ -61,6 +62,7 @@ const HistoryItem = ({
|
||||
|
||||
const localString = new Date(item.submitted).toLocaleString();
|
||||
const { symbol: ftsoSymbol } = useTokenSymbol(chainId, "FTSO")
|
||||
const { CONSTANTS } = useLocalStorage();
|
||||
|
||||
const chainInfo = useMemo(() => {
|
||||
const client = config?.getClient();
|
||||
@ -74,13 +76,28 @@ const HistoryItem = ({
|
||||
const delay = Number(finalityDelay * networkAvgBlockSpeed(chainId)) * 1000;
|
||||
const width = isVerySmallScreen ? "21px" : "100px";
|
||||
|
||||
if (item.submitted + delay > currentTime) {
|
||||
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 ? "" : "Ready"} 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 (
|
||||
<>
|
||||
@ -96,11 +113,11 @@ const HistoryItem = ({
|
||||
<Box display="flex" flexDirection="column">
|
||||
<Typography>{localString}</Typography>
|
||||
<Link
|
||||
href={`${chainInfo.url}/tx/${item.txHash}`}
|
||||
href={txHashMetadata.txUrl}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
>
|
||||
<Typography>{shorten(item.txHash)}</Typography>
|
||||
<Typography>{shorten(txHashMetadata.txHash)}</Typography>
|
||||
</Link>
|
||||
</Box>
|
||||
</Box>
|
||||
@ -128,11 +145,11 @@ const HistoryItem = ({
|
||||
<Box ml="10px" display="flex" flexDirection="column" alignItems="flex-start">
|
||||
<Typography>{item?.name ?? "Unknown"}{item?.isCustom ? " (Custom)" : ""}</Typography>
|
||||
<Link
|
||||
href={`${chainInfo.url}/tx/${item.txHash}`}
|
||||
href={txHashMetadata.txUrl}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
>
|
||||
<Typography>{shorten(item.txHash, 7, -5)}</Typography>
|
||||
<Typography>{shorten(txHashMetadata.txHash, 7, -5)}</Typography>
|
||||
</Link>
|
||||
</Box>
|
||||
</Box>
|
||||
@ -275,6 +292,16 @@ const HistoryList = ({ chainId, storedTransactions, historyType, config, eraseRe
|
||||
/>
|
||||
)}
|
||||
|
||||
{viewModalOpen !== null && historyType === CONSTANTS.bridgeOut.key && (
|
||||
<BridgeOutModal
|
||||
chainId={chainId}
|
||||
config={config}
|
||||
close={() => setViewModalOpen(null)}
|
||||
isOpen={true}
|
||||
historyRecord={storedTransactions.at(viewModalOpen)}
|
||||
/>
|
||||
)}
|
||||
|
||||
{viewModalOpen !== null && historyType === CONSTANTS.bond.key && (
|
||||
<BondModal
|
||||
chainId={chainId}
|
||||
@ -341,7 +368,7 @@ const History = ({ chainId, config, tryConnectInjected, address }) => {
|
||||
|
||||
useEffect(() => {
|
||||
clearPendingHistory(chainId, address, storedHistoryTypes.at(historyTypeIndex));
|
||||
}, [storedHistoryTypes, historyTypeIndex])
|
||||
}, [storedHistoryTypes, historyTypeIndex]);
|
||||
|
||||
return (
|
||||
<Box minHeight="calc(100vh - 43px)">
|
||||
|
||||
@ -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)}`;
|
||||
|
||||
@ -86,7 +86,7 @@ export const UnstableProviderProvider = ({ children }) => {
|
||||
return unsubscribe;
|
||||
}, [selectedExtension]);
|
||||
|
||||
const account = useMemo(() => accounts?.at(selectedAccountIndex)?.address, [accounts, selectedAccountIndex]);
|
||||
const account = useMemo(() => accounts?.at(selectedAccountIndex), [accounts, selectedAccountIndex]);
|
||||
const casperApi = useMemo(() => client?.getTypedApi(casperMetadata), [client]);
|
||||
const finalizedBlock$ = useMemo(() => client?.finalizedBlock$, [client]);
|
||||
|
||||
|
||||
@ -1,6 +1,6 @@
|
||||
import toast from "react-hot-toast";
|
||||
import { BaseError, UserRejectedRequestError } from 'viem';
|
||||
import { simulateContract, writeContract, waitForTransactionReceipt } from "@wagmi/core";
|
||||
import { encodeFunctionData, BaseError, UserRejectedRequestError } from 'viem';
|
||||
import { estimateGas, simulateContract, writeContract, waitForTransactionReceipt } from "@wagmi/core";
|
||||
|
||||
import {
|
||||
RESERVE_ADDRESSES,
|
||||
@ -231,7 +231,8 @@ export const executeOnChainTransaction = async ({
|
||||
args,
|
||||
account,
|
||||
messages,
|
||||
value
|
||||
value,
|
||||
gasMultiplier = 100n, // 100%
|
||||
}) => {
|
||||
try {
|
||||
const { request } = await simulateContract(config, {
|
||||
@ -244,7 +245,23 @@ 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,
|
||||
});
|
||||
|
||||
// const txHash = await writeContract(config, request);
|
||||
await waitForTransactionReceipt(config, {
|
||||
hash: txHash,
|
||||
onReplaced: () => toast(messages.replacedMsg),
|
||||
@ -263,6 +280,8 @@ export const executeOnChainTransaction = async ({
|
||||
console.log("User rejected the transaction in their wallet.");
|
||||
return undefined;
|
||||
}
|
||||
} else {
|
||||
console.error(err)
|
||||
}
|
||||
|
||||
toast.error(messages.errorMsg)
|
||||
@ -306,3 +325,90 @@ export const executePapiBareTransaction = async ({
|
||||
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,4 +1,5 @@
|
||||
import { useReadContract } from "wagmi";
|
||||
import { readContract } from "@wagmi/core";
|
||||
import toast from "react-hot-toast";
|
||||
|
||||
import {
|
||||
@ -18,6 +19,21 @@ import { DecimalBigNumber } from "../../helpers/DecimalBigNumber";
|
||||
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);
|
||||
|
||||
@ -29,7 +45,7 @@ export const useIsTransactionExecuted = (chainId, index) => {
|
||||
chainId: chainId,
|
||||
});
|
||||
|
||||
const { data: isTransactionExecuted, isLoading: isTransactionExecutedLoading, error } = useReadContract({
|
||||
const { data: isTransactionExecuted, isLoading: isTransactionExecutedLoading } = useReadContract({
|
||||
abi: GhostStorageHistoryAbi,
|
||||
address: storageHistory,
|
||||
functionName: "isTransactionExecuted",
|
||||
@ -300,7 +316,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) => {
|
||||
@ -418,7 +435,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({
|
||||
@ -470,3 +487,25 @@ export const ghost = async (chainId, account, receiver, amount) => {
|
||||
});
|
||||
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;
|
||||
}
|
||||
|
||||
Loading…
Reference in New Issue
Block a user