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