-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.html
2416 lines (2168 loc) · 76.3 KB
/
index.html
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
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta
name="description"
content="Generate, sign, and manage Digital Escrow Agreements for Labor (DEAL) on the Base L2 network. Supports ENS addresses and USDC payments."
/>
<link
rel="icon"
href="data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 100 100'><text y='.9em' font-size='90' fill='white'>𝓁𝓍</text></svg>"
/>
<title>Base DEAL</title>
<link rel="icon" href="favicon.ico" type="image/x-icon" />
<script src="https://cdn.ethers.io/lib/ethers-5.7.2.umd.min.js"></script>
<link
rel="stylesheet"
href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.1.1/css/all.min.css"
/>
<script>
const contractAddress = "0xde001DC6a918070f00e5B3676700050000787800";
const contractABI = [
"function draft(tuple(string,string,string,string,string,string,string,uint256,address,address)) view returns (string)",
"function send(string,string,string,string,tuple(uint256,uint256,uint256)) payable returns (uint256)",
"function getHashId(tuple(string,string,string,string,string,string,string,uint256,address,address)) public pure returns (uint256)",
"function checkSignature(address, uint256, bytes) view returns (bool)",
"function getHashIds(address) view returns (uint256[])",
"function deals(uint256) view returns (tuple(string,string,string,string,string,string,uint256,address,address))",
"function uri(uint256) view returns (string)",
"function sign(uint256) public payable returns (bytes32)",
"function escrowHashes(uint256) view returns (bytes32)",
];
const erc1155Address = "0x9d0cD028c081E461a52cD88fF056c4eaEFe204Ca";
const erc1155ABI = [
"function balanceOf(address account, uint256 id) view returns (uint256)",
];
const ieAddress = "0x1eB800E42c879193A1D3d940000000c300e80041";
const ieABI = [
"function whatIsTheNameOf(address) view returns (string)",
"function whatIsTheAddressOf(string) view returns (address, address, bytes32)",
];
const escrowsAddress = "0x00000000000044992CB97CB1A57A32e271C04c11";
const escrowsABI = [
"function lock(bytes32) public",
"function unlock(bytes32) public",
];
const BASE_CHAIN_ID = "0x2105"; // Hexadecimal representation of 8453.
const BASE_CHAIN_DETAILS = {
chainId: BASE_CHAIN_ID,
chainName: "Base",
nativeCurrency: {
name: "Ether",
symbol: "ETH",
decimals: 18,
},
rpcUrls: ["https://mainnet.base.org"],
blockExplorerUrls: ["https://basescan.org"],
};
let provider, signer, contract, ie, userAddress;
const dealInputs = {
clientName: "",
providerName: "",
resolverName: "corrective.base.eth",
dealAmount: "100",
dealNotes: "",
dealDate: "",
expiryDate: "",
expiryTimestamp: 0,
providerSignature: ethers.constants.AddressZero,
clientSignature: ethers.constants.AddressZero,
};
function initializeAndValidateForm() {
// Set default value for dealAmount.
const dealAmountInput = document.getElementById("dealAmount");
dealAmountInput.value = dealInputs.dealAmount;
// Set default value for resolverName.
const resolverNameInput = document.getElementById("resolverName");
resolverNameInput.value = dealInputs.resolverName;
// Validate the dealAmount
validateAmount(dealInputs.dealAmount, "dealAmount");
// Validate the resolverName (without ERC1155 check).
const isValid =
isValidEthAddress(dealInputs.resolverName) ||
dealInputs.resolverName.endsWith(".base.eth");
resolverNameInput.classList.toggle("valid", isValid);
resolverNameInput.classList.toggle("invalid", !isValid);
// Update the preview if the contract is available.
if (contract) {
updatePreview();
}
}
async function fetchEthPrice() {
const pricecheckerAddress =
"0xE22a73a39dE728Dc482D620021382db40BC42bEa";
const pricecheckerABI = [
"function ethPrice() public view returns (string memory)",
];
const pricechecker = new ethers.Contract(
pricecheckerAddress,
pricecheckerABI,
provider
);
try {
const price = await pricechecker.ethPrice();
document.getElementById("ethPrice").innerHTML = `ETH/USDC $${price}`;
return price;
} catch (error) {
console.error("Error fetching ETH price:", error);
document.getElementById("ethPrice").innerHTML = "$ Error";
throw error;
}
}
const estimateEthAmount = async (usdcAmountString) => {
try {
const ethPriceString = await fetchEthPrice();
console.log("ETH price (USDC):", ethPriceString);
// Convert price to a BigNumber (e.g., "2583.721611" -> 2583721611).
const ethPriceUSDC = ethers.utils.parseUnits(ethPriceString, 6);
// Convert USDC amount string to a BigNumber.
const usdcAmount = ethers.utils.parseUnits(usdcAmountString, 6);
// Calculate ETH amount: (usdcAmount * 1e18) / ethPriceUSDC.
const ethAmount = usdcAmount
.mul(ethers.constants.WeiPerEther)
.div(ethPriceUSDC);
console.log("Calculated ETH amount (Wei):", ethAmount.toString());
// Add 1% buffer.
const bufferedAmount = ethAmount.mul(101).div(100);
console.log("Buffered ETH amount (Wei):", bufferedAmount.toString());
return bufferedAmount;
} catch (error) {
console.error("Error in estimateEthAmount:", error);
throw error;
}
};
// Convert date to epoch days (matching the Solidity logic).
const dateToEpochDay = (year, month, day) => {
if (month < 3) {
year -= 1;
month += 12;
}
const era = Math.floor(year / 400);
const yoe = year % 400;
const doy = Math.floor((153 * (month + 1)) / 5) + day - 123;
const doe =
yoe * 365 + Math.floor(yoe / 4) - Math.floor(yoe / 100) + doy;
const epochDay = era * 146097 + doe - 719468;
return epochDay;
};
// Convert date to Unix timestamp (matching the Solidity logic).
const dateToTimestamp = (year, month, day) => {
const epochDay = dateToEpochDay(year, month, day);
return epochDay * 86400;
};
// Utility function to format date to "M/D/YYYY".
const formatDateMMDDYYYY = (dateString) => {
const date = new Date(dateString);
if (isNaN(date)) {
return "";
}
const month = `${date.getMonth() + 1}`;
const day = `${date.getDate()}`;
const year = date.getFullYear();
return `${month}/${day}/${year}`;
};
// Function to generate Unix timestamp for a given date in M/D/YYYY format.
const convertToTimestamp = (formattedDate) => {
const dateParts = formattedDate.split("/");
const month = parseInt(dateParts[0], 10);
const day = parseInt(dateParts[1], 10);
const year = parseInt(dateParts[2], 10);
return dateToTimestamp(year, month, day);
};
// Validate and format the expiry date.
const validateExpiryDate = (dateString) => {
const input = document.getElementById("expiryDate");
if (!dateString) {
input.classList.remove("valid", "invalid", "immediate", "escrow");
return false;
}
const formattedDate = formatDateMMDDYYYY(dateString);
if (!formattedDate) {
input.classList.add("invalid");
input.classList.remove("valid", "immediate", "escrow");
return false;
}
const selectedDate = new Date(formattedDate);
const today = new Date();
today.setHours(0, 0, 0, 0); // Reset time to start of day for accurate comparison.
input.classList.remove("invalid");
input.classList.add("valid");
if (selectedDate < today) {
input.classList.add("immediate");
input.classList.remove("escrow");
showNotification("Date set for immediate invoicing", "info");
} else {
input.classList.add("escrow");
input.classList.remove("immediate");
showNotification("Date set for future escrow", "info");
}
return formattedDate;
};
// Update form inputs.
const updateInputs = async () => {
for (const key of Object.keys(dealInputs)) {
if (
![
"providerSignature",
"clientSignature",
"dealDate",
"expiryTimestamp",
].includes(key)
) {
const inputValue = document.getElementById(key).value.trim();
dealInputs[key] = inputValue !== "" ? inputValue : dealInputs[key];
// Add specific validation for resolverName
if (key === "resolverName") {
await validateResolverName(dealInputs[key]);
}
}
}
dealInputs.dealDate = formatDateMMDDYYYY(
new Date().toISOString().split("T")[0]
);
const expiryDateInput = document.getElementById("expiryDate").value;
const formattedExpiryDate = validateExpiryDate(expiryDateInput);
if (formattedExpiryDate) {
dealInputs.expiryTimestamp = convertToTimestamp(formattedExpiryDate);
dealInputs.expiryDate = formattedExpiryDate;
} else {
dealInputs.expiryDate = "";
dealInputs.expiryTimestamp = 0;
}
console.log("Updated Inputs:", dealInputs);
await checkAllInputsFilled();
};
const validateProviderName = async (name) => {
const input = document.getElementById("providerName");
let isValid = false;
if (name === dealInputs.providerName) {
isValid = true; // Always valid for the connected provider.
} else if (name.endsWith(".base.eth")) {
try {
const queryString = name.slice(0, -9); // Remove '.base.eth'.
const [, address] = await ie.whatIsTheAddressOf(queryString);
isValid = address && address !== ethers.constants.AddressZero;
} catch (error) {
console.error("Provider name validation failed:", error);
}
} else {
isValid = ethers.utils.isAddress(name);
}
input.classList.toggle("valid", isValid);
input.classList.toggle("invalid", !isValid);
return isValid;
};
const isValidEthAddress = (address) => {
try {
return ethers.utils.isAddress(address);
} catch (error) {
return false;
}
};
const validateClientName = (name) => {
const inputElement = document.getElementById("clientName");
const isValid = isValidEthAddress(name) || name.endsWith(".base.eth");
inputElement.classList.toggle("valid", isValid);
inputElement.classList.toggle("invalid", !isValid);
return isValid;
};
const validateResolverName = async (name) => {
const inputElement = document.getElementById("resolverName");
let isValid = isValidEthAddress(name) || name.endsWith(".base.eth");
let hasERC1155Balance = false;
inputElement.classList.toggle("valid", isValid);
inputElement.classList.remove("invalid", "gold");
if (isValid && provider && signer) {
try {
const resolverAddress = await getAddressFromNameOrAddress(name);
const erc1155Contract = new ethers.Contract(
erc1155Address,
erc1155ABI,
provider
);
const balance = await erc1155Contract.balanceOf(resolverAddress, 0);
hasERC1155Balance = balance.gte(1);
if (hasERC1155Balance) {
inputElement.classList.add("gold");
}
} catch (error) {
console.error("Error checking ERC1155 balance:", error);
}
}
return isValid;
};
const validateDealNotes = (notes) => {
const input = document.getElementById("dealNotes");
const isValid = notes.trim().length > 0 && notes.length <= 200;
input.classList.toggle("valid", isValid);
input.classList.toggle("invalid", !isValid);
return isValid;
};
const getAddressFromNameOrAddress = async (nameOrAddress) => {
if (ethers.utils.isAddress(nameOrAddress)) {
return nameOrAddress;
} else if (ie) {
const queryString = nameOrAddress.replace(/\.base\.eth$/, "");
const [, address] = await ie.whatIsTheAddressOf(queryString);
return address;
} else {
throw new Error(
"ENS contract not initialized. Please connect your wallet."
);
}
};
const validateAmount = (amount, elementId) => {
const input = document.getElementById(elementId);
const value = parseFloat(amount);
const isValid =
!isNaN(value) && value > 0 && Number.isInteger(value * 1e6);
input.classList.toggle("valid", isValid);
input.classList.toggle("invalid", !isValid);
return isValid;
};
const toggleNotificationArea = () => {
console.log("Toggle notification area called");
const content = document.getElementById("notificationContent");
content.style.display =
content.style.display === "none" ? "block" : "none";
console.log("Notification content display:", content.style.display);
};
const updateNotificationCounter = (count) => {
console.log("Updating notification counter with count:", count);
const counterElement = document.getElementById("notificationCounter");
const toggleButton = document.getElementById("toggleNotification");
if (count > 0) {
console.log("Setting counter and displaying toggle button");
counterElement.textContent = count;
toggleVisibility("toggleNotification", true);
toggleVisibility("notificationArea", true);
} else {
console.log("Hiding toggle button");
toggleVisibility("toggleNotification", false);
toggleVisibility("notificationArea", false);
}
};
const populateHashIdDropdown = (ids) => {
console.log("Populating hash ID dropdown with ids:", ids);
const dropdown = document.getElementById("hashIdDropdown");
dropdown.innerHTML = '<option value="">Select a DEAL</option>';
ids.forEach((id, index) => {
const option = document.createElement("option");
option.value = id.toString(); // Ensure it's stored as a string.
option.textContent = `DEAL ${index + 1}`;
dropdown.appendChild(option);
});
console.log("Dropdown populated");
};
const switchToBaseNetwork = async () => {
try {
await window.ethereum.request({
method: "wallet_switchEthereumChain",
params: [{ chainId: BASE_CHAIN_ID }],
});
} catch (switchError) {
if (switchError.code === 4902) {
try {
await window.ethereum.request({
method: "wallet_addEthereumChain",
params: [BASE_CHAIN_DETAILS],
});
} catch (addError) {
throw new Error("Failed to add Base network to MetaMask");
}
} else {
throw new Error("Failed to switch to Base network");
}
}
};
const connectWallet = async () => {
console.log("Connecting wallet...");
if (typeof window.ethereum === "undefined") {
showNotification("Please install MetaMask!", "error");
return;
}
if (userAddress) {
window.open(`https://basescan.org/address/${userAddress}`, "_blank");
return;
}
showLoading(true);
try {
await window.ethereum.request({ method: "eth_requestAccounts" });
const chainId = await window.ethereum.request({
method: "eth_chainId",
});
if (chainId !== BASE_CHAIN_ID) {
await switchToBaseNetwork();
}
provider = new ethers.providers.Web3Provider(window.ethereum);
signer = provider.getSigner();
contract = new ethers.Contract(contractAddress, contractABI, signer);
ie = new ethers.Contract(ieAddress, ieABI, signer);
userAddress = await signer.getAddress();
console.log("Connected wallet address:", userAddress);
const hashIds = await fetchHashIds(userAddress);
console.log("Fetched hash IDs:", hashIds);
updateNotificationCounter(hashIds.length);
populateHashIdDropdown(hashIds);
setupEventListeners();
toggleVisibility("notificationArea", true);
dealInputs.providerSignature = userAddress;
try {
const ensName = await ie.whatIsTheNameOf(userAddress);
dealInputs.providerName =
ensName || ethers.utils.getAddress(userAddress);
} catch (error) {
console.error("ENS lookup failed:", error);
dealInputs.providerName = ethers.utils.getAddress(userAddress);
}
const providerNameInput = document.getElementById("providerName");
providerNameInput.value = dealInputs.providerName;
providerNameInput.readOnly = true;
await validateProviderName(dealInputs.providerName);
document.getElementById("dealAmount").value = dealInputs.dealAmount;
document
.getElementById("hashIdDropdown")
.addEventListener("change", (event) => {
if (event.target.value) {
displayDEALDetails(event.target.value);
} else {
toggleVisibility("dealDetailsWindow", false);
}
});
const debouncedUpdatePreview = debounce(updatePreview, 300);
const connectWalletBtn = document.getElementById("connectWallet");
const displayName = dealInputs.providerName.endsWith(".base")
? dealInputs.providerName
: shortenAddress(userAddress);
connectWalletBtn.innerHTML = `<span id="walletText"><a href="https://basescan.org/address/${userAddress}" target="_blank">${displayName}</a></span>`;
connectWalletBtn.classList.add("connected");
connectWalletBtn.classList.remove("flashing");
showNotification(
"Wallet connected successfully to Base network",
"success"
);
updatePreview();
fetchEthPrice();
setInterval(fetchEthPrice, 60000); // Update every 60 seconds.
} catch (error) {
console.error("Failed to connect wallet:", error);
showNotification(getWalletErrorMessage(error), "error");
} finally {
showLoading(false);
}
};
const getWalletErrorMessage = (error) => {
if (error.code === 4001) {
return "You rejected the connection request. Please try again.";
} else if (error.code === -32002) {
return "The connection request is already pending. Please check your MetaMask extension.";
} else if (
error.message.includes("Already processing eth_requestAccounts")
) {
return "A connection request is already in progress. Please check your MetaMask extension.";
}
return `Failed to connect wallet: ${error.message}`;
};
const fetchHashIds = async (address) => {
try {
console.log("Fetching hash IDs for address:", address);
const ids = await contract.getHashIds(address);
console.log("Fetched hash IDs:", ids);
return ids.map((id) => id.toString());
} catch (error) {
console.error("Error fetching hash IDs:", error);
showNotification(
"Failed to fetch DEAL IDs. Please try again.",
"error"
);
return [];
}
};
let signModal;
const displayDEALDetails = async (hashId) => {
try {
console.log("Fetching DEAL details for hashId:", hashId);
const hashIdBN = ethers.BigNumber.from(hashId);
console.log("HashId as BigNumber:", hashIdBN.toString());
// Fetch DEAL details.
const data = contract.interface.encodeFunctionData("deals", [
hashIdBN,
]);
const rawResult = await provider.call({
to: contract.address,
data: data,
});
console.log("Raw result:", rawResult);
const decodedResult = ethers.utils.defaultAbiCoder.decode(
[
"string",
"string",
"string",
"string",
"string",
"string",
"string",
"uint256",
"address",
"address",
],
rawResult
);
console.log("Decoded Result:", decodedResult);
const [
clientName,
providerName,
resolverName,
dealAmount,
dealNotes,
dealDate,
expiryDate,
expiryTimestamp,
providerSignature,
clientSignature,
] = decodedResult;
// Fetch escrow hash.
const escrowHash = await contract.escrowHashes(hashIdBN);
console.log("Escrow Hash:", escrowHash);
// Check if the DEAL is signed.
const isSigned = clientSignature !== ethers.constants.AddressZero;
// Check if the current user is the client.
const isClient =
userAddress === (await getAddressFromNameOrAddress(clientName));
// Update the UI details window.
const detailsWindow = document.getElementById("dealDetailsWindow");
detailsWindow.innerHTML = `
<button id="closeDetailsWindow">×</button>
<h3>DEAL Details</h3>
<p><strong>ID:</strong> <a href="https://opensea.io/assets/base/0xde001DC6a918070f00e5B3676700050000787800/${hashId}"
target="_blank">${hashId}</a></p>
<p><strong>Client Name:</strong> ${clientName}</p>
<p><strong>Provider Name:</strong> ${providerName}</p>
<p><strong>Resolver Name:</strong> ${resolverName}</p>
<p><strong>Deal Amount:</strong> ${dealAmount} USDC</p>
<p><strong>Deal Notes:</strong> ${dealNotes}</p>
<p><strong>Deal Date:</strong> ${dealDate}</p>
<p><strong>Expiry Date:</strong> ${expiryDate}</p>
<p><strong>Provider Signature:</strong> <a href="https://basescan.org/address/${providerSignature}"
target="_blank">${shortenAddress(providerSignature)}</a></p>
<p><strong>Client Signature:</strong> <a href="https://basescan.org/address/${clientSignature}" target="_blank">
${shortenAddress(clientSignature)}</a></p>
${
escrowHash !== ethers.constants.HashZero
? `<p><strong>Escrow Hash:</strong> ${escrowHash}</p>
<button id="lockEscrow" title="Lock Escrow"><i class="fas fa-lock"></i> Lock Escrow</button>
${
isClient
? `<button id="unlockEscrow" title="Unlock Escrow"><i class="fas fa-unlock"></i> Unlock Escrow</button>`
: ""
}`
: ""
}
${
isSigned
? "<p>DEAL already signed ✔️</p>"
: userAddress === (await getAddressFromNameOrAddress(clientName))
? `<button id="signDEAL" title="Sign DEAL"><i class="fas fa-file-signature"></i> Sign DEAL</button>`
: ""
}`;
// Add event listener for the close button.
document
.getElementById("closeDetailsWindow")
.addEventListener("click", () => {
detailsWindow.style.opacity = 0;
setTimeout(() => {
detailsWindow.style.display = "none";
detailsWindow.style.transition = "";
}, 300);
});
// Add event listener for the Sign DEAL button.
if (
!isSigned &&
userAddress === (await getAddressFromNameOrAddress(clientName))
) {
const signDEALButton = document.getElementById("signDEAL");
signDEALButton.addEventListener(
"click",
createSigningModal.bind(null, hashId, hashIdBN)
);
}
// Add event listener for the Lock Escrow button.
if (escrowHash !== ethers.constants.HashZero) {
const lockEscrowButton = document.getElementById("lockEscrow");
lockEscrowButton.addEventListener("click", () =>
lockEscrow(escrowHash)
);
// Add event listener for the Unlock Escrow button if the user is the client.
if (isClient) {
const unlockEscrowButton =
document.getElementById("unlockEscrow");
unlockEscrowButton.addEventListener("click", () =>
unlockEscrow(escrowHash)
);
}
}
// Show the details window with a fade-in effect.
detailsWindow.style.display = "block";
detailsWindow.style.opacity = 0;
setTimeout(() => {
detailsWindow.style.transition = "opacity 0.3s";
detailsWindow.style.opacity = 1;
}, 10);
} catch (error) {
console.error("Error fetching DEAL details:", error);
showNotification("Failed to fetch DEAL details", "error");
}
};
const createSigningModal = async (hashId, hashIdBN) => {
try {
const uriData = await contract.uri(hashId);
console.log("Fetched SVG data for preview:", uriData);
const jsonResponse = atob(uriData.split(",")[1]);
const svgData = JSON.parse(jsonResponse).image;
if (!signModal) {
signModal = document.createElement("div");
signModal.classList.add("modal");
document.body.appendChild(signModal);
}
signModal.innerHTML = `
<div class="modal-content">
<span class="close">×</span>
<h2>Sign DEAL</h2>
<div class="svg-container" style="text-align: center;">
<img src="${svgData}" alt="DEAL Document Preview" style="max-width: 100%; height: auto;" />
</div>
<div style="margin-top: 20px;">
<label style="margin-right: 15px;">
<input type="radio" name="paymentMethod" value="USDC" checked> Pay with USDC 🪙
</label>
<label>
<input type="radio" name="paymentMethod" value="ETH"> Pay with ETH ⟡
</label>
</div>
<p id="estimatedCost" style="display: none; margin-top: 10px;"></p>
<button id="confirmSign" title="Confirm Signature" style="margin-top: 20px;">
<i class="fas fa-check"></i> Confirm Signature
</button>
</div>`;
signModal.style.display = "block";
signModal.querySelector(".close").onclick = () => {
signModal.style.display = "none";
};
window.onclick = (event) => {
if (event.target == signModal) {
signModal.style.display = "none";
}
};
const updateEstimatedCost = async () => {
const paymentMethod = document.querySelector(
'input[name="paymentMethod"]:checked'
).value;
const estimatedCostElement =
document.getElementById("estimatedCost");
if (paymentMethod === "ETH") {
try {
// Get the raw data from the contract.
const rawData = await provider.call({
to: contract.address,
data: contract.interface.encodeFunctionData("deals", [
hashIdBN,
]),
});
console.log("Raw contract response:", rawData);
// Manually decode the dealAmount.
const decodedData = ethers.utils.defaultAbiCoder.decode(
[
"string",
"string",
"string",
"string",
"string",
"string",
"string",
"uint256",
"address",
"address",
],
rawData
);
const dealAmount = decodedData[3];
console.log("Deal amount (USDC):", dealAmount);
const ethAmount = await estimateEthAmount(dealAmount);
console.log(
"Estimated ETH amount (Wei):",
ethAmount.toString()
);
estimatedCostElement.textContent = `Estimated ETH cost: ${ethers.utils.formatEther(
ethAmount
)} ETH (includes 1% buffer)`;
estimatedCostElement.style.display = "block";
} catch (error) {
console.error("Error estimating ETH cost:", error);
estimatedCostElement.textContent =
"Error estimating ETH cost. Please check the console for details.";
estimatedCostElement.style.display = "block";
}
} else {
estimatedCostElement.style.display = "none";
}
};
document
.querySelectorAll('input[name="paymentMethod"]')
.forEach((radio) => {
radio.addEventListener("change", updateEstimatedCost);
});
await updateEstimatedCost();
const confirmSignButton = document.getElementById("confirmSign");
confirmSignButton.addEventListener("click", async function () {
try {
const paymentMethod = document.querySelector(
'input[name="paymentMethod"]:checked'
).value;
showLoading(true);
if (paymentMethod === "USDC") {
await handleUSDCPayment(dealHashId, hashIdBN);
} else {
await handleETHPayment(dealHashId, hashIdBN);
}
showNotification("DEAL signed successfully!", "success");
signModal.style.display = "none";
await displayDEALDetails(hashId);
} catch (error) {
console.error("Error during signing flow:", error);
showNotification(
"Failed during signing flow. Please check the console for details.",
"error"
);
} finally {
showLoading(false);
}
});
} catch (uriError) {
console.error("Error in createSigningModal:", uriError);
showNotification(
"Failed to create signing modal. Please check the console for details.",
"error"
);
}
};
const handleUSDCPayment = async (dealAmount, hashIdBN) => {
const usdcAddress = "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913";
const usdcABI = [
"function approve(address spender, uint256 amount) public returns (bool)",
"function allowance(address owner, address spender) public view returns (uint256)",
];
const usdcContract = new ethers.Contract(usdcAddress, usdcABI, signer);
const allowance = await usdcContract.allowance(
userAddress,
contractAddress
);
console.log("Current USDC allowance:", allowance.toString());
const requiredAmount = ethers.utils.parseUnits("10000", 6);
if (allowance.lt(requiredAmount)) {
const approvalTx = await usdcContract.approve(
contractAddress,
requiredAmount
);
console.log("Approval transaction sent:", approvalTx);
await approvalTx.wait();
console.log("Approval transaction confirmed");
showNotification(
"USDC approval succeeded. Proceeding with signing...",
"info"
);
}
const tx = await contract.sign(hashIdBN);
console.log("Sign transaction sent:", tx);
await tx.wait();
console.log("Sign transaction confirmed");
};
const handleETHPayment = async (dealHashId, hashIdBN) => {
try {
// Get the raw data from the contract.
const rawData = await provider.call({
to: contract.address,
data: contract.interface.encodeFunctionData("deals", [hashIdBN]),
});
console.log("Raw contract response:", rawData);
// Manually decode the dealAmount.
const decodedData = ethers.utils.defaultAbiCoder.decode(
[
"string",
"string",
"string",
"string",
"string",
"string",
"string",
"uint256",
"address",
"address",
],
rawData
);
const dealAmount = decodedData[3];
console.log("Deal amount (USDC):", dealAmount);
const ethAmount = await estimateEthAmount(dealAmount);
console.log("Estimated ETH amount (Wei):", ethAmount.toString());
// Estimate gas.
const gasLimit = await contract.estimateGas.sign(hashIdBN, {
value: ethAmount,
});
console.log("Estimated gas limit:", gasLimit.toString());
// Get current gas price.
const gasPrice = await provider.getGasPrice();
console.log("Current gas price:", gasPrice.toString());
// Calculate total cost (ETH amount + gas cost).
const totalCost = ethAmount.add(gasPrice.mul(gasLimit));
console.log("Total estimated cost (Wei):", totalCost.toString());
// Check if user has enough balance.
const balance = await provider.getBalance(userAddress);
if (balance.lt(totalCost)) {
throw new Error(
"Insufficient ETH balance to cover the payment and gas costs."
);
}
// Send the transaction.
const tx = await contract.sign(hashIdBN, {
value: ethAmount,
gasLimit,
});
console.log("Transaction sent:", tx.hash);
// Wait for the transaction to be mined.
await tx.wait();
console.log("Transaction confirmed");
return tx.hash;
} catch (error) {
console.error("Error in handleETHPayment:", error);
throw error;
}
};
function setupEventListeners() {
const hashIdDropdown = document.getElementById("hashIdDropdown");
if (hashIdDropdown) {
hashIdDropdown.addEventListener("change", (event) => {
if (event.target.value) {
displayDEALDetails(event.target.value);
}
});
} else {
console.warn("hashIdDropdown element not found");
}
}
const lockEscrow = async (escrowHash) => {
try {
const escrowsContract = new ethers.Contract(
escrowsAddress,
escrowsABI,
signer
);
const tx = await escrowsContract.lock(escrowHash);
console.log("Lock transaction sent:", tx.hash);
showNotification(
"Locking escrow. Please wait for confirmation.",