Skip to content

Commit

Permalink
Update dependencies and fix code formatting
Browse files Browse the repository at this point in the history
  • Loading branch information
g1nt0ki committed Feb 5, 2024
1 parent 789dcd8 commit 403b2aa
Show file tree
Hide file tree
Showing 9 changed files with 152 additions and 412 deletions.
6 changes: 4 additions & 2 deletions adapters/types.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Balances, util } from '@defillama/sdk';
import { Balances, ChainApi, util } from '@defillama/sdk';

const { blocks: { getChainBlocks } } = util

Expand Down Expand Up @@ -26,10 +26,12 @@ export type FetchOptions = {
getFromBlock: () => Promise<number>;
getToBlock: () => Promise<number>;
chain: string,
api: ChainApi,
}

export type FetchGetLogsOptions = {
eventAbi: string,
eventAbi?: string,
topic?: string,
target?: string,
targets?: string[],
onlyArgs?: boolean,
Expand Down
12 changes: 7 additions & 5 deletions adapters/utils/runAdapter.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Balances, getEventLogs } from '@defillama/sdk'
import { Balances, ChainApi, getEventLogs } from '@defillama/sdk'
import { BaseAdapter, ChainBlocks, DISABLED_ADAPTER_KEY, FetchGetLogsOptions, FetchResultGeneric, } from '../types'
import { getBlock } from "../../helpers/getBlock";

Expand Down Expand Up @@ -44,20 +44,21 @@ export default async function runAdapter(volumeAdapter: BaseAdapter, cleanCurren
}

function getOptionsObject(timestamp: number, chain: string, chainBlocks: ChainBlocks) {
const closeToCurrentTime = Math.trunc(Date.now() / 1000) - timestamp < 12 * 60 * 60 // 12 hours
const withinTwoHours = Math.trunc(Date.now() / 1000) - timestamp < 2 * 60 * 60 // 2 hours
const createBalances: () => Balances = () => {
const closeToCurrentTime = Math.trunc(Date.now() / 1000) - timestamp < 12 * 60 * 60 // 12 hours
return new Balances({ timestamp: closeToCurrentTime ? timestamp : undefined, chain })
return new Balances({ timestamp: closeToCurrentTime ? undefined : timestamp, 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) => {
const getLogs = async ({ target, targets, onlyArgs = true, fromBlock, toBlock, flatten = true, eventAbi, topics, topic, }: FetchGetLogsOptions) => {
fromBlock = fromBlock ?? await getFromBlock()
toBlock = toBlock ?? await getToBlock()

return getEventLogs({ fromBlock, toBlock, chain, target, targets, onlyArgs, flatten, eventAbi, topics, })
return getEventLogs({ fromBlock, toBlock, chain, target, targets, onlyArgs, flatten, eventAbi, topics, topic, })
}

return {
Expand All @@ -69,6 +70,7 @@ export default async function runAdapter(volumeAdapter: BaseAdapter, cleanCurren
getToBlock,
getLogs,
chain,
api: new ChainApi({ chain, timestamp: withinTwoHours ? undefined : timestamp, }),
}
}

Expand Down
4 changes: 2 additions & 2 deletions cli/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,8 +35,8 @@ export function printVolumes(volumes: any[], baseAdapter?: BaseAdapter) {
else if (!methodology) console.log("NO METHODOLOGY SPECIFIED")
Object.entries(element).forEach(([attribute, value]) => {
if (!exclude2Print.includes(attribute)) {
const valueFormatted = typeof value === 'object' ? JSON.stringify(value, null, 2) : attribute==="timestamp"?value: humanizeNumber(Number(value))
console.info(`${camelCaseToSpaces(attribute)}: ${valueFormatted}`)
const valueFormatted = typeof value === 'object' ? JSON.stringify(value, null, 2) : attribute === "timestamp" ? value + ` (${new Date((value as any) * 1e3).toISOString()})` : humanizeNumber(Number(value))
console.info(`${camelCaseToSpaces(attribute)}: ${valueFormatted}`)
if (valueFormatted !== undefined && typeof methodology === 'object' && methodology[attribute.slice(5)])
console.log("└─ Methodology:", methodology?.[attribute.slice(5)])
}
Expand Down
81 changes: 19 additions & 62 deletions dexs/aerodrome/index.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,7 @@
import { FetchResultFees, FetchResultVolume, SimpleAdapter } from "../../adapters/types"
import { FetchOptions, FetchResultVolume, SimpleAdapter } from "../../adapters/types"
import { CHAIN } from "../../helpers/chains"
import * as sdk from "@defillama/sdk";
import { getBlock } from "../../helpers/getBlock";
import { ethers } from "ethers";
import { getPrices } from "../../utils/prices";

const gurar = '0x2073D8035bB2b0F2e85aAF5a8732C6f397F9ff9b';
type TPrice = {
[s: string]: {
price: number;
decimals: number
};
}
const abis: any = {
"forSwaps": "function forSwaps() view returns ((address lp, bool stable, address token0, address token1, address factory)[])"
}
Expand All @@ -28,17 +18,11 @@ interface ILog {
transactionHash: string;
topics: string[];
}
const topic0_swap = '0xb3e2773606abfd36b5bd91394b3a54d1398336c65005baf7bf7a05efeffaf75b'
const event_swap = 'event Swap(address indexed sender,address indexed to,uint256 amount0In,uint256 amount1In,uint256 amount0Out,uint256 amount1Out)'

const contract_interface = new ethers.Interface([
event_swap
])

const fetch = async (timestamp: number): Promise<FetchResultVolume> => {
const fromTimestamp = timestamp - 60 * 60 * 24
const toTimestamp = timestamp
const forSwaps: IForSwap[] = (await sdk.api2.abi.call({
const fetch = async (timestamp: number, _: any, { api, getLogs, createBalances, }: FetchOptions): Promise<FetchResultVolume> => {
const dailyVolume = createBalances()
const forSwaps: IForSwap[] = (await api.call({
target: gurar,
abi: abis.forSwaps,
chain: CHAIN.BASE,
Expand All @@ -50,55 +34,28 @@ const fetch = async (timestamp: number): Promise<FetchResultVolume> => {
}
})

const fromBlock = (await getBlock(fromTimestamp, CHAIN.BASE, {}));
const toBlock = (await getBlock(toTimestamp, CHAIN.BASE, {}));

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 targets = forSwaps.map((forSwap: IForSwap) => forSwap.lp)

const coins = [...new Set([
...forSwaps.map((log: IForSwap) => `${CHAIN.BASE}:${log.token0}`),
...forSwaps.map((log: IForSwap) => `${CHAIN.BASE}:${log.token1}`)
])]
const logs: ILog[][] = await getLogs({
targets,
eventAbi: event_swap,
flatten: false,
})

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)
logs.forEach((logs: ILog[], idx: number) => {
const { token0, token1 } = forSwaps[idx]
logs.forEach((log: any) => {
dailyVolume.add(token0, log.amount0Out)
dailyVolume.add(token1, log.amount1Out)
})
})

return {
dailyVolume: `${volumeUSD}`,
timestamp
}
return { dailyVolume, timestamp }
}
const adapters: SimpleAdapter = {
adapter: {
[CHAIN.BASE]: {
fetch: fetch,
fetch: fetch as any,
start: 1693180800,
}
}
Expand Down
93 changes: 15 additions & 78 deletions dexs/airswap/index.ts
Original file line number Diff line number Diff line change
@@ -1,27 +1,7 @@
import { FetchResultVolume, SimpleAdapter } from "../../adapters/types";
import { Fetch, FetchOptions, FetchResultVolume, SimpleAdapter } 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";

interface ITx {
data: string;
transactionHash: string;
topics: string[];
}
interface IData {
signerAmount: number;
signerToken: string;
}

const event_swap = 'event SwapERC20(uint256 indexed nonce,address indexed signerWallet,address signerToken,uint256 signerAmount,uint256 protocolFee,address indexed senderWallet,address senderToken,uint256 senderAmount)';
const topic0 = '0xb651f2787ff61b5ab14f3936f2daebdad3d84aeb74438e82870cc3b7aee71e90';

const contract_interface = new ethers.Interface([
event_swap
]);

type TAddress = {
[c: string]: string;
Expand All @@ -34,67 +14,24 @@ const address: TAddress = {
[CHAIN.ARBITRUM]: '0xd82FA167727a4dc6D6F55830A2c47aBbB4b3a0F8'
}

const graph = (chain: Chain) => {
return async (timestamp: number): Promise<FetchResultVolume> => {
const fromTimestamp = timestamp - 60 * 60 * 24
const toTimestamp = timestamp
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 dailyVolume = untrackVolumes.reduce((a: number, b: number) => a + b, 0);
return {
dailyVolume: `${dailyVolume}`,
timestamp,
};
}
}
const fetch = (async (timestamp: number, _: any, { getLogs, createBalances, chain }: FetchOptions): Promise<FetchResultVolume> => {
const dailyVolume = createBalances();

const logs = (await getLogs({
target: address[chain],
eventAbi: event_swap,
}))
logs.forEach(i => dailyVolume.add(i.signerToken, i.signerAmount))
return { dailyVolume, timestamp, };
}) as Fetch

const adapter: SimpleAdapter = {
adapter: {
[CHAIN.ETHEREUM]: {
fetch: graph(CHAIN.ETHEREUM),
start: 1680307200,
},
[CHAIN.POLYGON]: {
fetch: graph(CHAIN.POLYGON),
start: 1680307200,
},
[CHAIN.AVAX]: {
fetch: graph(CHAIN.AVAX),
start: 1680307200,
},
[CHAIN.BSC]: {
fetch: graph(CHAIN.BSC),
start: 1680307200,
},
[CHAIN.ARBITRUM]: {
fetch: graph(CHAIN.ARBITRUM),
start: 1689811200,
},
[CHAIN.ETHEREUM]: { fetch, start: 1680307200, },
[CHAIN.POLYGON]: { fetch, start: 1680307200, },
[CHAIN.AVAX]: { fetch, start: 1680307200, },
[CHAIN.BSC]: { fetch, start: 1680307200, },
[CHAIN.ARBITRUM]: { fetch, start: 1689811200, },
}
};

Expand Down
Loading

0 comments on commit 403b2aa

Please sign in to comment.