-
Notifications
You must be signed in to change notification settings - Fork 106
Expand file tree
/
Copy pathwallet_info.dart
More file actions
586 lines (513 loc) · 18.1 KB
/
wallet_info.dart
File metadata and controls
586 lines (513 loc) · 18.1 KB
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
import 'dart:convert';
import 'package:isar_community/isar.dart';
import 'package:uuid/uuid.dart';
import '../../../app_config.dart';
import '../../../models/balance.dart';
import '../../../models/isar/models/blockchain_data/address.dart';
import '../../../models/keys/view_only_wallet_data.dart';
import '../../crypto_currency/crypto_currency.dart';
import '../isar_id_interface.dart';
import 'wallet_info_meta.dart';
part 'wallet_info.g.dart';
@Collection(accessor: "walletInfo", inheritance: false)
class WalletInfo implements IsarId {
@override
Id id = Isar.autoIncrement;
@Index(unique: true, replace: false)
final String walletId;
final String name;
@enumerated
final AddressType mainAddressType;
/// The highest index [mainAddressType] receiving address of the wallet
final String cachedReceivingAddress;
/// Only exposed for Isar. Use the [cachedBalance] getter.
// Only exposed for isar as Amount cannot be stored in isar easily
final String? cachedBalanceString;
/// Only exposed for Isar. Use the [cachedBalanceSecondary] getter.
// Only exposed for isar as Amount cannot be stored in isar easily
final String? cachedBalanceSecondaryString;
/// Only exposed for Isar. Use the [cachedBalanceTertiary] getter.
// Only exposed for isar as Amount cannot be stored in isar easily
final String? cachedBalanceTertiaryString;
/// Only exposed for Isar. Use the [coin] getter.
// Only exposed for isar to avoid dealing with storing enums as Coin can change
final String coinName;
/// User set favourites ordering. No restrictions are placed on uniqueness.
/// Reordering logic in the ui code should ensure this is unique.
///
/// Also represents if the wallet is a favourite. Any number greater then -1
/// denotes a favourite. Any number less than 0 means it is not a favourite.
final int favouriteOrderIndex;
/// The highest block height the wallet has scanned.
final int cachedChainHeight;
/// The block at which this wallet was or should be restored from
final int restoreHeight;
final String? otherDataJsonString;
//============================================================================
//=============== Getters ====================================================
bool get isFavourite => favouriteOrderIndex > -1;
List<String> get tokenContractAddresses {
if (otherData[WalletInfoKeys.tokenContractAddresses] is List) {
return List<String>.from(
otherData[WalletInfoKeys.tokenContractAddresses] as List,
);
} else {
return [];
}
}
@ignore
List<String> get solanaTokenMintAddresses {
if (otherData[WalletInfoKeys.solanaTokenMintAddresses] is List) {
return List<String>.from(
otherData[WalletInfoKeys.solanaTokenMintAddresses] as List,
);
} else {
return [];
}
}
@ignore
List<String> get solanaCustomTokenMintAddresses {
if (otherData[WalletInfoKeys.solanaCustomTokenMintAddresses] is List) {
return List<String>.from(
otherData[WalletInfoKeys.solanaCustomTokenMintAddresses] as List,
);
} else {
return [];
}
}
/// Special case for coins such as firo lelantus
@ignore
Balance get cachedBalanceSecondary {
if (cachedBalanceSecondaryString == null) {
return Balance.zeroFor(currency: coin);
} else {
return Balance.fromJson(
cachedBalanceSecondaryString!,
coin.fractionDigits,
);
}
}
/// Special case for coins such as firo spark
@ignore
Balance get cachedBalanceTertiary {
if (cachedBalanceTertiaryString == null) {
return Balance.zeroFor(currency: coin);
} else {
return Balance.fromJson(
cachedBalanceTertiaryString!,
coin.fractionDigits,
);
}
}
@ignore
CryptoCurrency get coin => AppConfig.getCryptoCurrencyFor(coinName)!;
@ignore
Balance get cachedBalance {
if (cachedBalanceString == null) {
return Balance.zeroFor(currency: coin);
} else {
return Balance.fromJson(cachedBalanceString!, coin.fractionDigits);
}
}
@ignore
Map<String, dynamic> get otherData => otherDataJsonString == null
? {}
: Map<String, dynamic>.from(jsonDecode(otherDataJsonString!) as Map);
@ignore
bool get isViewOnly =>
otherData[WalletInfoKeys.isViewOnlyKey] as bool? ?? false;
@ignore
ViewOnlyWalletType? get viewOnlyWalletType {
final index = otherData[WalletInfoKeys.viewOnlyTypeIndexKey] as int?;
if (index == null) return null;
return ViewOnlyWalletType.values[index];
}
Future<bool> isMnemonicVerified(Isar isar) async =>
(await isar.walletInfoMeta.where().walletIdEqualTo(walletId).findFirst())
?.isMnemonicVerified ==
true;
@ignore
bool get isDuressVisible =>
otherData[WalletInfoKeys.duressMarkedVisibleWalletKey] as bool? ?? false;
@ignore
bool get isMwebEnabled =>
otherData[WalletInfoKeys.mwebEnabled] as bool? ?? false;
@ignore
bool get isLegacyAddressesEnabled =>
otherData[WalletInfoKeys.enableLegacyAddresses] as bool? ?? false;
//============================================================================
//============= Updaters ================================================
Future<void> updateDuressVisibilityStatus({
required bool isDuressVisible,
required Isar isar,
}) async {
await updateOtherData(
newEntries: {
WalletInfoKeys.duressMarkedVisibleWalletKey: isDuressVisible,
},
isar: isar,
);
}
Future<void> updateBalance({
required Balance newBalance,
required Isar isar,
}) async {
// try to get latest instance of this from db
final thisInfo = await isar.walletInfo.get(id) ?? this;
final newEncoded = newBalance.toJsonIgnoreCoin();
// only update if there were changes to the balance
if (thisInfo.cachedBalanceString != newEncoded) {
await isar.writeTxn(() async {
await isar.walletInfo.delete(thisInfo.id);
await isar.walletInfo.put(
thisInfo.copyWith(cachedBalanceString: newEncoded),
);
});
}
}
Future<void> updateBalanceSecondary({
required Balance newBalance,
required Isar isar,
}) async {
// try to get latest instance of this from db
final thisInfo = await isar.walletInfo.get(id) ?? this;
final newEncoded = newBalance.toJsonIgnoreCoin();
// only update if there were changes to the balance
if (thisInfo.cachedBalanceSecondaryString != newEncoded) {
await isar.writeTxn(() async {
await isar.walletInfo.delete(thisInfo.id);
await isar.walletInfo.put(
thisInfo.copyWith(cachedBalanceSecondaryString: newEncoded),
);
});
}
}
Future<void> updateBalanceTertiary({
required Balance newBalance,
required Isar isar,
}) async {
// try to get latest instance of this from db
final thisInfo = await isar.walletInfo.get(id) ?? this;
final newEncoded = newBalance.toJsonIgnoreCoin();
// only update if there were changes to the balance
if (thisInfo.cachedBalanceTertiaryString != newEncoded) {
await isar.writeTxn(() async {
await isar.walletInfo.delete(thisInfo.id);
await isar.walletInfo.put(
thisInfo.copyWith(cachedBalanceTertiaryString: newEncoded),
);
});
}
}
/// copies this with a new chain height and updates the db
Future<void> updateCachedChainHeight({
required int newHeight,
required Isar isar,
}) async {
// try to get latest instance of this from db
final thisInfo = await isar.walletInfo.get(id) ?? this;
// only update if there were changes to the height
if (thisInfo.cachedChainHeight != newHeight) {
await isar.writeTxn(() async {
await isar.walletInfo.delete(thisInfo.id);
await isar.walletInfo.put(
thisInfo.copyWith(cachedChainHeight: newHeight),
);
});
}
}
/// update favourite wallet and its index it the ui list.
/// When [customIndexOverride] is not null the [flag] will be ignored.
Future<void> updateIsFavourite(
bool flag, {
required Isar isar,
int? customIndexOverride,
}) async {
final int index;
if (customIndexOverride != null) {
index = customIndexOverride;
} else if (flag) {
final highest = await isar.walletInfo
.where()
.sortByFavouriteOrderIndexDesc()
.favouriteOrderIndexProperty()
.findFirst();
index = (highest ?? 0) + 1;
} else {
index = -1;
}
// try to get latest instance of this from db
final thisInfo = await isar.walletInfo.get(id) ?? this;
// only update if there were changes to the height
if (thisInfo.favouriteOrderIndex != index) {
await isar.writeTxn(() async {
await isar.walletInfo.delete(thisInfo.id);
await isar.walletInfo.put(
thisInfo.copyWith(favouriteOrderIndex: index),
);
});
}
}
/// copies this with a new name and updates the db
Future<void> updateName({required String newName, required Isar isar}) async {
// don't allow empty names
if (newName.isEmpty) {
throw Exception("Empty wallet name not allowed!");
}
// try to get latest instance of this from db
final thisInfo = await isar.walletInfo.get(id) ?? this;
// only update if there were changes to the name
if (thisInfo.name != newName) {
await isar.writeTxn(() async {
await isar.walletInfo.delete(thisInfo.id);
await isar.walletInfo.put(thisInfo.copyWith(name: newName));
});
}
}
/// copies this with a new name and updates the db
Future<void> updateReceivingAddress({
required String newAddress,
required Isar isar,
}) async {
// try to get latest instance of this from db
final thisInfo = await isar.walletInfo.get(id) ?? this;
// only update if there were changes to the name
if (thisInfo.cachedReceivingAddress != newAddress) {
await isar.writeTxn(() async {
await isar.walletInfo.delete(thisInfo.id);
await isar.walletInfo.put(
thisInfo.copyWith(cachedReceivingAddress: newAddress),
);
});
}
}
/// update [otherData] with the map entries in [newEntries]
Future<void> updateOtherData({
required Map<String, dynamic> newEntries,
required Isar isar,
}) async {
// try to get latest instance of this from db
final thisInfo = await isar.walletInfo.get(id) ?? this;
final Map<String, dynamic> newMap = {};
newMap.addAll(thisInfo.otherData);
newMap.addAll(newEntries);
final encodedNew = jsonEncode(newMap);
// only update if there were changes
if (thisInfo.otherDataJsonString != encodedNew) {
await isar.writeTxn(() async {
await isar.walletInfo.delete(thisInfo.id);
await isar.walletInfo.put(
thisInfo.copyWith(otherDataJsonString: encodedNew),
);
});
}
}
/// Can be dangerous. Don't use unless you know the consequences
Future<void> setMnemonicVerified({required Isar isar}) async {
final meta = await isar.walletInfoMeta
.where()
.walletIdEqualTo(walletId)
.findFirst();
if (meta == null) {
await isar.writeTxn(() async {
await isar.walletInfoMeta.put(
WalletInfoMeta(walletId: walletId, isMnemonicVerified: true),
);
});
} else if (meta.isMnemonicVerified == false) {
await isar.writeTxn(() async {
await isar.walletInfoMeta.deleteByWalletId(walletId);
await isar.walletInfoMeta.put(
WalletInfoMeta(walletId: walletId, isMnemonicVerified: true),
);
});
} else {
throw Exception(
"setMnemonicVerified() called on already"
" verified wallet: $name, $walletId",
);
}
}
/// copies this with a new name and updates the db
Future<void> updateRestoreHeight({
required int newRestoreHeight,
required Isar isar,
}) async {
// don't allow empty names
if (newRestoreHeight < 0) {
throw Exception("Negative restore height not allowed!");
}
// try to get latest instance of this from db
final thisInfo = await isar.walletInfo.get(id) ?? this;
// only update if there were changes to the name
if (thisInfo.restoreHeight != newRestoreHeight) {
await isar.writeTxn(() async {
await isar.walletInfo.delete(thisInfo.id);
await isar.walletInfo.put(
thisInfo.copyWith(restoreHeight: newRestoreHeight),
);
});
}
}
/// copies this with a new name and updates the db
Future<void> updateContractAddresses({
required Set<String> newContractAddresses,
required Isar isar,
}) async {
await updateOtherData(
newEntries: {
WalletInfoKeys.tokenContractAddresses: newContractAddresses.toList(),
},
isar: isar,
);
}
/// Update Solana token mint addresses and update the db.
Future<void> updateSolanaTokenMintAddresses({
required Set<String> newMintAddresses,
required Isar isar,
}) async {
await updateOtherData(
newEntries: {
WalletInfoKeys.solanaTokenMintAddresses: newMintAddresses.toList(),
},
isar: isar,
);
}
/// Update custom Solana token mint addresses and update the db.
Future<void> updateSolanaCustomTokenMintAddresses({
required List<String> newMintAddresses,
required Isar isar,
}) async {
await updateOtherData(
newEntries: {
WalletInfoKeys.solanaCustomTokenMintAddresses: newMintAddresses
.toList(),
},
isar: isar,
);
}
Future<void> setMwebEnabled({
required bool newValue,
required Isar isar,
}) async {
await updateOtherData(
newEntries: {WalletInfoKeys.mwebEnabled: newValue},
isar: isar,
);
}
//============================================================================
WalletInfo({
required this.walletId,
required this.name,
required this.mainAddressType,
required this.coinName,
// cachedReceivingAddress should never actually be empty in practice as
// on wallet init it will be set
this.cachedReceivingAddress = "",
this.favouriteOrderIndex = -1,
this.cachedChainHeight = 0,
this.restoreHeight = 0,
this.cachedBalanceString,
this.cachedBalanceSecondaryString,
this.cachedBalanceTertiaryString,
this.otherDataJsonString,
}) : assert(AppConfig.coins.map((e) => e.identifier).contains(coinName));
WalletInfo copyWith({
String? name,
AddressType? mainAddressType,
String? cachedReceivingAddress,
String? cachedBalanceString,
String? cachedBalanceSecondaryString,
String? cachedBalanceTertiaryString,
String? coinName,
int? favouriteOrderIndex,
int? cachedChainHeight,
int? restoreHeight,
String? otherDataJsonString,
}) {
return WalletInfo(
walletId: walletId,
name: name ?? this.name,
mainAddressType: mainAddressType ?? this.mainAddressType,
cachedReceivingAddress:
cachedReceivingAddress ?? this.cachedReceivingAddress,
cachedBalanceString: cachedBalanceString ?? this.cachedBalanceString,
cachedBalanceSecondaryString:
cachedBalanceSecondaryString ?? this.cachedBalanceSecondaryString,
cachedBalanceTertiaryString:
cachedBalanceTertiaryString ?? this.cachedBalanceTertiaryString,
coinName: coinName ?? this.coinName,
favouriteOrderIndex: favouriteOrderIndex ?? this.favouriteOrderIndex,
cachedChainHeight: cachedChainHeight ?? this.cachedChainHeight,
restoreHeight: restoreHeight ?? this.restoreHeight,
otherDataJsonString: otherDataJsonString ?? this.otherDataJsonString,
)..id = id;
}
static WalletInfo createNew({
required CryptoCurrency coin,
required String name,
int restoreHeight = 0,
String? walletIdOverride,
String? otherDataJsonString,
AddressType? overrideAddressType, // added hack for spark view only wallets
}) {
return WalletInfo(
coinName: coin.identifier,
walletId: walletIdOverride ?? const Uuid().v1(),
name: name,
mainAddressType: overrideAddressType ?? coin.defaultAddressType,
restoreHeight: restoreHeight,
otherDataJsonString: otherDataJsonString,
);
}
@Deprecated("Legacy support")
factory WalletInfo.fromJson(
Map<String, dynamic> jsonObject,
AddressType mainAddressType,
) {
final coin = AppConfig.getCryptoCurrencyFor(jsonObject["coin"] as String)!;
return WalletInfo(
coinName: coin.identifier,
walletId: jsonObject["id"] as String,
name: jsonObject["name"] as String,
mainAddressType: mainAddressType,
);
}
@Deprecated("Legacy support")
Map<String, String> toMap() {
return {"name": name, "id": walletId, "coin": coin.identifier};
}
@Deprecated("Legacy support")
String toJsonString() {
return jsonEncode(toMap());
}
@override
String toString() {
return "WalletInfo: ${toJsonString()}";
}
}
abstract class WalletInfoKeys {
static const String tokenContractAddresses = "tokenContractAddressesKey";
static const String epiccashData = "epiccashDataKey";
static const String mimblewimblecoinData = "mimblewimblecoinDataKey";
static const String bananoMonkeyImageBytes = "monkeyImageBytesKey";
static const String tezosDerivationPath = "tezosDerivationPathKey";
static const String xelisDerivationPath = "xelisDerivationPathKey";
static const String firoSparkCacheSetBlockHashCache =
"firoSparkCacheSetBlockHashCacheKey";
static const String enableOptInRbf = "enableOptInRbfKey";
static const String reuseAddress = "reuseAddressKey";
static const String isViewOnlyKey = "isViewOnlyKey";
static const String viewOnlyTypeIndexKey = "viewOnlyTypeIndexKey";
static const String duressMarkedVisibleWalletKey =
"duressMarkedVisibleWalletKey";
static const String mwebEnabled = "mwebEnabledKey";
static const String mwebScanHeight = "mwebScanHeightKey";
static const String firoSparkUsedTagsCacheResetVersion =
"firoSparkUsedTagsCacheResetVersionKey";
static const String enableLegacyAddresses = "enableLegacyAddressesKey";
static const String solanaTokenMintAddresses = "solanaTokenMintAddressesKey";
static const String solanaCustomTokenMintAddresses =
"solanaCustomTokenMintAddressesKey";
static const String isRestoredFromKeysKey = "isRestoredFromKeysKey";
}