-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
351 lines (312 loc) · 8.73 KB
/
Copy pathscript.js
File metadata and controls
351 lines (312 loc) · 8.73 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
// Constants
const CONTRACT_ADDRESS = "0x373f77cFcd8167dA0A143EC1eb7B4DB204e04444";
// Hardcoded ABI Placeholder
// Replace this array with the actual ABI array from out/Bank.sol/Bank.json
const contractAbi = [
{
type: "function",
name: "accountsBalance",
inputs: [
{
name: "",
type: "address",
internalType: "address",
},
],
outputs: [
{
name: "",
type: "uint256",
internalType: "uint256",
},
],
stateMutability: "view",
},
{
type: "function",
name: "checkBalance",
inputs: [
{
name: "user",
type: "address",
internalType: "address",
},
],
outputs: [
{
name: "",
type: "uint256",
internalType: "uint256",
},
],
stateMutability: "view",
},
{
type: "function",
name: "deposit",
inputs: [
{
name: "amount",
type: "uint256",
internalType: "uint256",
},
],
outputs: [],
stateMutability: "payable",
},
{
type: "function",
name: "withdraw",
inputs: [
{
name: "amount",
type: "uint256",
internalType: "uint256",
},
],
outputs: [],
stateMutability: "nonpayable",
},
{
type: "event",
name: "DepositSuccessfully",
inputs: [
{
name: "account",
type: "address",
indexed: true,
internalType: "address",
},
{
name: "amount",
type: "uint256",
indexed: false,
internalType: "uint256",
},
],
anonymous: false,
},
{
type: "error",
name: "BANK__AccountNotFound",
inputs: [],
},
{
type: "error",
name: "BANK__AmountCannotBeZero",
inputs: [],
},
{
type: "error",
name: "BANK__DepositMisMatch",
inputs: [],
},
{
type: "error",
name: "BANK__InsuficentFunds",
inputs: [],
},
{
type: "error",
name: "BANK__WithdrawFailed",
inputs: [],
},
];
// Global State
let provider;
let signer;
let contract;
let userAddressStr = "";
// DOM Elements
const connectWalletBtn = document.getElementById("connectWalletBtn");
const walletInfo = document.getElementById("walletInfo");
const userAddressEl = document.getElementById("userAddress");
const userBalanceEl = document.getElementById("userBalance");
const bankDepositsEl = document.getElementById("bankDeposits");
const depositBtn = document.getElementById("depositBtn");
const withdrawBtn = document.getElementById("withdrawBtn");
const depositAmountInput = document.getElementById("depositAmount");
const withdrawAmountInput = document.getElementById("withdrawAmount");
const toastContainer = document.getElementById("toastContainer");
// Initialization
async function init() {
if (window.ethereum) {
// Handle account changes
window.ethereum.on("accountsChanged", handleAccountsChanged);
window.ethereum.on("chainChanged", () => window.location.reload());
// Setup ethers v6 provider
provider = new ethers.BrowserProvider(window.ethereum);
// Check if already connected
const accounts = await provider.listAccounts();
if (accounts.length > 0) {
handleAccountsChanged(accounts);
}
} else {
console.warn("Please install MetaMask to use this DApp.");
connectWalletBtn.innerText = "MetaMask Not Found";
connectWalletBtn.disabled = true;
}
}
// Connect Wallet
async function connectWallet() {
if (!window.ethereum) {
showToast("MetaMask is not installed!", "error");
return;
}
try {
connectWalletBtn.innerText = "Connecting...";
const accounts = await provider.send("eth_requestAccounts", []);
handleAccountsChanged(accounts);
showToast("Wallet Connected!", "success");
} catch (error) {
console.error(error);
showToast("User Denied Connection", "error");
connectWalletBtn.innerText = "Connect Wallet";
}
}
// Handle Account Connection
async function handleAccountsChanged(accounts) {
if (accounts.length === 0) {
// Disconnected
walletInfo.classList.add("hidden");
connectWalletBtn.classList.remove("hidden");
userAddressStr = "";
return;
}
// Set Signer & Contract
signer = await provider.getSigner();
userAddressStr = accounts[0].address || accounts[0]; // Ethers v6 might return objects or strings
if (typeof userAddressStr !== "string") {
userAddressStr = await signer.getAddress();
}
contract = new ethers.Contract(CONTRACT_ADDRESS, contractAbi, signer);
// Update UI
connectWalletBtn.classList.add("hidden");
walletInfo.classList.remove("hidden");
// Truncate address for display
userAddressEl.innerText = `${userAddressStr.substring(0, 6)}...${userAddressStr.substring(userAddressStr.length - 4)}`;
await updateBalances();
}
// Update User & Bank Balances
async function updateBalances() {
if (!signer || !contract) return;
try {
// Get ETH Balance
const balanceWei = await provider.getBalance(userAddressStr);
const balanceEth = ethers.formatEther(balanceWei);
userBalanceEl.innerText = parseFloat(balanceEth).toFixed(4);
// Get Bank Deposits
try {
const depositsWei = await contract.checkBalance(userAddressStr);
const depositsEth = ethers.formatEther(depositsWei);
bankDepositsEl.innerText = parseFloat(depositsEth).toFixed(4);
} catch (e) {
console.warn("checkBalance() failed. Ensure actual ABI is loaded.", e);
bankDepositsEl.innerText = "0.0000";
}
} catch (error) {
console.error("Error updating balances:", error);
}
}
// Deposit Function
async function depositFunds() {
const val = depositAmountInput.value;
if (!val || parseFloat(val) <= 0) {
showToast("Please enter a valid amount to deposit.", "error");
return;
}
if (!contract) {
showToast("Please connect your wallet first.", "error");
return;
}
try {
showToast("Processing Transaction...", "info");
const tx = await contract.deposit(ethers.parseEther(val), {
value: ethers.parseEther(val),
});
depositBtn.disabled = true;
depositBtn.innerText = "Depositing...";
await tx.wait();
showToast("Transaction Confirmed!", "success");
depositAmountInput.value = "";
await updateBalances();
} catch (error) {
console.error(error);
// Attempt to extract custom error name or reason
const customError = error.revert?.name || error.info?.error?.name || error.reason;
if (
error.code === "ACTION_REJECTED" ||
error.message.includes("user rejected")
) {
showToast("User Denied Transaction.", "error");
} else if (customError) {
showToast(`Failed: ${customError}`, "error");
} else {
showToast("Transaction Failed.", "error");
}
} finally {
depositBtn.disabled = false;
depositBtn.innerText = "Deposit Funds";
}
}
// Withdraw Function
async function withdrawFunds() {
const val = withdrawAmountInput.value;
if (!val || parseFloat(val) <= 0) {
showToast("Please enter a valid amount to withdraw.", "error");
return;
}
if (!contract) {
showToast("Please connect your wallet first.", "error");
return;
}
try {
showToast("Processing Transaction...", "info");
const tx = await contract.withdraw(ethers.parseEther(val));
withdrawBtn.disabled = true;
withdrawBtn.innerText = "Withdrawing...";
await tx.wait();
showToast("Transaction Confirmed!", "success");
withdrawAmountInput.value = "";
await updateBalances();
} catch (error) {
console.error(error);
// Attempt to extract custom error name or reason
const customError = error.revert?.name || error.info?.error?.name || error.reason;
if (
error.code === "ACTION_REJECTED" ||
error.message.includes("user rejected")
) {
showToast("User Denied Transaction.", "error");
} else if (customError) {
showToast(`Failed: ${customError}`, "error");
} else {
showToast("Transaction Failed.", "error");
}
} finally {
withdrawBtn.disabled = false;
withdrawBtn.innerText = "Withdraw Funds";
}
}
// UI Toast Notification System
function showToast(message, type = "info") {
const toast = document.createElement("div");
toast.className = `toast ${type}`;
toast.innerText = message;
toastContainer.appendChild(toast);
// Remove toast after 4 seconds
setTimeout(() => {
toast.style.animation = "slideOut 0.3s ease-in forwards";
setTimeout(() => {
if (toastContainer.contains(toast)) {
toastContainer.removeChild(toast);
}
}, 300);
}, 4000);
}
// Event Listeners
connectWalletBtn.addEventListener("click", connectWallet);
depositBtn.addEventListener("click", depositFunds);
withdrawBtn.addEventListener("click", withdrawFunds);
// Run init on load
window.addEventListener("DOMContentLoaded", init);