-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpersonalize-batch.html
More file actions
677 lines (629 loc) · 29.4 KB
/
Copy pathpersonalize-batch.html
File metadata and controls
677 lines (629 loc) · 29.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
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
---
layout: null
title: Personalize a batch of your Squares for the homepage
description: "Batch personalize multiple Su Squares you own at once so their titles, links, and images update together on the TenThousandSu.com homepage billboard."
permalink: /personalize-batch
image: "{{ site.baseurl }}/assets/images/su-OG.png"
---
<!doctype html>
<html lang="en" class="personalize-page">
<head>
<script>window.SITE_BASEURL = "{{ site.baseurl }}";</script>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
{% include pwa-meta-tags.html %}
{% seo %}
<link rel="stylesheet" href="{{ site.baseurl }}/assets/css/main.css">
<link rel="stylesheet" href="{{ site.baseurl }}/assets/css/personalize.css">
<link rel="stylesheet" href="{{ site.baseurl }}/assets/web3/tx/styles.css">
{% include nav-menu-head.html %}
{% include alert-modal-head.html %}
{% include offline-modal-head.html %}
{% include jsonld-nav.html %}
{% include jsonld/webpage.html %}
</head>
<body>
{% include nav-header.html %}
<article class="lead">
<h1>Batch personalize</h1>
<p>
<em>If you have any questions, please mail <a
href="mailto:Su@TenThousandSu.com?subject=Personalize+underlay+batch">Su@TenThousandSu.com</a>. The price to
personalize is <span id="personalize-price-display">0.001 ETH</span> per Square.</em>
</p>
<p>
Use this page to personalize Su Squares you own on TenThousandSu.com. If your Square was previously personalized
using the old, more expensive method you will need to <a href="#" id="open-unpersonalize-modal">unpersonalize</a>
it first.
</p>
<h2>Select top-left Square</h2>
<p>Which Square will be the topmost and leftmost Square you will personalize?</p>
<p>
<input id="top-left-square-number" type="number" min="1" max="10000" required style="width:7em"
placeholder="e.g. 101">
</p>
<h2>Enter title</h2>
<p>Enter a title for your Squares. Later you can change the title of each Square individually.</p>
<p>
<input id="title" type="text" maxlength="64" placeholder="e.g. My Su Squares">
</p>
<p><span id="title-count">0</span> of 64 bytes</p>
<h2>Enter URL</h2>
<p>Enter a URL for your Squares. Later you can change the URL of each Square individually. Typically this will start
with <code>https://</code>.</p>
<p>
<input id="url" type="text" maxlength="96" placeholder="e.g. https://example.com">
</p>
<p><span id="url-count">0</span> of 96 bytes</p>
<h2>Upload image</h2>
<p>Design your image carefully.</p>
<p>Do not use animation or transparency. PNG and some other formats can be used here.</p>
<p>Each Square is 10×10 pixels. For example, if the area you want to personalize is 3 Squares wide and 2
Squares tall, your image must be 30×20 pixels.</p>
<p>
<input id="image" type="file" accept="image/png, image/jpeg, image/gif">
</p>
<p>
Image status: <span id="image-status">no image selected</span>
</p>
<p>
<canvas id="image-preview" width="0" height="0"></canvas>
</p>
<h2>Preflight</h2>
<p>Click this button to prepare your batch personalization, no transaction or payment is made in this step. This
will overwrite anything already in the box.</p>
<p>
<button id="preflight" class="btn">Preflight</button>
</p>
<textarea id="preflight-output" style="width:100%;height:10em"></textarea>
<p>
To manually edit individual Squares, copy/paste to a spreadsheet, edit, and then copy/paste back here. If you
would like to personalize a non-rectangular area, delete any rows that are not needed.
</p>
<p>
Preflight status: <span id="preflight-status">preflight was not yet performed</span>
</p>
<h2>Personalize</h2>
<p>Click this button to personalize your Squares.</p>
<div class="wallet-actions">
<button id="open-wallet-app" type="button" class="btn">Open mobile wallet</button>
<button id="personalize" class="btn btn-lg">Personalize</button>
</div>
<div id="tx-fixture"></div>
<!-- Unpersonalize Modal (lazy loaded) -->
<div id="unpersonalize-modal" class="su-modal-overlay" aria-hidden="true">
<div class="su-modal">
<div class="su-modal__header">
<h3 class="su-modal__title">Unpersonalize Square</h3>
<button type="button" class="su-modal__close" aria-label="Close">×</button>
</div>
<div class="su-modal__body">
<p class="su-modal__desc">Remove personalization from the main contract so you can use the cheaper underlay
contract.</p>
<div class="su-modal__field">
<label for="unpersonalize-token-id" class="su-modal__label">Token ID</label>
<input id="unpersonalize-token-id" class="su-modal__input" type="number" min="1" max="10000" required
placeholder="e.g. 7421">
</div>
<div id="unpersonalize-status" class="su-modal__status"></div>
<div id="unpersonalize-tx-fixture"></div>
<div class="su-modal__actions">
<button id="unpersonalize-submit" class="btn btn-primary" disabled>Unpersonalize</button>
</div>
</div>
</div>
</div>
</article>
<footer>
<small>
No cookies. No analytics. To the extent possible under law, Su Entriken has waived all copyright and related or
neighboring rights to the TenThousandSu.com website. This work is published from the United States.
</small>
</footer>
<script>
(function() {
var cfg = window.suWeb3 || window.SU_WEB3 || {};
var pricing = cfg.pricing;
if (pricing && typeof pricing.personalizePriceEth === "number" && pricing.personalizePriceEth !== 0.001) {
var el = document.getElementById("personalize-price-display");
if (el) el.textContent = pricing.personalizePriceEth + " ETH";
}
})();
</script>
<script type="module">
import {
ensureConnected,
ensureCorrectNetwork,
isMobileDevice,
openWalletChooser,
} from "{{ site.baseurl }}/assets/web3/foundation.js";
import { createTxFixture } from "{{ site.baseurl }}/assets/web3/tx/index.js";
import { getTxErrorMessage } from "{{ site.baseurl }}/assets/web3/tx/errors.js";
import { getWeb3Config } from "{{ site.baseurl }}/assets/web3/config.js";
import { personalizeUnderlayBatch } from "{{ site.baseurl }}/assets/web3/services/underlay-batch.js";
import { buildTxUrl } from "{{ site.baseurl }}/assets/web3/services/explorer-links.js";
import { maybeAlertBillboardUpdate } from "{{ site.baseurl }}/assets/web3/alerts.js";
// Elements and state //////////////////////////////////////////////////////////////////////////////////////////////
const topLeftSquareNumberInput = document.getElementById("top-left-square-number");
const titleInput = document.getElementById("title");
const titleCountSpan = document.getElementById("title-count");
const urlInput = document.getElementById("url");
const urlCountSpan = document.getElementById("url-count");
const imageInput = document.getElementById("image");
const imageStatusSpan = document.getElementById("image-status");
const imagePreviewCanvas = document.getElementById("image-preview");
const preflightButton = document.getElementById("preflight");
const preflightOutputTextArea = document.getElementById("preflight-output");
const preflightStatusSpan = document.getElementById("preflight-status");
const openWalletButton = document.getElementById("open-wallet-app");
const personalizeButton = document.getElementById("personalize");
const txFixtureDiv = document.getElementById("tx-fixture");
const { pricing } = getWeb3Config();
const txUi = createTxFixture({
target: txFixtureDiv,
pricing,
mode: "personalize",
title: "Personalization status",
showPersonalizeTotal: true,
});
let topLeftSquareNumber;
let title;
let url;
let imageWidth;
let imageHeight;
let imagePixelData; // R of top-left pixel, its G, its B, R of pixel to its right, its G, its B, ...
let personalizationArgs;
// Validate changes to #square-number //////////////////////////////////////////////////////////////////////////////
topLeftSquareNumberInput.addEventListener("input", (event) => {
topLeftSquareNumber = null;
const value = parseInt(event.target.value);
if (isNaN(value) || value < 1 || value > 10000) {
return alert("Invalid Square number, please enter a number between 1 and 10000.");
}
topLeftSquareNumber = value;
});
// Validate changes to #title //////////////////////////////////////////////////////////////////////////////////////
titleInput.addEventListener("input", (event) => {
title = null;
const length = new TextEncoder().encode(event.target.value).length; // UTF-8 byte length
titleCountSpan.innerText = length;
if (length > 64) {
return alert("Title is too long, please try again.");
}
if (length < 1) {
return alert("Title is too short, please try again.");
}
title = event.target.value;
});
// Validate changes to #url ////////////////////////////////////////////////////////////////////////////////////////
urlInput.addEventListener("input", (event) => {
url = null;
const length = new TextEncoder().encode(event.target.value).length; // UTF-8 byte length
urlCountSpan.innerText = length;
if (length > 96) {
return alert("URL is too long, please try again.");
}
if (length < 1) {
return alert("URL is too short, please try again.");
}
url = event.target.value;
});
// Validate changes to #image //////////////////////////////////////////////////////////////////////////////////////
imageInput.addEventListener("change", (event) => {
imageWidth = null;
imageHeight = null;
imagePixelData = null;
imageStatusSpan.innerText = "Loading image…";
imagePreviewCanvas.width = 0;
imagePreviewCanvas.height = 0;
if (!event.target.files || !event.target.files[0]) {
imageStatusSpan.innerText = "No image selected";
imageInput.value = "";
return alert("Unable to read file");
}
const image = new Image();
image.addEventListener("load", () => {
if (image.width % 10 !== 0 || image.height % 10 !== 0) {
imageStatusSpan.innerText = "No image selected";
imageInput.value = "";
return alert("IMAGE ERROR: Image must be a multiple of 10 pixels. Please try again.");
}
if (image.width < 10 || image.height < 10) {
imageStatusSpan.innerText = "No image selected";
imageInput.value = "";
return alert("IMAGE ERROR: Image must be at least 10 pixels. Please try again.");
}
if (image.width > 1000 || image.height > 1000) {
imageStatusSpan.innerText = "No image selected";
imageInput.value = "";
return alert("IMAGE ERROR: Image must be at most 1000 pixels (assuming you own the whole row or column). Please try again.");
}
if (image.naturalWidth !== image.width || image.naturalHeight !== image.height) {
imageStatusSpan.innerText = "No image selected";
imageInput.value = "";
return alert("IMAGE ERROR: Image must not be animated. Please try again.");
}
imagePreviewCanvas.width = image.width;
imagePreviewCanvas.height = image.height;
const context = imagePreviewCanvas.getContext("2d");
context.drawImage(image, 0, 0);
const contextImageData = context.getImageData(0, 0, image.width, image.height);
let alphaWarning = false;
imagePixelData = [];
for (let i = 0; i < contextImageData.data.length; i += 4) {
const [red, green, blue, alpha] = contextImageData.data.slice(i, i + 4);
// Mix color to a white background (255) if there is transparency
const mixedRed = Math.floor((red * alpha + 255 * (255 - alpha)) / 255);
const mixedGreen = Math.floor((green * alpha + 255 * (255 - alpha)) / 255);
const mixedBlue = Math.floor((blue * alpha + 255 * (255 - alpha)) / 255);
if (alpha != 255) alphaWarning = true;
imagePixelData.push(mixedRed, mixedGreen, mixedBlue);
}
if (alphaWarning) {
alert("WARNING: Your image included transparency. Since Su Squares does not support transparency, we have mixed down this color on top of a white background. Proceed at your own risk.");
}
imageStatusSpan.innerText = "Image is " + image.width + "×" + image.height + " pixels, which is " + (image.width / 10) + "×" + (image.height / 10) + " Squares";
imageWidth = image.width;
imageHeight = image.height;
});
image.src = window.URL.createObjectURL(event.target.files[0]);
});
// Validate changes to #preflight //////////////////////////////////////////////////////////////////////////////////
preflightOutputTextArea.addEventListener("input", (event) => {
personalizationArgs = null;
preflightStatusSpan.innerText = "Contents are not valid.";
txUi.setPersonalizeCount?.(0);
// check that each line has a valid square number, title, url, and pixel data
const lines = event.target.value.trim().split(/\r\n|\n|\r/);
if (!lines[0]) {
return;
}
let newPersonalizationArgs = [];
const uniqueSquares = new Set();
for (let i = 0; i < lines.length; i++) {
const line = lines[i];
const cols = line.split(/\t/);
if (cols.length !== 4) {
preflightStatusSpan.innerText = "ERROR: Row " + (i + 1) + " has " + cols.length + " columns, expecting 4.";
return;
}
const [squareNumberText, title, url, pixelHexData] = cols;
const squareNumber = parseInt(squareNumberText);
if (isNaN(squareNumber) || squareNumber < 1 || squareNumber > 10000) {
preflightStatusSpan.innerText = "ERROR: Row " + (i + 1) + " has invalid square number.";
return;
}
uniqueSquares.add(squareNumber);
const titleLength = new TextEncoder().encode(title).length; // UTF-8 byte length
if (titleLength > 64) {
preflightStatusSpan.innerText = "ERROR: Row " + (i + 1) + " has title that is too long.";
return;
}
if (titleLength < 1) {
preflightStatusSpan.innerText = "ERROR: Row " + (i + 1) + " has title that is too short.";
return;
}
const urlLength = new TextEncoder().encode(url).length; // UTF-8 byte length
if (urlLength > 96) {
preflightStatusSpan.innerText = "ERROR: Row " + (i + 1) + " has URL that is too long.";
return;
}
if (urlLength < 1) {
preflightStatusSpan.innerText = "ERROR: Row " + (i + 1) + " has URL that is too short.";
return;
}
if (pixelHexData.length !== 602) {
preflightStatusSpan.innerText = "ERROR: Row " + (i + 1) + " has pixel data that is not 602 characters.";
return;
}
// regexp
if (!pixelHexData.match(/^0x[0-9a-f]{600}$/i)) {
preflightStatusSpan.innerText = "ERROR: Row " + (i + 1) + " has pixel data that is not valid hex.";
return;
}
newPersonalizationArgs.push({
squareId: squareNumber,
rgbData: pixelHexData,
title,
href: url
});
}
personalizationArgs = newPersonalizationArgs;
preflightStatusSpan.innerText = "successful, ready to personalize " + lines.length + " Squares.";
txUi.setPersonalizeCount?.(uniqueSquares.size);
});
// Perform #preflight //////////////////////////////////////////////////////////////////////////////////////////////
// todo: look up and show warnings if Square is personalized on main contract (which occludes)
preflightButton.addEventListener("click", async function () {
preflightOutputTextArea.value = "";
if (!topLeftSquareNumber) {
return alert("ERROR: Please enter a Square number and try again.");
}
if (!title) {
return alert("ERROR: Please enter a title and try again.");
}
if (!url) {
return alert("ERROR: Please enter a URL and try again.");
}
if (!imageWidth) {
return alert("ERROR: Please select an image and try again.");
}
if (!imageHeight) {
return alert("ERROR: Please select an image and try again.");
}
if (!imagePixelData) {
return alert("ERROR: Please select an image and try again.");
}
// check if the image goes off the right or bottom edge of the website
const topLeftColumn = (topLeftSquareNumber - 1) % 100 + 1;
const topLeftRow = Math.floor((topLeftSquareNumber - 1) / 100) + 1;
if (topLeftColumn + imageWidth / 10 > 101) {
return alert("ERROR: Image goes off the right edge of the website. Please try again.");
}
if (topLeftRow + imageHeight / 10 > 101) {
return alert("ERROR: Image goes off the bottom edge of the website. Please try again.");
}
// Write lines: Square number, title, URL, pixel data
// Pixels are RGB in English reading order, 602 characters per line including 0x prefix
for (let y = 0; y < imageHeight; y += 10) {
for (let x = 0; x < imageWidth; x += 10) {
const squareNumber = topLeftSquareNumber + (y / 10) * 100 + (x / 10);
const pixelData = [];
for (let i = 0; i < 10; i++) {
const pixelIndex = (y + i) * imageWidth + x;
for (let j = 0; j < 10; j++) {
const pixelDataIndex = pixelIndex + j;
pixelData.push(imagePixelData[pixelDataIndex * 3].toString(16).padStart(2, "0"));
pixelData.push(imagePixelData[pixelDataIndex * 3 + 1].toString(16).padStart(2, "0"));
pixelData.push(imagePixelData[pixelDataIndex * 3 + 2].toString(16).padStart(2, "0"));
}
}
preflightOutputTextArea.value += squareNumber + "\t" + title + "\t" + url + "\t0x" + pixelData.join("") + "\n";
}
}
preflightOutputTextArea.dispatchEvent(new Event("input"));
});
let currentWagmi = null; // Track current wagmi client for button visibility
// Open wallet button - shows on mobile when connected via WalletConnect
const updateOpenWalletButton = () => {
if (!openWalletButton) return;
const isWalletConnect = currentWagmi?.getAccount?.()?.connector?.id === "walletConnect";
const showButton = isMobileDevice() && isWalletConnect;
openWalletButton.style.display = showButton ? "inline-block" : "none";
};
if (openWalletButton) {
updateOpenWalletButton();
openWalletButton.addEventListener("click", () => {
// Opens OS app chooser with placeholder URI (no real session data exposed)
openWalletChooser();
});
}
// Handle personalize button ///////////////////////////////////////////////////////////////////////////////////////
personalizeButton.addEventListener("click", async function () {
if (!personalizationArgs) {
return alert("ERROR: Please perform preflight, or manually edit the preflight box and pass validation, then try again.");
}
txUi.startProcessing("Sending personalization batch. Confirm in your wallet to continue.");
const doSendTransaction = async (wagmi) => {
const isWalletConnect = wagmi?.getAccount?.()?.connector?.id === "walletConnect";
txUi.setWalletContext({
isWalletConnect,
});
// Trigger wallet app open on mobile for WalletConnect
if (isMobileDevice() && isWalletConnect) {
openWalletChooser();
}
let result;
try {
result = await personalizeUnderlayBatch(personalizationArgs, wagmi);
const pendingUrl = buildTxUrl(result.hash);
txUi.addPending(result.hash, pendingUrl);
const transaction = await wagmi.waitForTransaction({ hash: result.hash });
const txUrl = buildTxUrl(transaction.transactionHash);
txUi.markSuccess(
transaction.transactionHash,
txUrl,
"Transaction confirmed. Your image will show on the Su Squares homepage, which refreshes hourly."
);
maybeAlertBillboardUpdate();
} catch (error) {
console.log(error);
const message = getTxErrorMessage(error, { isWalletConnect });
txUi.markError(message);
return alert(message);
}
};
await ensureConnected(async (clients) => {
currentWagmi = clients;
updateOpenWalletButton();
await ensureCorrectNetwork(clients);
const { activeNetwork } = getWeb3Config();
const account = clients.getAccount?.();
if (account?.address) {
txUi.setBalanceContext({
address: account.address,
chainId: activeNetwork.chainId,
fetcher: (addr, chain) => clients.fetchBalance({ address: addr, chainId: chain }),
});
}
await doSendTransaction(clients);
});
});
// Unpersonalize Modal - Lazy Loaded /////////////////////////////////////////////////////////////////////////
const unpersonalizeModalTrigger = document.getElementById("open-unpersonalize-modal");
const unpersonalizeModal = document.getElementById("unpersonalize-modal");
const unpersonalizeTokenInput = document.getElementById("unpersonalize-token-id");
const unpersonalizeStatus = document.getElementById("unpersonalize-status");
const unpersonalizeSubmit = document.getElementById("unpersonalize-submit");
const unpersonalizeTxFixtureDiv = document.getElementById("unpersonalize-tx-fixture");
const unpersonalizeCloseBtn = unpersonalizeModal?.querySelector(".su-modal__close");
let unpersonalizeModuleLoaded = false;
let unpersonalizeService = null;
let unpersonalizeTxUi = null;
function showUnpersonalizeModal() {
if (!unpersonalizeModal) return;
unpersonalizeModal.classList.add("is-visible");
unpersonalizeModal.setAttribute("aria-hidden", "false");
// Pre-fill token ID from main form if available
if (topLeftSquareNumber && unpersonalizeTokenInput) {
unpersonalizeTokenInput.value = topLeftSquareNumber;
validateUnpersonalizeInput();
}
}
function hideUnpersonalizeModal() {
if (!unpersonalizeModal) return;
unpersonalizeModal.classList.remove("is-visible");
unpersonalizeModal.setAttribute("aria-hidden", "true");
if (unpersonalizeTxUi) {
unpersonalizeTxUi.reset();
}
if (unpersonalizeStatus) {
unpersonalizeStatus.textContent = "";
unpersonalizeStatus.className = "su-modal__status";
}
}
async function loadUnpersonalizeModule() {
if (unpersonalizeModuleLoaded) return;
try {
const [serviceModule, txModule] = await Promise.all([
import("{{ site.baseurl }}/assets/web3/services/unpersonalize.js"),
import("{{ site.baseurl }}/assets/web3/tx/index.js"),
]);
unpersonalizeService = serviceModule;
unpersonalizeTxUi = txModule.createTxFixture({
target: unpersonalizeTxFixtureDiv,
pricing,
mode: "unpersonalize",
title: "Unpersonalization status",
});
unpersonalizeModuleLoaded = true;
} catch (error) {
console.error("Failed to load unpersonalize module:", error);
if (unpersonalizeStatus) {
unpersonalizeStatus.textContent = "Failed to load module. Please refresh and try again.";
unpersonalizeStatus.className = "su-modal__status su-modal__status--error";
}
}
}
async function validateUnpersonalizeInput() {
const tokenId = parseInt(unpersonalizeTokenInput?.value);
if (!tokenId || tokenId < 1 || tokenId > 10000) {
if (unpersonalizeSubmit) unpersonalizeSubmit.disabled = true;
if (unpersonalizeStatus) {
unpersonalizeStatus.textContent = "";
unpersonalizeStatus.className = "su-modal__status";
}
return false;
}
// Check personalization status on main contract
if (unpersonalizeService?.checkMainContractStatus) {
try {
const status = await unpersonalizeService.checkMainContractStatus(tokenId);
if (unpersonalizeStatus) {
if (status.message) {
unpersonalizeStatus.textContent = status.message;
if (status.isOnMain && status.hasPersonalization) {
unpersonalizeStatus.className = "su-modal__status su-modal__status--success";
} else {
unpersonalizeStatus.className = "su-modal__status su-modal__status--warning";
}
} else {
unpersonalizeStatus.textContent = "";
unpersonalizeStatus.className = "su-modal__status";
}
}
} catch (error) {
console.warn("Could not check personalization status:", error);
}
}
if (unpersonalizeSubmit) unpersonalizeSubmit.disabled = false;
return true;
}
if (unpersonalizeModalTrigger) {
unpersonalizeModalTrigger.addEventListener("click", async (event) => {
event.preventDefault();
showUnpersonalizeModal();
await loadUnpersonalizeModule();
});
}
if (unpersonalizeCloseBtn) {
unpersonalizeCloseBtn.addEventListener("click", hideUnpersonalizeModal);
}
if (unpersonalizeModal) {
unpersonalizeModal.addEventListener("click", (event) => {
if (event.target === unpersonalizeModal) {
hideUnpersonalizeModal();
}
});
}
if (unpersonalizeTokenInput) {
unpersonalizeTokenInput.addEventListener("input", validateUnpersonalizeInput);
}
if (unpersonalizeSubmit) {
unpersonalizeSubmit.addEventListener("click", async () => {
const tokenId = parseInt(unpersonalizeTokenInput?.value);
if (!tokenId || tokenId < 1 || tokenId > 10000) {
return alert("Please enter a valid Token ID (1-10000).");
}
if (!unpersonalizeService || !unpersonalizeTxUi) {
return alert("Module not loaded. Please close and reopen the modal.");
}
unpersonalizeTxUi.startProcessing(`Unpersonalizing Square #${tokenId}. Confirm in your wallet to continue.`);
await ensureConnected(async (clients) => {
await ensureCorrectNetwork(clients);
const isWalletConnect = clients?.getAccount?.()?.connector?.id === "walletConnect";
unpersonalizeTxUi.setWalletContext({
isWalletConnect,
});
// Trigger wallet app open on mobile for WalletConnect
if (isMobileDevice() && isWalletConnect) {
openWalletChooser();
}
// Set balance context
const { activeNetwork } = getWeb3Config();
const account = clients.getAccount?.();
if (account?.address) {
unpersonalizeTxUi.setBalanceContext({
address: account.address,
chainId: activeNetwork.chainId,
fetcher: (addr, chain) => clients.fetchBalance({ address: addr, chainId: chain }),
});
}
// Check ownership before proceeding
try {
const owner = await unpersonalizeService.checkSquareOwner(tokenId, clients);
const signerAddress = account?.address;
if (owner?.toLowerCase() !== signerAddress?.toLowerCase()) {
unpersonalizeTxUi.markError("You do not own this Square.");
return alert("You do not own this Square. Transaction cancelled.");
}
} catch (error) {
console.error("Ownership check failed:", error);
unpersonalizeTxUi.markError("Could not verify ownership. Please try again.");
return;
}
// Proceed with unpersonalization
try {
const result = await unpersonalizeService.unpersonalizePrimary({ squareId: tokenId }, clients);
const pendingUrl = buildTxUrl(result.hash);
unpersonalizeTxUi.addPending(result.hash, pendingUrl);
const transaction = await clients.waitForTransaction({ hash: result.hash });
const txUrl = buildTxUrl(transaction.transactionHash);
unpersonalizeTxUi.markSuccess(
transaction.transactionHash,
txUrl,
"Square unpersonalized! You can now personalize using the cheaper underlay contract."
);
} catch (error) {
console.error("Unpersonalize transaction failed:", error);
const message = getTxErrorMessage(error, { isWalletConnect });
unpersonalizeTxUi.markError(message);
return alert(message);
}
});
});
}
</script>
<script src="{{ site.baseurl }}/assets/js/pwa-init.js"></script>
</body>
</html>