Skip to content
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

Feat/migration standalone #2078

Open
wants to merge 16 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -31,8 +31,8 @@
"test:coverage": "jest --coverage"
},
"dependencies": {
"@aave/contract-helpers": "1.28.1",
"@aave/math-utils": "1.28.1",
"@aave/contract-helpers": "^1.28.2",
"@aave/math-utils": "^1.28.2",
"@bgd-labs/aave-address-book": "^2.26.1",
"@emotion/cache": "11.10.3",
"@emotion/react": "11.10.4",
Expand Down
12 changes: 4 additions & 8 deletions pages/v3-migration.page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ import { ContentContainer } from 'src/components/ContentContainer';
import { getMarketInfoById } from 'src/components/MarketSwitcher';
import { useUserMigrationReserves } from 'src/hooks/migration/useUserMigrationReserves';
import { useUserSummaryAfterMigration } from 'src/hooks/migration/useUserSummaryAfterMigration';
import { useUserPoolReservesHumanized } from 'src/hooks/pool/useUserPoolReserves';
import { useUserSummaryAndIncentives } from 'src/hooks/pool/useUserSummaryAndIncentives';
import { MainLayout } from 'src/layouts/MainLayout';
import { useWeb3Context } from 'src/libs/hooks/useWeb3Context';
Expand Down Expand Up @@ -91,20 +90,16 @@ export default function V3Migration() {

const { data: fromUserSummaryAndIncentives, isLoading: fromUserSummaryAndIncentivesLoading } =
useUserSummaryAndIncentives(fromMarketData);

const { data: toUserReservesData, isLoading: toUserReservesDataLoading } =
useUserPoolReservesHumanized(toMarketData);
const { data: toUserSummaryForMigration, isLoading: toUserSummaryForMigrationLoading } =
useUserSummaryAndIncentives(toMarketData);
const toUserEModeCategoryId = toUserReservesData?.userEmodeCategoryId || 0;

const { data: userSummaryAfterMigration, isLoading: userSummaryAfterMigrationLoading } =
useUserSummaryAfterMigration(fromMarketData, toMarketData);

const toUserEModeCategoryId = toUserSummaryForMigration?.userEmodeCategoryId || 0;
const loading =
userMigrationReservesLoading ||
fromUserSummaryAndIncentivesLoading ||
toUserReservesDataLoading ||
toUserSummaryForMigrationLoading ||
userSummaryAfterMigrationLoading;

Expand Down Expand Up @@ -138,7 +133,7 @@ export default function V3Migration() {
setFromMarketData(marketData);
};

const bottomPanelProps = fromUserSummaryAndIncentives &&
const userSummaryBeforeMigration = fromUserSummaryAndIncentives &&
toUserSummaryForMigration && {
fromUserSummaryBeforeMigration: fromUserSummaryAndIncentives,
toUserSummaryBeforeMigration: toUserSummaryForMigration,
Expand All @@ -159,7 +154,7 @@ export default function V3Migration() {
>
<MigrationBottomPanel
userSummaryAfterMigration={userSummaryAfterMigration}
userSummaryBeforeMigration={bottomPanelProps}
userSummaryBeforeMigration={userSummaryBeforeMigration}
disableButton={selectedSupplyAssets.length === 0 && selectedBorrowAssets.length === 0}
enteringIsolationMode={isolatedReserveV3?.enteringIsolationMode || false}
loading={loading}
Expand All @@ -169,6 +164,7 @@ export default function V3Migration() {
selectableMarkets={selectableMarkets}
/>
<MigrationLists
toMarket={toMarketData}
loading={loading}
isSupplyPositionsAvailable={supplyReserves.length > 0}
isBorrowPositionsAvailable={borrowReserves.length > 0}
Expand Down
235 changes: 207 additions & 28 deletions src/components/transactions/MigrateV3/MigrateV3Actions.tsx
Original file line number Diff line number Diff line change
@@ -1,9 +1,28 @@
import { ProtocolAction } from '@aave/contract-helpers';
import {
MigrationDelegationApproval,
V3MigrationHelperSignedCreditDelegationPermit,
V3MigrationHelperSignedPermit,
} from '@aave/contract-helpers/dist/esm/v3-migration-contract/v3MigrationTypes';
import { Trans } from '@lingui/macro';
import { useTransactionHandler } from 'src/helpers/useTransactionHandler';
import { useQueryClient } from '@tanstack/react-query';
import { useState } from 'react';
import { MOCK_SIGNED_HASH } from 'src/helpers/useTransactionHandler';
import { useMigrationApprovalTxs } from 'src/hooks/migration/useMigrationApprovalTxs';
import { UserMigrationReserves } from 'src/hooks/migration/useUserMigrationReserves';
import { UserSummaryForMigration } from 'src/hooks/migration/useUserSummaryForMigration';
import { useModalContext } from 'src/hooks/useModal';
import { useWeb3Context } from 'src/libs/hooks/useWeb3Context';
import { useRootStore } from 'src/store/root';
import {
selectMigrationBorrowPermitPayloads,
selectMigrationRepayAssets,
selectUserSupplyAssetsForMigrationNoPermit,
} from 'src/store/v3MigrationSelectors';
import { ApprovalMethod } from 'src/store/walletSlice';
import { getErrorTextFromError, TxAction } from 'src/ui-config/errorMapping';
import { MarketDataType } from 'src/ui-config/marketsConfig';
import { queryKeysFactory } from 'src/ui-config/queries';
import { useSharedDependencies } from 'src/ui-config/SharedDependenciesProvider';

import { TxActionsWrapper } from '../TxActionsWrapper';

Expand All @@ -12,51 +31,211 @@ export type MigrateV3ActionsProps = {
blocked: boolean;
userMigrationReserves: UserMigrationReserves;
toUserSummaryForMigration: UserSummaryForMigration;
fromMarket: MarketDataType;
toMarket: MarketDataType;
};

export const MigrateV3Actions = ({
isWrongNetwork,
blocked,
userMigrationReserves,
toUserSummaryForMigration,
fromMarket,
toMarket,
}: MigrateV3ActionsProps) => {
const migrateWithPermits = useRootStore((store) => store.migrateWithPermits);
const migrateWithoutPermits = useRootStore((store) => store.migrateWithoutPermits);
const getApprovePermitsForSelectedAssets = useRootStore(
(store) => store.getApprovePermitsForSelectedAssets
const [signatures, setSignatures] = useState<{
supply: V3MigrationHelperSignedPermit[];
borrow: V3MigrationHelperSignedCreditDelegationPermit[];
}>({
supply: [],
borrow: [],
});
const { signTxData, sendTx } = useWeb3Context();
const [
user,
walletApprovalMethodPreference,
selectedMigrationSupplyAssets,
selectedMigrationBorrowAssets,
generateCreditDelegationSignatureRequest,
generateSignatureRequest,
estimateGasLimit,
] = useRootStore((store) => [
store.account,
store.walletApprovalMethodPreference,
store.selectedMigrationSupplyAssets,
store.selectedMigrationBorrowAssets,
store.generateCreditDelegationSignatureRequest,
store.generateSignatureRequest,
store.estimateGasLimit,
]);
const { approvalTxState, mainTxState, setApprovalTxState, setTxError, setMainTxState } =
useModalContext();
const queryClient = useQueryClient();

const { migrationService } = useSharedDependencies();

const usePermit = walletApprovalMethodPreference === ApprovalMethod.PERMIT;

const supplyAssets = selectUserSupplyAssetsForMigrationNoPermit(
selectedMigrationSupplyAssets,
userMigrationReserves.supplyReserves,
userMigrationReserves.isolatedReserveV3
);

const repayAssets = selectMigrationRepayAssets(
selectedMigrationBorrowAssets,
userMigrationReserves.borrowReserves
);

const borrowPermitPayloads = selectMigrationBorrowPermitPayloads(
selectedMigrationBorrowAssets,
toUserSummaryForMigration,
userMigrationReserves.borrowReserves,
true
);
const { approval, action, loadingTxns, requiresApproval, mainTxState, approvalTxState } =
useTransactionHandler({
handleGetTxns: async () =>
await migrateWithoutPermits(toUserSummaryForMigration, userMigrationReserves),
handleGetPermitTxns: async (signatures, deadline) =>
await migrateWithPermits(
signatures,
deadline,
toUserSummaryForMigration,
userMigrationReserves
),
tryPermit: true,
permitAction: ProtocolAction.migrateV3,
});

const handleApproval = async () => {
const approvePermitsForSelectedAssets = await getApprovePermitsForSelectedAssets(
toUserSummaryForMigration,
userMigrationReserves
);
approval(approvePermitsForSelectedAssets);
const creditDelegationApprovals: MigrationDelegationApproval[] = borrowPermitPayloads.map(
({ underlyingAsset, amount }) => ({ debtTokenAddress: underlyingAsset, amount })
);

const { data: approvals, isLoading: approvalsLoading } = useMigrationApprovalTxs(
fromMarket,
toMarket,
supplyAssets,
creditDelegationApprovals
);

const requiresApproval = approvals
? approvals.supplyApprovalTxs.length > 0 ||
approvals.borrowCreditDelegationApprovalTxs.length > 0
: false;

const approval = async () => {
if (requiresApproval && approvals) {
try {
if (usePermit) {
const deadline = Math.floor(Date.now() / 1000 + 3600).toString();
setApprovalTxState({ ...approvalTxState, loading: true });
const supplyApprovals = approvals.supplyApprovalTxs;
const borrowCreditDelegationApprovals = approvals.borrowCreditDelegationApprovalTxs;
const supplySigned = await Promise.all(
supplyApprovals.map(async (supplyApproval) => {
const signatureRequest = await generateSignatureRequest(
{
token: supplyApproval.token,
amount: supplyApproval.amount,
deadline: deadline.toString(),
spender: supplyApproval.spender,
},
{ chainId: fromMarket.chainId }
);
const signature = await signTxData(signatureRequest);
return {
deadline: deadline.toString(),
aToken: supplyApproval.token,
value: supplyApproval.amount,
signedPermit: signature,
};
})
);
const borrowSigned = await Promise.all(
borrowCreditDelegationApprovals.map(async (borrowCreditDelegationApproval) => {
const signatureRequest = await generateCreditDelegationSignatureRequest(
{
amount: borrowCreditDelegationApproval.amount,
underlyingAsset: borrowCreditDelegationApproval.debtTokenAddress,
deadline,
spender: borrowCreditDelegationApproval.delegatee,
},
{ chainId: fromMarket.chainId }
);
const signature = await signTxData(signatureRequest);
return {
deadline,
debtToken: borrowCreditDelegationApproval.debtTokenAddress,
value: borrowCreditDelegationApproval.amount,
signedPermit: signature,
};
})
);
setSignatures({
supply: supplySigned,
borrow: borrowSigned,
});
setTxError(undefined);
setApprovalTxState({
txHash: MOCK_SIGNED_HASH,
loading: false,
success: true,
});
} else {
setApprovalTxState({ ...approvalTxState, loading: true });
const allTxs = [
...approvals.supplyApprovalTxs,
...approvals.borrowCreditDelegationApprovalTxs,
];
const txsApprovalResponse = await Promise.all(
allTxs.map((approval) => sendTx(approval.tx))
);
await Promise.all(txsApprovalResponse.map((elem) => elem.wait(1)));
setApprovalTxState({
txHash: txsApprovalResponse[0]?.hash,
loading: false,
success: true,
});
setTxError(undefined);
}
} catch (error) {
const parsedError = getErrorTextFromError(error, TxAction.GAS_ESTIMATION, false);
setTxError(parsedError);
setApprovalTxState({
txHash: undefined,
loading: false,
});
}
}
};

const action = async () => {
try {
setMainTxState({ ...mainTxState, loading: true });
let tx = migrationService.getMigrationTx(
fromMarket,
toMarket,
user,
supplyAssets,
repayAssets,
signatures.supply,
signatures.borrow
);
tx = await estimateGasLimit(tx, fromMarket.chainId);
const response = await sendTx(tx);
await response.wait(1);
queryClient.invalidateQueries(queryKeysFactory.pool);
setMainTxState({
txHash: response.hash,
loading: false,
success: true,
});
} catch (error) {
const parsedError = getErrorTextFromError(error, TxAction.GAS_ESTIMATION, false);
setTxError(parsedError);
setMainTxState({
txHash: undefined,
loading: false,
});
}
};

return (
<TxActionsWrapper
requiresApproval={requiresApproval}
preparingTransactions={loadingTxns}
preparingTransactions={approvalsLoading}
mainTxState={mainTxState}
approvalTxState={approvalTxState}
isWrongNetwork={isWrongNetwork}
handleAction={action}
handleApproval={handleApproval}
handleApproval={approval}
blocked={blocked}
actionText={<Trans>Migrate</Trans>}
actionInProgressText={<Trans>Migrating</Trans>}
Expand Down
22 changes: 4 additions & 18 deletions src/components/transactions/MigrateV3/MigrateV3Modal.tsx
Original file line number Diff line number Diff line change
@@ -1,32 +1,18 @@
import React from 'react';
import { BasicModal } from 'src/components/primitives/BasicModal';
import { useUserMigrationReserves } from 'src/hooks/migration/useUserMigrationReserves';
import { useUserSummaryForMigration } from 'src/hooks/migration/useUserSummaryForMigration';
import { ModalType, useModalContext } from 'src/hooks/useModal';
import { selectCurrentChainIdV3MarketData } from 'src/store/poolSelectors';
import { useRootStore } from 'src/store/root';

import { MigrateV3ModalContent } from './MigrateV3ModalContent';

export const MigrateV3Modal = () => {
const { type, close } = useModalContext();
const { type, close, args } = useModalContext();

const currentChainId = useRootStore((store) => store.currentChainId);
const currentNetworkConfig = useRootStore((store) => store.currentNetworkConfig);
const currentMarketData = useRootStore((store) => store.currentMarketData);
const toMarketData = selectCurrentChainIdV3MarketData(currentChainId, currentNetworkConfig);
const fromMarketData = currentMarketData;

const { data: userMigrationReserves } = useUserMigrationReserves(fromMarketData, toMarketData);
const { data: toUserSummaryForMigration } = useUserSummaryForMigration(toMarketData);
const { fromMarket, toMarket } = args;

return (
<BasicModal open={type === ModalType.V3Migration} setOpen={close}>
{userMigrationReserves && toUserSummaryForMigration && (
<MigrateV3ModalContent
userMigrationReserves={userMigrationReserves}
toUserSummaryForMigration={toUserSummaryForMigration}
/>
{fromMarket && toMarket && (
<MigrateV3ModalContent fromMarket={fromMarket} toMarket={toMarket} />
)}
</BasicModal>
);
Expand Down
Loading
Loading