-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
ConnectionController.ts
267 lines (230 loc) · 7.95 KB
/
ConnectionController.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
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
import { subscribeKey as subKey } from 'valtio/vanilla/utils'
import { proxy, ref } from 'valtio/vanilla'
import { CoreHelperUtil } from '../utils/CoreHelperUtil.js'
import { StorageUtil } from '../utils/StorageUtil.js'
import type {
Connector,
EstimateGasTransactionArgs,
SendTransactionArgs,
WcWallet,
WriteContractArgs
} from '../utils/TypeUtil.js'
import { TransactionsController } from './TransactionsController.js'
import { ChainController } from './ChainController.js'
import { type W3mFrameTypes } from '@reown/appkit-wallet'
import { ModalController } from './ModalController.js'
import { ConnectorController } from './ConnectorController.js'
import { EventsController } from './EventsController.js'
import type { CaipNetwork, ChainNamespace } from '@reown/appkit-common'
import { OptionsController } from './OptionsController.js'
// -- Types --------------------------------------------- //
export interface ConnectExternalOptions {
id: Connector['id']
type: Connector['type']
provider?: Connector['provider']
info?: Connector['info']
chain?: ChainNamespace
chainId?: number | string
caipNetwork?: CaipNetwork
}
export interface ConnectionControllerClient {
connectWalletConnect?: (onUri: (uri: string) => void) => Promise<void>
disconnect: () => Promise<void>
signMessage: (message: string) => Promise<string>
sendTransaction: (args: SendTransactionArgs) => Promise<string | null>
estimateGas: (args: EstimateGasTransactionArgs) => Promise<bigint>
parseUnits: (value: string, decimals: number) => bigint
formatUnits: (value: bigint, decimals: number) => string
connectExternal?: (options: ConnectExternalOptions) => Promise<void>
reconnectExternal?: (options: ConnectExternalOptions) => Promise<void>
checkInstalled?: (ids?: string[]) => boolean
writeContract: (args: WriteContractArgs) => Promise<`0x${string}` | null>
getEnsAddress: (value: string) => Promise<false | string>
getEnsAvatar: (value: string) => Promise<false | string>
grantPermissions: (params: readonly unknown[] | object) => Promise<unknown>
revokePermissions: (params: {
pci: string
permissions: unknown[]
expiry: number
address: `0x${string}`
}) => Promise<`0x${string}`>
getCapabilities: (params: string) => Promise<unknown>
}
export interface ConnectionControllerState {
_client?: ConnectionControllerClient
wcUri?: string
wcPairingExpiry?: number
wcLinking?: {
href: string
name: string
}
wcError?: boolean
recentWallet?: WcWallet
buffering: boolean
status?: 'connecting' | 'connected' | 'disconnected'
connectionControllerClient?: ConnectionControllerClient
}
type StateKey = keyof ConnectionControllerState
// -- State --------------------------------------------- //
const state = proxy<ConnectionControllerState>({
wcError: false,
buffering: false,
status: 'disconnected'
})
// eslint-disable-next-line init-declarations
let wcConnectionPromise: Promise<void> | undefined
// -- Controller ---------------------------------------- //
export const ConnectionController = {
state,
subscribeKey<K extends StateKey>(
key: K,
callback: (value: ConnectionControllerState[K]) => void
) {
return subKey(state, key, callback)
},
_getClient() {
return state._client
},
setClient(client: ConnectionControllerClient) {
state._client = ref(client)
},
async connectWalletConnect() {
StorageUtil.setConnectedConnector('WALLET_CONNECT')
if (CoreHelperUtil.isTelegram()) {
if (wcConnectionPromise) {
try {
await wcConnectionPromise
} catch (error) {
/* Empty */
}
wcConnectionPromise = undefined
return
}
if (!CoreHelperUtil.isPairingExpired(state?.wcPairingExpiry)) {
const link = state.wcUri
state.wcUri = link
return
}
wcConnectionPromise = new Promise(async (resolve, reject) => {
await this._getClient()
?.connectWalletConnect?.(uri => {
state.wcUri = uri
state.wcPairingExpiry = CoreHelperUtil.getPairingExpiry()
})
.catch(reject)
resolve()
})
this.state.status = 'connecting'
await wcConnectionPromise
wcConnectionPromise = undefined
state.wcPairingExpiry = undefined
this.state.status = 'connected'
} else {
await this._getClient()?.connectWalletConnect?.(uri => {
state.wcUri = uri
state.wcPairingExpiry = CoreHelperUtil.getPairingExpiry()
})
}
},
async connectExternal(options: ConnectExternalOptions, chain: ChainNamespace, setChain = true) {
await this._getClient()?.connectExternal?.(options)
if (setChain) {
ChainController.setActiveNamespace(chain)
}
},
async reconnectExternal(options: ConnectExternalOptions) {
await this._getClient()?.reconnectExternal?.(options)
StorageUtil.setConnectedConnector(options.type === 'AUTH' ? 'ID_AUTH' : options.type)
},
async setPreferredAccountType(accountType: W3mFrameTypes.AccountType) {
ModalController.setLoading(true)
const authConnector = ConnectorController.getAuthConnector()
if (!authConnector) {
return
}
await authConnector?.provider.setPreferredAccount(accountType)
await this.reconnectExternal(authConnector)
ModalController.setLoading(false)
EventsController.sendEvent({
type: 'track',
event: 'SET_PREFERRED_ACCOUNT_TYPE',
properties: {
accountType,
network: ChainController.state.activeCaipNetwork?.caipNetworkId || ''
}
})
},
async signMessage(message: string) {
return this._getClient()?.signMessage(message)
},
parseUnits(value: string, decimals: number) {
return this._getClient()?.parseUnits(value, decimals)
},
formatUnits(value: bigint, decimals: number) {
return this._getClient()?.formatUnits(value, decimals)
},
async sendTransaction(args: SendTransactionArgs) {
return this._getClient()?.sendTransaction(args)
},
async getCapabilities(params: string) {
return this._getClient()?.getCapabilities(params)
},
async grantPermissions(params: object | readonly unknown[]) {
return this._getClient()?.grantPermissions(params)
},
async estimateGas(args: EstimateGasTransactionArgs) {
return this._getClient()?.estimateGas(args)
},
async writeContract(args: WriteContractArgs) {
return this._getClient()?.writeContract(args)
},
async getEnsAddress(value: string) {
return this._getClient()?.getEnsAddress(value)
},
async getEnsAvatar(value: string) {
return this._getClient()?.getEnsAvatar(value)
},
checkInstalled(ids?: string[]) {
return this._getClient()?.checkInstalled?.(ids) || false
},
resetWcConnection() {
state.wcUri = undefined
state.wcPairingExpiry = undefined
state.wcLinking = undefined
state.recentWallet = undefined
state.status = 'disconnected'
TransactionsController.resetTransactions()
StorageUtil.deleteWalletConnectDeepLink()
},
setWcLinking(wcLinking: ConnectionControllerState['wcLinking']) {
state.wcLinking = wcLinking
},
setWcError(wcError: ConnectionControllerState['wcError']) {
state.wcError = wcError
state.buffering = false
},
setRecentWallet(wallet: ConnectionControllerState['recentWallet']) {
state.recentWallet = wallet
},
setBuffering(buffering: ConnectionControllerState['buffering']) {
state.buffering = buffering
},
setStatus(status: ConnectionControllerState['status']) {
state.status = status
},
async disconnect() {
try {
const siwx = OptionsController.state.siwx
if (siwx) {
const activeCaipNetwork = ChainController.getActiveCaipNetwork()
const address = CoreHelperUtil.getPlainAddress(ChainController.getActiveCaipAddress())
if (activeCaipNetwork && address) {
await siwx.revokeSession(activeCaipNetwork.caipNetworkId, address)
}
}
await ChainController.disconnect()
} catch (error) {
throw new Error('Failed to disconnect')
}
}
}