@pioneer-platform/avax-network 0.2.6 → 0.3.1

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/lib/index.js DELETED
@@ -1,1011 +0,0 @@
1
- "use strict";
2
- /*
3
- ETH Network tools
4
-
5
-
6
- Goals:
7
-
8
- *
9
-
10
-
11
- */
12
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
13
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
14
- return new (P || (P = Promise))(function (resolve, reject) {
15
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
16
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
17
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
18
- step((generator = generator.apply(thisArg, _arguments || [])).next());
19
- });
20
- };
21
- var __generator = (this && this.__generator) || function (thisArg, body) {
22
- var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
23
- return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
24
- function verb(n) { return function (v) { return step([n, v]); }; }
25
- function step(op) {
26
- if (f) throw new TypeError("Generator is already executing.");
27
- while (g && (g = 0, op[0] && (_ = 0)), _) try {
28
- if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
29
- if (y = 0, t) op = [op[0] & 2, t.value];
30
- switch (op[0]) {
31
- case 0: case 1: t = op; break;
32
- case 4: _.label++; return { value: op[1], done: false };
33
- case 5: _.label++; y = op[1]; op = [0]; continue;
34
- case 7: op = _.ops.pop(); _.trys.pop(); continue;
35
- default:
36
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
37
- if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
38
- if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
39
- if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
40
- if (t[2]) _.ops.pop();
41
- _.trys.pop(); continue;
42
- }
43
- op = body.call(thisArg, _);
44
- } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
45
- if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
46
- }
47
- };
48
- Object.defineProperty(exports, "__esModule", { value: true });
49
- var TAG = " | avax-network | ";
50
- var Web3 = require('web3');
51
- //
52
- var Axios = require('axios');
53
- var https = require('https');
54
- var axios = Axios.create({
55
- httpsAgent: new https.Agent({
56
- rejectUnauthorized: false
57
- })
58
- });
59
- var request = require("request-promise");
60
- //blockbook
61
- var blockbook = require("@pioneer-platform/blockbook");
62
- var Web3Utils = require('web3-utils');
63
- // import * as etherscanAPI from './etherscan-api'
64
- var log = require('@pioneer-platform/loggerdog')();
65
- //
66
- var web3;
67
- var ETHERSCAN;
68
- var ETHPLORER;
69
- var PROVIDER;
70
- var NODE_URL;
71
- //TODO precision module
72
- var BASE = 1000000000000000000;
73
- // /* import moralis */
74
- // const Moralis = require("moralis-v1/node");
75
- //
76
- // /* Moralis init code */
77
- // const serverUrl = process.env['MORALIS_SERVER_URL'];
78
- // const appId = process.env['MORALIS_APP_ID'];
79
- // const masterKey = process.env['MORALIS_MASTER_KEY'];
80
- // const moralisSecret = process.env['MORALIS_SECRET'];
81
- // if(!serverUrl) throw Error("Missing MORALIS_SERVER_URL")
82
- // if(!appId) throw Error("Missing MORALIS_APP_ID")
83
- // if(!masterKey) throw Error("Missing MORALIS_MASTER_KEY")
84
- // if(!moralisSecret) throw Error("Missing MORALIS_SECRET")
85
- //TODO move thorchain/eth stuff to its own module?
86
- // @ts-ignore
87
- global.window = { ethereum: {} };
88
- module.exports = {
89
- init: function (settings) {
90
- return __awaiter(this, void 0, void 0, function () {
91
- return __generator(this, function (_a) {
92
- // Enable web3 and get the initialized web3 instance from Web3.js
93
- //await Moralis.start({ serverUrl, appId, masterKey, moralisSecret });
94
- //blockbook.init()
95
- //log.debug("node: ",process.env['PARITY_ARCHIVE_NODE'])
96
- //use default
97
- web3 = new Web3(process.env['AVAX_URL']);
98
- return [2 /*return*/];
99
- });
100
- });
101
- },
102
- // decodeTx:function (tx:string) {
103
- // return decode_tx(tx);
104
- // },
105
- getInfo: function () {
106
- return check_online_status();
107
- },
108
- // getAllowance:function (token:string,spender:string,sender:string) {
109
- // return get_allowance(token,spender,sender);
110
- // },
111
- // getNonce: function (address:string) {
112
- // return web3.eth.getTransactionCount(address,'pending')
113
- // },
114
- // getTxCount: function (address:string,options:any) {
115
- // return get_tx_count(address,options)
116
- // },
117
- // getFees: function (params:any): Promise<any> {
118
- // return get_fees(params)
119
- // },
120
- // estimateFee: function (sourceAsset:any,params:any): Promise<any> {
121
- // return estimate_fee(sourceAsset,params)
122
- // },
123
- // getMemoEncoded: function (params:any): Promise<any> {
124
- // return get_memo_data(params)
125
- // },
126
- // getStreamInfo:function (streamId:string) {
127
- // return get_stream(streamId);
128
- // },
129
- // getSymbolFromContract:function (contract:string) {
130
- // return get_symbol_from_contract(contract);
131
- // },
132
- // getPoolPositions:function (address:string) {
133
- // return get_pool_positions(address);
134
- // },
135
- // getAllTokensEth:function (address:string) {
136
- // return get_all_tokens_blockbook(address);
137
- // },
138
- // getPercentPool:function (amountFox:number,amountEth:string,poolAddress:string) {
139
- // return get_pool_percent(amountFox, amountEth, poolAddress);
140
- // },
141
- // checkAirdropClaim:function (address:string) {
142
- // return check_airdrop_claim(address);
143
- // },
144
- // buildAirdropClaim:function (address:string) {
145
- // return build_airdrop_claim(address);
146
- // },
147
- // // getFees: function (params: XFeesParams & FeesParams): Promise<Fees> {
148
- // // return get_fees()
149
- // // },
150
- // // estimateGasNormalTx: function (address:string): Promise<BaseAmount> {
151
- // // return get_balance_tokens(address)
152
- // // },
153
- // // estimateGasERC20Tx: function (address:string): Promise<BaseAmount> {
154
- // // return get_balance_tokens(address)
155
- // // },
156
- // getGasPrice: function () {
157
- // return web3.eth.getGasPrice()
158
- // },
159
- // getTransaction: function (txid:string) {
160
- // return get_transaction(txid)
161
- // },
162
- // getTransactions: function (address:string,options:any) {
163
- // return get_transactions(address,options)
164
- // },
165
- getBalance: function (address) {
166
- return get_balance(address);
167
- },
168
- // getBalances: function (addresses:string) {
169
- // return get_all_tokens(addresses)
170
- // },
171
- // getBalanceAddress: function (address:string) {
172
- // return get_balance(address)
173
- // },
174
- // getBalanceToken: function (address:string,token:string) {
175
- // return get_balance_token(address,token)
176
- // },
177
- // getBalanceTokens: function (address:string) {
178
- // return get_balance_tokens(address)
179
- // },
180
- broadcast: function (tx) {
181
- return broadcast_transaction(tx);
182
- }
183
- };
184
- // const decode_tx = async function(tx:string){
185
- // let tag = TAG + " | decode_tx | "
186
- // try{
187
- // const data = ethers.utils.parseTransaction(tx)
188
- //
189
- // return data
190
- // }catch(e){
191
- // console.error(tag,e)
192
- // }
193
- // }
194
- //
195
- // const build_airdrop_claim = async function(address:string){
196
- // let tag = TAG + " | build_airdrop_claim | "
197
- // try{
198
- // const airdropContract = new web3.eth.Contract(AIRDROP_ABI, AIRDROP_CONTRACT)
199
- //
200
- // let accountInfo = await axios({method:'GET',url: CLAIM_URL+'/'+address})
201
- // //console.log("accountInfo: ",accountInfo)
202
- //
203
- // if(!accountInfo.data.index) throw Error("Not found in db! ")
204
- //
205
- // //
206
- //
207
- // //console.log("airdropContract: ",accountInfo.data.contract)
208
- //
209
- // const AirDropInterface = new Interface(AIRDROP_ABI)
210
- //
211
- // // const data = airdropContract.methods.claim(
212
- // // accountInfo.data.index,
213
- // // address,
214
- // // 150,
215
- // // accountInfo.data.proof
216
- // // )
217
- //
218
- // // console.log("airdropContract: ",[
219
- // // accountInfo.data.index as number,
220
- // // address,
221
- // // '0x0821ab0d4414980000',
222
- // // accountInfo.data.proof
223
- // // ])
224
- //
225
- // const data = AirDropInterface.encodeFunctionData('claim', [
226
- // accountInfo.data.index as number,
227
- // address,
228
- // '0x0821ab0d4414980000',
229
- // accountInfo.data.proof
230
- // ])
231
- //
232
- // return data
233
- // }catch(e){
234
- // console.error(tag,e)
235
- // }
236
- // }
237
- //
238
- // const check_airdrop_claim = async function(address:string){
239
- // let tag = TAG + " | check_airdrop_claim | "
240
- // try{
241
- // //
242
- // let accountInfo = await axios({method:'GET',url: CLAIM_URL+'/'+address})
243
- // //console.log("accountInfo: ",accountInfo)
244
- //
245
- // let output:any = {
246
- // }
247
- //
248
- // if(accountInfo.data.index){
249
- // output.isElgible = true
250
- // output.contract = accountInfo.data.contractAddress
251
- //
252
- // //get index?
253
- //
254
- // //check contract
255
- //
256
- // //const AirDropInterface = new Interface(AirDropABI)
257
- // const airdropContract = new web3.eth.Contract(AIRDROP_ABI, accountInfo.data.contractAddress)
258
- //
259
- // //get index by address?
260
- // //log.debug("index: ",accountInfo.data.index)
261
- //
262
- // let isClaimed = await airdropContract.methods.isClaimed(accountInfo.data.index as number).call()
263
- // output.isClaimed = isClaimed
264
- // } else {
265
- // output.isElgible = false
266
- // }
267
- //
268
- //
269
- //
270
- // return output
271
- // }catch(e){
272
- // console.error(tag,e)
273
- // }
274
- // }
275
- //
276
- // const get_symbol_from_contract = async function(address:string){
277
- // let tag = TAG + " | get_symbol_from_contract | "
278
- // try{
279
- // //get total LP tokens
280
- //
281
- // //LP token
282
- // const contract:any = new web3.eth.Contract(ERC20ABI, address)
283
- // //log.debug(tag,"contract: ",contract)
284
- //
285
- // let tokenName = await contract.methods.name().call()
286
- // //log.debug(tag,"tokenName: ",tokenName)
287
- //
288
- // return tokenName
289
- // }catch(e){
290
- // console.error(tag,e)
291
- // }
292
- // }
293
- //
294
- // const get_stream = async function(streamId:any){
295
- // let tag = TAG + " | get_stream | "
296
- // try{
297
- // //get total LP tokens
298
- //
299
- // //LP token
300
- // const sablierContract = new web3.eth.Contract(SABLIER_ABI, PROXY_CONTRACT_SABLIER)
301
- // //log.debug(tag,"sablierContract: ",sablierContract)
302
- //
303
- // //log.debug(tag,"streamId: ",streamId)
304
- // streamId = parseInt(streamId)
305
- // let totalFox = await sablierContract.methods.getSalary(streamId).call()
306
- // //log.debug(tag,"totalFox: ",totalFox)
307
- //
308
- // return totalFox
309
- // }catch(e){
310
- // console.error(tag,e)
311
- // }
312
- // }
313
- //
314
- //
315
- // const get_tx_count = async function(address:string,options?:any){
316
- // let tag = TAG + " | get_tx_count | "
317
- // try{
318
- // log.debug(tag,"address: ",address)
319
- // if(!address) throw Error("102: address required!")
320
- // //confirmed
321
- // let txsConfirmed = await web3.eth.getTransactionCount(address)
322
- // //pending
323
- // let txsWithPending = await web3.eth.getTransactionCount(address,'pending')
324
- //
325
- // //count pending
326
- // let pending = txsConfirmed - txsWithPending
327
- //
328
- // return {
329
- // confirmed:txsConfirmed,
330
- // total:txsWithPending,
331
- // pending
332
- // }
333
- // }catch(e){
334
- // console.error(tag,e)
335
- // }
336
- // }
337
- //
338
- // const get_pool_percent = async function(amountFox:number,amountEth:string,poolAddress:string){
339
- // let tag = TAG + " | get_pool_percent | "
340
- // try{
341
- // //get total LP tokens
342
- //
343
- // //LP token
344
- // const lpContract = new web3.eth.Contract(ERC20ABI, UNISWAP_V2_WETH_FOX_POOL_ADDRESS)
345
- // const foxContract = new web3.eth.Contract(ERC20ABI, FOX_TOKEN_CONTRACT_ADDRESS)
346
- // const wethContract = new web3.eth.Contract(ERC20ABI, WETH_TOKEN_CONTRACT_ADDRESS)
347
- //
348
- // //log.debug("lpContract: ",lpContract)
349
- //
350
- // let totalSupply = await lpContract.methods.totalSupply().call()
351
- // totalSupply = totalSupply / BASE
352
- // log.debug("LP totalSupply: ",totalSupply)
353
- //
354
- // //get total fox in pool
355
- // let totalFox = await foxContract.methods.balanceOf(UNISWAP_V2_WETH_FOX_POOL_ADDRESS).call()
356
- // totalFox = totalFox / BASE
357
- // log.debug("totalFox: ",totalFox / BASE)
358
- //
359
- // //get total eth in pool
360
- // let totalEth = await wethContract.methods.balanceOf(UNISWAP_V2_WETH_FOX_POOL_ADDRESS).call()
361
- // totalEth = totalEth / BASE
362
- // log.debug("totalEth: ",totalEth)
363
- //
364
- // //token math
365
- // let result = totalFox / totalEth
366
- // log.debug("result: ",result)
367
- //
368
- // //balance
369
- // let lpTokens = (amountFox * totalSupply)/totalFox
370
- // log.debug("lpTokens: ",lpTokens)
371
- // //total LP tokens
372
- // //liquidity = Math.min(amount0.mul(_totalSupply) / _reserve0, amount1.mul(_totalSupply) / _reserve1);
373
- //
374
- // let percent = (lpTokens / totalSupply) * 100
375
- // log.debug("percent: ",percent)
376
- //
377
- // return percent
378
- // }catch(e){
379
- // console.error(tag,e)
380
- // }
381
- // }
382
- //
383
- //
384
- // const get_balances = async function(addresses:string){
385
- // let tag = TAG + " | get_balances | "
386
- // try{
387
- //
388
- // let actions = []
389
- // for(let i = 0; i < addresses.length; i++){
390
- // let address = addresses[i]
391
- // let action = {
392
- // method:"eth_getBalance",
393
- // params:[address]
394
- // }
395
- // actions.push(action)
396
- // }
397
- //
398
- // let result = await rpcCallBatch(actions)
399
- //
400
- // //covert
401
- // let output:any = []
402
- // for(let i = 0; i < result.length; i++){
403
- // let entry = result[i]
404
- // let balance = entry.result
405
- // balance = Web3Utils.hexToNumberString(balance);
406
- // balance = balance / BASE
407
- // output.push(balance)
408
- // }
409
- //
410
- // return output
411
- // }catch(e){
412
- // console.error(tag,e)
413
- // }
414
- // }
415
- //
416
- // const rpcCallBatch = async (actions:any)=>{
417
- // let tag = TAG + " | post_request | ";
418
- // try{
419
- //
420
- // let body = []
421
- //
422
- // for(let i = 0; i < actions.length; i++){
423
- // let action = actions[i]
424
- //
425
- // let req = {
426
- // "jsonrpc":"2.0",
427
- // "method" : action.method,
428
- // "params": action.params,
429
- // "id": 1
430
- // };
431
- //
432
- // body.push(req)
433
- // }
434
- //
435
- // let options = {
436
- // method : "POST",
437
- // url : NODE_URL,
438
- // headers :{'content-type':'application/json'},
439
- // body : JSON.stringify(body)
440
- // };
441
- // //console.log("options: ",options)
442
- // let result = await request(options);
443
- // //console.log("result: ",result)
444
- // result = JSON.parse(result);
445
- // if(result.error) throw JSON.stringify(result.error)
446
- // return result;
447
- // }catch(err){
448
- // throw new Error(err)
449
- // }
450
- // };
451
- //
452
- // //get_approval_status
453
- // const get_allowance = async function(tokenAddress:string,spender:string,sender:string){
454
- // let tag = TAG + " | get_allowance | "
455
- // try{
456
- //
457
- // let contract = new web3.eth.Contract(ERC20ABI,tokenAddress);
458
- // let allowance = await contract.methods.allowance(spender,sender).call()
459
- //
460
- // return allowance
461
- // }catch(e){
462
- // console.error(tag,e)
463
- // }
464
- // }
465
- //
466
- // const get_all_tokens_blockbook = async function(address:string){
467
- // let tag = TAG + " | get_all_tokens_blockbook | "
468
- // try{
469
- // //
470
- // let ethInto = await blockbook.getEthInfo(address)
471
- //
472
- // log.debug(tag,"ethInto: ",ethInto)
473
- //
474
- // return true
475
- // }catch(e){
476
- // console.error(tag,e)
477
- // }
478
- // }
479
- //
480
- // const get_nfts = async function(address:string){
481
- // let tag = TAG + " | get_nfts | "
482
- // try{
483
- // //get nfts from etherscan (v3 uniswap)
484
- //
485
- // //
486
- // let ethInfo = await blockbook.getAddressInfo('ETH',address)
487
- //
488
- // //TODO filter by LP contracts
489
- // log.debug(tag,"ethInfo: ",ethInfo)
490
- //
491
- // return ethInfo
492
- // }catch(e){
493
- // console.error(tag,e)
494
- // }
495
- // }
496
- //
497
- // const get_pool_positions = async function(address:string){
498
- // let tag = TAG + " | get_pool_positions | "
499
- // try{
500
- // //get nfts from etherscan (v3 uniswap)
501
- //
502
- // //
503
- // let ethInfo = await blockbook.getAddressInfo('ETH',address)
504
- //
505
- // //TODO filter by LP contracts
506
- // log.debug(tag,"ethInfo: ",ethInfo)
507
- //
508
- // return ethInfo
509
- // }catch(e){
510
- // console.error(tag,e)
511
- // }
512
- // }
513
- //
514
- //
515
- // /*
516
- // let swap = {
517
- // inboundAddress: {
518
- // chain: 'ETH',
519
- // pub_key: 'tthorpub1addwnpepqvuy8vh6yj4h28xp6gfpjsztpj6p46y2rs0763t6uw9f6lkky0ly5uvwla6',
520
- // address: '0x36286e570c412531aad366154eea9867b0e71755',
521
- // router: '0x9d496De78837f5a2bA64Cb40E62c19FBcB67f55a',
522
- // halted: false
523
- // },
524
- // asset: {
525
- // chain: 'ETH',
526
- // symbol: 'ETH',
527
- // ticker: 'ETH',
528
- // iconPath: 'https://raw.githubusercontent.com/trustwallet/assets/master/blockchains/binance/assets/ETH-1C9/logo.png'
529
- // },
530
- // memo: '=:THOR.RUNE:tthor1veu9u5h4mtdq34fjgu982s8pympp6w87ag58nh',
531
- // amount: "0.1"
532
- // }
533
- // */
534
- // let get_memo_data = async function(swap:any){
535
- // let tag = TAG + " | get_memo_data | "
536
- // try{
537
- // const web3 = new Web3()
538
- // if(!swap.inboundAddress.router) throw Error("Router required!")
539
- // const routerContract = new web3.eth.Contract(TCRopstenAbi, swap.inboundAddress.router)
540
- //
541
- // const memo = swap.memo
542
- // //TODO support tokens?
543
- // const data = routerContract.methods
544
- // .deposit(
545
- // swap.inboundAddress.address,
546
- // '0x0000000000000000000000000000000000000000', // 0 = ETH
547
- // web3.utils.toBN(swap.amount * BASE),
548
- // memo
549
- // )
550
- // .encodeABI()
551
- //
552
- // return data
553
- // }catch(e){
554
- // log.error(tag,e)
555
- // throw e
556
- // }
557
- // }
558
- //
559
- // /*
560
- // X-chain compatible call
561
- // */
562
- // let estimate_fee = async function(sourceAsset:any, params:any){
563
- // let tag = TAG + " | estimate_fee | "
564
- // try{
565
- //
566
- // let checkSummedAddress;
567
- // let decimal;
568
- //
569
- // if (sourceAsset.symbol === 'ETH') {
570
- // checkSummedAddress = '0x0000000000000000000000000000000000000000';
571
- // decimal = ETH_DECIMAL;
572
- // } else {
573
- // throw Error("TODO")
574
- // // const assetAddress = sourceAsset.symbol.slice(sourceAsset.ticker.length + 1);
575
- // // const strip0x = assetAddress.substr(2);
576
- // // checkSummedAddress = ethers.utils.getAddress(strip0x);
577
- // //
578
- // // const tokenContract = new ethers.Contract(checkSummedAddress, erc20ABI, wallet);
579
- // // const tokenDecimals = await tokenContract.decimals();
580
- // // decimal = tokenDecimals.toNumber();
581
- // }
582
- // // Connect to the network
583
- // let provider = PROVIDER;
584
- // //
585
- // const contract = new ethers.Contract(THORCHAIN_ROUTER_TESTNET, TCRopstenAbi, provider);
586
- //
587
- // console.log('checkppint estimateFee: params', params);
588
- // const estimateGas = await contract.estimateGas.deposit(...params);
589
- // console.log('checkppint estimateFee: params', params);
590
- //
591
- // let entry = {
592
- // asset: {
593
- // chain:"ETH",
594
- // symbol:"ETH",
595
- // ticker:"ETH",
596
- // },
597
- // amount: params[2],
598
- // recipient: params[0],
599
- // memo: params[3],
600
- // }
601
- //
602
- // const {fees} = await get_fees(entry);
603
- // let minimumWeiCost = BigNumber.from(fees.average)
604
- // minimumWeiCost = minimumWeiCost.mul(estimateGas.toNumber())
605
- // return minimumWeiCost;
606
- // }catch(e){
607
- // log.error(tag,e)
608
- // throw e
609
- // }
610
- // }
611
- //
612
- //
613
- // let get_gas_limit = async function({ asset, recipient, amount, memo }: FeesParams){
614
- // let tag = TAG + " | get_gas_limit | "
615
- // try{
616
- // log.debug(tag,"input: ",{ asset, recipient, amount, memo })
617
- // const txAmount = BigNumber.from(amount?.amount().toFixed())
618
- //
619
- // let assetAddress
620
- // if (asset && assetToString(asset) !== assetToString(AssetETH)) {
621
- // assetAddress = getTokenAddress(asset)
622
- // }
623
- //
624
- // let estimate
625
- //
626
- // //NOTE: I changed the from to recipient because this module has no context to address of the sender.
627
- // // I hope I dont skrew the pooch and the differnce +-1 byte between addresses actually matter
628
- // if (assetAddress && assetAddress !== ETHAddress) {
629
- // // ERC20 gas estimate
630
- // const contract = new ethers.Contract(assetAddress, erc20ABI, PROVIDER)
631
- //
632
- // estimate = await contract.estimateGas.transfer(recipient, txAmount, {
633
- // from: recipient,
634
- // })
635
- // } else {
636
- // // ETH gas estimate
637
- // const transactionRequest = {
638
- // from: "0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2", //address with lots of eth
639
- // to: recipient,
640
- // value: txAmount,
641
- // data: memo ? toUtf8Bytes(memo) : undefined,
642
- // }
643
- //
644
- // estimate = await PROVIDER.estimateGas(transactionRequest)
645
- // }
646
- //
647
- // return estimate
648
- //
649
- // }catch(e){
650
- // log.error(tag,e)
651
- // throw e
652
- // }
653
- // }
654
- //
655
- // let get_fees = async function(params: any){
656
- // let tag = TAG + " | get_fees | "
657
- // try{
658
- // const response: any = await etherscanAPI.getGasOracle(ETHERSCAN.baseUrl, ETHERSCAN.apiKey)
659
- //
660
- // // Convert result of gas prices: `Gwei` -> `Wei`
661
- // const averageWei = parseUnits(response.SafeGasPrice, 'gwei')
662
- // const fastWei = parseUnits(response.ProposeGasPrice, 'gwei')
663
- // const fastestWei = parseUnits(response.FastGasPrice, 'gwei')
664
- //
665
- // let gasPrices:any = {
666
- // average: baseAmount(averageWei.toString(), ETH_DECIMAL),
667
- // fast: baseAmount(fastWei.toString(), ETH_DECIMAL),
668
- // fastest: baseAmount(fastestWei.toString(), ETH_DECIMAL),
669
- // }
670
- // const { fast: fastGP, fastest: fastestGP, average: averageGP } = gasPrices
671
- //
672
- // if(!params.amount || !params?.amount?.amount){
673
- // // @ts-ignore
674
- // params.amount = {
675
- // // @ts-ignore
676
- // amount:function(){ return .98 }
677
- // }
678
- // }
679
- //
680
- // log.debug(tag,"get_gas_limit: ",{
681
- // asset: params.asset,
682
- // amount: params.amount,
683
- // recipient: params.recipient,
684
- // memo: params.memo,
685
- // })
686
- //
687
- // const gasLimit = await get_gas_limit({
688
- // asset: params.asset,
689
- // amount: params.amount,
690
- // recipient: params.recipient,
691
- // memo: params.memo,
692
- // })
693
- //
694
- // let output = {
695
- // gasPrices,
696
- // fees: {
697
- // type: 'byte',
698
- // average: getFee({ gasPrice: averageGP, gasLimit }).amount().toString(),
699
- // fast: getFee({ gasPrice: fastGP, gasLimit }).amount().toString(),
700
- // fastest: getFee({ gasPrice: fastestGP, gasLimit }).amount().toString(),
701
- // },
702
- // gasLimit,
703
- // }
704
- //
705
- // return output
706
- // }catch(e){
707
- // log.error(tag,e)
708
- // throw e
709
- // }
710
- // }
711
- var broadcast_transaction = function (tx) {
712
- return __awaiter(this, void 0, void 0, function () {
713
- var tag, output;
714
- return __generator(this, function (_a) {
715
- tag = TAG + " | broadcast_transaction | ";
716
- try {
717
- log.debug(tag, "tx: ", tx);
718
- if (!tx)
719
- throw Error("101: missing tx!");
720
- //push node
721
- web3.eth.sendSignedTransaction(tx);
722
- output = {
723
- success: true,
724
- // blockIncluded:result.result,
725
- // block:result.blockNumber,
726
- // txid:result.transactionHash,
727
- // gas:result.cumulativeGasUsed
728
- };
729
- return [2 /*return*/, output];
730
- }
731
- catch (e) {
732
- log.error(tag, e);
733
- throw e;
734
- }
735
- return [2 /*return*/];
736
- });
737
- });
738
- };
739
- // const get_balance_tokens = async function(address:string){
740
- // let tag = TAG + " | get_balance_tokens | "
741
- // try{
742
- // let balances:any = {}
743
- // let valueUsds:any = {}
744
- // let coinInfo:any = {}
745
- //
746
- // //TODO other? backup?
747
- // //ethpolorer.io
748
- // let resp = await axios({
749
- // method:'GET',
750
- // url: 'http://api.ethplorer.io/getAddressInfo/'+address+'?apiKey='+ETHPLORER_API_KEY
751
- // })
752
- //
753
- // log.debug(tag,"resp: ",resp.data)
754
- //
755
- // balances['ETH'] = resp.data.ETH.balance
756
- // valueUsds['ETH'] = parseFloat(resp.data.ETH.balance) * parseFloat(resp.data.ETH.price.rate)
757
- //
758
- // //infura
759
- // let tokenInfo = resp.data.tokens
760
- // log.debug(tag,"tokenInfo: ",tokenInfo)
761
- //
762
- // //
763
- // if(tokenInfo && Object.keys(tokenInfo).length > 0){
764
- // for(let i = 0; i < tokenInfo.length; i++){
765
- // let info = tokenInfo[i]
766
- // if(info){
767
- // log.debug(tag,"info: ",info)
768
- //
769
- // //let symbol
770
- // let symbol = info.tokenInfo.symbol
771
- // log.debug(tag,"symbol: ",symbol)
772
- //
773
- // //rate
774
- // let rate = 0
775
- // if(info.tokenInfo.price && info.tokenInfo.price.rate){
776
- // log.debug(tag,"rate: ",info.tokenInfo.price.rate)
777
- // rate = info.tokenInfo.price.rate
778
- // }
779
- //
780
- // // @ts-ignore
781
- // let balance = info.balance / parseInt(Math.pow(10,info.tokenInfo.decimals))
782
- // log.debug({rate,symbol,balance})
783
- //
784
- // balances[symbol] = balance
785
- // valueUsds[symbol] = balance * rate
786
- // coinInfo[symbol] = info.tokenInfo
787
- // }
788
- // }
789
- // }
790
- //
791
- // return {balances,valueUsds,coinInfo}
792
- // }catch(e){
793
- // console.error(tag,e)
794
- // }
795
- // }
796
- //
797
- //
798
- //
799
- // const get_balance_token = async function(address:string,token:string){
800
- // let tag = TAG + " | get_balance | "
801
- // try{
802
- // //decimals
803
- // let contract = new web3.eth.Contract(ERC20ABI,token);
804
- // let decimals = await contract.methods.decimals().call()
805
- // //log.debug(tag,"decimals: ",decimals)
806
- //
807
- // let balance = await contract.methods.balanceOf(address).call()
808
- // //log.debug(tag,"balance: ",balance)
809
- //
810
- // return balance / Math.pow(10, decimals);
811
- // }catch(e){
812
- // console.error(tag,e)
813
- // }
814
- // }
815
- //
816
- // const get_balance = async function(address:string){
817
- // let tag = TAG + " | get_balance | "
818
- // try{
819
- // let output:any = {}
820
- //
821
- // // get BSC native balance for a given address
822
- // const options = {
823
- // chain: "avalanche",
824
- // address,
825
- // // to_block: "1234",
826
- // };
827
- // const balance = await Moralis.Web3API.account.getNativeBalance(options);
828
- // log.debug(tag,"balance: ",balance)
829
- // return balance.balance / 1000000000000000000
830
- // }catch(e){
831
- // console.error(tag,e)
832
- // }
833
- // }
834
- //moralis
835
- // const get_all_tokens = async function(address:string){
836
- // let tag = TAG + " | get_all_tokens | "
837
- // try{
838
- // let output:any = {}
839
- //
840
- // // get BSC native balance for a given address
841
- // const options = {
842
- // chain: "avalanche",
843
- // address,
844
- // // to_block: "1234",
845
- // };
846
- // const balance = await Moralis.Web3API.token.getAllTokenIds(options);
847
- // log.debug(tag,"balance: ",balance)
848
- // return balance.balance / 1000000000000000000
849
- // }catch(e){
850
- // console.error(tag,e)
851
- // }
852
- // }
853
- // const get_transactions = async function(address:string,options:any){
854
- // let tag = TAG + " | get_transactions | "
855
- // try{
856
- // let output:any = {}
857
- //
858
- // let ethInfo = await blockbook.getAddressInfo('ETH',address)
859
- //
860
- // return ethInfo
861
- // }catch(e){
862
- // console.error(tag,e)
863
- // }
864
- // }
865
- //
866
- // const get_transaction = async function(txid:string){
867
- // let tag = TAG + " | get_transaction | "
868
- // try{
869
- // let output:any = {}
870
- //
871
- // //normal tx info
872
- // output.txInfo = await web3.eth.getTransaction(txid)
873
- //
874
- // //if contract
875
- // output.receipt = await web3.eth.getTransactionReceipt(txid)
876
- //
877
- // return output
878
- // }catch(e){
879
- // console.error(tag,e)
880
- // }
881
- // }
882
- var check_online_status = function () {
883
- return __awaiter(this, void 0, void 0, function () {
884
- var tag, output, _a, _b, _c, networkName, _d, e_1;
885
- return __generator(this, function (_e) {
886
- switch (_e.label) {
887
- case 0:
888
- tag = TAG + " | check_online_status | ";
889
- _e.label = 1;
890
- case 1:
891
- _e.trys.push([1, 6, , 7]);
892
- output = {};
893
- // const options = { chain: "bsc", block_number_or_hash: "2" };
894
- //
895
- // // get block content on BSC
896
- // const transactions = await Moralis.Web3API.native.getBlock(options);
897
- // log.debug(transactions)
898
- // const web3API = async () => {
899
- // await Moralis.start({ serverUrl, appId, moralisSecret });
900
- //
901
- // const price = await Moralis.Web3API.token.getTokenPrice({
902
- // address: "0x33b35c665496bA8E71B22373843376740401F106",
903
- // chain: "avax",
904
- // });
905
- // console.log(price);
906
- // };
907
- //
908
- // web3API();
909
- //isTestnet
910
- _a = output;
911
- return [4 /*yield*/, web3.eth.getNodeInfo()];
912
- case 2:
913
- // const options = { chain: "bsc", block_number_or_hash: "2" };
914
- //
915
- // // get block content on BSC
916
- // const transactions = await Moralis.Web3API.native.getBlock(options);
917
- // log.debug(transactions)
918
- // const web3API = async () => {
919
- // await Moralis.start({ serverUrl, appId, moralisSecret });
920
- //
921
- // const price = await Moralis.Web3API.token.getTokenPrice({
922
- // address: "0x33b35c665496bA8E71B22373843376740401F106",
923
- // chain: "avax",
924
- // });
925
- // console.log(price);
926
- // };
927
- //
928
- // web3API();
929
- //isTestnet
930
- _a.version = _e.sent();
931
- _b = output;
932
- return [4 /*yield*/, web3.eth.getChainId()];
933
- case 3:
934
- _b.chainId = _e.sent();
935
- _c = output;
936
- return [4 /*yield*/, web3.eth.getBlockNumber()
937
- //TODO get peer count
938
- // output.peers = await web3.eth.net.getPeerCount()
939
- ];
940
- case 4:
941
- _c.height = _e.sent();
942
- networkName = void 0;
943
- switch (output.chainId.toString()) {
944
- case "1":
945
- networkName = "Main";
946
- break;
947
- case "2":
948
- networkName = "Morden";
949
- break;
950
- case "3":
951
- networkName = "Ropsten";
952
- break;
953
- case "4":
954
- networkName = "Rinkeby";
955
- break;
956
- case "42":
957
- networkName = "Kovan";
958
- break;
959
- case "43114":
960
- networkName = "avalanche";
961
- break;
962
- default:
963
- networkName = "Unknown";
964
- }
965
- output.networkName = networkName;
966
- //
967
- _d = output;
968
- return [4 /*yield*/, web3.eth.getGasPrice()
969
- //
970
- // output.syncing = await web3.eth.isSyncing()
971
- ];
972
- case 5:
973
- //
974
- _d.gasPrice = _e.sent();
975
- //
976
- // output.syncing = await web3.eth.isSyncing()
977
- return [2 /*return*/, output];
978
- case 6:
979
- e_1 = _e.sent();
980
- console.error(tag, e_1);
981
- return [3 /*break*/, 7];
982
- case 7: return [2 /*return*/];
983
- }
984
- });
985
- });
986
- };
987
- var get_balance = function (address) {
988
- return __awaiter(this, void 0, void 0, function () {
989
- var tag, output, e_2;
990
- return __generator(this, function (_a) {
991
- switch (_a.label) {
992
- case 0:
993
- tag = TAG + " | get_balance | ";
994
- _a.label = 1;
995
- case 1:
996
- _a.trys.push([1, 3, , 4]);
997
- output = {};
998
- return [4 /*yield*/, web3.eth.getBalance(address)];
999
- case 2:
1000
- //normal tx info
1001
- output = (_a.sent()) / BASE;
1002
- return [2 /*return*/, output];
1003
- case 3:
1004
- e_2 = _a.sent();
1005
- console.error(tag, e_2);
1006
- return [3 /*break*/, 4];
1007
- case 4: return [2 /*return*/];
1008
- }
1009
- });
1010
- });
1011
- };