@paraswap/dex-lib 2.42.22 → 2.42.23
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/build/abi/hashflow/HashflowRouter.abi.json +816 -246
- package/build/abi/kyberswap-elastic/IAntiSnipAttackPositionManager.json +1276 -0
- package/build/abi/kyberswap-elastic/IFactory.json +550 -0
- package/build/abi/kyberswap-elastic/IPool.json +1042 -0
- package/build/abi/kyberswap-elastic/IQuoterV2.json +226 -0
- package/build/abi/kyberswap-elastic/IRouter.json +239 -0
- package/build/abi/kyberswap-elastic/TicksFeesReader.json +142 -0
- package/build/abi/wombat/asset.json +769 -0
- package/build/abi/wombat/bmw.json +1247 -0
- package/build/abi/wombat/pool.json +1364 -0
- package/build/config.js +14 -14
- package/build/dex/baseswap-v3/baseswap-v3-factory.d.ts +26 -0
- package/build/dex/baseswap-v3/baseswap-v3-factory.js +44 -0
- package/build/dex/baseswap-v3/baseswap-v3-factory.js.map +1 -0
- package/build/dex/baseswap-v3/baseswap-v3-pool.d.ts +46 -0
- package/build/dex/baseswap-v3/baseswap-v3-pool.js +312 -0
- package/build/dex/baseswap-v3/baseswap-v3-pool.js.map +1 -0
- package/build/dex/baseswap-v3/baseswap-v3.d.ts +71 -0
- package/build/dex/baseswap-v3/baseswap-v3.js +752 -0
- package/build/dex/baseswap-v3/baseswap-v3.js.map +1 -0
- package/build/dex/baseswap-v3/config.d.ts +9 -0
- package/build/dex/baseswap-v3/config.js +48 -0
- package/build/dex/baseswap-v3/config.js.map +1 -0
- package/build/dex/baseswap-v3/constants.d.ts +28 -0
- package/build/dex/baseswap-v3/constants.js +35 -0
- package/build/dex/baseswap-v3/constants.js.map +1 -0
- package/build/dex/baseswap-v3/contract-math/BitMath.d.ts +4 -0
- package/build/dex/baseswap-v3/contract-math/BitMath.js +93 -0
- package/build/dex/baseswap-v3/contract-math/BitMath.js.map +1 -0
- package/build/dex/baseswap-v3/contract-math/FixedPoint128.d.ts +3 -0
- package/build/dex/baseswap-v3/contract-math/FixedPoint128.js +8 -0
- package/build/dex/baseswap-v3/contract-math/FixedPoint128.js.map +1 -0
- package/build/dex/baseswap-v3/contract-math/FixedPoint96.d.ts +4 -0
- package/build/dex/baseswap-v3/contract-math/FixedPoint96.js +9 -0
- package/build/dex/baseswap-v3/contract-math/FixedPoint96.js.map +1 -0
- package/build/dex/baseswap-v3/contract-math/FullMath.d.ts +4 -0
- package/build/dex/baseswap-v3/contract-math/FullMath.js +19 -0
- package/build/dex/baseswap-v3/contract-math/FullMath.js.map +1 -0
- package/build/dex/baseswap-v3/contract-math/LiquidityMath.d.ts +3 -0
- package/build/dex/baseswap-v3/contract-math/LiquidityMath.js +22 -0
- package/build/dex/baseswap-v3/contract-math/LiquidityMath.js.map +1 -0
- package/build/dex/baseswap-v3/contract-math/Oracle.d.ts +10 -0
- package/build/dex/baseswap-v3/contract-math/Oracle.js +133 -0
- package/build/dex/baseswap-v3/contract-math/Oracle.js.map +1 -0
- package/build/dex/baseswap-v3/contract-math/SqrtPriceMath.d.ts +10 -0
- package/build/dex/baseswap-v3/contract-math/SqrtPriceMath.js +91 -0
- package/build/dex/baseswap-v3/contract-math/SqrtPriceMath.js.map +1 -0
- package/build/dex/baseswap-v3/contract-math/SwapMath.d.ts +8 -0
- package/build/dex/baseswap-v3/contract-math/SwapMath.js +70 -0
- package/build/dex/baseswap-v3/contract-math/SwapMath.js.map +1 -0
- package/build/dex/baseswap-v3/contract-math/Tick.d.ts +7 -0
- package/build/dex/baseswap-v3/contract-math/Tick.js +45 -0
- package/build/dex/baseswap-v3/contract-math/Tick.js.map +1 -0
- package/build/dex/baseswap-v3/contract-math/TickBitMap.d.ts +7 -0
- package/build/dex/baseswap-v3/contract-math/TickBitMap.js +84 -0
- package/build/dex/baseswap-v3/contract-math/TickBitMap.js.map +1 -0
- package/build/dex/baseswap-v3/contract-math/TickMath.d.ts +8 -0
- package/build/dex/baseswap-v3/contract-math/TickMath.js +162 -0
- package/build/dex/baseswap-v3/contract-math/TickMath.js.map +1 -0
- package/build/dex/baseswap-v3/contract-math/UnsafeMath.d.ts +3 -0
- package/build/dex/baseswap-v3/contract-math/UnsafeMath.js +10 -0
- package/build/dex/baseswap-v3/contract-math/UnsafeMath.js.map +1 -0
- package/build/dex/baseswap-v3/contract-math/uniswap-v3-math.d.ts +37 -0
- package/build/dex/baseswap-v3/contract-math/uniswap-v3-math.js +393 -0
- package/build/dex/baseswap-v3/contract-math/uniswap-v3-math.js.map +1 -0
- package/build/dex/baseswap-v3/contract-math/utils.d.ts +7 -0
- package/build/dex/baseswap-v3/contract-math/utils.js +42 -0
- package/build/dex/baseswap-v3/contract-math/utils.js.map +1 -0
- package/build/dex/baseswap-v3/types.d.ts +164 -0
- package/build/dex/baseswap-v3/types.js +9 -0
- package/build/dex/baseswap-v3/types.js.map +1 -0
- package/build/dex/baseswap-v3/utils.d.ts +6 -0
- package/build/dex/baseswap-v3/utils.js +65 -0
- package/build/dex/baseswap-v3/utils.js.map +1 -0
- package/build/dex/hashflow/config.d.ts +1 -1
- package/build/dex/hashflow/config.js +6 -6
- package/build/dex/hashflow/config.js.map +1 -1
- package/build/dex/hashflow/hashflow.d.ts +7 -7
- package/build/dex/hashflow/hashflow.js +47 -54
- package/build/dex/hashflow/hashflow.js.map +1 -1
- package/build/dex/hashflow/rate-fetcher.d.ts +1 -1
- package/build/dex/hashflow/rate-fetcher.js +2 -4
- package/build/dex/hashflow/rate-fetcher.js.map +1 -1
- package/build/dex/hashflow/types.d.ts +5 -6
- package/build/dex/hashflow/types.js.map +1 -1
- package/build/dex/hashflow/validators.js +11 -4
- package/build/dex/hashflow/validators.js.map +1 -1
- package/build/dex/hello/config.d.ts +4 -0
- package/build/dex/hello/config.js +15 -0
- package/build/dex/hello/config.js.map +1 -0
- package/build/dex/hello/hello-pool.d.ts +39 -0
- package/build/dex/hello/hello-pool.js +64 -0
- package/build/dex/hello/hello-pool.js.map +1 -0
- package/build/dex/hello/hello.d.ts +37 -0
- package/build/dex/hello/hello.js +126 -0
- package/build/dex/hello/hello.js.map +1 -0
- package/build/dex/hello/types.d.ts +6 -0
- package/build/dex/hello/types.js +3 -0
- package/build/dex/hello/types.js.map +1 -0
- package/build/dex/kyberswap-elastic/config.d.ts +4 -0
- package/build/dex/kyberswap-elastic/config.js +80 -0
- package/build/dex/kyberswap-elastic/config.js.map +1 -0
- package/build/dex/kyberswap-elastic/constants.d.ts +17 -0
- package/build/dex/kyberswap-elastic/constants.js +42 -0
- package/build/dex/kyberswap-elastic/constants.js.map +1 -0
- package/build/dex/kyberswap-elastic/contract-math/FixedPoint96.d.ts +4 -0
- package/build/dex/kyberswap-elastic/contract-math/FixedPoint96.js +9 -0
- package/build/dex/kyberswap-elastic/contract-math/FixedPoint96.js.map +1 -0
- package/build/dex/kyberswap-elastic/contract-math/FullMath.d.ts +5 -0
- package/build/dex/kyberswap-elastic/contract-math/FullMath.js +22 -0
- package/build/dex/kyberswap-elastic/contract-math/FullMath.js.map +1 -0
- package/build/dex/kyberswap-elastic/contract-math/LiqDeltaMath.d.ts +3 -0
- package/build/dex/kyberswap-elastic/contract-math/LiqDeltaMath.js +12 -0
- package/build/dex/kyberswap-elastic/contract-math/LiqDeltaMath.js.map +1 -0
- package/build/dex/kyberswap-elastic/contract-math/LiquidityMath.d.ts +3 -0
- package/build/dex/kyberswap-elastic/contract-math/LiquidityMath.js +22 -0
- package/build/dex/kyberswap-elastic/contract-math/LiquidityMath.js.map +1 -0
- package/build/dex/kyberswap-elastic/contract-math/QtyDeltaMath.d.ts +5 -0
- package/build/dex/kyberswap-elastic/contract-math/QtyDeltaMath.js +25 -0
- package/build/dex/kyberswap-elastic/contract-math/QtyDeltaMath.js.map +1 -0
- package/build/dex/kyberswap-elastic/contract-math/QuadMath.d.ts +4 -0
- package/build/dex/kyberswap-elastic/contract-math/QuadMath.js +27 -0
- package/build/dex/kyberswap-elastic/contract-math/QuadMath.js.map +1 -0
- package/build/dex/kyberswap-elastic/contract-math/ReinvestmentMath.d.ts +3 -0
- package/build/dex/kyberswap-elastic/contract-math/ReinvestmentMath.js +14 -0
- package/build/dex/kyberswap-elastic/contract-math/ReinvestmentMath.js.map +1 -0
- package/build/dex/kyberswap-elastic/contract-math/SafeCast.d.ts +8 -0
- package/build/dex/kyberswap-elastic/contract-math/SafeCast.js +30 -0
- package/build/dex/kyberswap-elastic/contract-math/SafeCast.js.map +1 -0
- package/build/dex/kyberswap-elastic/contract-math/SqrtPriceMath.d.ts +10 -0
- package/build/dex/kyberswap-elastic/contract-math/SqrtPriceMath.js +91 -0
- package/build/dex/kyberswap-elastic/contract-math/SqrtPriceMath.js.map +1 -0
- package/build/dex/kyberswap-elastic/contract-math/SwapMath.d.ts +13 -0
- package/build/dex/kyberswap-elastic/contract-math/SwapMath.js +188 -0
- package/build/dex/kyberswap-elastic/contract-math/SwapMath.js.map +1 -0
- package/build/dex/kyberswap-elastic/contract-math/TickLinkedList.d.ts +6 -0
- package/build/dex/kyberswap-elastic/contract-math/TickLinkedList.js +41 -0
- package/build/dex/kyberswap-elastic/contract-math/TickLinkedList.js.map +1 -0
- package/build/dex/kyberswap-elastic/contract-math/TickMath.d.ts +9 -0
- package/build/dex/kyberswap-elastic/contract-math/TickMath.js +165 -0
- package/build/dex/kyberswap-elastic/contract-math/TickMath.js.map +1 -0
- package/build/dex/kyberswap-elastic/contract-math/UnsafeMath.d.ts +3 -0
- package/build/dex/kyberswap-elastic/contract-math/UnsafeMath.js +10 -0
- package/build/dex/kyberswap-elastic/contract-math/UnsafeMath.js.map +1 -0
- package/build/dex/kyberswap-elastic/contract-math/kyberswap-elastic-math.d.ts +28 -0
- package/build/dex/kyberswap-elastic/contract-math/kyberswap-elastic-math.js +502 -0
- package/build/dex/kyberswap-elastic/contract-math/kyberswap-elastic-math.js.map +1 -0
- package/build/dex/kyberswap-elastic/contract-math/utils.d.ts +3 -0
- package/build/dex/kyberswap-elastic/contract-math/utils.js +16 -0
- package/build/dex/kyberswap-elastic/contract-math/utils.js.map +1 -0
- package/build/dex/kyberswap-elastic/errors.d.ts +2 -0
- package/build/dex/kyberswap-elastic/errors.js +6 -0
- package/build/dex/kyberswap-elastic/errors.js.map +1 -0
- package/build/dex/kyberswap-elastic/kyberswap-elastic-pool.d.ts +80 -0
- package/build/dex/kyberswap-elastic/kyberswap-elastic-pool.js +458 -0
- package/build/dex/kyberswap-elastic/kyberswap-elastic-pool.js.map +1 -0
- package/build/dex/kyberswap-elastic/kyberswap-elastic.d.ts +53 -0
- package/build/dex/kyberswap-elastic/kyberswap-elastic.js +610 -0
- package/build/dex/kyberswap-elastic/kyberswap-elastic.js.map +1 -0
- package/build/dex/kyberswap-elastic/types.d.ts +134 -0
- package/build/dex/kyberswap-elastic/types.js +9 -0
- package/build/dex/kyberswap-elastic/types.js.map +1 -0
- package/build/dex/kyberswap-elastic/utils/decoders.d.ts +9 -0
- package/build/dex/kyberswap-elastic/utils/decoders.js +78 -0
- package/build/dex/kyberswap-elastic/utils/decoders.js.map +1 -0
- package/build/dex/morphex/config.d.ts +11 -0
- package/build/dex/morphex/config.js +43 -0
- package/build/dex/morphex/config.js.map +1 -0
- package/build/dex/morphex/morphex.d.ts +25 -0
- package/build/dex/morphex/morphex.js +19 -0
- package/build/dex/morphex/morphex.js.map +1 -0
- package/build/dex/my-test-dex/config.d.ts +4 -0
- package/build/dex/my-test-dex/config.js +15 -0
- package/build/dex/my-test-dex/config.js.map +1 -0
- package/build/dex/my-test-dex/my-test-dex-pool.d.ts +39 -0
- package/build/dex/my-test-dex/my-test-dex-pool.js +64 -0
- package/build/dex/my-test-dex/my-test-dex-pool.js.map +1 -0
- package/build/dex/my-test-dex/my-test-dex.d.ts +37 -0
- package/build/dex/my-test-dex/my-test-dex.js +126 -0
- package/build/dex/my-test-dex/my-test-dex.js.map +1 -0
- package/build/dex/my-test-dex/types.d.ts +6 -0
- package/build/dex/my-test-dex/types.js +3 -0
- package/build/dex/my-test-dex/types.js.map +1 -0
- package/build/dex/solidly/forks-override/fvm.d.ts +20 -0
- package/build/dex/solidly/forks-override/fvm.js +42 -0
- package/build/dex/solidly/forks-override/fvm.js.map +1 -0
- package/build/dex/wombat/config.d.ts +4 -0
- package/build/dex/wombat/config.js +99 -0
- package/build/dex/wombat/config.js.map +1 -0
- package/build/dex/wombat/types.d.ts +33 -0
- package/build/dex/wombat/types.js +3 -0
- package/build/dex/wombat/types.js.map +1 -0
- package/build/dex/wombat/utils.d.ts +9 -0
- package/build/dex/wombat/utils.js +66 -0
- package/build/dex/wombat/utils.js.map +1 -0
- package/build/dex/wombat/wombat-bmw.d.ts +40 -0
- package/build/dex/wombat/wombat-bmw.js +147 -0
- package/build/dex/wombat/wombat-bmw.js.map +1 -0
- package/build/dex/wombat/wombat-pool.d.ts +22 -0
- package/build/dex/wombat/wombat-pool.js +161 -0
- package/build/dex/wombat/wombat-pool.js.map +1 -0
- package/build/dex/wombat/wombat-quoter.d.ts +16 -0
- package/build/dex/wombat/wombat-quoter.js +176 -0
- package/build/dex/wombat/wombat-quoter.js.map +1 -0
- package/build/dex/wombat/wombat.d.ts +55 -0
- package/build/dex/wombat/wombat.js +290 -0
- package/build/dex/wombat/wombat.js.map +1 -0
- package/build/lib/fetcher/fetcher.d.ts +1 -1
- package/build/lib/fetcher/fetcher.js.map +1 -1
- package/package.json +2 -2
- package/src/abi/hashflow/HashflowRouter.abi.json +816 -246
- package/src/config.ts +14 -14
- package/src/dex/hashflow/config.ts +8 -8
- package/src/dex/hashflow/hashflow-e2e.test.ts +4 -4
- package/src/dex/hashflow/hashflow-integration.test.ts +9 -6
- package/src/dex/hashflow/hashflow.ts +70 -87
- package/src/dex/hashflow/rate-fetcher.ts +6 -8
- package/src/dex/hashflow/types.ts +5 -6
- package/src/dex/hashflow/validators.ts +11 -4
- package/src/lib/fetcher/fetcher.ts +2 -2
- package/tests/constants-e2e.ts +1 -1
- package/tests/tenderly-simulation.ts +5 -2
- package/.vscode/launch.json +0 -39
- package/.vscode/settings.json +0 -2
- package/.vscode/tasks.json +0 -15
|
@@ -0,0 +1,752 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
3
|
+
if (k2 === undefined) k2 = k;
|
|
4
|
+
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
5
|
+
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
6
|
+
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
7
|
+
}
|
|
8
|
+
Object.defineProperty(o, k2, desc);
|
|
9
|
+
}) : (function(o, m, k, k2) {
|
|
10
|
+
if (k2 === undefined) k2 = k;
|
|
11
|
+
o[k2] = m[k];
|
|
12
|
+
}));
|
|
13
|
+
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
|
14
|
+
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
15
|
+
}) : function(o, v) {
|
|
16
|
+
o["default"] = v;
|
|
17
|
+
});
|
|
18
|
+
var __importStar = (this && this.__importStar) || function (mod) {
|
|
19
|
+
if (mod && mod.__esModule) return mod;
|
|
20
|
+
var result = {};
|
|
21
|
+
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
|
|
22
|
+
__setModuleDefault(result, mod);
|
|
23
|
+
return result;
|
|
24
|
+
};
|
|
25
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
26
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
27
|
+
};
|
|
28
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
29
|
+
exports.BaseswapV3 = void 0;
|
|
30
|
+
const abi_1 = require("@ethersproject/abi");
|
|
31
|
+
const lodash_1 = __importDefault(require("lodash"));
|
|
32
|
+
const solidity_1 = require("@ethersproject/solidity");
|
|
33
|
+
const constants_1 = require("../../constants");
|
|
34
|
+
const CALLDATA_GAS_COST = __importStar(require("../../calldata-gas-cost"));
|
|
35
|
+
const utils_1 = require("../../utils");
|
|
36
|
+
const types_1 = require("./types");
|
|
37
|
+
const simple_exchange_1 = require("../simple-exchange");
|
|
38
|
+
const config_1 = require("./config");
|
|
39
|
+
const baseswap_v3_pool_1 = require("./baseswap-v3-pool");
|
|
40
|
+
const UniswapV3Router_abi_json_1 = __importDefault(require("../../abi/uniswap-v3/UniswapV3Router.abi.json"));
|
|
41
|
+
const UniswapV3QuoterV2_abi_json_1 = __importDefault(require("../../abi/uniswap-v3/UniswapV3QuoterV2.abi.json"));
|
|
42
|
+
const UniswapMulti_abi_json_1 = __importDefault(require("../../abi/uniswap-v3/UniswapMulti.abi.json"));
|
|
43
|
+
const DirectSwap_json_1 = __importDefault(require("../../abi/DirectSwap.json"));
|
|
44
|
+
const UniswapV3StateMulticall_abi_json_1 = __importDefault(require("../../abi/uniswap-v3/UniswapV3StateMulticall.abi.json"));
|
|
45
|
+
const constants_2 = require("./constants");
|
|
46
|
+
const ts_essentials_1 = require("ts-essentials");
|
|
47
|
+
const uniswap_v3_math_1 = require("./contract-math/uniswap-v3-math");
|
|
48
|
+
const balancer_fetcher_1 = require("../../lib/tokens/balancer-fetcher");
|
|
49
|
+
const types_2 = require("../../lib/tokens/types");
|
|
50
|
+
const baseswap_v3_factory_1 = require("./baseswap-v3-factory");
|
|
51
|
+
const BASESWAPV3_CLEAN_NOT_EXISTING_POOL_TTL_MS = 3 * 24 * 60 * 60 * 1000; // 3 days
|
|
52
|
+
const BASESWAPV3_CLEAN_NOT_EXISTING_POOL_INTERVAL_MS = 24 * 60 * 60 * 1000; // Once in a day
|
|
53
|
+
const BASESWAPV3_QUOTE_GASLIMIT = 200000;
|
|
54
|
+
class BaseswapV3 extends simple_exchange_1.SimpleExchange {
|
|
55
|
+
constructor(network, dexKey, dexHelper, adapters = config_1.Adapters[network] || {}, routerIface = new abi_1.Interface(UniswapV3Router_abi_json_1.default), quoterIface = new abi_1.Interface(UniswapV3QuoterV2_abi_json_1.default), config = config_1.BaseswapV3Config[dexKey][network], poolsToPreload = config_1.PoolsToPreload[dexKey]?.[network] || []) {
|
|
56
|
+
super(dexHelper, dexKey);
|
|
57
|
+
this.network = network;
|
|
58
|
+
this.dexHelper = dexHelper;
|
|
59
|
+
this.adapters = adapters;
|
|
60
|
+
this.routerIface = routerIface;
|
|
61
|
+
this.quoterIface = quoterIface;
|
|
62
|
+
this.config = config;
|
|
63
|
+
this.poolsToPreload = poolsToPreload;
|
|
64
|
+
this.isFeeOnTransferSupported = false;
|
|
65
|
+
this.eventPools = {};
|
|
66
|
+
this.hasConstantPriceLargeAmounts = false;
|
|
67
|
+
this.needWrapNative = true;
|
|
68
|
+
this.directSwapIface = new abi_1.Interface(DirectSwap_json_1.default);
|
|
69
|
+
/*
|
|
70
|
+
* When a non existing pool is queried, it's blacklisted for an arbitrary long period in order to prevent issuing too many rpc calls
|
|
71
|
+
* Once the pool is created, it gets immediately flagged
|
|
72
|
+
*/
|
|
73
|
+
this.onPoolCreatedDeleteFromNonExistingSet = async ({ token0, token1, fee, }) => {
|
|
74
|
+
const logPrefix = '[UniswapV3.onPoolCreatedDeleteFromNonExistingSet]';
|
|
75
|
+
const [_token0, _token1] = this._sortTokens(token0, token1);
|
|
76
|
+
const poolKey = `${_token0}_${_token1}_${fee}`;
|
|
77
|
+
// consider doing it only from master pool for less calls to distant cache
|
|
78
|
+
// delete entry locally to let local instance discover the pool
|
|
79
|
+
delete this.eventPools[this.getPoolIdentifier(_token0, _token1, fee)];
|
|
80
|
+
try {
|
|
81
|
+
this.logger.info(`${logPrefix} delete pool from not existing set: ${poolKey}`);
|
|
82
|
+
// delete pool record from set
|
|
83
|
+
await this.dexHelper.cache.zrem(this.notExistingPoolSetKey, [poolKey]);
|
|
84
|
+
}
|
|
85
|
+
catch (error) {
|
|
86
|
+
this.logger.error(`${logPrefix} failed to delete pool from set: ${poolKey}`, error);
|
|
87
|
+
}
|
|
88
|
+
};
|
|
89
|
+
this.logger = dexHelper.getLogger(dexKey + '-' + network);
|
|
90
|
+
this.uniswapMulti = new this.dexHelper.web3Provider.eth.Contract(UniswapMulti_abi_json_1.default, this.config.uniswapMulticall);
|
|
91
|
+
this.stateMultiContract = new this.dexHelper.web3Provider.eth.Contract(this.config.stateMultiCallAbi !== undefined
|
|
92
|
+
? this.config.stateMultiCallAbi
|
|
93
|
+
: UniswapV3StateMulticall_abi_json_1.default, this.config.stateMulticall);
|
|
94
|
+
// To receive revert reasons
|
|
95
|
+
this.dexHelper.web3Provider.eth.handleRevert = false;
|
|
96
|
+
// Normalize once all config addresses and use across all scenarios
|
|
97
|
+
this.config = this._toLowerForAllConfigAddresses();
|
|
98
|
+
this.notExistingPoolSetKey =
|
|
99
|
+
`${constants_1.CACHE_PREFIX}_${network}_${dexKey}_not_existings_pool_set`.toLowerCase();
|
|
100
|
+
this.factory = new baseswap_v3_factory_1.BaseswapV3Factory(dexHelper, dexKey, this.config.factory, this.logger, this.onPoolCreatedDeleteFromNonExistingSet);
|
|
101
|
+
}
|
|
102
|
+
get supportedFees() {
|
|
103
|
+
return this.config.supportedFees;
|
|
104
|
+
}
|
|
105
|
+
getAdapters(side) {
|
|
106
|
+
return this.adapters[side] ? this.adapters[side] : null;
|
|
107
|
+
}
|
|
108
|
+
getPoolIdentifier(srcAddress, destAddress, fee) {
|
|
109
|
+
const tokenAddresses = this._sortTokens(srcAddress, destAddress).join('_');
|
|
110
|
+
return `${this.dexKey}_${tokenAddresses}_${fee}`;
|
|
111
|
+
}
|
|
112
|
+
async initializePricing(blockNumber) {
|
|
113
|
+
// Init listening to new pools creation
|
|
114
|
+
await this.factory.initialize(blockNumber);
|
|
115
|
+
// This is only for testing, because cold pool fetching is goes out of
|
|
116
|
+
// FETCH_POOL_INDENTIFIER_TIMEOUT range
|
|
117
|
+
await Promise.all(this.poolsToPreload.map(async (pool) => Promise.all(this.config.supportedFees.map(async (fee) => this.getPool(pool.token0, pool.token1, fee, blockNumber)))));
|
|
118
|
+
if (!this.dexHelper.config.isSlave) {
|
|
119
|
+
const cleanExpiredNotExistingPoolsKeys = async () => {
|
|
120
|
+
const maxTimestamp = Date.now() - BASESWAPV3_CLEAN_NOT_EXISTING_POOL_TTL_MS;
|
|
121
|
+
await this.dexHelper.cache.zremrangebyscore(this.notExistingPoolSetKey, 0, maxTimestamp);
|
|
122
|
+
};
|
|
123
|
+
this.intervalTask = setInterval(cleanExpiredNotExistingPoolsKeys.bind(this), BASESWAPV3_CLEAN_NOT_EXISTING_POOL_INTERVAL_MS);
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
async getPool(srcAddress, destAddress, fee, blockNumber) {
|
|
127
|
+
let pool = this.eventPools[this.getPoolIdentifier(srcAddress, destAddress, fee)];
|
|
128
|
+
if (pool === null)
|
|
129
|
+
return null;
|
|
130
|
+
if (pool) {
|
|
131
|
+
if (!pool.initFailed) {
|
|
132
|
+
return pool;
|
|
133
|
+
}
|
|
134
|
+
else {
|
|
135
|
+
// if init failed then prefer to early return pool with empty state to fallback to rpc call
|
|
136
|
+
if (++pool.initRetryAttemptCount % this.config.initRetryFrequency !==
|
|
137
|
+
0) {
|
|
138
|
+
return pool;
|
|
139
|
+
}
|
|
140
|
+
// else pursue with re-try initialization
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
const [token0, token1] = this._sortTokens(srcAddress, destAddress);
|
|
144
|
+
const key = `${token0}_${token1}_${fee}`.toLowerCase();
|
|
145
|
+
if (!pool) {
|
|
146
|
+
const notExistingPoolScore = await this.dexHelper.cache.zscore(this.notExistingPoolSetKey, key);
|
|
147
|
+
const poolDoesNotExist = notExistingPoolScore !== null;
|
|
148
|
+
if (poolDoesNotExist) {
|
|
149
|
+
this.eventPools[this.getPoolIdentifier(srcAddress, destAddress, fee)] =
|
|
150
|
+
null;
|
|
151
|
+
return null;
|
|
152
|
+
}
|
|
153
|
+
await this.dexHelper.cache.hset(this.dexmapKey, key, JSON.stringify({
|
|
154
|
+
token0,
|
|
155
|
+
token1,
|
|
156
|
+
fee: fee.toString(),
|
|
157
|
+
}));
|
|
158
|
+
}
|
|
159
|
+
this.logger.trace(`starting to listen to new pool: ${key}`);
|
|
160
|
+
const poolImplementation = this.config.eventPoolImplementation !== undefined
|
|
161
|
+
? this.config.eventPoolImplementation
|
|
162
|
+
: baseswap_v3_pool_1.BaseswapV3EventPool;
|
|
163
|
+
pool =
|
|
164
|
+
pool ||
|
|
165
|
+
new poolImplementation(this.dexHelper, this.dexKey, this.stateMultiContract, this.config.decodeStateMultiCallResultWithRelativeBitmaps, this.erc20Interface, this.config.factory, fee, token0, token1, this.logger, this.cacheStateKey, this.config.initHash);
|
|
166
|
+
try {
|
|
167
|
+
await pool.initialize(blockNumber, {
|
|
168
|
+
initCallback: (state) => {
|
|
169
|
+
//really hacky, we need to push poolAddress so that we subscribeToLogs in StatefulEventSubscriber
|
|
170
|
+
pool.addressesSubscribed[0] = state.pool;
|
|
171
|
+
pool.poolAddress = state.pool;
|
|
172
|
+
pool.initFailed = false;
|
|
173
|
+
pool.initRetryAttemptCount = 0;
|
|
174
|
+
},
|
|
175
|
+
});
|
|
176
|
+
}
|
|
177
|
+
catch (e) {
|
|
178
|
+
if (e instanceof Error && e.message.endsWith('Pool does not exist')) {
|
|
179
|
+
// no need to await we want the set to have the pool key but it's not blocking
|
|
180
|
+
this.dexHelper.cache.zadd(this.notExistingPoolSetKey, [Date.now(), key], 'NX');
|
|
181
|
+
// Pool does not exist for this feeCode, so we can set it to null
|
|
182
|
+
// to prevent more requests for this pool
|
|
183
|
+
pool = null;
|
|
184
|
+
this.logger.trace(`${this.dexHelper}: Pool: srcAddress=${srcAddress}, destAddress=${destAddress}, fee=${fee} not found`, e);
|
|
185
|
+
}
|
|
186
|
+
else {
|
|
187
|
+
// on unknown error mark as failed and increase retryCount for retry init strategy
|
|
188
|
+
// note: state would be null by default which allows to fallback
|
|
189
|
+
this.logger.warn(`${this.dexKey}: Can not generate pool state for srcAddress=${srcAddress}, destAddress=${destAddress}, fee=${fee} pool fallback to rpc and retry every ${this.config.initRetryFrequency} times, initRetryAttemptCount=${pool.initRetryAttemptCount}`, e);
|
|
190
|
+
pool.initFailed = true;
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
if (pool !== null) {
|
|
194
|
+
const allEventPools = Object.values(this.eventPools);
|
|
195
|
+
this.logger.info(`starting to listen to new non-null pool: ${key}. Already following ${allEventPools
|
|
196
|
+
// Not that I like this reduce, but since it is done only on initialization, expect this to be ok
|
|
197
|
+
.reduce((acc, curr) => (curr !== null ? ++acc : acc), 0)} non-null pools or ${allEventPools.length} total pools`);
|
|
198
|
+
}
|
|
199
|
+
this.eventPools[this.getPoolIdentifier(srcAddress, destAddress, fee)] =
|
|
200
|
+
pool;
|
|
201
|
+
return pool;
|
|
202
|
+
}
|
|
203
|
+
async addMasterPool(poolKey, blockNumber) {
|
|
204
|
+
const _pairs = await this.dexHelper.cache.hget(this.dexmapKey, poolKey);
|
|
205
|
+
if (!_pairs) {
|
|
206
|
+
this.logger.warn(`did not find poolConfig in for key ${this.dexmapKey} ${poolKey}`);
|
|
207
|
+
return false;
|
|
208
|
+
}
|
|
209
|
+
const poolInfo = JSON.parse(_pairs);
|
|
210
|
+
const pool = await this.getPool(poolInfo.token0, poolInfo.token1, BigInt(poolInfo.fee), blockNumber);
|
|
211
|
+
if (!pool) {
|
|
212
|
+
return false;
|
|
213
|
+
}
|
|
214
|
+
return true;
|
|
215
|
+
}
|
|
216
|
+
async getPoolIdentifiers(srcToken, destToken, side, blockNumber) {
|
|
217
|
+
const _srcToken = this.dexHelper.config.wrapETH(srcToken);
|
|
218
|
+
const _destToken = this.dexHelper.config.wrapETH(destToken);
|
|
219
|
+
const [_srcAddress, _destAddress] = this._getLoweredAddresses(_srcToken, _destToken);
|
|
220
|
+
if (_srcAddress === _destAddress)
|
|
221
|
+
return [];
|
|
222
|
+
const pools = (await Promise.all(this.supportedFees.map(async (fee) => this.getPool(_srcAddress, _destAddress, fee, blockNumber)))).filter(pool => pool);
|
|
223
|
+
if (pools.length === 0)
|
|
224
|
+
return [];
|
|
225
|
+
return pools.map(pool => this.getPoolIdentifier(_srcAddress, _destAddress, pool.feeCode));
|
|
226
|
+
}
|
|
227
|
+
async getPricingFromRpc(from, to, amounts, side, pools, states) {
|
|
228
|
+
if (pools.length === 0) {
|
|
229
|
+
return null;
|
|
230
|
+
}
|
|
231
|
+
this.logger.warn(`fallback to rpc for ${pools.length} pool(s)`);
|
|
232
|
+
const requests = pools.map(pool => ({
|
|
233
|
+
owner: pool.poolAddress,
|
|
234
|
+
asset: side == constants_1.SwapSide.SELL ? from.address : to.address,
|
|
235
|
+
assetType: types_2.AssetType.ERC20,
|
|
236
|
+
ids: [
|
|
237
|
+
{
|
|
238
|
+
id: types_2.DEFAULT_ID_ERC20,
|
|
239
|
+
spenders: [],
|
|
240
|
+
},
|
|
241
|
+
],
|
|
242
|
+
}), []);
|
|
243
|
+
const balances = await (0, balancer_fetcher_1.getBalances)(this.dexHelper.multiWrapper, requests);
|
|
244
|
+
pools = pools.filter((pool, index) => {
|
|
245
|
+
const balance = balances[index].amounts[types_2.DEFAULT_ID_ERC20_AS_STRING];
|
|
246
|
+
if (balance >= amounts[amounts.length - 1]) {
|
|
247
|
+
return true;
|
|
248
|
+
}
|
|
249
|
+
this.logger.warn(`[${this.network}][${pool.parentName}] have no balance ${pool.poolAddress} ${from.address} ${to.address}. (Balance: ${balance})`);
|
|
250
|
+
return false;
|
|
251
|
+
});
|
|
252
|
+
pools.forEach(pool => {
|
|
253
|
+
this.logger.warn(`[${this.network}][${pool.parentName}] fallback to rpc for ${pool.name}`);
|
|
254
|
+
});
|
|
255
|
+
const unitVolume = (0, utils_1.getBigIntPow)((side === constants_1.SwapSide.SELL ? from : to).decimals);
|
|
256
|
+
const chunks = amounts.length - 1;
|
|
257
|
+
const _width = Math.floor(chunks / this.config.chunksCount);
|
|
258
|
+
const _amounts = [unitVolume].concat(Array.from(Array(this.config.chunksCount).keys()).map(i => amounts[(i + 1) * _width]));
|
|
259
|
+
const calldata = pools.map(pool => _amounts.map(_amount => ({
|
|
260
|
+
target: this.config.quoter,
|
|
261
|
+
gasLimit: BASESWAPV3_QUOTE_GASLIMIT,
|
|
262
|
+
callData: side === constants_1.SwapSide.SELL
|
|
263
|
+
? this.quoterIface.encodeFunctionData('quoteExactInputSingle', [
|
|
264
|
+
[
|
|
265
|
+
from.address,
|
|
266
|
+
to.address,
|
|
267
|
+
_amount.toString(),
|
|
268
|
+
pool.feeCodeAsString,
|
|
269
|
+
0, //sqrtPriceLimitX96
|
|
270
|
+
],
|
|
271
|
+
])
|
|
272
|
+
: this.quoterIface.encodeFunctionData('quoteExactOutputSingle', [
|
|
273
|
+
[
|
|
274
|
+
from.address,
|
|
275
|
+
to.address,
|
|
276
|
+
_amount.toString(),
|
|
277
|
+
pool.feeCodeAsString,
|
|
278
|
+
0, //sqrtPriceLimitX96
|
|
279
|
+
],
|
|
280
|
+
]),
|
|
281
|
+
})));
|
|
282
|
+
const data = await this.uniswapMulti.methods
|
|
283
|
+
.multicall(calldata.flat())
|
|
284
|
+
.call();
|
|
285
|
+
const decode = (j) => {
|
|
286
|
+
if (!data.returnData[j].success) {
|
|
287
|
+
return 0n;
|
|
288
|
+
}
|
|
289
|
+
const decoded = abi_1.defaultAbiCoder.decode(['uint256'], data.returnData[j].returnData);
|
|
290
|
+
return BigInt(decoded[0].toString());
|
|
291
|
+
};
|
|
292
|
+
let i = 0;
|
|
293
|
+
const result = pools.map((pool, index) => {
|
|
294
|
+
const _rates = _amounts.map(() => decode(i++));
|
|
295
|
+
const unit = _rates[0];
|
|
296
|
+
const prices = (0, utils_1.interpolate)(_amounts.slice(1), _rates.slice(1), amounts, side);
|
|
297
|
+
return {
|
|
298
|
+
prices,
|
|
299
|
+
unit,
|
|
300
|
+
data: {
|
|
301
|
+
path: [
|
|
302
|
+
{
|
|
303
|
+
tokenIn: from.address,
|
|
304
|
+
tokenOut: to.address,
|
|
305
|
+
fee: pool.feeCodeAsString,
|
|
306
|
+
currentFee: states[index].fee.toString(),
|
|
307
|
+
},
|
|
308
|
+
],
|
|
309
|
+
exchange: pool.poolAddress,
|
|
310
|
+
},
|
|
311
|
+
poolIdentifier: this.getPoolIdentifier(pool.token0, pool.token1, pool.feeCode),
|
|
312
|
+
exchange: this.dexKey,
|
|
313
|
+
gasCost: prices.map(p => (p === 0n ? 0 : BASESWAPV3_QUOTE_GASLIMIT)),
|
|
314
|
+
poolAddresses: [pool.poolAddress],
|
|
315
|
+
};
|
|
316
|
+
});
|
|
317
|
+
return result;
|
|
318
|
+
}
|
|
319
|
+
async getPricesVolume(srcToken, destToken, amounts, side, blockNumber, limitPools) {
|
|
320
|
+
try {
|
|
321
|
+
const _srcToken = this.dexHelper.config.wrapETH(srcToken);
|
|
322
|
+
const _destToken = this.dexHelper.config.wrapETH(destToken);
|
|
323
|
+
const [_srcAddress, _destAddress] = this._getLoweredAddresses(_srcToken, _destToken);
|
|
324
|
+
if (_srcAddress === _destAddress)
|
|
325
|
+
return null;
|
|
326
|
+
let selectedPools = [];
|
|
327
|
+
if (!limitPools) {
|
|
328
|
+
selectedPools = (await Promise.all(this.supportedFees.map(async (fee) => {
|
|
329
|
+
const locallyFoundPool = this.eventPools[this.getPoolIdentifier(_srcAddress, _destAddress, fee)];
|
|
330
|
+
if (locallyFoundPool)
|
|
331
|
+
return locallyFoundPool;
|
|
332
|
+
const newlyFetchedPool = await this.getPool(_srcAddress, _destAddress, fee, blockNumber);
|
|
333
|
+
return newlyFetchedPool;
|
|
334
|
+
}))).filter(utils_1.isTruthy);
|
|
335
|
+
}
|
|
336
|
+
else {
|
|
337
|
+
const pairIdentifierWithoutFee = this.getPoolIdentifier(_srcAddress, _destAddress, 0n).slice(0, -1);
|
|
338
|
+
const poolIdentifiers = limitPools.filter(identifier => identifier.startsWith(pairIdentifierWithoutFee));
|
|
339
|
+
selectedPools = (await Promise.all(poolIdentifiers.map(async (identifier) => {
|
|
340
|
+
let locallyFoundPool = this.eventPools[identifier];
|
|
341
|
+
if (locallyFoundPool)
|
|
342
|
+
return locallyFoundPool;
|
|
343
|
+
const [, srcAddress, destAddress, fee] = identifier.split('_');
|
|
344
|
+
const newlyFetchedPool = await this.getPool(srcAddress, destAddress, BigInt(fee), blockNumber);
|
|
345
|
+
return newlyFetchedPool;
|
|
346
|
+
}))).filter(utils_1.isTruthy);
|
|
347
|
+
}
|
|
348
|
+
if (selectedPools.length === 0)
|
|
349
|
+
return null;
|
|
350
|
+
const poolsToUse = selectedPools.reduce((acc, pool) => {
|
|
351
|
+
let state = pool.getState(blockNumber);
|
|
352
|
+
if (state === null) {
|
|
353
|
+
this.logger.trace(`${this.dexKey}: State === null. Fallback to rpc ${pool.name}`);
|
|
354
|
+
acc.poolWithoutState.push(pool);
|
|
355
|
+
}
|
|
356
|
+
else {
|
|
357
|
+
acc.poolWithState.push(pool);
|
|
358
|
+
}
|
|
359
|
+
return acc;
|
|
360
|
+
}, {
|
|
361
|
+
poolWithState: [],
|
|
362
|
+
poolWithoutState: [],
|
|
363
|
+
});
|
|
364
|
+
const states = poolsToUse.poolWithState.map(p => p.getState(blockNumber));
|
|
365
|
+
const rpcResultsPromise = this.getPricingFromRpc(_srcToken, _destToken, amounts, side, this.network === constants_1.Network.ZKEVM ? [] : poolsToUse.poolWithoutState, this.network === constants_1.Network.ZKEVM ? [] : states);
|
|
366
|
+
const unitAmount = (0, utils_1.getBigIntPow)(side == constants_1.SwapSide.SELL ? _srcToken.decimals : _destToken.decimals);
|
|
367
|
+
const _amounts = [...amounts.slice(1)];
|
|
368
|
+
const [token0] = this._sortTokens(_srcAddress, _destAddress);
|
|
369
|
+
const zeroForOne = token0 === _srcAddress ? true : false;
|
|
370
|
+
const result = await Promise.all(poolsToUse.poolWithState.map(async (pool, i) => {
|
|
371
|
+
const state = states[i];
|
|
372
|
+
if (state.liquidity <= 0n) {
|
|
373
|
+
if (state.liquidity < 0) {
|
|
374
|
+
this.logger.error(`${this.dexKey}-${this.network}: ${pool.poolAddress} pool has negative liquidity: ${state.liquidity}. Find with key: ${pool.mapKey}`);
|
|
375
|
+
}
|
|
376
|
+
this.logger.trace(`pool have 0 liquidity`);
|
|
377
|
+
return null;
|
|
378
|
+
}
|
|
379
|
+
const balanceDestToken = _destAddress === pool.token0 ? state.balance0 : state.balance1;
|
|
380
|
+
const unitResult = this._getOutputs(state, [unitAmount], zeroForOne, side, balanceDestToken);
|
|
381
|
+
const pricesResult = this._getOutputs(state, _amounts, zeroForOne, side, balanceDestToken);
|
|
382
|
+
if (!unitResult || !pricesResult) {
|
|
383
|
+
this.logger.debug('Prices or unit is not calculated');
|
|
384
|
+
return null;
|
|
385
|
+
}
|
|
386
|
+
const prices = [0n, ...pricesResult.outputs];
|
|
387
|
+
const gasCost = [
|
|
388
|
+
0,
|
|
389
|
+
...pricesResult.outputs.map((p, index) => {
|
|
390
|
+
if (p == 0n) {
|
|
391
|
+
return 0;
|
|
392
|
+
}
|
|
393
|
+
else {
|
|
394
|
+
return (constants_2.UNISWAPV3_POOL_SEARCH_OVERHEAD +
|
|
395
|
+
constants_2.UNISWAPV3_TICK_BASE_OVERHEAD +
|
|
396
|
+
pricesResult.tickCounts[index] * constants_2.UNISWAPV3_TICK_GAS_COST);
|
|
397
|
+
}
|
|
398
|
+
}),
|
|
399
|
+
];
|
|
400
|
+
return {
|
|
401
|
+
unit: unitResult.outputs[0],
|
|
402
|
+
prices,
|
|
403
|
+
data: {
|
|
404
|
+
path: [
|
|
405
|
+
{
|
|
406
|
+
tokenIn: _srcAddress,
|
|
407
|
+
tokenOut: _destAddress,
|
|
408
|
+
fee: pool.feeCode.toString(),
|
|
409
|
+
currentFee: state.fee.toString(),
|
|
410
|
+
},
|
|
411
|
+
],
|
|
412
|
+
},
|
|
413
|
+
poolIdentifier: this.getPoolIdentifier(pool.token0, pool.token1, pool.feeCode),
|
|
414
|
+
exchange: this.dexKey,
|
|
415
|
+
gasCost: gasCost,
|
|
416
|
+
poolAddresses: [pool.poolAddress],
|
|
417
|
+
};
|
|
418
|
+
}));
|
|
419
|
+
const rpcResults = await rpcResultsPromise;
|
|
420
|
+
const notNullResult = result.filter(res => res !== null);
|
|
421
|
+
if (rpcResults) {
|
|
422
|
+
rpcResults.forEach(r => {
|
|
423
|
+
if (r) {
|
|
424
|
+
notNullResult.push(r);
|
|
425
|
+
}
|
|
426
|
+
});
|
|
427
|
+
}
|
|
428
|
+
return notNullResult;
|
|
429
|
+
}
|
|
430
|
+
catch (e) {
|
|
431
|
+
this.logger.error(`Error_getPricesVolume ${srcToken.symbol || srcToken.address}, ${destToken.symbol || destToken.address}, ${side}:`, e);
|
|
432
|
+
return null;
|
|
433
|
+
}
|
|
434
|
+
}
|
|
435
|
+
getAdapterParam(srcToken, destToken, srcAmount, destAmount, data, side) {
|
|
436
|
+
const { path: rawPath } = data;
|
|
437
|
+
const path = this._encodePath(rawPath, side);
|
|
438
|
+
const payload = this.abiCoder.encodeParameter({
|
|
439
|
+
ParentStruct: {
|
|
440
|
+
path: 'bytes',
|
|
441
|
+
deadline: 'uint256',
|
|
442
|
+
},
|
|
443
|
+
}, {
|
|
444
|
+
path,
|
|
445
|
+
deadline: (0, simple_exchange_1.getLocalDeadlineAsFriendlyPlaceholder)(), // FIXME: more gas efficient to pass block.timestamp in adapter
|
|
446
|
+
});
|
|
447
|
+
return {
|
|
448
|
+
targetExchange: this.config.router,
|
|
449
|
+
payload,
|
|
450
|
+
networkFee: '0',
|
|
451
|
+
};
|
|
452
|
+
}
|
|
453
|
+
getCalldataGasCost(poolPrices) {
|
|
454
|
+
const gasCost = CALLDATA_GAS_COST.DEX_OVERHEAD +
|
|
455
|
+
CALLDATA_GAS_COST.LENGTH_SMALL +
|
|
456
|
+
// ParentStruct header
|
|
457
|
+
CALLDATA_GAS_COST.OFFSET_SMALL +
|
|
458
|
+
// ParentStruct -> path header
|
|
459
|
+
CALLDATA_GAS_COST.OFFSET_SMALL +
|
|
460
|
+
// ParentStruct -> deadline
|
|
461
|
+
CALLDATA_GAS_COST.TIMESTAMP +
|
|
462
|
+
// ParentStruct -> path (20+3+20 = 43 = 32+11 bytes)
|
|
463
|
+
CALLDATA_GAS_COST.LENGTH_SMALL +
|
|
464
|
+
CALLDATA_GAS_COST.FULL_WORD +
|
|
465
|
+
CALLDATA_GAS_COST.wordNonZeroBytes(11);
|
|
466
|
+
const arr = new Array(poolPrices.prices.length);
|
|
467
|
+
poolPrices.prices.forEach((p, index) => {
|
|
468
|
+
if (p == 0n) {
|
|
469
|
+
arr[index] = 0;
|
|
470
|
+
}
|
|
471
|
+
else {
|
|
472
|
+
arr[index] = gasCost;
|
|
473
|
+
}
|
|
474
|
+
});
|
|
475
|
+
return arr;
|
|
476
|
+
}
|
|
477
|
+
getTokenFromAddress(address) {
|
|
478
|
+
// In this Dex decimals are not used
|
|
479
|
+
return { address, decimals: 0 };
|
|
480
|
+
}
|
|
481
|
+
async preProcessTransaction(optimalSwapExchange, srcToken, _0, _1, options) {
|
|
482
|
+
if (!options.isDirectMethod) {
|
|
483
|
+
return [
|
|
484
|
+
optimalSwapExchange,
|
|
485
|
+
{
|
|
486
|
+
deadline: BigInt((0, simple_exchange_1.getLocalDeadlineAsFriendlyPlaceholder)()),
|
|
487
|
+
},
|
|
488
|
+
];
|
|
489
|
+
}
|
|
490
|
+
(0, ts_essentials_1.assert)(optimalSwapExchange.data !== undefined, `preProcessTransaction: data field is missing`);
|
|
491
|
+
let isApproved;
|
|
492
|
+
try {
|
|
493
|
+
this.erc20Contract.options.address =
|
|
494
|
+
this.dexHelper.config.wrapETH(srcToken).address;
|
|
495
|
+
const allowance = await this.erc20Contract.methods
|
|
496
|
+
.allowance(this.augustusAddress, this.config.router)
|
|
497
|
+
.call(undefined, 'latest');
|
|
498
|
+
isApproved =
|
|
499
|
+
BigInt(allowance.toString()) >= BigInt(optimalSwapExchange.srcAmount);
|
|
500
|
+
}
|
|
501
|
+
catch (e) {
|
|
502
|
+
this.logger.error(`preProcessTransaction failed to retrieve allowance info: `, e);
|
|
503
|
+
}
|
|
504
|
+
return [
|
|
505
|
+
{
|
|
506
|
+
...optimalSwapExchange,
|
|
507
|
+
data: {
|
|
508
|
+
...optimalSwapExchange.data,
|
|
509
|
+
isApproved,
|
|
510
|
+
},
|
|
511
|
+
},
|
|
512
|
+
{
|
|
513
|
+
deadline: BigInt((0, simple_exchange_1.getLocalDeadlineAsFriendlyPlaceholder)()),
|
|
514
|
+
},
|
|
515
|
+
];
|
|
516
|
+
}
|
|
517
|
+
getDirectParam(srcToken, destToken, srcAmount, destAmount, expectedAmount, data, side, permit, uuid, feePercent, deadline, partner, beneficiary, contractMethod) {
|
|
518
|
+
if (contractMethod !== constants_2.DirectMethods.directSell &&
|
|
519
|
+
contractMethod !== constants_2.DirectMethods.directBuy) {
|
|
520
|
+
throw new Error(`Invalid contract method ${contractMethod}`);
|
|
521
|
+
}
|
|
522
|
+
let isApproved = !!data.isApproved;
|
|
523
|
+
if (data.isApproved === undefined) {
|
|
524
|
+
this.logger.warn(`isApproved is undefined, defaulting to false`);
|
|
525
|
+
}
|
|
526
|
+
const path = this._encodePath(data.path, side);
|
|
527
|
+
const swapParams = [
|
|
528
|
+
srcToken,
|
|
529
|
+
destToken,
|
|
530
|
+
this.config.router,
|
|
531
|
+
srcAmount,
|
|
532
|
+
destAmount,
|
|
533
|
+
expectedAmount,
|
|
534
|
+
feePercent,
|
|
535
|
+
deadline,
|
|
536
|
+
partner,
|
|
537
|
+
isApproved,
|
|
538
|
+
beneficiary,
|
|
539
|
+
path,
|
|
540
|
+
permit,
|
|
541
|
+
(0, utils_1.uuidToBytes16)(uuid),
|
|
542
|
+
];
|
|
543
|
+
const encoder = (...params) => {
|
|
544
|
+
return this.directSwapIface.encodeFunctionData(side === constants_1.SwapSide.SELL
|
|
545
|
+
? constants_2.DirectMethods.directSell
|
|
546
|
+
: constants_2.DirectMethods.directBuy, [params]);
|
|
547
|
+
};
|
|
548
|
+
return {
|
|
549
|
+
params: swapParams,
|
|
550
|
+
encoder,
|
|
551
|
+
networkFee: '0',
|
|
552
|
+
};
|
|
553
|
+
}
|
|
554
|
+
static getDirectFunctionName() {
|
|
555
|
+
return [constants_2.DirectMethods.directSell, constants_2.DirectMethods.directBuy];
|
|
556
|
+
}
|
|
557
|
+
async getSimpleParam(srcToken, destToken, srcAmount, destAmount, data, side) {
|
|
558
|
+
const swapFunction = side === constants_1.SwapSide.SELL
|
|
559
|
+
? types_1.UniswapV3Functions.exactInput
|
|
560
|
+
: types_1.UniswapV3Functions.exactOutput;
|
|
561
|
+
const path = this._encodePath(data.path, side);
|
|
562
|
+
const swapFunctionParams = side === constants_1.SwapSide.SELL
|
|
563
|
+
? {
|
|
564
|
+
recipient: this.augustusAddress,
|
|
565
|
+
deadline: (0, simple_exchange_1.getLocalDeadlineAsFriendlyPlaceholder)(),
|
|
566
|
+
amountIn: srcAmount,
|
|
567
|
+
amountOutMinimum: destAmount,
|
|
568
|
+
path,
|
|
569
|
+
}
|
|
570
|
+
: {
|
|
571
|
+
recipient: this.augustusAddress,
|
|
572
|
+
deadline: (0, simple_exchange_1.getLocalDeadlineAsFriendlyPlaceholder)(),
|
|
573
|
+
amountOut: destAmount,
|
|
574
|
+
amountInMaximum: srcAmount,
|
|
575
|
+
path,
|
|
576
|
+
};
|
|
577
|
+
const swapData = this.routerIface.encodeFunctionData(swapFunction, [
|
|
578
|
+
swapFunctionParams,
|
|
579
|
+
]);
|
|
580
|
+
return this.buildSimpleParamWithoutWETHConversion(srcToken, srcAmount, destToken, destAmount, swapData, this.config.router);
|
|
581
|
+
}
|
|
582
|
+
async getTopPoolsForToken(tokenAddress, limit) {
|
|
583
|
+
const _tokenAddress = tokenAddress.toLowerCase();
|
|
584
|
+
const res = await this._querySubgraph(`query ($token: Bytes!, $count: Int) {
|
|
585
|
+
pools0: pools(first: $count, orderBy: totalValueLockedUSD, orderDirection: desc, where: {token0: $token}) {
|
|
586
|
+
id
|
|
587
|
+
token0 {
|
|
588
|
+
id
|
|
589
|
+
decimals
|
|
590
|
+
}
|
|
591
|
+
token1 {
|
|
592
|
+
id
|
|
593
|
+
decimals
|
|
594
|
+
}
|
|
595
|
+
totalValueLockedUSD
|
|
596
|
+
}
|
|
597
|
+
pools1: pools(first: $count, orderBy: totalValueLockedUSD, orderDirection: desc, where: {token1: $token}) {
|
|
598
|
+
id
|
|
599
|
+
token0 {
|
|
600
|
+
id
|
|
601
|
+
decimals
|
|
602
|
+
}
|
|
603
|
+
token1 {
|
|
604
|
+
id
|
|
605
|
+
decimals
|
|
606
|
+
}
|
|
607
|
+
totalValueLockedUSD
|
|
608
|
+
}
|
|
609
|
+
}`, {
|
|
610
|
+
token: _tokenAddress,
|
|
611
|
+
count: limit,
|
|
612
|
+
});
|
|
613
|
+
if (!(res && res.pools0 && res.pools1)) {
|
|
614
|
+
this.logger.error(`Error_${this.dexKey}_Subgraph: couldn't fetch the pools from the subgraph`);
|
|
615
|
+
return [];
|
|
616
|
+
}
|
|
617
|
+
const pools0 = lodash_1.default.map(res.pools0, pool => ({
|
|
618
|
+
exchange: this.dexKey,
|
|
619
|
+
address: pool.id.toLowerCase(),
|
|
620
|
+
connectorTokens: [
|
|
621
|
+
{
|
|
622
|
+
address: pool.token1.id.toLowerCase(),
|
|
623
|
+
decimals: parseInt(pool.token1.decimals),
|
|
624
|
+
},
|
|
625
|
+
],
|
|
626
|
+
liquidityUSD: parseFloat(pool.totalValueLockedUSD) * constants_2.UNISWAPV3_EFFICIENCY_FACTOR,
|
|
627
|
+
}));
|
|
628
|
+
const pools1 = lodash_1.default.map(res.pools1, pool => ({
|
|
629
|
+
exchange: this.dexKey,
|
|
630
|
+
address: pool.id.toLowerCase(),
|
|
631
|
+
connectorTokens: [
|
|
632
|
+
{
|
|
633
|
+
address: pool.token0.id.toLowerCase(),
|
|
634
|
+
decimals: parseInt(pool.token0.decimals),
|
|
635
|
+
},
|
|
636
|
+
],
|
|
637
|
+
liquidityUSD: parseFloat(pool.totalValueLockedUSD) * constants_2.UNISWAPV3_EFFICIENCY_FACTOR,
|
|
638
|
+
}));
|
|
639
|
+
const pools = lodash_1.default.slice(lodash_1.default.sortBy(lodash_1.default.concat(pools0, pools1), [pool => -1 * pool.liquidityUSD]), 0, limit);
|
|
640
|
+
return pools;
|
|
641
|
+
}
|
|
642
|
+
async _getPoolsFromIdentifiers(poolIdentifiers, blockNumber) {
|
|
643
|
+
const pools = await Promise.all(poolIdentifiers.map(async (identifier) => {
|
|
644
|
+
const [, srcAddress, destAddress, fee] = identifier.split('_');
|
|
645
|
+
return this.getPool(srcAddress, destAddress, BigInt(fee), blockNumber);
|
|
646
|
+
}));
|
|
647
|
+
return pools.filter(pool => pool);
|
|
648
|
+
}
|
|
649
|
+
_getLoweredAddresses(srcToken, destToken) {
|
|
650
|
+
return [srcToken.address.toLowerCase(), destToken.address.toLowerCase()];
|
|
651
|
+
}
|
|
652
|
+
_sortTokens(srcAddress, destAddress) {
|
|
653
|
+
return [srcAddress, destAddress].sort((a, b) => (a < b ? -1 : 1));
|
|
654
|
+
}
|
|
655
|
+
_toLowerForAllConfigAddresses() {
|
|
656
|
+
// If new config property will be added, the TS will throw compile error
|
|
657
|
+
const newConfig = {
|
|
658
|
+
router: this.config.router.toLowerCase(),
|
|
659
|
+
quoter: this.config.quoter.toLowerCase(),
|
|
660
|
+
factory: this.config.factory.toLowerCase(),
|
|
661
|
+
supportedFees: this.config.supportedFees,
|
|
662
|
+
stateMulticall: this.config.stateMulticall.toLowerCase(),
|
|
663
|
+
chunksCount: this.config.chunksCount,
|
|
664
|
+
initRetryFrequency: this.config.initRetryFrequency,
|
|
665
|
+
uniswapMulticall: this.config.uniswapMulticall,
|
|
666
|
+
deployer: this.config.deployer?.toLowerCase(),
|
|
667
|
+
initHash: this.config.initHash,
|
|
668
|
+
subgraphURL: this.config.subgraphURL,
|
|
669
|
+
stateMultiCallAbi: this.config.stateMultiCallAbi,
|
|
670
|
+
eventPoolImplementation: this.config.eventPoolImplementation,
|
|
671
|
+
decodeStateMultiCallResultWithRelativeBitmaps: this.config.decodeStateMultiCallResultWithRelativeBitmaps,
|
|
672
|
+
};
|
|
673
|
+
return newConfig;
|
|
674
|
+
}
|
|
675
|
+
_getOutputs(state, amounts, zeroForOne, side, destTokenBalance) {
|
|
676
|
+
try {
|
|
677
|
+
const outputsResult = uniswap_v3_math_1.uniswapV3Math.queryOutputs(state, amounts, zeroForOne, side);
|
|
678
|
+
if (side === constants_1.SwapSide.SELL) {
|
|
679
|
+
if (outputsResult.outputs[0] > destTokenBalance) {
|
|
680
|
+
return null;
|
|
681
|
+
}
|
|
682
|
+
for (let i = 0; i < outputsResult.outputs.length; i++) {
|
|
683
|
+
if (outputsResult.outputs[i] > destTokenBalance) {
|
|
684
|
+
outputsResult.outputs[i] = 0n;
|
|
685
|
+
outputsResult.tickCounts[i] = 0;
|
|
686
|
+
}
|
|
687
|
+
}
|
|
688
|
+
}
|
|
689
|
+
else {
|
|
690
|
+
if (amounts[0] > destTokenBalance) {
|
|
691
|
+
return null;
|
|
692
|
+
}
|
|
693
|
+
// This may be improved by first checking outputs and requesting outputs
|
|
694
|
+
// only for amounts that makes more sense, but I don't think this is really
|
|
695
|
+
// important now
|
|
696
|
+
for (let i = 0; i < amounts.length; i++) {
|
|
697
|
+
if (amounts[i] > destTokenBalance) {
|
|
698
|
+
outputsResult.outputs[i] = 0n;
|
|
699
|
+
outputsResult.tickCounts[i] = 0;
|
|
700
|
+
}
|
|
701
|
+
}
|
|
702
|
+
}
|
|
703
|
+
return outputsResult;
|
|
704
|
+
}
|
|
705
|
+
catch (e) {
|
|
706
|
+
this.logger.debug(`${this.dexKey}: received error in _getOutputs while calculating outputs`, e);
|
|
707
|
+
return null;
|
|
708
|
+
}
|
|
709
|
+
}
|
|
710
|
+
async _querySubgraph(query, variables, timeout = 30000) {
|
|
711
|
+
try {
|
|
712
|
+
const res = await this.dexHelper.httpRequest.post(this.config.subgraphURL, { query, variables }, undefined, { timeout: timeout });
|
|
713
|
+
return res.data;
|
|
714
|
+
}
|
|
715
|
+
catch (e) {
|
|
716
|
+
this.logger.error(`${this.dexKey}: can not query subgraph: `, e);
|
|
717
|
+
return {};
|
|
718
|
+
}
|
|
719
|
+
}
|
|
720
|
+
_encodePath(path, side) {
|
|
721
|
+
if (path.length === 0) {
|
|
722
|
+
this.logger.error(`${this.dexKey}: Received invalid path=${path} for side=${side} to encode`);
|
|
723
|
+
return '0x';
|
|
724
|
+
}
|
|
725
|
+
const { _path, types } = path.reduce(({ _path, types }, curr, index) => {
|
|
726
|
+
if (index === 0) {
|
|
727
|
+
return {
|
|
728
|
+
types: ['address', 'uint24', 'address'],
|
|
729
|
+
_path: [curr.tokenIn, curr.fee, curr.tokenOut],
|
|
730
|
+
};
|
|
731
|
+
}
|
|
732
|
+
else {
|
|
733
|
+
return {
|
|
734
|
+
types: [...types, 'uint24', 'address'],
|
|
735
|
+
_path: [..._path, curr.fee, curr.tokenOut],
|
|
736
|
+
};
|
|
737
|
+
}
|
|
738
|
+
}, { _path: [], types: [] });
|
|
739
|
+
return side === constants_1.SwapSide.BUY
|
|
740
|
+
? (0, solidity_1.pack)(types.reverse(), _path.reverse())
|
|
741
|
+
: (0, solidity_1.pack)(types, _path);
|
|
742
|
+
}
|
|
743
|
+
releaseResources() {
|
|
744
|
+
if (this.intervalTask !== undefined) {
|
|
745
|
+
clearInterval(this.intervalTask);
|
|
746
|
+
this.intervalTask = undefined;
|
|
747
|
+
}
|
|
748
|
+
}
|
|
749
|
+
}
|
|
750
|
+
exports.BaseswapV3 = BaseswapV3;
|
|
751
|
+
BaseswapV3.dexKeysWithNetwork = (0, utils_1.getDexKeysWithNetwork)(lodash_1.default.pick(config_1.BaseswapV3Config, ['BaseswapV3']));
|
|
752
|
+
//# sourceMappingURL=baseswap-v3.js.map
|