Skip to content

Commit

Permalink
Integrated new fee resolver logic in Ajna and Morpho protocol impleme…
Browse files Browse the repository at this point in the history
…ntation
  • Loading branch information
piotrwitek committed Nov 6, 2024
1 parent 9eafe92 commit 9a4de75
Show file tree
Hide file tree
Showing 34 changed files with 296 additions and 94 deletions.
4 changes: 2 additions & 2 deletions packages/deploy-configurations/configs/mainnet.conf.ts
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ export const config: SystemConfig = {
},
Swap: {
name: 'Swap',
deploy: true,
deploy: false,
address: '0x826E9f2E79cEEA850dF4d4757e0D12115A720D74',
serviceRegistryName: SERVICE_REGISTRY_NAMES.common.SWAP,
history: [],
Expand Down Expand Up @@ -139,7 +139,7 @@ export const config: SystemConfig = {
},
SwapAction: {
name: 'SwapAction',
deploy: true,
deploy: false,
address: '0x313617D9CcBd96d66b2374c9bcB44b372D29b530',
serviceRegistryName: SERVICE_REGISTRY_NAMES.common.SWAP_ACTION,
history: ['0x7E7EB65A93441a2D2Bf0941216b4c1116B554d85'],
Expand Down
34 changes: 25 additions & 9 deletions packages/deploy-configurations/configs/tenderly.conf.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import { ADDRESS_ZERO, loadContractNames } from '@deploy-configurations/constants'
import { loadContractNames } from '@deploy-configurations/constants'
import { SystemConfig } from '@deploy-configurations/types/deployment-config'
import { Network } from '@deploy-configurations/types/network'

const SERVICE_REGISTRY_NAMES = loadContractNames(Network.TENDERLY)
const SERVICE_REGISTRY_NAMES = loadContractNames(Network.MAINNET)

export const config: SystemConfig = {
mpa: {
Expand Down Expand Up @@ -87,9 +87,9 @@ export const config: SystemConfig = {
Swap: {
name: 'Swap',
deploy: true,
address: '0xb779c4a8Df0054707F6E239159129bEd27b24878',
address: '0x826E9f2E79cEEA850dF4d4757e0D12115A720D74',
serviceRegistryName: SERVICE_REGISTRY_NAMES.common.SWAP,
history: ['0x826E9f2E79cEEA850dF4d4757e0D12115A720D74'],
history: [],
constructorArgs: [
'0x85f9b7408afE6CEb5E46223451f5d4b832B522dc',
'0xc7b548ad9cf38721810246c079b2d8083aba8909',
Expand Down Expand Up @@ -140,12 +140,9 @@ export const config: SystemConfig = {
SwapAction: {
name: 'SwapAction',
deploy: true,
address: '0xab0b80b169D12A4De609C88E5069873b445c8227',
address: '0x313617D9CcBd96d66b2374c9bcB44b372D29b530',
serviceRegistryName: SERVICE_REGISTRY_NAMES.common.SWAP_ACTION,
history: [
'0x7E7EB65A93441a2D2Bf0941216b4c1116B554d85',
'0x313617D9CcBd96d66b2374c9bcB44b372D29b530',
],
history: ['0x7E7EB65A93441a2D2Bf0941216b4c1116B554d85'],
constructorArgs: ['address:ServiceRegistry'],
},
TakeFlashloan: {
Expand Down Expand Up @@ -1087,6 +1084,25 @@ export const config: SystemConfig = {
},
},
},
spark: {
Oracle: {
name: 'Oracle',
address: '0x8105f69D9C41644c6A0803fDA7D03Aa70996cFD9',
},
LendingPool: {
name: 'LendingPool',
address: '0xC13e21B648A5Ee794902342038FF3aDAB66BE987',
serviceRegistryName: SERVICE_REGISTRY_NAMES.spark.LENDING_POOL,
},
PoolDataProvider: {
name: 'PoolDataProvider',
address: '0xFc21d6d146E6086B8359705C8b28512a983db0cb',
},
RewardsController: {
name: 'RewardsController',
address: '0x4370D3b6C9588E02ce9D22e684387859c7Ff5b34',
},
},
maker: {
common: {
FlashMintModule: {
Expand Down
18 changes: 9 additions & 9 deletions packages/deploy-configurations/constants/operation-names.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,15 +27,15 @@ export type SparkOperationNames =
export const OPERATION_NAMES = {
aave: {
v2: {
OPEN_POSITION: 'OpenAAVEPosition',
CLOSE_POSITION: 'CloseAAVEPosition_3',
INCREASE_POSITION: 'IncreaseAAVEPosition',
DECREASE_POSITION: 'DecreaseAAVEPosition',
DEPOSIT_BORROW: 'AAVEDepositBorrow',
OPEN_DEPOSIT_BORROW: 'AAVEOpenDepositBorrow',
DEPOSIT: 'AAVEDeposit',
BORROW: 'AAVEBorrow',
PAYBACK_WITHDRAW: 'AAVEPaybackWithdraw_2',
OPEN_POSITION: 'OpenAAVEPosition_v1',
CLOSE_POSITION: 'CloseAAVEPosition_v1',
INCREASE_POSITION: 'IncreaseAAVEPosition_v1',
DECREASE_POSITION: 'DecreaseAAVEPosition_v1',
DEPOSIT_BORROW: 'AAVEDepositBorrow_v1',
OPEN_DEPOSIT_BORROW: 'AAVEOpenDepositBorrow_v1',
DEPOSIT: 'AAVEDeposit_v1',
BORROW: 'AAVEBorrow_v1',
PAYBACK_WITHDRAW: 'AAVEPaybackWithdraw_v1',
},
v3: {
OPEN_POSITION: 'OpenAAVEV3Position_v3',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,22 +8,50 @@ type Action = {
export class OperationsRegistry {
address: string
signer: Signer
isTenderly: boolean
debug: boolean

constructor(address: string, signer: Signer) {
constructor(
address: string,
signer: Signer,
{ isTenderly, debug }: { isTenderly?: boolean; debug?: boolean } = {},
) {
this.address = address
this.signer = signer
this.isTenderly = isTenderly || false
this.debug = debug || false
}

async addOp(label: string, actions: Action[], debug = false): Promise<string> {
async addOp(label: string, actions: Action[]): Promise<string> {
const ethers = (await import('hardhat')).ethers
const entryHash = utils.keccak256(utils.toUtf8Bytes(label))
const registry = await ethers.getContractAt('OperationsRegistry', this.address, this.signer)
const actionHashes = actions.map(a => a.hash)
const optional = actions.map(a => a.optional)
await registry.addOperation({ name: label, actions: actionHashes, optional })

if (debug) {
console.log(`DEBUG: Service '${label}' has been added with hash: ${entryHash}`)
if (this.isTenderly) {
const tx = await registry.populateTransaction.addOperation({
name: label,
actions: actionHashes,
optional,
})
const provider = new ethers.providers.JsonRpcProvider(process.env.TENDERLY_FORK_URL)
const txHash = await provider
?.send('eth_sendTransaction', [
{
...tx,
from: process.env.IMPERSONATE_ADDRESS,
},
])
.catch(e => {
console.log('Error in the transaction', e)
})
await provider?.waitForTransaction(txHash)
} else {
await registry.addOperation({ name: label, actions: actionHashes, optional })
}
if (this.debug) {
console.log(`DEBUG: Operation '${label}' has been added with hash: ${entryHash}`)
console.log('DEBUG: Actions:', actionHashes)
console.log('DEBUG: Optional:', optional)
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,12 @@ export class ServiceRegistry {
address: string
signer: Signer
registry: Contract | undefined
isTenderly: boolean

constructor(address: string, signer: Signer) {
constructor(address: string, signer: Signer, { isTenderly }: { isTenderly?: boolean } = {}) {
this.address = address
this.signer = signer
this.isTenderly = isTenderly || false
}

private async _getRegistry(): Promise<Contract> {
Expand All @@ -24,16 +26,11 @@ export class ServiceRegistry {
return this._getRegistry()
}

async addEntry(
label: ContractNames,
address: string,
debug = false,
{ tenderly }: { tenderly: boolean } = { tenderly: false },
): Promise<string> {
async addEntry(label: ContractNames, address: string, debug = false): Promise<string> {
const entryHash = utils.keccak256(utils.toUtf8Bytes(label))
const registry = await this._getRegistry()

if (tenderly) {
if (this.isTenderly) {
const tx = await registry.populateTransaction.addNamedService(entryHash, address)
const provider = new ethers.providers.JsonRpcProvider(process.env.TENDERLY_FORK_URL)
const txHash = await provider
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ pragma solidity ^0.8.15;
import { Executable } from "../common/Executable.sol";
import { SafeERC20, IERC20 } from "../../libs/SafeERC20.sol";
import { PullTokenData } from "../../core/types/Common.sol";
import "../../core/types/Common.sol";

/**
* @title PullToken Action contract
Expand Down
1 change: 1 addition & 0 deletions packages/dma-contracts/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
"dev:mainnet": "yarn ts-node scripts/update-block-number.ts && yarn hardhat node --max-memory 8192 --fork $(grep MAINNET_URL ../../.env | cut -d '=' -f2)",
"dev:optimism": "yarn ts-node scripts/update-block-number.ts && yarn hardhat node --max-memory 8192 --fork $(grep OPTIMISM_URL ../../.env | cut -d '=' -f2)",
"deploy:dev": "yarn compile && yarn hardhat deploy --network local",
"deploy:mainnet": "yarn hardhat run scripts/deployment/deploy-mainnet.ts",
"deploy:morphoblue:integration": "yarn clean && yarn compile && yarn hardhat run scripts/morphoblue/deploy-morphoblue-integration.ts",
"compile": "npx hardhat --config hardhat.config.base.ts compile",
"clean": "rm -rf ./typechain && rm -rf ./artifacts && rm -rf ./cache",
Expand Down
4 changes: 2 additions & 2 deletions packages/dma-contracts/scripts/deployment/deploy-mainnet.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,8 @@ async function main() {
await ds.loadConfig()
await ds.deployCore()
await ds.deployActions()
await ds.saveConfig()
// await ds.addOperationEntries()
// await ds.saveConfig()
await ds.addOperationEntries()
// await ds.addAaveV3Operations()
// await ds.addSparkOperations()
}
Expand Down
21 changes: 17 additions & 4 deletions packages/dma-contracts/scripts/utils/deploy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ import {
getMorphoBlueAdjustDownOperationDefinition,
getMorphoBlueAdjustUpOperationDefinition,
getMorphoBlueBorrowOperationDefinition,
getMorphoBlueClaimRewardsOperationDefinition,
getMorphoBlueCloseOperationDefinition,
getMorphoBlueDepositBorrowOperationDefinition,
getMorphoBlueDepositOperationDefinition,
Expand Down Expand Up @@ -511,7 +512,6 @@ export class DeploymentSystem extends DeployedSystemHelpers {
configItem.serviceRegistryName,
contract.address,
true,
{ tenderly: this.isTenderly },
)
} catch (error: any) {
console.log(
Expand Down Expand Up @@ -558,7 +558,7 @@ export class DeploymentSystem extends DeployedSystemHelpers {
async addRegistryEntry(configItem: ConfigEntry, address: string) {
if (!this.serviceRegistryHelper) throw new Error('ServiceRegistryHelper not initialized')
if (configItem.serviceRegistryName) {
await this.serviceRegistryHelper.addEntry(configItem.serviceRegistryName, address)
await this.serviceRegistryHelper.addEntry(configItem.serviceRegistryName, address, true)
await this.postRegistryEntry(configItem, address)
}
}
Expand Down Expand Up @@ -607,7 +607,9 @@ export class DeploymentSystem extends DeployedSystemHelpers {
}

if (systemConfigEntry.name === 'ServiceRegistry') {
this.serviceRegistryHelper = new ServiceRegistry(systemConfigEntry.address, this.signer)
this.serviceRegistryHelper = new ServiceRegistry(systemConfigEntry.address, this.signer, {
isTenderly: this.isTenderly,
})

if (this.isLocal) {
if (!this.provider) throw new Error('No provider set')
Expand Down Expand Up @@ -712,7 +714,9 @@ export class DeploymentSystem extends DeployedSystemHelpers {
)

if (systemConfigEntry.name === 'ServiceRegistry') {
this.serviceRegistryHelper = new ServiceRegistry(contractInstance.address, this.signer)
this.serviceRegistryHelper = new ServiceRegistry(contractInstance.address, this.signer, {
isTenderly: this.isTenderly,
})
}

this.deployedSystem[systemConfigEntry.name] = {
Expand Down Expand Up @@ -922,6 +926,7 @@ export class DeploymentSystem extends DeployedSystemHelpers {
const operationsRegistry = new OperationsRegistry(
this.deployedSystem.OperationsRegistry.contract.address,
this.signer,
{ isTenderly: this.isTenderly, debug: true },
)

let network = this.network
Expand Down Expand Up @@ -1162,6 +1167,14 @@ export class DeploymentSystem extends DeployedSystemHelpers {
)
this.logOp(morphoblueAdjustDownOperationDefinition)

const morphoblueClaimRewardsOperationDefinition =
getMorphoBlueClaimRewardsOperationDefinition(network)
await operationsRegistry.addOp(
morphoblueClaimRewardsOperationDefinition.name,
morphoblueClaimRewardsOperationDefinition.actions,
)
this.logOp(morphoblueClaimRewardsOperationDefinition)

const sparkMigrateOperationDefinition = getSparkMigrateOperationDefinition(network)
await operationsRegistry.addOp(
sparkMigrateOperationDefinition.name,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ export const depositBorrow: AaveLikeDepositBorrow = async (args, dependencies) =
dependencies.addresses.tokens.WETH,
)

const deposit = await AaveCommon.buildDepositArgs(
const deposit = await AaveCommon.buildDepositBorrowArgs(
entryToken,
collateralToken,
collateralTokenAddress,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ export const openDepositBorrow: AaveLikeOpenDepositBorrow = async (args, depende
)

const alwaysReturnDepositArgs = true
const deposit = await AaveCommon.buildDepositArgs(
const deposit = await AaveCommon.buildDepositBorrowArgs(
entryToken,
collateralToken,
collateralTokenAddress,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import {
} from '@dma-library/strategies/aave/common'
import { resolveProtocolData } from '@dma-library/strategies/aave-like/common'
import * as StrategiesCommon from '@dma-library/strategies/common'
import { getPositionDataAaveLike } from '@dma-library/utils/fee-service'

import { buildOperation } from './build-operation'
import { generate } from './generate'
Expand Down Expand Up @@ -112,6 +113,7 @@ async function getAaveSwapDataToCloseToCollateral(
outstandingDebt: dependencies.currentPosition.debt.amount,
slippage,
getSwapData: dependencies.getSwapData,
positionData: getPositionDataAaveLike(dependencies),
})
}

Expand Down Expand Up @@ -144,5 +146,6 @@ async function getAaveSwapDataToCloseToDebt(
slippage,
swapAmountBeforeFees,
getSwapData: dependencies.getSwapData,
positionData: getPositionDataAaveLike(dependencies),
})
}
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import { amountToWei } from '@dma-common/utils/common'
import { getAaveTokenAddress } from '@dma-library/strategies/aave/common'
import { AaveLikeTokens } from '@dma-library/types/aave-like'
import { getPositionDataAaveLike } from '@dma-library/utils/fee-service'
import * as SwapUtils from '@dma-library/utils/swap'
import BigNumber from 'bignumber.js'

Expand All @@ -14,7 +13,7 @@ export const open: AaveLikeOpen = async (args, dependencies) => {
const fee = await SwapUtils.feeResolver(args.collateralToken.symbol, args.debtToken.symbol, {
isIncreasingRisk: true,
isEarnPosition: dependencies.positionType === 'Earn',
positionData: getPositionDataAaveLike(dependencies),
isOpeningPosition: true,
})

const estimatedSwapAmount = amountToWei(new BigNumber(1), args.debtToken.precision)
Expand Down
Original file line number Diff line number Diff line change
@@ -1,25 +1,22 @@
import { Address } from '@deploy-configurations/types/address'
import type { Network } from '@deploy-configurations/types/network'
import { ZERO } from '@dma-common/constants'
import { DepositArgs } from '@dma-library/operations'
import { AaveLikeStrategyAddresses } from '@dma-library/operations/aave-like'
import { getAaveTokenAddress } from '@dma-library/strategies/aave/common'
import { AaveLikeTokens, SwapData } from '@dma-library/types'
import * as StrategyParams from '@dma-library/types/strategy-params'
import { getPositionDataAaveLike } from '@dma-library/utils/fee-service'
import * as SwapUtils from '@dma-library/utils/swap'
import BigNumber from 'bignumber.js'

export async function buildDepositArgs(
import type { AaveLikeDepositBorrowDependencies } from '../../aave-like/borrow/deposit-borrow'
import type { AaveLikeOpenDepositBorrowDependencies } from '../../aave-like/borrow/open-deposit-borrow'

export async function buildDepositBorrowArgs(
entryToken: { symbol: AaveLikeTokens },
collateralToken: { symbol: AaveLikeTokens },
collateralTokenAddress: Address,
entryTokenAmount: BigNumber,
slippage: BigNumber,
dependencies: {
user: Address
network: Network
addresses: AaveLikeStrategyAddresses
} & StrategyParams.WithOptionalGetSwap,
dependencies: AaveLikeDepositBorrowDependencies | AaveLikeOpenDepositBorrowDependencies,
alwaysReturnArgs = false,
): Promise<{
swap:
Expand Down Expand Up @@ -71,8 +68,9 @@ export async function buildDepositArgs(
if (!dependencies.getSwapData) throw new Error('Swap data is required for swap to be performed')

const collectFeeInFromToken = collectFeeFrom === 'sourceToken'
const fee = SwapUtils.percentageFeeResolver(entryToken.symbol, collateralSymbol, {
const fee = await SwapUtils.feeResolver(entryToken.symbol, collateralSymbol, {
isEntrySwap: true,
positionData: getPositionDataAaveLike(dependencies),
})

const { swapData } = await SwapUtils.getSwapDataHelper<
Expand Down
Loading

0 comments on commit 9a4de75

Please sign in to comment.