-
-
Notifications
You must be signed in to change notification settings - Fork 8
/
index.js
444 lines (422 loc) · 13.4 KB
/
index.js
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
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
;(function () {
'use strict'
/*eslint no-unused-vars:"off"*/
const name = 'ethereum-library'
// https://github.com/ensdomains/resolvers
var EthereumLibrary = function (ipfsBundle) {
this.ipfsBundle = ipfsBundle
this.network = {
0x1: 'Ethereum Main Network: "Mainnet", chainId: "0x1"',
0x3: 'Ethereum Test Network (PoW): "Ropsten", chainId: "0x3"',
0x4: 'Ethereum Test Network (PoA): "Rinkeby", chainId: "0x4"',
0x5: 'Ethereum Test Network (PoA): "Goerli", chainId: "0x5"',
0x2a: 'Ethereum Test Network (PoA): "Kovan", chainId: "0x2a"'
}
this.etherscan = {
0x1: 'https://etherscan.io',
0x3: 'https://ropsten.etherscan.io',
0x4: 'https://rinkeby.etherscan.io',
0x5: 'https://goerli.etherscan.io',
0x2a: 'https://kovan.etherscan.io'
}
this.once = false
this.provider = null
}
EthereumLibrary.prototype.getLogger = function () {
return this.ipfsBundle.getLogger()
}
EthereumLibrary.prototype.getEthereumProvider = async function () {
if (this.provider == null) {
this.provider = await this.detectEthereumProvider()
}
return this.provider
}
/*
* https://github.com/ethereum/EIPs/blob/master/EIPS/eip-1193.md
* https://eips.ethereum.org/EIPS/eip-1193
* https://docs.metamask.io/guide/ethereum-provider.html#methods-current-api
*/
EthereumLibrary.prototype.init = async function () {
// Init once
if (this.once) {
return
}
const self = this
try {
const provider = await this.getEthereumProvider()
const chainId = await this.getChainId(provider)
this.getLogger().info(`Chain: ${this.network[chainId]}`)
// Init Ethereum listener
provider.on('accountsChanged', accounts => {
self.accounts(provider, accounts)
})
provider.on('chainChanged', chainId => {
const id = parseInt(chainId, 16)
self.getLogger().info(`Chain: ${self.network[id]}`)
})
provider.on('connect', chainId => {
const id = parseInt(chainId, 16)
self.getLogger().info(`Chain: ${self.network[id]}`)
})
provider.on('disconnect', (code, reason) => {
self.disconnectedFromAllChains(code, reason)
})
provider.on('message', message => {
self.providerMessage(message)
})
} catch (error) {
if (error.name !== 'InstallMetamask') {
this.getLogger().error(error)
$tw.utils.alert(name, error.message)
}
}
// Init once
this.once = true
}
EthereumLibrary.prototype.getChainId = async function (provider) {
if (provider === undefined || provider == null) {
provider = await this.getEthereumProvider()
}
var chainId = await provider.request({
method: 'eth_chainId'
})
chainId =
chainId === undefined || chainId == null || chainId.trim() === ''
? null
: chainId.trim()
return chainId !== null ? parseInt(chainId, 16) : null
}
EthereumLibrary.prototype.accounts = async function (provider, accounts) {
if (
accounts !== undefined &&
accounts !== null &&
Array.isArray(accounts) === true &&
accounts.length > 0
) {
try {
const chainId = await this.getChainId(provider)
this.getLogger().info(`Chain: ${this.network[chainId]}`)
this.getLogger().info(
`Ethereum account: ${this.etherscan[chainId]}/address/${accounts[0]}`
)
} catch (error) {
this.getLogger().error(error)
$tw.utils.alert(name, error.message)
}
} else {
this.getLogger().info('Unavailable Ethereum account...')
}
}
EthereumLibrary.prototype.disconnectedFromAllChains = function (
code,
reason
) {
this.getLogger().info(
`Ethereum Provider is disconnected: ${reason}. Code: ${code}`
)
}
EthereumLibrary.prototype.providerMessage = function (message) {
this.getLogger().info(`Ethereum Provider message: ${message}`)
}
EthereumLibrary.prototype.getEtherscanRegistry = function () {
return this.etherscan
}
EthereumLibrary.prototype.getNetworkRegistry = function () {
return this.network
}
EthereumLibrary.prototype.personalSign = async function (message, provider) {
message =
message === undefined || message == null || message.trim() === ''
? null
: message.trim()
if (message == null) {
throw new Error('Undefined Message....')
}
try {
if (provider === undefined || provider == null) {
provider = await this.getEthereumProvider()
}
const account = await this.getAccount(provider)
const signature = await provider.request({
method: 'personal_sign',
params: [message, account]
})
return signature
} catch (error) {
// EIP 1193 user Rejected Request
if (error.code === 4001) {
const err = new Error('Rejected User Request...')
err.name = 'RejectedUserRequest'
throw err
}
throw error
}
}
EthereumLibrary.prototype.personalRecover = async function (
message,
signature
) {
message =
message === undefined || message == null || message.trim() === ''
? null
: message.trim()
if (message == null) {
throw new Error('Undefined Message....')
}
signature =
signature === undefined || signature == null || signature.trim() === ''
? null
: signature.trim()
if (signature == null) {
throw new Error('Undefined Signature....')
}
await this.ipfsBundle.loadEthSigUtilLibrary()
const msgParams = { data: message, sig: signature }
const recovered = globalThis.sigUtil.recoverPersonalSignature(msgParams)
if (recovered === undefined || recovered == null) {
const err = new Error('Unrecoverable signature...')
err.name = 'UnrecoverableSignature'
throw err
}
return recovered
}
EthereumLibrary.prototype.decrypt = async function (text, provider) {
text =
text === undefined || text == null || text.trim() === ''
? null
: text.trim()
if (text == null) {
throw new Error('Undefined Text....')
}
try {
if (provider === undefined || provider == null) {
provider = await this.getEthereumProvider()
}
const account = await this.getAccount(provider)
var tStart = new Date()
const decryptedText = await provider.request({
method: 'eth_decrypt',
params: [text, account]
})
if (decryptedText !== undefined || decryptedText !== null) {
var tStop = new Date() - tStart
var ratio = Math.floor((decryptedText.length * 100) / text.length)
this.getLogger().info(
`Ethereum Decrypt: ${tStop}ms, In: ${text.length}, Out: ${decryptedText.length}, Ratio: ${ratio}%`
)
}
return decryptedText
} catch (error) {
// EIP 1193 user Rejected Request
if (error.code === 4001) {
const err = new Error('Rejected User Request...')
err.name = 'RejectedUserRequest'
throw err
}
throw error
}
}
EthereumLibrary.prototype.getPublicEncryptionKey = async function (
provider,
account
) {
try {
if (provider === undefined || provider == null) {
provider = await this.getEthereumProvider()
}
if (account === undefined) {
account = await this.getAccount(provider)
}
const encryptionKey = await provider.request({
method: 'eth_getEncryptionPublicKey',
params: [account]
})
return encryptionKey
} catch (error) {
// EIP 1193 user Rejected Request
if (error.code === 4001) {
const err = new Error('Rejected User Request...')
err.name = 'RejectedUserRequest'
throw err
}
throw error
}
}
/*
* https://eips.ethereum.org/EIPS/eip-1102
* https://eips.ethereum.org/EIPS/eip-1193
* https://github.com/ethereum/EIPs/blob/master/EIPS/eip-1193.md
* https://eips.ethereum.org/EIPS/eip-2255
* https://docs.metamask.io/guide/ethereum-provider.html#methods-current-api
*/
EthereumLibrary.prototype.detectEthereumProvider = async function () {
var provider = null
try {
if (typeof globalThis.detectEthereumProvider === 'function') {
provider = await globalThis.detectEthereumProvider({
mustBeMetaMask: true
})
if (provider !== undefined && provider !== null) {
provider.autoRefreshOnNetworkChange = false
}
}
} catch (error) {
this.getLogger().error(error)
}
if (provider === undefined || provider == null) {
const err = new Error('Please install ~MetaMask...')
err.name = 'InstallMetamask'
throw err
}
return provider
}
EthereumLibrary.prototype.checkAccountPermission = async function (provider) {
if (provider === undefined || provider == null) {
provider = await this.getEthereumProvider()
}
if (typeof provider.request === 'function') {
const permissions = await provider.request({
method: 'wallet_getPermissions'
})
const accountsPermission = permissions.find(
permission => permission.parentCapability === 'eth_accounts'
)
if (accountsPermission) {
return true
}
}
return false
}
EthereumLibrary.prototype.requestAccountPermission = async function (
provider
) {
if (provider === undefined || provider == null) {
provider = await this.getEthereumProvider()
}
if (typeof provider.request === 'function') {
const permissions = await provider.request({
method: 'wallet_requestPermissions',
params: [{ eth_accounts: {} }]
})
const accountsPermission = permissions.find(
permission => permission.parentCapability === 'eth_accounts'
)
if (accountsPermission) {
return true
}
}
return false
}
/*
* https://docs.metamask.io/guide/provider-migration.html#migrating-to-the-new-provider-api
*/
EthereumLibrary.prototype.getAccount = async function (provider) {
if (provider === undefined || provider == null) {
provider = await this.getEthereumProvider()
}
try {
var accounts = null
var permission = false
// Permission Attempt
try {
permission = await this.checkAccountPermission(provider)
if (permission === false) {
permission = await this.requestAccountPermission(provider)
}
} catch (error) {
if (error.code === 4001) {
throw error
}
this.getLogger().error(error)
}
// Request Accounts attempt
try {
if (
permission === false ||
(await provider._metamask.isUnlocked()) === false
) {
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-1102.md
accounts = await provider.request({ method: 'eth_requestAccounts' })
}
if (
accounts === undefined ||
accounts == null ||
Array.isArray(accounts) === false ||
accounts.length === 0
) {
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-1193.md
accounts = await provider.request({ method: 'eth_accounts' })
}
} catch (error) {
if (error.code === 4001) {
throw error
}
this.getLogger().error(error)
}
// Enable attempt
if (
accounts === undefined ||
accounts == null ||
Array.isArray(accounts) === false ||
accounts.length === 0
) {
if (typeof provider.enable === 'function') {
accounts = await provider.enable()
}
}
if (
accounts === undefined ||
accounts == null ||
Array.isArray(accounts) === false ||
accounts.length === 0
) {
throw new Error('Unable to retrieve any Ethereum accounts...')
}
await this.accounts(provider, accounts)
return accounts[0]
} catch (error) {
// EIP 1193 user Rejected Request
if (error.code === 4001) {
const err = new Error('Rejected User Request...')
err.name = 'RejectedUserRequest'
throw err
}
throw error
}
}
EthereumLibrary.prototype.getEnabledWeb3Provider = async function (provider) {
if (provider === undefined || provider == null) {
provider = await this.getEthereumProvider()
}
await this.ipfsBundle.loadEthersJsLibrary()
// Enable provider
// https://github.com/ethers-io/ethers.js/issues/433
const account = await this.getAccount(provider)
// Instantiate a Web3Provider
const web3 = new globalThis.ethers.providers.Web3Provider(provider, 'any')
// Retrieve current network
const network = await web3.getNetwork()
const chainId = parseInt(network.chainId, 16)
return {
account: account,
chainId: chainId,
web3: web3
}
}
EthereumLibrary.prototype.getWeb3Provider = async function (provider) {
if (provider === undefined || provider == null) {
provider = await this.getEthereumProvider()
}
await this.ipfsBundle.loadEthersJsLibrary()
// Instantiate an ethers Web3Provider
const web3 = new globalThis.ethers.providers.Web3Provider(provider, 'any')
// Retrieve current network
const network = await web3.getNetwork()
const chainId = parseInt(network.chainId, 16)
return {
web3: web3,
chainId: chainId
}
}
module.exports = EthereumLibrary
})()