Repository navigation
Expand file tree
/
Copy pathdex.ts
More file actions
117 lines (96 loc) · 2.71 KB
/
Copy pathdex.ts
File metadata and controls
117 lines (96 loc) · 2.71 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
import { Wallet } from 'ethers';
import * as Typechain from '../typechain/index.js';
import Chain from './chain.js';
import { GlacierFactory } from './dex/glacier.js';
import { PrimaryFactory } from './dex/primary.js';
import Pair from './pair.js';
export const getFactoryAdapter = (
dexName: string,
factory: Typechain.Factory | Typechain.Factory_avax_glacier,
) => {
if (dexName === 'glacier') {
return new GlacierFactory(factory as Typechain.Factory_avax_glacier);
}
return new PrimaryFactory(factory as Typechain.Factory);
};
export default class Dex {
private config: ChainConfigurationDex;
private chain: Chain;
private wallet: Wallet;
private router: Typechain.Router | Typechain.Router_arb_camelot | undefined;
private factory:
| Typechain.Factory
| Typechain.Factory_avax_glacier
| undefined;
constructor(config: ChainConfigurationDex, chain: Chain, wallet: Wallet) {
this.config = config;
this.chain = chain;
this.wallet = wallet;
}
getChain() {
return this.chain;
}
getRouter() {
if (!this.router) {
if (this.config.name === 'camelot') {
this.router = Typechain.Router_arb_camelot__factory.connect(
this.config.router,
this.wallet,
);
} else {
this.router = Typechain.Router__factory.connect(
this.config.router,
this.wallet,
);
}
}
return this.router;
}
async getFactory() {
if (!this.factory) {
let factoryAddress = this.config.factory;
if (!factoryAddress || factoryAddress.length === 0) {
const router = this.getRouter();
factoryAddress = await router.callStatic.factory();
}
if (this.config.name === 'glacier') {
this.factory = Typechain.Factory_avax_glacier__factory.connect(
factoryAddress,
this.wallet,
);
} else {
this.factory = Typechain.Factory__factory.connect(
factoryAddress,
this.wallet,
);
}
}
return this.factory;
}
getName() {
return this.config.name;
}
async getPair(
sourceToken: SourceToken,
targetToken: Token,
): Promise<Pair | undefined> {
const factory = await this.getFactory();
const address = await getFactoryAdapter(this.config.name, factory).getPair(
sourceToken,
targetToken,
);
if (!address || address.startsWith('0x0000000')) {
return undefined;
}
const pairContract = Typechain.Pair__factory.connect(address, this.wallet);
const token0 = await pairContract.callStatic.token0();
return new Pair(
pairContract,
sourceToken,
targetToken,
token0 === sourceToken.address,
this,
this.wallet,
);
}
}