Skip to content

Commit

Permalink
Fix: Fluid revenue (#2300)
Browse files Browse the repository at this point in the history
  • Loading branch information
0xpeluche authored Jan 10, 2025
1 parent 6089367 commit c4e3664
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 23 deletions.
15 changes: 14 additions & 1 deletion fees/fluid/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,20 @@ export const EVENT_ABI: any = {
logRebalance: "event LogRebalance(int colAmt_, int debtAmt_)"
}

export const TOPIC0: any = {
logOperate: '0x4d93b232a24e82b284ced7461bf4deacffe66759d5c24513e6f29e571ad78d15',
logCollectRevenue: '0x7ded56fbc1e1a41c85fd5fb3d0ce91eafc72414b7f06ed356c1d921823d4c37c',
logRebalance: '0x9a85dfb89c634cdc63db5d8cedaf8f9cfa4926df888bad563d70b7314a33a0ae'
}

export const METHODOLOGY_FLUID = {
Fees: "Interest paid by borrowers",
Revenue: "Percentage of interest going to treasury",
};
};

export const parseInTopic = (address: string): string => {
if (!/^0x[0-9a-fA-F]{40}$/.test(address)) {
throw new Error('Invalid EVM address');
}
return `0x000000000000000000000000${address.slice(2).toLowerCase()}`;
}
11 changes: 2 additions & 9 deletions fees/fluid/fees.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { ChainApi } from "@defillama/sdk";
import { FetchOptions } from "../../adapters/types";
import { CHAIN } from "../../helpers/chains";
import { ABI, EVENT_ABI, LIQUIDITY } from "./config";
import { ABI, EVENT_ABI, LIQUIDITY, parseInTopic, TOPIC0 } from "./config";

const reserveContract = "0x264786EF916af64a1DB19F513F24a3681734ce92"

Expand Down Expand Up @@ -45,13 +45,6 @@ export const getVaultsResolver = async (api: ChainApi) => {
}
}

const parseInTopic = (address: string): string => {
if (!/^0x[0-9a-fA-F]{40}$/.test(address)) {
throw new Error('Invalid EVM address');
}
return `0x000000000000000000000000${address.slice(2).toLowerCase()}`;
}

export const getFluidDailyFees = async ({ api, fromApi, toApi, getLogs, createBalances }: FetchOptions) => {
const dailyFees = createBalances();
const vaults: string[] = await (await getVaultsResolver(api)).getAllVaultsAddresses();
Expand Down Expand Up @@ -83,7 +76,7 @@ export const getFluidDailyFees = async ({ api, fromApi, toApi, getLogs, createBa
const initialBalance = Number(totalSupplyAndBorrowFrom.totalBorrowVault);
const borrowBalanceTo = Number(totalSupplyAndBorrowTo.totalBorrowVault);

const liquidityLogs = await getLogs({ target: LIQUIDITY, onlyArgs: true, topics: ['0x4d93b232a24e82b284ced7461bf4deacffe66759d5c24513e6f29e571ad78d15', parseInTopic(vault), parseInTopic(borrowToken)], eventAbi: EVENT_ABI.logOperate, flatten: true, skipCacheRead: true });
const liquidityLogs = await getLogs({ target: LIQUIDITY, onlyArgs: true, topics: [TOPIC0.logOperate, parseInTopic(vault), parseInTopic(borrowToken)], eventAbi: EVENT_ABI.logOperate, flatten: true, skipCacheRead: true });

const borrowBalances = liquidityLogs
.filter((log) => log[5] !== reserveContract)
Expand Down
25 changes: 12 additions & 13 deletions fees/fluid/revenue.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import * as sdk from "@defillama/sdk";
import { ChainApi } from "@defillama/sdk";
import { FetchOptions } from "../../adapters/types";
import { CHAIN } from "../../helpers/chains";
import { ABI, CONFIG_FLUID, EVENT_ABI, LIQUIDITY } from "./config";
import { ABI, CONFIG_FLUID, EVENT_ABI, LIQUIDITY, parseInTopic, TOPIC0 } from "./config";
import { getVaultsResolver } from './fees';

type CreateBalances = () => sdk.Balances
Expand Down Expand Up @@ -103,28 +103,28 @@ const getUncollectedLiquidities = async (api: ChainApi, timestamp: number, token

const getLiquidityRevenues = async ({ api, fromApi, toApi, getLogs, createBalances, fromTimestamp, toTimestamp }: FetchOptions) => {
const dailyValues = createBalances();
const collectedLiquidityLogs = await getLogs({ target: LIQUIDITY, eventAbi: EVENT_ABI.logCollectRevenue });
const tokens: string[] = (await (await liquidityResolver(api)).listedTokens()).map((t: string) => t.toLowerCase());

// Fetch uncollected revenues for the "from" and "to" timestamps
const [revenuesFrom, revenuesTo] = await Promise.all([
getUncollectedLiquidities(fromApi, fromTimestamp, tokens),
getUncollectedLiquidities(toApi, toTimestamp, tokens)
]);

tokens.forEach((token, i) => {
for (const [i, token] of tokens.entries()) {
// Default to 0 if revenues are missing
const collectedRevenue = collectedLiquidityLogs
.filter(([logToken]) => logToken.toLowerCase() === token)
.reduce((sum, [, amount]) => sum + (amount ? Number(amount) : 0), 0);
const collectedRevenueLogs = await getLogs({ target: LIQUIDITY, onlyArgs: true, topics:[TOPIC0.logCollectRevenue, parseInTopic(token)], eventAbi: EVENT_ABI.logCollectRevenue, skipCacheRead: true })
const collectedRevenue = collectedRevenueLogs.reduce((sum, log) => {
const amount = log.amount ? Number(log.amount) : 0;
return sum + amount;
}, 0);

const revenueTo = (revenuesTo[i] !== undefined ? Number(revenuesTo[i]) : 0) + collectedRevenue;
const revenueFrom = revenuesFrom[i] !== undefined ? Number(revenuesFrom[i]) : 0;
const netRevenue = Math.max(0, revenueTo - revenueFrom);

dailyValues.add(token, netRevenue);
});

dailyValues.add(token, netRevenue)
}
return dailyValues.getUSDValue();
};

Expand All @@ -134,7 +134,7 @@ const getVaultUncollectedRevenues = async (api: ChainApi, createBalances: Create

const vaultDatas = await ((await getVaultsResolver(api)).getVaultEntireData(vaults))

vaultDatas.forEach((data, index) => {
vaultDatas.forEach((data) => {
if (!data || !data.totalSupplyAndBorrow || !data.constantVariables) return

const { totalSupplyAndBorrow, constantVariables } = data;
Expand All @@ -154,8 +154,7 @@ const getVaultUncollectedRevenues = async (api: ChainApi, createBalances: Create

const getVaultCollectedRevenues = async (api: ChainApi, createBalances: CreateBalances, getLogs, vaults: string []) => {
const values = createBalances()
const rebalanceEventLogs: any [] = await getLogs({ targets: vaults, onlyArgs: true, flatten: false, eventAbi: EVENT_ABI.logRebalance})

const rebalanceEventLogs: any [] = await getLogs({ targets: vaults, onlyArgs: true, flatten: false, eventAbi: EVENT_ABI.logRebalance })
if (rebalanceEventLogs.length == 0) return values;

const contractViews = await api.multiCall({ abi: ABI.vault.constantsView, calls: vaults })
Expand Down

0 comments on commit c4e3664

Please sign in to comment.