From ce7c973929361e3bad2ba73bba81807351901372 Mon Sep 17 00:00:00 2001 From: Uncle Fatso Date: Fri, 20 Nov 2026 04:41:56 +0300 Subject: [PATCH] implement exodus page with verification for rotation messages Signed-off-by: Uncle Fatso --- .papi/descriptors/package.json | 2 +- .papi/polkadot-api.json | 2 +- ...er_runtime.scale => casper-metadata.scale} | Bin 204270 -> 204303 bytes package.json | 2 +- pnpm-lock.yaml | 2 +- .../TopBar/Wallet/InitialWalletView.tsx | 2 +- src/containers/Bridge/BridgeIn.jsx | 4 +- src/containers/Bridge/BridgeOut.jsx | 228 ++++++-- src/containers/Exodus/Exodus.jsx | 254 ++++++--- src/containers/Exodus/ExodusList.jsx | 40 +- src/containers/Exodus/ExodusModal.jsx | 65 ++- src/containers/Exodus/ExodusStatusCard.jsx | 23 +- src/containers/History/BondModal.jsx | 62 ++- src/containers/History/BridgeOutModal.jsx | 518 ++++++++++++++++++ src/containers/History/History.jsx | 39 +- src/helpers/index.js | 15 + src/hooks/ghost/UnstableProvider.jsx | 2 +- src/hooks/helpers.js | 114 +++- src/hooks/staking/index.js | 45 +- 19 files changed, 1227 insertions(+), 192 deletions(-) rename metadatas/{casper_runtime.scale => casper-metadata.scale} (99%) create mode 100644 src/containers/History/BridgeOutModal.jsx diff --git a/.papi/descriptors/package.json b/.papi/descriptors/package.json index aa2887d..a5078e4 100644 --- a/.papi/descriptors/package.json +++ b/.papi/descriptors/package.json @@ -1,5 +1,5 @@ { - "version": "0.1.0-autogenerated.3461409763779961730", + "version": "0.1.0-autogenerated.17780546383012228608", "name": "@polkadot-api/descriptors", "files": [ "dist" diff --git a/.papi/polkadot-api.json b/.papi/polkadot-api.json index b4ab7d7..eb0c3d9 100644 --- a/.papi/polkadot-api.json +++ b/.papi/polkadot-api.json @@ -3,7 +3,7 @@ "descriptorPath": ".papi\\descriptors", "entries": { "casper": { - "metadata": "casper_runtime.scale" + "metadata": "casper-metadata.scale" } } } diff --git a/metadatas/casper_runtime.scale b/metadatas/casper-metadata.scale similarity index 99% rename from metadatas/casper_runtime.scale rename to metadatas/casper-metadata.scale index bda52f55ea40cbaa8f480bcdb9bcae5b32789923..69a27eb6f9647673c0296c85a5c3362dbe7c85b1 100644 GIT binary patch delta 76 zcmaF2o2P#d&j$T;Mv2LdQeu#EmAA;Q%Z~Di&Kk>GxPHd7)@Nk0>KbI0~f>O Z0y)LzQ|a4Jr8AoRWfb22KZWW24gf#q9a;bY delta 43 zcmeC*!}D%8&j$T;Mv=*lQeu diff --git a/src/containers/Bridge/BridgeIn.jsx b/src/containers/Bridge/BridgeIn.jsx index 560be67..a099d4a 100644 --- a/src/containers/Bridge/BridgeIn.jsx +++ b/src/containers/Bridge/BridgeIn.jsx @@ -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); diff --git a/src/containers/Bridge/BridgeOut.jsx b/src/containers/Bridge/BridgeOut.jsx index 7b35e67..6311a3b 100644 --- a/src/containers/Bridge/BridgeOut.jsx +++ b/src/containers/Bridge/BridgeOut.jsx @@ -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, @@ -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 }) => { setConfirmOpen(true)} > - Bridge-Out + {isDkgQualificationPending ? "DKG Ongoing" : "Bridge-Out"} diff --git a/src/containers/Exodus/Exodus.jsx b/src/containers/Exodus/Exodus.jsx index f7e56c7..2297f47 100644 --- a/src/containers/Exodus/Exodus.jsx +++ b/src/containers/Exodus/Exodus.jsx @@ -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 }) => { }} > { headerContent={Exodus Metrics} > - - + + 0 + ? theme.colors.feedback.success + : theme.colors.feedback.error + }}> + {formatNumber(executionDiscount, 2)}% + + } + label="Discount" tooltip="some description to be added" /> @@ -205,14 +278,33 @@ const Exodus = ({ chainId, address, config }) => { fullWidth enableBackground topRight={ - - alert("smart search for exodus will be here")} - /> - + 0 + ? { cursor: "pointer" } + : { opacity: "50%" } + } + onClick={() => { + if (dkgHistory.length === 0) return; + setDkgHistory((prev) => prev.slice(0, -1)); + }} + /> + } + topLeft={ + { + if (!signedExodusRotations) return; + const entry = { + dkgIndex: signedExodusRotations.dkgIndex, + session: signedExodusRotations.exodusContext.session, + } + setDkgHistory((prev) => [...prev, entry]); + }} + /> } headerContent={ { alignItems="center" gap="15px" > - { - const index = SELECTABLE_OPTIONS.indexOf(selectedValue); - if (index !== -1) setSelected(index); - }} - TabIndicatorProps={{ style: { display: "none" } }} - > - {SELECTABLE_OPTIONS.map((option, i) => { - return ( - {option}} - /> - ) - })} - + + Ghost Exodus + {currentDkgIndex + ? #{formatNumber(currentDkgIndex)} + : + } + + + { + 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" + } + + } > diff --git a/src/containers/Exodus/ExodusList.jsx b/src/containers/Exodus/ExodusList.jsx index cf5433f..90c1cad 100644 --- a/src/containers/Exodus/ExodusList.jsx +++ b/src/containers/Exodus/ExodusList.jsx @@ -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 = ({ setVerifiedItem({ - exodusSession: item.data.at(0).session, + exodusContext: item.exodusContext, dkgIndex: item.dkgIndex, type: item.type })} @@ -167,9 +168,9 @@ const ExodusItem = ({ 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 ( - Loading Signed Rotations... + Loading Signed Messages... ) } @@ -214,13 +208,14 @@ const ExodusList = ({ if (isSmallScreen) { return ( - {chainedExoduses.map((item, i) => { + {signedMessages?.map((item, i) => { return ( - {chainedExoduses.map((item, i) => { + {signedMessages?.map((item, i) => { return ( { @@ -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 ( { - alert("not ready for now"); - onClose(); - }} + disabled={isPending || gatekeeperIsEmpty || evmMessageMetadataLoading || !evmMessageMetadata} + onClick={verifySignatureModal} > - Verify + {isPending ? "Pending..." : "Verify"} diff --git a/src/containers/Exodus/ExodusStatusCard.jsx b/src/containers/Exodus/ExodusStatusCard.jsx index acf345a..b907e30 100644 --- a/src/containers/Exodus/ExodusStatusCard.jsx +++ b/src/containers/Exodus/ExodusStatusCard.jsx @@ -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 ( - Execution Discount: + Bounty Escalation: 0 ? theme.colors.feedback.success : theme.colors.feedback.error }}> - {formatNumber(executionDiscount, 2)}% + {getGasLabel(Math.min(100, Number(currentGasPrice.div(maxGasPrice).toString()) * 100))} - Gas Price: - {`${formatNumber(currentGasPrice, 5)} / ${formatNumber(maxGasPrice, 5)} gwei`} + Multiplier: + {`${formatNumber(currentGasPrice, 5)} / ${formatNumber(maxGasPrice, 5)}`} diff --git a/src/containers/History/BondModal.jsx b/src/containers/History/BondModal.jsx index 6e25935..a9a8ff6 100644 --- a/src/containers/History/BondModal.jsx +++ b/src/containers/History/BondModal.jsx @@ -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 }) => { - Receiver - - {shorten(functionArgs.receiver, 12, -10)} - + {functionArgs.receiver !== "0x0000000000000000000000000000000000000000" && + <> + Receiver + + {shorten(functionArgs.receiver, 12, -10)} + + + } diff --git a/src/containers/History/BridgeOutModal.jsx b/src/containers/History/BridgeOutModal.jsx new file mode 100644 index 0000000..31e8601 --- /dev/null +++ b/src/containers/History/BridgeOutModal.jsx @@ -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 ( + + {historyRecord && decodedArgs?.args + ? + {signedBridge + ? Bridge-Out Signed + : <> + + Bridge-Out [{roastProgress.tracksCount} Track{roastProgress.tracksCount > 0 ? "s" : ""}] + + + + } + + : Parsing Transaction Hash + } + + } + onClose={close} + > + + + + + + {localString}} + tooltip="some description to be added." + /> + + decodedArgs?.args.receiver + ? copyToClipboard(getAddress(decodedArgs.args.receiver), 0) + : {} + } + > + + {decodedArgs?.args.receiver + ? shorten(getAddress(decodedArgs.args.receiver), 11, -8) + : + } + + + + } + /> + + {formatNumber(historyRecord.txHash.exodusSession)} + : + } + /> + + +
+ + + + + {formatNumber(amounts.bridgeShare, 2)}%} + /> + + + + + { + close(); + navigate(`/${network}/exodus`) + }} + > + {isTransactionExecuted ? "Bridge-Out Finished" : "Verify Bridge-Out"} + +
+
+ + ) +} + +const BridgeOutProgress = ({ isExecuted, roastProgress, signedBridge, dkgIndex, exodusSession, chainId }) => { + const theme = useTheme(); + return ( + + {!signedBridge && <> + + + } + + + ) +} + +const NonceCommitments = ({ roastProgress, theme }) => { + return ( + + + Nonces + + {`${roastProgress.nonces.bestTrack} on Track #${roastProgress.nonces.bestTrackIndex}`} + + + ) +} + +const GroupCommitments = ({ theme, roastProgress }) => { + return ( + + + Commitment + + {`${roastProgress.commitment.bestTrack} on Track #${roastProgress.commitment.bestTrackIndex}`} + + + ) +} + +const SignatureShares = ({ signedBridge, theme, roastProgress, isExecuted }) => { + return ( + + + Signature + {!signedBridge + ? `${roastProgress.signature.bestTrack} on Track #${roastProgress.signature.bestTrackIndex}` + : isExecuted ? "Already Verified" : "Ready for Verification" + } + + ) +} + +export default BridgeOutModal; diff --git a/src/containers/History/History.jsx b/src/containers/History/History.jsx index 43c0951..355273e 100644 --- a/src/containers/History/History.jsx +++ b/src/containers/History/History.jsx @@ -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 } return }, [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 = ({ {localString} - {shorten(item.txHash)} + {shorten(txHashMetadata.txHash)}
@@ -128,11 +145,11 @@ const HistoryItem = ({ {item?.name ?? "Unknown"}{item?.isCustom ? " (Custom)" : ""} - {shorten(item.txHash, 7, -5)} + {shorten(txHashMetadata.txHash, 7, -5)}
@@ -275,6 +292,16 @@ const HistoryList = ({ chainId, storedTransactions, historyType, config, eraseRe /> )} + {viewModalOpen !== null && historyType === CONSTANTS.bridgeOut.key && ( + setViewModalOpen(null)} + isOpen={true} + historyRecord={storedTransactions.at(viewModalOpen)} + /> + )} + {viewModalOpen !== null && historyType === CONSTANTS.bond.key && ( { useEffect(() => { clearPendingHistory(chainId, address, storedHistoryTypes.at(historyTypeIndex)); - }, [storedHistoryTypes, historyTypeIndex]) + }, [storedHistoryTypes, historyTypeIndex]); return ( diff --git a/src/helpers/index.js b/src/helpers/index.js index 781e888..b8f7ee9 100644 --- a/src/helpers/index.js +++ b/src/helpers/index.js @@ -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)}`; diff --git a/src/hooks/ghost/UnstableProvider.jsx b/src/hooks/ghost/UnstableProvider.jsx index 7bd3139..7024748 100644 --- a/src/hooks/ghost/UnstableProvider.jsx +++ b/src/hooks/ghost/UnstableProvider.jsx @@ -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]); diff --git a/src/hooks/helpers.js b/src/hooks/helpers.js index 66ca1c2..233568d 100644 --- a/src/hooks/helpers.js +++ b/src/hooks/helpers.js @@ -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; + } +}; diff --git a/src/hooks/staking/index.js b/src/hooks/staking/index.js index 67a0931..65f813b 100644 --- a/src/hooks/staking/index.js +++ b/src/hooks/staking/index.js @@ -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; +}