-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
1220 lines (1140 loc) · 40.6 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
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import eth from './eth';
import { isPrivateWindow } from './web';
import * as ethers from 'ethers';
const { Wallet } = ethers;
function noop() {}
function safe_not_equal(a, b) {
return a != a ? b == b : a !== b || ((a && typeof a === 'object') || typeof a === 'function');
}
const subscriber_queue = [];
function writable(value, start) {
if (!start) { start = noop; }
let stop;
const subscribers = [];
function set(new_value) {
if (safe_not_equal(value, new_value)) {
value = new_value;
if (stop) { // store is ready
const run_queue = !subscriber_queue.length;
for (let i = 0; i < subscribers.length; i += 1) {
const s = subscribers[i];
s[1]();
subscriber_queue.push(s, value);
}
if (run_queue) {
for (let i = 0; i < subscriber_queue.length; i += 2) {
subscriber_queue[i][0](subscriber_queue[i + 1]);
}
subscriber_queue.length = 0;
}
}
}
}
function update(fn){
set(fn(value));
}
function subscribe(run, invalidate) {
if (!invalidate) { invalidate = noop; }
const subscriber = [run, invalidate];
subscribers.push(subscriber);
if (subscribers.length === 1) {
stop = start(set) || noop;
}
run(value);
return () => {
const index = subscribers.indexOf(subscriber);
if (index !== -1) {
subscribers.splice(index, 1);
}
if (subscribers.length === 0) {
stop();
stop = null;
}
};
}
return { set, update, subscribe };
}
// TODO add timeout for settinpu Wallet // getting accounts, etc...
// TODO deal with error and error recovery
// error as notification, revert to previous state
const voidLog = {
trace:() => {},
debug:() => {},
info:() => {},
warn:() => {},
error:() => {},
fatal:() => {},
silent:() => {},
};
function getWalletVendor(ethereum) {
if (!ethereum) {
return undefined;
} else if(ethereum.isMetaMask) {
return 'Metamask';
} else if(navigator.userAgent.indexOf("Opera") != -1 || navigator.userAgent.indexOf("OPR/") != -1) {
return 'Opera';
} else {
return 'unknown';
}
// TODO
}
let _fallbackProvider;
const $wallet = {
status: 'Loading',
requestingTx: false, // TODO rename waitingTxConfirmation or add steps // number of block confirmation, etc...
};
if (typeof window !== 'undefined') {
window.$wallet = $wallet;
}
export default (log) => {
if(!log) {
log = voidLog;
}
let metamaskFirstLoadIssue;
let _ethSetup;
let _fallbackUrl;
let _registerContracts;
let _fetchInitialBalance;
let _supportedChainIds;
const _registeredWalletTypes = {};
let _ethereum;
let _onlyLocal;
let _onlyBuiltin;
let _accountFetchTimeout;
function reloadPage(reason, instant) {
if (typeof window !== 'undefined') {
log.info((instant ? 'instant ' : '') + 'reloading page because ' + reason);
if (instant) {
window.location.reload();
} else {
setTimeout(() => window.location.reload(), 100);
}
} else {
// TODO ?
}
}
const { subscribe, set, update } = writable();
let contracts = {};
function _set(obj) {
for (let key of Object.keys(obj)) {
$wallet[key] = obj[key];
}
log.info('WALLET', JSON.stringify($wallet, null, ' '));
set($wallet);
}
_set($wallet);
function getEthereum() {
if (typeof window !== 'undefined') {
if (window.ethereum) {
return window.ethereum;
} else if (window.web3) {
return window.web3.currentProvider;
}
}
return null;
}
function fetchEthereum() {
// TODO test with document.readyState !== 'complete' || document.readyState === 'interactive'
return new Promise((resolve, reject) => {
if(document.readyState !== 'complete') {
document.onreadystatechange = function() {
if (document.readyState === 'complete') {
document.onreadystatechange = null;
resolve(getEthereum());
}
};
} else {
resolve(getEthereum());
}
});
}
function watch(web3Provider) {
async function checkAccounts(accounts) {
if ($wallet.status === 'Locked' || $wallet.status === 'Unlocking') { // TODO SettingUpWallet ?
return; // skip as Unlock / post-Unlocking will fetch the account
}
// log.info('checking ' + accounts);
if (accounts && accounts.length > 0) {
const account = accounts[0];
if ($wallet.address) {
if (account.toLowerCase() !== $wallet.address.toLowerCase()) {
reloadPage('accountsChanged', true);
}
} else {
// if($wallet.readOnly) { // TODO check if it can reach there ?
// _ethSetup = eth._setup(web3Provider);
// }
let initialBalance;
if(_fetchInitialBalance) {
initialBalance = await _ethSetup.provider.getBalance(account);
}
log.info('now READY');
_set({
address: account,
status: 'Ready',
readOnly: undefined,
initialBalance,
});
}
} else {
if ($wallet.address) {
// if($wallet.readOnly) { // TODO check if it can reach there ?
// _ethSetup = eth._setup(web3Provider);
// }
_set({
address: undefined,
status: 'Locked',
readOnly: undefined,
});
}
}
}
function checkChain(newChainId) {
// log.info('checking new chain ' + newChainId);
if ($wallet.chainId && newChainId != $wallet.chainId) {
log.info('from ' + $wallet.chainId + ' to ' + newChainId);
reloadPage('networkChanged');
}
}
async function watchAccounts() {
if ($wallet.status === 'WalletToChoose' || $wallet.status === 'Locked' || $wallet.status === 'Unlocking') {
return; // skip as Unlock / post-Unlocking will fetch the account
}
let accounts;
try {
// log.trace('watching accounts...');
accounts = await eth.fetchAccounts();
// log.trace(`accounts : ${accounts}`);
} catch (e) {
log.error('watch account error', e);
}
await checkAccounts(accounts);
}
async function watchChain() {
let newChainId;
try {
// log.trace('watching chainId...');
newChainId = await eth.fetchBuiltinChainId();
// log.trace(`newChainId : ${newChainId}`);
} catch (e) {
log.error('watch account error', e);
}
checkChain(newChainId);
}
if (web3Provider) { // TODO only if builtin is chosen // can use onNetworkChanged / onChainChanged / onAccountChanged events for specific web3 provuder setup
try {
web3Provider.once('accountsChanged', checkAccounts);
web3Provider.once('networkChanged', checkChain);
web3Provider.once('chainChanged', checkChain);
} catch (e) {
log.info('no web3Provider.once');
}
}
// TODO move that into the catch block except for Metamask
// still need to watch as even metamask do not emit the "accountsChanged" event all the time: TODO report bug
setInterval(watchAccounts, 1000);
// still need to watch chain for old wallets
setInterval(watchChain, 2000);
}
async function retry() {
if (_retry) {
if(metamaskFirstLoadIssue) {
reloadPage('metamask issue', true);
} else {
return _retry(true);
}
} else {
throw new Error('cannot retry');
}
}
function withTimeout(ms, promise) {
let timeoutPromise = new Promise((resolve, reject) => {
let id = setTimeout(() => {
clearTimeout(id);
reject({message: 'Timed out in '+ ms + 'ms.', type: 'timeout'})
}, ms)
});
return Promise.race([
promise,
timeoutPromise
])
}
function fetchChainIdWithTimeout(eth, ms = 10000) {
let timeout = new Promise((resolve, reject) => { // TODO use `withTimeout(...)`
let id = setTimeout(() => {
clearTimeout(id);
reject('Timed out in '+ ms + 'ms.')
}, ms)
});
return Promise.race([
eth.fetchChainId(),
timeout
])
}
function _recordUse(walletTypeId) {
_set({
walletChosen: walletTypeId,
});
try {
localStorage.setItem('__last_wallet_used', walletTypeId);
} catch(e){}
}
async function _useBuiltinWallet(ethereum, unlock, isRetry) {
if (!ethereum) {
throw new Error('no ethereum provided');
}
_recordUse('builtin');
let opera_enabled_before = false;
const isOperaWallet = $wallet.builtinWalletPresent === 'Opera';
if (isOperaWallet) {
opera_enabled_before = localStorage.getItem('opera_wallet_enabled');
if (!opera_enabled_before && !isRetry) {
_set({
status: 'Opera_Locked', // TODO use Locked but mention it is not readable ?
});
return $wallet;
}
}
_ethSetup = eth._setup(ethereum);
// log.info('web3 is there...');
// log.info('checking chainId...');
let chainId;
try {
log.trace('fetching chainId...');
chainId = await fetchChainIdWithTimeout(eth);
log.trace(`chainId : ${chainId}`);
} catch (e) {
if(typeof e === 'string' && e.startsWith('Timed out')) {
metamaskFirstLoadIssue = true;
}
log.error('builtin wallet : error fetching chainId', e);
if(_fallbackUrl) {
_ethSetup = eth._setup(_fallbackUrl, ethereum);
}
if (isOperaWallet) {
log.info('Opera web3 quircks');
// if (isRetry) {
// _set({
// status: 'Error',
// error: {
// code: 5031,
// message: "Opera web3 implementation is non-standard, did you block our application or forgot to set up yoru wallet?",
// },
// readOnly: true
// });
// } else {
_set({
status: 'Opera_FailedChainId', // TODO use Locked but mention it is not readable ?
readOnly: _fallbackUrl ? true : undefined
});
// }
} else {
_set({
status: 'Error',
error: {
code: 5030,
message: "could not detect current chain",
},
readOnly: _fallbackUrl ? true : undefined
});
}
log.info('failed to get chain Id');
return $wallet;
}
if (isOperaWallet && !opera_enabled_before) {
localStorage.setItem('opera_wallet_enabled', true);
log.info('opera enabled saved');
}
_set({ chainId });
if (_supportedChainIds && _supportedChainIds.indexOf(chainId) == -1) {
let readOnly
if(_fallbackUrl) {
_ethSetup = eth._setup(_fallbackUrl, ethereum);
const fallbackChainId = await eth.fetchChainId();
if (_registerContracts) {
try {
const contractsInfo = await _registerContracts($wallet, fallbackChainId);
contracts = eth.setupContracts(contractsInfo);
} catch (e) {
log.error(`failed to setup contracts for chain ${fallbackChainId} using ${_fallbackUrl}`, e);
_set({
status: 'Error',
error: {
code: 5030,
message: `no contract deployed on chain ${fallbackChainId}`, // could try again
},
readOnly: true,
});
return;
}
}
readOnly = true;
}
_set({
chainNotSupported: true,
requireManualChainReload: isOperaWallet,
readOnly
})
} else {
if (_ethSetup && _registerContracts) {
const contractsInfo = await _registerContracts($wallet);
contracts = eth.setupContracts(contractsInfo);
}
}
await _fetchAccountAndWatch(ethereum, unlock);
return $wallet;
}
async function _fetchAccountAndWatch(provider, autoUnlock) {
let accounts;
let timeoutNotification;
try {
log.trace('getting accounts..');
timeoutNotification = setTimeout(() => {
_set({
walletTakingTimeToReply: true,
});
}, _accountFetchTimeout ? _accountFetchTimeout * 500 : 5000);
if (_accountFetchTimeout) {
accounts = await withTimeout(_accountFetchTimeout * 1000, eth.fetchAccounts());
} else {
accounts = await eth.fetchAccounts();
}
clearTimeout(timeoutNotification);
_set({
walletTakingTimeToReply: false,
});
log.trace(`accounts : ${accounts}`);
} catch (e) {
if (timeoutNotification) {
clearTimeout(timeoutNotification);
_set({
walletTakingTimeToReply: false,
});
}
console.error('ERROR', e);
// TODO timeout error
if(e.type == 'timeout') {
throw e;
}
log.error('accounts', e);
accounts = undefined;
}
if (accounts && accounts.length > 0) {
let initialBalance;
if(_fetchInitialBalance) {
initialBalance = await _ethSetup.provider.getBalance(accounts[0]);
}
log.info('already READY');
_set({
address: accounts[0],
status: 'Ready',
initialBalance,
});
} else {
if(autoUnlock) {
await unlock();
} else {
_set({ status: 'Locked' });
}
}
if (provider) {
watch(provider);
}
}
async function _useOrCreateLocalWallet(localKey) {
if(_fallbackUrl) {
_recordUse('local');
let ethersWallet;
if (localKey) {
log.trace('using localkey', localKey);
if(typeof localKey === 'string') {
ethersWallet = new Wallet(localKey); // do not save it on local Storage
await setupLocalWallet(ethersWallet);
} else { // assume it to be a boolean and create a wallet if not there
let privateKey
try {
privateKey = localStorage.getItem('__wallet_priv');
} catch(e) {}
if(privateKey && privateKey !== '') {
const ethersWallet = new Wallet(privateKey);
await setupLocalWallet(ethersWallet);
} else {
await createLocalWallet();
}
}
} else {
// log.trace('ckecking localStorage key', localKey);
let privateKey
try {
privateKey = localStorage.getItem('__wallet_priv');
} catch(e) {}
let ethersWallet;
if(privateKey && privateKey !== '') {
// log.trace('found key');
ethersWallet = new Wallet(privateKey);
}
await setupLocalWallet(ethersWallet, {createNew: false});
}
} else {
throw new Error('need a fallbackUrl for local wallet'); // TODO pass it in local config ? or reuse ?
}
return $wallet;
}
async function logout() {
if ($wallet.walletChosen == 'builtin') {
if ($wallet.walletChoice.length == 1 || _onlyBuiltin) {
_set({
status: 'Locked',
address: undefined,
});
} else {
try{
localStorage.removeItem('__last_wallet_used');
}catch(e){}
_set({
status: 'WalletToChoose',
address: undefined,
walletChosen: undefined,
isLocal: false
});
}
} else if($wallet.walletChosen == 'local') {
try{
localStorage.removeItem('__last_wallet_used');
}catch(e){}
if ($wallet.walletChoice.length > 1 && !_onlyLocal) {
_set({
status: 'WalletToChoose',
address: undefined,
walletChosen: undefined,
isLocal: undefined
});
}
} else {
try{
localStorage.removeItem('__last_wallet_used');
}catch(e){}
const walletModule = _registeredWalletTypes[$wallet.walletChosen];
if (walletModule && walletModule.logout) {
await walletModule.logout();
}
_set({
status: 'WalletToChoose',
address: undefined,
walletChosen: undefined,
isLocal: undefined
});
}
}
async function useFirstChoice() {
return use($wallet.walletChoice[0]);
}
async function use(walletTypeId, loadingTime) {
if(!loadingTime) {
_set({status: 'SettingUpWallet'});
}
log.trace('using walletType', walletTypeId);
const walletType = _registeredWalletTypes[walletTypeId];
if (!walletType) {
throw new Error('wallet type ' + walletType + ' not registered for use');
}
if(walletTypeId == 'builtin') {
return _useBuiltinWallet(_ethereum, true); // TODO ethereum;
} else if (walletTypeId == 'local') {
return _useOrCreateLocalWallet(true); // TODO
}
_recordUse(walletTypeId);
let chainId;
if(_fallbackUrl) {
_ethSetup = eth._setup(_fallbackUrl);
chainId = await eth.fetchChainId();
}
if (!chainId) {
chainId = _supportedChainIds[0]; // TODO explicit chainId to use as defaukt ?
}
log.trace('setting up wallet module on chain ' + chainId);
const result = await walletType.setup({chainId, fallbackUrl: _fallbackUrl});
const {web3Provider, accounts} = result;
_set({ chainId });
log.trace('setting up web3 provider');
// TODO record chainId //assume module us behaving correctly
_ethSetup = eth._setup(web3Provider); // TODO check if eth._setup assume builtin behaviour ?
log.trace('fetching accounts');
if (!accounts) {
// TODO
}
if (_ethSetup && _registerContracts) {
const contractsInfo = await _registerContracts($wallet);
contracts = eth.setupContracts(contractsInfo);
}
try {
await _fetchAccountAndWatch(web3Provider);
} catch(e) {
_set({
status: 'WalletToChoose',
error: {type: 'timeout', message: 'cannot fetch account'}
});
}
}
async function _load({
autoConnectWhenOnlyOneChoice,
accountFetchTimeout,
fallbackUrl,
autoLocalIfBuiltinNotAvailable,
autoBuiltinIfOnlyLocal,
removeBuiltinFromChoiceIfNotPresent,
reuseLastWallet,
supportedChainIds,
registerContracts,
walletTypes,
fetchInitialBalance
}, isRetry) {
if (typeof autoConnectWhenOnlyOneChoice== 'undefined') {
autoConnectWhenOnlyOneChoice = true;
}
_accountFetchTimeout = accountFetchTimeout;
_fallbackUrl = fallbackUrl;
if (fallbackUrl) {
_fallbackProvider = new ethers.providers.JsonRpcProvider(fallbackUrl);
}
_registerContracts = registerContracts;
_fetchInitialBalance = fetchInitialBalance;
_supportedChainIds = [];
const supportedChains = [];
function getChainName(chainId) {
if (chainId == '4') {
return 'Rinkeby';
} else if (chainId == '1') {
return 'Ethereum Mainnet';
} else if (chainId == '42') {
return 'Kovan';
} else if (chainId == '5') {
return 'Görli';
} else {
return 'chain with id \'' + chainId + '\'';
}
}
for (let supportedChainId of supportedChainIds) {
_supportedChainIds.push(supportedChainId);
supportedChains.push({
id: supportedChainId,
name: getChainName(supportedChainId),
url: undefined // TODO setting to pass (not hardcoded in svelte-wallet)
})
}
_set({ status: 'Loading', supportedChains });
if (isRetry) { // this only concern builtin wallets // TODO rename ? or use `use('builtin')` instead of retry flow ?
walletTypes = ['builtin'];
}
if(!walletTypes) {
walletTypes = ['builtin'];
} else if (typeof walletTypes == 'string') {
walletTypes = [walletTypes];
}
try {
_ethereum = await fetchEthereum();
} catch(e) {
log.error('error getting access to window.ethereum' , e);
// TODO error or not ? // TODO potentialError vs criticalError
}
const vendor = getWalletVendor(_ethereum);
const builtinWalletPresent = vendor ? vendor : false;
const allWalletTypes = [];
for (const walletType of walletTypes) {
let walletTypeId;
if(typeof walletType == 'string') {
walletTypeId = walletType;
} else {
walletTypeId = walletType.id;
}
if (!(removeBuiltinFromChoiceIfNotPresent && walletTypeId == 'builtin' && !builtinWalletPresent)) {
_registeredWalletTypes[walletTypeId] = walletType;
allWalletTypes.push(walletType);
}
}
let lastWalletUsed;
if (reuseLastWallet) {
try{
lastWalletUsed = localStorage.getItem('__last_wallet_used');
} catch(e){}
}
if (lastWalletUsed && !_registeredWalletTypes[lastWalletUsed]) { // allow recover even if configuration change
if(lastWalletUsed == 'builtin' || lastWalletUsed == 'local') {
allWalletTypes.push(lastWalletUsed);
_registeredWalletTypes[lastWalletUsed] = lastWalletUsed;
} else {
console.error('cannot reuse wallet type', lastWalletUsed);
// TODO error
}
}
if (!_registeredWalletTypes['local']) {
let privateKey
try {
privateKey = localStorage.getItem('__wallet_priv');
} catch(e) {}
if (privateKey) {
const walletType = {id: 'local', privateKey};
_registeredWalletTypes['local'] = walletType;
allWalletTypes.push(walletType);
}
}
const walletChoice = [];
let onlyBuiltInAndLocal = true;
let builtInInThere = false;
let localInThere = false;
for (const walletType of allWalletTypes) {
let walletTypeId;
if(typeof walletType == 'string') {
walletTypeId = walletType;
} else {
walletTypeId = walletType.id;
}
if (walletTypeId == 'local') {
localInThere = true;
} else if (walletTypeId == 'builtin') {
builtInInThere = true;
} else {
onlyBuiltInAndLocal = false;
}
walletChoice.push(walletTypeId);
}
onlyBuiltInAndLocal = onlyBuiltInAndLocal && builtInInThere && localInThere;
_onlyLocal = autoLocalIfBuiltinNotAvailable && onlyBuiltInAndLocal && !builtinWalletPresent;
_onlyBuiltin = autoBuiltinIfOnlyLocal && onlyBuiltInAndLocal && builtinWalletPresent;
_set({
builtinWalletPresent,
walletChoice
});
let walletTypeToUse;
if(lastWalletUsed) {
walletTypeToUse = lastWalletUsed;
if(lastWalletUsed == 'builtin') {
if(!builtinWalletPresent) {
console.error('no builtin wallet present anymore');
walletTypeToUse = undefined; // TODO error
}
}
}
if (!walletTypeToUse) {
if (allWalletTypes.length == 1 && autoConnectWhenOnlyOneChoice) {
walletTypeToUse = allWalletTypes[0].id || allWalletTypes[0];
} else if (_onlyLocal) {
walletTypeToUse = 'local';
} else if (_onlyBuiltin) {
walletTypeToUse = 'builtin';
}
}
if (walletTypeToUse) {
if(walletTypeToUse == 'builtin') {
if(builtinWalletPresent) {
return _useBuiltinWallet(_ethereum, false, isRetry);
} else {
if(_fallbackUrl) {
await setupLocalWallet(undefined, {createNew: false}); // TODO rename
} else {
_set({
status: 'NoWallet',
});
}
}
} else if (walletTypeToUse == 'local') {
return _useOrCreateLocalWallet(_registeredWalletTypes['local'].localKey || true);
} else {
use(walletTypeToUse, true);
}
} else {
if (_onlyBuiltin && !builtinWalletPresent) {
_set({
status: 'NoWallet',
});
} else if (allWalletTypes.length > 0) {
_set({
status: 'WalletToChoose',
});
} else {
_set({
status: 'NoWallet',
});
}
}
return $wallet;
}
let promise;
let _retry;
async function load(config) {
if (!process.browser) {
_set({ status: 'Loading' });
return $wallet;
}
if (promise) {
return promise;
}
if(!config) {
config = {};
}
_retry = (isRetry) => _load(config, isRetry);
promise = _retry(false);
return promise;
}
function call(options, contract, methodName, ...args) {
// cal with from ?
// const w = await ensureEnabled();
// if (!w || !w.address) {
// throw new Error('Can\'t perform tx');
// }
if (typeof options === 'string') {
if(typeof methodName !== 'undefined') {
args.unshift(methodName);
}
methodName = contract;
contract = options;
options = undefined;
}
if (typeof args === 'undefined') {
args = [];
}
if (contract) {
const ethersContract = contracts[contract];
const method = ethersContract.callStatic[methodName].bind(ethersContract);
if(args.length > 0) {
return method(...args, options || {}); // || defaultOptions);
} else {
return method(options || {}); // || defaultOptions);
}
} else {
log.error('TODO send raw call');
}
}
async function unlock() {
log.info('Requesting unlock');
_set({
status: 'Unlocking'
});
let accounts;
// try {
// accounts = await eth.fetchAccounts();
// } catch (e) {
// log.info('cannot get accounts', e);
// accounts = [];
// }
// if (!accounts || accounts.length == 0) {
// log.info('no accounts');
try {
log.trace('ethereum.enable...');
accounts = await _ethSetup.web3Provider.enable();
log.trace(`accounts : ${accounts}`);
} catch (e) {
log.info('refused to get accounts', e);
// try {
// log.info('trying accounts...', e);
// accounts = await window.web3.eth.getAccounts();
// } catch(e) {
// log.info('no accounts', e);
accounts = [];
// }
}
// }
if (accounts.length > 0) {
let initialBalance;
if(_fetchInitialBalance) {
initialBalance = await _ethSetup.provider.getBalance(accounts[0]);
}
log.info('unlocked READY');
_set({
address: accounts[0],
status: 'Ready',
initialBalance,
});
} else {
_set({
status: 'Locked'
});
return false;
}
return true;
}
async function ensureEnabled() {
if ($wallet.status === 'Opera_Locked') {
await wallet.retry();
}
if ($wallet.status === 'Locked') { // TODO check race condition 'Unlocking' // queue tx requests ?
await unlock();
}
return $wallet;
}
async function setupLocalWallet(ethersWallet, resetZeroWallet) {
log.trace('setting up local wallet...', ethersWallet);
_ethSetup = eth._setup(_fallbackUrl, null, ethersWallet ? ethersWallet.privateKey : undefined);
// if(ethersWallet && resetZeroWallet) { // TODO if dev
// const balance = await _ethSetup.provider.getBalance(ethersWallet.address);
// const nonce = await _ethSetup.provider.getTransactionCount(ethersWallet.address);
// if(balance.eq(0) && nonce === 0) {
// localStorage.removeItem('__wallet_priv');
// log.trace('zero wallet detected, reseting...');
// if(resetZeroWallet.createNew) {
// log.trace('creating a new wallet');
// await createLocalWallet()
// return;
// } else {
// log.trace('deleting wallet');
// ethersWallet = undefined;
// }
// }
// }
let chainId;
try {
log.trace('fetching chainId from fallback...');
chainId = await eth.fetchChainId();
log.trace(`chainId : ${chainId}`);
} catch (e) {
log.error('fallback : error fetching chainId', e);
}
if (chainId) {
_set({chainId});
if (_registerContracts) {
try {
const contractsInfo = await _registerContracts($wallet);
contracts = eth.setupContracts(contractsInfo);
} catch (e) {
log.error(`failed to setup contracts for chain ${chainId} using ${_fallbackUrl}`, e);
_set({
status: 'Error',
error: {
code: 5030,
message: `no contract deployed on chain ${chainId}`, // could try again
},
readOnly: true,
});
return;
}
}
if (ethersWallet) {
const hasPrivateModeRisk = await isPrivateWindow();
let initialBalance;
if(_fetchInitialBalance) {
initialBalance = await _ethSetup.provider.getBalance(ethersWallet.address);
}
_set({
address: ethersWallet.address,
status: 'Ready',
isLocal: true,
hasPrivateModeRisk: hasPrivateModeRisk ? true : undefined,
initialBalance,
});
} else {
_set({
status: 'NoWallet',
readOnly: true
});
}
} else {
_set({
status: 'Error',
error: {
code: 5030,
message: "could not detect current chain", // could try again
},
readOnly: ethersWallet ? undefined : true,