-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.html
559 lines (475 loc) · 15.8 KB
/
index.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="Simple web app to generate optimized function selectors for Solidity.">
<meta property="og:title" content="4-byte-gen">
<meta property="og:description" content="Simple web app to generate optimized function selectors for Solidity.">
<meta property="og:type" content="website">
<meta property="og:url" content="https://4bg.ardis.lu/">
<link rel="icon" href="data:,">
<link rel="preload" href="/Inter.woff2" as="font" crossorigin>
<link rel="preload" href="/Inter_600.woff2" as="font" crossorigin>
<link rel="preload" href="/Inter_700.woff2" as="font" crossorigin>
<link rel="modulepreload" href="/keccak256.js">
<link rel="modulepreload" href="/worker.js">
<title>4-byte-gen</title>
<style>
/* Globals */
@font-face {
font-family: 'Inter';
font-weight: 400;
src: url('/Inter.woff2') format('woff2');
}
@font-face {
font-family: 'Inter';
font-weight: 600;
src: url('/Inter_600.woff2') format('woff2');
}
@font-face {
font-family: 'Inter';
font-weight: 700;
src: url('/Inter_700.woff2') format('woff2');
}
:root {
font-family: 'Inter', sans-serif;
}
* {
box-sizing: border-box;
margin: 0;
font-family: inherit;
font-size: 1rem;
}
body {
background: hsl(216deg 50% 95%);
color: hsl(216deg 50% 5%);
}
/* Layout */
main {
inline-size: min(100% - 16px, 1440px);
margin-inline: auto;
margin-block: 48px;
display: grid;
grid-template:
"info input"
"output output"
/ 1fr 2fr;
gap: 16px;
}
.mobile-banner {
grid-area: banner;
display: none;
padding: 24px;
border-radius: 8px;
background: hsl(216deg 80% 90%);
}
.info {
grid-area: info;
display: flex;
flex-direction: column;
gap: 16px;
}
.input {
grid-area: input;
display: flex;
flex-direction: column;
gap: 8px;
margin-block-start: 55px;
}
output {
grid-area: output;
display: none;
overflow-x: auto;
}
/* Section styling */
.subtitle {
opacity: 0.9;
}
.status {
font-weight: 700;
}
.actions {
display: flex;
gap: 8px;
}
/* Element styling */
h1 {
font-size: clamp(1.5rem, 2.5vi, 2rem);
}
a {
text-decoration: none;
font-weight: 700;
color: hsl(216deg 80% 45%);
}
a:hover,
a:focus {
color: hsl(216deg 80% 55%);
text-decoration: underline;
}
label {
font-weight: 700;
margin-inline-end: 4px;
}
textarea,
input,
button {
padding: 8px;
border-radius: 8px;
border: 1px solid hsl(216deg 50% 80%);
}
textarea {
display: block;
min-inline-size: 100%;
min-block-size: 10ch;
margin-block-start: 4px;
resize: vertical;
}
input {
inline-size: 48px;
}
textarea,
input {
transition: border-color 600ms, filter 800ms;
}
textarea:hover,
input:hover {
border: 1px solid hsl(216deg 50% 70%);
filter: drop-shadow(0 0 4px hsl(216deg 80% 90%));
transition: border-color 200ms, filter 400ms;
}
textarea:focus-within,
input:focus-within {
border: 1px solid hsl(216deg 50% 60%);
filter: drop-shadow(0 0 8px hsl(216deg 70% 80%));
transition: border-color 200ms, filter 400ms;
}
button {
inline-size: fit-content;
padding-inline: 16px;
padding-block: 8px;
font-weight: 600;
opacity: 0.9;
background: hsl(216deg 80% 80%);
color: hsl(216deg 50% 10%);
border: hsl(216deg 80% 70%);
cursor: pointer;
transition: background-color 600ms, filter 800ms;
}
button:hover:not(:disabled) {
background: hsl(216deg 75% 75%);
filter: drop-shadow(0 0 8px hsl(216deg 70% 80%));
transition: background-color 200ms, filter 400ms;
}
button:disabled {
background: hsl(216deg 30% 80%);
cursor: not-allowed;
opacity: 0.7;
}
table {
inline-size: 100%;
}
td {
text-align: center;
}
/* Dialog styling */
dialog {
inline-size: min(100dvi, 450px);
inset-inline-start: 50dvi;
inset-block-start: 50dvb;
transform: translate(-50%, -50%);
background: inherit;
padding: 16px;
border-radius: 8px;
border: 1px solid hsl(216deg 50% 50%);
}
dialog>p {
margin-block: 16px;
}
dialog>form {
display: flex;
flex-wrap: wrap;
justify-content: space-between;
gap: 8px;
}
dialog>form>div {
flex-basis: 100%;
display: flex;
align-items: center;
gap: 8px;
}
input[type=checkbox] {
inline-size: 1rem;
block-size: 1rem;
}
#cancel {
border: 1px solid hsl(216deg 50% 50%);
background: hsl(216deg 5% 85%);
color: hsl(216deg 80% 5%);
}
/* This is a desktop-first tool. Below is the alternate view for small screens. */
@media (max-width: 900px) {
main {
grid-template:
"banner"
"info"
"input"
"output"
/ 1fr;
margin-block: 24px;
}
.input {
margin-block-start: 0;
}
.minimum-container {
display: flex;
align-items: center;
}
}
@media (max-width: 600px) {
.mobile-banner {
display: block;
}
.minimum-container label {
margin-inline-end: auto;
}
}
</style>
</head>
<body>
<main>
<div class="mobile-banner">
<p>This website is intended to be used on larger screens. It will still work on this device, but the experience
may not be optimal.</p>
</div>
<section class="info">
<h1>4-byte-gen</h1>
<p class="subtitle">This tool generates Solidity function names with leading zeroes in their 4-byte
selectors. These optimized function names will make your smart contract bytecode smaller and save gas on
deployment. The functions will also cost less gas to call after the smart contract is deployed.</p>
<p><a href="https://github.com/ardislu/4-byte-gen">GitHub</a></p>
<p class="status">Enter some Solidity code in the text box and press "Parse functions".</p>
</section>
<form class="input">
<div>
<label for="functions">Solidity code</label>
<textarea name="functions" id="functions" placeholder="function totalSupply() external view returns (uint256)" autocomplete="off" spellcheck="false" data-1p-ignore data-lpignore="true" data-form-type="other" data-bwignore required></textarea>
</div>
<div class="minimum-container">
<label for="minimum">Minimum number of zero bytes</label>
<input type="number" name="minimum" id="minimum" min="1" max="3" value="1" autocomplete="off" required>
</div>
<div class="actions">
<button id="parse-functions">Parse functions</button>
<button id="start-all" disabled>Start all</button>
</div>
</form>
<output>
<table>
<thead>
<tr>
<th>Original Name</th>
<th>Original Selector</th>
<th>Optimized Name</th>
<th>Optimized Selector</th>
<th>Seed</th>
</tr>
</thead>
<tbody></tbody>
</table>
</output>
</main>
<dialog>
<h1>Parse new functions</h1>
<p>All existing optimized names will be cleared. Continue?</p>
<form method="dialog">
<div>
<input type="checkbox" id="do-not-show" name="do-not-show">
<label for="do-not-show">Do not ask again during this session.</label>
</div>
<button id="cancel" type="button">Cancel</button>
<button>Parse</button>
</form>
</dialog>
<script type="module">
// From noble-hashes v1.4.0
import { keccak256 } from '/keccak256.js';
/* Globals */
const encoder = new TextEncoder();
const status = document.querySelector('p.status');
const functions = document.querySelector('#functions');
const minimum = document.querySelector('#minimum');
const form = document.querySelector('form');
const parseFunctions = document.querySelector('#parse-functions');
const startAll = document.querySelector('#start-all');
const outputContainer = document.querySelector('output')
const outputBody = document.querySelector('tbody');
const dialog = document.querySelector('dialog');
const state = new Map(); // Store for all active functions
globalThis.state = state; // For debugging
/* UI */
// Parse code input and update state to set the new functions
function setState(code) {
state.clear();
let position = 0;
let strict = false;
const fns = code.split('\n'); // Assume each function is on its own line
for (let fn of fns) {
// Track character index in code block for lookahead
const originalFnLength = fn.length;
position += originalFnLength;
// Clean up empty lines
fn = fn.trim();
if (fn === '') {
continue;
}
if (fn.substring(0, 15) === 'pragma solidity' || fn.substring(0, 8) === 'contract' || fn.substring(0, 17) === 'abstract contract') {
// Use strict-mode splitFunction for full contracts
strict = true;
continue;
}
// Basic lookahead for function definitions that span multiple lines
if ((fn.match(/\(/g)?.length ?? 0) > (fn.match(/\)/g)?.length ?? 0)) {
const start = code.indexOf(fn, position - originalFnLength - 1);
const end = code.indexOf(')', start);
fn = code.substring(start, end + 1).replaceAll('\n', '');
}
// Split out the name from the parameters
let name, parametersTypes;
try {
({ name, parametersTypes } = splitFunction(fn, strict));
}
catch {
continue;
}
// Add any new functions to the state
const normalizedName = `${name}(${parametersTypes})`;
const byteArray = keccak256(encoder.encode(normalizedName)).slice(0, 4);
const hash = `0x${[...byteArray].map(b => b.toString(16).padStart(2, '0')).join('')}`;
state.set(normalizedName, {
name,
parametersTypes,
normalizedName,
normalizedSelector: hash,
optimizedName: null,
optimizedSelector: null,
seed: 0,
worker: null
});
}
if (state.size === 0) {
status.textContent = 'No Solidity functions were found. Is the input valid Solidity code?';
return;
}
}
// Update status and output table to match state
function updateUi(state) {
outputBody.innerHTML = '';
if (state.size === 0) {
parseFunctions.disabled = false;
startAll.disabled = true;
return;
}
for (const row of state.values()) {
const rowElem = outputBody.insertRow();
row.rowElem = rowElem;
row.normalizedNameElem = rowElem.insertCell();
row.normalizedSelectorElem = rowElem.insertCell();
row.optimizedNameElem = rowElem.insertCell();
row.optimizedSelectorElem = rowElem.insertCell();
row.seedElem = rowElem.insertCell();
row.normalizedNameElem.textContent = row.normalizedName;
row.normalizedSelectorElem.textContent = row.normalizedSelector;
row.optimizedNameElem.textContent = row.optimizedName;
row.optimizedSelectorElem.textContent = row.optimizedSelector;
row.seedElem.textContent = row.seed;
}
startAll.disabled = false;
outputContainer.style.display = 'block';
status.textContent = 'Press the "START ALL" button to begin finding optimized function names for all functions.';
}
/* Business logic */
// Normalize and extract the function name and parameter types
function splitFunction(fn, strict = false) {
// Extract function name and all params until the last closing parenthesis. WARNING: if the input includes a
// "... returns ()", then all keywords up until the last "returns" type is included in params.
let functionRegex;
if (strict) {
functionRegex = /^(function )(?<name>[a-zA-Z$_][a-zA-Z0-9$_]*) *\((?<parameters>.*?)(?!.+\))/;
}
else {
fn = fn.replaceAll(/[;'"]/g, ''); // Clean all characters that definitely do not affect the selector
functionRegex = /^(function )?(?<name>[a-zA-Z$_][a-zA-Z0-9$_]*) *\((?<parameters>.*?)(?!.+\))/;
}
const { name, parameters } = functionRegex.exec(fn).groups;
// Drop parameter names and extraneous whitespace, if there are any. Preserves tuple parentheses.
// E.g. "(uint abc, uint256, bool test)[]" --> ['(uint', 'uint256', 'bool)[]']
const parametersArray = parameters.split(',').map(param => {
const trimmed = param.trim();
const trailingParens = trimmed.match(/\)*[\[\]]*$/)[0] ?? '';
const split = trimmed.split(' ');
return `${split[0]}${split.length > 1 ? trailingParens : ''}`;
});
// Convert types from Solidity to ABI (e.g., 'uint' --> 'uint256')
// Reference: https://docs.soliditylang.org/en/latest/abi-spec.html#types
for (const [index, param] of parametersArray.entries()) {
if (/int[1-9]/.test(param) || /uint[1-9]/.test(param)) {
continue;
}
parametersArray[index] = param
.replace('int', 'int256') // Includes uint --> uint256
.replace('contract', 'address')
.replace('enum', 'uint8');
}
let parametersTypes = parametersArray.join(',');
// Drop extra trailing parenthesis, if there is one. This happens when "... returns ()" is included in the input.
if ((parametersTypes.match(/\(/g)?.length ?? 0) < (parametersTypes.match(/\)/g)?.length ?? 0)) {
parametersTypes = parametersTypes.slice(0, -1);
}
return { name, parametersTypes };
}
function handleParseFunctions(e) {
// Ask for confirmation if any optimized functions have been mined and user has not dismissed the dialog
// sessionStorage will store STRING 'true' or 'false'
if (sessionStorage.getItem('do-not-show') !== 'true' && (state.values().next().value?.seed ?? 0) !== 0) {
dialog.showModal();
}
else {
setState(functions.value);
updateUi(state);
}
}
dialog.querySelector('#cancel').addEventListener('click', () => dialog.close());
dialog.querySelector('form').addEventListener('submit', e => {
const doNotShow = new FormData(e.target).get('do-not-show') === 'on';
sessionStorage.setItem('do-not-show', doNotShow); // Will store STRING 'true' or 'false'
setState(functions.value);
updateUi(state);
});
function handleStartAll(e) {
for (const row of state.values()) {
row.worker = new Worker('/worker.js', { type: 'module' });
row.worker.postMessage({ name: row.name, parametersTypes: row.parametersTypes, seed: row.seed, minimum: parseInt(minimum.value) });
row.worker.addEventListener('message', e => {
const { functionName, hash, counter } = e.data;
row.optimizedName = functionName;
row.optimizedSelector = hash ? hash : null;
row.seed = counter;
updateUi(state);
});
}
}
/* Wire up the UI to the business logic */
// On button click, call the appropriate handler
form.addEventListener('submit', e => {
e.preventDefault();
if (e.submitter === parseFunctions) {
handleParseFunctions(e);
}
else if (e.submitter === startAll) {
handleStartAll(e);
}
});
</script>
</body>
</html>