generated from Tahul/vue-composable-starter
-
-
Notifications
You must be signed in to change notification settings - Fork 56
/
Copy pathconnect.ts
179 lines (147 loc) · 5.55 KB
/
connect.ts
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
import { computed, readonly } from 'vue'
import { useStore } from '../store'
import { ConnectOptions, ConnectorName, ProviderTarget, RDNS } from '../types'
import { AutoConnectError, ConnectError, ConnectorNotFoundError } from '../errors'
import { normalizeChainId } from '../utils'
import {
getLastConnectedBrowserWallet,
removeLastConnectedBrowserWallet,
setLastConnectedBrowserWallet,
} from './localStorage'
export function useConnect(pinia?: any) {
const walletStore = useStore(pinia)
async function resetWallet() {
walletStore.wallet.status = 'idle'
walletStore.wallet.error = null
walletStore.wallet.connectorName = null
walletStore.wallet.provider = null
walletStore.wallet.connector = null
walletStore.wallet.address = null
walletStore.wallet.chainId = null
walletStore.wallet.providerInfo = null
walletStore.wallet.providerTarget = null
}
async function connectTo(connectorName: ConnectorName | string, options?: ConnectOptions) {
walletStore.wallet.error = ''
walletStore.wallet.status = 'connecting'
// find connector
const connector = walletStore.connectors.find(conn => conn.name === connectorName)
if (!connector) throw new ConnectorNotFoundError()
try {
const { provider, account, chainId, info } = await connector.connect(options)
if (connector.name === 'BrowserWallet') {
if (!info) throw new Error('BrowserWallet connector requires provider info')
if (!options?.target) throw new Error('BrowserWallet connector requires target')
walletStore.wallet.providerInfo = info
walletStore.wallet.providerTarget = options?.target
}
walletStore.wallet.connector = connector
walletStore.wallet.connectorName = connector.name as ConnectorName
walletStore.wallet.provider = provider
walletStore.wallet.address = account
walletStore.wallet.chainId = normalizeChainId(chainId)
walletStore.wallet.status = 'connected'
if (info?.rdns) setLastConnectedBrowserWallet(info.rdns)
} catch (err: any) {
await disconnect() // will resetWallet()
walletStore.wallet.error = err.message
throw new ConnectError(err)
}
// ============================= listen EIP-1193 events =============================
// Events: disconnect, chainChanged, and accountsChanged
walletStore.wallet.connector.onDisconnect((...args: any[]) => {
walletStore.onDisconnectCallback && walletStore.onDisconnectCallback(...args)
// TODO:
/**
* Exclude metamask to disconnect on this event
* @note MetaMask disconnect event would be triggered when the specific chain changed (like L2 network),
* so if we disconnect in this case, it would fail to reactivate ethers when chain changed
* because the wallet state was cleared.
* @todo better solution
*/
if (walletStore.wallet.connectorName === 'BrowserWallet') {
return
}
disconnect()
})
walletStore.wallet.connector.onAccountsChanged(async (accounts: string[]) => {
console.log('accounts changed:', accounts)
walletStore.onAccountsChangedCallback && walletStore.onAccountsChangedCallback(accounts)
if (!accounts.length) {
disconnect()
return
}
walletStore.wallet.address = accounts[0]
})
walletStore.wallet.connector.onChainChanged(async (chainId: number) => {
walletStore.onChainChangedCallback && walletStore.onChainChangedCallback(normalizeChainId(chainId))
walletStore.wallet.chainId = normalizeChainId(chainId)
})
}
async function disconnect() {
try {
if (walletStore.wallet.connector) {
await walletStore.wallet.connector.disconnect()
}
} catch (err: any) {
walletStore.error = `Failed to disconnect, wallet reset: ${err.message}`
throw new Error(`Failed to disconnect, wallet reset: ${err.message}`)
} finally {
resetWallet()
removeLastConnectedBrowserWallet()
}
}
const isWindowEthereumAvailable = typeof window !== 'undefined' && !!window.ethereum
async function autoConnect(target: ProviderTarget) {
const browserWallet = walletStore.connectors.find(conn => conn.name === 'BrowserWallet')
if (!browserWallet) return
let options: ConnectOptions
switch (target) {
case 'window.ethereum':
if (!isWindowEthereumAvailable) return
options = { target: 'window.ethereum' }
break
case 'rdns':
const lastRdns = getLastConnectedBrowserWallet()
if (!lastRdns) return
options = { target: 'rdns', rdns: lastRdns }
break
default:
throw new Error('target is required')
}
try {
await connectTo(browserWallet.name, options)
} catch (err: any) {
throw new AutoConnectError(err)
}
}
function onDisconnect(callback: (...args: any[]) => void) {
walletStore.onDisconnectCallback = callback
}
function onAccountsChanged(callback: (accounts: string[]) => void) {
walletStore.onAccountsChangedCallback = callback
}
function onChainChanged(callback: (chainId: number) => void) {
walletStore.onChainChangedCallback = callback
}
return {
isWindowEthereumAvailable,
wallet: readonly(walletStore.wallet),
status: computed(() => walletStore.wallet.status),
error: computed(() => walletStore.wallet.error),
connectorName: computed(() => walletStore.wallet.connectorName),
provider: computed(() => walletStore.wallet.provider),
providerInfo: computed(() => walletStore.wallet.providerInfo),
connector: computed(() => walletStore.wallet.connector),
address: computed(() => walletStore.wallet.address),
chainId: computed(() => walletStore.wallet.chainId),
isConnected: computed(() => walletStore.wallet.status === 'connected'),
resetWallet,
connectTo,
disconnect,
autoConnect,
onDisconnect,
onAccountsChanged,
onChainChanged,
}
}