-
-
Notifications
You must be signed in to change notification settings - Fork 140
/
ethereum-base.ts
408 lines (367 loc) · 11.8 KB
/
ethereum-base.ts
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
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
import {
BigNumber,
Contract,
providers,
Transaction,
utils,
Wallet,
} from 'ethers';
import axios from 'axios';
import { promises as fs } from 'fs';
import path from 'path';
import { rootPath } from '../../paths';
import { TokenListType, TokenValue, walletPath } from '../../services/base';
import { EVMNonceManager } from './evm.nonce';
import NodeCache from 'node-cache';
import { EvmTxStorage } from './evm.tx-storage';
import fse from 'fs-extra';
import { ConfigManagerCertPassphrase } from '../../services/config-manager-cert-passphrase';
import { logger } from '../../services/logger';
import { ReferenceCountingCloseable } from '../../services/refcounting-closeable';
import { getAddress } from 'ethers/lib/utils';
// information about an Ethereum token
export interface TokenInfo {
chainId: number;
address: string;
name: string;
symbol: string;
decimals: number;
}
export type NewBlockHandler = (bn: number) => void;
export type NewDebugMsgHandler = (msg: any) => void;
export class EthereumBase {
private _provider;
protected tokenList: TokenInfo[] = [];
private _tokenMap: Record<string, TokenInfo> = {};
// there are async values set in the constructor
private _ready: boolean = false;
private _initialized: Promise<boolean> = Promise.resolve(false);
public chainName;
public chainId;
public rpcUrl;
public gasPriceConstant;
private _gasLimitTransaction;
public tokenListSource: string;
public tokenListType: TokenListType;
public cache: NodeCache;
private readonly _refCountingHandle: string;
private readonly _nonceManager: EVMNonceManager;
private readonly _txStorage: EvmTxStorage;
constructor(
chainName: string,
chainId: number,
rpcUrl: string,
tokenListSource: string,
tokenListType: TokenListType,
gasPriceConstant: number,
gasLimitTransaction: number,
nonceDbPath: string,
transactionDbPath: string
) {
this._provider = new providers.StaticJsonRpcProvider(rpcUrl);
this.chainName = chainName;
this.chainId = chainId;
this.rpcUrl = rpcUrl;
this.gasPriceConstant = gasPriceConstant;
this.tokenListSource = tokenListSource;
this.tokenListType = tokenListType;
this._refCountingHandle = ReferenceCountingCloseable.createHandle();
this._nonceManager = new EVMNonceManager(
chainName,
chainId,
this.resolveDBPath(nonceDbPath)
);
this._nonceManager.declareOwnership(this._refCountingHandle);
this.cache = new NodeCache({ stdTTL: 3600 }); // set default cache ttl to 1hr
this._gasLimitTransaction = gasLimitTransaction;
this._txStorage = EvmTxStorage.getInstance(
this.resolveDBPath(transactionDbPath),
this._refCountingHandle
);
this._txStorage.declareOwnership(this._refCountingHandle);
}
ready(): boolean {
return this._ready;
}
public get provider() {
return this._provider;
}
public get gasLimitTransaction() {
return this._gasLimitTransaction;
}
public resolveDBPath(oldPath: string): string {
if (oldPath.charAt(0) === '/') return oldPath;
const dbDir: string = path.join(rootPath(), 'db/');
fse.mkdirSync(dbDir, { recursive: true });
return path.join(dbDir, oldPath);
}
public events() {
this._provider._events.map(function (event) {
return [event.tag];
});
}
public onNewBlock(func: NewBlockHandler) {
this._provider.on('block', func);
}
public onDebugMessage(func: NewDebugMsgHandler) {
this._provider.on('debug', func);
}
async init(): Promise<void> {
await this._initialized; // Wait for any previous init() calls to complete
if (!this.ready()) {
// If we're not ready, this._initialized will be a Promise that resolves after init() completes
this._initialized = (async () => {
try {
await this._nonceManager.init(
async (address) => await this.provider.getTransactionCount(address)
);
await this.loadTokens(this.tokenListSource, this.tokenListType);
return true;
} catch (e) {
logger.error(`Failed to initialize ${this.chainName} chain: ${e}`);
return false;
}
})();
this._ready = await this._initialized; // Wait for the initialization to complete
}
return;
}
async loadTokens(
tokenListSource: string,
tokenListType: TokenListType
): Promise<void> {
this.tokenList = await this.getTokenList(tokenListSource, tokenListType);
// Only keep tokens in the same chain
this.tokenList = this.tokenList.filter(
(token: TokenInfo) => token.chainId === this.chainId
);
if (this.tokenList) {
this.tokenList.forEach(
(token: TokenInfo) => (this._tokenMap[token.symbol] = token)
);
}
}
// returns a Tokens for a given list source and list type
async getTokenList(
tokenListSource: string,
tokenListType: TokenListType
): Promise<TokenInfo[]> {
let tokens: TokenInfo[];
if (tokenListType === 'URL') {
({
data: { tokens },
} = await axios.get(tokenListSource));
} else {
({ tokens } = JSON.parse(await fs.readFile(tokenListSource, 'utf8')));
}
const mappedTokens: TokenInfo[] = tokens.map((token) => {
token.address = getAddress(token.address);
return token;
});
return mappedTokens;
}
public get nonceManager() {
return this._nonceManager;
}
public get txStorage(): EvmTxStorage {
return this._txStorage;
}
// ethereum token lists are large. instead of reloading each time with
// getTokenList, we can read the stored tokenList value from when the
// object was initiated.
public get storedTokenList(): TokenInfo[] {
return Object.values(this._tokenMap);
}
// return the Token object for a symbol
getTokenForSymbol(symbol: string): TokenInfo | null {
return this._tokenMap[symbol] ? this._tokenMap[symbol] : null;
}
getWalletFromPrivateKey(privateKey: string): Wallet {
return new Wallet(privateKey, this._provider);
}
// returns Wallet for an address
// TODO: Abstract-away into base.ts
async getWallet(address: string): Promise<Wallet> {
const path = `${walletPath}/${this.chainName}`;
const encryptedPrivateKey: string = await fse.readFile(
`${path}/${address}.json`,
'utf8'
);
const passphrase = ConfigManagerCertPassphrase.readPassphrase();
if (!passphrase) {
throw new Error('missing passphrase');
}
return await this.decrypt(encryptedPrivateKey, passphrase);
}
encrypt(privateKey: string, password: string): Promise<string> {
const wallet = this.getWalletFromPrivateKey(privateKey);
return wallet.encrypt(password);
}
async decrypt(
encryptedPrivateKey: string,
password: string
): Promise<Wallet> {
const wallet = await Wallet.fromEncryptedJson(
encryptedPrivateKey,
password
);
return wallet.connect(this._provider);
}
// returns the Native balance, convert BigNumber to string
async getNativeBalance(wallet: Wallet): Promise<TokenValue> {
const balance = await wallet.getBalance();
return { value: balance, decimals: 18 };
}
// returns the balance for an ERC-20 token
async getERC20Balance(
contract: Contract,
wallet: Wallet,
decimals: number
): Promise<TokenValue> {
logger.info('Requesting balance for owner ' + wallet.address + '.');
const balance: BigNumber = await contract.balanceOf(wallet.address);
logger.info(
`Raw balance of ${contract.address} for ` +
`${wallet.address}: ${balance.toString()}`
);
return { value: balance, decimals: decimals };
}
// returns the allowance for an ERC-20 token
async getERC20Allowance(
contract: Contract,
wallet: Wallet,
spender: string,
decimals: number
): Promise<TokenValue> {
logger.info(
'Requesting spender ' +
spender +
' allowance for owner ' +
wallet.address +
'.'
);
const allowance = await contract.allowance(wallet.address, spender);
logger.info(allowance);
return { value: allowance, decimals: decimals };
}
// returns an ethereum TransactionResponse for a txHash.
async getTransaction(txHash: string): Promise<providers.TransactionResponse> {
return this._provider.getTransaction(txHash);
}
// caches transaction receipt once they arrive
cacheTransactionReceipt(tx: providers.TransactionReceipt) {
this.cache.set(tx.transactionHash, tx); // transaction hash is used as cache key since it is unique enough
}
// returns an ethereum TransactionReceipt for a txHash if the transaction has been mined.
async getTransactionReceipt(
txHash: string
): Promise<providers.TransactionReceipt | null> {
if (this.cache.keys().includes(txHash)) {
// If it's in the cache, return the value in cache, whether it's null or not
return this.cache.get(txHash) as providers.TransactionReceipt;
} else {
// If it's not in the cache,
const fetchedTxReceipt = await this._provider.getTransactionReceipt(
txHash
);
this.cache.set(txHash, fetchedTxReceipt); // Cache the fetched receipt, whether it's null or not
if (!fetchedTxReceipt) {
this._provider.once(txHash, this.cacheTransactionReceipt.bind(this));
}
return fetchedTxReceipt;
}
}
// adds allowance by spender to transfer the given amount of Token
async approveERC20(
contract: Contract,
wallet: Wallet,
spender: string,
amount: BigNumber,
nonce?: number,
maxFeePerGas?: BigNumber,
maxPriorityFeePerGas?: BigNumber,
gasPrice?: number
): Promise<Transaction> {
logger.info(
'Calling approve method called for spender ' +
spender +
' requesting allowance ' +
amount.toString() +
' from owner ' +
wallet.address +
'.'
);
return this.nonceManager.provideNonce(
nonce,
wallet.address,
async (nextNonce) => {
const params: any = {
gasLimit: this._gasLimitTransaction,
nonce: nextNonce,
};
if (maxFeePerGas || maxPriorityFeePerGas) {
params.maxFeePerGas = maxFeePerGas;
params.maxPriorityFeePerGas = maxPriorityFeePerGas;
} else if (gasPrice) {
params.gasPrice = (gasPrice * 1e9).toFixed(0);
}
return contract.approve(spender, amount, params);
}
);
}
public getTokenBySymbol(tokenSymbol: string): TokenInfo | undefined {
return this.tokenList.find(
(token: TokenInfo) =>
token.symbol.toUpperCase() === tokenSymbol.toUpperCase() &&
token.chainId === this.chainId
);
}
// returns the current block number
async getCurrentBlockNumber(): Promise<number> {
return this._provider.getBlockNumber();
}
// cancel transaction
async cancelTxWithGasPrice(
wallet: Wallet,
nonce: number,
gasPrice: number
): Promise<Transaction> {
return this.nonceManager.provideNonce(
nonce,
wallet.address,
async (nextNonce) => {
const tx = {
from: wallet.address,
to: wallet.address,
value: utils.parseEther('0'),
nonce: nextNonce,
gasPrice: (gasPrice * 1e9).toFixed(0),
};
const response = await wallet.sendTransaction(tx);
logger.info(response);
return response;
}
);
}
/**
* Get the base gas fee and the current max priority fee from the EVM
* node, and add them together.
*/
async getGasPrice(): Promise<number | null> {
if (!this.ready) {
await this.init();
}
const feeData: providers.FeeData = await this._provider.getFeeData();
if (feeData.gasPrice !== null && feeData.maxPriorityFeePerGas !== null) {
return (
feeData.gasPrice.add(feeData.maxPriorityFeePerGas).toNumber() * 1e-9
);
} else {
return null;
}
}
async close() {
await this._nonceManager.close(this._refCountingHandle);
await this._txStorage.close(this._refCountingHandle);
}
}