Repository navigation
Expand file tree
/
Copy pathprofileChecker.html
More file actions
1441 lines (1358 loc) · 83.7 KB
/
Copy pathprofileChecker.html
File metadata and controls
1441 lines (1358 loc) · 83.7 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
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Circles Checker (v1 & v2)</title>
<link
href="https://fonts.googleapis.com/css2?family=DM+Sans:wght@400;500;600;700&display=swap"
rel="stylesheet"
/>
<style>
/* --- Copied from groupChecker.html --- */
body {
margin: 0;
font-family: "DM Sans", sans-serif;
background: #fff7f5;
color: #191568;
line-height: 1.3;
}
header {
background: #191568;
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: 900px;
margin: 40px 0 40px 0; /* Remove auto centering */
padding: 0 0 0 0; /* Remove left/right padding */
}
label {
display: block;
margin-bottom: 0.5rem;
font-weight: 600;
}
input {
padding: 10px;
width: 100%;
max-width: 600px;
border: 1px solid #ccc;
border-radius: 4px;
font-size: 1rem;
}
#checkButton { /* Specific style for main button */
margin-top: 10px;
padding: 10px 20px;
background: #191568;
color: #fff;
border: none;
border-radius: 4px;
cursor: pointer;
font-size: 1rem;
font-weight: 600;
display: inline-block; /* Align with input */
width: auto; /* Reset width */
}
#checkButton:hover {
background: #251b9f;
}
.icon-btn { /* General icon button style */
margin-top: 0;
padding: 6px;
background: #ffede8;
color: #191568;
border: none;
border-radius: 50%;
cursor: pointer;
font-size: 1.1rem;
display: inline-flex;
align-items: center;
justify-content: center;
transition: background 0.2s;
width: 32px;
height: 32px;
margin-left: 2px;
margin-right: 0;
}
.icon-btn:hover {
background: #ffe3dc;
}
.icon-btn[title] {
position: relative;
}
.icon-btn[title]:hover:after {
content: attr(title);
position: absolute;
left: 50%;
top: 110%;
transform: translateX(-50%);
background: #222;
color: #fff;
padding: 2px 8px;
border-radius: 4px;
font-size: 0.85rem;
white-space: nowrap;
z-index: 10;
}
#result {
margin-top: 20px;
padding: 20px;
border-radius: 8px;
background: #fafafa;
border: 1px solid #eee;
min-height: 100px; /* Adjusted */
}
.info {
margin: 0.5rem 0; /* Increased margin */
line-height: 1.4; /* Increased line height */
font-size: 0.98rem;
}
.address-link {
color: #191568;
text-decoration: none;
font-weight: 500;
cursor: pointer;
}
.address-link:hover {
text-decoration: underline;
}
table {
border-collapse: separate;
border-spacing: 0 8px;
margin-top: 20px;
width: 100%;
font-size: 0.97rem;
background: #fff;
border-radius: 8px;
overflow: hidden;
border: 1px solid #eee;
box-shadow: 0 2px 12px 0 rgba(25,21,104,0.07);
margin-left: 0;
}
th,
td {
text-align: left;
padding: 12px 10px;
white-space: nowrap;
vertical-align: middle;
}
th {
background: #e5e3fb;
font-weight: 600;
border-bottom: 1px solid #eee;
user-select: none;
}
th[style*="cursor: pointer"]:hover {
background: #d5d3fb;
}
tr {
background: #fff;
border-radius: 8px; /* May not work with collapse: separate */
}
tr:nth-child(even) {
background: #fff7f5;
}
tr:hover td {
background: #ffede8;
}
td {
border-bottom: 1px solid #eee;
}
/* Cell for Address + Name + Actions */
.address-cell-container {
display: flex;
flex-direction: column;
align-items: flex-start;
gap: 2px;
}
.address-cell-main {
display: flex;
align-items: center;
gap: 6px;
width: 100%;
}
.address-cell-name {
font-weight: 600;
color: #222;
font-size: 1em;
}
/* Cell for ERC20 + Actions */
.erc20-cell-container {
display: flex;
align-items: center;
gap: 6px;
width: 100%;
}
.erc20-cell-address {
font-family: monospace;
font-size: 0.97em;
color: #222;
background: #ffede8;
border-radius: 4px;
padding: 2px 6px;
}
strong {
font-weight: 600;
}
/* Token Balances Section */
.token-summary {
display: flex;
gap: 12px;
flex-wrap: wrap;
margin: 20px 0 12px;
}
.token-summary-card {
background: #fff;
border: 1px solid #e5e3fb;
border-radius: 8px;
padding: 10px 14px;
min-width: 110px;
}
.token-summary-card .label {
font-size: 0.78rem;
color: #666;
margin-bottom: 2px;
}
.token-summary-card .value {
font-size: 1.15rem;
font-weight: 700;
color: #191568;
}
.token-filters {
display: flex;
gap: 6px;
margin-bottom: 10px;
flex-wrap: wrap;
}
.token-filter-btn {
padding: 4px 12px;
border: 1px solid #e5e3fb;
border-radius: 16px;
background: transparent;
font-family: inherit;
font-size: 0.82rem;
cursor: pointer;
transition: all 0.2s;
color: #191568;
}
.token-filter-btn:hover { background: #f0eef9; }
.token-filter-btn.active { background: #191568; color: #fff; border-color: #191568; }
.type-badge {
display: inline-block;
font-size: 0.72rem;
padding: 1px 6px;
border-radius: 8px;
font-weight: 600;
}
.type-badge.human { background: #dcfce7; color: #166534; }
.type-badge.group { background: #e0e7ff; color: #3730a3; }
.type-badge.wrapped { background: #dbeafe; color: #1e40af; }
.type-badge.v1 { background: #f3f4f6; color: #374151; }
th.sortable { cursor: pointer; user-select: none; }
th.sortable:hover { background: #d5d2f5; }
.loader {
border: 4px solid #f3f3f3;
border-top: 4px solid #191568;
border-radius: 50%;
width: 24px;
height: 24px;
animation: spin 1s linear infinite;
display: inline-block;
vertical-align: middle;
margin-left: 10px;
}
@keyframes spin {
0% { transform: rotate(0deg); }
100% { transform: rotate(360deg); }
}
</style>
</head>
<body>
<header>
<h1>Circles Checker (v1 & v2)</h1>
<p>Check an address to see Circles v1 & v2 status and trusted addresses.</p>
</header>
<div class="container">
<label for="addressInput">Address:</label>
<input type="text" id="addressInput" value="0x42cEDde51198D1773590311E2A340DC06B24cB37" />
<button id="checkButton">Check Address</button>
<div id="result"></div>
</div>
<!-- Ethers.js UMD build -->
<script src="https://cdn.jsdelivr.net/npm/ethers@5.7.2/dist/ethers.umd.min.js"></script>
<script>
/********************************************************
* Contract ABIs and addresses
********************************************************/
// 1) Profile Checker Helper contract (V2 - with pagination + group treasury support)
const helperABI = [
"function getUserDataWithTrustPage(address user, address startMarker, uint256 pageSize) 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(tuple(address trustedAddress, uint256 expiry, bool v1Org, bool v1Human, bool v2Human, bool v2Org, bool v2Group, uint256 v2TotalSupply, uint256 userHolds)[] entries, address nextMarker) trustPage)",
"function getUserDataWithTrustPageFor(address user, address balanceHolder, address startMarker, uint256 pageSize) 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(tuple(address trustedAddress, uint256 expiry, bool v1Org, bool v1Human, bool v2Human, bool v2Org, bool v2Group, uint256 v2TotalSupply, uint256 userHolds)[] entries, address nextMarker) trustPage)",
"function getTrustedAddressesPage(address user, address startMarker, uint256 pageSize) external view returns (tuple(tuple(address trustedAddress, uint256 expiry, bool v1Org, bool v1Human, bool v2Human, bool v2Org, bool v2Group, uint256 v2TotalSupply, uint256 userHolds)[] entries, address nextMarker) page)",
"function getTrustedAddressesPageFor(address user, address balanceHolder, address startMarker, uint256 pageSize) external view returns (tuple(tuple(address trustedAddress, uint256 expiry, bool v1Org, bool v1Human, bool v2Human, bool v2Org, bool v2Group, uint256 v2TotalSupply, uint256 userHolds)[] entries, address nextMarker) page)"
];
const helperAddress = "0x6885E3e0B510715A86B40818b45fbF69d37204fd";
// 1b) Group info getter (to find treasury for groups)
const groupGetterABI = [
"function getGroupsInfo(address[] calldata groups) external view returns (tuple(address owner, address service, address feeCollection, address[] membershipConditions, address baseMintHandler, address baseMintPolicy, address baseTreasury, address hub, address staticERC20, address demurragedERC20, address nameRegistry, uint256 maxConditions, uint256 erc1155TotalSupply, uint256 staticERC20TotalSupply, uint256 demurragedERC20TotalSupply, uint256 balance)[] memory)"
];
const groupGetterAddress = "0x3cd1c2be7ce9fc45b4c9a97ac9ef534fa85fc19d";
// 2) Avatar ERC20 contract
const avatarERC20ABI = [
"function getAvatarsERC20(address[] calldata avatars) external view returns (tuple(address staticERC20, address demurragedERC20)[] memory tokens)"
];
const avatarERC20Address = "0xeBe64dd348d1204391f6617f632cF99Af0b75561";
// 3) V1 Hub + migration contract (for V1 migration check)
const v1HubABI = [
"function userToToken(address) external view returns (address)",
"function organizations(address) external view returns (bool)"
];
const v1HubAddress = "0x29b9a7fBb8995b2423a71cC17cf9810798F6C543";
const v2HubABI = [
"function isHuman(address) external view returns (bool)",
"function isOrganization(address) external view returns (bool)",
"function isGroup(address) external view returns (bool)"
];
const v2HubAddress = "0xc12C1E50ABB450d6205Ea2C3Fa861b3B834d13e8";
const v1TokenABI = ["function balanceOf(address) external view returns (uint256)"];
const migrationABI = ["function convertFromV1ToDemurrage(uint256) external view returns (uint256)"];
const migrationContractAddress = "0xD44B8dcFBaDfC78EA64c55B705BFc68199B56376";
// Ethers.js provider (Gnosis chain)
const provider = new ethers.providers.JsonRpcProvider("https://rpc.aboutcircles.com");
// Contract instances
const helperContract = new ethers.Contract(helperAddress, helperABI, provider);
const avatarERC20Contract = new ethers.Contract(avatarERC20Address, avatarERC20ABI, provider);
const groupGetterContract = new ethers.Contract(groupGetterAddress, groupGetterABI, provider);
const v1HubContract = new ethers.Contract(v1HubAddress, v1HubABI, provider);
const v2HubContract = new ethers.Contract(v2HubAddress, v2HubABI, provider);
// Elements
const checkButton = document.getElementById("checkButton");
const resultDiv = document.getElementById("result");
const addressInput = document.getElementById("addressInput");
/********************************************************
* Async Data Fetching Functions (Profile Name, Price, Pools)
********************************************************/
// --- getProfileName (single) ---
async function getProfileName(address) {
if (!address || address === ethers.constants.AddressZero) return "None";
try {
const queryAddress = address.toLowerCase();
const url = `https://rpc.aboutcircles.com/profiles/search?address=${queryAddress}`;
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() === queryAddress);
return profile?.name || "No name";
}
return "No name";
} catch (error) {
console.warn("Error fetching profile for", address, error);
return "Fetch error";
}
}
// --- batchGetProfileNames: fetch names for many addresses with concurrency limit ---
// The Circles profile API only supports one address per request,
// so we use a worker pool pattern to parallelize with bounded concurrency.
async function batchGetProfileNames(addresses, concurrency = 15) {
const nameMap = {};
let idx = 0;
async function worker() {
while (idx < addresses.length) {
const i = idx++;
const addr = addresses[i];
try {
const queryAddr = addr.toLowerCase();
const resp = await fetch(`https://rpc.aboutcircles.com/profiles/search?address=${queryAddr}`);
if (resp.ok) {
const data = await resp.json();
if (Array.isArray(data)) {
const profile = data.find(e => e.address.toLowerCase() === queryAddr);
if (profile?.name) nameMap[queryAddr] = profile.name;
}
}
} catch {}
}
}
const workers = [];
for (let w = 0; w < Math.min(concurrency, addresses.length); w++) {
workers.push(worker());
}
await Promise.all(workers);
return nameMap;
}
// --- getPrice (in xDAI per CRC) ---
// Balancer pools only have liquidity for sCRC (inflationary/static tokens),
// so we first get the sCRC/xDAI price from Balancer, then convert to CRC price
// by dividing by the sCRC→CRC conversion factor from the V2 Hub.
// This factor changes daily as demurrage accrues (currently ~0.676, i.e. 1 sCRC ≈ 0.676 CRC).
let _cachedConvFactor = null;
async function getConvFactor() {
if (_cachedConvFactor) return _cachedConvFactor;
try {
const hubForConv = new ethers.Contract("0xc12C1E50ABB450d6205Ea2C3Fa861b3B834d13e8", [
"function convertInflationaryToDemurrageValue(uint256, uint64) external view returns (uint256)",
"function day(uint256) external view returns (uint64)"
], provider);
const today = await hubForConv.day(Math.floor(Date.now() / 1000));
const oneUnit = ethers.utils.parseUnits("1", 18);
const crcAmount = await hubForConv.convertInflationaryToDemurrageValue(oneUnit, today);
_cachedConvFactor = parseFloat(ethers.utils.formatUnits(crcAmount, 18));
} catch {
_cachedConvFactor = 1;
}
return _cachedConvFactor;
}
async function getPrice(sCRCAddress) {
if (!sCRCAddress || sCRCAddress === ethers.constants.AddressZero) return "N/A";
try {
const WXDAI = "0xe91D153E0b41518A2Ce8Dd3D7944Fa863463a97d";
const query = `{ sorGetSwapPaths( chain: GNOSIS, swapAmount: "0.1", swapType: EXACT_IN, tokenIn: "${sCRCAddress}", tokenOut: "${WXDAI}" ) { returnAmount } }`;
const response = await fetch("https://api-v3.balancer.fi/graphql", {
method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ query })
});
const data = await response.json();
if (data.data?.sorGetSwapPaths?.returnAmount) {
const sCRCPrice = Number(data.data.sorGetSwapPaths.returnAmount) * 10;
const convFactor = await getConvFactor();
return (sCRCPrice / convFactor).toFixed(6); // Price for 1 CRC in xDAI
}
return "N/A";
} catch (err) {
console.warn("Error fetching price for", sCRCAddress, err);
return "Error";
}
}
// --- getPoolsForToken ---
async function getPoolsForToken(tokenAddress) {
if (!tokenAddress || tokenAddress === ethers.constants.AddressZero) return [];
try {
const query = `{ poolGetPools(where: {tokensIn: ["${tokenAddress}"]}) { id address name } }`;
const response = await fetch("https://api-v3.balancer.fi/graphql", {
method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ query })
});
const data = await response.json();
return data.data?.poolGetPools || [];
} catch (err) {
console.warn("Error fetching pools for", tokenAddress, err);
return []; // Return empty array on error
}
}
// --- getBotClassification ---
async function getBotClassification(address) {
if (!address || address === ethers.constants.AddressZero) return null;
try {
const response = await fetch(`https://squid-app-3gxnl.ondigitalocean.app/aboutcircles-advanced-analytics2/bot-analytics/classify?address=${address}`, {
method: 'GET',
headers: { 'accept': 'application/json' },
mode: 'cors',
credentials: 'omit'
});
if (!response.ok) {
console.warn("Bot classification API returned non-OK status:", response.status);
return null;
}
const data = await response.json();
return data.verdicts?.[0] || null;
} catch (err) {
console.warn("Error fetching bot classification for", address, err);
return null;
}
}
/********************************************************
* Utility functions
********************************************************/
function relativeTimeSince(timestamp) {
const now = Date.now();
const diffMs = now - (timestamp * 1000);
if (diffMs < 0) return "in the future";
const diffMinutes = Math.floor(diffMs / 60000);
const minutes = diffMinutes % 60;
const hours = Math.floor(diffMinutes / 60);
let result = "";
if (hours > 0) result += hours + "h ";
result += minutes + "m ago";
return result.trim();
}
function formatExpiry(expiry) {
const expiryBN = ethers.BigNumber.from(expiry);
if (expiryBN.eq(0)) return "N/A";
const indefiniteVal = ethers.BigNumber.from("79228162514264337593543950335");
if (expiryBN.eq(indefiniteVal)) return "indefinite";
const expiryNum = Number(expiry);
const date = new Date(expiryNum * 1000);
if (isNaN(date.getTime())) return "Invalid Date";
return date.toUTCString();
}
function truncateAddress(address) {
if (!address) return '';
return address.slice(0, 6) + '...' + address.slice(-4);
}
function copyToClipboard(text) {
if (navigator.clipboard && window.isSecureContext) {
navigator.clipboard.writeText(text);
} else {
const ta = document.createElement('textarea');
ta.value = text;
ta.style.position = 'fixed';
ta.style.left = '-9999px';
document.body.appendChild(ta);
ta.select();
document.execCommand('copy');
document.body.removeChild(ta);
}
}
/********************************************************
* Main check function (Adapted from groupChecker)
********************************************************/
async function checkAddress(inputAddress) {
window.history.replaceState(null, "", "?address=" + inputAddress);
resultDiv.innerHTML = "";
if (!ethers.utils.isAddress(inputAddress)) {
resultDiv.innerHTML = "<p style='color:red;'>Invalid address</p>";
return;
}
// Show loader
const loader = document.createElement("div");
loader.className = "loader";
const loadingText = document.createElement("span");
loadingText.textContent = "Fetching data...";
resultDiv.appendChild(loadingText);
resultDiv.appendChild(loader);
try {
// 1) Set up constants and detect if this is a group
const SENTINEL = "0x0000000000000000000000000000000000000001";
const PAGE_SIZE = 200;
const indefiniteExpiry = ethers.BigNumber.from("79228162514264337593543950335");
// First, get basic user data (small page) to determine if this is a group
const initialData = await helperContract.getUserDataWithTrustPage(inputAddress, SENTINEL, 0);
const isGroup = initialData.v2Data.isGroup;
// Some group types (scored treasuries) hold no collateral in the registered
// treasury itself but route it to sub-treasuries. Detect those and treat the
// sub-treasuries as the real collateral holders.
async function resolveTreasuryHolders(treasury) {
try {
const router = new ethers.Contract(treasury, [
"function LOW_SCORE_SUB_TREASURY() view returns (address)",
"function HIGH_SCORE_SUB_TREASURY() view returns (address)"
], provider);
// Require BOTH probes to succeed (no per-call .catch): a revert means
// this is not a scored-treasury router, so we must not operate on a
// partial holder set (that would silently drop a treasury).
const [low, high] = await Promise.all([
router.LOW_SCORE_SUB_TREASURY(),
router.HIGH_SCORE_SUB_TREASURY()
]);
// high first (majority holder) as primary; dedupe case-insensitively
const uniq = [];
for (const a of [high, low]) {
if (a && a !== ethers.constants.AddressZero && !uniq.some(x => x.toLowerCase() === a.toLowerCase())) uniq.push(a);
}
if (uniq.length) return uniq;
} catch (err) { /* not a scored-treasury router */ }
return [treasury];
}
// If it's a group, look up the treasury address(es) for correct balance queries
let balanceHolder = inputAddress;
let extraTreasuryHolders = []; // additional collateral holders merged into per-member holds
if (isGroup) {
loadingText.textContent = "Detected group, fetching treasury...";
let registeredTreasury = ethers.constants.AddressZero;
try {
const [groupInfo] = await groupGetterContract.getGroupsInfo([inputAddress]);
if (groupInfo.baseTreasury && groupInfo.baseTreasury !== ethers.constants.AddressZero) {
registeredTreasury = groupInfo.baseTreasury;
}
} catch (err) {
console.warn("Could not fetch group treasury:", err);
}
// The GroupInfoGetter above only resolves "base" groups. For other group
// types its baseTreasury is 0x0, so fall back to the Hub's generic
// treasuries() mapping (works for any group).
if (registeredTreasury === ethers.constants.AddressZero) {
try {
const hubTreasuries = new ethers.Contract(
v2HubAddress,
["function treasuries(address) view returns (address)"],
provider
);
registeredTreasury = await hubTreasuries.treasuries(inputAddress);
} catch (err) {
console.warn("Could not fetch generic group treasury:", err);
}
}
if (registeredTreasury && registeredTreasury !== ethers.constants.AddressZero) {
const holders = await resolveTreasuryHolders(registeredTreasury);
balanceHolder = holders[0];
extraTreasuryHolders = holders.slice(1);
}
}
// Now fetch user data + first page of trust connections.
// For groups, use the "For" variant which queries balanceOf(treasury, tokenId)
// instead of balanceOf(group, tokenId), since group collateral sits in the treasury.
const helperData = isGroup
? await helperContract.getUserDataWithTrustPageFor(inputAddress, balanceHolder, SENTINEL, PAGE_SIZE)
: await helperContract.getUserDataWithTrustPage(inputAddress, SENTINEL, PAGE_SIZE);
const v1Data = helperData.v1Data;
const v2Data = helperData.v2Data;
// 2) Walk the on-chain V2 trust linked list (paginated, no limit).
// The linked list contains both active and expired/untrusted entries.
// Untrusting does NOT remove entries; it sets expiry to the current time.
loadingText.textContent = "Fetching trust connections...";
const onChainTrusts = [...helperData.trustPage[0]];
let nextMarker = helperData.trustPage.nextMarker;
let pageNum = 1;
while (nextMarker !== ethers.constants.AddressZero) {
pageNum++;
loadingText.textContent = `Fetching trust connections (page ${pageNum})...`;
const page = isGroup
? await helperContract.getTrustedAddressesPageFor(inputAddress, balanceHolder, nextMarker, PAGE_SIZE)
: await helperContract.getTrustedAddressesPage(inputAddress, nextMarker, PAGE_SIZE);
onChainTrusts.push(...page[0]);
nextMarker = page.nextMarker;
}
// 3) Build trust data from on-chain linked list only
const trustedAddressesData = onChainTrusts.map(entry => ({
trustedAddress: entry.trustedAddress,
expiry: entry.expiry,
trustLimit: -1, // on-chain, use expiry to determine active
v1Org: entry.v1Org, v1Human: entry.v1Human,
v2Human: entry.v2Human, v2Org: entry.v2Org, v2Group: entry.v2Group,
v2TotalSupply: entry.v2TotalSupply,
userHolds: entry.userHolds,
}));
// 3b) For groups whose collateral is split across sub-treasuries, the "For"
// query above only counted the primary sub-treasury. Add the remaining
// sub-treasuries' per-member holdings (fetched from the Circles indexer,
// which matches on-chain balanceOf exactly) so treasury totals are complete.
const INDEXER_ROW_LIMIT = 20000;
async function fetchTreasuryCrcBalances(account) {
// Returns { ok, truncated, map }. `ok` is false on any failure so callers
// can flag incomplete totals instead of silently undercounting.
const map = new Map();
let ok = false, truncated = false;
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), 15000);
try {
const resp = await fetch("https://rpc.aboutcircles.com/", {
method: "POST",
headers: { "content-type": "application/json" },
signal: controller.signal,
body: JSON.stringify({
jsonrpc: "2.0", id: 1, method: "circles_query",
params: [{
Namespace: "V_CrcV2", Table: "BalancesByAccountAndToken",
Columns: ["tokenAddress", "demurragedTotalBalance"],
Filter: [{ Type: "FilterPredicate", FilterType: "Equals", Column: "account", Value: account.toLowerCase() }],
Sorting: [], Limit: INDEXER_ROW_LIMIT
}]
})
});
if (!resp.ok) throw new Error("HTTP " + resp.status);
const json = await resp.json();
if (json.error) throw new Error("RPC error: " + JSON.stringify(json.error));
if (!json.result || !Array.isArray(json.result.rows) || !Array.isArray(json.result.columns)) throw new Error("malformed response");
const cols = json.result.columns;
const iTok = cols.indexOf("tokenAddress");
const iBal = cols.indexOf("demurragedTotalBalance");
if (iTok < 0 || iBal < 0) throw new Error("missing expected columns");
for (const row of json.result.rows) {
map.set(String(row[iTok]).toLowerCase(), ethers.BigNumber.from(String(row[iBal])));
}
if (json.result.rows.length >= INDEXER_ROW_LIMIT) truncated = true; // possibly truncated
ok = true;
} catch (err) {
console.warn("fetchTreasuryCrcBalances failed for", account, err);
} finally {
clearTimeout(timeoutId);
}
return { ok, truncated, map };
}
let treasuryTotalsIncomplete = false;
if (isGroup && extraTreasuryHolders.length) {
loadingText.textContent = "Aggregating sub-treasury balances...";
const extraResults = await Promise.all(extraTreasuryHolders.map(h => fetchTreasuryCrcBalances(h)));
for (const r of extraResults) { if (!r.ok || r.truncated) treasuryTotalsIncomplete = true; }
for (const entry of trustedAddressesData) {
const key = entry.trustedAddress.toLowerCase();
let extra = ethers.BigNumber.from(0);
for (const r of extraResults) { const v = r.map.get(key); if (v) extra = extra.add(v); }
if (!extra.isZero()) entry.userHolds = ethers.BigNumber.from(entry.userHolds).add(extra);
}
}
// 4) Get ERC20 tokens for the main user (skip per-row ERC20 for huge lists)
loadingText.textContent = "Fetching ERC20 data...";
const erc20Map = {};
const allAddrs = [inputAddress, ...trustedAddressesData.map(t => t.trustedAddress)];
const ERC20_CHUNK = 200;
for (let i = 0; i < allAddrs.length; i += ERC20_CHUNK) {
const chunk = allAddrs.slice(i, i + ERC20_CHUNK);
try {
const erc20Array = await avatarERC20Contract.getAvatarsERC20(chunk);
chunk.forEach((addr, idx) => {
erc20Map[addr.toLowerCase()] = erc20Array[idx];
});
} catch (err) {
console.warn("ERC20 batch failed for chunk at offset", i, err);
}
}
// 5) Remove loader
resultDiv.innerHTML = "";
// 6) Display main user summary
// Note: avatarERC20 returns (staticERC20, demurragedERC20) but the names
// are misleading: staticERC20 is actually the demurraged CRC token,
// and demurragedERC20 is actually the static/inflationary sCRC token.
const mainSCRC = erc20Map[inputAddress.toLowerCase()]?.demurragedERC20; // sCRC (inflationary/static)
let summaryHtml = '';
summaryHtml += `<div id="topSection" class="info" style="display:flex;align-items:center;gap:8px;flex-wrap:wrap;"><strong>Address:</strong> <span id="main-user-name">Loading...</span><span style="margin-left:auto;display:flex;gap:8px;font-size:0.85rem;"><a href="profileHistory.html?address=${inputAddress}" style="color:#191568;">CID History →</a><a href="#trustSection" style="color:#191568;">Trust ↓</a><a href="#tokenBalancesSection" style="color:#191568;">Balances ↓</a></span></div>`;
summaryHtml += `<div class="info"><strong>Price:</strong> $<span id="main-user-price">...</span> / CRC</div>`;
// V1 Info
summaryHtml += `<div class="info"><strong>[V1] Status:</strong> ${v1Data.isHuman ? 'human' : (v1Data.isOrg ? 'org' : 'none')}</div>`;
if (v1Data.isHuman) {
const v1SupplyExact = ethers.utils.formatUnits(v1Data.totalSupply, 18);
const v1SupplyFmt = Number(v1SupplyExact).toLocaleString(undefined, {maximumFractionDigits: 2});
summaryHtml += `<div class="info"><strong>[V1] Total Supply:</strong> ${v1SupplyFmt} <button class="icon-btn" title="Copy exact value" onclick="copyToClipboard('${v1SupplyExact}')"><svg width="16" height="16" fill="none" xmlns="http://www.w3.org/2000/svg"><rect x="3" y="3" width="10" height="10" rx="2" stroke="#191568" stroke-width="1.5"/><rect x="6" y="6" width="7" height="7" rx="1.5" stroke="#191568" stroke-width="1.5"/></svg></button> <span id="v1-migration" style="color: #666;"></span></div>`;
summaryHtml += `<div class="info"><strong>[V1] Stopped:</strong> ${v1Data.stopped}</div>`;
const lastMintV1 = v1Data.lastTouched.eq(0) ? "N/A" : new Date(v1Data.lastTouched.toNumber() * 1000).toLocaleString();
summaryHtml += `<div class="info"><strong>[V1] Last Mint:</strong> ${lastMintV1}</div>`;
}
// V2 Info
summaryHtml += `<div class="info"><strong>[V2] Status:</strong> ${v2Data.isHuman ? 'human' : (v2Data.isOrg ? 'org' : (v2Data.isGroup ? 'group' : 'none'))}</div>`;
if (v2Data.isHuman || v2Data.isGroup) { // Assuming groups might have CRC too
summaryHtml += `<div class="info"><strong>[V2] CRC Amount:</strong> ${Number(ethers.utils.formatUnits(v2Data.crcAmount, 18)).toLocaleString(undefined, {maximumFractionDigits: 2})}</div>`;
const lastMintV2 = v2Data.ts1.eq(0) ? "N/A" : relativeTimeSince(v2Data.ts1.toNumber());
summaryHtml += `<div class="info"><strong>[V2] Last Mint:</strong> ${lastMintV2}</div>`;
summaryHtml += `<div class="info"><strong>[V2] Total Supply:</strong> ${Number(ethers.utils.formatUnits(v2Data.totalSupply, 18)).toLocaleString(undefined, {maximumFractionDigits: 2})}</div>`;
}
if (mainSCRC && mainSCRC !== ethers.constants.AddressZero) {
summaryHtml += `<div class="info"><strong>ERC20 (sCRC):</strong> <a class="address-link" href="https://gnosisscan.io/token/${mainSCRC}" target="_blank" rel="noopener noreferrer">${mainSCRC}</a>`;
summaryHtml += ` <a class="address-link" href="https://swap.cow.fi/#/100/swap/WXDAI/${mainSCRC}" target="_blank" rel="noopener noreferrer" title="Buy on CowSwap">🐄 Buy</a>`;
summaryHtml += `</div>`;
} else {
summaryHtml += `<div class="info"><strong>ERC20 (sCRC):</strong> N/A</div>`;
}
// Filter: active vs expired/untrusted
// For on-chain entries (trustLimit == -1), use expiry to determine active
// For indexer-only entries, use trustLimit
const nowMs = Date.now();
const activeTrustedAddresses = trustedAddressesData.filter(t => {
if (t.trustLimit === -1) {
// On-chain entry: check expiry
const expiryBN = ethers.BigNumber.from(t.expiry);
if (expiryBN.eq(indefiniteExpiry)) return true;
if (expiryBN.eq(0)) return false;
return Number(t.expiry) * 1000 >= nowMs;
}
return t.trustLimit > 0;
});
const totalInList = trustedAddressesData.length;
const activeCount = activeTrustedAddresses.length;
const expiredCount = totalInList - activeCount;
summaryHtml += `<div class="info"><strong>Trust Connections (V2 linked list):</strong> ${activeCount} active of ${totalInList} total${expiredCount > 0 ? ` (${expiredCount} expired/untrusted)` : ''}</div>`;
if (isGroup && balanceHolder !== inputAddress) {
const allHolders = [balanceHolder, ...extraTreasuryHolders];
const holderLinks = allHolders.map(h => `<a class="address-link" href="https://gnosisscan.io/address/${h}" target="_blank" rel="noopener noreferrer">${h}</a>`).join(', ');
const holderLabel = allHolders.length > 1 ? 'Treasuries' : 'Treasury';
summaryHtml += `<div class="info"><strong>${holderLabel}:</strong> ${holderLinks} (balances held here)</div>`;
}
// Compute totals for summary
const fmtNum = (bn) => Number(ethers.utils.formatUnits(bn, 18)).toLocaleString(undefined, {maximumFractionDigits: 2});
let totalV2Supply = ethers.BigNumber.from(0);
let activeHolds = ethers.BigNumber.from(0);
let expiredHolds = ethers.BigNumber.from(0);
const activeSet = new Set(activeTrustedAddresses);
for (const t of trustedAddressesData) {
if (activeSet.has(t)) {
totalV2Supply = totalV2Supply.add(t.v2TotalSupply);
activeHolds = activeHolds.add(t.userHolds);
} else {
expiredHolds = expiredHolds.add(t.userHolds);
}
}
const allHolds = activeHolds.add(expiredHolds);
const holdsLabel = isGroup ? 'Treasury' : 'User';
summaryHtml += `<div class="info"><strong>Total Receivable CRC:</strong> ${fmtNum(totalV2Supply)}</div>`;
summaryHtml += `<div class="info"><strong>Total ${holdsLabel} Holds:</strong> ${fmtNum(allHolds)}</div>`;
if (!expiredHolds.eq(0)) {
const expiredPct = allHolds.gt(0) ? (Number(ethers.utils.formatUnits(expiredHolds, 18)) / Number(ethers.utils.formatUnits(allHolds, 18)) * 100).toFixed(1) : '0';
summaryHtml += `<div class="info"><strong>Untrusted Holds:</strong> ${fmtNum(expiredHolds)} (${expiredPct}% of total holds)</div>`;
}
if (isGroup) {
const groupSupply = v2Data.totalSupply;
const diff = groupSupply.sub(allHolds);
const diffSign = diff.isNegative() ? '' : '+';
summaryHtml += `<div class="info"><strong>Group Total Supply:</strong> ${fmtNum(groupSupply)} <span style="color: #666;">(difference to treasury: ${diffSign}${fmtNum(diff)})</span></div>`;
if (treasuryTotalsIncomplete) {
summaryHtml += `<div class="info" style="color: #b00;">⚠ Some sub-treasury balances could not be fully loaded, so treasury holds may be understated.</div>`;
}
}
resultDiv.innerHTML = summaryHtml;
// Async update main user name and price
getProfileName(inputAddress).then(name => { document.getElementById('main-user-name').textContent = name; });
getPrice(mainSCRC).then(price => {
const el = document.getElementById('main-user-price');
if (el) el.textContent = (price === 'N/A' || price === 'Error') ? price : Number(price).toFixed(4);
});
// Async V1 migration check
if (v1Data.isHuman && !v1Data.totalSupply.eq(0)) {
(async () => {
try {
const v1TokenAddr = await v1HubContract.userToToken(inputAddress);
const v1Token = new ethers.Contract(v1TokenAddr, v1TokenABI, provider);
const migrationContract = new ethers.Contract(migrationContractAddress, migrationABI, provider);
const [migratedBal, convRate] = await Promise.all([
v1Token.balanceOf(migrationContractAddress),
migrationContract.convertFromV1ToDemurrage(ethers.utils.parseUnits("1", 18))
]);
const migratedNum = parseFloat(ethers.utils.formatUnits(migratedBal, 18));
const v2Equivalent = migratedNum * parseFloat(ethers.utils.formatUnits(convRate, 18));
const el = document.getElementById('v1-migration');
if (el) {
const migratedFmt = migratedNum.toLocaleString(undefined, {maximumFractionDigits: 2});
const v2Fmt = v2Equivalent.toLocaleString(undefined, {maximumFractionDigits: 2});
el.textContent = `(${migratedFmt} migrated to V2 = ${v2Fmt} CRC today)`;
}
} catch (err) {
console.warn('V1 migration check failed:', err);
}
})();
}
// 8) Display trusted addresses table
// For large lists (>100), skip per-row async calls (price, bot, balancer)
const isLargeList = trustedAddressesData.length > 100;
if (trustedAddressesData.length > 0) {
const trustAnchor = document.createElement("div");
trustAnchor.id = "trustSection";
trustAnchor.style.cssText = 'display:flex;align-items:center;gap:8px;margin-top:16px;';
const trustLabel = document.createElement("strong");
trustLabel.textContent = "Trust Connections";
trustLabel.style.fontSize = "1.1rem";
trustAnchor.appendChild(trustLabel);
const trustTopLink = document.createElement("a");
trustTopLink.href = "#topSection";
trustTopLink.style.cssText = "font-size:0.8rem;color:#191568;";
trustTopLink.textContent = "\u2191 Top";
trustAnchor.appendChild(trustTopLink);
const trustTokenLink = document.createElement("a");
trustTokenLink.href = "#tokenBalancesSection";
trustTokenLink.style.cssText = "font-size:0.8rem;color:#191568;";
trustTokenLink.textContent = "Token Balances \u2193";
trustAnchor.appendChild(trustTokenLink);
resultDiv.appendChild(trustAnchor);
const table = document.createElement("table");
const thead = document.createElement("thead");
const headerRow = document.createElement("tr");
const holdsHeader = isGroup ? 'Treasury Holds' : 'User Holds';
const headers = isLargeList
? ['Trusted Address', 'Expiry', 'V1 State', 'V2 State', 'V2 Supply', holdsHeader, 'ERC20 (sCRC)']
: ['Trusted Address', 'Price', 'Expiry', 'V1 State', 'V2 State', 'V2 Supply', holdsHeader, 'Bot Status', 'ERC20 (sCRC)'];
const sortableColumns = ['V2 Supply', holdsHeader];
const sortableThs = {};
headers.forEach((headerText, colIdx) => {
const th = document.createElement("th");
th.textContent = headerText;
if (sortableColumns.includes(headerText)) {
th.style.cursor = 'pointer';
th.title = 'Click to sort';
th.dataset.colName = headerText;
th.dataset.sortDir = 'none';
th.innerHTML = headerText + ' <span style="opacity:0.4">\u21C5</span>';
sortableThs[headerText] = th;
th.addEventListener('click', () => {
const tbody = table.querySelector('tbody');
const rows = Array.from(tbody.querySelectorAll('tr'));
const newDir = th.dataset.sortDir === 'desc' ? 'asc' : 'desc';
// Reset all sortable headers
for (const [name, sth] of Object.entries(sortableThs)) {
sth.innerHTML = name + ' <span style="opacity:0.4">\u21C5</span>';
sth.dataset.sortDir = 'none';
}
th.dataset.sortDir = newDir;
th.innerHTML = headerText + (newDir === 'desc' ? ' \u25BC' : ' \u25B2');
const sortKey = 'sort' + colIdx;
rows.sort((a, b) => {
const va = parseFloat(a.dataset[sortKey]) || 0;
const vb = parseFloat(b.dataset[sortKey]) || 0;
return newDir === 'desc' ? vb - va : va - vb;
});
rows.forEach(r => tbody.appendChild(r));
});
}
headerRow.appendChild(th);
});
thead.appendChild(headerRow);
table.appendChild(thead);
// Filter controls
const filterDiv = document.createElement("div");
filterDiv.style.cssText = "margin: 12px 0; display: flex; flex-wrap: wrap; gap: 8px; align-items: center; font-size: 0.9rem;";
const activeFilters = { status: 'all', v1: 'all', v2: 'all' };
function createFilterGroup(label, key, options) {
const group = document.createElement('span');
group.innerHTML = `<strong>${label}:</strong> `;
options.forEach(([value, text]) => {
const btn = document.createElement('button');
btn.textContent = text;
btn.dataset.filterKey = key;
btn.dataset.filterValue = value;
btn.style.cssText = 'padding: 3px 10px; border: 1px solid #ccc; border-radius: 4px; cursor: pointer; font-size: 0.85rem; background: ' + (value === 'all' ? '#191568; color: #fff;' : '#fff; color: #191568;');
btn.addEventListener('click', () => {
activeFilters[key] = value;
group.querySelectorAll('button').forEach(b => {
b.style.background = b.dataset.filterValue === value ? '#191568' : '#fff';
b.style.color = b.dataset.filterValue === value ? '#fff' : '#191568';
});
applyFilters();
});
group.appendChild(btn);
group.appendChild(document.createTextNode(' '));
});
return group;
}
filterDiv.appendChild(createFilterGroup('Status', 'status', [['all', 'All'], ['active', 'Active'], ['expired', 'Expired']]));
filterDiv.appendChild(createFilterGroup('V1', 'v1', [['all', 'All'], ['human', 'Human'], ['org', 'Org'], ['none', 'None']]));
filterDiv.appendChild(createFilterGroup('V2', 'v2', [['all', 'All'], ['human', 'Human'], ['org', 'Org'], ['group', 'Group'], ['none', 'None']]));
resultDiv.appendChild(filterDiv);
function applyFilters() {
const rows = tbody.querySelectorAll('tr');
let visible = 0;
rows.forEach(row => {
const st = row.dataset.status || '';
const v1s = row.dataset.v1state || '';
const v2s = row.dataset.v2state || '';
const show = (activeFilters.status === 'all' || st === activeFilters.status)
&& (activeFilters.v1 === 'all' || v1s === activeFilters.v1)
&& (activeFilters.v2 === 'all' || v2s === activeFilters.v2);
row.style.display = show ? '' : 'none';
if (show) visible++;
});
filterCount.textContent = `${visible} / ${rows.length}`;
}
const filterCount = document.createElement('span');
filterCount.style.cssText = 'margin-left: 8px; color: #666;';
filterCount.textContent = `${trustedAddressesData.length} / ${trustedAddressesData.length}`;
filterDiv.appendChild(filterCount);
const tbody = document.createElement("tbody");
const activeSetForTable = new Set(activeTrustedAddresses);
for (let i = 0; i < trustedAddressesData.length; i++) {
const addrData = trustedAddressesData[i];
const isActive = activeSetForTable.has(addrData);
const row = document.createElement("tr");
row.dataset.status = isActive ? 'active' : 'expired';
if (!isActive) {
row.style.opacity = '0.5';
}
const trustedAddr = addrData.trustedAddress;
const trustedErc20 = erc20Map[trustedAddr.toLowerCase()]?.demurragedERC20; // actual sCRC token
// Trusted Address Cell (Name + Address + Copy/Link)