@paraswap/dex-lib 3.11.5-fluid-dex-changes.2 → 3.11.5

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.
Files changed (196) hide show
  1. package/.vscode/launch.json +53 -0
  2. package/.vscode/settings.json +2 -0
  3. package/.vscode/tasks.json +15 -0
  4. package/build/abi/fluid-dex/resolver.abi.json +4 -731
  5. package/build/abi/{cables/CablesMainnetRFQ.json → inception/inception-ineth-pool.json} +489 -510
  6. package/build/abi/inception/inception-ratio-feed.json +329 -0
  7. package/build/abi/inception/inception-vault.json +991 -0
  8. package/build/abi/uniswap-v3/AlienBaseV3Router.abi.json +52 -0
  9. package/build/abi/{integral/relayer.json → wombat/pool.json} +474 -721
  10. package/build/dex/aave-v1/aave-v1.d.ts +2 -1
  11. package/build/dex/aave-v1/aave-v1.js +23 -0
  12. package/build/dex/aave-v1/aave-v1.js.map +1 -1
  13. package/build/dex/aave-v2/tokens-avalanche.json +44 -0
  14. package/build/dex/aave-v2/tokens-mainnet.json +188 -0
  15. package/build/dex/aave-v2/tokens-polygon.json +44 -0
  16. package/build/dex/algebra/algebra.js +10 -18
  17. package/build/dex/algebra/algebra.js.map +1 -1
  18. package/build/dex/algebra/config.js +1 -1
  19. package/build/dex/algebra/config.js.map +1 -1
  20. package/build/dex/balancer-v3/abi/balancerBatchRouter.d.ts +729 -0
  21. package/build/dex/balancer-v3/abi/balancerBatchRouter.js +732 -0
  22. package/build/dex/balancer-v3/abi/balancerBatchRouter.js.map +1 -0
  23. package/build/dex/balancer-v3/abi/balancerRouter.d.ts +1406 -0
  24. package/build/dex/balancer-v3/abi/balancerRouter.js +1175 -0
  25. package/build/dex/balancer-v3/abi/balancerRouter.js.map +1 -0
  26. package/build/dex/balancer-v3/abi/vaultExtension.V3.d.ts +2081 -0
  27. package/build/dex/balancer-v3/abi/vaultExtension.V3.js +1851 -0
  28. package/build/dex/balancer-v3/abi/vaultExtension.V3.js.map +1 -0
  29. package/build/dex/balancer-v3/balancer-v3-pool.d.ts +76 -0
  30. package/build/dex/balancer-v3/balancer-v3-pool.js +383 -0
  31. package/build/dex/balancer-v3/balancer-v3-pool.js.map +1 -0
  32. package/build/dex/balancer-v3/balancer-v3.d.ts +57 -0
  33. package/build/dex/balancer-v3/balancer-v3.js +373 -0
  34. package/build/dex/balancer-v3/balancer-v3.js.map +1 -0
  35. package/build/dex/balancer-v3/config.d.ts +8 -0
  36. package/build/dex/balancer-v3/config.js +24 -0
  37. package/build/dex/balancer-v3/config.js.map +1 -0
  38. package/build/dex/balancer-v3/getOnChainState.d.ts +10 -0
  39. package/build/dex/balancer-v3/getOnChainState.js +158 -0
  40. package/build/dex/balancer-v3/getOnChainState.js.map +1 -0
  41. package/build/dex/balancer-v3/getPoolsApi.d.ts +2 -0
  42. package/build/dex/balancer-v3/getPoolsApi.js +81 -0
  43. package/build/dex/balancer-v3/getPoolsApi.js.map +1 -0
  44. package/build/dex/balancer-v3/getTopPoolsApi.d.ts +13 -0
  45. package/build/dex/balancer-v3/getTopPoolsApi.js +62 -0
  46. package/build/dex/balancer-v3/getTopPoolsApi.js.map +1 -0
  47. package/build/dex/balancer-v3/types.d.ts +63 -0
  48. package/build/dex/balancer-v3/types.js +3 -0
  49. package/build/dex/balancer-v3/types.js.map +1 -0
  50. package/build/dex/fluid-dex/config.js +1 -1
  51. package/build/dex/fluid-dex/fluid-dex-liquidity-proxy.js +1 -28
  52. package/build/dex/fluid-dex/fluid-dex-liquidity-proxy.js.map +1 -1
  53. package/build/dex/fluid-dex/fluid-dex.d.ts +10 -17
  54. package/build/dex/fluid-dex/fluid-dex.js +67 -219
  55. package/build/dex/fluid-dex/fluid-dex.js.map +1 -1
  56. package/build/dex/fluid-dex/types.d.ts +2 -22
  57. package/build/dex/inception/config.d.ts +4 -0
  58. package/build/dex/inception/config.js +109 -0
  59. package/build/dex/inception/config.js.map +1 -0
  60. package/build/dex/inception/inception-event-pool.d.ts +16 -0
  61. package/build/dex/inception/inception-event-pool.js +49 -0
  62. package/build/dex/inception/inception-event-pool.js.map +1 -0
  63. package/build/dex/inception/inception.d.ts +43 -0
  64. package/build/dex/inception/inception.js +180 -0
  65. package/build/dex/inception/inception.js.map +1 -0
  66. package/build/dex/inception/tokens.d.ts +9 -0
  67. package/build/dex/inception/tokens.js +28 -0
  68. package/build/dex/inception/tokens.js.map +1 -0
  69. package/build/dex/inception/types.d.ts +22 -0
  70. package/build/dex/inception/types.js +3 -0
  71. package/build/dex/inception/types.js.map +1 -0
  72. package/build/dex/inception/utils.d.ts +7 -0
  73. package/build/dex/inception/utils.js +58 -0
  74. package/build/dex/inception/utils.js.map +1 -0
  75. package/build/dex/jarvis.d.ts +2 -1
  76. package/build/dex/jarvis.js +58 -0
  77. package/build/dex/jarvis.js.map +1 -1
  78. package/build/dex/maker-psm/scripts/gem.abi.json +136 -0
  79. package/build/dex/maker-psm/scripts/validate-state.d.ts +0 -0
  80. package/build/dex/maker-psm/scripts/validate-state.js +185 -0
  81. package/build/dex/maker-psm/scripts/validate-state.js.map +1 -0
  82. package/build/dex/maker-psm/scripts/vat.abi.json +243 -0
  83. package/build/dex/platypus/platypus.d.ts +2 -1
  84. package/build/dex/platypus/platypus.js +45 -0
  85. package/build/dex/platypus/platypus.js.map +1 -1
  86. package/build/dex/solidly-v3/scripts/check-event-pool-event.d.ts +1 -0
  87. package/build/dex/solidly-v3/scripts/check-event-pool-event.js +53 -0
  88. package/build/dex/solidly-v3/scripts/check-event-pool-event.js.map +1 -0
  89. package/build/dex/stable-pool.js +1 -8
  90. package/build/dex/stable-pool.js.map +1 -1
  91. package/build/dex/swaap-v1/swaap-v1.d.ts +2 -1
  92. package/build/dex/swaap-v1/swaap-v1.js +14 -0
  93. package/build/dex/swaap-v1/swaap-v1.js.map +1 -1
  94. package/build/dex/uniswap-v3/config.js +1 -1
  95. package/build/dex/uniswap-v3/config.js.map +1 -1
  96. package/build/dex/uniswap-v3/forks/alien-base-v3/alien-base-v3.d.ts +17 -0
  97. package/build/dex/uniswap-v3/forks/alien-base-v3/alien-base-v3.js +64 -0
  98. package/build/dex/uniswap-v3/forks/alien-base-v3/alien-base-v3.js.map +1 -0
  99. package/build/dex/uniswap-v3/forks/alien-v3/alien-v3.d.ts +17 -0
  100. package/build/dex/uniswap-v3/forks/alien-v3/alien-v3.js +79 -0
  101. package/build/dex/uniswap-v3/forks/alien-v3/alien-v3.js.map +1 -0
  102. package/build/dex/uniswap-v3/uniswap-v3-pricing.d.ts +4 -0
  103. package/build/dex/uniswap-v3/uniswap-v3-pricing.js +43 -0
  104. package/build/dex/uniswap-v3/uniswap-v3-pricing.js.map +1 -0
  105. package/build/dex/uniswap-v3/uniswap-v3-worker.d.ts +1 -0
  106. package/build/dex/uniswap-v3/uniswap-v3-worker.js +10 -0
  107. package/build/dex/uniswap-v3/uniswap-v3-worker.js.map +1 -0
  108. package/build/dex/zerox/index.d.ts +4 -26
  109. package/build/dex/zerox/index.js +50 -42
  110. package/build/dex/zerox/index.js.map +1 -1
  111. package/build/dex/zerox/types.d.ts +29 -0
  112. package/build/dex/zerox/types.js +8 -1
  113. package/build/dex/zerox/types.js.map +1 -1
  114. package/build/executor/Executor03BytecodeBuilder.js +3 -8
  115. package/build/executor/Executor03BytecodeBuilder.js.map +1 -1
  116. package/package.json +1 -1
  117. package/src/abi/fluid-dex/resolver.abi.json +4 -731
  118. package/src/dex/algebra/algebra.ts +20 -19
  119. package/src/dex/algebra/config.ts +1 -2
  120. package/src/dex/fluid-dex/config.ts +1 -1
  121. package/src/dex/fluid-dex/fluid-dex-e2e.test.ts +6 -153
  122. package/src/dex/fluid-dex/fluid-dex-events.test.ts +4 -2
  123. package/src/dex/fluid-dex/fluid-dex-integration.test.ts +11 -79
  124. package/src/dex/fluid-dex/fluid-dex-liquidity-proxy.ts +0 -33
  125. package/src/dex/fluid-dex/fluid-dex.ts +104 -303
  126. package/src/dex/fluid-dex/types.ts +1 -25
  127. package/src/dex/uniswap-v3/config.ts +1 -2
  128. package/src/executor/Executor03BytecodeBuilder.ts +2 -10
  129. package/.idea/aws.xml +0 -17
  130. package/.idea/codeStyles/Project.xml +0 -19
  131. package/.idea/codeStyles/codeStyleConfig.xml +0 -5
  132. package/.idea/misc.xml +0 -6
  133. package/.idea/modules.xml +0 -8
  134. package/.idea/paraswap-dex-lib.iml +0 -9
  135. package/.idea/prettier.xml +0 -7
  136. package/.idea/vcs.xml +0 -6
  137. package/build/abi/integral/factory.json +0 -333
  138. package/build/abi/integral/oracle.json +0 -501
  139. package/build/abi/integral/pool.json +0 -1041
  140. package/build/dex/cables/cables.d.ts +0 -59
  141. package/build/dex/cables/cables.js +0 -599
  142. package/build/dex/cables/cables.js.map +0 -1
  143. package/build/dex/cables/config.d.ts +0 -4
  144. package/build/dex/cables/config.js +0 -15
  145. package/build/dex/cables/config.js.map +0 -1
  146. package/build/dex/cables/constants.d.ts +0 -20
  147. package/build/dex/cables/constants.js +0 -24
  148. package/build/dex/cables/constants.js.map +0 -1
  149. package/build/dex/cables/rate-fetcher.d.ts +0 -34
  150. package/build/dex/cables/rate-fetcher.js +0 -106
  151. package/build/dex/cables/rate-fetcher.js.map +0 -1
  152. package/build/dex/cables/types.d.ts +0 -113
  153. package/build/dex/cables/types.js +0 -19
  154. package/build/dex/cables/types.js.map +0 -1
  155. package/build/dex/cables/validators.d.ts +0 -5
  156. package/build/dex/cables/validators.js +0 -49
  157. package/build/dex/cables/validators.js.map +0 -1
  158. package/build/dex/fluid-dex/fluid-dex-generate-pool.d.ts +0 -49
  159. package/build/dex/fluid-dex/fluid-dex-generate-pool.js +0 -104
  160. package/build/dex/fluid-dex/fluid-dex-generate-pool.js.map +0 -1
  161. package/build/dex/integral/config.d.ts +0 -4
  162. package/build/dex/integral/config.js +0 -20
  163. package/build/dex/integral/config.js.map +0 -1
  164. package/build/dex/integral/context.d.ts +0 -40
  165. package/build/dex/integral/context.js +0 -158
  166. package/build/dex/integral/context.js.map +0 -1
  167. package/build/dex/integral/integral-factory.d.ts +0 -24
  168. package/build/dex/integral/integral-factory.js +0 -95
  169. package/build/dex/integral/integral-factory.js.map +0 -1
  170. package/build/dex/integral/integral-pool.d.ts +0 -50
  171. package/build/dex/integral/integral-pool.js +0 -149
  172. package/build/dex/integral/integral-pool.js.map +0 -1
  173. package/build/dex/integral/integral-pricing.d.ts +0 -18
  174. package/build/dex/integral/integral-pricing.js +0 -114
  175. package/build/dex/integral/integral-pricing.js.map +0 -1
  176. package/build/dex/integral/integral-relayer.d.ts +0 -42
  177. package/build/dex/integral/integral-relayer.js +0 -192
  178. package/build/dex/integral/integral-relayer.js.map +0 -1
  179. package/build/dex/integral/integral-token.d.ts +0 -27
  180. package/build/dex/integral/integral-token.js +0 -59
  181. package/build/dex/integral/integral-token.js.map +0 -1
  182. package/build/dex/integral/integral.d.ts +0 -41
  183. package/build/dex/integral/integral.js +0 -376
  184. package/build/dex/integral/integral.js.map +0 -1
  185. package/build/dex/integral/types.d.ts +0 -85
  186. package/build/dex/integral/types.js +0 -9
  187. package/build/dex/integral/types.js.map +0 -1
  188. package/build/dex/integral/utils-e2e.d.ts +0 -9
  189. package/build/dex/integral/utils-e2e.js +0 -131
  190. package/build/dex/integral/utils-e2e.js.map +0 -1
  191. package/build/dex/integral/utils.d.ts +0 -17
  192. package/build/dex/integral/utils.js +0 -94
  193. package/build/dex/integral/utils.js.map +0 -1
  194. package/build/dex/trader-joe-v2.1/optimizer.d.ts +0 -2
  195. package/build/dex/trader-joe-v2.1/optimizer.js +0 -47
  196. package/build/dex/trader-joe-v2.1/optimizer.js.map +0 -1
@@ -1,59 +0,0 @@
1
- import { Address, NumberAsString, OptimalSwapExchange, SwapSide } from '@paraswap/core';
2
- import { AsyncOrSync } from 'ts-essentials';
3
- import { Network } from '../../constants';
4
- import { IDexHelper } from '../../dex-helper';
5
- import { AdapterExchangeParam, DexExchangeParam, ExchangePrices, ExchangeTxInfo, Logger, PoolLiquidity, PoolPrices, PreprocessTransactionOptions, Token, TransferFeeParams } from '../../types';
6
- import { IDex } from '../idex';
7
- import { SimpleExchange } from '../simple-exchange';
8
- import { CablesData } from './types';
9
- import { Interface } from 'ethers/lib/utils';
10
- export declare class Cables extends SimpleExchange implements IDex<any> {
11
- readonly network: Network;
12
- readonly dexKey: string;
13
- readonly dexHelper: IDexHelper;
14
- readonly mainnetRFQAddress: string;
15
- protected rfqInterface: Interface;
16
- static dexKeysWithNetwork: {
17
- key: string;
18
- networks: Network[];
19
- }[];
20
- readonly isStatePollingDex = true;
21
- private rateFetcher;
22
- logger: Logger;
23
- private tokensMap;
24
- hasConstantPriceLargeAmounts: boolean;
25
- constructor(network: Network, dexKey: string, dexHelper: IDexHelper, mainnetRFQAddress?: string, rfqInterface?: Interface);
26
- preProcessTransaction?(optimalSwapExchange: OptimalSwapExchange<CablesData>, srcToken: Token, destToken: Token, side: SwapSide, options: PreprocessTransactionOptions): Promise<[OptimalSwapExchange<CablesData>, ExchangeTxInfo]>;
27
- getDexParam(srcToken: Address, destToken: Address, srcAmount: NumberAsString, destAmount: NumberAsString, recipient: Address, data: CablesData, side: SwapSide): DexExchangeParam;
28
- getAdapterParam(srcToken: string, destToken: string, srcAmount: string, destAmount: string, data: CablesData, side: SwapSide): AdapterExchangeParam;
29
- normalizeToken(token: Token): Token;
30
- normalizeTokenAddress(address: Address): Address;
31
- getTokenFromAddress(address: Address): Token;
32
- getPoolIdentifier(srcAddress: Address, destAddress: Address, mm?: string): string;
33
- getPoolIdentifiers(srcToken: Token, destToken: Token, side: SwapSide, blockNumber: number): Promise<string[]>;
34
- calculateOrderPrice(amounts: bigint[], orderbook: string[][], baseToken: Token, quoteToken: Token, isInputQuote: boolean): bigint[];
35
- calculatePriceSwap(prices: string[][], requiredQty: number, qtyMode: Boolean): number;
36
- getPricesVolume(srcToken: Token, destToken: Token, amounts: bigint[], side: SwapSide, blockNumber: number, limitPools?: string[], transferFees?: TransferFeeParams, isFirstSwap?: boolean): Promise<ExchangePrices<CablesData> | null>;
37
- getCalldataGasCost(poolPrices: PoolPrices<CablesData>): number | number[];
38
- initializePricing(blockNumber: number): Promise<void>;
39
- getAdapters(side: SwapSide): {
40
- name: string;
41
- index: number;
42
- }[] | null;
43
- releaseResources?(): AsyncOrSync<void>;
44
- normalizeAddress(address: string): string;
45
- getTopPoolsForToken(tokenAddress: Address, limit: number): Promise<PoolLiquidity[]>;
46
- /**
47
- * CACHED UTILS
48
- */
49
- getCachedTokens(): Promise<any>;
50
- getCachedPairs(): Promise<any>;
51
- getCachedPrices(): Promise<any>;
52
- getCachedTokensAddr(): Promise<any>;
53
- getPairString(baseToken: Token, quoteToken: Token): string;
54
- private findKeyByAddress;
55
- getPairData(srcToken: Token, destToken: Token): Promise<any>;
56
- isBlacklisted(txOrigin: Address): Promise<boolean>;
57
- isRestricted(): Promise<boolean>;
58
- restrict(): Promise<void>;
59
- }
@@ -1,599 +0,0 @@
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.Cables = void 0;
30
- const core_1 = require("@paraswap/core");
31
- const ts_essentials_1 = require("ts-essentials");
32
- const CALLDATA_GAS_COST = __importStar(require("../../calldata-gas-cost"));
33
- const constants_1 = require("../../constants");
34
- const utils_1 = require("../../utils");
35
- const simple_exchange_1 = require("../simple-exchange");
36
- const config_1 = require("./config");
37
- const constants_2 = require("./constants");
38
- const rate_fetcher_1 = require("./rate-fetcher");
39
- const types_1 = require("./types");
40
- const CablesMainnetRFQ_json_1 = __importDefault(require("../../abi/cables/CablesMainnetRFQ.json"));
41
- const utils_2 = require("ethers/lib/utils");
42
- const bignumber_js_1 = __importDefault(require("bignumber.js"));
43
- const ethers_1 = require("ethers");
44
- const bigint_constants_1 = require("../../bigint-constants");
45
- class Cables extends simple_exchange_1.SimpleExchange {
46
- constructor(network, dexKey, dexHelper, mainnetRFQAddress = config_1.CablesConfig['Cables'][network]
47
- .mainnetRFQAddress, rfqInterface = new utils_2.Interface(CablesMainnetRFQ_json_1.default)) {
48
- super(dexHelper, dexKey);
49
- this.network = network;
50
- this.dexKey = dexKey;
51
- this.dexHelper = dexHelper;
52
- this.mainnetRFQAddress = mainnetRFQAddress;
53
- this.rfqInterface = rfqInterface;
54
- this.isStatePollingDex = true;
55
- this.tokensMap = {};
56
- this.hasConstantPriceLargeAmounts = false;
57
- // Function to find a key by address
58
- this.findKeyByAddress = (jsonData, targetAddress) => {
59
- const entries = Object.entries(jsonData);
60
- const foundEntry = entries.find(([_, value]) => value.address.toLowerCase() === targetAddress.toLowerCase());
61
- return foundEntry ? foundEntry[0] : undefined;
62
- };
63
- this.logger = dexHelper.getLogger(dexKey);
64
- this.rateFetcher = new rate_fetcher_1.CablesRateFetcher(this.dexHelper, this.dexKey, this.network, this.logger, {
65
- rateConfig: {
66
- pairsReqParams: {
67
- url: constants_2.CABLES_API_URL + '/pairs',
68
- },
69
- pricesReqParams: {
70
- url: constants_2.CABLES_API_URL + '/prices',
71
- },
72
- blacklistReqParams: {
73
- url: constants_2.CABLES_API_URL + '/blacklist',
74
- },
75
- tokensReqParams: {
76
- url: constants_2.CABLES_API_URL + '/tokens',
77
- },
78
- pricesIntervalMs: constants_2.CABLES_API_PRICES_POLLING_INTERVAL_MS,
79
- pricesCacheTTLSecs: constants_2.CABLES_PRICES_CACHES_TTL_S,
80
- pricesCacheKey: 'cablesPricesCacheKey',
81
- pairsIntervalMs: constants_2.CABLES_API_PAIRS_POLLING_INTERVAL_MS,
82
- pairsCacheTTLSecs: constants_2.CABLES_PAIRS_CACHES_TTL_S,
83
- pairsCacheKey: 'cablesPairsCacheKey',
84
- tokensIntervalMs: constants_2.CABLES_API_TOKENS_POLLING_INTERVAL_MS,
85
- tokensCacheTTLSecs: constants_2.CABLES_TOKENS_CACHES_TTL_S,
86
- tokensCacheKey: 'cablesTokensCacheKey',
87
- blacklistIntervalMs: constants_2.CABLES_API_BLACKLIST_POLLING_INTERVAL_MS,
88
- blacklistCacheTTLSecs: constants_2.CABLES_BLACKLIST_CACHES_TTL_S,
89
- blacklistCacheKey: constants_2.CABLES_BLACKLIST_CACHE_KEY,
90
- },
91
- });
92
- }
93
- async preProcessTransaction(optimalSwapExchange, srcToken, destToken, side, options) {
94
- if (await this.isBlacklisted(options.txOrigin)) {
95
- this.logger.warn(`${this.dexKey}-${this.network}: blacklisted TX Origin address '${options.txOrigin}' trying to build a transaction. Bailing...`);
96
- throw new Error(`${this.dexKey}-${this.network}: user=${options.txOrigin.toLowerCase()} is blacklisted`);
97
- }
98
- if (BigInt(optimalSwapExchange.srcAmount) === 0n) {
99
- throw new Error('getFirmRate failed with srcAmount === 0');
100
- }
101
- const normalizedSrcToken = this.normalizeToken(srcToken);
102
- const normalizedDestToken = this.normalizeToken(destToken);
103
- const swapIdentifier = `${this.dexKey}_${normalizedSrcToken.address}_${normalizedDestToken.address}_${side}`;
104
- try {
105
- const makerToken = normalizedDestToken;
106
- const takerToken = normalizedSrcToken;
107
- const isSell = side === core_1.SwapSide.SELL;
108
- const isBuy = side === core_1.SwapSide.BUY;
109
- const rfqParams = {
110
- makerAsset: ethers_1.ethers.utils.getAddress(makerToken.address),
111
- takerAsset: ethers_1.ethers.utils.getAddress(takerToken.address),
112
- ...(isBuy && { makerAmount: optimalSwapExchange.destAmount }),
113
- ...(isSell && { takerAmount: optimalSwapExchange.srcAmount }),
114
- userAddress: options.executionContractAddress,
115
- chainId: String(this.network),
116
- };
117
- const rfq = await this.dexHelper.httpRequest.post(`${constants_2.CABLES_API_URL}/quote`, rfqParams, constants_2.CABLES_FIRM_QUOTE_TIMEOUT_MS);
118
- if (!rfq) {
119
- throw new Error('Failed to fetch RFQ' +
120
- swapIdentifier +
121
- JSON.stringify(rfq + 'params' + rfqParams));
122
- }
123
- const { order } = rfq;
124
- (0, ts_essentials_1.assert)(order.makerAsset.toLowerCase() === makerToken.address, `QuoteData makerAsset=${order.makerAsset} is different from Paraswap makerAsset=${makerToken.address}`);
125
- (0, ts_essentials_1.assert)(order.takerAsset.toLowerCase() === takerToken.address, `QuoteData takerAsset=${order.takerAsset} is different from Paraswap takerAsset=${takerToken.address}`);
126
- if (isSell) {
127
- (0, ts_essentials_1.assert)(order.takerAmount === optimalSwapExchange.srcAmount, `QuoteData takerAmount=${order.takerAmount} is different from Paraswap srcAmount=${optimalSwapExchange.srcAmount}`);
128
- }
129
- else {
130
- (0, ts_essentials_1.assert)(order.makerAmount === optimalSwapExchange.destAmount, `QuoteData makerAmount=${order.makerAmount} is different from Paraswap destAmount=${optimalSwapExchange.destAmount}`);
131
- }
132
- const expiryAsBigInt = BigInt(order.expiry);
133
- const minDeadline = expiryAsBigInt > 0 ? expiryAsBigInt : bigint_constants_1.BI_MAX_UINT256;
134
- if (side === core_1.SwapSide.SELL) {
135
- const requiredAmount = BigInt(optimalSwapExchange.destAmount);
136
- const quoteAmount = BigInt(order.makerAmount);
137
- const requiredAmountWithSlippage = new bignumber_js_1.default(requiredAmount.toString())
138
- .times(options.slippageFactor)
139
- .toFixed(0);
140
- if (quoteAmount < BigInt(requiredAmountWithSlippage)) {
141
- throw new types_1.SlippageError(`Slipped, factor: ${quoteAmount.toString()} < ${requiredAmountWithSlippage}`);
142
- }
143
- }
144
- else {
145
- const requiredAmount = BigInt(optimalSwapExchange.srcAmount);
146
- const quoteAmount = BigInt(order.takerAmount);
147
- const requiredAmountWithSlippage = new bignumber_js_1.default(requiredAmount.toString())
148
- .times(options.slippageFactor)
149
- .toFixed(0);
150
- if (quoteAmount > BigInt(requiredAmountWithSlippage)) {
151
- throw new types_1.SlippageError(`Slipped, factor: ${options.slippageFactor} ${quoteAmount.toString()} > ${requiredAmountWithSlippage}`);
152
- }
153
- }
154
- // Correction of the srcAmount
155
- // because flag specialDexSupportsInsertFromAmount: false
156
- // is not working for Buy in test
157
- if (isBuy) {
158
- optimalSwapExchange.srcAmount = (0, bignumber_js_1.default)((Number(optimalSwapExchange.srcAmount) * 10000) /
159
- (10000 + Number(options.slippageFactor))).toFixed(0);
160
- }
161
- return [
162
- {
163
- ...optimalSwapExchange,
164
- data: {
165
- quoteData: order,
166
- },
167
- },
168
- { deadline: minDeadline },
169
- ];
170
- }
171
- catch (e) {
172
- const message = `${this.dexKey}-${this.network}: ${e}`;
173
- this.logger.error(message);
174
- if (!e?.isSlippageError) {
175
- this.restrict();
176
- }
177
- throw new Error(message);
178
- }
179
- }
180
- getDexParam(srcToken, destToken, srcAmount, destAmount, recipient, data, side) {
181
- const { quoteData } = data;
182
- (0, ts_essentials_1.assert)(quoteData !== undefined, `${this.dexKey}-${this.network}: quoteData undefined`);
183
- const swapFunction = 'partialSwap';
184
- const swapFunctionParams = [
185
- [
186
- quoteData.nonceAndMeta,
187
- quoteData.expiry,
188
- quoteData.makerAsset,
189
- quoteData.takerAsset,
190
- quoteData.maker,
191
- quoteData.taker,
192
- quoteData.makerAmount,
193
- quoteData.takerAmount,
194
- ],
195
- quoteData.signature,
196
- quoteData.takerAmount,
197
- ];
198
- const exchangeData = this.rfqInterface.encodeFunctionData(swapFunction, swapFunctionParams);
199
- return {
200
- exchangeData,
201
- needWrapNative: this.needWrapNative,
202
- dexFuncHasRecipient: false,
203
- targetExchange: this.mainnetRFQAddress,
204
- returnAmountPos: undefined,
205
- };
206
- }
207
- getAdapterParam(srcToken, destToken, srcAmount, destAmount, data, side) {
208
- const { quoteData } = data;
209
- (0, ts_essentials_1.assert)(quoteData !== undefined, `${this.dexKey}-${this.network}: quoteData undefined`);
210
- const params = [
211
- {
212
- nonceAndMeta: quoteData.nonceAndMeta,
213
- expiry: quoteData.expiry,
214
- makerAsset: quoteData.makerAsset,
215
- takerAsset: quoteData.takerAsset,
216
- maker: quoteData.maker,
217
- taker: quoteData.taker,
218
- makerAmount: quoteData.makerAmount,
219
- takerAmount: quoteData.takerAmount,
220
- },
221
- quoteData.signature,
222
- ];
223
- const payload = this.abiCoder.encodeParameter({
224
- ParentStruct: {
225
- order: {
226
- nonceAndMeta: 'uint256',
227
- expiry: 'uint128',
228
- makerAsset: 'address',
229
- takerAsset: 'address',
230
- maker: 'address',
231
- taker: 'address',
232
- makerAmount: 'uint256',
233
- takerAmount: 'uint256',
234
- },
235
- signature: 'bytes',
236
- },
237
- }, {
238
- order: params[0],
239
- signature: params[1],
240
- });
241
- return {
242
- targetExchange: this.mainnetRFQAddress,
243
- payload,
244
- networkFee: '0',
245
- };
246
- }
247
- normalizeToken(token) {
248
- return {
249
- ...token,
250
- address: this.normalizeTokenAddress(token.address),
251
- };
252
- }
253
- normalizeTokenAddress(address) {
254
- return address.toLowerCase();
255
- }
256
- getTokenFromAddress(address) {
257
- return this.tokensMap[this.normalizeAddress(address)];
258
- }
259
- getPoolIdentifier(srcAddress, destAddress, mm) {
260
- return `${this.dexKey}_${srcAddress}_${destAddress}`.toLowerCase();
261
- return `${this.dexKey}_${srcAddress}_${destAddress}_${mm}`.toLowerCase();
262
- }
263
- async getPoolIdentifiers(srcToken, destToken, side, blockNumber) {
264
- if (!srcToken || !destToken) {
265
- return [];
266
- }
267
- if (srcToken.address.toLowerCase() === destToken.address.toLowerCase()) {
268
- return [];
269
- }
270
- const pairData = await this.getPairData(srcToken, destToken);
271
- if (!pairData) {
272
- return [];
273
- }
274
- const tokensAddr = (await this.getCachedTokensAddr()) || {};
275
- return [
276
- this.getPoolIdentifier(tokensAddr[pairData.base.toLowerCase()], tokensAddr[pairData.quote.toLowerCase()]),
277
- ];
278
- }
279
- calculateOrderPrice(amounts, orderbook, baseToken, quoteToken, isInputQuote) {
280
- let result = [];
281
- for (let i = 0; i < amounts.length; i++) {
282
- let amt = amounts[i];
283
- if (amt === 0n) {
284
- result.push(amt);
285
- continue;
286
- }
287
- let decimals = baseToken.decimals;
288
- if (isInputQuote) {
289
- decimals = quoteToken.decimals;
290
- }
291
- let price = this.calculatePriceSwap(orderbook, Number(amt) / 10 ** decimals, isInputQuote);
292
- result.push(BigInt(Math.round(price * 10 ** decimals)));
293
- }
294
- return result;
295
- }
296
- calculatePriceSwap(prices, requiredQty, qtyMode) {
297
- let sumBaseQty = 0;
298
- let sumQuoteQty = 0;
299
- const selectedRows = [];
300
- const isBase = !qtyMode;
301
- const isQuote = qtyMode;
302
- for (const [price, volume] of prices) {
303
- if (isBase) {
304
- if (sumBaseQty >= requiredQty) {
305
- break;
306
- }
307
- }
308
- if (isQuote) {
309
- if (sumQuoteQty >= requiredQty) {
310
- break;
311
- }
312
- }
313
- let currentBaseQty = Number(volume);
314
- let currentQuoteQty = Number(volume) * Number(price);
315
- const overQty = isBase
316
- ? currentBaseQty + sumBaseQty > requiredQty
317
- : currentQuoteQty + sumQuoteQty > requiredQty;
318
- if (overQty) {
319
- if (isBase) {
320
- currentBaseQty = requiredQty - sumBaseQty;
321
- currentQuoteQty = currentBaseQty * Number(price);
322
- }
323
- if (isQuote) {
324
- currentQuoteQty = requiredQty - sumQuoteQty;
325
- currentBaseQty =
326
- currentQuoteQty *
327
- new bignumber_js_1.default(1).dividedBy(new bignumber_js_1.default(price)).toNumber();
328
- }
329
- }
330
- sumBaseQty += currentBaseQty;
331
- sumQuoteQty += currentQuoteQty;
332
- selectedRows.push([price, currentBaseQty.toString()]);
333
- }
334
- const vSumBase = selectedRows.reduce((sum, [price, volume]) => {
335
- return sum + Number(price) * Number(volume);
336
- }, 0);
337
- if (isBase) {
338
- return sumBaseQty;
339
- }
340
- else {
341
- return sumQuoteQty;
342
- }
343
- }
344
- async getPricesVolume(srcToken, destToken, amounts, side, blockNumber, limitPools, transferFees, isFirstSwap) {
345
- const isRestricted = await this.isRestricted();
346
- if (isRestricted) {
347
- return null;
348
- }
349
- try {
350
- const normalizedSrcToken = this.normalizeToken(srcToken);
351
- const normalizedDestToken = this.normalizeToken(destToken);
352
- // If: same token, return null
353
- if (normalizedSrcToken.address.toLowerCase() ===
354
- normalizedDestToken.address.toLowerCase()) {
355
- return null;
356
- }
357
- // Ensure that "symbol" is set
358
- const tokens = await this.getCachedTokens();
359
- this.tokensMap = Object.keys(tokens).reduce((acc, key) => {
360
- //@ts-ignore
361
- acc[tokens[key].address.toLowerCase()] = tokens[key];
362
- return acc;
363
- }, {});
364
- for (const symbol of Object.keys(tokens)) {
365
- const normalizedTokenAddress = tokens[symbol].address.toLowerCase();
366
- if (normalizedSrcToken.address === normalizedTokenAddress) {
367
- normalizedSrcToken.symbol = tokens[symbol].symbol;
368
- }
369
- if (normalizedDestToken.address === normalizedTokenAddress) {
370
- normalizedDestToken.symbol = tokens[symbol].symbol;
371
- }
372
- }
373
- // ---------- Pools ----------
374
- let pools = await this.getPoolIdentifiers(srcToken, destToken, side, blockNumber);
375
- if (pools.length === 0)
376
- return null;
377
- // ---------- Prices ----------
378
- const priceMap = await this.getCachedPrices();
379
- if (!priceMap)
380
- return null;
381
- let pairKey = `${normalizedSrcToken.symbol}/${normalizedDestToken.symbol}`;
382
- const pairsKeys = Object.keys(priceMap);
383
- if (!pairsKeys.includes(pairKey)) {
384
- // Revert
385
- pairKey = `${normalizedDestToken.symbol}/${normalizedSrcToken.symbol}`;
386
- if (!pairsKeys.includes(pairKey)) {
387
- return null;
388
- }
389
- }
390
- /**
391
- * Orderbook
392
- */
393
- const priceData = priceMap[pairKey];
394
- let orderbook = [];
395
- if (side === core_1.SwapSide.BUY) {
396
- orderbook = priceData.asks;
397
- }
398
- else {
399
- orderbook = priceData.bids;
400
- }
401
- if (orderbook?.length === 0) {
402
- throw new Error(`Empty orderbook for ${pairKey}`);
403
- }
404
- const isInputQuote = side === core_1.SwapSide.BUY;
405
- const prices = this.calculateOrderPrice(amounts, orderbook, srcToken, destToken, isInputQuote);
406
- const outDecimals = side === core_1.SwapSide.BUY
407
- ? normalizedSrcToken.decimals
408
- : normalizedDestToken.decimals;
409
- const result = [
410
- {
411
- prices: prices,
412
- unit: BigInt(outDecimals),
413
- exchange: this.dexKey,
414
- gasCost: constants_2.CABLES_GAS_COST,
415
- poolAddresses: [this.mainnetRFQAddress],
416
- data: {},
417
- },
418
- ];
419
- return result;
420
- }
421
- catch (e) {
422
- this.logger.error(`Error in getPricesVolume`, {
423
- srcToken: srcToken.address || srcToken.symbol,
424
- destToken: destToken.address || destToken.symbol,
425
- side,
426
- }, e);
427
- return null;
428
- }
429
- }
430
- getCalldataGasCost(poolPrices) {
431
- return (CALLDATA_GAS_COST.DEX_OVERHEAD +
432
- // addresses: makerAsset, takerAsset, maker, taker
433
- CALLDATA_GAS_COST.ADDRESS * 4 +
434
- // uint256: expiry
435
- CALLDATA_GAS_COST.wordNonZeroBytes(16) +
436
- // uint256: nonceAndMeta, makerAmount, takerAmount
437
- CALLDATA_GAS_COST.AMOUNT * 3 +
438
- // bytes: _signature (65 bytes)
439
- CALLDATA_GAS_COST.FULL_WORD * 2 +
440
- CALLDATA_GAS_COST.OFFSET_SMALL);
441
- }
442
- async initializePricing(blockNumber) {
443
- if (!this.dexHelper.config.isSlave) {
444
- this.rateFetcher.start();
445
- }
446
- return;
447
- }
448
- getAdapters(side) {
449
- return null;
450
- }
451
- releaseResources() {
452
- if (this.rateFetcher) {
453
- this.rateFetcher.stop();
454
- }
455
- }
456
- normalizeAddress(address) {
457
- return address.toLowerCase() === constants_1.ETHER_ADDRESS
458
- ? constants_1.NULL_ADDRESS
459
- : address.toLowerCase();
460
- }
461
- async getTopPoolsForToken(tokenAddress, limit) {
462
- const tokens = (await this.getCachedTokens());
463
- const token = Object.values(tokens).find(token => token.address.toLowerCase() === tokenAddress.toLowerCase());
464
- if (!token) {
465
- return [];
466
- }
467
- const tokenPriceUsd = await this.dexHelper.getTokenUSDPrice(token, BigInt(10 ** token.decimals));
468
- const erc20BalanceCalldata = this.erc20Interface.encodeFunctionData('balanceOf', [this.mainnetRFQAddress]);
469
- const tokenBalanceMultiCall = [
470
- {
471
- target: token.address,
472
- callData: erc20BalanceCalldata,
473
- },
474
- ];
475
- const res = (await this.dexHelper.multiContract.methods
476
- .aggregate(tokenBalanceMultiCall)
477
- .call()).returnData[0];
478
- let tokenLiquidity = BigInt(res);
479
- let tokenLiquidityUsd = (tokenLiquidity * BigInt(tokenPriceUsd * 1000000)) /
480
- BigInt(1000000 * 10 ** token.decimals);
481
- let tokenWithLiquidity = [];
482
- tokenWithLiquidity.push({
483
- exchange: this.dexKey,
484
- address: this.mainnetRFQAddress,
485
- connectorTokens: [
486
- {
487
- address: token.address,
488
- decimals: token.decimals,
489
- },
490
- ],
491
- liquidityUSD: Number(tokenLiquidityUsd),
492
- });
493
- return tokenWithLiquidity;
494
- }
495
- /**
496
- * CACHED UTILS
497
- */
498
- async getCachedTokens() {
499
- const cachedTokens = await this.dexHelper.cache.get(this.dexKey, this.network, this.rateFetcher.tokensCacheKey);
500
- return cachedTokens ? JSON.parse(cachedTokens) : {};
501
- }
502
- async getCachedPairs() {
503
- const cachedPairs = await this.dexHelper.cache.get(this.dexKey, this.network, this.rateFetcher.pairsCacheKey);
504
- return cachedPairs ? JSON.parse(cachedPairs) : {};
505
- }
506
- async getCachedPrices() {
507
- const cachedPrices = await this.dexHelper.cache.get(this.dexKey, this.network, this.rateFetcher.pricesCacheKey);
508
- return cachedPrices ? JSON.parse(cachedPrices) : {};
509
- }
510
- async getCachedTokensAddr() {
511
- const tokens = await this.getCachedTokens();
512
- const tokensAddr = {};
513
- for (const key of Object.keys(tokens)) {
514
- tokensAddr[tokens[key].symbol.toLowerCase()] = tokens[key].address;
515
- }
516
- return tokensAddr;
517
- }
518
- getPairString(baseToken, quoteToken) {
519
- return `${baseToken.symbol}/${quoteToken.symbol}`.toLowerCase();
520
- }
521
- async getPairData(srcToken, destToken) {
522
- const normalizedSrcToken = this.normalizeToken(srcToken);
523
- const normalizedDestToken = this.normalizeToken(destToken);
524
- if (normalizedSrcToken.address === normalizedDestToken.address) {
525
- return null;
526
- }
527
- const cachedTokens = await this.getCachedTokens();
528
- normalizedSrcToken.symbol = this.findKeyByAddress(cachedTokens, normalizedSrcToken.address);
529
- normalizedDestToken.symbol = this.findKeyByAddress(cachedTokens, normalizedDestToken.address);
530
- const cachedPairs = await this.getCachedPairs();
531
- const potentialPairs = [
532
- {
533
- base: normalizedSrcToken.symbol,
534
- quote: normalizedDestToken.symbol,
535
- identifier: this.getPairString(normalizedSrcToken, normalizedDestToken),
536
- isSrcBase: true,
537
- },
538
- {
539
- base: normalizedDestToken.symbol,
540
- quote: normalizedSrcToken.symbol,
541
- identifier: this.getPairString(normalizedDestToken, normalizedSrcToken),
542
- isSrcBase: false,
543
- },
544
- ];
545
- for (const pair of potentialPairs) {
546
- if (pair.identifier in cachedPairs) {
547
- const pairData = cachedPairs[pair.identifier];
548
- pairData.isSrcBase = pair.isSrcBase;
549
- return pairData;
550
- }
551
- }
552
- return null;
553
- }
554
- async isBlacklisted(txOrigin) {
555
- const cachedBlacklist = await this.dexHelper.cache.get(this.dexKey, this.network, constants_2.CABLES_BLACKLIST_CACHE_KEY);
556
- if (cachedBlacklist) {
557
- const blacklist = JSON.parse(cachedBlacklist);
558
- return blacklist.includes(txOrigin.toLowerCase());
559
- }
560
- return false;
561
- }
562
- async isRestricted() {
563
- const result = await this.dexHelper.cache.get(this.dexKey, this.network, constants_2.CABLES_RESTRICTED_CACHE_KEY);
564
- return result === 'true';
565
- }
566
- async restrict() {
567
- const errorsDataRaw = await this.dexHelper.cache.get(this.dexKey, this.network, constants_2.CABLES_ERRORS_CACHE_KEY);
568
- const errorsData = utils_1.Utils.Parse(errorsDataRaw);
569
- const ERRORS_TTL_S = Math.floor(constants_2.CABLES_RESTRICT_CHECK_INTERVAL_MS / 1000);
570
- if (!errorsData ||
571
- errorsData?.addedDatetimeMs + constants_2.CABLES_RESTRICT_CHECK_INTERVAL_MS <
572
- Date.now()) {
573
- this.logger.warn(`${this.dexKey}-${this.network}: First encounter of error OR error ocurred outside of threshold, setting up counter`);
574
- const data = {
575
- count: 1,
576
- addedDatetimeMs: Date.now(),
577
- };
578
- await this.dexHelper.cache.setex(this.dexKey, this.network, constants_2.CABLES_ERRORS_CACHE_KEY, ERRORS_TTL_S, utils_1.Utils.Serialize(data));
579
- return;
580
- }
581
- else {
582
- if (errorsData.count + 1 >= constants_2.CABLES_RESTRICT_COUNT_THRESHOLD) {
583
- this.logger.warn(`${this.dexKey}-${this.network}: Restricting due to error count=${errorsData.count + 1} within ${constants_2.CABLES_RESTRICT_CHECK_INTERVAL_MS / 1000 / 60} minutes`);
584
- await this.dexHelper.cache.setex(this.dexKey, this.network, constants_2.CABLES_RESTRICTED_CACHE_KEY, constants_2.CABLES_RESTRICT_TTL_S, 'true');
585
- }
586
- else {
587
- this.logger.warn(`${this.dexKey}-${this.network}: Error count increased`);
588
- const data = {
589
- count: errorsData.count + 1,
590
- addedDatetimeMs: errorsData.addedDatetimeMs,
591
- };
592
- await this.dexHelper.cache.setex(this.dexKey, this.network, constants_2.CABLES_RESTRICTED_CACHE_KEY, ERRORS_TTL_S, utils_1.Utils.Serialize(data));
593
- }
594
- }
595
- }
596
- }
597
- exports.Cables = Cables;
598
- Cables.dexKeysWithNetwork = (0, utils_1.getDexKeysWithNetwork)(config_1.CablesConfig);
599
- //# sourceMappingURL=cables.js.map