-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathplayground.html
More file actions
391 lines (347 loc) · 17.4 KB
/
playground.html
File metadata and controls
391 lines (347 loc) · 17.4 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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>uint-quantization-lib Planner</title>
<style>
:root {
--bg: #0d0d0d; --surface: #151515; --surface-2: #1c1c1c; --border: #2e2e2e;
--text: #d4d4d4; --text-dim: #666; --text-bright: #f5f5f5;
--accent: #14b8a6; --accent-dim: #0d7d72;
--warn: #d97706; --err: #ef4444;
--mono: 'SF Mono','Fira Code','Cascadia Code','JetBrains Mono','Consolas',monospace;
}
* { margin:0; padding:0; box-sizing:border-box; }
body { font-family: system-ui, -apple-system, sans-serif; background: var(--bg); color: var(--text); min-height: 100vh; }
.hdr {
padding: 14px 24px; border-bottom: 1px solid var(--border);
display: flex; align-items: baseline; gap: 10px;
}
.hdr h1 { font-size: 15px; font-weight: 600; color: var(--text-bright); }
.hdr .ver { font-family: var(--mono); font-size: 11px; color: var(--text-dim); }
.hdr-links { margin-left: auto; display: flex; gap: 16px; }
.hdr-links a { font-size: 12px; color: var(--text-dim); text-decoration: none; }
.hdr-links a:hover { color: var(--text-bright); }
.pg { max-width: 1200px; margin: 0 auto; padding: 32px 24px 24px; }
/* Inputs */
.input-row { display: flex; gap: 16px; margin-bottom: 6px; }
.input-field { flex: 1; }
.input-field label { display: block; font-size: 12px; color: var(--text-dim); margin-bottom: 4px; }
.input-field input {
width: 100%; background: var(--surface-2); border: 1px solid var(--border);
color: var(--text-bright); font-family: var(--mono); font-size: 14px;
padding: 10px 12px; border-radius: 6px; outline: none; transition: border-color 0.15s;
}
.input-field input:focus { border-color: var(--accent); }
.input-field input.invalid { border-color: var(--err); }
.input-field .hint { font-size: 10px; color: var(--text-dim); margin-top: 3px; }
.hex-readout { font-family: var(--mono); font-size: 11px; color: var(--text-dim); margin-top: 2px; word-break: break-all; }
/* Intro */
.intro { margin-bottom: 32px; line-height: 1.7; }
.intro h2 { font-size: 16px; font-weight: 600; color: var(--text-bright); margin-bottom: 12px; }
.intro p { font-size: 13px; color: var(--text); margin-bottom: 12px; }
.intro ol { font-size: 13px; color: var(--text); padding-left: 20px; margin-bottom: 12px; }
.intro li { margin-bottom: 10px; }
.intro li strong { color: var(--text-bright); }
.intro code { font-family: var(--mono); font-size: 12px; color: var(--accent); background: var(--surface-2); padding: 1px 5px; border-radius: 3px; }
.intro sup { font-size: 9px; }
.error-msg { color: var(--err); font-size: 11px; font-family: var(--mono); margin-top: 4px; min-height: 16px; }
/* Output */
.output { margin-top: 24px; display: none; }
.output.visible { display: block; }
.compare {
display: flex; align-items: center; gap: 12px;
margin-bottom: 20px; font-family: var(--mono); font-size: 13px;
}
.compare-box {
flex: 1; padding: 12px 14px; border-radius: 6px; text-align: center;
}
.compare-box.before { background: var(--surface-2); border: 1px solid var(--border); color: var(--text-dim); }
.compare-box.after { background: rgba(20,184,166,0.08); border: 1px solid var(--accent-dim); color: var(--accent); }
.compare-box .type { font-size: 18px; font-weight: 700; color: var(--text-bright); }
.compare-box.after .type { color: var(--accent); }
.compare-box .sub { font-size: 10px; color: var(--text-dim); margin-top: 2px; }
.compare-arrow { color: var(--text-dim); font-size: 18px; flex-shrink: 0; }
.compare-save { font-size: 11px; color: var(--accent); text-align: center; flex-shrink: 0; }
.result-table {
width: 100%; border-collapse: collapse; font-family: var(--mono); font-size: 12px;
margin-bottom: 20px;
}
.result-table td { padding: 8px 12px; border-bottom: 1px solid var(--border); vertical-align: top; }
.result-table td:first-child { color: var(--text-dim); font-size: 10px; text-transform: uppercase; letter-spacing: 0.5px; width: 140px; padding-top: 10px; }
.result-table td:last-child { color: var(--text-bright); }
.result-table .sub { font-size: 10px; color: var(--text-dim); display: block; margin-top: 1px; }
.result-table .ok { color: var(--accent); }
.result-table .warn { color: var(--warn); }
.no-quant {
padding: 16px; background: var(--surface-2); border: 1px solid var(--border);
border-radius: 8px; font-size: 13px; color: var(--text); margin-bottom: 20px;
}
.no-quant strong { color: var(--text-bright); }
/* Code */
.code-wrap { position: relative; margin-bottom: 8px; }
.code-block {
background: var(--surface); border: 1px solid var(--border); border-radius: 8px;
padding: 14px 16px; font-family: var(--mono); font-size: 12px; line-height: 1.6;
color: var(--text); overflow-x: auto; white-space: pre;
}
.code-block .cm { color: var(--text-dim); }
.code-block .kw { color: #c084fc; }
.code-block .ty { color: #38bdf8; }
.code-block .num { color: #fbbf24; }
.code-block .fn { color: #34d399; }
.code-copy {
position: absolute; top: 8px; right: 8px;
background: var(--surface-2); border: 1px solid var(--border); color: var(--text-dim);
padding: 3px 10px; border-radius: 4px; font-size: 11px; font-family: inherit;
cursor: pointer; transition: all 0.15s;
}
.code-copy:hover { color: var(--text-bright); border-color: var(--accent); }
.code-copy.copied { color: #16a34a; border-color: #16a34a; }
/* Prompt */
.prompt-area { border-top: 1px solid var(--border); padding: 16px 24px; background: var(--surface); margin-top: 16px; }
.prompt-inner { max-width: 1200px; margin: 0 auto; }
.prompt-header { display: flex; align-items: center; justify-content: space-between; margin-bottom: 8px; }
.prompt-label { font-size: 10px; font-weight: 700; text-transform: uppercase; letter-spacing: 1px; color: var(--text-dim); }
.copy-btn {
background: var(--accent-dim); border: none; color: var(--text-bright);
padding: 5px 14px; border-radius: 6px; font-size: 12px; font-family: inherit;
cursor: pointer; transition: all 0.15s;
}
.copy-btn:hover { background: var(--accent); }
.copy-btn.copied { background: #16a34a; }
.prompt-text {
font-family: var(--mono); font-size: 12px; line-height: 1.6;
color: var(--text); white-space: pre-wrap; word-break: break-word; min-height: 36px;
}
@media (max-width: 500px) {
.input-row { flex-direction: column; gap: 12px; }
.compare { flex-direction: column; }
.compare-arrow { transform: rotate(90deg); }
}
</style>
</head>
<body>
<div class="hdr">
<h1>uint-quantization-lib</h1>
<span class="ver">v7.1.0 planner</span>
<div class="hdr-links">
<a href="index.html">Home</a>
<a href="https://github.com/0xferit/uint-quantization-lib/blob/main/README.md">Docs</a>
<a href="https://github.com/0xferit/uint-quantization-lib">GitHub</a>
</div>
</div>
<div class="pg">
<div class="intro">
<h2>Thinking through a quantization scheme</h2>
<p>Say you are building a staking contract and need to store ETH balances. ETH has 18 decimals, so 1 ETH = 10<sup>18</sup> wei. Where do you start?</p>
<ol>
<li><strong>What is the largest value I will ever store?</strong> The total ETH supply is ~120M ETH = 1.2 × 10<sup>26</sup> wei. No single balance can exceed that, so it is a safe domain max. If the field is an accumulator (e.g., total staked across all users), estimate the worst-case accumulated total instead.</li>
<li><strong>How many bits does that need?</strong> log<sub>2</sub>(1.2 × 10<sup>26</sup>) ≈ 86.6, so 87 bits minimum. Next byte boundary: <code>uint88</code>.</li>
<li><strong>How much resolution can I sacrifice?</strong> Do you need wei-level resolution? Probably not for staking. If you accept rounding to the nearest 65,536 wei (2<sup>16</sup>), that is roughly 0.000000000000065 ETH: invisible to any user. So discarding 16 bits is safe.</li>
<li><strong>What is the result?</strong> With <code>uint88</code> and 16 discarded bits: 88 − 16 = 72 encoded bits, stored as <code>uint72</code>. The call is <code>create(16, 72)</code>.</li>
<li><strong>What do I lose?</strong> Max error per value is 2<sup>16</sup> − 1 = 65,535 wei ≈ 0.000000000000065 ETH. Values within 65,535 of <code>uint88.max</code> will revert with <code>Overflow</code>. Both are negligible for ETH staking. If you want zero error, enforce step-aligned inputs: the library provides <code>requireAligned()</code> and <code>encode(value, true)</code> which revert on non-aligned values, guaranteeing lossless round-trips.</li>
</ol>
<p>Enter your domain max below to run this reasoning for your own field.</p>
</div>
<div class="input-row">
<div class="input-field">
<label for="maxInput">Domain maximum</label>
<input type="text" id="maxInput" value="120000000e18" placeholder="e.g., 120000000e18" spellcheck="false" autocomplete="off">
<div class="hint">your cap, worst-case accumulation, or supply bound in base units</div>
<div class="hex-readout" id="maxHex"></div>
</div>
<div class="input-field">
<label for="stepInput">Discarded bits</label>
<input type="number" id="stepInput" value="16" min="0" max="248" step="8">
<div class="hint">low-order bits to discard, multiples of 8 (0 = none)</div>
<div class="hex-readout" id="stepHex"></div>
</div>
</div>
<div class="error-msg" id="errorMsg"></div>
<div class="output" id="output"></div>
</div>
<div class="prompt-area">
<div class="prompt-inner">
<div class="prompt-header">
<span class="prompt-label">Prompt</span>
<button class="copy-btn" id="copyBtn">Copy</button>
</div>
<div class="prompt-text" id="promptText"></div>
</div>
</div>
<script>
const UINT256_MAX = (1n << 256n) - 1n;
// --- Parsing ---
function parseValue(str) {
str = str.trim().replace(/_/g, '');
if (!str) return null;
try {
if (str.startsWith('0x') || str.startsWith('0X')) return BigInt(str);
if (/^\d+[eE]\d+$/.test(str)) {
const [b, x] = str.split(/[eE]/);
return BigInt(b) * (10n ** BigInt(x));
}
if (/^\d+$/.test(str)) return BigInt(str);
return null;
} catch { return null; }
}
// --- Formatting ---
function fmt(n) {
if (n < 0n) return '-' + fmt(-n);
const s = n.toString();
if (s.length <= 22) return s.replace(/\B(?=(\d{3})+(?!\d))/g, ',');
return '~' + s[0] + '.' + s.slice(1, 5) + 'e' + (s.length - 1);
}
function fmtFull(n) { return n.toString(); }
function fmtHex(n) { return '0x' + n.toString(16); }
function bitLength(n) {
if (n <= 0n) return 0;
return n.toString(2).length;
}
// --- Derive scheme ---
function derive(domainMax, dBits) {
if (domainMax <= 0n) return { valid: false, error: 'Domain max must be > 0' };
if (domainMax > UINT256_MAX) return { valid: false, error: 'Exceeds uint256' };
// Derive field width from domain max
const rawBits = bitLength(domainMax);
const nativeBits = Math.ceil(rawBits / 8) * 8; // byte-aligned
const nativeType = 'uint' + nativeBits;
const fieldMax = (1n << BigInt(nativeBits)) - 1n;
if (dBits < 0) return { valid: false, error: 'Discarded bits must be >= 0' };
if (dBits >= nativeBits) return { valid: false, error: 'Discarded bits (' + dBits + ') must be < derived field width (' + nativeBits + ')' };
const d = dBits;
const e = nativeBits - dBits;
const step = 1n << BigInt(d);
const actualMax = ((1n << BigInt(e)) - 1n) << BigInt(d);
const uintBits = Math.ceil(e / 8) * 8;
const uintType = 'uint' + uintBits;
const maxError = step - 1n;
const identity = d === 0;
return {
valid: true, d, e, step, actualMax, fieldMax, domainMax, uintType, uintBits,
rawBits, nativeBits, nativeType, maxError, identity
};
}
// --- DOM ---
const maxInput = document.getElementById('maxInput');
const stepInput = document.getElementById('stepInput');
const errorMsg = document.getElementById('errorMsg');
const output = document.getElementById('output');
const promptText = document.getElementById('promptText');
const copyBtn = document.getElementById('copyBtn');
// --- Render ---
function update() {
const domainMax = parseValue(maxInput.value);
const dBits = parseInt(stepInput.value);
const maxValid = domainMax !== null && domainMax > 0n && domainMax <= UINT256_MAX;
const dValid = !isNaN(dBits) && dBits >= 0 && dBits % 8 === 0;
maxInput.classList.toggle('invalid', maxInput.value.trim() && !maxValid);
stepInput.classList.toggle('invalid', stepInput.value.trim() && !dValid);
if (maxValid) {
const rawBits = bitLength(domainMax);
const nb = Math.ceil(rawBits / 8) * 8;
const nt = 'uint' + nb;
const fm = (1n << BigInt(nb)) - 1n;
document.getElementById('maxHex').textContent = 'needs ' + rawBits + ' bits \u2192 ' + nt + ' (max ' + fmtHex(fm) + ')';
stepInput.max = nb - 8;
} else {
document.getElementById('maxHex').textContent = '';
}
if (dValid) {
const step = 1n << BigInt(dBits);
document.getElementById('stepHex').textContent = 'step = ' + fmtHex(step) + ' (' + fmt(step) + ')';
} else {
document.getElementById('stepHex').textContent = '';
}
if (!maxValid || !dValid) {
errorMsg.textContent = '';
output.classList.remove('visible');
promptText.textContent = '';
return;
}
const r = derive(domainMax, dBits);
if (!r.valid) {
errorMsg.textContent = r.error;
output.classList.remove('visible');
promptText.textContent = '';
return;
}
errorMsg.textContent = '';
output.classList.add('visible');
if (r.identity) {
output.innerHTML = `
<div class="no-quant">
<strong>0 bits discarded:</strong> domain max ${fmt(r.domainMax)} needs ${r.rawBits} bits, stored as <strong>${r.nativeType}</strong>. No compression.
Increase discarded bits to reduce the encoded width.
</div>
`;
promptText.textContent = `Domain max ${fmt(r.domainMax)} needs ${r.rawBits} bits (${r.nativeType}), 0 bits discarded: no compression.`;
return;
}
const saved = r.nativeBits - r.uintBits;
output.innerHTML = `
<div class="compare">
<div class="compare-box before">
<div class="type">${r.nativeType}</div>
<div class="sub">${r.rawBits} bits needed, ${r.nativeBits}-bit type</div>
</div>
<div class="compare-arrow">→</div>
<div class="compare-box after">
<div class="type">${r.uintType}</div>
<div class="sub">${r.nativeBits} − ${r.d} = ${r.e} bits encoded</div>
</div>
${saved > 0 ? `<div class="compare-save">−${saved} bits</div>` : ''}
</div>
<table class="result-table">
<tr><td>Domain max</td><td>${fmt(r.domainMax)}<span class="sub">${fmtHex(r.domainMax)} (needs ${r.rawBits} bits → ${r.nativeType})</span></td></tr>
<tr><td>Scheme</td><td>create(${r.d}, ${r.e})<span class="sub">discard ${r.d} low bits, keep ${r.e} bits</span></td></tr>
<tr><td>Step size</td><td>${fmtHex(r.step)}<span class="sub">2^${r.d} = ${fmt(r.step)}</span></td></tr>
<tr><td>Max representable</td><td>${fmtHex(r.actualMax)}<span class="sub">${fmt(r.actualMax)}${r.actualMax < r.fieldMax ? ' (values above this revert with Overflow)' : ''}</span></td></tr>
<tr><td>Max error</td><td>${fmtHex(r.maxError)}<span class="sub">${fmt(r.maxError)} (step − 1)</span></td></tr>
</table>
<div class="code-wrap">
<div class="code-block"><span class="kw">import</span> {<span class="ty">Quant</span>, <span class="ty">UintQuantizationLib</span> <span class="kw">as</span> QuantLib} <span class="kw">from</span> <span class="fn">"uint-quantization-lib/src/UintQuantizationLib.sol"</span>;
<span class="ty">Quant</span> <span class="kw">private</span> <span class="kw">immutable</span> SCHEME = QuantLib.<span class="fn">create</span>(<span class="num">${r.d}</span>, <span class="num">${r.e}</span>);
<span class="cm">// Encode:</span>
<span class="ty">${r.uintType}</span> encoded = <span class="ty">${r.uintType}</span>(SCHEME.<span class="fn">encode</span>(value));
<span class="cm">// Decode:</span>
<span class="ty">uint256</span> restored = SCHEME.<span class="fn">decode</span>(encoded);</div>
<button class="code-copy" onclick="copyCode(this)">Copy</button>
</div>
`;
let p = `I'm building a Solidity contract that stores __________ (describe your field: e.g., ETH staking balances, token amounts, timestamps).\n\n`;
p += `Using uint-quantization-lib (https://github.com/0xferit/uint-quantization-lib), help me:\n`;
p += `1. Determine the domain max for this field (contract cap, supply bound, or worst-case accumulation)\n`;
p += `2. Derive the minimum bit width and native Solidity type\n`;
p += `3. Decide how many bits of resolution to discard and justify the tradeoff\n`;
p += `4. Compute the quantization scheme: create(discardedBitWidth, encodedBitWidth)\n`;
p += `5. Show the Solidity integration code with encode/decode calls`;
promptText.textContent = p;
}
function copyCode(btn) {
const code = btn.previousElementSibling.textContent;
navigator.clipboard.writeText(code).then(() => {
btn.textContent = 'Copied!';
btn.classList.add('copied');
setTimeout(() => { btn.textContent = 'Copy'; btn.classList.remove('copied'); }, 1500);
});
}
// --- Events ---
maxInput.addEventListener('input', update);
maxInput.addEventListener('change', update);
stepInput.addEventListener('input', update);
stepInput.addEventListener('change', update);
copyBtn.addEventListener('click', () => {
navigator.clipboard.writeText(promptText.textContent).then(() => {
copyBtn.textContent = 'Copied!';
copyBtn.classList.add('copied');
setTimeout(() => { copyBtn.textContent = 'Copy'; copyBtn.classList.remove('copied'); }, 1500);
});
});
// --- Init ---
update();
</script>
</body>
</html>