@paraswap/dex-lib 3.10.0 → 3.10.2

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 (43) hide show
  1. package/build/abi/fluid-dex/dexFactory.abi.json +506 -0
  2. package/build/abi/fluid-dex/fluid-dex.abi.json +922 -0
  3. package/build/abi/fluid-dex/liquidityUserModule.abi.json +145 -0
  4. package/build/abi/fluid-dex/resolver.abi.json +999 -0
  5. package/build/dex/fluid-dex/config.d.ts +4 -0
  6. package/build/dex/fluid-dex/config.js +20 -0
  7. package/build/dex/fluid-dex/config.js.map +1 -0
  8. package/build/dex/fluid-dex/fluid-dex-factory.d.ts +49 -0
  9. package/build/dex/fluid-dex/fluid-dex-factory.js +104 -0
  10. package/build/dex/fluid-dex/fluid-dex-factory.js.map +1 -0
  11. package/build/dex/fluid-dex/fluid-dex-pool.d.ts +47 -0
  12. package/build/dex/fluid-dex/fluid-dex-pool.js +119 -0
  13. package/build/dex/fluid-dex/fluid-dex-pool.js.map +1 -0
  14. package/build/dex/fluid-dex/fluid-dex.d.ts +127 -0
  15. package/build/dex/fluid-dex/fluid-dex.js +502 -0
  16. package/build/dex/fluid-dex/fluid-dex.js.map +1 -0
  17. package/build/dex/fluid-dex/types.d.ts +52 -0
  18. package/build/dex/fluid-dex/types.js +3 -0
  19. package/build/dex/fluid-dex/types.js.map +1 -0
  20. package/build/dex/fluid-dex/utils.d.ts +2 -0
  21. package/build/dex/fluid-dex/utils.js +18 -0
  22. package/build/dex/fluid-dex/utils.js.map +1 -0
  23. package/build/dex/index.js +2 -0
  24. package/build/dex/index.js.map +1 -1
  25. package/build/dex/paraswap-limit-orders/paraswap-limit-orders.js +1 -1
  26. package/build/dex/paraswap-limit-orders/paraswap-limit-orders.js.map +1 -1
  27. package/package.json +1 -1
  28. package/src/abi/fluid-dex/dexFactory.abi.json +506 -0
  29. package/src/abi/fluid-dex/fluid-dex.abi.json +922 -0
  30. package/src/abi/fluid-dex/liquidityUserModule.abi.json +145 -0
  31. package/src/abi/fluid-dex/resolver.abi.json +999 -0
  32. package/src/dex/fluid-dex/config.ts +20 -0
  33. package/src/dex/fluid-dex/fluid-dex-e2e.test.ts +153 -0
  34. package/src/dex/fluid-dex/fluid-dex-events.test.ts +293 -0
  35. package/src/dex/fluid-dex/fluid-dex-factory.ts +143 -0
  36. package/src/dex/fluid-dex/fluid-dex-integration.test.ts +299 -0
  37. package/src/dex/fluid-dex/fluid-dex-pool.ts +178 -0
  38. package/src/dex/fluid-dex/fluid-dex.ts +790 -0
  39. package/src/dex/fluid-dex/types.ts +62 -0
  40. package/src/dex/fluid-dex/utils.ts +15 -0
  41. package/src/dex/index.ts +2 -0
  42. package/src/dex/paraswap-limit-orders/paraswap-limit-orders.ts +1 -1
  43. package/tests/constants-e2e.ts +2 -2
@@ -0,0 +1,4 @@
1
+ import { DexParams } from './types';
2
+ import { DexConfigMap } from '../../types';
3
+ export declare const FluidDexConfig: DexConfigMap<DexParams>;
4
+ export declare const FLUID_DEX_GAS_COST = 154000;
@@ -0,0 +1,20 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.FLUID_DEX_GAS_COST = exports.FluidDexConfig = void 0;
4
+ const constants_1 = require("../../constants");
5
+ exports.FluidDexConfig = {
6
+ FluidDex: {
7
+ [constants_1.Network.MAINNET]: {
8
+ commonAddresses: {
9
+ liquidityProxy: '0x52aa899454998be5b000ad077a46bbe360f4e497',
10
+ resolver: '0xE8a07a32489BD9d5a00f01A55749Cf5cB854Fd13',
11
+ dexFactory: '0x91716C4EDA1Fb55e84Bf8b4c7085f84285c19085',
12
+ },
13
+ },
14
+ },
15
+ };
16
+ // Uniswap takes total gas of 125k = 21k base gas & 104k swap (this is when user has token balance)
17
+ // Fluid takes total gas of 175k = 21k base gas & 154k swap (this is when user has token balance),
18
+ // with ETH swaps costing less (because no WETH conversion)
19
+ exports.FLUID_DEX_GAS_COST = 154000;
20
+ //# sourceMappingURL=config.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"config.js","sourceRoot":"","sources":["../../../src/dex/fluid-dex/config.ts"],"names":[],"mappings":";;;AAEA,+CAA0C;AAE7B,QAAA,cAAc,GAA4B;IACrD,QAAQ,EAAE;QACR,CAAC,mBAAO,CAAC,OAAO,CAAC,EAAE;YACjB,eAAe,EAAE;gBACf,cAAc,EAAE,4CAA4C;gBAC5D,QAAQ,EAAE,4CAA4C;gBACtD,UAAU,EAAE,4CAA4C;aACzD;SACF;KACF;CACF,CAAC;AAEF,mGAAmG;AACnG,kGAAkG;AAClG,2DAA2D;AAC9C,QAAA,kBAAkB,GAAG,MAAO,CAAC"}
@@ -0,0 +1,49 @@
1
+ import { Interface } from '@ethersproject/abi';
2
+ import { BytesLike } from 'ethers/lib/utils';
3
+ import { DeepReadonly } from 'ts-essentials';
4
+ import { Log, Logger } from '../../types';
5
+ import { StatefulEventSubscriber } from '../../stateful-event-subscriber';
6
+ import { IDexHelper } from '../../dex-helper/idex-helper';
7
+ import { CommonAddresses, Pool } from './types';
8
+ import { MultiResult } from '../../lib/multi-wrapper';
9
+ import { Address } from '../../types';
10
+ export declare class FluidDexFactory extends StatefulEventSubscriber<Pool[]> {
11
+ readonly parentName: string;
12
+ readonly commonAddresses: CommonAddresses;
13
+ protected network: number;
14
+ protected dexHelper: IDexHelper;
15
+ handlers: {
16
+ [event: string]: (event: any, state: DeepReadonly<Pool[]>, log: Readonly<Log>) => Promise<DeepReadonly<Pool[]> | null>;
17
+ };
18
+ logDecoder: (log: Log) => any;
19
+ addressesSubscribed: Address[];
20
+ protected dexFactoryIface: Interface;
21
+ protected resolverIface: Interface;
22
+ constructor(parentName: string, commonAddresses: CommonAddresses, network: number, dexHelper: IDexHelper, logger: Logger);
23
+ /**
24
+ * Handle a trade rate change on the pool.
25
+ */
26
+ handleDexDeployed(event: any, state: DeepReadonly<Pool[]>, log: Readonly<Log>): Promise<DeepReadonly<Pool[]> | null>;
27
+ decodePool: (result: MultiResult<BytesLike> | BytesLike) => Pool;
28
+ /**
29
+ * The function is called every time any of the subscribed
30
+ * addresses release log. The function accepts the current
31
+ * state, updates the state according to the log, and returns
32
+ * the updated state.
33
+ * @param state - Current state of event subscriber
34
+ * @param log - Log released by one of the subscribed addresses
35
+ * @returns Updates state of the event subscriber after the log
36
+ */
37
+ processLog(state: DeepReadonly<Pool[]>, log: Readonly<Log>): Promise<DeepReadonly<Pool[]> | null>;
38
+ getStateOrGenerate(blockNumber: number, readonly?: boolean): Promise<DeepReadonly<Pool[]>>;
39
+ /**
40
+ * The function generates state using on-chain calls. This
41
+ * function is called to regenerate state if the event based
42
+ * system fails to fetch events and the local state is no
43
+ * more correct.
44
+ * @param blockNumber - Blocknumber for which the state should
45
+ * should be generated
46
+ * @returns state of the event subscriber at blocknumber
47
+ */
48
+ generateState(blockNumber: number): Promise<DeepReadonly<Pool[]>>;
49
+ }
@@ -0,0 +1,104 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.FluidDexFactory = void 0;
7
+ const abi_1 = require("@ethersproject/abi");
8
+ const utils_1 = require("../../utils");
9
+ const stateful_event_subscriber_1 = require("../../stateful-event-subscriber");
10
+ const resolver_abi_json_1 = __importDefault(require("../../abi/fluid-dex/resolver.abi.json"));
11
+ const dexFactory_abi_json_1 = __importDefault(require("../../abi/fluid-dex/dexFactory.abi.json"));
12
+ const decoders_1 = require("../../lib/decoders");
13
+ const ethers_1 = require("ethers");
14
+ class FluidDexFactory extends stateful_event_subscriber_1.StatefulEventSubscriber {
15
+ constructor(parentName, commonAddresses, network, dexHelper, logger) {
16
+ super(parentName, 'getAllPools', dexHelper, logger);
17
+ this.parentName = parentName;
18
+ this.commonAddresses = commonAddresses;
19
+ this.network = network;
20
+ this.dexHelper = dexHelper;
21
+ this.handlers = {};
22
+ this.dexFactoryIface = new abi_1.Interface(dexFactory_abi_json_1.default);
23
+ this.resolverIface = new abi_1.Interface(resolver_abi_json_1.default);
24
+ this.decodePool = (result) => {
25
+ return (0, decoders_1.generalDecoder)(result, ['tuple(address pool, address token0, address token1, uint256 fee)'], undefined, decoded => {
26
+ return {
27
+ address: decoded[0].toLowerCase(),
28
+ token0: decoded[1].toLowerCase(),
29
+ token1: decoded[2].toLowerCase(),
30
+ };
31
+ });
32
+ };
33
+ this.logDecoder = (log) => this.dexFactoryIface.parseLog(log);
34
+ this.addressesSubscribed = [commonAddresses.dexFactory];
35
+ // Add handlers
36
+ this.handlers['DexDeployed'] = this.handleDexDeployed.bind(this);
37
+ }
38
+ /**
39
+ * Handle a trade rate change on the pool.
40
+ */
41
+ async handleDexDeployed(event, state, log) {
42
+ const blockNumber_ = await this.dexHelper.provider.getBlockNumber();
43
+ return this.getStateOrGenerate(blockNumber_, false);
44
+ }
45
+ /**
46
+ * The function is called every time any of the subscribed
47
+ * addresses release log. The function accepts the current
48
+ * state, updates the state according to the log, and returns
49
+ * the updated state.
50
+ * @param state - Current state of event subscriber
51
+ * @param log - Log released by one of the subscribed addresses
52
+ * @returns Updates state of the event subscriber after the log
53
+ */
54
+ async processLog(state, log) {
55
+ try {
56
+ let event;
57
+ try {
58
+ event = this.logDecoder(log);
59
+ }
60
+ catch (e) {
61
+ return null;
62
+ }
63
+ if (event.name in this.handlers) {
64
+ return await this.handlers[event.name](event, state, log);
65
+ }
66
+ }
67
+ catch (e) {
68
+ (0, utils_1.catchParseLogError)(e, this.logger);
69
+ }
70
+ return null;
71
+ }
72
+ async getStateOrGenerate(blockNumber, readonly = false) {
73
+ let state = this.getState(blockNumber);
74
+ if (!state) {
75
+ state = await this.generateState(blockNumber);
76
+ if (!readonly)
77
+ this.setState(state, blockNumber);
78
+ }
79
+ return state;
80
+ }
81
+ /**
82
+ * The function generates state using on-chain calls. This
83
+ * function is called to regenerate state if the event based
84
+ * system fails to fetch events and the local state is no
85
+ * more correct.
86
+ * @param blockNumber - Blocknumber for which the state should
87
+ * should be generated
88
+ * @returns state of the event subscriber at blocknumber
89
+ */
90
+ async generateState(blockNumber) {
91
+ const resolverContract = new ethers_1.Contract(this.commonAddresses.resolver, resolver_abi_json_1.default, this.dexHelper.provider);
92
+ const rawResult = await resolverContract.callStatic.getAllPools({
93
+ blockTag: blockNumber,
94
+ });
95
+ const pools = rawResult.map((result) => ({
96
+ address: result[0],
97
+ token0: result[1],
98
+ token1: result[2],
99
+ }));
100
+ return pools;
101
+ }
102
+ }
103
+ exports.FluidDexFactory = FluidDexFactory;
104
+ //# sourceMappingURL=fluid-dex-factory.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"fluid-dex-factory.js","sourceRoot":"","sources":["../../../src/dex/fluid-dex/fluid-dex-factory.ts"],"names":[],"mappings":";;;;;;AAAA,4CAA+C;AAI/C,uCAAiD;AACjD,+EAA0E;AAE1E,8FAAgE;AAChE,kGAAoE;AAIpE,iDAAoD;AACpD,mCAAkC;AAElC,MAAa,eAAgB,SAAQ,mDAA+B;IAelE,YACW,UAAkB,EAClB,eAAgC,EAC/B,OAAe,EACf,SAAqB,EAC/B,MAAc;QAEd,KAAK,CAAC,UAAU,EAAE,aAAa,EAAE,SAAS,EAAE,MAAM,CAAC,CAAC;QAN3C,eAAU,GAAV,UAAU,CAAQ;QAClB,oBAAe,GAAf,eAAe,CAAiB;QAC/B,YAAO,GAAP,OAAO,CAAQ;QACf,cAAS,GAAT,SAAS,CAAY;QAlBjC,aAAQ,GAMJ,EAAE,CAAC;QAKG,oBAAe,GAAG,IAAI,eAAS,CAAC,6BAAa,CAAC,CAAC;QAC/C,kBAAa,GAAG,IAAI,eAAS,CAAC,2BAAW,CAAC,CAAC;QA8BrD,eAAU,GAAG,CAAC,MAA0C,EAAQ,EAAE;YAChE,OAAO,IAAA,yBAAc,EACnB,MAAM,EACN,CAAC,kEAAkE,CAAC,EACpE,SAAS,EACT,OAAO,CAAC,EAAE;gBACR,OAAO;oBACL,OAAO,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;YACV,IAAA,0BAAkB,EAAC,CAAC,EAAE,IAAI,CAAC,MAAM,CAAC,CAAC;SACpC;QAED,OAAO,IAAI,CAAC;IACd,CAAC;IAED,KAAK,CAAC,kBAAkB,CACtB,WAAmB,EACnB,WAAoB,KAAK;QAEzB,IAAI,KAAK,GAAG,IAAI,CAAC,QAAQ,CAAC,WAAW,CAAC,CAAC;QACvC,IAAI,CAAC,KAAK,EAAE;YACV,KAAK,GAAG,MAAM,IAAI,CAAC,aAAa,CAAC,WAAW,CAAC,CAAC;YAC9C,IAAI,CAAC,QAAQ;gBAAE,IAAI,CAAC,QAAQ,CAAC,KAAK,EAAE,WAAW,CAAC,CAAC;SAClD;QACD,OAAO,KAAK,CAAC;IACf,CAAC;IAED;;;;;;;;OAQG;IACH,KAAK,CAAC,aAAa,CAAC,WAAmB;QACrC,MAAM,gBAAgB,GAAG,IAAI,iBAAQ,CACnC,IAAI,CAAC,eAAe,CAAC,QAAQ,EAC7B,2BAAW,EACX,IAAI,CAAC,SAAS,CAAC,QAAQ,CACxB,CAAC;QACF,MAAM,SAAS,GAAG,MAAM,gBAAgB,CAAC,UAAU,CAAC,WAAW,CAAC;YAC9D,QAAQ,EAAE,WAAW;SACtB,CAAC,CAAC;QAEH,MAAM,KAAK,GAAW,SAAS,CAAC,GAAG,CAAC,CAAC,MAAW,EAAE,EAAE,CAAC,CAAC;YACpD,OAAO,EAAE,MAAM,CAAC,CAAC,CAAC;YAClB,MAAM,EAAE,MAAM,CAAC,CAAC,CAAC;YACjB,MAAM,EAAE,MAAM,CAAC,CAAC,CAAC;SAClB,CAAC,CAAC,CAAC;QAEJ,OAAO,KAAK,CAAC;IACf,CAAC;CACF;AA/HD,0CA+HC"}
@@ -0,0 +1,47 @@
1
+ import { Interface } from '@ethersproject/abi';
2
+ import { DeepReadonly } from 'ts-essentials';
3
+ import { Log, Logger } from '../../types';
4
+ import { StatefulEventSubscriber } from '../../stateful-event-subscriber';
5
+ import { IDexHelper } from '../../dex-helper/idex-helper';
6
+ import { CommonAddresses, FluidDexPoolState } from './types';
7
+ import { Address } from '../../types';
8
+ export declare class FluidDexEventPool extends StatefulEventSubscriber<FluidDexPoolState> {
9
+ readonly parentName: string;
10
+ readonly pool: Address;
11
+ readonly commonAddresses: CommonAddresses;
12
+ protected network: number;
13
+ readonly dexHelper: IDexHelper;
14
+ handlers: {
15
+ [event: string]: (event: any, state: DeepReadonly<FluidDexPoolState>, log: Readonly<Log>) => Promise<DeepReadonly<FluidDexPoolState> | null>;
16
+ };
17
+ logDecoder: (log: Log) => any;
18
+ addressesSubscribed: Address[];
19
+ protected liquidityIface: Interface;
20
+ constructor(parentName: string, pool: Address, commonAddresses: CommonAddresses, network: number, dexHelper: IDexHelper, logger: Logger);
21
+ /**
22
+ * Handle a trade rate change on the pool.
23
+ */
24
+ handleOperate(event: any, state: DeepReadonly<FluidDexPoolState>, log: Readonly<Log>): Promise<DeepReadonly<FluidDexPoolState> | null>;
25
+ /**
26
+ * The function is called every time any of the subscribed
27
+ * addresses release log. The function accepts the current
28
+ * state, updates the state according to the log, and returns
29
+ * the updated state.
30
+ * @param state - Current state of event subscriber
31
+ * @param log - Log released by one of the subscribed addresses
32
+ * @returns Updates state of the event subscriber after the log
33
+ */
34
+ processLog(state: DeepReadonly<FluidDexPoolState>, log: Readonly<Log>): Promise<DeepReadonly<FluidDexPoolState> | null>;
35
+ getStateOrGenerate(blockNumber: number, readonly?: boolean): Promise<FluidDexPoolState>;
36
+ /**
37
+ * The function generates state using on-chain calls. This
38
+ * function is called to regenerate state if the event based
39
+ * system fails to fetch events and the local state is no
40
+ * more correct.
41
+ * @param blockNumber - Blocknumber for which the state should
42
+ * should be generated
43
+ * @returns state of the event subscriber at blocknumber
44
+ */
45
+ generateState(blockNumber: number): Promise<DeepReadonly<FluidDexPoolState>>;
46
+ private convertToFluidDexPoolState;
47
+ }
@@ -0,0 +1,119 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.FluidDexEventPool = void 0;
7
+ const abi_1 = require("@ethersproject/abi");
8
+ const utils_1 = require("../../utils");
9
+ const stateful_event_subscriber_1 = require("../../stateful-event-subscriber");
10
+ const resolver_abi_json_1 = __importDefault(require("../../abi/fluid-dex/resolver.abi.json"));
11
+ const liquidityUserModule_abi_json_1 = __importDefault(require("../../abi/fluid-dex/liquidityUserModule.abi.json"));
12
+ const ethers_1 = require("ethers");
13
+ class FluidDexEventPool extends stateful_event_subscriber_1.StatefulEventSubscriber {
14
+ constructor(parentName, pool, commonAddresses, network, dexHelper, logger) {
15
+ super(parentName, 'FluidDex_' + pool, dexHelper, logger);
16
+ this.parentName = parentName;
17
+ this.pool = pool;
18
+ this.commonAddresses = commonAddresses;
19
+ this.network = network;
20
+ this.dexHelper = dexHelper;
21
+ this.handlers = {};
22
+ this.liquidityIface = new abi_1.Interface(liquidityUserModule_abi_json_1.default);
23
+ this.logDecoder = (log) => this.liquidityIface.parseLog(log);
24
+ this.addressesSubscribed = [commonAddresses.liquidityProxy];
25
+ // Add handlers
26
+ this.handlers['LogOperate'] = this.handleOperate.bind(this);
27
+ }
28
+ /**
29
+ * Handle a trade rate change on the pool.
30
+ */
31
+ async handleOperate(event, state, log) {
32
+ if (!(event.args.user in [this.pool])) {
33
+ return null;
34
+ }
35
+ const resolverContract = new ethers_1.Contract(this.commonAddresses.resolver, resolver_abi_json_1.default, this.dexHelper.provider);
36
+ const rawResult = await resolverContract.callStatic.getPoolReservesAdjusted(this.pool, {
37
+ blockTag: this.dexHelper.provider,
38
+ });
39
+ const generatedState = this.convertToFluidDexPoolState(rawResult);
40
+ this.setState(generatedState, await this.dexHelper.provider.getBlockNumber());
41
+ return generatedState;
42
+ }
43
+ /**
44
+ * The function is called every time any of the subscribed
45
+ * addresses release log. The function accepts the current
46
+ * state, updates the state according to the log, and returns
47
+ * the updated state.
48
+ * @param state - Current state of event subscriber
49
+ * @param log - Log released by one of the subscribed addresses
50
+ * @returns Updates state of the event subscriber after the log
51
+ */
52
+ async processLog(state, log) {
53
+ try {
54
+ const event = this.logDecoder(log);
55
+ if (event.name in this.handlers) {
56
+ return await this.handlers[event.name](event, state, log);
57
+ }
58
+ }
59
+ catch (e) {
60
+ (0, utils_1.catchParseLogError)(e, this.logger);
61
+ }
62
+ return null;
63
+ }
64
+ async getStateOrGenerate(blockNumber, readonly = false) {
65
+ let state = this.getState(blockNumber);
66
+ if (!state) {
67
+ state = await this.generateState(blockNumber);
68
+ if (!readonly)
69
+ this.setState(state, blockNumber);
70
+ }
71
+ return state;
72
+ }
73
+ /**
74
+ * The function generates state using on-chain calls. This
75
+ * function is called to regenerate state if the event based
76
+ * system fails to fetch events and the local state is no
77
+ * more correct.
78
+ * @param blockNumber - Blocknumber for which the state should
79
+ * should be generated
80
+ * @returns state of the event subscriber at blocknumber
81
+ */
82
+ async generateState(blockNumber) {
83
+ const resolverContract = new ethers_1.Contract(this.commonAddresses.resolver, resolver_abi_json_1.default, this.dexHelper.provider);
84
+ const rawResult = await resolverContract.callStatic.getPoolReservesAdjusted(this.pool, {
85
+ blockTag: blockNumber,
86
+ });
87
+ const convertedResult = this.convertToFluidDexPoolState(rawResult);
88
+ return convertedResult;
89
+ }
90
+ convertToFluidDexPoolState(input) {
91
+ // Ignore the first three addresses
92
+ const [, , , feeHex, collateralReservesHex, debtReservesHex] = input;
93
+ // Convert fee from hex to number
94
+ const fee = Number(feeHex.toString());
95
+ // Convert collateral reserves
96
+ const collateralReserves = {
97
+ token0RealReserves: BigInt(collateralReservesHex[0].toString()),
98
+ token1RealReserves: BigInt(collateralReservesHex[1].toString()),
99
+ token0ImaginaryReserves: BigInt(collateralReservesHex[2].toString()),
100
+ token1ImaginaryReserves: BigInt(collateralReservesHex[3].toString()),
101
+ };
102
+ // Convert debt reserves
103
+ const debtReserves = {
104
+ token0Debt: BigInt(debtReservesHex[0].toString()),
105
+ token1Debt: BigInt(debtReservesHex[1].toString()),
106
+ token0RealReserves: BigInt(debtReservesHex[2].toString()),
107
+ token1RealReserves: BigInt(debtReservesHex[3].toString()),
108
+ token0ImaginaryReserves: BigInt(debtReservesHex[4].toString()),
109
+ token1ImaginaryReserves: BigInt(debtReservesHex[5].toString()),
110
+ };
111
+ return {
112
+ collateralReserves,
113
+ debtReserves,
114
+ fee,
115
+ };
116
+ }
117
+ }
118
+ exports.FluidDexEventPool = FluidDexEventPool;
119
+ //# sourceMappingURL=fluid-dex-pool.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"fluid-dex-pool.js","sourceRoot":"","sources":["../../../src/dex/fluid-dex/fluid-dex-pool.ts"],"names":[],"mappings":";;;;;;AAAA,4CAA+C;AAG/C,uCAAiD;AACjD,+EAA0E;AAE1E,8FAAgE;AAChE,oHAA4E;AAQ5E,mCAAkC;AAElC,MAAa,iBAAkB,SAAQ,mDAA0C;IAc/E,YACW,UAAkB,EAClB,IAAa,EACb,eAAgC,EAC/B,OAAe,EAChB,SAAqB,EAC9B,MAAc;QAEd,KAAK,CAAC,UAAU,EAAE,WAAW,GAAG,IAAI,EAAE,SAAS,EAAE,MAAM,CAAC,CAAC;QAPhD,eAAU,GAAV,UAAU,CAAQ;QAClB,SAAI,GAAJ,IAAI,CAAS;QACb,oBAAe,GAAf,eAAe,CAAiB;QAC/B,YAAO,GAAP,OAAO,CAAQ;QAChB,cAAS,GAAT,SAAS,CAAY;QAlBhC,aAAQ,GAMJ,EAAE,CAAC;QAKG,mBAAc,GAAG,IAAI,eAAS,CAAC,sCAAY,CAAC,CAAC;QAYrD,IAAI,CAAC,UAAU,GAAG,CAAC,GAAQ,EAAE,EAAE,CAAC,IAAI,CAAC,cAAc,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC;QAClE,IAAI,CAAC,mBAAmB,GAAG,CAAC,eAAe,CAAC,cAAc,CAAC,CAAC;QAE5D,eAAe;QACf,IAAI,CAAC,QAAQ,CAAC,YAAY,CAA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CAAC,CAAC,QAAQ,EAAE,CAAC;YAC/D,uBAAuB,EAAE,MAAM,CAAC,qBAAqB,CAAC,CAAC,CAAC,CAAC,QAAQ,EAAE,CAAC;YACpE,uBAAuB,EAAE,MAAM,CAAC,qBAAqB,CAAC,CAAC,CAAC,CAAC,QAAQ,EAAE,CAAC;SACrE,CAAC;QAEF,wBAAwB;QACxB,MAAM,YAAY,GAAiB;YACjC,UAAU,EAAE,MAAM,CAAC,eAAe,CAAC,CAAC,CAAC,CAAC,QAAQ,EAAE,CAAC;YACjD,UAAU,EAAE,MAAM,CAAC,eAAe,CAAC,CAAC,CAAC,CAAC,QAAQ,EAAE,CAAC;YACjD,kBAAkB,EAAE,MAAM,CAAC,eAAe,CAAC,CAAC,CAAC,CAAC,QAAQ,EAAE,CAAC;YACzD,kBAAkB,EAAE,MAAM,CAAC,eAAe,CAAC,CAAC,CAAC,CAAC,QAAQ,EAAE,CAAC;YACzD,uBAAuB,EAAE,MAAM,CAAC,eAAe,CAAC,CAAC,CAAC,CAAC,QAAQ,EAAE,CAAC;YAC9D,uBAAuB,EAAE,MAAM,CAAC,eAAe,CAAC,CAAC,CAAC,CAAC,QAAQ,EAAE,CAAC;SAC/D,CAAC;QAEF,OAAO;YACL,kBAAkB;YAClB,YAAY;YACZ,GAAG;SACJ,CAAC;IACJ,CAAC;CACF;AAhKD,8CAgKC"}
@@ -0,0 +1,127 @@
1
+ import { BytesLike } from 'ethers/lib/utils';
2
+ import { Interface } from '@ethersproject/abi';
3
+ import { Token, Address, ExchangePrices, PoolPrices, AdapterExchangeParam, PoolLiquidity, DexExchangeParam, Logger } from '../../types';
4
+ import { SwapSide, Network } from '../../constants';
5
+ import { Context, IDex } from '../../dex/idex';
6
+ import { IDexHelper } from '../../dex-helper/idex-helper';
7
+ import { FluidDexData, FluidDexPool, Pool } from './types';
8
+ import { SimpleExchange } from '../simple-exchange';
9
+ import { FluidDexEventPool } from './fluid-dex-pool';
10
+ import { FluidDexFactory } from './fluid-dex-factory';
11
+ import { MultiResult } from '../../lib/multi-wrapper';
12
+ export declare class FluidDex extends SimpleExchange implements IDex<FluidDexData> {
13
+ readonly network: Network;
14
+ readonly dexKey: string;
15
+ readonly dexHelper: IDexHelper;
16
+ eventPools: {
17
+ [id: string]: FluidDexEventPool;
18
+ };
19
+ readonly hasConstantPriceLargeAmounts = false;
20
+ readonly needWrapNative = false;
21
+ readonly isFeeOnTransferSupported = false;
22
+ static dexKeysWithNetwork: {
23
+ key: string;
24
+ networks: Network[];
25
+ }[];
26
+ logger: Logger;
27
+ pools: FluidDexPool[];
28
+ readonly factory: FluidDexFactory;
29
+ readonly fluidDexPoolIface: Interface;
30
+ FEE_100_PERCENT: bigint;
31
+ constructor(network: Network, dexKey: string, dexHelper: IDexHelper);
32
+ private fetchFluidDexPools;
33
+ initializePricing(blockNumber: number): Promise<void>;
34
+ getAdapters(side: SwapSide): null;
35
+ decodePools: (result: MultiResult<BytesLike> | BytesLike) => Pool[];
36
+ getPoolIdentifiers(srcToken: Token, destToken: Token, side: SwapSide, blockNumber: number): Promise<string[]>;
37
+ getPoolByTokenPair(srcToken: Address, destToken: Address): Promise<FluidDexPool | null>;
38
+ getPricesVolume(srcToken: Token, destToken: Token, amounts: bigint[], side: SwapSide, blockNumber: number, limitPools?: string[]): Promise<null | ExchangePrices<FluidDexData>>;
39
+ getCalldataGasCost(poolPrices: PoolPrices<FluidDexData>): number | number[];
40
+ getAdapterParam(srcToken: string, destToken: string, srcAmount: string, destAmount: string, data: FluidDexData, side: SwapSide): AdapterExchangeParam;
41
+ getTopPoolsForToken(tokenAddress: Address, limit: number): Promise<PoolLiquidity[]>;
42
+ getDexParam(srcToken: Address, destToken: Address, srcAmount: string, destAmount: string, recipient: Address, data: FluidDexData, side: SwapSide, context: Context, executorAddress: Address): Promise<DexExchangeParam>;
43
+ /**
44
+ * Calculates the output amount for a given input amount in a swap operation.
45
+ * @param swap0To1 - Direction of the swap. True if swapping token0 for token1, false otherwise.
46
+ * @param amountIn - The amount of input token to be swapped (as a BigInt).
47
+ * @param colReserves - The reserves of the collateral pool.
48
+ * @param debtReserves - The reserves of the debt pool.
49
+ * @param inDecimals - The number of decimals for the input token.
50
+ * @param outDecimals - The number of decimals for the output token.
51
+ * @returns The calculated output amount (as a BigInt).
52
+ */
53
+ private swapIn;
54
+ /**
55
+ * Calculates the output amount for a given input amount in a swap operation.
56
+ * @param swap0To1 - Direction of the swap. True if swapping token0 for token1, false otherwise.
57
+ * @param amountToSwap - The amount of input token to be swapped.
58
+ * @param colReserves - The reserves of the collateral pool.
59
+ * @param debtReserves - The reserves of the debt pool.
60
+ * @returns The calculated output amount.
61
+ */
62
+ private swapInAdjusted;
63
+ applyFee(amount: bigint, fee: bigint): bigint;
64
+ /**
65
+ * Given an input amount of asset and pair reserves, returns the maximum output amount of the other asset.
66
+ * @param amountIn - The amount of input asset.
67
+ * @param iReserveIn - Imaginary token reserve with input amount.
68
+ * @param iReserveOut - Imaginary token reserve of output amount.
69
+ * @returns The maximum output amount of the other asset.
70
+ */
71
+ private getAmountOut;
72
+ /**
73
+ * Given an output amount of asset and pair reserves, returns the input amount of the other asset
74
+ * @param amountOut - Desired output amount of the asset.
75
+ * @param iReserveIn - Imaginary token reserve of input amount.
76
+ * @param iReserveOut - Imaginary token reserve of output amount.
77
+ * @returns The input amount of the other asset.
78
+ */
79
+ private getAmountIn;
80
+ /**
81
+ * Calculates how much of a swap should go through the collateral pool for output amount.
82
+ * @param t - Total amount out.
83
+ * @param x - Imaginary reserves of token in of collateral.
84
+ * @param y - Imaginary reserves of token out of collateral.
85
+ * @param x2 - Imaginary reserves of token in of debt.
86
+ * @param y2 - Imaginary reserves of token out of debt.
87
+ * @returns How much swap should go through collateral pool. Remaining will go from debt.
88
+ * @note If a < 0 then entire trade route through debt pool and debt pool arbitrage with col pool.
89
+ * @note If a > t then entire trade route through col pool and col pool arbitrage with debt pool.
90
+ * @note If a > 0 & a < t then swap will route through both pools.
91
+ */
92
+ private swapRoutingOut;
93
+ /**
94
+ * Calculates how much of a swap should go through the collateral pool.
95
+ * @param t - Total amount in.
96
+ * @param x - Imaginary reserves of token out of collateral.
97
+ * @param y - Imaginary reserves of token in of collateral.
98
+ * @param x2 - Imaginary reserves of token out of debt.
99
+ * @param y2 - Imaginary reserves of token in of debt.
100
+ * @returns How much swap should go through collateral pool. Remaining will go from debt.
101
+ * @note If a < 0 then entire trade route through debt pool and debt pool arbitrage with col pool.
102
+ * @note If a > t then entire trade route through col pool and col pool arbitrage with debt pool.
103
+ * @note If a > 0 & a < t then swap will route through both pools.
104
+ */
105
+ private swapRoutingIn;
106
+ /**
107
+ * Calculates the input amount for a given output amount in a swap operation.
108
+ * @param {boolean} swap0to1 - Direction of the swap. True if swapping token0 for token1, false otherwise.
109
+ * @param {bigint} amountOut - The amount of output token to be swapped.
110
+ * @param {Reserves} colReserves - The reserves of the collateral pool.
111
+ * @param {Reserves} debtReserves - The reserves of the debt pool.
112
+ * @param {number} inDecimals - The number of decimals for the input token.
113
+ * @param {number} outDecimals - The number of decimals for the output token.
114
+ * @param {number} fee - The fee for the swap. 1e4 = 1%
115
+ * @returns {bigint} amountIn - The calculated input amount required for the swap.
116
+ */
117
+ private swapOut;
118
+ /**
119
+ * Calculates the input amount for a given output amount in a swap operation.
120
+ * @param {boolean} swap0to1 - Direction of the swap. True if swapping token0 for token1, false otherwise.
121
+ * @param {bigint} amountOut - The amount of output token to be swapped.
122
+ * @param {CollateralReserves} colReserves - The reserves of the collateral pool.
123
+ * @param {DebtReserves} debtReserves - The reserves of the debt pool.
124
+ * @returns {bigint} The calculated input amount required for the swap.
125
+ */
126
+ private swapOutAdjusted;
127
+ }