-
Notifications
You must be signed in to change notification settings - Fork 0
/
ath.js
489 lines (416 loc) · 18.1 KB
/
ath.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
// Version 2.0
var logger = require("./logger");
var Web3 = require('web3');
const net = require('net');
var date;
date = new Date();
date = date.getUTCFullYear() + '-' +
('00' + (date.getUTCMonth() + 1)).slice(-2) + '-' +
('00' + date.getUTCDate()).slice(-2) + ' ' +
('00' + date.getUTCHours()).slice(-2) + ':' +
('00' + date.getUTCMinutes()).slice(-2) + ':' +
('00' + date.getUTCSeconds()).slice(-2);
// create an instance of web3 using the HTTP provider.
//var web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8696"));
var web3;
var web3etho;
web3 = new Web3(new Web3.providers.HttpProvider('https://rpc.aheios.org'));
web3etho = new Web3(new Web3.providers.HttpProvider('https://rpc.ethoprotocol.com'));
var version = web3.version;
const ATHPASS=config.ATHPASS;
const FEE= "0.01";
/*
var subscription = web3.eth.subscribe('pendingTransactions', function(error, result){
if (!error) {
logger.info("#server.ath: Subscription: %s",result);
}
})
.on("data", function(transaction){
logger.info("#server.ath: Subscription TX: %s",transaction);
});
*/
// unsubscribes the subscription
//subscription.unsubscribe(function(error, success){
// if(success)
// console.log('Successfully unsubscribed!');
//});
exports.athSynced = function(currency) {
switch(currency) {
case "ATH":
res=web3.eth.isSyncing()
.then(console.log)
return(res);
break;
case "ETHO":
res=web3.eth.isSyncing()
.then(console.log)
return(res);
}
}
exports.athIsAddress = function(currency, address) {
switch(currency) {
case "ATH":
res=web3.utils.isAddress(address)
return(res);
break;
case "ETHO":
res=web3etho.utils.isAddress(address)
return(res);
default:
logger.error('"#server.ath.athIsAdrdees: Unsupported currency');
reject("Unsupported currency")
break;
}
}
exports.athGetAddress = function(currency, cb) {
var rows;
var accounts;
var athaddress;
return new Promise( ( resolve, reject ) => {
switch (currency) {
case "ATH":
web3.eth.personal.newAccount(ATHPASS, function (error, athaddress) {
if (error) {
logger.error("#server.ath.athGetAddress: Cannot create account");
reject(error);
} else {
logger.info("#server.ath.athGetAddress: New ATH address created: %s", athaddress);
resolve(athaddress);
}
});
break;
case "ETHO":
web3etho.eth.personal.newAccount(ATHPASS, function (error, ethoaddress) {
if (error) {
logger.error("#server.ath.athGetAddress: Cannot create account");
reject(error);
} else {
logger.info("#server.ath.athGetAddress: New ETHO address created: %s", ethoaddress);
resolve(ethoaddress);
}
});
break;
default:
logger.error('"#server.ath.athGetAddress: Unsupported currency');
reject("Unsupported currency")
break;
}
});
};
exports.athGetBalance = function(currency, fromaddress, cb) {
var athamount;
var ethoamount;
return new Promise( ( resolve, reject ) => {
logger.info("#server.ath.athGetBalance: Address to get balance: %s", fromaddress);
switch (currency) {
case "ATH":
web3.eth.getBalance(fromaddress, function (error, weiamount) {
if (error) {
logger.error("#server.ath.athGetBalance: Error fetching ATH balance: %s", error);
reject(error);
} else {
logger.info("#server.ath.athGetBalance: ATH Amount in Wei %s", weiamount);
athamount = web3.utils.fromWei(weiamount.toString(), 'ether');
resolve(athamount);
}
});
break;
case "ETHO":
web3etho.eth.getBalance(fromaddress, function (error, weiamount) {
if (error) {
logger.error("#server.ath.athGetBalance: Error fetching ETHO balance: %s", error);
reject(error);
} else {
logger.info("#server.ath.athGetBalance: ETHO Amount in Wei %s", weiamount);
ethoamount = web3etho.utils.fromWei(weiamount.toString(), 'ether');
resolve(ethoamount);
}
});
break;
default:
logger.error('"#server.ath.athGetBalance: Unsupported currency: %s', currency);
reject("Unsupported currency");
break;
}
});
};
exports.athdoWithdraw= function(currency, fromaddress, depositaddr, depositamount, cb) {
var rows;
var wb3;
return new Promise((resolve, reject) => {
logger.info("#server.ath.athdoWithdraw: Start process for %s", currency);
switch (currency) {
case "ATH":
wb3 = web3;
break;
case "ETHO":
wb3 = web3etho;
break;
}
if (fromaddress == undefined || fromaddress == "") {
reject("Fromaddress is not valid");
}
if (depositaddr == undefined || depositaddr == "") {
reject("Depositaddress is not valid");
}
if (depositamount == 0) {
reject("Deposit amount is zero");
}
const depositweiamount = wb3.utils.toWei(depositamount.toString());
const BN_depositamount = wb3.utils.toBN(depositweiamount);
var BN_depositamountwithfee = BN_depositamount.add(wb3.utils.toBN(wb3.utils.toWei(FEE)));
var depositamountwithfee = wb3.utils.fromWei(BN_depositamountwithfee,"ether");
logger.info("#server.ath.athdoWithdraw: depositamount %s", depositamount);
// Now let's check if we have enough money
exports.athGetBalance(currency, fromaddress)
.then(async function (amount) {
var BN_amount = wb3.utils.toWei(amount.toString());
logger.info("#server.ath.athdoWithdraw: Amount: %s, Withdraw (incl fee) %s", BN_amount.toString(), BN_depositamountwithfee.toString());
if (BN_depositamountwithfee.lt(BN_amount)) {
logger.error("#server.ath.athdoWithdraw: Balance issue: Amount: %s, Withdraw (incl fee) %s", BN_amount.toString(), BN_depositamountwithfee.toString());
reject("Not anough money to trigger the transfer. Check Your account");
} else {
// We have, so let's unlock the account
// Unlock account for data
logger.info("#server.ath.athdoWithdraw: Going to unlock account: %s", fromaddress);
await wb3.eth.personal.unlockAccount(fromaddress, ATHPASS, 50)
.then(async function () {
logger.info("#server.ath.athdoWithdraw: Transferring from: %s, to %s, amount %s", fromaddress, depositaddr, depositamountwithfee);
await transfer_ath(currency, fromaddress, depositaddr, depositamountwithfee)
.then(function (receipt) {
resolve (receipt);
})
.catch(function (error) {
reject ("Transfer failed: " + error);
})
})
.catch(function(error) {
logger.error("#server.ath.athdoWithdraw: Unlock not successful.");
reject("Can't unlock account: " + error);
})
}
})
.catch(function (error) {
logger.error("#server.ath.athdoWithdraw: Error: Unlock unsuccessful: %s", fromaddress);
reject ("Can't unlock account: " + error);
})
});
}
exports.athdoTransfer= function(currency, fromaddress, depositaddr, depositamount, cb) {
var rows;
var wb3;
return new Promise(async (resolve, reject) => {
logger.info("#server.ath.athdoTransfer: Start process for %s", currency);
switch (currency) {
case "ATH":
wb3 = web3;
break;
case "ETHO":
wb3 = web3etho;
break;
}
if (fromaddress == undefined || fromaddress == "") {
reject("Fromaddress is not valid");
}
if (depositaddr == undefined || depositaddr == "") {
reject("Depositaddress is not valid");
}
if (depositamount == 0) {
reject("Deposit amount is zero");
}
const depositweiamount = wb3.utils.toWei(depositamount.toString());
const BN_depositamount = wb3.utils.toBN(depositweiamount);
var BN_depositamountwithfee = BN_depositamount.add(wb3.utils.toBN(wb3.utils.toWei(FEE)));
var depositamountwithfee = wb3.utils.fromWei(BN_depositamountwithfee,"ether");
logger.info("#server.ath.athdoTransfer: depositamount %s", depositamount);
// Now let's check if we have enough money
exports.athGetBalance(currency, fromaddress)
.then(async function (amount) {
var BN_amount = wb3.utils.toWei(amount.toString());
logger.info("#server.ath.athdoTransfer: Amount: %s, Withdraw (incl fee) %s", BN_amount.toString(), BN_depositamountwithfee.toString());
if (BN_depositamountwithfee.lt(BN_amount)) {
logger.error("#server.ath.athdoTransfer: Balance issue: Amount: %s, Withdraw (incl fee) %s", BN_amount.toString(), BN_depositamountwithfee.toString());
reject("Not anough money to trigger the transfer. Check Your account");
} else {
// We have, so let's unlock the account
// Unlock account for data
const nonce = await wb3.eth.getTransactionCount(fromaddress, 'latest'); // nonce starts counting from 0
const transaction = {
'to': depositaddr, // faucet address to return eth
'value': BN_depositamount,
'gas': 30000,
'nonce': nonce,
// optional data field to send message or execute smart contract
};
const signedTx = await wb3.eth.accounts.signTransaction(transaction, config.ATHPASS);
await wb3.eth.sendSignedTransaction(signedTx.rawTransaction, function(error, hash) {
if (!error) {
resolve(hash);
} else {
reject("Can't send transaction: " + error);
}
});
}
})
.catch(function (error) {
logger.error("#server.ath.athdoTrasnfer: Error: Unlock unsuccessful: %s", fromaddress);
reject ("Can't unlock account: " + error);
})
});
}
// Send ath from an address to an address and with a certain amount
function transfer_ath(currency, fromaddress, toaddress, amount, cb) {
var wb3;
switch (currency) {
case "ATH":
wb3=web3;
break;
case "ETHO":
wb3=web3etho;
break;
}
var BN = web3.utils.BN;
var lo_weiamount = wb3.utils.toWei(amount.toString(), 'ether');
var BN_amount = wb3.utils.toBN(lo_weiamount);
var lo_tx = null;
return new Promise((resolve, reject) => {
wb3.eth.getGasPrice()
.then(async function(gasprice) {
// The amount includes already the trnasfer fee
logger.info("#server.ath.transfer_ath: Gasprice: %s: ", gasprice);
const gasprovided=21000;
var sendAmount = BN_amount.sub(new BN(gasprice*gasprovided*2));
logger.info("#server.ath.transfer_ath: Send addr: %s, Rec addr %s, Total wei: %s, with fee reduced: %s", fromaddress, toaddress, BN_amount, sendAmount);
// Prepare the transaction to send the balance
lo_tx = {
from: fromaddress,
to: toaddress,
gas: gasprovided,
value: wb3.utils.toHex(sendAmount)
};
logger.info("#server.ath.transfer_ath: Sending transaction ...%s", JSON.stringify(lo_tx));
await wb3.eth.personal.sendTransaction(lo_tx, ATHPASS, function (error, hash) {
if (error) {
logger.error("#server.ath.transfer_ath: Cannot send transaction: %s", error);
reject(error);
} else {
logger.info("#server.ath.transfer_ath: Successful transaction: %s", hash);
resolve(hash);
}
});
})
.catch(function(error) {
logger.error("#server.ath.transfer_ath: Cannot get pasprice: %s", error);
reject(error);
})
});
}
exports.athGetBlockNumber = function(cb) {
web3.eth.getBlockNumber(function(error, result) {
if(!error) {
logger.info("#server.ath.athGetBlockNumber: blockNumber: %s", result);
cb(null, result);
} else {
logger.error("#server.ath.athGetBlockNumber: Error: %s", error);
cb(error, null);
}
});
};
exports.athGetHashrate = function(cb) {
web3.eth.getBlockNumber(function(error, blockNum) {
let sampleSize=4;
if(!error) {
web3.eth.getBlock(blockNum, true, function(error, result) {
let t1=result.timestamp;
web3.eth.getBlock(blockNum-sampleSize, true, function(error, result2) {
let t2=result2.timestamp;
let blockTime=(t1-t2)/sampleSize;
let difficulty=result.difficulty;
let hashrate=difficulty / blockTime;
cb(null, hashrate);
});
});
} else {
logger.error("#server.ath.athGetHashrate: Error: %s", error);
cb(error, null);
}
});
};
exports.athGetBlockTime = function(cb) {
web3.eth.getBlockNumber(function(error, blockNum) {
let sampleSize=4;
if(!error) {
web3.eth.getBlock(blockNum, true, function(error, result) {
let t1=result.timestamp;
web3.eth.getBlock(blockNum-sampleSize, true, function(error, result2) {
let t2=result2.timestamp;
let blockTime=(t1-t2)/sampleSize;
cb(null, blockTime);
});
});
} else {
logger.error("#server.ath.athGetBlockTima: Error: %s", error);
cb(error, null);
}
});
};
exports.athGetDifficulty = function(cb) {
web3.eth.getBlockNumber(function(error, blockNum) {
if(!error) {
web3.eth.getBlock(blockNum, true, function(error, result) {
let difficulty=result.difficulty;
cb(null, difficulty);
});
} else {
console.log("error", error);
cb(error, null);
}
});
};
exports.athGetTransaction = function(cb) {
var gasUsed=[];
web3.eth.getBlockNumber(function(error, blockNum) {
if(!error) {
web3.eth.getBlock(blockNum, function(error, res) {
if(!error) {
gasUsed[0]=res.gasUsed;
web3.eth.getBlock(blockNum-1, function(error, res) {
if(!error) {
gasUsed[1]=res.gasUsed;
web3.eth.getBlock(blockNum-2, function(error, res) {
if(!error) {
gasUsed[2]=res.gasUsed;
web3.eth.getBlock(blockNum-3, function(error, res) {
if(!error) {
gasUsed[3]=res.gasUsed;
jsonstr='{ "gas" : [{"blocknr" : '+blockNum+', "gasUsed" : '+gasUsed[0]+'},'+
'{"blocknr" : '+(blockNum-1)+',"gasUsed" : '+gasUsed[1]+'},'+
'{"blocknr" : '+(blockNum-2)+',"gasUsed" : '+gasUsed[2]+'},'+
'{"blocknr" : '+(blockNum-3)+',"gasUsed" : '+gasUsed[3]+'}]}';
cb(null, jsonstr);
} else {
logger.error("#server.ath.athGetTransaction: Error: %s", error);
cb(error, null);
}
});
} else {
logger.error("#server.ath.athGetTransaction: Error: %s", error);
cb(error, null);
}
});
} else {
logger.error("#server.ath.athGetTransaction: Error: %s", error);
cb(error, null);
}
});
} else {
logger.error("#server.ath.athGetTransaction: Error: %s", error);
cb(error, null);
}
});
} else {
logger.error("#server.ath.athGetTransaction: Error: %s", error);
cb(error, null);
}
});
};