-
Notifications
You must be signed in to change notification settings - Fork 81
/
Copy pathuseWalletConnectV2.tsx
295 lines (254 loc) · 9.54 KB
/
useWalletConnectV2.tsx
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
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
import { useState, useCallback, useEffect, useMemo } from 'react'
import { SignClientTypes, SessionTypes, CoreTypes } from '@walletconnect/types'
import { SafeAppProvider } from '@safe-global/safe-apps-provider'
import { useSafeAppsSDK } from '@safe-global/safe-apps-react-sdk'
import { ChainInfo } from '@safe-global/safe-apps-sdk'
import { ethers } from 'ethers'
import { Core } from '@walletconnect/core'
import Web3WalletType, { Web3Wallet } from '@walletconnect/web3wallet'
import {
NEW_SESSION_ACTION,
TRANSACTION_CONFIRMED_ACTION,
WalletConnectVersion,
WALLET_CONNECT_VERSION_2,
} from '../utils/analytics'
import { isProduction, SAFE_WALLET_METADATA, WALLETCONNECT_V2_PROJECT_ID } from '../constants'
const EVMBasedNamespaces: string = 'eip155'
// see full list here: https://github.com/safe-global/safe-apps-sdk/blob/main/packages/safe-apps-provider/src/provider.ts#L35
export const compatibleSafeMethods: string[] = [
'eth_accounts',
'net_version',
'eth_chainId',
'personal_sign',
'eth_sign',
'eth_signTypedData',
'eth_signTypedData_v4',
'eth_sendTransaction',
'eth_blockNumber',
'eth_getBalance',
'eth_getCode',
'eth_getTransactionCount',
'eth_getStorageAt',
'eth_getBlockByNumber',
'eth_getBlockByHash',
'eth_getTransactionByHash',
'eth_getTransactionReceipt',
'eth_estimateGas',
'eth_call',
'eth_getLogs',
'eth_gasPrice',
'wallet_getPermissions',
'wallet_requestPermissions',
'safe_setSettings',
]
// see https://docs.walletconnect.com/2.0/specs/sign/error-codes
const UNSUPPORTED_CHAIN_ERROR_CODE = 5100
const INVALID_METHOD_ERROR_CODE = 1001
const USER_REJECTED_REQUEST_CODE = 4001
const USER_DISCONNECTED_CODE = 6000
const logger = isProduction ? undefined : 'debug'
export const errorLabel =
'We were unable to create a connection due to compatibility issues with the latest WalletConnect v2 upgrade. We are actively working with the WalletConnect team and the dApps to get these issues resolved. Use Safe Apps instead wherever possible.'
export type wcConnectType = (uri: string) => Promise<void>
export type wcDisconnectType = () => Promise<void>
type useWalletConnectType = {
wcClientData: SignClientTypes.Metadata | undefined
wcConnect: wcConnectType
wcDisconnect: wcDisconnectType
isWallectConnectInitialized: boolean
error: string | undefined
}
const useWalletConnectV2 = (
trackEvent: (action: string, version: WalletConnectVersion, meta?: CoreTypes.Metadata) => void,
): useWalletConnectType => {
const [web3wallet, setWeb3wallet] = useState<Web3WalletType>()
const [wcSession, setWcSession] = useState<SessionTypes.Struct>()
const [isWallectConnectInitialized, setIsWallectConnectInitialized] = useState<boolean>(false)
const [error, setError] = useState<string>()
const [chainInfo, setChainInfo] = useState<ChainInfo>()
const { safe, sdk } = useSafeAppsSDK()
const web3Provider = useMemo(
() => new ethers.providers.Web3Provider(new SafeAppProvider(safe, sdk)),
[sdk, safe],
)
useEffect(() => {
const getChainInfo = async () => {
try {
const chainInfo = await sdk.safe.getChainInfo()
setChainInfo(chainInfo)
} catch (error) {
console.error('Unable to get chain info:', error)
}
}
getChainInfo()
}, [sdk.safe])
// Initializing v2, see https://docs.walletconnect.com/2.0/javascript/web3wallet/wallet-usage
useEffect(() => {
const initializeWalletConnectV2Client = async () => {
const core = new Core({
projectId: WALLETCONNECT_V2_PROJECT_ID,
logger,
})
const web3wallet = await Web3Wallet.init({
core,
metadata: SAFE_WALLET_METADATA,
})
setWeb3wallet(web3wallet)
}
try {
initializeWalletConnectV2Client()
} catch (error) {
console.log('Error on walletconnect version 2 initialization: ', error)
setIsWallectConnectInitialized(true)
}
}, [])
// session_request needs to be a separate Effect because a valid wcSession should be present
useEffect(() => {
if (isWallectConnectInitialized && web3wallet && wcSession) {
web3wallet.on('session_request', async event => {
const { topic, id } = event
const { request, chainId: transactionChainId } = event.params
const { method, params } = request
const isSafeChainId = transactionChainId === `${EVMBasedNamespaces}:${safe.chainId}`
// we only accept transactions from the Safe chain
if (!isSafeChainId) {
const errorMessage = `Transaction rejected: the connected Dapp is not set to the correct chain. Make sure the Dapp only uses ${chainInfo?.chainName} to interact with this Safe.`
setError(errorMessage)
await web3wallet.respondSessionRequest({
topic,
response: rejectResponse(id, UNSUPPORTED_CHAIN_ERROR_CODE, errorMessage),
})
return
}
try {
setError(undefined)
const result = await web3Provider.send(method, params)
await web3wallet.respondSessionRequest({
topic,
response: {
id,
jsonrpc: '2.0',
result,
},
})
trackEvent(
TRANSACTION_CONFIRMED_ACTION,
WALLET_CONNECT_VERSION_2,
wcSession.peer.metadata,
)
} catch (error: any) {
setError(error?.message)
const isUserRejection = error?.message?.includes?.('Transaction was rejected')
const code = isUserRejection ? USER_REJECTED_REQUEST_CODE : INVALID_METHOD_ERROR_CODE
await web3wallet.respondSessionRequest({
topic,
response: rejectResponse(id, code, error.message),
})
}
})
}
}, [
chainInfo,
wcSession,
isWallectConnectInitialized,
web3wallet,
trackEvent,
safe,
web3Provider,
])
// we set here the events & restore an active previous session
useEffect(() => {
if (!isWallectConnectInitialized && web3wallet) {
// we try to find a compatible active session
const activeSessions = web3wallet.getActiveSessions()
const compatibleSession = Object.keys(activeSessions)
.map(topic => activeSessions[topic])
.find(
session =>
session.namespaces[EVMBasedNamespaces].accounts[0] ===
`${EVMBasedNamespaces}:${safe.chainId}:${safe.safeAddress}`, // Safe Account
)
if (compatibleSession) {
setWcSession(compatibleSession)
}
// events
web3wallet.on('session_proposal', async proposal => {
const { id, params } = proposal
const { requiredNamespaces } = params
console.log('Session proposal: ', proposal)
const safeAccount = `${EVMBasedNamespaces}:${safe.chainId}:${safe.safeAddress}`
const safeChain = `${EVMBasedNamespaces}:${safe.chainId}`
const safeEvents = requiredNamespaces[EVMBasedNamespaces]?.events || [] // we accept all events like chainChanged & accountsChanged (even if they are not compatible with the Safe)
try {
const wcSession = await web3wallet.approveSession({
id,
namespaces: {
eip155: {
accounts: [safeAccount], // only the Safe account
chains: [safeChain], // only the Safe chain
methods: compatibleSafeMethods, // only the Safe methods
events: safeEvents,
},
},
})
trackEvent(NEW_SESSION_ACTION, WALLET_CONNECT_VERSION_2, wcSession.peer.metadata)
setWcSession(wcSession)
setError(undefined)
} catch (error: any) {
console.log('error: ', error)
// human readeable error
setError(errorLabel)
const errorMessage = `Connection refused: This Safe Account is in ${chainInfo?.chainName} but the Wallet Connect session proposal is not valid because it contains: 1) A required chain different than ${chainInfo?.chainName} 2) Does not include ${chainInfo?.chainName} between the optional chains 3) No EVM compatible chain is included`
console.log(errorMessage)
await web3wallet.rejectSession({
id: proposal.id,
reason: {
code: UNSUPPORTED_CHAIN_ERROR_CODE,
message: errorMessage,
},
})
}
})
web3wallet.on('session_delete', async () => {
setWcSession(undefined)
setError(undefined)
})
setIsWallectConnectInitialized(true)
}
}, [safe, web3wallet, isWallectConnectInitialized, chainInfo, trackEvent])
const wcConnect = useCallback<wcConnectType>(
async (uri: string) => {
const isValidWalletConnectUri = uri && uri.startsWith('wc')
if (isValidWalletConnectUri && web3wallet) {
await web3wallet.core.pairing.pair({ uri })
}
},
[web3wallet],
)
const wcDisconnect = useCallback<wcDisconnectType>(async () => {
if (wcSession && web3wallet) {
await web3wallet.disconnectSession({
topic: wcSession.topic,
reason: {
code: USER_DISCONNECTED_CODE,
message: 'User disconnected. Safe Wallet Session ended by the user',
},
})
setWcSession(undefined)
setError(undefined)
}
}, [web3wallet, wcSession])
const wcClientData = wcSession?.peer.metadata
return { wcConnect, wcClientData, wcDisconnect, isWallectConnectInitialized, error }
}
export default useWalletConnectV2
const rejectResponse = (id: number, code: number, message: string) => {
return {
id,
jsonrpc: '2.0',
error: {
code,
message,
},
}
}