-
Notifications
You must be signed in to change notification settings - Fork 0
/
script.js
310 lines (254 loc) · 11.6 KB
/
script.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
import Web3 from 'web3';
import { Web3BigNumber } from 'web3-bignumber';
import { Web3errors } from 'web3-errors-extract';
BigInt.prototype.toJSON = function () {
return this.toString();
};
const eth_requestAccounts = async () => {
const accounts = await window.ethereum.request({
"method": "eth_requestAccounts",
"params": []
});
return accounts;
}
const wallet_switchEthereumChain = async (chainid) => {
await window.ethereum.request({
method: 'wallet_switchEthereumChain',
params: [{ chainId: "0x" + Number(chainid).toString(16) }]
});
}
export const topLevel = {
contract: null,
address: null,
userBalance: null,
web3: null,
web3Errors: null
}
export const setDataToLocalStorage = (name, data) => {
window.localStorage.setItem(name, data);
}
export const getDataFromLocalStorage = (name) => {
return window.localStorage.getItem(name);
}
export const reloadWindow = () => {
window.location.reload();
}
const handleClick = async (event, isCallFnc, isPayable) => {
const button = event.target;
console.log(button)
const { contract, web3Errors, address } = topLevel;
const children = [...button.parentNode.children];
const inputs = children.filter(element => element.nodeName === 'INPUT');
const displaySpan = children[children.length - 1];
displaySpan.innerText = "";
displaySpan.style.color = "";
displaySpan.style.fontWeight = "";
const argsFilter = inputs.filter(input => input.placeholder !== "ether value (in wei)");
const msgValue = inputs.filter(input => input.placeholder === "ether value (in wei)");
let required = false;
const args = argsFilter.map(input => {
if (!input.placeholder.includes("string") && input.value == "") {
required = true;
} else if (input.value.includes('\'') || input.value.includes('\"') || input.value.includes('[') || input.value.includes(']')) {
return JSON.parse(input.value);
} else if (input.placeholder.includes("bool")) {
return Boolean(input.value);
}
return input.value;
});
console.log(args)
if (required) {
displaySpan.innerText = "Error: Please enter all required fields";
displaySpan.style.color = "red";
displaySpan.style.fontWeight = "bold";
return;
}
const buttonText = button.innerText;
const functionName = buttonText.slice(buttonText.indexOf(")") + 1, buttonText.length).trim();
console.log("functionName: ", functionName);
let result;
let err;
try {
displaySpan.innerText = "Loading...";
const contractMethod = contract.methods[functionName](...args);
const fromData = isPayable ? { from: address, value: msgValue[0].value } : { from: address };
await contractMethod.estimateGas(fromData);
displaySpan.innerText = isCallFnc ? "Loading..." : "Transaction Initiated...";
displaySpan.classList.add("result");
result = await contractMethod[isCallFnc ? "call" : "send"](fromData);
} catch (error) {
console.log(error)
err = await web3Errors.getErrorMessage(error);
}
console.log("result: ", result);
if (result || parseInt(result) == 0 || typeof result == "boolean") {
delete result["__length__"];
const res = JSON.stringify(result, null, 4);
result = res;
} else {
if (err?.name) {
const res = JSON.stringify(err, null, 4);
err = err.name + "\n\n" + res;
}
displaySpan.style.color = "red";
displaySpan.style.fontWeight = "bold";
}
displaySpan.innerText = result || err;
}
export const connect = async (abi, chainid, rpc) => {
const connectwalletBtn = document.querySelector("#connectwallet");
const metamask_msg = document.querySelector("#metamask_msg");
const rpc_error = document.querySelector("#rpc-error");
const chain_error = document.querySelector("#chain-error");
const switch_network = document.querySelector("#switch-network");
const network_id = document.querySelector("#network_id");
if (!window.ethereum && !rpc) {
metamask_msg.innerHTML = 'Non-Ethereum browser detected. Required metamask for transactions or connect to rpc url';
rpc_error.style.display = "block";
console.log(
'Non-Ethereum browser detected. You should consider trying MetaMask!'
);
return;
}
let web3 = new Web3(window.ethereum);
let web3Errors = new Web3errors(window.ethereum, [abi || []]);
connectwalletBtn.innerText = "Connecting...";
switch_network.addEventListener("click", async () => {
await wallet_switchEthereumChain(chainid);
});
try {
const accounts = await eth_requestAccounts();
let address = accounts[0];
let userBalance = await web3.eth.getBalance(address);
console.log("Connected: ", address)
window.ethereum.on("accountsChanged", async (accounts) => {
address = accounts[0];
userBalance = await web3.eth.getBalance(address);
console.log("Connected: ", address)
metamask_msg.innerHTML = address ? `Metamask Connected (${address?.substring(0, 5)}...${address?.substring(address.length - 5, address.length)}) (${Web3BigNumber(userBalance).toSmall().trimDecimalPlaces(2)} eth)` : "Required metamask for transactions. Metamask Not Connected";
connectwalletBtn.style.display = address ? "none" : "inline-block";
});
window.ethereum.on("chainChanged", () => reloadWindow());
const networkid = await window.ethereum.request({
"method": "eth_chainId",
"params": []
});
if (chainid != "" && chainid != parseInt(networkid)) {
chain_error.style.display = "block";
await wallet_switchEthereumChain(chainid);
}
network_id.innerHTML = `Network ID: ${parseInt(networkid)}`;
console.log("Chain ID: ", parseInt(networkid));
metamask_msg.innerHTML = `Metamask Connected (${address?.substring(0, 6)}...${address?.substring(address.length - 4, address.length)}) (${Web3BigNumber(userBalance).toSmall().trimDecimalPlaces(2)} eth)`;
connectwalletBtn.innerText = "Connect Metamask";
connectwalletBtn.style.display = "none";
topLevel.web3 = web3;
topLevel.web3Errors = web3Errors;
topLevel.address = address;
topLevel.userBalance = userBalance;
} catch (error) {
metamask_msg.innerHTML = "Required metamask for transactions. Metamask Not Connected";
connectwalletBtn.innerText = "Connect Metamask";
connectwalletBtn.style.display = "inline-block";
console.log(error)
}
}
export const settingWeb3 = async (selectedLevel) => {
const rpc_error = document.querySelector("#rpc-error");
const metamask_msg = document.querySelector("#metamask_msg");
const contract_balance = document.querySelector("#contract_balance");
const input_web3rpc = document.getElementById("web3rpc");
const input_contractaddress = document.getElementById("contractaddress");
const input_abi = document.getElementById("abi");
const input_savename = document.getElementById("savename");
const input_chainid = document.getElementById("chainid");
const container = document.getElementById("container");
const readtab = document.getElementById("readtab");
const writetab = document.getElementById("writetab");
const { abi, contractaddress, rpc, savename, chainid } = selectedLevel;
let web3;
let web3Errors;
if (rpc) {
web3 = new Web3(rpc);
web3Errors = new Web3errors(rpc, [abi || []]);
rpc_error.style.display = "none";
} else if (window.ethereum) {
web3 = new Web3(window.ethereum);
web3Errors = new Web3errors(window.ethereum, [abi || []]);
rpc_error.style.display = "none";
} else {
rpc_error.style.display = "block";
metamask_msg.innerHTML = 'Non-Ethereum browser detected. Required metamask for transactions or connect to rpc url';
}
input_web3rpc.value = rpc || "";
input_contractaddress.value = contractaddress || "";
input_abi.value = abi ? JSON.stringify(abi, null, 2) : "";
input_savename.value = savename || "";
input_chainid.value = chainid || "";
await connect(abi, chainid, rpc);
if (!abi || !contractaddress || !web3) {
return;
}
topLevel.web3 = web3;
topLevel.web3Errors = web3Errors;
topLevel.contract = new web3.eth.Contract(abi, contractaddress);
const contractBalance = await web3.eth.getBalance(contractaddress);
contract_balance.innerHTML = `Contract Balance: ${Web3BigNumber(contractBalance).toSmall().trimDecimalPlaces(2)} eth`;
const abiSorted = abi.sort((a, b) => {
let x = a.name?.toLowerCase();
let y = b.name?.toLowerCase();
if (x < y) { return -1; }
if (x > y) { return 1; }
return 0;
});
const groups = abiSorted.filter(element => element.type === 'function')
.map(element => {
const button = document.createElement('button');
button.textContent = `(${element.stateMutability}) ${element.name}`;
button.onclick = (e) => handleClick(e, element.stateMutability === 'view' || element.stateMutability === 'pure', element.stateMutability === 'payable');
button.setAttribute("class", `btn ${element.stateMutability === 'view' || element.stateMutability === 'pure' ? "callbtn" : element.stateMutability === 'payable' ? "paybtn" : "nonpaybtn"}`);
const group = document.createElement('div');
group.setAttribute("class", "group");
group.ariaLabel = element.stateMutability === 'view' || element.stateMutability === 'pure' ? "read" : "write";
const panel = document.createElement('div');
panel.setAttribute("class", "accordian-panel");
const panelTitle = document.createElement('button');
panelTitle.setAttribute("class", "accordian-title");
panelTitle.textContent = `${element.name}`;
panelTitle.addEventListener("click", () => {
group.classList.toggle("activepanel")
})
const brEle = document.createElement('br');
group.appendChild(panelTitle);
panel.appendChild(button);
for (let i = 0; i < element.inputs.length; i++) {
const input = element.inputs[i];
const inputText = document.createElement('input');
inputText.setAttribute("type", "text");
inputText.setAttribute("placeholder", `${input.type} ${input.name}`);
inputText.setAttribute("required", "true");
inputText.setAttribute("class", "inputdata");
panel.appendChild(inputText);
}
if (element.stateMutability === 'payable') {
const inputText = document.createElement('input');
inputText.setAttribute("type", "text");
inputText.setAttribute("placeholder", `ether value (in wei)`);
inputText.setAttribute("required", "true");
inputText.setAttribute("class", "inputdata");
panel.appendChild(inputText);
}
const display = document.createElement('span');
panel.appendChild(brEle);
panel.appendChild(display);
group.appendChild(panel);
return group;
});
for (let i = 0; i < groups.length; i++) {
if (groups[i].ariaLabel === "read") {
readtab.appendChild(groups[i]);
} else {
writetab.appendChild(groups[i]);
}
}
}