Skip to content

Commit

Permalink
Update subgraph pool data (#148)
Browse files Browse the repository at this point in the history
* Update subgraph pool data

* Run prettier

* Add ptRate and IBTRate in APRInTime

* Change APR to APY in naming

* Change precision

* Make baseAPY a BigDecimal
  • Loading branch information
jeanchambras authored May 21, 2024
1 parent 303828c commit 74a4a72
Show file tree
Hide file tree
Showing 16 changed files with 296 additions and 276 deletions.
5 changes: 3 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,15 +12,16 @@
"authorize": "graph auth https://api.thegraph.com/deploy/",
"build": "graph build",
"deploy": "graph deploy perspectivefi/spectra-mainnet --ipfs https://api.thegraph.com/ipfs/ --node https://api.thegraph.com/deploy/",
"deploy:local": "graph deploy perspectivefi/spectra-mainnet --debug --ipfs http://localhost:5001 --node http://127.0.0.1:8020",
"deploy:local": "graph deploy perspectivefi/spectra-mainnet --ipfs http://localhost:5001 --node http://127.0.0.1:8020",
"deploy:goerli": "graph deploy perspectivefi/spectra-goerli subgraph.goerli.yaml --ipfs https://api.thegraph.com/ipfs/ --node https://api.thegraph.com/deploy/",
"deploy:sepolia": "graph deploy --studio spectra-subgraph-sepolia subgraph.sepolia.yaml",
"deploy:test": "graph deploy matstyler/spectra-subgraph subgraph.goerli.yaml --ipfs https://api.thegraph.com/ipfs/ --node https://api.thegraph.com/deploy/",
"generate-config:local": "node ./src/scripts/subgraphConfigGenerator.js local",
"generate-config": "node ./src/scripts/subgraphConfigGenerator.js",
"generate-config:goerli": "node ./src/scripts/subgraphConfigGenerator.js goerli",
"generate-config:sepolia": "node ./src/scripts/subgraphConfigGenerator.js sepolia",
"test": "graph test"
"test": "graph test",
"prettify": "prettier --write \"./**/*.{js,jsx,json,ts,tsx,css}\""
},
"devDependencies": {
"@chainlink/contracts": "^0.4.1",
Expand Down
19 changes: 9 additions & 10 deletions schema.graphql
Original file line number Diff line number Diff line change
Expand Up @@ -268,7 +268,9 @@ type FutureDailyStats @entity {
dailyAddLiquidity: BigInt! # total add liquidity in the day in the AMM (the unit is a count of transactions)
dailyRemoveLiquidity: BigInt! # total remove liquidity in the day in the AMM (the unit is a count of transactions)
dailyUpdates: BigInt! # total updates of the FutureDailyStats. This is used to compute the IBT rate as an incremental average (the unit is a count of transactions)
ibtRate: BigInt! # The average rate of the IBT token for the day
ibtRateMA: BigInt! # The average rate of the IBT token for the day
lastIBTRate: BigInt! # The last rate of the IBT token for the day
lastPTRate: BigInt! # The last rate of the PT token for the day
realizedAPR7D: BigDecimal! # The realized APR (in % i.e: realizedAPR7D = 1 <==> APR = 100%) of the IBT token over the last 7 days
realizedAPR30D: BigDecimal! # The realized APR of the IBT token over the last 30 days
realizedAPR90D: BigDecimal! # The realized APR of the IBT token over the last 90 days
Expand Down Expand Up @@ -330,19 +332,16 @@ type Transaction @entity {
# AMM
####################

type APRInTime @entity {
type APYInTime @entity {
id: ID!
createdAtTimestamp: BigInt!
block: BigInt!

spotPrice: BigInt!
ptRate: BigInt!
ibtRate: BigInt!
ibtSharesRate: BigInt!
underlyingToPT: BigInt!
"in %"
apr: BigDecimal!

pool: Pool
baseAPY: BigDecimal!
exponentAPY: BigDecimal!
lpVault: LPVault
}

Expand Down Expand Up @@ -375,7 +374,7 @@ type Pool @entity {
liquidityPositions: [AccountAsset!]! @derivedFrom(field: "pool")

spotPrice: BigInt!
apr: [APRInTime!]! @derivedFrom(field: "pool")
apy: [APYInTime!]! @derivedFrom(field: "pool")
}

type Transfer @entity {
Expand Down Expand Up @@ -432,5 +431,5 @@ type LPVault @entity {
transactions: [Transaction!]! @derivedFrom(field: "lpVaultInTransaction")

# interestInTime: [LPVaultInterest!]! @derivedFrom(field: "lpVault")
apr: [APRInTime!]! @derivedFrom(field: "lpVault")
apy: [APYInTime!]! @derivedFrom(field: "lpVault")
}
50 changes: 0 additions & 50 deletions src/entities/APRInTime.ts

This file was deleted.

49 changes: 49 additions & 0 deletions src/entities/APYInTime.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
import { Address, BigInt } from "@graphprotocol/graph-ts"

import { APYInTime } from "../../generated/schema"
import { UNIT_BI, ZERO_BD, ZERO_BI } from "../constants"

export function createAPYInTimeForPool(
poolAddress: Address,
timestamp: BigInt,
blockNumber: BigInt
): APYInTime {
let apyInTime = new APYInTime(
`${poolAddress.toHex()}-${timestamp.toString()}`
)

apyInTime.createdAtTimestamp = timestamp
apyInTime.block = blockNumber
apyInTime.pool = poolAddress.toHex()

apyInTime.spotPrice = UNIT_BI
apyInTime.ptRate = ZERO_BI
apyInTime.ibtRate = ZERO_BI
apyInTime.baseAPY = ZERO_BD
apyInTime.exponentAPY = ZERO_BD

apyInTime.save()

return apyInTime
}

export function createAPYInTimeForLPVault(
lpVaultAddress: Address,
timestamp: BigInt
): APYInTime {
let apyInTime = new APYInTime(
`${lpVaultAddress.toHex()}-${timestamp.toString()}`
)

apyInTime.createdAtTimestamp = timestamp
apyInTime.lpVault = lpVaultAddress.toHex()

apyInTime.spotPrice = UNIT_BI
apyInTime.ptRate = ZERO_BI
apyInTime.ibtRate = ZERO_BI
apyInTime.baseAPY = ZERO_BD
apyInTime.exponentAPY = ZERO_BD
apyInTime.save()

return apyInTime
}
28 changes: 18 additions & 10 deletions src/entities/FutureDailyStats.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,8 @@ import { Future, FutureDailyStats } from "../../generated/schema"
import { DAYS_PER_YEAR_BD, ZERO_BD, ZERO_BI } from "../constants"
import { generateFutureDailyStatsId } from "../utils"
import { getDayIdFromTimestamp, getPastDayId } from "../utils/dayId"
import { getIBTRate } from "./ERC4626"
import { getERC20Decimals } from "./ERC20"
import { getIBTRate, getPTRate, getUnderlying } from "./FutureVault"

/**
* Update the daily data for a future. This function is called every time a
Expand All @@ -19,6 +20,8 @@ export function updateFutureDailyStats(
futureAddress: Address
): FutureDailyStats {
let dayId = getDayIdFromTimestamp(event.block.timestamp)
const asset = getUnderlying(futureAddress)
const underlyingDecimals = getERC20Decimals(asset)
const futureDailyStatsID = generateFutureDailyStatsId(
futureAddress.toHex(),
dayId.toString()
Expand All @@ -27,17 +30,20 @@ export function updateFutureDailyStats(
if (futureDailyStats === null) {
futureDailyStats = createFutureDailyStats(futureAddress, dayId)
}
let future = Future.load(futureAddress.toHex())
let ibt = future!.ibtAsset
const currentRate = getIBTRate(Address.fromString(ibt))

let currentIBTRate = futureDailyStats.ibtRate
const currentRate = getIBTRate(futureAddress)
const currentPTRate = getPTRate(futureAddress)
let currentIBTRateMA = futureDailyStats.ibtRateMA
let dailyUpdates = futureDailyStats.dailyUpdates.plus(BigInt.fromI32(1))
const precision = BigInt.fromI32(underlyingDecimals)
// Compute the ibt rate new average
futureDailyStats.ibtRate = currentIBTRate.plus(
currentRate.minus(currentIBTRate).div(dailyUpdates)
let scaledDifference = currentRate.minus(currentIBTRateMA).times(precision)
let scaledDivision = scaledDifference.div(dailyUpdates)
futureDailyStats.ibtRateMA = currentIBTRateMA.plus(
scaledDivision.div(precision)
)
futureDailyStats.dailyUpdates = dailyUpdates
futureDailyStats.lastIBTRate = currentRate
futureDailyStats.lastPTRate = currentPTRate

futureDailyStats.realizedAPR7D = getAPR(
futureAddress,
Expand Down Expand Up @@ -82,7 +88,7 @@ export function getAPR(
if (previousFutureDailyStats === null) {
return ZERO_BD
}
const previousRate = previousFutureDailyStats.ibtRate
const previousRate = previousFutureDailyStats.ibtRateMA
if (previousRate.equals(ZERO_BI)) {
return ZERO_BD
}
Expand Down Expand Up @@ -143,7 +149,9 @@ export function createFutureDailyStats(
futureDailyStats.dailyAddLiquidity = ZERO_BI
futureDailyStats.dailyRemoveLiquidity = ZERO_BI
futureDailyStats.dailyUpdates = ZERO_BI
futureDailyStats.ibtRate = ZERO_BI
futureDailyStats.ibtRateMA = ZERO_BI
futureDailyStats.lastIBTRate = ZERO_BI
futureDailyStats.lastPTRate = ZERO_BI
futureDailyStats.realizedAPR7D = ZERO_BD
futureDailyStats.realizedAPR30D = ZERO_BD
futureDailyStats.realizedAPR90D = ZERO_BD
Expand Down
15 changes: 15 additions & 0 deletions src/entities/FutureVault.ts
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,21 @@ export function getIBTRate(address: Address): BigInt {
return UNIT_BI
}

// With 27 decimals precision
export function getPTRate(address: Address): BigInt {
const principalTokenContract = PrincipalToken.bind(address)

let ptRateCall = principalTokenContract.try_getPTRate()

if (!ptRateCall.reverted) {
return ptRateCall.value
}

log.warning("getPTRate() call reverted for {}", [address.toHex()])

return UNIT_BI
}

export function getYT(address: Address): Address {
const principalTokenContract = PrincipalToken.bind(address)

Expand Down
6 changes: 3 additions & 3 deletions src/entities/Pool.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { Address, BigInt, Bytes } from "@graphprotocol/graph-ts"
import { Future, Factory, Pool } from "../../generated/schema"
import { ZERO_BI } from "../constants"
import { AssetType } from "../utils"
import { createAPRInTimeForPool } from "./APRInTime"
import { createAPYInTimeForPool } from "./APYInTime"
import { getAsset } from "./Asset"
import { getAssetAmount } from "./AssetAmount"
import {
Expand Down Expand Up @@ -103,13 +103,13 @@ export function createPool(params: PoolDetails): Pool {

let spotPrice = getPoolPriceScale(params.poolAddress)
if (pool.futureVault) {
let poolAPR = createAPRInTimeForPool(
let poolAPY = createAPYInTimeForPool(
params.poolAddress,
params.timestamp,
params.blockNumber
)

poolAPR.save()
poolAPY.save()
}

pool.spotPrice = spotPrice
Expand Down
8 changes: 4 additions & 4 deletions src/mappings/amm.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ import { getERC20Decimals, getERC20TotalSupply } from "../entities/ERC20"
import { updateFutureDailyStats } from "../entities/FutureDailyStats"
import { createTransaction } from "../entities/Transaction"
import { AssetType, generateFeeClaimId } from "../utils"
import { updatePoolAPR } from "../utils/calculateAPR"
import { updatePoolAPY } from "../utils/calculateAPY"
import { generateTransactionId } from "../utils/idGenerators"
import { toPrecision } from "../utils/toPrecision"

Expand Down Expand Up @@ -163,7 +163,7 @@ export function handleAddLiquidity(event: AddLiquidity): void {
}

if (pool.futureVault) {
updatePoolAPR(
updatePoolAPY(
event.address,
Address.fromString(pool.futureVault!),
event.block.timestamp,
Expand Down Expand Up @@ -447,7 +447,7 @@ export function handleTokenExchange(event: TokenExchange): void {
}

if (pool.futureVault) {
updatePoolAPR(
updatePoolAPY(
event.address,
Address.fromString(pool.futureVault!),
event.block.timestamp,
Expand Down Expand Up @@ -606,7 +606,7 @@ export function handleRemoveLiquidityOne(event: RemoveLiquidityOne): void {
}

if (pool.futureVault) {
updatePoolAPR(
updatePoolAPY(
event.address,
Address.fromString(pool.futureVault!),
event.block.timestamp,
Expand Down
12 changes: 7 additions & 5 deletions src/mappings/futures.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ import {
Redeem,
} from "../../generated/templates/PrincipalToken/PrincipalToken"
import { ZERO_ADDRESS, UNIT_BI, ZERO_BI } from "../constants"
// import { createAPRInTimeForLPVault } from "../entities/APRInTime"
// import { createAPYInTimeForLPVault } from "../entities/APYInTime"
import { getAccount } from "../entities/Account"
import {
updateAccountAssetBalance,
Expand Down Expand Up @@ -57,7 +57,7 @@ import {
import { AssetType, generateFeeClaimId } from "../utils"
// import FutureState from "../utils/FutureState"
import transactionType from "../utils/TransactionType"
// import { calculateLpVaultAPR } from "../utils/calculateAPR"
// import { calculateLpVaultAPY } from "../utils/calculateAPY"
import { generateTransactionId } from "../utils/idGenerators"

export function handleRegistryChange(event: RegistryChange): void {
Expand Down Expand Up @@ -442,6 +442,7 @@ export function handleYieldClaimed(event: YieldClaimed): void {
event.params.yieldInIBT,
event.block.timestamp
)
updateFutureDailyStats(event, event.address)
} else {
log.warning("YieldClaimed event call for not existing Future {}", [
event.address.toHex(),
Expand All @@ -454,6 +455,7 @@ export function handlePTTransfer(event: PTTransfer): void {

if (future) {
updateYieldForAll(event.address, event.block.timestamp)
updateFutureDailyStats(event, event.address)
} else {
log.warning("PTTransfer event call for not existing Future {}", [
event.address.toHex(),
Expand Down Expand Up @@ -525,10 +527,10 @@ export function handlePTTransfer(event: PTTransfer): void {
// // Create dynamic data source for LPVault events
// LPVaultTemplate.create(Address.fromBytes(lpVault.address))
//
// let lpVaultAPR = createAPRInTimeForLPVault(
// let lpVaultAPY = createAPYInTimeForLPVault(
// event.params.lpv,
// event.block.timestamp
// )
// lpVaultAPR.apr = calculateLpVaultAPR(event.params.lpv)
// lpVaultAPR.save()
// lpVaultAPY.apy = calculateLpVaultAPY(event.params.lpv)
// lpVaultAPY.save()
// }
Loading

0 comments on commit 74a4a72

Please sign in to comment.