forked from sebseb7/cryptonote-proxy
-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathcoin.js
430 lines (355 loc) · 20.6 KB
/
coin.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
'use strict'
const axios = require('axios');
const urljoin = require('url-join');
const assumestaleafterxseconds = 8;
var CoinMethods = {
/**
* @typedef { {symbol: string, isdefault: boolean, name: string, algo: string, login: string, url: string, api: string, network: object, ticker: string, coinunit: number, marketvalue: number, rewardperday: number, mergewith:Coin, mergedreward: number} } Coin
* @typedef { {hashrate: number, difficulty: number, blockreward: number, poolblockheight: number, blockheight: number, pooleffort: number, lastblockdatetime: Date, coindifficultytarget: number, hasError: boolean, apiType: string, updatetime: number } } CoinNetwork
* @typedef { {priceapi: string, pricetype: string, marketname: string, converttobtc: string, price: number, hasError: boolean, updatetime: number} } Ticker
*/
/**
* @param {Coin[]} coins - Array of coins
* @param {Coin} activeCoin - actively mined coin
* @param {number} [algoswitchmultiplier] - Algo Switch Penalty Multiplier
* @returns {Coin}
*/
getPreferredCoin : async function(coins, activeCoin = null, algoswitchmultiplier = 1) {
let now = (new Date().getTime()) / 1000;
let promisechain = [];
let activeAlgo = activeCoin && activeCoin.algo;
algoswitchmultiplier = (activeAlgo && algoswitchmultiplier) || 1;
for(let mergedcoin of coins) {
let coin = mergedcoin;
while(coin) {
if(!coin.network.updatetime || (now - coin.network.updatetime) > assumestaleafterxseconds) promisechain.push(coin.FetchNetworkDetails());
if(!coin.ticker.updatetime || (now - coin.ticker.updatetime) > assumestaleafterxseconds) promisechain.push(coin.FetchMarketValue());
coin = coin.mergewith;
}
}
/**
* @type Coin
*/
let maxRewardCoin = await Promise.all(promisechain).then(()=> {
let targetCoin;
coins.map((c) => {
targetCoin = targetCoin || c;
let targetCoinHandicap = (targetCoin.algo == activeAlgo) && 1 || algoswitchmultiplier;
let testedCoinHandicap = (c.algo == activeAlgo) && 1 || algoswitchmultiplier;
targetCoin = ((c.mergedreward * testedCoinHandicap * (c.hashrate || 1)) > (targetCoin.mergedreward * targetCoinHandicap * targetCoin.hashrate || 1)) ? c : targetCoin;
});
return targetCoin;
});
return maxRewardCoin;
},
Coin: class {
/**
* @param {string} symbol
* @param {string} name
* @param {string} walletaddress
* @param {string} [url]
* @param {string} [api]
* @param {Ticker} [ticker]
* @param {number} hashrate
* @param {boolean} isdefault
* @param {Coin} mergewith
*/
constructor(symbol, name, algo, walletaddress, url, api, ticker, isdefault, hashrate, mergewith) {
this.symbol = symbol;
this.name = name || symbol;
this.login = walletaddress;
this.algo = algo,
this.url = url;
this.isdefault = isdefault;
this.hashrate = hashrate;
/** @type {boolean} */
this.minersupport = true;
this.api = api;
/** @type {CoinNetwork} */
this.network = {};
this.ticker = ticker || {};
this.coinunit = 1000000000;
this.marketvalue = 0;
this.rewardperday = 0;
this.mergewith = mergewith;
this.networkAPIS = {
genericCryptonote: async () => {
try {
this.network.hasError = "";
let response = await axios.get(urljoin(this.api, "stats")).catch(() => {throw new Error("URL failed to load")});
if(response.data.error) {throw new Error("API response error")};
this.network.difficulty = response.data.network.difficulty;
if(!(this.network.blockheight = response.data.network.height)) {throw new Error("Wrong api type")};
this.network.lastblockdatetime = response.data.pool.stats.lastBlockFound / 1000;
this.coinunit = response.data.config.coinUnits || this.coinunit;
//this.network.reward = (response.data.network.reward - (response.data.network.devfee || 0) - (response.data.network.coinbase || 0)) / this.coinunit;
if(!(this.network.reward = response.data.network.reward)) {throw new Error("Wrong api type")};
this.network.reward /= this.coinunit;
this.rewardperday = (86400000 / this.network.difficulty) * this.network.reward;
this.network.coindifficultytarget = response.data.config.coinDifficultyTarget;
this.network.updatetime = ((new Date).getTime())/1000;
}
catch(error) {
if (!this.network.apiType == "__detecting") console.log("Network API response error for coin:" + this.symbol + "/n" + error);
this.network.hasError = error;
}
},
fairpool: async () => {
try {
this.network.hasError = "";
let response = await axios.get(urljoin(this.api, "stats")).catch(() => {throw new Error("URL failed to load")});
if(response.data.error) {throw new Error("API response error")};
this.network.difficulty = response.data.network.difficulty;
this.network.lastblockdatetime = response.data.pool.stats.lastBlockFound / 1000;
this.coinunit = response.data.config.coinUnits || this.coinunit;
this.network.coindifficultytarget = response.data.config.coinDifficultyTarget
response = await axios.get(urljoin(this.api, "network")).catch(() => {throw new Error("URL failed to load")});
if(!(this.network.blockheight = response.data.blockchainHeight)) {throw new Error("Wrong api type")};
//Note: Not sure fair pool api supports dev fees or coinbase fees.
this.network.reward = response.data.reward / this.coinunit;
this.rewardperday = (86400000 / this.network.difficulty) * this.network.reward;
this.network.updatetime = ((new Date).getTime())/1000;
}
catch(error) {
if (!this.network.apiType == "__detecting") console.log("Network API response error for coin:" + this.symbol + "/n" + error);
this.network.hasError = error;
}
},
cryptonoteHashvault: async () => {
try {
this.network.hasError = "";
let response = await axios.get(urljoin(this.api, "stats")).catch(() => {throw new Error("URL failed to load")});
if(response.data.error) {throw new Error("API response error")};
if(!response.data.network_statistics || !response.data.pool_statistics || !response.data.pool_statistics.lastPoolBlock || !(this.network.difficulty = response.data.network_statistics.difficulty)) {throw new Error("Wrong api type")};
this.network.blockheight = response.data.network_statistics.height;
this.coinunit = response.data.config.sigDivisor || this.coinunit;
this.network.reward = (response.data.pool_statistics.lastPoolBlock.value || response.data.network_statistics.value) / this.coinunit;
this.network.lastblockdatetime = response.data.pool_statistics.lastBlockFoundTime;
if(!(this.network.coindifficultytarget = response.data.config.coinDiffTarget)) {throw new Error("Wrong api type")};
this.rewardperday = (86400000 / this.network.difficulty) * this.network.reward;
this.network.updatetime = ((new Date).getTime())/1000;
}
catch(error) {
if (!this.network.apiType == "__detecting") console.log("Network API response error for coin:" + this.symbol + "/n" + error);
this.network.hasError = error;
}
},
cryptonoteHashvaultV3: async () => {
try {
this.network.hasError = "";
let response = await axios.get(this.api).catch(() => {throw new Error("URL failed to load")});
if(response.data.error) {throw new Error("API response error")};
if(!response.data.network_statistics || !response.data.pool_statistics || !response.data.pool_statistics.collective || !(this.network.difficulty = response.data.block_template.difficulty)) {throw new Error("Wrong api type")};
this.network.blockheight = response.data.network_statistics.height;
this.coinunit = response.data.config.sigDivisor || this.coinunit;
this.network.reward = (response.data.pool_statistics.general.last10blocksAvgReward || response.data.network_statistics.value) / this.coinunit;
this.network.lastblockdatetime = response.data.pool_statistics.collective.lastFoundBlock.ts / 1000;
if(!(this.network.coindifficultytarget = response.data.config.coinDiffTarget)) {throw new Error("Wrong api type")};
this.rewardperday = (86400000 / this.network.difficulty) * this.network.reward;
this.network.updatetime = ((new Date).getTime())/1000;
}
catch(error) {
if (!this.network.apiType == "__detecting") console.log("Network API response error for coin:" + this.symbol + "/n" + error);
this.network.hasError = error;
}
},
cryptonotepool: async () => {
try {
this.network.hasError = "";
let response = await axios.get(urljoin(this.api, "network/stats")).catch(() => {throw new Error("URL failed to load")});
if(response.data.error) {throw new Error("API response error")};
if(!(this.network.difficulty = response.data.difficulty) || !(this.network.blockheight = response.data.height)) {throw new Error("Wrong api type")};
//Note: coin unit is not supported by this api. Assuming default cryptonote coin unit.
//this.coinunit = response.data.config.coinUnits || this.coinunit;
this.network.reward = response.data.value / this.coinunit;
//this.network.blockheight = response.data.height;
response = await axios.get(urljoin(this.api, "pool/stats")).catch(() => {throw new Error("URL failed to load")});;
this.network.lastblockdatetime = response.data.pool_statistics.lastBlockFoundTime;
//Note: coin difficulty target is not supported by this api. Pool effort cannot be calculated independently in future if this is not set.
this.network.coindifficultytarget = 0;
this.rewardperday = (86400000 / this.network.difficulty) * this.network.reward;
this.network.updatetime = ((new Date).getTime())/1000;
}
catch(error) {
if (!this.network.apiType == "__detecting") console.log("Network API response error for coin:" + this.symbol + "/n" + error);
this.network.hasError = error;
}
},
bombapi: async () => {
try {
this.network.hasError = "";
let response = await axios.get(this.api).catch(() => {throw new Error("URL failed to load")});
if(response.data.error) {throw new Error("API response error")};
if(!(this.network.difficulty = response.data.netStats && response.data.netStats.difficulty)) {throw new Error("Wrong api type")};
this.coinunit = response.data.sigDivisor || this.coinunit;
this.network.reward = response.data.lastBlockReward / this.coinunit;
this.network.blockheight = response.data.netStats.height;
this.network.lastblockdatetime = response.data.stats.lastBlockFoundTime;
this.network.coindifficultytarget = response.data.coinDiffTarget;
this.rewardperday = (86400000 / this.network.difficulty) * this.network.reward;
this.network.updatetime = ((new Date).getTime())/1000;
}
catch(error) {
if (!this.network.apiType == "__detecting") console.log("Network API response error for coin:" + this.symbol + "/n" + error);
this.network.hasError = error;
}
},
cryptonoteNodejs: async () => {
try {
this.network.hasError = "";
let response = await axios.get(urljoin(this.api, "stats")).catch(() => {throw new Error("URL failed to load")});
if(response.data.error) {throw new Error("API response error")};
if(!(this.network.difficulty = response.data.network.difficulty)) {throw new Error("Wrong api type")};
this.coinunit = response.data.config.coinUnits || this.coinunit;
this.network.reward = (response.data.pool.averageReward || response.data.lastblock.reward) / this.coinunit;
this.network.blockheight = response.data.network.height;
this.network.lastblockdatetime = response.data.pool.lastBlockFound / 1000;
this.network.coindifficultytarget = response.data.config.coinDifficultyTarget;
this.rewardperday = (86400000 / this.network.difficulty) * this.network.reward;
this.network.updatetime = ((new Date).getTime())/1000;
}
catch(error) {
if (!this.network.apiType == "__detecting") console.log("Network API response error for coin:" + this.symbol + "/n" + error);
this.network.hasError = error;
}
}
};
this.priceAPIS = {
tradeogre: async() => {
let pricetypes = {
buy: "ask",
sell: "bid",
market: "price"
}
if (!this.ticker || !this.ticker.marketname) return false;
try {
this.ticker.hasError = false;
let response = await axios.get(urljoin("https://tradeogre.com/api/v1/ticker/", this.ticker.marketname)).catch((error) => {throw new Error(error);});
let btcconvertresponse = (this.ticker.converttobtc) ? await axios.get(urljoin("https://tradeogre.com/api/v1/ticker/", this.ticker.converttobtc)).catch((error) => {throw new Error(error);}) : null;
if(response.data.error || (btcconvertresponse && btcconvertresponse.data.error)) {throw new Error("API response error")};
let btcconvertmultiplier = btcconvertresponse && btcconvertresponse.data[pricetypes.buy] || 1;
this.ticker.updatetime = ((new Date).getTime())/1000;
return this.marketvalue = response.data[pricetypes[this.ticker.pricetype]] * btcconvertmultiplier;
}
catch(error) {
this.ticker.hasError = true;
console.log("Ticker API response failed for coin:" + this.symbol + "/n" + error);
this.marketvalue = 0;
}
},
stex: async() => {
let pricetypes = {
buy: "ask",
sell: "bid",
market: "last"
}
if (!this.ticker || !this.ticker.marketname) return false;
try {
this.ticker.hasError = false;
let response = await axios.get(urljoin("https://api3.stex.com/public/ticker/", this.ticker.marketname)).catch((error) => {throw new Error(error);});
let btcconvertresponse = (this.ticker.converttobtc) ? await axios.get(urljoin("https://api3.stex.com/public/ticker/", this.ticker.converttobtc)).catch((error) => {throw new Error(error);}) : null;
if(response.data.Error || (btcconvertresponse && btcconvertresponse.data.Error)) {throw new Error("API response error")};
let btcconvertmultiplier = btcconvertresponse && btcconvertresponse.data.data[pricetypes.buy] || 1;
this.ticker.updatetime = ((new Date).getTime())/1000;
return this.marketvalue = response.data.data[pricetypes[this.ticker.pricetype]] * btcconvertmultiplier;
}
catch(error) {
this.ticker.hasError = true;
console.log("Ticker API response failed for coin:" + this.symbol + "/n" + error);
this.marketvalue = 0;
}
},
crex24: async() => {
let pricetypes = {
buy: "ask",
sell: "bid",
market: "last"
}
if (!this.ticker || !this.ticker.marketname) return false;
try {
let response = await axios.get("https://api.crex24.com/v2/public/tickers?instrument=" + this.ticker.marketname.toUpperCase()).catch((error) => { throw new Error(error); });
let btcconvertresponse = (this.ticker.converttobtc) ? await axios.get("https://api.crex24.com/v2/public/tickers?instrument=" + this.ticker.converttobtc.toUpperCase()).catch((error) => { throw new Error(error); }) : null;
if (response.data.errorDescription || (btcconvertresponse && btcconvertresponse.data.errorDescription)) {throw new Error("API response error")};
let btcconvertmultiplier = btcconvertresponse && btcconvertresponse.data[0][pricetypes.buy] || 1;
this.ticker.updatetime = ((new Date).getTime()) / 1000;
return this.marketvalue = response.data[0][pricetypes[this.ticker.pricetype]] * btcconvertmultiplier;
}
catch (error) {
this.ticker.hasError = true;
console.log("Ticker API response failed for coin:" + this.symbol + "/n" + error);
this.marketvalue = 0;
}
},
qtrade: async() => {
let pricetypes = {
buy: "ask",
sell: "bid",
market: "last"
}
if (!this.ticker || !this.ticker.marketname) return false;
try {
this.ticker.hasError = false;
let response = await axios.get(urljoin("https://api.qtrade.io/v1/ticker/", this.ticker.marketname)).catch((error) => {throw new Error(error);});
let btcconvertresponse = (this.ticker.converttobtc) ? await axios.get(urljoin("https://api.qtrade.io/v1/ticker/", this.ticker.converttobtc)).catch((error) => {throw new Error(error);}) : null;
if(response.data.errors || (btcconvertresponse && btcconvertresponse.data.errors)) {throw new Error("API response error")};
let btcconvertmultiplier = btcconvertresponse && btcconvertresponse.data.data[pricetypes.buy] || 1;
this.ticker.updatetime = ((new Date).getTime())/1000;
return this.marketvalue = response.data.data[pricetypes[this.ticker.pricetype]] * btcconvertmultiplier;
}
catch(error) {
this.ticker.hasError = true;
console.log("Ticker API response failed for coin:" + this.symbol + "/n" + error);
this.marketvalue = 0;
}
},
xcalibra: async() => {
let pricetypes = {
buy: "sell",
sell: "buy",
market: "close"
}
if (!this.ticker || !this.ticker.marketname) return false;
try {
let response = await axios.get(urljoin("https://app.xcalibra.com/api/public/v1/tickers/", this.ticker.marketname)).catch((error) => { throw new Error(error); });
let btcconvertresponse = (this.ticker.converttobtc) ? await axios.get(urljoin("https://app.xcalibra.com/api/public/v1/tickers/", this.ticker.converttobtc)).catch((error) => { throw new Error(error); }) : null;
//if (response.data.errorDescription || (btcconvertresponse && btcconvertresponse.data.errorDescription)) {throw new Error("API response error")};
let btcconvertmultiplier = btcconvertresponse && btcconvertresponse.data[pricetypes.buy] || 1;
this.ticker.updatetime = ((new Date).getTime()) / 1000;
return this.marketvalue = response.data[pricetypes[this.ticker.pricetype]] * btcconvertmultiplier;
}
catch (error) {
this.ticker.hasError = true;
console.log("Ticker API response failed for coin:" + this.symbol + "/n" + error);
this.marketvalue = 0;
}
},
}
this.FetchNetworkDetails = async () => (this.networkAPIS[await this.getApiType()] && this.networkAPIS[this.network.apiType]()) || (async () => {})
this.FetchMarketValue = (this.ticker && !this.ticker.price && this.priceAPIS[this.ticker.priceapi]) || (async () => (this.marketvalue = this.ticker.price) || false);
}
get mergedreward() {
let valuereward = 0;
if (!this.mergewith) { valuereward = (this.rewardperday || 0) * (this.marketvalue || 0); }
else {
let coin = this;
while (coin) {
valuereward += (coin.rewardperday || 0) * (coin.marketvalue || 0);
coin = coin.mergewith;
}
}
return valuereward;
}
async getApiType() {
if (this.network.apiType) return this.network.apiType;
if (!this.api) return "__apinotset"
this.network.apiType = "__detecting";
for(var apiname in this.networkAPIS) {
await this.networkAPIS[apiname]();
if(!this.network.hasError) return this.network.apiType = apiname;
}
console.log("Failed api detection for coin: " + this.symbol);
return this.network.apiType = "__failed";
}
}
}
module.exports = CoinMethods;