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