-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontent.js
More file actions
1121 lines (1014 loc) · 34.9 KB
/
Copy pathcontent.js
File metadata and controls
1121 lines (1014 loc) · 34.9 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
/**
* Isolated world: DOM scrape + FOMO API sniff (inject.js).
* Splits "you" vs "this profile" using GET /v2/users/{id} vs /balances on /profile/… pages.
*
* Uses chrome.storage.local (not session): session storage is blocked from content scripts
* unless setAccessLevel is used; local avoids "Access to storage is not allowed from this context."
*/
const RE_SOLANA = /\b[1-9A-HJ-NP-Za-km-z]{43,44}\b/g;
const RE_EVM = /\b0x[a-fA-F0-9]{40}\b/g;
const MSG_SOURCE = "fomo-deploy-sniffer";
/** OMO native mint — thesis deploy comments are only honored on this token page. */
const THESIS_WATCH_MINT =
"9xpmicYqcLM8aRNeTHpBHQZ6qbqx31X397nR9LKqaomo";
/** All API walk addresses */
const apiSeenSol = new Set();
const apiSeenEvm = new Set();
const apiListSol = [];
const apiListEvm = [];
/** Profile page: balances response wallets */
const profSeenSol = new Set();
const profSeenEvm = new Set();
const profListSol = [];
const profListEvm = [];
/** Logged-in viewer: GET /v2/users/{id} where id ≠ profile balances user */
const youSeenSol = new Set();
const youSeenEvm = new Set();
const youListSol = [];
const youListEvm = [];
/** Profile owner canonical from GET /v2/users/{profileUserId} */
const profileCanonSeenSol = new Set();
const profileCanonSeenEvm = new Set();
const profileCanonListSol = [];
const profileCanonListEvm = [];
/** Structured balances rows keyed by path UUID — fixes profile vs viewer when multiple /balances fire */
/** @type {Map<string, { sol: string[]; evm: string[] }>} */
const balancesByUserId = new Map();
/** @type {string | null} */
let lastProfileSlugPublished = null;
/** Last /balances path UUID seen (legacy fallback only; may be viewer after header refresh) */
let profileBuddyId = null;
/** @type {{ id: string; address: string | null; evmAddress: string | null; profileHandle?: string | null } | null} */
let pendingUserDetail = null;
/** FOMO @handle for the logged-in viewer (from user-detail API), for deploy metadata. */
let loggedInFomoHandle = "";
/** Load sticky handle from storage before processing user-detail (apply runs before publish). */
async function rehydrateLoggedInFomoHandleIfNeeded() {
if (loggedInFomoHandle) return;
try {
const r = await chrome.storage.local.get(["fomoLoggedIn", "lastYouFomoHandle"]);
if (r.fomoLoggedIn !== false) {
const h = String(r.lastYouFomoHandle || "").trim();
if (h) loggedInFomoHandle = h;
}
} catch {
/* ignore */
}
}
/** Last-known Sol/EVM per profile slug — survives FOMO 304/502/CORS gaps on UUID fetches. */
const PROFILE_CANON_CACHE_KEY = "omoProfileCanonV1";
function normalizeProfileSlugForCache(slug) {
return String(slug || "").trim().replace(/^@+/, "").toLowerCase();
}
async function hydrateProfileCanonFromStorage(slugNorm) {
if (!slugNorm) return;
try {
const r = await chrome.storage.local.get([PROFILE_CANON_CACHE_KEY]);
const map =
r[PROFILE_CANON_CACHE_KEY] && typeof r[PROFILE_CANON_CACHE_KEY] === "object"
? r[PROFILE_CANON_CACHE_KEY]
: {};
const row = map[slugNorm];
if (!row || typeof row !== "object") return;
const sol = typeof row.sol === "string" ? row.sol.trim() : "";
const evm = typeof row.evm === "string" ? row.evm.trim() : "";
if (sol && /^[1-9A-HJ-NP-Za-km-z]{43,44}$/.test(sol) && !profileCanonSeenSol.has(sol)) {
profileCanonSeenSol.add(sol);
profileCanonListSol.push(sol);
}
if (evm && /^0x[a-fA-F0-9]{40}$/i.test(evm) && !profileCanonSeenEvm.has(evm)) {
profileCanonSeenEvm.add(evm);
profileCanonListEvm.push(evm);
}
} catch {
/* ignore */
}
}
function persistProfileCanonCache(slugNorm, solAddr, evmAddr) {
if (!slugNorm) return;
const sol = typeof solAddr === "string" ? solAddr.trim() : "";
const evm = typeof evmAddr === "string" ? evmAddr.trim() : "";
if (!sol && !evm) return;
void chrome.storage.local
.get([PROFILE_CANON_CACHE_KEY])
.then((r) => {
const map =
r[PROFILE_CANON_CACHE_KEY] && typeof r[PROFILE_CANON_CACHE_KEY] === "object"
? { ...r[PROFILE_CANON_CACHE_KEY] }
: {};
const prev = map[slugNorm] && typeof map[slugNorm] === "object" ? map[slugNorm] : {};
map[slugNorm] = {
sol: sol || prev.sol || "",
evm: evm || prev.evm || "",
at: Date.now(),
};
return chrome.storage.local.set({ [PROFILE_CANON_CACHE_KEY]: map });
})
.catch(() => {});
}
function normalizeHandleForDeployMetrics(h) {
return String(h || "")
.trim()
.replace(/^@+/, "")
.toLowerCase();
}
/**
* Store deploy-gate stats only for the logged-in user's row, after `loggedInFomoHandle` is applied.
*/
async function maybePersistDeployMetrics(d) {
if (!d.deployMetrics || typeof d.deployMetrics !== "object") return;
let ownerRaw = d.deployMetricsOwnerHandle;
if (
(!ownerRaw || !String(ownerRaw).trim()) &&
d.userDetail &&
typeof d.userDetail.profileHandle === "string"
) {
ownerRaw = d.userDetail.profileHandle;
}
const owner = normalizeHandleForDeployMetrics(ownerRaw);
let you = normalizeHandleForDeployMetrics(loggedInFomoHandle);
if (!you) {
try {
const r = await chrome.storage.local.get(["lastYouFomoHandle"]);
you = normalizeHandleForDeployMetrics(r.lastYouFomoHandle);
} catch {
/* ignore */
}
}
if (!owner || !you || owner !== you) return;
let merged = { ...d.deployMetrics };
try {
const prev = await chrome.storage.local.get(["lastYouDeployMetrics"]);
const p = prev.lastYouDeployMetrics;
if (p && typeof p === "object") {
merged = { ...p, ...merged };
}
} catch {
/* ignore */
}
await chrome.storage.local.set({
lastYouDeployMetrics: merged,
lastYouDeployMetricsAt: Date.now(),
});
}
function requestMainWorldSniffer() {
chrome.runtime.sendMessage({ type: "INSTALL_MAIN_SNIFFER" }, () => {
void chrome.runtime.lastError;
});
}
requestMainWorldSniffer();
function currentProfileSlug() {
const m = location.pathname.match(/^\/profile\/([^/]+)/);
return m ? decodeURIComponent(m[1]) : null;
}
/** Same relay as popup / background — indexed deploys for profile overlay. */
const RELAY_ORIGIN = "https://fomofam-production.up.railway.app";
let omoDeployPanelTimer = 0;
/** ms — skip refetch if same @handle and panel already rendered OK */
const OMO_DEPLOY_PANEL_CACHE_MS = 90_000;
function scheduleOmoDeployProfilePanel() {
clearTimeout(omoDeployPanelTimer);
omoDeployPanelTimer = setTimeout(() => void renderOmoDeployProfilePanel(), 600);
}
/**
* Corner panel: only appears after a successful deploy list fetch with ≥1 token (no on-page “Loading…”).
* Uses the same relay as the popup; hide/remove when empty or error.
*/
async function renderOmoDeployProfilePanel() {
const rootId = "omo-deployed-tokens-root";
const slug = currentProfileSlug();
if (!slug) {
document.getElementById(rootId)?.remove();
return;
}
const handle = decodeURIComponent(slug).replace(/^@+/, "").trim().toLowerCase();
if (!handle) {
document.getElementById(rootId)?.remove();
return;
}
const existing = document.getElementById(rootId);
const lastAt = Number(existing?.dataset.omoFetchedAt || 0);
if (
existing &&
existing.dataset.omoHandle === handle &&
Date.now() - lastAt < OMO_DEPLOY_PANEL_CACHE_MS
) {
return;
}
const base = RELAY_ORIGIN.replace(/\/$/, "");
const controller = new AbortController();
const tid = setTimeout(() => controller.abort(), 12_000);
let tokens = [];
try {
const res = await fetch(
`${base}/api/deploy/tokens?fomoUsername=${encodeURIComponent(handle)}&limit=25`,
{ cache: "no-store", signal: controller.signal }
);
clearTimeout(tid);
const j = await res.json().catch(() => ({}));
tokens = Array.isArray(j.tokens) ? j.tokens : [];
} catch {
clearTimeout(tid);
document.getElementById(rootId)?.remove();
return;
}
if (!tokens.length) {
document.getElementById(rootId)?.remove();
return;
}
let root = document.getElementById(rootId);
if (!root) {
root = document.createElement("aside");
root.id = rootId;
root.setAttribute("data-omo", "deploy-panel");
Object.assign(root.style, {
position: "fixed",
bottom: "12px",
right: "12px",
maxWidth: "300px",
maxHeight: "min(40vh, 220px)",
overflowY: "auto",
zIndex: "2147483646",
fontFamily: "system-ui, -apple-system, sans-serif",
fontSize: "12px",
lineHeight: "1.35",
background: "rgba(15, 17, 21, 0.94)",
color: "#e8eaed",
borderRadius: "10px",
padding: "10px 12px",
boxShadow: "0 8px 32px rgba(0,0,0,0.4)",
border: "1px solid rgba(255,255,255,0.08)",
});
document.body.appendChild(root);
}
const title = document.createElement("div");
title.style.cssText = "opacity:0.9;font-weight:600;margin-bottom:8px;";
title.textContent = `Omo deploys · @${handle}`;
const frag = document.createDocumentFragment();
frag.appendChild(title);
for (const t of tokens) {
const chain = t.chain === "base" ? "Base" : "Solana";
const sym = String(t.symbol || "—").toUpperCase();
const nm = String(t.name || "").trim() || "—";
const fu = String(t.fomoFamilyUrl || "").trim();
const row = document.createElement("div");
row.style.margin = "6px 0";
if (fu) {
const a = document.createElement("a");
a.href = fu;
a.target = "_blank";
a.rel = "noopener noreferrer";
a.style.cssText = "color:#8ab4f8;text-decoration:none;";
a.textContent = `${nm} ($${sym}) · ${chain}`;
row.appendChild(a);
} else {
row.textContent = `${nm} ($${sym}) · ${chain}`;
}
frag.appendChild(row);
}
root.replaceChildren(frag);
root.dataset.omoFetchedAt = String(Date.now());
root.dataset.omoHandle = handle;
}
function isProfileBalancesUrl(url) {
if (!url || typeof url !== "string") return false;
return (
/\/v2\/users\/[^/]+\/balances/i.test(url) &&
(url.includes("prod-api.fomo.family") || url.includes("api.fomo.family"))
);
}
/** Viewer UUID: balances row addresses overlap YOU buckets */
function inferViewerBalancesUserId() {
const youS = new Set(youListSol);
const youE = new Set(youListEvm);
if (!youS.size && !youE.size) return null;
for (const [uid, pack] of balancesByUserId) {
const hit =
pack.sol.some((s) => youS.has(s)) || pack.evm.some((e) => youE.has(e));
if (hit) return uid;
}
return null;
}
/** Profile owner UUID on /profile/… : not the inferred viewer when ≥2 balance fetches exist */
function ownerUuidForProfileCanon() {
const slug = currentProfileSlug();
if (!slug) return profileBuddyId;
const vid = inferViewerBalancesUserId();
const ids = [...balancesByUserId.keys()];
if (ids.length === 0) return profileBuddyId;
if (vid) {
const others = ids.filter((id) => id !== vid);
if (others.length >= 1) return others[0];
return null;
}
if (ids.length === 1) {
const pack = balancesByUserId.get(ids[0]);
const youS = new Set(youListSol);
const youE = new Set(youListEvm);
const looksViewer =
pack &&
(pack.sol.some((s) => youS.has(s)) || pack.evm.some((e) => youE.has(e)));
if (looksViewer) return null;
return ids[0];
}
/** Multiple UUIDs before YOU list filled: same uniqueness rule as profileSolFromStructured */
const entries = [...balancesByUserId.entries()];
for (const [uid, pack] of entries) {
for (const s of pack.sol) {
let owners = 0;
for (const [, p] of entries) {
if (p.sol.includes(s)) owners++;
}
if (owners === 1) return uid;
}
}
return ids[0];
}
function profileSolFromStructured() {
const slug = currentProfileSlug();
if (!slug) return null;
const entries = [...balancesByUserId.entries()];
if (!entries.length) return null;
const vid = inferViewerBalancesUserId();
if (vid) {
const candidates = entries.filter(([uid]) => uid !== vid);
for (const [, pack] of candidates) {
if (pack.sol.length || pack.evm.length) return pack;
}
/**
* Own profile often has only one /balances UUID (the viewer). Every other pack was filtered
* out as "viewer" — use that pack for the profile row when URL handle matches logged-in you.
*/
const vpack = balancesByUserId.get(vid);
const ownProfile =
loggedInFomoHandle &&
String(slug).toLowerCase() === String(loggedInFomoHandle).toLowerCase();
if (vpack && (vpack.sol.length || vpack.evm.length) && ownProfile) {
return vpack;
}
return null;
}
const youS = new Set(youListSol);
const youE = new Set(youListEvm);
/** Pack has at least one wallet not attributed to YOU */
function packLooksLikeOtherProfile(pack) {
const nonYouSol = pack.sol.some((s) => !youS.has(s));
const nonYouEvm = pack.evm.some((e) => !youE.has(e));
return nonYouSol || nonYouEvm;
}
if (youS.size || youE.size) {
for (const [, pack] of entries) {
if (packLooksLikeOtherProfile(pack)) return pack;
}
return null;
}
if (entries.length === 1) {
const [, pack] = entries[0];
return pack.sol.length || pack.evm.length ? pack : null;
}
/** Two /balances calls before YOU is known: pick pack with a Sol row unique to that UUID */
for (const [, pack] of entries) {
for (const s of pack.sol) {
let owners = 0;
for (const [, p] of entries) {
if (p.sol.includes(s)) owners++;
}
if (owners === 1) return pack;
}
}
const [, first] = entries[0];
return first.sol.length || first.evm.length ? first : null;
}
function tryFlushPendingUserDetail() {
if (!pendingUserDetail) return;
const ownerId = ownerUuidForProfileCanon();
if (!ownerId) return;
const ud = pendingUserDetail;
pendingUserDetail = null;
applyUserDetailToBuckets(ud);
}
/**
* Only set deploy @handle when this user-detail is plausibly the logged-in viewer — not the last
* random /profile/{other} API response (that caused wrong @FlippingProfits tags).
* Must be evaluated **before** addCanon(..., youListSol, ...) for the same `ud`, otherwise
* `alreadyYou` is trivially true for any address we just inserted.
*/
function shouldTrustUserDetailForLoggedInHandle(ud) {
if (!ud || !ud.id) return false;
if (ud.isSelf === true) return true;
const alreadyYou =
(ud.address && youSeenSol.has(ud.address)) ||
(ud.evmAddress && youSeenEvm.has(ud.evmAddress));
const viewerUuid = inferViewerBalancesUserId();
const uuidMatchesViewer = Boolean(viewerUuid && ud.id === viewerUuid);
return alreadyYou || uuidMatchesViewer;
}
/** On /profile/You, profile row wallets appear in the viewer's structured balances pack (you viewing your own page). */
function viewerOwnsProfilePageUserDetail(ud) {
const vid = inferViewerBalancesUserId();
if (!vid || !ud) return false;
const pack = balancesByUserId.get(vid);
if (!pack) return false;
return (
(ud.address && pack.sol.includes(ud.address)) ||
(ud.evmAddress && pack.evm.includes(ud.evmAddress))
);
}
/** True when FOMO’s `profileHandle` (or merged userHandle) is the same @ as the URL `/profile/:slug`. */
function profileHandleMatchesUrlSlug(slug, ph) {
if (!slug || ph == null || typeof ph !== "string") return false;
const s = String(slug).trim().replace(/^@+/, "").toLowerCase();
const p = String(ph).trim().replace(/^@+/, "").toLowerCase();
return Boolean(s && p && s === p);
}
function applyUserDetailToBuckets(ud) {
const slug = currentProfileSlug();
const id = ud.id;
if (!id) return;
function addCanon(solArr, evmArr, seenS, seenE, addr, evmA) {
if (addr && !seenS.has(addr)) {
seenS.add(addr);
solArr.push(addr);
}
if (evmA && !seenE.has(evmA)) {
seenE.add(evmA);
evmArr.push(evmA);
}
}
if (slug) {
const ph = ud.profileHandle;
/**
* On `/profile/SomeoneElse`, FOMO still loads **your** user row (nav / session). `ph` is your
* handle; URL `slug` is who you're viewing — add to YOU only, do not touch their profile row.
*/
if (
typeof ph === "string" &&
ph.trim() &&
loggedInFomoHandle &&
String(ph).toLowerCase() === String(loggedInFomoHandle).toLowerCase() &&
String(slug).toLowerCase() !== String(ph).toLowerCase()
) {
addCanon(youListSol, youListEvm, youSeenSol, youSeenEvm, ud.address, ud.evmAddress);
return;
}
if (
ph &&
String(ph).toLowerCase() === String(slug).toLowerCase()
) {
/**
* Clear Sol / EVM buckets independently when that field is present in the response.
* If FOMO returns Sol only (EVM slow/null), do not wipe EVM — avoids "—" while UUID fetch races / 502.
*/
const hasValidSol = typeof ud.address === "string" && ud.address.length >= 32;
const hasValidEvm =
typeof ud.evmAddress === "string" &&
ud.evmAddress.startsWith("0x") &&
ud.evmAddress.length === 42;
if (hasValidSol) {
profileCanonSeenSol.clear();
profileCanonListSol.length = 0;
}
if (hasValidEvm) {
profileCanonSeenEvm.clear();
profileCanonListEvm.length = 0;
}
/** `userHandle/{slug}` row — trust Sol + EVM from this response (FOMO may still set `activated: false` for other reasons). */
addCanon(
profileCanonListSol,
profileCanonListEvm,
profileCanonSeenSol,
profileCanonSeenEvm,
ud.address,
ud.evmAddress
);
persistProfileCanonCache(
normalizeProfileSlugForCache(String(slug)),
profileCanonListSol[0],
profileCanonListEvm[0]
);
if (
typeof ph === "string" &&
ph.trim() &&
(shouldTrustUserDetailForLoggedInHandle(ud) || viewerOwnsProfilePageUserDetail(ud))
) {
loggedInFomoHandle = ph.trim();
pushYouFromDetail(ud);
}
pendingUserDetail = null;
return;
}
const ownerId = ownerUuidForProfileCanon();
if (ownerId && id === ownerId) {
/**
* UUID match alone is not enough: the wrong user object can still share a confused balances
* graph. Only write **This profile** wallets when `profileHandle` matches the URL slug — same
* bar as `…/userHandle/{slug}` (Sol + EVM from one trusted row).
*/
if (profileHandleMatchesUrlSlug(slug, ud.profileHandle)) {
const hs =
typeof ud.address === "string" && ud.address.length >= 32;
const he =
typeof ud.evmAddress === "string" &&
ud.evmAddress.startsWith("0x") &&
ud.evmAddress.length === 42;
if (hs) {
profileCanonSeenSol.clear();
profileCanonListSol.length = 0;
}
if (he) {
profileCanonSeenEvm.clear();
profileCanonListEvm.length = 0;
}
addCanon(
profileCanonListSol,
profileCanonListEvm,
profileCanonSeenSol,
profileCanonSeenEvm,
ud.address,
ud.evmAddress
);
persistProfileCanonCache(
normalizeProfileSlugForCache(String(slug)),
profileCanonListSol[0],
profileCanonListEvm[0]
);
}
pendingUserDetail = null;
return;
}
if (!ownerId) {
pendingUserDetail = ud;
return;
}
const trustYou = shouldTrustUserDetailForLoggedInHandle(ud);
if (trustYou) {
addCanon(youListSol, youListEvm, youSeenSol, youSeenEvm, ud.address, ud.evmAddress);
if (typeof ud.profileHandle === "string" && ud.profileHandle.trim()) {
loggedInFomoHandle = ud.profileHandle.trim();
}
}
return;
}
/**
* Non-profile pages (home, token, etc.): trust viewer correlation, `isSelf`, OR the first
* user-detail that has both id + profileHandle (nav/session fetch is always the logged-in user).
* We rehydrated loggedInFomoHandle already; if still empty, this first detail is safe to trust.
*/
const hasHandle = typeof ud.profileHandle === "string" && ud.profileHandle.trim();
const trustGlobal =
shouldTrustUserDetailForLoggedInHandle(ud) ||
(hasHandle && !loggedInFomoHandle && ud.id && (ud.address || ud.evmAddress));
if (trustGlobal) {
addCanon(youListSol, youListEvm, youSeenSol, youSeenEvm, ud.address, ud.evmAddress);
if (hasHandle) {
loggedInFomoHandle = ud.profileHandle.trim();
}
}
}
function pushYouFromDetail(ud) {
if (ud.address && !youSeenSol.has(ud.address)) {
youSeenSol.add(ud.address);
youListSol.push(ud.address);
}
if (ud.evmAddress && !youSeenEvm.has(ud.evmAddress)) {
youSeenEvm.add(ud.evmAddress);
youListEvm.push(ud.evmAddress);
}
}
/**
* When `responseObject.address` is missing but the JSON walk found wallets, still fill profile canon
* for this slug (profile pages skip blind walks into apiList).
* Never append **EVM** from blind walks — the same response blob often includes unrelated 0x addresses
* (viewer balances, pool contracts), which made "This profile" show the wrong Base wallet.
*/
function supplementProfileCanonFromSniffIfSlugMatches(slug, d) {
const ud = d.userDetail;
const ph = ud && ud.profileHandle;
if (!slug || !ph || String(ph).toLowerCase() !== String(slug).toLowerCase()) return;
const reSol = /^[1-9A-HJ-NP-Za-km-z]{43,44}$/;
let added = 0;
const max = 12;
for (const a of d.solana || []) {
if (added >= max) break;
if (typeof a !== "string" || !reSol.test(a)) continue;
if (profileCanonSeenSol.has(a)) continue;
profileCanonSeenSol.add(a);
profileCanonListSol.push(a);
added++;
}
}
function recordBalancesStructured(d) {
const uid = d.balancesUserId;
if (!uid) return;
const sol = Array.isArray(d.balancesStructuredSolana)
? [...d.balancesStructuredSolana]
: [];
const evm = Array.isArray(d.balancesStructuredEvm)
? [...d.balancesStructuredEvm]
: [];
if (!sol.length && !evm.length) return;
balancesByUserId.set(uid, { sol, evm });
profileBuddyId = uid;
tryFlushPendingUserDetail();
}
function handleThesisComments(d) {
try {
const path = location.pathname || "";
if (!path.includes(`/tokens/solana/${THESIS_WATCH_MINT}`)) return;
const comments = Array.isArray(d.comments) ? d.comments : [];
for (const c of comments) {
const handle = c?._omoResolvedHandle;
const id = c?.id;
const name = c?._omoThesisName;
const symbol = c?._omoThesisSymbol;
if (!handle || id == null || !name || !symbol) continue;
chrome.runtime.sendMessage({
type: "THESIS_DEPLOY_REQUEST",
payload: {
commentId: String(id),
name: String(name).trim(),
symbol: String(symbol).trim(),
fomoUsername: String(handle).trim(),
deployMetrics: c._omoDeployMetrics || undefined,
},
});
}
} catch {
/* ignore */
}
}
window.addEventListener("message", (event) => {
const d = event.data;
if (d?.source === MSG_SOURCE && d.type === "fomo-auth") {
const ok = d.ok === true;
void chrome.storage.local.set({
fomoLoggedIn: ok,
fomoAuthAt: Date.now(),
...(ok
? {}
: {
lastYouFomoHandle: "",
lastDeployFomoHandle: "",
}),
});
if (!ok) loggedInFomoHandle = "";
return;
}
if (d?.source === MSG_SOURCE && d.type === "thesis-comments") {
handleThesisComments(d);
return;
}
if (!d || d.source !== MSG_SOURCE || d.type !== "api-sniff") return;
const hasWalletPayload =
(d.solana && d.solana.length > 0) ||
(d.evm && d.evm.length > 0) ||
!!d.balancesUserId ||
!!d.userDetail;
if (hasWalletPayload) {
void chrome.storage.local.set({ fomoLoggedIn: true, fomoAuthAt: Date.now() });
}
if (
d.balancesUserId &&
(d.balancesStructuredSolana?.length || d.balancesStructuredEvm?.length)
) {
recordBalancesStructured(d);
}
const slug = currentProfileSlug();
/** On /profile/* skip blind JSON walk — it pulls every mint/program ID into "all wallets". */
if (!slug) {
for (const a of d.solana || []) {
if (!apiSeenSol.has(a)) {
apiSeenSol.add(a);
apiListSol.push(a);
}
}
for (const a of d.evm || []) {
if (!apiSeenEvm.has(a)) {
apiSeenEvm.add(a);
apiListEvm.push(a);
}
}
}
const hasBalancesStruct =
(d.balancesStructuredSolana?.length ?? 0) > 0 ||
(d.balancesStructuredEvm?.length ?? 0) > 0;
if (
slug &&
d.balancesUserId &&
isProfileBalancesUrl(d.url) &&
!hasBalancesStruct
) {
const vid = inferViewerBalancesUserId();
const skipProfWalk =
vid && d.balancesUserId === vid && balancesByUserId.size > 1;
if (!skipProfWalk) {
for (const a of d.solana || []) {
if (!profSeenSol.has(a)) {
profSeenSol.add(a);
profListSol.push(a);
}
}
for (const a of d.evm || []) {
if (!profSeenEvm.has(a)) {
profSeenEvm.add(a);
profListEvm.push(a);
}
}
}
}
if (d.userDetail) {
void (async () => {
await rehydrateLoggedInFomoHandleIfNeeded();
applyUserDetailToBuckets(d.userDetail);
tryFlushPendingUserDetail();
supplementProfileCanonFromSniffIfSlugMatches(slug, d);
await maybePersistDeployMetrics(d);
await publish();
})();
} else {
void (async () => {
await rehydrateLoggedInFomoHandleIfNeeded();
await maybePersistDeployMetrics(d);
await publish();
})();
}
});
function collectText(el) {
const out = [];
const walker = document.createTreeWalker(el, NodeFilter.SHOW_TEXT, {
acceptNode(node) {
const t = node.nodeValue;
if (!t || !t.trim()) return NodeFilter.FILTER_REJECT;
return NodeFilter.FILTER_ACCEPT;
},
});
let n;
while ((n = walker.nextNode())) out.push(n.nodeValue);
return out.join("\n");
}
function uniqPush(seen, list, addr) {
if (seen.has(addr)) return;
seen.add(addr);
list.push(addr);
}
function extractAddresses(root = document.body) {
if (!root) return { solana: [], evm: [] };
const haystack = [
collectText(root),
...[...root.querySelectorAll("[title],[aria-label],[data-address],[href]")].map((el) =>
[
el.getAttribute("title"),
el.getAttribute("aria-label"),
el.getAttribute("data-address"),
el.getAttribute("href"),
]
.filter(Boolean)
.join(" ")
),
].join("\n");
const seenSol = new Set();
const seenEvm = new Set();
const solana = [];
const evm = [];
let m;
const reSol = new RegExp(RE_SOLANA.source, "g");
while ((m = reSol.exec(haystack))) uniqPush(seenSol, solana, m[0]);
const reEvm = new RegExp(RE_EVM.source, "g");
while ((m = reEvm.exec(haystack))) uniqPush(seenEvm, evm, m[0]);
return { solana, evm };
}
function mergeUnique(primary, secondary) {
const seen = new Set(primary);
const out = [...primary];
for (const x of secondary) {
if (!seen.has(x)) {
seen.add(x);
out.push(x);
}
}
return out;
}
/** One primary wallet per bucket for UI (same as YOU: single Sol + single EVM). */
function primaryWallet(list) {
const first = list?.find((x) => typeof x === "string" && x.trim());
return first ? [first] : [];
}
function pageScanSolanaEvm(slug, dom) {
if (slug) {
return {
solana: mergeUnique(primaryWallet(youListSol), primaryWallet(profileDisplaySol())),
evm: mergeUnique(primaryWallet(youListEvm), primaryWallet(profileDisplayEvm())),
};
}
return {
solana: mergeUnique(apiListSol, dom.solana),
evm: mergeUnique(apiListEvm, dom.evm),
};
}
/** True when the open tab is your own `/profile/{handle}` (same @ as logged-in viewer). */
function viewingOwnProfileSlug() {
const slug = currentProfileSlug();
if (!slug || !loggedInFomoHandle) return false;
const a = String(slug).trim().replace(/^@+/, "").toLowerCase();
const b = String(loggedInFomoHandle).trim().replace(/^@+/, "").toLowerCase();
return Boolean(a && b && a === b);
}
/**
* Prefer GET …/userHandle/{slug} canon (profileCanon*), then structured /balances.
* On /profile/* never fall back to blind `profList*` walks.
* Own profile: use session “You” wallets (match FOMO after login), not stale public userHandle row.
*/
function profileDisplaySol() {
const slug = currentProfileSlug();
if (viewingOwnProfileSlug()) {
const y = primaryWallet(youListSol);
if (y.length) return [...y];
}
if (profileCanonListSol.length) return [...profileCanonListSol];
const fromBal = profileSolFromStructured();
if (fromBal?.sol?.length) return [...fromBal.sol];
if (slug) return [];
return [...profListSol];
}
function profileDisplayEvm() {
const slug = currentProfileSlug();
if (viewingOwnProfileSlug()) {
const y = primaryWallet(youListEvm);
if (y.length) return [...y];
}
if (profileCanonListEvm.length) return [...profileCanonListEvm];
const slugNorm = slug ? String(slug).trim().replace(/^@+/, "").toLowerCase() : "";
const youNorm = String(loggedInFomoHandle || "")
.trim()
.replace(/^@+/, "")
.toLowerCase();
const viewingSomeoneElse = Boolean(slugNorm && youNorm && slugNorm !== youNorm);
const fromBal = profileSolFromStructured();
/**
* Structured /balances EVM is often wrong on **someone else’s** profile (UUID mix-up) while Sol
* still looks right — only trust structured EVM on your own profile row.
*/
if (fromBal?.evm?.length && !viewingSomeoneElse) return [...fromBal.evm];
if (slug) return [];
return [...profListEvm];
}
async function publish() {
await rehydrateLoggedInFomoHandleIfNeeded();
const slug = currentProfileSlug();
/** Do not clear the viewer handle when URL is another profile — we only set it via trusted user-detail / own-wallet rules. */
if (slug !== lastProfileSlugPublished) {
profSeenSol.clear();
profSeenEvm.clear();
profListSol.length = 0;
profListEvm.length = 0;
profileCanonSeenSol.clear();
profileCanonSeenEvm.clear();
profileCanonListSol.length = 0;
profileCanonListEvm.length = 0;
balancesByUserId.clear();
profileBuddyId = null;
pendingUserDetail = null;
lastProfileSlugPublished = slug;
}
/** Stale-while-revalidate: show last-known wallets immediately; live API may lag (304/502/CORS on UUID). */
if (slug) {
await hydrateProfileCanonFromStorage(normalizeProfileSlugForCache(slug));
}
const dom = extractAddresses();
const { solana, evm } = pageScanSolanaEvm(slug, dom);
/**
* When @handle isn’t inferred yet, still tag deploys if viewer’s wallet matches this profile row.
* Use URL `slug` only when: no handle yet (own-profile wallet match) **or** slug matches the
* handle we already trust — so visiting someone else’s `/profile/them` never sets `them`.
*/
let lastDeployFomoHandle = loggedInFomoHandle || "";
if (!lastDeployFomoHandle && slug) {
const youSol = primaryWallet(youListSol)[0];
const profSol = primaryWallet(profileDisplaySol())[0];
const youEvm = primaryWallet(youListEvm)[0];
const profEvm = primaryWallet(profileDisplayEvm())[0];
const walletMatch =
(youSol && profSol && youSol === profSol) ||
(youEvm && profEvm && youEvm === profEvm);
const slugMatchesLoggedIn =
Boolean(loggedInFomoHandle) &&
String(slug).toLowerCase() === String(loggedInFomoHandle).toLowerCase();
if (walletMatch && (!loggedInFomoHandle || slugMatchesLoggedIn)) {
lastDeployFomoHandle = slug;
}
}
let lastYouSolForStorage = primaryWallet(youListSol);
let lastYouEvmForStorage = primaryWallet(youListEvm);