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: add import position to order planner #173

Merged
merged 34 commits into from
Apr 16, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
34 commits
Select commit Hold shift + click to select a range
ed44ce8
feat: add position created event
robercano Apr 3, 2024
18e902c
Merge branch 'dev' into rc/sc-14933/add-position-created-to-refinance…
robercano Apr 3, 2024
25ba44d
feat: re-add refinance same pair simulation
robercano Apr 3, 2024
5e40783
chore: disable refinance test
robercano Apr 3, 2024
07147b5
fix: refinance swap parameters
robercano Apr 3, 2024
74980fd
fix: constructor visibility
robercano Apr 3, 2024
3be54fe
feat: implement import simulation
paszkowskiDamian Apr 4, 2024
d1ccd3c
feat: add position type to Position
robercano Apr 4, 2024
024d2bf
fix: missing refactor for position type
robercano Apr 4, 2024
a6035db
Merge branch 'rc/sc-14933/add-position-created-to-refinance-simulator…
robercano Apr 4, 2024
6f54222
fix: broken cicheck
robercano Apr 4, 2024
86c621a
chore: add format to turbo cicheck
robercano Apr 4, 2024
01af749
Merge branch 'rc/sc-14933/add-position-created-to-refinance-simulator…
robercano Apr 4, 2024
e059ab1
fix: cicheck
robercano Apr 4, 2024
a4a6598
Merge branch 'rc/sc-14933/add-position-created-to-refinance-simulator…
robercano Apr 4, 2024
e394291
wip: add maker import to maker plugin
robercano Apr 12, 2024
8c0fe61
Merge branch 'dev' into rc/sc-14620/add-import-position-to-order-planner
robercano Apr 12, 2024
3e8b29b
Merge remote-tracking branch 'origin/damianpaszkowski/import-simulati…
robercano Apr 12, 2024
c7cf2e0
fix: tests
robercano Apr 12, 2024
5fb79c4
Merge branch 'dev' of github.com:OasisDEX/summerfi-monorepo into dami…
paszkowskiDamian Apr 12, 2024
ffa855d
feat: rpc query
paszkowskiDamian Apr 12, 2024
cb3079d
fix: build
robercano Apr 12, 2024
936fc32
Merge remote-tracking branch 'origin/damianpaszkowski/import-simulati…
robercano Apr 12, 2024
eaa8056
chore: format and fix
paszkowskiDamian Apr 12, 2024
ae48ec6
chore: changes names
paszkowskiDamian Apr 12, 2024
157b297
wip: test import simulation
robercano Apr 12, 2024
5426ef1
Merge remote-tracking branch 'origin/damianpaszkowski/import-simulati…
robercano Apr 12, 2024
dcd0f2d
test: add Maker import test
robercano Apr 12, 2024
65da45a
chore: update fork URL
robercano Apr 12, 2024
8717648
chore: cleanup test
robercano Apr 12, 2024
59856fa
test: maker import + maker refinance
robercano Apr 12, 2024
8ffeecd
fix: tests
robercano Apr 12, 2024
69e5fea
fix: any pair simulation
robercano Apr 16, 2024
10a3869
Merge branch 'dev' into rc/sc-14620/add-import-position-to-order-planner
robercano Apr 16, 2024
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
11 changes: 11 additions & 0 deletions sdk/.env.template
Original file line number Diff line number Diff line change
Expand Up @@ -13,4 +13,15 @@ ONE_INCH_ALLOWED_SWAP_PROTOCOLS='UNISWAP_V3,PMM1,PMM2,PMM3,PMM4,UNISWAP_V2,SUSHI
# ChainIDs where 1Inch swaps are allowed (comma separated)
ONE_INCH_SWAP_CHAIN_IDS='1'

# 1Inch API spot URL
ONE_INCH_API_SPOT_URL=''

# 1Inch API spot version, like v1.0
ONE_INCH_API_SPOT_VERSION='v1.0'

# 1Inch API spot key
ONE_INCH_API_SPOT_KEY=''

# SDK Logging
SDK_LOGGING_ENABLED=

Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { IConfigurationProvider } from '../interfaces/IConfigurationProvider'
import { ConfigItem } from '../types/ConfigItem'
import { ConfigKey } from '../types/ConfigKey'

// NOTICE: remember to add new config keys to the SDKs .env.template file as well
const CONFIG_KEYS: ConfigKey[] = [
'ONE_INCH_API_VERSION',
'ONE_INCH_API_KEY',
Expand Down
70 changes: 35 additions & 35 deletions sdk/order-planner-common/src/implementation/OrderPlanner.ts
Original file line number Diff line number Diff line change
@@ -1,33 +1,23 @@
import { Order, type IPositionsManager } from '@summerfi/sdk-common/orders'
import { Order, type IPositionsManager, TransactionInfo } from '@summerfi/sdk-common/orders'
import { ISimulation, SimulationType, steps } from '@summerfi/sdk-common/simulation'
import { Deployment } from '@summerfi/deployment-utils'
import { Address, Maybe } from '@summerfi/sdk-common/common'
import { HexData } from '@summerfi/sdk-common/common/aliases'
import { ISwapManager } from '@summerfi/swap-common/interfaces'
import { IUser } from '@summerfi/sdk-common/user'
import {
ActionBuilder,
ActionBuildersMap,
ActionCall,
IProtocolPluginsRegistry,
IStepBuilderContext,
StepBuilderContext,
} from '@summerfi/protocol-plugins-common'
import { IOrderPlanner } from '../interfaces/IOrderPlanner'
import { IOrderPlanner, OrderPlannerParams } from '../interfaces/IOrderPlanner'
import { encodeStrategy } from '../utils/EncodeStrategy'

export class OrderPlanner implements IOrderPlanner {
// TODO: receive it as parameter in the constructor
private readonly ExecutorContractName = 'OperationExecutor'

async buildOrder(params: {
user: IUser
positionsManager: IPositionsManager
simulation: ISimulation<SimulationType>
actionBuildersMap: ActionBuildersMap
deployment: Deployment
swapManager: ISwapManager
protocolsRegistry: IProtocolPluginsRegistry
}): Promise<Maybe<Order>> {
async buildOrder(params: OrderPlannerParams): Promise<Maybe<Order>> {
const {
user,
positionsManager,
Expand All @@ -43,7 +33,7 @@ export class OrderPlanner implements IOrderPlanner {
context.startSubContext()

for (const step of simulation.steps) {
const stepBuilder = this.getActionBuilder(actionBuildersMap, step)
const stepBuilder = this._getActionBuilder(actionBuildersMap, step)
if (!stepBuilder) {
throw new Error(`No step builder found for step type ${step.type}`)
}
Expand All @@ -65,10 +55,18 @@ export class OrderPlanner implements IOrderPlanner {
throw new Error('Mismatched nested calls levels, probably a missing endSubContext call')
}

return this._generateOrder(simulation, callsBatch, positionsManager, deployment)
const preRequisiteTransactions = context.transactions

return this._generateOrder({
simulation,
preRequisiteTransactions,
simulationCalls: callsBatch,
positionsManager,
deployment,
})
}

private getActionBuilder<T extends steps.Steps>(
private _getActionBuilder<T extends steps.Steps>(
actionBuildersMap: ActionBuildersMap,
step: T,
): Maybe<ActionBuilder<T>> {
Expand All @@ -79,37 +77,39 @@ export class OrderPlanner implements IOrderPlanner {
return `${simulation.simulationType}${simulation.sourcePosition?.pool.protocol.name}${simulation.targetPosition?.pool.protocol.name}`
}

private _generateOrder(
simulation: ISimulation<SimulationType>,
simulationCalls: ActionCall[],
positionsManager: IPositionsManager,
deployment: Deployment,
): Order {
private _generateOrder(params: {
simulation: ISimulation<SimulationType>
preRequisiteTransactions: TransactionInfo[]
simulationCalls: ActionCall[]
positionsManager: IPositionsManager
deployment: Deployment
}): Order {
const { simulation, preRequisiteTransactions, simulationCalls, positionsManager, deployment } =
params

const executorInfo = deployment.contracts[this.ExecutorContractName]
if (!executorInfo) {
throw new Error(`Executor contract ${this.ExecutorContractName} not found in deployment`)
}
const executorAddress = Address.createFromEthereum({ value: executorInfo.address as HexData })
const strategyName = this._getStrategyName(simulation)

const calldata = encodeStrategy({
const strategyExecutorTransaction = encodeStrategy({
strategyName: strategyName,
strategyExecutor: executorAddress,
positionsManager: positionsManager,
actions: simulationCalls,
})

const transactions = [...preRequisiteTransactions]

if (strategyExecutorTransaction) {
transactions.push(strategyExecutorTransaction)
}

return {
simulation: simulation,
transactions: [
{
transaction: {
target: positionsManager.address,
calldata: calldata,
value: '0',
},
description: 'Strategy execution',
},
],
simulation,
transactions,
}
}
}
19 changes: 10 additions & 9 deletions sdk/order-planner-common/src/interfaces/IOrderPlanner.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,15 @@ import { Maybe } from '@summerfi/sdk-common/common'
import { IUser } from '@summerfi/sdk-common/user'
import { ActionBuildersMap, IProtocolPluginsRegistry } from '@summerfi/protocol-plugins-common'

export type OrderPlannerParams = {
user: IUser
positionsManager: IPositionsManager
simulation: ISimulation<SimulationType>
actionBuildersMap: ActionBuildersMap
deployment: Deployment
swapManager: ISwapManager
protocolsRegistry: IProtocolPluginsRegistry
}
export interface IOrderPlanner {
buildOrder<T extends SimulationType>(params: {
user: IUser
positionsManager: IPositionsManager
simulation: ISimulation<T>
actionBuildersMap: ActionBuildersMap
deployment: Deployment
swapManager: ISwapManager
protocolsRegistry: IProtocolPluginsRegistry
}): Promise<Maybe<Order>>
buildOrder(params: OrderPlannerParams): Promise<Maybe<Order>>
}
21 changes: 18 additions & 3 deletions sdk/order-planner-common/src/utils/EncodeStrategy.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { ActionCall } from '@summerfi/protocol-plugins-common'
import { Address, HexData } from '@summerfi/sdk-common/common'
import { Address, HexData, Maybe } from '@summerfi/sdk-common/common'
import { IPositionsManager, TransactionInfo } from '@summerfi/sdk-common/orders'
import { encodeFunctionData, parseAbi } from 'viem'

type SkippableActionCall = ActionCall & {
Expand Down Expand Up @@ -42,14 +43,28 @@ export function encodeForPositionsManager(params: { target: Address; data: HexDa
export function encodeStrategy(params: {
strategyName: string
strategyExecutor: Address
positionsManager: IPositionsManager
actions: ActionCall[]
}): HexData {
}): Maybe<TransactionInfo> {
const { strategyName, strategyExecutor, actions } = params

if (actions.length == 0) {
return undefined
}

const executorData = encodeForExecutor({ strategyName, actions })

return encodeForPositionsManager({
const calldata = encodeForPositionsManager({
target: strategyExecutor,
data: executorData,
})

return {
transaction: {
target: params.positionsManager.address,
calldata: calldata,
value: '0',
},
paszkowskiDamian marked this conversation as resolved.
Show resolved Hide resolved
description: 'Strategy execution',
}
}
5 changes: 5 additions & 0 deletions sdk/order-planner-common/src/utils/GenerateStrategyName.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import { ISimulation, SimulationType } from '@summerfi/sdk-common/simulation'

export function generateStrategyName(simulation: ISimulation<SimulationType>): string {
return `${simulation.simulationType}${simulation.sourcePosition?.pool.protocol.name}${simulation.targetPosition?.pool.protocol.name}`
}
14 changes: 12 additions & 2 deletions sdk/order-planner-common/tests/EncodeStrategy.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import {
decodeStrategyExecutorCalldata,
} from '@summerfi/testing-utils'
import assert from 'assert'
import { IPositionsManager } from '@summerfi/sdk-common/orders'

class DerivedAction extends BaseAction {
public readonly config = {
Expand Down Expand Up @@ -51,14 +52,23 @@ describe.only('Encode Strategy', () => {
})

it('should encode calls for operation executor', () => {
const calldata = encodeStrategy({
const positionsManager: IPositionsManager = {
address: Address.createFromEthereum({
value: '0x5e81A7515f956aB642eb698821a449fe8fE7498B',
}),
}

const transactionInfo = encodeStrategy({
strategyName: 'SomeStrategyName',
strategyExecutor: strategyExecutorAddress,
positionsManager: positionsManager,
actions: [actionCall, otherActionCall],
})

assert(transactionInfo, 'Cannot encode strategy')

const positionsManagerParams = decodePositionsManagerCalldata({
calldata: calldata,
calldata: transactionInfo.transaction.calldata,
})

assert(positionsManagerParams, 'Cannot decode Positions Manager calldata')
Expand Down
10 changes: 8 additions & 2 deletions sdk/order-planner-service/scripts/encodeMakerGive.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { encodeMakerGiveThroughProxyActions } from '../src/utils/MakerGive'
import { encodeMakerGiveThroughProxyActions } from '@summerfi/protocol-plugins/plugins/maker'

import yargs from 'yargs/yargs'
import { Hex } from 'viem'

Expand Down Expand Up @@ -37,7 +38,12 @@ async function main() {
console.log(`CDP ID: ${cdpId}`)
console.log(`To: ${to}\n`)

const result = encodeMakerGiveThroughProxyActions({ makerProxyActions, cdpManager, cdpId, to })
const result = encodeMakerGiveThroughProxyActions({
makerProxyActionsAddress: makerProxyActions,
cdpManagerAddress: cdpManager,
cdpId,
giveToAddress: to,
})

console.log(`[Full transaction Calldata]`)
console.log(`${result.transactionCalldata}\n`)
Expand Down
2 changes: 2 additions & 0 deletions sdk/order-planner-service/src/config/Config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { ActionBuildersMap } from '@summerfi/protocol-plugins-common'
import {
DepositBorrowActionBuilder,
FlashloanActionBuilder,
ImportPositionActionBuilder,
PaybackWithdrawActionBuilder,
PositionCreatedActionBuilder,
PullTokenActionBuilder,
Expand All @@ -20,4 +21,5 @@ export const ActionBuildersConfig: ActionBuildersMap = {
[SimulationSteps.PaybackWithdraw]: PaybackWithdrawActionBuilder,
[SimulationSteps.ReturnFunds]: ReturnFundsActionBuilder,
[SimulationSteps.NewPositionEvent]: PositionCreatedActionBuilder,
[SimulationSteps.Import]: ImportPositionActionBuilder,
}
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,9 @@ describe('Order Planner Service', () => {
provider: undefined as unknown as PublicClient,
tokenService: undefined as unknown as ITokenService,
priceService: undefined as unknown as IPriceService,
deployments: deploymentsIndex,
},
deploymentConfigTag: 'standard',
})

orderPlannerService = new OrderPlannerService({
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -65,15 +65,15 @@ export function getRefinanceSimulation(params: {
amount: sourcePosition.debtAmount,
},
outputs: undefined,
} as steps.RepayFlashloan,
} as steps.RepayFlashloanStep,
{
name: 'ReturnFunds',
type: SimulationSteps.ReturnFunds,
inputs: {
token: sourcePosition.debtAmount.token,
},
outputs: undefined,
} as steps.ReturnFunds,
} as steps.ReturnFundsStep,
],
}
}
7 changes: 6 additions & 1 deletion sdk/order-planner-service/tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,11 @@
"outDir": "dist",
"baseUrl": "."
},
"include": ["src/**/*.ts", "tests/**/*.ts", "scripts/**/*.ts"],
"include": [
"src/**/*.ts",
"tests/**/*.ts",
"scripts/**/*.ts",
"../protocol-plugins/src/plugins/maker/utils/MakerGive.ts"
],
"exclude": ["node_modules"]
}
4 changes: 4 additions & 0 deletions sdk/protocol-manager-service/tests/ProtocolManager.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import {
PriceService,
ProtocolPluginsRegistry,
} from '@summerfi/protocol-plugins/implementation'
import { DeploymentIndex } from '@summerfi/deployment-utils'

describe('Protocol Manager', () => {
let ctx: IProtocolManagerContext
Expand All @@ -31,6 +32,7 @@ describe('Protocol Manager', () => {
pluginsRegistry = new ProtocolPluginsRegistry({
plugins: mockPlugins,
context: ctx,
deploymentConfigTag: 'standard',
})
protocolManager = new ProtocolManager({ pluginsRegistry })
})
Expand Down Expand Up @@ -71,6 +73,7 @@ describe('Protocol Manager', () => {
const pluginsRegistry = new ProtocolPluginsRegistry({
plugins: mockPlugins,
context: ctx,
deploymentConfigTag: 'standard',
})

protocolManager = new ProtocolManager({ pluginsRegistry })
Expand Down Expand Up @@ -140,5 +143,6 @@ async function createProtocolManagerContext(): Promise<IProtocolManagerContext>
provider,
tokenService: new TokenService(),
priceService: new PriceService(provider),
deployments: {} as DeploymentIndex,
}
}
3 changes: 2 additions & 1 deletion sdk/protocol-manager-service/tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,8 @@
"outDir": "dist",
"baseUrl": ".",
"paths": {
"@summerfi/protocol-plugins/*": ["node_modules/@summerfi/protocol-plugins/src/*"]
"@summerfi/protocol-plugins/*": ["node_modules/@summerfi/protocol-plugins/src/*"],
"@summerfi/deployment-utils": ["../../packages/deployment-utils/src/index.ts"]
}
},
"include": ["src/**/*.ts", "tests/**/*.ts"],
Expand Down
3 changes: 2 additions & 1 deletion sdk/protocol-manager-service/tsconfig.test.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,8 @@
"@summerfi/order-planner-common/*": ["node_modules/@summerfi/order-planner-common/src/*"],
"@summerfi/protocol-plugins-common": [
"node_modules/@summerfi/protocol-plugins-common/src/index.ts"
]
],
"@summerfi/deployment-utils": ["../../packages/deployment-utils/src/index.ts"]
}
},
"include": ["src/**/*.ts"],
Expand Down
Loading
Loading