@pioneer-platform/avax-network 0.3.1 → 0.5.0

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.
@@ -0,0 +1,2 @@
1
+
2
+ $ tsc -p .
package/CHANGELOG.md CHANGED
@@ -1,5 +1,29 @@
1
1
  # @pioneer-platform/avax-network
2
2
 
3
+ ## 0.5.0
4
+
5
+ ### Minor Changes
6
+
7
+ - Automated minor version bump for all packages
8
+
9
+ ### Patch Changes
10
+
11
+ - Updated dependencies
12
+ - @pioneer-platform/blockbook@8.6.0
13
+ - @pioneer-platform/loggerdog@8.6.0
14
+
15
+ ## 0.4.0
16
+
17
+ ### Minor Changes
18
+
19
+ - Automated minor version bump for all packages
20
+
21
+ ### Patch Changes
22
+
23
+ - Updated dependencies
24
+ - @pioneer-platform/blockbook@8.5.0
25
+ - @pioneer-platform/loggerdog@8.5.0
26
+
3
27
  ## 0.3.1
4
28
 
5
29
  ### Patch Changes
package/build.sh ADDED
@@ -0,0 +1,22 @@
1
+ #!/bin/bash
2
+ # Fast Bun build (replaces slow tsc)
3
+
4
+ OUTDIR="${1:-lib}"
5
+ ENTRY="${2:-src/index.ts}"
6
+
7
+ # Clean output
8
+ rm -rf "$OUTDIR"
9
+ mkdir -p "$OUTDIR"
10
+
11
+ # Build with Bun (10x faster than tsc)
12
+ bun build "$ENTRY" \
13
+ --outdir "$OUTDIR" \
14
+ --target node \
15
+ --format cjs \
16
+ --sourcemap \
17
+ --minify
18
+
19
+ # Generate TypeScript declarations
20
+ bunx tsc --emitDeclarationOnly --outDir "$OUTDIR" --project .
21
+
22
+ echo "✅ Built $OUTDIR"
package/lib/index.d.ts ADDED
@@ -0,0 +1 @@
1
+ export {};
package/lib/index.js ADDED
@@ -0,0 +1,958 @@
1
+ "use strict";
2
+ /*
3
+ ETH Network tools
4
+
5
+
6
+ Goals:
7
+
8
+ *
9
+
10
+
11
+ */
12
+ Object.defineProperty(exports, "__esModule", { value: true });
13
+ const TAG = " | avax-network | ";
14
+ let Web3 = require('web3');
15
+ // Replace ethers import with require
16
+ const ethers = require('ethers');
17
+ //
18
+ const axiosLib = require('axios');
19
+ const Axios = axiosLib.default || axiosLib;
20
+ const https = require('https');
21
+ const axios = Axios.create({
22
+ httpsAgent: new https.Agent({
23
+ rejectUnauthorized: false
24
+ })
25
+ });
26
+ const request = require("request-promise");
27
+ // Add missing log import
28
+ const log = require('@pioneer-platform/loggerdog')();
29
+ //blockbook
30
+ let blockbook = require("@pioneer-platform/blockbook");
31
+ const Web3Utils = require('web3-utils');
32
+ // Replace imports with requires
33
+ const ethersproviders = require('@ethersproject/providers');
34
+ const EtherscanProvider = ethersproviders.EtherscanProvider;
35
+ const getDefaultProvider = ethersproviders.getDefaultProvider;
36
+ // Helper functions to replace the imports
37
+ function assetToString(asset) {
38
+ return `${asset.chain}.${asset.symbol}`;
39
+ }
40
+ function baseAmount(amount, decimal) {
41
+ return {
42
+ amount: () => amount.toString(),
43
+ decimal
44
+ };
45
+ }
46
+ function delay(ms) {
47
+ return new Promise(resolve => setTimeout(resolve, ms));
48
+ }
49
+ const AssetETH = {
50
+ chain: 'ETH',
51
+ symbol: 'ETH',
52
+ ticker: 'ETH'
53
+ };
54
+ // Replace ethers utils import with require
55
+ const ethersUtils = require('ethers/lib/utils');
56
+ const toUtf8Bytes = ethersUtils.toUtf8Bytes;
57
+ const parseUnits = ethersUtils.parseUnits;
58
+ //
59
+ let web3;
60
+ let ETHERSCAN;
61
+ let ETHPLORER;
62
+ let PROVIDER;
63
+ let NODE_URL;
64
+ //TODO precision module
65
+ let BASE = 1000000000000000000;
66
+ // /* import moralis */
67
+ // const Moralis = require("moralis-v1/node");
68
+ //
69
+ // /* Moralis init code */
70
+ // const serverUrl = process.env['MORALIS_SERVER_URL'];
71
+ // const appId = process.env['MORALIS_APP_ID'];
72
+ // const masterKey = process.env['MORALIS_MASTER_KEY'];
73
+ // const moralisSecret = process.env['MORALIS_SECRET'];
74
+ // if(!serverUrl) throw Error("Missing MORALIS_SERVER_URL")
75
+ // if(!appId) throw Error("Missing MORALIS_APP_ID")
76
+ // if(!masterKey) throw Error("Missing MORALIS_MASTER_KEY")
77
+ // if(!moralisSecret) throw Error("Missing MORALIS_SECRET")
78
+ //TODO move thorchain/eth stuff to its own module?
79
+ // @ts-ignore
80
+ global.window = { ethereum: {} };
81
+ module.exports = {
82
+ init: async function (settings) {
83
+ // Enable web3 and get the initialized web3 instance from Web3.js
84
+ //await Moralis.start({ serverUrl, appId, masterKey, moralisSecret });
85
+ //blockbook.init()
86
+ //log.debug("node: ",process.env['PARITY_ARCHIVE_NODE'])
87
+ //use default
88
+ web3 = new Web3(process.env['AVAX_URL']);
89
+ //PROVIDER = new ethers.providers.InfuraProvider('mainnet', process.env['INFURA_API_KEY'])
90
+ //NODE_URL = process.env['AVAX_URL']
91
+ },
92
+ // decodeTx:function (tx:string) {
93
+ // return decode_tx(tx);
94
+ // },
95
+ getInfo: function () {
96
+ return check_online_status();
97
+ },
98
+ // getAllowance:function (token:string,spender:string,sender:string) {
99
+ // return get_allowance(token,spender,sender);
100
+ // },
101
+ // getNonce: function (address:string) {
102
+ // return web3.eth.getTransactionCount(address,'pending')
103
+ // },
104
+ // getTxCount: function (address:string,options:any) {
105
+ // return get_tx_count(address,options)
106
+ // },
107
+ // getFees: function (params:any): Promise<any> {
108
+ // return get_fees(params)
109
+ // },
110
+ // estimateFee: function (sourceAsset:any,params:any): Promise<any> {
111
+ // return estimate_fee(sourceAsset,params)
112
+ // },
113
+ // getMemoEncoded: function (params:any): Promise<any> {
114
+ // return get_memo_data(params)
115
+ // },
116
+ // getStreamInfo:function (streamId:string) {
117
+ // return get_stream(streamId);
118
+ // },
119
+ // getSymbolFromContract:function (contract:string) {
120
+ // return get_symbol_from_contract(contract);
121
+ // },
122
+ // getPoolPositions:function (address:string) {
123
+ // return get_pool_positions(address);
124
+ // },
125
+ // getAllTokensEth:function (address:string) {
126
+ // return get_all_tokens_blockbook(address);
127
+ // },
128
+ // getPercentPool:function (amountFox:number,amountEth:string,poolAddress:string) {
129
+ // return get_pool_percent(amountFox, amountEth, poolAddress);
130
+ // },
131
+ // checkAirdropClaim:function (address:string) {
132
+ // return check_airdrop_claim(address);
133
+ // },
134
+ // buildAirdropClaim:function (address:string) {
135
+ // return build_airdrop_claim(address);
136
+ // },
137
+ // // getFees: function (params: XFeesParams & FeesParams): Promise<Fees> {
138
+ // // return get_fees()
139
+ // // },
140
+ // // estimateGasNormalTx: function (address:string): Promise<BaseAmount> {
141
+ // // return get_balance_tokens(address)
142
+ // // },
143
+ // // estimateGasERC20Tx: function (address:string): Promise<BaseAmount> {
144
+ // // return get_balance_tokens(address)
145
+ // // },
146
+ // getGasPrice: function () {
147
+ // return web3.eth.getGasPrice()
148
+ // },
149
+ // getTransaction: function (txid:string) {
150
+ // return get_transaction(txid)
151
+ // },
152
+ // getTransactions: function (address:string,options:any) {
153
+ // return get_transactions(address,options)
154
+ // },
155
+ getBalance: function (address) {
156
+ return get_balance(address);
157
+ },
158
+ // getBalances: function (addresses:string) {
159
+ // return get_all_tokens(addresses)
160
+ // },
161
+ // getBalanceAddress: function (address:string) {
162
+ // return get_balance(address)
163
+ // },
164
+ // getBalanceToken: function (address:string,token:string) {
165
+ // return get_balance_token(address,token)
166
+ // },
167
+ // getBalanceTokens: function (address:string) {
168
+ // return get_balance_tokens(address)
169
+ // },
170
+ broadcast: function (tx) {
171
+ return broadcast_transaction(tx);
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
+ let broadcast_transaction = async function (tx) {
702
+ let tag = TAG + " | broadcast_transaction | ";
703
+ try {
704
+ log.debug(tag, "tx: ", tx);
705
+ if (!tx)
706
+ throw Error("101: missing tx!");
707
+ //push node
708
+ web3.eth.sendSignedTransaction(tx);
709
+ //push etherscan
710
+ //https://api.etherscan.io/api?module=proxy&action=eth_sendRawTransaction&hex=0xf904808000831cfde080&apikey=YourApiKeyToken
711
+ // let resp = await axios({
712
+ // method:'GET',
713
+ // url: 'https://api.etherscan.io/api?module=proxy&action=eth_sendRawTransaction&hex='+tx+'&apikey='+process.env['ETHERSCAN_API_KEY']
714
+ // })
715
+ // console.log(resp)
716
+ //push blockbook
717
+ //TODO lifecycle hook?
718
+ // let resp = await web3.eth.sendSignedTransaction(tx)
719
+ // .on('transactionHash', function(hash:any){
720
+ // console.log("hash: ",hash)
721
+ // })
722
+ // .on('receipt', function(receipt:any){
723
+ // console.log("receipt: ",receipt)
724
+ // })
725
+ // .on('confirmation', function(confirmationNumber:any, receipt:any){
726
+ // console.log(confirmationNumber,receipt)
727
+ // })
728
+ // .on('error', console.error);
729
+ //console.log("resp: ",resp)
730
+ let output = {
731
+ success: true,
732
+ // blockIncluded:result.result,
733
+ // block:result.blockNumber,
734
+ // txid:result.transactionHash,
735
+ // gas:result.cumulativeGasUsed
736
+ };
737
+ return output;
738
+ }
739
+ catch (e) {
740
+ log.error(tag, e);
741
+ throw e;
742
+ }
743
+ };
744
+ // const get_balance_tokens = async function(address:string){
745
+ // let tag = TAG + " | get_balance_tokens | "
746
+ // try{
747
+ // let balances:any = {}
748
+ // let valueUsds:any = {}
749
+ // let coinInfo:any = {}
750
+ //
751
+ // //TODO other? backup?
752
+ // //ethpolorer.io
753
+ // let resp = await axios({
754
+ // method:'GET',
755
+ // url: 'http://api.ethplorer.io/getAddressInfo/'+address+'?apiKey='+ETHPLORER_API_KEY
756
+ // })
757
+ //
758
+ // log.debug(tag,"resp: ",resp.data)
759
+ //
760
+ // balances['ETH'] = resp.data.ETH.balance
761
+ // valueUsds['ETH'] = parseFloat(resp.data.ETH.balance) * parseFloat(resp.data.ETH.price.rate)
762
+ //
763
+ // //infura
764
+ // let tokenInfo = resp.data.tokens
765
+ // log.debug(tag,"tokenInfo: ",tokenInfo)
766
+ //
767
+ // //
768
+ // if(tokenInfo && Object.keys(tokenInfo).length > 0){
769
+ // for(let i = 0; i < tokenInfo.length; i++){
770
+ // let info = tokenInfo[i]
771
+ // if(info){
772
+ // log.debug(tag,"info: ",info)
773
+ //
774
+ // //let symbol
775
+ // let symbol = info.tokenInfo.symbol
776
+ // log.debug(tag,"symbol: ",symbol)
777
+ //
778
+ // //rate
779
+ // let rate = 0
780
+ // if(info.tokenInfo.price && info.tokenInfo.price.rate){
781
+ // log.debug(tag,"rate: ",info.tokenInfo.price.rate)
782
+ // rate = info.tokenInfo.price.rate
783
+ // }
784
+ //
785
+ // // @ts-ignore
786
+ // let balance = info.balance / parseInt(Math.pow(10,info.tokenInfo.decimals))
787
+ // log.debug({rate,symbol,balance})
788
+ //
789
+ // balances[symbol] = balance
790
+ // valueUsds[symbol] = balance * rate
791
+ // coinInfo[symbol] = info.tokenInfo
792
+ // }
793
+ // }
794
+ // }
795
+ //
796
+ // return {balances,valueUsds,coinInfo}
797
+ // }catch(e){
798
+ // console.error(tag,e)
799
+ // }
800
+ // }
801
+ //
802
+ //
803
+ //
804
+ // const get_balance_token = async function(address:string,token:string){
805
+ // let tag = TAG + " | get_balance | "
806
+ // try{
807
+ // //decimals
808
+ // let contract = new web3.eth.Contract(ERC20ABI,token);
809
+ // let decimals = await contract.methods.decimals().call()
810
+ // //log.debug(tag,"decimals: ",decimals)
811
+ //
812
+ // let balance = await contract.methods.balanceOf(address).call()
813
+ // //log.debug(tag,"balance: ",balance)
814
+ //
815
+ // return balance / Math.pow(10, decimals);
816
+ // }catch(e){
817
+ // console.error(tag,e)
818
+ // }
819
+ // }
820
+ //
821
+ // const get_balance = async function(address:string){
822
+ // let tag = TAG + " | get_balance | "
823
+ // try{
824
+ // let output:any = {}
825
+ //
826
+ // // get BSC native balance for a given address
827
+ // const options = {
828
+ // chain: "avalanche",
829
+ // address,
830
+ // // to_block: "1234",
831
+ // };
832
+ // const balance = await Moralis.Web3API.account.getNativeBalance(options);
833
+ // log.debug(tag,"balance: ",balance)
834
+ // return balance.balance / 1000000000000000000
835
+ // }catch(e){
836
+ // console.error(tag,e)
837
+ // }
838
+ // }
839
+ //moralis
840
+ // const get_all_tokens = async function(address:string){
841
+ // let tag = TAG + " | get_all_tokens | "
842
+ // try{
843
+ // let output:any = {}
844
+ //
845
+ // // get BSC native balance for a given address
846
+ // const options = {
847
+ // chain: "avalanche",
848
+ // address,
849
+ // // to_block: "1234",
850
+ // };
851
+ // const balance = await Moralis.Web3API.token.getAllTokenIds(options);
852
+ // log.debug(tag,"balance: ",balance)
853
+ // return balance.balance / 1000000000000000000
854
+ // }catch(e){
855
+ // console.error(tag,e)
856
+ // }
857
+ // }
858
+ // const get_transactions = async function(address:string,options:any){
859
+ // let tag = TAG + " | get_transactions | "
860
+ // try{
861
+ // let output:any = {}
862
+ //
863
+ // let ethInfo = await blockbook.getAddressInfo('ETH',address)
864
+ //
865
+ // return ethInfo
866
+ // }catch(e){
867
+ // console.error(tag,e)
868
+ // }
869
+ // }
870
+ //
871
+ // const get_transaction = async function(txid:string){
872
+ // let tag = TAG + " | get_transaction | "
873
+ // try{
874
+ // let output:any = {}
875
+ //
876
+ // //normal tx info
877
+ // output.txInfo = await web3.eth.getTransaction(txid)
878
+ //
879
+ // //if contract
880
+ // output.receipt = await web3.eth.getTransactionReceipt(txid)
881
+ //
882
+ // return output
883
+ // }catch(e){
884
+ // console.error(tag,e)
885
+ // }
886
+ // }
887
+ let check_online_status = async function () {
888
+ let tag = TAG + " | check_online_status | ";
889
+ try {
890
+ let output = {};
891
+ // const options = { chain: "bsc", block_number_or_hash: "2" };
892
+ //
893
+ // // get block content on BSC
894
+ // const transactions = await Moralis.Web3API.native.getBlock(options);
895
+ // log.debug(transactions)
896
+ // const web3API = async () => {
897
+ // await Moralis.start({ serverUrl, appId, moralisSecret });
898
+ //
899
+ // const price = await Moralis.Web3API.token.getTokenPrice({
900
+ // address: "0x33b35c665496bA8E71B22373843376740401F106",
901
+ // chain: "avax",
902
+ // });
903
+ // console.log(price);
904
+ // };
905
+ //
906
+ // web3API();
907
+ //isTestnet
908
+ output.version = await web3.eth.getNodeInfo();
909
+ output.chainId = await web3.eth.getChainId();
910
+ output.height = await web3.eth.getBlockNumber();
911
+ //TODO get peer count
912
+ // output.peers = await web3.eth.net.getPeerCount()
913
+ let networkName;
914
+ switch (output.chainId.toString()) {
915
+ case "1":
916
+ networkName = "Main";
917
+ break;
918
+ case "2":
919
+ networkName = "Morden";
920
+ break;
921
+ case "3":
922
+ networkName = "Ropsten";
923
+ break;
924
+ case "4":
925
+ networkName = "Rinkeby";
926
+ break;
927
+ case "42":
928
+ networkName = "Kovan";
929
+ break;
930
+ case "43114":
931
+ networkName = "avalanche";
932
+ break;
933
+ default:
934
+ networkName = "Unknown";
935
+ }
936
+ output.networkName = networkName;
937
+ //
938
+ output.gasPrice = await web3.eth.getGasPrice();
939
+ //
940
+ // output.syncing = await web3.eth.isSyncing()
941
+ return output;
942
+ }
943
+ catch (e) {
944
+ console.error(tag, e);
945
+ }
946
+ };
947
+ const get_balance = async function (address) {
948
+ let tag = TAG + " | get_balance | ";
949
+ try {
950
+ let output = {};
951
+ //normal tx info
952
+ output = (await web3.eth.getBalance(address)) / BASE;
953
+ return output;
954
+ }
955
+ catch (e) {
956
+ console.error(tag, e);
957
+ }
958
+ };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pioneer-platform/avax-network",
3
- "version": "0.3.1",
3
+ "version": "0.5.0",
4
4
  "main": "./lib/index.js",
5
5
  "types": "./lib/index.d.ts",
6
6
  "scripts": {
@@ -15,8 +15,8 @@
15
15
  },
16
16
  "dependencies": {
17
17
  "@ethersproject/providers": "^5.1.0",
18
- "@pioneer-platform/blockbook": "^8.4.1",
19
- "@pioneer-platform/loggerdog": "^8.4.1",
18
+ "@pioneer-platform/blockbook": "^8.6.0",
19
+ "@pioneer-platform/loggerdog": "^8.6.0",
20
20
  "@xchainjs/xchain-util": "^0.2.6",
21
21
  "axios": "^1.6.0",
22
22
  "dotenv": "^8.2.0",