16
import 'package:cw_core/wallet_info.dart';
17
import 'package:cw_ethereum/erc20_balance.dart';
18
import 'package:cw_ethereum/ethereum_formatter.dart';
19
-import 'package:cw_ethereum/ethereum_transaction_model.dart';
19
import 'package:cw_ethereum/file.dart';
20
import 'package:cw_core/erc20_token.dart';
22
-import 'package:cw_polygon/default_erc20_tokens.dart';
21
+import 'package:cw_polygon/default_polygon_erc20_tokens.dart';
22
import 'package:cw_polygon/polygon_client.dart';
23
import 'package:cw_polygon/polygon_exceptions.dart';
24
import 'package:cw_polygon/polygon_formatter.dart';
41
42
class PolygonWallet = PolygonWalletBase with _$PolygonWallet;
43
45
-abstract class PolygonWalletBase extends WalletBase<ERC20Balance,
46
- PolygonTransactionHistory, PolygonTransactionInfo> with Store {
44
+abstract class PolygonWalletBase
45
+ extends WalletBase<ERC20Balance, PolygonTransactionHistory, PolygonTransactionInfo> with Store {
46
PolygonWalletBase({
47
required WalletInfo walletInfo,
48
String? mnemonic,
49
String? privateKey,
50
required String password,
51
ERC20Balance? initialBalance,
53
- }) : syncStatus = NotConnectedSyncStatus(),
52
+ }) : syncStatus = const NotConnectedSyncStatus(),
53
_password = password,
54
_mnemonic = mnemonic,
55
_hexPrivateKey = privateKey,
56
_isTransactionUpdating = false,
57
_client = PolygonClient(),
58
walletAddresses = PolygonWalletAddresses(walletInfo),
60
- balance = ObservableMap<CryptoCurrency, ERC20Balance>.of({
61
- CryptoCurrency.maticpoly: initialBalance ?? ERC20Balance(BigInt.zero)
62
- }),
59
+ balance = ObservableMap<CryptoCurrency, ERC20Balance>.of(
60
+ {CryptoCurrency.maticpoly: initialBalance ?? ERC20Balance(BigInt.zero)}),
61
super(walletInfo) {
62
this.walletInfo = walletInfo;
65
- transactionHistory =
66
- PolygonTransactionHistory(walletInfo: walletInfo, password: password);
63
+ transactionHistory = PolygonTransactionHistory(walletInfo: walletInfo, password: password);
64
65
if (!CakeHive.isAdapterRegistered(Erc20Token.typeId)) {
66
CakeHive.registerAdapter(Erc20TokenAdapter());
77
78
late final EthPrivateKey _polygonPrivateKey;
79
83
- EthPrivateKey get polygonPrivateKey => _polygonPrivateKey;
80
+ late final PolygonClient _client;
81
85
- late PolygonClient _client;
82
+ EthPrivateKey get polygonPrivateKey => _polygonPrivateKey;
83
84
int? _gasPrice;
85
int? _estimatedGas;
99
@observable
100
late ObservableMap<CryptoCurrency, ERC20Balance> balance;
101
105
- Completer<SharedPreferences> _sharedPrefs = Completer();
102
+ final Completer<SharedPreferences> _sharedPrefs = Completer();
103
104
Future<void> init() async {
108
- polygonErc20TokensBox =
109
- await CakeHive.openBox<Erc20Token>(Erc20Token.polygonBoxName);
105
+ polygonErc20TokensBox = await CakeHive.openBox<Erc20Token>(
106
+ "${walletInfo.name.replaceAll(" ", "_")}_${Erc20Token.polygonBoxName}");
107
await walletAddresses.init();
108
await transactionHistory.init();
109
_polygonPrivateKey = await getPrivateKey(
119
int calculateEstimatedFee(TransactionPriority priority, int? amount) {
120
try {
121
if (priority is PolygonTransactionPriority) {
125
- final priorityFee =
126
- EtherAmount.fromInt(EtherUnit.gwei, priority.tip).getInWei.toInt();
122
+ final priorityFee = EtherAmount.fromInt(EtherUnit.gwei, priority.tip).getInWei.toInt();
123
return (_gasPrice! + priorityFee) * (_estimatedGas ?? 0);
124
}
125
164
165
@override
166
Future<PendingTransaction> createTransaction(Object credentials) async {
171
- final _credentials = credentials as PolygonTransactionCredentials;
172
- final outputs = _credentials.outputs;
167
+ final credentials0 = credentials as PolygonTransactionCredentials;
168
+ final outputs = credentials0.outputs;
169
final hasMultiDestination = outputs.length > 1;
170
175
- final CryptoCurrency transactionCurrency = balance.keys
176
- .firstWhere((element) => element.title == _credentials.currency.title);
171
+ final CryptoCurrency transactionCurrency =
172
+ balance.keys.firstWhere((element) => element.title == credentials0.currency.title);
173
178
- final _erc20Balance = balance[transactionCurrency]!;
174
+ final erc20Balance = balance[transactionCurrency]!;
175
BigInt totalAmount = BigInt.zero;
180
- int exponent =
181
- transactionCurrency is Erc20Token ? transactionCurrency.decimal : 18;
176
+ int exponent = transactionCurrency is Erc20Token ? transactionCurrency.decimal : 18;
177
num amountToPolygonMultiplier = pow(10, exponent);
178
179
// so far this can not be made with Polygon as Polygon does not support multiple recipients
180
if (hasMultiDestination) {
186
- if (outputs.any(
187
- (item) => item.sendAll || (item.formattedCryptoAmount ?? 0) <= 0)) {
181
+ if (outputs.any((item) => item.sendAll || (item.formattedCryptoAmount ?? 0) <= 0)) {
182
throw PolygonTransactionCreationException(transactionCurrency);
183
}
184
185
final totalOriginalAmount = PolygonFormatter.parsePolygonAmountToDouble(
192
- outputs.fold(
193
- 0, (acc, value) => acc + (value.formattedCryptoAmount ?? 0)));
194
- totalAmount =
195
- BigInt.from(totalOriginalAmount * amountToPolygonMultiplier);
186
+ outputs.fold(0, (acc, value) => acc + (value.formattedCryptoAmount ?? 0)));
187
+ totalAmount = BigInt.from(totalOriginalAmount * amountToPolygonMultiplier);
188
197
- if (_erc20Balance.balance < totalAmount) {
189
+ if (erc20Balance.balance < totalAmount) {
190
throw PolygonTransactionCreationException(transactionCurrency);
191
}
192
} else {
195
// then no need to subtract the fees from the amount if send all
196
final BigInt allAmount;
197
if (transactionCurrency is Erc20Token) {
206
- allAmount = _erc20Balance.balance;
198
+ allAmount = erc20Balance.balance;
199
} else {
208
- allAmount = _erc20Balance.balance -
209
- BigInt.from(calculateEstimatedFee(_credentials.priority!, null));
200
+ allAmount =
201
+ erc20Balance.balance - BigInt.from(calculateEstimatedFee(credentials0.priority!, null));
202
}
211
- final totalOriginalAmount = EthereumFormatter.parseEthereumAmountToDouble(
212
- output.formattedCryptoAmount ?? 0);
213
- totalAmount = output.sendAll
214
- ? allAmount
215
- : BigInt.from(totalOriginalAmount * amountToPolygonMultiplier);
203
+ final totalOriginalAmount =
204
+ EthereumFormatter.parseEthereumAmountToDouble(output.formattedCryptoAmount ?? 0);
205
+ totalAmount =
206
+ output.sendAll ? allAmount : BigInt.from(totalOriginalAmount * amountToPolygonMultiplier);
207
217
- if (_erc20Balance.balance < totalAmount) {
208
+ if (erc20Balance.balance < totalAmount) {
209
throw PolygonTransactionCreationException(transactionCurrency);
210
}
211
}
212
213
final pendingPolygonTransaction = await _client.signTransaction(
214
privateKey: _polygonPrivateKey,
224
- toAddress: _credentials.outputs.first.isParsedAddress
225
- ? _credentials.outputs.first.extractedAddress!
226
- : _credentials.outputs.first.address,
215
+ toAddress: credentials0.outputs.first.isParsedAddress
216
+ ? credentials0.outputs.first.extractedAddress!
217
+ : credentials0.outputs.first.address,
218
amount: totalAmount.toString(),
219
gas: _estimatedGas!,
229
- priority: _credentials.priority!,
220
+ priority: credentials0.priority!,
221
currency: transactionCurrency,
222
exponent: exponent,
232
- contractAddress: transactionCurrency is Erc20Token
233
- ? transactionCurrency.contractAddress
234
- : null,
223
+ contractAddress:
224
+ transactionCurrency is Erc20Token ? transactionCurrency.contractAddress : null,
225
);
226
227
return pendingPolygonTransaction;
252
final address = _polygonPrivateKey.address.hex;
253
final transactions = await _client.fetchTransactions(address);
254
265
- final List<Future<List<PolygonTransactionModel>>> polygonErc20TokensTransactions =
266
- [];
255
+ final List<Future<List<PolygonTransactionModel>>> polygonErc20TokensTransactions = [];
256
257
for (var token in balance.keys) {
258
if (token is Erc20Token) {
270
- polygonErc20TokensTransactions.add(_client.fetchTransactions(
271
- address,
272
- contractAddress: token.contractAddress,
273
- ) as Future<List<PolygonTransactionModel>>);
259
+ polygonErc20TokensTransactions.add(
260
+ _client.fetchTransactions(
261
+ address,
262
+ contractAddress: token.contractAddress,
263
+ ),
264
+ );
265
}
266
}
267
285
isPending: false,
286
date: transactionModel.date,
287
confirmations: transactionModel.confirmations,
297
- ethFee:
298
- BigInt.from(transactionModel.gasUsed) * transactionModel.gasPrice,
288
+ ethFee: BigInt.from(transactionModel.gasUsed) * transactionModel.gasPrice,
289
exponent: transactionModel.tokenDecimal ?? 18,
290
tokenSymbol: transactionModel.tokenSymbol ?? "MATIC",
291
to: transactionModel.to,
327
_gasPrice = await _client.getGasUnitPrice();
328
_estimatedGas = await _client.getEstimatedGas();
329
340
- Timer.periodic(const Duration(minutes: 1),
341
- (timer) async => _gasPrice = await _client.getGasUnitPrice());
330
+ Timer.periodic(
331
+ const Duration(minutes: 1), (timer) async => _gasPrice = await _client.getGasUnitPrice());
332
Timer.periodic(const Duration(seconds: 10),
333
(timer) async => _estimatedGas = await _client.getEstimatedGas());
334
338
}
339
}
340
351
- Future<String> makePath() async =>
352
- pathForWallet(name: walletInfo.name, type: walletInfo.type);
341
+ Future<String> makePath() async => pathForWallet(name: walletInfo.name, type: walletInfo.type);
342
343
String toJSON() => json.encode({
344
'mnemonic': _mnemonic,
356
final data = json.decode(jsonSource) as Map;
357
final mnemonic = data['mnemonic'] as String?;
358
final privateKey = data['private_key'] as String?;
370
- final balance = ERC20Balance.fromJSON(data['balance'] as String) ??
371
- ERC20Balance(BigInt.zero);
359
+ final balance = ERC20Balance.fromJSON(data['balance'] as String) ?? ERC20Balance(BigInt.zero);
360
361
return PolygonWallet(
362
walletInfo: walletInfo,
406
407
final root = bip32.BIP32.fromSeed(seed);
408
421
- const _hdPathPolygon = "m/44'/60'/0'/0";
409
+ const hdPathPolygon = "m/44'/60'/0'/0";
410
const index = 0;
423
- final addressAtIndex = root.derivePath("$_hdPathPolygon/$index");
411
+ final addressAtIndex = root.derivePath("$hdPathPolygon/$index");
412
425
- return EthPrivateKey.fromHex(
426
- HEX.encode(addressAtIndex.privateKey as List<int>));
413
+ return EthPrivateKey.fromHex(HEX.encode(addressAtIndex.privateKey as List<int>));
414
}
415
416
+ @override
417
Future<void>? updateBalance() async => await _updateBalance();
418
419
List<Erc20Token> get erc20Currencies => polygonErc20TokensBox.values.toList();
422
String? iconPath;
423
try {
424
iconPath = CryptoCurrency.all
437
- .firstWhere((element) =>
438
- element.title.toUpperCase() == token.symbol.toUpperCase())
425
+ .firstWhere((element) => element.title.toUpperCase() == token.symbol.toUpperCase())
426
.iconPath;
427
} catch (_) {}
428
442
- final _token = Erc20Token(
429
+ final token0 = Erc20Token(
430
name: token.name,
431
symbol: token.symbol,
432
contractAddress: token.contractAddress,
433
decimal: token.decimal,
434
enabled: token.enabled,
435
+ tag: token.tag ?? "POLY",
436
iconPath: iconPath,
437
);
438
451
- await polygonErc20TokensBox.put(_token.contractAddress, _token);
439
+ await polygonErc20TokensBox.put(token0.contractAddress, token0);
440
453
- if (_token.enabled) {
454
- balance[_token] = await _client.fetchERC20Balances(
441
+ if (token0.enabled) {
442
+ balance[token0] = await _client.fetchERC20Balances(
443
_polygonPrivateKey.address,
456
- _token.contractAddress,
444
+ token0.contractAddress,
445
);
446
} else {
459
- balance.remove(_token);
447
+ balance.remove(token0);
448
}
449
}
450
464
}
465
466
void addInitialTokens() {
479
- final initialErc20Tokens =
480
- DefaultPolygonErc20Tokens().initialPolygonErc20Tokens;
467
+ final initialErc20Tokens = DefaultPolygonErc20Tokens().initialPolygonErc20Tokens;
468
469
for (var token in initialErc20Tokens) {
470
polygonErc20TokensBox.put(token.contractAddress, token);
473
474
@override
475
Future<void> renameWalletFiles(String newWalletName) async {
489
- final currentWalletPath =
490
- await pathForWallet(name: walletInfo.name, type: type);
476
+ final currentWalletPath = await pathForWallet(name: walletInfo.name, type: type);
477
final currentWalletFile = File(currentWalletPath);
478
493
- final currentDirPath =
494
- await pathForWalletDir(name: walletInfo.name, type: type);
495
- final currentTransactionsFile =
496
- File('$currentDirPath/$transactionsHistoryFileName');
479
+ final currentDirPath = await pathForWalletDir(name: walletInfo.name, type: type);
480
+ final currentTransactionsFile = File('$currentDirPath/$transactionsHistoryFileName');
481
482
// Copies current wallet files into new wallet name's dir and files
483
if (currentWalletFile.existsSync()) {
500
- final newWalletPath =
501
- await pathForWallet(name: newWalletName, type: type);
484
+ final newWalletPath = await pathForWallet(name: newWalletName, type: type);
485
await currentWalletFile.copy(newWalletPath);
486
}
487
if (currentTransactionsFile.existsSync()) {
505
- final newDirPath =
506
- await pathForWalletDir(name: newWalletName, type: type);
507
- await currentTransactionsFile
508
- .copy('$newDirPath/$transactionsHistoryFileName');
488
+ final newDirPath = await pathForWalletDir(name: newWalletName, type: type);
489
+ await currentTransactionsFile.copy('$newDirPath/$transactionsHistoryFileName');
490
}
491
492
// Delete old name's dir and files
498
_transactionsUpdateTimer!.cancel();
499
}
500
520
- _transactionsUpdateTimer = Timer.periodic(Duration(seconds: 10), (_) {
501
+ _transactionsUpdateTimer = Timer.periodic(const Duration(seconds: 10), (_) {
502
_updateTransactions();
503
_updateBalance();
504
});
514
}
515
516
@override
536
- String signMessage(String message, {String? address = null}) => bytesToHex(
537
- _polygonPrivateKey.signPersonalMessageToUint8List(ascii.encode(message)));
517
+ String signMessage(String message, {String? address}) =>
518
+ bytesToHex(_polygonPrivateKey.signPersonalMessageToUint8List(ascii.encode(message)));
519
520
Web3Client? getWeb3Client() => _client.getWeb3Client();
521
}