@paraswap/dex-lib 3.11.6-fluid-dex-changes.0 → 3.11.7-cables.0

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.
@@ -0,0 +1,13 @@
1
+ import { Network } from '../../constants';
2
+ import { DexConfigMap } from '../../types';
3
+
4
+ export const CablesConfig: DexConfigMap<{ mainnetRFQAddress: string }> = {
5
+ Cables: {
6
+ [Network.AVALANCHE]: {
7
+ mainnetRFQAddress: '0xfA12DCB2e1FD72bD92E8255Db6A781b2c76adC20',
8
+ },
9
+ [Network.ARBITRUM]: {
10
+ mainnetRFQAddress: '0xfA12DCB2e1FD72bD92E8255Db6A781b2c76adC20',
11
+ },
12
+ },
13
+ };
@@ -0,0 +1,35 @@
1
+ import BigNumber from 'bignumber.js';
2
+
3
+ /**
4
+ * Cables
5
+ */
6
+ export const CABLES_API_URL =
7
+ 'https://cables-evm-rfq-service.cryptosrvc.com/v1';
8
+
9
+ export const CABLES_PRICES_CACHES_TTL_S = 10;
10
+ export const CABLES_API_PRICES_POLLING_INTERVAL_MS = 2000; // 2 sec
11
+
12
+ export const CABLES_PAIRS_CACHES_TTL_S = 12;
13
+ export const CABLES_API_PAIRS_POLLING_INTERVAL_MS = 10000; // 10 sec
14
+
15
+ export const CABLES_BLACKLIST_CACHES_TTL_S = 60;
16
+ export const CABLES_API_BLACKLIST_POLLING_INTERVAL_MS = 30000; // 30 sec
17
+
18
+ export const CABLES_TOKENS_CACHES_TTL_S = 60;
19
+ export const CABLES_API_TOKENS_POLLING_INTERVAL_MS = 30000; // 30 sec
20
+
21
+ export const CABLES_FIRM_QUOTE_TIMEOUT_MS = 2000;
22
+
23
+ export const CABLES_BLACKLIST_CACHE_KEY = 'cablesBlacklistCacheKey';
24
+
25
+ export const CABLES_RESTRICTED_CACHE_KEY = 'restricted';
26
+
27
+ export const CABLES_ERRORS_CACHE_KEY = 'errors';
28
+
29
+ export const CABLES_RESTRICT_CHECK_INTERVAL_MS = 1000 * 60 * 3; // 3 min
30
+
31
+ export const CABLES_RESTRICT_COUNT_THRESHOLD = 3;
32
+
33
+ export const CABLES_RESTRICT_TTL_S = 10 * 60; // 10 min
34
+
35
+ export const CABLES_GAS_COST = 120_000;
@@ -0,0 +1,212 @@
1
+ import { Network } from '../../constants';
2
+ import { IDexHelper } from '../../dex-helper';
3
+ import { Fetcher } from '../../lib/fetcher/fetcher';
4
+ import { validateAndCast } from '../../lib/validators';
5
+ import { Logger, Token } from '../../types';
6
+ import { PairData } from '../cables/types';
7
+ import {
8
+ CablesBlacklistResponse,
9
+ CablesPairsResponse,
10
+ CablesPricesResponse,
11
+ CablesRateFetcherConfig,
12
+ CablesTokensResponse,
13
+ } from './types';
14
+ import {
15
+ blacklistResponseValidator,
16
+ pairsResponseValidator,
17
+ pricesResponseValidator,
18
+ tokensResponseValidator,
19
+ } from './validators';
20
+
21
+ export class CablesRateFetcher {
22
+ public tokensFetcher: Fetcher<CablesTokensResponse>;
23
+ public tokensCacheKey: string;
24
+ public tokensCacheTTL: number;
25
+
26
+ public pairsFetcher: Fetcher<CablesPairsResponse>;
27
+ public pairsCacheKey: string;
28
+ public pairsCacheTTL: number;
29
+
30
+ public pricesFetcher: Fetcher<CablesPricesResponse>;
31
+ public pricesCacheKey: string;
32
+ public pricesCacheTTL: number;
33
+
34
+ public blacklistFetcher: Fetcher<CablesBlacklistResponse>;
35
+ public blacklistCacheKey: string;
36
+ public blacklistCacheTTL: number;
37
+
38
+ constructor(
39
+ private dexHelper: IDexHelper,
40
+ private dexKey: string,
41
+ private network: Network,
42
+ private logger: Logger,
43
+ config: CablesRateFetcherConfig,
44
+ ) {
45
+ this.tokensCacheKey = config.rateConfig.tokensCacheKey;
46
+ this.tokensCacheTTL = config.rateConfig.tokensCacheTTLSecs;
47
+
48
+ this.pairsCacheKey = config.rateConfig.pairsCacheKey;
49
+ this.pairsCacheTTL = config.rateConfig.pairsCacheTTLSecs;
50
+
51
+ this.pricesCacheKey = config.rateConfig.pricesCacheKey;
52
+ this.pricesCacheTTL = config.rateConfig.pricesCacheTTLSecs;
53
+
54
+ this.blacklistCacheKey = config.rateConfig.blacklistCacheKey;
55
+ this.blacklistCacheTTL = config.rateConfig.blacklistCacheTTLSecs;
56
+
57
+ this.pairsFetcher = new Fetcher<CablesPairsResponse>(
58
+ dexHelper.httpRequest,
59
+ {
60
+ info: {
61
+ requestOptions: config.rateConfig.pairsReqParams,
62
+ caster: (data: unknown) => {
63
+ return validateAndCast<CablesPairsResponse>(
64
+ data,
65
+ pairsResponseValidator,
66
+ );
67
+ },
68
+ },
69
+ handler: this.handlePairsResponse.bind(this),
70
+ },
71
+ config.rateConfig.pairsIntervalMs,
72
+ logger,
73
+ );
74
+
75
+ this.pricesFetcher = new Fetcher<CablesPricesResponse>(
76
+ dexHelper.httpRequest,
77
+ {
78
+ info: {
79
+ requestOptions: config.rateConfig.pricesReqParams,
80
+ caster: (data: unknown) => {
81
+ return validateAndCast<CablesPricesResponse>(
82
+ data,
83
+ pricesResponseValidator,
84
+ );
85
+ },
86
+ },
87
+ handler: this.handlePricesResponse.bind(this),
88
+ },
89
+ config.rateConfig.pricesIntervalMs,
90
+ logger,
91
+ );
92
+
93
+ this.blacklistFetcher = new Fetcher<CablesBlacklistResponse>(
94
+ dexHelper.httpRequest,
95
+ {
96
+ info: {
97
+ requestOptions: config.rateConfig.blacklistReqParams,
98
+ caster: (data: unknown) => {
99
+ return validateAndCast<CablesBlacklistResponse>(
100
+ data,
101
+ blacklistResponseValidator,
102
+ );
103
+ },
104
+ },
105
+ handler: this.handleBlacklistResponse.bind(this),
106
+ },
107
+ config.rateConfig.blacklistIntervalMs,
108
+ logger,
109
+ );
110
+
111
+ this.tokensFetcher = new Fetcher<CablesTokensResponse>(
112
+ dexHelper.httpRequest,
113
+ {
114
+ info: {
115
+ requestOptions: config.rateConfig.tokensReqParams,
116
+ caster: (data: unknown) => {
117
+ return validateAndCast<CablesTokensResponse>(
118
+ data,
119
+ tokensResponseValidator,
120
+ );
121
+ },
122
+ },
123
+ handler: this.handleTokensResponse.bind(this),
124
+ },
125
+ config.rateConfig.tokensIntervalMs,
126
+ logger,
127
+ );
128
+ }
129
+
130
+ /**
131
+ * Utils
132
+ */
133
+ start() {
134
+ this.pairsFetcher.startPolling();
135
+ this.pricesFetcher.startPolling();
136
+ this.blacklistFetcher.startPolling();
137
+ this.tokensFetcher.startPolling();
138
+ }
139
+ stop() {
140
+ this.pairsFetcher.stopPolling();
141
+ this.pricesFetcher.stopPolling();
142
+ this.blacklistFetcher.stopPolling();
143
+ this.tokensFetcher.stopPolling();
144
+ }
145
+
146
+ private handlePairsResponse(res: CablesPairsResponse): void {
147
+ const networkId = String(this.network);
148
+ const pairs = res.pairs[networkId];
149
+
150
+ let normalized_pairs: { [token: string]: PairData } = {};
151
+ Object.keys(pairs).forEach(key => {
152
+ normalized_pairs[key.toLowerCase()] = pairs[key];
153
+ });
154
+
155
+ this.dexHelper.cache.setex(
156
+ this.dexKey,
157
+ this.network,
158
+ this.pairsCacheKey,
159
+ this.pairsCacheTTL,
160
+ JSON.stringify(normalized_pairs),
161
+ );
162
+ }
163
+
164
+ private handlePricesResponse(res: CablesPricesResponse): void {
165
+ const networkId = String(this.network);
166
+ const prices = res.prices[networkId];
167
+
168
+ this.dexHelper.cache.setex(
169
+ this.dexKey,
170
+ this.network,
171
+ this.pricesCacheKey,
172
+ this.pricesCacheTTL,
173
+ JSON.stringify(prices),
174
+ );
175
+ }
176
+
177
+ private handleBlacklistResponse(res: CablesBlacklistResponse): void {
178
+ const { blacklist } = res;
179
+ this.dexHelper.cache.setex(
180
+ this.dexKey,
181
+ this.network,
182
+ this.blacklistCacheKey,
183
+ this.blacklistCacheTTL,
184
+ JSON.stringify(blacklist.map(item => item.toLowerCase())),
185
+ );
186
+ }
187
+
188
+ // Convert addresses to lowercase
189
+ private normalizeAddressesToLowerCase = (
190
+ jsonData: Record<string, { address: string }>,
191
+ ) => {
192
+ Object.keys(jsonData).forEach(key => {
193
+ jsonData[key].address = jsonData[key].address.toLowerCase();
194
+ });
195
+ return jsonData;
196
+ };
197
+
198
+ private handleTokensResponse(res: CablesTokensResponse): void {
199
+ const networkId = String(this.network);
200
+ const tokens = res.tokens[networkId];
201
+
202
+ const normalized_tokens = this.normalizeAddressesToLowerCase(tokens);
203
+
204
+ this.dexHelper.cache.setex(
205
+ this.dexKey,
206
+ this.network,
207
+ this.tokensCacheKey,
208
+ this.tokensCacheTTL,
209
+ JSON.stringify(normalized_tokens),
210
+ );
211
+ }
212
+ }
@@ -0,0 +1,128 @@
1
+ import { RequestHeaders } from '../../dex-helper';
2
+ import { Token } from '../../types';
3
+ import { Method } from '../../dex-helper/irequest-wrapper';
4
+ import { AugustusRFQOrderData } from '../augustus-rfq';
5
+
6
+ export type CablesRFQResponse = {
7
+ order: AugustusRFQOrderData;
8
+ signature: string;
9
+ };
10
+
11
+ export type CablesData = {
12
+ quoteData?: AugustusRFQOrderData;
13
+ };
14
+
15
+ export enum OrderbookSide {
16
+ bids = 'bids',
17
+ asks = 'asks',
18
+ }
19
+
20
+ /**
21
+ * Utils
22
+ */
23
+ export type CablesAPIParameters = {
24
+ url: string;
25
+ method: Method;
26
+ };
27
+ export class CablesRfqError extends Error {}
28
+
29
+ /**
30
+ * Types
31
+ */
32
+ export type PairData = {
33
+ base: string;
34
+ quote: string;
35
+ liquidityUSD: number;
36
+ };
37
+
38
+ export type PriceAndAmount = [string, string];
39
+
40
+ export type PriceData = {
41
+ bids: PriceAndAmount[];
42
+ asks: PriceAndAmount[];
43
+ };
44
+
45
+ export type PriceDataMap = {
46
+ [network: string]: {
47
+ [pair: string]: PriceData;
48
+ };
49
+ };
50
+
51
+ export type TokenDataMap = {
52
+ [network: string]: {
53
+ [token: string]: Token;
54
+ };
55
+ };
56
+
57
+ export type PairsDataMap = {
58
+ [network: string]: {
59
+ [token: string]: PairData;
60
+ };
61
+ };
62
+
63
+ /**
64
+ * Responses
65
+ */
66
+ export type CablesPricesResponse = {
67
+ prices: PriceDataMap;
68
+ };
69
+ export type CablesBlacklistResponse = {
70
+ blacklist: string[];
71
+ };
72
+ export type CablesTokensResponse = {
73
+ tokens: TokenDataMap;
74
+ };
75
+ export type CablesPairsResponse = {
76
+ pairs: PairsDataMap;
77
+ };
78
+
79
+ /**
80
+ * Rate Fetcher
81
+ */
82
+ export type CablesRateFetcherConfig = {
83
+ rateConfig: {
84
+ pairsReqParams: {
85
+ url: string;
86
+ headers?: RequestHeaders;
87
+ params?: any;
88
+ };
89
+ pricesReqParams: {
90
+ url: string;
91
+ headers?: RequestHeaders;
92
+ params?: any;
93
+ };
94
+ blacklistReqParams: {
95
+ url: string;
96
+ headers?: RequestHeaders;
97
+ params?: any;
98
+ };
99
+ tokensReqParams: {
100
+ url: string;
101
+ headers?: RequestHeaders;
102
+ params?: any;
103
+ };
104
+ pairsIntervalMs: number;
105
+ pricesIntervalMs: number;
106
+ blacklistIntervalMs: number;
107
+ tokensIntervalMs: number;
108
+
109
+ pairsCacheKey: string;
110
+ pricesCacheKey: string;
111
+ blacklistCacheKey: string;
112
+ tokensCacheKey: string;
113
+
114
+ blacklistCacheTTLSecs: number;
115
+ pairsCacheTTLSecs: number;
116
+ pricesCacheTTLSecs: number;
117
+ tokensCacheTTLSecs: number;
118
+ };
119
+ };
120
+
121
+ export type RestrictData = {
122
+ count: number;
123
+ addedDatetimeMs: number;
124
+ } | null;
125
+
126
+ export class SlippageError extends Error {
127
+ isSlippageError = true;
128
+ }
@@ -0,0 +1,151 @@
1
+ import Joi from 'joi';
2
+ import {
3
+ pairsResponseValidator,
4
+ pricesResponseValidator,
5
+ tokensResponseValidator,
6
+ blacklistResponseValidator,
7
+ } from './validators'; //
8
+
9
+ describe('Validation Schemas', () => {
10
+ describe('pairsResponseValidator', () => {
11
+ it('should validate correct pairs response', () => {
12
+ const validData = {
13
+ pairs: { '43114': { 'USDC/USDT': { base: 'USDC', quote: 'USDT' } } },
14
+ };
15
+ const { error } = pairsResponseValidator.validate(validData);
16
+ expect(error).toBeUndefined();
17
+ });
18
+
19
+ it('should invalidate incorrect pairs response', () => {
20
+ const invalidData = { pairs: { '43114': 'USDC/USDT' } };
21
+ const { error } = pairsResponseValidator.validate(invalidData);
22
+ expect(error).toBeDefined();
23
+ });
24
+ });
25
+
26
+ describe('pricesResponseValidator', () => {
27
+ it('should validate correct prices response', () => {
28
+ const validData = {
29
+ prices: {
30
+ '43114': {
31
+ 'USDC/USDT': {
32
+ bids: [
33
+ ['0.9996', '244305.9'],
34
+ ['0.9995', '236021.6'],
35
+ ],
36
+ asks: [
37
+ ['0.9996', '244305.9'],
38
+ ['0.9995', '236021.6'],
39
+ ],
40
+ },
41
+ },
42
+ },
43
+ };
44
+ const { error } = pricesResponseValidator.validate(validData);
45
+ expect(error).toBeUndefined();
46
+ });
47
+
48
+ it('should invalidate incorrect prices response', () => {
49
+ const invalidData = {
50
+ prices: {
51
+ chain1: {
52
+ bids: [
53
+ ['1000'], // invalid entry length
54
+ ],
55
+ asks: [['1010', '1']],
56
+ },
57
+ },
58
+ };
59
+ const { error } = pricesResponseValidator.validate(invalidData);
60
+ expect(error).toBeDefined();
61
+ });
62
+ });
63
+
64
+ describe('tokensResponseValidator', () => {
65
+ it('should validate correct tokens response', () => {
66
+ const validData = {
67
+ tokens: {
68
+ '43114': {
69
+ AVAX: {
70
+ symbol: 'AVAX',
71
+ decimals: 18,
72
+ name: 'AVAX',
73
+ address: '0x0000000000000000000000000000000000000000',
74
+ },
75
+ WAVAX: {
76
+ symbol: 'WAVAX',
77
+ decimals: 18,
78
+ name: 'WAVAX',
79
+ address: '0xB31f66AA3C1e785363F0875A1B74E27b85FD66c7',
80
+ },
81
+ 'WETH.e': {
82
+ symbol: 'WETH.e',
83
+ decimals: 18,
84
+ name: 'WETH.e',
85
+ address: '0x49D5c2BdFfac6CE2BFdB6640F4F80f226bc10bAB',
86
+ },
87
+ USDT: {
88
+ symbol: 'USDT',
89
+ decimals: 6,
90
+ name: 'USDT',
91
+ address: '0x9702230A8Ea53601f5cD2dc00fDBc13d4dF4A8c7',
92
+ },
93
+ USDC: {
94
+ symbol: 'USDC',
95
+ decimals: 6,
96
+ name: 'USDC',
97
+ address: '0xB97EF9Ef8734C71904D8002F8b6Bc66Dd9c48a6E',
98
+ },
99
+ 'USDC.e': {
100
+ symbol: 'USDC.e',
101
+ decimals: 6,
102
+ name: 'USDC.e',
103
+ address: '0xA7D7079b0FEaD91F3e65f86E8915Cb59c1a4C664',
104
+ },
105
+ },
106
+ },
107
+ };
108
+ const { error } = tokensResponseValidator.validate(validData);
109
+ expect(error).toBeUndefined();
110
+ });
111
+
112
+ it('should invalidate incorrect tokens response', () => {
113
+ const invalidData = {
114
+ tokens: {
115
+ chain1: {
116
+ ETH: {
117
+ symbol: '', // invalid value
118
+ name: 'Ethereum',
119
+ description: 'A popular cryptocurrency',
120
+ address: '0x...',
121
+ decimals: 18,
122
+ type: 'ERC20',
123
+ },
124
+ },
125
+ },
126
+ };
127
+ const { error } = tokensResponseValidator.validate(invalidData);
128
+ expect(error).toBeDefined();
129
+ });
130
+ });
131
+
132
+ describe('blacklistResponseValidator', () => {
133
+ it('should validate correct blacklist response', () => {
134
+ const validData = {
135
+ blacklist: ['0xAddress1', '0xAddress2'],
136
+ };
137
+ const { error } = blacklistResponseValidator.validate(validData);
138
+ expect(error).toBeUndefined();
139
+ });
140
+
141
+ it('should invalidate incorrect blacklist response', () => {
142
+ const invalidData = {
143
+ blacklist: [
144
+ '', // invalid value
145
+ ],
146
+ };
147
+ const { error } = blacklistResponseValidator.validate(invalidData);
148
+ expect(error).toBeDefined();
149
+ });
150
+ });
151
+ });
@@ -0,0 +1,61 @@
1
+ import joi from 'joi';
2
+
3
+ const pairValidator = joi.object({
4
+ base: joi.string().min(1),
5
+ quote: joi.string().min(1),
6
+ liquidityUSD: joi.number().min(0),
7
+ baseAddress: joi.string().min(1),
8
+ quoteAddress: joi.string().min(1),
9
+ baseDecimals: joi.number().min(0),
10
+ quoteDecimals: joi.number().min(0),
11
+ });
12
+
13
+ const pairMap = joi.object().pattern(
14
+ joi.string(), // Pair name ETH/USDT
15
+ pairValidator,
16
+ );
17
+
18
+ export const pairsResponseValidator = joi.object({
19
+ pairs: joi.object().pattern(
20
+ joi.string(), // chain id
21
+ pairMap,
22
+ ),
23
+ });
24
+
25
+ const orderbookEntry = joi.array().items(joi.string().min(1)).length(2);
26
+
27
+ const orderbookValidator = joi.object({
28
+ bids: joi.array().items(orderbookEntry),
29
+ asks: joi.array().items(orderbookEntry),
30
+ });
31
+
32
+ const chainDataSchema = joi.object().pattern(
33
+ joi.string(), // pair name USDC/USDT
34
+ orderbookValidator,
35
+ );
36
+
37
+ export const pricesResponseValidator = joi.object({
38
+ prices: joi.object().pattern(
39
+ joi.string(), // chain id
40
+ chainDataSchema,
41
+ ),
42
+ });
43
+
44
+ const tokenValidator = joi.object({
45
+ symbol: joi.string().min(1),
46
+ name: joi.string().min(1),
47
+ description: joi.string().min(1),
48
+ address: joi.string().min(1),
49
+ decimals: joi.number().min(0),
50
+ type: joi.string().min(1),
51
+ });
52
+
53
+ const chainTokens = joi.object().pattern(joi.string(), tokenValidator);
54
+
55
+ export const tokensResponseValidator = joi.object({
56
+ tokens: joi.object().pattern(joi.string(), chainTokens),
57
+ });
58
+
59
+ export const blacklistResponseValidator = joi.object({
60
+ blacklist: joi.array().items(joi.string().min(1)),
61
+ });
@@ -201,22 +201,22 @@ const limitsWide: DexLimits = {
201
201
  withdrawableToken0: {
202
202
  available: BigInt(34242332879776515083099999),
203
203
  expandsTo: BigInt(34242332879776515083099999),
204
- expandsDuration: BigInt(0),
204
+ expandsDuration: 0n,
205
205
  },
206
206
  withdrawableToken1: {
207
207
  available: BigInt(34242332879776515083099999),
208
208
  expandsTo: BigInt(34242332879776515083099999),
209
- expandsDuration: BigInt(22),
209
+ expandsDuration: 22n,
210
210
  },
211
211
  borrowableToken0: {
212
212
  available: BigInt(34242332879776515083099999),
213
213
  expandsTo: BigInt(34242332879776515083099999),
214
- expandsDuration: BigInt(0),
214
+ expandsDuration: 0n,
215
215
  },
216
216
  borrowableToken1: {
217
217
  available: BigInt(34242332879776515083099999),
218
218
  expandsTo: BigInt(34242332879776515083099999),
219
- expandsDuration: BigInt(308),
219
+ expandsDuration: 308n,
220
220
  },
221
221
  };
222
222
 
@@ -40,12 +40,6 @@ function getReaderCalldata(
40
40
  item => item.address.toLowerCase() === poolAddress.toLowerCase(),
41
41
  );
42
42
 
43
- console.log('amounts: ', amounts);
44
- console.log(
45
- 'pool!.token0.toLowerCase() === srcToken.toLowerCase() ? true : false,: ',
46
- pool!.token0.toLowerCase() === srcToken.toLowerCase() ? true : false,
47
- );
48
-
49
43
  return amounts.map(amount => ({
50
44
  target: exchangeAddress,
51
45
  callData: readerIface.encodeFunctionData(funcName, [
@@ -116,21 +110,7 @@ async function checkOnChainPricing(
116
110
  decodeReaderResult(readerResult, readerIface, funcName),
117
111
  );
118
112
 
119
- console.log('EXPECTED PRICES: ', expectedPrices);
120
- console.log('ACTUAL PRICES: ', prices);
121
-
122
113
  expect(prices).toEqual(expectedPrices);
123
-
124
- // expect(
125
- // prices.every((price, index) => {
126
- // const expectedPrice = expectedPrices[index];
127
- // if (expectedPrice === 0n) {
128
- // return price === 0n;
129
- // }
130
- // const percentDiff = ((price - expectedPrice) * 100n) / expectedPrice;
131
- // return percentDiff <= 0.01 && percentDiff >= -0.01;
132
- // }),
133
- // ).toBe(true);
134
114
  }
135
115
 
136
116
  async function testPricingOnNetwork(