-
Notifications
You must be signed in to change notification settings - Fork 621
/
connection.ts
241 lines (218 loc) · 6.14 KB
/
connection.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
import EventEmitter from 'events'
import { convertNumberToHex } from '@walletconnect/utils'
import WalletConnect from '@walletconnect/browser'
import WCQRCode from '@walletconnect/qrcode-modal'
import HTTPConnection from './http'
import {
ISessionParams,
IWalletConnectConnectionOptions,
IRPCMap
} from '@walletconnect/types'
// -- WalletConnectConnection --------------------------------------------- //
class WalletConnectConnection extends EventEmitter {
public bridge: string = 'https://bridge.walletconnect.org'
public qrcode: boolean = true
public infuraId: string = ''
public rpc: IRPCMap | null = null
public wc: WalletConnect | null = null
public http: HTTPConnection | null = null
public accounts: string[] = []
public chainId: number = 1
public networkId: number = 1
public rpcUrl: string = ''
public connected: boolean = false
public closed: boolean = false
constructor (opts: IWalletConnectConnectionOptions) {
super()
this.bridge = opts.bridge || 'https://bridge.walletconnect.org'
this.qrcode = typeof opts.qrcode === 'undefined' || opts.qrcode !== false
this.rpc = opts.rpc || null
if (
!this.rpc &&
(!opts.infuraId ||
typeof opts.infuraId !== 'string' ||
!opts.infuraId.trim())
) {
throw new Error('Invalid or missing Infura App ID')
}
this.infuraId = opts.infuraId || ''
this.chainId = typeof opts.chainId !== 'undefined' ? opts.chainId : 1
this.networkId = this.chainId
this.on('error', () => this.close())
}
public openQRCode () {
const uri = this.wc ? this.wc.uri : ''
if (uri) {
WCQRCode.open(uri, () => {
this.emit('error', new Error('User close WalletConnect QR Code modal'))
})
}
}
public create () {
try {
this.wc = new WalletConnect({ bridge: this.bridge })
} catch (e) {
this.emit('error', e)
return
}
if (!this.wc.connected) {
const sessionRequestOpions = this.chainId
? { chainId: this.chainId }
: undefined
// Create new session
this.wc
.createSession(sessionRequestOpions)
.then(() => {
if (this.qrcode) {
this.openQRCode()
}
})
.catch((e: Error) => this.emit('error', e))
} else {
this.connected = true
this.emit('connect')
}
this.wc.on('connect', (err: Error | null, payload: any) => {
if (err) {
this.emit('error', err)
return
}
this.connected = true
if (this.qrcode) {
WCQRCode.close() // Close QR Code Modal
}
// Handle session update
this.updateState(payload.params[0])
// Emit connect event
this.emit('connect')
})
this.wc.on('session_update', (err: Error | null, payload: any) => {
if (err) {
this.emit('error', err)
return
}
// Handle session update
this.updateState(payload.params[0])
})
this.wc.on('disconnect', (err: Error | null, payload: any) => {
if (err) {
this.emit('error', err)
return
}
this.onClose()
})
}
public onClose () {
this.wc = null
this.connected = false
this.closed = true
this.emit('close')
this.removeAllListeners()
}
public close () {
if (this.wc) {
this.wc.killSession()
}
this.onClose()
}
public error (payload: any, message: string, code = -1) {
this.emit('payload', {
id: payload.id,
jsonrpc: payload.jsonrpc,
error: { message, code }
})
}
public async send (payload: any) {
if (this.wc && this.wc.connected) {
if (payload.method.includes('chan_')) {
const response = await this.wc.unsafeSend(payload)
this.emit('payload', response)
} else {
if (this.http) {
this.http.send(payload)
} else {
this.error(payload, 'HTTP Connection not available')
}
}
} else {
this.error(payload, 'Not connected')
}
}
public async handleStateMethods (payload: any) {
let result: any = null
switch (payload.method) {
case 'eth_accounts':
result = this.accounts
break
case 'eth_chainId':
result = convertNumberToHex(this.chainId)
break
case 'net_version':
result = this.networkId
break
default:
break
}
return {
id: payload.id,
jsonrpc: payload.jsonrpc,
result
}
}
public async updateState (sessionParams: ISessionParams) {
const { accounts, chainId, networkId, rpcUrl } = sessionParams
// Check if accounts changed and trigger event
if (accounts && this.accounts !== accounts) {
this.accounts = accounts
this.emit('accountsChanged', accounts)
}
// Check if chainId changed and trigger event
if (chainId && this.chainId !== chainId) {
this.chainId = chainId
this.emit('chainChanged', chainId)
}
// Check if networkId changed and trigger event
if (networkId && this.networkId !== networkId) {
this.networkId = networkId
this.emit('networkChanged', networkId)
}
// Handle rpcUrl update
this.updateRpcUrl(this.chainId, rpcUrl || '')
}
public updateRpcUrl (chainId: number, rpcUrl: string = '') {
const infuraNetworks = {
1: 'mainnet',
3: 'ropsten',
4: 'rinkeby',
5: 'goerli',
42: 'kovan'
}
const network = infuraNetworks[chainId]
if (!rpcUrl) {
if (this.rpc && this.rpc[chainId]) {
rpcUrl = this.rpc[chainId]
} else if (network) {
rpcUrl = `https://${network}.infura.io/v3/${this.infuraId}`
}
}
if (rpcUrl) {
// Update rpcUrl
this.rpcUrl = rpcUrl
// Handle http update
this.updateHttpConnection()
} else {
this.emit(
'error',
new Error(`No RPC Url available for chainId: ${chainId}`)
)
}
}
public updateHttpConnection = () => {
if (this.rpcUrl) {
this.http = new HTTPConnection(this.rpcUrl)
this.http.on('payload', payload => this.emit('payload', payload))
this.http.on('error', (error: Error) => this.emit('error', error))
}
}
}
export default WalletConnectConnection