-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.js
472 lines (410 loc) · 19.6 KB
/
main.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
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
// Uses the async-await "serial" fashion to fetch the chain data.
//
// This can be slow, but simplifies the logic.
// (Anyway, Ethereum is slower!!)
//
async function fetchAndShowContractData(contract, signableContract) {
let yourAddress = ethereum.selectedAddress;
document.getElementById("your-address").innerHTML = `Your address: ${yourAddress}`;
// Demo-use nicknaming:
let nickName = getNickName(yourAddress);
if (nickName != null) {
document.getElementById("header").innerText = `Welcome, ${nickName}!`;
}
clearAllButtons();
if (yourAddress == null) {
addLogInButton();
}
let generalInfo = "\nGeneral Info:\n";
let personalInfo = "\nPersonal Info:\n";
let errorInfo = "\n";
if (yourAddress == null) {
personalInfo += "N/A\n";
}
let noError = errorInfo;
let summary = "This auction has not started yet.";
let query = async (queryName, queryFunction) => {
try {
return await queryFunction();
} catch (err) {
console.error(err);
errorInfo += `Failed to query "${queryName}"; see console log for details.\n`;
return null;
}
}
// I still wanna know how fast/slow it is. Let me measure it.
let startTime = new Date().getTime();
let seller = await query("seller()", async () => {
let seller = await contract.seller();
generalInfo += `Auction seller: ${seller}\n`;
return seller;
})
let tokenAddress = await query("tokenAddress()", async () => {
let tokenAddress = await contract.tokenAddress();
generalInfo += `Address of the NFT: ${tokenAddress}\n`;
return tokenAddress;
})
let tokenID = await query("tokenID()", async () => {
let tokenID = await contract.tokenID();
generalInfo += `ID of the NFT: ${tokenID}\n`;
return tokenID;
})
let reservePrice = await query("reservePrice()", async () => {
let priceInWei = await contract.reservePrice();
generalInfo += `The lowest possible price to bid: ${asWeiAndEther(priceInWei)}\n`;
return priceInWei;
})
let started = await query("started()", async () => {
let started = await contract.started();
if (!started) {
generalInfo += "Auction has not started yet!\n";
if (isEqual(seller, yourAddress)) {
if (tokenID != null && tokenAddress != null) {
let nftContract = await getContractAPI(tokenAddress, "toy-nft.abi.json", true);
let approvedAddress = await nftContract.getApproved(tokenID);
if (isEqual(approvedAddress, contract.address)) {
personalInfo += "You are the seller! Are you ready to start the auction?\n";
addStartAuctionButton(signableContract);
} else {
personalInfo += "You have not approved this contract to use your NFT yet.\n";
addApproveButton(signableContract, tokenAddress, tokenID);
}
}
} else if (yourAddress != null) {
personalInfo += "Please wait patiently until the auction starts. Wanna learn how to play?\n";
}
}
return started;
})
if (started) {
let endOfBidding = await query("endofBidding()", async () => {
let timestamp = await contract.endOfBidding();
timestamp = timestamp.toNumber();
readableTime = new Date(timestamp * 1000).toLocaleString();
generalInfo += `Bidding deadline: ${readableTime} (Timestamp is ${timestamp})\n`;
return timestamp;
})
let endOfRevealing = await query("endOfRevealing()", async () => {
let timestamp = await contract.endOfRevealing();
timestamp = timestamp.toNumber();
readableTime = new Date(timestamp * 1000).toLocaleString();
generalInfo += `Revealing deadline: ${readableTime} (Timestamp is ${timestamp})\n`;
return timestamp;
})
let now = Math.floor(new Date().getTime() / 1000);
if (endOfBidding != null && now > endOfBidding) {
summary = "This auction is at the REVEALING stage.";
} else {
summary = "This auction is at the BIDDING stage.";
}
if (endOfBidding != null && endOfRevealing != null) {
if ((yourAddress != null && !isEqual(yourAddress, seller)) && now < endOfBidding) {
await query("hashedBidOf(address)", async () => {
let yourHashedBid = await contract.hashedBidOf(yourAddress);
if (isZeroHex(yourHashedBid)) {
personalInfo += `Seems like you have not bidded yet. Wanna join?\n`;
if (reservePrice != null) {
addDepositButton(signableContract, reservePrice);
}
} else {
personalInfo += `Your secret bid is ${yourHashedBid}.\nDon't forget to reveal it when it's time!\n`;
}
})
}
if ((yourAddress != null && !isEqual(yourAddress, seller)) && (now >= endOfBidding && now < endOfRevealing)) {
await query("revealed(address)", async () => {
let yourHashedBid = await contract.hashedBidOf(yourAddress);
if (isZeroHex(yourHashedBid)) {
personalInfo += `You cannot join at this time.\n`;
} else {
let youHaveRevealed = await contract.revealed(yourAddress);
if (youHaveRevealed) {
personalInfo += `You have successfully revealed! Let's wait for the final result. Good luck!\n`;
} else {
personalInfo += `Seems like you have not revealed yet. Don't miss the deadline!\n`;
addRevealButton(signableContract);
}
}
})
}
if (isEqual(yourAddress, seller) && now < endOfRevealing) {
personalInfo += `Welcome back, seller! Let's grab some tea and wait for a good price!\n`;
}
let gracePeriod = 30; // wait for another 30 seconds just to be sure (avg. block time on Ethereum is ~15s)
if (now >= endOfRevealing && now < endOfRevealing + gracePeriod) {
summary = "This auction will end soon!";
if (yourAddress != null) {
personalInfo += `Do you believe in last-minute miracles???\n`;
}
}
if (now >= endOfRevealing + gracePeriod) {
summary = "This auction has ended.";
let highBidder = await query("highBidder()", async () => {
let highBidder = await contract.highBidder();
if (isEqual(highBidder, seller)) {
generalInfo += `There was no winner! Oops...\n`;
} else {
generalInfo += `Auction ended, the winner was ${highBidder}\n`;
}
return highBidder;
})
let highBid = await query("highBid()", async () => {
let highBidInWei = await contract.highBid();
if (highBidder != null && !isEqual(highBidder, seller)) {
generalInfo += `The highest bid was ${asWeiAndEther(highBidInWei)}\n`;
}
return highBidInWei;
})
let secondBid = await query("secondBid()", async () => {
let secondBidInWei = await contract.secondBid();
if (highBidder != null && !isEqual(highBidder, seller)) {
generalInfo += `The second highest bid (the deal) was ${asWeiAndEther(secondBidInWei)}\n`;
}
return secondBidInWei;
})
let withdrawn = await query("balanceOf()", async () => {
let yourBalance = await contract.balanceOf(yourAddress);
return yourBalance.eq(0);
})
let claimed = await query("nft.ownerOf()", async () => {
let nftContract = await getContractAPI(tokenAddress, "toy-nft.abi.json", true);
let owner = await nftContract.ownerOf(tokenID);
return owner != null && !isEqual(owner, contract.address);
})
if (isEqual(seller, yourAddress)) {
if (isEqual(highBidder, seller)) {
personalInfo += `Unfortunately, your NFT was not sold out!\n`;
if (claimed) {
personalInfo += `You have successfully claimed your NFT back.\n`;
} else {
personalInfo += `You can call claim() to get your NFT back, if you haven't done so.\n`;
addClaimButton(signableContract);
}
} else if (highBidder != null && secondBid != null) {
personalInfo += `Congratulations! Your NFT was sold at the price of ${asWeiAndEther(secondBid)}!\n`;
if (withdrawn) {
personalInfo += `There is no more money to withdraw at this time.\n`;
} else {
personalInfo += `You can call withdraw() to get your money.\n`;
addWithdrawButton(signableContract);
}
}
}
if (yourAddress != null && !isEqual(yourAddress, seller)) {
if (isEqual(highBidder, yourAddress) && secondBid != null) {
personalInfo += `Congratulations! You won the auction. You paid the seller ${asWeiAndEther(secondBid)}.\n`;
if (claimed) {
personalInfo += `You have successfully claimed your NFT.\n`;
} else {
personalInfo += `You can call claim() to claim your NFT, if you haven't done so.\n`;
addClaimButton(signableContract);
}
if (withdrawn) {
personalInfo += `There is no more money to withdraw at this time.\n`;
} else {
personalInfo += `And you can call withdraw() to get back your overpaid part of the deposit.\n`;
addWithdrawButton(signableContract);
}
}
if (!isEqual(highBidder, yourAddress)) {
await query("revealed(address)", async () => {
let yourHashedBid = await contract.hashedBidOf(yourAddress);
if (!isZeroHex(yourHashedBid)) {
personalInfo += `You did not win the auction. Better luck next time!\n`;
youHaveRevealed = await contract.revealed(yourAddress);
if (true || youHaveRevealed == true) {
if (withdrawn) {
personalInfo += `There is no more money to withdraw at this time.\n`;
} else {
personalInfo += `You can call withdraw() to get back your deposit.\n`;
addWithdrawButton(signableContract);
}
}
// if (youHaveRevealed == false) {
// personalInfo += `Unfortunately you cannot withdraw your deposit, because you did not reveal your bid in time.\n`;
// }
} else {
personalInfo += `You did not participate in this auction.\n`;
}
})
}
}
}
}
}
// finalize:
let endTime = new Date().getTime();
console.log(`Query time elapsed: ${endTime - startTime} ms.`)
document.getElementById("general-info").innerText = generalInfo;
document.getElementById("personal-info").innerText = personalInfo;
document.getElementById("error-info").innerText = errorInfo;
if (errorInfo != noError) {
summary = ""; // does not show summary upon error
}
document.getElementById("summary").innerText = summary;
if (yourAddress != null && document.getElementById("buttons").childElementCount > 0) {
document.getElementById("waiting-time").innerText = await waitingTimeAsString();
}
// set timeout for the next run:
setTimeout(fetchAndShowContractData, 10000, contract, signableContract);
}
// functions to add buttons:
function addRecommendButton(text, customAsyncFunction) {
let button = document.createElement("button");
button.innerText = text;
button.onclick = async () => {
try {
let result = await customAsyncFunction();
let txURL = "https://ropsten.etherscan.io/tx/" + result.hash;
document.getElementById("success-info").innerHTML =
"Your transaction has been successfully submitted to the blockchain!<br>" +
"It should take effect shortly; when it's done, this page will be automatically updated.<br>" +
"Track the progress " + makeHref("here", txURL) + "!";
document.getElementById("errors").innerText = "";
addDinoGame("game");
// clear info when done:
await result.wait();
location.reload();
} catch (err) {
console.log(err);
document.getElementById("errors").innerText = "Operation failed!\n"
+ "Error Message: " + err.message + "\n"
+ "See console logs for more information.";
document.getElementById("success-info").innerText = "";
}
}
document.getElementById("buttons").appendChild(button);
}
function addDepositButton(signableContract, minimum) {
addRecommendButton("Secretly Bid", async () => {
// query the user:
let bidInWei = null;
while (!bidInWei || bidInWei.lt(minimum)) {
response = window.prompt(
"How much (in wei) would you bid for the NFT?\n\n" +
"NOTE: your bid must be NO SMALLER THAN the minimal price (" + minimum.toString() + " wei)",
""
);
bidInWei = parseBigNumber(response);
}
let deposit = null;
while (!deposit || deposit.lt(bidInWei)) {
response = window.prompt(
"How much (in wei) would you deposit into the auction contract?\n\n" +
"NOTE1: your deposit must be NO SMALLER THAN your bid (" + bidInWei.toString() + " wei).\n\n" +
"NOTE2: your bid is a secret, but YOUR DEPOSIT IS PUBLIC. I recommend you use a different value from your bid.",
""
);
deposit = parseBigNumber(response);
}
let nonce = generateRandomNonce(); // directly make one for you!
let encoder = ethers.utils.defaultAbiCoder;
let hash = ethers.utils.keccak256(encoder.encode(["uint", "bytes32"], [bidInWei, nonce]));
// Download the info and alert the user:
let obj = {
"contract": signableContract.address,
"bid": bidInWei.toString(),
"nonce": nonce,
"hash": hash,
"deposit": deposit.toString(),
};
fileName = "IMPORTANT-SECRET.json";
downloadJSONFile(fileName, obj);
window.alert(`Be sure to keep the downloaded file (${fileName}) in a secure place! You need it at the revealing stage.`);
// process the transaction:
let result = await signableContract.deposit(hash, {value: deposit});
return result;
});
}
function addRevealButton(signableContract) {
addRecommendButton("Reveal Secret", async () => {
window.alert("Please choose your secret file you downloaded MOST RECENTLY, probably with a name similar to 'IMPORTANT-SECRET.json'.")
// fetch the secret file:
let obj = await uploadFileAsJSON();
if (!obj.contract || !obj.bid || !obj.nonce || !obj.hash || !obj.deposit) {
throw Error("Wrong File: Missing JSON fields");
}
if (obj.contract != signableContract.address) {
throw Error("Wrong File: Contract address mismatch");
}
// process the transaction:
let result = await signableContract.reveal(obj.bid, obj.nonce);
return result;
});
}
function addClaimButton(signableContract) {
addRecommendButton("Claim", async () => {
let result = await signableContract.claim();
return result;
});
}
function addWithdrawButton(signableContract) {
addRecommendButton("Withdraw", async () => {
let result = await signableContract.withdraw();
return result;
});
}
function addStartAuctionButton(signableContract) {
addRecommendButton("Start Auction", async () => {
let result = await signableContract.startAuction();
return result;
});
}
function addApproveButton(signableContract, tokenAddress, tokenID) {
addRecommendButton("Approve NFT Transfer", async () => {
let nftContract = await getContractAPI(tokenAddress, "toy-nft.abi.json", false);
let result = await nftContract.approve(signableContract.address, tokenID);
return result;
})
}
function addLogInButton() {
let button = document.createElement("button");
button.innerText = "Log in via Metamask";
button.onclick = async () => {
try {
await ethereum.request({ method: 'eth_requestAccounts' }); // connect to MetaMask
location.reload(); // reload page
} catch (err) {
console.log(err);
document.getElementById("errors").innerText = "Cannot log in. See console logs for more information.";
}
}
document.getElementById("buttons").appendChild(button);
}
function clearAllButtons() {
let buttons = document.getElementById("buttons");
while (buttons.firstChild) {
buttons.removeChild(buttons.firstChild);
}
}
// MAIN:
async function onLoad() {
// Query string checks:
let info = getJsonFromUrl();
if (!info.addr) {
location.href = "navigator.html";
return;
}
if (!isLegalAddress(info.addr)) {
window.alert("Invalid address of auction contract.");
location.href = "navigator.html";
return;
}
// Environment sanity checks:
let web3Provider = await checkWeb3();
if (web3Provider == null) {
return;
}
// Show current time (updated every 500 ms):
showTime();
// Fetch & refresh the constract data every 10 seconds:
let abi = await (await fetch("nft-vickrey.abi.json")).json();
let auctionContract = new ethers.Contract(info.addr, abi, web3Provider);
let web3Signer = web3Provider.getSigner();
let signableContract = new ethers.Contract(info.addr, abi, web3Signer);
fetchAndShowContractData(auctionContract, signableContract);
// Show some static info:
let prefix = "https://ropsten.etherscan.io/address/"
document.getElementById("contract-address").innerHTML =
`Auction contract address: ${info.addr} [${makeHref("View on Etherscan", prefix + info.addr)}]`;
}