-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
705 lines (588 loc) · 28.7 KB
/
script.js
File metadata and controls
705 lines (588 loc) · 28.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
// TGE Pressure Calculator
// Sharp. Ruthless. Professional.
class TGECalculator {
constructor() {
this.form = document.getElementById('calculatorForm');
this.resultsSection = document.getElementById('results');
this.advancedToggle = document.getElementById('advancedToggle');
this.advancedSection = document.getElementById('advancedSection');
this.savedCalculations = this.loadComparisons();
this.init();
this.loadFromURL();
this.loadSavedData();
this.renderComparisons();
}
init() {
// Form submit
this.form.addEventListener('submit', (e) => {
e.preventDefault();
if (this.validateForm()) {
// Button press feedback
const btn = document.getElementById('calculateBtn');
btn.classList.add('firing');
setTimeout(() => btn.classList.remove('firing'), 160);
this.calculatePressure();
}
});
// Advanced toggle
this.advancedToggle.addEventListener('click', () => this.toggleAdvanced());
// Real-time validation on required inputs
this.form.querySelectorAll('input[required]').forEach(input => {
input.addEventListener('blur', () => this.validateInput(input));
});
// Breakdown validation
['airdrop', 'publicSale', 'liquidity', 'team', 'other'].forEach(id => {
const el = document.getElementById(id);
if (el) el.addEventListener('input', () => this.validateBreakdown());
});
// Action buttons
document.getElementById('saveBtn').addEventListener('click', () => this.saveCalculation());
document.getElementById('shareBtn').addEventListener('click', () => this.shareCalculation());
document.getElementById('shareXBtn').addEventListener('click', () => this.shareOnX());
document.getElementById('clearBtn').addEventListener('click', () => this.clearForm());
document.getElementById('exportBtn').addEventListener('click', () => this.exportToPNG());
document.getElementById('compareBtn').addEventListener('click', () => this.addToComparison());
// Chart resize
this.initChartResize();
}
// ─── Advanced section ─────────────────────────────────────
toggleAdvanced() {
const isOpen = this.advancedSection.classList.contains('open');
this.advancedSection.classList.toggle('open', !isOpen);
this.advancedToggle.setAttribute('aria-expanded', String(!isOpen));
this.advancedSection.setAttribute('aria-hidden', String(isOpen));
this.advancedToggle.querySelector('.toggle-label').textContent =
isOpen ? 'Breakdown by category' : 'Hide breakdown';
}
// ─── Validation ───────────────────────────────────────────
validateInput(input) {
const value = parseFloat(input.value);
const errorEl = document.getElementById(input.id + 'Error');
let isValid = true;
let errorMsg = '';
if (input.required && (!input.value || isNaN(value))) {
isValid = false;
errorMsg = 'Required';
} else if (!isNaN(value) && value < 0) {
isValid = false;
errorMsg = 'Cannot be negative';
} else if (input.id === 'unlockedPercent' && value > 100) {
isValid = false;
errorMsg = 'Max 100%';
} else if (['airdrop','publicSale','liquidity','team','other'].includes(input.id) && value > 100) {
isValid = false;
errorMsg = 'Max 100%';
} else if (input.id === 'fdv' && value > 1e12) {
isValid = false;
errorMsg = 'Unreasonably high';
}
input.classList.toggle('error', !isValid);
if (errorEl) {
errorEl.textContent = errorMsg;
errorEl.classList.toggle('show', !isValid);
}
return isValid;
}
validateForm() {
let isValid = true;
this.form.querySelectorAll('input[required]').forEach(input => {
if (!this.validateInput(input)) isValid = false;
});
return isValid;
}
validateBreakdown() {
const airdrop = parseFloat(document.getElementById('airdrop').value) || 0;
const publicSale = parseFloat(document.getElementById('publicSale').value) || 0;
const liquidity = parseFloat(document.getElementById('liquidity').value) || 0;
const team = parseFloat(document.getElementById('team').value) || 0;
const other = parseFloat(document.getElementById('other').value) || 0;
const unlocked = parseFloat(document.getElementById('unlockedPercent').value) || 0;
const total = airdrop + publicSale + liquidity + team + other;
const warning = document.getElementById('breakdownWarning');
const mismatch = total > 0 && Math.abs(total - unlocked) > 1;
warning.classList.toggle('show', mismatch);
if (mismatch) {
warning.textContent = `Breakdown total (${total.toFixed(1)}%) ≠ % Unlocked (${unlocked.toFixed(1)}%)`;
warning.setAttribute('aria-hidden', 'false');
} else {
warning.setAttribute('aria-hidden', 'true');
}
return !mismatch;
}
// ─── Core calculation ─────────────────────────────────────
calculatePressure() {
const totalSupply = parseFloat(document.getElementById('totalSupply').value);
const fdv = parseFloat(document.getElementById('fdv').value);
const unlockedPercent= parseFloat(document.getElementById('unlockedPercent').value);
const expectedPrice = parseFloat(document.getElementById('expectedPrice').value) || 0;
const airdrop = parseFloat(document.getElementById('airdrop').value) || 0;
const publicSale = parseFloat(document.getElementById('publicSale').value) || 0;
const liquidity = parseFloat(document.getElementById('liquidity').value) || 0;
const team = parseFloat(document.getElementById('team').value) || 0;
const other = parseFloat(document.getElementById('other').value) || 0;
const hasBreakdown = (airdrop + publicSale + liquidity + team + other) > 0;
// Weighted selling pressure
let effectivePressure;
if (hasBreakdown) {
effectivePressure = (airdrop * 1.0) + (publicSale * 1.0) + (team * 0.3) + (other * 0.2) + (liquidity * 0);
} else {
effectivePressure = unlockedPercent * 0.8;
}
const initialMcap = (unlockedPercent / 100) * fdv;
const potentialSell= (effectivePressure / 100) * fdv;
const mcfdvRatio = unlockedPercent;
// Risk dimensions
const dumpRisk = Math.min(effectivePressure * 2, 100);
const dilutionRisk = Math.max(0, 100 - unlockedPercent);
const liquidityScore= Math.min(liquidity * 2, 100);
// Verdict
let verdict, verdictClass;
if (effectivePressure > 40 || unlockedPercent > 60) {
verdict = 'HIGH';
verdictClass = 'verdict-high';
} else if (effectivePressure >= 20 || unlockedPercent >= 30) {
verdict = 'MEDIUM';
verdictClass = 'verdict-medium';
} else {
verdict = 'LOW';
verdictClass = 'verdict-low';
}
// Description
const description = this.buildDescription(verdict, effectivePressure, unlockedPercent, airdrop, publicSale, team, liquidity, fdv, hasBreakdown);
// Update DOM — set content before reveal
const verdictBlock = document.getElementById('verdictBlock');
verdictBlock.className = `verdict-block ${verdictClass}`;
document.getElementById('verdictRating').textContent = verdict;
document.getElementById('verdictDescription').textContent = description;
document.getElementById('verdictPressureLine').textContent =
hasBreakdown ? `Weighted pressure: ${effectivePressure.toFixed(1)}%` : '';
// Price context
const priceContext = document.getElementById('priceContext');
if (expectedPrice > 0) {
const tokensToSell = (effectivePressure / 100) * totalSupply;
priceContext.innerHTML =
`<strong>At $${expectedPrice.toFixed(4)}/token —</strong> ` +
`~${this.formatLargeNumber(tokensToSell)} tokens likely sold, ` +
`worth ${this.formatCurrency(tokensToSell * expectedPrice)}`;
priceContext.classList.add('show');
} else {
priceContext.classList.remove('show');
}
// Chart
this.createUnlockChart(airdrop, publicSale, liquidity, team, other);
// Show section, then fire the kinetic sequence
this.showResults(() => {
this.animateVerdict(verdictClass);
this.animateMetrics(potentialSell, unlockedPercent, initialMcap, mcfdvRatio);
this.animateRiskBars(dumpRisk, dilutionRisk, liquidityScore);
});
// Auto-save
this.autoSave();
}
buildDescription(verdict, effectivePressure, unlocked, airdrop, publicSale, team, liquidity, fdv, hasBreakdown) {
const parts = [];
if (verdict === 'HIGH') {
if (effectivePressure > 40) {
parts.push(`Effective selling pressure is ${effectivePressure.toFixed(1)}% — a substantial portion of FDV will hit the market at open.`);
} else {
parts.push(`${unlocked.toFixed(1)}% of supply unlocks immediately. High float creates inflation risk from day one.`);
}
} else if (verdict === 'MEDIUM') {
parts.push(`Moderate selling pressure at ${effectivePressure.toFixed(1)}%. Monitor initial price action closely.`);
} else {
parts.push(`Effective pressure is ${effectivePressure.toFixed(1)}%. Most supply remains locked — healthy vesting structure.`);
}
if (hasBreakdown) {
const highPct = airdrop + publicSale;
if (highPct > 25) parts.push(`Airdrop + public sale (${highPct.toFixed(1)}%) will sell near-immediately.`);
if (team > 0) parts.push(`Team tokens unlocked at TGE — a credibility red flag.`);
if (liquidity > 50) parts.push(`Liquidity allocation (${liquidity.toFixed(1)}%) provides meaningful cushion.`);
}
if (unlocked < 10 && fdv > 1e8) {
parts.push(`Low float + high FDV: future unlock events will be severe.`);
}
return parts.join(' ');
}
showResults(onVisible) {
const el = this.resultsSection;
const reduced = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
el.style.display = 'block';
el.classList.add('visible');
void el.offsetHeight;
if (reduced) {
onVisible?.();
el.scrollIntoView({ behavior: 'instant', block: 'nearest' });
return;
}
el.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
// Small delay lets the scroll settle before the impact hits
setTimeout(() => onVisible?.(), 180);
}
// ─── Kinetic sequence ─────────────────────────────────────
animateVerdict(verdictClass) {
const reduced = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
const ratingEl = document.getElementById('verdictRating');
const blockEl = document.getElementById('verdictBlock');
const descEl = document.getElementById('verdictDescription');
const lineEl = document.getElementById('verdictPressureLine');
if (reduced) return;
// 1. Flash the block — brief color burst then settle
blockEl.animate([
{ filter: 'brightness(2.2)', offset: 0 },
{ filter: 'brightness(1)', offset: 0.25 },
{ filter: 'brightness(1)', offset: 1 }
], { duration: 500, easing: 'ease-out', fill: 'none' });
// 2. Verdict text slams down from oversized
ratingEl.animate([
{ transform: 'scale(1.55) translateY(-6px)', opacity: 0, offset: 0 },
{ transform: 'scale(1.04) translateY(2px)', opacity: 1, offset: 0.45 },
{ transform: 'scale(0.99) translateY(0px)', opacity: 1, offset: 0.65 },
{ transform: 'scale(1) translateY(0)', opacity: 1, offset: 1 }
], {
duration: 480,
easing: 'cubic-bezier(0.22, 1, 0.36, 1)',
fill: 'backwards'
});
// 3. Description fades up after the slam
descEl.animate([
{ opacity: 0, transform: 'translateY(6px)' },
{ opacity: 1, transform: 'translateY(0)' }
], { duration: 340, delay: 260, easing: 'ease-out', fill: 'backwards' });
lineEl.animate([
{ opacity: 0, transform: 'translateY(4px)' },
{ opacity: 1, transform: 'translateY(0)' }
], { duration: 280, delay: 360, easing: 'ease-out', fill: 'backwards' });
}
animateMetrics(potentialSell, unlockedPercent, initialMcap, mcfdvRatio) {
const reduced = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
const metrics = [
{ id: 'dollarAmount', end: potentialSell, isCurrency: true, suffix: '' },
{ id: 'circulatingPercent',end: unlockedPercent, isCurrency: false, suffix: '%' },
{ id: 'initialMcap', end: initialMcap, isCurrency: true, suffix: '' },
{ id: 'mcfdvRatio', end: mcfdvRatio, isCurrency: false, suffix: '%' },
];
metrics.forEach(({ id, end, isCurrency, suffix }, i) => {
const el = document.getElementById(id);
if (!el) return;
const delay = i * 80; // stagger: 0, 80, 160, 240ms
if (!reduced) {
// Slide up entrance
el.animate([
{ opacity: 0, transform: 'translateY(10px)' },
{ opacity: 1, transform: 'translateY(0)' }
], {
duration: 320,
delay,
easing: 'cubic-bezier(0.22, 1, 0.36, 1)',
fill: 'backwards'
});
}
// Count up — starts after entrance delay
setTimeout(() => {
this.countUp(el, 0, end, 800, isCurrency, suffix);
}, reduced ? 0 : delay + 60);
});
}
animateRiskBars(dumpRisk, dilutionRisk, liquidityScore) {
const reduced = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
const bars = [
{ barId: 'dumpRiskBar', valId: 'dumpRiskValue', pct: dumpRisk, delay: 320 },
{ barId: 'dilutionRiskBar',valId: 'dilutionRiskValue',pct: dilutionRisk, delay: 420 },
{ barId: 'liquidityBar', valId: 'liquidityValue', pct: liquidityScore,delay: 520 },
];
bars.forEach(({ barId, valId, pct, delay }) => {
const bar = document.getElementById(barId);
const val = document.getElementById(valId);
if (!bar || !val) return;
const run = () => {
val.textContent = `${pct.toFixed(0)}%`;
if (reduced) {
bar.style.width = `${pct}%`;
return;
}
// Spring-like: overshoot slightly then settle
bar.animate([
{ width: '0%', offset: 0 },
{ width: `${pct * 1.06}%`, offset: 0.7 },
{ width: `${pct * 0.98}%`, offset: 0.85 },
{ width: `${pct}%`, offset: 1 }
], {
duration: 700,
easing: 'cubic-bezier(0.22, 1, 0.36, 1)',
fill: 'forwards'
});
};
reduced ? run() : setTimeout(run, delay);
});
}
// ─── Number counter ───────────────────────────────────────
countUp(el, start, end, duration, isCurrency = false, suffix = '') {
const startTime = performance.now();
const tick = (now) => {
const elapsed = now - startTime;
const progress = Math.min(elapsed / duration, 1);
const eased = 1 - Math.pow(1 - progress, 4); // ease-out-quart
const current = start + (end - start) * eased;
el.textContent = isCurrency
? this.formatCurrency(current)
: current.toFixed(2) + suffix;
if (progress < 1) requestAnimationFrame(tick);
};
requestAnimationFrame(tick);
}
// ─── Chart ────────────────────────────────────────────────
createUnlockChart(airdrop, publicSale, liquidity, team, other) {
const section = document.getElementById('chartSection');
const canvas = document.getElementById('unlockChart');
const categories = [
{ name: 'Airdrop', value: airdrop, color: 'oklch(62% 0.18 22)' },
{ name: 'Public Sale', value: publicSale, color: 'oklch(74% 0.15 50)' },
{ name: 'Team', value: team, color: 'oklch(76% 0.16 65)' },
{ name: 'Other', value: other, color: 'oklch(65% 0.10 220)' },
{ name: 'Liquidity', value: liquidity, color: 'oklch(65% 0.13 155)' }
].filter(c => c.value > 0);
if (categories.length === 0) {
section.style.display = 'none';
return;
}
section.style.display = 'block';
setTimeout(() => {
const dpr = window.devicePixelRatio || 1;
const cssWidth = section.offsetWidth || 600;
const cssHeight = 180;
canvas.style.width = cssWidth + 'px';
canvas.style.height = cssHeight + 'px';
canvas.width = cssWidth * dpr;
canvas.height = cssHeight * dpr;
const ctx = canvas.getContext('2d');
ctx.scale(dpr, dpr);
ctx.clearRect(0, 0, cssWidth, cssHeight);
const gap = 8;
const barW = (cssWidth - gap * (categories.length - 1)) / categories.length;
const maxVal = Math.max(...categories.map(c => c.value));
const availH = cssHeight - 54;
categories.forEach((cat, i) => {
const x = i * (barW + gap);
const barH = (cat.value / maxVal) * availH;
const y = availH - barH;
ctx.fillStyle = cat.color;
ctx.fillRect(x, y, barW, barH);
// Value label above bar
ctx.fillStyle = 'oklch(92% 0.008 60)';
ctx.font = `700 13px "Barlow Condensed", sans-serif`;
ctx.textAlign = 'center';
ctx.fillText(`${cat.value.toFixed(1)}%`, x + barW / 2, y - 6);
// Category label below
ctx.fillStyle = 'oklch(55% 0.010 60)';
ctx.font = `600 11px "Mada", sans-serif`;
ctx.fillText(cat.name, x + barW / 2, availH + 20);
});
}, 80);
}
initChartResize() {
let timer;
window.addEventListener('resize', () => {
clearTimeout(timer);
timer = setTimeout(() => {
const section = document.getElementById('chartSection');
if (section && section.style.display !== 'none') {
const data = this.getFormData();
if (data) {
this.createUnlockChart(
parseFloat(data.airdrop) || 0,
parseFloat(data.publicSale) || 0,
parseFloat(data.liquidity) || 0,
parseFloat(data.team) || 0,
parseFloat(data.other) || 0
);
}
}
}, 200);
});
}
// ─── Persistence ──────────────────────────────────────────
saveCalculation() {
localStorage.setItem('tge-calc-save', JSON.stringify(this.getFormData()));
this.showToast('Saved');
}
autoSave() {
localStorage.setItem('tge-calc-autosave', JSON.stringify(this.getFormData()));
}
loadSavedData() {
if (new URLSearchParams(location.search).size) return; // URL params take priority
const saved = localStorage.getItem('tge-calc-autosave');
if (!saved) return;
try {
this.populateForm(JSON.parse(saved));
} catch (_) {}
}
shareCalculation() {
const data = this.getFormData();
const params = new URLSearchParams();
Object.entries(data).forEach(([k, v]) => { if (v) params.set(k, v); });
const url = `${location.origin}${location.pathname}?${params}`;
navigator.clipboard.writeText(url).then(() => {
this.showToast('Link copied');
}).catch(() => {
prompt('Share this URL:', url);
});
}
shareOnX() {
const name = document.getElementById('projectName').value || 'this project';
const rating = document.getElementById('verdictRating').textContent;
const sell = document.getElementById('dollarAmount').textContent;
const text = `Analyzed ${name}'s TGE selling pressure\n\nVerdict: ${rating}\nSell pressure: ${sell}\n\n${location.href}`;
window.open(`https://twitter.com/intent/tweet?text=${encodeURIComponent(text)}`, '_blank', 'width=550,height=420');
}
exportToPNG() {
this.showToast('Opening print dialog…');
setTimeout(() => window.print(), 800);
}
// ─── Comparison ───────────────────────────────────────────
addToComparison() {
const rating = document.getElementById('verdictRating').textContent;
if (!rating || rating === '—') {
this.showToast('Run analysis first');
return;
}
const data = {
...this.getFormData(),
rating,
sellPressure: document.getElementById('dollarAmount').textContent,
ts: Date.now()
};
this.savedCalculations.push(data);
if (this.savedCalculations.length > 3) this.savedCalculations.shift();
localStorage.setItem('tge-calc-comparisons', JSON.stringify(this.savedCalculations));
this.renderComparisons();
this.showToast('Added to comparison');
}
loadComparisons() {
try {
return JSON.parse(localStorage.getItem('tge-calc-comparisons') || '[]');
} catch (_) { return []; }
}
renderComparisons() {
const section = document.getElementById('comparisonSection');
const grid = document.getElementById('comparisonGrid');
const count = document.getElementById('comparisonCount');
if (this.savedCalculations.length === 0) {
section.classList.remove('show');
return;
}
section.classList.add('show');
count.textContent = `${this.savedCalculations.length} / 3`;
grid.innerHTML = '';
this.savedCalculations.forEach((calc, i) => {
const ratingClass = (calc.rating || '').toLowerCase();
const card = document.createElement('div');
card.className = 'comparison-card';
card.innerHTML = `
<button class="comparison-remove" onclick="calculator.removeComparison(${i})" aria-label="Remove comparison">×</button>
<div class="comparison-card-name">${calc.projectName || `Project ${i + 1}`}</div>
<div class="comparison-card-rating ${ratingClass}">${calc.rating}</div>
<div class="comparison-stat">
<span>Sell pressure</span>
<span class="comparison-stat-val">${calc.sellPressure}</span>
</div>
<div class="comparison-stat">
<span>% Unlocked</span>
<span class="comparison-stat-val">${calc.unlockedPercent}%</span>
</div>
<div class="comparison-stat">
<span>FDV</span>
<span class="comparison-stat-val">${this.formatCurrency(parseFloat(calc.fdv) || 0)}</span>
</div>
`;
grid.appendChild(card);
});
}
removeComparison(i) {
this.savedCalculations.splice(i, 1);
localStorage.setItem('tge-calc-comparisons', JSON.stringify(this.savedCalculations));
this.renderComparisons();
}
// ─── URL loading ──────────────────────────────────────────
loadFromURL() {
const params = new URLSearchParams(location.search);
if (!params.size) return;
const data = {};
params.forEach((v, k) => { data[k] = v; });
this.populateForm(data);
if (data.totalSupply && data.fdv && data.unlockedPercent) {
setTimeout(() => {
if (this.validateForm()) this.calculatePressure();
}, 100);
}
}
// ─── Form helpers ─────────────────────────────────────────
getFormData() {
return {
projectName: document.getElementById('projectName').value,
totalSupply: document.getElementById('totalSupply').value,
fdv: document.getElementById('fdv').value,
unlockedPercent:document.getElementById('unlockedPercent').value,
expectedPrice: document.getElementById('expectedPrice').value,
airdrop: document.getElementById('airdrop').value,
publicSale: document.getElementById('publicSale').value,
liquidity: document.getElementById('liquidity').value,
team: document.getElementById('team').value,
other: document.getElementById('other').value
};
}
populateForm(data) {
Object.entries(data).forEach(([k, v]) => {
const el = document.getElementById(k);
if (el && v !== undefined && v !== null) el.value = v;
});
const hasAdvanced = ['airdrop','publicSale','liquidity','team','other'].some(k => data[k]);
if (hasAdvanced && !this.advancedSection.classList.contains('open')) {
this.toggleAdvanced();
}
}
clearForm() {
if (!confirm('Clear all inputs and results?')) return;
this.form.reset();
// Hide results
const el = this.resultsSection;
el.classList.remove('revealed');
setTimeout(() => {
el.classList.remove('visible');
el.style.display = 'none';
}, 400);
// Clear errors
this.form.querySelectorAll('input').forEach(input => {
input.classList.remove('error');
const err = document.getElementById(input.id + 'Error');
if (err) err.classList.remove('show');
});
document.getElementById('verdictBlock').className = 'verdict-block';
localStorage.removeItem('tge-calc-autosave');
this.showToast('Cleared');
}
// ─── Utilities ────────────────────────────────────────────
formatCurrency(value) {
if (value >= 1e9) return '$' + (value / 1e9).toFixed(2) + 'B';
if (value >= 1e6) return '$' + (value / 1e6).toFixed(2) + 'M';
if (value >= 1e3) return '$' + (value / 1e3).toFixed(1) + 'K';
return '$' + value.toFixed(2);
}
formatLargeNumber(value) {
if (value >= 1e9) return (value / 1e9).toFixed(2) + 'B';
if (value >= 1e6) return (value / 1e6).toFixed(2) + 'M';
if (value >= 1e3) return (value / 1e3).toFixed(1) + 'K';
return value.toFixed(0);
}
showToast(msg) {
const toast = document.getElementById('toast');
toast.textContent = msg;
toast.classList.add('show');
clearTimeout(this._toastTimer);
this._toastTimer = setTimeout(() => toast.classList.remove('show'), 2800);
}
}
// Boot
let calculator;
document.addEventListener('DOMContentLoaded', () => {
calculator = new TGECalculator();
});