-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathtrustViz.html
833 lines (801 loc) · 33.2 KB
/
trustViz.html
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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<title>Circles Trust Graph Visualizer with Avatars, PageRank, Stats & Table</title>
<!-- Vis Network CSS -->
<link href="https://unpkg.com/vis-network/styles/vis-network.min.css" rel="stylesheet" />
<style>
body {
margin: 0;
font-family: 'Inter', Helvetica, Arial, sans-serif;
background: #fff;
color: #333;
line-height: 1.3;
}
header {
background: #5C49E4;
color: #fff;
padding: 20px;
text-align: center;
}
h1 { margin: 0; font-weight: 600; font-size: 1.5rem; }
p { margin: 0.5rem 0 0; font-weight: 400; }
.container { max-width: 1200px; margin: 20px auto; padding: 0 20px; }
.controls { margin-bottom: 20px; display: flex; justify-content: center; align-items: center; gap: 10px; }
input[type="text"] { padding: 10px; width: 300px; border: 1px solid #ccc; border-radius: 4px; font-size: 1rem; }
button { padding: 10px 20px; background: #5C49E4; color: #fff; border: none; border-radius: 4px; cursor: pointer; font-size: 1rem; }
button:hover { background: #4A39CC; }
/* New buttons for extra rounds and extra profiles */
#moreRoundsBtn, #addProfilesBtn { background: #007BFF; }
#moreRoundsBtn:hover, #addProfilesBtn:hover { background: #0056b3; }
#toggles { text-align: center; margin-bottom: 10px; }
#toggles label { margin: 0 10px; font-size: 1rem; }
#legend { text-align: center; margin-bottom: 20px; }
#legend ul { list-style: none; padding: 0; display: inline-block; text-align: left; }
#legend li { margin: 5px 0; }
#legend span { display: inline-block; width: 16px; height: 16px; margin-right: 5px; vertical-align: middle; }
#stats { text-align: center; margin-bottom: 10px; font-weight: bold; }
#loader { margin-top: 10px; text-align: center; }
#expansionProgress { text-align: center; margin-top: 10px; font-weight: bold; display: none; }
#network { width: 100%; height: 600px; border: 1px solid #ddd; border-radius: 8px; background: #fff; }
/* Table styles */
#statsTableContainer { margin-top: 20px; text-align: center; }
#statsTable { margin: 0 auto; border-collapse: collapse; }
#statsTable th, #statsTable td { border: 1px solid #ccc; padding: 5px 10px; }
#statsTable th { background: #f0f0f0; }
#statsTable tbody tr { cursor: pointer; }
/* Tooltip styles */
.trust-tooltip {
position: absolute;
background: #fff;
border: 1px solid #ccc;
padding: 5px;
box-shadow: 2px 2px 5px rgba(0,0,0,0.3);
z-index: 1000;
display: none;
max-width: 250px;
font-size: 0.9rem;
}
</style>
</head>
<body>
<header>
<h1>Circles Trust Graph Visualizer with Avatars, PageRank, Stats & Table</h1>
<p>
Enter an address to fetch its trusted connections.<br>
Double‑click a node to expand it recursively (max 50 new connections per click).<br>
Toggle checkboxes to filter Humans, Groups, and Orgs.<br>
Edges show directional trust (bidirectional edges display arrows on both ends).<br>
Node image, name, and size reflect its (magnified) PageRank (trust score).<br>
Expanded profiles are shown with a thicker border.
</p>
</header>
<div class="container">
<div class="controls">
<input type="text" id="addressInput" placeholder="Enter an address" value="0x42cEDde51198D1773590311E2A340DC06B24cB37">
<button id="generateBtn">Generate Graph</button>
<button id="expandHighestBtn">Expand Highest Rank Unexpanded</button>
<!-- New buttons -->
<button id="moreRoundsBtn">Run +1 Round</button>
<button id="addProfilesBtn">Add 10 More Profiles</button>
</div>
<div id="toggles">
<label><input type="checkbox" id="toggleHumans" checked> Humans</label>
<label><input type="checkbox" id="toggleGroups" checked> Groups</label>
<label><input type="checkbox" id="toggleOrgs" checked> Orgs</label>
</div>
<div id="legend">
<h3>Legend</h3>
<ul>
<li><span style="background:#A3E4D7; border:2px solid #1ABC9C; border-radius:50%;"></span> Human (Expanded)</li>
<li><span style="background:#F9E79F; border:2px solid #F4D03F;"></span> Group (Expanded)</li>
<li><span style="background:#F5B7B1; border:2px solid #E74C3C;"></span> Org (Expanded)</li>
<li><span style="background:#E0E0E0; border:2px solid #B0B0B0; border-radius:50%;"></span> Unexpanded (Grey)</li>
</ul>
</div>
<div id="stats"></div>
<div id="loader" style="display: none;">Loading graph...</div>
<div id="expansionProgress"></div>
<div id="network"></div>
<div id="statsTableContainer">
<h3>Node Trust Table</h3>
<table id="statsTable">
<thead id="statsTableHead"></thead>
<tbody id="statsTableBody"></tbody>
</table>
</div>
</div>
<!-- Tooltip Containers -->
<div id="incomingTooltip" class="trust-tooltip"></div>
<div id="outgoingTooltip" class="trust-tooltip"></div>
<!-- Ethers.js -->
<!-- Vis Network Library -->
<script src="https://unpkg.com/vis-network/standalone/umd/vis-network.min.js"></script>
<script>
// Global variables: current PageRank vector and round counter.
let currentPR = {};
let currentRound = 0;
const displayFactor = 1e6; // Magnify trust scores for display.
// Separate caches: one for names (aboutcircles) and one for full data (circles.garden)
const nameCache = {};
const gardenCache = {};
// --- getProfileName using nameCache (aboutcircles API) ---
async function getProfileName(address) {
const key = address.toLowerCase();
if (nameCache[key] && nameCache[key].profileName) {
return nameCache[key].profileName;
}
try {
const url = `https://rpc.aboutcircles.com/profiles/search?address=${key}`;
const response = await fetch(url);
if (!response.ok) return "No name";
const data = await response.json();
if (Array.isArray(data)) {
const profile = data.find(entry => entry.address.toLowerCase() === key);
const name = profile?.name || "No name";
nameCache[key] = { profileName: name };
return name;
}
return "No name";
} catch (error) {
console.error("Error fetching profile for", address, error);
return "No name";
}
}
// Global vis-network variables.
let network, visNodes, visEdges;
let expansionInProgress = {};
let currentExpandingAddress = null;
// --- Helper Contract Setup ---
const helperABI = [
"function getAllDataForUser(address user) external view returns (tuple(bool isOrg, bool isHuman, uint256 totalSupply, bool stopped, uint256 lastTouched) v1Data, tuple(bool isHuman, bool isOrg, bool isGroup, uint256 crcAmount, uint256 ts1, uint256 ts2, uint256 totalSupply) v2Data, tuple(address trustedAddress, uint256 expiry, bool v1Org, bool v1Human, bool v2Human, bool v2Org, bool v2Group, uint256 v2TotalSupply, uint256 userHolds)[] trustedAddresses)"
];
const helperAddress = "0xD5934724C19f9DbEeBC263066D627872e55e63Aa";
const provider = new ethers.providers.JsonRpcProvider("https://rpc.ankr.com/gnosis");
const helperContract = new ethers.Contract(helperAddress, helperABI, provider);
// --- Graph Data Structures ---
const nodesMap = new Map();
const edgesArray = [];
let loadedCount = {};
// --- Colors ---
const COLORS = {
human: { background: "#A3E4D7", border: "#1ABC9C" },
group: { background: "#F9E79F", border: "#F4D03F" },
org: { background: "#F5B7B1", border: "#E74C3C" },
unknown: { background: "#D7DBDD", border: "#AAB7B8" }
};
const GREY = { background: "#E0E0E0", border: "#B0B0B0" };
// --- Add Node & Edge Functions ---
function addNode(address, type) {
if (!nodesMap.has(address)) {
nodesMap.set(address, {
id: address,
label: address.substring(0, 8) + "...",
title: address,
nodeType: type,
expanded: false,
shape: (type === "human" ? "circle" : (type === "group" ? "box" : (type === "org" ? "diamond" : "ellipse"))),
color: GREY,
hidden: false,
profileName: "",
prevTrust: null
});
}
}
function addEdge(from, to) {
if (!edgesArray.some(e => e.from === from && e.to === to)) {
edgesArray.push({ from, to, hidden: false });
}
}
// --- Mark Node as Expanded (with thicker border) ---
function updateExpanded(address, type) {
let color, shape;
if (type === "human") { shape = "circle"; color = COLORS.human; }
else if (type === "group") { shape = "box"; color = COLORS.group; }
else if (type === "org") { shape = "diamond"; color = COLORS.org; }
else { shape = "ellipse"; color = COLORS.unknown; }
if (nodesMap.has(address)) {
let node = nodesMap.get(address);
node.expanded = true;
node.nodeType = type;
node.color = color;
node.shape = shape;
nodesMap.set(address, node);
if (visNodes) visNodes.update({ id: address, expanded: true, color: color, shape: shape, borderWidth: 3 });
} else {
nodesMap.set(address, {
id: address,
label: address.substring(0, 8) + "...",
title: address,
nodeType: type,
expanded: true,
shape: (type === "human" ? "circle" : (type === "group" ? "box" : (type === "org" ? "diamond" : "ellipse"))),
color: (type === "human" ? COLORS.human : (type === "group" ? COLORS.group : (type === "org" ? COLORS.org : COLORS.unknown))),
hidden: false,
profileName: "",
prevTrust: null
});
}
}
// --- Explore Trust Connections ---
async function explore(address, depth, limit = Infinity) {
try {
console.log(`Exploring ${address} with depth ${depth} and limit ${limit}`);
const data = await helperContract.getAllDataForUser(address);
let type = "unknown";
if (data.v2Data.isGroup) type = "group";
else if (data.v2Data.isHuman) type = "human";
else if (data.v2Data.isOrg) type = "org";
const trusts = data.trustedAddresses;
const alreadyLoaded = loadedCount[address] || 0;
const newTrusts = trusts.slice(alreadyLoaded, alreadyLoaded + limit);
loadedCount[address] = alreadyLoaded + newTrusts.length;
if (loadedCount[address] >= trusts.length) {
updateExpanded(address, type);
}
for (let i = 0; i < newTrusts.length; i++) {
const t = newTrusts[i];
const trustedAddr = t.trustedAddress;
if (trustedAddr.toLowerCase() === address.toLowerCase()) continue;
let trustedType = "unknown";
if (t.v2Group) trustedType = "group";
else if (t.v2Human) trustedType = "human";
else if (t.v2Org) trustedType = "org";
addNode(trustedAddr, trustedType);
addEdge(address, trustedAddr);
if (depth > 1) {
await explore(trustedAddr, depth - 1, Infinity);
}
}
} catch (error) {
console.error(`Error exploring ${address}:`, error);
}
}
// --- Expand Node on Double‑Click ---
async function expandNodeRecursive(address) {
let node = nodesMap.get(address);
if (node && node.expanded) return;
if (expansionInProgress[address]) return;
expansionInProgress[address] = true;
currentExpandingAddress = address;
document.getElementById("expansionProgress").style.display = "block";
await explore(address, 1, 50);
expansionInProgress[address] = false;
currentExpandingAddress = null;
document.getElementById("expansionProgress").innerText = "";
document.getElementById("expansionProgress").style.display = "none";
updateGraphNodes();
updateGraphEdges();
await updateNodeNames();
await updateNodeAvatars();
updateVisibility();
updateEdgeDirections();
await recalcPageRank(); // Initial rounds for convergence
updateStats();
updateTable();
}
// --- Update Node Names (with caching) ---
async function updateNodeNames() {
const nodesArray = Array.from(nodesMap.values());
const updates = await Promise.all(nodesArray.map(async (node) => {
const name = await getProfileName(node.id);
return { id: node.id, profileName: name, label: name, title: name };
}));
updates.forEach(update => {
const node = nodesMap.get(update.id);
if (node) {
node.profileName = update.profileName;
nodesMap.set(update.id, { ...node, ...update });
if (visNodes) visNodes.update(update);
}
});
}
// --- Update Node Avatars for the Graph (using circles.garden API) ---
async function updateNodeAvatars() {
try {
const addresses = Array.from(nodesMap.keys());
for (let i = 0; i < addresses.length; i += 50) {
const chunk = addresses.slice(i, i + 50);
const userData = await fetchUserDataForAddresses(chunk);
chunk.forEach(addr => {
const user = userData[addr.toLowerCase()];
let node = nodesMap.get(addr);
if (user && user.avatarUrl && user.avatarUrl.trim() !== "") {
console.debug("Updating node", addr, "with avatar", user.avatarUrl);
node.shape = "image";
node.image = user.avatarUrl;
node.profileName = user.username || node.profileName;
} else {
console.debug("No valid avatar for node", addr, "- using default shape with username label.");
delete node.image;
node.shape = (node.nodeType === "human" ? "circle" : (node.nodeType === "group" ? "box" : (node.nodeType === "org" ? "diamond" : "ellipse")));
}
nodesMap.set(addr, node);
if (visNodes) {
visNodes.update({ id: addr, shape: node.shape, image: node.image, profileName: node.profileName });
}
});
}
if (visNodes) {
visNodes.update(Array.from(nodesMap.values()));
}
if (network) network.redraw();
} catch (e) {
console.error("updateNodeAvatars failed:", e);
}
}
// --- Fetch User Data from circles.garden API with caching (using gardenCache) ---
async function fetchUserDataForAddresses(addresses) {
const newAddresses = addresses.filter(addr => !gardenCache[addr.toLowerCase()]);
if (newAddresses.length > 0) {
const params = newAddresses.map(addr => `address[]=${encodeURIComponent(addr)}`).join("&");
const url = `https://api.circles.garden/api/users/?${params}`;
try {
const response = await fetch(url);
if (response.ok) {
const result = await response.json();
if (result.status === "ok" && Array.isArray(result.data)) {
result.data.forEach(user => {
gardenCache[user.safeAddress.toLowerCase()] = user;
});
}
} else {
console.error("Error fetching user data", response.statusText);
}
} catch (error) {
console.error("Error fetching user data", error);
}
}
const dataMap = {};
addresses.forEach(addr => {
const key = addr.toLowerCase();
if (gardenCache[key]) {
dataMap[key] = gardenCache[key];
}
});
return dataMap;
}
// --- Incrementally Update Graph Datasets ---
function updateGraphNodes() {
const currentIds = visNodes.getIds();
const newNodes = [];
nodesMap.forEach((node, id) => {
if (!currentIds.includes(id)) newNodes.push(node);
});
if (newNodes.length > 0) visNodes.add(newNodes);
}
function updateGraphEdges() {
const currentEdges = visEdges.get();
const existingEdgeKeys = new Set(currentEdges.map(e => e.from + "-" + e.to));
const newEdges = [];
edgesArray.forEach(edge => {
const key = edge.from + "-" + edge.to;
if (!existingEdgeKeys.has(key)) newEdges.push({ ...edge, id: key });
});
if (newEdges.length > 0) visEdges.add(newEdges);
}
// --- Update Edge Directions ---
function updateEdgeDirections() {
const allEdges = visEdges.get();
allEdges.forEach(edge => {
const reverse = allEdges.find(e => e.from === edge.to && e.to === edge.from);
if (reverse) {
visEdges.update({ id: edge.id, arrows: { to: { enabled: true }, from: { enabled: true } } });
} else {
visEdges.update({ id: edge.id, arrows: { to: { enabled: true } } });
}
});
}
// --- Update Visibility (and borderWidth for expanded nodes) ---
function updateVisibility() {
const showHumans = document.getElementById("toggleHumans").checked;
const showGroups = document.getElementById("toggleGroups").checked;
const showOrgs = document.getElementById("toggleOrgs").checked;
const allNodes = visNodes.get();
allNodes.forEach(node => {
let shouldShow = true;
if (node.nodeType === "human" && !showHumans) shouldShow = false;
if (node.nodeType === "group" && !showGroups) shouldShow = false;
if (node.nodeType === "org" && !showOrgs) shouldShow = false;
visNodes.update({ id: node.id, hidden: !shouldShow, borderWidth: (node.expanded ? 3 : 1) });
});
const allEdges = visEdges.get();
allEdges.forEach(edge => {
const fromNode = visNodes.get(edge.from);
const toNode = visNodes.get(edge.to);
const edgeHidden = fromNode.hidden || toNode.hidden;
visEdges.update({ id: edge.id, hidden: edgeHidden });
});
}
document.getElementById("toggleHumans").addEventListener("change", updateVisibility);
document.getElementById("toggleGroups").addEventListener("change", updateVisibility);
document.getElementById("toggleOrgs").addEventListener("change", updateVisibility);
// --- PageRank Calculation & Label Update (Incremental 1-Round Updates) ---
async function recalcPageRank(rounds = 1) {
const nodes = Array.from(nodesMap.values());
const N = nodes.length;
if (N === 0) return;
const d = 0.85;
nodes.forEach(node => {
if (currentPR[node.id] === undefined) {
currentPR[node.id] = 1 / N;
}
});
let outDegree = {};
nodes.forEach(node => { outDegree[node.id] = 0; });
edgesArray.forEach(edge => {
outDegree[edge.from] = (outDegree[edge.from] || 0) + 1;
});
for (let i = 0; i < rounds; i++) {
let newPR = {};
nodes.forEach(node => { newPR[node.id] = (1 - d) / N; });
nodes.forEach(node => {
const u = node.id;
if (outDegree[u] > 0) {
const share = currentPR[u] / outDegree[u];
edgesArray.forEach(edge => {
if (edge.from === u) {
newPR[edge.to] += d * share;
}
});
} else {
nodes.forEach(node2 => {
newPR[node2.id] += d * (currentPR[u] / N);
});
}
});
let maxDiff = 0;
nodes.forEach(node => {
const diff = Math.abs(newPR[node.id] - currentPR[node.id]);
if (diff > maxDiff) maxDiff = diff;
});
console.log(`After round ${currentRound + i + 1}, maximum change in PageRank: ${maxDiff}`);
currentPR = newPR;
}
const magnified = {};
for (let id in currentPR) {
magnified[id] = Number(currentPR[id]) * displayFactor;
}
const minPR = Math.min(...Object.values(magnified));
const maxPR = Math.max(...Object.values(magnified));
nodes.forEach(node => {
let cur = nodesMap.get(node.id);
if (cur.pageRank !== undefined) {
cur.prevTrust = Number(cur.pageRank);
}
cur.pageRank = Number(currentPR[node.id]) * displayFactor;
const name = cur.profileName || cur.label || "Unknown";
cur.label = `${name} (${cur.pageRank.toFixed(3)})`;
cur.title = `${name} - Trust Score: ${cur.pageRank.toFixed(3)}`;
let size = 50;
if (maxPR > minPR) {
size = 50 + (500 - 50) * ((cur.pageRank - minPR) / (maxPR - minPR));
}
if (visNodes) visNodes.update({ id: node.id, size: size });
if (cur.shape === "image") {
cur.scaling = { min: 50, max: 500 };
if (visNodes) visNodes.update({ id: node.id, scaling: cur.scaling });
}
nodesMap.set(node.id, cur);
});
nodes.forEach(node => {
const cur = nodesMap.get(node.id);
if (cur && visNodes) visNodes.update({ id: node.id, label: cur.label, title: cur.title, borderWidth: (cur.expanded ? 3 : 1) });
});
if (network) network.redraw();
currentRound += rounds;
}
// --- Update Overall Statistics ---
function updateStats() {
let totalNodes = nodesMap.size;
let groups = 0, people = 0, peopleFullyExpanded = 0;
nodesMap.forEach(node => {
if (node.nodeType === "group") groups++;
if (node.nodeType === "human") {
people++;
if (node.expanded) peopleFullyExpanded++;
}
});
const statsEl = document.getElementById("stats");
statsEl.innerHTML = `Total Nodes: ${totalNodes} Groups: ${groups} People: ${people} People Fully Expanded: ${peopleFullyExpanded}`;
}
// --- Update the Trust Table (sorted by most recent trust score) ---
function updateTable() {
let headerHTML = "";
if (currentRound === 0) {
headerHTML += "<tr><th>Avatar & Name</th><th>Trust Score</th><th>Incoming Trust</th><th>Outgoing Trust</th><th>Address</th></tr>";
} else {
headerHTML += `<tr>
<th>Avatar & Name</th>
<th>Trust Score (Round ${currentRound})</th>
<th>Trust Score (Round ${currentRound + 1})</th>
<th>Incoming Trust</th>
<th>Outgoing Trust</th>
<th>Address</th>
</tr>`;
}
document.getElementById("statsTableHead").innerHTML = headerHTML;
const nodeArray = Array.from(nodesMap.values());
nodeArray.sort((a, b) => (b.pageRank || 0) - (a.pageRank || 0));
let html = "";
nodeArray.forEach(node => {
let trustCell = "";
if (currentRound === 0) {
trustCell = `<td>${node.pageRank ? node.pageRank.toFixed(3) : "0.000"}</td>`;
} else {
trustCell = `<td>${node.prevTrust !== null ? node.prevTrust.toFixed(3) : "—"}</td>
<td>${node.pageRank ? node.pageRank.toFixed(3) : "0.000"}</td>`;
}
let nameDisplay = node.profileName || node.label;
if (node.nodeType === "human" && node.expanded) {
nameDisplay = `<span style="color: green;">${nameDisplay}</span>`;
}
const edgeData = visEdges.get();
let incoming = edgeData.filter(edge => edge.to === node.id).length;
let outgoing = edgeData.filter(edge => edge.from === node.id).length;
html += `<tr data-address="${node.id}" onclick="onTableRowClick('${node.id}')">
<td>${nameDisplay}</td>
${trustCell}
<td class="incoming-cell">${incoming}</td>
<td class="outgoing-cell">${outgoing}</td>
<td>${node.id} <button onclick="copyAddress(event, '${node.id}')">Copy</button></td>
</tr>`;
});
document.getElementById("statsTableBody").innerHTML = html;
attachTrustTooltipListeners();
loadTableAvatars();
}
// --- Attach Tooltip Listeners ---
function attachTrustTooltipListeners() {
const incomingCells = document.querySelectorAll("#statsTableBody td.incoming-cell");
incomingCells.forEach(cell => {
cell.addEventListener("mouseenter", function(e) {
const row = cell.parentElement;
const address = row.getAttribute("data-address");
showIncomingTooltip(address, e);
});
cell.addEventListener("mouseleave", function(e) {
hideIncomingTooltip();
});
});
const outgoingCells = document.querySelectorAll("#statsTableBody td.outgoing-cell");
outgoingCells.forEach(cell => {
cell.addEventListener("mouseenter", function(e) {
const row = cell.parentElement;
const address = row.getAttribute("data-address");
showOutgoingTooltip(address, e);
});
cell.addEventListener("mouseleave", function(e) {
hideOutgoingTooltip();
});
});
}
// --- Tooltip Functions ---
function showIncomingTooltip(address, event) {
const incomingEdges = edgesArray.filter(edge => edge.to === address);
if (incomingEdges.length === 0) return;
const tooltip = document.getElementById("incomingTooltip");
let html = "<strong>Trusted by:</strong><br/>";
incomingEdges.forEach(edge => {
const source = nodesMap.get(edge.from);
if (source) {
const name = source.profileName || source.label || "Unknown";
const score = source.pageRank ? source.pageRank.toFixed(3) : "0.000";
let avatar = "";
if (source.shape === "image" && source.image) {
avatar = `<img src="${source.image}" style="width:20px;height:20px;border-radius:50%;margin-right:5px;vertical-align:middle;">`;
}
html += `<div>${avatar}<span>${name} (${score})</span></div>`;
}
});
tooltip.innerHTML = html;
tooltip.style.left = event.pageX + 10 + "px";
tooltip.style.top = event.pageY + 10 + "px";
tooltip.style.display = "block";
}
function hideIncomingTooltip() {
document.getElementById("incomingTooltip").style.display = "none";
}
function showOutgoingTooltip(address, event) {
const outgoingEdges = edgesArray.filter(edge => edge.from === address);
if (outgoingEdges.length === 0) return;
const tooltip = document.getElementById("outgoingTooltip");
let html = "<strong>Trusts:</strong><br/>";
outgoingEdges.forEach(edge => {
const target = nodesMap.get(edge.to);
if (target) {
const name = target.profileName || target.label || "Unknown";
const score = target.pageRank ? target.pageRank.toFixed(3) : "0.000";
let avatar = "";
if (target.shape === "image" && target.image) {
avatar = `<img src="${target.image}" style="width:20px;height:20px;border-radius:50%;margin-right:5px;vertical-align:middle;">`;
}
html += `<div>${avatar}<span>${name} (${score})</span></div>`;
}
});
tooltip.innerHTML = html;
tooltip.style.left = event.pageX + 10 + "px";
tooltip.style.top = event.pageY + 10 + "px";
tooltip.style.display = "block";
}
function hideOutgoingTooltip() {
document.getElementById("outgoingTooltip").style.display = "none";
}
// --- Table Row Click Handler ---
function onTableRowClick(nodeId) {
network.selectNodes([nodeId]);
expandNodeRecursive(nodeId);
}
function copyAddress(event, address) {
event.stopPropagation();
navigator.clipboard.writeText(address).then(() => {
alert("Address copied: " + address);
}).catch(err => {
console.error("Error copying address: ", err);
});
}
// --- Draw the Graph ---
function drawGraph() {
const container = document.getElementById("network");
visNodes = new vis.DataSet(Array.from(nodesMap.values()));
visEdges = new vis.DataSet(edgesArray.map(edge => ({ ...edge, id: edge.from + "-" + edge.to })));
const data = { nodes: visNodes, edges: visEdges };
const options = {
layout: { improvedLayout: false },
physics: {
stabilization: { enabled: true, iterations: 150, updateInterval: 25 },
barnesHut: { gravitationalConstant: -30000, springLength: 200, springConstant: 0.001 }
},
interaction: { hover: true, tooltipDelay: 200 }
};
network = new vis.Network(container, data, options);
network.on("doubleClick", async function(params) {
if (params.nodes.length > 0) {
const nodeId = params.nodes[0];
await expandNodeRecursive(nodeId);
await recalcPageRank();
updateStats();
updateTable();
}
});
}
// --- Expand Highest Rank Unexpanded Node ---
async function expandHighestRank() {
let candidate = null;
nodesMap.forEach(node => {
if (!node.expanded) {
if (!candidate || (node.pageRank || 0) > (candidate.pageRank || 0)) {
candidate = node;
}
}
});
if (candidate) {
await expandNodeRecursive(candidate.id);
await recalcPageRank();
updateStats();
updateTable();
} else {
alert("All nodes are expanded.");
}
}
// --- +1 Round Button Handler ---
document.getElementById("moreRoundsBtn").addEventListener("click", async () => {
nodesMap.forEach(node => {
node.prevTrust = Number(node.pageRank);
});
console.log("Running 1 additional PageRank round...");
await recalcPageRank(1);
updateStats();
updateTable();
});
// --- Add 10 More Profiles Button Handler ---
async function addMoreProfiles() {
let nodesToExpand = [];
nodesMap.forEach(node => {
if (!node.expanded) {
nodesToExpand.push(node.id);
}
});
nodesToExpand = nodesToExpand.slice(0, 10);
for (let nodeId of nodesToExpand) {
console.log("Expanding 10 more profiles for node", nodeId);
await explore(nodeId, 1, 10);
}
updateGraphNodes();
updateGraphEdges();
await recalcPageRank(1);
updateStats();
updateTable();
}
document.getElementById("addProfilesBtn").addEventListener("click", async () => {
await addMoreProfiles();
});
// --- Main Graph Generation ---
document.getElementById("generateBtn").addEventListener("click", async () => {
const inputAddress = document.getElementById("addressInput").value.trim();
nodesMap.clear();
edgesArray.length = 0;
loadedCount = {};
expansionInProgress = {};
currentPR = {};
currentRound = 0;
document.getElementById("loader").style.display = "block";
await explore(inputAddress, 2, Infinity);
drawGraph();
await updateNodeNames();
await updateNodeAvatars();
updateVisibility();
updateEdgeDirections();
await recalcPageRank();
updateStats();
updateTable();
document.getElementById("loader").style.display = "none";
});
document.getElementById("expandHighestBtn").addEventListener("click", async () => {
await expandHighestRank();
});
// --- Load Table Avatars ---
async function loadTableAvatars() {
const addresses = Array.from(nodesMap.keys());
for (let i = 0; i < addresses.length; i += 50) {
const chunk = addresses.slice(i, i + 50);
const userData = await fetchUserDataForAddresses(chunk);
chunk.forEach(addr => {
const user = userData[addr.toLowerCase()];
if (user && user.avatarUrl) {
const row = document.querySelector(`tr[data-address="${addr}"]`);
if (row) {
const firstCell = row.querySelector("td");
if (firstCell) {
const imgs = firstCell.querySelectorAll("img");
imgs.forEach(img => img.remove());
const img = document.createElement("img");
img.src = user.avatarUrl;
img.style.width = "24px";
img.style.height = "24px";
img.style.borderRadius = "50%";
img.style.marginRight = "5px";
firstCell.insertAdjacentElement("afterbegin", img);
}
}
}
});
}
}
// --- Fetch User Data from circles.garden API with caching (using gardenCache) ---
async function fetchUserDataForAddresses(addresses) {
const newAddresses = addresses.filter(addr => !gardenCache[addr.toLowerCase()]);
if (newAddresses.length > 0) {
const params = newAddresses.map(addr => `address[]=${encodeURIComponent(addr)}`).join("&");
const url = `https://api.circles.garden/api/users/?${params}`;
try {
const response = await fetch(url);
if (response.ok) {
const result = await response.json();
if (result.status === "ok" && Array.isArray(result.data)) {
result.data.forEach(user => {
gardenCache[user.safeAddress.toLowerCase()] = user;
});
}
} else {
console.error("Error fetching user data", response.statusText);
}
} catch (error) {
console.error("Error fetching user data", error);
}
}
const dataMap = {};
addresses.forEach(addr => {
const key = addr.toLowerCase();
if (gardenCache[key]) {
dataMap[key] = gardenCache[key];
}
});
return dataMap;
}
</script>
</body>
</html>