-
-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
disconnect.ts
71 lines (61 loc) · 2.05 KB
/
disconnect.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
import type { Config, Connection, Connector } from '../createConfig.js'
import type { BaseErrorType, ErrorType } from '../errors/base.js'
import type {
ConnectorNotConnectedErrorType,
ConnectorNotFoundErrorType,
} from '../errors/config.js'
import type { ConnectorParameter } from '../types/properties.js'
export type DisconnectParameters = ConnectorParameter
export type DisconnectReturnType = void
export type DisconnectErrorType =
| ConnectorNotFoundErrorType
| ConnectorNotConnectedErrorType
// base
| BaseErrorType
| ErrorType
/** https://wagmi.sh/core/api/actions/disconnect */
export async function disconnect(
config: Config,
parameters: DisconnectParameters = {},
): Promise<DisconnectReturnType> {
let connector: Connector | undefined
if (parameters.connector) connector = parameters.connector
else {
const { connections, current } = config.state
const connection = connections.get(current!)
connector = connection?.connector
}
const connections = config.state.connections
if (connector) {
await connector.disconnect()
connector.emitter.off('change', config._internal.events.change)
connector.emitter.off('disconnect', config._internal.events.disconnect)
connector.emitter.on('connect', config._internal.events.connect)
connections.delete(connector.uid)
}
config.setState((x) => {
// if no connections exist, move to disconnected state
if (connections.size === 0)
return {
...x,
connections: new Map(),
current: null,
status: 'disconnected',
}
// switch over to another connection
const nextConnection = connections.values().next().value as Connection
return {
...x,
connections: new Map(connections),
current: nextConnection.connector.uid,
}
})
// Set recent connector if exists
{
const current = config.state.current
if (!current) return
const connector = config.state.connections.get(current)?.connector
if (!connector) return
await config.storage?.setItem('recentConnectorId', connector.id)
}
}