forked from citycoins/scripts
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutils.js
627 lines (581 loc) · 18 KB
/
utils.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
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
import chalk from "chalk";
import { StacksMainnet } from "@stacks/network";
import {
callReadOnlyFunction,
cvToJSON,
cvToValue,
standardPrincipalCV,
uintCV,
} from "@stacks/transactions";
export const title = chalk.bold.blue;
export const success = chalk.bold.green;
export const warn = chalk.bold.yellow;
export const err = chalk.bold.red;
/** @module Utilities */
/**
* @constant
* @type {integer}
* @description used to convert uSTX to STX and reverse
* @default
*/
export const USTX = 1000000;
/**
* @constant
* @type {StacksNetwork}
* @description default Stacks network to connect to
* @default
*/
export const STACKS_NETWORK = new StacksMainnet();
//STACKS_NETWORK.coreApiUrl = "http://157.245.221.74:3999";
STACKS_NETWORK.coreApiUrl = "https://stacks-node-api.stacks.co";
//STACKS_NETWORK.coreApiUrl = "https://mainnet.syvita.org";
/**
* @async
* @function safeFetch
* @param {string} url URL to fetch JSON content from
* @description Returns the JSON content from the specified URL
* @returns {Object[]} JSON object
*/
export async function safeFetch(url) {
// wrapper to handle common errors for fetching from the API
const response = await fetch(url);
if (response.status === 200) {
// success
const responseJson = await response.json();
return responseJson;
} else {
// error
exitWithError(`safeFetch err: ${response.status} ${response.statusText}`);
}
}
/**
* @async
* @function timer
* @param {integer} ms number of milliseconds
* @description Sleeps for the given amount of milliseconds
*/
export const timer = (ms) => new Promise((res) => setTimeout(res, ms));
/**
* @function cancelPrompt
* @param {Object[]} prompt An object that contains the current prompt displayed to the user
* @description Catches a cancel event in prompts, sets the message, and exits the AutoMiner
*/
export const cancelPrompt = (prompt) => {
exitWithError(`ERROR: cancelled by user at ${prompt.name}, exiting...`);
};
/**
* @async
* @function processTx
* @param {TxBroadcastResult} broadcastedResult result from broadcastTransaction() in @stacks/transactions
* @param {string} tx the txid of the transaction
* @description Monitors a transaction and returns the block height it succeeds at
* @returns {integer}
*/
export async function processTx(broadcastedResult, tx) {
let count = 0;
const countLimit = 50;
const url = `${STACKS_NETWORK.coreApiUrl}/extended/v1/tx/${tx}`;
do {
const result = await fetch(url);
const txResult = await result.json();
printDivider();
console.log(
title(
`TX STATUS: ${
txResult.hasOwnProperty("tx_status")
? txResult.tx_status.toUpperCase()
: "PENDING"
}`
)
);
printDivider();
printTimeStamp();
console.log(`https://explorer.stacks.co/txid/${txResult.tx_id}`);
console.log(`attempt ${count + 1} of ${countLimit}`);
if (broadcastedResult.error) {
console.log(`error: ${broadcastedResult.reason}`);
console.log(`details:\n${JSON.stringify(broadcastedResult.reason_data)}`);
return 0;
} else {
if (txResult.tx_status === "success") {
return txResult.block_height;
}
if (txResult.tx_status === "abort_by_post_condition") {
exitWithError(
`tx failed, exiting...\ntxid: ${txResult.tx_id}\nhttps://explorer.stacks.co/txid/${txResult.tx_id}`
);
}
}
// pause for 30min before checking again
await timer(300000);
count++;
} while (count < countLimit);
console.log(warning(`reached retry limit, check tx`));
console.log(`https://explorer.stacks.co/txid/${txResult.tx_id}`);
exitWithError(
"Unable to find target block height for next transaction, exiting..."
);
}
/**
* @async
* @function getBlockHeight
* @description Returns the current Stacks block height
* @returns {integer}
*/
export async function getBlockHeight() {
const url = `${STACKS_NETWORK.coreApiUrl}/v2/info`;
const result = await fetch(url);
const resultJson = await result.json();
return resultJson.stacks_tip_height;
}
/**
* @async
* @function getStxBalance
* @param {string} address STX address to query
* @description Returns the current STX balance of a given address
* @returns {integer}
*/
export async function getStxBalance(address) {
const url = `${STACKS_NETWORK.coreApiUrl}/extended/v1/address/${address}/balances`;
const result = await fetch(url);
const resultJson = await result.json();
return resultJson.stx.balance;
}
/**
* @async
* @function getNonce
* @param {string} address STX address to query
* @description Returns the current nonce for the given address
* @returns {integer}
*/
export async function getNonce(address) {
const url = `${STACKS_NETWORK.coreApiUrl}/v2/accounts/${address}?proof=0`;
const result = await safeFetch(url);
return result.nonce;
}
/**
* @async
* @function getTotalMempoolTx
* @description Returns the total number of transactions in the mempool
* @returns {integer}
*/
export async function getTotalMempoolTx() {
const url = `${STACKS_NETWORK.coreApiUrl}/extended/v1/tx/mempool`;
const result = await fetch(url);
const resultJson = await result.json();
return resultJson.total;
}
/**
* @async
* @function getAccountTxs
* @param {string} address STX address to query
* @description Returns all account transactions for a given address or contract identifier
* @returns {Array[]}
*/
export async function getAccountTxs(address) {
let counter = 0;
let total = 0;
let limit = 50;
let url = "";
let txResults = [];
// bonus points if you use your own node
let stxApi = "https://stacks-node-api.mainnet.stacks.co";
console.log(`getting txs for: ${address}`);
// obtain all account transactions 50 at a time
do {
url = `${stxApi}/extended/v1/address/${address}/transactions?limit=${limit}&offset=${counter}`;
const response = await fetch(url);
if (response.status === 200) {
// success
const responseJson = await response.json();
// get total number of tx
if (total === 0) {
total = responseJson.total;
console.log(`Total Txs: ${total}`);
}
// add all transactions to main array
responseJson.results.map((tx) => {
txResults.push(tx);
counter++;
});
// output counter
console.log(`Processed ${counter} of ${total}`);
} else {
// error
exitWithError(
`getAccountTxs err: ${response.status} ${response.statusText}`
);
}
// pause for 1sec, avoid rate limiting
await timer(1000);
} while (counter < total);
// view the output
//console.log(JSON.stringify(txResults));
return txResults;
}
/**
* @async
* @function getOptimalFee
* @param {integer} multiplier Mulitiplier for mempool average
* @param {boolean} [checkAllTx=false] Boolean to check all transactions in mempool
* @description Averages the fees for the first 200 transactions in the mempool, or optionally all transactions, and applies a multiplier
* @returns {integer} Optimal fee in uSTX
*/
export async function getOptimalFee(multiplier, checkAllTx = false) {
let counter = 0;
let total = checkAllTx ? 0 : 200;
let limit = 200;
let url = "";
let txResults = [];
// query the stacks-node for multiple transactions
do {
url = `${STACKS_NETWORK.coreApiUrl}/extended/v1/tx/mempool?limit=${limit}&offset=${counter}&unanchored=true`;
const result = await safeFetch(url);
// get total number of tx
if (total === 0) {
total = result.total;
}
// add all transactions to main array
result.results.map((tx) => {
txResults.push(tx);
counter++;
});
// output counter
checkAllTx && console.log(`Processed ${counter} of ${total}`);
} while (counter < total);
const max = txResults
.map((fee) => parseInt(fee.fee_rate))
.reduce((a, b) => {
return a > b ? a : b;
});
console.log(`maxFee: ${(max / USTX).toFixed(6)} STX`);
const sum = txResults
.map((fee) => parseInt(fee.fee_rate))
.reduce((a, b) => a + b, 0);
const avg = sum / txResults.length;
console.log(`avgFee: ${(avg / USTX).toFixed(6)} STX`);
return avg * multiplier;
}
/**
* @async
* @function getBlockCommit
* @param {Object[]} userConfig An object that contains the user configuration
* @param {Object[]} miningStrategy An object that contains properties for automatically calculating a commit
* @description Returns a target block commit based on provided user config and mining strategy
* @returns {integer}
*/
export async function getBlockCommit(userConfig, miningStrategy) {
console.log(`strategyDistance: ${miningStrategy.strategyDistance}`);
// get current block height
const currentBlock = await getBlockHeight().catch((err) =>
exitWithError(`getBlockHeight err: ${err}`)
);
// get average block commit for past blocks based on strategy distance
const avgPast = await getBlockAvg(
-1,
currentBlock,
miningStrategy,
userConfig
).catch((err) => exitWithError(`getBlockAvg err: ${err}`));
console.log(`avgPast: ${(avgPast / USTX).toFixed(6)} STX`);
const commitPast = parseInt(
avgPast * (miningStrategy.targetPercentage / 100)
);
// get average block commit for future blocks based on strategy distance
const avgFuture = await getBlockAvg(
1,
currentBlock,
miningStrategy,
userConfig
).catch((err) => exitWithError(`getBlockAvg err: ${err}`));
console.log(`avgFuture: ${(avgFuture / USTX).toFixed(6)} STX`);
const commitFuture = parseInt(
avgFuture * (miningStrategy.targetPercentage / 100)
);
// set commit amount by averaging past and future values
const commitAmount = (commitPast + commitFuture) / 2;
return commitAmount.toFixed();
}
/**
* @async
* @function getBlockAvg
* @param {Object[]} userConfig An object that contains the user configuration
* @description Returns the average block commit for strategyDistance blocks in the past/future
* @returns {integer}
*/
async function getBlockAvg(
direction,
currentBlock,
miningStrategy,
userConfig
) {
const targetBlock =
currentBlock + miningStrategy.strategyDistance * direction;
const blockStats = [];
for (
let i = currentBlock;
direction > 0 ? i < targetBlock : i > targetBlock;
direction > 0 ? i++ : i--
) {
const result = await getMiningStatsAtBlock(
userConfig.contractAddress,
userConfig.contractName,
i
);
blockStats.push(result);
// avoid API rate limiting
await timer(1000);
}
const sum = blockStats.reduce((a, b) => parseInt(a) + parseInt(b), 0);
const avg = sum / miningStrategy.strategyDistance;
return avg;
}
/**
* @async
* @function getMiningStatsAtBlock
* @param {string} contractAddress STX address of the contract deployer
* @param {string} contractName Name of the contract
* @param {integer} blockHeight Block height to query
* @description Returns the total amount of STX sent for a given block height in the specified contracts
* @returns {integer}
*/
async function getMiningStatsAtBlock(
contractAddress,
contractName,
blockHeight
) {
const resultCV = await callReadOnlyFunction({
contractAddress: contractAddress,
contractName: contractName,
functionName: "get-mining-stats-at-block-or-default",
functionArgs: [uintCV(blockHeight)],
network: STACKS_NETWORK,
senderAddress: contractAddress,
});
const result = cvToJSON(resultCV);
return result.value.amount.value;
}
/**
* @async
* @function getStackerAtCycleOrDefault
* @param {string} contractAddress STX address of the contract deployer
* @param {string} contractName Name of the contract
* @param {integer} cycleId Reward cycle to query
* @param {integer} userId User ID to query
* @description Returns the amount stacked and amount to return for a given cycle and user
* @returns {Object[]}
*/
export async function getStackerAtCycleOrDefault(
contractAddress,
contractName,
cycleId,
userId
) {
const resultCv = await callReadOnlyFunction({
contractAddress: contractAddress,
contractName: contractName,
functionName: "get-stacker-at-cycle-or-default",
functionArgs: [uintCV(cycleId), uintCV(userId)],
network: STACKS_NETWORK,
senderAddress: contractAddress,
});
const result = cvToJSON(resultCv);
return result;
}
/**
* @async
* @function getStackingReward
* @param {string} contractAddress STX address of the contract deployer
* @param {string} contractName Name of the contract
* @param {integer} cycleId Reward cycle to query
* @param {integer} userId User ID to query
* @description Returns the amount of STX a user can claim in a given reward cycle in uSTX.
* @returns {integer}
*/
export async function getStackingReward(
contractAddress,
contractName,
cycleId,
userId
) {
const resultCv = await callReadOnlyFunction({
contractAddress: contractAddress,
contractName: contractName,
functionName: "get-stacking-reward",
functionArgs: [uintCV(userId), uintCV(cycleId)],
network: STACKS_NETWORK,
senderAddress: contractAddress,
});
const result = cvToJSON(resultCv);
return parseInt(result.value);
}
/**
* @async
* @function getUserId
* @param {string} contractAddress STX address of the contract deployer
* @param {string} contractName Name of the contract
* @param {string} address Stacks address to query
* @description Returns the userId in the CityCoin contract for a given address
* @returns {integer}
*/
export async function getUserId(contractAddress, contractName, address) {
const resultCv = await callReadOnlyFunction({
contractAddress: contractAddress,
contractName: contractName,
functionName: "get-user-id",
functionArgs: [standardPrincipalCV(address)],
network: STACKS_NETWORK,
senderAddress: contractAddress,
});
const result = cvToValue(resultCv);
return parseInt(result.value);
}
/**
* @async
* @function getRewardCycle
* @param {string} contractAddress STX address of the contract deployer
* @param {string} contractName Name of the contract
* @param {integer} blockHeight Block height to query
* @description Returns the reward cycle for a given block height
* @returns {integer}
*/
export async function getRewardCycle(
contractAddress,
contractName,
blockHeight
) {
const resultCv = await callReadOnlyFunction({
contractAddress: contractAddress,
contractName: contractName,
functionName: "get-reward-cycle",
functionArgs: [uintCV(blockHeight)],
network: STACKS_NETWORK,
senderAddress: contractAddress,
});
const result = cvToJSON(resultCv);
return parseInt(result.value.value);
}
/**
* @async
* @function canClaimMiningReward
* @param {string} contractAddress
* @param {string} contractName
* @param {string} address
* @param {integer} blockHeight
* @description Returns true if the user can claim a reward for a given block height
* @returns {bool}
*/
export async function canClaimMiningReward(
contractAddress,
contractName,
address,
blockHeight
) {
const resultCv = await callReadOnlyFunction({
contractAddress: contractAddress,
contractName: contractName,
functionName: "can-claim-mining-reward",
functionArgs: [standardPrincipalCV(address), uintCV(blockHeight)],
network: STACKS_NETWORK,
senderAddress: contractAddress,
});
const result = cvToJSON(resultCv);
return result.value;
}
/**
* @function printDivider
* @description Prints a consistent divider used for logging
*/
export function printDivider() {
console.log(`-------------------------`);
}
/**
* @function printTimeStamp
* @description Prints a consistent timestamp used for logging
*/
export function printTimeStamp() {
let newDate = new Date().toLocaleString();
newDate = newDate.replace(/,/g, "");
console.log(newDate);
}
/**
* @function exitWithSuccess
* @param {string} message
* @description Prints a final message and exits the running script
*/
export function exitWithSuccess(message) {
console.log(success(message));
process.exit(1);
}
/**
* @function exitWithError
* @param {string} message
* @description Prints an error message and exits the running script
*/
export function exitWithError(message) {
console.log(err(message));
process.exit(1);
}
/**
* @async
* @function waitUntilBlock
* @param {Object[]} userConfig An object that contains the user configuration
* @returns {boolean}
*/
export async function waitUntilBlock(userConfig) {
// config
var init = true;
var currentBlock = 0;
// loop until target block is reached
do {
if (init) {
init = !init;
} else {
if (userConfig.targetBlockHeight - currentBlock > 25) {
// over 25 blocks (4 hours / 240 minutes)
// check every 2hr
await timer(7200000);
} else if (userConfig.targetBlockHeight - currentBlock > 5) {
// between 5-25 blocks (50 minutes - 4 hours)
// check every 30min
await timer(1800000);
} else {
// less than 5 blocks (50 minutes)
// check every 5min
await timer(300000);
}
}
printDivider();
console.log(title(`STATUS: WAITING FOR TARGET BLOCK`));
printDivider();
printTimeStamp();
console.log(
`account: ${userConfig.stxAddress.slice(
0,
5
)}...${userConfig.stxAddress.slice(userConfig.stxAddress.length - 5)}`
);
currentBlock = await getBlockHeight().catch((err) =>
exitWithError(`getBlockHeight err: ${err}`)
);
console.log(`currentBlock: ${currentBlock}`);
console.log(`targetBlock: ${userConfig.targetBlockHeight}`);
if (currentBlock < userConfig.targetBlockHeight) {
console.log(
`distance: ${userConfig.targetBlockHeight - currentBlock} blocks to go`
);
const remainingTime =
((userConfig.targetBlockHeight - currentBlock) * 10) / 60;
if (remainingTime >= 1) {
console.log(`time: ${remainingTime.toFixed(2)} hours`);
} else {
console.log(`time: ${(remainingTime * 60).toFixed()} minutes`);
}
}
const mempoolTxCount = await getTotalMempoolTx().catch((err) =>
exitWithError(`getTotalMempoolTx err: ${err}`)
);
console.log(`mempoolTxCount: ${mempoolTxCount}`);
} while (userConfig.targetBlockHeight > currentBlock);
return true;
}