-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathl.js
More file actions
72 lines (60 loc) · 2.83 KB
/
Copy pathl.js
File metadata and controls
72 lines (60 loc) · 2.83 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
async function connectMetaMask() {
try {
const accounts = await ethereum.request({ method: "eth_requestAccounts" });
if (accounts.length > 0) {
const account = accounts[0];
console.log("Connected account:", account);
// Display connected account
document.getElementById("connected-account").textContent = account;
document.getElementById("account-info").style.display = "block";
// Fetch and display balance
const balanceInWei = await ethereum.request({
method: "eth_getBalance",
params: [account, "latest"],
});
const balanceInEth = parseInt(balanceInWei, 16) / 10 ** 18;
document.getElementById("account-balance").textContent = balanceInEth.toFixed(4);
// Fetch and display transactions
await fetchTransactions(account);
}
} catch (error) {
console.error("Error connecting to MetaMask:", error);
alert("Error connecting to MetaMask.");
}
}
async function fetchTransactions(account) {
const apiKey = "D5VCAXY2D5SE2Q2TAGZ6QBPEBGVQBTRQ26"; // Replace with your Etherscan API key
const url = `https://api-sepolia.etherscan.io/api?module=account&action=txlist&address=${account}&startblock=0&endblock=99999999&sort=desc&apikey=${apiKey}`;
try {
const response = await fetch(url);
const data = await response.json();
if (data.status === "1" && data.result.length > 0) {
displayTransactions(data.result);
} else {
console.error("No transactions found:", data.message);
document.getElementById("transactions-list").innerHTML = "<li>No transactions found.</li>";
}
} catch (error) {
console.error("Error fetching transactions:", error);
document.getElementById("transactions-list").innerHTML = "<li>Error fetching transactions.</li>";
}
}
function displayTransactions(transactions) {
const transactionsList = document.getElementById("transactions-list");
transactionsList.innerHTML = ""; // Clear previous transactions
transactions.forEach((tx) => {
const listItem = document.createElement("li");
listItem.innerHTML = `
<strong>Hash:</strong> ${tx.hash}<br>
<strong>From:</strong> ${tx.from}<br>
<strong>To:</strong> ${tx.to}<br>
<strong>Value:</strong> ${parseInt(tx.value, 16) / 10 ** 18} ETH<br>
<strong>Gas Used:</strong> ${tx.gasUsed}<br>
<strong>Timestamp:</strong> ${new Date(tx.timeStamp * 1000).toLocaleString()}
`;
transactionsList.appendChild(listItem);
});
document.getElementById("transactions-info").style.display = "block";
}
// Attach event listener
document.getElementById("connect-button").addEventListener("click", connectMetaMask);