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

Eliminate several fields which change every block #22

Merged
merged 3 commits into from
Jun 19, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
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
4 changes: 2 additions & 2 deletions ganache-indexer.yml
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ services:
image: ghcr.io/ajna-finance/ajna-testnet:rc5
ports:
- 8555:8555
container_name: ajna-testnet
container_name: ajna-testnet-subgraph
networks:
- ajna_test_network
graph-node:
Expand Down Expand Up @@ -55,4 +55,4 @@ services:
- ./data/postgres:/var/lib/postgresql/data
networks:
ajna_test_network:
name: ajna_test_network
name: ajna_test_network
26 changes: 7 additions & 19 deletions schema.graphql
Original file line number Diff line number Diff line change
Expand Up @@ -48,8 +48,6 @@ type Pool @entity {
feeRate: BigDecimal!
# amount of deposit in the pool
poolSize: BigDecimal!
# total debt in the pool
debt: BigDecimal!
# debt in T0 terms, useful when the caller knows the pending inflator
t0debt: BigDecimal!
# pool inflator snapshot
Expand Down Expand Up @@ -88,10 +86,6 @@ type Pool @entity {
claimableReserves: BigDecimal!
# remaining claimable reserves not yet taken
claimableReservesRemaining: BigDecimal!
# current reserve auction auctionPrice
reserveAuctionPrice: BigDecimal!
# current reserve auction timeRemaining
reserveAuctionTimeRemaining: BigInt!
# current burn epoch
burnEpoch: BigInt!
# total ajna burned in the pool
Expand All @@ -102,8 +96,6 @@ type Pool @entity {
# UTILIZATION INFORMATION
# current pool minimum debt amount for a new borrow
minDebtAmount: BigDecimal!
# current pool collateralization ratio across all borrowers
collateralization: BigDecimal!
# current pool utilization across all borrowers
actualUtilization: BigDecimal!
# current pool target utilization rate
Expand Down Expand Up @@ -173,12 +165,8 @@ type Loan @entity {
liquidationAuction: LiquidationAuction
# collateral tokens deposited in a pool by the borrower
collateralPledged: BigDecimal!
# collateralization of the borrow position in the pool
collateralization: BigDecimal!
# total quote drawn from the pool in the loan
debt: BigDecimal!
# borrowers threshold price
tp: BigDecimal!
# debt in T0 terms, useful when the caller knows the pending inflator
t0debt: BigDecimal!
}

type Account @entity {
Expand Down Expand Up @@ -207,7 +195,7 @@ type LiquidationAuction @entity {
id: Bytes! # $poolAddress + '|' + $loanId + '|' + blockNumber
pool: Pool! # pool in which the liquidation occurred
borrower: Bytes! # address of the borrower being liquidated
auctionPrice: BigDecimal! # price of auction upon kick or last take
lastTakePrice: BigDecimal! # price of auction upon most recent take
collateral: BigDecimal! # initial collateral up for auction
collateralRemaining: BigDecimal! # collateral which has not been taken
debt: BigDecimal! # initial debt to be covered by the auction
Expand All @@ -230,11 +218,11 @@ type LiquidationAuction @entity {
# tracks the reserve auction process across multiple takes in a single auction
# used as start and take events are emitted as ReserveAuction
type ReserveAuction @entity {
id: Bytes! # $poolAddress + '|' + $burnEpoch
pool: Pool! # Pool in which the reserve auction occurred
id: Bytes! # $poolAddress + '|' + $burnEpoch
pool: Pool! # Pool in which the reserve auction occurred
claimableReservesRemaining: BigDecimal! # uint256 claimable reserves remaining at start or at latest take
auctionPrice: BigDecimal! # uint256 price at start or at latest take
burnEpoch: BigInt! # uint256 burn epoch at which the reserve auction was started
lastTakePrice: BigDecimal! # uint256 price of auction upon most recent take, denominated in AJNA
burnEpoch: BigInt! # uint256 burn epoch at which the reserve auction was started
kick: ReserveAuctionKick! # kick information
takes: [ReserveAuctionTake!]! # list of reserve auction takes that occured during this auction process
ajnaBurned: BigDecimal! # total amount of ajna burned across all takes in the reserve auction
Expand Down
4 changes: 0 additions & 4 deletions src/erc-20-pool-factory.ts
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,6 @@ export function handlePoolCreated(event: PoolCreatedEvent): void {
pool.createdAtBlockNumber = event.block.number
pool.collateralToken = collateralToken.id
pool.quoteToken = quoteToken.id
pool.debt = ZERO_BD
pool.t0debt = ZERO_BD
pool.feeRate = wadToDecimal(interestRateResults.value1)
pool.inflator = ONE_BD
Expand Down Expand Up @@ -123,15 +122,12 @@ export function handlePoolCreated(event: PoolCreatedEvent): void {
pool.reserves = ZERO_BD
pool.claimableReserves = ZERO_BD
pool.claimableReservesRemaining = ZERO_BD
pool.reserveAuctionPrice = ZERO_BD
pool.reserveAuctionTimeRemaining = ZERO_BI
pool.burnEpoch = ZERO_BI
pool.totalAjnaBurned = ZERO_BD
pool.reserveAuctions = []

// utilization information
pool.minDebtAmount = ZERO_BD
pool.collateralization = ONE_BD
pool.actualUtilization = ZERO_BD
pool.targetUtilization = ONE_BD

Expand Down
69 changes: 21 additions & 48 deletions src/erc-20-pool.ts
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ import {
} from "../generated/schema"

import { ZERO_BD, ONE_BI, TEN_BI, positionManagerAddressTable } from "./utils/constants"
import { addressToBytes, bigIntArrayToIntArray, wadToDecimal } from "./utils/convert"
import { addressToBytes, bigIntArrayToIntArray, decimalToWad, wadToDecimal } from "./utils/convert"
import { loadOrCreateAccount, updateAccountLends, updateAccountLoans, updateAccountPools, updateAccountKicks, updateAccountTakes, updateAccountSettles, updateAccountReserveAuctions } from "./utils/account"
import { getBucketId, getBucketInfo, loadOrCreateBucket } from "./utils/bucket"
import { getLendId, loadOrCreateLend } from "./utils/lend"
Expand Down Expand Up @@ -248,11 +248,9 @@ export function handleAuctionSettle(event: AuctionSettleEvent): void {
auction.save()

// update loan state
loan.debt = ZERO_BD
loan.t0debt = ZERO_BD
loan.collateralPledged = auctionSettle.collateral
loan.inLiquidation = false
loan.collateralization = ZERO_BD
loan.tp = ZERO_BD
loan.save()

// update auctionSettle pointers
Expand Down Expand Up @@ -347,16 +345,9 @@ export function handleBucketTake(event: BucketTakeEvent): void {
// update loan state
const loanId = getLoanId(pool.id, addressToBytes(event.params.borrower))
const loan = loadOrCreateLoan(loanId, pool.id, addressToBytes(event.params.borrower))
loan.debt = loan.debt.minus(wadToDecimal(event.params.amount))
loan.collateralPledged = loan.collateralPledged.minus(wadToDecimal(event.params.collateral))
if (loan.debt.notEqual(ZERO_BD) && loan.collateralPledged.notEqual(ZERO_BD)) {
loan.collateralization = collateralizationAtLup(loan.debt, loan.collateralPledged, pool.lup)
loan.tp = thresholdPrice(loan.debt, loan.collateralPledged)
} else {
// set collateralization and tp to zero if loan is fully repaid
loan.collateralization = ZERO_BD
loan.tp = ZERO_BD
}
const borrowerInfo = getBorrowerInfo(addressToBytes(event.params.borrower), pool.id)
loan.collateralPledged = wadToDecimal(borrowerInfo.collateral)
loan.t0debt = wadToDecimal(borrowerInfo.t0debt)

// retrieve auction information on the take's auction
const auctionInfo = getAuctionInfoERC20Pool(bucketTake.borrower, pool)
Expand All @@ -366,8 +357,6 @@ export function handleBucketTake(event: BucketTakeEvent): void {
const auctionId = loan.liquidationAuction!
const auction = LiquidationAuction.load(auctionId)!
updateLiquidationAuction(auction, auctionInfo, auctionStatus)
auction.debtRemaining = auction.debtRemaining.minus(wadToDecimal(event.params.amount))
auction.collateralRemaining = auction.collateralRemaining.minus(wadToDecimal(event.params.collateral))
auction.bucketTakes = auction.bucketTakes.concat([bucketTake.id])

bucketTake.auctionPrice = wadToDecimal(auctionStatus.price)
Expand Down Expand Up @@ -492,7 +481,6 @@ export function handleDrawDebt(event: DrawDebtEvent): void {
const pool = Pool.load(addressToBytes(event.address))
if (pool != null) {
// update pool state
pool.debt = pool.debt.plus(wadToDecimal(event.params.amountBorrowed))
pool.pledgedCollateral = pool.pledgedCollateral.plus(wadToDecimal(event.params.collateralPledged))
updatePool(pool)
pool.txCount = pool.txCount.plus(ONE_BI)
Expand All @@ -508,10 +496,9 @@ export function handleDrawDebt(event: DrawDebtEvent): void {
// update loan state
const loanId = getLoanId(pool.id, accountId)
const loan = loadOrCreateLoan(loanId, pool.id, drawDebt.borrower)
loan.collateralPledged = loan.collateralPledged.plus(wadToDecimal(event.params.collateralPledged))
loan.debt = loan.debt.plus(wadToDecimal(event.params.amountBorrowed))
loan.collateralization = collateralizationAtLup(loan.debt, loan.collateralPledged, pool.lup)
loan.tp = thresholdPrice(loan.debt, loan.collateralPledged)
const borrowerInfo = getBorrowerInfo(addressToBytes(event.params.borrower), pool.id)
loan.collateralPledged = wadToDecimal(borrowerInfo.collateral)
loan.t0debt = wadToDecimal(borrowerInfo.t0debt)

// update account's list of pools and loans if necessary
updateAccountPools(account, pool)
Expand Down Expand Up @@ -604,9 +591,7 @@ export function handleKick(event: KickEvent): void {
const loan = loadOrCreateLoan(loanId, pool.id, kick.borrower)
loan.inLiquidation = true
loan.collateralPledged = kick.collateral
loan.debt = kick.debt // update loan debt to account for kick penalty
loan.collateralization = collateralizationAtLup(loan.debt, loan.collateralPledged, pool.lup)
loan.tp = thresholdPrice(loan.debt, loan.collateralPledged)
loan.t0debt = kick.debt.div(pool.inflator) // update loan debt to account for kick penalty

// retrieve auction information on the kicked loan
const auctionInfo = getAuctionInfoERC20Pool(kick.borrower, pool)
Expand All @@ -615,7 +600,7 @@ export function handleKick(event: KickEvent): void {
// update liquidation auction state
const auctionId = getLiquidationAuctionId(pool.id, loan.id, kick.blockNumber)
const auction = loadOrCreateLiquidationAuction(pool.id, auctionId, kick, loan)
updateLiquidationAuction(auction, auctionInfo, auctionStatus)
updateLiquidationAuction(auction, auctionInfo, auctionStatus, false)

kick.kickMomp = wadToDecimal(auctionInfo.kickMomp)
kick.startingPrice = wadToDecimal(auctionStatus.price)
Expand Down Expand Up @@ -901,9 +886,7 @@ export function handleRepayDebt(event: RepayDebtEvent): void {
const loan = loadOrCreateLoan(loanId, pool.id, repayDebt.borrower)
const borrowerInfo = getBorrowerInfo(accountId, pool.id)
loan.collateralPledged = wadToDecimal(borrowerInfo.collateral)
loan.debt = wadToDecimal(borrowerInfo.debt)
loan.collateralization = collateralizationAtLup(loan.debt, loan.collateralPledged, pool.lup)
loan.tp = thresholdPrice(loan.debt, loan.collateralPledged)
loan.t0debt = wadToDecimal(borrowerInfo.t0debt)

// update account loans if necessary
updateAccountLoans(account, loan)
Expand Down Expand Up @@ -940,7 +923,6 @@ export function handleReserveAuctionKick(event: KickReserveAuctionEvent): void {
reserveKick.transactionHash = event.transaction.hash

reserveAuction.claimableReservesRemaining = reserveKick.claimableReserves
reserveAuction.auctionPrice = reserveKick.startingPrice
reserveAuction.kick = reserveKick.id

// update pool state
Expand Down Expand Up @@ -981,7 +963,7 @@ export function handleReserveAuctionTake(event: ReserveAuctionEvent): void {
// since only one reserve auction can occur at a time, look at the difference since the last reserve auction
reserveTake.ajnaBurned = wadToDecimal(burnInfo.totalBurned).minus(pool.totalAjnaBurned)
reserveAuction.claimableReservesRemaining = reserveTake.claimableReservesRemaining
reserveAuction.auctionPrice = reserveTake.auctionPrice
reserveAuction.lastTakePrice = reserveTake.auctionPrice
reserveAuction.ajnaBurned = reserveAuction.ajnaBurned.plus(reserveTake.ajnaBurned)
reserveAuction.takes = reserveAuction.takes.concat([reserveTake.id])

Expand Down Expand Up @@ -1100,17 +1082,10 @@ export function handleTake(event: TakeEvent): void {

// update loan state
const loanId = getLoanId(pool.id, addressToBytes(event.params.borrower))
const loan = Loan.load(loanId)!
loan.debt = loan.debt.minus(wadToDecimal(event.params.amount))
loan.collateralPledged = loan.collateralPledged.minus(wadToDecimal(event.params.collateral))
if (loan.debt.notEqual(ZERO_BD) && loan.collateralPledged.notEqual(ZERO_BD)) {
loan.collateralization = collateralizationAtLup(loan.debt, loan.collateralPledged, pool.lup)
loan.tp = thresholdPrice(loan.debt, loan.collateralPledged)
} else {
// set collateralization and tp to zero if loan is fully repaid
loan.collateralization = ZERO_BD
loan.tp = ZERO_BD
}
const loan = Loan.load(loanId)!
const borrowerInfo = getBorrowerInfo(addressToBytes(event.params.borrower), pool.id)
loan.collateralPledged = wadToDecimal(borrowerInfo.collateral)
loan.t0debt = wadToDecimal(borrowerInfo.t0debt)

// update liquidation auction state
const auctionId = loan.liquidationAuction!
Expand All @@ -1120,12 +1095,10 @@ export function handleTake(event: TakeEvent): void {
const auctionStatus = getAuctionStatus(pool, event.params.borrower)
updateLiquidationAuction(auction, auctionInfo, auctionStatus)

const debtCovered = wadToDecimal(event.params.amount)
auction.debtRemaining = auction.debtRemaining.minus(debtCovered)
const collateralPurchased = wadToDecimal(event.params.collateral)
auction.collateralRemaining = auction.collateralRemaining.minus(collateralPurchased)
pool.pledgedCollateral = pool.pledgedCollateral.minus(collateralPurchased)
take.auctionPrice = wadToDecimal(auctionStatus.price)
const debtCovered = wadToDecimal(event.params.amount)
const collateralPurchased = wadToDecimal(event.params.collateral)
pool.pledgedCollateral = pool.pledgedCollateral.minus(collateralPurchased)
take.auctionPrice = wadToDecimal(auctionStatus.price)

// update kick and pool for the change in bond as a result of the take
const kick = Kick.load(auction.kick)!
Expand Down Expand Up @@ -1183,7 +1156,7 @@ export function handleSettle(event: SettleEvent): void {
const auction = LiquidationAuction.load(auctionId)!
const auctionInfo = getAuctionInfoERC20Pool(settle.borrower, pool)
const auctionStatus = getAuctionStatus(pool, event.params.borrower)
updateLiquidationAuction(auction, auctionInfo, auctionStatus, true)
updateLiquidationAuction(auction, auctionInfo, auctionStatus, false, true)
auction.settles = auction.settles.concat([settle.id])

// update settle pointers
Expand Down
4 changes: 2 additions & 2 deletions src/utils/account.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,9 +52,9 @@ export function updateAccountLoans(account: Account, loan: Loan): void {
const loans = account.loans
// get current index of loan in account's list of loans
const index = loans.indexOf(loan.id)
if (loan.debt != ZERO_BD && index == -1) {
if (loan.t0debt != ZERO_BD && index == -1) {
loans.push(loan.id)
} else if (loan.collateralPledged == ZERO_BD && loan.debt == ZERO_BD && index != -1) {
} else if (loan.collateralPledged == ZERO_BD && loan.t0debt == ZERO_BD && index != -1) {
loans.splice(index, 1)
}
account.loans = loans
Expand Down
5 changes: 3 additions & 2 deletions src/utils/liquidation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ export function loadOrCreateLiquidationAuction(poolId: Bytes, liquidationAuction
liquidationAuction.kick = kick.id

// write accumulators
liquidationAuction.auctionPrice = ZERO_BD // FIXME: not exposed by contracts
liquidationAuction.lastTakePrice = ZERO_BD // FIXME: not exposed by contracts
liquidationAuction.collateral = kick.collateral
liquidationAuction.collateralRemaining = kick.collateral
liquidationAuction.debt = kick.debt
Expand All @@ -50,9 +50,10 @@ export function updateLiquidationAuction(
liquidationAuction: LiquidationAuction,
auctionInfo: AuctionInfo,
auctionStatus: AuctionStatus,
isTake: bool = true,
isSettle: bool = false): void {
if (!isSettle) {
liquidationAuction.auctionPrice = wadToDecimal(auctionStatus.price)
if (isTake) liquidationAuction.lastTakePrice = wadToDecimal(auctionStatus.price)
liquidationAuction.bondFactor = wadToDecimal(auctionInfo.bondFactor)
liquidationAuction.bondSize = wadToDecimal(auctionInfo.bondSize)
liquidationAuction.kickTime = auctionInfo.kickTime
Expand Down
16 changes: 7 additions & 9 deletions src/utils/loan.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { PoolInfoUtils } from "../../generated/templates/ERC20Pool/PoolInfoUtils

import { Loan } from "../../generated/schema"
import { poolInfoUtilsAddressTable, ZERO_BD, ZERO_BI } from "./constants"
import { ERC20Pool } from '../../generated/templates/ERC20Pool/ERC20Pool'

export function getLoanId(poolId: Bytes, accountId: Bytes): Bytes {
return poolId.concat(Bytes.fromUTF8('|').concat(accountId))
Expand All @@ -18,9 +19,7 @@ export function loadOrCreateLoan(loanId: Bytes, poolId: Bytes, borrower: Bytes):
loan.pool = poolId
loan.poolAddress = poolId.toHexString()
loan.collateralPledged = ZERO_BD
loan.collateralization = ZERO_BD
loan.debt = ZERO_BD
loan.tp = ZERO_BD
loan.t0debt = ZERO_BD
loan.inLiquidation = false
loan.liquidationAuction = null
}
Expand All @@ -29,19 +28,18 @@ export function loadOrCreateLoan(loanId: Bytes, poolId: Bytes, borrower: Bytes):
}

export class BorrowerInfo {
debt: BigInt
t0debt: BigInt
collateral: BigInt
t0Np: BigInt
constructor(debt: BigInt, collateral: BigInt, t0Np: BigInt) {
this.debt = debt
constructor(t0debt: BigInt, collateral: BigInt, t0Np: BigInt) {
this.t0debt = t0debt
this.collateral = collateral
this.t0Np = t0Np
}
}
export function getBorrowerInfo(borrower: Bytes, poolId: Bytes): BorrowerInfo {
const poolInfoUtilsAddress = poolInfoUtilsAddressTable.get(dataSource.network())!
const poolInfoUtilsContract = PoolInfoUtils.bind(poolInfoUtilsAddress)
const borrowerInfoResult = poolInfoUtilsContract.borrowerInfo(Address.fromBytes(poolId), Address.fromBytes(borrower))
const poolContract = ERC20Pool.bind(Address.fromBytes(poolId))
const borrowerInfoResult = poolContract.borrowerInfo(Address.fromBytes(borrower))

return new BorrowerInfo(
borrowerInfoResult.value0,
Expand Down
4 changes: 0 additions & 4 deletions src/utils/pool.ts
Original file line number Diff line number Diff line change
Expand Up @@ -174,7 +174,6 @@ export function updatePool(pool: Pool): void {

// update amount of debt in pool
const debtInfo = getDebtInfo(pool)
pool.debt = wadToDecimal(debtInfo.pendingDebt)
pool.t0debt = wadToDecimal(wdiv(debtInfo.pendingDebt, poolLoansInfo.pendingInflator))

// update pool prices information
Expand All @@ -192,13 +191,10 @@ export function updatePool(pool: Pool): void {
pool.reserves = wadToDecimal(poolReservesInfo.reserves)
pool.claimableReserves = wadToDecimal(poolReservesInfo.claimableReserves)
pool.claimableReservesRemaining = wadToDecimal(poolReservesInfo.claimableReservesRemaining)
pool.reserveAuctionPrice = wadToDecimal(poolReservesInfo.reserveAuctionPrice)
pool.reserveAuctionTimeRemaining = poolReservesInfo.reserveAuctionTimeRemaining

// update pool utilization information
const poolUtilizationInfo = getPoolUtilizationInfo(pool)
pool.minDebtAmount = wadToDecimal(poolUtilizationInfo.minDebtAmount)
pool.collateralization = wadToDecimal(poolUtilizationInfo.collateralization)
pool.actualUtilization = wadToDecimal(poolUtilizationInfo.actualUtilization)
pool.targetUtilization = wadToDecimal(poolUtilizationInfo.targetUtilization)

Expand Down
2 changes: 1 addition & 1 deletion src/utils/reserve-auction.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ export function loadOrCreateReserveAuction(poolId: Bytes, burnEpoch: BigInt): Re
// set initial values
reserveAuction.pool = poolId
reserveAuction.claimableReservesRemaining = ZERO_BD
reserveAuction.auctionPrice = ZERO_BD
reserveAuction.lastTakePrice = ZERO_BD
reserveAuction.burnEpoch = burnEpoch
reserveAuction.ajnaBurned = ZERO_BD
reserveAuction.takes = []
Expand Down
Loading