-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
331 lines (278 loc) · 10.4 KB
/
script.js
File metadata and controls
331 lines (278 loc) · 10.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
document.addEventListener("DOMContentLoaded", initializeApp);
async function initializeApp() {
setupChainDropdown();
setupRedirectFromUrl();
setupEventListeners();
updateSwitchNetworkButtonText();
}
// Detect if the user is on a mobile device
function isMobileDevice() {
return /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);
}
// Create a MetaMask deeplink for switching networks
function createMetaMaskDeeplink() {
// get url params to append to the deeplink
const urlParams = new URLSearchParams(window.location.search).toString();
return `https://metamask.app.link/dapp/chainswitch.xyz/?${urlParams}`;
}
async function setupChainDropdown() {
const chainSelect = document.getElementById("chainSelect");
if (!chainSelect) return;
for (const chain of CHAINS) {
const option = document.createElement("option");
option.value = option.textContent = chain.name;
chainSelect.appendChild(option);
}
await setInitialChainSelection(chainSelect);
}
async function setInitialChainSelection(chainSelect) {
const chainValue = new URLSearchParams(window.location.search).get("chain") || (await getCurrentChain()) || 1;
const chainDetails = getChainDetails(chainValue);
chainSelect.value = chainDetails.name;
}
function getChainDetails(chainValue) {
//chainValue could be a number as a string
if (!isNaN(chainValue)) {
return CHAINS.find((chain) => chain.chainId === parseInt(chainValue)) || CHAINS[0];
}
// try to find a direct match first
const directMatch = CHAINS.find(
({ name, shortName }) =>
name.localeCompare(chainValue, "en", { sensitivity: "base" }) === 0 ||
shortName.localeCompare(chainValue, "en", { sensitivity: "base" }) === 0
);
if (directMatch) {
return directMatch;
}
// if no direct match, find the closest match
const lowercaseChainNames = CHAINS.map(({ name }) => name.toLowerCase());
const distances = lowercaseChainNames.map((name) => levenshteinDistance(name, chainValue));
const minDistance = Math.min(...distances);
const bestNameMatch = CHAINS[distances.indexOf(minDistance)].name;
return CHAINS.find(({ name }) => name === bestNameMatch) || CHAINS[0];
}
function setupRedirectFromUrl() {
const redirectParam = new URLSearchParams(window.location.search).get("redirect");
if (!redirectParam) return;
const redirectUrlInput = document.getElementById("redirectUrl");
if (redirectUrlInput) {
redirectUrlInput.value = decodeURIComponent(redirectParam).replace(/^https?:\/\//, "");
}
document.getElementById("redirectUrl")?.addEventListener("input", (e) => {
e.target.value = e.target.value.replace(/^https?:\/\//, "");
updateGoToLinkButtonState();
updateUrlParams("redirect", e.target.value);
});
}
function setupEventListeners() {
setupModalListeners();
setupNetworkSwitchListener();
setupUrlParamListeners();
setupCopyLinkButton();
setupDraggableWindow();
setupGoToLinkButton();
}
function setupModalListeners() {
document.getElementById("closeAlert")?.addEventListener("click", closeAlert);
document.querySelector(".close")?.addEventListener("click", closeAlert);
}
function setupNetworkSwitchListener() {
document.getElementById("switchNetwork")?.addEventListener("click", switchNetworkListener);
}
async function switchNetworkListener() {
// Check if the user is on a mobile device and window.ethereum is not available
if (isMobileDevice() && !window.ethereum) {
const chainSelect = document.getElementById("chainSelect");
const selectedChainName = chainSelect.value;
const chainDetails = CHAINS.find((chain) => chain.name === selectedChainName);
if (!chainDetails) {
return showAlert("Please select a valid chain.");
}
// Use a deeplink to redirect to MetaMask for mobile users
const deeplink = createMetaMaskDeeplink(chainDetails);
window.location.href = deeplink; // Redirect the user to MetaMask
return;
} else if (!window.ethereum) {
return showAlert("No wallet detected.");
}
const chainSelect = document.getElementById("chainSelect");
const selectedChainName = chainSelect.value;
const chainDetails = CHAINS.find((chain) => chain.name === selectedChainName);
if (!chainDetails) {
return showAlert("Please select a valid chain.");
}
await switchNetwork(chainDetails);
}
async function getCurrentChain() {
const chainIdHex = await window.ethereum.request({ method: "eth_chainId" });
return parseInt(chainIdHex, 16);
}
function setupUrlParamListeners() {
document.getElementById("chainSelect")?.addEventListener("change", (e) => updateUrlParams("chain", e.target.value));
document.getElementById("redirectUrl")?.addEventListener("input", (e) => {
updateGoToLinkButtonState();
updateUrlParams("redirect", e.target.value);
updateSwitchNetworkButtonText();
});
}
function updateSwitchNetworkButtonText() {
const switchNetworkButton = document.getElementById("switchNetwork");
const redirectUrl = document.getElementById("redirectUrl").value;
if (redirectUrl) {
switchNetworkButton.textContent = "Switch and Go";
} else {
switchNetworkButton.textContent = "Chain Switch";
}
}
function updateGoToLinkButtonState() {
const goToLinkButton = document.getElementById("goToLink");
const redirectUrl = document.getElementById("redirectUrl").value;
// Enable or disable the button based on redirectUrl content
goToLinkButton.disabled = !redirectUrl;
if (redirectUrl) {
goToLinkButton.classList.remove("retro-btn-disabled");
} else {
goToLinkButton.classList.add("retro-btn-disabled");
}
}
function setupGoToLinkButton() {
const goToLinkButton = document.getElementById("goToLink");
const redirectUrl = document.getElementById("redirectUrl")?.value;
goToLinkButton.disabled = !redirectUrl;
goToLinkButton.addEventListener("click", () => {
const redirectUrl = document.getElementById("redirectUrl")?.value;
if (!goToLinkButton.disabled && redirectUrl) {
window.open(`https://${redirectUrl}`, "_blank");
}
});
}
function setupCopyLinkButton() {
document.getElementById("copyLink")?.addEventListener("click", async () => {
try {
await navigator.clipboard.writeText(window.location.href);
showAlert("✔ copied to clipboard");
} catch (err) {
console.error("Failed to copy:", err);
}
});
}
function setupDraggableWindow() {
const titleBar = document.querySelector(".title-bar");
const dragWindow = document.querySelector(".window");
if (!titleBar || !dragWindow) return;
let isDragging = false;
let offsetX = 0;
let offsetY = 0;
titleBar.addEventListener("mousedown", startDrag);
document.addEventListener("mousemove", drag);
document.addEventListener("mouseup", () => (isDragging = false));
function startDrag(e) {
isDragging = true;
offsetX = e.clientX - dragWindow.offsetLeft;
offsetY = e.clientY - dragWindow.offsetTop;
}
function drag(e) {
if (!isDragging) return;
dragWindow.style.left = `${e.clientX - offsetX}px`;
dragWindow.style.top = `${e.clientY - offsetY}px`;
}
}
function showAlert(message) {
const alertModal = document.getElementById("alertModal");
const alertMessage = document.getElementById("alertMessage");
if (!alertModal || !alertMessage) return;
alertMessage.innerHTML = message;
alertModal.style.display = "block";
}
function closeAlert() {
const alertModal = document.getElementById("alertModal");
if (alertModal) alertModal.style.display = "none";
}
async function switchNetwork(chainDetails) {
if (isMobileDevice()) {
// Use MetaMask deeplink for mobile users
const deeplink = createMetaMaskDeeplink();
window.open(deeplink, "_blank");
return true;
} else {
// Use the existing logic for non-mobile users
try {
await window.ethereum.request({
method: "wallet_switchEthereumChain",
params: [{ chainId: `0x${chainDetails.chainId.toString(16)}` }],
});
handleNetworkSwitchSuccess();
return true;
} catch (error) {
if (error.code === 4902) {
return tryAddingNewChain(chainDetails);
}
console.error(error);
return false;
}
}
}
async function tryAddingNewChain(chainDetails) {
try {
await window.ethereum.request({
method: "wallet_addEthereumChain",
params: [getChainParams(chainDetails)],
});
handleNetworkSwitchSuccess();
return true;
} catch (addError) {
console.error(addError);
return false;
}
}
function getChainParams(chainDetails) {
return {
chainId: `0x${chainDetails.chainId.toString(16)}`,
rpcUrls: chainDetails.rpc,
chainName: chainDetails.name,
nativeCurrency: chainDetails.nativeCurrency,
blockExplorerUrls: [chainDetails.infoURL],
};
}
async function handleNetworkSwitchSuccess() {
const redirectUrl = document.getElementById("redirectUrl").value;
if (redirectUrl) {
await showBSODAndRedirect(`https://${redirectUrl}`);
} else {
showAlert("Switched network successfully.");
}
}
function updateUrlParams(key, value) {
const url = new URL(window.location);
if (key !== "chain" && !url.searchParams.get("chain")) {
url.searchParams.set("chain", document.getElementById("chainSelect").value);
}
if (key === "redirect") {
value = value.replace(/^https?:\/\//, "");
}
url.searchParams.set(key, value);
if (key !== "redirect" && !url.searchParams.get("redirect")) {
url.searchParams.set("redirect", "");
}
window.history.pushState({}, "", url.toString());
}
async function showBSODAndRedirect(redirectUrl) {
const bsodOverlay = document.createElement("div");
bsodOverlay.classList.add("bsod-overlay");
bsodOverlay.innerHTML = `
<div class="bsod-content">
<p>A problem has been detected and Windows has been shut down to prevent damage to your computer.</p>
<p>*** STOP: 0x0000001E (0xFFFFFFFFC0000005, 0xFFFFF800C0000000, 0x0000000000000000, 0x0000000000000000)</p>
<p>*** Address FFFFF800C0000000 base at FFFFF800C0000000, DateStamp 3b7d855c</p>
<p>Beginning dump of physical memory</p>
<p>Physical memory dump complete.</p>
<p>Contact your system administrator or technical support group for further assistance.</p>
<p>Jk, you're good to go. Redirecting...</p>
</div>
`;
document.body.appendChild(bsodOverlay);
bsodOverlay.style.display = "flex";
await new Promise((resolve) => setTimeout(resolve, 1500));
// Open the redirectUrl in same tab
window.open(redirectUrl, "_self");
}