diff --git a/adapters/types.ts b/adapters/types.ts index 35d583e031..c524a2b3e2 100644 --- a/adapters/types.ts +++ b/adapters/types.ts @@ -17,9 +17,32 @@ export type FetchResultGeneric = FetchResultBase & { [key: string]: FetchResponseValue | undefined; } +export type FetchOptions = { + createBalances: () => Balances; + getBlock: (timestamp: number, chain: string, chainBlocks: ChainBlocks) => Promise; + getLogs: (params: FetchGetLogsOptions) => Promise; + toTimestamp: number; + fromTimestamp: number; + getFromBlock: () => Promise; + getToBlock: () => Promise; + chain: string, +} + +export type FetchGetLogsOptions = { + eventAbi: string, + target?: string, + targets?: string[], + onlyArgs?: boolean, + fromBlock?: number, + toBlock?: number, + flatten?: boolean, + topics?: string[], +} + export type Fetch = ( timestamp: number, - chainBlocks: ChainBlocks + chainBlocks: ChainBlocks, + options?: FetchOptions, ) => Promise; export type IStartTimestamp = () => Promise diff --git a/adapters/utils/runAdapter.ts b/adapters/utils/runAdapter.ts index dae5360adf..f123bbdf95 100644 --- a/adapters/utils/runAdapter.ts +++ b/adapters/utils/runAdapter.ts @@ -1,5 +1,6 @@ -import { Balances } from '@defillama/sdk' -import { BaseAdapter, ChainBlocks, DISABLED_ADAPTER_KEY, FetchResultGeneric, } from '../types' +import { Balances, getEventLogs } from '@defillama/sdk' +import { BaseAdapter, ChainBlocks, DISABLED_ADAPTER_KEY, FetchGetLogsOptions, FetchResultGeneric, } from '../types' +import { getBlock } from "../../helpers/getBlock"; const ONE_DAY_IN_SECONDS = 60 * 60 * 24 @@ -19,7 +20,8 @@ export default async function runAdapter(volumeAdapter: BaseAdapter, cleanCurren async function getChainResult(chain: string) { const fetchFunction = volumeAdapter[chain].customBackfill ?? volumeAdapter[chain].fetch try { - const result: FetchResultGeneric = await fetchFunction(cleanCurrentDayTimestamp - 1, chainBlocks); + const options = getOptionsObject(cleanCurrentDayTimestamp, chain, chainBlocks) + const result: FetchResultGeneric = await fetchFunction(options.toTimestamp, chainBlocks, options); const ignoreKeys = ['timestamp', 'block'] // if (id) // console.log("Result before cleaning", id, version, cleanCurrentDayTimestamp, chain, result, JSON.stringify(chainBlocks ?? {})) @@ -27,8 +29,8 @@ export default async function runAdapter(volumeAdapter: BaseAdapter, cleanCurren if (ignoreKeys.includes(key)) continue; if (value === undefined || value === null) throw new Error(`Value: ${value} ${key} is undefined or null`) if (value instanceof Balances) result[key] = await value.getUSDString() - result[key] = +Number(value).toFixed(0) - if (isNaN(result[key] as number)) throw new Error(`Value: ${value} ${key} is NaN`) + result[key] = +Number(result[key]).toFixed(0) + if (isNaN(result[key] as number)) throw new Error(`[${chain}]Value: ${value} ${key} is NaN`) } return { chain, @@ -41,6 +43,35 @@ export default async function runAdapter(volumeAdapter: BaseAdapter, cleanCurren } } + function getOptionsObject(timestamp: number, chain: string, chainBlocks: ChainBlocks) { + const createBalances: () => Balances = () => { + const closeToCurrentTime = Math.trunc(Date.now() / 1000) - timestamp < 12 * 60 * 60 // 12 hours + return new Balances({ timestamp: closeToCurrentTime ? timestamp : undefined, chain }) + } + const toTimestamp = timestamp - 1 + const fromTimestamp = toTimestamp - ONE_DAY_IN_SECONDS + const fromChainBlocks = {} + const getFromBlock = async () => await getBlock(fromTimestamp, chain, fromChainBlocks) + const getToBlock = async () => await getBlock(toTimestamp, chain, chainBlocks) + const getLogs = async ({ target, targets, onlyArgs = true, fromBlock, toBlock, flatten = true, eventAbi, topics, }: FetchGetLogsOptions) => { + fromBlock = fromBlock ?? await getFromBlock() + toBlock = toBlock ?? await getToBlock() + + return getEventLogs({ fromBlock, toBlock, chain, target, targets, onlyArgs, flatten, eventAbi, topics, }) + } + + return { + createBalances, + getBlock, + toTimestamp, + fromTimestamp, + getFromBlock, + getToBlock, + getLogs, + chain, + } + } + async function setChainValidStart(chain: string) { const _start = volumeAdapter[chain]?.start if (_start === undefined) return; diff --git a/aggregators/aggre/index.ts b/aggregators/aggre/index.ts index 112c417325..4da32796c2 100644 --- a/aggregators/aggre/index.ts +++ b/aggregators/aggre/index.ts @@ -1,10 +1,10 @@ -import {Chain} from "@defillama/sdk/build/general"; -import {FetchResultAggregators, SimpleAdapter} from "../../adapters/types"; -import {getBlock} from "../../helpers/getBlock"; -import {CHAIN} from "../../helpers/chains"; +import { Chain } from "@defillama/sdk/build/general"; +import { FetchResultAggregators, SimpleAdapter } from "../../adapters/types"; +import { getBlock } from "../../helpers/getBlock"; +import { CHAIN } from "../../helpers/chains"; import * as sdk from "@defillama/sdk"; -let abi = [ "event SwapExecuted(address indexed user, address tokenIn, address tokenOut, uint amountIn, uint amountOut, uint swapType)" ]; +let abi = ["event SwapExecuted(address indexed user, address tokenIn, address tokenOut, uint amountIn, uint amountOut, uint swapType)"]; type IContract = { [c: string | Chain]: string; @@ -20,38 +20,27 @@ const fetch = (chain: Chain) => { const toTimestamp = timestamp; - try { - const api = new sdk.ChainApi({chain, timestamp}); - const fromBlock = (await getBlock(fromTimestamp, chain, {})); - const toBlock = (await getBlock(toTimestamp, chain, {})); - const logs = (await api.getLogs({ - target: contract[chain], - toBlock: toBlock, - fromBlock: fromBlock, - chain, - eventAbi: abi[0], - onlyArgs: true, - })) + const api = new sdk.ChainApi({ chain, timestamp }); + const fromBlock = (await getBlock(fromTimestamp, chain, {})); + const toBlock = (await getBlock(toTimestamp, chain, {})); + const logs = (await api.getLogs({ + target: contract[chain], + toBlock: toBlock, + fromBlock: fromBlock, + chain, + eventAbi: abi[0], + onlyArgs: true, + })) - logs.map((parsed: any) => { - api.add(parsed.tokenOut, parsed.amountOut) - }); - const VUSD = Number(await api.getUSDValue()).toFixed(0); - - return { - dailyVolume: VUSD, - timestamp, - }; - } catch (e) { - console.log('err::', e); - } + logs.map((parsed: any) => { + api.add(parsed.tokenOut, parsed.amountOut) + }); + const VUSD = Number(await api.getUSDValue()).toFixed(0); return { - dailyVolume: '0', - block: 0, - timestamp: 0, - totalVolume: "" - } + dailyVolume: VUSD, + timestamp, + }; }; }; diff --git a/aggregators/jumper-exchange/index.ts b/aggregators/jumper-exchange/index.ts index 9d5e14d911..d33088dbb5 100644 --- a/aggregators/jumper-exchange/index.ts +++ b/aggregators/jumper-exchange/index.ts @@ -31,25 +31,20 @@ const fetch = (chain: Chain) => { const fromTimestamp = timestamp - 60 * 60 * 24; const toTimestamp = timestamp; const api = new sdk.ChainApi({ chain, timestamp }); - try { - const data: IData[] = (await api.getLogs({ - target: contract[chain], - fromTimestamp, toTimestamp, - chain: chain, - onlyArgs: true, - eventAbi: 'event LiFiGenericSwapCompleted(bytes32 indexed transactionId, string integrator, string referrer, address receiver, address fromAssetId, address toAssetId, uint256 fromAmount, uint256 toAmount)' - })) as any - console.log(data.length, chain) - data.forEach((e: IData) => api.add(e.toAssetId, e.toAmount)); - const { usdTvl } = await api.getUSDJSONs() - return { - dailyVolume: Number(usdTvl).toFixed(0), - timestamp, - } as any; - } catch (error) { - console.error(error); - throw error; - } + const data: IData[] = (await api.getLogs({ + target: contract[chain], + fromTimestamp, toTimestamp, + chain: chain, + onlyArgs: true, + eventAbi: 'event LiFiGenericSwapCompleted(bytes32 indexed transactionId, string integrator, string referrer, address receiver, address fromAssetId, address toAssetId, uint256 fromAmount, uint256 toAmount)' + })) as any + console.log(data.length, chain) + data.forEach((e: IData) => api.add(e.toAssetId, e.toAmount)); + const { usdTvl } = await api.getUSDJSONs() + return { + dailyVolume: Number(usdTvl).toFixed(0), + timestamp, + } as any; }; }; diff --git a/aggregators/kyberswap/index.ts b/aggregators/kyberswap/index.ts index 8cc2d3f96d..b8d45cd311 100644 --- a/aggregators/kyberswap/index.ts +++ b/aggregators/kyberswap/index.ts @@ -35,24 +35,16 @@ const fetch = (chain: string) => async (timestamp: number) => { new Date(timestamp * 1000) ); - try { - const data = ( - await fetchURL( - `https://common-service.kyberswap.com/api/v1/aggregator/volume/daily?chainId=${chainToId[chain]}×tamps=${unixTimestamp}` - ) - ).data?.volumes?.[0]; + const data = ( + await fetchURL( + `https://common-service.kyberswap.com/api/v1/aggregator/volume/daily?chainId=${chainToId[chain]}×tamps=${unixTimestamp}` + ) + ).data?.volumes?.[0]; - return { - dailyVolume: data?.value ?? "0", - timestamp: unixTimestamp, - }; - } catch (e) { - console.log(e); - return { - dailyVolume: "0", - timestamp: unixTimestamp, - }; - } + return { + dailyVolume: data.value, + timestamp: unixTimestamp, + }; }; const adapter: any = { diff --git a/aggregators/llamaswap/index.ts b/aggregators/llamaswap/index.ts index bce146184a..1b08e65042 100644 --- a/aggregators/llamaswap/index.ts +++ b/aggregators/llamaswap/index.ts @@ -40,10 +40,9 @@ const chains = [ const fetch = (chain: string) => - async (timestamp: number): Promise => { - const dayTimestamp = timestamp; + async (timestamp: number): Promise => { + const dayTimestamp = timestamp; - try { const dailyVolume = await fetchURL( `${URL}getSwapDailyVolume/?timestamp=${dayTimestamp}&chain=${chain}` ); @@ -52,18 +51,11 @@ const fetch = ); return { - dailyVolume: dailyVolume.volume || "0", - totalVolume: totalVolume.volume || "0", + dailyVolume: dailyVolume.volume, + totalVolume: totalVolume.volume, timestamp: dayTimestamp, }; - } catch (e) { - return { - dailyVolume: "0", - totalVolume: "0", - timestamp: dayTimestamp, - }; - } - }; + }; const adapter: SimpleAdapter = { adapter: {}, diff --git a/aggregators/openocean/index.tsx b/aggregators/openocean/index.tsx index c9591acfe8..c8e05dde8b 100644 --- a/aggregators/openocean/index.tsx +++ b/aggregators/openocean/index.tsx @@ -25,16 +25,14 @@ const chains = [ const fetch = (chain: string) => - async (timestamp: number): Promise => { - const today = new Date(); - const timestampDate = new Date(timestamp * 1000); - const unixTimestamp = getUniqStartOfTodayTimestamp(timestampDate); - const dayDiff = today.getTime() - timestampDate.getTime(); - const daysPassed = (dayDiff / (1000 * 3600 * 24)).toFixed(0); - try { + async (timestamp: number): Promise => { + const today = new Date(); + const timestampDate = new Date(timestamp * 1000); + const unixTimestamp = getUniqStartOfTodayTimestamp(timestampDate); + const dayDiff = today.getTime() - timestampDate.getTime(); + const daysPassed = (dayDiff / (1000 * 3600 * 24)).toFixed(0); const data = await fetchURL( - `https://open-api.openocean.finance/v3/DefiLlama/volume?limit=${ - daysPassed || 1 + `https://open-api.openocean.finance/v3/DefiLlama/volume?limit=${daysPassed || 1 }&total=true` ); @@ -42,13 +40,7 @@ const fetch = dailyVolume: data.data[chainsMap[chain] || chain]?.volume, timestamp: unixTimestamp, }; - } catch (e) { - return { - dailyVolume: "0", - timestamp: unixTimestamp, - }; - } - }; + }; const adapter: any = { adapter: { diff --git a/aggregators/zrx/index.ts b/aggregators/zrx/index.ts index 687a8a4e5d..774f6db5ef 100644 --- a/aggregators/zrx/index.ts +++ b/aggregators/zrx/index.ts @@ -49,24 +49,17 @@ const fetch = (chain: string) => async (timestamp: number) => { new Date(timestamp * 1000) ); - try { - const data = await getVolumeByChain(chain); - const dayData = data.find( - ({ timestamp }: { timestamp: number }) => - getUniqStartOfTodayTimestamp(new Date(timestamp)) === - unixTimestamp - ); + const data = await getVolumeByChain(chain); + const dayData = data.find( + ({ timestamp }: { timestamp: number }) => + getUniqStartOfTodayTimestamp(new Date(timestamp)) === + unixTimestamp + ); - return { - dailyVolume: dayData?.volumeUSD ?? '0', - timestamp: unixTimestamp, - }; - } catch (e) { - return { - dailyVolume: '0', - timestamp: unixTimestamp, - }; - } + return { + dailyVolume: dayData.volumeUSD, + timestamp: unixTimestamp, + }; }; const adapter: any = { diff --git a/dexs/aerodrome/index.ts b/dexs/aerodrome/index.ts index 28063b7ef1..1af2fe4ffa 100644 --- a/dexs/aerodrome/index.ts +++ b/dexs/aerodrome/index.ts @@ -38,68 +38,62 @@ const contract_interface = new ethers.Interface([ const fetch = async (timestamp: number): Promise => { const fromTimestamp = timestamp - 60 * 60 * 24 const toTimestamp = timestamp - try { - const forSwaps: IForSwap[] = (await sdk.api2.abi.call({ - target: gurar, - abi: abis.forSwaps, - chain: CHAIN.BASE, - })).map((e: any) => { - return { - lp: e.lp, - token0: e.token0, - token1: e.token1, - } - }) - - const fromBlock = (await getBlock(fromTimestamp, CHAIN.BASE, {})); - const toBlock = (await getBlock(toTimestamp, CHAIN.BASE, {})); + const forSwaps: IForSwap[] = (await sdk.api2.abi.call({ + target: gurar, + abi: abis.forSwaps, + chain: CHAIN.BASE, + })).map((e: any) => { + return { + lp: e.lp, + token0: e.token0, + token1: e.token1, + } + }) - const logs: ILog[] = (await Promise.all(forSwaps.map((forSwaps: IForSwap) => sdk.getEventLogs({ - target: forSwaps.lp, - toBlock: toBlock, - fromBlock: fromBlock, - chain: CHAIN.BASE, - topics: [topic0_swap] - })))).flat(); + const fromBlock = (await getBlock(fromTimestamp, CHAIN.BASE, {})); + const toBlock = (await getBlock(toTimestamp, CHAIN.BASE, {})); - const coins = [...new Set([ - ...forSwaps.map((log: IForSwap) => `${CHAIN.BASE}:${log.token0}`), - ...forSwaps.map((log: IForSwap) => `${CHAIN.BASE}:${log.token1}`) - ])] + const logs: ILog[] = (await Promise.all(forSwaps.map((forSwaps: IForSwap) => sdk.getEventLogs({ + target: forSwaps.lp, + toBlock: toBlock, + fromBlock: fromBlock, + chain: CHAIN.BASE, + topics: [topic0_swap] + })))).flat(); - const coins_split: string[][] = []; - for(let i = 0; i < coins.length; i+=100) { - coins_split.push(coins.slice(i, i + 100)) - } - const prices_result: any = (await Promise.all(coins_split.map((a: string[]) => getPrices(a, timestamp)))).flat().flat().flat(); - const prices: TPrice = Object.assign({}, {}); - prices_result.map((a: any) => Object.assign(prices, a)) - const volumeUSD: number = logs.map((log: ILog) => { - const value = contract_interface.parseLog(log); - const amount0In = Number(value!.args.amount0In); - const amount1In = Number(value!.args.amount1In); - const amount0Out = Number(value!.args.amount0Out); - const amount1Out = Number(value!.args.amount1Out); - const {token0, token1} = forSwaps.find((forSwap: IForSwap) => forSwap.lp.toLowerCase() === log.address.toLowerCase()) as IForSwap - const token0Decimals = prices[`${CHAIN.BASE}:${token0}`]?.decimals || 0 - const token1Decimals = prices[`${CHAIN.BASE}:${token1}`]?.decimals || 0 - const price0 = prices[`${CHAIN.BASE}:${token0}`]?.price || 0 - const price1 = prices[`${CHAIN.BASE}:${token1}`]?.price || 0 - const totalAmount0 = ((amount0In + amount0Out) / 10 ** token0Decimals) * price0 - const totalAmount1 = ((amount1In + amount1Out) / 10 ** token1Decimals) * price1 - const untrackAmountUSD = price0 !== 0 ? totalAmount0 : price1 !== 0 ? totalAmount1 : 0; - return untrackAmountUSD; - }).reduce((a: number, b: number) => a+b, 0) + const coins = [...new Set([ + ...forSwaps.map((log: IForSwap) => `${CHAIN.BASE}:${log.token0}`), + ...forSwaps.map((log: IForSwap) => `${CHAIN.BASE}:${log.token1}`) + ])] - return { - dailyVolume: `${volumeUSD}`, - timestamp - } - } catch(e) { - console.error(e) - throw e; + const coins_split: string[][] = []; + for (let i = 0; i < coins.length; i += 100) { + coins_split.push(coins.slice(i, i + 100)) } + const prices_result: any = (await Promise.all(coins_split.map((a: string[]) => getPrices(a, timestamp)))).flat().flat().flat(); + const prices: TPrice = Object.assign({}, {}); + prices_result.map((a: any) => Object.assign(prices, a)) + const volumeUSD: number = logs.map((log: ILog) => { + const value = contract_interface.parseLog(log); + const amount0In = Number(value!.args.amount0In); + const amount1In = Number(value!.args.amount1In); + const amount0Out = Number(value!.args.amount0Out); + const amount1Out = Number(value!.args.amount1Out); + const { token0, token1 } = forSwaps.find((forSwap: IForSwap) => forSwap.lp.toLowerCase() === log.address.toLowerCase()) as IForSwap + const token0Decimals = prices[`${CHAIN.BASE}:${token0}`]?.decimals || 0 + const token1Decimals = prices[`${CHAIN.BASE}:${token1}`]?.decimals || 0 + const price0 = prices[`${CHAIN.BASE}:${token0}`]?.price || 0 + const price1 = prices[`${CHAIN.BASE}:${token1}`]?.price || 0 + const totalAmount0 = ((amount0In + amount0Out) / 10 ** token0Decimals) * price0 + const totalAmount1 = ((amount1In + amount1Out) / 10 ** token1Decimals) * price1 + const untrackAmountUSD = price0 !== 0 ? totalAmount0 : price1 !== 0 ? totalAmount1 : 0; + return untrackAmountUSD; + }).reduce((a: number, b: number) => a + b, 0) + return { + dailyVolume: `${volumeUSD}`, + timestamp + } } const adapters: SimpleAdapter = { adapter: { diff --git a/dexs/airswap/index.ts b/dexs/airswap/index.ts index 2afa12c7dc..6068de2816 100644 --- a/dexs/airswap/index.ts +++ b/dexs/airswap/index.ts @@ -4,14 +4,14 @@ import * as sdk from "@defillama/sdk"; import { getBlock } from "../../helpers/getBlock"; import { getPrices } from "../../utils/prices"; import { Chain } from "@defillama/sdk/build/general"; -import { ethers, } from "ethers"; +import { ethers, } from "ethers"; interface ITx { data: string; transactionHash: string; topics: string[]; } -interface IData { +interface IData { signerAmount: number; signerToken: string; } @@ -38,42 +38,37 @@ const graph = (chain: Chain) => { return async (timestamp: number): Promise => { const fromTimestamp = timestamp - 60 * 60 * 24 const toTimestamp = timestamp - try { - const fromBlock = (await getBlock(fromTimestamp, chain, {})); - const toBlock = (await getBlock(toTimestamp, chain, {})); + const fromBlock = (await getBlock(fromTimestamp, chain, {})); + const toBlock = (await getBlock(toTimestamp, chain, {})); - const logs: ITx[] = (await sdk.getEventLogs({ - target: address[chain], - toBlock: toBlock, - fromBlock: fromBlock, - chain: chain, - topics: [topic0] - })).map((e: any) => { return { data: e.data, transactionHash: e.transactionHash, topics: e.topics } as ITx}); - const rawData = logs.map((e: ITx) => { - const data = contract_interface.parseLog(e); - return { - signerAmount: Number(data!.args.signerAmount), - signerToken: data!.args.signerToken, - } - }) - const rawCoins = rawData.map((e: IData) => `${chain}:${e.signerToken.toLowerCase()}`); - const coins = [...new Set(rawCoins)] - const prices = await getPrices(coins, timestamp); - const untrackVolumes: number[] = rawData.map((e: IData) => { - const decimals = prices[`${chain}:${e.signerToken.toLowerCase()}`].decimals; - const price = prices[`${chain}:${e.signerToken.toLowerCase()}`].price; - return (Number(e.signerAmount) / 10 ** decimals) * price; - }); + const logs: ITx[] = (await sdk.getEventLogs({ + target: address[chain], + toBlock: toBlock, + fromBlock: fromBlock, + chain: chain, + topics: [topic0] + })).map((e: any) => { return { data: e.data, transactionHash: e.transactionHash, topics: e.topics } as ITx }); + const rawData = logs.map((e: ITx) => { + const data = contract_interface.parseLog(e); + return { + signerAmount: Number(data!.args.signerAmount), + signerToken: data!.args.signerToken, + } + }) + const rawCoins = rawData.map((e: IData) => `${chain}:${e.signerToken.toLowerCase()}`); + const coins = [...new Set(rawCoins)] + const prices = await getPrices(coins, timestamp); + const untrackVolumes: number[] = rawData.map((e: IData) => { + const decimals = prices[`${chain}:${e.signerToken.toLowerCase()}`].decimals; + const price = prices[`${chain}:${e.signerToken.toLowerCase()}`].price; + return (Number(e.signerAmount) / 10 ** decimals) * price; + }); - const dailyVolume = untrackVolumes.reduce((a: number, b: number) => a + b, 0); - return { - dailyVolume: `${dailyVolume}`, - timestamp, - }; - } catch(error) { - console.error(error); - throw error; - } + const dailyVolume = untrackVolumes.reduce((a: number, b: number) => a + b, 0); + return { + dailyVolume: `${dailyVolume}`, + timestamp, + }; } } diff --git a/dexs/caviarnine/index.ts b/dexs/caviarnine/index.ts index 2a6c999f99..142ea8b2e2 100644 --- a/dexs/caviarnine/index.ts +++ b/dexs/caviarnine/index.ts @@ -8,21 +8,14 @@ const url_trades = 'https://api-core.caviarnine.com/v1.0/stats/product/shapeliqu const fetchSpot = async (timestamp: number): Promise => { let dailyVolume = 0; - try { - const orderbookVolume = (await fetchURL(url_orderbook)).summary.volume.interval_1d.usd; - dailyVolume += Number(orderbookVolume); - } catch (e) { - console.error('Failed to fetch orderbook volume', e); - } + const orderbookVolume = (await fetchURL(url_orderbook)).summary.volume.interval_1d.usd; + dailyVolume += Number(orderbookVolume); + + const dailyVolumeTrades = (await fetchURL(url_trades)).summary.volume.interval_1d.usd; + dailyVolume += Number(dailyVolumeTrades); - try { - const dailyVolumeTrades = (await fetchURL(url_trades)).summary.volume.interval_1d.usd; - dailyVolume += Number(dailyVolumeTrades); - } catch (e) { - console.error('Failed to fetch trades volume', e); - } return { - dailyVolume: dailyVolume ? `${dailyVolume}` : undefined, + dailyVolume: dailyVolume ? `${dailyVolume}` : undefined, timestamp } } diff --git a/dexs/e3/index.ts b/dexs/e3/index.ts index 9094d3bffe..905a315e76 100644 --- a/dexs/e3/index.ts +++ b/dexs/e3/index.ts @@ -4,7 +4,7 @@ import * as sdk from "@defillama/sdk"; import { getBlock } from "../../helpers/getBlock"; import { getPrices } from "../../utils/prices"; import { Chain } from "@defillama/sdk/build/general"; -import { ethers, } from "ethers"; +import { ethers, } from "ethers"; interface ILog { data: string; @@ -27,94 +27,88 @@ type TABI = { [k: string]: string; } const ABIs: TABI = { - "getNumberOfLBPairs": "uint256:getNumberOfLBPairs", - "getLBPairAtIndex": "function getLBPairAtIndex(uint256 index) view returns (address lbPair)" + "getNumberOfLBPairs": "uint256:getNumberOfLBPairs", + "getLBPairAtIndex": "function getLBPairAtIndex(uint256 index) view returns (address lbPair)" } const graph = (_chain: Chain) => { return async (timestamp: number) => { const fromTimestamp = timestamp - 60 * 60 * 24 const toTimestamp = timestamp - try { - - const poolLength = (await sdk.api2.abi.call({ + const poolLength = (await sdk.api2.abi.call({ + target: FACTORY_ADDRESS, + chain: _chain, + abi: ABIs.getNumberOfLBPairs, + })); + + const poolsRes = await sdk.api2.abi.multiCall({ + abi: ABIs.getLBPairAtIndex, + calls: Array.from(Array(Number(poolLength)).keys()).map((i) => ({ target: FACTORY_ADDRESS, - chain: _chain, - abi: ABIs.getNumberOfLBPairs, - })); - - const poolsRes = await sdk.api2.abi.multiCall({ - abi: ABIs.getLBPairAtIndex, - calls: Array.from(Array(Number(poolLength)).keys()).map((i) => ({ - target: FACTORY_ADDRESS, - params: i, - })), - chain: _chain - }); - - const lpTokens = poolsRes - - const [underlyingToken0, underlyingToken1] = await Promise.all( - ['address:getTokenX', 'address:getTokenY'].map((abi: string) => - sdk.api2.abi.multiCall({ - abi, - calls: lpTokens, - chain: _chain - }) - ) - ); - - const tokens0 = underlyingToken0; - const tokens1 = underlyingToken1; - const fromBlock = (await getBlock(fromTimestamp, _chain, {})); - const toBlock = (await getBlock(toTimestamp, _chain, {})); - - const logs: ILog[][] = (await Promise.all(lpTokens.map((address: string) => sdk.getEventLogs({ - target: address, - toBlock: toBlock, - fromBlock: fromBlock, - chain: _chain, - topics: [topic0] - })))) as any; - - const rawCoins = [...tokens0, ...tokens1].map((e: string) => `${_chain}:${e}`); - const coins = [...new Set(rawCoins)] - const prices = await getPrices(coins, timestamp); - - - const untrackVolumes: number[] = lpTokens.map((_: string, index: number) => { - const token0Decimals = prices[`${_chain}:${tokens0[index]}`]?.decimals || 0 - const token1Decimals = prices[`${_chain}:${tokens1[index]}`]?.decimals || 0 - const log: IAmount[] = logs[index] - .map((e: ILog) => { return { ...e } }) - .map((p: ILog) => { - const value = contract_interface.parseLog(p); - const amountInX = Number('0x'+'0'.repeat(32)+value!.args.amountsIn.replace('0x', '').slice(0, 32)) / 10 ** token1Decimals - const amountInY = Number('0x'+'0'.repeat(32)+value!.args.amountsIn.replace('0x', '').slice(32, 64)) / 10 ** token0Decimals - return { - amountInX, - amountInY, - } as IAmount - }) as IAmount[]; - - const token0Price = (prices[`${_chain}:${tokens0[index]}`]?.price || 0); - const token1Price = (prices[`${_chain}:${tokens1[index]}`]?.price || 0); - const totalAmountInX = log - .reduce((a: number, b: IAmount) => Number(b.amountInX) + a, 0) * token1Price; - const totalAmountInY = log - .reduce((a: number, b: IAmount) => Number(b.amountInY) + a, 0) * token0Price; - const untrackAmountUSD = (totalAmountInX + totalAmountInY); // counted only we have price data - return untrackAmountUSD; - }); - const dailyVolume = untrackVolumes.reduce((a: number, b: number) => a + b, 0); - return { - dailyVolume: `${dailyVolume}`, - timestamp, - }; - } catch(error) { - console.error(error); - throw error; - } + params: i, + })), + chain: _chain + }); + + const lpTokens = poolsRes + + const [underlyingToken0, underlyingToken1] = await Promise.all( + ['address:getTokenX', 'address:getTokenY'].map((abi: string) => + sdk.api2.abi.multiCall({ + abi, + calls: lpTokens, + chain: _chain + }) + ) + ); + + const tokens0 = underlyingToken0; + const tokens1 = underlyingToken1; + const fromBlock = (await getBlock(fromTimestamp, _chain, {})); + const toBlock = (await getBlock(toTimestamp, _chain, {})); + + const logs: ILog[][] = (await Promise.all(lpTokens.map((address: string) => sdk.getEventLogs({ + target: address, + toBlock: toBlock, + fromBlock: fromBlock, + chain: _chain, + topics: [topic0] + })))) as any; + + const rawCoins = [...tokens0, ...tokens1].map((e: string) => `${_chain}:${e}`); + const coins = [...new Set(rawCoins)] + const prices = await getPrices(coins, timestamp); + + + const untrackVolumes: number[] = lpTokens.map((_: string, index: number) => { + const token0Decimals = prices[`${_chain}:${tokens0[index]}`]?.decimals || 0 + const token1Decimals = prices[`${_chain}:${tokens1[index]}`]?.decimals || 0 + const log: IAmount[] = logs[index] + .map((e: ILog) => { return { ...e } }) + .map((p: ILog) => { + const value = contract_interface.parseLog(p); + const amountInX = Number('0x' + '0'.repeat(32) + value!.args.amountsIn.replace('0x', '').slice(0, 32)) / 10 ** token1Decimals + const amountInY = Number('0x' + '0'.repeat(32) + value!.args.amountsIn.replace('0x', '').slice(32, 64)) / 10 ** token0Decimals + return { + amountInX, + amountInY, + } as IAmount + }) as IAmount[]; + + const token0Price = (prices[`${_chain}:${tokens0[index]}`]?.price || 0); + const token1Price = (prices[`${_chain}:${tokens1[index]}`]?.price || 0); + const totalAmountInX = log + .reduce((a: number, b: IAmount) => Number(b.amountInX) + a, 0) * token1Price; + const totalAmountInY = log + .reduce((a: number, b: IAmount) => Number(b.amountInY) + a, 0) * token0Price; + const untrackAmountUSD = (totalAmountInX + totalAmountInY); // counted only we have price data + return untrackAmountUSD; + }); + const dailyVolume = untrackVolumes.reduce((a: number, b: number) => a + b, 0); + return { + dailyVolume: `${dailyVolume}`, + timestamp, + }; } } diff --git a/dexs/gains-network/index.ts b/dexs/gains-network/index.ts index 8cb7aaf24a..c68a5167d1 100644 --- a/dexs/gains-network/index.ts +++ b/dexs/gains-network/index.ts @@ -48,65 +48,60 @@ const fetch = (chain: Chain) => { const fromBlock = await getBlock(fromTimestamp, chain, {}); const toBlock = await getBlock(toTimestamp, chain, {}); - try { - const limitLogs: ILog[] = ( - (await Promise.all( - topic0_limit_ex.map(async (topic0) => - sdk.getEventLogs({ - targets: contract_addresses[chain], - toBlock: toBlock, - fromBlock: fromBlock, - chain: chain, - topics: [topic0], - }) - ) - )) as ILog[][] - ).reduce((acc, curr) => [...acc, ...curr], []); + const limitLogs: ILog[] = ( + (await Promise.all( + topic0_limit_ex.map(async (topic0) => + sdk.getEventLogs({ + targets: contract_addresses[chain], + toBlock: toBlock, + fromBlock: fromBlock, + chain: chain, + topics: [topic0], + }) + ) + )) as ILog[][] + ).reduce((acc, curr) => [...acc, ...curr], []); - const marketLogs: ILog[] = ( - (await Promise.all( - topic0_market_ex.map(async (topic0) => - sdk.getEventLogs({ - targets: contract_addresses[chain], - toBlock: toBlock, - fromBlock: fromBlock, - chain: chain, - topics: [topic0], - }) - ) - )) as ILog[][] - ).reduce((acc, curr) => [...acc, ...curr], []); + const marketLogs: ILog[] = ( + (await Promise.all( + topic0_market_ex.map(async (topic0) => + sdk.getEventLogs({ + targets: contract_addresses[chain], + toBlock: toBlock, + fromBlock: fromBlock, + chain: chain, + topics: [topic0], + }) + ) + )) as ILog[][] + ).reduce((acc, curr) => [...acc, ...curr], []); - const limit_volume = limitLogs - .map((e: ILog) => { - const data = e.data.replace("0x", ""); - const leverage = Number("0x" + data.slice(512, 576)); - const positionSizeDai = Number("0x" + data.slice(896, 960)) / (precisionException[e.address] ?? 1e18); - const collateralPrice = (data.length === 1216 ? Number("0x" + data.slice(1088, 1152)) : 1e8) / 1e8; - return leverage * positionSizeDai * collateralPrice; - }) - .reduce((a: number, b: number) => a + b, 0); + const limit_volume = limitLogs + .map((e: ILog) => { + const data = e.data.replace("0x", ""); + const leverage = Number("0x" + data.slice(512, 576)); + const positionSizeDai = Number("0x" + data.slice(896, 960)) / (precisionException[e.address] ?? 1e18); + const collateralPrice = (data.length === 1216 ? Number("0x" + data.slice(1088, 1152)) : 1e8) / 1e8; + return leverage * positionSizeDai * collateralPrice; + }) + .reduce((a: number, b: number) => a + b, 0); - const market_volume = marketLogs - .map((e: ILog) => { - const data = e.data.replace("0x", ""); - const leverage = Number("0x" + data.slice(448, 512)); - const positionSizeDai = Number("0x" + data.slice(832, 896)) / (precisionException[e.address] ?? 1e18); - const collateralPrice = (data.length === 1088 ? Number("0x" + data.slice(1024, 1088)) : 1e8) / 1e8; - return leverage * positionSizeDai * collateralPrice; - }) - .reduce((a: number, b: number) => a + b, 0); + const market_volume = marketLogs + .map((e: ILog) => { + const data = e.data.replace("0x", ""); + const leverage = Number("0x" + data.slice(448, 512)); + const positionSizeDai = Number("0x" + data.slice(832, 896)) / (precisionException[e.address] ?? 1e18); + const collateralPrice = (data.length === 1088 ? Number("0x" + data.slice(1024, 1088)) : 1e8) / 1e8; + return leverage * positionSizeDai * collateralPrice; + }) + .reduce((a: number, b: number) => a + b, 0); - const dailyVolume = limit_volume + market_volume; + const dailyVolume = limit_volume + market_volume; - return { - dailyVolume: `${dailyVolume}`, - timestamp, - }; - } catch (error) { - console.error(error); - throw error; - } + return { + dailyVolume: `${dailyVolume}`, + timestamp, + }; }; }; diff --git a/dexs/gambit/index.ts b/dexs/gambit/index.ts index e362d94f4c..ea6bc5abcb 100644 --- a/dexs/gambit/index.ts +++ b/dexs/gambit/index.ts @@ -33,63 +33,58 @@ const fetch = (chain: Chain) => { const fromBlock = (await getBlock(fromTimestamp, chain, {})); const toBlock = (await getBlock(toTimestamp, chain, {})); const contractAddressList = CONTRACT_ADDRESS[chain]; - try { - const logs_limit_ex: ILog[] = ( - await Promise.all( - contractAddressList.map(async (address) => { - return sdk.getEventLogs({ - target: address, - toBlock: toBlock, - fromBlock: fromBlock, - chain: chain, - topics: [topic0_limit_ex], - }); - }) - ) - ).flatMap((response) => (response as any)) as ILog[]; + const logs_limit_ex: ILog[] = ( + await Promise.all( + contractAddressList.map(async (address) => { + return sdk.getEventLogs({ + target: address, + toBlock: toBlock, + fromBlock: fromBlock, + chain: chain, + topics: [topic0_limit_ex], + }); + }) + ) + ).flatMap((response) => (response as any)) as ILog[]; - const logs_market_ex: ILog[] = ( - await Promise.all( - contractAddressList.map(async (address) => { - return sdk.getEventLogs({ - target: address, - toBlock: toBlock, - fromBlock: fromBlock, - chain: chain, - topics: [topic0_market_ex], - }); - }) - ) - ).flatMap((response) => (response as any)) as ILog[]; + const logs_market_ex: ILog[] = ( + await Promise.all( + contractAddressList.map(async (address) => { + return sdk.getEventLogs({ + target: address, + toBlock: toBlock, + fromBlock: fromBlock, + chain: chain, + topics: [topic0_market_ex], + }); + }) + ) + ).flatMap((response) => (response as any)) as ILog[]; - const limit_volume = logs_limit_ex.map((e: ILog) => { - const data = e.data.replace('0x', ''); - let leverage = Number('0x' + data.slice(448, 512)); - if (leverage > 1000) { - leverage = leverage / 10 ** LEVERAGE_DECIMAL - } - const positionSizeUsdc = Number('0x' + data.slice(896, 960)) / 10 ** USDC_DECIMAL; - return (leverage * positionSizeUsdc) - }).reduce((a: number, b: number) => a + b, 0); - - const market_volume = logs_market_ex.map((e: ILog) => { - const data = e.data.replace('0x', ''); - let leverage = Number('0x' + data.slice(448, 512)); - if (leverage > 1000) { - leverage = leverage / 10 ** LEVERAGE_DECIMAL - } - const positionSizeUsdc = Number('0x' + data.slice(832, 896)) / 10 ** USDC_DECIMAL; - return (leverage * positionSizeUsdc) - }).reduce((a: number, b: number) => a + b, 0); + const limit_volume = logs_limit_ex.map((e: ILog) => { + const data = e.data.replace('0x', ''); + let leverage = Number('0x' + data.slice(448, 512)); + if (leverage > 1000) { + leverage = leverage / 10 ** LEVERAGE_DECIMAL + } + const positionSizeUsdc = Number('0x' + data.slice(896, 960)) / 10 ** USDC_DECIMAL; + return (leverage * positionSizeUsdc) + }).reduce((a: number, b: number) => a + b, 0); - const dailyVolume = (limit_volume + market_volume) - return { - dailyVolume: `${dailyVolume}`, - timestamp + const market_volume = logs_market_ex.map((e: ILog) => { + const data = e.data.replace('0x', ''); + let leverage = Number('0x' + data.slice(448, 512)); + if (leverage > 1000) { + leverage = leverage / 10 ** LEVERAGE_DECIMAL } - } catch (error) { - console.error(error) - throw error; + const positionSizeUsdc = Number('0x' + data.slice(832, 896)) / 10 ** USDC_DECIMAL; + return (leverage * positionSizeUsdc) + }).reduce((a: number, b: number) => a + b, 0); + + const dailyVolume = (limit_volume + market_volume) + return { + dailyVolume: `${dailyVolume}`, + timestamp } } } diff --git a/dexs/gmx-v2-trade/index.ts b/dexs/gmx-v2-trade/index.ts index 69bbe635dd..1383f185f0 100644 --- a/dexs/gmx-v2-trade/index.ts +++ b/dexs/gmx-v2-trade/index.ts @@ -19,7 +19,7 @@ const topic1_des = '0x07d51b51b408d7c62dcc47cc558da5ce6a6e0fd129a427ebce150f52b0 const topic0_fees = '0x137a44067c8961cd7e1d876f4754a5a3a75989b4552f1843fc69c3b372def160'; const topic1_fees = '0xe096982abd597114bdaa4a60612f87fabfcc7206aa12d61c50e7ba1e6c291100'; -type TChain = { +type TChain = { [s: Chain | string]: string; } @@ -29,68 +29,63 @@ const contract: TChain = { } const fetch = (chain: Chain) => { - return async (timestamp: number): Promise => { - const fromTimestamp = timestamp - 60 * 60 * 24 - const toTimestamp = timestamp - try { - const fromBlock = (await getBlock(fromTimestamp, chain, {})); - const toBlock = (await getBlock(toTimestamp, chain, {})); - - const posistion_logs: ILog[] = (await sdk.getEventLogs({ - target: contract[chain], - toBlock: toBlock, - fromBlock: fromBlock, - chain: chain, - topics: [topic0_ins, topic1_ins] - }))as ILog[]; - - const decress_logs: ILog[] = (await sdk.getEventLogs({ - target: contract[chain], - toBlock: toBlock, - fromBlock: fromBlock, - chain: chain, - topics: [topic0_des, topic1_des] - }))as ILog[]; - - // const fees_logs: ILog[] = (await sdk.getEventLogs({ - // target: contract[chain], - // toBlock: toBlock, - // fromBlock: fromBlock, - // chain: chain, - // topics: [topic0_fees, topic1_fees] - // }))as ILog[]; - - let hash: string[] = []; - const raw_des = decress_logs.map((e: ILog) => { - const data = e.data.replace('0x', ''); - const volume = data.slice(102 * 64, (102 * 64) + 64); - const key = Number('0x'+data.slice(118 * 64, (118 * 64) + 64)); - if (key === 7) return 0; - hash.push(e.transactionHash); - // 156 - return Number('0x'+volume) / 1e30; - }) - - const raw_in = posistion_logs.filter(e => !hash.includes(e.transactionHash)).map((e: ILog) => { - const data = e.data.replace('0x', ''); - const volume = data.slice(100 * 64, (100 * 64) + 64); - return Number('0x'+volume) / 1e30; - }) - - - - const dailyVolume: number = [...raw_des, ...raw_in] - .reduce((a: number, b: number) => a+b, 0); - - return { - dailyVolume: `${dailyVolume}`, - timestamp - } - } catch (error) { - console.error(error); - throw error; - } + return async (timestamp: number): Promise => { + const fromTimestamp = timestamp - 60 * 60 * 24 + const toTimestamp = timestamp + const fromBlock = (await getBlock(fromTimestamp, chain, {})); + const toBlock = (await getBlock(toTimestamp, chain, {})); + + const posistion_logs: ILog[] = (await sdk.getEventLogs({ + target: contract[chain], + toBlock: toBlock, + fromBlock: fromBlock, + chain: chain, + topics: [topic0_ins, topic1_ins] + })) as ILog[]; + + const decress_logs: ILog[] = (await sdk.getEventLogs({ + target: contract[chain], + toBlock: toBlock, + fromBlock: fromBlock, + chain: chain, + topics: [topic0_des, topic1_des] + })) as ILog[]; + + // const fees_logs: ILog[] = (await sdk.getEventLogs({ + // target: contract[chain], + // toBlock: toBlock, + // fromBlock: fromBlock, + // chain: chain, + // topics: [topic0_fees, topic1_fees] + // }))as ILog[]; + + let hash: string[] = []; + const raw_des = decress_logs.map((e: ILog) => { + const data = e.data.replace('0x', ''); + const volume = data.slice(102 * 64, (102 * 64) + 64); + const key = Number('0x' + data.slice(118 * 64, (118 * 64) + 64)); + if (key === 7) return 0; + hash.push(e.transactionHash); + // 156 + return Number('0x' + volume) / 1e30; + }) + + const raw_in = posistion_logs.filter(e => !hash.includes(e.transactionHash)).map((e: ILog) => { + const data = e.data.replace('0x', ''); + const volume = data.slice(100 * 64, (100 * 64) + 64); + return Number('0x' + volume) / 1e30; + }) + + + + const dailyVolume: number = [...raw_des, ...raw_in] + .reduce((a: number, b: number) => a + b, 0); + + return { + dailyVolume: `${dailyVolume}`, + timestamp } + } } diff --git a/dexs/joe-v2.1/index.ts b/dexs/joe-v2.1/index.ts index 0ef5e0cd2f..064290a219 100644 --- a/dexs/joe-v2.1/index.ts +++ b/dexs/joe-v2.1/index.ts @@ -4,7 +4,7 @@ import * as sdk from "@defillama/sdk"; import { getBlock } from "../../helpers/getBlock"; import { getPrices } from "../../utils/prices"; import { Chain } from "@defillama/sdk/build/general"; -import { ethers, } from "ethers"; +import { ethers, } from "ethers"; interface ILog { data: string; @@ -70,69 +70,64 @@ const graph = (chain: Chain) => { return async (timestamp: number) => { const fromTimestamp = timestamp - 60 * 60 * 24 const toTimestamp = timestamp - try { - const lpTokens = pools[chain] - const [underlyingToken0, underlyingToken1] = await Promise.all( - ['address:getTokenX', 'address:getTokenY'].map((abi: string) => - sdk.api2.abi.multiCall({ - abi, - calls: lpTokens, - chain: chain - }) - ) - ); + const lpTokens = pools[chain] + const [underlyingToken0, underlyingToken1] = await Promise.all( + ['address:getTokenX', 'address:getTokenY'].map((abi: string) => + sdk.api2.abi.multiCall({ + abi, + calls: lpTokens, + chain: chain + }) + ) + ); - const tokens0 = underlyingToken0; - const tokens1 = underlyingToken1; - const fromBlock = (await getBlock(fromTimestamp, chain, {})); - const toBlock = (await getBlock(toTimestamp, chain, {})); + const tokens0 = underlyingToken0; + const tokens1 = underlyingToken1; + const fromBlock = (await getBlock(fromTimestamp, chain, {})); + const toBlock = (await getBlock(toTimestamp, chain, {})); - const logs: ILog[][] = (await Promise.all(lpTokens.map((address: string) => sdk.getEventLogs({ - target: address, - toBlock: toBlock, - fromBlock: fromBlock, - chain: chain, - topics: [topic0] - })))) as ILog[][]; + const logs: ILog[][] = (await Promise.all(lpTokens.map((address: string) => sdk.getEventLogs({ + target: address, + toBlock: toBlock, + fromBlock: fromBlock, + chain: chain, + topics: [topic0] + })))) as ILog[][]; - const rawCoins = [...tokens0, ...tokens1].map((e: string) => `${chain}:${e}`); - const coins = [...new Set(rawCoins)] - const prices = await getPrices(coins, timestamp); + const rawCoins = [...tokens0, ...tokens1].map((e: string) => `${chain}:${e}`); + const coins = [...new Set(rawCoins)] + const prices = await getPrices(coins, timestamp); - const untrackVolumes: number[] = lpTokens.map((_: string, index: number) => { - const token0Decimals = prices[`${chain}:${tokens0[index]}`]?.decimals || 0 - const token1Decimals = prices[`${chain}:${tokens1[index]}`]?.decimals || 0 - const log: IAmount[] = logs[index] - .map((e: ILog) => { return { ...e } }) - .map((p: ILog) => { - const value = contract_interface.parseLog(p); - const amountInX = Number('0x'+'0'.repeat(32)+value!.args.amountsIn.replace('0x', '').slice(0, 32)) / 10 ** token1Decimals - const amountInY = Number('0x'+'0'.repeat(32)+value!.args.amountsIn.replace('0x', '').slice(32, 64)) / 10 ** token0Decimals - return { - amountInX, - amountInY, - } as IAmount - }) as IAmount[]; + const untrackVolumes: number[] = lpTokens.map((_: string, index: number) => { + const token0Decimals = prices[`${chain}:${tokens0[index]}`]?.decimals || 0 + const token1Decimals = prices[`${chain}:${tokens1[index]}`]?.decimals || 0 + const log: IAmount[] = logs[index] + .map((e: ILog) => { return { ...e } }) + .map((p: ILog) => { + const value = contract_interface.parseLog(p); + const amountInX = Number('0x' + '0'.repeat(32) + value!.args.amountsIn.replace('0x', '').slice(0, 32)) / 10 ** token1Decimals + const amountInY = Number('0x' + '0'.repeat(32) + value!.args.amountsIn.replace('0x', '').slice(32, 64)) / 10 ** token0Decimals + return { + amountInX, + amountInY, + } as IAmount + }) as IAmount[]; - const token0Price = (prices[`${chain}:${tokens0[index]}`]?.price || 0); - const token1Price = (prices[`${chain}:${tokens1[index]}`]?.price || 0); - const totalAmountInX = log - .reduce((a: number, b: IAmount) => Number(b.amountInX) + a, 0) * token1Price; - const totalAmountInY = log - .reduce((a: number, b: IAmount) => Number(b.amountInY) + a, 0) * token0Price; - const untrackAmountUSD = (totalAmountInX + totalAmountInY); // counted only we have price data - return untrackAmountUSD; - }); - const dailyVolume = untrackVolumes.reduce((a: number, b: number) => a + b, 0); - return { - dailyVolume: `${dailyVolume}`, - timestamp, - }; - } catch(error) { - console.error(error); - throw error; - } + const token0Price = (prices[`${chain}:${tokens0[index]}`]?.price || 0); + const token1Price = (prices[`${chain}:${tokens1[index]}`]?.price || 0); + const totalAmountInX = log + .reduce((a: number, b: IAmount) => Number(b.amountInX) + a, 0) * token1Price; + const totalAmountInY = log + .reduce((a: number, b: IAmount) => Number(b.amountInY) + a, 0) * token0Price; + const untrackAmountUSD = (totalAmountInX + totalAmountInY); // counted only we have price data + return untrackAmountUSD; + }); + const dailyVolume = untrackVolumes.reduce((a: number, b: number) => a + b, 0); + return { + dailyVolume: `${dailyVolume}`, + timestamp, + }; } } diff --git a/dexs/jupiter-perpetual/index.ts b/dexs/jupiter-perpetual/index.ts index 640fb45847..f788c093d2 100644 --- a/dexs/jupiter-perpetual/index.ts +++ b/dexs/jupiter-perpetual/index.ts @@ -5,19 +5,12 @@ import { queryDune } from "../../helpers/dune"; const fetch = async (timestamp: number): Promise => { const unixTimestamp = getUniqStartOfTodayTimestamp(new Date(timestamp * 1000)); - try { - // 3385640 old query id - const data = await queryDune("3391484", { endTime: unixTimestamp + 86400 }); - return { - dailyVolume: data?.volume || "0", - timestamp: unixTimestamp, - }; - } catch (e: any) { - return { - dailyVolume: "0", - timestamp: unixTimestamp, - }; - } + // 3385640 old query id + const data = await queryDune("3391484", { endTime: unixTimestamp + 86400 }); + return { + dailyVolume: data.volume, + timestamp: unixTimestamp, + }; }; const adapter = { diff --git a/dexs/panacakeswap-perp/index.ts b/dexs/panacakeswap-perp/index.ts index 83ade6af79..500f3f88cd 100644 --- a/dexs/panacakeswap-perp/index.ts +++ b/dexs/panacakeswap-perp/index.ts @@ -14,7 +14,7 @@ type TBrokerID = { } const brokerID: TBrokerID = { [CHAIN.BSC]: [2], - [CHAIN.ARBITRUM]: [1,2] + [CHAIN.ARBITRUM]: [1, 2] } const contract_address: TID = { [CHAIN.BSC]: '2826941', @@ -35,21 +35,16 @@ interface IData { const fetchVolume = (chain: Chain) => { return async (timestamp: number) => { - try { - const dayTimestamp = getUniqStartOfTodayTimestamp(new Date(timestamp * 1000)); - const dateString = new Date(dayTimestamp * 1000).toISOString().split("T")[0]; - const query: IData[] = (await queryDune(contract_address[chain])) - // const query: IData[] = require(`./${chain}.json`); - const dailyVolume = query.find((e: IData) => e.dt.split(' ')[0] === dateString)?.volume; + const dayTimestamp = getUniqStartOfTodayTimestamp(new Date(timestamp * 1000)); + const dateString = new Date(dayTimestamp * 1000).toISOString().split("T")[0]; + const query: IData[] = (await queryDune(contract_address[chain])) + // const query: IData[] = require(`./${chain}.json`); + const dailyVolume = query.find((e: IData) => e.dt.split(' ')[0] === dateString)?.volume; - return { - dailyVolume: `${dailyVolume}`, - timestamp, - }; - } catch (error) { - console.error(error); - throw error; - } + return { + dailyVolume: `${dailyVolume}`, + timestamp, + }; }; }; diff --git a/dexs/primex-finance/index.ts b/dexs/primex-finance/index.ts index 410550ac53..ccc882b80e 100644 --- a/dexs/primex-finance/index.ts +++ b/dexs/primex-finance/index.ts @@ -36,127 +36,122 @@ const fetch = (chain: string) => async (timestamp: number): Promise { - return (await Promise.all(targets.map(target => { - return sdk.getEventLogs({ - target, - toBlock: toBlock, - fromBlock: fromBlock, - chain, - topics - }) - }))).map(r => r as ethers.Log[]).flat() - }))) - - const swapTokens: string[] = swapLogs - .map((log: ethers.Log) => { - const parsedLog = contractInterface.parseLog(log as any); - const tokenA = parsedLog!.args.tokenA.toLowerCase(); - return tokenA - }); - - const openPositionTokens: string[] = openPositionLogs - .map((log: ethers.Log) => { - const parsedLog = contractInterface.parseLog(log as any); - const soldAsset = parsedLog!.args.position.soldAsset.toLowerCase(); - return soldAsset - }); - - const closePositionTokens: string[] = closePositionLogs - .map((log: ethers.Log) => { - const parsedLog = contractInterface.parseLog(log as any); - const soldAsset = parsedLog!.args.soldAsset.toLowerCase(); - return soldAsset + const fromBlock = (await getBlock(fromTimestamp, chain, {})); + const toBlock = (await getBlock(toTimestamp, chain, {})); + + const [swapLogs, openPositionLogs, closePositionLogs, partiallyClosePositionLogs, closePositionBatchLogs] = (await Promise.all(logsConfig.map(async ({ targets, topics }) => { + return (await Promise.all(targets.map(target => { + return sdk.getEventLogs({ + target, + toBlock: toBlock, + fromBlock: fromBlock, + chain, + topics }) - - const partiallyClosePositionTokens: string[] = partiallyClosePositionLogs - .map((log: ethers.Log) => { - const parsedLog = contractInterface.parseLog(log as any); - const soldAsset = parsedLog!.args.soldAsset.toLowerCase(); - return soldAsset - }) - - const closePositionBatchTokens: string[] = closePositionBatchLogs - .map((log: ethers.Log) => { - const parsedLog = contractInterface.parseLog(log as any); - const soldAsset = parsedLog!.args.soldAsset.toLowerCase(); - return soldAsset - }) - - const uniqueTokens = Array.from(new Set(swapTokens.concat(openPositionTokens, closePositionTokens, partiallyClosePositionTokens, closePositionBatchTokens))) - - const priceKeys = uniqueTokens.map((t) => `${chain}:${t}`) - const prices = await getPrices(priceKeys, timestamp); - - const swapVolumeUSD: number = swapLogs - .map((log: ethers.Log) => { - const parsedLog = contractInterface.parseLog(log as any); - const amountSold = Number(parsedLog!.args.amountSold); - const tokenA = parsedLog!.args.tokenA; - const priceA = prices[`${chain}:${tokenA.toLowerCase()}`]?.price || 0; - const decimalsA = prices[`${chain}:${tokenA.toLowerCase()}`]?.decimals || 0; - return (amountSold / 10 ** decimalsA) * priceA; - }) - .reduce((a: number, b: number) => a + b, 0) - - const openPositionVolumeUSD: number = openPositionLogs - .map((log: ethers.Log) => { - const parsedLog = contractInterface.parseLog(log as any); - const soldAsset = parsedLog!.args.position.soldAsset; - const priceSoldAsset = prices[`${chain}:${soldAsset.toLowerCase()}`]?.price || 0; - const decimalsSoldAsset = prices[`${chain}:${soldAsset.toLowerCase()}`]?.decimals || 0; - const depositAmountInSoldAsset = Number(parsedLog!.args.position.depositAmountInSoldAsset) / 10 ** decimalsSoldAsset; - const leverage = Number(parsedLog!.args.leverage) / 10 ** 18 - return depositAmountInSoldAsset * leverage * priceSoldAsset; - }) - .reduce((a: number, b: number) => a + b, 0) - - const closePositionVolumeUSD: number = closePositionLogs - .map((log: ethers.Log) => { - const parsedLog = contractInterface.parseLog(log as any); - const soldAsset = parsedLog!.args.soldAsset; - const priceSoldAsset = prices[`${chain}:${soldAsset.toLowerCase()}`]?.price || 0; - const decimalsSoldAsset = prices[`${chain}:${soldAsset.toLowerCase()}`]?.decimals || 0; - const amountOut = Number(parsedLog!.args.amountOut) / 10 ** decimalsSoldAsset; - return amountOut * priceSoldAsset; - }) - .reduce((a: number, b: number) => a + b, 0) - - const partiallyClosePositionVolumeUSD: number = partiallyClosePositionLogs - .map((log: ethers.Log) => { - const parsedLog = contractInterface.parseLog(log as any); - const soldAsset = parsedLog!.args.soldAsset; - const priceSoldAsset = prices[`${chain}:${soldAsset.toLowerCase()}`]?.price || 0; - const decimalsSoldAsset = prices[`${chain}:${soldAsset.toLowerCase()}`]?.decimals || 0; - const amountOut = Number(parsedLog!.args.amountOut) / 10 ** decimalsSoldAsset; - return amountOut * priceSoldAsset; - }) - .reduce((a: number, b: number) => a + b, 0) - - const closePositionBatchVolumeUSD: number = closePositionBatchLogs - .map((log: ethers.Log) => { - const parsedLog = contractInterface.parseLog(log as any); - const soldAsset = parsedLog!.args.soldAsset; - const priceSoldAsset = prices[`${chain}:${soldAsset.toLowerCase()}`]?.price || 0; - const decimalsSoldAsset = prices[`${chain}:${soldAsset.toLowerCase()}`]?.decimals || 0; - const amountOut = Number(parsedLog!.args.amountOut) / 10 ** decimalsSoldAsset; - return amountOut * priceSoldAsset; - }) - .reduce((a: number, b: number) => a + b, 0) - - const dailyVolume = swapVolumeUSD + openPositionVolumeUSD + closePositionVolumeUSD + partiallyClosePositionVolumeUSD + closePositionBatchVolumeUSD - - return { - dailyVolume: `${dailyVolume}`, - timestamp - } - } catch(e) { - console.error(e) - throw e; + }))).map(r => r as ethers.Log[]).flat() + }))) + + const swapTokens: string[] = swapLogs + .map((log: ethers.Log) => { + const parsedLog = contractInterface.parseLog(log as any); + const tokenA = parsedLog!.args.tokenA.toLowerCase(); + return tokenA + }); + + const openPositionTokens: string[] = openPositionLogs + .map((log: ethers.Log) => { + const parsedLog = contractInterface.parseLog(log as any); + const soldAsset = parsedLog!.args.position.soldAsset.toLowerCase(); + return soldAsset + }); + + const closePositionTokens: string[] = closePositionLogs + .map((log: ethers.Log) => { + const parsedLog = contractInterface.parseLog(log as any); + const soldAsset = parsedLog!.args.soldAsset.toLowerCase(); + return soldAsset + }) + + const partiallyClosePositionTokens: string[] = partiallyClosePositionLogs + .map((log: ethers.Log) => { + const parsedLog = contractInterface.parseLog(log as any); + const soldAsset = parsedLog!.args.soldAsset.toLowerCase(); + return soldAsset + }) + + const closePositionBatchTokens: string[] = closePositionBatchLogs + .map((log: ethers.Log) => { + const parsedLog = contractInterface.parseLog(log as any); + const soldAsset = parsedLog!.args.soldAsset.toLowerCase(); + return soldAsset + }) + + const uniqueTokens = Array.from(new Set(swapTokens.concat(openPositionTokens, closePositionTokens, partiallyClosePositionTokens, closePositionBatchTokens))) + + const priceKeys = uniqueTokens.map((t) => `${chain}:${t}`) + const prices = await getPrices(priceKeys, timestamp); + + const swapVolumeUSD: number = swapLogs + .map((log: ethers.Log) => { + const parsedLog = contractInterface.parseLog(log as any); + const amountSold = Number(parsedLog!.args.amountSold); + const tokenA = parsedLog!.args.tokenA; + const priceA = prices[`${chain}:${tokenA.toLowerCase()}`]?.price || 0; + const decimalsA = prices[`${chain}:${tokenA.toLowerCase()}`]?.decimals || 0; + return (amountSold / 10 ** decimalsA) * priceA; + }) + .reduce((a: number, b: number) => a + b, 0) + + const openPositionVolumeUSD: number = openPositionLogs + .map((log: ethers.Log) => { + const parsedLog = contractInterface.parseLog(log as any); + const soldAsset = parsedLog!.args.position.soldAsset; + const priceSoldAsset = prices[`${chain}:${soldAsset.toLowerCase()}`]?.price || 0; + const decimalsSoldAsset = prices[`${chain}:${soldAsset.toLowerCase()}`]?.decimals || 0; + const depositAmountInSoldAsset = Number(parsedLog!.args.position.depositAmountInSoldAsset) / 10 ** decimalsSoldAsset; + const leverage = Number(parsedLog!.args.leverage) / 10 ** 18 + return depositAmountInSoldAsset * leverage * priceSoldAsset; + }) + .reduce((a: number, b: number) => a + b, 0) + + const closePositionVolumeUSD: number = closePositionLogs + .map((log: ethers.Log) => { + const parsedLog = contractInterface.parseLog(log as any); + const soldAsset = parsedLog!.args.soldAsset; + const priceSoldAsset = prices[`${chain}:${soldAsset.toLowerCase()}`]?.price || 0; + const decimalsSoldAsset = prices[`${chain}:${soldAsset.toLowerCase()}`]?.decimals || 0; + const amountOut = Number(parsedLog!.args.amountOut) / 10 ** decimalsSoldAsset; + return amountOut * priceSoldAsset; + }) + .reduce((a: number, b: number) => a + b, 0) + + const partiallyClosePositionVolumeUSD: number = partiallyClosePositionLogs + .map((log: ethers.Log) => { + const parsedLog = contractInterface.parseLog(log as any); + const soldAsset = parsedLog!.args.soldAsset; + const priceSoldAsset = prices[`${chain}:${soldAsset.toLowerCase()}`]?.price || 0; + const decimalsSoldAsset = prices[`${chain}:${soldAsset.toLowerCase()}`]?.decimals || 0; + const amountOut = Number(parsedLog!.args.amountOut) / 10 ** decimalsSoldAsset; + return amountOut * priceSoldAsset; + }) + .reduce((a: number, b: number) => a + b, 0) + + const closePositionBatchVolumeUSD: number = closePositionBatchLogs + .map((log: ethers.Log) => { + const parsedLog = contractInterface.parseLog(log as any); + const soldAsset = parsedLog!.args.soldAsset; + const priceSoldAsset = prices[`${chain}:${soldAsset.toLowerCase()}`]?.price || 0; + const decimalsSoldAsset = prices[`${chain}:${soldAsset.toLowerCase()}`]?.decimals || 0; + const amountOut = Number(parsedLog!.args.amountOut) / 10 ** decimalsSoldAsset; + return amountOut * priceSoldAsset; + }) + .reduce((a: number, b: number) => a + b, 0) + + const dailyVolume = swapVolumeUSD + openPositionVolumeUSD + closePositionVolumeUSD + partiallyClosePositionVolumeUSD + closePositionBatchVolumeUSD + + return { + dailyVolume: `${dailyVolume}`, + timestamp } } diff --git a/dexs/slingshot/index.ts b/dexs/slingshot/index.ts index 58b71951db..4fa20051f9 100644 --- a/dexs/slingshot/index.ts +++ b/dexs/slingshot/index.ts @@ -5,7 +5,7 @@ import { getBlock } from "../../helpers/getBlock"; import * as sdk from "@defillama/sdk"; import { getPrices } from "../../utils/prices"; -type TContract = { +type TContract = { [s: string | Chain]: string[]; } const topic0 = '0x899a8968d68f840cf01fdaf129bf72e96ca51b8ecad8c4f7566938e7a2ba6bcf'; @@ -46,53 +46,48 @@ interface ISwap { } const fetchVolume = (chain: Chain) => { return async (timestamp: number): Promise => { - try { - const fromTimestamp = timestamp - 60 * 60 * 24 - const toTimestamp = timestamp - const fromBlock = (await getBlock(fromTimestamp, chain, {})); - const toBlock = (await getBlock(toTimestamp, chain, {})); - const logs: ILog[] = (await Promise.all(contract_address[chain].map((address: string) => sdk.getEventLogs({ - target: address, - toBlock: toBlock, - fromBlock: fromBlock, - chain: chain, - topics: [topic0] - })))).flat(); - const rawData: ISwap[] = logs.map((log: ILog) => { - const data = log.data.replace('0x', ''); - const token0 = data.slice(0, 64); - const token1 = data.slice(64, 128); - const token0Amount = Number('0x'+data.slice(128, 192)); - const token1Amount = Number('0x'+data.slice(192, 256)); - const token0Address = `0x${token0.slice(24, 64)}`; - const token1Address = `0x${token1.slice(24, 64)}`; - return { - token0Address, - token1Address, - token0Amount, - token1Amount - } - }) - const coins = [...new Set(rawData.map((e: ISwap) => `${chain}:${e.token0Address}`).concat(rawData.map((e: ISwap) => `${chain}:${e.token1Address}`)))]; - const prices = await getPrices(coins, timestamp); - const volume: number[] = rawData.map((e: ISwap) => { - const token0Price = prices[`${chain}:${e.token0Address}`]?.price || 0; - const token1Price = prices[`${chain}:${e.token1Address}`]?.price || 0; - const token0Decimals = prices[`${chain}:${e.token0Address}`]?.decimals || 0; - const token1Decimals = prices[`${chain}:${e.token1Address}`]?.decimals || 0; - const token0Value = token0Price * (Number(e.token0Amount) / 10 ** token0Decimals); - const token1Value = token1Price * (Number(e.token1Amount) / 10 ** token1Decimals); - const untrackAmountUSD = token0Price !== 0 ? token0Value : token1Price !== 0 ? token1Value : 0; - return untrackAmountUSD; - }) - const dailyVolume = volume.reduce((a: number, b: number) => a + b, 0); + const fromTimestamp = timestamp - 60 * 60 * 24 + const toTimestamp = timestamp + const fromBlock = (await getBlock(fromTimestamp, chain, {})); + const toBlock = (await getBlock(toTimestamp, chain, {})); + const logs: ILog[] = (await Promise.all(contract_address[chain].map((address: string) => sdk.getEventLogs({ + target: address, + toBlock: toBlock, + fromBlock: fromBlock, + chain: chain, + topics: [topic0] + })))).flat(); + const rawData: ISwap[] = logs.map((log: ILog) => { + const data = log.data.replace('0x', ''); + const token0 = data.slice(0, 64); + const token1 = data.slice(64, 128); + const token0Amount = Number('0x' + data.slice(128, 192)); + const token1Amount = Number('0x' + data.slice(192, 256)); + const token0Address = `0x${token0.slice(24, 64)}`; + const token1Address = `0x${token1.slice(24, 64)}`; return { - dailyVolume: `${dailyVolume}`, - timestamp + token0Address, + token1Address, + token0Amount, + token1Amount } - } catch (error) { - console.error(error); - throw error; + }) + const coins = [...new Set(rawData.map((e: ISwap) => `${chain}:${e.token0Address}`).concat(rawData.map((e: ISwap) => `${chain}:${e.token1Address}`)))]; + const prices = await getPrices(coins, timestamp); + const volume: number[] = rawData.map((e: ISwap) => { + const token0Price = prices[`${chain}:${e.token0Address}`]?.price || 0; + const token1Price = prices[`${chain}:${e.token1Address}`]?.price || 0; + const token0Decimals = prices[`${chain}:${e.token0Address}`]?.decimals || 0; + const token1Decimals = prices[`${chain}:${e.token1Address}`]?.decimals || 0; + const token0Value = token0Price * (Number(e.token0Amount) / 10 ** token0Decimals); + const token1Value = token1Price * (Number(e.token1Amount) / 10 ** token1Decimals); + const untrackAmountUSD = token0Price !== 0 ? token0Value : token1Price !== 0 ? token1Value : 0; + return untrackAmountUSD; + }) + const dailyVolume = volume.reduce((a: number, b: number) => a + b, 0); + return { + dailyVolume: `${dailyVolume}`, + timestamp } } } diff --git a/dexs/synthetix/index.ts b/dexs/synthetix/index.ts index d41de05df4..1e7dcdd910 100644 --- a/dexs/synthetix/index.ts +++ b/dexs/synthetix/index.ts @@ -69,48 +69,43 @@ interface ILog { const fetchVolume = async (timestamp: number): Promise => { const fromTimestamp = timestamp - 60 * 60 * 24 const toTimestamp = timestamp - try { - const fromBlock = (await getBlock(fromTimestamp, CHAIN.OPTIMISM, {})); - const toBlock = (await getBlock(toTimestamp, CHAIN.OPTIMISM, {})); + const fromBlock = (await getBlock(fromTimestamp, CHAIN.OPTIMISM, {})); + const toBlock = (await getBlock(toTimestamp, CHAIN.OPTIMISM, {})); - const logs_modify: ILog[] = (await Promise.all(contracts.map((address: string) => sdk.getEventLogs({ - target: address, - toBlock: toBlock, - fromBlock: fromBlock, - chain: CHAIN.OPTIMISM, - topics: [topics0_modified_positions] - })))).flat(); - const contract_active: string[] = [...new Set(logs_modify.map((e: ILog) => e.address))] - const logs_liq: ILog[] = (await Promise.all(contract_active.map((address: string) => sdk.getEventLogs({ - target: address, - toBlock: toBlock, - fromBlock: fromBlock, - chain: CHAIN.OPTIMISM, - topics: [topics0_postions_liq] - })))).flat(); + const logs_modify: ILog[] = (await Promise.all(contracts.map((address: string) => sdk.getEventLogs({ + target: address, + toBlock: toBlock, + fromBlock: fromBlock, + chain: CHAIN.OPTIMISM, + topics: [topics0_modified_positions] + })))).flat(); + const contract_active: string[] = [...new Set(logs_modify.map((e: ILog) => e.address))] + const logs_liq: ILog[] = (await Promise.all(contract_active.map((address: string) => sdk.getEventLogs({ + target: address, + toBlock: toBlock, + fromBlock: fromBlock, + chain: CHAIN.OPTIMISM, + topics: [topics0_postions_liq] + })))).flat(); - const tradeVolume = logs_modify.map((e: ILog) => { - const value = contract_interface.parseLog(e) - const tradeSize = Number(value!.args.tradeSize.toString().replace('-', '')) / 10 ** 18; - const lastPrice = Number(value!.args.lastPrice.toString().replace('-', '')) / 10 ** 18; - return (tradeSize * lastPrice); - }).filter((e: number) => !isNaN(e)).reduce((a: number, b: number) => a + b, 0); + const tradeVolume = logs_modify.map((e: ILog) => { + const value = contract_interface.parseLog(e) + const tradeSize = Number(value!.args.tradeSize.toString().replace('-', '')) / 10 ** 18; + const lastPrice = Number(value!.args.lastPrice.toString().replace('-', '')) / 10 ** 18; + return (tradeSize * lastPrice); + }).filter((e: number) => !isNaN(e)).reduce((a: number, b: number) => a + b, 0); - const liqVolume = logs_liq.map((e: ILog) => { - const value = contract_interface.parseLog(e) - const tradeSize = Number(value!.args.size.toString().replace('-', '')) / 10 ** 18; - const lastPrice = Number(value!.args.price.toString().replace('-', '')) / 10 ** 18; - return (tradeSize * lastPrice); - }).filter((e: number) => !isNaN(e)).reduce((a: number, b: number) => a + b, 0); - const dailyVolume = tradeVolume + liqVolume; - return { - dailyVolume: `${dailyVolume}`, - timestamp - } - } catch (error) { - console.error(error); - throw error; + const liqVolume = logs_liq.map((e: ILog) => { + const value = contract_interface.parseLog(e) + const tradeSize = Number(value!.args.size.toString().replace('-', '')) / 10 ** 18; + const lastPrice = Number(value!.args.price.toString().replace('-', '')) / 10 ** 18; + return (tradeSize * lastPrice); + }).filter((e: number) => !isNaN(e)).reduce((a: number, b: number) => a + b, 0); + const dailyVolume = tradeVolume + liqVolume; + return { + dailyVolume: `${dailyVolume}`, + timestamp } } const adapter: SimpleAdapter = { diff --git a/dexs/velocore-v2/index.ts b/dexs/velocore-v2/index.ts index 878f780873..1e8df8757b 100644 --- a/dexs/velocore-v2/index.ts +++ b/dexs/velocore-v2/index.ts @@ -13,45 +13,40 @@ interface ILog { const abs = (a: number) => a < 0 ? -a : a; const fetch = async (timestamp: number) => { - try { - let abi = ["event Swap(address indexed pool, address indexed user, bytes32[] tokenRef, int128[] delta)"]; - let iface = new ethers.Interface(abi); - const volume: { [addr: string]: number } = ((await sdk.getEventLogs({ - target: "0x1d0188c4B276A09366D05d6Be06aF61a73bC7535", - fromBlock: await getBlock(timestamp - 60 * 60 * 24, CHAIN.LINEA, {}), - toBlock: await getBlock(timestamp, CHAIN.LINEA, {}), - chain: CHAIN.LINEA, - topics: ["0xbaec78ca3218aba6fc32d82b79acdd1a47663d7b8da46e0c00947206d08f2071"] - }))as any as ILog[]).map((i) => { - const e = iface.parseLog(i)!.args; - let volume: { [addr: string]: number } = {}; - for (let i = 0; i < e.tokenRef.length; i++) { - if (e.tokenRef[i].slice(2 + 24).toLowerCase() == e.pool.slice(2).toLowerCase()) { - // this is lp deposit/withdrawal, not swap - return {}; - } - - volume['0x' + e.tokenRef[i].slice(2 + 24)] = (volume['0x' + e.tokenRef[i].slice(2 + 24)] ?? 0) + abs(Number(e.delta[i])) - } - volume["0xe5D7C2a44FfDDf6b295A15c148167daaAf5Cf34f"] = volume["0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee"]; // WETH - delete volume["0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee"]; - return volume; - }).reduce((a, b) => { - for (let i in b) { - a[i] = (a[i] ?? 0) + (b[i]); + let abi = ["event Swap(address indexed pool, address indexed user, bytes32[] tokenRef, int128[] delta)"]; + let iface = new ethers.Interface(abi); + const volume: { [addr: string]: number } = ((await sdk.getEventLogs({ + target: "0x1d0188c4B276A09366D05d6Be06aF61a73bC7535", + fromBlock: await getBlock(timestamp - 60 * 60 * 24, CHAIN.LINEA, {}), + toBlock: await getBlock(timestamp, CHAIN.LINEA, {}), + chain: CHAIN.LINEA, + topics: ["0xbaec78ca3218aba6fc32d82b79acdd1a47663d7b8da46e0c00947206d08f2071"] + })) as any as ILog[]).map((i) => { + const e = iface.parseLog(i)!.args; + let volume: { [addr: string]: number } = {}; + for (let i = 0; i < e.tokenRef.length; i++) { + if (e.tokenRef[i].slice(2 + 24).toLowerCase() == e.pool.slice(2).toLowerCase()) { + // this is lp deposit/withdrawal, not swap + return {}; } - return a; - }, {}) - let prices = await getPrices(Object.keys(volume).map((i) => `${CHAIN.LINEA}:${i}`), timestamp); - const dailyVolume = Object.keys(volume).map((addr) => (prices[`${CHAIN.LINEA}:${addr}`]?.price * volume[addr] / 10 ** prices[`${CHAIN.LINEA}:${addr}`]?.decimals) || 0).reduce((a, b) => a + b, 0) / 2; - return { - dailyVolume: `${dailyVolume}`, - timestamp, - }; - } catch (error) { - console.error(error); - throw error; - } + + volume['0x' + e.tokenRef[i].slice(2 + 24)] = (volume['0x' + e.tokenRef[i].slice(2 + 24)] ?? 0) + abs(Number(e.delta[i])) + } + volume["0xe5D7C2a44FfDDf6b295A15c148167daaAf5Cf34f"] = volume["0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee"]; // WETH + delete volume["0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee"]; + return volume; + }).reduce((a, b) => { + for (let i in b) { + a[i] = (a[i] ?? 0) + (b[i]); + } + return a; + }, {}) + let prices = await getPrices(Object.keys(volume).map((i) => `${CHAIN.LINEA}:${i}`), timestamp); + const dailyVolume = Object.keys(volume).map((addr) => (prices[`${CHAIN.LINEA}:${addr}`]?.price * volume[addr] / 10 ** prices[`${CHAIN.LINEA}:${addr}`]?.decimals) || 0).reduce((a, b) => a + b, 0) / 2; + return { + dailyVolume: `${dailyVolume}`, + timestamp, + }; } const adapter: SimpleAdapter = { diff --git a/dexs/velodrome-v2/v2.ts b/dexs/velodrome-v2/v2.ts index 462ae9f8cc..5438fa9c88 100644 --- a/dexs/velodrome-v2/v2.ts +++ b/dexs/velodrome-v2/v2.ts @@ -36,91 +36,86 @@ const ABIs: TABI = { export const fetchV2 = async (timestamp: number) => { const fromTimestamp = timestamp - 60 * 60 * 24 const toTimestamp = timestamp - try { - const poolLength = (await sdk.api2.abi.call({ - target: FACTORY_ADDRESS, - chain: CHAIN.OPTIMISM, - abi: ABIs.allPoolsLength, - })); + const poolLength = (await sdk.api2.abi.call({ + target: FACTORY_ADDRESS, + chain: CHAIN.OPTIMISM, + abi: ABIs.allPoolsLength, + })); - const poolsRes = await sdk.api2.abi.multiCall({ - abi: ABIs.allPools, - calls: Array.from(Array(Number(poolLength)).keys()).map((i) => ({ - target: FACTORY_ADDRESS, - params: i, - })), - chain: CHAIN.OPTIMISM - }); + const poolsRes = await sdk.api2.abi.multiCall({ + abi: ABIs.allPools, + calls: Array.from(Array(Number(poolLength)).keys()).map((i) => ({ + target: FACTORY_ADDRESS, + params: i, + })), + chain: CHAIN.OPTIMISM + }); - const lpTokens = poolsRes + const lpTokens = poolsRes - const [underlyingToken0, underlyingToken1] = await Promise.all( - ['address:token0', 'address:token1'].map((method) => - sdk.api2.abi.multiCall({ - abi: method, - calls: lpTokens, - chain: CHAIN.OPTIMISM, - permitFailure: true, - }) - ) - ); + const [underlyingToken0, underlyingToken1] = await Promise.all( + ['address:token0', 'address:token1'].map((method) => + sdk.api2.abi.multiCall({ + abi: method, + calls: lpTokens, + chain: CHAIN.OPTIMISM, + permitFailure: true, + }) + ) + ); - const tokens0 = underlyingToken0; - const tokens1 = underlyingToken1; - const fromBlock = (await getBlock(fromTimestamp, CHAIN.OPTIMISM, {})); - const toBlock = (await getBlock(toTimestamp, CHAIN.OPTIMISM, {})); - const logs: ILog[][] = (await Promise.all(lpTokens.map((address: string) => sdk.getEventLogs({ - target: address, - topic: topic_name, - toBlock: toBlock, - fromBlock: fromBlock, - chain: CHAIN.OPTIMISM, - topics: [topic0] - })))) as any; - const rawCoins = [...tokens0, ...tokens1].map((e: string) => `${CHAIN.OPTIMISM}:${e}`); - const coins: string[] = [...new Set(rawCoins)] - const coins_split: string[][] = []; - for(let i = 0; i < coins.length; i+=100) { - coins_split.push(coins.slice(i, i + 100)) - } - const prices_result: any = (await Promise.all(coins_split.map((a: string[]) => getPrices(a, timestamp)))).flat().flat().flat(); - const prices: TPrice = Object.assign({}, {}); - prices_result.map((a: any) => Object.assign(prices, a)) - const untrackVolumes: number[] = lpTokens.map((_: string, index: number) => { - const log: IAmount[] = logs[index] - .map((e: ILog) => { return { ...e, data: e.data.replace('0x', '') } }) - .map((p: ILog) => { - const amount0In = Number('0x' + p.data.slice(0, 64)).toString(); - const amount1In = Number('0x' + p.data.slice(64, 128)).toString(); - const amount0Out = Number('0x' + p.data.slice(128, 192)).toString(); - const amount1Out = Number('0x' + p.data.slice(192, 256)).toString(); - return { - amount0In, - amount1In, - amount0Out, - amount1Out, - } as IAmount - }) as IAmount[]; - const token0Price = (prices[`${CHAIN.OPTIMISM}:${tokens0[index]}`]?.price || 0); - const token1Price = (prices[`${CHAIN.OPTIMISM}:${tokens1[index]}`]?.price || 0); - const token0Decimals = (prices[`${CHAIN.OPTIMISM}:${tokens0[index]}`]?.decimals || 0) - const token1Decimals = (prices[`${CHAIN.OPTIMISM}:${tokens1[index]}`]?.decimals || 0) - const totalAmount0 = log - .reduce((a: number, b: IAmount) => Number(b.amount0In) + Number(b.amount0Out) + a, 0) / 10 ** token0Decimals * token0Price; - const totalAmount1 = log - .reduce((a: number, b: IAmount) => Number(b.amount1In) + Number(b.amount1Out) + a, 0) / 10 ** token1Decimals * token1Price; + const tokens0 = underlyingToken0; + const tokens1 = underlyingToken1; + const fromBlock = (await getBlock(fromTimestamp, CHAIN.OPTIMISM, {})); + const toBlock = (await getBlock(toTimestamp, CHAIN.OPTIMISM, {})); + const logs: ILog[][] = (await Promise.all(lpTokens.map((address: string) => sdk.getEventLogs({ + target: address, + topic: topic_name, + toBlock: toBlock, + fromBlock: fromBlock, + chain: CHAIN.OPTIMISM, + topics: [topic0] + })))) as any; + const rawCoins = [...tokens0, ...tokens1].map((e: string) => `${CHAIN.OPTIMISM}:${e}`); + const coins: string[] = [...new Set(rawCoins)] + const coins_split: string[][] = []; + for (let i = 0; i < coins.length; i += 100) { + coins_split.push(coins.slice(i, i + 100)) + } + const prices_result: any = (await Promise.all(coins_split.map((a: string[]) => getPrices(a, timestamp)))).flat().flat().flat(); + const prices: TPrice = Object.assign({}, {}); + prices_result.map((a: any) => Object.assign(prices, a)) + const untrackVolumes: number[] = lpTokens.map((_: string, index: number) => { + const log: IAmount[] = logs[index] + .map((e: ILog) => { return { ...e, data: e.data.replace('0x', '') } }) + .map((p: ILog) => { + const amount0In = Number('0x' + p.data.slice(0, 64)).toString(); + const amount1In = Number('0x' + p.data.slice(64, 128)).toString(); + const amount0Out = Number('0x' + p.data.slice(128, 192)).toString(); + const amount1Out = Number('0x' + p.data.slice(192, 256)).toString(); + return { + amount0In, + amount1In, + amount0Out, + amount1Out, + } as IAmount + }) as IAmount[]; + const token0Price = (prices[`${CHAIN.OPTIMISM}:${tokens0[index]}`]?.price || 0); + const token1Price = (prices[`${CHAIN.OPTIMISM}:${tokens1[index]}`]?.price || 0); + const token0Decimals = (prices[`${CHAIN.OPTIMISM}:${tokens0[index]}`]?.decimals || 0) + const token1Decimals = (prices[`${CHAIN.OPTIMISM}:${tokens1[index]}`]?.decimals || 0) + const totalAmount0 = log + .reduce((a: number, b: IAmount) => Number(b.amount0In) + Number(b.amount0Out) + a, 0) / 10 ** token0Decimals * token0Price; + const totalAmount1 = log + .reduce((a: number, b: IAmount) => Number(b.amount1In) + Number(b.amount1Out) + a, 0) / 10 ** token1Decimals * token1Price; - const untrackAmountUSD = token0Price !== 0 ? totalAmount0 : token1Price !== 0 ? totalAmount1 : 0; // counted only we have price data - return untrackAmountUSD; - }); + const untrackAmountUSD = token0Price !== 0 ? totalAmount0 : token1Price !== 0 ? totalAmount1 : 0; // counted only we have price data + return untrackAmountUSD; + }); - const dailyVolume = untrackVolumes.reduce((a: number, b: number) => a + b, 0); - return { - dailyVolume: `${dailyVolume}`, - timestamp, - }; - } catch(error) { - console.error(error); - throw error; - } + const dailyVolume = untrackVolumes.reduce((a: number, b: number) => a + b, 0); + return { + dailyVolume: `${dailyVolume}`, + timestamp, + }; } diff --git a/fees/0x0dex.ts b/fees/0x0dex.ts index e0e39fa4a8..8489cb8d22 100644 --- a/fees/0x0dex.ts +++ b/fees/0x0dex.ts @@ -20,26 +20,22 @@ const discount = 0.0045; const targetTopic = "0x90890809c654f11d6e72a28fa60149770a0d11ec6c92319d6ceb2bb0a4ea1a15"; const discountThreshold = 1000000 * (9 ** 18); -async function calcFees(calcData: IDeposit[], chain: CHAIN){ +async function calcFees(calcData: IDeposit[], chain: CHAIN) { let fees = 0; - for(var i=0; i < calcData.length; i++){ + for (var i = 0; i < calcData.length; i++) { let c = calcData[i]; - try{ - let { output: balance } = await sdk.api.erc20.balanceOf({ - target: OxOToken, - owner: c.sender, - block: c.blockNumber, - chain: chain - }); - - if(parseInt(balance) >= discountThreshold){ - fees += Number(c.depositAmount) * discount; - }else{ - fees += Number(c.depositAmount) * fee; - } - } catch(e){ - // console.log(e); + let { output: balance } = await sdk.api.erc20.balanceOf({ + target: OxOToken, + owner: c.sender, + block: c.blockNumber, + chain: chain + }); + + if (parseInt(balance) >= discountThreshold) { + fees += Number(c.depositAmount) * discount; + } else { + fees += Number(c.depositAmount) * fee; } } @@ -47,10 +43,10 @@ async function calcFees(calcData: IDeposit[], chain: CHAIN){ } async function getDepositTXs( - fromBlock: number, - toBlock: number, + fromBlock: number, + toBlock: number, chain: CHAIN -): Promise{ +): Promise { const iface = new ethers.Interface([ "event Deposit (address, uint256 tokenAmount, uint256 ringIndex)" ]); @@ -74,7 +70,7 @@ async function getDepositTXs( return calcData; } - + const fetch = async (timestamp: number): Promise => { const chain = CHAIN.ETHEREUM; diff --git a/fees/Scale.ts b/fees/Scale.ts index 786d4660fa..2f0205419b 100644 --- a/fees/Scale.ts +++ b/fees/Scale.ts @@ -40,7 +40,7 @@ const CHAIN_SLUG = 'base'; type TABI = { [k: string]: string; } -const ABIs: TABI ={ +const ABIs: TABI = { "allPairsLength": "uint256:allPairsLength", "allPairs": "function allPairs(uint256) view returns (address)" } @@ -54,196 +54,194 @@ const VOTER_ABI: TABI = { const fetch = async (timestamp: number): Promise => { const fromTimestamp = timestamp - 60 * 60 * 24 const toTimestamp = timestamp - try { - - const poolLength = (await sdk.api2.abi.call({ - target: FACTORY_ADDRESS, - chain: CHAIN_SLUG, - abi: ABIs.allPairsLength, - })); - - const poolsRes = await sdk.api2.abi.multiCall({ - abi: ABIs.allPairs, - target: FACTORY_ADDRESS, - calls: Array.from(Array(Number(poolLength)).keys()), - chain: CHAIN_SLUG - }); - - const lpTokens = poolsRes - - const [underlyingToken0, underlyingToken1] = await Promise.all( - ['address:token0', 'address:token1'].map((method) => - sdk.api2.abi.multiCall({ - abi: method, - calls: lpTokens.map((address: string) => ({ - target: address, - })), - chain: CHAIN_SLUG - }) - ) - ); - - const tokens0 = underlyingToken0; - const tokens1 = underlyingToken1; - - - const poolsGauges = await sdk.api2.abi.multiCall({ - abi: VOTER_ABI.gauges, - target: VOTER_ADDRESS, - calls: lpTokens, - chain: CHAIN_SLUG - }); + const poolLength = (await sdk.api2.abi.call({ + target: FACTORY_ADDRESS, + chain: CHAIN_SLUG, + abi: ABIs.allPairsLength, + })); - const voterGauges = poolsGauges.filter( (_vg: string) => - _vg !== '0x0000000000000000000000000000000000000000' - ); + const poolsRes = await sdk.api2.abi.multiCall({ + abi: ABIs.allPairs, + target: FACTORY_ADDRESS, + calls: Array.from(Array(Number(poolLength)).keys()), + chain: CHAIN_SLUG + }); + const lpTokens = poolsRes + const [underlyingToken0, underlyingToken1] = await Promise.all( + ['address:token0', 'address:token1'].map((method) => + sdk.api2.abi.multiCall({ + abi: method, + calls: lpTokens.map((address: string) => ({ + target: address, + })), + chain: CHAIN_SLUG + }) + ) + ); - const poolsGaugesToBribes = await sdk.api2.abi.multiCall({ - abi: VOTER_ABI.bribes, - target: VOTER_ADDRESS, - calls: voterGauges, - chain: CHAIN_SLUG - }); + const tokens0 = underlyingToken0; + const tokens1 = underlyingToken1; - const voterBribes = poolsGaugesToBribes; + const poolsGauges = await sdk.api2.abi.multiCall({ + abi: VOTER_ABI.gauges, + target: VOTER_ADDRESS, + calls: lpTokens, + chain: CHAIN_SLUG + }); + const voterGauges = poolsGauges.filter((_vg: string) => + _vg !== '0x0000000000000000000000000000000000000000' + ); - const fromBlock = (await getBlock(fromTimestamp, CHAIN_SLUG, {})); - const toBlock = (await getBlock(toTimestamp, CHAIN_SLUG, {})); + const poolsGaugesToBribes = await sdk.api2.abi.multiCall({ + abi: VOTER_ABI.bribes, + target: VOTER_ADDRESS, + calls: voterGauges, + chain: CHAIN_SLUG + }); - const tradefeeLogs: ILog[][] = (await Promise.all(lpTokens.map((address: string) => sdk.getEventLogs({ - target: address, - toBlock: toBlock, - fromBlock: fromBlock, - chain: CHAIN_SLUG, - topics: [TOPIC_Fees] - })))) as ILog[][]; + const voterBribes = poolsGaugesToBribes; - const bribeAndFeeLogs: ILog[][] = (await Promise.all(voterBribes.map((address: string) => sdk.getEventLogs({ - target: address, - toBlock: toBlock, - fromBlock: fromBlock, - chain: CHAIN_SLUG, - topics: [TOPIC_NotifyRewardAmount] - })))) as ILog[][]; - var allBribedTokens: string[] = new Array(0); - const listOfBribedTokensByPool: string[][] = bribeAndFeeLogs.map( (perBribeLogs: ILog[]) => { - const _innerBT: string[] = perBribeLogs.map( (e: ILog) => { - const _l = INTERFACE_N.parseLog(e); - if(_l==null) { return "" } - const _t = `${CHAIN_USED}:${_l.args.reward.toLowerCase()}`; - return _t; - //return `${CHAIN_USED}:${e.topics[2].toLowerCase()}`; - }); - allBribedTokens = allBribedTokens.concat(_innerBT); - return _innerBT; - }); - - allBribedTokens.filter( (_ta: string) => { _ta != "" } ) - + const fromBlock = (await getBlock(fromTimestamp, CHAIN_SLUG, {})); + const toBlock = (await getBlock(toTimestamp, CHAIN_SLUG, {})); + const tradefeeLogs: ILog[][] = (await Promise.all(lpTokens.map((address: string) => sdk.getEventLogs({ + target: address, + toBlock: toBlock, + fromBlock: fromBlock, + chain: CHAIN_SLUG, + topics: [TOPIC_Fees] + })))) as ILog[][]; + const bribeAndFeeLogs: ILog[][] = (await Promise.all(voterBribes.map((address: string) => sdk.getEventLogs({ + target: address, + toBlock: toBlock, + fromBlock: fromBlock, + chain: CHAIN_SLUG, + topics: [TOPIC_NotifyRewardAmount] + })))) as ILog[][]; - const rawCoins = [...tokens0, ...tokens1, ...allBribedTokens].map((e: string) => `${CHAIN_SLUG}:${e}`); - const coins = [...new Set(rawCoins)]; - // const prices = await getPrices(coins, timestamp); - // { getPrices } function breaks above 100 tokens..splitting into chunks of 100 + var allBribedTokens: string[] = new Array(0); + const listOfBribedTokensByPool: string[][] = bribeAndFeeLogs.map((perBribeLogs: ILog[]) => { + const _innerBT: string[] = perBribeLogs.map((e: ILog) => { + const _l = INTERFACE_N.parseLog(e); + if (_l == null) { return "" } + const _t = `${CHAIN_USED}:${_l.args.reward.toLowerCase()}`; + return _t; + //return `${CHAIN_USED}:${e.topics[2].toLowerCase()}`; + }); + allBribedTokens = allBribedTokens.concat(_innerBT); + return _innerBT; + }); - const coins_split: string[][] = []; - for(let i = 0; i < coins.length; i+=100) { - coins_split.push(coins.slice(i, i + 100)) - } - const prices_result: any = (await Promise.all(coins_split.map((a: string[]) => getPrices(a, timestamp)))).flat().flat().flat(); - const prices: TPrice = Object.assign({}, {}); - prices_result.map((a: any) => Object.assign(prices, a)) + allBribedTokens.filter((_ta: string) => { _ta != "" }) - const tradefees: number[] = lpTokens.map((_: string, index: number) => { - const token0Decimals = (prices[`${CHAIN_SLUG}:${tokens0[index]}`]?.decimals || 0) - const token1Decimals = (prices[`${CHAIN_SLUG}:${tokens1[index]}`]?.decimals || 0) - const tradefeesLog: IAmount[] = tradefeeLogs[index] - .map((e: ILog) => { return { ...e, data: e.data.replace('0x', '') } }) - .map((p: ILog) => { - const amount0 = Number('0x' + p.data.slice( 0, 64)) / 10 ** token0Decimals; - const amount1 = Number('0x' + p.data.slice(64, 128)) / 10 ** token1Decimals; - return { - amount0, - amount1 - } as IAmount - }) as IAmount[]; - const token0Price = (prices[`${CHAIN_SLUG}:${tokens0[index]}`]?.price || 0); - const token1Price = (prices[`${CHAIN_SLUG}:${tokens1[index]}`]?.price || 0); - const feesAmount0 = tradefeesLog - .reduce((a: number, b: IAmount) => Number(b.amount0) + a, 0) * token0Price; - const feesAmount1 = tradefeesLog - .reduce((a: number, b: IAmount) => Number(b.amount1) + a, 0) * token1Price; - const feesUSD = feesAmount0 + feesAmount1; - return feesUSD; - }); + const rawCoins = [...tokens0, ...tokens1, ...allBribedTokens].map((e: string) => `${CHAIN_SLUG}:${e}`); + const coins = [...new Set(rawCoins)]; + // const prices = await getPrices(coins, timestamp); + // { getPrices } function breaks above 100 tokens..splitting into chunks of 100 - const notifiedFees: number[] = voterBribes.map((_: string, index: number) => { - const notifiedFeesLog: IAmountUSD[] = bribeAndFeeLogs[index] - .map((e: ILog) => { return { ...e } }) - .map((p: ILog) => { - const _log = INTERFACE_N.parseLog(p); - if(_log==null || _log.args.from != voterGauges[index]) { - const amount = 0; - return { amount } as IAmountUSD - } - const _token = _log.args.reward; - const _price = (prices[`${CHAIN_SLUG}:${_token}`]?.price || 0); - const _deci = prices[`${CHAIN_SLUG}:${_token}`]?.decimals || 0; - //console.log("_log.args.from", _log.args.from); - const amount = Number(p.data) / 10 ** _deci * _price ; + const coins_split: string[][] = []; + for (let i = 0; i < coins.length; i += 100) { + coins_split.push(coins.slice(i, i + 100)) + } + const prices_result: any = (await Promise.all(coins_split.map((a: string[]) => getPrices(a, timestamp)))).flat().flat().flat(); + const prices: TPrice = Object.assign({}, {}); + prices_result.map((a: any) => Object.assign(prices, a)) + + + + const tradefees: number[] = lpTokens.map((_: string, index: number) => { + const token0Decimals = (prices[`${CHAIN_SLUG}:${tokens0[index]}`]?.decimals || 0) + const token1Decimals = (prices[`${CHAIN_SLUG}:${tokens1[index]}`]?.decimals || 0) + const tradefeesLog: IAmount[] = tradefeeLogs[index] + .map((e: ILog) => { return { ...e, data: e.data.replace('0x', '') } }) + .map((p: ILog) => { + const amount0 = Number('0x' + p.data.slice(0, 64)) / 10 ** token0Decimals; + const amount1 = Number('0x' + p.data.slice(64, 128)) / 10 ** token1Decimals; + return { + amount0, + amount1 + } as IAmount + }) as IAmount[]; + const token0Price = (prices[`${CHAIN_SLUG}:${tokens0[index]}`]?.price || 0); + const token1Price = (prices[`${CHAIN_SLUG}:${tokens1[index]}`]?.price || 0); + + const feesAmount0 = tradefeesLog + .reduce((a: number, b: IAmount) => Number(b.amount0) + a, 0) * token0Price; + const feesAmount1 = tradefeesLog + .reduce((a: number, b: IAmount) => Number(b.amount1) + a, 0) * token1Price; + + const feesUSD = feesAmount0 + feesAmount1; + return feesUSD; + }); + + + + const notifiedFees: number[] = voterBribes.map((_: string, index: number) => { + const notifiedFeesLog: IAmountUSD[] = bribeAndFeeLogs[index] + .map((e: ILog) => { return { ...e } }) + .map((p: ILog) => { + const _log = INTERFACE_N.parseLog(p); + if (_log == null || _log.args.from != voterGauges[index]) { + const amount = 0; return { amount } as IAmountUSD - }) as IAmountUSD[]; + } + const _token = _log.args.reward; + const _price = (prices[`${CHAIN_SLUG}:${_token}`]?.price || 0); + const _deci = prices[`${CHAIN_SLUG}:${_token}`]?.decimals || 0; + //console.log("_log.args.from", _log.args.from); + const amount = Number(p.data) / 10 ** _deci * _price; + return { amount } as IAmountUSD + }) as IAmountUSD[]; - const notifiedFeeAmount = notifiedFeesLog - .reduce((a: number, b: IAmountUSD) => Number(b.amount) + a, 0); + const notifiedFeeAmount = notifiedFeesLog + .reduce((a: number, b: IAmountUSD) => Number(b.amount) + a, 0); - return notifiedFeeAmount; - }); + return notifiedFeeAmount; + }); - const notifiedBribes: number[] = voterBribes.map((_: string, index: number) => { - const bribesLog: IAmountUSD[] = bribeAndFeeLogs[index] - .map((e: ILog) => { return { ...e } }) - .map((p: ILog) => { - const _log = INTERFACE_N.parseLog(p); - if(_log==null || _log.args.from == voterGauges[index]) { - const amount = 0; - return { amount } as IAmountUSD - } - const _token = _log.args.reward; - const _price = (prices[`${CHAIN_SLUG}:${_token}`]?.price || 0); - const _deci = prices[`${CHAIN_SLUG}:${_token}`]?.decimals || 0; - const amount = Number(p.data) / 10 ** _deci * _price ; + const notifiedBribes: number[] = voterBribes.map((_: string, index: number) => { + const bribesLog: IAmountUSD[] = bribeAndFeeLogs[index] + .map((e: ILog) => { return { ...e } }) + .map((p: ILog) => { + const _log = INTERFACE_N.parseLog(p); + if (_log == null || _log.args.from == voterGauges[index]) { + const amount = 0; return { amount } as IAmountUSD - }) as IAmountUSD[]; + } + const _token = _log.args.reward; + const _price = (prices[`${CHAIN_SLUG}:${_token}`]?.price || 0); + const _deci = prices[`${CHAIN_SLUG}:${_token}`]?.decimals || 0; + const amount = Number(p.data) / 10 ** _deci * _price; + return { amount } as IAmountUSD + }) as IAmountUSD[]; - const bribedAmount = bribesLog.reduce((a: number, b: IBribedAmount) => Number(b.amount) + a, 0); + const bribedAmount = bribesLog.reduce((a: number, b: IBribedAmount) => Number(b.amount) + a, 0); - return bribedAmount; - }); + return bribedAmount; + }); @@ -251,23 +249,19 @@ const fetch = async (timestamp: number): Promise => { - const dailyFees = tradefees.reduce((a: number, b: number) => a+b,0) - const dailyRevenueFees = notifiedFees.reduce((a: number, b: number) => a+b,0) - const dailyRevenueBribes = notifiedBribes.reduce((a: number, b: number) => a+b,0) + const dailyFees = tradefees.reduce((a: number, b: number) => a + b, 0) + const dailyRevenueFees = notifiedFees.reduce((a: number, b: number) => a + b, 0) + const dailyRevenueBribes = notifiedBribes.reduce((a: number, b: number) => a + b, 0) - return { - dailyFees: `${dailyFees}`, - dailyRevenue: `${dailyRevenueFees}`, - dailyHoldersRevenue: `${dailyRevenueFees}`, - dailyBribesRevenue: `${dailyRevenueBribes}`, - timestamp, - }; - } catch(error) { - console.error(error); - throw error; - } + return { + dailyFees: `${dailyFees}`, + dailyRevenue: `${dailyRevenueFees}`, + dailyHoldersRevenue: `${dailyRevenueFees}`, + dailyBribesRevenue: `${dailyRevenueBribes}`, + timestamp, + }; } const adapter: SimpleAdapter = { diff --git a/fees/aerodrome/bribes.ts b/fees/aerodrome/bribes.ts index 1e7949620b..b2a5d657a4 100644 --- a/fees/aerodrome/bribes.ts +++ b/fees/aerodrome/bribes.ts @@ -32,53 +32,48 @@ interface IBribes { const gurar = '0x2073D8035bB2b0F2e85aAF5a8732C6f397F9ff9b'; -const abis: any ={ +const abis: any = { "all": "function all(uint256 _limit, uint256 _offset, address _account) view returns ((address lp, string symbol, uint8 decimals, bool stable, uint256 total_supply, address token0, uint256 reserve0, uint256 claimable0, address token1, uint256 reserve1, uint256 claimable1, address gauge, uint256 gauge_total_supply, bool gauge_alive, address fee, address bribe, address factory, uint256 emissions, address emissions_token, uint256 account_balance, uint256 account_earned, uint256 account_staked, uint256 pool_fee, uint256 token0_fees, uint256 token1_fees)[])" } export const fees_bribes = async (fromBlock: number, toBlock: number, timestamp: number): Promise => { - try { - const ZERO_ADDRESS = '0x0000000000000000000000000000000000000000'; - const bribeVotingReward: string[] = (await sdk.api2.abi.call({ - target: gurar, - params: [1000, 0, '0x0000000000000000000000000000000000000000'], - abi: abis.all, - chain: CHAIN.BASE, - })).map((e: any) => { - return e.bribe; - }).filter((e: string) => e !== ZERO_ADDRESS); - const bribe_contracct = [...new Set(bribeVotingReward)]; - const logs: ILog[] = (await Promise.all(bribe_contracct.map((address: string) => sdk.getEventLogs({ - target: address, - toBlock: toBlock, - fromBlock: fromBlock, - chain: CHAIN.BASE, - topics: ['0x52977ea98a2220a03ee9ba5cb003ada08d394ea10155483c95dc2dc77a7eb24b'] - })))).flat() as ILog[]; + const ZERO_ADDRESS = '0x0000000000000000000000000000000000000000'; + const bribeVotingReward: string[] = (await sdk.api2.abi.call({ + target: gurar, + params: [1000, 0, '0x0000000000000000000000000000000000000000'], + abi: abis.all, + chain: CHAIN.BASE, + })).map((e: any) => { + return e.bribe; + }).filter((e: string) => e !== ZERO_ADDRESS); + const bribe_contracct = [...new Set(bribeVotingReward)]; + const logs: ILog[] = (await Promise.all(bribe_contracct.map((address: string) => sdk.getEventLogs({ + target: address, + toBlock: toBlock, + fromBlock: fromBlock, + chain: CHAIN.BASE, + topics: ['0x52977ea98a2220a03ee9ba5cb003ada08d394ea10155483c95dc2dc77a7eb24b'] + })))).flat() as ILog[]; - const logs_bribes = logs.map((e: ILog) => { - const value = contract_interface.parseLog(e) - return { - token: value!.args.reward, - amount: Number(value!.args.amount) - } as IBribes - }) - const coins = [...new Set(logs_bribes.map((e: IBribes) => `${CHAIN.BASE}:${e.token.toLowerCase()}`))] - const coins_split: string[][] = []; - for(let i = 0; i < coins.length; i+=100) { - coins_split.push(coins.slice(i, i + 100)) - } - const prices_result: any = (await Promise.all(coins_split.map((a: string[]) => getPrices(a, timestamp)))).flat().flat().flat(); - const prices: TPrice = Object.assign({}, {}); - prices_result.map((a: any) => Object.assign(prices, a)) - const fees_bribes_usd = logs_bribes.map((e: IBribes) => { - const price = prices[`${CHAIN.BASE}:${e.token.toLowerCase()}`]?.price || 0; - const decimals = prices[`${CHAIN.BASE}:${e.token.toLowerCase()}`]?.decimals || 0; - return (Number(e.amount) / 10 ** decimals) * price; - }).reduce((a: number, b: number) => a+b, 0); - return fees_bribes_usd; - } catch (error) { - console.error(error); - throw error; + const logs_bribes = logs.map((e: ILog) => { + const value = contract_interface.parseLog(e) + return { + token: value!.args.reward, + amount: Number(value!.args.amount) + } as IBribes + }) + const coins = [...new Set(logs_bribes.map((e: IBribes) => `${CHAIN.BASE}:${e.token.toLowerCase()}`))] + const coins_split: string[][] = []; + for (let i = 0; i < coins.length; i += 100) { + coins_split.push(coins.slice(i, i + 100)) } + const prices_result: any = (await Promise.all(coins_split.map((a: string[]) => getPrices(a, timestamp)))).flat().flat().flat(); + const prices: TPrice = Object.assign({}, {}); + prices_result.map((a: any) => Object.assign(prices, a)) + const fees_bribes_usd = logs_bribes.map((e: IBribes) => { + const price = prices[`${CHAIN.BASE}:${e.token.toLowerCase()}`]?.price || 0; + const decimals = prices[`${CHAIN.BASE}:${e.token.toLowerCase()}`]?.decimals || 0; + return (Number(e.amount) / 10 ** decimals) * price; + }).reduce((a: number, b: number) => a + b, 0); + return fees_bribes_usd; } diff --git a/fees/aimbot.ts b/fees/aimbot.ts index fd5cd6abe2..32cf743836 100644 --- a/fees/aimbot.ts +++ b/fees/aimbot.ts @@ -61,7 +61,6 @@ const fetch = async (timestamp: number): Promise => { } } catch (error) { await sql.end({ timeout: 3 }) - console.error(error); throw error; } diff --git a/fees/airswap.ts b/fees/airswap.ts index cd17d63f79..ef65533a8e 100644 --- a/fees/airswap.ts +++ b/fees/airswap.ts @@ -4,14 +4,14 @@ import * as sdk from "@defillama/sdk"; import { getBlock } from "../helpers/getBlock"; import { getPrices } from "../utils/prices"; import { Chain } from "@defillama/sdk/build/general"; -import { ethers, } from "ethers"; +import { ethers, } from "ethers"; interface ITx { data: string; transactionHash: string; topics: string[]; } -interface IData { +interface IData { signerAmount: number; signerToken: string; protocolFee: number; @@ -39,44 +39,39 @@ const graph = (chain: Chain) => { return async (timestamp: number): Promise => { const fromTimestamp = timestamp - 60 * 60 * 24 const toTimestamp = timestamp - try { - const fromBlock = (await getBlock(fromTimestamp, chain, {})); - const toBlock = (await getBlock(toTimestamp, chain, {})); + const fromBlock = (await getBlock(fromTimestamp, chain, {})); + const toBlock = (await getBlock(toTimestamp, chain, {})); - const logs: ITx[] = (await sdk.getEventLogs({ - target: address[chain], - toBlock: toBlock, - fromBlock: fromBlock, - chain: chain, - topics: [topic0] - })).map((e: any) => { return { data: e.data, transactionHash: e.transactionHash, topics: e.topics } as ITx}); - const rawData = logs.map((e: ITx) => { - const data = contract_interface.parseLog(e); - return { - signerAmount: Number(data!.args.signerAmount), - signerToken: data!.args.signerToken, - protocolFee: Number(data!.args.protocolFee) - } - }) - const rawCoins = rawData.map((e: IData) => `${chain}:${e.signerToken.toLowerCase()}`); - const coins = [...new Set(rawCoins)] - const prices = await getPrices(coins, timestamp); - const feesAmount: number[] = rawData.map((e: IData) => { - const decimals = prices[`${chain}:${e.signerToken.toLowerCase()}`].decimals; - const price = prices[`${chain}:${e.signerToken.toLowerCase()}`].price; - return ((Number(e.signerAmount) / 10 ** decimals) * (e.protocolFee / 10000)) * price; - }); + const logs: ITx[] = (await sdk.getEventLogs({ + target: address[chain], + toBlock: toBlock, + fromBlock: fromBlock, + chain: chain, + topics: [topic0] + })).map((e: any) => { return { data: e.data, transactionHash: e.transactionHash, topics: e.topics } as ITx }); + const rawData = logs.map((e: ITx) => { + const data = contract_interface.parseLog(e); + return { + signerAmount: Number(data!.args.signerAmount), + signerToken: data!.args.signerToken, + protocolFee: Number(data!.args.protocolFee) + } + }) + const rawCoins = rawData.map((e: IData) => `${chain}:${e.signerToken.toLowerCase()}`); + const coins = [...new Set(rawCoins)] + const prices = await getPrices(coins, timestamp); + const feesAmount: number[] = rawData.map((e: IData) => { + const decimals = prices[`${chain}:${e.signerToken.toLowerCase()}`].decimals; + const price = prices[`${chain}:${e.signerToken.toLowerCase()}`].price; + return ((Number(e.signerAmount) / 10 ** decimals) * (e.protocolFee / 10000)) * price; + }); - const dailyFees = feesAmount.reduce((a: number, b: number) => a + b, 0); - return { - dailyFees: `${dailyFees}`, - dailyRevenue: `${dailyFees}`, - timestamp, - }; - } catch(error) { - console.error(error); - throw error; - } + const dailyFees = feesAmount.reduce((a: number, b: number) => a + b, 0); + return { + dailyFees: `${dailyFees}`, + dailyRevenue: `${dailyFees}`, + timestamp, + }; } } diff --git a/fees/allbridge-core.ts b/fees/allbridge-core.ts index 755d9b3dd7..1c8e251a8d 100644 --- a/fees/allbridge-core.ts +++ b/fees/allbridge-core.ts @@ -136,26 +136,21 @@ const getTronLogs = async (address: string, eventName: string, minBlockTimestamp const fetch = (chain: Chain) => { return async (timestamp: number): Promise => { - try { - let fees = 0; - if (chain === CHAIN.TRON) { - fees = await fetchFeesTron(chain, timestamp); - } else { - fees = await fetchFees(chain, timestamp); - } - const dailyFees = fees; - const dailyRevenue = dailyFees * 0.2; - const dailySupplySideRevenue = dailyFees * 0.8; - return { - dailyFees: dailyFees.toString(), - dailyRevenue: dailyRevenue.toString(), - dailySupplySideRevenue: dailySupplySideRevenue.toString(), - timestamp, - }; - } catch (e) { - console.error(e); - throw e; + let fees = 0; + if (chain === CHAIN.TRON) { + fees = await fetchFeesTron(chain, timestamp); + } else { + fees = await fetchFees(chain, timestamp); } + const dailyFees = fees; + const dailyRevenue = dailyFees * 0.2; + const dailySupplySideRevenue = dailyFees * 0.8; + return { + dailyFees: dailyFees.toString(), + dailyRevenue: dailyRevenue.toString(), + dailySupplySideRevenue: dailySupplySideRevenue.toString(), + timestamp, + }; }; }; diff --git a/fees/banana-gun-trading.ts b/fees/banana-gun-trading.ts index aac51bf829..d220e63954 100644 --- a/fees/banana-gun-trading.ts +++ b/fees/banana-gun-trading.ts @@ -55,7 +55,6 @@ const fetch = async (timestamp: number): Promise => { } } catch (error) { await sql.end({ timeout: 3 }) - console.error(error); throw error; } diff --git a/fees/base.ts b/fees/base.ts index 2a636c736f..5bce7779c9 100644 --- a/fees/base.ts +++ b/fees/base.ts @@ -122,7 +122,6 @@ const fetch = async (timestamp: number, chainBlocks: ChainBlocks): Promise => { const fromTimestamp = timestamp - 60 * 60 * 24 const toTimestamp = timestamp - try { - const fromBlock = (await getBlock(fromTimestamp, CHAIN.BASE, {})); - const toBlock = (await getBlock(toTimestamp, CHAIN.BASE, {})); - const logs = (await sdk.getEventLogs({ - target: contract, - topic: topic_0, - toBlock: toBlock, - fromBlock: fromBlock, - chain: CHAIN.BASE, - topics: [topic_0] - })) as ILog[]; + const fromBlock = (await getBlock(fromTimestamp, CHAIN.BASE, {})); + const toBlock = (await getBlock(toTimestamp, CHAIN.BASE, {})); + const logs = (await sdk.getEventLogs({ + target: contract, + topic: topic_0, + toBlock: toBlock, + fromBlock: fromBlock, + chain: CHAIN.BASE, + topics: [topic_0] + })) as ILog[]; - const artic_fees = logs.map((e: ILog) => { - const amount = Number(e.data) / 10 ** 18; - return amount; - }); + const artic_fees = logs.map((e: ILog) => { + const amount = Number(e.data) / 10 ** 18; + return amount; + }); - const artic_fees_amount = artic_fees.reduce((a: number, b: number) => a + b, 0); - const ethAddress = "ethereum:0x0000000000000000000000000000000000000000"; - const ethPrice = (await getPrices([ethAddress], timestamp))[ethAddress].price; + const artic_fees_amount = artic_fees.reduce((a: number, b: number) => a + b, 0); + const ethAddress = "ethereum:0x0000000000000000000000000000000000000000"; + const ethPrice = (await getPrices([ethAddress], timestamp))[ethAddress].price; - const dailyFees = (artic_fees_amount / ((100 - 10)/100)) * ethPrice; - const dailyRevenue = dailyFees * (protocol_fees/100); + const dailyFees = (artic_fees_amount / ((100 - 10) / 100)) * ethPrice; + const dailyRevenue = dailyFees * (protocol_fees / 100); - return { - dailyFees: `${dailyFees}`, - dailyRevenue: `${dailyRevenue}`, - timestamp - } - } catch (error) { - console.error(error) - throw error; + return { + dailyFees: `${dailyFees}`, + dailyRevenue: `${dailyRevenue}`, + timestamp } } -const adapterFees: SimpleAdapter = { +const adapterFees: SimpleAdapter = { adapter: { [CHAIN.BASE]: { fetch: fetchFees, - start: async () => 1691625600, + start: async () => 1691625600, } } } diff --git a/fees/beethoven-x.ts b/fees/beethoven-x.ts index 5d8015a4fb..86450b805d 100644 --- a/fees/beethoven-x.ts +++ b/fees/beethoven-x.ts @@ -3,7 +3,7 @@ import { getBlock } from "../helpers/getBlock"; import { FetchResultFees, SimpleAdapter } from "../adapters/types"; import { CHAIN } from "../helpers/chains"; import * as sdk from "@defillama/sdk"; -import { ethers} from 'ethers' +import { ethers } from 'ethers' import BigNumber from "bignumber.js"; import { getPrices } from "../utils/prices"; @@ -70,122 +70,117 @@ const fetchFees = (chain: Chain) => { const toBlock = await getBlock(toTimestamp, chain, {}) const fromBlock = await getBlock(fromTimestamp, chain, {}) - try { - const logs_balance: ILogs[] = (await sdk.getEventLogs({ - target: vualtAddress[chain], - fromBlock, - toBlock, - topics: [topic0_pools_balance_change], - chain: chain, - })) as ILogs[] - - const rawDataBalanceChange: IBalanceChange[] = logs_balance.map((a: ILogs) => { - const value = contract_interface.parseLog(a) - return { - tokens: value!.args.tokens, - protocolFeeAmounts: value!.args.protocolFeeAmounts - } - }); - - const logs_flash_bot: ILogs[] = (await sdk.getEventLogs({ - target: vualtAddress[chain], - fromBlock, - toBlock, - topics: [topic0_flash_bot], - chain: chain, - })) as ILogs[] + const logs_balance: ILogs[] = (await sdk.getEventLogs({ + target: vualtAddress[chain], + fromBlock, + toBlock, + topics: [topic0_pools_balance_change], + chain: chain, + })) as ILogs[] - const logs_swap: ILogs[] = (await sdk.getEventLogs({ + const rawDataBalanceChange: IBalanceChange[] = logs_balance.map((a: ILogs) => { + const value = contract_interface.parseLog(a) + return { + tokens: value!.args.tokens, + protocolFeeAmounts: value!.args.protocolFeeAmounts + } + }); + + const logs_flash_bot: ILogs[] = (await sdk.getEventLogs({ + target: vualtAddress[chain], + fromBlock, + toBlock, + topics: [topic0_flash_bot], + chain: chain, + })) as ILogs[] + + const logs_swap: ILogs[] = (await sdk.getEventLogs({ + target: vualtAddress[chain], + fromBlock, + toBlock, + topics: [topic0_swap], + chain: chain, + })) as ILogs[] + + const swapRaw: ISwap[] = logs_swap.map((a: ILogs) => { + const value = contract_interface.parseLog(a) + return { + poolId: value!.args.poolId, + tokenIn: value!.args.tokenIn, + tokenOut: value!.args.tokenOut, + amountIn: Number(value!.args.amountIn), + amountOut: Number(value!.args.amountOut), + } as ISwap + }); + const poolIds = [...new Set(swapRaw.map((a: ISwap) => a.poolId))] + const pools = (await sdk.api2.abi.multiCall({ + abi: abis.getPool, + calls: poolIds.map((a: string) => ({ target: vualtAddress[chain], - fromBlock, - toBlock, - topics: [topic0_swap], - chain: chain, - })) as ILogs[] - - const swapRaw: ISwap[] = logs_swap.map((a: ILogs) => { - const value = contract_interface.parseLog(a) - return { - poolId: value!.args.poolId, - tokenIn: value!.args.tokenIn, - tokenOut: value!.args.tokenOut, - amountIn: Number(value!.args.amountIn), - amountOut: Number(value!.args.amountOut), - } as ISwap - }); - const poolIds = [...new Set(swapRaw.map((a: ISwap) => a.poolId))] - const pools = (await sdk.api2.abi.multiCall({ - abi: abis.getPool, - calls: poolIds.map((a: string) => ({ - target: vualtAddress[chain], - params: [a] - })), - chain: chain, - })) - .map((a: any) => a[0]); - - const swapFees = (await sdk.api2.abi.multiCall({ - abi: abis.getSwapFeePercentage, - calls: pools.map((a: string) => ({ - target: a, - })), - chain: chain, - })) ; - - - const rawDataFlashBot: IBalanceChange[] = logs_flash_bot.map((a: ILogs) => { - const value = contract_interface.parseLog(a) - return { - tokens: [value!.args.token], - protocolFeeAmounts: [value!.args.feeAmount] - } - }); - - const coins = [...new Set([...rawDataBalanceChange.flatMap((a: IBalanceChange) => a.tokens), ...rawDataFlashBot.flatMap((a: IBalanceChange) => a.tokens), ...swapRaw.flatMap((a: ISwap) => [a.tokenIn, a.tokenOut])])] - .map((a: string) => `${chain}:${a.toLowerCase()}`) - const prices = await getPrices(coins, timestamp) - - const dailyFee = [...rawDataBalanceChange, ...rawDataFlashBot].map((a: IBalanceChange) => { - return a.tokens.map((b: string, i: number) => { - const price = prices[`${chain}:${b.toLowerCase()}`]?.price || 0; - const decimals = prices[`${chain}:${b.toLowerCase()}`]?.decimals || 0; - if (!price || !decimals) return 0; - const amount = Number(a.protocolFeeAmounts[i].toString()) / 10 ** decimals; - return amount * price; - }).reduce((a: number, b: number) => a + b, 0); - }).flat().reduce((a: number, b: number) => a + b, 0); - - const dailySwapFees: SwapFees[] = swapRaw.map((a: ISwap) => { - const priceIn = prices[`${chain}:${a.tokenIn.toLowerCase()}`]?.price || 0; - const decimalsIn = prices[`${chain}:${a.tokenIn.toLowerCase()}`]?.decimals || 0; - const priceOut = prices[`${chain}:${a.tokenOut.toLowerCase()}`]?.price || 0; - const decimalsOut = prices[`${chain}:${a.tokenOut.toLowerCase()}`]?.decimals || 0; - const amountIn = a.amountIn / 10 ** decimalsIn; - const amountOut = a.amountOut / 10 ** decimalsOut; - const amountIdUSD = (amountIn * priceIn) - const amountOutUSD = (amountOut * priceOut) - const indexPool = poolIds.indexOf(a.poolId); - const fee = (Number(swapFees[indexPool] || 0) / 1e18); - return { - amountIdUSD, - amountOutUSD, - fee - } as SwapFees - }); - const dailySwapFeesUSD = dailySwapFees.reduce((a: number, b: any) => a + b.fee * b.amountIdUSD, 0); - - const dailyFees = dailyFee + dailySwapFeesUSD; - const dailyRevenue = (dailyFees) * (25/100); - const dailySupplySideRevenue = dailyFees - dailyRevenue; + params: [a] + })), + chain: chain, + })) + .map((a: any) => a[0]); + + const swapFees = (await sdk.api2.abi.multiCall({ + abi: abis.getSwapFeePercentage, + calls: pools.map((a: string) => ({ + target: a, + })), + chain: chain, + })); + + + const rawDataFlashBot: IBalanceChange[] = logs_flash_bot.map((a: ILogs) => { + const value = contract_interface.parseLog(a) return { - dailyFees: `${dailyFees}`, - dailyRevenue: `${dailyRevenue}`, - dailySupplySideRevenue: `${dailySupplySideRevenue}`, - timestamp, + tokens: [value!.args.token], + protocolFeeAmounts: [value!.args.feeAmount] } - } catch (e) { - console.error(e) - throw e; + }); + + const coins = [...new Set([...rawDataBalanceChange.flatMap((a: IBalanceChange) => a.tokens), ...rawDataFlashBot.flatMap((a: IBalanceChange) => a.tokens), ...swapRaw.flatMap((a: ISwap) => [a.tokenIn, a.tokenOut])])] + .map((a: string) => `${chain}:${a.toLowerCase()}`) + const prices = await getPrices(coins, timestamp) + + const dailyFee = [...rawDataBalanceChange, ...rawDataFlashBot].map((a: IBalanceChange) => { + return a.tokens.map((b: string, i: number) => { + const price = prices[`${chain}:${b.toLowerCase()}`]?.price || 0; + const decimals = prices[`${chain}:${b.toLowerCase()}`]?.decimals || 0; + if (!price || !decimals) return 0; + const amount = Number(a.protocolFeeAmounts[i].toString()) / 10 ** decimals; + return amount * price; + }).reduce((a: number, b: number) => a + b, 0); + }).flat().reduce((a: number, b: number) => a + b, 0); + + const dailySwapFees: SwapFees[] = swapRaw.map((a: ISwap) => { + const priceIn = prices[`${chain}:${a.tokenIn.toLowerCase()}`]?.price || 0; + const decimalsIn = prices[`${chain}:${a.tokenIn.toLowerCase()}`]?.decimals || 0; + const priceOut = prices[`${chain}:${a.tokenOut.toLowerCase()}`]?.price || 0; + const decimalsOut = prices[`${chain}:${a.tokenOut.toLowerCase()}`]?.decimals || 0; + const amountIn = a.amountIn / 10 ** decimalsIn; + const amountOut = a.amountOut / 10 ** decimalsOut; + const amountIdUSD = (amountIn * priceIn) + const amountOutUSD = (amountOut * priceOut) + const indexPool = poolIds.indexOf(a.poolId); + const fee = (Number(swapFees[indexPool] || 0) / 1e18); + return { + amountIdUSD, + amountOutUSD, + fee + } as SwapFees + }); + const dailySwapFeesUSD = dailySwapFees.reduce((a: number, b: any) => a + b.fee * b.amountIdUSD, 0); + + const dailyFees = dailyFee + dailySwapFeesUSD; + const dailyRevenue = (dailyFees) * (25 / 100); + const dailySupplySideRevenue = dailyFees - dailyRevenue; + return { + dailyFees: `${dailyFees}`, + dailyRevenue: `${dailyRevenue}`, + dailySupplySideRevenue: `${dailySupplySideRevenue}`, + timestamp, } } } diff --git a/fees/benqi-staked-avax.ts b/fees/benqi-staked-avax.ts index 0416be59ee..717a421d5c 100644 --- a/fees/benqi-staked-avax.ts +++ b/fees/benqi-staked-avax.ts @@ -13,38 +13,33 @@ interface ILog { } const fetchFees = async (timestamp: number): Promise => { - try { - const toTimestamp = timestamp - const fromTimestamp = timestamp - 60 * 60 * 24 - const toBlock = await getBlock(toTimestamp, CHAIN.AVAX, {}) - const fromBlock = await getBlock(fromTimestamp, CHAIN.AVAX, {}) - const logs: ILog[] = (await sdk.getEventLogs({ - target: address, - topic: topic0, - toBlock: toBlock, - fromBlock: fromBlock, - chain: CHAIN.AVAX, - topics: [topic0] - })) as ILog[]; - const reward = logs.reduce((acc, log) => { - const amount = Number(log.data) / 10 ** 18 - return acc + amount - },0) - const avaxAddress = `${CHAIN.AVAX}:0x2b2c81e08f1af8835a78bb2a90ae924ace0ea4be` - const prices = await getPrices([avaxAddress], timestamp) - const sAVAXPrice = prices[avaxAddress]?.price || 0; - const dailyFees = (reward * sAVAXPrice) / .90 - const dailySupplySideRevenue = dailyFees * 0.90; - const dailyRevenue = dailyFees * 0.1; - return { - dailyFees: dailyFees.toString(), - dailyRevenue: dailyRevenue.toString(), - dailySupplySideRevenue: dailySupplySideRevenue.toString(), - timestamp - } - } catch (e) { - console.error(e) - throw e + const toTimestamp = timestamp + const fromTimestamp = timestamp - 60 * 60 * 24 + const toBlock = await getBlock(toTimestamp, CHAIN.AVAX, {}) + const fromBlock = await getBlock(fromTimestamp, CHAIN.AVAX, {}) + const logs: ILog[] = (await sdk.getEventLogs({ + target: address, + topic: topic0, + toBlock: toBlock, + fromBlock: fromBlock, + chain: CHAIN.AVAX, + topics: [topic0] + })) as ILog[]; + const reward = logs.reduce((acc, log) => { + const amount = Number(log.data) / 10 ** 18 + return acc + amount + }, 0) + const avaxAddress = `${CHAIN.AVAX}:0x2b2c81e08f1af8835a78bb2a90ae924ace0ea4be` + const prices = await getPrices([avaxAddress], timestamp) + const sAVAXPrice = prices[avaxAddress]?.price || 0; + const dailyFees = (reward * sAVAXPrice) / .90 + const dailySupplySideRevenue = dailyFees * 0.90; + const dailyRevenue = dailyFees * 0.1; + return { + dailyFees: dailyFees.toString(), + dailyRevenue: dailyRevenue.toString(), + dailySupplySideRevenue: dailySupplySideRevenue.toString(), + timestamp } } diff --git a/fees/blur/index.ts b/fees/blur/index.ts index c9c2a6abb4..271fbbd09f 100644 --- a/fees/blur/index.ts +++ b/fees/blur/index.ts @@ -108,7 +108,6 @@ const fetchFees = async (timestamp: number): Promise => { } } catch (e) { await sql.end({ timeout: 5 }) - console.error(e) throw e; } diff --git a/fees/caviar-tangible.ts b/fees/caviar-tangible.ts index 54bd9296aa..7c3e30a27c 100644 --- a/fees/caviar-tangible.ts +++ b/fees/caviar-tangible.ts @@ -18,30 +18,25 @@ interface ILog { const fetchFees = async (timestamp: number): Promise => { const toTimestamp = timestamp; const fromTimestamp = timestamp - 60 * 60 * 24; - try { - const fromBlock = (await getBlock(fromTimestamp, CHAIN.POLYGON, {})); - const toBlock = (await getBlock(toTimestamp, CHAIN.POLYGON, {})); + const fromBlock = (await getBlock(fromTimestamp, CHAIN.POLYGON, {})); + const toBlock = (await getBlock(toTimestamp, CHAIN.POLYGON, {})); - const logs: ILog[] = (await sdk.getEventLogs({ - target: usdc, - toBlock: toBlock, - fromBlock: fromBlock, - chain: CHAIN.POLYGON, - topics: [topic0_evt_transfer, topic1_evt_transfer, topic2_evt_transfer] - })) as ILog[]; - const dailyFees = logs.reduce((acc: number, log: ILog) => { - const amount = Number(log.data) / 10 ** 6; - return acc + amount; - }, 0); - return { - dailyFees: `${dailyFees}`, - dailyHoldersRevenue: `${dailyFees}`, - dailyRevenue: `${dailyFees}`, - timestamp - } - } catch (error) { - console.error(error) - throw error; + const logs: ILog[] = (await sdk.getEventLogs({ + target: usdc, + toBlock: toBlock, + fromBlock: fromBlock, + chain: CHAIN.POLYGON, + topics: [topic0_evt_transfer, topic1_evt_transfer, topic2_evt_transfer] + })) as ILog[]; + const dailyFees = logs.reduce((acc: number, log: ILog) => { + const amount = Number(log.data) / 10 ** 6; + return acc + amount; + }, 0); + return { + dailyFees: `${dailyFees}`, + dailyHoldersRevenue: `${dailyFees}`, + dailyRevenue: `${dailyFees}`, + timestamp } } diff --git a/fees/chainlink-ccip.ts b/fees/chainlink-ccip.ts index 16308a129e..1d4cfdebea 100644 --- a/fees/chainlink-ccip.ts +++ b/fees/chainlink-ccip.ts @@ -84,59 +84,54 @@ const contract_address: IContractAddress = { const fetchFees = (chain: Chain) => { return async (timestamp: number): Promise => { - try { - const toTimestamp = timestamp; - const fromTimestamp = timestamp - 60 * 60 * 24; - const toBlock = await getBlock(toTimestamp, chain, {}); - const fromBlock = await getBlock(fromTimestamp, chain, {}); - const logs: ILog[] = (await Promise.all(contract_address[chain].map((address: string) => sdk.getEventLogs({ - target: address, - toBlock: toBlock, - fromBlock: fromBlock, - chain: chain, - topics: [topic_0] - })))).flat(); - const rawData = logs.map((log: ILog) => { - const data = log.data.replace('0x', ''); - const amount = Number('0x'+data.slice((3*64), (3*64) + 64)); - const address = data.slice((11*64), (11*64) + 64); - const addressString = `0x${address.slice(24)}`; - return { - amount: amount, - address: addressString, - } - }); - const linkETH = `${CHAIN.ETHEREUM}:0x514910771af9ca656af840dff83e8264ecf986ca` - const coins = [...new Set(rawData.map((e: any) => `${chain}:${e.address}`)), linkETH]; - const prices = await getPrices(coins, timestamp); - const dailyFees = rawData.reduce((acc: number, { amount, address }: any) => { - if (chain === CHAIN.BSC && address === '0x404460c6a5ede2d891e8297795264fde62adbb75') { - const price = prices[linkETH].price; - const decimals = prices[linkETH].decimals; - const normalizedAmount = amount / (10 ** decimals); - return acc + (normalizedAmount * price); - } - if (chain === CHAIN.POLYGON && address === '0xb0897686c545045afc77cf20ec7a532e3120e0f1') { - const price = prices[linkETH].price; - const decimals = prices[linkETH].decimals; - const normalizedAmount = amount / (10 ** decimals); - return acc + (normalizedAmount * price); - } - const price = prices[`${chain}:${address}`].price; - const decimals = prices[`${chain}:${address}`].decimals; + const toTimestamp = timestamp; + const fromTimestamp = timestamp - 60 * 60 * 24; + const toBlock = await getBlock(toTimestamp, chain, {}); + const fromBlock = await getBlock(fromTimestamp, chain, {}); + const logs: ILog[] = (await Promise.all(contract_address[chain].map((address: string) => sdk.getEventLogs({ + target: address, + toBlock: toBlock, + fromBlock: fromBlock, + chain: chain, + topics: [topic_0] + })))).flat(); + const rawData = logs.map((log: ILog) => { + const data = log.data.replace('0x', ''); + const amount = Number('0x' + data.slice((3 * 64), (3 * 64) + 64)); + const address = data.slice((11 * 64), (11 * 64) + 64); + const addressString = `0x${address.slice(24)}`; + return { + amount: amount, + address: addressString, + } + }); + const linkETH = `${CHAIN.ETHEREUM}:0x514910771af9ca656af840dff83e8264ecf986ca` + const coins = [...new Set(rawData.map((e: any) => `${chain}:${e.address}`)), linkETH]; + const prices = await getPrices(coins, timestamp); + const dailyFees = rawData.reduce((acc: number, { amount, address }: any) => { + if (chain === CHAIN.BSC && address === '0x404460c6a5ede2d891e8297795264fde62adbb75') { + const price = prices[linkETH].price; + const decimals = prices[linkETH].decimals; + const normalizedAmount = amount / (10 ** decimals); + return acc + (normalizedAmount * price); + } + if (chain === CHAIN.POLYGON && address === '0xb0897686c545045afc77cf20ec7a532e3120e0f1') { + const price = prices[linkETH].price; + const decimals = prices[linkETH].decimals; const normalizedAmount = amount / (10 ** decimals); return acc + (normalizedAmount * price); - }, 0); + } + const price = prices[`${chain}:${address}`].price; + const decimals = prices[`${chain}:${address}`].decimals; + const normalizedAmount = amount / (10 ** decimals); + return acc + (normalizedAmount * price); + }, 0); - return { - timestamp, - dailyFees: `${dailyFees}`, - dailyRevenue: '0' - }; - } catch (e) { - console.error(e); - throw e; - } + return { + timestamp, + dailyFees: `${dailyFees}`, + dailyRevenue: '0' + }; } } diff --git a/fees/chainlink-keepers.ts b/fees/chainlink-keepers.ts index 1f33dead26..e90931a381 100644 --- a/fees/chainlink-keepers.ts +++ b/fees/chainlink-keepers.ts @@ -44,45 +44,40 @@ const fetchKeeper = (chain: Chain) => { return async (timestamp: number, _: ChainBlocks): Promise => { const fromTimestamp = timestamp - 60 * 60 * 24 const toTimestamp = timestamp - try { - const fromBlock = (await getBlock(fromTimestamp, chain, {})); - const toBlock = (await getBlock(toTimestamp, chain, {})); - const logs: ITx[] = (await sdk.getEventLogs({ - target: address_keeper[chain], - fromBlock: fromBlock, - toBlock: toBlock, - topics: [topic0_keeper], - chain: chain - })).map((e: any) => { return { ...e, data: e.data.replace('0x', ''), transactionHash: e.transactionHash, } as ITx }) - .filter((e: ITx) => e.topics.includes(success_topic)); - const tx_hash: string[] = [...new Set([...logs].map((e: ITx) => e.transactionHash))] - const txReceipt: number[] = chain === CHAIN.OPTIMISM ? [] : (await getTxReceipts(chain, tx_hash)) - .map((e: any) => { - const amount = (Number(e?.gasUsed || 0) * Number(e.effectiveGasPrice || 0)) / 10 ** 18 - return amount - }) - const payAmount: number[] = logs.map((tx: ITx) => { - const amount = Number('0x' + tx.data.slice(0, 64)) / 10 ** 18 - return amount; - }); - const linkAddress = "coingecko:chainlink"; - const gasToken = gasTokenId[chain]; - const prices = (await getPrices([linkAddress, gasToken], timestamp)) - const linkPrice = prices[linkAddress].price - const gagPrice = prices[gasToken].price - const dailyFees = payAmount.reduce((a: number, b: number) => a + b, 0); - const dailyFeesUsd = dailyFees * linkPrice; - const dailyGas = txReceipt.reduce((a: number, b: number) => a + b, 0); - const dailyGasUsd = dailyGas * gagPrice; - const dailyRevenue = dailyFeesUsd - dailyGasUsd; - return { - dailyFees: dailyFeesUsd.toString(), - dailyRevenue: chain === CHAIN.OPTIMISM ? undefined : dailyRevenue.toString(), - timestamp - } - } catch (error) { - console.log(error); - throw error; + const fromBlock = (await getBlock(fromTimestamp, chain, {})); + const toBlock = (await getBlock(toTimestamp, chain, {})); + const logs: ITx[] = (await sdk.getEventLogs({ + target: address_keeper[chain], + fromBlock: fromBlock, + toBlock: toBlock, + topics: [topic0_keeper], + chain: chain + })).map((e: any) => { return { ...e, data: e.data.replace('0x', ''), transactionHash: e.transactionHash, } as ITx }) + .filter((e: ITx) => e.topics.includes(success_topic)); + const tx_hash: string[] = [...new Set([...logs].map((e: ITx) => e.transactionHash))] + const txReceipt: number[] = chain === CHAIN.OPTIMISM ? [] : (await getTxReceipts(chain, tx_hash)) + .map((e: any) => { + const amount = (Number(e?.gasUsed || 0) * Number(e.effectiveGasPrice || 0)) / 10 ** 18 + return amount + }) + const payAmount: number[] = logs.map((tx: ITx) => { + const amount = Number('0x' + tx.data.slice(0, 64)) / 10 ** 18 + return amount; + }); + const linkAddress = "coingecko:chainlink"; + const gasToken = gasTokenId[chain]; + const prices = (await getPrices([linkAddress, gasToken], timestamp)) + const linkPrice = prices[linkAddress].price + const gagPrice = prices[gasToken].price + const dailyFees = payAmount.reduce((a: number, b: number) => a + b, 0); + const dailyFeesUsd = dailyFees * linkPrice; + const dailyGas = txReceipt.reduce((a: number, b: number) => a + b, 0); + const dailyGasUsd = dailyGas * gagPrice; + const dailyRevenue = dailyFeesUsd - dailyGasUsd; + return { + dailyFees: dailyFeesUsd.toString(), + dailyRevenue: chain === CHAIN.OPTIMISM ? undefined : dailyRevenue.toString(), + timestamp } } } diff --git a/fees/chainlink-vrf-v2.ts b/fees/chainlink-vrf-v2.ts index ad477176b3..0805c3331b 100644 --- a/fees/chainlink-vrf-v2.ts +++ b/fees/chainlink-vrf-v2.ts @@ -68,49 +68,44 @@ const fetch = (chain: Chain, version: number) => { return async (timestamp: number, _: ChainBlocks): Promise => { const fromTimestamp = timestamp - 60 * 60 * 24 const toTimestamp = timestamp - try { - const fromBlock = (await getBlock(fromTimestamp, chain, {})); - const toBlock = (await getBlock(toTimestamp, chain, {})); - const logs_1: ITx[] = (await sdk.getEventLogs({ - target: version === 1 ? address_v1[chain] : address_v2[chain], - fromBlock: fromBlock, - toBlock: toBlock, - topics: version === 1 ? [topic0_v1] : [topic0_v2], - chain: chain - })).map((e: any) => { return { data: e.data.replace('0x', ''), transactionHash: e.transactionHash } as ITx }); - - const amount_fullfill = logs_1.map((e: ITx) => { - const payment = Number('0x'+e.data.slice(64, 128)) / 10 ** 18 - return payment; - }).reduce((a: number, b: number) => a+b, 0); - - const tx_hash: string[] = [...new Set([...logs_1].map((e: ITx) => e.transactionHash))] - const txReceipt: number[] = chain === CHAIN.OPTIMISM ? [] : (await getTxReceipts(chain, tx_hash)) - .map((e: any) => { - const amount = (Number(e?.gasUsed || 0) * Number(e.effectiveGasPrice || 0)) / 10 ** 18 - return amount - }) - const linkAddress = "coingecko:chainlink"; - const gasToken = gasTokenId[chain]; - const prices = (await getPrices([linkAddress, gasToken], timestamp)); - const dailyGas = txReceipt.reduce((a: number, b: number) => a + b, 0); - const linkPrice = prices[linkAddress].price - const gagPrice = prices[gasToken].price - const dailyGasUsd = dailyGas * gagPrice; - const totalExFees = (amount_fullfill * linkPrice); - const dailyFees = (totalExFees) - const dailyRevenue = dailyFees - dailyGasUsd; - - return { - dailyFees: dailyFees.toString(), - dailyRevenue: chain === CHAIN.OPTIMISM ? undefined : dailyRevenue.toString(), - timestamp - } - - } catch (error) { - console.error(error) - throw error; + const fromBlock = (await getBlock(fromTimestamp, chain, {})); + const toBlock = (await getBlock(toTimestamp, chain, {})); + const logs_1: ITx[] = (await sdk.getEventLogs({ + target: version === 1 ? address_v1[chain] : address_v2[chain], + fromBlock: fromBlock, + toBlock: toBlock, + topics: version === 1 ? [topic0_v1] : [topic0_v2], + chain: chain + })).map((e: any) => { return { data: e.data.replace('0x', ''), transactionHash: e.transactionHash } as ITx }); + + const amount_fullfill = logs_1.map((e: ITx) => { + const payment = Number('0x' + e.data.slice(64, 128)) / 10 ** 18 + return payment; + }).reduce((a: number, b: number) => a + b, 0); + + const tx_hash: string[] = [...new Set([...logs_1].map((e: ITx) => e.transactionHash))] + const txReceipt: number[] = chain === CHAIN.OPTIMISM ? [] : (await getTxReceipts(chain, tx_hash)) + .map((e: any) => { + const amount = (Number(e?.gasUsed || 0) * Number(e.effectiveGasPrice || 0)) / 10 ** 18 + return amount + }) + const linkAddress = "coingecko:chainlink"; + const gasToken = gasTokenId[chain]; + const prices = (await getPrices([linkAddress, gasToken], timestamp)); + const dailyGas = txReceipt.reduce((a: number, b: number) => a + b, 0); + const linkPrice = prices[linkAddress].price + const gagPrice = prices[gasToken].price + const dailyGasUsd = dailyGas * gagPrice; + const totalExFees = (amount_fullfill * linkPrice); + const dailyFees = (totalExFees) + const dailyRevenue = dailyFees - dailyGasUsd; + + return { + dailyFees: dailyFees.toString(), + dailyRevenue: chain === CHAIN.OPTIMISM ? undefined : dailyRevenue.toString(), + timestamp } + } } diff --git a/fees/cipher.ts b/fees/cipher.ts index 31edd4cbf6..d9dc31cbca 100644 --- a/fees/cipher.ts +++ b/fees/cipher.ts @@ -30,50 +30,45 @@ const fetch = async (timestamp: number): Promise => { const fromBlock = (await getBlock(fromTimestamp, CHAIN.ARBITRUM, {})); const toBlock = (await getBlock(toTimestamp, CHAIN.ARBITRUM, {})); - try { - // let _logs: ILog[] = []; - // for(let i = fromBlock; i < toBlock; i += 10000) { - // const logs: ILog[] = (await sdk.getEventLogs({ - // target: FriendtechSharesAddress, - // toBlock: i + 10000, - // fromBlock: i, - // chain: CHAIN.ARBITRUM, - // topics: [topic0_trade] - // }))as ILog[]; - // console.log(logs.length) - // _logs = _logs.concat(logs); - // } - const logs: ILog[] = (await sdk.getEventLogs({ - target: FriendtechSharesAddress, - toBlock: toBlock, - fromBlock: fromBlock, - chain: CHAIN.ARBITRUM, - topics: [topic0_trade] - })) as ILog[]; + // let _logs: ILog[] = []; + // for(let i = fromBlock; i < toBlock; i += 10000) { + // const logs: ILog[] = (await sdk.getEventLogs({ + // target: FriendtechSharesAddress, + // toBlock: i + 10000, + // fromBlock: i, + // chain: CHAIN.ARBITRUM, + // topics: [topic0_trade] + // }))as ILog[]; + // console.log(logs.length) + // _logs = _logs.concat(logs); + // } + const logs: ILog[] = (await sdk.getEventLogs({ + target: FriendtechSharesAddress, + toBlock: toBlock, + fromBlock: fromBlock, + chain: CHAIN.ARBITRUM, + topics: [topic0_trade] + })) as ILog[]; - const fees_details: IFee[] = logs.map((e: ILog) => { - const value = contract_interface.parseLog(e); - const protocolEthAmount = Number(value!.args.protocolEthAmount) / 10 ** 18; - const subjectEthAmount = Number(value!.args.subjectEthAmount) / 10 ** 18; - return { - fees: protocolEthAmount + subjectEthAmount, - rev: protocolEthAmount - } as IFee - }) - const dailyFees = fees_details.reduce((a: number, b: IFee) => a+b.fees, 0) - const dailyRev = fees_details.reduce((a: number, b: IFee) => a+b.rev, 0) - const ethAddress = "ethereum:0x0000000000000000000000000000000000000000"; - const ethPrice = (await getPrices([ethAddress], timestamp))[ethAddress].price; - const dailyFeesUSD = (dailyFees) * ethPrice; - const dailyRevUSD = (dailyRev) * ethPrice; + const fees_details: IFee[] = logs.map((e: ILog) => { + const value = contract_interface.parseLog(e); + const protocolEthAmount = Number(value!.args.protocolEthAmount) / 10 ** 18; + const subjectEthAmount = Number(value!.args.subjectEthAmount) / 10 ** 18; return { - dailyFees: `${dailyFeesUSD}`, - dailyRevenue: `${dailyRevUSD}`, - timestamp - } - } catch (error) { - console.error(error) - throw error; + fees: protocolEthAmount + subjectEthAmount, + rev: protocolEthAmount + } as IFee + }) + const dailyFees = fees_details.reduce((a: number, b: IFee) => a + b.fees, 0) + const dailyRev = fees_details.reduce((a: number, b: IFee) => a + b.rev, 0) + const ethAddress = "ethereum:0x0000000000000000000000000000000000000000"; + const ethPrice = (await getPrices([ethAddress], timestamp))[ethAddress].price; + const dailyFeesUSD = (dailyFees) * ethPrice; + const dailyRevUSD = (dailyRev) * ethPrice; + return { + dailyFees: `${dailyFeesUSD}`, + dailyRevenue: `${dailyRevUSD}`, + timestamp } } @@ -82,8 +77,8 @@ const fetch = async (timestamp: number): Promise => { const adapter: Adapter = { adapter: { [CHAIN.ARBITRUM]: { - fetch: fetch, - start: async () => 1695600000, + fetch: fetch, + start: async () => 1695600000, }, } } diff --git a/fees/crv-usd.ts b/fees/crv-usd.ts index fbb24c8e36..af71000224 100644 --- a/fees/crv-usd.ts +++ b/fees/crv-usd.ts @@ -5,7 +5,7 @@ import { getBlock } from "../helpers/getBlock"; import * as sdk from "@defillama/sdk"; import { getPrices } from "../utils/prices"; -type TContract = { +type TContract = { [s: string | Chain]: string[]; } const controller: TContract = { @@ -27,37 +27,32 @@ interface ILog { const fetchFees = (chain: Chain) => { return async (timestamp: number): Promise => { - try { - const toTimestamp = timestamp - const fromTimestamp = timestamp - 60 * 60 * 24 - const fromBlock = (await getBlock(fromTimestamp, chain, {})); - const toBlock = (await getBlock(toTimestamp, chain, {})); + const toTimestamp = timestamp + const fromTimestamp = timestamp - 60 * 60 * 24 + const fromBlock = (await getBlock(fromTimestamp, chain, {})); + const toBlock = (await getBlock(toTimestamp, chain, {})); - const logs: ILog[] = (await Promise.all(controller[chain].map((address: string) => sdk.getEventLogs({ - target: address, - toBlock: toBlock, - fromBlock: fromBlock, - chain: chain, - topics: [topic0] - })))).flat(); - const crvUSDAddress = `${CHAIN.ETHEREUM}:0xf939E0A03FB07F59A73314E73794Be0E57ac1b4E` - const prices = await getPrices([crvUSDAddress], timestamp); - const crvUSDPrice = prices[crvUSDAddress]?.price || 1; - const dailyFees = logs.reduce((acc: number, log: ILog) => { - const data = log.data.replace('0x', ''); - const fee = (Number('0x' + data.slice(0, 64)) / 1e18) * crvUSDPrice; - return acc + fee; - },0) + const logs: ILog[] = (await Promise.all(controller[chain].map((address: string) => sdk.getEventLogs({ + target: address, + toBlock: toBlock, + fromBlock: fromBlock, + chain: chain, + topics: [topic0] + })))).flat(); + const crvUSDAddress = `${CHAIN.ETHEREUM}:0xf939E0A03FB07F59A73314E73794Be0E57ac1b4E` + const prices = await getPrices([crvUSDAddress], timestamp); + const crvUSDPrice = prices[crvUSDAddress]?.price || 1; + const dailyFees = logs.reduce((acc: number, log: ILog) => { + const data = log.data.replace('0x', ''); + const fee = (Number('0x' + data.slice(0, 64)) / 1e18) * crvUSDPrice; + return acc + fee; + }, 0) - return { - dailyFees: `${dailyFees}`, - dailyHoldersRevenue: `${dailyFees}`, - dailyRevenue: `${dailyFees}`, - timestamp - } - } catch (e) { - console.error(e) - throw e; + return { + dailyFees: `${dailyFees}`, + dailyHoldersRevenue: `${dailyFees}`, + dailyRevenue: `${dailyFees}`, + timestamp } } } diff --git a/fees/cryptex-v2.ts b/fees/cryptex-v2.ts index cb9fd4868d..cf4408e0cd 100644 --- a/fees/cryptex-v2.ts +++ b/fees/cryptex-v2.ts @@ -18,10 +18,10 @@ const products: string[] = [ '0x1cd33f4e6edeee8263aa07924c2760cf2ec8aad0', // TCAP ]; -const make_closed_topic0 = '0x39854479080fac0b5e7c0ecedb0fb02308a72a43cd102c6b9f918653d3400367' -const make_opened_topic0 = '0xf98b31465ac12e92b5cb136ade913276c267463c4395bb1a3999bc88fb837806' -const take_closed_topic0 = '0x63625b85818a29587ee919ee6a968ee0b32f3513f2884b3968001062ba49eb6b' -const take_opened_topic0 = '0xb9726781b72c53f23217f424d70445b222951f008aeac7eece8139caed71ed2d' +const make_closed_topic0 = '0x39854479080fac0b5e7c0ecedb0fb02308a72a43cd102c6b9f918653d3400367' +const make_opened_topic0 = '0xf98b31465ac12e92b5cb136ade913276c267463c4395bb1a3999bc88fb837806' +const take_closed_topic0 = '0x63625b85818a29587ee919ee6a968ee0b32f3513f2884b3968001062ba49eb6b' +const take_opened_topic0 = '0xb9726781b72c53f23217f424d70445b222951f008aeac7eece8139caed71ed2d' const make_closed_event = 'event MakeClosed(address indexed account,uint256 version,uint256 amount)' const make_opened_event = 'event MakeOpened(address indexed account,uint256 version,uint256 amount)' @@ -37,7 +37,7 @@ const contract_interface = new ethers.Interface([ ]); type IMapCoin = { - [s:string]: string; + [s: string]: string; } const coinsId: IMapCoin = { '0x4243b34374cfb0a12f184b92f52035d03d4f7056': 'coingecko:total-crypto-market-cap-token', // TCAP @@ -57,122 +57,117 @@ const fetch = async (timestamp: number): Promise => { const fromTimestamp = timestamp - 60 * 60 * 24 const toTimestamp = timestamp - try { - const fromBlock = (await getBlock(fromTimestamp, CHAIN.ARBITRUM, {})); - const toBlock = (await getBlock(toTimestamp, CHAIN.ARBITRUM, {})); - const make_closed_topic0_logs: ILog[] = (await Promise.all(products.map((address: string) => sdk.getEventLogs({ - target: address, - toBlock: toBlock, - fromBlock: fromBlock, - chain: CHAIN.ARBITRUM, - topics: [make_closed_topic0] - })))).flat(); - - const make_opened_topic0_logs: ILog[] = (await Promise.all(products.map((address: string) => sdk.getEventLogs({ - target: address, - toBlock: toBlock, - fromBlock: fromBlock, - chain: CHAIN.ARBITRUM, - topics: [make_opened_topic0] - })))).flat(); - - const take_closed_topic0_logs: ILog[] = (await Promise.all(products.map((address: string) => sdk.getEventLogs({ - target: address, - toBlock: toBlock, - fromBlock: fromBlock, - chain: CHAIN.ARBITRUM, - topics: [take_closed_topic0] - })))).flat(); - - const take_opened_topic0_logs: ILog[] = (await Promise.all(products.map((address: string) => sdk.getEventLogs({ - target: address, - toBlock: toBlock, - fromBlock: fromBlock, - chain: CHAIN.ARBITRUM, - topics: [take_opened_topic0] - })))).flat(); - - const [makerFee, takerFee] = await Promise.all( - ['makerFee', 'takerFee'].map((method: string) => - sdk.api2.abi.multiCall({ - abi: abis[method], - calls: products.map((address: string) => ({ - target: address, - })), - chain: CHAIN.ARBITRUM - }) - ) - ); - - const makerFees = makerFee.map((res: any) => Number(res) / 10 ** 18); - const takerFees = takerFee.map((res: any) => Number(res) / 10 ** 18); - - const all: ILog[] = [ - ...make_closed_topic0_logs, - ...make_opened_topic0_logs, - ...take_closed_topic0_logs, - ...take_opened_topic0_logs - ] - const versions = [...new Set(all.map(e => contract_interface.parseLog(e)).map(e => Number(e!.args.version)))]; - const price_ = (await sdk.api2.abi.multiCall({ - abi: abis.atVersion, - calls: versions.map((version: number) => ({ - target: products[0], - params: [version] - })), - chain: CHAIN.ARBITRUM - })) - const _prices: IPrice = {} - price_.forEach((e: any) => { - const raw_price: string = e.price; - const version: string = e.version; - const price = Number(raw_price.toString().replace('-', '')) / 10 ** 18; - _prices[version] = price; - }); - - const maker_logs: ILog[] = [ - ...make_closed_topic0_logs, - ...make_opened_topic0_logs, - ] - const taker_logs: ILog[] = [ - ...take_closed_topic0_logs, - ...take_opened_topic0_logs - ] - - const makerFeesAmount = maker_logs.map((a: ILog) => { - const value = contract_interface.parseLog(a); - const price = _prices[value!.args.version] - const findIndex = products.findIndex(p => p.toLowerCase() === a.address.toLowerCase()); - const fees = makerFees[findIndex] - return ((Number(value!.args.amount) / 1e18) * price) * fees; - }).reduce((a: number,b: number) => a + b, 0) - - const takerFeesAmount = taker_logs.map((a: ILog) => { - const value = contract_interface.parseLog(a); - const price = _prices[value!.args.version] - const findIndex = products.findIndex(p => p.toLowerCase() === a.address.toLowerCase()); - const fees = takerFees[findIndex] - return ((Number(value!.args.amount) / 1e18) * price) * fees; - }).reduce((a: number,b: number) => a + b, 0) - - const dailyFees = (makerFeesAmount + takerFeesAmount); - const dailyRevenue = dailyFees; - return { - dailyFees: `${dailyFees}`, - dailyRevenue: `${dailyRevenue}`, - timestamp - } - } catch (error) { - console.error(error); - throw error; + const fromBlock = (await getBlock(fromTimestamp, CHAIN.ARBITRUM, {})); + const toBlock = (await getBlock(toTimestamp, CHAIN.ARBITRUM, {})); + const make_closed_topic0_logs: ILog[] = (await Promise.all(products.map((address: string) => sdk.getEventLogs({ + target: address, + toBlock: toBlock, + fromBlock: fromBlock, + chain: CHAIN.ARBITRUM, + topics: [make_closed_topic0] + })))).flat(); + + const make_opened_topic0_logs: ILog[] = (await Promise.all(products.map((address: string) => sdk.getEventLogs({ + target: address, + toBlock: toBlock, + fromBlock: fromBlock, + chain: CHAIN.ARBITRUM, + topics: [make_opened_topic0] + })))).flat(); + + const take_closed_topic0_logs: ILog[] = (await Promise.all(products.map((address: string) => sdk.getEventLogs({ + target: address, + toBlock: toBlock, + fromBlock: fromBlock, + chain: CHAIN.ARBITRUM, + topics: [take_closed_topic0] + })))).flat(); + + const take_opened_topic0_logs: ILog[] = (await Promise.all(products.map((address: string) => sdk.getEventLogs({ + target: address, + toBlock: toBlock, + fromBlock: fromBlock, + chain: CHAIN.ARBITRUM, + topics: [take_opened_topic0] + })))).flat(); + + const [makerFee, takerFee] = await Promise.all( + ['makerFee', 'takerFee'].map((method: string) => + sdk.api2.abi.multiCall({ + abi: abis[method], + calls: products.map((address: string) => ({ + target: address, + })), + chain: CHAIN.ARBITRUM + }) + ) + ); + + const makerFees = makerFee.map((res: any) => Number(res) / 10 ** 18); + const takerFees = takerFee.map((res: any) => Number(res) / 10 ** 18); + + const all: ILog[] = [ + ...make_closed_topic0_logs, + ...make_opened_topic0_logs, + ...take_closed_topic0_logs, + ...take_opened_topic0_logs + ] + const versions = [...new Set(all.map(e => contract_interface.parseLog(e)).map(e => Number(e!.args.version)))]; + const price_ = (await sdk.api2.abi.multiCall({ + abi: abis.atVersion, + calls: versions.map((version: number) => ({ + target: products[0], + params: [version] + })), + chain: CHAIN.ARBITRUM + })) + const _prices: IPrice = {} + price_.forEach((e: any) => { + const raw_price: string = e.price; + const version: string = e.version; + const price = Number(raw_price.toString().replace('-', '')) / 10 ** 18; + _prices[version] = price; + }); + + const maker_logs: ILog[] = [ + ...make_closed_topic0_logs, + ...make_opened_topic0_logs, + ] + const taker_logs: ILog[] = [ + ...take_closed_topic0_logs, + ...take_opened_topic0_logs + ] + + const makerFeesAmount = maker_logs.map((a: ILog) => { + const value = contract_interface.parseLog(a); + const price = _prices[value!.args.version] + const findIndex = products.findIndex(p => p.toLowerCase() === a.address.toLowerCase()); + const fees = makerFees[findIndex] + return ((Number(value!.args.amount) / 1e18) * price) * fees; + }).reduce((a: number, b: number) => a + b, 0) + + const takerFeesAmount = taker_logs.map((a: ILog) => { + const value = contract_interface.parseLog(a); + const price = _prices[value!.args.version] + const findIndex = products.findIndex(p => p.toLowerCase() === a.address.toLowerCase()); + const fees = takerFees[findIndex] + return ((Number(value!.args.amount) / 1e18) * price) * fees; + }).reduce((a: number, b: number) => a + b, 0) + + const dailyFees = (makerFeesAmount + takerFeesAmount); + const dailyRevenue = dailyFees; + return { + dailyFees: `${dailyFees}`, + dailyRevenue: `${dailyRevenue}`, + timestamp } } const adapter: Adapter = { adapter: { [CHAIN.ARBITRUM]: { - fetch: fetch, - start: async () => 1684540800 + fetch: fetch, + start: async () => 1684540800 } } } diff --git a/fees/defi-saver.ts b/fees/defi-saver.ts index 353289d0fb..6fdc0df089 100644 --- a/fees/defi-saver.ts +++ b/fees/defi-saver.ts @@ -48,7 +48,6 @@ const fetch = async (timestamp: number): Promise => { } } catch (error) { sql.end({ timeout: 3 }) - console.error(error); throw error; } diff --git a/fees/e3.ts b/fees/e3.ts index 0d8b5bf949..025955edd5 100644 --- a/fees/e3.ts +++ b/fees/e3.ts @@ -21,133 +21,127 @@ const event_swap = 'event Swap(address indexed sender,address indexed to,uint24 const topic0 = '0xad7d6f97abf51ce18e17a38f4d70e975be9c0708474987bb3e26ad21bd93ca70'; const FACTORY_ADDRESS = '0x8597db3ba8de6baadeda8cba4dac653e24a0e57b'; -const contract_interface = new ethers.Interface([ event_swap]); +const contract_interface = new ethers.Interface([event_swap]); type TABI = { [k: string]: string; } const ABIs: TABI = { - "getNumberOfLBPairs": "uint256:getNumberOfLBPairs", - "getLBPairAtIndex": "function getLBPairAtIndex(uint256 index) view returns (address lbPair)" + "getNumberOfLBPairs": "uint256:getNumberOfLBPairs", + "getLBPairAtIndex": "function getLBPairAtIndex(uint256 index) view returns (address lbPair)" } const graph = (_chain: Chain) => { return async (timestamp: number) => { const fromTimestamp = timestamp - 60 * 60 * 24 const toTimestamp = timestamp - try { - - const poolLength = (await sdk.api2.abi.call({ + const poolLength = (await sdk.api2.abi.call({ + target: FACTORY_ADDRESS, + chain: _chain, + abi: ABIs.getNumberOfLBPairs, + })); + + const poolsRes = await sdk.api2.abi.multiCall({ + abi: ABIs.getLBPairAtIndex, + calls: Array.from(Array(Number(poolLength)).keys()).map((i) => ({ target: FACTORY_ADDRESS, - chain: _chain, - abi: ABIs.getNumberOfLBPairs, - })); - - const poolsRes = await sdk.api2.abi.multiCall({ - abi: ABIs.getLBPairAtIndex, - calls: Array.from(Array(Number(poolLength)).keys()).map((i) => ({ - target: FACTORY_ADDRESS, - params: i, - })), - chain: _chain - }); - - const lpTokens = poolsRes - - const [underlyingToken0, underlyingToken1] = await Promise.all( - ['address:getTokenX', 'address:getTokenY'].map((method: string) => - sdk.api2.abi.multiCall({ - abi: method, - calls: lpTokens.map((address: string) => ({ - target: address, - })), - chain: _chain - }) - ) - ); - - const tokens0 = underlyingToken0; - const tokens1 = underlyingToken1; - const fromBlock = (await getBlock(fromTimestamp, _chain, {})); - const toBlock = (await getBlock(toTimestamp, _chain, {})); - - const logs: ILog[][] = (await Promise.all(lpTokens.map((address: string) => sdk.getEventLogs({ - target: address, - toBlock: toBlock, - fromBlock: fromBlock, - chain: _chain, - topics: [topic0] - })))) as any; - - const rawCoins = [...tokens0, ...tokens1].map((e: string) => `${_chain}:${e}`); - const coins = [...new Set(rawCoins)] - const prices = await getPrices(coins, timestamp); - - - const untrackVolumes: any[] = lpTokens.map((_: string, index: number) => { - const token0Decimals = prices[`${_chain}:${tokens0[index]}`]?.decimals || 0 - const token1Decimals = prices[`${_chain}:${tokens1[index]}`]?.decimals || 0 - const log: IAmount[] = logs[index] - .map((e: ILog) => { return { ...e } }) - .map((p: ILog) => { - const value = contract_interface.parseLog(p); - const protocolFeesX = Number('0x'+'0'.repeat(32)+value!.args.protocolFees.replace('0x', '').slice(0, 32)) / 10 ** token1Decimals - const protocolFeesY = Number('0x'+'0'.repeat(32)+value!.args.protocolFees.replace('0x', '').slice(32, 64)) / 10 ** token0Decimals - const totalFeesX = Number('0x'+'0'.repeat(32)+value!.args.totalFees.replace('0x', '').slice(0, 32)) / 10 ** token1Decimals; - const totalFeesY = Number('0x'+'0'.repeat(32)+value!.args.totalFees.replace('0x', '').slice(32, 64)) / 10 ** token0Decimals; - return { - protocolFeesX, - protocolFeesY, - totalFeesX, - totalFeesY, - // tx: p.transactionHash, // for debugging - // token0Decimals, - // token1Decimals - } as IAmount - }); - - const token0Price = (prices[`${_chain}:${tokens0[index]}`]?.price || 0); - const token1Price = (prices[`${_chain}:${tokens1[index]}`]?.price || 0); - const protocolFeesX = log - .reduce((a: number, b: IAmount) => Number(b.protocolFeesX) + a, 0) * token1Price; - const protocolFeesY = log - .reduce((a: number, b: IAmount) => Number(b.protocolFeesY) + a, 0) * token0Price; - const totalFeesX = log - .reduce((a: number, b: IAmount) => Number(b.totalFeesX) + a, 0) * token1Price; - const totalFeesY = log - .reduce((a: number, b: IAmount) => Number(b.totalFeesY) + a, 0) * token0Price; - - return ( { - totalFees: (totalFeesX + totalFeesY), - protocolFees: (protocolFeesX + protocolFeesY) - }); + params: i, + })), + chain: _chain + }); + + const lpTokens = poolsRes + + const [underlyingToken0, underlyingToken1] = await Promise.all( + ['address:getTokenX', 'address:getTokenY'].map((method: string) => + sdk.api2.abi.multiCall({ + abi: method, + calls: lpTokens.map((address: string) => ({ + target: address, + })), + chain: _chain + }) + ) + ); + + const tokens0 = underlyingToken0; + const tokens1 = underlyingToken1; + const fromBlock = (await getBlock(fromTimestamp, _chain, {})); + const toBlock = (await getBlock(toTimestamp, _chain, {})); + + const logs: ILog[][] = (await Promise.all(lpTokens.map((address: string) => sdk.getEventLogs({ + target: address, + toBlock: toBlock, + fromBlock: fromBlock, + chain: _chain, + topics: [topic0] + })))) as any; + + const rawCoins = [...tokens0, ...tokens1].map((e: string) => `${_chain}:${e}`); + const coins = [...new Set(rawCoins)] + const prices = await getPrices(coins, timestamp); + + + const untrackVolumes: any[] = lpTokens.map((_: string, index: number) => { + const token0Decimals = prices[`${_chain}:${tokens0[index]}`]?.decimals || 0 + const token1Decimals = prices[`${_chain}:${tokens1[index]}`]?.decimals || 0 + const log: IAmount[] = logs[index] + .map((e: ILog) => { return { ...e } }) + .map((p: ILog) => { + const value = contract_interface.parseLog(p); + const protocolFeesX = Number('0x' + '0'.repeat(32) + value!.args.protocolFees.replace('0x', '').slice(0, 32)) / 10 ** token1Decimals + const protocolFeesY = Number('0x' + '0'.repeat(32) + value!.args.protocolFees.replace('0x', '').slice(32, 64)) / 10 ** token0Decimals + const totalFeesX = Number('0x' + '0'.repeat(32) + value!.args.totalFees.replace('0x', '').slice(0, 32)) / 10 ** token1Decimals; + const totalFeesY = Number('0x' + '0'.repeat(32) + value!.args.totalFees.replace('0x', '').slice(32, 64)) / 10 ** token0Decimals; + return { + protocolFeesX, + protocolFeesY, + totalFeesX, + totalFeesY, + // tx: p.transactionHash, // for debugging + // token0Decimals, + // token1Decimals + } as IAmount }); - const dailyFees = untrackVolumes.reduce((a: number, b: any) => a + b.totalFees, 0); - const dailyProtocolFees = untrackVolumes.reduce((a: number, b: any) => a + b.protocolFees, 0); - return { - dailyFees: `${dailyFees}`, - dailyUserFees: `${dailyFees}`, - dailyProtocolRevenue: `${dailyProtocolFees}`, - dailyRevenue: `${dailyProtocolFees}`, - dailyHoldersRevenue: `${dailyProtocolFees}`, - dailySupplySideRevenue: `${dailyFees-dailyProtocolFees}`, - timestamp, - }; - } catch(error) { - console.error(error); - throw error; - } + const token0Price = (prices[`${_chain}:${tokens0[index]}`]?.price || 0); + const token1Price = (prices[`${_chain}:${tokens1[index]}`]?.price || 0); + const protocolFeesX = log + .reduce((a: number, b: IAmount) => Number(b.protocolFeesX) + a, 0) * token1Price; + const protocolFeesY = log + .reduce((a: number, b: IAmount) => Number(b.protocolFeesY) + a, 0) * token0Price; + const totalFeesX = log + .reduce((a: number, b: IAmount) => Number(b.totalFeesX) + a, 0) * token1Price; + const totalFeesY = log + .reduce((a: number, b: IAmount) => Number(b.totalFeesY) + a, 0) * token0Price; + + return ({ + totalFees: (totalFeesX + totalFeesY), + protocolFees: (protocolFeesX + protocolFeesY) + }); + }); + + const dailyFees = untrackVolumes.reduce((a: number, b: any) => a + b.totalFees, 0); + const dailyProtocolFees = untrackVolumes.reduce((a: number, b: any) => a + b.protocolFees, 0); + return { + dailyFees: `${dailyFees}`, + dailyUserFees: `${dailyFees}`, + dailyProtocolRevenue: `${dailyProtocolFees}`, + dailyRevenue: `${dailyProtocolFees}`, + dailyHoldersRevenue: `${dailyProtocolFees}`, + dailySupplySideRevenue: `${dailyFees - dailyProtocolFees}`, + timestamp, + }; } } const methodology = { - UserFees: "Eâ…¢ users pay a Trading fee on each swap. Includes Flash Loan Fees.", - Fees: "Net Trading fees paid is the Sum of fees sent to LP & Protocol Fees", - Revenue: "A variable % of the trading fee is collected as Protocol Fees.", - ProtocolRevenue: "100% of Revenue is collected by Protocol Treasury.", - HoldersRevenue: "100% of Revenue is used to buyback ELITE.", - SupplySideRevenue: "The portion of trading fees paid to liquidity providers." + UserFees: "Eâ…¢ users pay a Trading fee on each swap. Includes Flash Loan Fees.", + Fees: "Net Trading fees paid is the Sum of fees sent to LP & Protocol Fees", + Revenue: "A variable % of the trading fee is collected as Protocol Fees.", + ProtocolRevenue: "100% of Revenue is collected by Protocol Treasury.", + HoldersRevenue: "100% of Revenue is used to buyback ELITE.", + SupplySideRevenue: "The portion of trading fees paid to liquidity providers." } const adapter: SimpleAdapter = { diff --git a/fees/equalizer-exchange.ts b/fees/equalizer-exchange.ts index 50a18c6a8b..a04dbb06af 100644 --- a/fees/equalizer-exchange.ts +++ b/fees/equalizer-exchange.ts @@ -58,196 +58,195 @@ const VOTER_ABI: TABI = { const fetch = async (timestamp: number): Promise => { const fromTimestamp = timestamp - 60 * 60 * 24 const toTimestamp = timestamp - try { - - const poolLength = (await sdk.api2.abi.call({ - target: FACTORY_ADDRESS, - chain: CHAIN_SLUG, - abi: ABIs.allPairsLength, - })); - - const poolsRes = await sdk.api2.abi.multiCall({ - abi: ABIs.allPairs, - target: FACTORY_ADDRESS, - calls: Array.from(Array(Number(poolLength)).keys()), - chain: CHAIN_SLUG - }); - const lpTokens = poolsRes - - const [underlyingToken0, underlyingToken1] = await Promise.all( - ['address:token0', 'address:token1'].map((method) => - sdk.api2.abi.multiCall({ - abi: method, - calls: lpTokens.map((address: string) => ({ - target: address, - })), - chain: CHAIN_SLUG - }) - ) - ); - - const tokens0 = underlyingToken0; - const tokens1 = underlyingToken1; - - - const poolsGauges = await sdk.api2.abi.multiCall({ - abi: VOTER_ABI.gauges, - target: VOTER_ADDRESS, - calls: lpTokens, - chain: CHAIN_SLUG - }); + const poolLength = (await sdk.api2.abi.call({ + target: FACTORY_ADDRESS, + chain: CHAIN_SLUG, + abi: ABIs.allPairsLength, + })); - const voterGauges = poolsGauges.filter((_vg: string) => - _vg !== '0x0000000000000000000000000000000000000000' - ); + const poolsRes = await sdk.api2.abi.multiCall({ + abi: ABIs.allPairs, + target: FACTORY_ADDRESS, + calls: Array.from(Array(Number(poolLength)).keys()), + chain: CHAIN_SLUG + }); + const lpTokens = poolsRes + const [underlyingToken0, underlyingToken1] = await Promise.all( + ['address:token0', 'address:token1'].map((method) => + sdk.api2.abi.multiCall({ + abi: method, + calls: lpTokens.map((address: string) => ({ + target: address, + })), + chain: CHAIN_SLUG + }) + ) + ); - const poolsGaugesToBribes = await sdk.api2.abi.multiCall({ - abi: VOTER_ABI.bribes, - target: VOTER_ADDRESS, - calls: voterGauges, - chain: CHAIN_SLUG - }); + const tokens0 = underlyingToken0; + const tokens1 = underlyingToken1; - const voterBribes = poolsGaugesToBribes; + const poolsGauges = await sdk.api2.abi.multiCall({ + abi: VOTER_ABI.gauges, + target: VOTER_ADDRESS, + calls: lpTokens, + chain: CHAIN_SLUG + }); + const voterGauges = poolsGauges.filter((_vg: string) => + _vg !== '0x0000000000000000000000000000000000000000' + ); - const fromBlock = (await getBlock(fromTimestamp, CHAIN_SLUG, {})); - const toBlock = (await getBlock(toTimestamp, CHAIN_SLUG, {})); + const poolsGaugesToBribes = await sdk.api2.abi.multiCall({ + abi: VOTER_ABI.bribes, + target: VOTER_ADDRESS, + calls: voterGauges, + chain: CHAIN_SLUG + }); - const tradefeeLogs: ILog[][] = (await Promise.all(lpTokens.map((address: string) => sdk.getEventLogs({ - target: address, - toBlock: toBlock, - fromBlock: fromBlock, - chain: CHAIN_SLUG, - topics: [TOPIC_Fees] - })))) as ILog[][]; + const voterBribes = poolsGaugesToBribes; - const bribeAndFeeLogs: ILog[][] = (await Promise.all(voterBribes.map((address: string) => sdk.getEventLogs({ - target: address, - toBlock: toBlock, - fromBlock: fromBlock, - chain: CHAIN_SLUG, - topics: [TOPIC_NotifyRewardAmount] - })))) as ILog[][]; - var allBribedTokens: string[] = new Array(0); - const listOfBribedTokensByPool: string[][] = bribeAndFeeLogs.map((perBribeLogs: ILog[]) => { - const _innerBT: string[] = perBribeLogs.map((e: ILog) => { - const _l = INTERFACE_N.parseLog(e); - if (_l == null) { return "" } - const _t = `${CHAIN_USED}:${_l.args.reward.toLowerCase()}`; - return _t; - //return `${CHAIN_USED}:${e.topics[2].toLowerCase()}`; - }); - allBribedTokens = allBribedTokens.concat(_innerBT); - return _innerBT; - }); + const fromBlock = (await getBlock(fromTimestamp, CHAIN_SLUG, {})); + const toBlock = (await getBlock(toTimestamp, CHAIN_SLUG, {})); - allBribedTokens.filter((_ta: string) => { _ta != "" }) + const tradefeeLogs: ILog[][] = (await Promise.all(lpTokens.map((address: string) => sdk.getEventLogs({ + target: address, + toBlock: toBlock, + fromBlock: fromBlock, + chain: CHAIN_SLUG, + topics: [TOPIC_Fees] + })))) as ILog[][]; + const bribeAndFeeLogs: ILog[][] = (await Promise.all(voterBribes.map((address: string) => sdk.getEventLogs({ + target: address, + toBlock: toBlock, + fromBlock: fromBlock, + chain: CHAIN_SLUG, + topics: [TOPIC_NotifyRewardAmount] + })))) as ILog[][]; + var allBribedTokens: string[] = new Array(0); + const listOfBribedTokensByPool: string[][] = bribeAndFeeLogs.map((perBribeLogs: ILog[]) => { + const _innerBT: string[] = perBribeLogs.map((e: ILog) => { + const _l = INTERFACE_N.parseLog(e); + if (_l == null) { return "" } + const _t = `${CHAIN_USED}:${_l.args.reward.toLowerCase()}`; + return _t; + //return `${CHAIN_USED}:${e.topics[2].toLowerCase()}`; + }); + allBribedTokens = allBribedTokens.concat(_innerBT); + return _innerBT; + }); - const rawCoins = [...tokens0, ...tokens1, ...allBribedTokens].map((e: string) => `${CHAIN_SLUG}:${e}`); - const coins = [...new Set(rawCoins)]; - - // const prices = await getPrices(coins, timestamp); - // { getPrices } function breaks above 100 tokens..splitting into chunks of 100 + allBribedTokens.filter((_ta: string) => { _ta != "" }) - const coins_split: string[][] = []; - for (let i = 0; i < coins.length; i += 100) { - coins_split.push(coins.slice(i, i + 100)) - } - const prices_result: any = (await Promise.all(coins_split.map((a: string[]) => getPrices(a, timestamp)))).flat().flat().flat(); - const prices: TPrice = Object.assign({}, {}); - prices_result.map((a: any) => Object.assign(prices, a)) - const tradefees: number[] = lpTokens.map((_: string, index: number) => { - const token0Decimals = (prices[`${CHAIN_SLUG}:${tokens0[index]}`]?.decimals || 0) - const token1Decimals = (prices[`${CHAIN_SLUG}:${tokens1[index]}`]?.decimals || 0) - const tradefeesLog: IAmount[] = tradefeeLogs[index] - .map((e: ILog) => { return { ...e, data: e.data.replace('0x', '') } }) - .map((p: ILog) => { - const amount0 = Number('0x' + p.data.slice(0, 64)) / 10 ** token0Decimals; - const amount1 = Number('0x' + p.data.slice(64, 128)) / 10 ** token1Decimals; - return { - amount0, - amount1 - } as IAmount - }) as IAmount[]; - const token0Price = (prices[`${CHAIN_SLUG}:${tokens0[index]}`]?.price || 0); - const token1Price = (prices[`${CHAIN_SLUG}:${tokens1[index]}`]?.price || 0); - const feesAmount0 = tradefeesLog - .reduce((a: number, b: IAmount) => Number(b.amount0) + a, 0) * token0Price; - const feesAmount1 = tradefeesLog - .reduce((a: number, b: IAmount) => Number(b.amount1) + a, 0) * token1Price; - const feesUSD = feesAmount0 + feesAmount1; - return feesUSD; - }); + const rawCoins = [...tokens0, ...tokens1, ...allBribedTokens].map((e: string) => `${CHAIN_SLUG}:${e}`); + const coins = [...new Set(rawCoins)]; + // const prices = await getPrices(coins, timestamp); + // { getPrices } function breaks above 100 tokens..splitting into chunks of 100 - - const notifiedFees: number[] = voterBribes.map((_: string, index: number) => { - const notifiedFeesLog: IAmountUSD[] = bribeAndFeeLogs[index] - .map((e: ILog) => { return { ...e } }) - .map((p: ILog) => { - const _log = INTERFACE_N.parseLog(p); - if (_log == null || _log.args.from != voterGauges[index]) { - const amount = 0; - return { amount } as IAmountUSD - } - const _token = _log.args.reward; - const _price = (prices[`${CHAIN_SLUG}:${_token}`]?.price || 0); - const _deci = prices[`${CHAIN_SLUG}:${_token}`]?.decimals || 0; - //console.log("_log.args.from", _log.args.from); - const amount = Number(p.data) / 10 ** _deci * _price; + const coins_split: string[][] = []; + for (let i = 0; i < coins.length; i += 100) { + coins_split.push(coins.slice(i, i + 100)) + } + const prices_result: any = (await Promise.all(coins_split.map((a: string[]) => getPrices(a, timestamp)))).flat().flat().flat(); + const prices: TPrice = Object.assign({}, {}); + prices_result.map((a: any) => Object.assign(prices, a)) + + + + const tradefees: number[] = lpTokens.map((_: string, index: number) => { + const token0Decimals = (prices[`${CHAIN_SLUG}:${tokens0[index]}`]?.decimals || 0) + const token1Decimals = (prices[`${CHAIN_SLUG}:${tokens1[index]}`]?.decimals || 0) + const tradefeesLog: IAmount[] = tradefeeLogs[index] + .map((e: ILog) => { return { ...e, data: e.data.replace('0x', '') } }) + .map((p: ILog) => { + const amount0 = Number('0x' + p.data.slice(0, 64)) / 10 ** token0Decimals; + const amount1 = Number('0x' + p.data.slice(64, 128)) / 10 ** token1Decimals; + return { + amount0, + amount1 + } as IAmount + }) as IAmount[]; + const token0Price = (prices[`${CHAIN_SLUG}:${tokens0[index]}`]?.price || 0); + const token1Price = (prices[`${CHAIN_SLUG}:${tokens1[index]}`]?.price || 0); + + const feesAmount0 = tradefeesLog + .reduce((a: number, b: IAmount) => Number(b.amount0) + a, 0) * token0Price; + const feesAmount1 = tradefeesLog + .reduce((a: number, b: IAmount) => Number(b.amount1) + a, 0) * token1Price; + + const feesUSD = feesAmount0 + feesAmount1; + return feesUSD; + }); + + + + const notifiedFees: number[] = voterBribes.map((_: string, index: number) => { + const notifiedFeesLog: IAmountUSD[] = bribeAndFeeLogs[index] + .map((e: ILog) => { return { ...e } }) + .map((p: ILog) => { + const _log = INTERFACE_N.parseLog(p); + if (_log == null || _log.args.from != voterGauges[index]) { + const amount = 0; return { amount } as IAmountUSD - }) as IAmountUSD[]; + } + const _token = _log.args.reward; + const _price = (prices[`${CHAIN_SLUG}:${_token}`]?.price || 0); + const _deci = prices[`${CHAIN_SLUG}:${_token}`]?.decimals || 0; + //console.log("_log.args.from", _log.args.from); + const amount = Number(p.data) / 10 ** _deci * _price; + return { amount } as IAmountUSD + }) as IAmountUSD[]; - const notifiedFeeAmount = notifiedFeesLog - .reduce((a: number, b: IAmountUSD) => Number(b.amount) + a, 0); + const notifiedFeeAmount = notifiedFeesLog + .reduce((a: number, b: IAmountUSD) => Number(b.amount) + a, 0); - return notifiedFeeAmount; - }); + return notifiedFeeAmount; + }); - const notifiedBribes: number[] = voterBribes.map((_: string, index: number) => { - const bribesLog: IAmountUSD[] = bribeAndFeeLogs[index] - .map((e: ILog) => { return { ...e } }) - .map((p: ILog) => { - const _log = INTERFACE_N.parseLog(p); - if (_log == null || _log.args.from == voterGauges[index]) { - const amount = 0; - return { amount } as IAmountUSD - } - const _token = _log.args.reward; - const _price = (prices[`${CHAIN_SLUG}:${_token}`]?.price || 0); - const _deci = prices[`${CHAIN_SLUG}:${_token}`]?.decimals || 0; - const amount = Number(p.data) / 10 ** _deci * _price; + const notifiedBribes: number[] = voterBribes.map((_: string, index: number) => { + const bribesLog: IAmountUSD[] = bribeAndFeeLogs[index] + .map((e: ILog) => { return { ...e } }) + .map((p: ILog) => { + const _log = INTERFACE_N.parseLog(p); + if (_log == null || _log.args.from == voterGauges[index]) { + const amount = 0; return { amount } as IAmountUSD - }) as IAmountUSD[]; + } + const _token = _log.args.reward; + const _price = (prices[`${CHAIN_SLUG}:${_token}`]?.price || 0); + const _deci = prices[`${CHAIN_SLUG}:${_token}`]?.decimals || 0; + const amount = Number(p.data) / 10 ** _deci * _price; + return { amount } as IAmountUSD + }) as IAmountUSD[]; - const bribedAmount = bribesLog.reduce((a: number, b: IBribedAmount) => Number(b.amount) + a, 0); + const bribedAmount = bribesLog.reduce((a: number, b: IBribedAmount) => Number(b.amount) + a, 0); - return bribedAmount; - }); + return bribedAmount; + }); @@ -255,23 +254,19 @@ const fetch = async (timestamp: number): Promise => { - const dailyFees = tradefees.reduce((a: number, b: number) => a + b, 0) - const dailyRevenueFees = notifiedFees.reduce((a: number, b: number) => a + b, 0) - const dailyRevenueBribes = notifiedBribes.reduce((a: number, b: number) => a + b, 0) + const dailyFees = tradefees.reduce((a: number, b: number) => a + b, 0) + const dailyRevenueFees = notifiedFees.reduce((a: number, b: number) => a + b, 0) + const dailyRevenueBribes = notifiedBribes.reduce((a: number, b: number) => a + b, 0) - return { - dailyFees: `${dailyFees}`, - dailyRevenue: `${dailyRevenueFees}`, - dailyHoldersRevenue: `${dailyRevenueFees}`, - dailyBribesRevenue: `${dailyRevenueBribes}`, - timestamp, - }; - } catch (error) { - console.error(error); - throw error; - } + return { + dailyFees: `${dailyFees}`, + dailyRevenue: `${dailyRevenueFees}`, + dailyHoldersRevenue: `${dailyRevenueFees}`, + dailyBribesRevenue: `${dailyRevenueBribes}`, + timestamp, + }; } const adapter: SimpleAdapter = { diff --git a/fees/first-crypto-bank/index.ts b/fees/first-crypto-bank/index.ts index 42a953722d..9e329e1c54 100644 --- a/fees/first-crypto-bank/index.ts +++ b/fees/first-crypto-bank/index.ts @@ -53,7 +53,6 @@ async function usdEquivalent(timestamp: number) { return dailyFees; } catch (error) { await sql.end({ timeout: 3 }) - console.error(error); throw error; } } diff --git a/fees/foundation.ts b/fees/foundation.ts index 25b044ea96..35ccf6b3c5 100644 --- a/fees/foundation.ts +++ b/fees/foundation.ts @@ -25,108 +25,103 @@ interface IFee { const fetch = async (timestamp: number): Promise => { const fromTimestamp = timestamp - 60 * 60 * 24 const toTimestamp = timestamp - try { - const fromBlock = (await getBlock(fromTimestamp, CHAIN.ETHEREUM, {})); - const toBlock = (await getBlock(toTimestamp, CHAIN.ETHEREUM, {})); - const logs_reserveAuction_finalized: IFee[] = (await sdk.getEventLogs({ - target: market_address, - toBlock: toBlock, - fromBlock: fromBlock, - chain: CHAIN.ETHEREUM, - topics: [topic_0_reserveAuction_finalized] - })).map((e: any) => { - const amount = Number('0x' + e.data.replace('0x', '').slice(0, 64)) / 10 ** 18; - return { - totalFees: amount - } - }); - - const logs_private_sale_finalized: IFee[] = (await sdk.getEventLogs({ - target: market_address, - toBlock: toBlock, - fromBlock: fromBlock, - chain: CHAIN.ETHEREUM, - topics: [topic_0_private_sale_finalized] - })).map((e: any) => { - const amount = Number('0x' + e.data.replace('0x', '').slice(64, 128)) / 10 ** 18; - return { - totalFees: amount - } - }); - - const logs_buyPrice_accepted: IFee[] = (await sdk.getEventLogs({ - target: market_address, - toBlock: toBlock, - fromBlock: fromBlock, - chain: CHAIN.ETHEREUM, - topics: [topic_0_buyPrice_accepted] - })).map((e: any) => { - const amount = Number('0x' + e.data.replace('0x', '').slice(64, 128)) / 10 ** 18; - return { - totalFees: amount - } - }); - - const logs_offer_accepted: IFee[] = (await sdk.getEventLogs({ - target: market_address, - toBlock: toBlock, - fromBlock: fromBlock, - chain: CHAIN.ETHEREUM, - topics: [topic_0_offer_accepted] - })).map((e: any) => { - const amount = Number('0x' + e.data.replace('0x', '').slice(64, 128)) / 10 ** 18; - return { - totalFees: amount - } - }); - - const logs_mint_from_fixed_price_drop: IFee[] = (await sdk.getEventLogs({ - target: nft_drop_market_address, - toBlock: toBlock, - fromBlock: fromBlock, - chain: CHAIN.ETHEREUM, - topics: [topic_0_mint_from_fixed_price_drop] - })).map((e: any) => { - const amount = Number('0x' + e.data.replace('0x', '').slice(64, 128)) / 10 ** 18; - return { - totalFees: amount - } - }); - - const logs_withdraw_creator_revenue_from_dutch_auction: IFee[] = (await sdk.getEventLogs({ - target: nft_drop_market_address, - toBlock: toBlock, - fromBlock: fromBlock, - chain: CHAIN.ETHEREUM, - topics: [topic_0_withdraw_creator_revenue_from_dutch_auction] - })).map((e: any) => { - const amount = Number('0x' + e.data.replace('0x', '').slice(128, 192)) / 10 ** 18; - return { - totalFees: amount - } - }); - - const total_logs = [ - ...logs_reserveAuction_finalized, - ...logs_private_sale_finalized, - ...logs_buyPrice_accepted, - ...logs_offer_accepted, - ...logs_mint_from_fixed_price_drop, - ...logs_withdraw_creator_revenue_from_dutch_auction, - ] - const ethAddress = "ethereum:0x0000000000000000000000000000000000000000"; - const ethPrice = (await getPrices([ethAddress], timestamp))[ethAddress].price; - const totalFees = total_logs.reduce((a: number, b: IFee) => a + b.totalFees, 0) - const dailyFees = totalFees * ethPrice - const dailyRevenue = dailyFees; + const fromBlock = (await getBlock(fromTimestamp, CHAIN.ETHEREUM, {})); + const toBlock = (await getBlock(toTimestamp, CHAIN.ETHEREUM, {})); + const logs_reserveAuction_finalized: IFee[] = (await sdk.getEventLogs({ + target: market_address, + toBlock: toBlock, + fromBlock: fromBlock, + chain: CHAIN.ETHEREUM, + topics: [topic_0_reserveAuction_finalized] + })).map((e: any) => { + const amount = Number('0x' + e.data.replace('0x', '').slice(0, 64)) / 10 ** 18; return { - dailyFees: `${dailyFees}`, - dailyRevenue: `${dailyRevenue}`, - timestamp + totalFees: amount } - } catch (error) { - console.error(error); - throw error; + }); + + const logs_private_sale_finalized: IFee[] = (await sdk.getEventLogs({ + target: market_address, + toBlock: toBlock, + fromBlock: fromBlock, + chain: CHAIN.ETHEREUM, + topics: [topic_0_private_sale_finalized] + })).map((e: any) => { + const amount = Number('0x' + e.data.replace('0x', '').slice(64, 128)) / 10 ** 18; + return { + totalFees: amount + } + }); + + const logs_buyPrice_accepted: IFee[] = (await sdk.getEventLogs({ + target: market_address, + toBlock: toBlock, + fromBlock: fromBlock, + chain: CHAIN.ETHEREUM, + topics: [topic_0_buyPrice_accepted] + })).map((e: any) => { + const amount = Number('0x' + e.data.replace('0x', '').slice(64, 128)) / 10 ** 18; + return { + totalFees: amount + } + }); + + const logs_offer_accepted: IFee[] = (await sdk.getEventLogs({ + target: market_address, + toBlock: toBlock, + fromBlock: fromBlock, + chain: CHAIN.ETHEREUM, + topics: [topic_0_offer_accepted] + })).map((e: any) => { + const amount = Number('0x' + e.data.replace('0x', '').slice(64, 128)) / 10 ** 18; + return { + totalFees: amount + } + }); + + const logs_mint_from_fixed_price_drop: IFee[] = (await sdk.getEventLogs({ + target: nft_drop_market_address, + toBlock: toBlock, + fromBlock: fromBlock, + chain: CHAIN.ETHEREUM, + topics: [topic_0_mint_from_fixed_price_drop] + })).map((e: any) => { + const amount = Number('0x' + e.data.replace('0x', '').slice(64, 128)) / 10 ** 18; + return { + totalFees: amount + } + }); + + const logs_withdraw_creator_revenue_from_dutch_auction: IFee[] = (await sdk.getEventLogs({ + target: nft_drop_market_address, + toBlock: toBlock, + fromBlock: fromBlock, + chain: CHAIN.ETHEREUM, + topics: [topic_0_withdraw_creator_revenue_from_dutch_auction] + })).map((e: any) => { + const amount = Number('0x' + e.data.replace('0x', '').slice(128, 192)) / 10 ** 18; + return { + totalFees: amount + } + }); + + const total_logs = [ + ...logs_reserveAuction_finalized, + ...logs_private_sale_finalized, + ...logs_buyPrice_accepted, + ...logs_offer_accepted, + ...logs_mint_from_fixed_price_drop, + ...logs_withdraw_creator_revenue_from_dutch_auction, + ] + const ethAddress = "ethereum:0x0000000000000000000000000000000000000000"; + const ethPrice = (await getPrices([ethAddress], timestamp))[ethAddress].price; + const totalFees = total_logs.reduce((a: number, b: IFee) => a + b.totalFees, 0) + const dailyFees = totalFees * ethPrice + const dailyRevenue = dailyFees; + return { + dailyFees: `${dailyFees}`, + dailyRevenue: `${dailyRevenue}`, + timestamp } } @@ -134,8 +129,8 @@ const fetch = async (timestamp: number): Promise => { const adapter: Adapter = { adapter: { [CHAIN.ETHEREUM]: { - fetch: fetch, - start: async () => 1612137600, + fetch: fetch, + start: async () => 1612137600, }, } } diff --git a/fees/friend-room.ts b/fees/friend-room.ts index 2f64299745..ca39d5f510 100644 --- a/fees/friend-room.ts +++ b/fees/friend-room.ts @@ -30,38 +30,33 @@ const fetch = async (timestamp: number): Promise => { const fromBlock = (await getBlock(fromTimestamp, CHAIN.ETHEREUM, {})); const toBlock = (await getBlock(toTimestamp, CHAIN.ETHEREUM, {})); - try { - const logs: ILog[] = (await sdk.getEventLogs({ - target: friendRoomSharesAddress, - toBlock: toBlock, - fromBlock: fromBlock, - chain: CHAIN.ETHEREUM, - topics: [topic0_trade] - })) as ILog[]; + const logs: ILog[] = (await sdk.getEventLogs({ + target: friendRoomSharesAddress, + toBlock: toBlock, + fromBlock: fromBlock, + chain: CHAIN.ETHEREUM, + topics: [topic0_trade] + })) as ILog[]; - const fees_details: IFee[] = logs.map((e: ILog) => { - const value = contract_interface.parseLog(e); - const protocolEthAmount = Number(value!.args.protocolEthAmount) / 10 ** 18; - const subjectEthAmount = Number(value!.args.subjectEthAmount) / 10 ** 18; - return { - fees: protocolEthAmount + subjectEthAmount, - rev: protocolEthAmount - } as IFee - }) - const dailyFees = fees_details.reduce((a: number, b: IFee) => a+b.fees, 0) - const dailyRev = fees_details.reduce((a: number, b: IFee) => a+b.rev, 0) - const ethAddress = "ethereum:0x0000000000000000000000000000000000000000"; - const ethPrice = (await getPrices([ethAddress], timestamp))[ethAddress].price; - const dailyFeesUSD = (dailyFees) * ethPrice; - const dailyRevUSD = (dailyRev) * ethPrice; + const fees_details: IFee[] = logs.map((e: ILog) => { + const value = contract_interface.parseLog(e); + const protocolEthAmount = Number(value!.args.protocolEthAmount) / 10 ** 18; + const subjectEthAmount = Number(value!.args.subjectEthAmount) / 10 ** 18; return { - dailyFees: `${dailyFeesUSD}`, - dailyRevenue: `${dailyRevUSD}`, - timestamp - } - } catch (error) { - console.error(error) - throw error; + fees: protocolEthAmount + subjectEthAmount, + rev: protocolEthAmount + } as IFee + }) + const dailyFees = fees_details.reduce((a: number, b: IFee) => a + b.fees, 0) + const dailyRev = fees_details.reduce((a: number, b: IFee) => a + b.rev, 0) + const ethAddress = "ethereum:0x0000000000000000000000000000000000000000"; + const ethPrice = (await getPrices([ethAddress], timestamp))[ethAddress].price; + const dailyFeesUSD = (dailyFees) * ethPrice; + const dailyRevUSD = (dailyRev) * ethPrice; + return { + dailyFees: `${dailyFeesUSD}`, + dailyRevenue: `${dailyRevUSD}`, + timestamp } } @@ -70,8 +65,8 @@ const fetch = async (timestamp: number): Promise => { const adapter: Adapter = { adapter: { [CHAIN.ETHEREUM]: { - fetch: fetch, - start: async () => 1693731179, + fetch: fetch, + start: async () => 1693731179, }, } } diff --git a/fees/friend-tech.ts b/fees/friend-tech.ts index d26950fd60..2caefd789e 100644 --- a/fees/friend-tech.ts +++ b/fees/friend-tech.ts @@ -30,42 +30,37 @@ const fetch = async (timestamp: number): Promise => { const fromBlock = (await getBlock(fromTimestamp, CHAIN.BASE, {})); const toBlock = (await getBlock(toTimestamp, CHAIN.BASE, {})); - try { - let _logs: ILog[] = []; - for(let i = fromBlock; i < toBlock; i += 5000) { - const logs: ILog[] = (await sdk.getEventLogs({ - target: FriendtechSharesAddress, - toBlock: i + 5000, - fromBlock: i, - chain: CHAIN.BASE, - topics: [topic0_trade] - })) as ILog[]; - _logs = _logs.concat(logs); - } + let _logs: ILog[] = []; + for (let i = fromBlock; i < toBlock; i += 5000) { + const logs: ILog[] = (await sdk.getEventLogs({ + target: FriendtechSharesAddress, + toBlock: i + 5000, + fromBlock: i, + chain: CHAIN.BASE, + topics: [topic0_trade] + })) as ILog[]; + _logs = _logs.concat(logs); + } - const fees_details: IFee[] = _logs.map((e: ILog) => { - const value = contract_interface.parseLog(e); - const protocolEthAmount = Number(value!.args.protocolEthAmount) / 10 ** 18; - const subjectEthAmount = Number(value!.args.subjectEthAmount) / 10 ** 18; - return { - fees: protocolEthAmount + subjectEthAmount, - rev: protocolEthAmount - } as IFee - }) - const dailyFees = fees_details.reduce((a: number, b: IFee) => a+b.fees, 0) - const dailyRev = fees_details.reduce((a: number, b: IFee) => a+b.rev, 0) - const ethAddress = "ethereum:0x0000000000000000000000000000000000000000"; - const ethPrice = (await getPrices([ethAddress], timestamp))[ethAddress].price; - const dailyFeesUSD = (dailyFees) * ethPrice; - const dailyRevUSD = (dailyRev) * ethPrice; + const fees_details: IFee[] = _logs.map((e: ILog) => { + const value = contract_interface.parseLog(e); + const protocolEthAmount = Number(value!.args.protocolEthAmount) / 10 ** 18; + const subjectEthAmount = Number(value!.args.subjectEthAmount) / 10 ** 18; return { - dailyFees: `${dailyFeesUSD}`, - dailyRevenue: `${dailyRevUSD}`, - timestamp - } - } catch (error) { - console.error(error) - throw error; + fees: protocolEthAmount + subjectEthAmount, + rev: protocolEthAmount + } as IFee + }) + const dailyFees = fees_details.reduce((a: number, b: IFee) => a + b.fees, 0) + const dailyRev = fees_details.reduce((a: number, b: IFee) => a + b.rev, 0) + const ethAddress = "ethereum:0x0000000000000000000000000000000000000000"; + const ethPrice = (await getPrices([ethAddress], timestamp))[ethAddress].price; + const dailyFeesUSD = (dailyFees) * ethPrice; + const dailyRevUSD = (dailyRev) * ethPrice; + return { + dailyFees: `${dailyFeesUSD}`, + dailyRevenue: `${dailyRevUSD}`, + timestamp } } @@ -74,8 +69,8 @@ const fetch = async (timestamp: number): Promise => { const adapter: Adapter = { adapter: { [CHAIN.BASE]: { - fetch: fetch, - start: async () => 1691539200, + fetch: fetch, + start: async () => 1691539200, }, } } diff --git a/fees/friend3.ts b/fees/friend3.ts index 31ffdbd8e8..467d59fd07 100644 --- a/fees/friend3.ts +++ b/fees/friend3.ts @@ -1,150 +1,51 @@ -import { Adapter, FetchResultFees } from "../adapters/types"; +import { Adapter, Fetch, FetchOptions, FetchResultFees } from "../adapters/types"; import { CHAIN } from "../helpers/chains"; -import * as sdk from "@defillama/sdk"; -import { getBlock } from "../helpers/getBlock"; -import { getPrices } from "../utils/prices"; -import { ethers } from "ethers"; const FriendV1Address = '0x1e70972ec6c8a3fae3ac34c9f3818ec46eb3bd5d'; -const topic0_trade = '0x2c76e7a47fd53e2854856ac3f0a5f3ee40d15cfaa82266357ea9779c486ab9c3'; const event_trade = 'event Trade(address trader, address subject, bool isBuy, uint256 ticketAmount, uint256 ethAmount, uint256 protocolEthAmount, uint256 subjectEthAmount, uint256 supply)' -const contract_interface = new ethers.Interface([ - event_trade -]); - const FriendV2Address = '0x2C5bF6f0953ffcDE678A35AB7d6CaEBC8B6b29F0'; -const topic0_trade_V2 = '0x5acb97638a46771a62aed2578c5c5c260108ffe0c606b887d61a9057af4034c9'; const event_trade_V2 = 'event Trade (address trader , bytes32 subjectId , bool isBuy , uint256 ticketAmount , uint256 tokenAmount , uint256 protocolAmount , uint256 subjectAmount , uint256 holderAmount , uint256 referralAmount , uint256 supply)' -const contract_interface_V2 = new ethers.Interface([ - event_trade_V2 -]); - -interface ILog { - data: string; - transactionHash: string; - topics: string[]; -} - -interface IFee { - fees: number; - rev: number; -} - -const fetch = async (timestamp: number): Promise => { - const fromTimestamp = timestamp - 60 * 60 * 24 - const toTimestamp = timestamp - - try { - const fromBlock = await getBlock(fromTimestamp, CHAIN.BSC, {}); - const toBlock = await getBlock(toTimestamp, CHAIN.BSC, {}); - - - let _logs: ILog[] = []; - for(let i = fromBlock; i < toBlock; i += 5000) { - const logs: ILog[] = (await sdk.getEventLogs({ - target: FriendV1Address, - toBlock: i + 5000, - fromBlock: i, - chain: CHAIN.BSC, - topics: [topic0_trade] - })) as ILog[]; - _logs = _logs.concat(logs); - } - - const fees_details: IFee[] = _logs.map((e: ILog) => { - const value = contract_interface.parseLog(e); - const protocolEthAmount = Number(value!.args.protocolEthAmount) / 10 ** 18; - const subjectEthAmount = Number(value!.args.subjectEthAmount) / 10 ** 18; - return { - fees: protocolEthAmount + subjectEthAmount, - rev: protocolEthAmount - } as IFee - }) - const dailyFees = fees_details.reduce((a: number, b: IFee) => a+b.fees, 0) - const dailyRev = fees_details.reduce((a: number, b: IFee) => a+b.rev, 0) - const ethAddress = "bsc:0x0000000000000000000000000000000000000000"; - const ethPrice = (await getPrices([ethAddress], timestamp))[ethAddress].price; - const dailyFeesUSD = (dailyFees) * ethPrice; - const dailyRevUSD = (dailyRev) * ethPrice; - return { - dailyFees: `${dailyFeesUSD}`, - dailyRevenue: `${dailyRevUSD}`, - timestamp - } - } catch (error) { - console.error(error) - throw error; - } - -} - -const fetchOpbnb = async (timestamp: number): Promise => { - const fromTimestamp = timestamp - 60 * 60 * 24 - const toTimestamp = timestamp - - try { - const fromBlock = await getBlock(fromTimestamp, CHAIN.OP_BNB, {}); - const toBlock = await getBlock(toTimestamp, CHAIN.OP_BNB, {}); - let _logs: ILog[] = []; - for(let i = fromBlock; i < toBlock; i += 3400) { - try { - const logs: ILog[] = (await sdk.getEventLogs({ - target: FriendV2Address, - toBlock: i + 3400, - fromBlock: i, - chain: CHAIN.OP_BNB, - topics: [topic0_trade_V2] - })) as ILog[]; - _logs = _logs.concat(logs); - } catch (error) { - // console.error(error) - // skip error - } - } - - const fees_details: IFee[] = _logs.map((e: ILog) => { - const value = contract_interface_V2.parseLog(e); - const protocolAmount = Number(value!.args.protocolAmount) / 10 ** 18; - const subjectAmount = Number(value!.args.subjectAmount) / 10 ** 18; - const holderAmount = Number(value!.args.holderAmount) / 10 ** 18; - const referralAmount = Number(value!.args.referralAmount) / 10 ** 18; - return { - fees: protocolAmount + subjectAmount + holderAmount, - rev: protocolAmount-referralAmount - } as IFee - }) - const dailyFees = fees_details.reduce((a: number, b: IFee) => a+b.fees, 0) - const dailyRev = fees_details.reduce((a: number, b: IFee) => a+b.rev, 0) - const ethAddress = "op_bnb:0x0000000000000000000000000000000000000000"; - const ethPrice = (await getPrices([ethAddress], timestamp))[ethAddress].price; - const dailyFeesUSD = (dailyFees) * ethPrice; - const dailyRevUSD = (dailyRev) * ethPrice; - return { - dailyFees: `${dailyFeesUSD}`, - dailyRevenue: `${dailyRevUSD}`, - timestamp - } - } catch (error) { - console.error(error) - throw error; - } - -} +const fetch = (async (timestamp: number, _cb: any, { getLogs, createBalances }: FetchOptions): Promise => { + let logs = await getLogs({ target: FriendV1Address, eventAbi: event_trade, }) + const dailyFees = createBalances() + const dailyRevenue = createBalances() + logs.forEach(i => { + dailyFees.addGasToken(i.protocolEthAmount) + dailyFees.addGasToken(i.subjectEthAmount) + dailyRevenue.addGasToken(i.protocolEthAmount) + }) + return { dailyFees, dailyRevenue, timestamp } +}) as Fetch + +const fetchOpbnb = (async (timestamp: number, _cb: any, { getLogs, createBalances }: FetchOptions): Promise => { + + let logs = await getLogs({ target: FriendV2Address, eventAbi: event_trade_V2, }) + const dailyFees = createBalances() + const dailyRevenue = createBalances() + logs.forEach(i => { + dailyFees.addGasToken(i.protocolAmount) + dailyFees.addGasToken(i.subjectAmount) + dailyFees.addGasToken(i.holderAmount) + dailyRevenue.addGasToken(i.protocolEthAmount) + dailyRevenue.addGasToken(i.referralAmount * -1) + }) + return { dailyFees, dailyRevenue, timestamp } +}) as Fetch const adapter: Adapter = { adapter: { [CHAIN.BSC]: { - fetch: fetch, - start: async () => 1692835200, + fetch: fetch, + start: async () => 1692835200, }, [CHAIN.OP_BNB]: { fetch: fetchOpbnb, - start: async () => 1698710400, - }, + start: async () => 1698710400, + }, } } diff --git a/fees/fvm-exchange.ts b/fees/fvm-exchange.ts index b8ed5bbf76..1834c1a23a 100644 --- a/fees/fvm-exchange.ts +++ b/fees/fvm-exchange.ts @@ -30,127 +30,122 @@ process.env.FANTOM_BATCH_MAX_COUNT = "10"; // 10 is the default value const fetch = async (timestamp: number): Promise => { const fromTimestamp = timestamp - 60 * 60 * 24; const toTimestamp = timestamp; - try { - const poolLength = ( - await sdk.api2.abi.call({ - target: FACTORY_ADDRESS, - chain: CHAIN.FANTOM, - abi: ABIs.allPairsLength, - }) - ); - - const poolsRes = await sdk.api2.abi.multiCall({ - abi: ABIs.allPairs, - calls: Array.from(Array(Number(poolLength)).keys()).map((i) => ({ - target: FACTORY_ADDRESS, - params: i, - })), + const poolLength = ( + await sdk.api2.abi.call({ + target: FACTORY_ADDRESS, chain: CHAIN.FANTOM, - permitFailure: true, - }); + abi: ABIs.allPairsLength, + }) + ); + + const poolsRes = await sdk.api2.abi.multiCall({ + abi: ABIs.allPairs, + calls: Array.from(Array(Number(poolLength)).keys()).map((i) => ({ + target: FACTORY_ADDRESS, + params: i, + })), + chain: CHAIN.FANTOM, + permitFailure: true, + }); - const lpTokens = poolsRes + const lpTokens = poolsRes + + const [underlyingToken0, underlyingToken1] = await Promise.all( + ["address:token0", "address:token1"].map((method) => + sdk.api2.abi.multiCall({ + abi: method, + calls: lpTokens, + chain: CHAIN.FANTOM, + permitFailure: true, + }) + ) + ); - const [underlyingToken0, underlyingToken1] = await Promise.all( - ["address:token0", "address:token1"].map((method) => - sdk.api2.abi.multiCall({ - abi: method, - calls: lpTokens, + const tokens0 = underlyingToken0; + const tokens1 = underlyingToken1; + const fromBlock = await getBlock(fromTimestamp, CHAIN.FANTOM, {}); + const toBlock = await getBlock(toTimestamp, CHAIN.FANTOM, {}); + const logs: ILog[][] = ( + await Promise.all( + lpTokens.map((address: string) => + sdk.getEventLogs({ + target: address, + toBlock: toBlock, + fromBlock: fromBlock, chain: CHAIN.FANTOM, - permitFailure: true, + topics: [topic0], + skipCache: true, }) ) - ); + ) + ) as any - const tokens0 = underlyingToken0; - const tokens1 = underlyingToken1; - const fromBlock = await getBlock(fromTimestamp, CHAIN.FANTOM, {}); - const toBlock = await getBlock(toTimestamp, CHAIN.FANTOM, {}); - const logs: ILog[][] = ( - await Promise.all( - lpTokens.map((address: string) => - sdk.getEventLogs({ - target: address, - toBlock: toBlock, - fromBlock: fromBlock, - chain: CHAIN.FANTOM, - topics: [topic0], - skipCache: true, - }) - ) - ) - ) as any - - const rawCoins = [...tokens0, ...tokens1].map( - (e: string) => `${CHAIN.FANTOM}:${e}` - ); - const coins = [...new Set(rawCoins)]; - const prices = await getPrices(coins, timestamp); - const fees: number[] = lpTokens.map((_: string, index: number) => { - const token0Decimals = - prices[`${CHAIN.FANTOM}:${tokens0[index]}`]?.decimals || 0; - const token1Decimals = - prices[`${CHAIN.FANTOM}:${tokens1[index]}`]?.decimals || 0; - const log: IAmount[] = logs[index] - .map((e: ILog) => { - return { ...e, data: e.data.replace("0x", "") }; - }) - .map((p: ILog) => { - // event GaugeFees(address indexed token, uint amount, address externalBribe); - const [, token] = p.topics; - const isToken0 = - "0x" + token.substring(26).toLowerCase() === - tokens0[index].toLowerCase(); - const isToken1 = - "0x" + token.substring(26).toLowerCase() === - tokens1[index].toLowerCase(); - if (isToken0) { - return { - amount0: - Number("0x" + p.data.slice(0, 64)) / 10 ** token0Decimals, - amount1: 0, - }; - } - if (isToken1) { - return { - amount0: 0, - amount1: - Number("0x" + p.data.slice(0, 64)) / 10 ** token1Decimals, - }; - } + const rawCoins = [...tokens0, ...tokens1].map( + (e: string) => `${CHAIN.FANTOM}:${e}` + ); + const coins = [...new Set(rawCoins)]; + const prices = await getPrices(coins, timestamp); + const fees: number[] = lpTokens.map((_: string, index: number) => { + const token0Decimals = + prices[`${CHAIN.FANTOM}:${tokens0[index]}`]?.decimals || 0; + const token1Decimals = + prices[`${CHAIN.FANTOM}:${tokens1[index]}`]?.decimals || 0; + const log: IAmount[] = logs[index] + .map((e: ILog) => { + return { ...e, data: e.data.replace("0x", "") }; + }) + .map((p: ILog) => { + // event GaugeFees(address indexed token, uint amount, address externalBribe); + const [, token] = p.topics; + const isToken0 = + "0x" + token.substring(26).toLowerCase() === + tokens0[index].toLowerCase(); + const isToken1 = + "0x" + token.substring(26).toLowerCase() === + tokens1[index].toLowerCase(); + if (isToken0) { return { - amount0: 0, + amount0: + Number("0x" + p.data.slice(0, 64)) / 10 ** token0Decimals, amount1: 0, - } as IAmount; - }) as IAmount[]; + }; + } + if (isToken1) { + return { + amount0: 0, + amount1: + Number("0x" + p.data.slice(0, 64)) / 10 ** token1Decimals, + }; + } + return { + amount0: 0, + amount1: 0, + } as IAmount; + }) as IAmount[]; - const token0Price = - prices[`${CHAIN.FANTOM}:${tokens0[index]}`]?.price || 0; - const token1Price = - prices[`${CHAIN.FANTOM}:${tokens1[index]}`]?.price || 0; + const token0Price = + prices[`${CHAIN.FANTOM}:${tokens0[index]}`]?.price || 0; + const token1Price = + prices[`${CHAIN.FANTOM}:${tokens1[index]}`]?.price || 0; - const feesAmount0 = - log.reduce((a: number, b: IAmount) => Number(b.amount0) + a, 0) * - token0Price; - const feesAmount1 = - log.reduce((a: number, b: IAmount) => Number(b.amount1) + a, 0) * - token1Price; + const feesAmount0 = + log.reduce((a: number, b: IAmount) => Number(b.amount0) + a, 0) * + token0Price; + const feesAmount1 = + log.reduce((a: number, b: IAmount) => Number(b.amount1) + a, 0) * + token1Price; - const feesUSD = feesAmount0 + feesAmount1; - return feesUSD; - }); + const feesUSD = feesAmount0 + feesAmount1; + return feesUSD; + }); - const dailyFees = fees.reduce((a: number, b: number) => a + b, 0); - return { - dailyFees: `${dailyFees}`, - dailyRevenue: `${dailyFees}`, - dailyHoldersRevenue: `${dailyFees}`, - timestamp, - }; - } catch (error) { - console.error(error); - throw error; - } + const dailyFees = fees.reduce((a: number, b: number) => a + b, 0); + return { + dailyFees: `${dailyFees}`, + dailyRevenue: `${dailyFees}`, + dailyHoldersRevenue: `${dailyFees}`, + timestamp, + }; }; const adapter: SimpleAdapter = { diff --git a/fees/gmx-v2/index.ts b/fees/gmx-v2/index.ts index cb224e10ef..81b358235b 100644 --- a/fees/gmx-v2/index.ts +++ b/fees/gmx-v2/index.ts @@ -13,26 +13,21 @@ interface IFee { const fetch = (chain: Chain) => { return async (timestamp: number): Promise => { - try { - const fees: IFee[] = (await queryDune(chain === CHAIN.ARBITRUM ? "3186689" : "3186714")) - // const fees: IFee[] = require(`./${chain}.json`); - const dayTimestamp = getUniqStartOfTodayTimestamp(new Date(timestamp * 1000)); - const dateString = new Date(dayTimestamp * 1000).toISOString().split("T")[0]; - const daily = fees.find(fee => fee.time.split(' ')[0] === dateString); - const dailyFees = daily?.v2_fees || 0 - const total_fees = daily?.total_fees; - return { - dailyFees:`${dailyFees}`, - dailyRevenue: `${dailyFees*0.37}`, - dailyProtocolRevenue: `${dailyFees*0.1}`, - dailyHoldersRevenue: `${dailyFees*0.27}`, - totalFees: `${total_fees}`, - timestamp, - }; - } catch (error) { - console.error(error); - throw error; - } + const fees: IFee[] = (await queryDune(chain === CHAIN.ARBITRUM ? "3186689" : "3186714")) + // const fees: IFee[] = require(`./${chain}.json`); + const dayTimestamp = getUniqStartOfTodayTimestamp(new Date(timestamp * 1000)); + const dateString = new Date(dayTimestamp * 1000).toISOString().split("T")[0]; + const daily = fees.find(fee => fee.time.split(' ')[0] === dateString); + const dailyFees = daily?.v2_fees || 0 + const total_fees = daily?.total_fees; + return { + dailyFees: `${dailyFees}`, + dailyRevenue: `${dailyFees * 0.37}`, + dailyProtocolRevenue: `${dailyFees * 0.1}`, + dailyHoldersRevenue: `${dailyFees * 0.27}`, + totalFees: `${total_fees}`, + timestamp, + }; }; }; diff --git a/fees/goldfinch.ts b/fees/goldfinch.ts index c2ebc5353b..6278a11d2d 100644 --- a/fees/goldfinch.ts +++ b/fees/goldfinch.ts @@ -77,60 +77,55 @@ const fetchFees = async (timestamp: number): Promise => { const ONE_DAY_IN_SECONDS = 86400; const toTimestamp = timestamp; const fromTimestamp = timestamp - ONE_DAY_IN_SECONDS; - try { - const toBlock = await getBlock(toTimestamp, 'ethereum', {}); - const fromBlock = await getBlock(fromTimestamp, 'ethereum', {}); - - const logs_interest_collect: EventLog[] = (await sdk.getEventLogs({ - target: core_pool, - fromBlock: fromBlock, - toBlock: toBlock, - topics: [topic0_interest_collected], - chain: 'ethereum' - })) as EventLog[]; - const pool_interest_collected = logs_interest_collect - .reduce((a: number, b: EventLog) => a + Number('0x'+b.data.replace('0x','').slice(0, 64)), 0) / 1e6; - - const logs_pool_payment_applie: EventLog[] = (await Promise.all(pools.map(async (pool: string) => sdk.getEventLogs({ - target: pool, - fromBlock: fromBlock, - toBlock: toBlock, - topics: [topic0_payment_appli], - chain: 'ethereum' - })))).flat() as EventLog[]; - - const logs_reserve_fund_collect: EventLog[] = (await Promise.all([...pools, core_pool, senior_pool].map(async (pool: string) => sdk.getEventLogs({ - target: pool, - fromBlock: fromBlock, - toBlock: toBlock, - topics: [topic0_reserve_fund_collect], - chain: 'ethereum' - })))).flat() as EventLog[]; - - const pool_payment_applied = logs_pool_payment_applie.map((log: EventLog) => { - const data = log.data.replace('0x','') - const interestAmount = Number('0x'+data.slice(0, 64)) / 1e6; - const reserveAmount = Number('0x'+data.slice(64 * 3, (64 * 3) + 64)) / 1e6; - return interestAmount - reserveAmount; - }).reduce((a: number, b: number) => a + b, 0); - - const pool_reserve_fund_collect = logs_reserve_fund_collect.map((log: EventLog) => { - const amount = Number(log.data) / 1e6; - return amount; - }).reduce((a: number, b: number) => a + b, 0); - const dailyFees = pool_interest_collected + pool_payment_applied + pool_reserve_fund_collect; - const dailyRevenue = pool_reserve_fund_collect; - const dailySupplySideRevenue = dailyFees - dailyRevenue; - - return { - dailyFees: dailyFees.toString(), - dailyRevenue: dailyRevenue.toString(), - dailySupplySideRevenue: dailySupplySideRevenue > 0 ? dailySupplySideRevenue.toString() : '0', - timestamp - } - } catch (error) { - console.error(error) - throw error; + const toBlock = await getBlock(toTimestamp, 'ethereum', {}); + const fromBlock = await getBlock(fromTimestamp, 'ethereum', {}); + + const logs_interest_collect: EventLog[] = (await sdk.getEventLogs({ + target: core_pool, + fromBlock: fromBlock, + toBlock: toBlock, + topics: [topic0_interest_collected], + chain: 'ethereum' + })) as EventLog[]; + const pool_interest_collected = logs_interest_collect + .reduce((a: number, b: EventLog) => a + Number('0x' + b.data.replace('0x', '').slice(0, 64)), 0) / 1e6; + + const logs_pool_payment_applie: EventLog[] = (await Promise.all(pools.map(async (pool: string) => sdk.getEventLogs({ + target: pool, + fromBlock: fromBlock, + toBlock: toBlock, + topics: [topic0_payment_appli], + chain: 'ethereum' + })))).flat() as EventLog[]; + + const logs_reserve_fund_collect: EventLog[] = (await Promise.all([...pools, core_pool, senior_pool].map(async (pool: string) => sdk.getEventLogs({ + target: pool, + fromBlock: fromBlock, + toBlock: toBlock, + topics: [topic0_reserve_fund_collect], + chain: 'ethereum' + })))).flat() as EventLog[]; + + const pool_payment_applied = logs_pool_payment_applie.map((log: EventLog) => { + const data = log.data.replace('0x', '') + const interestAmount = Number('0x' + data.slice(0, 64)) / 1e6; + const reserveAmount = Number('0x' + data.slice(64 * 3, (64 * 3) + 64)) / 1e6; + return interestAmount - reserveAmount; + }).reduce((a: number, b: number) => a + b, 0); + + const pool_reserve_fund_collect = logs_reserve_fund_collect.map((log: EventLog) => { + const amount = Number(log.data) / 1e6; + return amount; + }).reduce((a: number, b: number) => a + b, 0); + const dailyFees = pool_interest_collected + pool_payment_applied + pool_reserve_fund_collect; + const dailyRevenue = pool_reserve_fund_collect; + const dailySupplySideRevenue = dailyFees - dailyRevenue; + + return { + dailyFees: dailyFees.toString(), + dailyRevenue: dailyRevenue.toString(), + dailySupplySideRevenue: dailySupplySideRevenue > 0 ? dailySupplySideRevenue.toString() : '0', + timestamp } } diff --git a/fees/hono.ts b/fees/hono.ts index c36922ad2d..a5a2714f07 100644 --- a/fees/hono.ts +++ b/fees/hono.ts @@ -1,5 +1,5 @@ import { Adapter, FetchResultFees } from "../adapters/types"; -import { CHAIN} from "../helpers/chains"; +import { CHAIN } from "../helpers/chains"; import { request, gql } from "graphql-request"; import type { ChainEndpoints } from "../adapters/types" import { Chain } from '@defillama/sdk/build/general'; @@ -30,25 +30,20 @@ const graph = (graphUrls: ChainEndpoints) => { const fromTimestamp = timestamp - 60 * 60 * 24 const toTimestamp = timestamp - try { - const graphRes: IData[] = (await request(graphUrls[chain], graphQuery, { - timestampFrom: fromTimestamp, - timestampTo: toTimestamp - })).dailyRevenueAggregators; - const ethcoinID = "ethereum:0x0000000000000000000000000000000000000000"; - const prices = await getPrices([ethcoinID], timestamp); - const value = graphRes.reduce((acc, cur) => acc + Number(cur.todayETHRevenue)/10**18, 0); - const dailyRevenue = (value) * prices[ethcoinID].price; - const dailyFees = dailyRevenue; + const graphRes: IData[] = (await request(graphUrls[chain], graphQuery, { + timestampFrom: fromTimestamp, + timestampTo: toTimestamp + })).dailyRevenueAggregators; + const ethcoinID = "ethereum:0x0000000000000000000000000000000000000000"; + const prices = await getPrices([ethcoinID], timestamp); + const value = graphRes.reduce((acc, cur) => acc + Number(cur.todayETHRevenue) / 10 ** 18, 0); + const dailyRevenue = (value) * prices[ethcoinID].price; + const dailyFees = dailyRevenue; return { dailyFees: `${dailyFees}`, dailyRevenue: `${dailyRevenue}`, timestamp } - } catch (error) { - console.error(error); - throw error; - } } } }; diff --git a/fees/houdini-swap.ts b/fees/houdini-swap.ts index 95ecaa14e4..de52717c88 100644 --- a/fees/houdini-swap.ts +++ b/fees/houdini-swap.ts @@ -46,7 +46,6 @@ const graph = (chain: Chain) => { } } catch (err) { await sql.end({ timeout: 3 }) - console.log(err); throw err; } diff --git a/fees/joe-v2.1.ts b/fees/joe-v2.1.ts index 51343dbfc8..22a32ef3e2 100644 --- a/fees/joe-v2.1.ts +++ b/fees/joe-v2.1.ts @@ -72,87 +72,82 @@ const graph = (chain: Chain) => { return async (timestamp: number): Promise => { const fromTimestamp = timestamp - 60 * 60 * 24 const toTimestamp = timestamp - try { - const lpTokens = pools[chain] - const [underlyingToken0, underlyingToken1] = await Promise.all( - ['address:getTokenX', 'address:getTokenY'].map((method: string) => - sdk.api2.abi.multiCall({ - abi: method, - calls: lpTokens.map((address: string) => ({ - target: address, - })), - chain: chain - }) - ) - ); + const lpTokens = pools[chain] + const [underlyingToken0, underlyingToken1] = await Promise.all( + ['address:getTokenX', 'address:getTokenY'].map((method: string) => + sdk.api2.abi.multiCall({ + abi: method, + calls: lpTokens.map((address: string) => ({ + target: address, + })), + chain: chain + }) + ) + ); - const tokens0 = underlyingToken0; - const tokens1 = underlyingToken1; - const fromBlock = (await getBlock(fromTimestamp, chain, {})); - const toBlock = (await getBlock(toTimestamp, chain, {})); + const tokens0 = underlyingToken0; + const tokens1 = underlyingToken1; + const fromBlock = (await getBlock(fromTimestamp, chain, {})); + const toBlock = (await getBlock(toTimestamp, chain, {})); - const logs: ILog[][] = (await Promise.all(lpTokens.map((address: string) => sdk.getEventLogs({ - target: address, - toBlock: toBlock, - fromBlock: fromBlock, - chain: chain, - topics: [topic0] - })))) as any; + const logs: ILog[][] = (await Promise.all(lpTokens.map((address: string) => sdk.getEventLogs({ + target: address, + toBlock: toBlock, + fromBlock: fromBlock, + chain: chain, + topics: [topic0] + })))) as any; - const rawCoins = [...tokens0, ...tokens1].map((e: string) => `${chain}:${e}`); - const coins = [...new Set(rawCoins)] - const prices = await getPrices(coins, timestamp); + const rawCoins = [...tokens0, ...tokens1].map((e: string) => `${chain}:${e}`); + const coins = [...new Set(rawCoins)] + const prices = await getPrices(coins, timestamp); - const untrackVolumes: any[] = lpTokens.map((_: string, index: number) => { - const token0Decimals = prices[`${chain}:${tokens0[index]}`]?.decimals || 0 - const token1Decimals = prices[`${chain}:${tokens1[index]}`]?.decimals || 0 - const log: IAmount[] = logs[index] - .map((e: ILog) => { return { ...e } }) - .map((p: ILog) => { - const value = contract_interface.parseLog(p); - const protocolFeesX = Number('0x'+'0'.repeat(32)+value!.args.protocolFees.replace('0x', '').slice(0, 32)) / 10 ** token1Decimals - const protocolFeesY = Number('0x'+'0'.repeat(32)+value!.args.protocolFees.replace('0x', '').slice(32, 64)) / 10 ** token0Decimals - const totalFeesX = Number('0x'+'0'.repeat(32)+value!.args.totalFees.replace('0x', '').slice(0, 32)) / 10 ** token1Decimals; - const totalFeesY = Number('0x'+'0'.repeat(32)+value!.args.totalFees.replace('0x', '').slice(32, 64)) / 10 ** token0Decimals; - return { - protocolFeesX, - protocolFeesY, - totalFeesX, - totalFeesY, - // tx: p.transactionHash, // for debugging - // token0Decimals, - // token1Decimals - } as IAmount - }); - - const token0Price = (prices[`${chain}:${tokens0[index]}`]?.price || 0); - const token1Price = (prices[`${chain}:${tokens1[index]}`]?.price || 0); - const totalFeesX = log - .reduce((a: number, b: IAmount) => Number(b.totalFeesX) + a, 0) * token1Price; - const totalFeesY = log - .reduce((a: number, b: IAmount) => Number(b.totalFeesY) + a, 0) * token0Price; - const totalProtocolFeesX = log.reduce((a: number, b: IAmount) => Number(b.protocolFeesX) + a, 0) * token1Price; - const totalProtocolFeesY = log.reduce((a: number, b: IAmount) => Number(b.protocolFeesY) + a, 0) * token0Price; + const untrackVolumes: any[] = lpTokens.map((_: string, index: number) => { + const token0Decimals = prices[`${chain}:${tokens0[index]}`]?.decimals || 0 + const token1Decimals = prices[`${chain}:${tokens1[index]}`]?.decimals || 0 + const log: IAmount[] = logs[index] + .map((e: ILog) => { return { ...e } }) + .map((p: ILog) => { + const value = contract_interface.parseLog(p); + const protocolFeesX = Number('0x' + '0'.repeat(32) + value!.args.protocolFees.replace('0x', '').slice(0, 32)) / 10 ** token1Decimals + const protocolFeesY = Number('0x' + '0'.repeat(32) + value!.args.protocolFees.replace('0x', '').slice(32, 64)) / 10 ** token0Decimals + const totalFeesX = Number('0x' + '0'.repeat(32) + value!.args.totalFees.replace('0x', '').slice(0, 32)) / 10 ** token1Decimals; + const totalFeesY = Number('0x' + '0'.repeat(32) + value!.args.totalFees.replace('0x', '').slice(32, 64)) / 10 ** token0Decimals; return { - fees: (totalFeesX + totalFeesY), - rev: (totalProtocolFeesX + totalProtocolFeesY), - }; + protocolFeesX, + protocolFeesY, + totalFeesX, + totalFeesY, + // tx: p.transactionHash, // for debugging + // token0Decimals, + // token1Decimals + } as IAmount }); - const dailyFees = untrackVolumes.reduce((a: number, b: any) => a + b.fees, 0); - const dailyRevenue = untrackVolumes.reduce((a: number, b: any) => a + b.rev, 0); - return { - dailyFees: `${dailyFees}`, - dailyRevenue: `${dailyRevenue}`, - dailyHoldersRevenue: `${dailyRevenue}`, - dailySupplySideRevenue: dailyFees ? `${(dailyFees || 0) - (dailyRevenue || 0)}` : undefined, - timestamp, - }; - } catch(error) { - console.error(error); - throw error; - } + const token0Price = (prices[`${chain}:${tokens0[index]}`]?.price || 0); + const token1Price = (prices[`${chain}:${tokens1[index]}`]?.price || 0); + const totalFeesX = log + .reduce((a: number, b: IAmount) => Number(b.totalFeesX) + a, 0) * token1Price; + const totalFeesY = log + .reduce((a: number, b: IAmount) => Number(b.totalFeesY) + a, 0) * token0Price; + const totalProtocolFeesX = log.reduce((a: number, b: IAmount) => Number(b.protocolFeesX) + a, 0) * token1Price; + const totalProtocolFeesY = log.reduce((a: number, b: IAmount) => Number(b.protocolFeesY) + a, 0) * token0Price; + return { + fees: (totalFeesX + totalFeesY), + rev: (totalProtocolFeesX + totalProtocolFeesY), + }; + }); + + const dailyFees = untrackVolumes.reduce((a: number, b: any) => a + b.fees, 0); + const dailyRevenue = untrackVolumes.reduce((a: number, b: any) => a + b.rev, 0); + return { + dailyFees: `${dailyFees}`, + dailyRevenue: `${dailyRevenue}`, + dailyHoldersRevenue: `${dailyRevenue}`, + dailySupplySideRevenue: dailyFees ? `${(dailyFees || 0) - (dailyRevenue || 0)}` : undefined, + timestamp, + }; } } diff --git a/fees/liquis.ts b/fees/liquis.ts index 3d4bd323a8..0fd456c681 100644 --- a/fees/liquis.ts +++ b/fees/liquis.ts @@ -20,32 +20,31 @@ interface ILog { const fetch = () => { return async (timestamp: number): Promise => { - try { - const todaysTimestamp = getTimestampAtStartOfDayUTC(timestamp); - const dayAgo = todaysTimestamp - 60 * 60 * 24; - const fromBlock = await getBlock(dayAgo, CHAIN.ETHEREUM, {}); - const toBlock = await getBlock(todaysTimestamp, CHAIN.ETHEREUM, {}); + const todaysTimestamp = getTimestampAtStartOfDayUTC(timestamp); + const dayAgo = todaysTimestamp - 60 * 60 * 24; + const fromBlock = await getBlock(dayAgo, CHAIN.ETHEREUM, {}); + const toBlock = await getBlock(todaysTimestamp, CHAIN.ETHEREUM, {}); - const logs: ILog[] = (await sdk.getEventLogs({ - target: OLIT_TOKEN, - topic: topic, - toBlock, - fromBlock, - chain: CHAIN.ETHEREUM, - topics: [topic0, topic1, topic2] - })) as ILog[]; + const logs: ILog[] = (await sdk.getEventLogs({ + target: OLIT_TOKEN, + topic: topic, + toBlock, + fromBlock, + chain: CHAIN.ETHEREUM, + topics: [topic0, topic1, topic2] + })) as ILog[]; - const olit_transfer_amounts: number[] = logs.map((e:any) => { + const olit_transfer_amounts: number[] = logs.map((e: any) => { return Number(e.data) / 10 ** 18; }); const litAddress = `ethereum:${LIT.toLowerCase()}`; const litPrice = (await getPrices([litAddress], todaysTimestamp))[litAddress].price; - const olit_transfer_amount = olit_transfer_amounts.reduce((a: number, b: number) => a+b,0); + const olit_transfer_amount = olit_transfer_amounts.reduce((a: number, b: number) => a + b, 0); const dailyFee = olit_transfer_amount * (litPrice / 2); const dailySupplySideRevenue = dailyFee * .75 - const dailyRevenue = dailyFee * .25; + const dailyRevenue = dailyFee * .25; const dailyHoldersRevenue = dailyFee * .03; return { @@ -55,17 +54,14 @@ const fetch = () => { dailySupplySideRevenue: dailySupplySideRevenue.toString(), dailyHoldersRevenue: dailyHoldersRevenue.toString(), } as FetchResultFees - } catch (error) { - throw error - } } } const adapter: Adapter = { adapter: { [CHAIN.ETHEREUM]: { - fetch: fetch(), - start: async () => 1693380630, + fetch: fetch(), + start: async () => 1693380630, }, }, diff --git a/fees/lybra-finance.ts b/fees/lybra-finance.ts index b276fce114..d91112d73b 100644 --- a/fees/lybra-finance.ts +++ b/fees/lybra-finance.ts @@ -17,30 +17,25 @@ const contract_interface = new ethers.Interface([ const fetch = async (timestamp: number): Promise => { const fromTimestamp = timestamp - 60 * 60 * 24 const toTimestamp = timestamp - try { - const fromBlock = (await getBlock(fromTimestamp, CHAIN.ETHEREUM, {})); - const toBlock = (await getBlock(toTimestamp, CHAIN.ETHEREUM, {})); - const dailyFees = (await sdk.getEventLogs({ - target: address, - fromBlock: fromBlock, - toBlock: toBlock, - topics: [topic0_fees_distibute], - chain: CHAIN.ETHEREUM - })).map((e: any) => contract_interface.parseLog(e)) + const fromBlock = (await getBlock(fromTimestamp, CHAIN.ETHEREUM, {})); + const toBlock = (await getBlock(toTimestamp, CHAIN.ETHEREUM, {})); + const dailyFees = (await sdk.getEventLogs({ + target: address, + fromBlock: fromBlock, + toBlock: toBlock, + topics: [topic0_fees_distibute], + chain: CHAIN.ETHEREUM + })).map((e: any) => contract_interface.parseLog(e)) .map((e: any) => { return Number(e!.args.feeAmount) / 10 ** 18; - }).reduce((a: number, b: number) => a + b,0) - const dailyRevenue = dailyFees; - const dailyHoldersRevenue = dailyFees; - return { - dailyFees: `${dailyFees}`, - dailyRevenue: `${dailyRevenue}`, - dailyHoldersRevenue: `${dailyHoldersRevenue}`, - timestamp - } - } catch(error) { - console.error(error); - throw error; + }).reduce((a: number, b: number) => a + b, 0) + const dailyRevenue = dailyFees; + const dailyHoldersRevenue = dailyFees; + return { + dailyFees: `${dailyFees}`, + dailyRevenue: `${dailyRevenue}`, + dailyHoldersRevenue: `${dailyHoldersRevenue}`, + timestamp } } diff --git a/fees/lybra-v2.ts b/fees/lybra-v2.ts index 54935880cb..9447186bd3 100644 --- a/fees/lybra-v2.ts +++ b/fees/lybra-v2.ts @@ -17,30 +17,25 @@ const contract_interface = new ethers.Interface([ const fetch = async (timestamp: number): Promise => { const fromTimestamp = timestamp - 60 * 60 * 24 const toTimestamp = timestamp - try { - const fromBlock = (await getBlock(fromTimestamp, CHAIN.ETHEREUM, {})); - const toBlock = (await getBlock(toTimestamp, CHAIN.ETHEREUM, {})); - const dailyFees = (await sdk.getEventLogs({ - target: address, - fromBlock: fromBlock, - toBlock: toBlock, - topics: [topic0_fees_distibute], - chain: CHAIN.ETHEREUM - })).map((e: any) => contract_interface.parseLog(e)) + const fromBlock = (await getBlock(fromTimestamp, CHAIN.ETHEREUM, {})); + const toBlock = (await getBlock(toTimestamp, CHAIN.ETHEREUM, {})); + const dailyFees = (await sdk.getEventLogs({ + target: address, + fromBlock: fromBlock, + toBlock: toBlock, + topics: [topic0_fees_distibute], + chain: CHAIN.ETHEREUM + })).map((e: any) => contract_interface.parseLog(e)) .map((e: any) => { return Number(e!.args.feeAmount) / 10 ** 18; - }).reduce((a: number, b: number) => a + b,0) - const dailyRevenue = dailyFees; - const dailyHoldersRevenue = dailyFees; - return { - dailyFees: `${dailyFees}`, - dailyRevenue: `${dailyRevenue}`, - dailyHoldersRevenue: `${dailyHoldersRevenue}`, - timestamp - } - } catch(error) { - console.error(error); - throw error; + }).reduce((a: number, b: number) => a + b, 0) + const dailyRevenue = dailyFees; + const dailyHoldersRevenue = dailyFees; + return { + dailyFees: `${dailyFees}`, + dailyRevenue: `${dailyRevenue}`, + dailyHoldersRevenue: `${dailyHoldersRevenue}`, + timestamp } } diff --git a/fees/maestro.ts b/fees/maestro.ts index 043cae57ab..e088960569 100644 --- a/fees/maestro.ts +++ b/fees/maestro.ts @@ -21,7 +21,7 @@ const build_query = (timestamp: number): string => { const dayAgo = new Date(now.getTime() - 1000 * 60 * 60 * 24) return chains.map((chain: Chain) => ` SELECT - SUM(${chain === "bsc"?"BNB_VALUE":"eth_value"}), + SUM(${chain === "bsc" ? "BNB_VALUE" : "eth_value"}), '${chain}' as chain from ${chain}.core.fact_transactions @@ -32,26 +32,21 @@ const build_query = (timestamp: number): string => { const graph = (chain: Chain) => { return async (timestamp: number): Promise => { - try { - const query = build_query(timestamp); - const value: number = (await queryFlipside(query, 260)) - .map(([fee, chain]: [string, string]) => { - return { - fee, chain - } as any - }).filter((e: any) => e.chain === chain).map((e: any) => Number(e.fee)).reduce((a: number, b: number) => a + b, 0); - const amount = value; - const gasId = gasTokenId[chain]; - const gasIdPrice = (await getPrices([gasId], timestamp))[gasId].price; - const dailyFees = (amount * gasIdPrice) - return { - dailyFees: `${dailyFees}`, - dailyRevenue: `${dailyFees}`, - timestamp - } - } catch (err) { - console.log(err); - throw err; + const query = build_query(timestamp); + const value: number = (await queryFlipside(query, 260)) + .map(([fee, chain]: [string, string]) => { + return { + fee, chain + } as any + }).filter((e: any) => e.chain === chain).map((e: any) => Number(e.fee)).reduce((a: number, b: number) => a + b, 0); + const amount = value; + const gasId = gasTokenId[chain]; + const gasIdPrice = (await getPrices([gasId], timestamp))[gasId].price; + const dailyFees = (amount * gasIdPrice) + return { + dailyFees: `${dailyFees}`, + dailyRevenue: `${dailyFees}`, + timestamp } } @@ -61,16 +56,16 @@ const graph = (chain: Chain) => { const adapter: Adapter = { adapter: { [CHAIN.ETHEREUM]: { - fetch: graph(CHAIN.ETHEREUM), - start: async () => 1656633600, + fetch: graph(CHAIN.ETHEREUM), + start: async () => 1656633600, }, [CHAIN.BSC]: { fetch: graph(CHAIN.BSC), - start: async () => 1656633600, + start: async () => 1656633600, }, [CHAIN.ARBITRUM]: { fetch: graph(CHAIN.ARBITRUM), - start: async () => 1675468800, + start: async () => 1675468800, }, } } diff --git a/fees/manta.ts b/fees/manta.ts index 7b97de795d..ba3301c333 100644 --- a/fees/manta.ts +++ b/fees/manta.ts @@ -100,7 +100,6 @@ const fetch = async (timestamp: number, chainBlocks: ChainBlocks): Promise { } } catch (error) { await sql.end({ timeout: 3 }) - console.error(error); throw error; } } diff --git a/fees/metamask.ts b/fees/metamask.ts index ceae8705b8..379ac216c8 100644 --- a/fees/metamask.ts +++ b/fees/metamask.ts @@ -42,10 +42,9 @@ const graph = (chain: Chain) => { const fromTimestamp = timestamp - 60 * 60 * 24 const toTimestamp = timestamp - try { - const startblock = (await getBlock(fromTimestamp, chain, {})); - const endblock = (await getBlock(toTimestamp, chain, {})); - const query = ` + const startblock = (await getBlock(fromTimestamp, chain, {})); + const endblock = (await getBlock(toTimestamp, chain, {})); + const query = ` select input_data, TX_HASH @@ -56,56 +55,52 @@ const graph = (chain: Chain) => { ` - const value: string[][] = (await queryFlipside(query, 210)) - const rawData = value.map((a: string[]) => { - const data = a[0].replace('0x5f575529', ''); - const address = data.slice(64, 128); - const amount = Number('0x'+data.slice(128, 192)); - const tokenAddress = '0x' + address.slice(24, address.length); - return { - amount: amount, - tokenAddress: tokenAddress, - tx: a[1] - } as IVolume - }) - const coins =[...new Set(rawData.map((a: IVolume) => `${chain}:${a.tokenAddress.toLowerCase()}`))] - const coins_split = []; - for(let i = 0; i < coins.length; i+=100) { - coins_split.push(coins.slice(i, i + 100)) - } - const prices_result: any = (await Promise.all(coins_split.map((a: string[]) => getPrices(a, timestamp)))).flat().flat().flat(); - const prices: TPrice = Object.assign({}, {}); - prices_result.map((a: any) => Object.assign(prices, a)) - - const volumeUSD: IVolume[] = rawData.map((e: IVolume) => { - const price = prices[`${chain}:${e.tokenAddress.toLowerCase()}`]?.price || 0; - const decimals = prices[`${chain}:${e.tokenAddress.toLowerCase()}`]?.decimals || 0; - if (!price || !decimals) return { - amount: 0, - tokenAddress: e.tokenAddress, - tx: e.tx - } as IVolume; - const amount = (Number(e.amount) / 10 ** decimals) * price; - return { - amount: amount, - tokenAddress: e.tokenAddress, - tx: e.tx - } as IVolume - }).filter((a: IVolume) => !isNaN(a.amount)) - .filter((a: IVolume) => !blackList[chain]?.includes(a.tokenAddress.toLowerCase())) - .filter((a: IVolume) => a.amount < 10_000_000) - const dailyVolume = volumeUSD.reduce((a: number, b: IVolume) => a + b.amount, 0); - const dailyFees = dailyVolume * 0.0085 + const value: string[][] = (await queryFlipside(query, 210)) + const rawData = value.map((a: string[]) => { + const data = a[0].replace('0x5f575529', ''); + const address = data.slice(64, 128); + const amount = Number('0x' + data.slice(128, 192)); + const tokenAddress = '0x' + address.slice(24, address.length); + return { + amount: amount, + tokenAddress: tokenAddress, + tx: a[1] + } as IVolume + }) + const coins = [...new Set(rawData.map((a: IVolume) => `${chain}:${a.tokenAddress.toLowerCase()}`))] + const coins_split = []; + for (let i = 0; i < coins.length; i += 100) { + coins_split.push(coins.slice(i, i + 100)) + } + const prices_result: any = (await Promise.all(coins_split.map((a: string[]) => getPrices(a, timestamp)))).flat().flat().flat(); + const prices: TPrice = Object.assign({}, {}); + prices_result.map((a: any) => Object.assign(prices, a)) + const volumeUSD: IVolume[] = rawData.map((e: IVolume) => { + const price = prices[`${chain}:${e.tokenAddress.toLowerCase()}`]?.price || 0; + const decimals = prices[`${chain}:${e.tokenAddress.toLowerCase()}`]?.decimals || 0; + if (!price || !decimals) return { + amount: 0, + tokenAddress: e.tokenAddress, + tx: e.tx + } as IVolume; + const amount = (Number(e.amount) / 10 ** decimals) * price; return { - dailyFees: `${dailyFees}`, - dailyProtocolRevenue: `${dailyFees}`, - dailyRevenue: `${dailyFees}`, - timestamp - } - } catch (err) { - console.log(err); - throw err; + amount: amount, + tokenAddress: e.tokenAddress, + tx: e.tx + } as IVolume + }).filter((a: IVolume) => !isNaN(a.amount)) + .filter((a: IVolume) => !blackList[chain]?.includes(a.tokenAddress.toLowerCase())) + .filter((a: IVolume) => a.amount < 10_000_000) + const dailyVolume = volumeUSD.reduce((a: number, b: IVolume) => a + b.amount, 0); + const dailyFees = dailyVolume * 0.0085 + + return { + dailyFees: `${dailyFees}`, + dailyProtocolRevenue: `${dailyFees}`, + dailyRevenue: `${dailyFees}`, + timestamp } } @@ -115,19 +110,19 @@ const adapter: Adapter = { adapter: { [CHAIN.ETHEREUM]: { fetch: graph(CHAIN.ETHEREUM), - start: async () => 1672531200, + start: async () => 1672531200, }, [CHAIN.POLYGON]: { fetch: graph(CHAIN.POLYGON), - start: async () => 1672531200, + start: async () => 1672531200, }, [CHAIN.BSC]: { fetch: graph(CHAIN.BSC), - start: async () => 1672531200, + start: async () => 1672531200, }, [CHAIN.ARBITRUM]: { fetch: graph(CHAIN.ARBITRUM), - start: async () => 1672531200, + start: async () => 1672531200, } } } diff --git a/fees/none-trading-bot.ts b/fees/none-trading-bot.ts index 055fa2347e..411c7084ac 100644 --- a/fees/none-trading-bot.ts +++ b/fees/none-trading-bot.ts @@ -49,7 +49,6 @@ const fetch = async (timestamp: number): Promise => { } } catch (error) { await sql.end({ timeout: 3 }) - console.error(error); throw error; } diff --git a/fees/odos.ts b/fees/odos.ts index 5056e9364f..b462272245 100644 --- a/fees/odos.ts +++ b/fees/odos.ts @@ -59,88 +59,83 @@ type TPool = { [c: string]: string[]; } const FEE_COLLECTORS: TPool = { - [CHAIN.ETHEREUM]: [ '0xCf5540fFFCdC3d510B18bFcA6d2b9987b0772559', ], - [CHAIN.ARBITRUM]: [ '0xa669e7A0d4b3e4Fa48af2dE86BD4CD7126Be4e13', ], - [CHAIN.OPTIMISM]: [ '0xCa423977156BB05b13A2BA3b76Bc5419E2fE9680', ], - [CHAIN.BASE]: [ '0x19cEeAd7105607Cd444F5ad10dd51356436095a1', ], - [CHAIN.POLYGON]: [ '0x4E3288c9ca110bCC82bf38F09A7b425c095d92Bf', ], - [CHAIN.AVAX]: [ '0x88de50B233052e4Fb783d4F6db78Cc34fEa3e9FC', ], - [CHAIN.BSC]: [ '0x89b8AA89FDd0507a99d334CBe3C808fAFC7d850E', ], - [CHAIN.FANTOM]: [ '0xd0c22a5435f4e8e5770c1fafb5374015fc12f7cd', ], + [CHAIN.ETHEREUM]: ['0xCf5540fFFCdC3d510B18bFcA6d2b9987b0772559',], + [CHAIN.ARBITRUM]: ['0xa669e7A0d4b3e4Fa48af2dE86BD4CD7126Be4e13',], + [CHAIN.OPTIMISM]: ['0xCa423977156BB05b13A2BA3b76Bc5419E2fE9680',], + [CHAIN.BASE]: ['0x19cEeAd7105607Cd444F5ad10dd51356436095a1',], + [CHAIN.POLYGON]: ['0x4E3288c9ca110bCC82bf38F09A7b425c095d92Bf',], + [CHAIN.AVAX]: ['0x88de50B233052e4Fb783d4F6db78Cc34fEa3e9FC',], + [CHAIN.BSC]: ['0x89b8AA89FDd0507a99d334CBe3C808fAFC7d850E',], + [CHAIN.FANTOM]: ['0xd0c22a5435f4e8e5770c1fafb5374015fc12f7cd',], //[CHAIN.ZKSYNC]: [ '0x4bBa932E9792A2b917D47830C93a9BC79320E4f7', ], - [CHAIN.POLYGON_ZKEVM]:[ '0x2b8B3f0949dfB616602109D2AAbBA11311ec7aEC', ], + [CHAIN.POLYGON_ZKEVM]: ['0x2b8B3f0949dfB616602109D2AAbBA11311ec7aEC',], } const graph = (chain: Chain) => { return async (timestamp: number): Promise => { const fromTimestamp = timestamp - 60 * 60 * 24 const toTimestamp = timestamp - try { - const feeCollectors = FEE_COLLECTORS[chain]; - - const fromBlock = (await getBlock(fromTimestamp, chain, {})); - const toBlock = (await getBlock(toTimestamp, chain, {})); - - //console.log(feeCollectors,fromBlock,toBlock,chain); - - const logs: ILog[][] = (await Promise.all(feeCollectors.map((address: string) => sdk.getEventLogs({ - target: address, - toBlock: toBlock, - fromBlock: fromBlock, - chain: chain, - topics: [topic0_swap_one] - })))) as ILog[][]; - - const rawCoinsPerTreasury: string[][] = feeCollectors.map((_: string, index: number) => { - const logsToTokenList: string[] = logs[index] - .map((e: ILog) => { return { ...e } }) - .map((p: ILog) => { - return `${chain}:${contract_interface.parseLog(p)!.args.outputToken}`; - }); - return (logsToTokenList); - }); - - const rawCoins: string[] = rawCoinsPerTreasury.reduce( (a:string[], b:any) => [...a, ...b] ); - const coins = [...new Set(rawCoins)]; - const prices = await getPrices(coins, timestamp); - - - const untrackVolumes: any[] = feeCollectors.map((_: string, index: number) => { - //const token0Decimals = prices[`${chain}:${tokens0[index]}`]?.decimals || 0 - //const token1Decimals = prices[`${chain}:${tokens1[index]}`]?.decimals || 0 - const log: IAmount[] = logs[index] - .map((e: ILog) => { return { ...e } }) - .map((p: ILog) => { - const value = contract_interface.parseLog(p); - const _token = value!.args.outputToken; - const _price = (prices[`${chain}:${_token}`]?.price || 0); - const _deci = prices[`${chain}:${_token}`]?.decimals || 0; - const _slip = Number(value!.args.slippage); - const feesAmount = (_slip>0?_slip:0) / 10 ** _deci * _price; - return { - feesAmount, - } as IAmount - }); - - const totalFees = log.reduce((a: number, b: IAmount) => Number(b.feesAmount) + a, 0) ; - return { - fees: totalFees - }; - }); - - const dailyFees = untrackVolumes.reduce((a: number, b: any) => a + b.fees, 0); - const dailyRevenue = untrackVolumes.reduce((a: number, b: any) => a + b.rev, 0); + const feeCollectors = FEE_COLLECTORS[chain]; + + const fromBlock = (await getBlock(fromTimestamp, chain, {})); + const toBlock = (await getBlock(toTimestamp, chain, {})); + + //console.log(feeCollectors,fromBlock,toBlock,chain); + + const logs: ILog[][] = (await Promise.all(feeCollectors.map((address: string) => sdk.getEventLogs({ + target: address, + toBlock: toBlock, + fromBlock: fromBlock, + chain: chain, + topics: [topic0_swap_one] + })))) as ILog[][]; + + const rawCoinsPerTreasury: string[][] = feeCollectors.map((_: string, index: number) => { + const logsToTokenList: string[] = logs[index] + .map((e: ILog) => { return { ...e } }) + .map((p: ILog) => { + return `${chain}:${contract_interface.parseLog(p)!.args.outputToken}`; + }); + return (logsToTokenList); + }); + + const rawCoins: string[] = rawCoinsPerTreasury.reduce((a: string[], b: any) => [...a, ...b]); + const coins = [...new Set(rawCoins)]; + const prices = await getPrices(coins, timestamp); + + + const untrackVolumes: any[] = feeCollectors.map((_: string, index: number) => { + //const token0Decimals = prices[`${chain}:${tokens0[index]}`]?.decimals || 0 + //const token1Decimals = prices[`${chain}:${tokens1[index]}`]?.decimals || 0 + const log: IAmount[] = logs[index] + .map((e: ILog) => { return { ...e } }) + .map((p: ILog) => { + const value = contract_interface.parseLog(p); + const _token = value!.args.outputToken; + const _price = (prices[`${chain}:${_token}`]?.price || 0); + const _deci = prices[`${chain}:${_token}`]?.decimals || 0; + const _slip = Number(value!.args.slippage); + const feesAmount = (_slip > 0 ? _slip : 0) / 10 ** _deci * _price; + return { + feesAmount, + } as IAmount + }); + + const totalFees = log.reduce((a: number, b: IAmount) => Number(b.feesAmount) + a, 0); return { - dailyFees: `${dailyFees}`, - dailyRevenue: `${dailyFees}`, - dailyHoldersRevenue: `${0}`, - dailySupplySideRevenue: `${0}`, - timestamp, + fees: totalFees }; - } catch(error) { - console.error(error); - throw error; - } + }); + + const dailyFees = untrackVolumes.reduce((a: number, b: any) => a + b.fees, 0); + const dailyRevenue = untrackVolumes.reduce((a: number, b: any) => a + b.rev, 0); + return { + dailyFees: `${dailyFees}`, + dailyRevenue: `${dailyFees}`, + dailyHoldersRevenue: `${0}`, + dailySupplySideRevenue: `${0}`, + timestamp, + }; } } @@ -148,16 +143,16 @@ const graph = (chain: Chain) => { const adapter: SimpleAdapter = { adapter: { - [CHAIN.ETHEREUM]: { fetch: graph(CHAIN.ETHEREUM), start: 1689292800 }, - [CHAIN.ARBITRUM]: { fetch: graph(CHAIN.ARBITRUM), start: 1689292800 }, - [CHAIN.OPTIMISM]: { fetch: graph(CHAIN.OPTIMISM), start: 1689292800 }, - [CHAIN.BASE]: { fetch: graph(CHAIN.BASE), start: 1689292800 }, - [CHAIN.POLYGON]: { fetch: graph(CHAIN.POLYGON), start: 1689292800 }, - [CHAIN.AVAX]: { fetch: graph(CHAIN.AVAX), start: 1689292800 }, - //[CHAIN.BSC]: { fetch: graph(CHAIN.BSC), start: 1689292800 }, - [CHAIN.FANTOM]: { fetch: graph(CHAIN.FANTOM), start: 1689292800 }, - //[CHAIN.ZKSYNC]: { fetch: graph(CHAIN.ZKSYNC), start: 1689292800 }, - [CHAIN.POLYGON_ZKEVM]:{ fetch: graph(CHAIN.POLYGON_ZKEVM), start: 1689292800 } + [CHAIN.ETHEREUM]: { fetch: graph(CHAIN.ETHEREUM), start: 1689292800 }, + [CHAIN.ARBITRUM]: { fetch: graph(CHAIN.ARBITRUM), start: 1689292800 }, + [CHAIN.OPTIMISM]: { fetch: graph(CHAIN.OPTIMISM), start: 1689292800 }, + [CHAIN.BASE]: { fetch: graph(CHAIN.BASE), start: 1689292800 }, + [CHAIN.POLYGON]: { fetch: graph(CHAIN.POLYGON), start: 1689292800 }, + [CHAIN.AVAX]: { fetch: graph(CHAIN.AVAX), start: 1689292800 }, + //[CHAIN.BSC]: { fetch: graph(CHAIN.BSC), start: 1689292800 }, + [CHAIN.FANTOM]: { fetch: graph(CHAIN.FANTOM), start: 1689292800 }, + //[CHAIN.ZKSYNC]: { fetch: graph(CHAIN.ZKSYNC), start: 1689292800 }, + [CHAIN.POLYGON_ZKEVM]: { fetch: graph(CHAIN.POLYGON_ZKEVM), start: 1689292800 } } }; diff --git a/fees/op-bnb.ts b/fees/op-bnb.ts index 3ed030955c..a4e1ed0e23 100644 --- a/fees/op-bnb.ts +++ b/fees/op-bnb.ts @@ -15,10 +15,10 @@ interface ILog { topics: string[]; } -async function getFees(toTimestamp:number, fromTimestamp:number, chainBlocks: ChainBlocks){ - const todaysBlock1 = (await getBlock(toTimestamp,CHAIN.OP_BNB, {})); - const todaysBlock = (await getBlock(toTimestamp,CHAIN.OP_BNB, chainBlocks)); - const yesterdaysBlock = (await getBlock(fromTimestamp,CHAIN.OP_BNB, {})); +async function getFees(toTimestamp: number, fromTimestamp: number, chainBlocks: ChainBlocks) { + const todaysBlock1 = (await getBlock(toTimestamp, CHAIN.OP_BNB, {})); + const todaysBlock = (await getBlock(toTimestamp, CHAIN.OP_BNB, chainBlocks)); + const yesterdaysBlock = (await getBlock(fromTimestamp, CHAIN.OP_BNB, {})); const feeWallet = '0x4200000000000000000000000000000000000011'; const l1FeeVault = '0x420000000000000000000000000000000000001a'; const logsWithdrawal: ILog[] = (await Promise.all([feeWallet, l1FeeVault].map(address => sdk.getEventLogs({ @@ -35,51 +35,45 @@ async function getFees(toTimestamp:number, fromTimestamp:number, chainBlocks: Ch }).reduce((a: number, b: number) => a + b, 0); return await retry(async () => { - try { + const [feeWalletStart, feeWalletEnd, l1FeeVaultStart, l1FeeVaultEnd] = (await Promise.all([ + getBalance({ + target: feeWallet, + block: yesterdaysBlock, + chain: CHAIN.OP_BNB + }), + getBalance({ + target: feeWallet, + block: todaysBlock, + chain: CHAIN.OP_BNB + }), + getBalance({ + target: l1FeeVault, + block: yesterdaysBlock, + chain: CHAIN.OP_BNB + }), + getBalance({ + target: l1FeeVault, + block: todaysBlock, + chain: CHAIN.OP_BNB + }) + ])).map(i => i.output); - const [feeWalletStart, feeWalletEnd, l1FeeVaultStart, l1FeeVaultEnd] = (await Promise.all([ - getBalance({ - target: feeWallet, - block: yesterdaysBlock, - chain:CHAIN.OP_BNB - }), - getBalance({ - target: feeWallet, - block: todaysBlock, - chain:CHAIN.OP_BNB - }), - getBalance({ - target: l1FeeVault, - block: yesterdaysBlock, - chain:CHAIN.OP_BNB - }), - getBalance({ - target: l1FeeVault, - block: todaysBlock, - chain:CHAIN.OP_BNB - }) - ])).map(i => i.output); + const ethBalance = (new BigNumber(feeWalletEnd).minus(feeWalletStart)) + .plus((new BigNumber(l1FeeVaultEnd).minus(l1FeeVaultStart))) - const ethBalance = (new BigNumber(feeWalletEnd).minus(feeWalletStart)) - .plus((new BigNumber(l1FeeVaultEnd).minus(l1FeeVaultStart))) - - return (ethBalance.plus(withdrawAmount)).div(1e18) - } catch (e) { - throw e; - } - }, { retries: 5, minTimeout: 1000 * 60 * 5 }); + return (ethBalance.plus(withdrawAmount)).div(1e18) + }, { retries: 5, minTimeout: 1000 * 60 * 5 }); } const fetch = async (timestamp: number, chainBlocks: ChainBlocks): Promise => { const fromTimestamp = timestamp - 60 * 60 * 24 const toTimestamp = timestamp - try { - const [totalFees] = await Promise.all([ - getFees(toTimestamp, fromTimestamp, chainBlocks), - ]); - const endblock = (await getBlock(toTimestamp,CHAIN.BSC, chainBlocks)); - const startblock = (await getBlock(fromTimestamp,CHAIN.BSC, {})); - const query = ` + const [totalFees] = await Promise.all([ + getFees(toTimestamp, fromTimestamp, chainBlocks), + ]); + const endblock = (await getBlock(toTimestamp, CHAIN.BSC, chainBlocks)); + const startblock = (await getBlock(fromTimestamp, CHAIN.BSC, {})); + const query = ` select SUM(TX_FEE) from @@ -88,31 +82,27 @@ const fetch = async (timestamp: number, chainBlocks: ChainBlocks): Promise ${startblock} AND BLOCK_NUMBER < ${endblock} ` - const value: number[] = (await queryFlipside(query, 260)).flat(); - const cost_to_l1 = value[0] - const bnbAddress = "bsc:0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c"; - const pricesObj: any = await getPrices([bnbAddress], toTimestamp); - const latestPrice = pricesObj[bnbAddress]["price"] - const finalDailyFee = totalFees.times(latestPrice) - const cost_to_l1_usd = cost_to_l1 * latestPrice - const dailyRevenue = finalDailyFee.minus(cost_to_l1_usd); - return { - timestamp, - dailyFees: `${finalDailyFee}`, - dailyRevenue: `${dailyRevenue}` - } - } catch(error) { - console.error(error); - throw error; - } + const value: number[] = (await queryFlipside(query, 260)).flat(); + const cost_to_l1 = value[0] + const bnbAddress = "bsc:0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c"; + const pricesObj: any = await getPrices([bnbAddress], toTimestamp); + const latestPrice = pricesObj[bnbAddress]["price"] + const finalDailyFee = totalFees.times(latestPrice) + const cost_to_l1_usd = cost_to_l1 * latestPrice + const dailyRevenue = finalDailyFee.minus(cost_to_l1_usd); + return { + timestamp, + dailyFees: `${finalDailyFee}`, + dailyRevenue: `${dailyRevenue}` + } } const adapter: Adapter = { adapter: { - [CHAIN.OP_BNB]: { - fetch: fetch, - start: 1691971200, - }, + [CHAIN.OP_BNB]: { + fetch: fetch, + start: 1691971200, + }, }, protocolType: ProtocolType.CHAIN } diff --git a/fees/opensea/seaport.ts b/fees/opensea/seaport.ts index 5560b4023b..ddd05d410d 100644 --- a/fees/opensea/seaport.ts +++ b/fees/opensea/seaport.ts @@ -41,62 +41,57 @@ const fees_collector = '0x0000a26b00c1f0df003000390027140000faa719'; export const fetch = async (timestamp: number): Promise => { const fromTimestamp = timestamp - 60 * 60 * 24 const toTimestamp = timestamp - try { - const fromBlock = (await getBlock(fromTimestamp, CHAIN.ETHEREUM, {})); - const toBlock = (await getBlock(toTimestamp, CHAIN.ETHEREUM, {})); - const logs: ILog[] = (await Promise.all(contracts.filter(e => e.startBlcok <= fromBlock).map((contract: IConrtact) => sdk.getEventLogs({ - target: contract.adddress, - toBlock: toBlock, - fromBlock: fromBlock, - chain: CHAIN.ETHEREUM, - topics: [topic0] - })))).flat() as ILog[]; + const fromBlock = (await getBlock(fromTimestamp, CHAIN.ETHEREUM, {})); + const toBlock = (await getBlock(toTimestamp, CHAIN.ETHEREUM, {})); + const logs: ILog[] = (await Promise.all(contracts.filter(e => e.startBlcok <= fromBlock).map((contract: IConrtact) => sdk.getEventLogs({ + target: contract.adddress, + toBlock: toBlock, + fromBlock: fromBlock, + chain: CHAIN.ETHEREUM, + topics: [topic0] + })))).flat() as ILog[]; - const fes_raw: IAmount[] = logs.filter(e => e.data.length === 1602) - .map((e: ILog) => { - const data = e.data.replace('0x', ''); - const fees_1 = Number('0x'+data.slice(18 * 64, (18*64)+64)) / 10 ** 18; - const address_1 = data.slice((19 * 64), (19 * 64) + 64); - const contract_address_1 = '0x' + address_1.slice(24, address_1.length); + const fes_raw: IAmount[] = logs.filter(e => e.data.length === 1602) + .map((e: ILog) => { + const data = e.data.replace('0x', ''); + const fees_1 = Number('0x' + data.slice(18 * 64, (18 * 64) + 64)) / 10 ** 18; + const address_1 = data.slice((19 * 64), (19 * 64) + 64); + const contract_address_1 = '0x' + address_1.slice(24, address_1.length); - const fees_2 = Number('0x'+data.slice(23 * 64, (23*64)+64)) / 10 ** 18; - const address_2 = data.slice((24 * 64), (24 * 64) + 64); - const contract_address_2 = '0x' + address_2.slice(24, address_2.length); - const min = Math.min(fees_1, fees_2); - const max = Math.max(fees_1, fees_2); - const isHaveMPFees = [contract_address_1.toLowerCase(), contract_address_2.toLowerCase()].includes(fees_collector.toLowerCase()); - return { - creator_fee: max, - marketplace_fee: min, - isHaveMPFees - } - }) + const fees_2 = Number('0x' + data.slice(23 * 64, (23 * 64) + 64)) / 10 ** 18; + const address_2 = data.slice((24 * 64), (24 * 64) + 64); + const contract_address_2 = '0x' + address_2.slice(24, address_2.length); + const min = Math.min(fees_1, fees_2); + const max = Math.max(fees_1, fees_2); + const isHaveMPFees = [contract_address_1.toLowerCase(), contract_address_2.toLowerCase()].includes(fees_collector.toLowerCase()); + return { + creator_fee: max, + marketplace_fee: min, + isHaveMPFees + } + }) - const marketplace_fee = fes_raw - .filter(e => e.isHaveMPFees) - .map(e => e.marketplace_fee as number) - .filter((e) => !isNaN(e)) - .filter(e => e < 100) - .reduce((a: number, b: number) => a+b,0) + const marketplace_fee = fes_raw + .filter(e => e.isHaveMPFees) + .map(e => e.marketplace_fee as number) + .filter((e) => !isNaN(e)) + .filter(e => e < 100) + .reduce((a: number, b: number) => a + b, 0) - const creator_fee = fes_raw.map(e => e.creator_fee as number) - .filter((e) => !isNaN(e)) - .filter(e => e < 100) - .reduce((a: number, b: number) => a+b,0) + const creator_fee = fes_raw.map(e => e.creator_fee as number) + .filter((e) => !isNaN(e)) + .filter(e => e < 100) + .reduce((a: number, b: number) => a + b, 0) - const fees = (marketplace_fee + creator_fee); - const rev = (marketplace_fee); - const ethAddress = "ethereum:0x0000000000000000000000000000000000000000"; - const ethPrice = (await getPrices([ethAddress], timestamp))[ethAddress].price; - const dailyFees = (fees * ethPrice) - const dailyRevenue = (rev * ethPrice) - return { - dailyFees: `${dailyFees}`, - dailyRevenue: `${dailyRevenue}`, - timestamp - } - } catch (error) { - console.error(error); - throw error; + const fees = (marketplace_fee + creator_fee); + const rev = (marketplace_fee); + const ethAddress = "ethereum:0x0000000000000000000000000000000000000000"; + const ethPrice = (await getPrices([ethAddress], timestamp))[ethAddress].price; + const dailyFees = (fees * ethPrice) + const dailyRevenue = (rev * ethPrice) + return { + dailyFees: `${dailyFees}`, + dailyRevenue: `${dailyRevenue}`, + timestamp } } diff --git a/fees/optimism.ts b/fees/optimism.ts index c6cf3089c1..2eabb055b5 100644 --- a/fees/optimism.ts +++ b/fees/optimism.ts @@ -136,7 +136,6 @@ const feesAdapter = async (timestamp: number, chainBlocks: ChainBlocks) => { }; } catch (error) { await sql.end({ timeout: 3 }) - console.error(error); throw error; } diff --git a/fees/paal-ai/index.ts b/fees/paal-ai/index.ts index 4fea072979..10c4379af7 100644 --- a/fees/paal-ai/index.ts +++ b/fees/paal-ai/index.ts @@ -79,7 +79,6 @@ async function usdEquivalent(_: string, timestamp: number) { return dailyFees; } catch (error) { await sql.end({ timeout: 3 }) - console.error(error); throw error; } } diff --git a/fees/perpetual-protocol.ts b/fees/perpetual-protocol.ts index d771a1ccb7..90bfd0e155 100644 --- a/fees/perpetual-protocol.ts +++ b/fees/perpetual-protocol.ts @@ -20,35 +20,30 @@ interface ILog { const fetchFees = async (timestamp: number): Promise => { const toTimestamp = timestamp const fromTimestamp = timestamp - 60 * 60 * 24 - try { - const fromBlock = (await getBlock(fromTimestamp, CHAIN.OPTIMISM, {})) - const toBlock = (await getBlock(toTimestamp, CHAIN.OPTIMISM, {})) - const logs_position_chnage: ILog[] = (await sdk.getEventLogs({ - target: address, - topics: [topic0_position_change], - toBlock: toBlock, - fromBlock: fromBlock, - chain: CHAIN.OPTIMISM - })) as ILog[]; + const fromBlock = (await getBlock(fromTimestamp, CHAIN.OPTIMISM, {})) + const toBlock = (await getBlock(toTimestamp, CHAIN.OPTIMISM, {})) + const logs_position_chnage: ILog[] = (await sdk.getEventLogs({ + target: address, + topics: [topic0_position_change], + toBlock: toBlock, + fromBlock: fromBlock, + chain: CHAIN.OPTIMISM + })) as ILog[]; - const fees_details = logs_position_chnage.map((e: ILog) => { - const value = contract_interface.parseLog(e); - return Number(value!.args.fee) / 10 ** 18; - }).reduce((a: number, b: number) => a + b, 0) + const fees_details = logs_position_chnage.map((e: ILog) => { + const value = contract_interface.parseLog(e); + return Number(value!.args.fee) / 10 ** 18; + }).reduce((a: number, b: number) => a + b, 0) - const dailyFees = fees_details - const dailyRevenue = dailyFees * 0.2; - const dailySupplySideRevenue = dailyFees * 0.8; - return { - dailyFees: `${dailyFees}`, - dailyRevenue: `${dailyRevenue}`, - dailySupplySideRevenue: `${dailySupplySideRevenue}`, - timestamp - } - } catch (error) { - console.error(error) - throw error; + const dailyFees = fees_details + const dailyRevenue = dailyFees * 0.2; + const dailySupplySideRevenue = dailyFees * 0.8; + return { + dailyFees: `${dailyFees}`, + dailyRevenue: `${dailyRevenue}`, + dailySupplySideRevenue: `${dailySupplySideRevenue}`, + timestamp } } diff --git a/fees/post-tech.ts b/fees/post-tech.ts index 805c64562b..33f5fb3dbd 100644 --- a/fees/post-tech.ts +++ b/fees/post-tech.ts @@ -58,7 +58,6 @@ const fetchFees = async (timestamp: number): Promise => { timestamp } } catch (error) { - console.error(error) throw error; } diff --git a/fees/prisma-finance.ts b/fees/prisma-finance.ts index 1ac73c212e..c82134d174 100644 --- a/fees/prisma-finance.ts +++ b/fees/prisma-finance.ts @@ -46,7 +46,6 @@ const fetch = async (timestamp: number): Promise => { } } catch (error) { sql.end({ timeout: 3 }) - console.error(error); throw error; } diff --git a/fees/qidao.ts b/fees/qidao.ts index 1cb110cc36..d2f86c44bc 100644 --- a/fees/qidao.ts +++ b/fees/qidao.ts @@ -53,66 +53,61 @@ const fetch = (chain: Chain) => { return async (timestamp: number): Promise => { const fromTimestamp = timestamp - 60 * 60 * 24 const toTimestamp = timestamp - try { - const fromBlock = (await getBlock(fromTimestamp, chain, {})); - const toBlock = (await getBlock(toTimestamp, chain, {})); - - const log_withdraw_fees: ILog[] = Vault_Fee_Manager_Contracts[chain] ? (await sdk.getEventLogs({ - target: Vault_Fee_Manager_Contracts[chain], - toBlock: toBlock, - fromBlock: fromBlock, - chain: chain, - topics: [topic0_fees_withdraw] - })) as ILog[] : []; - - const log_token_earned: ILog[] = Performance_Fee_Management_Contracts[chain] ? (await sdk.getEventLogs({ - target: Performance_Fee_Management_Contracts[chain], - toBlock: toBlock, - fromBlock: fromBlock, - chain: chain, - topics: [topic0_token_earned] - })) as ILog[] : []; - - const raw_withdraw: IRAW[] = log_withdraw_fees.map((e: ILog) => { - const value = contract_interface.parseLog(e); - const token = value!.args.token; - const amount = Number(value!.args.amount); - return { - token: token, - amount: amount, - } as IRAW - }) - - const raw_token_earned: IRAW[] = log_token_earned.map((e: ILog) => { - const value = contract_interface.parseLog(e); - const token = value!.args.perfToken; - const amount = Number(value!.args.amount); - return { - token: token, - amount: amount, - } as IRAW - }) - - const coins = [...new Set([...raw_withdraw,...raw_token_earned].map((e: IRAW) => `${chain}:${e.token}`.toLowerCase()))] - const prices = await getPrices(coins, timestamp); - const dailyFeesUSD = [...raw_withdraw, ...raw_token_earned].map((e: IRAW) => { - const price = (prices[`${chain}:${e.token}`.toLowerCase()]?.price || 0); - const decimals = (prices[`${chain}:${e.token}`.toLowerCase()]?.decimals || 0); - return (Number(e.amount) / 10 ** decimals) * price; - }).reduce((a: number, b: number) => a+b, 0) - const dailyFees = dailyFeesUSD; - const dailyRevenue = dailyFees * .5; - const totalSupplySideRevenue = dailyFees * .5; + const fromBlock = (await getBlock(fromTimestamp, chain, {})); + const toBlock = (await getBlock(toTimestamp, chain, {})); + + const log_withdraw_fees: ILog[] = Vault_Fee_Manager_Contracts[chain] ? (await sdk.getEventLogs({ + target: Vault_Fee_Manager_Contracts[chain], + toBlock: toBlock, + fromBlock: fromBlock, + chain: chain, + topics: [topic0_fees_withdraw] + })) as ILog[] : []; + + const log_token_earned: ILog[] = Performance_Fee_Management_Contracts[chain] ? (await sdk.getEventLogs({ + target: Performance_Fee_Management_Contracts[chain], + toBlock: toBlock, + fromBlock: fromBlock, + chain: chain, + topics: [topic0_token_earned] + })) as ILog[] : []; + + const raw_withdraw: IRAW[] = log_withdraw_fees.map((e: ILog) => { + const value = contract_interface.parseLog(e); + const token = value!.args.token; + const amount = Number(value!.args.amount); return { - dailyFees: `${dailyFees}`, - dailyRevenue: `${dailyRevenue}`, - dailyHoldersRevenue: `${dailyRevenue}`, - dailySupplySideRevenue: `${totalSupplySideRevenue}`, - timestamp - } - } catch (error) { - console.log(error) - throw error; + token: token, + amount: amount, + } as IRAW + }) + + const raw_token_earned: IRAW[] = log_token_earned.map((e: ILog) => { + const value = contract_interface.parseLog(e); + const token = value!.args.perfToken; + const amount = Number(value!.args.amount); + return { + token: token, + amount: amount, + } as IRAW + }) + + const coins = [...new Set([...raw_withdraw, ...raw_token_earned].map((e: IRAW) => `${chain}:${e.token}`.toLowerCase()))] + const prices = await getPrices(coins, timestamp); + const dailyFeesUSD = [...raw_withdraw, ...raw_token_earned].map((e: IRAW) => { + const price = (prices[`${chain}:${e.token}`.toLowerCase()]?.price || 0); + const decimals = (prices[`${chain}:${e.token}`.toLowerCase()]?.decimals || 0); + return (Number(e.amount) / 10 ** decimals) * price; + }).reduce((a: number, b: number) => a + b, 0) + const dailyFees = dailyFeesUSD; + const dailyRevenue = dailyFees * .5; + const totalSupplySideRevenue = dailyFees * .5; + return { + dailyFees: `${dailyFees}`, + dailyRevenue: `${dailyRevenue}`, + dailyHoldersRevenue: `${dailyRevenue}`, + dailySupplySideRevenue: `${totalSupplySideRevenue}`, + timestamp } } } diff --git a/fees/rainbow-wallet.ts b/fees/rainbow-wallet.ts index 3f15514af9..c6d25e6d01 100644 --- a/fees/rainbow-wallet.ts +++ b/fees/rainbow-wallet.ts @@ -22,13 +22,12 @@ const fetch = (chain: Chain) => { const fromTimestamp = timestamp - 60 * 60 * 24 const toTimestamp = timestamp - try { - const startblock = (await getBlock(fromTimestamp, chain, {})); - const endblock = (await getBlock(toTimestamp, chain, {})); + const startblock = (await getBlock(fromTimestamp, chain, {})); + const endblock = (await getBlock(toTimestamp, chain, {})); - const query =` + const query = ` SELECT data, contract_address @@ -41,43 +40,40 @@ const fetch = (chain: Chain) => { `; - const logs: [string, string][] = (await queryFlipside(query, 260)) - const log = logs.map(([data, contract_address]: [string, string]) => { - const volume = Number(data) - return { - volume: volume, - contract_address: contract_address, - } as IFee - }); - const coins = [...new Set(log.map((e: IFee) => `${chain}:${e.contract_address}`.toLowerCase()))] - const coins_split = []; - for(let i = 0; i < coins.length; i+=100) { - coins_split.push(coins.slice(i, i + 100)) - } - const prices_result: any = (await Promise.all(coins_split.map((a: string[]) => getPrices(a, timestamp)))).flat().flat().flat(); - const prices: TPrice = Object.assign({}, {}); - prices_result.map((a: any) => Object.assign(prices, a)) - const amounts = log.map((p: IFee) => { - const price = prices[`${chain}:${p.contract_address}`.toLowerCase()]?.price || 0; - const decimals = prices[`${chain}:${p.contract_address}`.toLowerCase()]?.decimals || 0; - return (p.volume / 10 ** decimals) * price; - }) - const volume = amounts - .filter((e: any) => !isNaN(e)) - .filter((e: number) => e < 100_000_000) - .reduce((a: number, b: number) => a+b, 0); - const dailyFees = volume * .0085; - + const logs: [string, string][] = (await queryFlipside(query, 260)) + const log = logs.map(([data, contract_address]: [string, string]) => { + const volume = Number(data) return { - timestamp: timestamp, - dailyFees: dailyFees.toString(), - dailyRevenue: dailyFees.toString(), - dailyProtocolRevenue: dailyFees.toString(), - } as FetchResultFees + volume: volume, + contract_address: contract_address, + } as IFee + }); + const coins = [...new Set(log.map((e: IFee) => `${chain}:${e.contract_address}`.toLowerCase()))] + const coins_split = []; + for (let i = 0; i < coins.length; i += 100) { + coins_split.push(coins.slice(i, i + 100)) + } + const prices_result: any = (await Promise.all(coins_split.map((a: string[]) => getPrices(a, timestamp)))).flat().flat().flat(); + const prices: TPrice = Object.assign({}, {}); + prices_result.map((a: any) => Object.assign(prices, a)) + const amounts = log.map((p: IFee) => { + const price = prices[`${chain}:${p.contract_address}`.toLowerCase()]?.price || 0; + const decimals = prices[`${chain}:${p.contract_address}`.toLowerCase()]?.decimals || 0; + return (p.volume / 10 ** decimals) * price; + }) + const volume = amounts + .filter((e: any) => !isNaN(e)) + .filter((e: number) => e < 100_000_000) + .reduce((a: number, b: number) => a + b, 0); + const dailyFees = volume * .0085; + + return { + timestamp: timestamp, + dailyFees: dailyFees.toString(), + dailyRevenue: dailyFees.toString(), + dailyProtocolRevenue: dailyFees.toString(), + } as FetchResultFees - } catch (error) { - throw error - } } } @@ -89,36 +85,36 @@ const methodology = { const adapter: Adapter = { adapter: { [CHAIN.ETHEREUM]: { - fetch: fetch(CHAIN.ETHEREUM), - start: async () => 1672531200, - meta: { - methodology - } + fetch: fetch(CHAIN.ETHEREUM), + start: async () => 1672531200, + meta: { + methodology + } }, [CHAIN.OPTIMISM]: { fetch: fetch(CHAIN.OPTIMISM), - start: async () => 1672531200, + start: async () => 1672531200, meta: { methodology } }, [CHAIN.ARBITRUM]: { fetch: fetch(CHAIN.ARBITRUM), - start: async () => 1672531200, + start: async () => 1672531200, meta: { methodology } }, [CHAIN.POLYGON]: { fetch: fetch(CHAIN.POLYGON), - start: async () => 1672531200, + start: async () => 1672531200, meta: { methodology } }, [CHAIN.BSC]: { fetch: fetch(CHAIN.BSC), - start: async () => 1672531200, + start: async () => 1672531200, meta: { methodology } diff --git a/fees/ramses-exchange-v2/bribes.ts b/fees/ramses-exchange-v2/bribes.ts index fd5fe7a51a..56718fcb1c 100644 --- a/fees/ramses-exchange-v2/bribes.ts +++ b/fees/ramses-exchange-v2/bribes.ts @@ -17,9 +17,8 @@ interface IBribes { } export const fees_bribes = async (fromBlock: number, timestamp: number): Promise => { - try { - const endpoint = 'https://api.thegraph.com/subgraphs/name/ramsesexchange/concentrated-liquidity-graph'; - const graphQuery = gql` + const endpoint = 'https://api.thegraph.com/subgraphs/name/ramsesexchange/concentrated-liquidity-graph'; + const graphQuery = gql` query GetBribes($fromBlock: Int!) { bribes( where: { timestamp_gte: ${timestamp} } @@ -32,30 +31,26 @@ export const fees_bribes = async (fromBlock: number, timestamp: number): Promise } `; - const graphRes: { bribes: IBribes[] } = await request(endpoint, graphQuery, { - fromBlock, - }); + const graphRes: { bribes: IBribes[] } = await request(endpoint, graphQuery, { + fromBlock, + }); - const logs_bribes = graphRes.bribes; + const logs_bribes = graphRes.bribes; - const coins = [...new Set(logs_bribes.map((e: IBribes) => `${CHAIN.ARBITRUM}:${e.token.id.toLowerCase()}`))]; - const coins_split: string[][] = []; + const coins = [...new Set(logs_bribes.map((e: IBribes) => `${CHAIN.ARBITRUM}:${e.token.id.toLowerCase()}`))]; + const coins_split: string[][] = []; - for (let i = 0; i < coins.length; i += 100) { - coins_split.push(coins.slice(i, i + 100)); - } + for (let i = 0; i < coins.length; i += 100) { + coins_split.push(coins.slice(i, i + 100)); + } - const prices_result: TPrice[] = await Promise.all(coins_split.map((a: string[]) => getPrices(a, timestamp))); - const prices: TPrice = Object.assign({}, ...prices_result); + const prices_result: TPrice[] = await Promise.all(coins_split.map((a: string[]) => getPrices(a, timestamp))); + const prices: TPrice = Object.assign({}, ...prices_result); - const fees_bribes_usd = logs_bribes.map((e: IBribes) => { - const price = prices[`${CHAIN.ARBITRUM}:${e.token.id.toLowerCase()}`]?.price || 0; - const decimals = prices[`${CHAIN.ARBITRUM}:${e.token.id.toLowerCase()}`]?.decimals || 0; - return (Number(e.amount)) * price; - }).reduce((a: number, b: number) => a + b, 0); - return fees_bribes_usd; - } catch (error) { - console.error(error); - throw error; - } + const fees_bribes_usd = logs_bribes.map((e: IBribes) => { + const price = prices[`${CHAIN.ARBITRUM}:${e.token.id.toLowerCase()}`]?.price || 0; + const decimals = prices[`${CHAIN.ARBITRUM}:${e.token.id.toLowerCase()}`]?.decimals || 0; + return (Number(e.amount)) * price; + }).reduce((a: number, b: number) => a + b, 0); + return fees_bribes_usd; }; diff --git a/fees/scatter.ts b/fees/scatter.ts index 69726a0164..d60caf806d 100644 --- a/fees/scatter.ts +++ b/fees/scatter.ts @@ -46,7 +46,6 @@ const graph = (chain: Chain) => { } } catch (error) { indexa.end({ timeout: 3 }); - console.error(error); throw error; } } diff --git a/fees/sharesgram.ts b/fees/sharesgram.ts index 9c2eb4be44..548a1f8070 100644 --- a/fees/sharesgram.ts +++ b/fees/sharesgram.ts @@ -12,58 +12,53 @@ const protocol_wallet_address = '0xefb9a25a5d892bdf587103a226e6dd0369b220de'; const fetch = async (timestamp: number, chainBlocks: ChainBlocks): Promise => { const toTimestamp = timestamp; const fromTimestamp = timestamp - 60 * 60 * 24 - try { - const todaysBlock = (await getBlock(toTimestamp, CHAIN.BASE, chainBlocks)); - const yesterdaysBlock = (await getBlock(fromTimestamp, CHAIN.BASE, {})); + const todaysBlock = (await getBlock(toTimestamp, CHAIN.BASE, chainBlocks)); + const yesterdaysBlock = (await getBlock(fromTimestamp, CHAIN.BASE, {})); - const [ - holderBalanceStart, - holderBalanceEnd, - protocolBalanceStart, - protocolBalanceEnd, - ] = (await Promise.all([ - getBalance({ - target: holder_wallet_address, - block: yesterdaysBlock, - chain: CHAIN.BASE - }), - getBalance({ - target: holder_wallet_address, - block: todaysBlock, - chain: CHAIN.BASE - }), - getBalance({ - target: protocol_wallet_address, - block: yesterdaysBlock, - chain: CHAIN.BASE - }), - getBalance({ - target: protocol_wallet_address, - block: todaysBlock, - chain: CHAIN.BASE - }), - ])).map(i => i.output) - const ethBalance = (new BigNumber(holderBalanceEnd).minus(holderBalanceStart)) - .plus((new BigNumber(protocolBalanceEnd).minus(protocolBalanceStart))) - const fees: BigNumber = ethBalance.dividedBy(10**18) - const dailyFee: number = fees.dividedBy(.7).toNumber() - const ethAddress = "ethereum:0x0000000000000000000000000000000000000000"; - const pricesObj: any = await getPrices([ethAddress], toTimestamp); - const latestPrice = pricesObj[ethAddress]["price"] - const dailyFees = dailyFee * latestPrice; - const dailyRevenue = dailyFees * .7; - const dailyHolderRev = dailyFees * .5; - const dailyProtocolRevenue = dailyFees * .2; - return { - dailyFees: dailyFees.toString(), - dailyRevenue: dailyRevenue.toString(), - dailyProtocolRevenue: dailyProtocolRevenue.toString(), - dailyHoldersRevenue: dailyHolderRev.toString(), - timestamp - } - } catch (e) { - console.error(e) - throw e; + const [ + holderBalanceStart, + holderBalanceEnd, + protocolBalanceStart, + protocolBalanceEnd, + ] = (await Promise.all([ + getBalance({ + target: holder_wallet_address, + block: yesterdaysBlock, + chain: CHAIN.BASE + }), + getBalance({ + target: holder_wallet_address, + block: todaysBlock, + chain: CHAIN.BASE + }), + getBalance({ + target: protocol_wallet_address, + block: yesterdaysBlock, + chain: CHAIN.BASE + }), + getBalance({ + target: protocol_wallet_address, + block: todaysBlock, + chain: CHAIN.BASE + }), + ])).map(i => i.output) + const ethBalance = (new BigNumber(holderBalanceEnd).minus(holderBalanceStart)) + .plus((new BigNumber(protocolBalanceEnd).minus(protocolBalanceStart))) + const fees: BigNumber = ethBalance.dividedBy(10 ** 18) + const dailyFee: number = fees.dividedBy(.7).toNumber() + const ethAddress = "ethereum:0x0000000000000000000000000000000000000000"; + const pricesObj: any = await getPrices([ethAddress], toTimestamp); + const latestPrice = pricesObj[ethAddress]["price"] + const dailyFees = dailyFee * latestPrice; + const dailyRevenue = dailyFees * .7; + const dailyHolderRev = dailyFees * .5; + const dailyProtocolRevenue = dailyFees * .2; + return { + dailyFees: dailyFees.toString(), + dailyRevenue: dailyRevenue.toString(), + dailyProtocolRevenue: dailyProtocolRevenue.toString(), + dailyHoldersRevenue: dailyHolderRev.toString(), + timestamp } } diff --git a/fees/shuriken.ts b/fees/shuriken.ts index 9e0839b565..e30e2178e6 100644 --- a/fees/shuriken.ts +++ b/fees/shuriken.ts @@ -55,7 +55,6 @@ const fetch = async (timestamp: number): Promise => { } } catch (error) { await sql.end({ timeout: 3 }) - console.error(error); throw error; } diff --git a/fees/squa-defi.ts b/fees/squa-defi.ts index 7cbe60220a..9621d9997c 100644 --- a/fees/squa-defi.ts +++ b/fees/squa-defi.ts @@ -62,7 +62,6 @@ const fetch = async (timestamp: number): Promise => { timestamp } } catch (error) { - console.error(error) throw error; } diff --git a/fees/stakewise.ts b/fees/stakewise.ts index 2a0cd6b5f9..766ae2bedf 100644 --- a/fees/stakewise.ts +++ b/fees/stakewise.ts @@ -27,54 +27,49 @@ interface ILog { const fetchFees = async (timestamp: number): Promise => { const fromTimestamp = timestamp - 60 * 60 * 24 const toTimestamp = timestamp - try { - const fromBlock = (await getBlock(fromTimestamp, CHAIN.ETHEREUM, {})); - const toBlock = (await getBlock(toTimestamp, CHAIN.ETHEREUM, {})); + const fromBlock = (await getBlock(fromTimestamp, CHAIN.ETHEREUM, {})); + const toBlock = (await getBlock(toTimestamp, CHAIN.ETHEREUM, {})); - // fetch rETH2 logs - let logs: ILog[] = (await sdk.getEventLogs({ - target: reth2Address, - toBlock: toBlock, - fromBlock: fromBlock, - topics: [reth2Topic], - chain: CHAIN.ETHEREUM - })) as ILog[] - const rEth2Rewards = logs.map((log: ILog) => { - const value = reth2Interface.parseLog(log); - return Number(value!.args.periodRewards) / 10 ** 18; - }).reduce((a: number, b: number) => a + b, 0); + // fetch rETH2 logs + let logs: ILog[] = (await sdk.getEventLogs({ + target: reth2Address, + toBlock: toBlock, + fromBlock: fromBlock, + topics: [reth2Topic], + chain: CHAIN.ETHEREUM + })) as ILog[] + const rEth2Rewards = logs.map((log: ILog) => { + const value = reth2Interface.parseLog(log); + return Number(value!.args.periodRewards) / 10 ** 18; + }).reduce((a: number, b: number) => a + b, 0); - // fetch osETH logs - logs = (await sdk.getEventLogs({ - target: osTokenCtrlAddress, - toBlock: toBlock, - fromBlock: fromBlock, - topics: [osTokenCtrlTopic], - chain: CHAIN.ETHEREUM - })) as ILog[] - const osEthRewards = logs.map((log: ILog) => { - const value = osTokenCtrlInterface.parseLog(log); - return Number(value!.args.profitAccrued) / 10 ** 18; - }).reduce((a: number, b: number) => a + b, 0); + // fetch osETH logs + logs = (await sdk.getEventLogs({ + target: osTokenCtrlAddress, + toBlock: toBlock, + fromBlock: fromBlock, + topics: [osTokenCtrlTopic], + chain: CHAIN.ETHEREUM + })) as ILog[] + const osEthRewards = logs.map((log: ILog) => { + const value = osTokenCtrlInterface.parseLog(log); + return Number(value!.args.profitAccrued) / 10 ** 18; + }).reduce((a: number, b: number) => a + b, 0); - const ethPrice = (await getPrices([ethAddress], timestamp))[ethAddress].price; - let dailyFees = (osEthRewards + rEth2Rewards) * ethPrice; - const dailyRevenue = ((osEthRewards * 0.05) + (rEth2Rewards * 0.1)) * ethPrice; - const dailySupplySideRevenue = ((osEthRewards * 0.95) + (rEth2Rewards * 0.9)) * ethPrice; - return { - dailyFees: `${dailyFees}`, - dailyRevenue: `${dailyRevenue}`, - dailySupplySideRevenue: `${dailySupplySideRevenue}`, - timestamp - } - } catch (e) { - console.error(e) - throw e; + const ethPrice = (await getPrices([ethAddress], timestamp))[ethAddress].price; + let dailyFees = (osEthRewards + rEth2Rewards) * ethPrice; + const dailyRevenue = ((osEthRewards * 0.05) + (rEth2Rewards * 0.1)) * ethPrice; + const dailySupplySideRevenue = ((osEthRewards * 0.95) + (rEth2Rewards * 0.9)) * ethPrice; + return { + dailyFees: `${dailyFees}`, + dailyRevenue: `${dailyRevenue}`, + dailySupplySideRevenue: `${dailySupplySideRevenue}`, + timestamp } } -const adapter: SimpleAdapter = { +const adapter: SimpleAdapter = { adapter: { [CHAIN.ETHEREUM]: { fetch: fetchFees, diff --git a/fees/stars-arena.ts b/fees/stars-arena.ts index 1264ae1354..e33acaaac2 100644 --- a/fees/stars-arena.ts +++ b/fees/stars-arena.ts @@ -1,47 +1,21 @@ import { Adapter, DISABLED_ADAPTER_KEY, FetchResultFees } from "../adapters/types"; import { CHAIN } from "../helpers/chains"; -import { ethers } from "ethers"; import disabledAdapter from "../helpers/disabledAdapter"; -const address = '0x563395a2a04a7ae0421d34d62ae67623caf67d03'; -const topic0_trade = '0xc9d4f93ded9b42fa24561e02b2a40f720f71601eb1b3f7b3fd4eff20877639ee'; -const event_trade = 'event Trade(address trader,address subject,bool isBuy,uint256 shareAmount,uint256 amount,uint256 protocolAmount,uint256 subjectAmount,uint256 referralAmount,uint256 supply,uint256 buyPrice,uint256 myShares)' -const contract_interface = new ethers.Interface([ - event_trade -]); - -interface ILog { - data: string; - transactionHash: string; - topics: string[]; -} - -interface IFee { - fees: number; - rev: number; -} - const fetch = async (timestamp: number): Promise => { - try { - return { - dailyFees: `${0}`, - dailyRevenue: `${0}`, - timestamp - } - } catch (error) { - console.error(error) - throw error; + return { + dailyFees: `${0}`, + dailyRevenue: `${0}`, + timestamp } - } - const adapter: Adapter = { adapter: { [DISABLED_ADAPTER_KEY]: disabledAdapter, [CHAIN.AVAX]: { - fetch: fetch, - start: async () => 1695081600, + fetch: fetch, + start: async () => 1695081600, }, } } diff --git a/fees/sudoswap-v1.ts b/fees/sudoswap-v1.ts index b06ac2cd0f..b05711b676 100644 --- a/fees/sudoswap-v1.ts +++ b/fees/sudoswap-v1.ts @@ -31,7 +31,6 @@ const fetchFees = async (timestamp: number): Promise => { } } catch (e) { await sql.end({ timeout: 3 }) - console.error(e) throw e; } } diff --git a/fees/sudoswap-v2.ts b/fees/sudoswap-v2.ts index c6a5cc789d..2b3fc21cc8 100644 --- a/fees/sudoswap-v2.ts +++ b/fees/sudoswap-v2.ts @@ -64,7 +64,6 @@ const fetchFees = async (timestamp: number): Promise => { } } catch (e) { await sql.end({ timeout: 3 }) - console.error(e) throw e; } } diff --git a/fees/tangible-rwa.ts b/fees/tangible-rwa.ts index b8d9c115da..ba0933f625 100644 --- a/fees/tangible-rwa.ts +++ b/fees/tangible-rwa.ts @@ -20,29 +20,24 @@ interface ILog { const fetchFees = async (timestamp: number): Promise => { const toTimestamp = timestamp; const fromTimestamp = timestamp - 60 * 60 * 24; - try { - const fromBlock = (await getBlock(fromTimestamp, CHAIN.POLYGON, {})); - const toBlock = (await getBlock(toTimestamp, CHAIN.POLYGON, {})); - const logs: ILog[] = (await Promise.all(list_from_addres_hex.map((topic1: string) => sdk.getEventLogs({ - target: usdc, - toBlock: toBlock, - fromBlock: fromBlock, - chain: CHAIN.POLYGON, - topics: [topic0, topic1, topic2] - })))).flat(); - const dailyFees = logs.map((e: ILog) => { - const value = Number(e.data) / 10 ** 6; - return value; - }).reduce((a: number, b: number) => a + b, 0) + const fromBlock = (await getBlock(fromTimestamp, CHAIN.POLYGON, {})); + const toBlock = (await getBlock(toTimestamp, CHAIN.POLYGON, {})); + const logs: ILog[] = (await Promise.all(list_from_addres_hex.map((topic1: string) => sdk.getEventLogs({ + target: usdc, + toBlock: toBlock, + fromBlock: fromBlock, + chain: CHAIN.POLYGON, + topics: [topic0, topic1, topic2] + })))).flat(); + const dailyFees = logs.map((e: ILog) => { + const value = Number(e.data) / 10 ** 6; + return value; + }).reduce((a: number, b: number) => a + b, 0) - return { - dailyFees: `${dailyFees}`, - dailyRevenue: `${dailyFees}`, - timestamp - } - } catch (error) { - console.error(error); - throw error; + return { + dailyFees: `${dailyFees}`, + dailyRevenue: `${dailyFees}`, + timestamp } } diff --git a/fees/tigris/index.ts b/fees/tigris/index.ts index da0d043d63..cd62324728 100644 --- a/fees/tigris/index.ts +++ b/fees/tigris/index.ts @@ -46,36 +46,23 @@ function startOfDayTimestamp(timestamp: number): number { const fetch = (chain: Chain) => { return async (timestamp: number): Promise => { - try { - const dataPoints = await fetchFromAPI(chain, timestamp); + const dataPoints = await fetchFromAPI(chain, timestamp); - const adjustedTimestamp = startOfDayTimestamp(timestamp); + const adjustedTimestamp = startOfDayTimestamp(timestamp); - const matchingData = dataPoints.find(e => e.day === adjustedTimestamp); + const matchingData = dataPoints.find(e => e.day === adjustedTimestamp); - if (!matchingData) { - console.warn(`No matching data found for timestamp ${adjustedTimestamp}. Returning zero values.`); - return { - dailyFees: '0', - dailyRevenue: '0', - dailyProtocolRevenue: '0', - dailyHoldersRevenue: '0', - timestamp: adjustedTimestamp, - totalFees: '0' - }; - } + if (!matchingData) + throw new Error(`No matching data found for timestamp ${adjustedTimestamp}. Returning zero values.`); + - return { - dailyFees: matchingData.dailyFees.toString(), - dailyRevenue: matchingData.dailyRevenue.toString(), - dailyProtocolRevenue: matchingData.dailyProtocolRevenue.toString(), - dailyHoldersRevenue: matchingData.dailyHoldersRevenue.toString(), - timestamp: matchingData.day, - totalFees: matchingData.totalFees.toString() - } - } catch (e) { - console.error(e); - throw e; + return { + dailyFees: matchingData.dailyFees.toString(), + dailyRevenue: matchingData.dailyRevenue.toString(), + dailyProtocolRevenue: matchingData.dailyProtocolRevenue.toString(), + dailyHoldersRevenue: matchingData.dailyHoldersRevenue.toString(), + timestamp: matchingData.day, + totalFees: matchingData.totalFees.toString() } } } diff --git a/fees/touch.fan.ts b/fees/touch.fan.ts index 0569ef1510..37f0113f78 100644 --- a/fees/touch.fan.ts +++ b/fees/touch.fan.ts @@ -98,7 +98,6 @@ const fetch = async (timestamp: number): Promise => { timestamp } } catch (error) { - console.error(error) throw error; } diff --git a/fees/unibot.ts b/fees/unibot.ts index 57a5751afb..faaf676897 100644 --- a/fees/unibot.ts +++ b/fees/unibot.ts @@ -110,7 +110,6 @@ const fetch = async (timestamp: number): Promise => { } } catch (error) { await sql.end({ timeout: 3 }) - console.error(error); throw error; } diff --git a/fees/uniswap-lab.ts b/fees/uniswap-lab.ts index d9633f2cca..8b9e7445a5 100644 --- a/fees/uniswap-lab.ts +++ b/fees/uniswap-lab.ts @@ -9,12 +9,11 @@ interface tokenInfo { token: string; amount: number; } -const fetchFees = (chain: Chain) => { +const fetchFees = (chain: Chain) => { return async (timestamp: number): Promise => { - try { - const now = new Date(timestamp * 1e3) - const dayAgo = new Date(now.getTime() - 1000 * 60 * 60 * 24) - const query =` + const now = new Date(timestamp * 1e3) + const dayAgo = new Date(now.getTime() - 1000 * 60 * 60 * 24) + const query = ` SELECT data, contract_address, @@ -67,37 +66,33 @@ const fetchFees = (chain: Chain) => { and topics[2] = '0x000000000000000000000000d4ce1f1b8640c1988360a6729d9a73c85a0c80a3' AND BLOCK_TIMESTAMP BETWEEN '${dayAgo.toISOString()}' AND '${now.toISOString()}' ` - const token_tranfer = await queryFlipside(query, 260) + const token_tranfer = await queryFlipside(query, 260) - const token_info: tokenInfo[] = token_tranfer.filter((e: any) => e[2] === chain).map((item: any) => { - const token = item[1]; - const amount = Number(item[0]); - return { - token, - amount - } - }) - const coins = [...new Set(token_info.map((item: any) => `${chain}:${item.token}`))]; - const prices = await getPrices(coins, timestamp); - const fees = token_info.reduce((acc: number, item: any) => { - const price = prices[`${chain}:${item.token}`]?.price || 0; - const decimals = prices[`${chain}:${item.token}`]?.decimals || 0; - if (price === 0 || decimals === 0) return acc; - const fee = (Number(item.amount) / 10 ** decimals) * price; - return acc + fee; - }, 0) - const dailyFees = fees; - const dailyRevenue = dailyFees; - const dailyProtocolRevenue = dailyFees; - return { - dailyFees: `${dailyFees}`, - dailyProtocolRevenue: `${dailyProtocolRevenue}`, - dailyRevenue: `${dailyRevenue}`, - timestamp + const token_info: tokenInfo[] = token_tranfer.filter((e: any) => e[2] === chain).map((item: any) => { + const token = item[1]; + const amount = Number(item[0]); + return { + token, + amount } - } catch (e) { - console.error(e) - throw e + }) + const coins = [...new Set(token_info.map((item: any) => `${chain}:${item.token}`))]; + const prices = await getPrices(coins, timestamp); + const fees = token_info.reduce((acc: number, item: any) => { + const price = prices[`${chain}:${item.token}`]?.price || 0; + const decimals = prices[`${chain}:${item.token}`]?.decimals || 0; + if (price === 0 || decimals === 0) return acc; + const fee = (Number(item.amount) / 10 ** decimals) * price; + return acc + fee; + }, 0) + const dailyFees = fees; + const dailyRevenue = dailyFees; + const dailyProtocolRevenue = dailyFees; + return { + dailyFees: `${dailyFees}`, + dailyProtocolRevenue: `${dailyProtocolRevenue}`, + dailyRevenue: `${dailyRevenue}`, + timestamp } } } diff --git a/fees/usdo.ts b/fees/usdo.ts index 2c24fd1caa..80d2e2eff4 100644 --- a/fees/usdo.ts +++ b/fees/usdo.ts @@ -27,7 +27,7 @@ const pools: string[] = [ ] const topic0_increase_value = '0x8ba9e55d654c01fafe9a9dadb284af89fae3126f7b9b50355639672bd22bdbe5'; -const event_increase_value = 'event IncreaseValue(address indexed from, uint256 usdValue)'; +const event_increase_value = 'event IncreaseValue(address indexed from, uint256 usdValue)'; const topic0_swap = '0xd78ad95fa46c994b6551d0da85fc275fe613ce37657fb8d5e3d130840159d822'; const topic0_withdraw = '0xdf273cb619d95419a9cd0ec88123a0538c85064229baa6363788f743fff90deb'; @@ -39,95 +39,90 @@ const fetch = async (timestamp: number): Promise => { const fromTimestamp = timestamp - 60 * 60 * 24 const toTimestamp = timestamp - try { - const fromBlock = (await getBlock(fromTimestamp, CHAIN.ONUS, {})); - const toBlock = (await getBlock(toTimestamp, CHAIN.ONUS, {})); - const logs_increase_value = (await sdk.getEventLogs({ - target: usdo, - toBlock: toBlock, - fromBlock: fromBlock, - chain: CHAIN.ONUS, - topics: [topic0_increase_value] - })).map(((e: any) => contract_interface.parseLog(e))); - - const logs_tx: string[] = (await sdk.getEventLogs({ - target: usdo, - toBlock: toBlock, - fromBlock: fromBlock, - chain: CHAIN.ONUS, - topics: [topic0_withdraw] - })).map((e: any) => e.transactionHash.toLowerCase()); - - const logs: ILog[][] = (await Promise.all(pools.map((address: string) => sdk.getEventLogs({ - target: address, - toBlock: toBlock, - fromBlock: fromBlock, - chain: CHAIN.ONUS, - topics: [topic0_swap] - })))) as any; - - const [underlyingToken0, underlyingToken1] = await Promise.all( - ['address:token0', 'address:token1'].map((method) => - sdk.api2.abi.multiCall({ - abi: method, - calls: pools.map((address: string) => ({ - target: address, - })), - chain: CHAIN.ONUS - }) - ) - ); - - const tokens0 = underlyingToken0; - const tokens1 = underlyingToken1; - const rawCoins = [...tokens0, ...tokens1].map((e: string) => `${CHAIN.ONUS}:${e}`); - const coins = [...new Set(rawCoins)] - const prices = await getPrices(coins, timestamp); - - const untrackVolumes: number[] = pools.map((_: string, index: number) => { - const token0Decimals = (prices[`${CHAIN.ONUS}:${tokens0[index]}`]?.decimals || 0) - const token1Decimals = (prices[`${CHAIN.ONUS}:${tokens1[index]}`]?.decimals || 0) - const log: IAmount[] = logs[index] - .filter((e: ILog) => logs_tx.includes(e.transactionHash.toLowerCase())) - .map((e: ILog) => { return { ...e, data: e.data.replace('0x', '') } }) - .map((p: ILog) => { - const amount0In = Number('0x' + p.data.slice(0, 64)) / 10 ** token0Decimals; - const amount1In = Number('0x' + p.data.slice(64, 128)) / 10 ** token1Decimals; - const amount0Out = Number('0x' + p.data.slice(128, 192)) / 10 ** token0Decimals; - const amount1Out = Number('0x' + p.data.slice(192, 256)) / 10 ** token1Decimals; - return { - amount0In, - amount1In, - amount0Out, - amount1Out, - } as IAmount - }) as IAmount[]; - const token0Price = (prices[`${CHAIN.ONUS}:${tokens0[index]}`]?.price || 0); - const token1Price = (prices[`${CHAIN.ONUS}:${tokens1[index]}`]?.price || 0); - - const totalAmount0 = log - .reduce((a: number, b: IAmount) => Number(b.amount0In) + Number(b.amount0Out) + a, 0) * token0Price; - const totalAmount1 = log - .reduce((a: number, b: IAmount) => Number(b.amount1In) + Number(b.amount1Out) + a, 0) * token1Price; - - const untrackAmountUSD = token0Price !== 0 ? totalAmount0 : token1Price !== 0 ? totalAmount1 : 0; // counted only we have price data - return untrackAmountUSD; - }); - - const increase_value_fees = logs_increase_value.map((e: any) => { - return Number(e!.args.usdValue) / 10 ** 18 - }).reduce((a: number, b: number) => a + b, 0) - const swapFees = untrackVolumes.reduce((a: number, b: number) => a + b, 0); - - const dailyFee = increase_value_fees + swapFees; - return { - dailyFees: `${dailyFee}`, - dailyRevenue: `${dailyFee}`, - timestamp - } - } catch (error) { - console.log(error); - throw error; + const fromBlock = (await getBlock(fromTimestamp, CHAIN.ONUS, {})); + const toBlock = (await getBlock(toTimestamp, CHAIN.ONUS, {})); + const logs_increase_value = (await sdk.getEventLogs({ + target: usdo, + toBlock: toBlock, + fromBlock: fromBlock, + chain: CHAIN.ONUS, + topics: [topic0_increase_value] + })).map(((e: any) => contract_interface.parseLog(e))); + + const logs_tx: string[] = (await sdk.getEventLogs({ + target: usdo, + toBlock: toBlock, + fromBlock: fromBlock, + chain: CHAIN.ONUS, + topics: [topic0_withdraw] + })).map((e: any) => e.transactionHash.toLowerCase()); + + const logs: ILog[][] = (await Promise.all(pools.map((address: string) => sdk.getEventLogs({ + target: address, + toBlock: toBlock, + fromBlock: fromBlock, + chain: CHAIN.ONUS, + topics: [topic0_swap] + })))) as any; + + const [underlyingToken0, underlyingToken1] = await Promise.all( + ['address:token0', 'address:token1'].map((method) => + sdk.api2.abi.multiCall({ + abi: method, + calls: pools.map((address: string) => ({ + target: address, + })), + chain: CHAIN.ONUS + }) + ) + ); + + const tokens0 = underlyingToken0; + const tokens1 = underlyingToken1; + const rawCoins = [...tokens0, ...tokens1].map((e: string) => `${CHAIN.ONUS}:${e}`); + const coins = [...new Set(rawCoins)] + const prices = await getPrices(coins, timestamp); + + const untrackVolumes: number[] = pools.map((_: string, index: number) => { + const token0Decimals = (prices[`${CHAIN.ONUS}:${tokens0[index]}`]?.decimals || 0) + const token1Decimals = (prices[`${CHAIN.ONUS}:${tokens1[index]}`]?.decimals || 0) + const log: IAmount[] = logs[index] + .filter((e: ILog) => logs_tx.includes(e.transactionHash.toLowerCase())) + .map((e: ILog) => { return { ...e, data: e.data.replace('0x', '') } }) + .map((p: ILog) => { + const amount0In = Number('0x' + p.data.slice(0, 64)) / 10 ** token0Decimals; + const amount1In = Number('0x' + p.data.slice(64, 128)) / 10 ** token1Decimals; + const amount0Out = Number('0x' + p.data.slice(128, 192)) / 10 ** token0Decimals; + const amount1Out = Number('0x' + p.data.slice(192, 256)) / 10 ** token1Decimals; + return { + amount0In, + amount1In, + amount0Out, + amount1Out, + } as IAmount + }) as IAmount[]; + const token0Price = (prices[`${CHAIN.ONUS}:${tokens0[index]}`]?.price || 0); + const token1Price = (prices[`${CHAIN.ONUS}:${tokens1[index]}`]?.price || 0); + + const totalAmount0 = log + .reduce((a: number, b: IAmount) => Number(b.amount0In) + Number(b.amount0Out) + a, 0) * token0Price; + const totalAmount1 = log + .reduce((a: number, b: IAmount) => Number(b.amount1In) + Number(b.amount1Out) + a, 0) * token1Price; + + const untrackAmountUSD = token0Price !== 0 ? totalAmount0 : token1Price !== 0 ? totalAmount1 : 0; // counted only we have price data + return untrackAmountUSD; + }); + + const increase_value_fees = logs_increase_value.map((e: any) => { + return Number(e!.args.usdValue) / 10 ** 18 + }).reduce((a: number, b: number) => a + b, 0) + const swapFees = untrackVolumes.reduce((a: number, b: number) => a + b, 0); + + const dailyFee = increase_value_fees + swapFees; + return { + dailyFees: `${dailyFee}`, + dailyRevenue: `${dailyFee}`, + timestamp } } diff --git a/fees/velodrome-v2/bribes.ts b/fees/velodrome-v2/bribes.ts index 8ef3e24e8b..b0bbf8019b 100644 --- a/fees/velodrome-v2/bribes.ts +++ b/fees/velodrome-v2/bribes.ts @@ -5,34 +5,29 @@ const event_notify_reward = 'event NotifyReward(address indexed from,address ind const event_geuge_created = 'event GaugeCreated(address indexed poolFactory,address indexed votingRewardsFactory,address indexed gaugeFactory,address pool,address bribeVotingReward,address feeVotingReward,address gauge,address creator)' export const fees_bribes = async (fromBlock: number, toBlock: number, _: number): Promise => { - try { - const api = new sdk.ChainApi({ chain: CHAIN.OPTIMISM }); - const voter = '0x41c914ee0c7e1a5edcd0295623e6dc557b5abf3c'; - const logs_geuge_created= (await api.getLogs({ - target: voter, - fromBlock: 105896851, - toBlock: toBlock, - chain: CHAIN.OPTIMISM, - onlyArgs: true, - eventAbi: event_geuge_created, - })) - const bribes_contract: string[] = logs_geuge_created.map((e: any) => e.bribeVotingReward.toLowerCase()); + const api = new sdk.ChainApi({ chain: CHAIN.OPTIMISM }); + const voter = '0x41c914ee0c7e1a5edcd0295623e6dc557b5abf3c'; + const logs_geuge_created = (await api.getLogs({ + target: voter, + fromBlock: 105896851, + toBlock: toBlock, + chain: CHAIN.OPTIMISM, + onlyArgs: true, + eventAbi: event_geuge_created, + })) + const bribes_contract: string[] = logs_geuge_created.map((e: any) => e.bribeVotingReward.toLowerCase()); - const logs =await api.getLogs({ - targets: bribes_contract, - toBlock: toBlock, - fromBlock: fromBlock, - chain: CHAIN.OPTIMISM, - onlyArgs: true, - eventAbi: event_notify_reward, - }) + const logs = await api.getLogs({ + targets: bribes_contract, + toBlock: toBlock, + fromBlock: fromBlock, + chain: CHAIN.OPTIMISM, + onlyArgs: true, + eventAbi: event_notify_reward, + }) - logs.forEach((e: any) => { - api.add(e.reward, e.amount) - }) - return api.getUSDValue(); - } catch (error) { - console.error(error); - throw error; - } + logs.forEach((e: any) => { + api.add(e.reward, e.amount) + }) + return api.getUSDValue(); } diff --git a/fees/zapper-channels.ts b/fees/zapper-channels.ts index 5522f261bc..b6d48dca89 100644 --- a/fees/zapper-channels.ts +++ b/fees/zapper-channels.ts @@ -30,42 +30,37 @@ const fetch = async (timestamp: number): Promise => { const fromBlock = (await getBlock(fromTimestamp, CHAIN.BASE, {})); const toBlock = (await getBlock(toTimestamp, CHAIN.BASE, {})); - try { - let _logs: ILog[] = []; - for(let i = fromBlock; i < toBlock; i += 5000) { - const logs: ILog[] = (await sdk.getEventLogs({ - target: FriendtechSharesAddress, - toBlock: i + 5000, - fromBlock: i, - chain: CHAIN.BASE, - topics: [topic0_trade] - })) as ILog[]; - _logs = _logs.concat(logs); - } + let _logs: ILog[] = []; + for (let i = fromBlock; i < toBlock; i += 5000) { + const logs: ILog[] = (await sdk.getEventLogs({ + target: FriendtechSharesAddress, + toBlock: i + 5000, + fromBlock: i, + chain: CHAIN.BASE, + topics: [topic0_trade] + })) as ILog[]; + _logs = _logs.concat(logs); + } - const fees_details: IFee[] = _logs.map((e: ILog) => { - const value = contract_interface.parseLog(e); - const protocolEthAmount = Number(value!.args.protocolEthAmount) / 10 ** 18; - const subjectEthAmount = Number(value!.args.channelEthAmount) / 10 ** 18; - return { - fees: protocolEthAmount + subjectEthAmount, - rev: protocolEthAmount - } as IFee - }) - const dailyFees = fees_details.reduce((a: number, b: IFee) => a+b.fees, 0) - const dailyRev = fees_details.reduce((a: number, b: IFee) => a+b.rev, 0) - const ethAddress = "ethereum:0x0000000000000000000000000000000000000000"; - const ethPrice = (await getPrices([ethAddress], timestamp))[ethAddress].price; - const dailyFeesUSD = (dailyFees) * ethPrice; - const dailyRevUSD = (dailyRev) * ethPrice; + const fees_details: IFee[] = _logs.map((e: ILog) => { + const value = contract_interface.parseLog(e); + const protocolEthAmount = Number(value!.args.protocolEthAmount) / 10 ** 18; + const subjectEthAmount = Number(value!.args.channelEthAmount) / 10 ** 18; return { - dailyFees: `${dailyFeesUSD}`, - dailyRevenue: `${dailyRevUSD}`, - timestamp - } - } catch (error) { - console.error(error) - throw error; + fees: protocolEthAmount + subjectEthAmount, + rev: protocolEthAmount + } as IFee + }) + const dailyFees = fees_details.reduce((a: number, b: IFee) => a + b.fees, 0) + const dailyRev = fees_details.reduce((a: number, b: IFee) => a + b.rev, 0) + const ethAddress = "ethereum:0x0000000000000000000000000000000000000000"; + const ethPrice = (await getPrices([ethAddress], timestamp))[ethAddress].price; + const dailyFeesUSD = (dailyFees) * ethPrice; + const dailyRevUSD = (dailyRev) * ethPrice; + return { + dailyFees: `${dailyFeesUSD}`, + dailyRevenue: `${dailyRevUSD}`, + timestamp } } @@ -74,8 +69,8 @@ const fetch = async (timestamp: number): Promise => { const adapter: Adapter = { adapter: { [CHAIN.BASE]: { - fetch: fetch, - start: async () => 1696204800, + fetch: fetch, + start: async () => 1696204800, }, } } diff --git a/fees/zerion-wallet.ts b/fees/zerion-wallet.ts index 653c6eea08..a708a922e4 100644 --- a/fees/zerion-wallet.ts +++ b/fees/zerion-wallet.ts @@ -58,7 +58,7 @@ const build_query_rev = (timestamp: number) => { `).join(" union all "); } -const toHexTopic = (multisigs: string[]) => multisigs +const toHexTopic = (multisigs: string[]) => multisigs .map((multisig: string) => multisig.replace('0x', '')) .map((multisig: string) => multisig.padStart(64, '0')) .map((multisig: string) => `0x${multisig}`); @@ -82,84 +82,80 @@ const build_query = (timestamp: number) => { const fetch = (chain: Chain, gasToken: string) => { return async (timestamp: number): Promise => { - try { - let revenues : IFee[] = []; - - const query = build_query_rev(timestamp) - - const ethRevenues: any[] = (await queryFlipside(query, 260)) - .map(([eth_revenue, chain]: [string, string]) => { - return { - eth_revenue, - chain - } - }).filter((e: any) => e.chain === chain); - - const ethRevenue = ethRevenues.map((e: any) => { - const revenue = Number(e.eth_value) - return { - volume: revenue, - contract_address: gasToken, - } as IFee - }); - - revenues = revenues.concat(ethRevenue) - - const queryTokens = build_query(timestamp) - const tokenRevenues: any[] = (await queryFlipside(queryTokens, 360)) - .map(([data, contract_address, chain]: [string, string, string]) => { - return { - data, - contract_address, - chain - } - }).filter((e: any) => e.chain === chain); - - const tokenRevenue = tokenRevenues.map((e: any) => { - const volume = Number(e.data) - return { - volume: volume, - contract_address: e.contract_address, - } as IFee - }); - - revenues = revenues.concat(tokenRevenue) - - const coins = [...new Set( - revenues.map((e: IFee) => `${chain}:${e.contract_address}`.toLowerCase()) - )]; - - const coins_split = []; - for(let i = 0; i < coins.length; i+=100) { - coins_split.push(coins.slice(i, i + 100)) - } + let revenues: IFee[] = []; - const prices_result: any = (await Promise.all(coins_split.map((a: string[]) => getPrices(a, timestamp)))).flat().flat().flat(); - const prices: TPrice = Object.assign({}, {}); + const query = build_query_rev(timestamp) - prices_result.map((a: any) => Object.assign(prices, a)) + const ethRevenues: any[] = (await queryFlipside(query, 260)) + .map(([eth_revenue, chain]: [string, string]) => { + return { + eth_revenue, + chain + } + }).filter((e: any) => e.chain === chain); - const amounts = revenues.map((p: IFee) => { - const price = prices[`${chain}:${p.contract_address}`.toLowerCase()]?.price || 0; - const decimals = prices[`${chain}:${p.contract_address}`.toLowerCase()]?.decimals || 0; - return (p.volume / 10 ** decimals) * price; - }) + const ethRevenue = ethRevenues.map((e: any) => { + const revenue = Number(e.eth_value) + return { + volume: revenue, + contract_address: gasToken, + } as IFee + }); - const volume = amounts - .filter((e: any) => !isNaN(e)) - .filter((e: number) => e < 100_000_000) - .reduce((a: number, b: number) => a+b, 0); - const dailyFees = volume; + revenues = revenues.concat(ethRevenue) + const queryTokens = build_query(timestamp) + const tokenRevenues: any[] = (await queryFlipside(queryTokens, 360)) + .map(([data, contract_address, chain]: [string, string, string]) => { return { - timestamp: timestamp, - dailyFees: dailyFees.toString(), - dailyRevenue: dailyFees.toString(), - dailyProtocolRevenue: dailyFees.toString(), - } as FetchResultFees - } catch (error) { - throw error - } + data, + contract_address, + chain + } + }).filter((e: any) => e.chain === chain); + + const tokenRevenue = tokenRevenues.map((e: any) => { + const volume = Number(e.data) + return { + volume: volume, + contract_address: e.contract_address, + } as IFee + }); + + revenues = revenues.concat(tokenRevenue) + + const coins = [...new Set( + revenues.map((e: IFee) => `${chain}:${e.contract_address}`.toLowerCase()) + )]; + + const coins_split = []; + for (let i = 0; i < coins.length; i += 100) { + coins_split.push(coins.slice(i, i + 100)) + } + + const prices_result: any = (await Promise.all(coins_split.map((a: string[]) => getPrices(a, timestamp)))).flat().flat().flat(); + const prices: TPrice = Object.assign({}, {}); + + prices_result.map((a: any) => Object.assign(prices, a)) + + const amounts = revenues.map((p: IFee) => { + const price = prices[`${chain}:${p.contract_address}`.toLowerCase()]?.price || 0; + const decimals = prices[`${chain}:${p.contract_address}`.toLowerCase()]?.decimals || 0; + return (p.volume / 10 ** decimals) * price; + }) + + const volume = amounts + .filter((e: any) => !isNaN(e)) + .filter((e: number) => e < 100_000_000) + .reduce((a: number, b: number) => a + b, 0); + const dailyFees = volume; + + return { + timestamp: timestamp, + dailyFees: dailyFees.toString(), + dailyRevenue: dailyFees.toString(), + dailyProtocolRevenue: dailyFees.toString(), + } as FetchResultFees } } @@ -171,49 +167,49 @@ const methodology = { const adapter: Adapter = { adapter: { [CHAIN.ETHEREUM]: { - fetch: fetch(CHAIN.ETHEREUM, + fetch: fetch(CHAIN.ETHEREUM, "0x0000000000000000000000000000000000000000"), - start: async () => 1672531200, - meta: { - methodology - } + start: 1672531200, + meta: { + methodology + } }, [CHAIN.OPTIMISM]: { fetch: fetch(CHAIN.OPTIMISM, - "0x0000000000000000000000000000000000000000"), - start: async () => 1672531200, + "0x0000000000000000000000000000000000000000"), + start: 1672531200, meta: { methodology } }, [CHAIN.ARBITRUM]: { fetch: fetch(CHAIN.ARBITRUM, - "0x0000000000000000000000000000000000000000"), - start: async () => 1672531200, + "0x0000000000000000000000000000000000000000"), + start: 1672531200, meta: { methodology } }, [CHAIN.BASE]: { fetch: fetch(CHAIN.BASE, - "0x0000000000000000000000000000000000000000"), - start: async () => 1672531200, + "0x0000000000000000000000000000000000000000"), + start: 1672531200, meta: { methodology } }, [CHAIN.POLYGON]: { fetch: fetch(CHAIN.POLYGON, - "0x7d1afa7b718fb893db30a3abc0cfc608aacfebb0"), - start: async () => 1672531200, + "0x7d1afa7b718fb893db30a3abc0cfc608aacfebb0"), + start: 1672531200, meta: { methodology } }, [CHAIN.BSC]: { fetch: fetch(CHAIN.BSC, - "0xb8c77482e45f1f44de1745f52c74426c631bdd52"), - start: async () => 1672531200, + "0xb8c77482e45f1f44de1745f52c74426c631bdd52"), + start: 1672531200, meta: { methodology } diff --git a/helpers/dexVolumeLogs.ts b/helpers/dexVolumeLogs.ts index f05373ed09..6e283d95ff 100644 --- a/helpers/dexVolumeLogs.ts +++ b/helpers/dexVolumeLogs.ts @@ -11,45 +11,40 @@ type getDexVolumeExportsParams = { chain: string, factory?: string, pools?: stri type getDexVolumeExportsParamsV3 = { chain: string, factory?: string, pools?: string[], factoryFromBlock?: number, } export async function getDexVolume({ chain, fromTimestamp, toTimestamp, factory, timestamp, pools }: getDexVolumeParams) { - try { - if (!toTimestamp) toTimestamp = timestamp - const api = new sdk.ChainApi({ chain, timestamp: toTimestamp }); - const fromBlock = (await sdk.blocks.getBlock(chain, fromTimestamp)).block; - const toBlock = (await sdk.blocks.getBlock(chain, toTimestamp)).block; - // await api.getBlock(); - if (!pools) pools = await api.fetchList({ lengthAbi: 'allPairsLength', itemAbi: 'allPairs', target: factory! }) + if (!toTimestamp) toTimestamp = timestamp + const api = new sdk.ChainApi({ chain, timestamp: toTimestamp }); + const fromBlock = (await sdk.blocks.getBlock(chain, fromTimestamp)).block; + const toBlock = (await sdk.blocks.getBlock(chain, toTimestamp)).block; + // await api.getBlock(); + if (!pools) pools = await api.fetchList({ lengthAbi: 'allPairsLength', itemAbi: 'allPairs', target: factory! }) - const token0s = await api.multiCall({ abi: 'address:token0', calls: pools! }) - const token1s = await api.multiCall({ abi: 'address:token1', calls: pools! }) + const token0s = await api.multiCall({ abi: 'address:token0', calls: pools! }) + const token1s = await api.multiCall({ abi: 'address:token1', calls: pools! }) - const logs = await sdk.getEventLogs({ - targets: pools, - toBlock: toBlock, - fromBlock: fromBlock, - chain, - eventAbi: swapEvent, - flatten: false, - onlyArgs: true, - }); - logs.forEach((log: any[], index: number) => { - const token0 = token0s[index] - const token1 = token1s[index] - if (!log.length) return - log.forEach((i: any) => { - // api.add(token0, i.amount0In) // we should count only one side of the swap - api.add(token0, i.amount0Out) - // api.add(token1, i.amount1In) - api.add(token1, i.amount1Out) - }) + const logs = await sdk.getEventLogs({ + targets: pools, + toBlock: toBlock, + fromBlock: fromBlock, + chain, + eventAbi: swapEvent, + flatten: false, + onlyArgs: true, + }); + logs.forEach((log: any[], index: number) => { + const token0 = token0s[index] + const token1 = token1s[index] + if (!log.length) return + log.forEach((i: any) => { + // api.add(token0, i.amount0In) // we should count only one side of the swap + api.add(token0, i.amount0Out) + // api.add(token1, i.amount1In) + api.add(token1, i.amount1Out) }) - const { usdTvl } = await api.getUSDJSONs() - return { - timestamp, - dailyVolume: Number(usdTvl).toFixed(0), - } - } catch (e) { - console.error(e) - throw e + }) + const { usdTvl } = await api.getUSDJSONs() + return { + timestamp, + dailyVolume: Number(usdTvl).toFixed(0), } } @@ -66,48 +61,43 @@ type getDexFeesExportParams = { chain: string, factory?: string, pools?: string[ const feesEvent = "event Fees(address indexed sender, uint256 amount0, uint256 amount1)" // const feesTopic = '0x112c256902bf554b6ed882d2936687aaeb4225e8cd5b51303c90ca6cf43a8602' export async function getDexFees({ chain, fromTimestamp, toTimestamp, factory, timestamp, pools, lengthAbi = 'allPairsLength', itemAbi = 'allPairs', fromBlock, toBlock, }: getDexFeesParams) { - try { - if (!toTimestamp) toTimestamp = timestamp - const api = new sdk.ChainApi({ chain, timestamp: toTimestamp }); - if (!fromBlock) - fromBlock = (await sdk.blocks.getBlock(chain, fromTimestamp)).block; - if (!toBlock) - toBlock = (await sdk.blocks.getBlock(chain, toTimestamp)).block; - // await api.getBlock(); - if (!pools) pools = await api.fetchList({ lengthAbi, itemAbi, target: factory! }) - - const token0s = await api.multiCall({ abi: 'address:token0', calls: pools! }) - const token1s = await api.multiCall({ abi: 'address:token1', calls: pools! }) + if (!toTimestamp) toTimestamp = timestamp + const api = new sdk.ChainApi({ chain, timestamp: toTimestamp }); + if (!fromBlock) + fromBlock = (await sdk.blocks.getBlock(chain, fromTimestamp)).block; + if (!toBlock) + toBlock = (await sdk.blocks.getBlock(chain, toTimestamp)).block; + // await api.getBlock(); + if (!pools) pools = await api.fetchList({ lengthAbi, itemAbi, target: factory! }) - const logs = await sdk.getEventLogs({ - targets: pools, - toBlock: toBlock, - fromBlock: fromBlock, - chain, - eventAbi: feesEvent, - flatten: false, - onlyArgs: true, - }); - logs.forEach((log: any[], index: number) => { - const token0 = token0s[index] - const token1 = token1s[index] - if (!log.length) return - log.forEach((i: any) => { - api.add(token0, i.amount0) - api.add(token1, i.amount1) - }) + const token0s = await api.multiCall({ abi: 'address:token0', calls: pools! }) + const token1s = await api.multiCall({ abi: 'address:token1', calls: pools! }) + + const logs = await sdk.getEventLogs({ + targets: pools, + toBlock: toBlock, + fromBlock: fromBlock, + chain, + eventAbi: feesEvent, + flatten: false, + onlyArgs: true, + }); + logs.forEach((log: any[], index: number) => { + const token0 = token0s[index] + const token1 = token1s[index] + if (!log.length) return + log.forEach((i: any) => { + api.add(token0, i.amount0) + api.add(token1, i.amount1) }) - const { usdTvl } = await api.getUSDJSONs() - const value = Number(usdTvl).toFixed(0) - return { - timestamp, - dailyFees: value, - dailyRevenue: value, - dailyHoldersRevenue: value, - } - } catch (e) { - console.error(e) - throw e + }) + const { usdTvl } = await api.getUSDJSONs() + const value = Number(usdTvl).toFixed(0) + return { + timestamp, + dailyFees: value, + dailyRevenue: value, + dailyHoldersRevenue: value, } } @@ -141,7 +131,7 @@ export async function getDexVolumeFeeV3({ chain, fromTimestamp, toTimestamp, fac // const token0s = await api.multiCall({ abi: 'address:token0', calls: pools! }) let fees = [] as any - if (isFee) + if (isFee) fees = await api.multiCall({ abi: 'function fee() view returns (uint24)', calls: pools! }) const token1s = await api.multiCall({ abi: 'address:token1', calls: pools! }) diff --git a/helpers/getBlock.ts b/helpers/getBlock.ts index 25b070a63d..b87ef821e6 100644 --- a/helpers/getBlock.ts +++ b/helpers/getBlock.ts @@ -6,7 +6,7 @@ import * as sdk from "@defillama/sdk" import { httpGet } from "../utils/fetchURL"; const retry = require("async-retry") -async function getBlock(timestamp: number, chain: Chain, chainBlocks: ChainBlocks) { +async function getBlock(timestamp: number, chain: Chain, chainBlocks = {} as ChainBlocks) { if (chainBlocks[chain] !== undefined) return chainBlocks[chain] diff --git a/options/tigris/index.ts b/options/tigris/index.ts index d3a935d401..d790765028 100644 --- a/options/tigris/index.ts +++ b/options/tigris/index.ts @@ -39,35 +39,22 @@ function startOfDayTimestamp(timestamp: number): number { const fetch = (chain: Chain) => { return async (timestamp: number) => { - try { - const dataPoints = await fetchFromAPI(chain, timestamp); + const dataPoints = await fetchFromAPI(chain, timestamp); - const adjustedTimestamp = startOfDayTimestamp(timestamp); + const adjustedTimestamp = startOfDayTimestamp(timestamp); - const matchingData = dataPoints.find(e => e.day === adjustedTimestamp); + const matchingData = dataPoints.find(e => e.day === adjustedTimestamp); - if (!matchingData) { - console.warn(`No matching data found for timestamp ${adjustedTimestamp}. Returning zero values.`); - return { - dailyNotionalVolume: '0', - totalNotionalVolume: '0', - dailyPremiumVolume: '0', - totalPremuimVolume: '0', - timestamp: adjustedTimestamp - }; - } + if (!matchingData) + throw new Error(`No matching data found for timestamp ${adjustedTimestamp}. Returning zero values.`); - return { - dailyPremiumVolume: '0', - totalPremuimVolume: '0', - dailyNotionalVolume: matchingData.dailyNotionalVolume.toString(), - totalNotionalVolume: matchingData.totalNotionalVolume.toString(), - timestamp: matchingData.day - }; - } catch (e) { - console.error(e); - throw e; - } + return { + dailyPremiumVolume: '0', + totalPremuimVolume: '0', + dailyNotionalVolume: matchingData.dailyNotionalVolume.toString(), + totalNotionalVolume: matchingData.totalNotionalVolume.toString(), + timestamp: matchingData.day + }; } } diff --git a/package-lock.json b/package-lock.json index 02ad7509d7..e6e7713564 100644 --- a/package-lock.json +++ b/package-lock.json @@ -802,9 +802,9 @@ } }, "node_modules/@defillama/sdk": { - "version": "5.0.24", - "resolved": "https://registry.npmjs.org/@defillama/sdk/-/sdk-5.0.24.tgz", - "integrity": "sha512-s+Uug2oKbNk2P/7BQ08lKPcOzsJORLF3w2f70oI8HmYHWQdQih7SoyyqiwzxkpxLBF7NZO9hP3pJs6gUL3r16g==", + "version": "5.0.26", + "resolved": "https://registry.npmjs.org/@defillama/sdk/-/sdk-5.0.26.tgz", + "integrity": "sha512-zttsd9q17OYJxHMBobMbi/QiUBUaCNWdUWTtwzF72JZNS7hJv/54T/7nT6CtAtrwqyBa/gg1Xf8d2t7puIfNNw==", "dependencies": { "@aws-sdk/client-s3": "^3.400.0", "@supercharge/promise-pool": "^2.1.0", diff --git a/utils/fetchURL.ts b/utils/fetchURL.ts index f0d8d9e707..f10165f4f4 100644 --- a/utils/fetchURL.ts +++ b/utils/fetchURL.ts @@ -22,13 +22,11 @@ export async function postURL(url: string, data: any, retries = 3) { function formAxiosError(url: string, error: any, options?: any) { let e = new Error((error as any)?.message) - try { - const axiosError = (error as any)?.response?.data?.message || (error as any)?.response?.data?.error || (error as any)?.response?.statusText || (error as any)?.response?.data; - (e as any).url = url; - Object.keys(options || {}).forEach((key) => (e as any)[key] = options[key]); - if (axiosError) (e as any).axiosError = axiosError; - delete (e as any).stack - } catch { } + const axiosError = (error as any)?.response?.data?.message || (error as any)?.response?.data?.error || (error as any)?.response?.statusText || (error as any)?.response?.data; + (e as any).url = url; + Object.keys(options || {}).forEach((key) => (e as any)[key] = options[key]); + if (axiosError) (e as any).axiosError = axiosError; + delete (e as any).stack return e }