-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscript.js
342 lines (304 loc) · 13.8 KB
/
script.js
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
// Check if the screen width is 768 pixels or less
const isMobile = () => window.innerWidth <= 768;
// Initial setup
const totalSupply = 21000000000;
const blocksPerYear = 525600;
const initialCirculatingSupply = 2520000000;
const simulationYears = 100; // Simulation duration in years
const kOriginal = 22;
let labels = [];
let datasets = [];
let originalCirculatingSupply = initialCirculatingSupply;
const curves = [
'GREY curve',
'RED Curve',
'GREEN Curve',
'Yellow Curve',
];
const colors = [
'rgb(128, 128, 128)',
'rgb(200, 90, 90)',
'rgb(90, 200, 90)',
'rgb(255, 215, 0)',
];
// Adjusted start year and month for label generation
const startYear = 2018;
const startMonth = 4; // April
const startDate = 14; // 14th
// Generate labels for each year, starting from April 14th, 2018
for (let year = startYear; year < startYear + simulationYears; year++) {
labels.push(`April ${year}`);
}
// Function to generate block rewards
function generateBlockRewards(k, circulatingSupply, labels, startYear = 2018, startPercentage = 0) {
return labels.map((label, index) => {
let year = parseInt(label);
if (year < startYear) return null;
if (index === 0 || year === startYear) {
let initialRate = startPercentage / 100;
let blockReward = circulatingSupply * initialRate;
circulatingSupply += blockReward * blocksPerYear;
return circulatingSupply;
} else {
for(let i = 0; i < blocksPerYear; i++) {
let blockReward = (totalSupply - circulatingSupply) / Math.pow(2, k);
circulatingSupply += blockReward;
}
return circulatingSupply;
}
}).filter(n => n);
}
// Generate original emission curve
let blockRewardsOriginal = generateBlockRewards(kOriginal, originalCirculatingSupply, labels);
datasets.push({
label: `${curves[0]} (No Change, Current Curve)`,
data: blockRewardsOriginal,
fill: false,
borderColor: colors[0], // Green color
tension: 0.1,
pointRadius: isMobile() ? 0 : 1 // Hide the data points
});
// Add event listeners to input fields for automatic chart update
const timeoutDuration = 500;
let updateTimeout;
document.getElementById('inputYear').addEventListener('input', () => {
clearTimeout(updateTimeout);
updateTimeout = setTimeout(updateCurves, timeoutDuration);
});
document.getElementById('inputPercentage').addEventListener('input', () => {
clearTimeout(updateTimeout);
updateTimeout = setTimeout(updateCurves, timeoutDuration);
});
window.addEventListener('resize', () => {
clearTimeout(updateTimeout);
updateTimeout = setTimeout(updateCurves, timeoutDuration);
});
// Function to generate a curve with emission reduction
function generateSecondCurveWithEmissionReduction(startingSupply, startYear, initialPercentage, emissionReduction) {
let supply = startingSupply;
let percentage = initialPercentage;
let data = new Array(labels.length).fill(NaN); // Initialize with NaN for all years
for (let i = startYear - 2018; i < labels.length; i++) {
data[i] = supply;
if (i != startYear - 2018) {
percentage *= ((100 - emissionReduction) / 100);
}
supply += supply * (percentage / 100);
}
return { finalSupply: supply, data: data.map((val) => val > 21e9 ? 21e9 : val) };
}
// Function to find the best emission reduction percentage
function findBestEmissionReduction(startingSupply, startYear, initialPercentage) {
let closest = { emissionReduction: 0, finalSupply: Number.MAX_VALUE, difference: Number.MAX_VALUE };
for (let reduction = 0; reduction <= 100; reduction += 0.01) { // Increment by 0.01% for finer granularity
const { finalSupply } = generateSecondCurveWithEmissionReduction(startingSupply, startYear, initialPercentage, reduction);
const difference = Math.abs(finalSupply - totalSupply);
if (difference < closest.difference) {
closest = { emissionReduction: reduction, finalSupply, difference };
}
}
return closest.emissionReduction;
}
function addCurve(startingSupply, inputYear, percentage, name, color) {
const bestEmissionReduction = findBestEmissionReduction(startingSupply, inputYear, percentage);
let { data: blockRewardsNewCurve } = generateSecondCurveWithEmissionReduction(
startingSupply, inputYear, percentage, bestEmissionReduction);
// const labelWithEmissionReduction = `${name} (Yearly Emission Reduction: ${bestEmissionReduction.toFixed(2)}%)`;
// Adjust the label based on the curve name
let labelWithEmissionReduction;
switch (name) {
case 'GREEN Curve':
labelWithEmissionReduction = `${name} (- A - 525 NIM Initial Reward/Block)`;
break;
case 'RED Curve':
labelWithEmissionReduction = `${name} (- B - 4,17% Initial 'Inflation')`;
break;
case 'Yellow Curve':
labelWithEmissionReduction = `${name} (Your Curve)`;
break;
default:
labelWithEmissionReduction = `${name} (Yearly Emission Reduction: ${bestEmissionReduction.toFixed(2)}%)`;
}
if (datasets[curves.indexOf(name)]) {
datasets[curves.indexOf(name)].data = blockRewardsNewCurve;
datasets[curves.indexOf(name)].label = labelWithEmissionReduction;
} else {
datasets.push({
label: labelWithEmissionReduction,
data: blockRewardsNewCurve,
fill: false,
borderColor: color,
tension: 0.1,
pointRadius: isMobile() ? 0 : 1, // Hide the data points
});
}
}
// Function to update the chart with a new curve
function updateCurves() {
const inputYear = parseInt(document.getElementById('inputYear').value);
const inputPercentage = parseFloat(document.getElementById('inputPercentage').value);
const startingSupplyIndex = inputYear - 2018;
const startingSupply = blockRewardsOriginal[startingSupplyIndex] || originalCirculatingSupply;
// Update datasets with new curve
// datasets = datasets.slice(0, 1); // Keep only the original dataset
// Add the predefined curves first
addCurve(startingSupply, inputYear, 4.17, curves[1], colors[1]); // Blue
const initialRewardRate = (525 * 60 * 24 * 365) / startingSupply * 100; // Convert 525 per minute to annual percentage of the starting supply
addCurve(startingSupply, inputYear, initialRewardRate, curves[2], colors[2]); // Red
// Now add "Your Curve" to ensure it is the last one
addCurve(startingSupply, inputYear, inputPercentage, curves[3], colors[3]); // Golden color
// Redraw chart with updated datasets
drawChart();
}
// Function to draw the chart
function drawChart() {
const ctx = document.getElementById('emissionCurve').getContext('2d');
if (window.emissionChart) {
window.emissionChart.data.labels = labels;
window.emissionChart.data.datasets = datasets.map(dataset => ({
...dataset,
pointRadius: isMobile() ? 0 : 2 // Hide the data points on mobile
}));
// Adjust font size for mobile
window.emissionChart.options.plugins.legend.labels.font.size = isMobile() ? 10 : 14; // Example sizes, adjust as needed
window.emissionChart.options.scales.x.ticks.font.size = isMobile() ? 10 : 14; // Adjust x-axis font size
window.emissionChart.options.scales.y.ticks.font.size = isMobile() ? 10 : 14; // Adjust y-axis font size
window.emissionChart.options.aspectRatio = isMobile() ? 1 : 2; // Adjust y-axis font size
window.emissionChart.options.scales.y.display = isMobile() ? false : true;
window.emissionChart.update();
} else {
window.emissionChart = new Chart(ctx, {
type: 'line',
data: {
labels: labels,
datasets: datasets.map(dataset => ({
...dataset,
pointRadius: isMobile() ? 0 : 2 // Hide the data points on mobile
}))
},
options: {
animation: false,
aspectRatio: isMobile() ? 1 : 2,
scales: {
y: {
display: isMobile() ? false : true,
ticks: {
font: {
size: isMobile() ? 10 : 14, // Reduce font size by 30% on mobile
},
},
},
x: {
ticks: {
font: {
size: isMobile() ? 10 : 14, // Reduce font size by 30% on mobile
},
},
}
},
plugins: {
legend: {
labels: {
font: {
size: isMobile() ? 10 : 14, // Reduce font size by 30% on mobile
},
},
},
tooltip: {
callbacks: {
label: function(context) {
const index = context.dataIndex;
const dataset = context.dataset.data;
const formatter = new Intl.NumberFormat('en-US', { maximumFractionDigits: 0 });
if (index < dataset.length - 1) {
const currentYearSupply = dataset[index];
const nextYearSupply = dataset[index + 1];
const emissionRate = ((nextYearSupply - currentYearSupply) / currentYearSupply) * 100;
return `Year: ${labels[index]}, Emission Rate: ${emissionRate.toFixed(1)}%, Supply: ${formatter.format(dataset[index])}`;
} else {
return `Supply at ${labels[index]}: ${formatter.format(dataset[index])}`;
}
}
}
}
}
}
});
}
updateCurveValuesTable();
}
// Update the curve values table
function updateCurveValuesTable() {
const table = document.getElementById('curveValuesTable');
const thead = table.querySelector('thead');
const tbody = table.querySelector('tbody');
// Update or create the header
let headerRow = thead.querySelector('tr');
if (!headerRow) {
headerRow = document.createElement('tr');
thead.appendChild(headerRow);
}
// Ensure the 'Year' column is always present
if (headerRow.cells.length === 0) {
const yearHeaderCell = document.createElement('th');
yearHeaderCell.textContent = 'Year';
headerRow.appendChild(yearHeaderCell);
}
// Update dataset headers
datasets.forEach((dataset, index) => {
let th = headerRow.cells[index + 1]; // +1 to skip the 'Year' column
if (!th) {
th = document.createElement('th');
headerRow.appendChild(th);
}
th.colSpan = "2"; // Spanning two columns: one for supply and one for emission rate
th.innerHTML = `${dataset.label}<br>(Supply, Emission Rate)`; // Use innerHTML to include the <br> tag
});
// Adjust the number of header cells to match the datasets count
while (headerRow.cells.length > datasets.length + 1) {
headerRow.removeChild(headerRow.lastChild);
}
// Update body rows
labels.forEach((label, yearIndex) => {
let row = tbody.rows[yearIndex];
if (!row) {
row = tbody.insertRow();
}
// Ensure the 'Year' cell is always present
let yearCell = row.cells[0];
if (!yearCell) {
yearCell = row.insertCell();
}
yearCell.textContent = label;
datasets.forEach((dataset, datasetIndex) => {
const dataIndex = datasetIndex * 2; // Each dataset has two columns: supply and emission rate
let supplyCell = row.cells[dataIndex + 1]; // +1 to skip the 'Year' cell
let emissionRateCell = row.cells[dataIndex + 2];
if (!supplyCell) {
supplyCell = row.insertCell(dataIndex + 1);
}
if (!emissionRateCell) {
emissionRateCell = row.insertCell(dataIndex + 2);
}
const formatter = new Intl.NumberFormat('en-US', { maximumFractionDigits: 0 });
const currentYearSupply = dataset.data[yearIndex];
const nextYearSupply = dataset.data[yearIndex + 1];
const emissionRate = yearIndex < dataset.data.length - 1 ? ((nextYearSupply - currentYearSupply) / currentYearSupply) * 100 : '—';
supplyCell.textContent = currentYearSupply !== undefined ? (isNaN(currentYearSupply) ? '—' : formatter.format(currentYearSupply)) : '—';
emissionRateCell.textContent = emissionRate !== '—' ? (isNaN(emissionRate) ? '—' : `${emissionRate.toFixed(1)}%`) : '—';
// Apply the dataset's borderColor as the left border color for the cells
const borderColor = dataset.borderColor;
supplyCell.style.borderLeft = `4px solid ${borderColor}`;
emissionRateCell.style.borderLeft = `4px solid ${borderColor}`;
});
// Adjust the number of cells in the row to match the datasets count
while (row.cells.length > datasets.length * 2 + 1) {
row.removeChild(row.lastChild);
}
});
// Adjust the number of rows to match the labels count
while (tbody.rows.length > labels.length) {
tbody.deleteRow(tbody.rows.length - 1);
}
}
document.addEventListener('DOMContentLoaded', updateCurves); // Wait for the page to be fully loaded before updating curves