-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathapply_abi_on_etherscan.user.js
411 lines (327 loc) · 12.3 KB
/
apply_abi_on_etherscan.user.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
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
// ==UserScript==
// @name Apply ABI on Etherscan
// @namespace https://openuserjs.org/users/Velenir
// @version 1.1.3
// @encoding utf-8
// @description Adds an option to use abi from a different contract to etherscan's Read Contract/Write Contract panes
// @author Velenir
// @homepage https://github.com/Velenir/apply-abi-on-etherscan/
// @supportURL https://github.com/Velenir/apply-abi-on-etherscan/issues
// @updateURL https://raw.githubusercontent.com/Velenir/apply-abi-on-etherscan/master/apply_abi_on_etherscan.user.js
// @downloadURL https://raw.githubusercontent.com/Velenir/apply-abi-on-etherscan/master/apply_abi_on_etherscan.user.js
// @license MIT
// @match http://*.etherscan.io/address/*
// @match https://*.etherscan.io/address/*
// @run-at document-body
// @grant unsafeWindow
// @grant GM_setValue
// @grant GM_getValue
// @grant GM_deleteValue
// ==/UserScript==
(function () {
"use strict";
const window = typeof unsafeWindow !== "undefined" ? unsafeWindow : window;
const saveValue =
typeof GM_setValue !== "undefined"
? GM_setValue
: window.localStorage.setItem.bind(localStorage);
const getValue =
typeof GM_getValue !== "undefined"
? GM_getValue
: window.localStorage.getItem.bind(localStorage);
const deleteValue =
typeof GM_deleteValue !== "undefined"
? GM_deleteValue
: window.localStorage.removeItem.bind(localStorage);
window.addEventListener("DOMContentLoaded", addProxyForms);
const isElementVisible = element => element.offsetParent !== null;
const getlocalStorageKey = () => {
const { origin, pathname } = window.location;
return origin + pathname;
};
const getInfoFromURL = () => {
const { pathname, hostname } = window.location;
const pathnameSegments = pathname.split("/");
const address = pathnameSegments[pathnameSegments.length - 1];
const network = hostname.replace("etherscan.io", "").slice(0, -1);
return {
address,
network: network || "mainnet"
};
};
const blockOriginalABIloading = () => {
window.readContractLoaded = true;
window.writeContractLoaded = true;
};
function addProxyForms() {
const readContractPane = document.getElementById("readContract");
const writeContractPane = document.getElementById("writeContract");
const eventsPane = document.getElementById("events");
if (!readContractPane || !writeContractPane || !eventsPane) return;
blockOriginalABIloading();
const { address: originalAddress, network } = getInfoFromURL();
const originalABIAddress =
window.litContractABIAddressCode || originalAddress;
let abiAddress = null;
const panes = [readContractPane, writeContractPane, eventsPane];
const iframes = panes.map(pane => pane.querySelector("iframe"));
const [readframe, writeframe, eventsframe] = iframes;
const inputId = "apply-abi-address-";
const forms = panes.map((pane, i) => {
const form = createForm(inputId, i);
pane.prepend(form);
return form;
});
const [readform, writeform, eventsform] = forms;
const onSubmit = e => {
e.preventDefault();
const form = e.currentTarget;
const address = form.getAddress();
abiAddress = address;
setFormsTo(forms, address);
applyAddressToIframes(address, iframes);
};
const onReset = e => {
e.preventDefault();
const form = e.currentTarget;
abiAddress = null;
clearForms(forms);
applyAddressToIframes(
originalAddress,
iframes,
false,
originalABIAddress
);
clearStorage();
};
forms.forEach(form => {
form.addEventListener("submit", onSubmit);
form.addEventListener("reset", onReset);
});
window.addEventListener("load", () =>
applyAddressToIframes(
abiAddress || originalAddress,
iframes,
false,
abiAddress || originalABIAddress
)
);
restoreFromStorage(address => {
abiAddress = address;
setFormsTo(forms, address);
applyAddressToIframes(address, iframes);
});
changeLinks(iframes, forms);
function changeLinks() {
const rcTab = document.querySelector('a[href="#readContract"]');
const wcTab = document.querySelector('a[href="#writeContract"]');
const eTab = document.querySelector('a[href="#events"]');
const addClickListener = (tab, form, frame) => {
tab.addEventListener("click", () => {
// only change the form that will be displayed
if (!isElementVisible(form))
abiAddress ? form.setAddress(abiAddress) : form.clear();
applyAddressToIframes(
abiAddress || originalAddress,
[frame],
true,
abiAddress || originalABIAddress
);
});
};
addClickListener(rcTab, readform, readframe);
addClickListener(wcTab, writeform, writeframe);
addClickListener(eTab, eventsform, eventsframe);
}
function applyAddressToIframes(
address,
iframes,
force,
abiAddress = address
) {
iframes.forEach(iframe => {
// don't reload the frmae unless it's visible or about to come into view
// otherwise it doesn't get properly resized on load event
if (!force && !isElementVisible(iframe)) return;
const url = new URL(iframe.src);
const { id } = iframe;
let prop;
if (id === "readcontractiframe" || id === "eventsIframe") {
prop = "v";
} else if (id === "writecontractiframe") {
prop = "a";
} else {
throw new Error(
`Expected iframe with id readcontractiframe or writecontractiframe. Got ${id}`
);
}
const prevAddress = url.searchParams.get(prop);
if (
prevAddress === null ||
prevAddress.toLowerCase() !== address.toLowerCase()
) {
let newSrc;
if (id === "readcontractiframe") {
newSrc = createReadIframeSrc(address, abiAddress);
} else if (id === "writecontractiframe") {
newSrc = createWriteIframeSrc(address);
} else if (id === "eventsIframe") {
newSrc = createEventsIframeSrc(address, abiAddress);
}
iframe.src = newSrc;
}
});
}
function createReadIframeSrc(address, abiAddress = address) {
return `/readContract?m=${
window.mode
}&a=${originalAddress}&v=${abiAddress}`;
}
function createWriteIframeSrc(address) {
return `/writecontract/index.html?m=${
window.mode
}&v=0.0.6&a=${address}&n=${network}`;
}
function createEventsIframeSrc(address, abiAddress = address) {
return `/address-events?m=${
window.mode
}&a=${originalAddress}&v=${abiAddress}`;
}
const observer = createMutationObserverForConnector();
// watch for when Metamask is connected
writeframe.addEventListener("load", () => {
// observer may have not been disconnected frm previous iframe's #connector
// happens when Metamask was never connected
observer.disconnect();
const header = writeframe.contentDocument.getElementById("header");
if (!header)
throw new Error(
"iframe #writecontractiframe doesn't have '.row .header' element"
);
observer.observe(header, {
attributes: true,
attributeFilter: ["title"],
subtree: true
});
});
window.addEventListener("beforeunload", () => {
if (!abiAddress) return
const readframeFailed = /Sorry, we were unable to retrieve a valid Contract ABI for this contract\.[\n\s]Unable to read contract information/.test(
readframe.contentDocument.body.innerText
);
const writeframeFailed = /Sorry, we were unable to locate a matching Contract ABI or SourceCode for this contract\.(\n\n)?If you are the contract owner, please Verify Your Contract Source Code here/.test(
readframe.contentDocument.body.innerText
);
if (readframeFailed || writeframeFailed) return;
saveToStorage(abiAddress);
});
function createMutationObserverForConnector() {
const observer = new MutationObserver(mutations => {
// can't observe #connector directly, it's dynamically added after page load
const connectorMutation = mutations.find(
m => m.target.id === "connector"
);
// only react to change to #connector.title
if (!connectorMutation) return;
const connectorSpan = connectorMutation.target;
const title = connectorSpan.title;
// Logic inside iframe #writecontract changes #connector.title to Connected when
// Metamask is connected and
// myContractInstance var is filled
if (title === "Connected") {
const frameWindow = writeframe.contentWindow;
const { myContract, myContractInstance } = frameWindow;
if (!myContract) {
throw new Error(
`No web3 Contract object at window.myContract in ${
writeframe.id
} iframe`
);
}
if (!myContractInstance) {
throw new Error(
`No web3 Contract instance at window.myContractInstance in ${
writeframe.id
} iframe`
);
}
if (myContractInstance.address !== originalAddress) {
// replace contract instance with one connected to originalAddress
// otherwise it is connected to ?a=<address> from iframe.src
// which is abiAddress we provided
frameWindow.myContractInstance = myContract.at(originalAddress);
}
// currently myContractInstance is no longer recreated
// safe to disconnect observer
observer.disconnect();
}
});
return observer;
}
}
function restoreFromStorage(cb) {
const prevAddress = getValue(getlocalStorageKey());
if (prevAddress) cb(prevAddress);
}
function saveToStorage(value) {
saveValue(getlocalStorageKey(), value);
}
function clearStorage() {
deleteValue(getlocalStorageKey());
}
function createForm(InputId, idInd) {
const form = document.createElement("form");
form.className =
"mb-2 mb-md-0 mt-2 order-md-1 w-100 w-lg-auto space-bottom-1";
form.autocomplete = "off";
form.setAttribute("autocorrect", "off");
form.autocapitalize = "off";
form.spellcheck = false;
// outer
const divOuter = document.createElement("div");
divOuter.className = "input-group input-group-sm";
form.appendChild(divOuter);
// label
const divLabel = document.createElement("div");
divLabel.className = "d-md-block input-group-prepend";
const inputId = InputId + idInd++;
const label = document.createElement("label");
label.textContent = "Apply abi from ";
label.htmlFor = inputId;
label.className =
"font-size-base font-weight-bold input-group-text text-dark";
divLabel.appendChild(label);
// input
const input = document.createElement("input");
input.id = inputId;
input.placeholder = "address";
input.required = true;
input.pattern = "^\\s*0x[0-9A-Fa-f]{40}\\s*$";
input.title = "Contract address 0x1234...";
input.className = "form-control";
// buttons
const divButtons = document.createElement("div");
divButtons.className = "input-group-append";
const buttonApply = document.createElement("button");
buttonApply.textContent = "Apply";
buttonApply.type = "submit";
buttonApply.className = "btn btn-primary font-size-base font-weight-bold";
const buttonReset = document.createElement("button");
buttonReset.textContent = "Restore";
buttonReset.type = "reset";
buttonReset.className = "btn btn-secondary font-size-base font-weight-bold";
divButtons.append(buttonApply, buttonReset);
//outer
divOuter.append(divLabel, input, divButtons);
form.setAddress = address => (input.value = address);
form.getAddress = () => input.value.trim();
form.clear = () => (input.value = "");
return form;
}
function clearForms(forms) {
forms.forEach(f => f.clear());
}
function setFormsTo(forms, address) {
forms.forEach(f => f.setAddress(address));
}
})();