Skip to content

Commit 4d71cd6

Browse files
committed
feat: migrate with borrow and permits continue
1 parent f6e3698 commit 4d71cd6

File tree

7 files changed

+160
-55
lines changed

7 files changed

+160
-55
lines changed

src/helpers/useTransactionHandler.tsx

Lines changed: 0 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -272,11 +272,8 @@ export const useTransactionHandler = ({
272272
if ((!usePermit || !approvalTxes) && actionTx) {
273273
try {
274274
setMainTxState({ ...mainTxState, loading: true });
275-
console.log(actionTx, 'actionTx');
276275
const params = await actionTx.tx();
277-
console.log(params, 'actionTx');
278276
// delete params.gasPrice;
279-
console.log(params);
280277
return processTx({
281278
tx: () => sendTx(params),
282279
successCallback: (txnResponse: TransactionResponse) => {
@@ -319,7 +316,6 @@ export const useTransactionHandler = ({
319316
return handleGetTxns()
320317
.then(async (data) => {
321318
if (!mounted.current) return;
322-
// setApprovalTxes(data.filte((tx) => tx.txType === 'ERC20_APPROVAL'));
323319
const approvals = data.filter((tx) => tx.txType == 'ERC20_APPROVAL');
324320
if (approvals.length > 0) {
325321
setApprovalTxes(approvals);

src/store/poolSelectors.ts

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,8 @@ export const selectCurrentUserLendingPoolData = (state: RootStore) => {
1010
?.get(state.currentMarketData.addresses.LENDING_POOL_ADDRESS_PROVIDER);
1111
};
1212

13+
export const selectLendingPoolDataV2 = (state: RootStore) => {};
14+
1315
export const selectCurrentUserEmodeCategoryId = (state: RootStore): number => {
1416
return selectCurrentUserLendingPoolData(state)?.userEmodeCategoryId || 0;
1517
};

src/store/poolSlice.ts

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -34,8 +34,8 @@ import { RepayActionProps } from 'src/components/transactions/Repay/RepayActions
3434
import { SupplyActionProps } from 'src/components/transactions/Supply/SupplyActions';
3535
import { SwapActionProps } from 'src/components/transactions/Swap/SwapActions';
3636
import { getRepayCallData, getSwapCallData } from 'src/hooks/useSwap';
37-
import { MarketDataType, marketsData } from 'src/ui-config/marketsConfig';
38-
import { availableMarkets, networkConfigs } from 'src/utils/marketsAndNetworksConfig';
37+
import { MarketDataType } from 'src/ui-config/marketsConfig';
38+
import { availableMarkets, marketsData, networkConfigs } from 'src/utils/marketsAndNetworksConfig';
3939
import { optimizedPath } from 'src/utils/utils';
4040
import { StateCreator } from 'zustand';
4141

@@ -199,9 +199,8 @@ export const createPoolSlice: StateCreator<
199199
},
200200
refreshPoolV3Data: async () => {
201201
// how to determine which v2 markets to pool? for now always fetch polygon fork
202-
const v3MarketData = marketsData[availableMarkets[11]];
203-
console.log(marketsData);
204-
// get().refreshPoolData(availableMarkets);
202+
const v3MarketData = marketsData['fork_proto_polygon_v3'];
203+
get().refreshPoolData(v3MarketData);
205204
},
206205
mint: async (args) => {
207206
if (!get().currentMarketData.addresses.FAUCET)

src/store/protocolDataSlice.ts

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,6 @@ export const createProtocolDataSlice: StateCreator<
3838
setCurrentMarket: (market, omitQueryParameterUpdate) => {
3939
if (!availableMarkets.includes(market as CustomMarket)) return;
4040
const nextMarketData = marketsData[market];
41-
console.log(marketsData['fork_proto_polygon_v3'], marketsData);
4241
localStorage.setItem('selectedMarket', market);
4342
if (!omitQueryParameterUpdate) {
4443
setQueryParameter('marketName', market);

src/store/root.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import { enableMapSet } from 'immer';
22
import { CustomMarket } from 'src/ui-config/marketsConfig';
3+
import { marketsData } from 'src/utils/marketsAndNetworksConfig';
34
import create from 'zustand';
45
import { devtools } from 'zustand/middleware';
56

src/store/v3MigrationSelectors.ts

Lines changed: 77 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,89 @@
1-
import { selectUserNonEmtpySummaryAndIncentive } from './poolSelectors';
1+
import { InterestRate } from '@aave/contract-helpers';
2+
import { V3MigrationHelperSignedPermit } from '@aave/contract-helpers/dist/esm/v3-migration-contract/v3MigrationTypes';
3+
import { valueToBigNumber } from '@aave/math-utils';
4+
import { SignatureLike } from '@ethersproject/bytes';
5+
import { BigNumber, BigNumberish, constants } from 'ethers';
6+
import {
7+
selectUserNonEmtpySummaryAndIncentive,
8+
selectUserSummaryAndIncentives,
9+
} from './poolSelectors';
210
import { RootStore } from './root';
311

4-
export const selectedUserReservesForMigration = (store: RootStore, timestamp: number) => {
12+
export const selectedUserSupplyReservesForMigration = (store: RootStore, timestamp: number) => {
513
const user = selectUserNonEmtpySummaryAndIncentive(store, timestamp);
614
const selectedUserReserves = user.userReservesData.filter(
715
(userReserve) => store.selectedMigrationSupplyAssets[userReserve.underlyingAsset]
816
);
917
return selectedUserReserves;
1018
};
1119

20+
export const selectUserSupplyIncreasedReservesForMigrationPermits = (
21+
store: RootStore,
22+
timestamp: number
23+
) => {
24+
console.log('selectUserSupplyIncreasedReservesForMigrationPermits')
25+
return selectedUserSupplyReservesForMigration(store, timestamp).map((userReserve) => {
26+
const increasedAmount = addPercent(userReserve.underlyingBalance);
27+
return { ...userReserve, increasedAmount };
28+
});
29+
};
30+
31+
export const selectUserSupplyAssetsForMigrationNoPermit = (store: RootStore, timestamp: number) => {
32+
const selectedUserReserves = selectedUserSupplyReservesForMigration(store, timestamp);
33+
return selectedUserReserves.map(({ underlyingAsset, reserve }) => {
34+
const deadline = Math.floor(Date.now() / 1000 + 3600);
35+
return {
36+
amount: constants.MaxUint256.toString(),
37+
aToken: reserve.aTokenAddress,
38+
underlyingAsset: underlyingAsset,
39+
deadline,
40+
};
41+
});
42+
};
43+
44+
export const selectUserSupplyAssetsForMigrationWithPermits = (
45+
store: RootStore,
46+
signatures: SignatureLike[],
47+
deadline: BigNumberish
48+
): V3MigrationHelperSignedPermit[] => {
49+
return store.approvalPermitsForMigrationAssets.map(({ amount, underlyingAsset }, index) => {
50+
return {
51+
signedPermit: signatures[index],
52+
deadline,
53+
aToken: underlyingAsset,
54+
value: amount,
55+
};
56+
});
57+
};
58+
59+
const addPercent = (amount: string) => {
60+
const convertedAmount = valueToBigNumber(amount);
61+
return convertedAmount.plus(convertedAmount.div(1000)).toString();
62+
};
63+
64+
export const selectUserBorrowReservesForMigration = (store: RootStore, timestamp: number) => {
65+
const user = selectUserSummaryAndIncentives(store, timestamp);
66+
const selectedUserReserves = user.userReservesData
67+
// should filter for empty positions?
68+
.filter(
69+
(userReserve) =>
70+
valueToBigNumber(userReserve.stableBorrows).isGreaterThan(0) ||
71+
valueToBigNumber(userReserve.variableBorrows).isGreaterThan(0)
72+
)
73+
.filter((userReserve) => store.selectedMigrationBorrowAssets[userReserve.underlyingAsset])
74+
.map(({ reserve, ...userReserve }) => {
75+
const stableBorrows = valueToBigNumber(userReserve.stableBorrows);
76+
if (stableBorrows.isGreaterThan(0)) {
77+
const increasedAmount = addPercent(userReserve.stableBorrows);
78+
return { ...userReserve, reserve, increasedAmount, interestRate: InterestRate.Stable };
79+
}
80+
const increasedAmount = addPercent(userReserve.variableBorrows);
81+
return { ...userReserve, reserve, increasedAmount, interestRate: InterestRate.Variable };
82+
});
83+
84+
return selectedUserReserves;
85+
};
86+
1287
export const selectCurrentMarketV2Reserves = (store: RootStore, timestamp: number) => {
1388
const currentChainId = store.currentChainId;
1489
return store.data.get(currentChainId);

src/store/v3MigrationSlice.ts

Lines changed: 76 additions & 43 deletions
Original file line numberDiff line numberDiff line change
@@ -4,16 +4,26 @@ import {
44
EthereumTransactionTypeExtended,
55
V3MigrationHelperService,
66
valueToWei,
7+
Pool,
8+
InterestRate,
79
} from '@aave/contract-helpers';
10+
import { V3MigrationHelperSignedPermit } from '@aave/contract-helpers/dist/esm/v3-migration-contract/v3MigrationTypes';
11+
import { valueToBigNumber } from '@aave/math-utils';
812
import { SignatureLike } from '@ethersproject/bytes';
913
import dayjs from 'dayjs';
10-
import { BigNumberish, constants } from 'ethers';
14+
import { BigNumber, BigNumberish, constants } from 'ethers';
1115
import { produce } from 'immer';
1216
import { Approval } from 'src/helpers/useTransactionHandler';
1317
import { StateCreator } from 'zustand';
1418

1519
import { RootStore } from './root';
16-
import { selectedUserReservesForMigration } from './v3MigrationSelectors';
20+
import {
21+
selectedUserSupplyReservesForMigration,
22+
selectUserBorrowReservesForMigration,
23+
selectUserSupplyAssetsForMigrationNoPermit,
24+
selectUserSupplyAssetsForMigrationWithPermits,
25+
selectUserSupplyIncreasedReservesForMigrationPermits,
26+
} from './v3MigrationSelectors';
1727

1828
export type V3MigrationSlice = {
1929
//STATE
@@ -38,6 +48,9 @@ export type V3MigrationSlice = {
3848
deadline: BigNumberish
3949
) => Promise<EthereumTransactionTypeExtended[]>;
4050
migrateWithoutPermits: () => Promise<EthereumTransactionTypeExtended[]>;
51+
migrateBorrow: (
52+
signedPermits?: V3MigrationHelperSignedPermit[]
53+
) => Promise<EthereumTransactionTypeExtended[]>;
4154
_testMigration: () => void;
4255
// migrateSelectedPositions: () => void;
4356
};
@@ -71,7 +84,14 @@ export const createV3MigrationSlice: StateCreator<
7184

7285
const typeData = {
7386
types: {
87+
EIP712Domain: [
88+
{ name: 'name', type: 'string' },
89+
{ name: 'version', type: 'string' },
90+
{ name: 'chainId', type: 'uint256' },
91+
{ name: 'verifyingContract', type: 'address' },
92+
],
7493
Permit: [
94+
// { name: 'PERMIT_TYPEHASH', type: 'string' },
7595
{ name: 'owner', type: 'address' },
7696
{ name: 'spender', type: 'address' },
7797
{ name: 'value', type: 'uint256' },
@@ -121,12 +141,12 @@ export const createV3MigrationSlice: StateCreator<
121141
getApprovePermitsForSelectedAssets: async () => {
122142
const timestamp = dayjs().unix();
123143
const approvalPermitsForMigrationAssets = await Promise.all(
124-
selectedUserReservesForMigration(get(), timestamp).map(
125-
async ({ reserve, underlyingBalance }): Promise<Approval> => {
144+
selectUserSupplyIncreasedReservesForMigrationPermits(get(), timestamp).map(
145+
async ({ reserve, increasedAmount, underlyingBalance }): Promise<Approval> => {
146+
console.log(underlyingBalance, 'underlyingBalance');
126147
const { getTokenData } = new ERC20Service(get().jsonRpcProvider());
127-
const { name, decimals } = await getTokenData(reserve.aTokenAddress);
128-
const amount = (Number(underlyingBalance) + 100).toString();
129-
const convertedAmount = valueToWei(amount, decimals);
148+
const { decimals } = await getTokenData(reserve.aTokenAddress);
149+
const convertedAmount = valueToWei(increasedAmount, decimals);
130150
return {
131151
// TODO: should we allow spending of exact ammount of the reserver?
132152
amount: convertedAmount,
@@ -140,53 +160,38 @@ export const createV3MigrationSlice: StateCreator<
140160
return approvalPermitsForMigrationAssets;
141161
},
142162
migrateWithoutPermits: () => {
163+
console.log('should be called before gas');
143164
const timestamp = dayjs().unix();
144165
set({ timestamp });
145-
const assets: {
146-
aToken: string;
147-
deadline: number;
148-
amount: string;
149-
underlyingAsset: string;
150-
}[] = selectedUserReservesForMigration(get(), timestamp).map(
151-
({ underlyingAsset, underlyingBalance, reserve }) => {
152-
const deadline = Math.floor(Date.now() / 1000 + 3600);
153-
return {
154-
amount: constants.MaxUint256.toString(),
155-
aToken: reserve.aTokenAddress,
156-
underlyingAsset: underlyingAsset,
157-
// TODO: fow how long to approve?
158-
deadline,
159-
};
160-
}
161-
);
166+
const borrowedPositions = selectUserBorrowReservesForMigration(get(), timestamp);
167+
if (borrowedPositions.length > 0) {
168+
return get().migrateBorrow();
169+
}
170+
const assets = selectUserSupplyAssetsForMigrationNoPermit(get(), timestamp);
162171
const user = get().account;
163172
return get().getMigrationServiceInstance().migrateNoBorrow({ assets, user });
164173
},
165174
migrateWithPermits: async (signatures: SignatureLike[], deadline: BigNumberish) => {
166-
const permits = await Promise.all(
167-
get().approvalPermitsForMigrationAssets.map(async ({ amount, underlyingAsset }, index) => {
168-
return {
169-
signedPermit: signatures[index],
170-
deadline,
171-
aToken: underlyingAsset,
172-
value: amount,
173-
};
174-
})
175+
const signedPermits = selectUserSupplyAssetsForMigrationWithPermits(
176+
get(),
177+
signatures,
178+
deadline
175179
);
176-
// branch out into flashloan or migrate no borrow
177-
// move that to separate instance and save cache the Migrator instance
180+
const borrowedPositions = selectUserBorrowReservesForMigration(get(), get().timestamp);
181+
if (borrowedPositions.length > 0) {
182+
return get().migrateBorrow(signedPermits);
183+
}
184+
178185
const migratorHelperInstance = get().getMigrationServiceInstance();
179186
const user = get().account;
180-
const assets = selectedUserReservesForMigration(get(), get().timestamp).map(
187+
const assets = selectedUserSupplyReservesForMigration(get(), get().timestamp).map(
181188
(reserve) => reserve.underlyingAsset
182189
);
183-
await get()._testMigration();
184-
console.log(assets);
185190
return migratorHelperInstance.migrateNoBorrowWithPermits({
186191
user,
187192
assets,
188193
deadline,
189-
signedPermits: permits,
194+
signedPermits,
190195
});
191196
},
192197
getMigratorAddress: () => {
@@ -201,20 +206,48 @@ export const createV3MigrationSlice: StateCreator<
201206
}
202207
const provider = get().jsonRpcProvider();
203208
const migratorAddress = get().getMigratorAddress();
204-
const newMigratorInstance = new V3MigrationHelperService(provider, migratorAddress);
209+
const currentMarketData = get().currentMarketData;
210+
// TODO: make it dynamic when network switch will be there
211+
const pool = new Pool(provider, {
212+
POOL: '0x794a61358D6845594F94dc1DB02A252b5b4814aD',
213+
REPAY_WITH_COLLATERAL_ADAPTER: currentMarketData.addresses.REPAY_WITH_COLLATERAL_ADAPTER,
214+
SWAP_COLLATERAL_ADAPTER: currentMarketData.addresses.SWAP_COLLATERAL_ADAPTER,
215+
WETH_GATEWAY: currentMarketData.addresses.WETH_GATEWAY,
216+
L2_ENCODER: currentMarketData.addresses.L2_ENCODER,
217+
});
218+
const newMigratorInstance = new V3MigrationHelperService(provider, migratorAddress, pool);
205219
// TODO: don't forget to add maping here
206220
return newMigratorInstance;
207221
},
208222
_testMigration: async () => {
209223
const currentTimestamp = dayjs().unix();
210-
const selectedReservers = selectedUserReservesForMigration(get(), currentTimestamp);
224+
const selectedReservers = selectedUserSupplyReservesForMigration(get(), currentTimestamp);
211225
const mappedAddresses = await Promise.all(
212226
selectedReservers.map((reserve) =>
213227
get().getMigrationServiceInstance().testDeployment(reserve.underlyingAsset)
214228
)
215229
);
216-
217-
console.log(mappedAddresses);
230+
},
231+
migrateBorrow: async (signedPermits: V3MigrationHelperSignedPermit[] = []) => {
232+
const currentTimestamp = dayjs().unix();
233+
const user = get().account;
234+
const suppliedPositions = selectUserSupplyAssetsForMigrationNoPermit(get(), currentTimestamp);
235+
const borrowedPositions = selectUserBorrowReservesForMigration(get(), currentTimestamp);
236+
const mappedBorrowPositions = borrowedPositions.map(
237+
({ increasedAmount, interestRate, underlyingAsset }) => {
238+
return {
239+
amount: increasedAmount,
240+
interestRate,
241+
address: underlyingAsset,
242+
};
243+
}
244+
);
245+
return get().getMigrationServiceInstance().migrateWithBorrow({
246+
user,
247+
borrowedPositions: mappedBorrowPositions,
248+
suppliedPositions,
249+
signedPermits,
250+
});
218251
},
219252
};
220253
};

0 commit comments

Comments
 (0)