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

fix: optimize updating pools #110

Merged
merged 23 commits into from
Feb 29, 2024
Merged
Changes from 1 commit
Commits
Show all changes
23 commits
Select commit Hold shift + click to select a range
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
53 changes: 29 additions & 24 deletions src/mappings/handlers/ethHandlers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ async function _handleEthBlock(block: EthereumBlock): Promise<void> {
logger.info(`It's a new period on EVM block ${blockNumber}: ${date.toISOString()}`)

// update pool states
for (const tinlakePool of tinlakePools) {
const poolUpdatePromises = tinlakePools.map(async (tinlakePool) => {
let pool
AStox marked this conversation as resolved.
Show resolved Hide resolved
if (block.number >= tinlakePool.startBlock) {
pool = await PoolService.getOrSeed(tinlakePool.id)
AStox marked this conversation as resolved.
Show resolved Hide resolved
Expand Down Expand Up @@ -67,7 +67,9 @@ async function _handleEthBlock(block: EthereumBlock): Promise<void> {
)
}
}
}
})

await Promise.all(poolUpdatePromises)

// Take snapshots
await evmStateSnapshotter('Pool', 'PoolSnapshot', block, 'poolId')
Expand All @@ -80,19 +82,16 @@ async function _handleEthBlock(block: EthereumBlock): Promise<void> {
}

async function updateLoans(poolId: string, blockDate: Date, shelf: string, pile: string, navFeed: string) {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A few remarks on the general architecture:

  1. We usually define all the required helper functions as methods inside the corresponding services... in this case the LoanService.ts would be the most appropriated.

  2. Event and Block Handlers should never set or assign directly the properties of entities (such as pools or loans) such as:

pool.totalReserve = ...

This is reserved to Service Methods only. This guarantees that the logic can be reused and maintained easily whenever the same operation occurs as a result of calls in different blocks or event handlers.

We can address this refactoring in a dedicated ticket. I will prepare a backlog item ;)

Copy link
Collaborator

@filo87 filo87 Feb 9, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Issue -> #111

logger.info(`Updating loans for pool ${poolId}`)
let existingLoans = await LoanService.getByPoolId(poolId)
logger.info(`Existing loans for pool ${poolId}: ${existingLoans.length}`)
let loanIndex = existingLoans.length || 1
const contractLoans = []
// eslint-disable-next-line
while (true) {
logger.info(`Checking loan ${loanIndex} for pool ${poolId}`)
const shelfContract = ShelfAbi__factory.connect(shelf, api as unknown as Provider)
logger.info(`after shelfContract ${shelfContract}`)
let response
try {
response = await shelfContract.token(loanIndex)
logger.info(`after response ${response}`)
} catch (e) {
logger.info(`Error ${e}`)
break
Expand All @@ -105,7 +104,9 @@ async function updateLoans(poolId: string, blockDate: Date, shelf: string, pile:
contractLoans.push(loanIndex)
loanIndex++
}
logger.info(`loans for pool ${poolId}: ${contractLoans.length}`)
const newLoans = contractLoans.filter((loanIndex) => !existingLoans.includes(loanIndex))

// create new loans
for (const loanIndex of newLoans) {
const loan = new Loan(`${poolId}-${loanIndex}`, blockDate, poolId, true, LoanStatus.CREATED)
Expand All @@ -116,30 +117,34 @@ async function updateLoans(poolId: string, blockDate: Date, shelf: string, pile:
loan.actualMaturityDate = new Date(Number(maturityDate) * 1000)
loan.save()
}
logger.info(`New loans for pool ${poolId}: ${newLoans.length}`)

// update all loans
existingLoans = await LoanService.getByPoolId(poolId)
for (const loan of existingLoans) {
const shelfContract = ShelfAbi__factory.connect(shelf, api as unknown as Provider)
const loanIndex = loan.id.split('-')[1]
const nftLocked = await shelfContract.nftLocked(loanIndex)
if (!nftLocked) {
loan.isActive = false
loan.status = LoanStatus.CLOSED
loan.save()
}
const pileContract = PileAbi__factory.connect(pile, api as unknown as Provider)
const prevDebt = loan.outstandingDebt
const debt = await pileContract.debt(loanIndex)
loan.outstandingDebt = debt.toBigInt()
const rateGroup = await pileContract.loanRates(loanIndex)
const rates = await pileContract.rates(rateGroup)
loan.interestRatePerSec = rates.ratePerSecond.toBigInt()
if (loan.status !== LoanStatus.CLOSED) {
const shelfContract = ShelfAbi__factory.connect(shelf, api as unknown as Provider)
const loanIndex = loan.id.split('-')[1]
const nftLocked = await shelfContract.nftLocked(loanIndex)
if (!nftLocked) {
loan.isActive = false
loan.status = LoanStatus.CLOSED
loan.save()
}
const pileContract = PileAbi__factory.connect(pile, api as unknown as Provider)
const prevDebt = loan.outstandingDebt
const debt = await pileContract.debt(loanIndex)
loan.outstandingDebt = debt.toBigInt()
const rateGroup = await pileContract.loanRates(loanIndex)
const rates = await pileContract.rates(rateGroup)
loan.interestRatePerSec = rates.ratePerSecond.toBigInt()

if (prevDebt > loan.outstandingDebt) {
loan.repaidAmountByPeriod = prevDebt - loan.outstandingDebt
if (prevDebt > loan.outstandingDebt) {
loan.repaidAmountByPeriod = prevDebt - loan.outstandingDebt
}
logger.info(`Updating loan ${loan.id} for pool ${poolId}`)
loan.save()
}
loan.save()
}
}

Expand Down
Loading