Skip to content

Commit

Permalink
injectable unwrap cache (#323)
Browse files Browse the repository at this point in the history
  • Loading branch information
bergarces authored Sep 24, 2024
1 parent e66b3d7 commit 87bf0ef
Show file tree
Hide file tree
Showing 6 changed files with 251 additions and 12 deletions.
15 changes: 11 additions & 4 deletions packages/adapters-library/src/core/getProfits.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import {
Underlying,
} from '../types/adapter'
import { Erc20Metadata } from '../types/erc20Metadata'
import { IUnwrapCache } from '../unwrapCache'
import { aggregateFiatBalances } from './utils/aggregateFiatBalances'
import { aggregateFiatBalancesFromMovements } from './utils/aggregateFiatBalancesFromMovements'
import { calculateDeFiAttributionPerformance } from './utils/calculateDeFiAttributionPerformance'
Expand All @@ -25,6 +26,7 @@ export async function getProfits({
protocolTokenAddresses,
tokenIds,
includeRawValues,
unwrapCache,
}: {
adapter: IProtocolAdapter
userAddress: string
Expand All @@ -33,6 +35,7 @@ export async function getProfits({
protocolTokenAddresses?: string[]
tokenIds?: string[]
includeRawValues?: boolean
unwrapCache: IUnwrapCache
}): Promise<ProfitsWithRange> {
let endPositionValues: ReturnType<typeof aggregateFiatBalances>
let startPositionValues: ReturnType<typeof aggregateFiatBalances>
Expand All @@ -52,7 +55,7 @@ export async function getProfits({
tokenIds,
})
.then(async (result) => {
await unwrap(adapter, toBlock, result, 'balanceRaw')
await unwrap(adapter, toBlock, result, 'balanceRaw', unwrapCache)
return result
})
.then((result) => {
Expand All @@ -67,7 +70,7 @@ export async function getProfits({
tokenIds,
})
.then(async (result) => {
await unwrap(adapter, fromBlock, result, 'balanceRaw')
await unwrap(adapter, fromBlock, result, 'balanceRaw', unwrapCache)
return result
})
.then((result) => {
Expand All @@ -83,7 +86,7 @@ export async function getProfits({
blockNumber: toBlock,
})
.then(async (result) => {
await unwrap(adapter, toBlock, result, 'balanceRaw')
await unwrap(adapter, toBlock, result, 'balanceRaw', unwrapCache)
return result
})
.then((result) => {
Expand All @@ -99,7 +102,7 @@ export async function getProfits({
tokenIds: Object.keys(endPositionValues), // endPositionValues is indexed by tokenId ?? protocolTokenAddress
})
.then(async (result) => {
await unwrap(adapter, fromBlock, result, 'balanceRaw')
await unwrap(adapter, fromBlock, result, 'balanceRaw', unwrapCache)
return result
})
.then((result) => {
Expand Down Expand Up @@ -140,6 +143,7 @@ export async function getProfits({
positionMovements.blockNumber,
positionMovements.tokens,
'balanceRaw',
unwrapCache,
)
}),
)
Expand Down Expand Up @@ -169,6 +173,7 @@ export async function getProfits({
positionMovements.blockNumber,
positionMovements.tokens,
'balanceRaw',
unwrapCache,
)
}),
)
Expand Down Expand Up @@ -198,6 +203,7 @@ export async function getProfits({
positionMovements.blockNumber,
positionMovements.tokens,
'balanceRaw',
unwrapCache,
)
}),
)
Expand Down Expand Up @@ -227,6 +233,7 @@ export async function getProfits({
positionMovements.blockNumber,
positionMovements.tokens,
'balanceRaw',
unwrapCache,
)
}),
)
Expand Down
27 changes: 22 additions & 5 deletions packages/adapters-library/src/core/utils/unwrap.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { Protocol } from '../../adapters/protocols'
import { IProtocolAdapter } from '../../types/IProtocolAdapter'
import { TokenType, UnderlyingTokenTypeMap } from '../../types/adapter'
import { Erc20Metadata } from '../../types/erc20Metadata'
import { IUnwrapCache } from '../../unwrapCache'
import {
AdapterMissingError,
NotImplementedError,
Expand All @@ -20,10 +21,11 @@ export async function unwrap(
blockNumber: number | undefined,
tokens: Token[],
fieldToUpdate: string,
unwrapCache: IUnwrapCache,
) {
return await Promise.all(
tokens.map(async (token) => {
await unwrapToken(adapter, blockNumber, token, fieldToUpdate)
await unwrapToken(adapter, blockNumber, token, fieldToUpdate, unwrapCache)
}),
)
}
Expand All @@ -33,6 +35,7 @@ async function unwrapToken(
blockNumber: number | undefined,
token: Token,
fieldToUpdate: string,
unwrapCache: IUnwrapCache,
) {
const underlyingProtocolTokenAdapter =
await adapter.adaptersController.fetchTokenAdapter(
Expand All @@ -45,7 +48,12 @@ async function unwrapToken(

if (!underlyingProtocolTokenAdapter) {
// Try to fetch prices if there is no tokens and no adapter to resolve
const tokenPriceRaw = await fetchPrice(adapter, token, blockNumber)
const tokenPriceRaw = await fetchPrice(
adapter,
token,
blockNumber,
unwrapCache,
)
if (tokenPriceRaw) {
token.priceRaw = tokenPriceRaw
}
Expand All @@ -55,6 +63,7 @@ async function unwrapToken(
underlyingProtocolTokenAdapter,
token,
blockNumber,
unwrapCache,
)

if (unwrapExchangeRates?.tokens) {
Expand Down Expand Up @@ -82,7 +91,13 @@ async function unwrapToken(

await Promise.all(
token.tokens?.map(async (underlyingToken) => {
await unwrapToken(adapter, blockNumber, underlyingToken, fieldToUpdate)
await unwrapToken(
adapter,
blockNumber,
underlyingToken,
fieldToUpdate,
unwrapCache,
)
}) ?? [],
)
}
Expand All @@ -91,9 +106,10 @@ async function fetchUnwrapExchangeRates(
underlyingProtocolTokenAdapter: IProtocolAdapter,
underlyingProtocolTokenPosition: Token,
blockNumber: number | undefined,
unwrapCache: IUnwrapCache,
) {
try {
return await underlyingProtocolTokenAdapter.unwrap({
return await unwrapCache.fetchWithCache(underlyingProtocolTokenAdapter, {
protocolTokenAddress: underlyingProtocolTokenPosition.address,
blockNumber,
})
Expand All @@ -114,6 +130,7 @@ async function fetchPrice(
adapter: IProtocolAdapter,
token: Erc20Metadata & { priceRaw?: bigint },
blockNumber: number | undefined,
unwrapCache: IUnwrapCache,
) {
let priceAdapter: IProtocolAdapter
try {
Expand All @@ -131,7 +148,7 @@ async function fetchPrice(
}

try {
const price = await priceAdapter.unwrap({
const price = await unwrapCache.fetchWithCache(priceAdapter, {
protocolTokenAddress: token.address,
blockNumber,
})
Expand Down
27 changes: 24 additions & 3 deletions packages/adapters-library/src/defiProvider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ import {
} from './types/response'

import { existsSync } from 'node:fs'
import { IUnwrapCache, IUnwrapCacheProvider, UnwrapCache } from './unwrapCache'

function buildMetadataProviders(): Record<Chain, IMetadataProvider> {
return Object.values(Chain).reduce(
Expand Down Expand Up @@ -77,12 +78,15 @@ export class DefiProvider {
private adaptersControllerWithoutPrices: AdaptersController

private metadataProviders: Record<Chain, IMetadataProvider>
private unwrapCache: IUnwrapCache

constructor(
config?: DeepPartial<IConfig>,
metadataProviders?: Record<Chain, IMetadataProvider>,
unwrapCacheProvider?: IUnwrapCacheProvider,
) {
this.metadataProviders = metadataProviders ?? buildMetadataProviders()
this.unwrapCache = new UnwrapCache(unwrapCacheProvider)

this.parsedConfig = new Config(config)
this.chainProvider = new ChainProvider(this.parsedConfig.values)
Expand Down Expand Up @@ -195,7 +199,13 @@ export class DefiProvider {

const getRewardTime = Date.now()

await unwrap(adapter, blockNumber, protocolPositions, 'balanceRaw')
await unwrap(
adapter,
blockNumber,
protocolPositions,
'balanceRaw',
this.unwrapCache,
)

const unwrapTime = Date.now()

Expand Down Expand Up @@ -392,6 +402,7 @@ export class DefiProvider {
protocolTokenAddresses,
tokenIds: filterTokenIds,
includeRawValues,
unwrapCache: this.unwrapCache,
})

const endTime = Date.now()
Expand Down Expand Up @@ -461,7 +472,7 @@ export class DefiProvider {
protocolTokens.map(async (address) => {
const startTime = Date.now()

const unwrap = await adapter.unwrap({
const unwrap = await this.unwrapCache.fetchWithCache(adapter, {
protocolTokenAddress: getAddress(address),
blockNumber,
})
Expand Down Expand Up @@ -571,6 +582,7 @@ export class DefiProvider {
positionMovements.blockNumber,
positionMovements.tokens,
'balanceRaw',
this.unwrapCache,
)
}),
)
Expand Down Expand Up @@ -654,6 +666,7 @@ export class DefiProvider {
positionMovements.blockNumber,
positionMovements.tokens,
'balanceRaw',
this.unwrapCache,
)
}),
)
Expand Down Expand Up @@ -707,6 +720,7 @@ export class DefiProvider {
positionMovements.blockNumber,
positionMovements.tokens,
'balanceRaw',
this.unwrapCache,
)
}),
)
Expand Down Expand Up @@ -760,6 +774,7 @@ export class DefiProvider {
positionMovements.blockNumber,
positionMovements.tokens,
'balanceRaw',
this.unwrapCache,
)
}),
)
Expand Down Expand Up @@ -793,7 +808,13 @@ export class DefiProvider {
blockNumber,
})

await unwrap(adapter, blockNumber, tokens, 'totalSupplyRaw')
await unwrap(
adapter,
blockNumber,
tokens,
'totalSupplyRaw',
this.unwrapCache,
)

return {
tokens: tokens.map((value) =>
Expand Down
1 change: 1 addition & 0 deletions packages/adapters-library/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,3 +17,4 @@ export {
} from './adapters/supportedProtocols'

export { SQLiteMetadataProvider } from './SQLiteMetadataProvider'
export type { IUnwrapCacheProvider } from './unwrapCache'
Loading

0 comments on commit 87bf0ef

Please sign in to comment.