mirror of
https://github.com/cake-tech/cake_wallet.git
synced 2025-06-28 12:29:51 +00:00
CW-527-Add-Polygon-MATIC-Wallet (#1179)
* chore: Initial setup for polygon package * feat: Add polygon node urls * feat: Add Polygon(MATIC) wallet WIP * feat: Add Polygon(MATIC) wallet WIP * feat: Add Polygon MATIC wallet [skip ci] * fix: Issue with create/restore wallet for polygon * feat: Add erc20 tokens for polygon * feat: Adding Polygon MATIC Wallet * fix: Add build command for polygon to workflow file to fix failing action * fix: Switch evm to not display additional balance * chore: Sync with remote * fix: Revert change to inject app script * feat: Add polygon erc20 tokens * feat: Increase migration version * fix: Restore from QR address validator fix * fix: Adjust wallet connect connection flow to adapt to wallet type * fix: Make wallet fetch nfts based on the current wallet type * fix: Make wallet fetch nfts based on the current wallet type * fix: Try fetching transactions with moralis * fix: Requested review changes * fix: Error creating new wallet * fix: Revert script * fix: Exclude spam NFTs from nft listing API response * Update default_erc20_tokens.dart * replace matic with matic poly * Add polygon wallet scheme to app links * style: reformat default_settings_migration.dart * minor enhancement * fix using different wallet function for setting the transaction priorities * fix: Add chain to calls * Add USDC.e to initial coins * Add other default polygon node * Use Polygon scan some UI fixes * Add polygon scan api key to secrets generation code --------- Co-authored-by: Omar Hatem <omarh.ismail1@gmail.com>
This commit is contained in:
parent
3b7f9a297c
commit
b3d579c24a
116 changed files with 2351 additions and 206 deletions
30
cw_polygon/.gitignore
vendored
Normal file
30
cw_polygon/.gitignore
vendored
Normal file
|
@ -0,0 +1,30 @@
|
|||
# Miscellaneous
|
||||
*.class
|
||||
*.log
|
||||
*.pyc
|
||||
*.swp
|
||||
.DS_Store
|
||||
.atom/
|
||||
.buildlog/
|
||||
.history
|
||||
.svn/
|
||||
migrate_working_dir/
|
||||
|
||||
# IntelliJ related
|
||||
*.iml
|
||||
*.ipr
|
||||
*.iws
|
||||
.idea/
|
||||
|
||||
# The .vscode folder contains launch configuration and tasks you configure in
|
||||
# VS Code which you may wish to be included in version control, so this line
|
||||
# is commented out by default.
|
||||
#.vscode/
|
||||
|
||||
# Flutter/Dart/Pub related
|
||||
# Libraries should not include pubspec.lock, per https://dart.dev/guides/libraries/private-files#pubspeclock.
|
||||
/pubspec.lock
|
||||
**/doc/api/
|
||||
.dart_tool/
|
||||
.packages
|
||||
build/
|
10
cw_polygon/.metadata
Normal file
10
cw_polygon/.metadata
Normal file
|
@ -0,0 +1,10 @@
|
|||
# This file tracks properties of this Flutter project.
|
||||
# Used by Flutter tool to assess capabilities and perform upgrades etc.
|
||||
#
|
||||
# This file should be version controlled and should not be manually edited.
|
||||
|
||||
version:
|
||||
revision: f468f3366c26a5092eb964a230ce7892fda8f2f8
|
||||
channel: stable
|
||||
|
||||
project_type: package
|
3
cw_polygon/CHANGELOG.md
Normal file
3
cw_polygon/CHANGELOG.md
Normal file
|
@ -0,0 +1,3 @@
|
|||
## 0.0.1
|
||||
|
||||
* TODO: Describe initial release.
|
1
cw_polygon/LICENSE
Normal file
1
cw_polygon/LICENSE
Normal file
|
@ -0,0 +1 @@
|
|||
TODO: Add your license here.
|
39
cw_polygon/README.md
Normal file
39
cw_polygon/README.md
Normal file
|
@ -0,0 +1,39 @@
|
|||
<!--
|
||||
This README describes the package. If you publish this package to pub.dev,
|
||||
this README's contents appear on the landing page for your package.
|
||||
|
||||
For information about how to write a good package README, see the guide for
|
||||
[writing package pages](https://dart.dev/guides/libraries/writing-package-pages).
|
||||
|
||||
For general information about developing packages, see the Dart guide for
|
||||
[creating packages](https://dart.dev/guides/libraries/create-library-packages)
|
||||
and the Flutter guide for
|
||||
[developing packages and plugins](https://flutter.dev/developing-packages).
|
||||
-->
|
||||
|
||||
TODO: Put a short description of the package here that helps potential users
|
||||
know whether this package might be useful for them.
|
||||
|
||||
## Features
|
||||
|
||||
TODO: List what your package can do. Maybe include images, gifs, or videos.
|
||||
|
||||
## Getting started
|
||||
|
||||
TODO: List prerequisites and provide or point to information on how to
|
||||
start using the package.
|
||||
|
||||
## Usage
|
||||
|
||||
TODO: Include short and useful examples for package users. Add longer examples
|
||||
to `/example` folder.
|
||||
|
||||
```dart
|
||||
const like = 'sample';
|
||||
```
|
||||
|
||||
## Additional information
|
||||
|
||||
TODO: Tell users more about the package: where to find more information, how to
|
||||
contribute to the package, how to file issues, what response they can expect
|
||||
from the package authors, and more.
|
4
cw_polygon/analysis_options.yaml
Normal file
4
cw_polygon/analysis_options.yaml
Normal file
|
@ -0,0 +1,4 @@
|
|||
include: package:flutter_lints/flutter.yaml
|
||||
|
||||
# Additional information about this file can be found at
|
||||
# https://dart.dev/guides/language/analysis-options
|
7
cw_polygon/lib/cw_polygon.dart
Normal file
7
cw_polygon/lib/cw_polygon.dart
Normal file
|
@ -0,0 +1,7 @@
|
|||
library cw_polygon;
|
||||
|
||||
/// A Calculator.
|
||||
class Calculator {
|
||||
/// Returns [value] plus 1.
|
||||
int addOne(int value) => value + 1;
|
||||
}
|
86
cw_polygon/lib/default_erc20_tokens.dart
Normal file
86
cw_polygon/lib/default_erc20_tokens.dart
Normal file
|
@ -0,0 +1,86 @@
|
|||
import 'package:cw_core/crypto_currency.dart';
|
||||
import 'package:cw_core/erc20_token.dart';
|
||||
|
||||
class DefaultPolygonErc20Tokens {
|
||||
final List<Erc20Token> _defaultTokens = [
|
||||
Erc20Token(
|
||||
name: "Wrapped Ether",
|
||||
symbol: "WETH",
|
||||
contractAddress: "0x7ceB23fD6bC0adD59E62ac25578270cFf1b9f619",
|
||||
decimal: 18,
|
||||
enabled: false,
|
||||
),
|
||||
Erc20Token(
|
||||
name: "Tether USD (PoS)",
|
||||
symbol: "USDT",
|
||||
contractAddress: "0xc2132D05D31c914a87C6611C10748AEb04B58e8F",
|
||||
decimal: 6,
|
||||
enabled: true,
|
||||
),
|
||||
Erc20Token(
|
||||
name: "USD Coin",
|
||||
symbol: "USDC",
|
||||
contractAddress: "0x3c499c542cEF5E3811e1192ce70d8cC03d5c3359",
|
||||
decimal: 6,
|
||||
enabled: true,
|
||||
),
|
||||
Erc20Token(
|
||||
name: "USD Coin (POS)",
|
||||
symbol: "USDC.e",
|
||||
contractAddress: "0x2791Bca1f2de4661ED88A30C99A7a9449Aa84174",
|
||||
decimal: 6,
|
||||
enabled: false,
|
||||
),
|
||||
Erc20Token(
|
||||
name: "Avalanche Token",
|
||||
symbol: "AVAX",
|
||||
contractAddress: "0x2C89bbc92BD86F8075d1DEcc58C7F4E0107f286b",
|
||||
decimal: 18,
|
||||
enabled: false,
|
||||
),
|
||||
Erc20Token(
|
||||
name: "Wrapped BTC (PoS)",
|
||||
symbol: "WBTC",
|
||||
contractAddress: "0x1BFD67037B42Cf73acF2047067bd4F2C47D9BfD6",
|
||||
decimal: 8,
|
||||
enabled: false,
|
||||
),
|
||||
Erc20Token(
|
||||
name: "Dai (PoS)",
|
||||
symbol: "DAI",
|
||||
contractAddress: "0x8f3Cf7ad23Cd3CaDbD9735AFf958023239c6A063",
|
||||
decimal: 18,
|
||||
enabled: true,
|
||||
),
|
||||
Erc20Token(
|
||||
name: "SHIBA INU (PoS)",
|
||||
symbol: "SHIB",
|
||||
contractAddress: "0x6f8a06447Ff6FcF75d803135a7de15CE88C1d4ec",
|
||||
decimal: 18,
|
||||
enabled: false,
|
||||
),
|
||||
Erc20Token(
|
||||
name: "Uniswap (PoS)",
|
||||
symbol: "UNI",
|
||||
contractAddress: "0xb33EaAd8d922B1083446DC23f610c2567fB5180f",
|
||||
decimal: 18,
|
||||
enabled: false,
|
||||
),
|
||||
];
|
||||
|
||||
List<Erc20Token> get initialPolygonErc20Tokens => _defaultTokens.map((token) {
|
||||
String? iconPath;
|
||||
try {
|
||||
iconPath = CryptoCurrency.all
|
||||
.firstWhere((element) =>
|
||||
element.title.toUpperCase() == token.symbol.toUpperCase())
|
||||
.iconPath;
|
||||
} catch (_) {}
|
||||
|
||||
if (iconPath != null) {
|
||||
return Erc20Token.copyWith(token, iconPath);
|
||||
}
|
||||
|
||||
return token;
|
||||
}).toList();
|
||||
}
|
19
cw_polygon/lib/pending_polygon_transaction.dart
Normal file
19
cw_polygon/lib/pending_polygon_transaction.dart
Normal file
|
@ -0,0 +1,19 @@
|
|||
import 'dart:typed_data';
|
||||
|
||||
import 'package:cw_ethereum/pending_ethereum_transaction.dart';
|
||||
|
||||
class PendingPolygonTransaction extends PendingEthereumTransaction {
|
||||
PendingPolygonTransaction({
|
||||
required Function sendTransaction,
|
||||
required Uint8List signedTransaction,
|
||||
required BigInt fee,
|
||||
required String amount,
|
||||
required int exponent,
|
||||
}) : super(
|
||||
amount: amount,
|
||||
sendTransaction: sendTransaction,
|
||||
signedTransaction: signedTransaction,
|
||||
fee: fee,
|
||||
exponent: exponent,
|
||||
);
|
||||
}
|
34
cw_polygon/lib/polygon_client.dart
Normal file
34
cw_polygon/lib/polygon_client.dart
Normal file
|
@ -0,0 +1,34 @@
|
|||
import 'dart:convert';
|
||||
|
||||
import 'package:cw_ethereum/ethereum_client.dart';
|
||||
import 'package:cw_polygon/polygon_transaction_model.dart';
|
||||
import 'package:cw_ethereum/.secrets.g.dart' as secrets;
|
||||
|
||||
class PolygonClient extends EthereumClient {
|
||||
@override
|
||||
Future<List<PolygonTransactionModel>> fetchTransactions(String address,
|
||||
{String? contractAddress}) async {
|
||||
try {
|
||||
final response = await httpClient.get(Uri.https("api.polygonscan.com", "/api", {
|
||||
"module": "account",
|
||||
"action": contractAddress != null ? "tokentx" : "txlist",
|
||||
if (contractAddress != null) "contractaddress": contractAddress,
|
||||
"address": address,
|
||||
"apikey": secrets.polygonScanApiKey,
|
||||
}));
|
||||
|
||||
final jsonResponse = json.decode(response.body) as Map<String, dynamic>;
|
||||
|
||||
if (response.statusCode >= 200 && response.statusCode < 300 && jsonResponse['status'] != 0) {
|
||||
return (jsonResponse['result'] as List)
|
||||
.map((e) => PolygonTransactionModel.fromJson(e as Map<String, dynamic>))
|
||||
.toList();
|
||||
}
|
||||
|
||||
return [];
|
||||
} catch (e) {
|
||||
print(e);
|
||||
return [];
|
||||
}
|
||||
}
|
||||
}
|
6
cw_polygon/lib/polygon_exceptions.dart
Normal file
6
cw_polygon/lib/polygon_exceptions.dart
Normal file
|
@ -0,0 +1,6 @@
|
|||
import 'package:cw_core/crypto_currency.dart';
|
||||
import 'package:cw_ethereum/ethereum_exceptions.dart';
|
||||
|
||||
class PolygonTransactionCreationException extends EthereumTransactionCreationException {
|
||||
PolygonTransactionCreationException(CryptoCurrency currency) : super(currency);
|
||||
}
|
25
cw_polygon/lib/polygon_formatter.dart
Normal file
25
cw_polygon/lib/polygon_formatter.dart
Normal file
|
@ -0,0 +1,25 @@
|
|||
import 'package:intl/intl.dart';
|
||||
|
||||
const polygonAmountLength = 12;
|
||||
const polygonAmountDivider = 1000000000000;
|
||||
final polygonAmountFormat = NumberFormat()
|
||||
..maximumFractionDigits = polygonAmountLength
|
||||
..minimumFractionDigits = 1;
|
||||
|
||||
class PolygonFormatter {
|
||||
static int parsePolygonAmount(String amount) {
|
||||
try {
|
||||
return (double.parse(amount) * polygonAmountDivider).round();
|
||||
} catch (_) {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
static double parsePolygonAmountToDouble(int amount) {
|
||||
try {
|
||||
return amount / polygonAmountDivider;
|
||||
} catch (_) {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
}
|
5
cw_polygon/lib/polygon_mnemonics_exception.dart
Normal file
5
cw_polygon/lib/polygon_mnemonics_exception.dart
Normal file
|
@ -0,0 +1,5 @@
|
|||
class PolygonMnemonicIsIncorrectException implements Exception {
|
||||
@override
|
||||
String toString() =>
|
||||
'Polygon mnemonic has incorrect format. Mnemonic should contain 12 or 24 words separated by space.';
|
||||
}
|
18
cw_polygon/lib/polygon_transaction_credentials.dart
Normal file
18
cw_polygon/lib/polygon_transaction_credentials.dart
Normal file
|
@ -0,0 +1,18 @@
|
|||
import 'package:cw_core/crypto_currency.dart';
|
||||
import 'package:cw_core/output_info.dart';
|
||||
import 'package:cw_ethereum/ethereum_transaction_credentials.dart';
|
||||
import 'package:cw_polygon/polygon_transaction_priority.dart';
|
||||
|
||||
class PolygonTransactionCredentials extends EthereumTransactionCredentials {
|
||||
PolygonTransactionCredentials(
|
||||
List<OutputInfo> outputs, {
|
||||
required PolygonTransactionPriority? priority,
|
||||
required CryptoCurrency currency,
|
||||
final int? feeRate,
|
||||
}) : super(
|
||||
outputs,
|
||||
currency: currency,
|
||||
priority: priority,
|
||||
feeRate: feeRate,
|
||||
);
|
||||
}
|
77
cw_polygon/lib/polygon_transaction_history.dart
Normal file
77
cw_polygon/lib/polygon_transaction_history.dart
Normal file
|
@ -0,0 +1,77 @@
|
|||
import 'dart:convert';
|
||||
import 'dart:core';
|
||||
import 'package:cw_core/pathForWallet.dart';
|
||||
import 'package:cw_core/wallet_info.dart';
|
||||
import 'package:cw_ethereum/file.dart';
|
||||
import 'package:cw_polygon/polygon_transaction_info.dart';
|
||||
import 'package:mobx/mobx.dart';
|
||||
import 'package:cw_core/transaction_history.dart';
|
||||
|
||||
part 'polygon_transaction_history.g.dart';
|
||||
|
||||
const transactionsHistoryFileName = 'polygon_transactions.json';
|
||||
|
||||
class PolygonTransactionHistory = PolygonTransactionHistoryBase with _$PolygonTransactionHistory;
|
||||
|
||||
abstract class PolygonTransactionHistoryBase extends TransactionHistoryBase<PolygonTransactionInfo>
|
||||
with Store {
|
||||
PolygonTransactionHistoryBase({required this.walletInfo, required String password})
|
||||
: _password = password {
|
||||
transactions = ObservableMap<String, PolygonTransactionInfo>();
|
||||
}
|
||||
|
||||
final WalletInfo walletInfo;
|
||||
String _password;
|
||||
|
||||
Future<void> init() async => await _load();
|
||||
|
||||
@override
|
||||
Future<void> save() async {
|
||||
try {
|
||||
final dirPath = await pathForWalletDir(name: walletInfo.name, type: walletInfo.type);
|
||||
final path = '$dirPath/$transactionsHistoryFileName';
|
||||
final data = json.encode({'transactions': transactions});
|
||||
await writeData(path: path, password: _password, data: data);
|
||||
} catch (e, s) {
|
||||
print('Error while saving polygon transaction history: ${e.toString()}');
|
||||
print(s);
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
void addOne(PolygonTransactionInfo transaction) => transactions[transaction.id] = transaction;
|
||||
|
||||
@override
|
||||
void addMany(Map<String, PolygonTransactionInfo> transactions) =>
|
||||
this.transactions.addAll(transactions);
|
||||
|
||||
Future<Map<String, dynamic>> _read() async {
|
||||
final dirPath = await pathForWalletDir(name: walletInfo.name, type: walletInfo.type);
|
||||
final path = '$dirPath/$transactionsHistoryFileName';
|
||||
final content = await read(path: path, password: _password);
|
||||
if (content.isEmpty) {
|
||||
return {};
|
||||
}
|
||||
return json.decode(content) as Map<String, dynamic>;
|
||||
}
|
||||
|
||||
Future<void> _load() async {
|
||||
try {
|
||||
final content = await _read();
|
||||
final txs = content['transactions'] as Map<String, dynamic>? ?? {};
|
||||
|
||||
txs.entries.forEach((entry) {
|
||||
final val = entry.value;
|
||||
|
||||
if (val is Map<String, dynamic>) {
|
||||
final tx = PolygonTransactionInfo.fromJson(val);
|
||||
_update(tx);
|
||||
}
|
||||
});
|
||||
} catch (e) {
|
||||
print(e);
|
||||
}
|
||||
}
|
||||
|
||||
void _update(PolygonTransactionInfo transaction) => transactions[transaction.id] = transaction;
|
||||
}
|
49
cw_polygon/lib/polygon_transaction_info.dart
Normal file
49
cw_polygon/lib/polygon_transaction_info.dart
Normal file
|
@ -0,0 +1,49 @@
|
|||
import 'package:cw_core/transaction_direction.dart';
|
||||
import 'package:cw_ethereum/ethereum_transaction_info.dart';
|
||||
|
||||
class PolygonTransactionInfo extends EthereumTransactionInfo {
|
||||
PolygonTransactionInfo({
|
||||
required String id,
|
||||
required int height,
|
||||
required BigInt ethAmount,
|
||||
int exponent = 18,
|
||||
required TransactionDirection direction,
|
||||
required DateTime date,
|
||||
required bool isPending,
|
||||
required BigInt ethFee,
|
||||
required int confirmations,
|
||||
String tokenSymbol = "MATIC",
|
||||
required String? to,
|
||||
}) : super(
|
||||
confirmations: confirmations,
|
||||
id: id,
|
||||
height: height,
|
||||
ethAmount: ethAmount,
|
||||
exponent: exponent,
|
||||
direction: direction,
|
||||
date: date,
|
||||
isPending: isPending,
|
||||
ethFee: ethFee,
|
||||
to: to,
|
||||
tokenSymbol: tokenSymbol,
|
||||
);
|
||||
|
||||
factory PolygonTransactionInfo.fromJson(Map<String, dynamic> data) {
|
||||
return PolygonTransactionInfo(
|
||||
id: data['id'] as String,
|
||||
height: data['height'] as int,
|
||||
ethAmount: BigInt.parse(data['amount']),
|
||||
exponent: data['exponent'] as int,
|
||||
ethFee: BigInt.parse(data['fee']),
|
||||
direction: parseTransactionDirectionFromInt(data['direction'] as int),
|
||||
date: DateTime.fromMillisecondsSinceEpoch(data['date'] as int),
|
||||
isPending: data['isPending'] as bool,
|
||||
confirmations: data['confirmations'] as int,
|
||||
tokenSymbol: data['tokenSymbol'] as String,
|
||||
to: data['to'],
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
String feeFormatted() => '${(ethFee / BigInt.from(10).pow(18)).toString()} MATIC';
|
||||
}
|
49
cw_polygon/lib/polygon_transaction_model.dart
Normal file
49
cw_polygon/lib/polygon_transaction_model.dart
Normal file
|
@ -0,0 +1,49 @@
|
|||
import 'package:cw_ethereum/ethereum_transaction_model.dart';
|
||||
|
||||
class PolygonTransactionModel extends EthereumTransactionModel {
|
||||
PolygonTransactionModel({
|
||||
required DateTime date,
|
||||
required String hash,
|
||||
required String from,
|
||||
required String to,
|
||||
required BigInt amount,
|
||||
required int gasUsed,
|
||||
required BigInt gasPrice,
|
||||
required String contractAddress,
|
||||
required int confirmations,
|
||||
required int blockNumber,
|
||||
required String? tokenSymbol,
|
||||
required int? tokenDecimal,
|
||||
required bool isError,
|
||||
}) : super(
|
||||
amount: amount,
|
||||
date: date,
|
||||
hash: hash,
|
||||
from: from,
|
||||
to: to,
|
||||
gasPrice: gasPrice,
|
||||
gasUsed: gasUsed,
|
||||
confirmations: confirmations,
|
||||
contractAddress: contractAddress,
|
||||
blockNumber: blockNumber,
|
||||
tokenDecimal: tokenDecimal,
|
||||
tokenSymbol: tokenSymbol,
|
||||
isError: isError,
|
||||
);
|
||||
|
||||
factory PolygonTransactionModel.fromJson(Map<String, dynamic> json) => PolygonTransactionModel(
|
||||
date: DateTime.fromMillisecondsSinceEpoch(int.parse(json["timeStamp"]) * 1000),
|
||||
hash: json["hash"],
|
||||
from: json["from"],
|
||||
to: json["to"],
|
||||
amount: BigInt.parse(json["value"]),
|
||||
gasUsed: int.parse(json["gasUsed"]),
|
||||
gasPrice: BigInt.parse(json["gasPrice"]),
|
||||
contractAddress: json["contractAddress"],
|
||||
confirmations: int.parse(json["confirmations"]),
|
||||
blockNumber: int.parse(json["blockNumber"]),
|
||||
tokenSymbol: json["tokenSymbol"] ?? "MATIC",
|
||||
tokenDecimal: int.tryParse(json["tokenDecimal"] ?? ""),
|
||||
isError: json["isError"] == "1",
|
||||
);
|
||||
}
|
51
cw_polygon/lib/polygon_transaction_priority.dart
Normal file
51
cw_polygon/lib/polygon_transaction_priority.dart
Normal file
|
@ -0,0 +1,51 @@
|
|||
import 'package:cw_ethereum/ethereum_transaction_priority.dart';
|
||||
|
||||
class PolygonTransactionPriority extends EthereumTransactionPriority {
|
||||
const PolygonTransactionPriority({required String title, required int raw, required int tip})
|
||||
: super(title: title, raw: raw, tip: tip);
|
||||
|
||||
static const List<PolygonTransactionPriority> all = [fast, medium, slow];
|
||||
static const PolygonTransactionPriority slow =
|
||||
PolygonTransactionPriority(title: 'slow', raw: 0, tip: 1);
|
||||
static const PolygonTransactionPriority medium =
|
||||
PolygonTransactionPriority(title: 'Medium', raw: 1, tip: 2);
|
||||
static const PolygonTransactionPriority fast =
|
||||
PolygonTransactionPriority(title: 'Fast', raw: 2, tip: 4);
|
||||
|
||||
static PolygonTransactionPriority deserialize({required int raw}) {
|
||||
switch (raw) {
|
||||
case 0:
|
||||
return slow;
|
||||
case 1:
|
||||
return medium;
|
||||
case 2:
|
||||
return fast;
|
||||
default:
|
||||
throw Exception('Unexpected token: $raw for PolygonTransactionPriority deserialize');
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
String get units => 'gas';
|
||||
|
||||
@override
|
||||
String toString() {
|
||||
var label = '';
|
||||
|
||||
switch (this) {
|
||||
case PolygonTransactionPriority.slow:
|
||||
label = 'Slow';
|
||||
break;
|
||||
case PolygonTransactionPriority.medium:
|
||||
label = 'Medium';
|
||||
break;
|
||||
case PolygonTransactionPriority.fast:
|
||||
label = 'Fast';
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
|
||||
return label;
|
||||
}
|
||||
}
|
540
cw_polygon/lib/polygon_wallet.dart
Normal file
540
cw_polygon/lib/polygon_wallet.dart
Normal file
|
@ -0,0 +1,540 @@
|
|||
import 'dart:async';
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
import 'dart:math';
|
||||
|
||||
import 'package:cw_core/crypto_currency.dart';
|
||||
import 'package:cw_core/cake_hive.dart';
|
||||
import 'package:cw_core/node.dart';
|
||||
import 'package:cw_core/pathForWallet.dart';
|
||||
import 'package:cw_core/pending_transaction.dart';
|
||||
import 'package:cw_core/sync_status.dart';
|
||||
import 'package:cw_core/transaction_direction.dart';
|
||||
import 'package:cw_core/transaction_priority.dart';
|
||||
import 'package:cw_core/wallet_addresses.dart';
|
||||
import 'package:cw_core/wallet_base.dart';
|
||||
import 'package:cw_core/wallet_info.dart';
|
||||
import 'package:cw_ethereum/erc20_balance.dart';
|
||||
import 'package:cw_ethereum/ethereum_formatter.dart';
|
||||
import 'package:cw_ethereum/ethereum_transaction_model.dart';
|
||||
import 'package:cw_ethereum/file.dart';
|
||||
import 'package:cw_core/erc20_token.dart';
|
||||
import 'package:cw_polygon/default_erc20_tokens.dart';
|
||||
import 'package:cw_polygon/polygon_client.dart';
|
||||
import 'package:cw_polygon/polygon_exceptions.dart';
|
||||
import 'package:cw_polygon/polygon_formatter.dart';
|
||||
import 'package:cw_polygon/polygon_transaction_credentials.dart';
|
||||
import 'package:cw_polygon/polygon_transaction_history.dart';
|
||||
import 'package:cw_polygon/polygon_transaction_info.dart';
|
||||
import 'package:cw_polygon/polygon_transaction_model.dart';
|
||||
import 'package:cw_polygon/polygon_transaction_priority.dart';
|
||||
import 'package:cw_polygon/polygon_wallet_addresses.dart';
|
||||
import 'package:hive/hive.dart';
|
||||
import 'package:hex/hex.dart';
|
||||
import 'package:mobx/mobx.dart';
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
import 'package:web3dart/crypto.dart';
|
||||
import 'package:web3dart/web3dart.dart';
|
||||
import 'package:bip39/bip39.dart' as bip39;
|
||||
import 'package:bip32/bip32.dart' as bip32;
|
||||
|
||||
part 'polygon_wallet.g.dart';
|
||||
|
||||
class PolygonWallet = PolygonWalletBase with _$PolygonWallet;
|
||||
|
||||
abstract class PolygonWalletBase extends WalletBase<ERC20Balance,
|
||||
PolygonTransactionHistory, PolygonTransactionInfo> with Store {
|
||||
PolygonWalletBase({
|
||||
required WalletInfo walletInfo,
|
||||
String? mnemonic,
|
||||
String? privateKey,
|
||||
required String password,
|
||||
ERC20Balance? initialBalance,
|
||||
}) : syncStatus = NotConnectedSyncStatus(),
|
||||
_password = password,
|
||||
_mnemonic = mnemonic,
|
||||
_hexPrivateKey = privateKey,
|
||||
_isTransactionUpdating = false,
|
||||
_client = PolygonClient(),
|
||||
walletAddresses = PolygonWalletAddresses(walletInfo),
|
||||
balance = ObservableMap<CryptoCurrency, ERC20Balance>.of({
|
||||
CryptoCurrency.maticpoly: initialBalance ?? ERC20Balance(BigInt.zero)
|
||||
}),
|
||||
super(walletInfo) {
|
||||
this.walletInfo = walletInfo;
|
||||
transactionHistory =
|
||||
PolygonTransactionHistory(walletInfo: walletInfo, password: password);
|
||||
|
||||
if (!CakeHive.isAdapterRegistered(Erc20Token.typeId)) {
|
||||
CakeHive.registerAdapter(Erc20TokenAdapter());
|
||||
}
|
||||
|
||||
_sharedPrefs.complete(SharedPreferences.getInstance());
|
||||
}
|
||||
|
||||
final String? _mnemonic;
|
||||
final String? _hexPrivateKey;
|
||||
final String _password;
|
||||
|
||||
late final Box<Erc20Token> polygonErc20TokensBox;
|
||||
|
||||
late final EthPrivateKey _polygonPrivateKey;
|
||||
|
||||
EthPrivateKey get polygonPrivateKey => _polygonPrivateKey;
|
||||
|
||||
late PolygonClient _client;
|
||||
|
||||
int? _gasPrice;
|
||||
int? _estimatedGas;
|
||||
bool _isTransactionUpdating;
|
||||
|
||||
// TODO: remove after integrating our own node and having eth_newPendingTransactionFilter
|
||||
Timer? _transactionsUpdateTimer;
|
||||
|
||||
@override
|
||||
WalletAddresses walletAddresses;
|
||||
|
||||
@override
|
||||
@observable
|
||||
SyncStatus syncStatus;
|
||||
|
||||
@override
|
||||
@observable
|
||||
late ObservableMap<CryptoCurrency, ERC20Balance> balance;
|
||||
|
||||
Completer<SharedPreferences> _sharedPrefs = Completer();
|
||||
|
||||
Future<void> init() async {
|
||||
polygonErc20TokensBox =
|
||||
await CakeHive.openBox<Erc20Token>(Erc20Token.polygonBoxName);
|
||||
await walletAddresses.init();
|
||||
await transactionHistory.init();
|
||||
_polygonPrivateKey = await getPrivateKey(
|
||||
mnemonic: _mnemonic,
|
||||
privateKey: _hexPrivateKey,
|
||||
password: _password,
|
||||
);
|
||||
walletAddresses.address = _polygonPrivateKey.address.toString();
|
||||
await save();
|
||||
}
|
||||
|
||||
@override
|
||||
int calculateEstimatedFee(TransactionPriority priority, int? amount) {
|
||||
try {
|
||||
if (priority is PolygonTransactionPriority) {
|
||||
final priorityFee =
|
||||
EtherAmount.fromInt(EtherUnit.gwei, priority.tip).getInWei.toInt();
|
||||
return (_gasPrice! + priorityFee) * (_estimatedGas ?? 0);
|
||||
}
|
||||
|
||||
return 0;
|
||||
} catch (e) {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> changePassword(String password) {
|
||||
throw UnimplementedError("changePassword");
|
||||
}
|
||||
|
||||
@override
|
||||
void close() {
|
||||
_client.stop();
|
||||
_transactionsUpdateTimer?.cancel();
|
||||
}
|
||||
|
||||
@action
|
||||
@override
|
||||
Future<void> connectToNode({required Node node}) async {
|
||||
try {
|
||||
syncStatus = ConnectingSyncStatus();
|
||||
|
||||
final isConnected = _client.connect(node);
|
||||
|
||||
if (!isConnected) {
|
||||
throw Exception("Polygon Node connection failed");
|
||||
}
|
||||
|
||||
_client.setListeners(_polygonPrivateKey.address, _onNewTransaction);
|
||||
|
||||
_setTransactionUpdateTimer();
|
||||
|
||||
syncStatus = ConnectedSyncStatus();
|
||||
} catch (e) {
|
||||
syncStatus = FailedSyncStatus();
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Future<PendingTransaction> createTransaction(Object credentials) async {
|
||||
final _credentials = credentials as PolygonTransactionCredentials;
|
||||
final outputs = _credentials.outputs;
|
||||
final hasMultiDestination = outputs.length > 1;
|
||||
|
||||
final CryptoCurrency transactionCurrency = balance.keys
|
||||
.firstWhere((element) => element.title == _credentials.currency.title);
|
||||
|
||||
final _erc20Balance = balance[transactionCurrency]!;
|
||||
BigInt totalAmount = BigInt.zero;
|
||||
int exponent =
|
||||
transactionCurrency is Erc20Token ? transactionCurrency.decimal : 18;
|
||||
num amountToPolygonMultiplier = pow(10, exponent);
|
||||
|
||||
// so far this can not be made with Polygon as Polygon does not support multiple recipients
|
||||
if (hasMultiDestination) {
|
||||
if (outputs.any(
|
||||
(item) => item.sendAll || (item.formattedCryptoAmount ?? 0) <= 0)) {
|
||||
throw PolygonTransactionCreationException(transactionCurrency);
|
||||
}
|
||||
|
||||
final totalOriginalAmount = PolygonFormatter.parsePolygonAmountToDouble(
|
||||
outputs.fold(
|
||||
0, (acc, value) => acc + (value.formattedCryptoAmount ?? 0)));
|
||||
totalAmount =
|
||||
BigInt.from(totalOriginalAmount * amountToPolygonMultiplier);
|
||||
|
||||
if (_erc20Balance.balance < totalAmount) {
|
||||
throw PolygonTransactionCreationException(transactionCurrency);
|
||||
}
|
||||
} else {
|
||||
final output = outputs.first;
|
||||
// since the fees are taken from Ethereum
|
||||
// then no need to subtract the fees from the amount if send all
|
||||
final BigInt allAmount;
|
||||
if (transactionCurrency is Erc20Token) {
|
||||
allAmount = _erc20Balance.balance;
|
||||
} else {
|
||||
allAmount = _erc20Balance.balance -
|
||||
BigInt.from(calculateEstimatedFee(_credentials.priority!, null));
|
||||
}
|
||||
final totalOriginalAmount = EthereumFormatter.parseEthereumAmountToDouble(
|
||||
output.formattedCryptoAmount ?? 0);
|
||||
totalAmount = output.sendAll
|
||||
? allAmount
|
||||
: BigInt.from(totalOriginalAmount * amountToPolygonMultiplier);
|
||||
|
||||
if (_erc20Balance.balance < totalAmount) {
|
||||
throw PolygonTransactionCreationException(transactionCurrency);
|
||||
}
|
||||
}
|
||||
|
||||
final pendingPolygonTransaction = await _client.signTransaction(
|
||||
privateKey: _polygonPrivateKey,
|
||||
toAddress: _credentials.outputs.first.isParsedAddress
|
||||
? _credentials.outputs.first.extractedAddress!
|
||||
: _credentials.outputs.first.address,
|
||||
amount: totalAmount.toString(),
|
||||
gas: _estimatedGas!,
|
||||
priority: _credentials.priority!,
|
||||
currency: transactionCurrency,
|
||||
exponent: exponent,
|
||||
contractAddress: transactionCurrency is Erc20Token
|
||||
? transactionCurrency.contractAddress
|
||||
: null,
|
||||
);
|
||||
|
||||
return pendingPolygonTransaction;
|
||||
}
|
||||
|
||||
Future<void> _updateTransactions() async {
|
||||
try {
|
||||
if (_isTransactionUpdating) {
|
||||
return;
|
||||
}
|
||||
bool isPolygonScanEnabled = (await _sharedPrefs.future).getBool("use_polygonscan") ?? true;
|
||||
if (!isPolygonScanEnabled) {
|
||||
return;
|
||||
}
|
||||
|
||||
_isTransactionUpdating = true;
|
||||
final transactions = await fetchTransactions();
|
||||
transactionHistory.addMany(transactions);
|
||||
await transactionHistory.save();
|
||||
_isTransactionUpdating = false;
|
||||
} catch (_) {
|
||||
_isTransactionUpdating = false;
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Future<Map<String, PolygonTransactionInfo>> fetchTransactions() async {
|
||||
final address = _polygonPrivateKey.address.hex;
|
||||
final transactions = await _client.fetchTransactions(address);
|
||||
|
||||
final List<Future<List<PolygonTransactionModel>>> polygonErc20TokensTransactions =
|
||||
[];
|
||||
|
||||
for (var token in balance.keys) {
|
||||
if (token is Erc20Token) {
|
||||
polygonErc20TokensTransactions.add(_client.fetchTransactions(
|
||||
address,
|
||||
contractAddress: token.contractAddress,
|
||||
) as Future<List<PolygonTransactionModel>>);
|
||||
}
|
||||
}
|
||||
|
||||
final tokensTransaction = await Future.wait(polygonErc20TokensTransactions);
|
||||
transactions.addAll(tokensTransaction.expand((element) => element));
|
||||
|
||||
final Map<String, PolygonTransactionInfo> result = {};
|
||||
|
||||
for (var transactionModel in transactions) {
|
||||
if (transactionModel.isError) {
|
||||
continue;
|
||||
}
|
||||
|
||||
result[transactionModel.hash] = PolygonTransactionInfo(
|
||||
id: transactionModel.hash,
|
||||
height: transactionModel.blockNumber,
|
||||
ethAmount: transactionModel.amount,
|
||||
direction: transactionModel.from == address
|
||||
? TransactionDirection.outgoing
|
||||
: TransactionDirection.incoming,
|
||||
isPending: false,
|
||||
date: transactionModel.date,
|
||||
confirmations: transactionModel.confirmations,
|
||||
ethFee:
|
||||
BigInt.from(transactionModel.gasUsed) * transactionModel.gasPrice,
|
||||
exponent: transactionModel.tokenDecimal ?? 18,
|
||||
tokenSymbol: transactionModel.tokenSymbol ?? "MATIC",
|
||||
to: transactionModel.to,
|
||||
);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
@override
|
||||
Object get keys => throw UnimplementedError("keys");
|
||||
|
||||
@override
|
||||
Future<void> rescan({required int height}) {
|
||||
throw UnimplementedError("rescan");
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> save() async {
|
||||
await walletAddresses.updateAddressesInBox();
|
||||
final path = await makePath();
|
||||
await write(path: path, password: _password, data: toJSON());
|
||||
await transactionHistory.save();
|
||||
}
|
||||
|
||||
@override
|
||||
String? get seed => _mnemonic;
|
||||
|
||||
@override
|
||||
String get privateKey => HEX.encode(_polygonPrivateKey.privateKey);
|
||||
|
||||
@action
|
||||
@override
|
||||
Future<void> startSync() async {
|
||||
try {
|
||||
syncStatus = AttemptingSyncStatus();
|
||||
await _updateBalance();
|
||||
await _updateTransactions();
|
||||
_gasPrice = await _client.getGasUnitPrice();
|
||||
_estimatedGas = await _client.getEstimatedGas();
|
||||
|
||||
Timer.periodic(const Duration(minutes: 1),
|
||||
(timer) async => _gasPrice = await _client.getGasUnitPrice());
|
||||
Timer.periodic(const Duration(seconds: 10),
|
||||
(timer) async => _estimatedGas = await _client.getEstimatedGas());
|
||||
|
||||
syncStatus = SyncedSyncStatus();
|
||||
} catch (e) {
|
||||
syncStatus = FailedSyncStatus();
|
||||
}
|
||||
}
|
||||
|
||||
Future<String> makePath() async =>
|
||||
pathForWallet(name: walletInfo.name, type: walletInfo.type);
|
||||
|
||||
String toJSON() => json.encode({
|
||||
'mnemonic': _mnemonic,
|
||||
'private_key': privateKey,
|
||||
'balance': balance[currency]!.toJSON(),
|
||||
});
|
||||
|
||||
static Future<PolygonWallet> open({
|
||||
required String name,
|
||||
required String password,
|
||||
required WalletInfo walletInfo,
|
||||
}) async {
|
||||
final path = await pathForWallet(name: name, type: walletInfo.type);
|
||||
final jsonSource = await read(path: path, password: password);
|
||||
final data = json.decode(jsonSource) as Map;
|
||||
final mnemonic = data['mnemonic'] as String?;
|
||||
final privateKey = data['private_key'] as String?;
|
||||
final balance = ERC20Balance.fromJSON(data['balance'] as String) ??
|
||||
ERC20Balance(BigInt.zero);
|
||||
|
||||
return PolygonWallet(
|
||||
walletInfo: walletInfo,
|
||||
password: password,
|
||||
mnemonic: mnemonic,
|
||||
privateKey: privateKey,
|
||||
initialBalance: balance,
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> _updateBalance() async {
|
||||
balance[currency] = await _fetchMaticBalance();
|
||||
|
||||
await _fetchErc20Balances();
|
||||
await save();
|
||||
}
|
||||
|
||||
Future<ERC20Balance> _fetchMaticBalance() async {
|
||||
final balance = await _client.getBalance(_polygonPrivateKey.address);
|
||||
return ERC20Balance(balance.getInWei);
|
||||
}
|
||||
|
||||
Future<void> _fetchErc20Balances() async {
|
||||
for (var token in polygonErc20TokensBox.values) {
|
||||
try {
|
||||
if (token.enabled) {
|
||||
balance[token] = await _client.fetchERC20Balances(
|
||||
_polygonPrivateKey.address,
|
||||
token.contractAddress,
|
||||
);
|
||||
} else {
|
||||
balance.remove(token);
|
||||
}
|
||||
} catch (_) {}
|
||||
}
|
||||
}
|
||||
|
||||
Future<EthPrivateKey> getPrivateKey(
|
||||
{String? mnemonic, String? privateKey, required String password}) async {
|
||||
assert(mnemonic != null || privateKey != null);
|
||||
|
||||
if (privateKey != null) {
|
||||
return EthPrivateKey.fromHex(privateKey);
|
||||
}
|
||||
|
||||
final seed = bip39.mnemonicToSeed(mnemonic!);
|
||||
|
||||
final root = bip32.BIP32.fromSeed(seed);
|
||||
|
||||
const _hdPathPolygon = "m/44'/60'/0'/0";
|
||||
const index = 0;
|
||||
final addressAtIndex = root.derivePath("$_hdPathPolygon/$index");
|
||||
|
||||
return EthPrivateKey.fromHex(
|
||||
HEX.encode(addressAtIndex.privateKey as List<int>));
|
||||
}
|
||||
|
||||
Future<void>? updateBalance() async => await _updateBalance();
|
||||
|
||||
List<Erc20Token> get erc20Currencies => polygonErc20TokensBox.values.toList();
|
||||
|
||||
Future<void> addErc20Token(Erc20Token token) async {
|
||||
String? iconPath;
|
||||
try {
|
||||
iconPath = CryptoCurrency.all
|
||||
.firstWhere((element) =>
|
||||
element.title.toUpperCase() == token.symbol.toUpperCase())
|
||||
.iconPath;
|
||||
} catch (_) {}
|
||||
|
||||
final _token = Erc20Token(
|
||||
name: token.name,
|
||||
symbol: token.symbol,
|
||||
contractAddress: token.contractAddress,
|
||||
decimal: token.decimal,
|
||||
enabled: token.enabled,
|
||||
iconPath: iconPath,
|
||||
);
|
||||
|
||||
await polygonErc20TokensBox.put(_token.contractAddress, _token);
|
||||
|
||||
if (_token.enabled) {
|
||||
balance[_token] = await _client.fetchERC20Balances(
|
||||
_polygonPrivateKey.address,
|
||||
_token.contractAddress,
|
||||
);
|
||||
} else {
|
||||
balance.remove(_token);
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> deleteErc20Token(Erc20Token token) async {
|
||||
await token.delete();
|
||||
|
||||
balance.remove(token);
|
||||
_updateBalance();
|
||||
}
|
||||
|
||||
Future<Erc20Token?> getErc20Token(String contractAddress) async =>
|
||||
await _client.getErc20Token(contractAddress);
|
||||
|
||||
void _onNewTransaction() {
|
||||
_updateBalance();
|
||||
_updateTransactions();
|
||||
}
|
||||
|
||||
void addInitialTokens() {
|
||||
final initialErc20Tokens =
|
||||
DefaultPolygonErc20Tokens().initialPolygonErc20Tokens;
|
||||
|
||||
for (var token in initialErc20Tokens) {
|
||||
polygonErc20TokensBox.put(token.contractAddress, token);
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> renameWalletFiles(String newWalletName) async {
|
||||
final currentWalletPath =
|
||||
await pathForWallet(name: walletInfo.name, type: type);
|
||||
final currentWalletFile = File(currentWalletPath);
|
||||
|
||||
final currentDirPath =
|
||||
await pathForWalletDir(name: walletInfo.name, type: type);
|
||||
final currentTransactionsFile =
|
||||
File('$currentDirPath/$transactionsHistoryFileName');
|
||||
|
||||
// Copies current wallet files into new wallet name's dir and files
|
||||
if (currentWalletFile.existsSync()) {
|
||||
final newWalletPath =
|
||||
await pathForWallet(name: newWalletName, type: type);
|
||||
await currentWalletFile.copy(newWalletPath);
|
||||
}
|
||||
if (currentTransactionsFile.existsSync()) {
|
||||
final newDirPath =
|
||||
await pathForWalletDir(name: newWalletName, type: type);
|
||||
await currentTransactionsFile
|
||||
.copy('$newDirPath/$transactionsHistoryFileName');
|
||||
}
|
||||
|
||||
// Delete old name's dir and files
|
||||
await Directory(currentDirPath).delete(recursive: true);
|
||||
}
|
||||
|
||||
void _setTransactionUpdateTimer() {
|
||||
if (_transactionsUpdateTimer?.isActive ?? false) {
|
||||
_transactionsUpdateTimer!.cancel();
|
||||
}
|
||||
|
||||
_transactionsUpdateTimer = Timer.periodic(Duration(seconds: 10), (_) {
|
||||
_updateTransactions();
|
||||
_updateBalance();
|
||||
});
|
||||
}
|
||||
|
||||
void updatePolygonScanUsageState(bool isEnabled) {
|
||||
if (isEnabled) {
|
||||
_updateTransactions();
|
||||
_setTransactionUpdateTimer();
|
||||
} else {
|
||||
_transactionsUpdateTimer?.cancel();
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
String signMessage(String message, {String? address = null}) => bytesToHex(
|
||||
_polygonPrivateKey.signPersonalMessageToUint8List(ascii.encode(message)));
|
||||
|
||||
Web3Client? getWeb3Client() => _client.getWeb3Client();
|
||||
}
|
5
cw_polygon/lib/polygon_wallet_addresses.dart
Normal file
5
cw_polygon/lib/polygon_wallet_addresses.dart
Normal file
|
@ -0,0 +1,5 @@
|
|||
import 'package:cw_ethereum/ethereum_wallet_addresses.dart';
|
||||
|
||||
class PolygonWalletAddresses extends EthereumWalletAddresses {
|
||||
PolygonWalletAddresses(super.walletInfo);
|
||||
}
|
28
cw_polygon/lib/polygon_wallet_creation_credentials.dart
Normal file
28
cw_polygon/lib/polygon_wallet_creation_credentials.dart
Normal file
|
@ -0,0 +1,28 @@
|
|||
import 'package:cw_core/wallet_credentials.dart';
|
||||
import 'package:cw_core/wallet_info.dart';
|
||||
class PolygonNewWalletCredentials extends WalletCredentials {
|
||||
PolygonNewWalletCredentials({required String name, WalletInfo? walletInfo})
|
||||
: super(name: name, walletInfo: walletInfo);
|
||||
}
|
||||
|
||||
class PolygonRestoreWalletFromSeedCredentials extends WalletCredentials {
|
||||
PolygonRestoreWalletFromSeedCredentials(
|
||||
{required String name,
|
||||
required String password,
|
||||
required this.mnemonic,
|
||||
WalletInfo? walletInfo})
|
||||
: super(name: name, password: password, walletInfo: walletInfo);
|
||||
|
||||
final String mnemonic;
|
||||
}
|
||||
|
||||
class PolygonRestoreWalletFromPrivateKey extends WalletCredentials {
|
||||
PolygonRestoreWalletFromPrivateKey(
|
||||
{required String name,
|
||||
required String password,
|
||||
required this.privateKey,
|
||||
WalletInfo? walletInfo})
|
||||
: super(name: name, password: password, walletInfo: walletInfo);
|
||||
|
||||
final String privateKey;
|
||||
}
|
123
cw_polygon/lib/polygon_wallet_service.dart
Normal file
123
cw_polygon/lib/polygon_wallet_service.dart
Normal file
|
@ -0,0 +1,123 @@
|
|||
import 'dart:io';
|
||||
|
||||
import 'package:cw_core/pathForWallet.dart';
|
||||
import 'package:cw_core/wallet_base.dart';
|
||||
import 'package:cw_core/wallet_info.dart';
|
||||
import 'package:cw_core/wallet_service.dart';
|
||||
import 'package:cw_core/wallet_type.dart';
|
||||
import 'package:cw_ethereum/ethereum_mnemonics.dart';
|
||||
import 'package:cw_polygon/polygon_wallet.dart';
|
||||
import 'package:bip39/bip39.dart' as bip39;
|
||||
import 'package:hive/hive.dart';
|
||||
import 'polygon_wallet_creation_credentials.dart';
|
||||
import 'package:collection/collection.dart';
|
||||
|
||||
class PolygonWalletService extends WalletService<PolygonNewWalletCredentials,
|
||||
PolygonRestoreWalletFromSeedCredentials, PolygonRestoreWalletFromPrivateKey> {
|
||||
PolygonWalletService(this.walletInfoSource);
|
||||
|
||||
final Box<WalletInfo> walletInfoSource;
|
||||
|
||||
@override
|
||||
Future<PolygonWallet> create(PolygonNewWalletCredentials credentials) async {
|
||||
final strength = (credentials.seedPhraseLength == 12)
|
||||
? 128
|
||||
: (credentials.seedPhraseLength == 24)
|
||||
? 256
|
||||
: 128;
|
||||
|
||||
final mnemonic = bip39.generateMnemonic(strength: strength);
|
||||
final wallet = PolygonWallet(
|
||||
walletInfo: credentials.walletInfo!,
|
||||
mnemonic: mnemonic,
|
||||
password: credentials.password!,
|
||||
);
|
||||
|
||||
await wallet.init();
|
||||
wallet.addInitialTokens();
|
||||
await wallet.save();
|
||||
|
||||
return wallet;
|
||||
}
|
||||
|
||||
@override
|
||||
WalletType getType() => WalletType.polygon;
|
||||
|
||||
@override
|
||||
Future<bool> isWalletExit(String name) async =>
|
||||
File(await pathForWallet(name: name, type: getType())).existsSync();
|
||||
|
||||
@override
|
||||
Future<PolygonWallet> openWallet(String name, String password) async {
|
||||
final walletInfo =
|
||||
walletInfoSource.values.firstWhere((info) => info.id == WalletBase.idFor(name, getType()));
|
||||
final wallet = await PolygonWalletBase.open(
|
||||
name: name,
|
||||
password: password,
|
||||
walletInfo: walletInfo,
|
||||
);
|
||||
|
||||
await wallet.init();
|
||||
await wallet.save();
|
||||
|
||||
return wallet;
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> remove(String wallet) async {
|
||||
File(await pathForWalletDir(name: wallet, type: getType())).delete(recursive: true);
|
||||
final walletInfo = walletInfoSource.values
|
||||
.firstWhereOrNull((info) => info.id == WalletBase.idFor(wallet, getType()))!;
|
||||
await walletInfoSource.delete(walletInfo.key);
|
||||
}
|
||||
|
||||
@override
|
||||
Future<PolygonWallet> restoreFromKeys(PolygonRestoreWalletFromPrivateKey credentials) async {
|
||||
final wallet = PolygonWallet(
|
||||
password: credentials.password!,
|
||||
privateKey: credentials.privateKey,
|
||||
walletInfo: credentials.walletInfo!,
|
||||
);
|
||||
|
||||
await wallet.init();
|
||||
wallet.addInitialTokens();
|
||||
await wallet.save();
|
||||
|
||||
return wallet;
|
||||
}
|
||||
|
||||
@override
|
||||
Future<PolygonWallet> restoreFromSeed(PolygonRestoreWalletFromSeedCredentials credentials) async {
|
||||
if (!bip39.validateMnemonic(credentials.mnemonic)) {
|
||||
throw EthereumMnemonicIsIncorrectException();
|
||||
}
|
||||
|
||||
final wallet = PolygonWallet(
|
||||
password: credentials.password!,
|
||||
mnemonic: credentials.mnemonic,
|
||||
walletInfo: credentials.walletInfo!,
|
||||
);
|
||||
|
||||
await wallet.init();
|
||||
wallet.addInitialTokens();
|
||||
await wallet.save();
|
||||
|
||||
return wallet;
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> rename(String currentName, String password, String newName) async {
|
||||
final currentWalletInfo = walletInfoSource.values
|
||||
.firstWhere((info) => info.id == WalletBase.idFor(currentName, getType()));
|
||||
final currentWallet = await PolygonWalletBase.open(
|
||||
password: password, name: currentName, walletInfo: currentWalletInfo);
|
||||
|
||||
await currentWallet.renameWalletFiles(newName);
|
||||
|
||||
final newWalletInfo = currentWalletInfo;
|
||||
newWalletInfo.id = WalletBase.idFor(newName, getType());
|
||||
newWalletInfo.name = newName;
|
||||
|
||||
await walletInfoSource.put(currentWalletInfo.key, newWalletInfo);
|
||||
}
|
||||
}
|
73
cw_polygon/pubspec.yaml
Normal file
73
cw_polygon/pubspec.yaml
Normal file
|
@ -0,0 +1,73 @@
|
|||
name: cw_polygon
|
||||
description: A new Flutter package project.
|
||||
version: 0.0.1
|
||||
publish_to: none
|
||||
author: Cake Wallet
|
||||
homepage: https://cakewallet.com
|
||||
|
||||
environment:
|
||||
sdk: '>=3.0.6 <4.0.0'
|
||||
flutter: ">=1.17.0"
|
||||
|
||||
dependencies:
|
||||
flutter:
|
||||
sdk: flutter
|
||||
cw_core:
|
||||
path: ../cw_core
|
||||
cw_ethereum:
|
||||
path: ../cw_ethereum
|
||||
mobx: ^2.0.7+4
|
||||
intl: ^0.18.0
|
||||
bip39: ^1.0.6
|
||||
hive: ^2.2.3
|
||||
collection: ^1.17.1
|
||||
web3dart: ^2.7.1
|
||||
bip32: ^2.0.0
|
||||
hex: ^0.2.0
|
||||
shared_preferences: ^2.0.15
|
||||
|
||||
|
||||
dev_dependencies:
|
||||
flutter_test:
|
||||
sdk: flutter
|
||||
flutter_lints: ^2.0.0
|
||||
build_runner: ^2.1.11
|
||||
mobx_codegen: ^2.0.7
|
||||
hive_generator: ^1.1.3
|
||||
|
||||
# For information on the generic Dart part of this file, see the
|
||||
# following page: https://dart.dev/tools/pub/pubspec
|
||||
|
||||
# The following section is specific to Flutter packages.
|
||||
flutter:
|
||||
|
||||
# To add assets to your package, add an assets section, like this:
|
||||
# assets:
|
||||
# - images/a_dot_burr.jpeg
|
||||
# - images/a_dot_ham.jpeg
|
||||
#
|
||||
# For details regarding assets in packages, see
|
||||
# https://flutter.dev/assets-and-images/#from-packages
|
||||
#
|
||||
# An image asset can refer to one or more resolution-specific "variants", see
|
||||
# https://flutter.dev/assets-and-images/#resolution-aware
|
||||
|
||||
# To add custom fonts to your package, add a fonts section here,
|
||||
# in this "flutter" section. Each entry in this list should have a
|
||||
# "family" key with the font family name, and a "fonts" key with a
|
||||
# list giving the asset and other descriptors for the font. For
|
||||
# example:
|
||||
# fonts:
|
||||
# - family: Schyler
|
||||
# fonts:
|
||||
# - asset: fonts/Schyler-Regular.ttf
|
||||
# - asset: fonts/Schyler-Italic.ttf
|
||||
# style: italic
|
||||
# - family: Trajan Pro
|
||||
# fonts:
|
||||
# - asset: fonts/TrajanPro.ttf
|
||||
# - asset: fonts/TrajanPro_Bold.ttf
|
||||
# weight: 700
|
||||
#
|
||||
# For details regarding fonts in packages, see
|
||||
# https://flutter.dev/custom-fonts/#from-packages
|
12
cw_polygon/test/cw_polygon_test.dart
Normal file
12
cw_polygon/test/cw_polygon_test.dart
Normal file
|
@ -0,0 +1,12 @@
|
|||
import 'package:flutter_test/flutter_test.dart';
|
||||
|
||||
import 'package:cw_polygon/cw_polygon.dart';
|
||||
|
||||
void main() {
|
||||
test('adds one to input values', () {
|
||||
final calculator = Calculator();
|
||||
expect(calculator.addOne(2), 3);
|
||||
expect(calculator.addOne(-7), -6);
|
||||
expect(calculator.addOne(0), 1);
|
||||
});
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue