-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathscript.js
More file actions
8017 lines (7239 loc) · 371 KB
/
Copy pathscript.js
File metadata and controls
8017 lines (7239 loc) · 371 KB
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
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* =========================================================================
* script.js — Shard Market
* Hypixel SkyBlock Attribute Shard profitability + fusion analyzer.
*
* No build step. No backend. Pure browser JavaScript, designed for hosting
* on GitHub Pages.
*
* SECTIONS
* 1. Config & constants
* 2. State container
* 3. Cache (localStorage with TTL)
* 4. API + static-data clients
* 5. Profitability math (flip)
* 6. Fusion math (craft-vs-buy)
* 7. Pipeline: raw → enriched → filtered → sorted
* 8. Rendering / DOM
* 9. Event handlers & boot
* ======================================================================= */
"use strict";
/* =========================================================================
* 1. CONFIG
* ======================================================================= */
const CONFIG = {
API_BASE: "https://hypixie.skermiebro.workers.dev",
BAZAAR_ENDPOINT: "/skyblock/bazaar",
PROFILES_ENDPOINT: "/skyblock/profiles",
GARDEN_ENDPOINT: "/skyblock/garden",
ITEMS_ENDPOINT: "/resources/skyblock/items",
ELITE_CONTEST_ENDPOINT: "/elite/contests/at/now",
FIRESALES_PUBLIC_URL: "https://api.hypixel.net/v2/skyblock/firesales",
/* CORS-friendly Mojang proxy for username → UUID resolution. */
USERNAME_LOOKUP_URL: "https://api.ashcon.app/mojang/v2/user/",
/* Static SkyShards datasets (bundled in /data/). */
FUSION_PROPS_URL: "data/fusion-properties.json",
FUSION_DATA_URL: "data/fusion-data.json",
ATTR_DESC_URL: "data/attribute-desc.json",
/* Public bazaar endpoint needs no key. The key IS required for profile
* lookups — surfaced to the user with a clear error. */
API_KEY_STORAGE: "shardmarket.apiKey",
/* Bazaar tax (sell-order tax) — default 1.25% base. Configurable in UI. */
TAX_STORAGE: "shardmarket.tax",
DEFAULT_TAX: 0.0125,
/* Texture pack preference. */
TEXTURE_STORAGE: "shardmarket.texturePack",
DEFAULT_TEXTURE: "vanilla",
/* Player profile preferences. */
USERNAME_STORAGE: "shardmarket.username",
PROFILE_ID_STORAGE: "shardmarket.profileId",
SWEEP_SHOW_COMPLETED_STORAGE: "shardmarket.sweep.showCompleted",
GARDEN_CHIP_RARITY_STORAGE: "hypixie.gardenChips.targetRarity",
GARDEN_CHIP_LEVEL_STORAGE: "hypixie.gardenChips.targetLevel",
GARDEN_CHIP_SORT_STORAGE: "hypixie.gardenChips.sort",
GARDEN_CHIP_PROGRESS_STORAGE: "hypixie.gardenChips.progress.v1",
/* Cache TTLs. */
CACHE_TTL_BAZAAR_MS: 60_000,
CACHE_TTL_STATIC_MS: 86_400_000,
CACHE_TTL_PROFILE_MS: 300_000, // 5 min — profiles change slowly
CACHE_KEY_BAZAAR: "shardmarket.cache.bazaar",
CACHE_KEY_FUSION_PROPS: "shardmarket.cache.fusionProps.v1",
CACHE_KEY_FUSION_DATA: "shardmarket.cache.fusionData.v1",
CACHE_KEY_ITEMS: "shardmarket.cache.items.v1",
CACHE_KEY_ATTR_DESC: "shardmarket.cache.attrDesc.v1",
CACHE_KEY_BINS: "shardmarket.cache.lowestBins.v3",
CACHE_KEY_FIRESALES: "shardmarket.cache.fireSales.v1",
CACHE_KEY_PROFILE_PREFIX: "shardmarket.cache.profile.", // + uuid
CACHE_KEY_GARDEN_PREFIX: "shardmarket.cache.garden.", // + profile id
CACHE_TTL_BINS_MS: 300_000, // 5 min — AH moves but a full scan is heavy
CACHE_TTL_FIRESALES_MS: 60_000, // Fire Sales are public and can update around start/end times
/* Accessory page preferences. */
BAZAAR_MODE_STORAGE: "shardmarket.bazaarMode", // "instaBuy" | "buyOrder"
PREFER_MAX_STORAGE: "shardmarket.preferMax", // "1" | "0"
ACC_SORT_STORAGE: "shardmarket.accSortKey", // "mp" | "costPerMp" | "price"
ATTR_USABLE_ONLY_STORAGE: "shardmarket.attributes.usableOnly", // "1" | "0"
/* Filter out dead markets where no shards traded in the past week. */
MIN_WEEKLY_VOLUME: 1,
};
/* =========================================================================
* 2. STATE
* Single source of truth, mutated by API/UI code, read by renderers.
* ======================================================================= */
const state = {
/* Raw data */
raw: null, // raw bazaar response
fusionProps: null, // SkyShards properties (per-shard metadata)
fusionRecipes: null, // SkyShards recipe graph
shardsDb: {}, // derived: bazaarId → {name, rarity, ...}
codeToBazaar: {}, // SkyShards code → bazaarId
bazaarToCode: {}, // bazaarId → SkyShards code
/* Computed */
lastUpdated: null, // bazaar lastUpdated (ms)
fetchedAt: null, // when we received bazaar (ms)
rows: [], // enriched shard rows
loading: false,
error: null,
allItemsById: null,
/* Filters & sorting */
search: "",
selectedRarities: new Set(["COMMON", "UNCOMMON", "RARE", "EPIC", "LEGENDARY", "UNKNOWN"]),
selectedSkills: new Set(window.ATTRIBUTE_SKILLS || ["Unknown"]),
sortKey: "profitPerUnit",
sortDir: "desc",
fusionOnly: false,
profitableFusionsOnly: false,
/* Settings */
tax: getNumberFromStorage(CONFIG.TAX_STORAGE, CONFIG.DEFAULT_TAX),
texturePack: localStorage.getItem(CONFIG.TEXTURE_STORAGE) || CONFIG.DEFAULT_TEXTURE,
/* Player profile (optional — enriches calculations) */
player: {
username: localStorage.getItem(CONFIG.USERNAME_STORAGE) || "",
uuid: null,
profiles: [], // [{profile_id, cute_name, selected, game_mode}]
selectedId: localStorage.getItem(CONFIG.PROFILE_ID_STORAGE) || null,
coinPurse: null, // coins available in the selected profile
huntingLevel: null, // current Hunting skill level
huntingXp: null,
extra: {}, // bank, sbLevel, fairySouls, slayerXp, combatLevel
ownedAccessories: null, // Set<string> of owned accessory ids (null = not loaded)
accessoryAnalysis: null, // {currentMP, maxMP, missing, upgrades}
attributeStacks: null, // raw {attrId: shards} from profile
attributeAnalysis: null, // {rows, totalShardsNeeded, totalCost, ...}
sweepAnalysis: null, // profile-aware Sweep ownership/completion map
craftedMinions: null, // parsed profile crafted minions
mutationAnalysis: null, // derived from profile API mutation/greenhouse fields when available
equippedArmor: null,
equippedEquipment: null,
hotbar: null,
inventory: null,
storage: null,
gardenData: null,
gardenLoading: false,
gardenError: null,
profileInventoryLoading: false,
inventoryError: null,
loading: false,
error: null,
},
/* Item catalog (accessories + Sweep optimizer) — loaded once from the resources endpoint. */
accessoryCatalog: null,
sweepCatalog: null,
attributeCatalog: null, // from attribute-desc.json
lowestBins: null, // Map<id, price> | null (not loaded)
cosmeticBins: null, // Map<tokenKey, {price, name}> | null — skins/dyes/runes by name tokens
binsLoading: false,
binsProgress: 0, // 0..1
/* Accessory sourcing preferences. Prefer-max defaults ON (matches the
* "max this accessory out" intent); user can turn it off to target the
* cheaper next tier instead. */
bazaarMode: localStorage.getItem(CONFIG.BAZAAR_MODE_STORAGE) || "instaBuy",
preferMax: localStorage.getItem(CONFIG.PREFER_MAX_STORAGE) !== "0",
accSortKey: localStorage.getItem(CONFIG.ACC_SORT_STORAGE) || "mp",
attrUsableOnly: localStorage.getItem(CONFIG.ATTR_USABLE_ONLY_STORAGE) === "1",
sweepShowCompleted: localStorage.getItem(CONFIG.SWEEP_SHOW_COMPLETED_STORAGE) === "1",
minionManualTiers: {},
minionStartFromLvl1: false,
expandedMinions: {},
/* SkyBlock Mutations planner/tracker. */
mutations: {
search: "",
selectedId: "ALL_IN_ALOE",
quantity: 1,
showUnlockedOnly: false,
sortKey: "profitPerHour",
greenhouseTarget: 25,
manualCycleHours: 4,
},
/* Garden Chips planner. Profile API support for consumed chips is not
* documented, so this page is a live-priced manual target planner. */
gardenChips: {
targetRarity: localStorage.getItem(CONFIG.GARDEN_CHIP_RARITY_STORAGE) || "LEGENDARY",
targetLevel: getNumberFromStorage(CONFIG.GARDEN_CHIP_LEVEL_STORAGE, 20),
sortKey: localStorage.getItem(CONFIG.GARDEN_CHIP_SORT_STORAGE) || "legendaryCost",
progress: getJsonFromStorage(CONFIG.GARDEN_CHIP_PROGRESS_STORAGE, {}),
},
/* Active page: "home" | "shards" | "missing" | "upgrades" | "attributes" | "sweep" | "minions" | "mutations" | "garden-chips" | "farming" | "profile" | "p2w" */
view: "home",
farmingActiveTab: "stats",
farmingSelectedCropId: null,
profileSubTab: "overview",
/* P2W Calculator settings */
p2w: {
selectedItemId: "HYPERION",
selectedItemName: "Hyperion",
customPrice: null,
cookieMethod: "instantSell",
currency: "USD",
exchangeRate: 1.5,
searchQuery: "",
activeTab: "cookies",
fireSales: null,
fireSalesLoading: false,
fireSalesError: null,
fireSalesFetchedAt: null,
bundleFocusId: null, // which bundle the Bundles tab panel/results target (null → best value)
bundleSkinPrices: {} // { [skinName]: coinValueOverride } — user overrides for bundle skin prices
},
};
function getNumberFromStorage(key, fallback) {
try {
const v = parseFloat(localStorage.getItem(key));
return Number.isFinite(v) ? v : fallback;
} catch {
return fallback;
}
}
function getJsonFromStorage(key, fallback) {
try {
const raw = localStorage.getItem(key);
if (!raw) return fallback;
return JSON.parse(raw);
} catch {
return fallback;
}
}
/* =========================================================================
* 3. CACHE — localStorage with TTL
* ======================================================================= */
const cache = {
read(key, ttlMs) {
try {
const raw = localStorage.getItem(key);
if (!raw) return null;
const { ts, data } = JSON.parse(raw);
if (Date.now() - ts > ttlMs) return null;
return { ts, data };
} catch {
return null;
}
},
write(key, data) {
try {
localStorage.setItem(key, JSON.stringify({ ts: Date.now(), data }));
} catch {
/* quota exceeded — silently ignore. Static datasets are ~2 MB; some
* browsers' localStorage caps at 5 MB so this can legitimately fail
* if the user has other state. Not critical — we just refetch. */
}
},
clear(key) {
try { localStorage.removeItem(key); } catch {}
},
};
/* =========================================================================
* 4. CLIENTS
* ======================================================================= */
async function apiFetch(path, { useCache = true, cacheKey = null, cacheTtl = 60_000 } = {}) {
if (useCache && cacheKey) {
const cached = cache.read(cacheKey, cacheTtl);
if (cached) return { data: cached.data, cached: true, cachedAt: cached.ts };
}
const headers = {};
const apiKey = localStorage.getItem(CONFIG.API_KEY_STORAGE);
if (apiKey) headers["API-Key"] = apiKey;
const url = CONFIG.API_BASE + path;
let resp;
try {
resp = await fetch(url, { headers });
} catch (e) {
throw new Error(`Network error: ${e.message}. Check your connection.`);
}
if (!resp.ok) {
let detail = "";
try {
const body = await resp.json();
detail = body?.cause || "";
} catch { /* not JSON */ }
switch (resp.status) {
case 403: throw new Error(`API rejected the request (403). ${detail || "Likely a temporary upstream block — retry in a minute. If it persists, the proxy's API key may be invalid."}`);
case 422: throw new Error(`Malformed request (422). ${detail}`);
case 429: throw new Error(`Rate limited (429). Slow down — wait a minute and retry.`);
case 503: throw new Error(`Hypixel API is warming up (503). Try again in a few seconds.`);
default: throw new Error(`API error ${resp.status}: ${detail || resp.statusText}`);
}
}
const data = await resp.json();
if (data && data.success === false) {
throw new Error(`Hypixel returned an error: ${data.cause || "unknown"}`);
}
if (useCache && cacheKey) cache.write(cacheKey, data);
return { data, cached: false, cachedAt: Date.now() };
}
/* Fetch one of our bundled static JSON files. Same TTL caching as the API. */
async function staticFetch(url, { cacheKey, cacheTtl }) {
const cached = cache.read(cacheKey, cacheTtl);
if (cached) return { data: cached.data, cached: true, cachedAt: cached.ts };
const resp = await fetch(url);
if (!resp.ok) throw new Error(`Failed to load ${url}: ${resp.status}`);
const data = await resp.json();
cache.write(cacheKey, data);
return { data, cached: false, cachedAt: Date.now() };
}
const api = {
fetchBazaar: () => apiFetch(CONFIG.BAZAAR_ENDPOINT, {
cacheKey: CONFIG.CACHE_KEY_BAZAAR,
cacheTtl: CONFIG.CACHE_TTL_BAZAAR_MS,
}),
fetchFusionProps: () => staticFetch(CONFIG.FUSION_PROPS_URL, {
cacheKey: CONFIG.CACHE_KEY_FUSION_PROPS,
cacheTtl: CONFIG.CACHE_TTL_STATIC_MS,
}),
fetchFusionData: () => staticFetch(CONFIG.FUSION_DATA_URL, {
cacheKey: CONFIG.CACHE_KEY_FUSION_DATA,
cacheTtl: CONFIG.CACHE_TTL_STATIC_MS,
}),
/* Resolve a Minecraft username → UUID via ashcon (CORS-friendly Mojang proxy). */
async resolveUsername(username) {
const url = CONFIG.USERNAME_LOOKUP_URL + encodeURIComponent(username);
let resp;
try {
resp = await fetch(url);
} catch (e) {
throw new Error(`Network error resolving username: ${e.message}`);
}
if (resp.status === 404) throw new Error(`User "${username}" not found.`);
if (!resp.ok) throw new Error(`Username lookup failed (${resp.status}).`);
const data = await resp.json();
return { uuid: data.uuid.replace(/-/g, ""), username: data.username };
},
/* Fetch SkyBlock profiles for a UUID. Requires an API key. */
fetchProfiles(uuid) {
return apiFetch(`${CONFIG.PROFILES_ENDPOINT}?uuid=${uuid}`, {
cacheKey: CONFIG.CACHE_KEY_PROFILE_PREFIX + uuid,
cacheTtl: CONFIG.CACHE_TTL_PROFILE_MS,
});
},
/* Fetch standalone Garden data for a SkyBlock profile UUID. */
fetchGarden(profileId) {
return apiFetch(`${CONFIG.GARDEN_ENDPOINT}?profile=${profileId}`, {
cacheKey: CONFIG.CACHE_KEY_GARDEN_PREFIX + profileId,
cacheTtl: CONFIG.CACHE_TTL_PROFILE_MS,
});
},
/* Fetch the full SkyBlock item catalog (public, no key). Cached 1 day. */
fetchItems() {
return apiFetch(CONFIG.ITEMS_ENDPOINT, {
cacheKey: CONFIG.CACHE_KEY_ITEMS,
cacheTtl: CONFIG.CACHE_TTL_STATIC_MS,
});
},
/* Bundled attribute metadata (attribute-id → rarity/title/desc). */
fetchAttrDesc: () => staticFetch(CONFIG.ATTR_DESC_URL, {
cacheKey: CONFIG.CACHE_KEY_ATTR_DESC,
cacheTtl: CONFIG.CACHE_TTL_STATIC_MS,
}),
};
/* =========================================================================
* 4b. PLAYER PROFILE
*
* Skill XP → level conversion uses the standard SkyBlock skill curve from
* the wiki. We only need Hunting for shard syphoning eligibility, but the
* table is included so we can extend to other skills cheaply later.
*
* Cumulative XP required to reach each level (index = level).
* Source: https://wiki.hypixel.net/Skills (regular skills, 0 → 60)
* ======================================================================= */
const SKILL_XP_TABLE = [
0, 50, 175, 375, 675, 1175, 1925, 2925, 4425, 6425, 9925, 14925, 22425, 32425,
47425, 67425, 97425, 147425, 222425, 322425, 522425, 822425, 1222425, 1722425,
2322425, 3022425, 3822425, 4722425, 5722425, 6822425, 8022425, 9322425,
10722425, 12222425, 13822425, 15522425, 17322425, 19222425, 21222425, 23322425,
25522425, 27822425, 30222425, 32722425, 35322425, 38072425, 40972425, 44072425,
47472425, 51172425, 55172425, 59472425, 64072425, 68972425, 74172425, 79672425,
85472425, 91572425, 97972425, 104672425, 111672425,
];
function xpToLevel(xp) {
if (xp == null || !Number.isFinite(xp) || xp <= 0) return 0;
for (let i = SKILL_XP_TABLE.length - 1; i >= 0; i--) {
if (xp >= SKILL_XP_TABLE[i]) return i;
}
return 0;
}
/* Pull out the bits of a SkyBlock profile we care about for shard work. */
function extractProfileStats(profile, uuid) {
const member = profile?.members?.[uuid];
if (!member) return { coinPurse: null, huntingLevel: null, huntingXp: null, attributeStacks: null, extra: {} };
const coinPurse = member.currencies?.coin_purse ?? null;
const exp = member.player_data?.experience || {};
const huntingXp = exp.SKILL_HUNTING ?? null;
const huntingLevel = huntingXp != null ? xpToLevel(huntingXp) : null;
const attributeStacks = member.attributes?.stacks ?? null;
/* Extra account stats for the player panel. */
const bank = profile?.banking?.balance ?? null;
const sbXp = member.leveling?.experience ?? null;
const sbLevel = sbXp != null ? Math.floor(sbXp / 100) : null; // SB level = XP/100
const fairySouls = member.fairy_soul?.total_collected ?? null;
/* Total slayer XP across all bosses. */
let slayerXp = 0;
const bosses = member.slayer?.slayer_bosses || {};
for (const b of Object.values(bosses)) slayerXp += b?.xp || 0;
/* Combat skill level (handy alongside Hunting for shard grinding). */
const combatXp = exp.SKILL_COMBAT ?? null;
const combatLevel = combatXp != null ? xpToLevel(combatXp) : null;
return {
coinPurse, huntingLevel, huntingXp, attributeStacks,
extra: { bank, sbLevel, fairySouls, slayerXp, combatLevel },
};
}
/* Load (and cache) the player's profiles. Errors set state.player.error. */
async function loadPlayerProfiles(username) {
state.player.loading = true;
state.player.error = null;
renderPlayerPanel();
try {
// API key check is bypassed since the secure Cloudflare proxy handles key injection!
const { uuid, username: canonical } = await api.resolveUsername(username);
state.player.uuid = uuid;
state.player.username = canonical;
localStorage.setItem(CONFIG.USERNAME_STORAGE, canonical);
const { data } = await api.fetchProfiles(uuid);
const profiles = (data.profiles || []).map((p) => ({
profile_id: p.profile_id,
cute_name: p.cute_name,
selected: !!p.selected,
game_mode: p.game_mode || null,
_raw: p,
}));
if (!profiles.length) throw new Error(`${canonical} has no SkyBlock profiles.`);
state.player.profiles = profiles;
/* Pick the previously-saved profile if still present, else the game's "selected" one. */
const savedId = localStorage.getItem(CONFIG.PROFILE_ID_STORAGE);
const pick =
profiles.find((p) => p.profile_id === savedId)
|| profiles.find((p) => p.selected)
|| profiles[0];
selectProfile(pick.profile_id);
} catch (e) {
state.player.error = e.message;
state.player.profiles = [];
state.player.selectedId = null;
state.player.coinPurse = state.player.huntingLevel = state.player.huntingXp = null;
console.error("[Hypixie] player load failed:", e);
} finally {
state.player.loading = false;
renderPlayerPanel();
rebuildRows(); // re-evaluate Hunting-gated fusion eligibility
renderTable();
renderBestFusionsPanel();
renderActiveView();
}
}
/* Extract all owned accessory ids from a profile member by decoding the
* talisman bag (and inventory / ender chest as a fallback for accessories
* carried outside the bag). Returns a Map<id, {recombobulated}>. */
async function extractOwnedAccessories(member, catalog) {
const owned = new Map();
if (!member?.inventory) return owned;
const slices = [
member.inventory.bag_contents?.talisman_bag,
member.inventory.inv_contents,
member.inventory.ender_chest_contents,
];
for (const slice of slices) {
if (!slice?.data) continue;
try {
const items = await decodeInventory(slice.data);
for (const it of items) {
/* Only keep ids the catalog knows. Merge recomb status — if any copy
* is recombobulated, treat the accessory as recombobulated. */
if (catalog.byId[it.skyblockId]) {
const prev = owned.get(it.skyblockId);
owned.set(it.skyblockId, {
recombobulated: (prev?.recombobulated || it.recombobulated) === true,
});
}
}
} catch (e) {
console.warn("[Hypixie] inventory decode failed for a slice:", e.message);
}
}
return owned;
}
function sweepInventorySlices(member) {
const inv = member?.inventory || {};
const bag = inv.bag_contents || {};
return [
inv.inv_contents,
inv.ender_chest_contents,
inv.equipment_contents,
inv.inv_armor,
inv.wardrobe_contents,
inv.personal_vault_contents,
...Object.values(inv.backpack_contents || {}),
...Object.values(bag || {}),
].filter((slice) => slice?.data);
}
async function extractSweepProfileItems(member) {
const items = [];
const ids = new Set();
for (const slice of sweepInventorySlices(member)) {
try {
for (const it of await decodeInventory(slice.data)) {
items.push(it);
ids.add(it.skyblockId);
}
} catch (e) {
console.warn("[Hypixie] Sweep inventory decode failed for a slice:", e.message);
}
}
return { items, ids };
}
const SWEEP_ATTR_BY_SOURCE_ID = {
"crow-attribute": "fig_sharpening",
"heron-attribute": "mangrove_sharpening",
"phanpyre-attribute": "nocturnal_animal",
"bambuleaf-attribute": "strong_arms",
"mochibear-attribute": "strong_legs",
"tadgang-attribute": "unity_is_strength",
};
/* Shards needed to max (level X) the attribute granted by a shard, from the
* shard's rarity (wiki: Common 96, Uncommon 64, Rare 48, Epic 32,
* Legendary 24). Falls back to the Common total when the shard is unknown. */
function attributeMaxShardsForShardId(shardId) {
const code = state.bazaarToCode?.[shardId];
const rarity = code ? (RARITY_FROM_CODE[code[0]] || "UNKNOWN") : "UNKNOWN";
return (window.ATTR_MAX_SHARDS_BY_RARITY || {})[rarity] || 96;
}
const SWEEP_ARMOR_IDS = new Set(["CANOPY_HELMET", "CANOPY_CHESTPLATE", "CANOPY_LEGGINGS", "CANOPY_BOOTS", "FIG_HELMET", "FIG_CHESTPLATE", "FIG_LEGGINGS", "FIG_BOOTS"]);
const SWEEP_EQUIPMENT_IDS = new Set(["DAVIDS_CLOAK", "MANGROVE_GRIPPERS", "MANGROVE_LOCKET", "MANGROVE_VINE"]);
const SWEEP_AXE_ID_RE = /(AXE|TREECAPITATOR)/i;
/* Mutually-exclusive gear progressions for profile-aware Sweep suggestions.
* If the player already owns a higher completed tier in the same slot, lower
* alternatives should not be recommended as separate next purchases. */
const SWEEP_GEAR_PROGRESSIONS = [
["canopy-armor", "fig-armor"],
["spruce-axe", "seriously-damaged-axe", "decent-axe", "treecapitator", "fig-hew", "figstone-splitter"],
];
function hasSweepBooster(it) {
return (it?.rawTag?.ExtraAttributes?.boosters || []).includes("sweep");
}
function firstImpressionLevel(it) {
return Number(it?.rawTag?.ExtraAttributes?.enchantments?.ultimate_first_impression || 0);
}
function countWithSweepBooster(items, predicate) {
return items.filter((it) => predicate(it.skyblockId) && hasSweepBooster(it)).length;
}
function countUniqueWithSweepBooster(items, predicate) {
const ids = new Set();
for (const it of items) if (predicate(it.skyblockId) && hasSweepBooster(it)) ids.add(it.skyblockId);
return ids.size;
}
function countOwnedUnique(ids, wanted) {
return wanted.filter((id) => ids.has(id)).length;
}
function sweepSourceFullyOwned(src, ids) {
if (!src?.itemIds?.length) return false;
if (src.costKind === "auction-bundle") return countOwnedUnique(ids, src.itemIds) >= src.itemIds.length;
if (src.costKind === "auction") return src.itemIds.some((id) => ids.has(id));
return false;
}
function higherOwnedSweepGear(src, ctx) {
const chain = SWEEP_GEAR_PROGRESSIONS.find((ids) => ids.includes(src.id));
if (!chain) return null;
const idx = chain.indexOf(src.id);
for (let i = chain.length - 1; i > idx; i--) {
const higher = ctx.sourcesById?.[chain[i]] || (window.SWEEP_SOURCES || []).find((s) => s.id === chain[i]);
if (higher && sweepSourceFullyOwned(higher, ctx.ids)) return higher;
}
return null;
}
function sweepDone(done, reason, current = null, max = null) {
return { completed: !!done, reason, current, max };
}
function sweepPartial(reason, current = null, max = null) {
return { completed: false, partial: true, reason, current, max };
}
function sweepSourceCompletion(src, ctx) {
const { ids, items, member } = ctx;
const foraging = member?.foraging || {};
const treeGifts = foraging.tree_gifts || {};
const personalBests = foraging.starlyn?.personal_bests || {};
const taskProgress = foraging.hina?.tasks?.task_progress || {};
const nodes = member?.skill_tree?.nodes?.foraging || {};
const stacks = member?.attributes?.stacks || {};
const higherGear = higherOwnedSweepGear(src, ctx);
if (higherGear) {
return sweepDone(true, `Covered by higher-tier ${higherGear.name} found in this profile.`);
}
if (src.id === "jade-dragon-pet") {
const has = (member?.pets_data?.pets || []).some((p) => p.type === "JADE_DRAGON");
return sweepDone(has, has ? "Jade Dragon pet found in profile pets." : "Not found in profile pets.");
}
if (src.id === "monkey-pet") {
const has = (member?.pets_data?.pets || []).some((p) => p.type === "MONKEY");
return sweepDone(has, has ? "Monkey pet found in profile pets." : "Not found in profile pets.");
}
if (src.costKind === "auction-bundle" && src.itemIds?.length) {
const have = countOwnedUnique(ids, src.itemIds);
if (have >= src.itemIds.length) return sweepDone(true, `All ${src.itemIds.length}/${src.itemIds.length} pieces found.`, have, src.itemIds.length);
if (have > 0) return sweepPartial(`${have}/${src.itemIds.length} pieces found; still missing pieces.`, have, src.itemIds.length);
return sweepDone(false, "No pieces found in decoded inventory.", 0, src.itemIds.length);
}
if (src.costKind === "auction" && src.itemIds?.length) {
const has = src.itemIds.some((id) => ids.has(id));
return sweepDone(has, has ? "Item found in decoded inventory." : "Item not found in decoded inventory.");
}
if (src.id === "first-impression-v") {
const max = Math.max(0, ...items.map(firstImpressionLevel));
return max >= 5 ? sweepDone(true, "First Impression V found on a decoded item.", max, 5) : (max > 0 ? sweepPartial(`First Impression ${max} found; level V still recommended.`, max, 5) : sweepDone(false, "First Impression V not found on decoded items.", 0, 5));
}
if (src.id === "sweep-booster-axe") {
const boosted = countWithSweepBooster(items, (id) => SWEEP_AXE_ID_RE.test(id));
return boosted > 0 ? sweepDone(true, "Sweep booster already found on an axe.", boosted, 1) : sweepDone(false, "No Sweep-boosted axe found.", 0, 1);
}
if (src.id === "sweep-booster-armor") {
const boosted = countUniqueWithSweepBooster(items, (id) => SWEEP_ARMOR_IDS.has(id));
if (boosted >= 4) return sweepDone(true, "At least 4 armor pieces already have Sweep booster.", boosted, 4);
if (boosted > 0) return sweepPartial(`${boosted}/4 armor Sweep boosters found.`, boosted, 4);
return sweepDone(false, "No Sweep-boosted armor pieces found.", 0, 4);
}
if (src.id === "sweep-booster-equipment") {
const boosted = countUniqueWithSweepBooster(items, (id) => SWEEP_EQUIPMENT_IDS.has(id));
if (boosted >= 4) return sweepDone(true, "All 4 equipment slots already have Sweep booster.", boosted, 4);
if (boosted > 0) return sweepPartial(`${boosted}/4 equipment Sweep boosters found.`, boosted, 4);
return sweepDone(false, "No Sweep-boosted equipment found.", 0, 4);
}
const attrId = SWEEP_ATTR_BY_SOURCE_ID[src.id];
if (attrId) {
const current = Number(stacks[attrId] || 0);
const max = attributeMaxShardsForShardId(src.shardId);
if (current >= max) return sweepDone(true, `${attrId.replaceAll("_", " ")} is already level X/maxed.`, current, max);
if (current > 0) return sweepPartial(`${current}/${max} shards syphoned into ${attrId.replaceAll("_", " ")}.`, current, max);
return sweepDone(false, `${attrId.replaceAll("_", " ")} not started.`, 0, max);
}
if (src.id === "fig-tree-gifts") {
const current = Number(treeGifts.FIG || taskProgress.FIG_GIFTS || 0);
return current >= 1000 ? sweepDone(true, "Fig Tree Gift milestones appear complete.", current, 1000) : (current > 0 ? sweepPartial(`${fmtInt(current)} Fig gifts tracked; more milestones may remain.`, current, 1000) : sweepDone(false, "No Fig Tree Gift progress found.", 0, 1000));
}
if (src.id === "mangrove-tree-gifts") {
const current = Number(treeGifts.MANGROVE || taskProgress.MANGROVE_GIFTS || 0);
return current >= 1000 ? sweepDone(true, "Mangrove Tree Gift milestones appear complete.", current, 1000) : (current > 0 ? sweepPartial(`${fmtInt(current)} Mangrove gifts tracked; more milestones may remain.`, current, 1000) : sweepDone(false, "No Mangrove Tree Gift progress found.", 0, 1000));
}
if (src.id === "fig-personal-best") {
const current = Number(personalBests.FIG_LOG || 0);
return current >= 100000 ? sweepDone(true, "Fig personal best is at the 100k cap.", current, 100000) : (current > 0 ? sweepPartial(`${fmtInt(current)}/100k Fig personal best.`, current, 100000) : sweepDone(false, "No Fig personal best found.", 0, 100000));
}
if (src.id === "mangrove-personal-best") {
const current = Number(personalBests.MANGROVE_LOG || 0);
return current >= 100000 ? sweepDone(true, "Mangrove personal best is at the 100k cap.", current, 100000) : (current > 0 ? sweepPartial(`${fmtInt(current)}/100k Mangrove personal best.`, current, 100000) : sweepDone(false, "No Mangrove personal best found.", 0, 100000));
}
if (src.id === "hotf-sweep") {
const current = Number(nodes.sweep || 0);
return current >= 50 ? sweepDone(true, "Heart of the Forest Sweep perk is maxed.", current, 50) : (current > 0 ? sweepPartial(`HOTF Sweep perk is ${current}/50.`, current, 50) : sweepDone(false, "HOTF Sweep perk not found.", 0, 50));
}
return null;
}
async function loadSweepAnalysis(rawProfile) {
try {
const member = rawProfile?.members?.[state.player.uuid];
if (!member || !Array.isArray(window.SWEEP_SOURCES)) {
state.player.sweepAnalysis = null;
return;
}
const { items, ids } = await extractSweepProfileItems(member);
const sourcesById = Object.fromEntries(window.SWEEP_SOURCES.map((src) => [src.id, src]));
const bySource = {};
for (const src of window.SWEEP_SOURCES) {
const completion = sweepSourceCompletion(src, { member, items, ids, sourcesById });
if (completion) bySource[src.id] = completion;
}
state.player.sweepAnalysis = { bySource, itemCount: items.length };
} catch (e) {
console.error("[Hypixie] Sweep analysis failed:", e);
state.player.sweepAnalysis = { bySource: {}, itemCount: 0, error: e.message };
} finally {
if (state.view === "sweep" || state.view === "profile") renderActiveView();
}
}
function selectProfile(profileId) {
const prof = state.player.profiles.find((p) => p.profile_id === profileId);
if (!prof) return;
state.player.selectedId = profileId;
localStorage.setItem(CONFIG.PROFILE_ID_STORAGE, profileId);
const stats = extractProfileStats(prof._raw, state.player.uuid);
state.player.coinPurse = stats.coinPurse;
state.player.huntingLevel = stats.huntingLevel;
state.player.huntingXp = stats.huntingXp;
state.player.attributeStacks = stats.attributeStacks;
state.player.extra = stats.extra || {};
const craftedList = prof._raw?.members?.[state.player.uuid]?.player_data?.crafted_generators || [];
state.player.craftedMinions = typeof parseCraftedMinions !== "undefined" ? parseCraftedMinions(craftedList) : {};
/* Accessory analysis runs async (NBT decode). Reset, then fill in. */
state.player.ownedAccessories = null;
state.player.accessoryAnalysis = null;
state.player.attributeAnalysis = null;
state.player.sweepAnalysis = null;
state.player.mutationAnalysis = analyseProfileMutations(prof._raw, state.player.uuid);
state.player.equippedArmor = null;
state.player.equippedEquipment = null;
state.player.hotbar = null;
state.player.inventory = null;
state.player.storage = null;
state.player.gardenData = null;
state.player.gardenError = null;
state.player.gardenLoading = false;
loadAccessoryAnalysis(prof._raw);
loadAttributeAnalysis();
loadSweepAnalysis(prof._raw);
loadProfileInventory(prof._raw);
loadGardenData(profileId);
rebuildRows();
if (state.view === "mutations") renderActiveView();
}
/* Decode inventories + analyse accessories for the selected profile. */
async function loadAccessoryAnalysis(rawProfile) {
try {
if (!state.accessoryCatalog) {
const { data } = await api.fetchItems();
state.accessoryCatalog = buildAccessoryCatalog(data);
}
const member = rawProfile?.members?.[state.player.uuid];
const owned = await extractOwnedAccessories(member, state.accessoryCatalog);
state.player.ownedAccessories = owned;
state.player.accessoryAnalysis = analyseAccessories(state.accessoryCatalog, owned, { preferMax: state.preferMax });
} catch (e) {
console.error("[Hypixie] accessory analysis failed:", e);
state.player.ownedAccessories = new Set();
state.player.accessoryAnalysis = { currentMP: 0, maxMP: 0, missing: [], upgrades: [], error: e.message };
} finally {
renderPlayerPanel();
if (state.view === "missing" || state.view === "upgrades" || state.view === "profile") renderActiveView();
}
}
/* Fetch standalone Garden API data for richer visitor tracking. */
async function loadGardenData(profileId) {
const requestedProfileId = profileId || state.player.selectedId;
if (!requestedProfileId) return;
state.player.gardenLoading = true;
state.player.gardenError = null;
try {
const { data } = await api.fetchGarden(requestedProfileId);
if (state.player.selectedId !== requestedProfileId) return;
state.player.gardenData = data?.garden || data;
state.player.mutationAnalysis = mergeGardenIntoMutationAnalysis(state.player.mutationAnalysis, state.player.gardenData);
} catch (e) {
if (state.player.selectedId !== requestedProfileId) return;
state.player.gardenData = null;
state.player.gardenError = e.message || String(e);
console.error("[Hypixie] garden load failed:", e);
} finally {
if (state.player.selectedId === requestedProfileId) {
state.player.gardenLoading = false;
if (state.view === "farming" || state.view === "mutations") renderActiveView();
}
}
}
/* Decode armor, equipment, inventory, and storage for the Profile Viewer. */
async function loadProfileInventory(rawProfile) {
state.player.profileInventoryLoading = true;
state.player.equippedArmor = null;
state.player.equippedEquipment = null;
state.player.hotbar = null;
state.player.inventory = null;
state.player.storage = null;
state.player.inventoryError = null;
try {
const member = rawProfile?.members?.[state.player.uuid];
if (!member?.inventory) {
state.player.inventoryError = "Inventory API is disabled in Hypixel settings.";
return;
}
// Decode armor
if (member.inventory.inv_armor?.data) {
const armor = await decodeInventory(member.inventory.inv_armor.data);
// In Minecraft: slot 0 = boots, slot 1 = leggings, slot 2 = chestplate, slot 3 = helmet.
// We keep slot indices but we can also store the array.
state.player.equippedArmor = armor;
}
// Decode equipment
if (member.inventory.equipment_contents?.data) {
state.player.equippedEquipment = await decodeInventory(member.inventory.equipment_contents.data);
}
// Decode full inventory. Slots 0-8 are the hotbar, 9-35 are the main inventory.
if (member.inventory.inv_contents?.data) {
const inv = await decodeInventory(member.inventory.inv_contents.data);
state.player.inventory = inv;
state.player.hotbar = inv.filter((it) => it.slotIndex < 9);
}
const backpackEntries = Object.entries(member.inventory.backpack_contents || {});
const backpacks = [];
for (const [key, slice] of backpackEntries) {
if (!slice?.data) continue;
backpacks.push({
id: key,
label: `Backpack ${backpacks.length + 1}`,
items: await decodeInventory(slice.data),
});
}
const personalVaultSlice = member.inventory.personal_vault_contents || member.inventory.personal_vault;
state.player.storage = {
enderChest: member.inventory.ender_chest_contents?.data
? await decodeInventory(member.inventory.ender_chest_contents.data)
: [],
personalVault: personalVaultSlice?.data
? await decodeInventory(personalVaultSlice.data)
: [],
backpacks,
};
} catch (e) {
console.error("[Hypixie] profile inventory decode failed:", e);
state.player.inventoryError = "Failed to decode inventory NBT data.";
} finally {
state.player.profileInventoryLoading = false;
if (state.view === "profile") renderActiveView();
}
}
/* Build the attribute-maxing analysis for the selected profile. */
async function loadAttributeAnalysis() {
try {
if (!state.attributeCatalog) {
const { data } = await api.fetchAttrDesc();
state.attributeCatalog = buildAttributeCatalog(data);
}
/* Missing attributes do not appear in profile attributes.stacks at all.
* Treat a missing stacks object as an empty map so the report can still
* show the full SkyShards catalog as 0/max instead of rendering only the
* few attributes the user has already syphoned. */
const stacks = state.player.attributeStacks || {};
/* Price each attribute's source shard via the live bazaar.
* The shard granting attribute `code` is fusion-props[code].name → SHARD_<NAME>.
* Respects the user's bazaar-price preference (insta-buy vs buy-order). */
const shardPriceFor = (code) => {
const propName = state.fusionProps?.[code]?.name;
if (!propName) return null;
const bazaarId = state.codeToBazaar?.[code]
|| ("SHARD_" + propName.toUpperCase().replace(/[^A-Z0-9]+/g, "_").replace(/^_+|_+$/g, ""));
const qs = state.raw?.products?.[bazaarId]?.quick_status;
if (!qs) return null;
return state.bazaarMode === "buyOrder"
? (qs.sellPrice || qs.buyPrice || null) // place a buy order (cheaper)
: (qs.buyPrice || qs.sellPrice || null); // insta-buy
};
state.player.attributeAnalysis = analyseAttributes(state.attributeCatalog, stacks, shardPriceFor, {
onlyUsable: false,
requirementForCode: huntingRequirementForCode,
canUseCode: (code, requiredLevel) => playerCanUseFusion(requiredLevel),
});
} catch (e) {
console.error("[Hypixie] attribute analysis failed:", e);
state.player.attributeAnalysis = { rows: [], totalShardsNeeded: 0, totalCost: 0, maxedCount: 0, totalCount: 0, error: e.message };
} finally {
renderPlayerPanel();
if (state.view === "attributes") renderActiveView();
}
}
function clearPlayer() {
state.player = {
username: "", uuid: null, profiles: [], selectedId: null,
coinPurse: null, huntingLevel: null, huntingXp: null, extra: {},
ownedAccessories: null, accessoryAnalysis: null,
attributeStacks: null, attributeAnalysis: null, sweepAnalysis: null,
craftedMinions: null, mutationAnalysis: null,
equippedArmor: null, equippedEquipment: null, hotbar: null,
inventory: null, storage: null,
gardenData: null, gardenLoading: false, gardenError: null,
profileInventoryLoading: false, inventoryError: null,
loading: false, error: null,
};
localStorage.removeItem(CONFIG.USERNAME_STORAGE);
localStorage.removeItem(CONFIG.PROFILE_ID_STORAGE);
rebuildRows();
renderPlayerPanel();
renderTable();
renderBestFusionsPanel();
if (state.view !== "shards") renderActiveView();
}
/* =========================================================================
* 5. PROFITABILITY MATH — bazaar flipping
*
* Terminology (matches the in-game Bazaar):
* buyPrice — what you PAY to insta-buy (lowest sell-offer band)
* sellPrice — what you RECEIVE from insta-sell (highest buy-order band)
*
* Realistic flip uses ORDERS rather than instant transactions:
* 1) BUY ORDER at ≈ sellPrice + ε → fills at ≈ sellPrice
* 2) SELL OFFER at ≈ buyPrice − ε → receives buyPrice × (1 − tax)
* (sell-offer payouts are taxed; buy-order spending is not)
*
* profitPerUnit = buyPrice × (1 − tax) − sellPrice
* marginPercent = profitPerUnit / sellPrice × 100
* ======================================================================= */
function computeMetrics(qs, tax) {
const buyPrice = qs?.buyPrice ?? 0;
const sellPrice = qs?.sellPrice ?? 0;
const spread = buyPrice - sellPrice;
const profitPerUnit = buyPrice * (1 - tax) - sellPrice;
const marginPercent = sellPrice > 0 ? (profitPerUnit / sellPrice) * 100 : 0;
const sellWeek = qs?.sellMovingWeek ?? 0;
const buyWeek = qs?.buyMovingWeek ?? 0;
const weeklyVolume = sellWeek + buyWeek;
return {
buyPrice,
sellPrice,
spread,
profitPerUnit,
marginPercent,
weeklyVolume,
sellWeek,
buyWeek,
sellOrders: qs?.sellOrders ?? 0,
buyOrders: qs?.buyOrders ?? 0,
};
}
/* Project profit over realistic weekly throughput.
* Capped at half the weaker market side — you can't move more units than
* the market absorbs without driving the price. */
function projectedWeeklyProfit(m) {
if (!Number.isFinite(m?.profitPerUnit) || !Number.isFinite(m?.sellWeek) || !Number.isFinite(m?.buyWeek)) return null;
const throughput = Math.min(m.sellWeek, m.buyWeek) * 0.5;
return m.profitPerUnit * throughput;
}