-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconnection.js
More file actions
98 lines (89 loc) · 2.59 KB
/
Copy pathconnection.js
File metadata and controls
98 lines (89 loc) · 2.59 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
// Base Sepolia Network Configuration
const BASE_SEPOLIA = {
chainId: "0x14A34", // 84532 in hex
chainName: "Base Sepolia Testnet",
nativeCurrency: {
name: "Base",
symbol: "ETH",
decimals: 18,
},
rpcUrls: ["https://sepolia.base.org"],
blockExplorerUrls: ["https://sepolia.basescan.org"],
}
// Auto-Connect on Refresh
const checkConnection = async () => {
if (typeof window !== "undefined" && window.ethereum) {
try {
const accounts = await window.ethereum.request({ method: "eth_accounts" })
if (accounts.length > 0) {
setWalletAddress(accounts[0])
setIsConnected(true)
}
} catch (error) {
console.error("Error checking connection:", error)
}
}
}
// Adding Network in wallet
const addLiskSepoliaNetwork = async () => {
try {
await window.ethereum.request({
method: "wallet_addEthereumChain",
params: [BASE_SEPOLIA],
})
return true
} catch (error) {
console.error("Error adding network:", error)
return false
}
}
// Switching to Network
const switchToLiskSepolia = async () => {
try {
await window.ethereum.request({
method: "wallet_switchEthereumChain",
params: [{ chainId: BASE_SEPOLIA.chainId }],
})
return true
} catch (error) {
if (error.code === 4902) {
// Network not added, try to add it
return await addLiskSepoliaNetwork()
}
console.error("Error switching network:", error)
return false
}
}
// Connect Button Handler
const connectWallet = async () => {
if (!window.ethereum) {
alert("Please install MetaMask or another Web3 wallet!")
return
}
setIsConnecting(true)
try {
// Request account access
const accounts = await window.ethereum.request({
method: "eth_requestAccounts",
})
if (accounts.length > 0) {
// Switch to Lisk Sepolia
const networkSwitched = await switchToLiskSepolia()
if (networkSwitched) {
setWalletAddress(accounts[0])
setIsConnected(true)
} else {
alert("Please switch to Lisk Sepolia network to continue")
}
}
} catch (error) {
console.error("Error connecting wallet:", error)
alert("Failed to connect wallet. Please try again.")
} finally {
setIsConnecting(false)
}
}
const disconnectWallet = () => {
setIsConnected(false)
setWalletAddress("")
}