-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
365 lines (299 loc) · 9.33 KB
/
index.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
const { ethereum } = window;
const STORAGE_STUB = "worlcoin_tester";
const abi = [
"function verifyAndExecute(address, uint256, uint256, uint256[8]) external",
];
let accounts, verifiedProof, unsavedChanges;
window.onload = load();
async function load() {
eventListeners();
getAccount();
loadData();
initWID();
setSignal();
}
function initWID() {
console.log("init World ID widget");
const _action_id = document.getElementById("actionId").value;
if (!_action_id) {
console.log("Action ID required to initialise WID widget");
showError(["actionId", "actionId_Btn"]);
return;
}
worldID.init("world-id-container", {
enable_telemetry: false,
action_id: _action_id,
on_success: onWorldIDVerified, // callback function receives proof after verification on simulator
});
}
// callback function receives proof after verification on simulator
function onWorldIDVerified(proof) {
console.log("world id verified!!");
console.log(proof);
verifiedProof = proof;
document.getElementById("autoLoad").checked && loadProof();
}
// connect metamask
async function connectWallet() {
if(!accounts.length === 0) return;
accounts = await ethereum.request({ method: "eth_requestAccounts" });
if (accounts.length !== 0) {
const account = accounts[0];
console.log("Found an authorized account:", account);
document.getElementById("walletAddress").value = account.slice(0,6) + ".." + account.slice(-6);
} else {
document.getElementById("walletAddress").value = "connect wallet";
console.log("No authorized account found");
}
const chainId = await ethereum.request({ method: "eth_chainId" });
console.log("chainId: ", chainId);
}
// gets connected wallet account
async function getAccount() {
accounts = await ethereum.request({ method: "eth_accounts" });
if (accounts.length !== 0) {
const account = accounts[0];
console.log("Found an authorized account:", account);
document.getElementById("walletAddress").value = account.slice(0,6) + ".." + account.slice(-6);
} else {
document.getElementById("walletAddress").value = "connect wallet";
console.log("No authorized account found");
}
const chainId = await ethereum.request({ method: "eth_chainId" });
console.log("chainId: ", chainId);
}
// copy the connected wallet address to the clipboard
function copyWalletAddress() {
if(accounts[0]) {
navigator.clipboard.writeText(accounts[0]);
} else {
console.log("no wallet connected");
showError(["walletAddress"]);
}
}
// action id can't be updated even though it doesn't throw and error, it doesn't work
// have to save actionId element and reload page so it is initialised with the new id
function setActionId() {
const newActionId = document.getElementById("actionId").value.trim();
if(newActionId){
localStorage.setItem(STORAGE_STUB + "actionId", JSON.stringify(newActionId));
console.log("updated action id: ", newActionId);
window.location.reload();
} else {
showError(["actionId", "actionId_Btn"]);
}
}
// to set/update the signal param
function setSignal() {
try {worldID.getProps().length;}
catch {
showError(["actionId", "actionId_Btn"]);
console.log("World ID widget not intialised");
return;
}
console.log("worldID", worldID.getProps().length == 0);
const signal = document.getElementById("inputSignal").value.trim();
if(signal){
worldID.update({
signal: signal,
});
// document.getElementById("inputSignal").value = newSignal;
console.log("updated signal: ", signal);
console.log("WID widget props:", worldID.getProps()); // log proof that the signal is what it should be
} else {
showError(["inputSignal", "signal_Btn"]);
}
}
// call verifyAndExecute on the smart contract
async function verifyProof() {
try {
const { ethereum } = window;
if (ethereum) {
const missingInputs = [];
if(accounts.length === 0) missingInputs.push(["walletAddress"]);
const contractAddress = document.getElementById("contractAddress").value.trim();
!contractAddress && missingInputs.push("contractAddress");
console.log("contract address:", contractAddress);
const signal = document.getElementById("inputSignal").value.trim();
!signal && missingInputs.push("inputSignal");
console.log("signal:", signal);
let root = document.getElementById("inputMerkRoot").value.trim();
if(!root) missingInputs.push("inputMerkRoot");
else root = ethers.BigNumber.from(root);
console.log("merkle root:", root);
let nullifier = document.getElementById("inputNullHash").value.trim();
if(!nullifier) missingInputs.push("inputNullHash");
else nullifier = ethers.BigNumber.from(nullifier);
console.log("nullifier hash:", nullifier);
const proof = document.getElementById("inputProof").value.trim();
!proof && missingInputs.push("inputProof");
if(missingInputs.length) {
showError(missingInputs);
console.log("required inputs missing:",...missingInputs)
return;
}
const unpackedProof = ethers.utils.defaultAbiCoder.decode(
["uint256[8]"],
proof
)[0];
console.log("unpacked proof");
console.log(unpackedProof);
console.log("/unpacked proof");
const provider = new ethers.providers.Web3Provider(ethereum);
const signer = provider.getSigner();
const connectedContract = new ethers.Contract(
contractAddress,
abi,
signer
);
try {
console.log("verifyAndExecute");
const retVal = await connectedContract.verifyAndExecute(
signal,
root,
nullifier,
unpackedProof,
{ gasLimit: 600000 }
);
await retVal.wait();
console.log("result: ", retVal);
} catch (error) {
console.log("error:", error);
}
} else {
showError(["walletAddress"]);
console.log("Ethereum object doesn't exist!");
}
} catch (error) {
console.log(error);
}
}
// populate the verifyAndExecute proof inputs with the most recently received
// verified proof: merkle root, nullifier hash, & packed proof
function loadProof() {
console.log("load proof");
document.getElementById("inputMerkRoot").value = verifiedProof.merkle_root;
document.getElementById("inputNullHash").value = verifiedProof.nullifier_hash;
document.getElementById("inputProof").value = verifiedProof.proof;
}
// save inputs and text area state
function saveData() {
const allSaveableElements = document.getElementsByClassName("saveable");
Object.values(allSaveableElements).forEach((element) => {
let value = element.type == "checkbox" ? element.checked : element.value
localStorage.setItem(
STORAGE_STUB + element.id,
JSON.stringify(value)
);
});
console.log("saved state")
unsavedChanges = false;
}
// load saved state back into inputs and text area
function loadData() {
const allSaveableElements = document.getElementsByClassName("saveable");
Object.values(allSaveableElements).forEach((element) => {
if(element.type == "checkbox") {
element.checked = JSON.parse(localStorage.getItem(STORAGE_STUB + element.id));
// console.log("loaded %s: ", element.id, element.checked);
} else {
element.value = JSON.parse(localStorage.getItem(STORAGE_STUB + element.id));
// console.log("loaded %s: ", element.id, element.value);
}
});
console.log("loaded state")
}
// event listeners
function eventListeners() {
// event listeners
console.log("event listeners");
const copyIcon = document.getElementById("walletCopy");
copyIcon.addEventListener(
"click",
function () {
copyWalletAddress();
},
false
);
const walletAddressBox = document.getElementById("walletAddress")
walletAddressBox.addEventListener(
"click",
function () {
connectWallet();
},
false
);
const actionId_Btn = document.getElementById("actionId_Btn");
actionId_Btn.addEventListener(
"click",
function () {
setActionId();
},
false
);
const signal_Btn = document.getElementById("signal_Btn");
signal_Btn.addEventListener(
"click",
function () {
setSignal();
},
false
);
const save_Btn = document.getElementById("save_Btn");
save_Btn.addEventListener(
"click",
function () {
saveData();
},
false
);
const verify_Btn = document.getElementById("verify_Btn");
verify_Btn.addEventListener(
"click",
function () {
verifyProof();
},
false
);
const loadProof_Btn = document.getElementById("loadProof_Btn");
loadProof_Btn.addEventListener(
"click",
function () {
loadProof();
},
false
);
// prompt if leaving page with unsaved changes
window.onbeforeunload = function () {
console.log("leaving with unsaved changes?");
if (unsavedChanges) return "leaving page with unsaved changes?";
};
// list for metamask account change
ethereum.on('accountsChanged', function () {
console.log("account changed");
getAccount();
})
// listen for saveable changes
addEventListener("input", (evt) => {
if (!unsavedChanges && evt.target.classList.contains("saveable")) {
console.log("unsaved changes");
unsavedChanges = true;
}
});
// ctrl + s shortcut calls page saveData()
document.addEventListener("keydown", (event) => {
if (event.ctrlKey && (event.key === "s" || event.key === "S")) {
event.preventDefault(); //prevent browser save dialogue
console.log("ctrl + s: save");
saveData();
}
});
}
// highlight elements in error : takes an array of elements
function showError(targetElements) {
targetElements.forEach((element) => {
const tgt = document.getElementById(element);
tgt.classList.add("errorEffects");
setTimeout(() => tgt.classList.remove("errorEffects"), 2000);
});
}