-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathadmin.html
More file actions
677 lines (613 loc) · 31.6 KB
/
Copy pathadmin.html
File metadata and controls
677 lines (613 loc) · 31.6 KB
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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Admin Panel - TimeLockedBond</title>
<link rel="stylesheet" href="styles/fonts.css" />
<link rel="stylesheet" href="styles/index.css" />
<link rel="stylesheet" href="styles/admin.css" />
<link rel="icon" type="image/png" href="styles/logo.png" />
</head>
<body>
<!-- Logo and navigation buttons on same line -->
<div class="top-nav">
<button id="connectWallet" class="connect-wallet">Connect</button>
<img src="styles/logo.png" alt="Logo" class="logo-img" />
<button class="admin-btn page-direct" onclick="navigateToDeposit()">Deposit Page</button>
</div>
<div class="container">
<h2>Admin Panel</h2>
<div id="walletDisplay" class="wallet-display wallet-display-hidden">
<span id="walletAddress"></span>
</div>
<div id="contractBalance"></div>
<div id="ownerStatus"></div>
<form id="deductForm">
<label for="userAddressSelect">Select User:</label>
<select id="userAddressSelect" required>
<option value="">Loading addresses...</option>
</select>
<div id="selectedUserInfo">
<h4>Selected User Bond Info:</h4>
<div id="bondInfo"></div>
</div>
<div class="deduction-section">
<h4>Make Deduction</h4>
<div class="deduction-field">
<label for="deductAmount" class="deduction-label">Deduction Amount (ETH):</label>
<input type="number" id="deductAmount" step="0.001" min="0" placeholder="0.000" required>
</div>
<div class="deduction-field">
<label for="deductionReason" class="deduction-label">Reason for Deduction:</label>
<select id="deductionReason" required onchange="toggleNotesField()">
<option value="">Select a reason...</option>
<option value="Late Rent Payment">Late Rent Payment</option>
<option value="Property Damages">Property Damages</option>
<option value="Cleaning Fee">Cleaning Fee</option>
<option value="Unpaid Utilities">Unpaid Utilities</option>
<option value="Early Lease Termination">Early Lease Termination</option>
<option value="Pet Policy Violation">Pet Policy Violation</option>
<option value="Noise Complaints">Noise Complaints</option>
<option value="Unauthorized Modifications">Unauthorized Modifications</option>
<option value="Missing/Damaged Items">Missing/Damaged Items</option>
<option value="Administrative Fee">Administrative Fee</option>
<option value="Maintenance Costs">Maintenance Costs</option>
<option value="Other">Other (specify below)</option>
</select>
</div>
</div>
<button type="submit" class="deduct-submit-btn">
Make Deduction
</button>
</form>
<div id="status"></div>
</div>
<script src="https://cdn.jsdelivr.net/npm/ethers@5.7.2/dist/ethers.umd.min.js"></script>
<script>
let account;
// Helper function to show/hide status div based on content
function setStatus(content, isHTML = false) {
const statusDiv = document.getElementById('status');
if (content && content.trim() !== '') {
if (isHTML) {
statusDiv.innerHTML = content;
} else {
statusDiv.innerText = content;
}
statusDiv.style.display = 'block';
} else {
statusDiv.innerHTML = '';
statusDiv.style.display = 'none';
}
}
window.addEventListener('DOMContentLoaded', async () => {
account = undefined;
// Check for stored wallet connection
const storedWallet = localStorage.getItem('connectedWallet');
if (storedWallet && window.ethereum) {
try {
const accounts = await window.ethereum.request({ method: 'eth_accounts' });
if (accounts.includes(storedWallet)) {
account = storedWallet;
await initializeConnectedState();
return;
} else {
// Stored wallet is no longer connected, clear it
localStorage.removeItem('connectedWallet');
}
} catch (err) {
console.log('Error checking stored wallet:', err);
localStorage.removeItem('connectedWallet');
}
}
setStatus('Wallet disconnected.');
updateWalletButton();
});
// Function to initialize the connected state
async function initializeConnectedState() {
document.getElementById('walletAddress').innerText = `Connected: ${account}`;
document.getElementById('walletDisplay').classList.remove('wallet-display-hidden');
setStatus(''); // Clear status when connected
// Show contract balance
try {
const provider = new ethers.providers.Web3Provider(window.ethereum, 'any');
const balance = await provider.getBalance(contractAddress);
const ethBalance = ethers.utils.formatEther(balance);
document.getElementById('contractBalance').innerText = `Contract Balance: ${ethBalance} ETH`;
} catch (err) {
document.getElementById('contractBalance').innerText = 'Error fetching contract balance.';
}
// Check if owner
try {
const provider = new ethers.providers.Web3Provider(window.ethereum, 'any');
const contract = new ethers.Contract(contractAddress, contractABI, provider);
const ownerAddress = await contract.owner();
if (account.toLowerCase() === ownerAddress.toLowerCase()) {
document.getElementById('ownerStatus').innerText = 'You are the contract owner.';
document.getElementById('deductForm').style.display = 'block';
await loadDepositorAddresses(); // Load depositor addresses
} else {
document.getElementById('ownerStatus').innerText = 'You are NOT the contract owner. Admin features are disabled.';
document.getElementById('deductForm').style.display = 'none';
}
} catch (err) {
document.getElementById('ownerStatus').innerText = 'Error checking owner: ' + err.message;
}
updateWalletButton();
}
// Contract address and ABI
const contractAddress = '0x1693E3550A169234CfA7190ACB5E0ffE27697917'; // Set your deployed address
const contractABI = [
{
"inputs": [
{ "internalType": "address", "name": "_initialOwner", "type": "address" }
],
"stateMutability": "nonpayable",
"type": "constructor"
},
{
"inputs": [
{ "internalType": "address", "name": "owner", "type": "address" }
],
"name": "OwnableInvalidOwner",
"type": "error"
},
{
"inputs": [
{ "internalType": "address", "name": "account", "type": "address" }
],
"name": "OwnableUnauthorizedAccount",
"type": "error"
},
{
"anonymous": false,
"inputs": [
{ "indexed": true, "internalType": "address", "name": "depositor", "type": "address" },
{ "indexed": false, "internalType": "uint256", "name": "amount", "type": "uint256" },
{ "indexed": false, "internalType": "uint256", "name": "remaining", "type": "uint256" }
],
"name": "Deducted",
"type": "event"
},
{
"anonymous": false,
"inputs": [
{ "indexed": true, "internalType": "address", "name": "depositor", "type": "address" },
{ "indexed": false, "internalType": "uint256", "name": "amount", "type": "uint256" },
{ "indexed": false, "internalType": "uint256", "name": "releaseTime", "type": "uint256" }
],
"name": "Deposited",
"type": "event"
},
{
"anonymous": false,
"inputs": [
{ "indexed": true, "internalType": "address", "name": "previousOwner", "type": "address" },
{ "indexed": true, "internalType": "address", "name": "newOwner", "type": "address" }
],
"name": "OwnershipTransferred",
"type": "event"
},
{
"anonymous": false,
"inputs": [
{ "indexed": true, "internalType": "address", "name": "depositor", "type": "address" },
{ "indexed": false, "internalType": "uint256", "name": "amount", "type": "uint256" }
],
"name": "Withdrawn",
"type": "event"
},
{
"inputs": [],
"name": "DURATION",
"outputs": [
{ "internalType": "uint256", "name": "", "type": "uint256" }
],
"stateMutability": "view",
"type": "function"
},
{
"inputs": [
{ "internalType": "address", "name": "_depositor", "type": "address" },
{ "internalType": "uint256", "name": "_amount", "type": "uint256" }
],
"name": "deductETH",
"outputs": [],
"stateMutability": "nonpayable",
"type": "function"
},
{
"inputs": [],
"name": "depositETH",
"outputs": [],
"stateMutability": "payable",
"type": "function"
},
{
"inputs": [
{ "internalType": "address", "name": "_depositor", "type": "address" }
],
"name": "getDepositInfo",
"outputs": [
{ "internalType": "uint256", "name": "amount", "type": "uint256" },
{ "internalType": "uint256", "name": "releaseTime", "type": "uint256" },
{ "internalType": "uint256", "name": "deductedAmount", "type": "uint256" },
{ "internalType": "uint256", "name": "availableAmount", "type": "uint256" },
{ "internalType": "bool", "name": "isWithdrawable", "type": "bool" }
],
"stateMutability": "view",
"type": "function"
},
{
"inputs": [
{ "internalType": "address", "name": "_depositor", "type": "address" }
],
"name": "hasDeposit",
"outputs": [
{ "internalType": "bool", "name": "", "type": "bool" }
],
"stateMutability": "view",
"type": "function"
},
{
"inputs": [],
"name": "owner",
"outputs": [
{ "internalType": "address", "name": "", "type": "address" }
],
"stateMutability": "view",
"type": "function"
},
{
"inputs": [],
"name": "renounceOwnership",
"outputs": [],
"stateMutability": "nonpayable",
"type": "function"
},
{
"inputs": [
{ "internalType": "address", "name": "newOwner", "type": "address" }
],
"name": "transferOwnership",
"outputs": [],
"stateMutability": "nonpayable",
"type": "function"
},
{
"inputs": [],
"name": "withdrawETH",
"outputs": [],
"stateMutability": "nonpayable",
"type": "function"
}
];
function updateWalletButton() {
const btn = document.getElementById('connectWallet');
if (account) {
btn.textContent = 'Disconnect';
btn.style.background = '#dc3545';
btn.onclick = () => {
account = undefined;
localStorage.removeItem('connectedWallet'); // Clear stored connection
document.getElementById('walletDisplay').classList.add('wallet-display-hidden');
setStatus('Wallet disconnected.');
document.getElementById('ownerStatus').innerText = '';
document.getElementById('deductForm').style.display = 'none';
document.getElementById('contractBalance').innerText = '';
updateWalletButton();
};
} else {
btn.textContent = 'Connect';
btn.style.background = '';
btn.onclick = async () => {
if (window.ethereum) {
try {
const accounts = await window.ethereum.request({ method: 'eth_requestAccounts' });
account = accounts[0];
localStorage.setItem('connectedWallet', account); // Store connection
await initializeConnectedState();
} catch (err) {
if (err.code === 4001) {
setStatus('Connection request rejected by user.');
} else {
setStatus(err.message);
}
}
} else {
alert('MetaMask not detected!');
}
};
}
}
// Function to navigate back to deposit page while preserving connection
function navigateToDeposit() {
if (account) {
localStorage.setItem('connectedWallet', account);
}
window.location.href = 'index.html';
}
// Function to load all depositor addresses
async function loadDepositorAddresses() {
try {
const provider = new ethers.providers.Web3Provider(window.ethereum, 'any');
const contract = new ethers.Contract(contractAddress, contractABI, provider);
console.log('Loading depositor addresses...');
console.log('Contract address:', contractAddress);
console.log('Connected network:', await provider.getNetwork());
// Get all Deposited events from the contract
const filter = contract.filters.Deposited();
console.log('Event filter created:', filter);
let events;
try {
// For local networks, try querying from a recent block instead of all history
const latestBlock = await provider.getBlockNumber();
console.log('Latest block:', latestBlock);
// Query from block 0 to latest (for local network this should be manageable)
events = await contract.queryFilter(filter, 0, latestBlock);
console.log('Events found:', events.length);
console.log('Raw events:', events);
} catch (filterError) {
console.log('Error with queryFilter, trying alternative approach:', filterError);
// Fallback: try without block range
events = await contract.queryFilter(filter);
}
if (events.length === 0) {
console.log('No Deposited events found');
// Let's also try to directly check if the current connected wallet has a deposit
const accounts = await window.ethereum.request({ method: 'eth_accounts' });
if (accounts.length > 0) {
const currentAccount = accounts[0];
console.log('Checking if current account has deposit:', currentAccount);
try {
const hasDeposit = await contract.hasDeposit(currentAccount);
console.log('Current account hasDeposit result:', hasDeposit);
// Also try getting deposit info directly
try {
const depositInfo = await contract.getDepositInfo(currentAccount);
console.log('Deposit info for current account:', depositInfo);
} catch (depositError) {
console.log('No deposit info for current account:', depositError.message);
}
} catch (err) {
console.log('Error checking current account deposit:', err);
}
}
const select = document.getElementById('userAddressSelect');
select.innerHTML = '<option value="">No deposits found in events</option>';
return;
}
// Extract unique depositor addresses
const depositors = [...new Set(events.map(event => event.args.depositor))];
console.log('Unique depositors found:', depositors);
// Filter to only include addresses that still have deposits AND are not expired
const activeDepositors = [];
for (const depositor of depositors) {
try {
console.log(`Checking deposit for ${depositor}...`);
const hasDeposit = await contract.hasDeposit(depositor);
console.log(`${depositor} has deposit:`, hasDeposit);
if (hasDeposit) {
// Check if the bond has expired
try {
const depositInfo = await contract.getDepositInfo(depositor);
const currentTime = Math.floor(Date.now() / 1000); // Current timestamp in seconds
const releaseTime = depositInfo.releaseTime.toNumber();
const isExpired = currentTime >= releaseTime;
console.log(`${depositor} bond status:`, {
currentTime: new Date(currentTime * 1000),
releaseTime: new Date(releaseTime * 1000),
isExpired: isExpired,
timeLeft: isExpired ? 0 : releaseTime - currentTime
});
// Only include if not expired
if (!isExpired) {
activeDepositors.push(depositor);
console.log(`${depositor} added to active depositors (not expired)`);
} else {
console.log(`${depositor} excluded - bond has expired and can be withdrawn`);
}
// Log deposit info for debugging
console.log(`Deposit info for ${depositor}:`, {
amount: ethers.utils.formatEther(depositInfo.amount),
releaseTime: new Date(depositInfo.releaseTime.toNumber() * 1000),
deductedAmount: ethers.utils.formatEther(depositInfo.deductedAmount),
availableAmount: ethers.utils.formatEther(depositInfo.availableAmount),
isWithdrawable: depositInfo.isWithdrawable,
isExpired: isExpired
});
} catch (infoErr) {
console.log(`Error getting deposit info for ${depositor}:`, infoErr);
// If we can't get deposit info, don't include in active list
}
}
} catch (err) {
console.log(`Error checking deposit for ${depositor}:`, err);
}
}
console.log('Active depositors:', activeDepositors);
// Populate the dropdown
const select = document.getElementById('userAddressSelect');
select.innerHTML = '<option value="">Select a user address</option>';
if (activeDepositors.length === 0) {
if (depositors.length > 0) {
select.innerHTML = '<option value="">No active bonds (all expired/withdrawable)</option>';
} else {
select.innerHTML = '<option value="">No active deposits found</option>';
}
return;
}
activeDepositors.forEach(address => {
const option = document.createElement('option');
option.value = address;
option.textContent = `${address.substring(0, 6)}...${address.substring(38)}`;
select.appendChild(option);
});
// Add change event listener
select.onchange = handleAddressSelection;
} catch (err) {
console.error('Error loading depositor addresses:', err);
const select = document.getElementById('userAddressSelect');
select.innerHTML = '<option value="">Error loading addresses</option>';
}
}
// Function to handle address selection and display bond info
async function handleAddressSelection() {
const select = document.getElementById('userAddressSelect');
const selectedAddress = select.value;
const infoDiv = document.getElementById('selectedUserInfo');
const bondInfoDiv = document.getElementById('bondInfo');
if (!selectedAddress) {
infoDiv.style.display = 'none';
return;
}
try {
const provider = new ethers.providers.Web3Provider(window.ethereum, 'any');
const contract = new ethers.Contract(contractAddress, contractABI, provider);
// Get deposit info
const depositInfo = await contract.getDepositInfo(selectedAddress);
const [amount, releaseTime, deductedAmount, availableAmount, isWithdrawable] = depositInfo;
const ethAmount = ethers.utils.formatEther(amount);
const ethDeducted = ethers.utils.formatEther(deductedAmount);
const ethAvailable = ethers.utils.formatEther(availableAmount);
const now = Math.floor(Date.now() / 1000);
const timeLeft = Math.max(0, releaseTime - now);
const days = Math.floor(timeLeft / 86400);
const hours = Math.floor((timeLeft % 86400) / 3600);
const minutes = Math.floor((timeLeft % 3600) / 60);
const seconds = timeLeft % 60;
const releaseDate = new Date(releaseTime * 1000).toLocaleString();
const isExpired = now >= releaseTime;
let statusText = isExpired ?
(isWithdrawable ? "✅ Ready for withdrawal" : "⚠️ Expired but no funds available") :
"🔒 Still locked";
bondInfoDiv.innerHTML = `
<p><strong>Address:</strong> ${selectedAddress}</p>
<p><strong>Status:</strong> ${statusText}</p>
<p><strong>Original Deposit:</strong> ${ethAmount} ETH</p>
<p><strong>Deducted Amount:</strong> ${ethDeducted} ETH</p>
<p><strong>Available Amount:</strong> ${ethAvailable} ETH</p>
<p><strong>Release Date:</strong> ${releaseDate}</p>
${!isExpired ? `<p><strong>Time Remaining:</strong> ${days} days, ${hours} hours, ${minutes} minutes, ${seconds} seconds</p>` : ''}
`;
infoDiv.style.display = 'block';
} catch (err) {
console.error('Error getting bond info:', err);
bondInfoDiv.innerHTML = `<p class="status-error"><strong>Error:</strong> ${err.message}</p>`;
infoDiv.style.display = 'block';
}
}
// Function to toggle notes field requirement when "Other" is selected
function toggleNotesField() {
const reason = document.getElementById('deductionReason').value;
const notesField = document.getElementById('deductionNotes');
const notesRequired = document.getElementById('notesRequired');
if (reason === 'Other') {
notesField.required = true;
notesRequired.style.display = 'inline';
notesField.placeholder = 'Please specify the reason for deduction...';
} else {
notesField.required = false;
notesRequired.style.display = 'none';
notesField.placeholder = 'Additional details about the deduction...';
}
}
document.getElementById('deductForm').onsubmit = async (e) => {
e.preventDefault();
if (!account) {
alert('Connect your wallet first!');
return;
}
const selectedAddress = document.getElementById('userAddressSelect').value;
const amount = document.getElementById('deductAmount').value;
const reason = document.getElementById('deductionReason').value;
if (!selectedAddress) {
alert('Please select a user address');
return;
}
if (!amount || amount <= 0) {
alert('Please enter a valid deduct amount (must be greater than 0)');
return;
}
// Check if deduction amount exceeds available bond amount
try {
const provider = new ethers.providers.Web3Provider(window.ethereum, 'any');
const contract = new ethers.Contract(contractAddress, contractABI, provider);
const depositInfo = await contract.getDepositInfo(selectedAddress);
const [bondAmount, , deductedAmount] = depositInfo;
const remainingAmount = bondAmount - deductedAmount;
const deductionAmountWei = ethers.utils.parseEther(amount);
if (deductionAmountWei > remainingAmount) {
const maxDeductible = ethers.utils.formatEther(remainingAmount);
alert(`Deduction amount (${amount} ETH) exceeds available bond amount (${maxDeductible} ETH)`);
return;
}
} catch (err) {
alert('Error checking bond amount: ' + err.message);
return;
}
if (!reason) {
alert('Please select a reason for the deduction');
return;
}
// Log deduction details for record keeping
const deductionRecord = {
address: selectedAddress,
amount: amount + ' ETH',
reason: reason,
timestamp: new Date().toISOString(),
executor: account
};
console.log('Making deduction:', deductionRecord);
try {
const provider = new ethers.providers.Web3Provider(window.ethereum, 'any');
const signer = provider.getSigner();
const contract = new ethers.Contract(contractAddress, contractABI, signer);
setStatus(`Making deduction: ${amount} ETH for "${reason}"...`);
const tx = await contract.deductETH(selectedAddress, ethers.utils.parseEther(amount), {
gasLimit: 200000, // Set a reasonable gas limit for deductions
gasPrice: ethers.utils.parseUnits('20', 'gwei') // Set gas price for Sepolia
});
setStatus(`
<div class="status-info">
Deduction transaction sent! Waiting for confirmation...
</div>
`, true);
const receipt = await tx.wait();
// Check if we're on Sepolia network and show Etherscan link
const network = await provider.getNetwork();
// Enhanced success message with network-specific links
if (network.chainId === 11155111) { // Sepolia chainId
const etherscanUrl = `https://sepolia.etherscan.io/tx/${tx.hash}`;
setStatus(`
<div class="status-success">
✅ Deduction successful!<br>
<small>Amount: ${amount} ETH<br>
Reason: ${reason}<br>
Transaction Hash: ${tx.hash}<br>
<a href="${etherscanUrl}" target="_blank" class="etherscan-link">View on Sepolia Etherscan</a></small>
</div>
`, true);
} else {
setStatus(`
<div class="status-success">
✅ Deduction successful!<br>
<small>Amount: ${amount} ETH<br>
Reason: ${reason}<br>
Transaction Hash: ${tx.hash}</small>
</div>
`, true);
}
// Refresh the bond info for the selected user
await handleAddressSelection();
// Clear the form fields
document.getElementById('deductAmount').value = '';
document.getElementById('deductionReason').value = '';
} catch (err) {
setStatus(`Error: ${err.message}`);
}
};
</script>
</body>
</html>