-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.js
694 lines (487 loc) · 17.7 KB
/
utils.js
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
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
import EventEmitter from 'events'
import { ERC20_ABI } from './abi/ERC20_ABI.js'
import { UNICRYPT_ABI } from './abi/unicrypt-abi.js'
import { PINKLOCK_ABI } from './abi/pinklock-abi.js'
import { TEAMFINANCE_ABI } from './abi/teamfinance-abi.js'
import { UNISWAP_V2_POOL_ABI } from './abi/uniswapv2-pool-abi.js'
import * as fs from 'fs'
import * as uniconst from './uni-catch/const.js'
import assert from 'assert';
import * as afx from './global.js'
import { application } from 'express';
import * as ethscan_api from './etherscan-api.js'
import * as ethUtil from 'ethereumjs-util'
import { ethers } from "ethers";
import * as crypto from './aes.js'
import dotenv from 'dotenv'
dotenv.config()
export const isValidWalletAddress = (walletAddress) => {
// The regex pattern to match a wallet address.
const pattern = /^(0x){1}[0-9a-fA-F]{40}$/;
// Test the passed-in wallet address against the regex pattern.
return pattern.test(walletAddress);
}
export const getTokenBalanceFromWallet = async (web3, walletAddress, tokenAddress) => {
let tokenContract = null;
try {
tokenContract = new web3.eth.Contract(ERC20_ABI, tokenAddress);
} catch (error) {
afx.error_log('getTokenBalanceFromWallet 1', error)
return -1
}
if (!tokenContract) {
return -1;
}
try {
const balance = await tokenContract.methods.balanceOf(walletAddress).call();
const decimals = await tokenContract.methods.decimals().call();
const tokenBalance = Number(balance) / 10 ** Number(decimals);
return tokenBalance;
} catch (error) {
afx.error_log('getTokenBalanceFromWallet 2', error)
}
return -1;
//console.log(`getTokenBalanceFromWallet(wallet = ${walletAddress} token = ${tokenAddress})`, "Token Balance:", tokenBalance);
}
export const isValidAddress = (address) => {
// Check if it's 20 bytes
if (!address) {
return false
}
if (address.length !== 42) {
return false;
}
// Check that it starts with 0x
if (address.slice(0,2) !== '0x') {
return false;
}
// Check that each character is a valid hexadecimal digit
for (let i = 2; i < address.length; i++) {
let charCode = address.charCodeAt(i);
if (!((charCode >= 48 && charCode <= 57) ||
(charCode >= 65 && charCode <= 70) ||
(charCode >= 97 && charCode <= 102))) {
return false;
}
}
// If all checks pass, it's a valid address
return true;
}
export function isValidPrivateKey(privateKey) {
try {
if (privateKey.startsWith('0x')) {
privateKey = privateKey.substring(2)
}
const privateKeyBuffer = Buffer.from(privateKey, 'hex');
const publicKeyBuffer = ethUtil.privateToPublic(privateKeyBuffer);
const addressBuffer = ethUtil.pubToAddress(publicKeyBuffer);
const address = ethUtil.bufferToHex(addressBuffer);
return true
} catch (error) {
return false
}
}
export const roundDecimal = (number, digits) => {
return number.toLocaleString('en-US', {maximumFractionDigits: digits});
}
export let web3Inst = null
export const init = (web3) => {
web3Inst = web3
}
export const getTokenInfo = async (tokenAddress) => {
assert(web3Inst)
return new Promise( async (resolve, reject) => {
getTokenInfoW(web3Inst, tokenAddress).then(result => {
resolve(result)
})
})
}
export const getTokenInfoW = async (web3, tokenAddress) => {
return new Promise( async (resolve, reject) => {
let tokenContract = null
try {
tokenContract = new web3.eth.Contract(ERC20_ABI, tokenAddress);
} catch (err) {
resolve(null)
return
}
var tokenPromises = [];
tokenPromises.push(tokenContract.methods.name().call());
tokenPromises.push(tokenContract.methods.symbol().call());
tokenPromises.push(tokenContract.methods.decimals().call());
tokenPromises.push(tokenContract.methods.totalSupply().call());
Promise.all(tokenPromises).then(tokenInfo => {
const decimal = parseInt(tokenInfo[2])
const totalSupply = Number(tokenInfo[3]) / 10 ** decimal
const result = {address: tokenAddress, name: tokenInfo[0], symbol: tokenInfo[1], decimal, totalSupply}
resolve(result)
}).catch(err => {
resolve(null)
})
})
}
export const getEthPrice = async (web3) => {
try {
const pairContract = new web3.eth.Contract(UNISWAP_V2_POOL_ABI, uniconst.ETH_USDT_V2_PAIR_ADDRESS);
let res = await pairContract.methods.getReserves().call()
let tokenBalance = res._reserve0
let baseTokenBalance = res._reserve1
tokenBalance = Number(tokenBalance) / 10 ** 18
baseTokenBalance = Number(baseTokenBalance) / 10 ** 6
let price = baseTokenBalance / tokenBalance
return price
} catch (error) {
afx.error_log('[getEthPrice]', error)
}
return 0.0
}
export const getTimeStringUTC = (timestamp) => {
const options = {
year: 'numeric',
month: 'long',
day: 'numeric',
hour: 'numeric',
minute: 'numeric',
timeZone: 'UTC'
};
const formattedDate = timestamp.toLocaleString('en-US', options);
return formattedDate
}
export function isValidDate(dateString) {
const date = new Date(dateString);
// The date constructor returns 'Invalid Date' if the date string is invalid
return date instanceof Date && !isNaN(date);
}
export const fetchAPI = async (url, method, data = {}) => {
try {
let params = {
method: method,
headers: {
'Content-Type': 'application/json'
}
}
if (method === "POST") {
params.body = JSON.stringify(data)
}
const res = await fetch(url, params);
if (res) {
const resData = await res.json()
//console.log(resData)
return resData
}
} catch (error) {
}
return null
}
export const getUnicryptDetails = (web3, pairAddress) => {
return new Promise( async (resolve, reject) => {
let contract = null
try {
contract = new web3.eth.Contract(UNICRYPT_ABI, uniconst.UNICRYPT_CONTRACT_ADDRESS);
} catch (err) {
resolve(null)
return
}
let numLocks = 0
try {
numLocks = await contract.methods.getNumLocksForToken(pairAddress).call()
// console.log('numLocks', numLocks, pairAddress)
} catch (err) {
resolve(null)
return
}
let resAmount = 0
let resUnlockDate = 0
for (let iLock = 0; iLock < numLocks; iLock++) {
let detail = null
try {
detail = await contract.methods.tokenLocks(pairAddress, iLock).call()
// console.log(detail)
} catch (error) {
//console.log(err)
afx.error_log('getUnicryptDetails', error)
continue
}
if (!detail) {
continue
}
resAmount += Number(detail.amount)
if (resUnlockDate < Number(detail.unlockDate)) {
resUnlockDate = Number(detail.unlockDate)
}
}
resolve({resAmount, resUnlockDate})
})
}
export const getPinkLockDetails = (web3, pairAddress) => {
return new Promise( async (resolve, reject) => {
let contract = null
try {
contract = new web3.eth.Contract(PINKLOCK_ABI, uniconst.PINKLOCK_CONTRACT_ADDRESS);
} catch (err) {
resolve(null)
return
}
let numLocks = 10
let detail = null
try {
detail = await contract.methods.getLocksForToken(pairAddress, 0, numLocks).call()
} catch (err) {
resolve(null)
return
}
if (!detail) {
resolve(null)
return
}
let resAmount = 0
let resUnlockDate = 0
for (const lockInfo of detail) {
if (!lockInfo[5]) {
continue
}
const unlockDate = Number(lockInfo[5])
if (resUnlockDate < unlockDate) {
resUnlockDate = unlockDate
}
}
resolve({resAmount, resUnlockDate})
})
}
export const addressToHex = (address) => {
const hexString = '0x' + address.slice(2).toLowerCase().padStart(64, '0');
return hexString.toLowerCase();
}
export async function getTokenSender(web3, tokenContractAddress, dest) {
const transferEventSignature = web3.utils.keccak256("Transfer(address,address,uint256)").toString();
const destAddress = addressToHex(dest)
const url = `https://api.etherscan.io/api?module=logs&action=getLogs&fromBlock=0&toBlock=latest&address=${tokenContractAddress}&topic0=${transferEventSignature}&topic2=${destAddress}`
const apiKey = await ethscan_api.getApiKey()
const res = await ethscan_api.executeEthscanAPI(url, apiKey)
let senders = []
if (res.result) {
console.log(res)
senders = res.result.map(log => {
return '0x' + log.topics[1].substr(26);
});
}
// extract the sender's address from each log
return senders
}
export const getTeamFinanceDetails = async (web3, pairAddress) => {
return new Promise( async (resolve, reject) => {
let senders = null
try {
senders = await getTokenSender(web3, pairAddress, uniconst.TEAMFINANCE_CONTRACT_ADDRESS)
} catch (error) {
//console.log(err)
afx.error_log('getTeamFinanceDetails', error)
resolve(null)
return
}
//console.log('senders', senders)
if (!senders || senders.length == 0) {
return
}
let contract = null
try {
contract = new web3.eth.Contract(TEAMFINANCE_ABI, uniconst.TEAMFINANCE_CONTRACT_ADDRESS);
} catch (err) {
console.log('err', err)
resolve(null)
return
}
let resAmount = 0
let resUnlockDate = 0
for (const sender of senders) {
let lockIds = []
try {
lockIds = await contract.methods.getDepositsByWithdrawalAddress(sender).call()
//console.log('lockIds', lockIds, pairAddress, sender)
} catch (err) {
resolve(null)
return
}
for (const lockId of lockIds) {
let detail = null
try {
detail = await contract.methods.getDepositDetails(lockId).call()
//console.log(detail)
} catch (error) {
// console.log(err)
afx.error_log('getTeamFinanceDetails', error)
continue
}
if (!detail) {
continue
}
resAmount += Number(detail._tokenAmount)
if (resUnlockDate < Number(detail._unlockTime)) {
resUnlockDate = Number(detail._unlockTime)
}
}
}
//console.log({resAmount, resUnlockDate})
resolve({resAmount, resUnlockDate})
})
}
export const getLastTransactionDateFromAddress = async (address) => {
let url = `https://api.etherscan.io/api?module=account&action=txlist&address=${address}&startblock=0&endblock=99999999&sort=desc&offset=1&page=1`
const apiKey = await ethscan_api.getApiKey()
const resp = await ethscan_api.executeEthscanAPI(url, apiKey)
if (!resp || !resp.result || resp.result.length == 0) {
return null
}
return resp.result[0].timeStamp
}
export const getContractVerified = async (web3, address) => {
let url = `https://api.etherscan.io/api?module=contract&action=getsourcecode&address=${address}&apikey=3QBM5TM1N5K8KFI69HYXIKH466AUXI3PTA`
const apiKey = await ethscan_api.getApiKey()
const resp = await ethscan_api.executeEthscanAPI(url, apiKey)
if (!resp
|| !resp.status
|| resp.status !== '1'
|| !resp.message
|| resp.message !== 'OK'
|| !resp.result
|| resp.result.length === 0
|| !resp.result[0].SourceCode || resp.result[0].SourceCode === '' || !resp.result[0].ABI || resp.result[0].ABI === 'Contract source code not verified') {
return null
}
const bytecodeHash = web3.utils.keccak256(resp.result[0].SourceCode);
const checksum = '0x' + bytecodeHash.slice(-8);
return checksum
}
export const createDirectoryIfNotExists = (directoryPath) => {
if (!fs.existsSync(directoryPath)) {
fs.mkdirSync(directoryPath);
console.log(`The directory '${directoryPath}' has been created.`);
} else {
}
};
export const getTopHolders = async (tokenAddress, decimals) => {
let res = { topHoldersMsg: '', holderCount: 0 }
let resultMsg = ''
const url = `https://api.honeypot.is/v1/TopHolders?address=${tokenAddress}&chainID=1`
let resp = await fetchAPI(url, 'GET')
if (!resp) {
return res
}
if (!resp.totalSupply || !resp.holders || resp.holders.length === 0) {
return res
}
const icons = ['👮♀️', '🕵️', '👩🚀', '🧑🚒', '👩🎨', '🧑✈️', '👨🎤', '🧑🔬', '👩🍳', '👩🌾', '🦹', '🧙', '🧝♀️', '🧟' ]
const totalSupply = Number(resp.totalSupply)
resultMsg = '<u>Top holders</u>'
let row = 0
for (const holder of resp.holders) {
const iconIndex = parseInt(Math.random() * icons.length) % icons.length
row++
let percent = Number(holder.balance) * 100 / totalSupply
let bal = Number(holder.balance) / (10 ** decimals)
resultMsg += `\n${icons[iconIndex]} ${row}. <a href='https://etherscan.io/address/${holder.address}'>${roundDecimal(bal, 3)}</a> | ${roundDecimal(percent, 3)} %`
// resultMsg += `\n${icons[iconIndex]} ${row}. <a href='https://etherscan.io/address/${holder.address}'>${getShortenedAddress(holder.address)}</a> | ${roundDecimal(percent, 3)} %`
if (row >= 10) {
break
}
}
return { topHoldersMsg: resultMsg, holderCount: resp.holders.length }
}
export const getTokenDetailInfo = async (tokenAddress) => {
const url = `https://api.isrug.app/tokens/scan?mode=detailed&addr=${tokenAddress}&chain=ethereum`
let resp = await fetchAPI(url, 'GET')
if (!resp) {
return null
}
return resp
}
export const getShortenedAddress = (address) => {
if (!address) {
return ''
}
let str = address.slice(0, 24) + '...'
return str
}
export const getWalletAddressFromPKeyW = (web3, privateKey) => {
const account = web3.eth.accounts.privateKeyToAccount(privateKey);
const walletAddress = account.address;
return walletAddress
}
export const getWalletAddressFromPKey = (privateKey) => {
if (!web3Inst) {
return null
}
return getWalletAddressFromPKeyW(web3Inst, privateKey)
}
export const encryptPKey = (text) => {
if (text.startsWith('0x')) {
text = text.substring(2)
}
return crypto.aesEncrypt(text, process.env.CRYPT_KEY)
}
export const decryptPKey = (text) => {
return crypto.aesDecrypt(text, process.env.CRYPT_KEY)
}
export const generateNewWallet = () => {
try {
const mnemonic = ethers.Wallet.createRandom().mnemonic;
const wallet = ethers.Wallet.fromMnemonic(mnemonic.phrase.toString());
const privateKey = wallet.privateKey;
const address = wallet.address;
return {mnemonic: mnemonic.phrase, privateKey, address}
} catch (error) {
console.log(error)
return null
}
}
export function waitForEvent(eventEmitter, eventName) {
return new Promise(resolve => {
eventEmitter.on(eventName, resolve)
})
}
export async function waitSeconds(seconds) {
const eventEmitter = new EventEmitter()
setTimeout(() => {
eventEmitter.emit('TimeEvent')
}, seconds * 1000)
await waitForEvent(eventEmitter, 'TimeEvent')
}
export async function waitMilliseconds(ms) {
const eventEmitter = new EventEmitter()
setTimeout(() => {
eventEmitter.emit('TimeEvent')
}, ms)
await waitForEvent(eventEmitter, 'TimeEvent')
}
export const getTokenPriceInETH = async (tokenAddress, decimal) => {
const url = `https://api.honeypot.is/v1/GetPairs?address=${tokenAddress}&chainID=1`
let resp = await fetchAPI(url, 'GET')
if (!resp) {
return 0
}
tokenAddress = tokenAddress.toLowerCase()
try {
let maxPrice = 0.0
for (const info of resp) {
if (info.Pair && info.Pair.Tokens && info.Pair.Tokens.length === 2 && info.Reserves && info.Reserves.length === 2) {
const token0 = info.Pair.Tokens[0].toLowerCase()
const token1 = info.Pair.Tokens[1].toLowerCase()
let price = 0.0
if (token0 === uniconst.WETH_ADDRESS.toLowerCase()) {
price = info.Reserves[0] / (info.Reserves[1] / (10 ** decimal))
} else if (token1 === uniconst.WETH_ADDRESS.toLowerCase()) {
price = info.Reserves[1] / (info.Reserves[0] / (10 ** decimal))
} else {
continue
}
if (maxPrice < price) {
maxPrice = price
}
}
}
return maxPrice
} catch (error) {
console.error('getTokenPriceInETH', error)
return 0
}
}