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

Maker history from subgraph #4019

Merged
merged 5 commits into from
Sep 24, 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
65 changes: 0 additions & 65 deletions features/automation/api/allActiveTriggers.ts

This file was deleted.

51 changes: 23 additions & 28 deletions features/automation/api/automationTriggersData.ts
Original file line number Diff line number Diff line change
@@ -1,54 +1,51 @@
import { TriggerType } from '@oasisdex/automation'
import type BigNumber from 'bignumber.js'
import { getNetworkContracts } from 'blockchain/contracts'
import { every5Seconds$ } from 'blockchain/network.constants'
import type { Context } from 'blockchain/network.types'
import { NetworkIds } from 'blockchain/networks'
import type { AddressesRelatedWithPosition } from 'features/aave/helpers/getProxiesRelatedWithPosition'
import type { PositionId } from 'features/aave/types/position-id'
import { getAllActiveTriggers } from 'features/automation/api/allActiveTriggers'
import type { NetworkIds } from 'blockchain/networks'
import { extractAutoBSData } from 'features/automation/common/state/autoBSTriggerData'
import { extractAutoTakeProfitData } from 'features/automation/optimization/autoTakeProfit/state/autoTakeProfitTriggerData'
import { extractConstantMultipleData } from 'features/automation/optimization/constantMultiple/state/constantMultipleTriggerData'
import { extractStopLossData } from 'features/automation/protection/stopLoss/state/stopLossTriggerData'
import { GraphQLClient } from 'graphql-request'
import type { SubgraphsResponses } from 'features/subgraphLoader/types'
import { loadSubgraph } from 'features/subgraphLoader/useSubgraphLoader'
import { type Observable, of } from 'rxjs'
import { distinctUntilChanged, map, mergeMap, shareReplay, withLatestFrom } from 'rxjs/operators'

import type { TriggersData } from './automationTriggersData.types'

export async function loadTriggerDataFromCache({
async function loadTriggerDataFromSubgraph({
positionId,
proxyAddress,
cacheApi,
chainId,
}: {
positionId: number
cacheApi: string
proxyAddress?: string
chainId: NetworkIds
}): Promise<TriggersData> {
const activeTriggersForVault = await getAllActiveTriggers(
new GraphQLClient(cacheApi),
positionId.toString(),
proxyAddress,
)
const { response } = (await loadSubgraph({
subgraph: 'Discover',
method: 'getMakerTriggersOld',
networkId: chainId,
params: {
cdpId: positionId,
},
})) as SubgraphsResponses['Discover']['getMakerTriggersOld']

const triggers = response.cdps[0].triggers

return {
isAutomationDataLoaded: true,
isAutomationEnabled: activeTriggersForVault.length > 0,
triggers: activeTriggersForVault,
isAutomationEnabled: triggers.length > 0,
triggers: triggers.map((item) => ({
...item,
triggerId: item.id,
executionParams: item.triggerData,
})),
chainId,
}
}

export function createAutomationTriggersData(
context$: Observable<Context>,
onEveryBlock$: Observable<number>,
proxiesRelatedWithPosition$: (
positionId: PositionId,
networkId: NetworkIds,
) => Observable<AddressesRelatedWithPosition>,
id: BigNumber,
networkId: NetworkIds,
): Observable<TriggersData> {
Expand All @@ -62,12 +59,10 @@ export function createAutomationTriggersData(
})
}
return every5Seconds$.pipe(
withLatestFrom(context$, proxiesRelatedWithPosition$({ vaultId: id.toNumber() }, networkId)),
mergeMap(([, context, proxies]) => {
return loadTriggerDataFromCache({
withLatestFrom(context$),
mergeMap(([, context]) => {
return loadTriggerDataFromSubgraph({
positionId: id.toNumber(),
proxyAddress: proxies.dpmProxy?.proxy,
cacheApi: getNetworkContracts(NetworkIds.MAINNET, context.chainId).cacheApi,
chainId: context.chainId,
})
}),
Expand Down
8 changes: 4 additions & 4 deletions features/automation/api/automationTxHandlers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ import { takeWhileInclusive } from 'rxjs-take-while-inclusive'
import { takeUntilTxState } from './takeUntilTxState'

export function removeAutomationTrigger(
{ sendWithGasEstimation }: TxHelpers,
{ send }: TxHelpers,
txData: AutomationRemoveTriggerData,
uiChanges: UIChanges,
ethPrice: BigNumber,
Expand All @@ -32,7 +32,7 @@ export function removeAutomationTrigger(
) {
const resolvedTxDef = removeTriggerDef || removeAutomationBotAggregatorTriggers

sendWithGasEstimation(resolvedTxDef as TransactionDef<AutomationTxData>, txData)
send(resolvedTxDef as TransactionDef<AutomationTxData>, txData)
.pipe(takeWhileInclusive((txState) => !takeUntilTxState.includes(txState.status)))
.subscribe((txState) =>
handleTransaction({
Expand All @@ -45,7 +45,7 @@ export function removeAutomationTrigger(
}

export function addAutomationTrigger(
{ sendWithGasEstimation }: TxHelpers,
{ send }: TxHelpers,
txData: AutomationAddTriggerData,
uiChanges: UIChanges,
ethPrice: BigNumber,
Expand All @@ -60,7 +60,7 @@ export function addAutomationTrigger(

const resolvedTxDef = addTriggerDef || txDef

sendWithGasEstimation(resolvedTxDef as TransactionDef<AutomationTxData>, txData)
send(resolvedTxDef as TransactionDef<AutomationTxData>, txData)
.pipe(takeWhileInclusive((txState) => !takeUntilTxState.includes(txState.status)))
.subscribe((txState) => {
return handleTransaction({
Expand Down
2 changes: 2 additions & 0 deletions features/positionHistory/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -141,6 +141,8 @@ export interface Trigger {
executedTransaction: string
decodedDataNames: string[]
decodedData: string[]
commandAddress: string
triggerData: string
tokens: {
symbol: string
address: string
Expand Down
83 changes: 83 additions & 0 deletions features/subgraphLoader/consts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -897,4 +897,87 @@ export const subgraphMethodsRecord: SubgraphMethodsRecord = {
}
}
`,
getMakerHistoryOld: gql`
query getMakerHistoryOld($cdpId: Int!) {
cdps(where: { cdp: $cdpId }) {
stateLogs {
kind
collateralBefore
collateralAfter
collateralDiff
debtBefore
debtAfter
debtDiff
normalizedDebtBefore
normalizedDebtAfter
normalizedDebtDiff
beforeMultiple
afterMultiple
liquidationPriceBefore
liquidationPriceAfter
collRatioBefore
collRatioAfter
rate
oraclePrice
multipleDiff
collRatioDiff
oazoFee
loadFee
gasFee
totalFee
netValue
marketPrice
collateralMarketPrice
logIndex
tab
flip
bought
sold
depositCollateral
depositDai
withdrawnCollateral
withdrawnDai
exitCollateral
exitDai
debt
lockedCollateral
block
timestamp
transaction
}
}
}
`,
getMakerTriggersOld: gql`
query getMakerTriggersOld($cdpId: Int!) {
cdps(where: { cdp: $cdpId }) {
triggers {
id
commandAddress
triggerData
}
}
}
`,
getMakerAutomationEvents: gql`
query getAutomationEvents($cdpId: ID!) {
triggerEvents(where: { trigger_: { cdpId: $cdpId } }) {
eventType
transaction
timestamp
trigger {
kind
simpleName
tokens {
symbol
address
}
decodedData
decodedDataNames
triggerData
commandAddress
}
}
}
`,
}
10 changes: 10 additions & 0 deletions features/subgraphLoader/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,9 @@ import type { AjnaDpmPositionsResponse } from 'handlers/portfolio/positions/hand
import type { Erc4626DpmPositionsResponse } from 'handlers/portfolio/positions/handlers/erc-4626/types'
import type {
MakerDiscoverPositionsResponse,
MakerHistoryOldResponse,
MakerOsmResponse,
MakerTriggersOldResponse,
} from 'handlers/portfolio/positions/handlers/maker/types'
import type { MorphoDpmPositionsResponse } from 'handlers/portfolio/positions/handlers/morpho-blue/types'
import type { Erc4626InterestRatesResponse } from 'handlers/product-hub/update-handlers/erc-4626/erc4626Handler'
Expand Down Expand Up @@ -67,6 +69,8 @@ export type Subgraphs = {
Discover: {
getMakerDiscoverPositions: { walletAddress: string }
getOsm: { id: string; block: number }
getMakerHistoryOld: { cdpId: number }
getMakerTriggersOld: { cdpId: number }
}
Morpho: {
getMorphoVauldIdPositions: { positionId: number }
Expand All @@ -93,6 +97,9 @@ export type Subgraphs = {
collateralAddress: string
debtAddress: string
}
getMakerAutomationEvents: {
cdpId: number
}
}
}

Expand Down Expand Up @@ -170,6 +177,8 @@ export type SubgraphsResponses = {
Discover: {
getMakerDiscoverPositions: SubgraphBaseResponse<MakerDiscoverPositionsResponse>
getOsm: SubgraphBaseResponse<MakerOsmResponse>
getMakerHistoryOld: SubgraphBaseResponse<MakerHistoryOldResponse>
getMakerTriggersOld: SubgraphBaseResponse<MakerTriggersOldResponse>
}
Morpho: {
getMorphoVauldIdPositions: SubgraphBaseResponse<MorphoVauldIdPositionsResponse>
Expand Down Expand Up @@ -197,6 +206,7 @@ export type SubgraphsResponses = {
}
Automation: {
getAutomationEvents: SubgraphBaseResponse<{ triggerEvents: TriggerEvent[] }>
getMakerAutomationEvents: SubgraphBaseResponse<{ triggerEvents: TriggerEvent[] }>
}
}

Expand Down
2 changes: 1 addition & 1 deletion features/vaultHistory/VaultHistoryView.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ export function VaultHistoryView({ vaultHistory }: { vaultHistory: VaultHistoryE
? getNetworkContracts(NetworkIds.MAINNET, context.chainId).etherscan
: undefined
}
key={`${item.id}-${item.splitId || item.hash}`}
key={`${item.id}-${item.splitId || item.hash}-${'eventType' in item ? item.eventType : ''}-${item.timestamp}`}
/>
))}
</DefinitionList>
Expand Down
32 changes: 32 additions & 0 deletions features/vaultHistory/mapMakerSubgraphAutomationHistoryOld.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import type { TriggerEvent } from 'features/positionHistory/types'

const triggerKindMap: Record<string, string> = {
BasicBuy: 'basic-buy',
BasicSell: 'basic-sell',
StopLossToDai: 'stop-loss',
StopLossToCollateral: 'stop-loss',
AutoTakeProfitToDai: 'auto-take-profit',
AutoTakeProfitToCollateral: 'auto-take-profit',
}

export const mapMakerSubgraphAutomationHistoryOld = (triggerEvents: TriggerEvent[]) => {
return triggerEvents.map((event) => {
const debtAddressIndex = event.trigger.decodedDataNames.findIndex((x) => x === 'triggerId')
const cpdIdIndex = event.trigger.decodedDataNames.findIndex((x) => x === 'cpdId')

return {
cdpId: event.trigger.decodedData[cpdIdIndex],
chainId: 1,
commandAddress: event.trigger.commandAddress,
ethPrice: '1',
eventType: event.eventType.toLowerCase(),
gasFee: '0',
hash: event.transaction,
id: event.transaction,
kind: triggerKindMap[event.trigger.kind],
timestamp: Number(event.timestamp) * 1000,
triggerData: event.trigger.triggerData,
triggerId: event.trigger.decodedData[debtAddressIndex],
}
})
piekczyk marked this conversation as resolved.
Show resolved Hide resolved
}
Loading
Loading