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: no debt refinance #213

Merged
merged 2 commits into from
Apr 29, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
Original file line number Diff line number Diff line change
Expand Up @@ -25,20 +25,22 @@ export const MakerPaybackWithdrawActionBuilder: ActionBuilder<steps.PaybackWithd

const paybackAmount = getValueFromReference(step.inputs.paybackAmount)

context.addActionCall({
step: params.step,
action: new MakerPaybackAction(),
arguments: {
pool: step.inputs.position.pool,
positionsManager: positionsManager,
amount: getValueFromReference(step.inputs.paybackAmount),
paybackAll: paybackAmount.toBN().gte(step.inputs.position.debtAmount.toBN()),
},
connectedInputs: {},
connectedOutputs: {
paybackAmount: 'amountPaidBack',
},
})
if (!paybackAmount.toBN().isZero()) {
context.addActionCall({
step: params.step,
action: new MakerPaybackAction(),
arguments: {
pool: step.inputs.position.pool,
positionsManager: positionsManager,
amount: getValueFromReference(step.inputs.paybackAmount),
paybackAll: paybackAmount.toBN().gte(step.inputs.position.debtAmount.toBN()),
},
connectedInputs: {},
connectedOutputs: {
paybackAmount: 'amountPaidBack',
},
})
}

context.addActionCall({
step: step,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -62,16 +62,20 @@ export const SparkDepositBorrowActionBuilder: ActionBuilder<steps.DepositBorrowS
},
})

context.addActionCall({
step: step,
action: new SparkBorrowAction(),
arguments: {
borrowAmount: getValueFromReference(step.inputs.borrowAmount),
borrowTo: getBorrowTargetAddress(params),
},
connectedInputs: {},
connectedOutputs: {
borrowAmount: 'borrowedAmount',
},
})
const borrowAmount = getValueFromReference(step.inputs.borrowAmount)

if (!borrowAmount.toBN().isZero()) {
context.addActionCall({
step: step,
action: new SparkBorrowAction(),
arguments: {
borrowAmount: borrowAmount,
borrowTo: getBorrowTargetAddress(params),
},
connectedInputs: {},
connectedOutputs: {
borrowAmount: 'borrowedAmount',
},
})
}
}
4 changes: 4 additions & 0 deletions sdk/sdk-common/src/simulation/Enums.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ export enum SimulationType {
RefinanceDifferentPair = 'RefinanceDifPair',
RefinanceDifferentDebt = 'RefinanceDifDebt',
RefinanceDifferentCollateral = 'RefinanceDifCol',
RefinanceNoDebt = 'RefinanceNoDebt',
RefinanceNoDebtDifferentCollateral = 'RefNoDebtDifCol',
}

export enum SimulationSteps {
Expand Down Expand Up @@ -39,3 +41,5 @@ export type RefinanceSimulationTypes =
| SimulationType.RefinanceDifferentPair
| SimulationType.RefinanceDifferentCollateral
| SimulationType.RefinanceDifferentDebt
| SimulationType.RefinanceNoDebt
| SimulationType.RefinanceNoDebtDifferentCollateral
29 changes: 13 additions & 16 deletions sdk/sdk-e2e/tests/refinanceMakerSparkAnyPair.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,23 +15,21 @@ import { ProtocolName, isLendingPool } from '@summerfi/sdk-common/protocols'
import { makeSDK, type Chain, type User, Protocol } from '@summerfi/sdk-client'
import { TokenSymbol } from '@summerfi/sdk-common/common/enums'
import { IPositionsManager, IRefinanceParameters, Order } from '@summerfi/sdk-common/orders'
import { ISimulation } from '@summerfi/sdk-common/simulation'
import { TransactionUtils } from './utils/TransactionUtils'

import { Hex } from 'viem'
import assert from 'assert'
import { EmodeType } from '@summerfi/protocol-plugins/plugins/common'
import { ILKType, MakerPoolId } from '@summerfi/protocol-plugins/plugins/maker'
import { SparkPoolId, isSparkPoolId } from '@summerfi/protocol-plugins/plugins/spark'
import { RefinanceSimulationTypes } from '@summerfi/sdk-common'

jest.setTimeout(300000)

const SDKAPiUrl = 'https://nkllstfoy8.execute-api.us-east-1.amazonaws.com/api/sdk'
const TenderlyForkUrl =
'https://virtual.mainnet.rpc.tenderly.co/f3d20ba3-707e-4c49-88ef-21f8c32cb18d'
'https://virtual.mainnet.rpc.tenderly.co/ea4060f8-c16d-49ba-84dd-2c12afb98cdd'

describe.skip('Refinance Maker Spark | SDK', () => {
describe.only('Refinance Maker Spark | SDK', () => {
it('should allow refinance Maker -> Spark with same pair', async () => {
// SDK
const sdk = makeSDK({ apiURL: SDKAPiUrl })
Expand All @@ -58,7 +56,7 @@ describe.skip('Refinance Maker Spark | SDK', () => {
// Positions Manager
const positionsManager: IPositionsManager = {
address: Address.createFromEthereum({
value: '0x1858b76756d19f8cb7c7756a0f96e0d7673285ed',
value: '0xd1edd5ff690a83e9a1ebcd0ac1c3f7e231b72f76',
}),
}

Expand Down Expand Up @@ -90,7 +88,7 @@ describe.skip('Refinance Maker Spark | SDK', () => {
chainInfo: chain.chainInfo,
},
ilkType: ILKType.ETH_C,
vaultId: '31697',
vaultId: '31717',
}

const makerPool = await maker.getPool({
Expand All @@ -105,14 +103,14 @@ describe.skip('Refinance Maker Spark | SDK', () => {
// Source position
const makerPosition: Position = Position.createFrom({
type: PositionType.Multiply,
positionId: PositionId.createFrom({ id: '31697' }),
positionId: PositionId.createFrom({ id: '31717' }),
debtAmount: TokenAmount.createFromBaseUnit({
token: DAI,
amount: '5000000000000000000000',
amount: '0',
}),
collateralAmount: TokenAmount.createFromBaseUnit({
token: WETH,
amount: '100000000000000000000',
amount: '10000000000000000000',
}),
pool: makerPool,
})
Expand Down Expand Up @@ -146,13 +144,12 @@ describe.skip('Refinance Maker Spark | SDK', () => {
assert(false, 'Spark pool type is not lending')
}

const emptyTargetPosition = newEmptyPositionFromPool(sparkPool, WETH, SDAI)
const refinanceSimulation: ISimulation<RefinanceSimulationTypes> =
await sdk.simulator.refinance.simulateRefinancePosition({
sourcePosition: makerPosition,
targetPosition: emptyTargetPosition,
slippage: Percentage.createFrom({ value: 0.2 }),
} as IRefinanceParameters)
const emptyTargetPosition = newEmptyPositionFromPool(sparkPool, DAI, WBTC)
const refinanceSimulation = await sdk.simulator.refinance.simulateRefinancePosition({
sourcePosition: makerPosition,
targetPosition: emptyTargetPosition,
slippage: Percentage.createFrom({ value: 0.2 }),
} as IRefinanceParameters)

expect(refinanceSimulation).toBeDefined()

Expand Down
5 changes: 5 additions & 0 deletions sdk/sdk-server/src/handlers/getRefinanceSimulation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import {
refinanceLendingToLendingSamePair,
type IRefinanceDependencies,
refinanceLendingToLendingAnyPair,
refinanceLendingToLendingNoDebt,
} from '@summerfi/simulator-service/strategies'
import type { IRefinanceParameters } from '@summerfi/sdk-common/orders'
import { publicProcedure } from '../TRPC'
Expand Down Expand Up @@ -34,6 +35,10 @@ export const getRefinanceSimulation = publicProcedure
protocolManager: opts.ctx.protocolManager,
}

if (opts.input.sourcePosition.debtAmount.amount === '0') {
return refinanceLendingToLendingNoDebt(args, dependencies)
}

// TODO: in the end we should use just any pair
if (isToSamePair(opts.input)) {
return refinanceLendingToLendingSamePair(args, dependencies)
Expand Down
1 change: 1 addition & 0 deletions sdk/simulator-service/src/strategies/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
export * from './refinanceSamePair'
export * from './refinanceAnyPair'
export * from './refinanceNoDebt'
export * from './common'
export * from './import'
Original file line number Diff line number Diff line change
@@ -0,0 +1,139 @@
import {
ISimulation,
SimulationSteps,
SimulationType,
TokenTransferTargetType,
} from '@summerfi/sdk-common/simulation'
import { Simulator } from '../../implementation/simulator-engine'
import { Percentage, Position, TokenAmount } from '@summerfi/sdk-common/common'
import { newEmptyPositionFromPool } from '@summerfi/sdk-common/common/utils'
import { IRefinanceParameters } from '@summerfi/sdk-common/orders'
import { isLendingPool } from '@summerfi/sdk-common/protocols'
import { refinanceLendingToLendingNoDebtStrategy } from './Strategy'
import { type IRefinanceDependencies } from '../common/Types'
import { getSwapStepData } from '../../implementation/utils/GetSwapStepData'

export async function refinanceLendingToLendingNoDebt(
args: IRefinanceParameters,
dependencies: IRefinanceDependencies,
): Promise<
ISimulation<SimulationType.RefinanceNoDebt | SimulationType.RefinanceNoDebtDifferentCollateral>
> {
// args validation
if (!isLendingPool(args.targetPosition.pool)) {
throw new Error('Target pool is not a lending pool')
}

const position = Position.createFrom(args.sourcePosition)
const targetPool = await dependencies.protocolManager.getPool(args.targetPosition.pool.poolId)

if (!isLendingPool(targetPool)) {
throw new Error('Target pool is not a lending pool')
}
const simulator = Simulator.create(refinanceLendingToLendingNoDebtStrategy)

const targetTokenConfig = targetPool.collaterals.get({ token: position.collateralAmount.token })
if (!targetTokenConfig) {
throw new Error('Target token not found in pool')
}

const zeroAmount = TokenAmount.createFromBaseUnit({
token: position.debtAmount.token,
amount: '0',
})

const targetCollateralConfig = targetPool.collaterals.get({
token: args.targetPosition.collateralAmount.token,
})
const targetDebtConfig = targetPool.debts.get({ token: args.targetPosition.debtAmount.token })

if (!targetCollateralConfig || !targetDebtConfig) {
throw new Error('Target token config not found in pool')
}

const isCollateralSwapSkipped = targetCollateralConfig.token.address.equals(
position.collateralAmount.token.address,
)

const simulation = await simulator
.next(async () => ({
name: 'PaybackWithdrawFromSource',
type: SimulationSteps.PaybackWithdraw,
inputs: {
paybackAmount: zeroAmount,
withdrawAmount: position.collateralAmount,
position: position,
},
}))
.next(
async () => ({
name: 'CollateralSwap',
type: SimulationSteps.Swap,
inputs: await getSwapStepData({
chainInfo: position.pool.protocol.chainInfo,
fromAmount: position.collateralAmount,
toToken: targetCollateralConfig.token,
slippage: Percentage.createFrom({ value: args.slippage.value }),
swapManager: dependencies.swapManager,
}),
}),
isCollateralSwapSkipped,
)
.next(async (ctx) => ({
name: 'DepositBorrowToTarget',
type: SimulationSteps.DepositBorrow,
inputs: {
depositAmount: ctx.getReference(
isCollateralSwapSkipped
? ['PaybackWithdrawFromSource', 'withdrawAmount']
: ['CollateralSwap', 'received'],
),
borrowAmount: TokenAmount.createFrom({
amount: '0',
token: position.debtAmount.token,
}),
position: newEmptyPositionFromPool(
targetPool,
targetDebtConfig.token,
targetCollateralConfig.token,
),
borrowTargetType: TokenTransferTargetType.PositionsManager,
},
}))
.next(async (ctx) => {
// TODO: we should have a way to get the target position more easily and realiably,
const targetPosition = Object.values(ctx.state.positions).find(
(p) => p.pool.protocol === targetPool.protocol,
)
if (!targetPosition) {
throw new Error('Target position not found')
}

return {
name: 'NewPositionEvent',
type: SimulationSteps.NewPositionEvent,
inputs: {
position: targetPosition,
},
}
})
.run()

const targetPosition = Object.values(simulation.positions).find(
(p) => p.pool.protocol === targetPool.protocol,
)

if (!targetPosition) {
throw new Error('Target position not found')
}

return {
simulationType: isCollateralSwapSkipped
? SimulationType.RefinanceNoDebt
: SimulationType.RefinanceNoDebtDifferentCollateral,
sourcePosition: position,
targetPosition,
swaps: Object.values(simulation.swaps),
steps: Object.values(simulation.steps),
}
}
21 changes: 21 additions & 0 deletions sdk/simulator-service/src/strategies/refinanceNoDebt/Strategy.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import { SimulationSteps } from '@summerfi/sdk-common/simulation'
import { makeStrategy } from '../../implementation/utils'

export const refinanceLendingToLendingNoDebtStrategy = makeStrategy([
{
step: SimulationSteps.PaybackWithdraw,
optional: false,
},
{
step: SimulationSteps.Swap,
optional: true,
},
{
step: SimulationSteps.DepositBorrow,
optional: false,
},
{
step: SimulationSteps.NewPositionEvent,
optional: false,
},
])
2 changes: 2 additions & 0 deletions sdk/simulator-service/src/strategies/refinanceNoDebt/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
export * from './RefinanceLendingToLendingNoDebt'
export * from './Strategy'
Loading