@paraswap/dex-lib 3.8.31 → 3.8.32

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/src/dex/index.ts CHANGED
@@ -88,6 +88,7 @@ import { ConcentratorArusd } from './concentrator-arusd/concentrator-arusd';
88
88
  import { FxProtocolRusd } from './fx-protocol-rusd/fx-protocol-rusd';
89
89
  import { AaveGsm } from './aave-gsm/aave-gsm';
90
90
  import { LitePsm } from './lite-psm/lite-psm';
91
+ import { StkGHO } from './stkgho/stkgho';
91
92
 
92
93
  const LegacyDexes = [
93
94
  CurveV2,
@@ -171,6 +172,7 @@ const Dexes = [
171
172
  FxProtocolRusd,
172
173
  AaveGsm,
173
174
  LitePsm,
175
+ StkGHO,
174
176
  ];
175
177
 
176
178
  export type LegacyDexConstructor = new (dexHelper: IDexHelper) => IDexTxBuilder<
@@ -0,0 +1,14 @@
1
+ import { DexParams } from './types';
2
+ import { DexConfigMap } from '../../types';
3
+ import { Network } from '../../constants';
4
+
5
+ import { MiscEthereum } from '@bgd-labs/aave-address-book';
6
+
7
+ export const StkGHOConfig: DexConfigMap<DexParams> = {
8
+ StkGHO: {
9
+ [Network.MAINNET]: {
10
+ stkGHO: '0x1a88Df1cFe15Af22B3c4c783D4e6F7F9e0C1885d',
11
+ GHO: MiscEthereum.GHO_TOKEN,
12
+ },
13
+ },
14
+ };
@@ -0,0 +1,77 @@
1
+ /* eslint-disable no-console */
2
+ import dotenv from 'dotenv';
3
+ dotenv.config();
4
+
5
+ import { testE2E } from '../../../tests/utils-e2e';
6
+ import { Tokens, Holders } from '../../../tests/constants-e2e';
7
+ import { Network, ContractMethod, SwapSide } from '../../constants';
8
+ import { StaticJsonRpcProvider } from '@ethersproject/providers';
9
+ import { generateConfig } from '../../config';
10
+
11
+ function testForNetwork(
12
+ network: Network,
13
+ dexKey: string,
14
+ tokenASymbol: string,
15
+ tokenBSymbol: string,
16
+ tokenAAmount: string,
17
+ tokenBAmount: string,
18
+ ) {
19
+ const provider = new StaticJsonRpcProvider(
20
+ generateConfig(network).privateHttpProvider,
21
+ network,
22
+ );
23
+ const tokens = Tokens[network];
24
+ const holders = Holders[network];
25
+
26
+ const sideToContractMethods = new Map([
27
+ [SwapSide.SELL, [ContractMethod.swapExactAmountIn]],
28
+ [SwapSide.BUY, [ContractMethod.swapExactAmountOut]],
29
+ ]);
30
+
31
+ describe(`${network}`, () => {
32
+ sideToContractMethods.forEach((contractMethods, side) =>
33
+ describe(`${side}`, () => {
34
+ contractMethods.forEach((contractMethod: ContractMethod) => {
35
+ describe(`${contractMethod}`, () => {
36
+ it(`${tokenASymbol} -> ${tokenBSymbol}`, async () => {
37
+ await testE2E(
38
+ tokens[tokenASymbol],
39
+ tokens[tokenBSymbol],
40
+ holders[tokenASymbol],
41
+ side === SwapSide.SELL ? tokenAAmount : tokenBAmount,
42
+ side,
43
+ dexKey,
44
+ contractMethod,
45
+ network,
46
+ provider,
47
+ );
48
+ });
49
+ });
50
+ });
51
+ }),
52
+ );
53
+ });
54
+ }
55
+
56
+ describe('StkGHO E2E', () => {
57
+ const dexKey = 'StkGHO';
58
+
59
+ describe('Mainnet', () => {
60
+ const network = Network.MAINNET;
61
+
62
+ const tokenASymbol: string = 'GHO';
63
+ const tokenBSymbol: string = 'stkGHO';
64
+
65
+ const tokenAAmount: string = '1000000000000000000';
66
+ const tokenBAmount: string = '1000000000000000000';
67
+
68
+ testForNetwork(
69
+ network,
70
+ dexKey,
71
+ tokenASymbol,
72
+ tokenBSymbol,
73
+ tokenAAmount,
74
+ tokenBAmount,
75
+ );
76
+ });
77
+ });
@@ -0,0 +1,79 @@
1
+ /* eslint-disable no-console */
2
+ import dotenv from 'dotenv';
3
+ dotenv.config();
4
+
5
+ import { StkGHOEventPool } from './stkgho-pool';
6
+ import { Network } from '../../constants';
7
+ import { Address } from '../../types';
8
+ import { DummyDexHelper } from '../../dex-helper/index';
9
+ import { testEventSubscriber } from '../../../tests/utils-events';
10
+ import { PoolState } from './types';
11
+ import { StkGHOConfig } from './config';
12
+
13
+ jest.setTimeout(50 * 1000);
14
+
15
+ async function fetchPoolState(
16
+ stkGHOPool: StkGHOEventPool,
17
+ blockNumber: number,
18
+ poolAddress: string,
19
+ ): Promise<PoolState> {
20
+ const eventState = stkGHOPool.getState(blockNumber);
21
+ if (eventState) return eventState;
22
+ const onChainState = await stkGHOPool.generateState(blockNumber);
23
+ stkGHOPool.setState(onChainState, blockNumber);
24
+ return onChainState;
25
+ }
26
+
27
+ // eventName -> blockNumbers
28
+ type EventMappings = Record<string, number[]>;
29
+
30
+ describe('StkGHO EventPool Mainnet', function () {
31
+ const dexKey = 'StkGHO';
32
+ const network = Network.MAINNET;
33
+ const dexHelper = new DummyDexHelper(network);
34
+ const logger = dexHelper.getLogger(dexKey);
35
+ let stkGHOPool: StkGHOEventPool;
36
+
37
+ // poolAddress -> EventMappings
38
+ const eventsToTest: Record<Address, EventMappings> = {
39
+ [StkGHOConfig[dexKey][network].stkGHO]: {
40
+ ExchangeRateChanged: [], // haven't been emitted yet
41
+ },
42
+ };
43
+
44
+ beforeEach(async () => {
45
+ stkGHOPool = new StkGHOEventPool(
46
+ dexKey,
47
+ dexKey,
48
+ network,
49
+ dexHelper,
50
+ logger,
51
+ );
52
+ });
53
+
54
+ Object.entries(eventsToTest).forEach(
55
+ ([poolAddress, events]: [string, EventMappings]) => {
56
+ describe(`Events for ${poolAddress}`, () => {
57
+ Object.entries(events).forEach(
58
+ ([eventName, blockNumbers]: [string, number[]]) => {
59
+ describe(`${eventName}`, () => {
60
+ blockNumbers.forEach((blockNumber: number) => {
61
+ it(`State after ${blockNumber}`, async function () {
62
+ await testEventSubscriber(
63
+ stkGHOPool,
64
+ stkGHOPool.addressesSubscribed,
65
+ (_blockNumber: number) =>
66
+ fetchPoolState(stkGHOPool, _blockNumber, poolAddress),
67
+ blockNumber,
68
+ `${dexKey}_${poolAddress}`,
69
+ dexHelper.provider,
70
+ );
71
+ });
72
+ });
73
+ });
74
+ },
75
+ );
76
+ });
77
+ },
78
+ );
79
+ });
@@ -0,0 +1,226 @@
1
+ /* eslint-disable no-console */
2
+ import dotenv from 'dotenv';
3
+ dotenv.config();
4
+
5
+ import { Interface, Result } from '@ethersproject/abi';
6
+ import { DummyDexHelper } from '../../dex-helper/index';
7
+ import { Network, SwapSide } from '../../constants';
8
+ import { BI_POWS } from '../../bigint-constants';
9
+ import { StkGHO } from './stkgho';
10
+ import {
11
+ checkPoolPrices,
12
+ checkPoolsLiquidity,
13
+ checkConstantPoolPrices,
14
+ } from '../../../tests/utils';
15
+ import { Tokens } from '../../../tests/constants-e2e';
16
+ import StkGHO_ABI from '../../abi/stkGHO.json';
17
+
18
+ function getReaderCalldata(
19
+ exchangeAddress: string,
20
+ readerIface: Interface,
21
+ amounts: bigint[],
22
+ funcName: string,
23
+ ) {
24
+ return amounts.map(amount => ({
25
+ target: exchangeAddress,
26
+ callData: readerIface.encodeFunctionData(funcName, [amount]),
27
+ }));
28
+ }
29
+
30
+ function decodeReaderResult(
31
+ results: Result,
32
+ readerIface: Interface,
33
+ funcName: string,
34
+ ) {
35
+ return results.map(result => {
36
+ const parsed = readerIface.decodeFunctionResult(funcName, result);
37
+ return BigInt(parsed[0]._hex);
38
+ });
39
+ }
40
+
41
+ async function checkOnChainPricing(
42
+ stkGHO: StkGHO,
43
+ funcName: string,
44
+ blockNumber: number,
45
+ prices: bigint[],
46
+ amounts: bigint[],
47
+ ) {
48
+ const exchangeAddress = '0x1a88Df1cFe15Af22B3c4c783D4e6F7F9e0C1885d';
49
+ const readerIface = new Interface(StkGHO_ABI);
50
+
51
+ const readerCallData = getReaderCalldata(
52
+ exchangeAddress,
53
+ readerIface,
54
+ amounts.slice(1),
55
+ funcName,
56
+ );
57
+ const readerResult = (
58
+ await stkGHO.dexHelper.multiContract.methods
59
+ .aggregate(readerCallData)
60
+ .call({}, blockNumber)
61
+ ).returnData;
62
+
63
+ const expectedPrices = [0n].concat(
64
+ decodeReaderResult(readerResult, readerIface, funcName),
65
+ );
66
+
67
+ expect(prices).toEqual(expectedPrices);
68
+ }
69
+
70
+ async function testPricingOnNetwork(
71
+ stkGHO: StkGHO,
72
+ network: Network,
73
+ dexKey: string,
74
+ blockNumber: number,
75
+ srcTokenSymbol: string,
76
+ destTokenSymbol: string,
77
+ side: SwapSide,
78
+ amounts: bigint[],
79
+ funcNameToCheck: string,
80
+ ) {
81
+ const networkTokens = Tokens[network];
82
+
83
+ const pools = await stkGHO.getPoolIdentifiers(
84
+ networkTokens[srcTokenSymbol],
85
+ networkTokens[destTokenSymbol],
86
+ side,
87
+ blockNumber,
88
+ );
89
+ console.log(
90
+ `${srcTokenSymbol} <> ${destTokenSymbol} Pool Identifiers: `,
91
+ pools,
92
+ );
93
+
94
+ expect(pools.length).toBeGreaterThan(0);
95
+
96
+ const poolPrices = await stkGHO.getPricesVolume(
97
+ networkTokens[srcTokenSymbol],
98
+ networkTokens[destTokenSymbol],
99
+ amounts,
100
+ side,
101
+ blockNumber,
102
+ pools,
103
+ );
104
+ console.log(
105
+ `${srcTokenSymbol} <> ${destTokenSymbol} Pool Prices: `,
106
+ poolPrices,
107
+ );
108
+
109
+ expect(poolPrices).not.toBeNull();
110
+ if (stkGHO.hasConstantPriceLargeAmounts) {
111
+ checkConstantPoolPrices(poolPrices!, amounts, dexKey);
112
+ } else {
113
+ checkPoolPrices(poolPrices!, amounts, side, dexKey);
114
+ }
115
+
116
+ await checkOnChainPricing(
117
+ stkGHO,
118
+ funcNameToCheck,
119
+ blockNumber,
120
+ poolPrices![0].prices,
121
+ amounts,
122
+ );
123
+ }
124
+
125
+ describe('StkGHO', function () {
126
+ const dexKey = 'StkGHO';
127
+ let blockNumber: number;
128
+ let stkGHO: StkGHO;
129
+
130
+ describe('Mainnet', () => {
131
+ const network = Network.MAINNET;
132
+ const dexHelper = new DummyDexHelper(network);
133
+
134
+ const tokens = Tokens[network];
135
+
136
+ // Don't forget to update relevant tokens in constant-e2e.ts
137
+ const srcTokenSymbol = 'GHO';
138
+ const destTokenSymbol = 'stkGHO';
139
+
140
+ const amountsForSell = [
141
+ 0n,
142
+ 1n * BI_POWS[tokens[srcTokenSymbol].decimals],
143
+ 2n * BI_POWS[tokens[srcTokenSymbol].decimals],
144
+ 3n * BI_POWS[tokens[srcTokenSymbol].decimals],
145
+ 4n * BI_POWS[tokens[srcTokenSymbol].decimals],
146
+ 5n * BI_POWS[tokens[srcTokenSymbol].decimals],
147
+ 6n * BI_POWS[tokens[srcTokenSymbol].decimals],
148
+ 7n * BI_POWS[tokens[srcTokenSymbol].decimals],
149
+ 8n * BI_POWS[tokens[srcTokenSymbol].decimals],
150
+ 9n * BI_POWS[tokens[srcTokenSymbol].decimals],
151
+ 10n * BI_POWS[tokens[srcTokenSymbol].decimals],
152
+ ];
153
+
154
+ const amountsForBuy = [
155
+ 0n,
156
+ 1n * BI_POWS[tokens[destTokenSymbol].decimals],
157
+ 2n * BI_POWS[tokens[destTokenSymbol].decimals],
158
+ 3n * BI_POWS[tokens[destTokenSymbol].decimals],
159
+ 4n * BI_POWS[tokens[destTokenSymbol].decimals],
160
+ 5n * BI_POWS[tokens[destTokenSymbol].decimals],
161
+ 6n * BI_POWS[tokens[destTokenSymbol].decimals],
162
+ 7n * BI_POWS[tokens[destTokenSymbol].decimals],
163
+ 8n * BI_POWS[tokens[destTokenSymbol].decimals],
164
+ 9n * BI_POWS[tokens[destTokenSymbol].decimals],
165
+ 10n * BI_POWS[tokens[destTokenSymbol].decimals],
166
+ ];
167
+
168
+ beforeAll(async () => {
169
+ blockNumber = await dexHelper.web3Provider.eth.getBlockNumber();
170
+ stkGHO = new StkGHO(network, dexKey, dexHelper);
171
+ if (stkGHO.initializePricing) {
172
+ await stkGHO.initializePricing(blockNumber);
173
+ }
174
+ });
175
+
176
+ it('getPoolIdentifiers and getPricesVolume SELL', async function () {
177
+ await testPricingOnNetwork(
178
+ stkGHO,
179
+ network,
180
+ dexKey,
181
+ blockNumber,
182
+ srcTokenSymbol,
183
+ destTokenSymbol,
184
+ SwapSide.SELL,
185
+ amountsForSell,
186
+ 'previewStake',
187
+ );
188
+ });
189
+
190
+ it('getPoolIdentifiers and getPricesVolume BUY', async function () {
191
+ await testPricingOnNetwork(
192
+ stkGHO,
193
+ network,
194
+ dexKey,
195
+ blockNumber,
196
+ srcTokenSymbol,
197
+ destTokenSymbol,
198
+ SwapSide.BUY,
199
+ amountsForBuy,
200
+ 'previewStake',
201
+ );
202
+ });
203
+
204
+ it('getTopPoolsForToken', async function () {
205
+ // We have to check without calling initializePricing, because
206
+ // pool-tracker is not calling that function
207
+ const newStkGHO = new StkGHO(network, dexKey, dexHelper);
208
+ if (newStkGHO.updatePoolState) {
209
+ await newStkGHO.updatePoolState();
210
+ }
211
+ const poolLiquidity = await newStkGHO.getTopPoolsForToken(
212
+ tokens[srcTokenSymbol].address,
213
+ 10,
214
+ );
215
+ console.log(`${srcTokenSymbol} Top Pools:`, poolLiquidity);
216
+
217
+ if (!newStkGHO.hasConstantPriceLargeAmounts) {
218
+ checkPoolsLiquidity(
219
+ poolLiquidity,
220
+ Tokens[network][srcTokenSymbol].address,
221
+ dexKey,
222
+ );
223
+ }
224
+ });
225
+ });
226
+ });
@@ -0,0 +1,111 @@
1
+ import { Interface } from '@ethersproject/abi';
2
+ import { DeepReadonly } from 'ts-essentials';
3
+ import { Log, Logger } from '../../types';
4
+ import { catchParseLogError } from '../../utils';
5
+ import { StatefulEventSubscriber } from '../../stateful-event-subscriber';
6
+ import { IDexHelper } from '../../dex-helper/idex-helper';
7
+ import { PoolState } from './types';
8
+ import StkGHO_ABI from '../../abi/stkGHO.json';
9
+ import { StkGHOConfig } from './config';
10
+ import { uint256ToBigInt } from '../../lib/decoders';
11
+
12
+ export class StkGHOEventPool extends StatefulEventSubscriber<PoolState> {
13
+ handlers: {
14
+ [event: string]: (
15
+ event: any,
16
+ state: DeepReadonly<PoolState>,
17
+ log: Readonly<Log>,
18
+ ) => DeepReadonly<PoolState> | null;
19
+ } = {};
20
+
21
+ logDecoder: (log: Log) => any;
22
+
23
+ addressesSubscribed: string[];
24
+
25
+ constructor(
26
+ readonly poolName: string,
27
+ readonly parentName: string,
28
+ protected network: number,
29
+ protected dexHelper: IDexHelper,
30
+ logger: Logger,
31
+ protected stkGHOIface = new Interface(StkGHO_ABI),
32
+ ) {
33
+ super(parentName, poolName, dexHelper, logger);
34
+
35
+ this.logDecoder = (log: Log) => this.stkGHOIface.parseLog(log);
36
+ this.addressesSubscribed = [StkGHOConfig[parentName][network].stkGHO];
37
+
38
+ this.handlers['ExchangeRateChanged'] =
39
+ this.handleExchangeRateChanged.bind(this);
40
+ }
41
+
42
+ getIdentifier(): string {
43
+ return `${this.parentName}`;
44
+ }
45
+
46
+ /**
47
+ * The function is called every time any of the subscribed
48
+ * addresses release log. The function accepts the current
49
+ * state, updates the state according to the log, and returns
50
+ * the updated state.
51
+ * @param state - Current state of event subscriber
52
+ * @param log - Log released by one of the subscribed addresses
53
+ * @returns Updates state of the event subscriber after the log
54
+ */
55
+ protected processLog(
56
+ state: DeepReadonly<PoolState>,
57
+ log: Readonly<Log>,
58
+ ): DeepReadonly<PoolState> | null {
59
+ try {
60
+ const event = this.logDecoder(log);
61
+ if (event.name in this.handlers) {
62
+ return this.handlers[event.name](event, state, log);
63
+ }
64
+ } catch (e) {
65
+ catchParseLogError(e, this.logger);
66
+ }
67
+
68
+ return null;
69
+ }
70
+
71
+ /**
72
+ * The function generates state using on-chain calls. This
73
+ * function is called to regenerate state if the event based
74
+ * system fails to fetch events and the local state is no
75
+ * more correct.
76
+ * @param blockNumber - Blocknumber for which the state should
77
+ * should be generated
78
+ * @returns state of the event subscriber at blocknumber
79
+ */
80
+ async generateState(blockNumber: number): Promise<DeepReadonly<PoolState>> {
81
+ const callData = [
82
+ {
83
+ target: this.addressesSubscribed[0],
84
+ callData: this.stkGHOIface.encodeFunctionData('getExchangeRate', []),
85
+ decodeFunction: uint256ToBigInt,
86
+ },
87
+ ];
88
+
89
+ const res = await this.dexHelper.multiWrapper.tryAggregate<bigint>(
90
+ true,
91
+ callData,
92
+ blockNumber,
93
+ );
94
+
95
+ const result = {
96
+ exchangeRate: res[0].returnData,
97
+ };
98
+
99
+ return result;
100
+ }
101
+
102
+ handleExchangeRateChanged(
103
+ event: any,
104
+ state: DeepReadonly<PoolState>,
105
+ log: Readonly<Log>,
106
+ ): DeepReadonly<PoolState> | null {
107
+ return {
108
+ exchangeRate: BigInt(event.args.exchangeRate),
109
+ };
110
+ }
111
+ }