-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathApp.js
More file actions
539 lines (499 loc) · 21.2 KB
/
App.js
File metadata and controls
539 lines (499 loc) · 21.2 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
import React, { useState, useEffect } from 'react';
import { ethers } from 'ethers'; // Library for interacting with Ethereum blockchain
import './App.css';
import ExpenseTrackerABI from './ExpenseTrackerABI.json'; // This contains information about how to talk to our smart contract
function App() {
// --- VARIABLES STORED IN THE COMPONENT (STATE) ---
// These variables can change and when they do, the page will update
const [provider, setProvider] = useState(null); // Connection to the Ethereum network
const [contract, setContract] = useState(null); // Our expense tracker smart contract
const [account, setAccount] = useState(''); // User's Ethereum wallet address
const [isConnected, setIsConnected] = useState(false); // Whether user connected their wallet
const [isRegistered, setIsRegistered] = useState(false); // Whether user registered their name
const [name, setName] = useState(''); // User's name
const [expenses, setExpenses] = useState([]); // List of all expenses
const [people, setPeople] = useState([]); // List of all registered people
const [loadingExpenses, setLoadingExpenses] = useState(false); // Whether expenses are being loaded
const [expenseLabel, setExpenseLabel] = useState(''); // Description for a new expense
const [participants, setParticipants] = useState([{ address: '', amountPaid: 0, amountOwed: 0 }]); // People involved in a new expense
const [showAddExpense, setShowAddExpense] = useState(false); // Whether to show the "Add Expense" form
const contractAddress = process.env.REACT_APP_CONTRACT_ADDRESS; // Paste the address recieved from Remix IDE here
const [totalUsers, setTotalUsers] = useState(0); // js task // to display total number of users
const [isEditing, setIsEditing] = useState(false); // solodidity task // to edit name
const [newName, setNewName] = useState('');
// --- RUNS WHEN THE PAGE FIRST LOADS ---
// This connects to the user's Ethereum wallet (like MetaMask)
useEffect(() => {
const init = async () => {
// Check if MetaMask (or similar wallet) is installed
if (window.ethereum) {
try {
// Ask user permission to connect to their wallet
await window.ethereum.request({ method: 'eth_requestAccounts' });
// Create a connection to Ethereum
const providerInstance = new ethers.providers.Web3Provider(window.ethereum);
setProvider(providerInstance);
// Check if user is on the right Ethereum network (Sepolia test network)
const network = await providerInstance.getNetwork();
if (network.chainId !== 11155111) { // 11155111 is the ID for Sepolia testnet
alert("Please connect to Sepolia testnet.");
return;
}
// Get user's account and save it
const signer = providerInstance.getSigner();
const address = await signer.getAddress();
setAccount(address);
setIsConnected(true);
// Connect to our expense tracker smart contract
const contractInstance = new ethers.Contract(contractAddress, ExpenseTrackerABI, signer);
setContract(contractInstance);
// Listen for user changing their account in MetaMask
window.ethereum.on('accountsChanged', (accounts) => {
setAccount(accounts[0] || '');
setIsConnected(accounts.length > 0);
});
} catch (error) {
console.error("Initialization error:", error);
}
} else {
// If MetaMask is not installed
alert("Please install MetaMask.");
}
};
init(); // Run the initialization function
// Clean up when component unmounts (good practice to prevent memory leaks)
return () => {
if (window.ethereum) {
window.ethereum.removeAllListeners('accountsChanged');
}
};
}, []); // Empty array means this runs only once when page loads
// --- RUNS WHEN CONTRACT OR ACCOUNT CHANGES ---
// Checks if user is registered and loads their data
useEffect(() => {
const checkRegistration = async () => {
if (!contract || !account) return; // Skip if contract or account isn't ready
try {
// Ask the contract if this user is registered
const person = await contract.getPerson(account);
const registered = person.walletAddress !== ethers.constants.AddressZero;
setIsRegistered(registered);
if (registered) {
setName(person.name); // Save the user's name
await loadExpenses(); // Load all expenses
await loadPeople(); // Load all registered people
}
await loadTotalUsers(); // Load total users count // js task
} catch (error) {
console.error("Error checking registration:", error);
}
};
checkRegistration();
}, [contract, account]); // Run this when contract or account changes
// --- DEBUGGING HELP ---
// Prints expense information to console for troubleshooting
useEffect(() => {
if (expenses.length > 0) {
console.log("LOADED EXPENSES:", expenses);
console.log("LOADED PEOPLE:", people);
// Print each expense's details to the console
expenses.forEach(expense => {
console.log(`Expense: ${expense.label}`);
expense.participants.forEach(p => {
console.log(` Participant: ${p.address.substring(0, 8)}...`);
console.log(` Paid: ${p.amountPaid} ETH, Owes: ${p.amountOwed} ETH`);
console.log(` Net: ${parseFloat(p.amountPaid) - parseFloat(p.amountOwed)} ETH`);
});
});
}
}, [expenses, people]); // Run when expenses or people change
// --- REGISTER NEW USER ---
// Saves user's name to the blockchain
const registerPerson = async () => {
if (!name.trim()) { // Check if name is empty
alert("Please enter your name.");
return;
}
try {
// Call the registerPerson function in our smart contract
const tx = await contract.registerPerson(name.trim());
await tx.wait(); // Wait for transaction to be confirmed on blockchain
setIsRegistered(true);
alert("Registration successful!");
await loadPeople(); // Refresh list of people
await loadExpenses(); // Refresh list of expenses
await loadTotalUsers(); // Load total users count // js task
} catch (error) {
console.error("Registration failed:", error);
alert(`Registration failed: ${error.message}`);
}
};
// --- LOAD ALL EXPENSES ---
// Gets all expenses from the blockchain
const loadExpenses = async () => {
if (!contract || !isRegistered) return; // Skip if not ready
setLoadingExpenses(true); // Show loading indicator
try {
// Get the total number of expenses
const count = await contract.expenseCount();
const loaded = [];
// Loop through each expense and load its details
for (let i = 0; i < count; i++) {
try {
// Get basic expense info
const [id, label, timestamp] = await contract.getExpenseBasicInfo(i);
// Get list of addresses involved in this expense
const participantsAddresses = await contract.getExpenseParticipants(i);
// For each participant, get how much they paid and owe
const participantsData = await Promise.all(
participantsAddresses.map(async (address) => {
try {
const amountPaid = await contract.getAmountPaid(i, address);
const amountOwed = await contract.getAmountOwed(i, address);
return {
address,
amountPaid: ethers.utils.formatEther(amountPaid), // Convert from wei to ETH
amountOwed: ethers.utils.formatEther(amountOwed), // Convert from wei to ETH
};
} catch (error) {
console.error(`Error loading amounts for participant ${address}:`, error);
return { address, amountPaid: "0", amountOwed: "0" };
}
})
);
// Add this expense to our list
loaded.push({
id: id.toNumber(), // Convert from BigNumber to regular number
label,
timestamp: new Date(timestamp.toNumber() * 1000).toLocaleString(), // Convert timestamp to readable date
participants: participantsData,
});
} catch (error) {
console.error(`Error loading expense ${i}:`, error);
}
}
setExpenses(loaded); // Save all expenses to state
} catch (error) {
console.error("Error loading expenses:", error);
alert("Could not load expenses. Check console.");
} finally {
setLoadingExpenses(false); // Hide loading indicator
}
};
// --- LOAD ALL REGISTERED PEOPLE ---
// Gets list of all registered users
const loadPeople = async () => {
if (!contract) return; // Skip if contract isn't ready
try {
// Get all registered addresses
const addresses = await contract.getAllRegisteredPeople();
// For each address, get their name and balance
const peopleData = await Promise.all(
addresses.map(async (address) => {
const person = await contract.getPerson(address);
const netBalance = await contract.getNetBalance(address);
return {
address,
name: person.name,
netBalance: ethers.utils.formatEther(netBalance), // Convert from wei to ETH
};
})
);
setPeople(peopleData); // Save people to state
} catch (error) {
console.error("Error loading people:", error);
}
};
// --- EDIT USER NAME --- // solidity task
const updateName = async () => {
if (!newName.trim()) {
alert("Please enter a name");
return;
}
try {
const tx = await contract.updatePersonName(newName.trim());
await tx.wait();
setName(newName);
setIsEditing(false);
alert("Name updated successfully!");
await loadPeople();
} catch (error) {
console.error("Error updating name:", error);
alert(`Update failed: ${error.message}`);
}
};
// --- LOAD TOTAL USERS COUNT --- //js task
const loadTotalUsers = async () => {
if (!contract) return;
try {
const count = await contract.getTotalRegisteredUsers();
setTotalUsers(count.toNumber());
} catch (error) {
console.error("Error loading total users:", error);
}
};
// --- ADD NEW EXPENSE ---
// Creates a new expense on the blockchain
const addExpense = async () => {
// Input validation
if (!expenseLabel.trim()) {
alert("Enter an expense label.");
return;
}
if (participants.length === 0) {
alert("Add at least one participant.");
return;
}
for (const participant of participants) {
if (!participant.address || participant.amountPaid < 0 || participant.amountOwed < 0) {
alert("Participant details are invalid.");
return;
}
}
try {
// Prepare data for the smart contract
const addresses = participants.map(p => p.address.trim());
const paidAmounts = participants.map(p => ethers.utils.parseEther(p.amountPaid.toString())); // Convert ETH to wei
const owedAmounts = participants.map(p => ethers.utils.parseEther(p.amountOwed.toString())); // Convert ETH to wei
// Call the addExpense function in our smart contract
const tx = await contract.addExpense(expenseLabel, addresses, paidAmounts, owedAmounts);
await tx.wait(); // Wait for transaction to be confirmed
// Reset form and reload data
setExpenseLabel('');
setParticipants([{ address: '', amountPaid: 0, amountOwed: 0 }]);
setShowAddExpense(false);
await loadExpenses();
await loadPeople();
} catch (error) {
console.error("Error adding expense:", error);
alert(`Error: ${error.message}`);
}
};
// --- HELPER FUNCTIONS FOR PARTICIPANTS ---
// Add a new participant row to the form
const addParticipant = () => {
setParticipants([...participants, { address: '', amountPaid: 0, amountOwed: 0 }]);
};
// Update a participant's information
const updateParticipant = (index, field, value) => {
const updated = [...participants];
updated[index][field] = value;
setParticipants(updated);
};
// Remove a participant from the form
const removeParticipant = (index) => {
if (participants.length > 1) {
setParticipants(participants.filter((_, i) => i !== index));
}
};
// --- THE PAGE LAYOUT (USER INTERFACE) ---
return (
<div className="App">
<header className="App-header">
{/*js task to display total number of users */}
<div style={{
position: 'absolute',
top: '10px',
right: '10px',
background: '#4CAF50',
padding: '8px 15px',
borderRadius: '5px',
color: 'white',
fontSize: '14px',
fontWeight: 'bold'
}}>
Total Users: {totalUsers}
</div>
<h1>On-Chain Expense Tracker</h1>
{/* STEP 1: CONNECT WALLET - Show if not connected */}
{!isConnected ? (
<button onClick={() => window.ethereum.request({ method: 'eth_requestAccounts' })}>
Connect Wallet
</button>
)
/* STEP 2: REGISTER - Show if connected but not registered */
: !isRegistered ? (
<div>
<h2>Register</h2>
<input
type="text"
placeholder="Your Name"
value={name}
onChange={(e) => setName(e.target.value)}
/>
<button onClick={registerPerson}>Register</button>
</div>
)
/* STEP 3: MAIN APP - Show if connected and registered */
: (
<div>
<h2>
Welcome, {isEditing ? ( /*for edting the users name */ //solidity task */
<span>
<input
type="text"
value={newName}
onChange={(e) => setNewName(e.target.value)}
placeholder="Enter new name"
style={{
fontSize: '1em',
padding: '5px',
marginRight: '10px'
}}
/>
<button
onClick={updateName}
style={{
padding: '5px 10px',
marginRight: '5px',
background: '#4CAF50',
border: 'none',
borderRadius: '3px',
color: 'white',
cursor: 'pointer'
}}
>
Save
</button>
<button
onClick={() => {
setIsEditing(false);
setNewName(name);
}}
style={{
padding: '5px 10px',
background: '#f44336',
border: 'none',
borderRadius: '3px',
color: 'white',
cursor: 'pointer'
}}
>
Cancel
</button>
</span>
) : (
<span>
{name}
<button
onClick={() => {
setIsEditing(true);
setNewName(name);
}}
style={{
marginLeft: '10px',
padding: '5px 10px',
background: '#2196F3',
border: 'none',
borderRadius: '3px',
color: 'white',
cursor: 'pointer'
}}
>
Edit Name
</button>
</span>
)}
</h2>
<p>Account: {account}</p>
<button onClick={() => setShowAddExpense(!showAddExpense)}>
{showAddExpense ? "Cancel" : "Add Expense"}
</button>
<button onClick={loadExpenses}>Refresh Expenses</button>
{/* ADD EXPENSE FORM - Show when "Add Expense" is clicked */}
{showAddExpense && (
<div>
<h3>New Expense</h3>
<input
type="text"
placeholder="Expense Label"
value={expenseLabel}
onChange={(e) => setExpenseLabel(e.target.value)}
/>
{/* For each participant, show input fields */}
{participants.map((p, idx) => (
<div key={idx}>
<input
placeholder="Address"
value={p.address}
onChange={(e) => updateParticipant(idx, 'address', e.target.value)}
/>
<input
type="number"
placeholder="Paid"
value={p.amountPaid}
onChange={(e) => updateParticipant(idx, 'amountPaid', e.target.value)}
/>
<input
type="number"
placeholder="Owed"
value={p.amountOwed}
onChange={(e) => updateParticipant(idx, 'amountOwed', e.target.value)}
/>
<button onClick={() => removeParticipant(idx)}>Remove</button>
</div>
))}
<button onClick={addParticipant}>Add Participant</button>
<button onClick={addExpense}>Save Expense</button>
</div>
)}
{/* PEOPLE LIST - Show all registered users */}
<h3>People</h3>
<table style={{ borderCollapse: 'collapse', margin: '10px 0' }}>
<thead>
<tr>
<th style={{ padding: '8px', border: '1px solid #ddd' }}>Name</th>
<th style={{ padding: '8px', border: '1px solid #ddd' }}>Address</th>
<th style={{ padding: '8px', border: '1px solid #ddd' }}>Net Balance</th>
</tr>
</thead>
<tbody>
{people.map((person, idx) => (
<tr key={idx}>
<td style={{ padding: '8px', border: '1px solid #ddd' }}>{person.name}</td>
<td style={{ padding: '8px', border: '1px solid #ddd' }}>{person.address.substring(0, 8)}...</td>
<td style={{ padding: '8px', border: '1px solid #ddd', color: parseFloat(person.netBalance) < 0 ? 'red' : 'green' }}>
{parseFloat(person.netBalance).toFixed(5)} ETH
</td>
</tr>
))}
</tbody>
</table>
{/* EXPENSE HISTORY - Show all expenses */}
<h3>Expense History</h3>
{loadingExpenses ? <p>Loading...</p> : (
expenses.map(expense => (
<div key={expense.id} style={{ border: '1px solid #ddd', margin: '10px 0', padding: '10px' }}>
<h4>{expense.label}</h4>
<p>{expense.timestamp}</p>
<table style={{ borderCollapse: 'collapse', width: '100%' }}>
<thead>
<tr>
<th style={{ padding: '5px', border: '1px solid #ddd' }}>Participant</th>
<th style={{ padding: '5px', border: '1px solid #ddd' }}>Paid</th>
<th style={{ padding: '5px', border: '1px solid #ddd' }}>Owes</th>
</tr>
</thead>
<tbody>
{expense.participants.map((p, idx) => (
<tr key={idx}>
<td style={{ padding: '5px', border: '1px solid #ddd' }}>
{/* Show name if found, otherwise show shortened address */}
{people.find(person => person.address === p.address)?.name || p.address.substring(0, 8)}...
</td>
<td style={{ padding: '5px', border: '1px solid #ddd' }}>{p.amountPaid} ETH</td>
<td style={{ padding: '5px', border: '1px solid #ddd' }}>{p.amountOwed} ETH</td>
</tr>
))}
</tbody>
</table>
</div>
))
)}
</div>
)}
</header>
</div>
);
}
export default App;