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

Tinlake additions #260

Merged
merged 11 commits into from
Nov 5, 2024
28 changes: 28 additions & 0 deletions chains-cfg/_root.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -51,21 +51,49 @@ dataSources:
- handler: handleInvestOrderUpdated
kind: substrate/EventHandler
filter:
specVersion: [1400]
module: investments
method: InvestOrderUpdated
- handler: handleInvestOrderUpdatedBefore1400
kind: substrate/EventHandler
filter:
specVersion: [null,1399]
module: investments
method: InvestOrderUpdated
- handler: handleRedeemOrderUpdated
kind: substrate/EventHandler
filter:
specVersion: [1400]
module: investments
method: RedeemOrderUpdated
- handler: handleRedeemOrderUpdatedBefore1400
kind: substrate/EventHandler
filter:
specVersion: [null,1399]
module: investments
method: RedeemOrderUpdated
- handler: handleInvestOrdersCollected
kind: substrate/EventHandler
filter:
specVersion: [1400]
module: investments
method: InvestOrdersCollected
- handler: handleInvestOrdersCollectedBefore1400
kind: substrate/EventHandler
filter:
specVersion: [null,1399]
module: investments
method: InvestOrdersCollected
- handler: handleRedeemOrdersCollected
kind: substrate/EventHandler
filter:
specVersion: [1400]
module: investments
method: RedeemOrdersCollected
- handler: handleRedeemOrdersCollectedBefore1400
kind: substrate/EventHandler
filter:
specVersion: [null,1399]
module: investments
method: RedeemOrdersCollected
# - handler: handleProxyAdded
Expand Down
13 changes: 13 additions & 0 deletions schema.graphql
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,8 @@ type Pool @entity {

availableReserve: BigInt
maxReserve: BigInt

weightedAverageInterestRatePerSec: BigInt

# Aggregated transaction data over the last period
sumBorrowedAmountByPeriod: BigInt
Expand Down Expand Up @@ -96,6 +98,9 @@ type Pool @entity {
sumUnscheduledRepaidAmount: BigInt
sumNumberOfAssets: BigInt

sumBorrowsCount: BigInt
sumRepaysCount: BigInt

tranches: [Tranche] @derivedFrom(field: "pool")
assets: [Asset] @derivedFrom(field: "pool")
}
Expand All @@ -121,6 +126,8 @@ type PoolSnapshot @entity {
availableReserve: BigInt
maxReserve: BigInt

weightedAverageInterestRatePerSec: BigInt

# Aggregated transaction data over the last period
sumBorrowedAmountByPeriod: BigInt
sumRepaidAmountByPeriod: BigInt
Expand Down Expand Up @@ -160,6 +167,9 @@ type PoolSnapshot @entity {
sumInterestRepaidAmount: BigInt
sumUnscheduledRepaidAmount: BigInt
sumNumberOfAssets: BigInt

sumBorrowsCount: BigInt
sumRepaysCount: BigInt
}

type Tranche @entity {
Expand Down Expand Up @@ -489,6 +499,9 @@ type Asset @entity {
totalRepaidInterest: BigInt
totalRepaidUnscheduled: BigInt

borrowsCount: BigInt
repaysCount: BigInt

borrowedAmountByPeriod: BigInt
repaidAmountByPeriod: BigInt

Expand Down
44 changes: 22 additions & 22 deletions src/helpers/types.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
//find out types: const a = createType(api.registry, '[u8;32]', 18)
import { AugmentedCall, AugmentedRpc, PromiseRpcResult } from '@polkadot/api/types'
import { Codec } from '@polkadot/types-codec/types'
import { Enum, Null, Struct, u128, u32, u64, U8aFixed, Option, Vec, Bytes, Result, bool } from '@polkadot/types'
import { AccountId32, Perquintill, Balance } from '@polkadot/types/interfaces'
import { ITuple, Observable } from '@polkadot/types/types'
Expand Down Expand Up @@ -39,16 +40,11 @@ export interface TrancheData extends Struct {
}

export interface TrancheEssence extends Struct {
currency: TrancheCurrency
currency: TrancheCurrency | TrancheCurrencyBefore1400
ty: TrancheTypeEnum
metadata: TrancheMetadata
}

export interface TrancheCurrency extends Struct {
poolId: u64
trancheId: U8aFixed
}

export interface TrancheMetadata extends Struct {
tokenName: Bytes
tokenSymbol: Bytes
Expand All @@ -57,7 +53,7 @@ export interface TrancheMetadata extends Struct {
export interface TrancheDetails extends Struct {
trancheType: TrancheTypeEnum
seniority: u32
currency: TrancheCurrency
currency: TrancheCurrency | TrancheCurrencyBefore1400
debt: u128
reserve: u128
loss: u128
Expand All @@ -71,6 +67,7 @@ export interface TrancheTypeEnum extends Enum {
isNonResidual: boolean
asNonResidual: { interestRatePerSec: u128; minRiskBuffer: Perquintill }
asResidual: Null
readonly type: 'Residual' | 'NonResidual';
}

export interface NavDetails extends Struct {
Expand All @@ -89,7 +86,7 @@ export interface EpochExecutionInfo extends Struct {
}

export interface EpochExecutionTranche extends Struct {
currency: TrancheCurrency
currency: TrancheCurrency | TrancheCurrencyBefore1400
supply: u128
price: u128
invest: u128
Expand All @@ -114,7 +111,7 @@ export interface TokensCurrencyId extends Enum {
isNative: boolean
asNative: null
isTranche: boolean
asTranche: ITuple<[poolId: u64, trancheId: U8aFixed]> //poolId, trancheId
asTranche: TrancheCurrency | TrancheCurrencyBefore1400
isAUSD: boolean
asAUSD: null
isForeignAsset: boolean
Expand Down Expand Up @@ -457,22 +454,19 @@ export type PoolMetadataSetEvent = ITuple<[poolId: u64, metadata: Bytes]>
export type EpochClosedExecutedEvent = ITuple<[poolId: u64, epochId: u32]>
export type EpochSolutionEvent = ITuple<[poolId: u64, epochId: u32, solution: EpochSolution]>

export type InvestOrdersCollectedEvent = ITuple<
[
investmentId: TrancheCurrency,
who: AccountId32,
processedOrders: Vec<u64>,
collection: InvestCollection,
outcome: Enum,
]
export type InvestOrdersCollectedEvent<T extends Codec = TrancheCurrency> = ITuple<
[investmentId: T, who: AccountId32, processedOrders: Vec<u64>, collection: InvestCollection, outcome: Enum]
>

export type RedeemOrdersCollectedEvent<T extends Codec = TrancheCurrency> = ITuple<
[investmentId: T, who: AccountId32, collections: Vec<u64>, collection: RedeemCollection, outcome: Enum]
>
export type RedeemOrdersCollectedEvent = ITuple<
[investmentId: TrancheCurrency, who: AccountId32, collections: Vec<u64>, collection: RedeemCollection, outcome: Enum]
export type OrderUpdatedEvent<T extends Codec = TrancheCurrency> = ITuple<
[investmentId: T, submittedAt: u64, who: AccountId32, amount: u128]
>
export type OrderUpdatedEvent = ITuple<
[investmentId: TrancheCurrency, submittedAt: u64, who: AccountId32, amount: u128]
export type OrdersClearedEvent<T extends Codec = TrancheCurrency> = ITuple<
[investmentId: T, orderId: u64, fulfillment: OrdersFulfillment]
>
export type OrdersClearedEvent = ITuple<[investmentId: TrancheCurrency, orderId: u64, fulfillment: OrdersFulfillment]>
export type TokensTransferEvent = ITuple<
[currencyId: TokensCurrencyId, from: AccountId32, to: AccountId32, amount: u128]
>
Expand Down Expand Up @@ -520,3 +514,9 @@ export type ExtendedCall = typeof api.call & {
}

export type ApiQueryLoansActiveLoans = Vec<ITuple<[u64, LoanInfoActive]>>

export type TrancheCurrency = ITuple<[poolId: u64, trancheId: U8aFixed]>
export interface TrancheCurrencyBefore1400 extends Struct {
poolId: u64
trancheId: U8aFixed
}
4 changes: 2 additions & 2 deletions src/mappings/handlers/blockHandlers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -64,10 +64,10 @@ async function _handleBlock(block: SubstrateBlock): Promise<void> {
const trancheTokenPrices = await pool.getTrancheTokenPrices()
for (const tranche of tranches) {
const index = tranche.index
if (trancheTokenPrices !== undefined)
if (trancheTokenPrices)
await tranche.updatePrice(trancheTokenPrices[index].toBigInt(), block.block.header.number.toNumber())
await tranche.updateSupply()
await tranche.updateDebt(trancheData[tranche.trancheId].data.debt.toBigInt())
await tranche.updateDebt(trancheData[tranche.trancheId].debt)
await tranche.computeYield('yieldSinceLastPeriod', lastPeriodStart)
await tranche.computeYield('yieldSinceInception')
await tranche.computeYield('yieldYTD', beginningOfYear)
Expand Down
36 changes: 30 additions & 6 deletions src/mappings/handlers/ethHandlers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -187,6 +187,7 @@ async function updateLoans(
const newLoans = await getNewLoans(existingLoanIds as number[], shelf)
logger.info(`Found ${newLoans.length} new loans for pool ${poolId}`)

const pool = await PoolService.getById(poolId)
const isAlt1AndAfterEndBlock = poolId === ALT_1_POOL_ID && blockNumber > ALT_1_END_BLOCK

const nftIdCalls: PoolMulticall[] = []
Expand Down Expand Up @@ -340,6 +341,12 @@ async function updateLoans(
}
}

let sumDebt = BigInt(0)
let sumBorrowed = BigInt(0)
let sumRepaid = BigInt(0)
let sumInterestRatePerSec = BigInt(0)
let sumBorrowsCount = BigInt(0)
let sumRepaysCount = BigInt(0)
for (let i = 0; i < existingLoans.length; i++) {
const loan = existingLoans[i]
const loanIndex = loan.id.split('-')[1]
Expand All @@ -364,22 +371,39 @@ async function updateLoans(

if (prevDebt > currentDebt) {
loan.repaidAmountByPeriod = prevDebt - currentDebt
loan.totalRepaid
? (loan.totalRepaid += loan.repaidAmountByPeriod)
: (loan.totalRepaid = loan.repaidAmountByPeriod)
loan.totalRepaid = (loan.totalRepaid || BigInt(0)) + loan.repaidAmountByPeriod
loan.repaysCount = (loan.repaysCount || BigInt(0)) + BigInt(1)
}
if (
prevDebt * (loan.interestRatePerSec / BigInt(10) ** BigInt(27)) * BigInt(86400) <
(loan.outstandingDebt || BigInt(0))
) {
loan.borrowedAmountByPeriod = (loan.outstandingDebt || BigInt(0)) - prevDebt
loan.totalBorrowed
? (loan.totalBorrowed += loan.borrowedAmountByPeriod)
: (loan.totalBorrowed = loan.borrowedAmountByPeriod)
loan.totalBorrowed = (loan.totalBorrowed || BigInt(0)) + loan.borrowedAmountByPeriod
loan.borrowsCount = (loan.borrowsCount || BigInt(0)) + BigInt(1)
}
logger.info(`Updating loan ${loan.id} for pool ${poolId}`)
await loan.save()

sumDebt += loan.outstandingDebt || BigInt(0)
sumBorrowed += loan.totalBorrowed || BigInt(0)
sumRepaid += loan.totalRepaid || BigInt(0)
sumInterestRatePerSec += (loan.interestRatePerSec || BigInt(0)) * (loan.outstandingDebt || BigInt(0))
sumBorrowsCount += loan.borrowsCount || BigInt(0)
sumRepaysCount += loan.repaysCount || BigInt(0)
}

pool.sumDebt = sumDebt
pool.sumBorrowedAmount = sumBorrowed
pool.sumRepaidAmount = sumRepaid
if (sumDebt > BigInt(0)) {
pool.weightedAverageInterestRatePerSec = sumInterestRatePerSec / sumDebt
} else {
pool.weightedAverageInterestRatePerSec = BigInt(0)
}
pool.sumBorrowsCount = sumBorrowsCount
pool.sumRepaysCount = sumRepaysCount
await pool.save()
}
}

Expand Down
Loading
Loading