Repository navigation
Expand file tree
/
Copy pathchain.ts
More file actions
268 lines (203 loc) · 5.96 KB
/
Copy pathchain.ts
File metadata and controls
268 lines (203 loc) · 5.96 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
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
import { BigNumber, Wallet, ethers, providers } from 'ethers';
import { existsSync, readFileSync } from 'fs';
import lodash from 'lodash';
import { join } from 'path';
import pino, { Logger } from 'pino';
import TOML from 'toml';
import { LOG_LEVEL } from '../constants.js';
import { Erc20__factory } from '../typechain/index.js';
import Dex from './dex.js';
const PATH_CHAINS_DIR = join(process.cwd(), 'configs', 'chains');
export default class Chain {
static getConfiguration(name: string) {
const chainConfigurationPath = join(PATH_CHAINS_DIR, `${name}.toml`);
if (!existsSync(chainConfigurationPath)) {
throw new Error(
`Could not open chain cnfig file "${chainConfigurationPath}" - please ensure it exists`,
);
}
const contents = readFileSync(chainConfigurationPath).toString();
return TOML.parse(contents) as ChainConfiguration;
}
static fromName(
name: string,
wallet: Wallet,
options?: { dex?: string; exactApproval?: boolean },
) {
const configuration = this.getConfiguration(name);
return new Chain(configuration, wallet, options);
}
private config: ChainConfiguration;
private wallet: Wallet;
private rpcProviders: providers.JsonRpcProvider[];
private dex: Dex;
private exactApproval: boolean;
private logger: Logger;
private tokenCache: Map<string, Token> = new Map<string, Token>();
private sourceTokenCache: Map<string, SourceToken> = new Map<
string,
SourceToken
>();
constructor(
config: ChainConfiguration,
wallet: Wallet,
options?: { dex?: string; exactApproval?: boolean },
) {
this.config = config;
this.exactApproval = options?.exactApproval ?? false;
// Setup RPC provider
this.rpcProviders = this.config.rpc.map(
(url) => new providers.JsonRpcProvider(url),
);
// Setup connected Wallet
this.wallet = wallet.connect(this.rpcProviders[0]);
// Setup dex
let resolvedDexName = this.config.dex;
if (options && options.dex) {
resolvedDexName = options.dex;
}
const dex = this.config.dexes.find(
(dex) => dex.name === resolvedDexName.toLowerCase(),
);
if (!dex) {
throw new Error(
`Selected DEX "${resolvedDexName.toLowerCase()}" does not exists in [[dexes]] configuration`,
);
}
this.dex = new Dex(dex, this, this.wallet);
this.logger = pino({
name: 'class::chain',
level: LOG_LEVEL,
});
}
getConfiguration() {
return this.config;
}
getName() {
return this.config.name;
}
getRpcUrls() {
return this.config.rpc;
}
getDex() {
return this.dex;
}
useExactApproval() {
return this.exactApproval;
}
async getBlockNumber() {
return this.wallet.provider.getBlockNumber();
}
async getLatestBlock() {
return this.wallet.provider.getBlock('latest');
}
async getToken(address: string): Promise<Token> {
this.logger.debug(
{
address,
},
'[Started] Loading token',
);
const existing = this.tokenCache.get(address);
if (existing) {
return existing;
}
const contract = Erc20__factory.connect(address, this.wallet);
const [name, symbol, decimals] = await Promise.all([
contract.callStatic.name(),
contract.callStatic.symbol(),
contract.callStatic.decimals(),
]);
const token = {
address,
name,
symbol,
decimals:
typeof decimals === 'number'
? decimals
: (decimals as BigNumber).toNumber(),
contract,
};
this.logger.debug(
lodash.omit(token, ['contract']),
'[Finished] Loading token',
);
this.tokenCache.set(address, token);
return token;
}
async getSourceToken(type: ChainConfigurationSourceType) {
const foundToken = this.config.sources.find(
(source) => source.type === type,
);
if (!foundToken) {
throw new Error(`Could not find token with type "${type}"`);
}
return this.loadSourceToken(foundToken.address);
}
async getCheckableTokens(name?: string) {
let foundTokens = this.config.sources.filter((source) => source.check);
if (name) {
foundTokens = foundTokens.filter((ft) => ft.name === name);
}
return Promise.all(
foundTokens.map((ft) => this.loadSourceToken(ft.address)),
);
}
async getReserveToken() {
return this.getSourceToken('reserve');
}
async getNativeToken() {
return this.getSourceToken('native');
}
async getStableToken() {
return this.getSourceToken('stable');
}
async getTokenBalance(token: Token | SourceToken) {
if (
(token as SourceToken).type &&
(token as SourceToken).type === 'native'
) {
return this.wallet.getBalance();
}
return token.contract.balanceOf(this.wallet.address);
}
async getTokenBalanceNumber(token: Token | SourceToken) {
const balance = await this.getTokenBalance(token);
return ethers.utils.formatUnits(balance, token.decimals);
}
private async loadSourceToken(address: string) {
this.logger.debug(
{
address,
},
'[Started] Loading source token',
);
const { sources } = this.config;
const source = sources.find((source) => source.address === address);
if (!source) {
throw new Error(`Could not find source token with address "${address}"`);
}
const existing = this.sourceTokenCache.get(address);
if (existing) {
return existing;
}
const contract = Erc20__factory.connect(source.address, this.wallet);
const symbol = await contract.callStatic.symbol();
const token = {
address: source.address,
name: source.name,
symbol,
decimals: source.decimals,
type: source.type,
minimumLp: source.minimumLp,
config: source,
contract,
};
this.logger.debug(
lodash.omit(token, ['config', 'contract']),
'[Finished] Loading source token',
);
this.sourceTokenCache.set(source.address, token);
return token as SourceToken;
}
}