Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
966 changes: 163 additions & 803 deletions package-lock.json

Large diffs are not rendered by default.

25 changes: 8 additions & 17 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@cryptoalgebra/hx-finance-alm-sdk",
"version": "1.0.0",
"name": "@hx_finance_npm/hx-finance-alm-sdk",
"version": "1.0.1",
"description": "Algebra ALM SDK",
"main": "dist/src/index.cjs.js",
"module": "dist/src/index.esm.js",
Expand All @@ -17,7 +17,7 @@
"coverage": "jest --runInBand",
"dev": "rollup -c -w",
"format": "prettier --write \"src/**/*.ts\"",
"generate": "rm-cli -r ./abis && typechain --target=ethers-v5 \"src/abis/**/*.json\" --out-dir \"abis/types\"",
"generate": "rm-cli -r ./abis && typechain --target=ethers-v6 \"src/abis/**/*.json\" --out-dir \"abis/types\"",
"lint:ts": "eslint --ext .js,.ts --ignore-path .gitignore . --fix",
"lint": "npm run lint:ts",
"prebuild": "rm-cli -r ./dist",
Expand All @@ -34,21 +34,11 @@
"author": "skdamn",
"license": "MIT",
"dependencies": {
"@ethersproject/abi": "^5.7.0",
"@ethersproject/abstract-signer": "^5.6.2",
"@ethersproject/address": "^5.6.0",
"@ethersproject/bignumber": "^5.6.0",
"@ethersproject/bytes": "^5.6.1",
"@ethersproject/constants": "^5.6.0",
"@ethersproject/contracts": "^5.6.2",
"@ethersproject/providers": "^5.6.5",
"@ethersproject/units": "^5.6.1",
"@ethersproject/wallet": "^5.6.2",
"@thanpolas/univ3prices": "^3.0.2",
"@typechain/ethers-v5": "^10.0.0",
"@typechain/ethers-v6": "^0.5.0",
"bignumber.js": "^9.0.1",
"ethereumjs-util": "^7.1.4",
"ethers": "^5.6.8",
"ethers": "^6.15.0",
"global": "^4.4.0",
"graphql": "^16.6.0",
"graphql-request": "^6.0.0",
Expand All @@ -61,7 +51,7 @@
"@babel/preset-env": "^7.17.10",
"@jest/globals": "^29.5.0",
"@rollup/plugin-babel": "^5.3.1",
"@rollup/plugin-commonjs": "^22.0.0",
"@rollup/plugin-commonjs": "^22.0.2",
"@rollup/plugin-json": "^4.1.0",
"@rollup/plugin-node-resolve": "^13.3.0",
"@rollup/plugin-typescript": "^8.3.2",
Expand All @@ -80,6 +70,7 @@
"prettier": "^2.8.7",
"rm-cli": "^1.4.2",
"rollup": "^2.72.1",
"rollup-plugin-node-polyfills": "^0.2.1",
"rollup-plugin-terser": "^7.0.2",
"ts-jest": "^29.1.0",
"tslib": "^2.4.0",
Expand All @@ -88,4 +79,4 @@
"typescript": "^4.7.3",
"web3-provider-engine": "^16.0.5"
}
}
}
19 changes: 19 additions & 0 deletions rollup.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,9 @@

import typescript from '@rollup/plugin-typescript';
import json from '@rollup/plugin-json';
import commonjs from '@rollup/plugin-commonjs';
import resolve from '@rollup/plugin-node-resolve';
import nodePolyfills from 'rollup-plugin-node-polyfills';
import pkg from './package.json';

const moduleName = pkg.name.replace(/^@.*\//, '');
Expand All @@ -28,9 +31,25 @@ export default {
file: pkg.module,
format: 'es',
banner,
inlineDynamicImports: true,
},
],
external: [
'ethers',
'graphql-request',
'bignumber.js',
'node-cache',
'@algebra/sdk',
],
plugins: [
resolve({
browser: true,
preferBuiltins: false,
}),
commonjs({
transformMixedEsModules: true,
}),
nodePolyfills(),
typescript({
exclude: ['tests/*.spec.ts'],
}),
Expand Down
3 changes: 1 addition & 2 deletions src/contracts/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
/* eslint-disable camelcase */
import { getAddress } from '@ethersproject/address';
import { JsonRpcProvider } from '@ethersproject/providers';
import { getAddress, JsonRpcProvider } from 'ethers';
import { SignerOrProvider } from '../types';
import {
ERC20__factory as ERC20Factory,
Expand Down
7 changes: 3 additions & 4 deletions src/functions/_totalBalances.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,7 @@
/* eslint-disable import/prefer-default-export */
/* eslint-disable no-underscore-dangle */

import { JsonRpcProvider } from '@ethersproject/providers';
import { BigNumber } from 'ethers';
import { JsonRpcProvider } from 'ethers';
import { getERC20Contract, getAlgebraVaultContract } from '../contracts';
import { AlgebraVault, SupportedChainId, TotalAmounts, TotalAmountsBN, algebraVaultDecimals } from '../types';
import formatBigInt from '../utils/formatBigInt';
Expand All @@ -25,7 +24,7 @@ export async function getTokenDecimals(
const tokenContract = getERC20Contract(tokenAddress, jsonProvider);
const tokenDecimals = await tokenContract.decimals();
cache.set(key, tokenDecimals, ttl);
return tokenDecimals;
return Number(tokenDecimals);
} catch (error) {
console.error(error);
throw new Error(`Could not get token decimals for ${tokenAddress} on ${chainId}`);
Expand Down Expand Up @@ -77,7 +76,7 @@ export async function _getTotalSupply(
vaultAddress: string,
jsonProvider: JsonRpcProvider,
raw: true,
): Promise<BigNumber>;
): Promise<bigint>;

export async function _getTotalSupply(vaultAddress: string, jsonProvider: JsonRpcProvider, raw?: true) {
try {
Expand Down
5 changes: 2 additions & 3 deletions src/functions/calculateApr.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import { JsonRpcProvider } from '@ethersproject/providers';
import { BigNumber } from 'ethers';
import { JsonRpcProvider } from 'ethers';
import { AlgebraVault, PriceChange, TotalAmountsBN, VaultApr, VaultState, algebraVaultDecimals } from '../types';
// eslint-disable-next-line import/no-cycle
import { validateVaultData } from './vault';
Expand Down Expand Up @@ -30,7 +29,7 @@ export function getLpPriceAt(
const { totalAmount0, totalAmount1, sqrtPrice } = e;
const formattedTotalAmount0 = formatBigInt(totalAmount0, token0decimals);
const formattedTotalAmount1 = formatBigInt(totalAmount1, token1decimals);
const price = getPrice(isVaultInverted, BigNumber.from(sqrtPrice), depositTokenDecimals, scarceTokenDecimals, 15);
const price = getPrice(isVaultInverted, BigInt(sqrtPrice), depositTokenDecimals, scarceTokenDecimals, 15);
const tvl = !isVaultInverted
? Number(formattedTotalAmount0) + Number(formattedTotalAmount1) * price
: Number(formattedTotalAmount1) + Number(formattedTotalAmount0) * price;
Expand Down
29 changes: 14 additions & 15 deletions src/functions/calculateDtr.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
/* eslint-disable no-redeclare */
/* eslint-disable import/prefer-default-export */

import { JsonRpcProvider } from '@ethersproject/providers';
import { BigNumber } from '@ethersproject/bignumber';
import { parseUnits } from '@ethersproject/units';
import { JsonRpcProvider } from 'ethers';
import { parseUnits } from 'ethers';
import { AverageDepositTokenRatio, DepositTokenRatio, VaultState, VaultTransactionEvent } from '../types';
// eslint-disable-next-line import/no-cycle
import { validateVaultData } from './vault';
Expand All @@ -18,23 +17,23 @@ import { _getDeposits, _getFeesCollectedEvents, _getRebalances, _getWithdraws }
import truncateToDecimals from '../utils/truncateToDecimals';

export function getAmountsInDepositToken(
sqrtPrice: BigNumber,
amount0: BigNumber,
amount1: BigNumber,
sqrtPrice: bigint,
amount0: bigint,
amount1: bigint,
token0Decimals: number,
token1Decimals: number,
depositToken: 0 | 1,
): BigNumber {
): bigint {
const isVaultInverted = depositToken === 1;

const depositTokenDecimals = isVaultInverted ? token1Decimals : token0Decimals;
const scarceTokenDecimals = isVaultInverted ? token0Decimals : token1Decimals;
const price0 = !isVaultInverted
? 1
: getPrice(isVaultInverted, BigNumber.from(sqrtPrice), depositTokenDecimals, scarceTokenDecimals, 15);
: getPrice(isVaultInverted, BigInt(sqrtPrice), depositTokenDecimals, scarceTokenDecimals, 15);
const price1 = isVaultInverted
? 1
: getPrice(isVaultInverted, BigNumber.from(sqrtPrice), depositTokenDecimals, scarceTokenDecimals, 15);
: getPrice(isVaultInverted, BigInt(sqrtPrice), depositTokenDecimals, scarceTokenDecimals, 15);

const amountInDepositToken =
Number(formatBigInt(amount0, token0Decimals)) * price0 + Number(formatBigInt(amount1, token1Decimals)) * price1;
Expand All @@ -59,7 +58,7 @@ function getTotalAmountsAtTransactionEvent(
? 1
: getPrice(
isVaultInverted,
BigNumber.from(objTransactionEvent.sqrtPrice),
BigInt(objTransactionEvent.sqrtPrice),
depositTokenDecimals,
scarceTokenDecimals,
15,
Expand All @@ -68,17 +67,17 @@ function getTotalAmountsAtTransactionEvent(
? 1
: getPrice(
isVaultInverted,
BigNumber.from(objTransactionEvent.sqrtPrice),
BigInt(objTransactionEvent.sqrtPrice),
depositTokenDecimals,
scarceTokenDecimals,
15,
);
const amount0 = beforeEvent
? Number(formatBigInt(BigNumber.from(objTransactionEvent.totalAmount0BeforeEvent), token0Decimals)) * price0
: Number(formatBigInt(BigNumber.from(objTransactionEvent.totalAmount0), token0Decimals)) * price0;
? Number(formatBigInt(BigInt(objTransactionEvent.totalAmount0BeforeEvent), token0Decimals)) * price0
: Number(formatBigInt(BigInt(objTransactionEvent.totalAmount0), token0Decimals)) * price0;
const amount1 = beforeEvent
? Number(formatBigInt(BigNumber.from(objTransactionEvent.totalAmount1BeforeEvent), token1Decimals)) * price1
: Number(formatBigInt(BigNumber.from(objTransactionEvent.totalAmount1), token1Decimals)) * price1;
? Number(formatBigInt(BigInt(objTransactionEvent.totalAmount1BeforeEvent), token1Decimals)) * price1
: Number(formatBigInt(BigInt(objTransactionEvent.totalAmount1), token1Decimals)) * price1;
return [amount0, amount1];
}

Expand Down
35 changes: 17 additions & 18 deletions src/functions/calculateFees.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,7 @@
/* eslint-disable import/prefer-default-export */
/* eslint-disable import/no-cycle */

import { JsonRpcProvider } from '@ethersproject/providers';
import { BigNumber } from '@ethersproject/bignumber';
import { JsonRpcProvider } from 'ethers';
import { Fees, FeesInfo, TotalAmounts, TotalAmountsBN, VaultState } from '../types';
import { validateVaultData } from './vault';
import { getTokenDecimals } from './_totalBalances';
Expand All @@ -15,12 +14,12 @@ import { getVaultTvl } from './priceFromPool';
import getGraphUrls from '../utils/getGraphUrls';
import { _getFeesCollectedEvents, _getRebalances } from './_vaultEvents';

function getCollectedTokenAmountBN(ind: 0 | 1, feesDataset: Fees[]): BigNumber {
function getCollectedTokenAmountBN(ind: 0 | 1, feesDataset: Fees[]): bigint {
const amounts =
ind === 0
? feesDataset.map((r) => BigNumber.from(r.feeAmount0))
: feesDataset.map((r) => BigNumber.from(r.feeAmount1));
const amountBN = amounts.reduce((total, curr) => total.add(curr), BigNumber.from(0));
? feesDataset.map((r) => BigInt(r.feeAmount0))
: feesDataset.map((r) => BigInt(r.feeAmount1));
const amountBN = amounts.reduce((total, curr) => total + curr, BigInt(0));
return amountBN;
}

Expand All @@ -34,12 +33,12 @@ export function getTotalAmountsAtFeeCollectionEvent(
const scarceTokenDecimals = isVaultInverted ? token0Decimals : token1Decimals;
const price0 = !isVaultInverted
? 1
: getPrice(isVaultInverted, BigNumber.from(objFees.sqrtPrice), depositTokenDecimals, scarceTokenDecimals, 15);
: getPrice(isVaultInverted, BigInt(objFees.sqrtPrice), depositTokenDecimals, scarceTokenDecimals, 15);
const price1 = isVaultInverted
? 1
: getPrice(isVaultInverted, BigNumber.from(objFees.sqrtPrice), depositTokenDecimals, scarceTokenDecimals, 15);
const amount0 = Number(formatBigInt(BigNumber.from(objFees.totalAmount0), token0Decimals)) * price0;
const amount1 = Number(formatBigInt(BigNumber.from(objFees.totalAmount1), token1Decimals)) * price1;
: getPrice(isVaultInverted, BigInt(objFees.sqrtPrice), depositTokenDecimals, scarceTokenDecimals, 15);
const amount0 = Number(formatBigInt(BigInt(objFees.totalAmount0), token0Decimals)) * price0;
const amount1 = Number(formatBigInt(BigInt(objFees.totalAmount1), token1Decimals)) * price1;
return [amount0, amount1];
}

Expand All @@ -53,12 +52,12 @@ export function getFeesAmountInBaseTokens(
const scarceTokenDecimals = isVaultInverted ? token0Decimals : token1Decimals;
const price0 = !isVaultInverted
? 1
: getPrice(isVaultInverted, BigNumber.from(objFees.sqrtPrice), depositTokenDecimals, scarceTokenDecimals, 15);
: getPrice(isVaultInverted, BigInt(objFees.sqrtPrice), depositTokenDecimals, scarceTokenDecimals, 15);
const price1 = isVaultInverted
? 1
: getPrice(isVaultInverted, BigNumber.from(objFees.sqrtPrice), depositTokenDecimals, scarceTokenDecimals, 15);
const amount0 = Number(formatBigInt(BigNumber.from(objFees.feeAmount0), token0Decimals)) * price0;
const amount1 = Number(formatBigInt(BigNumber.from(objFees.feeAmount1), token1Decimals)) * price1;
: getPrice(isVaultInverted, BigInt(objFees.sqrtPrice), depositTokenDecimals, scarceTokenDecimals, 15);
const amount0 = Number(formatBigInt(BigInt(objFees.feeAmount0), token0Decimals)) * price0;
const amount1 = Number(formatBigInt(BigInt(objFees.feeAmount1), token1Decimals)) * price1;
return amount0 + amount1;
}

Expand Down Expand Up @@ -106,8 +105,8 @@ export async function getFeesCollected(
const collectedFees = await _getFeesCollectedEvents(vaultAddress, chainId, numOfDays);
if (!collectedFees) throw new Error(`Error getting vault collected fees on ${chainId} for ${vaultAddress}`);

const amount0BN = getCollectedTokenAmountBN(0, rebalances).add(getCollectedTokenAmountBN(0, collectedFees));
const amount1BN = getCollectedTokenAmountBN(1, rebalances).add(getCollectedTokenAmountBN(1, collectedFees));
const amount0BN = getCollectedTokenAmountBN(0, rebalances)+(getCollectedTokenAmountBN(0, collectedFees));
const amount1BN = getCollectedTokenAmountBN(1, rebalances)+(getCollectedTokenAmountBN(1, collectedFees));

const feeAmountsBN = {
total0: amount0BN,
Expand Down Expand Up @@ -162,8 +161,8 @@ export async function getFeesCollectedInfo(
const arrOtherFees = collectedFees
.slice()
.filter((r) => Number(r.createdAtTimestamp) * 1000 > Date.now() - daysToMilliseconds(dayPeriod));
const amount0BN = getCollectedTokenAmountBN(0, arrRebalances).add(getCollectedTokenAmountBN(0, arrOtherFees));
const amount1BN = getCollectedTokenAmountBN(1, arrRebalances).add(getCollectedTokenAmountBN(1, arrOtherFees));
const amount0BN = getCollectedTokenAmountBN(0, arrRebalances)+(getCollectedTokenAmountBN(0, arrOtherFees));
const amount1BN = getCollectedTokenAmountBN(1, arrRebalances)+(getCollectedTokenAmountBN(1, arrOtherFees));
const totalFeesAmount =
getTotalFeesAmountInBaseTokens(arrRebalances, token0Decimals, token1Decimals, isVaultInverted) +
getTotalFeesAmountInBaseTokens(arrOtherFees, token0Decimals, token1Decimals, isVaultInverted);
Expand Down
35 changes: 17 additions & 18 deletions src/functions/calculatePnl.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import { JsonRpcProvider } from '@ethersproject/providers';
import { BigNumber } from 'ethers';
import { JsonRpcProvider } from 'ethers';
import cache from '../utils/cache';
import formatBigInt from '../utils/formatBigInt';
// eslint-disable-next-line import/no-cycle
Expand All @@ -9,9 +8,9 @@ import { getChainByProvider, validateVaultData } from './vault';
import { getUserDeposits, getUserWithdraws } from './vaultEvents';

interface UserPnl {
totalDepositAmountBN: BigNumber;
totalWithdrawAmountBN: BigNumber;
pnlBN: BigNumber;
totalDepositAmountBN: bigint;
totalWithdrawAmountBN: bigint;
pnlBN: bigint;
pnl: string;
roi: number;
}
Expand Down Expand Up @@ -45,39 +44,39 @@ export async function calculateUserDepositTokenPNL(

const totalDepositAmountBN = deposits.reduce((acc, deposit) => {
const amount = getAmountsInDepositToken(
BigNumber.from(deposit.sqrtPrice),
BigNumber.from(deposit.amount0),
BigNumber.from(deposit.amount1),
BigInt(deposit.sqrtPrice),
BigInt(deposit.amount0),
BigInt(deposit.amount1),
decimals0,
decimals1,
vault.allowTokenA ? 0 : 1,
);
return acc.add(amount);
}, BigNumber.from(0));
return acc+(amount);
}, BigInt(0));

const totalWithdrawAmountBN = withdraws.reduce((acc, withdraw) => {
const amount = getAmountsInDepositToken(
BigNumber.from(withdraw.sqrtPrice),
BigNumber.from(withdraw.amount0),
BigNumber.from(withdraw.amount1),
BigInt(withdraw.sqrtPrice),
BigInt(withdraw.amount0),
BigInt(withdraw.amount1),
decimals0,
decimals1,
vault.allowTokenA ? 0 : 1,
);
return acc.add(amount);
}, BigNumber.from(0));
return acc+(amount);
}, BigInt(0));

const currentSqrtPrice = await getSqrtPriceFromPool(vault, jsonProvider);
const currentAmount = getAmountsInDepositToken(
currentSqrtPrice,
BigNumber.from(currentAmount0),
BigNumber.from(currentAmount1),
BigInt(currentAmount0),
BigInt(currentAmount1),
decimals0,
decimals1,
vault.allowTokenA ? 0 : 1,
);

const pnlBN = totalWithdrawAmountBN.add(currentAmount).sub(totalDepositAmountBN);
const pnlBN = totalWithdrawAmountBN+(currentAmount)-(totalDepositAmountBN);

const pnl = formatBigInt(pnlBN, vault.allowTokenA ? decimals0 : decimals1);
const roi =
Expand Down
Loading