-
Notifications
You must be signed in to change notification settings - Fork 491
feat: add migrator button and action #3045
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
AGMASO
wants to merge
1
commit into
main
Choose a base branch
from
feat/add-stkghomigrator
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
128 changes: 128 additions & 0 deletions
128
src/components/transactions/StkGhoMigrate/StkGhoMigrateActions.tsx
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,128 @@ | ||
| import { evmAddress, useStkGhoMigrate } from '@aave/react'; | ||
| import { useSendTransaction } from '@aave/react/viem'; | ||
| import { Trans } from '@lingui/macro'; | ||
| import { BoxProps } from '@mui/material'; | ||
| import { useQueryClient } from '@tanstack/react-query'; | ||
| import { errAsync } from 'neverthrow'; | ||
| import React, { useEffect } from 'react'; | ||
| import { oracles, stakedTokens } from 'src/hooks/stake/common'; | ||
| import { useModalContext } from 'src/hooks/useModal'; | ||
| import { useSavingsMarketData } from 'src/hooks/useSavingsMarketData'; | ||
| import { useWeb3Context } from 'src/libs/hooks/useWeb3Context'; | ||
| import { useSGhoVaultContext } from 'src/modules/sGho/SGhoVaultContext'; | ||
| import { useRootStore } from 'src/store/root'; | ||
| import { queryKeysFactory } from 'src/ui-config/queries'; | ||
| import { wagmiConfig } from 'src/ui-config/wagmiConfig'; | ||
| import { useWalletClient } from 'wagmi'; | ||
| import { waitForTransactionReceipt } from 'wagmi/actions'; | ||
| import { useShallow } from 'zustand/shallow'; | ||
|
|
||
| import { TxActionsWrapper } from '../TxActionsWrapper'; | ||
|
|
||
| // Static recommendation: migrate redeems the full stkGHO position and deposits | ||
| // it into the sGHO vault. No approval step exists (the migrator holds the | ||
| // stkGHO claim-helper role and redeems on the user's behalf), so this is a safe | ||
| // upper bound for the single migrate() call. | ||
| const STK_GHO_MIGRATE_GAS_LIMIT = 250_000; | ||
|
|
||
| export interface StkGhoMigrateActionsProps extends BoxProps { | ||
| isWrongNetwork: boolean; | ||
| blocked: boolean; | ||
| } | ||
|
|
||
| export const StkGhoMigrateActions = React.memo( | ||
| ({ isWrongNetwork, blocked, sx, ...props }: StkGhoMigrateActionsProps) => { | ||
| const { currentAccount } = useWeb3Context(); | ||
| const { chainId: targetChainId, sdkChainId } = useSavingsMarketData(); | ||
| const { mainTxState, setMainTxState, setTxError, setGasLimit } = useModalContext(); | ||
| const { refresh } = useSGhoVaultContext(); | ||
| const queryClient = useQueryClient(); | ||
| const [user, marketData] = useRootStore( | ||
| useShallow((state) => [state.account, state.currentMarketData]) | ||
| ); | ||
|
|
||
| const { data: walletClient } = useWalletClient(); | ||
| const [migrate] = useStkGhoMigrate(); | ||
| const [sendTransaction] = useSendTransaction(walletClient); | ||
|
|
||
| useEffect(() => { | ||
| setGasLimit(STK_GHO_MIGRATE_GAS_LIMIT.toString()); | ||
| }, [setGasLimit]); | ||
|
|
||
| const action = async () => { | ||
| if (!currentAccount || !walletClient) return; | ||
| setMainTxState({ loading: true }); | ||
| setTxError(undefined); | ||
|
|
||
| const result = await migrate({ | ||
| user: evmAddress(currentAccount), | ||
| chainId: sdkChainId, | ||
| }).andThen((plan) => { | ||
| // The migrator holds the stkGHO claim-helper role and redeems on the | ||
| // user's behalf, so migration never requires an approval — the backend | ||
| // always returns a plain TransactionRequest. Guard the other | ||
| // ExecutionPlan union members defensively. | ||
| if (plan.__typename !== 'TransactionRequest') { | ||
| return errAsync(new Error('Unexpected migration plan; expected a transaction request.')); | ||
| } | ||
| return sendTransaction(plan); | ||
| }); | ||
|
|
||
| if (result.isErr()) { | ||
| setMainTxState({ loading: false }); | ||
| setTxError({ | ||
| blocking: true, | ||
| actionBlocked: true, | ||
| rawError: result.error as Error, | ||
| error: <span>{(result.error as Error).message}</span>, | ||
| // eslint-disable-next-line @typescript-eslint/no-explicit-any | ||
| txAction: 0 as any, | ||
| }); | ||
| return; | ||
| } | ||
|
|
||
| const submittedTxHash = result.value; | ||
| setMainTxState({ loading: true, txHash: submittedTxHash }); | ||
|
|
||
| // Wait for the receipt on the connected chain (works on forks too). | ||
| try { | ||
| await waitForTransactionReceipt(wagmiConfig, { | ||
| hash: submittedTxHash as `0x${string}`, | ||
| chainId: targetChainId, | ||
| }); | ||
| } catch (e) { | ||
| console.warn('waitForTransactionReceipt failed', e); | ||
| } | ||
|
|
||
| // Refresh the sGHO vault cache (new shares) and invalidate the stkGHO | ||
| // position + pool balances so both panels reflect the migration. | ||
| refresh(); | ||
| await new Promise((resolve) => setTimeout(resolve, 1000)); | ||
|
|
||
| queryClient.invalidateQueries({ queryKey: queryKeysFactory.pool }); | ||
| queryClient.invalidateQueries({ | ||
| queryKey: queryKeysFactory.userStakeUiData(user, marketData, stakedTokens, oracles), | ||
| }); | ||
|
|
||
| setMainTxState({ loading: false, success: true, txHash: submittedTxHash }); | ||
| }; | ||
|
|
||
| return ( | ||
| <TxActionsWrapper | ||
| requiresApproval={false} | ||
| preparingTransactions={false} | ||
| mainTxState={mainTxState} | ||
| isWrongNetwork={isWrongNetwork} | ||
| handleAction={action} | ||
| symbol="stkGHO" | ||
| actionText={<Trans>Proceed with migration</Trans>} | ||
| actionInProgressText={<Trans>Migrating</Trans>} | ||
| sx={sx} | ||
| blocked={blocked} | ||
| {...props} | ||
| /> | ||
| ); | ||
| } | ||
| ); | ||
|
|
||
| StkGhoMigrateActions.displayName = 'StkGhoMigrateActions'; |
24 changes: 24 additions & 0 deletions
24
src/components/transactions/StkGhoMigrate/StkGhoMigrateModal.tsx
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,24 @@ | ||
| import { Trans } from '@lingui/macro'; | ||
| import { BasicModal } from 'src/components/primitives/BasicModal'; | ||
| import { ModalContextType, ModalType, useModalContext } from 'src/hooks/useModal'; | ||
|
|
||
| import { ModalWrapper } from '../FlowCommons/ModalWrapper'; | ||
| import { StkGhoMigrateModalContent } from './StkGhoMigrateModalContent'; | ||
|
|
||
| export const StkGhoMigrateModal = () => { | ||
| const { type, close, args } = useModalContext() as ModalContextType<{ | ||
| underlyingAsset: string; | ||
| }>; | ||
|
|
||
| return ( | ||
| <BasicModal open={type === ModalType.StkGhoMigrate} setOpen={close}> | ||
| <ModalWrapper | ||
| title={<Trans>Migrate stkGHO to sGHO</Trans>} | ||
| underlyingAsset={args.underlyingAsset} | ||
| hideTitleSymbol | ||
| > | ||
| {() => <StkGhoMigrateModalContent />} | ||
| </ModalWrapper> | ||
| </BasicModal> | ||
| ); | ||
| }; |
98 changes: 98 additions & 0 deletions
98
src/components/transactions/StkGhoMigrate/StkGhoMigrateModalContent.tsx
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,98 @@ | ||
| import { Stake } from '@aave/contract-helpers'; | ||
| import { bigDecimal, useSghoVaultPreviewDeposit } from '@aave/react'; | ||
| import { Trans } from '@lingui/macro'; | ||
| import { formatEther } from 'ethers/lib/utils'; | ||
| import { useRef } from 'react'; | ||
| import { useUserStakeUiData } from 'src/hooks/stake/useUserStakeUiData'; | ||
| import { useModalContext } from 'src/hooks/useModal'; | ||
| import { useSavingsMarketData } from 'src/hooks/useSavingsMarketData'; | ||
| import { useSGhoVaultContext } from 'src/modules/sGho/SGhoVaultContext'; | ||
| import { useRootStore } from 'src/store/root'; | ||
|
|
||
| import { useWeb3Context } from '../../../libs/hooks/useWeb3Context'; | ||
| import { TxErrorView } from '../FlowCommons/Error'; | ||
| import { TxSuccessView } from '../FlowCommons/Success'; | ||
| import { DetailsNumberLineWithSub, TxModalDetails } from '../FlowCommons/TxModalDetails'; | ||
| import { StkGhoMigrateActions } from './StkGhoMigrateActions'; | ||
|
|
||
| export const StkGhoMigrateModalContent = () => { | ||
| const { chainId: connectedChainId } = useWeb3Context(); | ||
| const { chainId: targetChainId, sdkChainId } = useSavingsMarketData(); | ||
| const { mainTxState, txError, gasLimit } = useModalContext(); | ||
|
|
||
| const currentMarketData = useRootStore((store) => store.currentMarketData); | ||
| const { data: stakeUserResult } = useUserStakeUiData(currentMarketData, Stake.gho); | ||
|
|
||
| // stkGHO is redeemable 1:1 to GHO, so the migrated GHO amount equals the | ||
| // user's full stkGHO position. We use it to preview the sGHO shares minted. | ||
| const stkGhoBalance = formatEther(stakeUserResult?.[0]?.stakeTokenRedeemableAmount || '0'); | ||
|
|
||
| const previewAmount = +stkGhoBalance > 0 ? stkGhoBalance : '0'; | ||
| const { data: previewShares, loading: previewFetching } = useSghoVaultPreviewDeposit({ | ||
| amount: bigDecimal(previewAmount), | ||
| chainId: sdkChainId, | ||
| }); | ||
|
|
||
| // USD pricing from the sGHO vault. stkGHO is 1:1 to GHO, so it's priced at the | ||
| // GHO rate (`usdPerToken`). sGHO shares appreciate (not 1:1 to GHO), so they're | ||
| // priced at the vault share price = totalAssetsUSD / totalSupply. | ||
| const { vault } = useSGhoVaultContext(); | ||
| const ghoUsdPerToken = +(vault?.totalAssets?.usdPerToken ?? '1'); | ||
| const totalAssetsUsd = +(vault?.totalAssets?.usd ?? '0'); | ||
| const totalSupply = +(vault?.totalSupply?.value ?? '0'); | ||
| const sghoUsdPerShare = | ||
| totalSupply > 0 && totalAssetsUsd > 0 ? totalAssetsUsd / totalSupply : ghoUsdPerToken; | ||
|
|
||
| const stkGhoUSD = (+stkGhoBalance * ghoUsdPerToken).toString(); | ||
| const sghoUSD = (+(previewShares?.value ?? '0') * sghoUsdPerShare).toString(); | ||
|
|
||
| const isWrongNetwork = connectedChainId !== targetChainId; | ||
|
|
||
| // Snapshot the received shares at submit time — once the tx mines the Actions | ||
| // invalidate the stake data, so `stkGhoBalance` (and thus `previewShares`) | ||
| // refetches to 0 and would otherwise blank the success view. | ||
| const receivedSharesRef = useRef<string | null>(null); | ||
| if (mainTxState.txHash && receivedSharesRef.current === null) { | ||
| receivedSharesRef.current = previewShares?.value ?? '0'; | ||
| } | ||
| if (!mainTxState.txHash && !mainTxState.success && receivedSharesRef.current !== null) { | ||
| receivedSharesRef.current = null; | ||
| } | ||
|
|
||
| if (txError && txError.blocking) return <TxErrorView txError={txError} />; | ||
| if (mainTxState.success) { | ||
| return ( | ||
| <TxSuccessView | ||
| action={<Trans>received</Trans>} | ||
| amount={receivedSharesRef.current ?? previewShares?.value ?? '0'} | ||
| symbol="sGHO" | ||
| /> | ||
| ); | ||
| } | ||
|
|
||
| return ( | ||
| <> | ||
| <TxModalDetails gasLimit={gasLimit} chainId={targetChainId}> | ||
| <DetailsNumberLineWithSub | ||
| description={<Trans>Migrating</Trans>} | ||
| futureValue={stkGhoBalance} | ||
| futureValueUSD={stkGhoUSD} | ||
| symbol="stkGHO" | ||
| /> | ||
| <DetailsNumberLineWithSub | ||
| description={<Trans>You'll receive</Trans>} | ||
| futureValue={previewShares?.value ?? '0'} | ||
| futureValueUSD={sghoUSD} | ||
| symbol="sGHO" | ||
| loading={previewFetching} | ||
| /> | ||
| </TxModalDetails> | ||
|
|
||
| <StkGhoMigrateActions | ||
| isWrongNetwork={isWrongNetwork} | ||
| blocked={+stkGhoBalance <= 0} | ||
| sx={{ mt: '48px' }} | ||
| /> | ||
| </> | ||
| ); | ||
| }; | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Large diffs are not rendered by default.
Oops, something went wrong.
Large diffs are not rendered by default.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Large diffs are not rendered by default.
Oops, something went wrong.
Large diffs are not rendered by default.
Oops, something went wrong.
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
If the user submits the migration while
useSghoVaultPreviewDepositis still loading, this branch runs as soon astxHashis set and permanently stores'0'becausepreviewSharesis still undefined. When the preview response arrives, the ref no longer updates, so the success view can report that the user received 0 sGHO even though the migration succeeded. Consider disabling submission until the preview is ready or only snapshotting oncepreviewShares?.valueis available.Useful? React with 👍 / 👎.