forked from Heimdall-Industries/Heidrun
-
Notifications
You must be signed in to change notification settings - Fork 0
/
start.js
653 lines (594 loc) · 17.2 KB
/
start.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
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
const web3 = require("@solana/web3.js");
const atlas = require("@staratlas/factory");
const { PublicKey } = require("@solana/web3.js");
const readlineModule = require("readline");
const args = require("minimist")(process.argv.slice(2));
const Write = require("./lib/write");
const Web3 = require("./lib/web3");
const {
DECIMALS,
autoBuy,
autoStake,
atlasTokenMint,
connection,
resourceAddresses,
scoreProgramId,
keypair,
traderProgramId,
traderOwnerId,
nftInformation,
nftShipInformation,
nftResourceInformation,
inventory,
getNftInformation,
} = Web3;
let nftAutoBuyInformation;
let activeFleets = [];
const triggerPercentage = 1;
const orderForDays = 30;
const userPublicKey = keypair.publicKey;
const millisecondsInDay = 86100000;
const minimumIntervalTime = 600000;
const maximumIntervalTime = 6000000;
let intervalTime = 0;
let nowSec;
let perDay = {
fuel: [],
food: [],
arms: [],
toolkit: [],
};
const getResupplyInstruction = async (resource, shipInfo, fleet) => {
const {
createRefeedInstruction,
createRearmInstruction,
createRefuelInstruction,
createRepairInstruction,
} = atlas;
let quantity;
let createInstruction;
switch (resource.name) {
case "Ammunition":
createInstruction = createRearmInstruction;
quantity =
(shipInfo.armsMaxReserve -
getResourcesLeft(
fleet.armsCurrentCapacity,
shipInfo.millisecondsToBurnOneArms,
fleet.currentCapacityTimestamp,
nowSec
)) *
fleet.shipQuantityInEscrow;
break;
case "Food":
createInstruction = createRefeedInstruction;
quantity =
(shipInfo.foodMaxReserve -
getResourcesLeft(
fleet.foodCurrentCapacity,
shipInfo.millisecondsToBurnOneFood,
fleet.currentCapacityTimestamp,
nowSec
)) *
fleet.shipQuantityInEscrow;
break;
case "Fuel":
createInstruction = createRefuelInstruction;
quantity =
(shipInfo.fuelMaxReserve -
getResourcesLeft(
fleet.fuelCurrentCapacity,
shipInfo.millisecondsToBurnOneFuel,
fleet.currentCapacityTimestamp,
nowSec
)) *
fleet.shipQuantityInEscrow;
break;
case "Toolkit":
createInstruction = createRepairInstruction;
quantity =
(shipInfo.toolkitMaxReserve -
getResourcesLeft(
fleet.healthCurrentCapacity,
shipInfo.millisecondsToBurnOneToolkit,
fleet.currentCapacityTimestamp,
nowSec
)) *
fleet.shipQuantityInEscrow;
break;
default:
return false;
}
return await createInstruction(
connection,
userPublicKey,
userPublicKey,
quantity,
fleet.shipMint,
new PublicKey(resource.mint),
new PublicKey(resource.tokenAccount),
scoreProgramId
);
};
async function sendTransactions(txInstruction) {
try {
const tx = new web3.Transaction().add(...txInstruction);
return await connection.sendTransaction(tx, [keypair]);
} catch (e) {
Write.printError(e);
}
}
const getResourcesLeft = (
fleetResourceBurnOutTime,
shipTimeToBurnOneResource,
currentCapacityTimestamp,
currentTimeSec
) => {
const fleetResourceCapacity =
fleetResourceBurnOutTime / (shipTimeToBurnOneResource / 1000);
return (
fleetResourceCapacity -
(currentTimeSec - currentCapacityTimestamp) /
(shipTimeToBurnOneResource / 1000)
);
};
function calculatePercentLeft(
fleetResourceBurnOutTime,
shipTimeToBurnOneResource,
currentCapacityTimestamp,
shipResourceMaxReserve,
currentTimeSec
) {
const resourcesLeft = getResourcesLeft(
fleetResourceBurnOutTime,
shipTimeToBurnOneResource,
currentCapacityTimestamp,
currentTimeSec
);
return resourcesLeft / (shipResourceMaxReserve / 100);
}
let runningProcess;
const gmClientService = new atlas.GmClientService();
async function claimAtlas() {
const txInstructions = [];
for (const fleet of activeFleets) {
txInstructions.push(
await atlas.createHarvestInstruction(
connection,
userPublicKey,
new PublicKey(Web3.atlasTokenMint),
fleet.shipMint,
scoreProgramId
)
);
}
if (!!txInstructions.length) {
return await sendTransactions(txInstructions);
}
return Promise.resolve(false);
}
const sendMarketOrder = async ({ order, quantity }) => {
try {
await connection.sendTransaction(
new web3.Transaction().add(
(
await gmClientService.getCreateExchangeTransaction(
connection,
order,
userPublicKey,
quantity,
traderProgramId
)
).transaction
),
[keypair]
);
} catch (e) {
Write.printError(e);
}
};
const orderResources = async (nftInformation) => {
const orders = await gmClientService.getOpenOrdersForPlayer(
connection,
new PublicKey(traderOwnerId),
traderProgramId
);
return await Promise.allSettled(
orders.map(async (order) => {
const resource = nftInformation.find((nft) => {
return nft.mint === order.orderMint;
});
const resourceName =
resource.name === "Ammunition" ? "Arms" : resource.name;
await sendMarketOrder({
order,
quantity:
perDay[resourceName.toLowerCase()].reduce(
(partialSum, a) => partialSum + a,
0
) * orderForDays,
}).then(async () => {
Write.printLine({
text: "\n RESOURCE ORDER COMPLETED: " + resource.name,
});
});
})
);
};
const haveEnoughResources = ({ fleet, shipInfo }, nowSec) => {
let enoughResources = true;
for (const resource of Object.keys(resourceAddresses)) {
const shipAmount = fleet.shipQuantityInEscrow;
const fleetResource = resource === "toolkit" ? "health" : resource;
const left = getResourcesLeft(
fleet[`${fleetResource}CurrentCapacity`],
shipInfo[
`millisecondsToBurnOne${
resource.charAt(0).toUpperCase() + resource.slice(1)
}`
],
fleet.currentCapacityTimestamp,
nowSec
);
const max = shipInfo[`${resource}MaxReserve`] * shipAmount;
const current = left * shipAmount;
const needed = max - current;
if (inventory[resource] < needed) {
enoughResources = false;
}
}
return Promise.resolve(enoughResources);
};
const processAutoBuy = async (shipToAutoBuy) => {
if (!!shipToAutoBuy) {
const sellOrders = (
await gmClientService.getOpenOrdersForAsset(
connection,
new PublicKey(autoBuy),
traderProgramId
)
)
.filter(
(order) =>
order.currencyMint === atlasTokenMint && order.orderType === "sell"
)
.sort((a, b) => (a.price / DECIMALS < b.price / DECIMALS ? -1 : 1));
sellOrders.splice(0, 2);
const [sellOrder] = sellOrders;
const atlas = inventory.find((item) => item.mint === atlasTokenMint);
const price =
sellOrder.price / Number("1".padEnd(sellOrder.currencyDecimals + 1, "0"));
if (atlas.amount > price) {
const quantity = Math.floor(atlas.amount / price);
return await sendMarketOrder({
order: sellOrder,
quantity:
quantity > sellOrder.orderQtyRemaining
? sellOrder.orderQtyRemaining
: quantity,
});
}
}
};
const refillResources = async ({ fleet, shipInfo }) => {
const txInstructions = [];
const resources = inventory.filter((item) => item.type === "resource");
for (const resource of resources) {
const instruction = await getResupplyInstruction(resource, shipInfo, fleet);
txInstructions.push(instruction);
}
return await sendTransactions(txInstructions);
};
const refreshStakingFleet = async () => {
activeFleets = await atlas.getAllFleetsForUserPublicKey(
connection,
userPublicKey,
scoreProgramId
);
};
const refreshInventory = async () => {
const inventory = [];
const accountInfo = await Web3.refreshAccountInfo();
if (autoStake) {
const ships = accountInfo.filter((value) => value.type === "ship");
const others = accountInfo.filter((value) => value.type !== "ship");
if (!!ships.length) {
for (const ship of ships) {
Write.printLine({
text: "\n Auto staking " + ship.name,
color: Write.colors.fgYellow,
});
const fleet = activeFleets.find(
(fleet) => fleet.shipMint.toString() === ship.mint
);
let tx;
if (!!fleet) {
tx = await atlas.createPartialDepositInstruction(
connection,
userPublicKey,
ship.amount,
new PublicKey(ship.mint),
new PublicKey(ship.tokenAccount),
new PublicKey(scoreProgramId)
);
} else {
tx = await atlas.createInitialDepositInstruction(
connection,
userPublicKey,
ship.amount,
new PublicKey(ship.mint),
new PublicKey(ship.tokenAccount),
new PublicKey(scoreProgramId)
);
}
if (!!tx) {
await sendTransactions([tx]).then(async () => {
Write.printLine([
{
text:
"\n " +
ship.name +
" is now staking, it will be reflected on refresh.",
color: Write.colors.fgYellow,
},
]);
});
}
}
inventory.push(...others);
} else {
inventory.push(...ships, ...others);
}
} else {
inventory.push(...accountInfo);
}
return inventory;
};
async function start(isFirst = false) {
if (isFirst) {
Write.printLogo();
}
perDay = {
fuel: [],
food: [],
arms: [],
toolkit: [],
};
nowSec = new Date().getTime() / 1000;
Write.printLine([
{ text: " Fetching latest flight data...", color: Write.colors.fgYellow },
]);
if (!nftInformation.length) {
nftInformation.push(...(await getNftInformation()));
nftShipInformation.push(
...nftInformation.filter((nft) => nft.attributes.itemType === "ship")
);
nftResourceInformation.push(
...nftInformation.filter((nft) => nft.attributes.itemType === "resource")
);
nftAutoBuyInformation =
!!autoBuy && nftShipInformation.find((nft) => nft.mint === autoBuy);
}
if (!!autoBuy) {
if (!!nftAutoBuyInformation) {
Write.printLine({
text: ` Auto buy enabled for ${nftAutoBuyInformation.name}.`,
color: Write.colors.fgYellow,
});
} else {
Write.printLine({
text: `Auto buy value incorrect.`,
color: Write.colors.fgRed,
});
}
}
inventory.length = 0;
await refreshStakingFleet();
inventory.push(...(await refreshInventory()));
Write.printAvailableSupply(inventory);
const transactionFleet = [];
if (!!activeFleets.length) {
Write.printLine({
text: ` ${"-".repeat(27)} STAKING ${"-".repeat(27)}`,
});
activeFleets.sort((a, b) =>
nftInformation.find((nft) => nft.mint === a.shipMint.toString())?.name <
nftInformation.find((nft) => nft.mint === b.shipMint.toString())?.name
? -1
: 1
);
} else {
Write.printLine({
text: ` ${"-".repeat(63)}`,
});
}
for (const fleet of activeFleets) {
let needTransaction = false;
const nft = nftInformation.find(
(nft) => nft.mint === fleet.shipMint.toString()
);
const name = ` | ${nft.name} (${fleet.shipQuantityInEscrow})`;
Write.printLine({
text: `${name}${" ".repeat(65 - name.length - 1)}|`,
});
const shipInfo = await atlas.getScoreVarsShipInfo(
connection,
scoreProgramId,
new web3.PublicKey(nft.mint)
);
const healthPercent = calculatePercentLeft(
fleet.healthCurrentCapacity,
shipInfo.millisecondsToBurnOneToolkit,
fleet.currentCapacityTimestamp,
shipInfo.toolkitMaxReserve,
nowSec
);
Write.printPercent(healthPercent > 0 ? healthPercent : 0 , "HEALTH");
if (healthPercent <= triggerPercentage) needTransaction = true;
const fuelPercent = calculatePercentLeft(
fleet.fuelCurrentCapacity,
shipInfo.millisecondsToBurnOneFuel,
fleet.currentCapacityTimestamp,
shipInfo.fuelMaxReserve,
nowSec
);
Write.printPercent(fuelPercent > 0 ? fuelPercent : 0, "FUEL");
if (fuelPercent <= triggerPercentage) needTransaction = true;
const foodPercent = calculatePercentLeft(
fleet.foodCurrentCapacity,
shipInfo.millisecondsToBurnOneFood,
fleet.currentCapacityTimestamp,
shipInfo.foodMaxReserve,
nowSec
);
Write.printPercent(foodPercent > 0 ? foodPercent : 0, "FOOD");
if (foodPercent <= triggerPercentage) needTransaction = true;
const armsPercent = calculatePercentLeft(
fleet.armsCurrentCapacity,
shipInfo.millisecondsToBurnOneArms,
fleet.currentCapacityTimestamp,
shipInfo.armsMaxReserve,
nowSec
);
Write.printPercent(armsPercent > 0 ? armsPercent : 0, "ARMS");
if (armsPercent <= triggerPercentage) {
needTransaction = true;
}
if (needTransaction) {
transactionFleet.push({
fleet,
shipInfo,
nft,
});
}
const calculateDailyUsage = (millisecondsForOne) =>
(millisecondsInDay / millisecondsForOne) * fleet.shipQuantityInEscrow;
const {
millisecondsToBurnOneFuel,
millisecondsToBurnOneArms,
millisecondsToBurnOneFood,
millisecondsToBurnOneToolkit,
} = shipInfo;
perDay.fuel.push(calculateDailyUsage(millisecondsToBurnOneFuel));
perDay.food.push(calculateDailyUsage(millisecondsToBurnOneFood));
perDay.arms.push(calculateDailyUsage(millisecondsToBurnOneArms));
perDay.toolkit.push(calculateDailyUsage(millisecondsToBurnOneToolkit));
Write.printLine({
text: ` ${"-".repeat(63)}`,
});
}
if (transactionFleet.length > 0) {
for (const { fleet, shipInfo, nft } of transactionFleet) {
Write.printLine({
text: `\n ### Resupplying ${nft.name} ###`,
});
const hasEnoughResources = await haveEnoughResources(
{ fleet, shipInfo },
nowSec
);
if (hasEnoughResources) {
await refillResources({ shipInfo, fleet }).then(async () => {
Write.printLine({ text: "\n Resources refilled successfully" });
});
} else {
Write.printLine({ text: "\n Not enough resources, claiming ATLAS" });
await claimAtlas().then(async (result) => {
if (!!result) {
Write.printLine({
text: " ATLAS claimed successfully, buying resources",
});
await orderResources(nftInformation).then(async () => {
Write.printLine({ text: " Resources bought, resupplying" });
await refillResources({ shipInfo, fleet }).then(async () => {
Write.printLine({
text: " Resources resupplied successfully",
});
await processAutoBuy(nftAutoBuyInformation).then(async () => {
Write.printLine({
text:
" Auto buy order completed: " +
nftAutoBuyInformation.name,
});
});
});
});
}
});
}
}
}
intervalTime =
args.interval && args.interval > minimumIntervalTime
? args.interval < maximumIntervalTime
? args.interval
: maximumIntervalTime
: minimumIntervalTime;
Write.printRefreshInformation(intervalTime);
}
const exitProcess = async () => {
Write.printLine({
text: "\n Button 'q' pressed",
color: Write.colors.fgYellow,
});
Write.printLine({
text: "Stopping STAR ATLAS AUTOMATION.",
color: Write.colors.fgYellow,
});
clearInterval(runningProcess);
process.exit(0);
};
readlineModule.emitKeypressEvents(process.stdin);
if (process.stdin.isTTY) {
process.stdin.setRawMode(true);
}
process.stdin.on("keypress", (character) => {
if (character?.toString() === "q") {
return exitProcess();
}
if (character?.toString() === "b") {
if (!!nftAutoBuyInformation) {
Write.printLine({
text: "Starting auto buy process.",
color: Write.colors.fgYellow,
});
return processAutoBuy(nftAutoBuyInformation).then(() => {
Write.printLine({
text: "Auto buy process finished.",
color: Write.colors.fgYellow,
});
});
} else {
Write.printLine({
text: "Auto buy not enabled.",
color: Write.colors.fgRed,
});
}
}
if (character?.toString() === "c") {
Write.printLine({
text: "Starting claim ATLAS process.",
color: Write.colors.fgYellow,
});
return claimAtlas().then(() => {
Write.printLine({
text: "Claim ATLAS process finished.",
color: Write.colors.fgYellow,
});
});
}
if (character?.toString() === "i") {
return Write.printAvailableSupply(inventory, true);
}
return false;
});
const startInterval = async () => {
if (args.noRunningProcess !== "true") {
clearInterval(runningProcess);
runningProcess = setInterval(start, intervalTime);
} else {
process.exit(0);
}
};
start(true)
.then(startInterval)
.catch((err) => console.error(err));