Skip to content

Commit

Permalink
upd: apr recalculation
Browse files Browse the repository at this point in the history
  • Loading branch information
DevTeaLeaf committed Jan 3, 2025
1 parent aeb2d28 commit d66d183
Show file tree
Hide file tree
Showing 9 changed files with 111 additions and 71 deletions.
1 change: 1 addition & 0 deletions schema.graphql
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@ type VaultEntity @entity {
initAssetsAmounts: [BigInt!]
lastAssetsPrices: [String!]!
lastAssetsSum: String!
isInitialized: Boolean!
}

type VaultTypeEntity @entity {
Expand Down
16 changes: 7 additions & 9 deletions src/Factory.ts
Original file line number Diff line number Diff line change
Expand Up @@ -103,14 +103,6 @@ export function handleVaultAndStrategy(event: VaultAndStrategyEvent): void {
VaultData.create(event.params.vault);
StrategyData.create(event.params.strategy);

//Calculate vault.AssetsPricesOnCreation//

const _amounts: Array<BigInt> = [];
for (let i = 0; i < _vaultInfo.value1.length; i++) {
_amounts.push(ZeroBigInt);
}

const assetsPrices = priceReader.getAssetsPrice(_vaultInfo.value1, _amounts);
/////

vault.lastHardWork = ZeroBigInt;
Expand Down Expand Up @@ -143,7 +135,13 @@ export function handleVaultAndStrategy(event: VaultAndStrategyEvent): void {
vault.NFTtokenID = vaultManagerContract
.totalSupply()
.minus(BigInt.fromI32(1));
vault.AssetsPricesOnCreation = assetsPrices.value2;
vault.AssetsPricesOnCreation = [
ZeroBigInt,
ZeroBigInt,
ZeroBigInt,
ZeroBigInt,
];
vault.isInitialized = false;
vault.lifeTimeAPR = ZeroBigInt;
if (event.block.number > BigInt.fromI32(53088320)) {
const getBalanceContract = GetBalanceContract.bind(
Expand Down
126 changes: 66 additions & 60 deletions src/Strategy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,8 @@ import {
platformAddress,
WeekInSecondsBigDecimal,
DayInSecondsBigDecimal,
DayInSecondsBigInt,
OneBigInt,
} from "./utils/constants";

import { BigIntToBigDecimal, pow } from "./utils/math";
Expand All @@ -59,6 +61,10 @@ export function handleHardWork(event: HardWorkEvent): void {

const vault = VaultEntity.load(vaultAddress) as VaultEntity;

const vaultMetricsEntity = VaultMetricsEntity.load(
vaultAddress
) as VaultMetricsEntity;

const vaultInfo = vaultManagerContract.vaultInfo(vaultAddress);

const lastSharePrice = BigDecimal.fromString(vault.sharePrice.toString()).div(
Expand Down Expand Up @@ -106,12 +112,36 @@ export function handleHardWork(event: HardWorkEvent): void {
vaultHistoryEntity.APR = event.params.apr;
vaultHistoryEntity.APR_Compound = event.params.compoundApr;

//===========APR24H===========//
//***** Get timestamp from last HardWork to calculate days from event ******//

const vaultMetricsEntity = VaultMetricsEntity.load(
vaultAddress
) as VaultMetricsEntity;
let lastTimestamp = vault.created;

if (vaultMetricsEntity.timestamps.length) {
lastTimestamp =
vaultMetricsEntity.timestamps[vaultMetricsEntity.timestamps.length - 1];
}

const currentTime = event.block.timestamp;
const differenceInSeconds = currentTime.minus(lastTimestamp);
const differenceInSecondsFromCreation = currentTime.minus(vault.created);

let daysFromLastHardWork: BigDecimal = differenceInSeconds
.toBigDecimal()
.div(BigDecimal.fromString((60 * 60 * 24).toString()));

let daysFromCreation: string = differenceInSecondsFromCreation
.div(BigInt.fromI32(60 * 60 * 24))
.toString();

if (daysFromLastHardWork.equals(ZeroBigDecimal)) {
daysFromLastHardWork = BigDecimal.fromString("1");
}

if (BigDecimal.fromString(daysFromCreation).lt(OneBigDecimal)) {
daysFromCreation = "1";
}

//===========dailyAPR===========//
let _APRArray = vaultMetricsEntity.APRS;
let _timestampsArray = vaultMetricsEntity.timestamps;
let _periodVsHoldAPRs = vaultMetricsEntity.periodVsHoldAPRs;
Expand All @@ -124,13 +154,24 @@ export function handleHardWork(event: HardWorkEvent): void {
_APRArray.reverse();
_timestampsArray.reverse();

const day = BigInt.fromI32(86400);
const day = DayInSecondsBigInt;
let relativeWeek = BigInt.fromI32(604800);

if (BigInt.fromString(daysFromCreation).lt(BigInt.fromI32(7))) {
relativeWeek = DayInSecondsBigInt.times(
BigInt.fromString(daysFromCreation)
);
}

const DENOMINATOR = BigInt.fromI32(100000);
const APRs: Array<BigInt> = [];

const dailyAPRs: Array<BigInt> = [];
const weeklyAPRs: Array<BigInt> = [];

const dailyWeights: Array<BigInt> = [];
const weeklyWeights: Array<BigInt> = [];

let threshold = ZeroBigInt;
const weights: Array<BigInt> = [];

for (let i = 0; i < _APRArray.length; i++) {
if (i + 1 == _APRArray.length) {
Expand All @@ -139,65 +180,60 @@ export function handleHardWork(event: HardWorkEvent): void {
const diff = _timestampsArray[i].minus(_timestampsArray[i + 1]);
if (threshold.plus(diff) <= day) {
threshold = threshold.plus(diff);
weights.push(diff.times(DENOMINATOR).div(day));
dailyWeights.push(diff.times(DENOMINATOR).div(day));
} else {
const result = day
.minus(threshold)
.times(DENOMINATOR)
.div(day);
weights.push(result);
dailyWeights.push(result);
break;
}
}

for (let i = 0; i < weights.length; i++) {
APRs.push(_APRArray[i].times(weights[i]));
for (let i = 0; i < dailyWeights.length; i++) {
dailyAPRs.push(_APRArray[i].times(dailyWeights[i]));
}

let averageAPR24H = APRs.reduce(
const averageDailyAPR = dailyAPRs.reduce(
(accumulator: BigInt, currentValue: BigInt) =>
accumulator.plus(currentValue),
ZeroBigInt
);
averageAPR24H = averageAPR24H.div(DENOMINATOR);

//===========WeeklyAPR===========//

const week = BigInt.fromI32(604800);
//===========weeklyAPR===========//
threshold = ZeroBigInt;
let weightsWeeklyAPR: Array<BigInt> = [];

for (let i = 0; i < _APRArray.length; i++) {
if (i + 1 == _APRArray.length) {
break;
}
const diff = _timestampsArray[i].minus(_timestampsArray[i + 1]);
if (threshold.plus(diff) <= week) {
if (threshold.plus(diff) <= relativeWeek) {
threshold = threshold.plus(diff);
weightsWeeklyAPR.push(diff.times(DENOMINATOR).div(week));
weeklyWeights.push(diff.times(DENOMINATOR).div(relativeWeek));
} else {
const result = week
const result = relativeWeek
.minus(threshold)
.times(DENOMINATOR)
.div(week);
weightsWeeklyAPR.push(result);
.div(relativeWeek);
weeklyWeights.push(result);
break;
}
}

let WeeklyAPRS: Array<BigInt> = [];

for (let i = 0; i < weightsWeeklyAPR.length; i++) {
WeeklyAPRS.push(_APRArray[i].times(weightsWeeklyAPR[i]));
for (let i = 0; i < weeklyWeights.length; i++) {
weeklyAPRs.push(_APRArray[i].times(weeklyWeights[i]));
}

let averageWeeklyAPR = WeeklyAPRS.reduce(
const averageWeeklyAPR = weeklyAPRs.reduce(
(accumulator: BigInt, currentValue: BigInt) =>
accumulator.plus(currentValue),
ZeroBigInt
);

vaultHistoryEntity.APR24H = averageDailyAPR.div(DENOMINATOR);
vaultHistoryEntity.APRWeekly = averageWeeklyAPR.div(DENOMINATOR);

//===========Get platform data===========//
const platformContract = PlatformContract.bind(
Address.fromString(platformAddress)
Expand All @@ -223,36 +259,6 @@ export function handleHardWork(event: HardWorkEvent): void {
}

//======================VS HOLD======================//
//***** Get timestamp from last HardWork to calculate days from event ******//

let lastTimestamp = vault.created;

if (vaultMetricsEntity.timestamps.length) {
lastTimestamp =
vaultMetricsEntity.timestamps[vaultMetricsEntity.timestamps.length - 1];
}

const currentTime = event.block.timestamp;
const differenceInSeconds = currentTime.minus(lastTimestamp);
const differenceInSecondsFromCreation = currentTime.minus(vault.created);

let daysFromLastHardWork: BigDecimal = differenceInSeconds
.toBigDecimal()
.div(BigDecimal.fromString((60 * 60 * 24).toString()));

let daysFromCreation: string = differenceInSecondsFromCreation
.div(BigInt.fromI32(60 * 60 * 24))
.toString();

if (daysFromLastHardWork.equals(ZeroBigDecimal)) {
daysFromLastHardWork = BigDecimal.fromString("1");
}

if (BigDecimal.fromString(daysFromCreation).lt(OneBigDecimal)) {
daysFromCreation = "1";
}
//***** Initialize all other variables ******//

const strategyAssets = assetsAmounts.value0;

let strategyAssetsAmounts: BigInt[] = [];
Expand Down Expand Up @@ -533,6 +539,8 @@ export function handleHardWork(event: HardWorkEvent): void {

vaultHistoryEntity.vsHoldAPR = vsHoldAPR.toString();
vaultHistoryEntity.assetsVsHoldAPR = assetsVsHoldAPR;

vaultHistoryEntity.save();
//===========LifeTimeAPR===========//

const lifeLength = _timestampsArray[0].minus(vault.created);
Expand Down Expand Up @@ -572,8 +580,6 @@ export function handleHardWork(event: HardWorkEvent): void {
vaultMetricsEntity.periodAsset1VsHoldAPRs = _periodAsset1VsHoldAPRs;
vaultMetricsEntity.periodAsset2VsHoldAPRs = _periodAsset2VsHoldAPRs;
vaultMetricsEntity.save();
vaultHistoryEntity.APR24H = averageAPR24H;
vaultHistoryEntity.save();

//===========vaultHistoryEntity(VaultEntity)===========//
let _vaultHistoryEntity = vault.vaultHistoryEntity;
Expand Down
29 changes: 28 additions & 1 deletion src/Vault.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,18 +20,45 @@ import {
import { PriceReaderABI as PriceReaderContract } from "../generated/templates/IchiQuickSwapMerklFarmData/PriceReaderABI";
import { WithdrawAssets as WithdrawAssetsEventOld } from "../generated/templates/deprecatedData/deprecatedABI";
import { StrategyBaseABI as StrategyContract } from "../generated/templates/StrategyData/StrategyBaseABI";
import { VaultManagerABI as VaultManagerContract } from "../generated/templates/VaultManagerData/VaultManagerABI";

import {
ZeroBigInt,
addressZero,
oneEther,
platformAddress,
vaultManagerAddress,
priceReaderAddress,
} from "./utils/constants";

export function handleDepositAssets(event: DepositAssetsEvent): void {
const vault = VaultEntity.load(event.address) as VaultEntity;
const vaultContract = VaultContract.bind(event.address);

if (!vault.isInitialized) {
const vaultManagerContract = VaultManagerContract.bind(
Address.fromString(vaultManagerAddress)
);

const _vaultInfo = vaultManagerContract.vaultInfo(event.address);

const _amounts: Array<BigInt> = [];
for (let i = 0; i < _vaultInfo.value1.length; i++) {
_amounts.push(ZeroBigInt);
}

const priceReader = PriceReaderContract.bind(
Address.fromString(priceReaderAddress)
);

const assetsPrices = priceReader.getAssetsPrice(
_vaultInfo.value1,
_amounts
);

vault.AssetsPricesOnCreation = assetsPrices.value2;
vault.isInitialized = true;
}

const _VaultUserId = event.address
.toHexString()
.concat(":")
Expand Down
4 changes: 4 additions & 0 deletions src/utils/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,10 +26,12 @@ const getBalanceAddress = "0x1Ebd614F038a6cED8faBf0Be075995dd1BB549cE";

const oneEther = BigInt.fromI32(10).pow(18);
const ZeroBigInt = BigInt.fromI32(0);
const OneBigInt = BigInt.fromI32(1);
const ZeroBigDecimal = BigDecimal.fromString("0");
const OneBigDecimal = BigDecimal.fromString("1");
const WeeksBigDecimal = BigDecimal.fromString("52");
const DayInSecondsBigDecimal = BigDecimal.fromString("86400");
const DayInSecondsBigInt = BigInt.fromI32(86400);
const WeekInSecondsBigDecimal = BigDecimal.fromString("604800");
const OneHundredBigDecimal = BigDecimal.fromString("100");
const YearBigDecimal = BigDecimal.fromString("365");
Expand All @@ -55,4 +57,6 @@ export {
defiedgeFactoryAddress,
DayInSecondsBigDecimal,
WeekInSecondsBigDecimal,
DayInSecondsBigInt,
OneBigInt,
};
2 changes: 1 addition & 1 deletion template-generator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ if (!selectedNetworkConfig) {
const templates = {
basic: "templates/basic.yaml.mustache",
real: "templates/real.yaml.mustache",
network: "templates/network.mustache",
network: "templates/network.yaml.mustache",
};

const getTemplateContent = (templatePath) =>
Expand Down
2 changes: 2 additions & 0 deletions templates/basic.yaml.mustache
Original file line number Diff line number Diff line change
Expand Up @@ -135,6 +135,8 @@ templates:
file: ./abis/ERC20UpgradeableABI.json
- name: PlatformABI
file: ./abis/PlatformABI.json
- name: VaultManagerABI
file: ./abis/VaultManagerABI.json
eventHandlers:
- event: Transfer(indexed address,indexed address,uint256)
handler: handleTransfer
Expand Down
File renamed without changes.
2 changes: 2 additions & 0 deletions templates/real.yaml.mustache
Original file line number Diff line number Diff line change
Expand Up @@ -125,6 +125,8 @@ templates:
file: ./abis/ERC20UpgradeableABI.json
- name: PlatformABI
file: ./abis/PlatformABI.json
- name: VaultManagerABI
file: ./abis/VaultManagerABI.json
eventHandlers:
- event: Transfer(indexed address,indexed address,uint256)
handler: handleTransfer
Expand Down

0 comments on commit d66d183

Please sign in to comment.