Skip to content

Commit

Permalink
refactor versions (#349)
Browse files Browse the repository at this point in the history
* add typechain-typesV3 and updated readme

* refactor versions
  • Loading branch information
tommyzhao451 authored Sep 25, 2024
1 parent 492a493 commit 0559bab
Show file tree
Hide file tree
Showing 6 changed files with 361 additions and 390 deletions.
168 changes: 167 additions & 1 deletion src/viem/solver/increaseLiquidityOptimal.ts
Original file line number Diff line number Diff line change
@@ -1,21 +1,28 @@
import { ApertureSupportedChainId, getAMMInfo } from '@/index';
import { ApertureSupportedChainId, getAMMInfo, getLogger } from '@/index';
import { IncreaseOptions, Position } from '@aperture_finance/uniswap-v3-sdk';
import { CurrencyAmount, Token } from '@uniswap/sdk-core';
import { AutomatedMarketMakerEnum } from 'aperture-lens/dist/src/viem';
import Big from 'big.js';
import { Address, Hex, PublicClient } from 'viem';

import { SwapRoute, get1InchQuote, getIsOkx, getOkxQuote } from '.';
import { ALL_SOLVERS, E_Solver, getSolver } from '.';
import { computePoolAddress } from '../../utils';
import {
IncreaseLiquidityParams,
encodeOptimalSwapData,
getAutomanContract,
simulateIncreaseLiquidityOptimal,
} from '../automan';
import { estimateIncreaseLiquidityOptimalGas } from '../automan';
import { get1InchApproveTarget } from './get1InchSolver';
import { getOkxApproveTarget } from './getOkxSolver';
import { calcPriceImpact, getSwapPath } from './internal';
import {
buildOptimalSolutions,
getOptimalSwapAmount,
getSwapRoute,
} from './internal';
import { SolverResult } from './types';

/**
Expand Down Expand Up @@ -300,3 +307,162 @@ async function getIncreaseLiquidityOptimalSwapData(
swapData: '0x',
};
}

/**
* Get the optimal amount of liquidity to increase for a given pool and token amounts.
* @param chainId The chain ID.
* @param amm The Automated Market Maker.
* @param publicClient Viem public client.
* @param position The current position to simulate the call from.
* @param increaseOptions Increase liquidity options.
* @param token0Amount The token0 amount.
* @param token1Amount The token1 amount.
* @param fromAddress The address to increase liquidity from.
* @param blockNumber Optional. The block number to simulate the call from.
* @param includeSolvers Optional. The solvers to include.
*/
export async function increaseLiquidityOptimalV2(
chainId: ApertureSupportedChainId,
amm: AutomatedMarketMakerEnum,
publicClient: PublicClient,
position: Position,
increaseOptions: IncreaseOptions,
token0Amount: CurrencyAmount<Token>,
token1Amount: CurrencyAmount<Token>,
fromAddress: Address,
blockNumber?: bigint,
includeSolvers: E_Solver[] = ALL_SOLVERS,
): Promise<SolverResult[]> {
if (!token0Amount.currency.sortsBefore(token1Amount.currency)) {
throw new Error('token0 must be sorted before token1');
}

const increaseParams: IncreaseLiquidityParams = {
tokenId: BigInt(increaseOptions.tokenId.toString()),
amount0Desired: BigInt(token0Amount.quotient.toString()),
amount1Desired: BigInt(token1Amount.quotient.toString()),
amount0Min: 0n,
amount1Min: 0n,
deadline: BigInt(Math.floor(Date.now() / 1000 + 86400)),
};

const token0 = position.pool.token0.address as Address;
const token1 = position.pool.token1.address as Address;
const { tickLower, tickUpper } = position;
const feeOrTickSpacing =
amm === AutomatedMarketMakerEnum.enum.SLIPSTREAM
? position.pool.tickSpacing
: position.pool.fee;

const { poolAmountIn, zeroForOne } = await getOptimalSwapAmount(
chainId,
amm,
publicClient,
token0,
token1,
feeOrTickSpacing,
tickLower,
tickUpper,
increaseParams.amount0Desired,
increaseParams.amount1Desired,
blockNumber,
);

const solve = async (solver: E_Solver) => {
try {
const slippage =
Number(increaseOptions.slippageTolerance.toSignificant()) / 100;
const { swapData, swapRoute } = await getSolver(solver).optimalMint({
chainId,
amm,
fromAddress,
token0,
token1,
feeOrTickSpacing,
tickLower,
tickUpper,
slippage,
poolAmountIn,
zeroForOne,
});
const [liquidity, amount0, amount1] =
await simulateIncreaseLiquidityOptimal(
chainId,
amm,
publicClient,
fromAddress,
position,
increaseParams,
swapData,
blockNumber,
);

let gasFeeEstimation = 0n;
try {
const [gasPrice, gasAmount] = await Promise.all([
publicClient.getGasPrice(),
estimateIncreaseLiquidityOptimalGas(
chainId,
amm,
publicClient,
fromAddress,
position,
increaseParams,
swapData,
blockNumber,
),
]);
gasFeeEstimation = gasPrice * gasAmount;
} catch (e) {
getLogger().error('SDK.increaseLiquidityOptimalV2.EstimateGas.Error', {
error: JSON.stringify((e as Error).message),
swapData,
increaseParams,
});
}

return {
solver,
amount0,
amount1,
liquidity,
swapData,
gasFeeEstimation,
swapRoute: getSwapRoute(
token0,
token1,
amount0 - increaseParams.amount0Desired,
swapRoute,
),
priceImpact: calcPriceImpact(
position.pool,
increaseParams.amount0Desired,
increaseParams.amount1Desired,
amount0,
amount1,
),
swapPath: getSwapPath(
token0,
token1,
increaseParams.amount0Desired,
increaseParams.amount1Desired,
amount0,
amount1,
slippage,
),
} as SolverResult;
} catch (e) {
if (!(e as Error)?.message.startsWith('Expected')) {
getLogger().error('SDK.Solver.increaseLiquidityOptimalV2.Error', {
solver,
error: JSON.stringify((e as Error).message),
});
} else {
console.warn('SDK.Solver.increaseLiquidityOptimalV2.Warning', solver);
}
return null;
}
};

return buildOptimalSolutions(solve, includeSolvers);
}
179 changes: 0 additions & 179 deletions src/viem/solver/increaseLiquidityOptimalV2.ts

This file was deleted.

4 changes: 1 addition & 3 deletions src/viem/solver/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,8 @@ export { getOkxQuote } from './getOkxSolver'; // TODO: remove when complete refa
export { get1InchQuote } from './get1InchSolver';

export * from './increaseLiquidityOptimal';
export * from './increaseLiquidityOptimalV2';
export * from './optimalMint';
export * from './optimalMintV2';
export * from './optimalRebalanceV2';
export * from './optimalRebalance';
export * from './types';

const defaultSwapInfo: SolvedSwapInfo = {
Expand Down
Loading

0 comments on commit 0559bab

Please sign in to comment.