Skip to content

Commit

Permalink
Add fetchTokenList parameter to addTokensReceived function
Browse files Browse the repository at this point in the history
  • Loading branch information
g1nt0ki committed Feb 11, 2024
1 parent dc9ac09 commit 7ea0f09
Show file tree
Hide file tree
Showing 14 changed files with 157 additions and 687 deletions.
129 changes: 37 additions & 92 deletions dexs/synfutures-v2/index.ts
Original file line number Diff line number Diff line change
@@ -1,48 +1,30 @@
import ADDRESSES from '../../helpers/coreAssets.json'
import { Chain } from "@defillama/sdk/build/general";
import { getUniqStartOfTodayTimestamp } from "../../helpers/getUniSubgraphVolume";
import { getBlock } from "../../helpers/getBlock";
import { CHAIN } from "../../helpers/chains";
import * as sdk from "@defillama/sdk";
import { SimpleAdapter } from "../../adapters/types";
import { get } from "http";
import { getPrices } from "../../utils/prices";
import { ChainBlocks, FetchOptions, SimpleAdapter } from "../../adapters/types";

type TContracts = {
[key in Chain]: string[][];
};
const contracts: TContracts = {
[CHAIN.POLYGON]: [
['0x89cf9a71d45c58673a7f8b4c829df466da7a473a',ADDRESSES.polygon.WETH_1],
['0xa40986ccd9dc00c533ba71c9362529c9694f9f7b',ADDRESSES.polygon.USDC],
['0xf479405a2518b02a79c060f3d91fe0c98cfe6e25',ADDRESSES.polygon.USDC],
['0x64b8b618cddc31c61305338c6ab7a2d85a7ab5ca',ADDRESSES.polygon.USDC],
['0x19759660e5ee693df6105fc3629d5d91cb0a9447',ADDRESSES.polygon.WMATIC_2],
['0xbda26f37656218b2b3983800bc5734998445cc92',ADDRESSES.polygon.USDC],
['0x4b6e851015581e88824f1efd71cb65dd9826189b',ADDRESSES.polygon.USDC],
['0x4baa9f1af8653a875d51324ca563d12d7925adf5',ADDRESSES.polygon.USDC],
['0x8c7822f283137e1e73ea0bdc537ccfb2fa1fb030',ADDRESSES.polygon.USDC],
['0x13f7f23db676431a2371d0f1884ae1526a0fe5c2',ADDRESSES.polygon.WMATIC_2],
['0xb09d2ec9afff13589ddfab190e2d1aba7e02095b',ADDRESSES.polygon.WMATIC_2],
['0x6909bfbe79f9c33589c637eed166a32afea76ef6',ADDRESSES.polygon.USDC],
['0xf51dcd52bd075c91632aac42c3926b2a523b3da5',ADDRESSES.polygon.WMATIC_2],
['0x9ceeb2a6f17d3c7bd086471095fcf80cfe780149',ADDRESSES.polygon.WETH_1],
['0x89cf9a71d45c58673a7f8b4c829df466da7a473a', ADDRESSES.polygon.WETH_1],
['0xa40986ccd9dc00c533ba71c9362529c9694f9f7b', ADDRESSES.polygon.USDC],
['0xf479405a2518b02a79c060f3d91fe0c98cfe6e25', ADDRESSES.polygon.USDC],
['0x64b8b618cddc31c61305338c6ab7a2d85a7ab5ca', ADDRESSES.polygon.USDC],
['0x19759660e5ee693df6105fc3629d5d91cb0a9447', ADDRESSES.polygon.WMATIC_2],
['0xbda26f37656218b2b3983800bc5734998445cc92', ADDRESSES.polygon.USDC],
['0x4b6e851015581e88824f1efd71cb65dd9826189b', ADDRESSES.polygon.USDC],
['0x4baa9f1af8653a875d51324ca563d12d7925adf5', ADDRESSES.polygon.USDC],
['0x8c7822f283137e1e73ea0bdc537ccfb2fa1fb030', ADDRESSES.polygon.USDC],
['0x13f7f23db676431a2371d0f1884ae1526a0fe5c2', ADDRESSES.polygon.WMATIC_2],
['0xb09d2ec9afff13589ddfab190e2d1aba7e02095b', ADDRESSES.polygon.WMATIC_2],
['0x6909bfbe79f9c33589c637eed166a32afea76ef6', ADDRESSES.polygon.USDC],
['0xf51dcd52bd075c91632aac42c3926b2a523b3da5', ADDRESSES.polygon.WMATIC_2],
['0x9ceeb2a6f17d3c7bd086471095fcf80cfe780149', ADDRESSES.polygon.WETH_1],
]
}


interface ILogs {
address: string;
blockHash: string;
blockNumber: string;
data: string;
logIndex: string;
removed: boolean;
topics: string[];
transactionHash: string;
transactionIndex: string;
}

function twosComplementHexToDecimal(hexValue: string): number {
// Check if the hex value starts with '0xf'
if (!hexValue.startsWith('0xf')) {
Expand All @@ -66,69 +48,32 @@ function twosComplementHexToDecimal(hexValue: string): number {
}

const topic0_trade = '0xeef2964c19d154a021c80f1901318bed137c1214368f991d6a118e9c64c5d9f6';
interface IVolume {
contract: string;
amount_quote: number;
quoteAddr: string;
}

const fetchVolume = (chain: Chain) => {
return async (timestamp: number) => {
const now = new Date().getTime() / 1000;
const fromTimestamp = getUniqStartOfTodayTimestamp(new Date(timestamp * 1000));
const toTimestamp = timestamp > now ? now : timestamp;
return async (timestamp: number, _: ChainBlocks, { createBalances, getLogs, api }: FetchOptions) => {
const dailyVolume = createBalances()
const tokens = contracts[chain].map(i => i[1]);
const decimals = await api.multiCall({ abi: 'erc20:decimals', calls: tokens})

const toBlock = await getBlock(toTimestamp, chain, {});
const fromBlock = await getBlock(fromTimestamp, chain, {});

const logs: ILogs[] = (await Promise.all(contracts[chain].map(contract => sdk.getEventLogs({
target: contract[0],
const logs = await getLogs({
targets: contracts[chain].map(i => i[0]),
topics: [topic0_trade],
toBlock,
fromBlock,
chain: chain,
})))).flat();

const volumeRaw: IVolume[] = logs.map((log:ILogs) => {
const data = log.data.replace('0x', '');
const price = Number('0x'+data.slice(0, 64)) / 10 ** 18;
const amount = twosComplementHexToDecimal('0x'+data.slice(64, 128)) / 10 ** 18;
const quoteAddr = contracts[chain].find((x: string[]) => x[0].toLowerCase() === log.address.toLowerCase())?.[1];
return {
contract: log.address,
amount_quote: amount * price,
quoteAddr: quoteAddr || ''
}
});

const coins = [...new Set(volumeRaw.map(e => `${chain}:${e.quoteAddr.toLowerCase()}`))];
const prices = await getPrices(coins, fromTimestamp);


// getPrices API currently has a bug that it doesn't return price for polygon:0x2791bca1f2de4661ed88a30c99a7a9449aa84174 (USDC) for some reason
// so we set it as 1 manually to temporarily fix this issue
if (!prices['polygon:' + ADDRESSES.polygon.USDC]) {
prices['polygon:' + ADDRESSES.polygon.USDC] = {
symbol: 'USDC',
timestamp: now,
price: 1,
decimals: 18
}
}

// check prices
coins.forEach(coin => {
if (!prices[coin]) {
throw new Error(`No price found for ${coin}`);
}
});

const volume = volumeRaw.map((e: IVolume) => e.amount_quote * prices[`${chain}:${e.quoteAddr.toLowerCase()}`]?.price || 0);
const dailyVolume = volume.reduce((acc: number, cur: number) => acc + cur, 0);
return {
dailyVolume: `${dailyVolume}`,
timestamp
}
flatten: false,
skipCacheRead: true,
})
logs.forEach((_logs, index) => {
const token = tokens[index]
const powDivider = 18 - +decimals[index]

_logs.forEach((log) => {
const data = log.data.replace('0x', '');
const price = Number('0x' + data.slice(0, 64)) / 10 ** 18;
const amount = twosComplementHexToDecimal('0x' + data.slice(64, 128)) / (10 ** powDivider)
dailyVolume.add(token, amount * price);
})
})

return { dailyVolume, timestamp }
}
}

Expand Down
72 changes: 17 additions & 55 deletions dexs/zkSwap_Finance/zkswapFinance.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { getUniqStartOfTodayTimestamp } from "../../helpers/getUniSubgraphVolume";
import { CHAIN } from "../../helpers/chains";
import { getPrices } from "../../utils/prices";
const { request, gql } = require("graphql-request");
import { ChainBlocks, FetchOptions } from "../../adapters/types";
const { request, } = require("graphql-request");

const info: { [key: string]: any } = {
[CHAIN.ERA]: {
Expand All @@ -11,44 +11,13 @@ const info: { [key: string]: any } = {
},
};

const getData = async (chain: string, timestamp: number) => {
const startDayTimestamp = getUniqStartOfTodayTimestamp(
new Date(timestamp * 1000)
);
const getData = async ({ chain, startOfDay, createBalances}: FetchOptions) => {
const dailyVolume = createBalances()

let dayMiliseconds = 24 * 60 * 60;
let returnCount = 1000;
let daySum = 0;
let totalSum = 0;
let step = 0;

const graphQLTotalVolume = `{
pairs(first: 1000) {
volumeToken0
token0 {
id
}
volumeUSD
}
}`;

const data = await request(info[chain].subgraph_v1, graphQLTotalVolume);

let token0rray = [] as string[];
for (const pair of data.pairs) {
token0rray.push(chain + ":" + pair.token0.id);
}
let unique = [...new Set(token0rray)] as string[];
const prices = await getPrices(unique, startDayTimestamp);

for (const pair of data.pairs) {
const token0Id = chain + ":" + pair.token0.id;
let price0 = prices[token0Id] === undefined ? 0 : prices[token0Id].price;

totalSum += Number(pair.volumeToken0) * price0;
}

let lasTimestampQuery = startDayTimestamp;
let lasTimestampQuery = startOfDay;

while (returnCount == 1000) {
const graphQL = `{
Expand All @@ -57,7 +26,7 @@ const getData = async (chain: string, timestamp: number) => {
orderDirection: asc
first: 1000
where: {timestamp_gte: ${lasTimestampQuery}, timestamp_lt: ${
startDayTimestamp + dayMiliseconds
startOfDay + dayMiliseconds
} }
) {
amount0In
Expand All @@ -66,6 +35,7 @@ const getData = async (chain: string, timestamp: number) => {
pair {
token0 {
id
decimals
}
}
}
Expand All @@ -77,18 +47,16 @@ const getData = async (chain: string, timestamp: number) => {
lasTimestampQuery = data?.swaps[returnCount - 1]?.timestamp;

for (const swap of data.swaps) {
const token0Id = chain + ":" + swap.pair.token0.id;
let price0 = prices[token0Id] === undefined ? 0 : prices[token0Id].price;

daySum += Number(swap.amount0In) * price0;
daySum += Number(swap.amount0Out) * price0;
const token0Id = swap.pair.token0.id;
const multiplier = Math.pow(10, swap.pair.token0.decimals);
dailyVolume.add(token0Id, Number(swap.amount0In) * multiplier);
dailyVolume.add(token0Id, Number(swap.amount0Out) * multiplier);
}
}

return {
totalVolume: `${totalSum}`,
dailyVolume: `${daySum}`,
timestamp: startDayTimestamp,
dailyVolume,
timestamp: startOfDay,
};
};

Expand Down Expand Up @@ -134,15 +102,9 @@ const getToDateVolume = async (chain: string, timestamp: number) => {
return volumSum;
};

export const fetchVolume = (chain: string) => {
return async (timestamp: number) => {
const data = await getData(chain, timestamp);
const totalVolume = await getToDateVolume(chain, timestamp);

return {
totalVolume: totalVolume.toString(),
dailyVolume: data.dailyVolume,
timestamp: data.timestamp,
};
export const fetchVolume = (_chain: string) => {
return async (_timestamp: number, _: ChainBlocks, options: FetchOptions) => {
return getData(options);
// const totalVolume = await getToDateVolume(options);
};
};
64 changes: 3 additions & 61 deletions fees/friend-room.ts
Original file line number Diff line number Diff line change
@@ -1,72 +1,14 @@
import ADDRESSES from '../helpers/coreAssets.json'
import { Adapter, FetchResultFees, SimpleAdapter } from "../adapters/types";
import { Adapter, } 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 { Chain } from "@defillama/sdk/build/general";
import { ethers } from "ethers";
import { getFeesExport } from '../helpers/friend-tech';

const friendRoomSharesAddress = '0x9BD0474CC4F118efe56f9f781AA8f0F03D4e7A9c';
const topic0_trade = '0x68e42cc58cdc03b82d6c135e12e98660f43a75ce1ccfb1a625965e253f50d7b0';
const event_trade = 'event Trade(uint256 index, uint256 serverId, address trader, uint256 tokenId, bool isBuy, uint256 shareAmount, uint256 ethAmount, uint256 protocolEthAmount, uint256 subjectEthAmount, uint256 supply)'
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<FetchResultFees> => {
const fromTimestamp = timestamp - 60 * 60 * 24
const toTimestamp = timestamp

const fromBlock = (await getBlock(fromTimestamp, CHAIN.ETHEREUM, {}));
const toBlock = (await getBlock(toTimestamp, CHAIN.ETHEREUM, {}));
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:" + ADDRESSES.null;
const ethPrice = (await getPrices([ethAddress], timestamp))[ethAddress].price;
const dailyFeesUSD = (dailyFees) * ethPrice;
const dailyRevUSD = (dailyRev) * ethPrice;
return {
dailyFees: `${dailyFeesUSD}`,
dailyRevenue: `${dailyRevUSD}`,
timestamp
}

}


const adapter: Adapter = {
adapter: {
[CHAIN.ETHEREUM]: {
fetch: fetch,
fetch: getFeesExport(friendRoomSharesAddress, [event_trade]),
start: 1693731179,
},
}
Expand Down
Loading

0 comments on commit 7ea0f09

Please sign in to comment.