New Case Study:See how Anthropic automated 95% of dependency reviews with Socket.Learn More
Socket
Sign inDemoInstall
Socket

@paraswap/dex-lib

Package Overview
Dependencies
Maintainers
8
Versions
1855
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@paraswap/dex-lib - npm Package Compare versions

Comparing version

to
2.0.65-1

build/dex/uniswap-v3/scripts/check-pool-bitmap-ranges.d.ts

4

.vscode/launch.json

@@ -39,3 +39,3 @@ {

"request": "launch",
"name": "Launch check-bitmaps",
"name": "Launch calc-measures-uni-v3",
"runtimeExecutable": "npx",

@@ -45,3 +45,3 @@ "cwd": "${workspaceFolder}",

"ts-node",
"src/dex/uniswap-v3/check-pool-bitmap-ranges.ts"
"src/dex/uniswap-v3/scripts/measure-calc-time.ts"
],

@@ -48,0 +48,0 @@ "runtimeVersion": "16.15.0",

@@ -10,3 +10,3 @@ import { PoolState } from '../types';

declare class UniswapV3Math {
queryOutputs(poolState: DeepReadonly<PoolState>, amounts: bigint[], zeroForOne: boolean, side: SwapSide): bigint[];
queryOutputs(poolState: DeepReadonly<PoolState>, amounts: bigint[], zeroForOne: boolean, side: SwapSide): Promise<bigint[]>;
swapFromEvent(poolState: PoolState, newSqrtPriceX96: bigint, newTick: bigint, newLiquidity: bigint, zeroForOne: boolean): void;

@@ -13,0 +13,0 @@ _modifyPosition(state: PoolState, params: ModifyPositionParams): [bigint, bigint];

@@ -19,2 +19,3 @@ "use strict";

const constants_1 = require("../constants");
const utils_2 = require("../utils");
function _updatePriceComputationObjects(toUpdate, updateBy) {

@@ -25,3 +26,3 @@ for (const k of Object.keys(updateBy)) {

}
function _priceComputationCycles(poolState, ticksCopy, slot0Start, state, cache, sqrtPriceLimitX96, zeroForOne, exactInput) {
async function _priceComputationCycles(poolState, ticksCopy, slot0Start, state, cache, sqrtPriceLimitX96, zeroForOne, exactInput) {
const latestFullCycleState = { ...state };

@@ -121,6 +122,7 @@ const latestFullCycleCache = { ...cache };

}
await (0, utils_2.setImmediatePromise)();
return [state, { latestFullCycleState, latestFullCycleCache }];
}
class UniswapV3Math {
queryOutputs(poolState,
async queryOutputs(poolState,
// Amounts must increase

@@ -158,5 +160,8 @@ amounts, zeroForOne, side) {

let previousAmount = 0n;
return amounts.map(amount => {
if (amount === 0n)
return 0n;
const outputs = new Array(amounts.length);
for (const [i, amount] of amounts.entries()) {
if (amount === 0n) {
outputs[i] = 0n;
continue;
}
const amountSpecified = isSell

@@ -171,5 +176,4 @@ ? BigInt.asIntN(256, amount)

else {
state.amountSpecifiedRemaining = isSell
? amountSpecified - (previousAmount - state.amountSpecifiedRemaining)
: amountSpecified + (previousAmount - state.amountSpecifiedRemaining);
state.amountSpecifiedRemaining =
amountSpecified - (previousAmount - state.amountSpecifiedRemaining);
}

@@ -183,7 +187,8 @@ const exactInput = amountSpecified > 0n;

if (!isOutOfRange) {
const [finalState, { latestFullCycleState, latestFullCycleCache }] = _priceComputationCycles(poolState, ticksCopy, slot0Start, state, cache, sqrtPriceLimitX96, zeroForOne, exactInput);
const [finalState, { latestFullCycleState, latestFullCycleCache }] = await _priceComputationCycles(poolState, ticksCopy, slot0Start, state, cache, sqrtPriceLimitX96, zeroForOne, exactInput);
if (finalState.amountSpecifiedRemaining === 0n &&
finalState.amountCalculated === 0n) {
isOutOfRange = true;
return 0n;
outputs[i] = 0n;
continue;
}

@@ -206,14 +211,17 @@ // We use it on next step to correct state.amountSpecifiedRemaining

if (isSell) {
return BigInt.asUintN(256, -(zeroForOne ? amount1 : amount0));
outputs[i] = BigInt.asUintN(256, -(zeroForOne ? amount1 : amount0));
continue;
}
else {
return zeroForOne
outputs[i] = zeroForOne
? BigInt.asUintN(256, amount0)
: BigInt.asUintN(256, amount1);
continue;
}
}
else {
return 0n;
outputs[i] = 0n;
}
});
}
return outputs;
}

@@ -220,0 +228,0 @@ swapFromEvent(poolState, newSqrtPriceX96, newTick, newLiquidity, zeroForOne) {

@@ -52,3 +52,2 @@ "use strict";

await Promise.all(this.poolsToPreload.map(async (pool) => Promise.all(this.config.supportedFees.map(async (fee) => this.getPool(pool.token0, pool.token1, fee, blockNumber)))));
console.log(0);
}

@@ -71,3 +70,3 @@ async getPool(srcAddress, destAddress, fee, blockNumber) {

pool = null;
this.logger.warn(`${this.dexHelper}: Pool: srcAddress=${srcAddress}, destAddress=${destAddress}, fee=${fee} not found`, e);
this.logger.trace(`${this.dexHelper}: Pool: srcAddress=${srcAddress}, destAddress=${destAddress}, fee=${fee} not found`, e);
}

@@ -97,55 +96,67 @@ else {

async getPricesVolume(srcToken, destToken, amounts, side, blockNumber, limitPools) {
const _srcToken = (0, utils_1.wrapETH)(srcToken, this.network);
const _destToken = (0, utils_1.wrapETH)(destToken, this.network);
const [_srcAddress, _destAddress] = this._getLoweredAddresses(_srcToken, _destToken);
if (_srcAddress === _destAddress)
return null;
let selectedPools = [];
if (limitPools === undefined) {
selectedPools = (await Promise.all(this.supportedFees.map(async (fee) => this.getPool(_srcAddress, _destAddress, fee, blockNumber)))).filter(pool => pool);
}
else {
const pairIdentifierWithoutFee = this.getPoolIdentifier(_srcAddress, _destAddress, 0n).slice(0, -1);
selectedPools = await this._getPoolsFromIdentifiers(limitPools.filter(identifier => identifier.startsWith(pairIdentifierWithoutFee)), blockNumber);
}
if (selectedPools.length === 0)
return null;
const states = await Promise.all(selectedPools.map(async (pool) => {
let state = pool.getState(blockNumber);
if (state === null || !state.isValid) {
state = await pool.generateState(blockNumber);
pool.setState(state, blockNumber);
try {
const _srcToken = (0, utils_1.wrapETH)(srcToken, this.network);
const _destToken = (0, utils_1.wrapETH)(destToken, this.network);
const [_srcAddress, _destAddress] = this._getLoweredAddresses(_srcToken, _destToken);
if (_srcAddress === _destAddress)
return null;
let selectedPools = [];
if (limitPools === undefined) {
selectedPools = (await Promise.all(this.supportedFees.map(async (fee) => this.getPool(_srcAddress, _destAddress, fee, blockNumber)))).filter(pool => pool);
}
return state;
}));
const unitAmount = (0, utils_1.getBigIntPow)(side == constants_1.SwapSide.SELL ? _srcToken.decimals : _destToken.decimals);
const _amounts = [...amounts.slice(1)];
const [token0] = this._sortTokens(_srcAddress, _destAddress);
const zeroForOne = token0 === _srcAddress ? true : false;
const result = new Array(selectedPools.length);
for (const [i, pool] of selectedPools.entries()) {
const state = states[i];
const unit = this._getOutputs(state, [unitAmount], zeroForOne, side);
const prices = this._getOutputs(state, _amounts, zeroForOne, side);
if (!prices || !unit)
else {
const pairIdentifierWithoutFee = this.getPoolIdentifier(_srcAddress, _destAddress, 0n).slice(0, -1);
selectedPools = await this._getPoolsFromIdentifiers(limitPools.filter(identifier => identifier.startsWith(pairIdentifierWithoutFee)), blockNumber);
}
if (selectedPools.length === 0)
return null;
result[i] = {
unit: unit[0],
prices: [0n, ...prices],
data: {
path: [
{
tokenIn: _srcAddress,
tokenOut: _destAddress,
fee: pool.feeCode.toString(),
},
],
},
poolIdentifier: this.getPoolIdentifier(pool.token0, pool.token1, pool.feeCode),
exchange: this.dexKey,
gasCost: constants_2.UNISWAPV3_QUOTE_GASLIMIT,
poolAddresses: [pool.poolAddress],
};
const states = await Promise.all(selectedPools.map(async (pool) => {
let state = pool.getState(blockNumber);
if (state === null || !state.isValid) {
if (state === null) {
this.logger.trace(`${this.dexKey}: State === null. Generating new one`);
}
else if (!state.isValid) {
this.logger.trace(`${this.dexKey}: State is invalid. Generating new one`);
}
state = await pool.generateState(blockNumber);
pool.setState(state, blockNumber);
}
return state;
}));
const unitAmount = (0, utils_1.getBigIntPow)(side == constants_1.SwapSide.SELL ? _srcToken.decimals : _destToken.decimals);
const _amounts = [...amounts.slice(1)];
const [token0] = this._sortTokens(_srcAddress, _destAddress);
const zeroForOne = token0 === _srcAddress ? true : false;
const result = await Promise.all(selectedPools.map(async (pool, i) => {
const state = states[i];
const [unit, prices] = await Promise.all([this._getOutputs(state, [unitAmount], zeroForOne, side),
this._getOutputs(state, _amounts, zeroForOne, side)]);
if (!prices || !unit) {
throw new Error('Prices or unit is not calculated');
}
return {
unit: unit[0],
prices: [0n, ...prices],
data: {
path: [
{
tokenIn: _srcAddress,
tokenOut: _destAddress,
fee: pool.feeCode.toString(),
},
],
},
poolIdentifier: this.getPoolIdentifier(pool.token0, pool.token1, pool.feeCode),
exchange: this.dexKey,
gasCost: constants_2.UNISWAPV3_QUOTE_GASLIMIT,
poolAddresses: [pool.poolAddress],
};
}));
return result;
}
return result;
catch (e) {
this.logger.error(`Error_getPricesVolume ${srcToken.symbol || srcToken.address}, ${destToken.symbol || destToken.address}, ${side}:`, e);
return null;
}
}

@@ -278,5 +289,6 @@ getAdapterParam(srcToken, destToken, srcAmount, destAmount, data, side) {

}
_getOutputs(state, amounts, zeroForOne, side) {
async _getOutputs(state, amounts, zeroForOne, side) {
try {
return uniswap_v3_math_1.uniswapV3Math.queryOutputs(state, amounts, zeroForOne, side);
const outputs = await uniswap_v3_math_1.uniswapV3Math.queryOutputs(state, amounts, zeroForOne, side);
return outputs;
}

@@ -283,0 +295,0 @@ catch (e) {

import { DexConfigMap } from '../../types';
import { DexParams } from './types';
export declare function getUniswapV3DexKey(UniswapV3Config: DexConfigMap<DexParams>): string;
export declare function setImmediatePromise(): Promise<void>;
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getUniswapV3DexKey = void 0;
exports.setImmediatePromise = exports.getUniswapV3DexKey = void 0;
function getUniswapV3DexKey(UniswapV3Config) {

@@ -12,2 +12,10 @@ const UniswapV3Keys = Object.keys(UniswapV3Config);

exports.getUniswapV3DexKey = getUniswapV3DexKey;
function setImmediatePromise() {
return new Promise(resolve => {
setImmediate(() => {
resolve();
});
});
}
exports.setImmediatePromise = setImmediatePromise;
//# sourceMappingURL=utils.js.map

@@ -19,3 +19,3 @@ "use strict";

catch (e) {
this.logger.error('Error_startListening:', e);
this.logger.error(`Error_startListening_${dexKey}:`, e);
setTimeout(() => this.initializeDex(dexKey, blockNumber), constants_1.SETUP_RETRY_TIMEOUT);

@@ -22,0 +22,0 @@ }

{
"name": "@paraswap/dex-lib",
"version": "2.0.65-0",
"version": "2.0.65-1",
"main": "build/index.js",

@@ -5,0 +5,0 @@ "types": "build/index.d.ts",

@@ -15,2 +15,3 @@ import _ from 'lodash';

import { OUT_OF_RANGE_ERROR_POSTFIX } from '../constants';
import { setImmediatePromise } from '../utils';

@@ -50,3 +51,3 @@ type ModifyPositionParams = {

function _priceComputationCycles(
async function _priceComputationCycles(
poolState: DeepReadonly<PoolState>,

@@ -60,11 +61,13 @@ ticksCopy: Record<NumberAsString, TickInfo>,

exactInput: boolean,
): [
// result
PriceComputationState,
// Latest calculated full cycle state we can use for bigger amounts
{
latestFullCycleState: PriceComputationState;
latestFullCycleCache: PriceComputationCache;
},
] {
): Promise<
[
// result
PriceComputationState,
// Latest calculated full cycle state we can use for bigger amounts
{
latestFullCycleState: PriceComputationState;
latestFullCycleCache: PriceComputationCache;
},
]
> {
const latestFullCycleState: PriceComputationState = { ...state };

@@ -207,2 +210,4 @@ const latestFullCycleCache: PriceComputationCache = { ...cache };

await setImmediatePromise();
return [state, { latestFullCycleState, latestFullCycleCache }];

@@ -212,3 +217,3 @@ }

class UniswapV3Math {
queryOutputs(
async queryOutputs(
poolState: DeepReadonly<PoolState>,

@@ -219,3 +224,3 @@ // Amounts must increase

side: SwapSide,
): bigint[] {
): Promise<bigint[]> {
const slot0Start = poolState.slot0;

@@ -258,4 +263,8 @@

return amounts.map(amount => {
if (amount === 0n) return 0n;
const outputs = new Array(amounts.length);
for (const [i, amount] of amounts.entries()) {
if (amount === 0n) {
outputs[i] = 0n;
continue;
}

@@ -271,5 +280,4 @@ const amountSpecified = isSell

} else {
state.amountSpecifiedRemaining = isSell
? amountSpecified - (previousAmount - state.amountSpecifiedRemaining)
: amountSpecified + (previousAmount - state.amountSpecifiedRemaining);
state.amountSpecifiedRemaining =
amountSpecified - (previousAmount - state.amountSpecifiedRemaining);
}

@@ -292,3 +300,3 @@

const [finalState, { latestFullCycleState, latestFullCycleCache }] =
_priceComputationCycles(
await _priceComputationCycles(
poolState,

@@ -309,3 +317,4 @@ ticksCopy,

isOutOfRange = true;
return 0n;
outputs[i] = 0n;
continue;
}

@@ -333,12 +342,16 @@

if (isSell) {
return BigInt.asUintN(256, -(zeroForOne ? amount1 : amount0));
outputs[i] = BigInt.asUintN(256, -(zeroForOne ? amount1 : amount0));
continue;
} else {
return zeroForOne
outputs[i] = zeroForOne
? BigInt.asUintN(256, amount0)
: BigInt.asUintN(256, amount1);
continue;
}
} else {
return 0n;
outputs[i] = 0n;
}
});
}
return outputs;
}

@@ -345,0 +358,0 @@

@@ -36,3 +36,2 @@ import { Interface } from '@ethersproject/abi';

import { uniswapV3Math } from './contract-math/uniswap-v3-math';
import { TickMath } from './contract-math/TickMath';

@@ -97,3 +96,2 @@ export class UniswapV3

);
console.log(0);
}

@@ -140,3 +138,3 @@

pool = null;
this.logger.warn(
this.logger.trace(
`${this.dexHelper}: Pool: srcAddress=${srcAddress}, destAddress=${destAddress}, fee=${fee} not found`,

@@ -200,95 +198,116 @@ e,

): Promise<null | ExchangePrices<UniswapV3Data>> {
const _srcToken = wrapETH(srcToken, this.network);
const _destToken = wrapETH(destToken, this.network);
try {
const _srcToken = wrapETH(srcToken, this.network);
const _destToken = wrapETH(destToken, this.network);
const [_srcAddress, _destAddress] = this._getLoweredAddresses(
_srcToken,
_destToken,
);
const [_srcAddress, _destAddress] = this._getLoweredAddresses(
_srcToken,
_destToken,
);
if (_srcAddress === _destAddress) return null;
if (_srcAddress === _destAddress) return null;
let selectedPools: UniswapV3EventPool[] = [];
if (limitPools === undefined) {
selectedPools = (
await Promise.all(
this.supportedFees.map(async fee =>
this.getPool(_srcAddress, _destAddress, fee, blockNumber),
let selectedPools: UniswapV3EventPool[] = [];
if (limitPools === undefined) {
selectedPools = (
await Promise.all(
this.supportedFees.map(async fee =>
this.getPool(_srcAddress, _destAddress, fee, blockNumber),
),
)
).filter(pool => pool) as UniswapV3EventPool[];
} else {
const pairIdentifierWithoutFee = this.getPoolIdentifier(
_srcAddress,
_destAddress,
0n,
// Trim from 0 fee postfix, so it become comparable
).slice(0, -1);
selectedPools = await this._getPoolsFromIdentifiers(
limitPools.filter(identifier =>
identifier.startsWith(pairIdentifierWithoutFee),
),
)
).filter(pool => pool) as UniswapV3EventPool[];
} else {
const pairIdentifierWithoutFee = this.getPoolIdentifier(
_srcAddress,
_destAddress,
0n,
// Trim from 0 fee postfix, so it become comparable
).slice(0, -1);
selectedPools = await this._getPoolsFromIdentifiers(
limitPools.filter(identifier =>
identifier.startsWith(pairIdentifierWithoutFee),
),
blockNumber,
);
}
blockNumber,
);
}
if (selectedPools.length === 0) return null;
if (selectedPools.length === 0) return null;
const states = await Promise.all(
selectedPools.map(async pool => {
let state = pool.getState(blockNumber);
if (state === null || !state.isValid) {
state = await pool.generateState(blockNumber);
pool.setState(state, blockNumber);
}
return state;
}),
);
const states = await Promise.all(
selectedPools.map(async pool => {
let state = pool.getState(blockNumber);
if (state === null || !state.isValid) {
if (state === null) {
this.logger.trace(
`${this.dexKey}: State === null. Generating new one`,
);
} else if (!state.isValid) {
this.logger.trace(
`${this.dexKey}: State is invalid. Generating new one`,
);
}
const unitAmount = getBigIntPow(
side == SwapSide.SELL ? _srcToken.decimals : _destToken.decimals,
);
state = await pool.generateState(blockNumber);
pool.setState(state, blockNumber);
}
return state;
}),
);
const _amounts = [...amounts.slice(1)];
const unitAmount = getBigIntPow(
side == SwapSide.SELL ? _srcToken.decimals : _destToken.decimals,
);
const [token0] = this._sortTokens(_srcAddress, _destAddress);
const _amounts = [...amounts.slice(1)];
const zeroForOne = token0 === _srcAddress ? true : false;
const [token0] = this._sortTokens(_srcAddress, _destAddress);
const result: ExchangePrices<UniswapV3Data> = new Array(
selectedPools.length,
);
const zeroForOne = token0 === _srcAddress ? true : false;
for (const [i, pool] of selectedPools.entries()) {
const state = states[i];
const result = await Promise.all(
selectedPools.map(async (pool, i) => {
const state = states[i];
const unit = this._getOutputs(state, [unitAmount], zeroForOne, side);
const [unit, prices] = await Promise.all(
[this._getOutputs(state, [unitAmount], zeroForOne, side),
this._getOutputs(state, _amounts, zeroForOne, side)]
);
const prices = this._getOutputs(state, _amounts, zeroForOne, side);
if (!prices || !unit) {
throw new Error('Prices or unit is not calculated');
}
if (!prices || !unit) return null;
result[i] = {
unit: unit[0],
prices: [0n, ...prices],
data: {
path: [
{
tokenIn: _srcAddress,
tokenOut: _destAddress,
fee: pool.feeCode.toString(),
return {
unit: unit[0],
prices: [0n, ...prices],
data: {
path: [
{
tokenIn: _srcAddress,
tokenOut: _destAddress,
fee: pool.feeCode.toString(),
},
],
},
],
},
poolIdentifier: this.getPoolIdentifier(
pool.token0,
pool.token1,
pool.feeCode,
),
exchange: this.dexKey,
gasCost: UNISWAPV3_QUOTE_GASLIMIT,
poolAddresses: [pool.poolAddress],
};
poolIdentifier: this.getPoolIdentifier(
pool.token0,
pool.token1,
pool.feeCode,
),
exchange: this.dexKey,
gasCost: UNISWAPV3_QUOTE_GASLIMIT,
poolAddresses: [pool.poolAddress],
};
}),
);
return result;
} catch (e) {
this.logger.error(
`Error_getPricesVolume ${srcToken.symbol || srcToken.address}, ${
destToken.symbol || destToken.address
}, ${side}:`,
e,
);
return null;
}
return result;
}

@@ -483,3 +502,3 @@

private _getOutputs(
private async _getOutputs(
state: DeepReadonly<PoolState>,

@@ -489,5 +508,11 @@ amounts: bigint[],

side: SwapSide,
): bigint[] | null {
): Promise<bigint[] | null> {
try {
return uniswapV3Math.queryOutputs(state, amounts, zeroForOne, side);
const outputs = await uniswapV3Math.queryOutputs(
state,
amounts,
zeroForOne,
side,
);
return outputs;
} catch (e) {

@@ -494,0 +519,0 @@ this.logger.error(

@@ -17,1 +17,9 @@ import { DexConfigMap } from '../../types';

}
export function setImmediatePromise() {
return new Promise<void>(resolve => {
setImmediate(() => {
resolve();
});
});
}

@@ -45,3 +45,3 @@ import {

} catch (e) {
this.logger.error('Error_startListening:', e);
this.logger.error(`Error_startListening_${dexKey}:`, e);
setTimeout(

@@ -48,0 +48,0 @@ () => this.initializeDex(dexKey, blockNumber),

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet