diff --git a/.github/workflows/pr_test_build.yml b/.github/workflows/pr_test_build.yml index 12d5dda5b..d8251a614 100644 --- a/.github/workflows/pr_test_build.yml +++ b/.github/workflows/pr_test_build.yml @@ -6,9 +6,9 @@ on: workflow_dispatch: inputs: branch: - description: 'Branch name to build' + description: "Branch name to build" required: true - default: 'main' + default: "main" jobs: PR_test_build: @@ -112,6 +112,7 @@ jobs: cd cw_bitcoin_cash && flutter pub get && flutter packages pub run build_runner build --delete-conflicting-outputs && cd .. cd cw_nano && flutter pub get && flutter packages pub run build_runner build --delete-conflicting-outputs && cd .. cd cw_lightning && flutter pub get && flutter packages pub run build_runner build --delete-conflicting-outputs && cd .. + cd cw_solana && flutter pub get && flutter packages pub run build_runner build --delete-conflicting-outputs && cd .. cd cw_ethereum && flutter pub get && cd .. cd cw_polygon && flutter pub get && cd .. flutter packages pub run build_runner build --delete-conflicting-outputs @@ -121,6 +122,7 @@ jobs: cd /opt/android/cake_wallet touch lib/.secrets.g.dart touch cw_evm/lib/.secrets.g.dart + touch cw_solana/lib/.secrets.g.dart echo "const salt = '${{ secrets.SALT }}';" > lib/.secrets.g.dart echo "const keychainSalt = '${{ secrets.KEY_CHAIN_SALT }}';" >> lib/.secrets.g.dart echo "const key = '${{ secrets.KEY }}';" >> lib/.secrets.g.dart @@ -157,6 +159,7 @@ jobs: echo "const polygonScanApiKey = '${{ secrets.POLYGON_SCAN_API_KEY }}';" >> cw_evm/lib/.secrets.g.dart echo "const breezApiKey = '${{ secrets.BREEZ_API_KEY }}';" >> cw_lightning/lib/.secrets.g.dart echo "const breezInviteCode = '${{ secrets.BREEZ_INVITE_CODE }}';" >> cw_lightning/lib/.secrets.g.dart + echo "const ankrApiKey = '${{ secrets.ANKR_API_KEY }}';" >> cw_solana/lib/.secrets.g.dart - name: Rename app run: echo -e "id=com.cakewallet.test\nname=${{ env.BRANCH_NAME }}" > /opt/android/cake_wallet/android/app.properties @@ -166,18 +169,18 @@ jobs: cd /opt/android/cake_wallet flutter build apk --release -# - name: Push to App Center -# run: | -# echo 'Installing App Center CLI tools' -# npm install -g appcenter-cli -# echo "Publishing test to App Center" -# appcenter distribute release \ -# --group "Testers" \ -# --file "/opt/android/cake_wallet/build/app/outputs/apk/release/app-release.apk" \ -# --release-notes ${{ env.BRANCH_NAME }} \ -# --app Cake-Labs/Cake-Wallet \ -# --token ${{ secrets.APP_CENTER_TOKEN }} \ -# --quiet + # - name: Push to App Center + # run: | + # echo 'Installing App Center CLI tools' + # npm install -g appcenter-cli + # echo "Publishing test to App Center" + # appcenter distribute release \ + # --group "Testers" \ + # --file "/opt/android/cake_wallet/build/app/outputs/apk/release/app-release.apk" \ + # --release-notes ${{ env.BRANCH_NAME }} \ + # --app Cake-Labs/Cake-Wallet \ + # --token ${{ secrets.APP_CENTER_TOKEN }} \ + # --quiet - name: Rename apk file run: | diff --git a/.gitignore b/.gitignore index c06b277f8..9300421f4 100644 --- a/.gitignore +++ b/.gitignore @@ -92,8 +92,10 @@ android/key.properties **/tool/.secrets-config.json **/tool/.evm-secrets-config.json **/tool/.ethereum-secrets-config.json +**/tool/.solana-secrets-config.json **/lib/.secrets.g.dart **/cw_evm/lib/.secrets.g.dart +**/cw_solana/lib/.secrets.g.dart vendor/ @@ -129,6 +131,7 @@ lib/ethereum/ethereum.dart lib/bitcoin_cash/bitcoin_cash.dart lib/nano/nano.dart lib/polygon/polygon.dart +lib/solana/solana.dart ios/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_180.png ios/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_120.png diff --git a/android/app/src/main/AndroidManifestBase.xml b/android/app/src/main/AndroidManifestBase.xml index 4929b5763..91bf93dbd 100644 --- a/android/app/src/main/AndroidManifestBase.xml +++ b/android/app/src/main/AndroidManifestBase.xml @@ -69,6 +69,7 @@ + with Serializable implemen required this.decimals, this.fullName, this.iconPath, - this.tag}) + this.tag, this.enabled = false, + }) : super(title: title, raw: raw); final String name; @@ -17,6 +18,9 @@ class CryptoCurrency extends EnumerableItem with Serializable implemen final String? fullName; final String? iconPath; final int decimals; + final bool enabled; + + set enabled(bool value) => this.enabled = value; static const all = [ CryptoCurrency.xmr, @@ -208,6 +212,7 @@ class CryptoCurrency extends EnumerableItem with Serializable implemen static const usdtPoly = CryptoCurrency(title: 'USDT', tag: 'POLY', fullName: 'Tether USD (PoS)', raw: 87, name: 'usdtpoly', iconPath: 'assets/images/usdt_icon.png', decimals: 6); static const usdcEPoly = CryptoCurrency(title: 'USDC.E', tag: 'POLY', fullName: 'USD Coin (PoS)', raw: 88, name: 'usdcepoly', iconPath: 'assets/images/usdc_icon.png', decimals: 6); static const kaspa = CryptoCurrency(title: 'KAS', fullName: 'Kaspa', raw: 89, name: 'kaspa', iconPath: 'assets/images/kaspa_icon.png', decimals: 8); + static const usdtSol = CryptoCurrency(title: 'USDT', tag: 'SOL', fullName: 'USDT Tether', raw: 90, name: 'usdtsol', iconPath: 'assets/images/usdt_icon.png', decimals: 6); static final Map _rawCurrencyMap = diff --git a/cw_core/lib/currency_for_wallet_type.dart b/cw_core/lib/currency_for_wallet_type.dart index bcc34fd6f..9ca5dd2c1 100644 --- a/cw_core/lib/currency_for_wallet_type.dart +++ b/cw_core/lib/currency_for_wallet_type.dart @@ -23,6 +23,8 @@ CryptoCurrency currencyForWalletType(WalletType type) { return CryptoCurrency.banano; case WalletType.polygon: return CryptoCurrency.maticpoly; + case WalletType.solana: + return CryptoCurrency.sol; default: throw Exception('Unexpected wallet type: ${type.toString()} for CryptoCurrency currencyForWalletType'); } diff --git a/cw_core/lib/hive_type_ids.dart b/cw_core/lib/hive_type_ids.dart index 4d4d1a6a8..3fa2eb647 100644 --- a/cw_core/lib/hive_type_ids.dart +++ b/cw_core/lib/hive_type_ids.dart @@ -13,4 +13,5 @@ const ADDRESS_INFO_TYPE_ID = 11; const ERC20_TOKEN_TYPE_ID = 12; const NANO_ACCOUNT_TYPE_ID = 13; const POW_NODE_TYPE_ID = 14; -const DERIVATION_TYPE_TYPE_ID = 15; \ No newline at end of file +const DERIVATION_TYPE_TYPE_ID = 15; +const SPL_TOKEN_TYPE_ID = 16; diff --git a/cw_core/lib/node.dart b/cw_core/lib/node.dart index 2c43dd21a..585bc3c38 100644 --- a/cw_core/lib/node.dart +++ b/cw_core/lib/node.dart @@ -70,15 +70,10 @@ class Node extends HiveObject with Keyable { Uri get uri { switch (type) { case WalletType.monero: - return Uri.http(uriRaw, ''); - case WalletType.bitcoin: - return createUriFromElectrumAddress(uriRaw); - case WalletType.litecoin: - return createUriFromElectrumAddress(uriRaw); case WalletType.haven: return Uri.http(uriRaw, ''); - case WalletType.ethereum: - return Uri.https(uriRaw, ''); + case WalletType.bitcoin: + case WalletType.litecoin: case WalletType.bitcoinCash: return createUriFromElectrumAddress(uriRaw); case WalletType.nano: @@ -88,7 +83,9 @@ class Node extends HiveObject with Keyable { } else { return Uri.http(uriRaw, ''); } + case WalletType.ethereum: case WalletType.polygon: + case WalletType.solana: return Uri.https(uriRaw, ''); default: throw Exception('Unexpected type ${type.toString()} for Node uri'); @@ -134,21 +131,17 @@ class Node extends HiveObject with Keyable { try { switch (type) { case WalletType.monero: - return requestMoneroNode(); - case WalletType.bitcoin: - return requestElectrumServer(); - case WalletType.litecoin: - return requestElectrumServer(); case WalletType.haven: return requestMoneroNode(); - case WalletType.ethereum: - return requestElectrumServer(); - case WalletType.bitcoinCash: - return requestElectrumServer(); case WalletType.nano: case WalletType.banano: return requestNanoNode(); + case WalletType.bitcoin: + case WalletType.litecoin: + case WalletType.bitcoinCash: + case WalletType.ethereum: case WalletType.polygon: + case WalletType.solana: return requestElectrumServer(); default: return false; diff --git a/cw_core/lib/pathForWallet.dart b/cw_core/lib/pathForWallet.dart index af4838ffa..cfc33ef21 100644 --- a/cw_core/lib/pathForWallet.dart +++ b/cw_core/lib/pathForWallet.dart @@ -1,6 +1,5 @@ import 'dart:io'; import 'package:cw_core/wallet_type.dart'; -import 'package:flutter/foundation.dart'; import 'package:path_provider/path_provider.dart'; Future pathForWalletDir({required String name, required WalletType type}) async { diff --git a/cw_core/lib/wallet_type.dart b/cw_core/lib/wallet_type.dart index 5b58e9a56..edecc6d81 100644 --- a/cw_core/lib/wallet_type.dart +++ b/cw_core/lib/wallet_type.dart @@ -15,6 +15,7 @@ const walletTypes = [ WalletType.nano, WalletType.banano, WalletType.polygon, + WalletType.solana, ]; @HiveType(typeId: WALLET_TYPE_TYPE_ID) @@ -50,6 +51,9 @@ enum WalletType { polygon, @HiveField(10) + solana, + + @HiveField(11) lightning } @@ -73,8 +77,10 @@ int serializeToInt(WalletType type) { return 7; case WalletType.polygon: return 8; - case WalletType.lightning: + case WalletType.solana: return 9; + case WalletType.lightning: + return 10; default: return -1; } @@ -101,6 +107,8 @@ WalletType deserializeFromInt(int raw) { case 8: return WalletType.polygon; case 9: + return WalletType.solana; + case 10: return WalletType.lightning; default: throw Exception('Unexpected token: $raw for WalletType deserializeFromInt'); @@ -129,6 +137,8 @@ String walletTypeToString(WalletType type) { return 'Polygon'; case WalletType.lightning: return 'Lightning'; + case WalletType.solana: + return 'Solana'; default: return ''; } @@ -156,6 +166,8 @@ String walletTypeToDisplayName(WalletType type) { return 'Polygon (MATIC)'; case WalletType.lightning: return 'Bitcoin (Lightning)'; + case WalletType.solana: + return 'Solana (SOL)'; default: return ''; } @@ -183,6 +195,8 @@ CryptoCurrency walletTypeToCryptoCurrency(WalletType type) { return CryptoCurrency.maticpoly; case WalletType.lightning: return CryptoCurrency.btc; + case WalletType.solana: + return CryptoCurrency.sol; default: throw Exception( 'Unexpected wallet type: ${type.toString()} for CryptoCurrency walletTypeToCryptoCurrency'); diff --git a/cw_solana/.gitignore b/cw_solana/.gitignore new file mode 100644 index 000000000..96486fd93 --- /dev/null +++ b/cw_solana/.gitignore @@ -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/ diff --git a/cw_solana/.metadata b/cw_solana/.metadata new file mode 100644 index 000000000..fa347fc6a --- /dev/null +++ b/cw_solana/.metadata @@ -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 diff --git a/cw_solana/CHANGELOG.md b/cw_solana/CHANGELOG.md new file mode 100644 index 000000000..41cc7d819 --- /dev/null +++ b/cw_solana/CHANGELOG.md @@ -0,0 +1,3 @@ +## 0.0.1 + +* TODO: Describe initial release. diff --git a/cw_solana/LICENSE b/cw_solana/LICENSE new file mode 100644 index 000000000..ba75c69f7 --- /dev/null +++ b/cw_solana/LICENSE @@ -0,0 +1 @@ +TODO: Add your license here. diff --git a/cw_solana/README.md b/cw_solana/README.md new file mode 100644 index 000000000..02fe8ecab --- /dev/null +++ b/cw_solana/README.md @@ -0,0 +1,39 @@ + + +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. diff --git a/cw_solana/analysis_options.yaml b/cw_solana/analysis_options.yaml new file mode 100644 index 000000000..a5744c1cf --- /dev/null +++ b/cw_solana/analysis_options.yaml @@ -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 diff --git a/cw_solana/lib/cw_solana.dart b/cw_solana/lib/cw_solana.dart new file mode 100644 index 000000000..d04069b3b --- /dev/null +++ b/cw_solana/lib/cw_solana.dart @@ -0,0 +1,7 @@ +library cw_solana; + +/// A Calculator. +class Calculator { + /// Returns [value] plus 1. + int addOne(int value) => value + 1; +} diff --git a/cw_solana/lib/default_spl_tokens.dart b/cw_solana/lib/default_spl_tokens.dart new file mode 100644 index 000000000..f96d62d86 --- /dev/null +++ b/cw_solana/lib/default_spl_tokens.dart @@ -0,0 +1,109 @@ +import 'package:cw_core/crypto_currency.dart'; +import 'package:cw_solana/spl_token.dart'; + +class DefaultSPLTokens { + final List _defaultTokens = [ + SPLToken( + name: 'USDT Tether', + symbol: 'USDT', + mintAddress: 'Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB', + decimal: 6, + mint: 'usdtsol', + enabled: true, + ), + SPLToken( + name: 'USD Coin', + symbol: 'USDC', + mintAddress: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v', + decimal: 6, + mint: 'usdcsol', + enabled: true, + ), + SPLToken( + name: 'Wrapped Ethereum (Sollet)', + symbol: 'soETH', + mintAddress: '2FPyTwcZLUg1MDrwsyoP4D6s1tM7hAkHYRjkNb5w6Pxk', + decimal: 6, + mint: 'soEth', + enabled: true, + iconPath: 'assets/images/eth_icon.png', + ), + SPLToken( + name: 'Wrapped SOL', + symbol: 'WSOL', + mintAddress: 'So11111111111111111111111111111111111111112', + decimal: 9, + mint: 'WSOL', + enabled: true, + iconPath: 'assets/images/sol_icon.png', + ), + SPLToken( + name: 'Wrapped Bitcoin (Sollet)', + symbol: 'BTC', + mintAddress: '9n4nbM75f5Ui33ZbPYXn59EwSgE8CGsHtAeTH5YFeJ9E', + decimal: 6, + mint: 'btcsol', + iconPath: 'assets/images/btc.png', + ), + SPLToken( + name: 'Bonk', + symbol: 'Bonk', + mintAddress: 'DezXAZ8z7PnrnRJjz3wXBoRgixCa6xjnB7YaB1pPB263', + decimal: 5, + mint: 'Bonk', + iconPath: 'assets/images/bonk_icon.png', + ), + SPLToken( + name: 'Helium Network Token', + symbol: 'HNT', + mintAddress: 'hntyVP6YFm1Hg25TN9WGLqM12b8TQmcknKrdu1oxWux', + decimal: 8, + mint: 'hnt', + iconPath: 'assets/images/hnt_icon.png', + ), + SPLToken( + name: 'Pyth Network', + symbol: 'PYTH', + mintAddress: 'HZ1JovNiVvGrGNiiYvEozEVgZ58xaU3RKwX8eACQBCt3', + decimal: 6, + mint: 'pyth', + ), + SPLToken( + name: 'Raydium', + symbol: 'RAY', + mintAddress: '4k3Dyjzvzp8eMZWUXbBCjEvwSkkk59S5iCNLY3QrkX6R', + decimal: 6, + mint: 'ray', + iconPath: 'assets/images/ray_icon.png', + ), + SPLToken( + name: 'GMT', + symbol: 'GMT', + mintAddress: '7i5KKsX2weiTkry7jA4ZwSuXGhs5eJBEjY8vVxR4pfRx', + decimal: 6, + mint: 'ray', + iconPath: 'assets/images/gmt_icon.png', + ), + SPLToken( + name: 'AvocadoCoin', + symbol: 'AVDO', + mintAddress: 'EE5L8cMU4itTsCSuor7NLK6RZx6JhsBe8GGV3oaAHm3P', + decimal: 8, + mint: 'avdo', + iconPath: 'assets/images/avdo_icon.png', + ), + ]; + + List get initialSPLTokens => _defaultTokens.map((token) { + String? iconPath; + if (token.iconPath != null) return token; + + try { + iconPath = CryptoCurrency.all + .firstWhere((element) => element.title.toUpperCase() == token.symbol.toUpperCase()) + .iconPath; + } catch (_) {} + + return SPLToken.copyWith(token, iconPath, 'SOL'); + }).toList(); +} diff --git a/cw_solana/lib/file.dart b/cw_solana/lib/file.dart new file mode 100644 index 000000000..8fd236ec3 --- /dev/null +++ b/cw_solana/lib/file.dart @@ -0,0 +1,39 @@ +import 'dart:io'; +import 'package:cw_core/key.dart'; +import 'package:encrypt/encrypt.dart' as encrypt; + +Future write( + {required String path, + required String password, + required String data}) async { + final keys = extractKeys(password); + final key = encrypt.Key.fromBase64(keys.first); + final iv = encrypt.IV.fromBase64(keys.last); + final encrypted = await encode(key: key, iv: iv, data: data); + final f = File(path); + f.writeAsStringSync(encrypted); +} + +Future writeData( + {required String path, + required String password, + required String data}) async { + final keys = extractKeys(password); + final key = encrypt.Key.fromBase64(keys.first); + final iv = encrypt.IV.fromBase64(keys.last); + final encrypted = await encode(key: key, iv: iv, data: data); + final f = File(path); + f.writeAsStringSync(encrypted); +} + +Future read({required String path, required String password}) async { + final file = File(path); + + if (!file.existsSync()) { + file.createSync(); + } + + final encrypted = file.readAsStringSync(); + + return decode(password: password, data: encrypted); +} diff --git a/cw_solana/lib/pending_solana_transaction.dart b/cw_solana/lib/pending_solana_transaction.dart new file mode 100644 index 000000000..38347ed13 --- /dev/null +++ b/cw_solana/lib/pending_solana_transaction.dart @@ -0,0 +1,43 @@ +import 'package:cw_core/pending_transaction.dart'; +import 'package:solana/encoder.dart'; + +class PendingSolanaTransaction with PendingTransaction { + final double amount; + final SignedTx signedTransaction; + final String destinationAddress; + final Function sendTransaction; + final double fee; + + PendingSolanaTransaction({ + required this.fee, + required this.amount, + required this.signedTransaction, + required this.destinationAddress, + required this.sendTransaction, + }); + + @override + String get amountFormatted { + String stringifiedAmount = amount.toString(); + + if (stringifiedAmount.toString().length >= 6) { + stringifiedAmount = stringifiedAmount.substring(0, 6); + } + + return stringifiedAmount; + } + + @override + Future commit() async { + return await sendTransaction(); + } + + @override + String get feeFormatted => fee.toString(); + + @override + String get hex => signedTransaction.encode(); + + @override + String get id => ''; +} diff --git a/cw_solana/lib/solana_balance.dart b/cw_solana/lib/solana_balance.dart new file mode 100644 index 000000000..b1f0ef153 --- /dev/null +++ b/cw_solana/lib/solana_balance.dart @@ -0,0 +1,39 @@ +import 'dart:convert'; + +import 'package:cw_core/balance.dart'; + +class SolanaBalance extends Balance { + SolanaBalance(this.balance) : super(balance.toInt(), balance.toInt()); + + final double balance; + + @override + String get formattedAdditionalBalance => _balanceFormatted(); + + @override + String get formattedAvailableBalance => _balanceFormatted(); + + String _balanceFormatted() { + String stringBalance = balance.toString(); + if (stringBalance.toString().length >= 6) { + stringBalance = stringBalance.substring(0, 6); + } + return stringBalance; + } + + static SolanaBalance? fromJSON(String? jsonSource) { + if (jsonSource == null) { + return null; + } + + final decoded = json.decode(jsonSource) as Map; + + try { + return SolanaBalance(decoded['balance']); + } catch (e) { + return SolanaBalance(0.0); + } + } + + String toJSON() => json.encode({'balance': balance.toString()}); +} diff --git a/cw_solana/lib/solana_client.dart b/cw_solana/lib/solana_client.dart new file mode 100644 index 000000000..ececc56ba --- /dev/null +++ b/cw_solana/lib/solana_client.dart @@ -0,0 +1,477 @@ +import 'dart:async'; +import 'dart:convert'; +import 'dart:math'; + +import 'package:cw_core/crypto_currency.dart'; +import 'package:cw_core/node.dart'; +import 'package:cw_solana/pending_solana_transaction.dart'; +import 'package:cw_solana/solana_balance.dart'; +import 'package:cw_solana/solana_transaction_model.dart'; +import 'package:http/http.dart' as http; +import 'package:solana/dto.dart'; +import 'package:solana/encoder.dart'; +import 'package:solana/solana.dart'; +import '.secrets.g.dart' as secrets; + +class SolanaWalletClient { + final httpClient = http.Client(); + SolanaClient? _client; + + bool connect(Node node) { + try { + Uri? rpcUri; + String webSocketUrl; + bool isModifiedNodeUri = false; + + if (node.uriRaw == 'rpc.ankr.com') { + isModifiedNodeUri = true; + String ankrApiKey = secrets.ankrApiKey; + + rpcUri = Uri.https(node.uriRaw, '/solana/$ankrApiKey'); + webSocketUrl = 'wss://${node.uriRaw}/solana/ws/$ankrApiKey'; + } else { + webSocketUrl = 'wss://${node.uriRaw}'; + } + + _client = SolanaClient( + rpcUrl: isModifiedNodeUri ? rpcUri! : node.uri, + websocketUrl: Uri.parse(webSocketUrl), + timeout: const Duration(minutes: 2), + ); + return true; + } catch (e) { + return false; + } + } + + Future getBalance(String address) async { + try { + final balance = await _client!.rpcClient.getBalance(address); + + final solBalance = balance.value / lamportsPerSol; + + return solBalance; + } catch (_) { + return 0.0; + } + } + + Future getSPLTokenAccounts(String mintAddress, String publicKey) async { + try { + final tokenAccounts = await _client!.rpcClient.getTokenAccountsByOwner( + publicKey, + TokenAccountsFilter.byMint(mintAddress), + commitment: Commitment.confirmed, + encoding: Encoding.jsonParsed, + ); + return tokenAccounts; + } catch (e) { + return null; + } + } + + Future getSplTokenBalance(String mintAddress, String publicKey) async { + // Fetch the token accounts (a token can have multiple accounts for various uses) + final tokenAccounts = await getSPLTokenAccounts(mintAddress, publicKey); + + // Handle scenario where there is no token account + if (tokenAccounts == null || tokenAccounts.value.isEmpty) { + return null; + } + + // Sum the balances of all accounts with the specified mint address + double totalBalance = 0.0; + + for (var programAccount in tokenAccounts.value) { + final tokenAmountResult = + await _client!.rpcClient.getTokenAccountBalance(programAccount.pubkey); + + final balance = tokenAmountResult.value.uiAmountString; + + final balanceAsDouble = double.tryParse(balance ?? '0.0') ?? 0.0; + + totalBalance += balanceAsDouble; + } + + return SolanaBalance(totalBalance); + } + + Future getGasForMessage(String message) async { + try { + final gasPrice = await _client!.rpcClient.getFeeForMessage(message) ?? 0; + final fee = gasPrice / lamportsPerSol; + return fee; + } catch (_) { + return 0; + } + } + + /// Load the Address's transactions into the account + Future> fetchTransactions( + Ed25519HDPublicKey publicKey, { + String? splTokenSymbol, + int? splTokenDecimal, + }) async { + List transactions = []; + + try { + final response = await _client!.rpcClient.getTransactionsList( + publicKey, + commitment: Commitment.confirmed, + limit: 1000, + ); + + for (final tx in response) { + if (tx.transaction is ParsedTransaction) { + final parsedTx = (tx.transaction as ParsedTransaction); + final message = parsedTx.message; + + final fee = (tx.meta?.fee ?? 0) / lamportsPerSol; + + for (final instruction in message.instructions) { + if (instruction is ParsedInstruction) { + instruction.map( + system: (systemData) { + systemData.parsed.map( + transfer: (transferData) { + ParsedSystemTransferInformation transfer = transferData.info; + bool isOutgoingTx = transfer.source == publicKey.toBase58(); + + double amount = transfer.lamports.toDouble() / lamportsPerSol; + + transactions.add( + SolanaTransactionModel( + id: parsedTx.signatures.first, + from: transfer.source, + to: transfer.destination, + amount: amount, + isOutgoingTx: isOutgoingTx, + blockTimeInInt: tx.blockTime!, + fee: fee, + programId: SystemProgram.programId, + tokenSymbol: 'SOL', + ), + ); + }, + transferChecked: (_) {}, + unsupported: (_) {}, + ); + }, + splToken: (splTokenData) { + if (splTokenSymbol != null) { + splTokenData.parsed.map( + transfer: (transferData) { + SplTokenTransferInfo transfer = transferData.info; + bool isOutgoingTx = transfer.source == publicKey.toBase58(); + + double amount = (double.tryParse(transfer.amount) ?? 0.0) / + pow(10, splTokenDecimal ?? 9); + + transactions.add( + SolanaTransactionModel( + id: parsedTx.signatures.first, + fee: fee, + from: transfer.source, + to: transfer.destination, + amount: amount, + isOutgoingTx: isOutgoingTx, + programId: TokenProgram.programId, + blockTimeInInt: tx.blockTime!, + tokenSymbol: splTokenSymbol, + ), + ); + }, + transferChecked: (transferCheckedData) { + SplTokenTransferCheckedInfo transfer = transferCheckedData.info; + bool isOutgoingTx = transfer.source == publicKey.toBase58(); + double amount = + double.tryParse(transfer.tokenAmount.uiAmountString ?? '0.0') ?? 0.0; + + transactions.add( + SolanaTransactionModel( + id: parsedTx.signatures.first, + fee: fee, + from: transfer.source, + to: transfer.destination, + amount: amount, + isOutgoingTx: isOutgoingTx, + programId: TokenProgram.programId, + blockTimeInInt: tx.blockTime!, + tokenSymbol: splTokenSymbol, + ), + ); + }, + generic: (genericData) {}, + ); + } + }, + memo: (_) {}, + unsupported: (a) {}, + ); + } + } + } + } + + return transactions; + } catch (err) { + return []; + } + } + + Future> getSPLTokenTransfers( + String address, + String splTokenSymbol, + int splTokenDecimal, + Ed25519HDKeyPair ownerKeypair, + ) async { + final tokenMint = Ed25519HDPublicKey.fromBase58(address); + + ProgramAccount? associatedTokenAccount; + + try { + associatedTokenAccount = await _client!.getAssociatedTokenAccount( + mint: tokenMint, + owner: ownerKeypair.publicKey, + commitment: Commitment.confirmed, + ); + } catch (_) {} + + if (associatedTokenAccount == null) return []; + + final accountPublicKey = Ed25519HDPublicKey.fromBase58(associatedTokenAccount.pubkey); + + final tokenTransactions = await fetchTransactions( + accountPublicKey, + splTokenSymbol: splTokenSymbol, + splTokenDecimal: splTokenDecimal, + ); + + return tokenTransactions; + } + + void stop() {} + + SolanaClient? get getSolanaClient => _client; + + Future signSolanaTransaction({ + required String tokenTitle, + required int tokenDecimals, + String? tokenMint, + required double inputAmount, + required String destinationAddress, + required Ed25519HDKeyPair ownerKeypair, + List references = const [], + }) async { + const commitment = Commitment.finalized; + + final latestBlockhash = + await _client!.rpcClient.getLatestBlockhash(commitment: commitment).value; + + final recentBlockhash = RecentBlockhash( + blockhash: latestBlockhash.blockhash, + feeCalculator: const FeeCalculator( + lamportsPerSignature: 500, + ), + ); + + if (tokenTitle == CryptoCurrency.sol.title) { + final pendingNativeTokenTransaction = await _signNativeTokenTransaction( + tokenTitle: tokenTitle, + tokenDecimals: tokenDecimals, + inputAmount: inputAmount, + destinationAddress: destinationAddress, + ownerKeypair: ownerKeypair, + recentBlockhash: recentBlockhash, + commitment: commitment, + ); + return pendingNativeTokenTransaction; + } else { + final pendingSPLTokenTransaction = _signSPLTokenTransaction( + tokenTitle: tokenTitle, + tokenDecimals: tokenDecimals, + tokenMint: tokenMint!, + inputAmount: inputAmount, + destinationAddress: destinationAddress, + ownerKeypair: ownerKeypair, + recentBlockhash: recentBlockhash, + commitment: commitment, + ); + return pendingSPLTokenTransaction; + } + } + + Future _signNativeTokenTransaction({ + required String tokenTitle, + required int tokenDecimals, + required double inputAmount, + required String destinationAddress, + required Ed25519HDKeyPair ownerKeypair, + required RecentBlockhash recentBlockhash, + required Commitment commitment, + }) async { + // Convert SOL to lamport + int lamports = (inputAmount * lamportsPerSol).toInt(); + + final instructions = [ + SystemInstruction.transfer( + fundingAccount: ownerKeypair.publicKey, + recipientAccount: Ed25519HDPublicKey.fromBase58(destinationAddress), + lamports: lamports, + ), + ]; + + final message = Message(instructions: instructions); + final signers = [ownerKeypair]; + + final signedTx = await _signTransactionInternal( + message: message, + signers: signers, + commitment: commitment, + recentBlockhash: recentBlockhash, + ); + + final fee = await _getFeeFromCompiledMessage( + message, + recentBlockhash, + signers.first.publicKey, + ); + + sendTx() async => await sendTransaction( + signedTransaction: signedTx, + commitment: commitment, + ); + + final pendingTransaction = PendingSolanaTransaction( + amount: inputAmount, + signedTransaction: signedTx, + destinationAddress: destinationAddress, + sendTransaction: sendTx, + fee: fee, + ); + + return pendingTransaction; + } + + Future _signSPLTokenTransaction({ + required String tokenTitle, + required int tokenDecimals, + required String tokenMint, + required double inputAmount, + required String destinationAddress, + required Ed25519HDKeyPair ownerKeypair, + required RecentBlockhash recentBlockhash, + required Commitment commitment, + }) async { + final destinationOwner = Ed25519HDPublicKey.fromBase58(destinationAddress); + final mint = Ed25519HDPublicKey.fromBase58(tokenMint); + + ProgramAccount? associatedRecipientAccount; + ProgramAccount? associatedSenderAccount; + + associatedRecipientAccount = await _client!.getAssociatedTokenAccount( + mint: mint, + owner: destinationOwner, + commitment: commitment, + ); + + associatedSenderAccount = await _client!.getAssociatedTokenAccount( + owner: ownerKeypair.publicKey, + mint: mint, + commitment: commitment, + ); + + // Throw an appropriate exception if the sender has no associated + // token account + if (associatedSenderAccount == null) { + throw NoAssociatedTokenAccountException(ownerKeypair.address, mint.toBase58()); + } + + try { + associatedRecipientAccount ??= await _client!.createAssociatedTokenAccount( + mint: mint, + owner: destinationOwner, + funder: ownerKeypair, + ); + } catch (e) { + throw Exception( + 'Error while creating an associated token account for the recipient: ${e.toString()}', + ); + } + + // Input by the user + final amount = (inputAmount * pow(10, tokenDecimals)).toInt(); + + final instruction = TokenInstruction.transfer( + source: Ed25519HDPublicKey.fromBase58(associatedSenderAccount.pubkey), + destination: Ed25519HDPublicKey.fromBase58(associatedRecipientAccount.pubkey), + owner: ownerKeypair.publicKey, + amount: amount, + ); + + final message = Message(instructions: [instruction]); + final signers = [ownerKeypair]; + + final signedTx = await _signTransactionInternal( + message: message, + signers: signers, + commitment: commitment, + recentBlockhash: recentBlockhash, + ); + + final fee = await _getFeeFromCompiledMessage( + message, + recentBlockhash, + signers.first.publicKey, + ); + + sendTx() async => await sendTransaction( + signedTransaction: signedTx, + commitment: commitment, + ); + + final pendingTransaction = PendingSolanaTransaction( + amount: inputAmount, + signedTransaction: signedTx, + destinationAddress: destinationAddress, + sendTransaction: sendTx, + fee: fee, + ); + return pendingTransaction; + } + + Future _getFeeFromCompiledMessage( + Message message, RecentBlockhash recentBlockhash, Ed25519HDPublicKey feePayer) async { + final compile = message.compile( + recentBlockhash: recentBlockhash.blockhash, + feePayer: feePayer, + ); + + final base64Message = base64Encode(compile.toByteArray().toList()); + + final fee = await getGasForMessage(base64Message); + return fee; + } + + Future _signTransactionInternal({ + required Message message, + required List signers, + required Commitment commitment, + required RecentBlockhash recentBlockhash, + }) async { + final signedTx = await signTransaction(recentBlockhash, message, signers); + + return signedTx; + } + + Future sendTransaction({ + required SignedTx signedTransaction, + required Commitment commitment, + }) async { + final signature = await _client!.rpcClient.sendTransaction(signedTransaction.encode()); + + _client!.waitForSignatureStatus(signature, status: commitment); + + return signature; + } +} diff --git a/cw_solana/lib/solana_exceptions.dart b/cw_solana/lib/solana_exceptions.dart new file mode 100644 index 000000000..7409b0500 --- /dev/null +++ b/cw_solana/lib/solana_exceptions.dart @@ -0,0 +1,21 @@ +import 'package:cw_core/crypto_currency.dart'; + +class SolanaTransactionCreationException implements Exception { + final String exceptionMessage; + + SolanaTransactionCreationException(CryptoCurrency currency) + : exceptionMessage = 'Error creating ${currency.title} transaction.'; + + @override + String toString() => exceptionMessage; +} + +class SolanaTransactionWrongBalanceException implements Exception { + final String exceptionMessage; + + SolanaTransactionWrongBalanceException(CryptoCurrency currency) + : exceptionMessage = 'Wrong balance. Not enough ${currency.title} on your balance.'; + + @override + String toString() => exceptionMessage; +} diff --git a/cw_solana/lib/solana_mnemonics.dart b/cw_solana/lib/solana_mnemonics.dart new file mode 100644 index 000000000..21cbb613a --- /dev/null +++ b/cw_solana/lib/solana_mnemonics.dart @@ -0,0 +1,2058 @@ +class SolanaMnemonicIsIncorrectException implements Exception { + @override + String toString() => + 'Solana mnemonic has incorrect format. Mnemonic should contain 12 or 24 words separated by space.'; +} + +class SolanaMnemonics { + static const englishWordlist = [ + 'abandon', + 'ability', + 'able', + 'about', + 'above', + 'absent', + 'absorb', + 'abstract', + 'absurd', + 'abuse', + 'access', + 'accident', + 'account', + 'accuse', + 'achieve', + 'acid', + 'acoustic', + 'acquire', + 'across', + 'act', + 'action', + 'actor', + 'actress', + 'actual', + 'adapt', + 'add', + 'addict', + 'address', + 'adjust', + 'admit', + 'adult', + 'advance', + 'advice', + 'aerobic', + 'affair', + 'afford', + 'afraid', + 'again', + 'age', + 'agent', + 'agree', + 'ahead', + 'aim', + 'air', + 'airport', + 'aisle', + 'alarm', + 'album', + 'alcohol', + 'alert', + 'alien', + 'all', + 'alley', + 'allow', + 'almost', + 'alone', + 'alpha', + 'already', + 'also', + 'alter', + 'always', + 'amateur', + 'amazing', + 'among', + 'amount', + 'amused', + 'analyst', + 'anchor', + 'ancient', + 'anger', + 'angle', + 'angry', + 'animal', + 'ankle', + 'announce', + 'annual', + 'another', + 'answer', + 'antenna', + 'antique', + 'anxiety', + 'any', + 'apart', + 'apology', + 'appear', + 'apple', + 'approve', + 'april', + 'arch', + 'arctic', + 'area', + 'arena', + 'argue', + 'arm', + 'armed', + 'armor', + 'army', + 'around', + 'arrange', + 'arrest', + 'arrive', + 'arrow', + 'art', + 'artefact', + 'artist', + 'artwork', + 'ask', + 'aspect', + 'assault', + 'asset', + 'assist', + 'assume', + 'asthma', + 'athlete', + 'atom', + 'attack', + 'attend', + 'attitude', + 'attract', + 'auction', + 'audit', + 'august', + 'aunt', + 'author', + 'auto', + 'autumn', + 'average', + 'avocado', + 'avoid', + 'awake', + 'aware', + 'away', + 'awesome', + 'awful', + 'awkward', + 'axis', + 'baby', + 'bachelor', + 'bacon', + 'badge', + 'bag', + 'balance', + 'balcony', + 'ball', + 'bamboo', + 'banana', + 'banner', + 'bar', + 'barely', + 'bargain', + 'barrel', + 'base', + 'basic', + 'basket', + 'battle', + 'beach', + 'bean', + 'beauty', + 'because', + 'become', + 'beef', + 'before', + 'begin', + 'behave', + 'behind', + 'believe', + 'below', + 'belt', + 'bench', + 'benefit', + 'best', + 'betray', + 'better', + 'between', + 'beyond', + 'bicycle', + 'bid', + 'bike', + 'bind', + 'biology', + 'bird', + 'birth', + 'bitter', + 'black', + 'blade', + 'blame', + 'blanket', + 'blast', + 'bleak', + 'bless', + 'blind', + 'blood', + 'blossom', + 'blouse', + 'blue', + 'blur', + 'blush', + 'board', + 'boat', + 'body', + 'boil', + 'bomb', + 'bone', + 'bonus', + 'book', + 'boost', + 'border', + 'boring', + 'borrow', + 'boss', + 'bottom', + 'bounce', + 'box', + 'boy', + 'bracket', + 'brain', + 'brand', + 'brass', + 'brave', + 'bread', + 'breeze', + 'brick', + 'bridge', + 'brief', + 'bright', + 'bring', + 'brisk', + 'broccoli', + 'broken', + 'bronze', + 'broom', + 'brother', + 'brown', + 'brush', + 'bubble', + 'buddy', + 'budget', + 'buffalo', + 'build', + 'bulb', + 'bulk', + 'bullet', + 'bundle', + 'bunker', + 'burden', + 'burger', + 'burst', + 'bus', + 'business', + 'busy', + 'butter', + 'buyer', + 'buzz', + 'cabbage', + 'cabin', + 'cable', + 'cactus', + 'cage', + 'cake', + 'call', + 'calm', + 'camera', + 'camp', + 'can', + 'canal', + 'cancel', + 'candy', + 'cannon', + 'canoe', + 'canvas', + 'canyon', + 'capable', + 'capital', + 'captain', + 'car', + 'carbon', + 'card', + 'cargo', + 'carpet', + 'carry', + 'cart', + 'case', + 'cash', + 'casino', + 'castle', + 'casual', + 'cat', + 'catalog', + 'catch', + 'category', + 'cattle', + 'caught', + 'cause', + 'caution', + 'cave', + 'ceiling', + 'celery', + 'cement', + 'census', + 'century', + 'cereal', + 'certain', + 'chair', + 'chalk', + 'champion', + 'change', + 'chaos', + 'chapter', + 'charge', + 'chase', + 'chat', + 'cheap', + 'check', + 'cheese', + 'chef', + 'cherry', + 'chest', + 'chicken', + 'chief', + 'child', + 'chimney', + 'choice', + 'choose', + 'chronic', + 'chuckle', + 'chunk', + 'churn', + 'cigar', + 'cinnamon', + 'circle', + 'citizen', + 'city', + 'civil', + 'claim', + 'clap', + 'clarify', + 'claw', + 'clay', + 'clean', + 'clerk', + 'clever', + 'click', + 'client', + 'cliff', + 'climb', + 'clinic', + 'clip', + 'clock', + 'clog', + 'close', + 'cloth', + 'cloud', + 'clown', + 'club', + 'clump', + 'cluster', + 'clutch', + 'coach', + 'coast', + 'coconut', + 'code', + 'coffee', + 'coil', + 'coin', + 'collect', + 'color', + 'column', + 'combine', + 'come', + 'comfort', + 'comic', + 'common', + 'company', + 'concert', + 'conduct', + 'confirm', + 'congress', + 'connect', + 'consider', + 'control', + 'convince', + 'cook', + 'cool', + 'copper', + 'copy', + 'coral', + 'core', + 'corn', + 'correct', + 'cost', + 'cotton', + 'couch', + 'country', + 'couple', + 'course', + 'cousin', + 'cover', + 'coyote', + 'crack', + 'cradle', + 'craft', + 'cram', + 'crane', + 'crash', + 'crater', + 'crawl', + 'crazy', + 'cream', + 'credit', + 'creek', + 'crew', + 'cricket', + 'crime', + 'crisp', + 'critic', + 'crop', + 'cross', + 'crouch', + 'crowd', + 'crucial', + 'cruel', + 'cruise', + 'crumble', + 'crunch', + 'crush', + 'cry', + 'crystal', + 'cube', + 'culture', + 'cup', + 'cupboard', + 'curious', + 'current', + 'curtain', + 'curve', + 'cushion', + 'custom', + 'cute', + 'cycle', + 'dad', + 'damage', + 'damp', + 'dance', + 'danger', + 'daring', + 'dash', + 'daughter', + 'dawn', + 'day', + 'deal', + 'debate', + 'debris', + 'decade', + 'december', + 'decide', + 'decline', + 'decorate', + 'decrease', + 'deer', + 'defense', + 'define', + 'defy', + 'degree', + 'delay', + 'deliver', + 'demand', + 'demise', + 'denial', + 'dentist', + 'deny', + 'depart', + 'depend', + 'deposit', + 'depth', + 'deputy', + 'derive', + 'describe', + 'desert', + 'design', + 'desk', + 'despair', + 'destroy', + 'detail', + 'detect', + 'develop', + 'device', + 'devote', + 'diagram', + 'dial', + 'diamond', + 'diary', + 'dice', + 'diesel', + 'diet', + 'differ', + 'digital', + 'dignity', + 'dilemma', + 'dinner', + 'dinosaur', + 'direct', + 'dirt', + 'disagree', + 'discover', + 'disease', + 'dish', + 'dismiss', + 'disorder', + 'display', + 'distance', + 'divert', + 'divide', + 'divorce', + 'dizzy', + 'doctor', + 'document', + 'dog', + 'doll', + 'dolphin', + 'domain', + 'donate', + 'donkey', + 'donor', + 'door', + 'dose', + 'double', + 'dove', + 'draft', + 'dragon', + 'drama', + 'drastic', + 'draw', + 'dream', + 'dress', + 'drift', + 'drill', + 'drink', + 'drip', + 'drive', + 'drop', + 'drum', + 'dry', + 'duck', + 'dumb', + 'dune', + 'during', + 'dust', + 'dutch', + 'duty', + 'dwarf', + 'dynamic', + 'eager', + 'eagle', + 'early', + 'earn', + 'earth', + 'easily', + 'east', + 'easy', + 'echo', + 'ecology', + 'economy', + 'edge', + 'edit', + 'educate', + 'effort', + 'egg', + 'eight', + 'either', + 'elbow', + 'elder', + 'electric', + 'elegant', + 'element', + 'elephant', + 'elevator', + 'elite', + 'else', + 'embark', + 'embody', + 'embrace', + 'emerge', + 'emotion', + 'employ', + 'empower', + 'empty', + 'enable', + 'enact', + 'end', + 'endless', + 'endorse', + 'enemy', + 'energy', + 'enforce', + 'engage', + 'engine', + 'enhance', + 'enjoy', + 'enlist', + 'enough', + 'enrich', + 'enroll', + 'ensure', + 'enter', + 'entire', + 'entry', + 'envelope', + 'episode', + 'equal', + 'equip', + 'era', + 'erase', + 'erode', + 'erosion', + 'error', + 'erupt', + 'escape', + 'essay', + 'essence', + 'estate', + 'eternal', + 'ethics', + 'evidence', + 'evil', + 'evoke', + 'evolve', + 'exact', + 'example', + 'excess', + 'exchange', + 'excite', + 'exclude', + 'excuse', + 'execute', + 'exercise', + 'exhaust', + 'exhibit', + 'exile', + 'exist', + 'exit', + 'exotic', + 'expand', + 'expect', + 'expire', + 'explain', + 'expose', + 'express', + 'extend', + 'extra', + 'eye', + 'eyebrow', + 'fabric', + 'face', + 'faculty', + 'fade', + 'faint', + 'faith', + 'fall', + 'false', + 'fame', + 'family', + 'famous', + 'fan', + 'fancy', + 'fantasy', + 'farm', + 'fashion', + 'fat', + 'fatal', + 'father', + 'fatigue', + 'fault', + 'favorite', + 'feature', + 'february', + 'federal', + 'fee', + 'feed', + 'feel', + 'female', + 'fence', + 'festival', + 'fetch', + 'fever', + 'few', + 'fiber', + 'fiction', + 'field', + 'figure', + 'file', + 'film', + 'filter', + 'final', + 'find', + 'fine', + 'finger', + 'finish', + 'fire', + 'firm', + 'first', + 'fiscal', + 'fish', + 'fit', + 'fitness', + 'fix', + 'flag', + 'flame', + 'flash', + 'flat', + 'flavor', + 'flee', + 'flight', + 'flip', + 'float', + 'flock', + 'floor', + 'flower', + 'fluid', + 'flush', + 'fly', + 'foam', + 'focus', + 'fog', + 'foil', + 'fold', + 'follow', + 'food', + 'foot', + 'force', + 'forest', + 'forget', + 'fork', + 'fortune', + 'forum', + 'forward', + 'fossil', + 'foster', + 'found', + 'fox', + 'fragile', + 'frame', + 'frequent', + 'fresh', + 'friend', + 'fringe', + 'frog', + 'front', + 'frost', + 'frown', + 'frozen', + 'fruit', + 'fuel', + 'fun', + 'funny', + 'furnace', + 'fury', + 'future', + 'gadget', + 'gain', + 'galaxy', + 'gallery', + 'game', + 'gap', + 'garage', + 'garbage', + 'garden', + 'garlic', + 'garment', + 'gas', + 'gasp', + 'gate', + 'gather', + 'gauge', + 'gaze', + 'general', + 'genius', + 'genre', + 'gentle', + 'genuine', + 'gesture', + 'ghost', + 'giant', + 'gift', + 'giggle', + 'ginger', + 'giraffe', + 'girl', + 'give', + 'glad', + 'glance', + 'glare', + 'glass', + 'glide', + 'glimpse', + 'globe', + 'gloom', + 'glory', + 'glove', + 'glow', + 'glue', + 'goat', + 'goddess', + 'gold', + 'good', + 'goose', + 'gorilla', + 'gospel', + 'gossip', + 'govern', + 'gown', + 'grab', + 'grace', + 'grain', + 'grant', + 'grape', + 'grass', + 'gravity', + 'great', + 'green', + 'grid', + 'grief', + 'grit', + 'grocery', + 'group', + 'grow', + 'grunt', + 'guard', + 'guess', + 'guide', + 'guilt', + 'guitar', + 'gun', + 'gym', + 'habit', + 'hair', + 'half', + 'hammer', + 'hamster', + 'hand', + 'happy', + 'harbor', + 'hard', + 'harsh', + 'harvest', + 'hat', + 'have', + 'hawk', + 'hazard', + 'head', + 'health', + 'heart', + 'heavy', + 'hedgehog', + 'height', + 'hello', + 'helmet', + 'help', + 'hen', + 'hero', + 'hidden', + 'high', + 'hill', + 'hint', + 'hip', + 'hire', + 'history', + 'hobby', + 'hockey', + 'hold', + 'hole', + 'holiday', + 'hollow', + 'home', + 'honey', + 'hood', + 'hope', + 'horn', + 'horror', + 'horse', + 'hospital', + 'host', + 'hotel', + 'hour', + 'hover', + 'hub', + 'huge', + 'human', + 'humble', + 'humor', + 'hundred', + 'hungry', + 'hunt', + 'hurdle', + 'hurry', + 'hurt', + 'husband', + 'hybrid', + 'ice', + 'icon', + 'idea', + 'identify', + 'idle', + 'ignore', + 'ill', + 'illegal', + 'illness', + 'image', + 'imitate', + 'immense', + 'immune', + 'impact', + 'impose', + 'improve', + 'impulse', + 'inch', + 'include', + 'income', + 'increase', + 'index', + 'indicate', + 'indoor', + 'industry', + 'infant', + 'inflict', + 'inform', + 'inhale', + 'inherit', + 'initial', + 'inject', + 'injury', + 'inmate', + 'inner', + 'innocent', + 'input', + 'inquiry', + 'insane', + 'insect', + 'inside', + 'inspire', + 'install', + 'intact', + 'interest', + 'into', + 'invest', + 'invite', + 'involve', + 'iron', + 'island', + 'isolate', + 'issue', + 'item', + 'ivory', + 'jacket', + 'jaguar', + 'jar', + 'jazz', + 'jealous', + 'jeans', + 'jelly', + 'jewel', + 'job', + 'join', + 'joke', + 'journey', + 'joy', + 'judge', + 'juice', + 'jump', + 'jungle', + 'junior', + 'junk', + 'just', + 'kangaroo', + 'keen', + 'keep', + 'ketchup', + 'key', + 'kick', + 'kid', + 'kidney', + 'kind', + 'kingdom', + 'kiss', + 'kit', + 'kitchen', + 'kite', + 'kitten', + 'kiwi', + 'knee', + 'knife', + 'knock', + 'know', + 'lab', + 'label', + 'labor', + 'ladder', + 'lady', + 'lake', + 'lamp', + 'language', + 'laptop', + 'large', + 'later', + 'latin', + 'laugh', + 'laundry', + 'lava', + 'law', + 'lawn', + 'lawsuit', + 'layer', + 'lazy', + 'leader', + 'leaf', + 'learn', + 'leave', + 'lecture', + 'left', + 'leg', + 'legal', + 'legend', + 'leisure', + 'lemon', + 'lend', + 'length', + 'lens', + 'leopard', + 'lesson', + 'letter', + 'level', + 'liar', + 'liberty', + 'library', + 'license', + 'life', + 'lift', + 'light', + 'like', + 'limb', + 'limit', + 'link', + 'lion', + 'liquid', + 'list', + 'little', + 'live', + 'lizard', + 'load', + 'loan', + 'lobster', + 'local', + 'lock', + 'logic', + 'lonely', + 'long', + 'loop', + 'lottery', + 'loud', + 'lounge', + 'love', + 'loyal', + 'lucky', + 'luggage', + 'lumber', + 'lunar', + 'lunch', + 'luxury', + 'lyrics', + 'machine', + 'mad', + 'magic', + 'magnet', + 'maid', + 'mail', + 'main', + 'major', + 'make', + 'mammal', + 'man', + 'manage', + 'mandate', + 'mango', + 'mansion', + 'manual', + 'maple', + 'marble', + 'march', + 'margin', + 'marine', + 'market', + 'marriage', + 'mask', + 'mass', + 'master', + 'match', + 'material', + 'math', + 'matrix', + 'matter', + 'maximum', + 'maze', + 'meadow', + 'mean', + 'measure', + 'meat', + 'mechanic', + 'medal', + 'media', + 'melody', + 'melt', + 'member', + 'memory', + 'mention', + 'menu', + 'mercy', + 'merge', + 'merit', + 'merry', + 'mesh', + 'message', + 'metal', + 'method', + 'middle', + 'midnight', + 'milk', + 'million', + 'mimic', + 'mind', + 'minimum', + 'minor', + 'minute', + 'miracle', + 'mirror', + 'misery', + 'miss', + 'mistake', + 'mix', + 'mixed', + 'mixture', + 'mobile', + 'model', + 'modify', + 'mom', + 'moment', + 'monitor', + 'monkey', + 'monster', + 'month', + 'moon', + 'moral', + 'more', + 'morning', + 'mosquito', + 'mother', + 'motion', + 'motor', + 'mountain', + 'mouse', + 'move', + 'movie', + 'much', + 'muffin', + 'mule', + 'multiply', + 'muscle', + 'museum', + 'mushroom', + 'music', + 'must', + 'mutual', + 'myself', + 'mystery', + 'myth', + 'naive', + 'name', + 'napkin', + 'narrow', + 'nasty', + 'nation', + 'nature', + 'near', + 'neck', + 'need', + 'negative', + 'neglect', + 'neither', + 'nephew', + 'nerve', + 'nest', + 'net', + 'network', + 'neutral', + 'never', + 'news', + 'next', + 'nice', + 'night', + 'noble', + 'noise', + 'nominee', + 'noodle', + 'normal', + 'north', + 'nose', + 'notable', + 'note', + 'nothing', + 'notice', + 'novel', + 'now', + 'nuclear', + 'number', + 'nurse', + 'nut', + 'oak', + 'obey', + 'object', + 'oblige', + 'obscure', + 'observe', + 'obtain', + 'obvious', + 'occur', + 'ocean', + 'october', + 'odor', + 'off', + 'offer', + 'office', + 'often', + 'oil', + 'okay', + 'old', + 'olive', + 'olympic', + 'omit', + 'once', + 'one', + 'onion', + 'online', + 'only', + 'open', + 'opera', + 'opinion', + 'oppose', + 'option', + 'orange', + 'orbit', + 'orchard', + 'order', + 'ordinary', + 'organ', + 'orient', + 'original', + 'orphan', + 'ostrich', + 'other', + 'outdoor', + 'outer', + 'output', + 'outside', + 'oval', + 'oven', + 'over', + 'own', + 'owner', + 'oxygen', + 'oyster', + 'ozone', + 'pact', + 'paddle', + 'page', + 'pair', + 'palace', + 'palm', + 'panda', + 'panel', + 'panic', + 'panther', + 'paper', + 'parade', + 'parent', + 'park', + 'parrot', + 'party', + 'pass', + 'patch', + 'path', + 'patient', + 'patrol', + 'pattern', + 'pause', + 'pave', + 'payment', + 'peace', + 'peanut', + 'pear', + 'peasant', + 'pelican', + 'pen', + 'penalty', + 'pencil', + 'people', + 'pepper', + 'perfect', + 'permit', + 'person', + 'pet', + 'phone', + 'photo', + 'phrase', + 'physical', + 'piano', + 'picnic', + 'picture', + 'piece', + 'pig', + 'pigeon', + 'pill', + 'pilot', + 'pink', + 'pioneer', + 'pipe', + 'pistol', + 'pitch', + 'pizza', + 'place', + 'planet', + 'plastic', + 'plate', + 'play', + 'please', + 'pledge', + 'pluck', + 'plug', + 'plunge', + 'poem', + 'poet', + 'point', + 'polar', + 'pole', + 'police', + 'pond', + 'pony', + 'pool', + 'popular', + 'portion', + 'position', + 'possible', + 'post', + 'potato', + 'pottery', + 'poverty', + 'powder', + 'power', + 'practice', + 'praise', + 'predict', + 'prefer', + 'prepare', + 'present', + 'pretty', + 'prevent', + 'price', + 'pride', + 'primary', + 'print', + 'priority', + 'prison', + 'private', + 'prize', + 'problem', + 'process', + 'produce', + 'profit', + 'program', + 'project', + 'promote', + 'proof', + 'property', + 'prosper', + 'protect', + 'proud', + 'provide', + 'public', + 'pudding', + 'pull', + 'pulp', + 'pulse', + 'pumpkin', + 'punch', + 'pupil', + 'puppy', + 'purchase', + 'purity', + 'purpose', + 'purse', + 'push', + 'put', + 'puzzle', + 'pyramid', + 'quality', + 'quantum', + 'quarter', + 'question', + 'quick', + 'quit', + 'quiz', + 'quote', + 'rabbit', + 'raccoon', + 'race', + 'rack', + 'radar', + 'radio', + 'rail', + 'rain', + 'raise', + 'rally', + 'ramp', + 'ranch', + 'random', + 'range', + 'rapid', + 'rare', + 'rate', + 'rather', + 'raven', + 'raw', + 'razor', + 'ready', + 'real', + 'reason', + 'rebel', + 'rebuild', + 'recall', + 'receive', + 'recipe', + 'record', + 'recycle', + 'reduce', + 'reflect', + 'reform', + 'refuse', + 'region', + 'regret', + 'regular', + 'reject', + 'relax', + 'release', + 'relief', + 'rely', + 'remain', + 'remember', + 'remind', + 'remove', + 'render', + 'renew', + 'rent', + 'reopen', + 'repair', + 'repeat', + 'replace', + 'report', + 'require', + 'rescue', + 'resemble', + 'resist', + 'resource', + 'response', + 'result', + 'retire', + 'retreat', + 'return', + 'reunion', + 'reveal', + 'review', + 'reward', + 'rhythm', + 'rib', + 'ribbon', + 'rice', + 'rich', + 'ride', + 'ridge', + 'rifle', + 'right', + 'rigid', + 'ring', + 'riot', + 'ripple', + 'risk', + 'ritual', + 'rival', + 'river', + 'road', + 'roast', + 'robot', + 'robust', + 'rocket', + 'romance', + 'roof', + 'rookie', + 'room', + 'rose', + 'rotate', + 'rough', + 'round', + 'route', + 'royal', + 'rubber', + 'rude', + 'rug', + 'rule', + 'run', + 'runway', + 'rural', + 'sad', + 'saddle', + 'sadness', + 'safe', + 'sail', + 'salad', + 'salmon', + 'salon', + 'salt', + 'salute', + 'same', + 'sample', + 'sand', + 'satisfy', + 'satoshi', + 'sauce', + 'sausage', + 'save', + 'say', + 'scale', + 'scan', + 'scare', + 'scatter', + 'scene', + 'scheme', + 'school', + 'science', + 'scissors', + 'scorpion', + 'scout', + 'scrap', + 'screen', + 'script', + 'scrub', + 'sea', + 'search', + 'season', + 'seat', + 'second', + 'secret', + 'section', + 'security', + 'seed', + 'seek', + 'segment', + 'select', + 'sell', + 'seminar', + 'senior', + 'sense', + 'sentence', + 'series', + 'service', + 'session', + 'settle', + 'setup', + 'seven', + 'shadow', + 'shaft', + 'shallow', + 'share', + 'shed', + 'shell', + 'sheriff', + 'shield', + 'shift', + 'shine', + 'ship', + 'shiver', + 'shock', + 'shoe', + 'shoot', + 'shop', + 'short', + 'shoulder', + 'shove', + 'shrimp', + 'shrug', + 'shuffle', + 'shy', + 'sibling', + 'sick', + 'side', + 'siege', + 'sight', + 'sign', + 'silent', + 'silk', + 'silly', + 'silver', + 'similar', + 'simple', + 'since', + 'sing', + 'siren', + 'sister', + 'situate', + 'six', + 'size', + 'skate', + 'sketch', + 'ski', + 'skill', + 'skin', + 'skirt', + 'skull', + 'slab', + 'slam', + 'sleep', + 'slender', + 'slice', + 'slide', + 'slight', + 'slim', + 'slogan', + 'slot', + 'slow', + 'slush', + 'small', + 'smart', + 'smile', + 'smoke', + 'smooth', + 'snack', + 'snake', + 'snap', + 'sniff', + 'snow', + 'soap', + 'soccer', + 'social', + 'sock', + 'soda', + 'soft', + 'solar', + 'soldier', + 'solid', + 'solution', + 'solve', + 'someone', + 'song', + 'soon', + 'sorry', + 'sort', + 'soul', + 'sound', + 'soup', + 'source', + 'south', + 'space', + 'spare', + 'spatial', + 'spawn', + 'speak', + 'special', + 'speed', + 'spell', + 'spend', + 'sphere', + 'spice', + 'spider', + 'spike', + 'spin', + 'spirit', + 'split', + 'spoil', + 'sponsor', + 'spoon', + 'sport', + 'spot', + 'spray', + 'spread', + 'spring', + 'spy', + 'square', + 'squeeze', + 'squirrel', + 'stable', + 'stadium', + 'staff', + 'stage', + 'stairs', + 'stamp', + 'stand', + 'start', + 'state', + 'stay', + 'steak', + 'steel', + 'stem', + 'step', + 'stereo', + 'stick', + 'still', + 'sting', + 'stock', + 'stomach', + 'stone', + 'stool', + 'story', + 'stove', + 'strategy', + 'street', + 'strike', + 'strong', + 'struggle', + 'student', + 'stuff', + 'stumble', + 'style', + 'subject', + 'submit', + 'subway', + 'success', + 'such', + 'sudden', + 'suffer', + 'sugar', + 'suggest', + 'suit', + 'summer', + 'sun', + 'sunny', + 'sunset', + 'super', + 'supply', + 'supreme', + 'sure', + 'surface', + 'surge', + 'surprise', + 'surround', + 'survey', + 'suspect', + 'sustain', + 'swallow', + 'swamp', + 'swap', + 'swarm', + 'swear', + 'sweet', + 'swift', + 'swim', + 'swing', + 'switch', + 'sword', + 'symbol', + 'symptom', + 'syrup', + 'system', + 'table', + 'tackle', + 'tag', + 'tail', + 'talent', + 'talk', + 'tank', + 'tape', + 'target', + 'task', + 'taste', + 'tattoo', + 'taxi', + 'teach', + 'team', + 'tell', + 'ten', + 'tenant', + 'tennis', + 'tent', + 'term', + 'test', + 'text', + 'thank', + 'that', + 'theme', + 'then', + 'theory', + 'there', + 'they', + 'thing', + 'this', + 'thought', + 'three', + 'thrive', + 'throw', + 'thumb', + 'thunder', + 'ticket', + 'tide', + 'tiger', + 'tilt', + 'timber', + 'time', + 'tiny', + 'tip', + 'tired', + 'tissue', + 'title', + 'toast', + 'tobacco', + 'today', + 'toddler', + 'toe', + 'together', + 'toilet', + 'token', + 'tomato', + 'tomorrow', + 'tone', + 'tongue', + 'tonight', + 'tool', + 'tooth', + 'top', + 'topic', + 'topple', + 'torch', + 'tornado', + 'tortoise', + 'toss', + 'total', + 'tourist', + 'toward', + 'tower', + 'town', + 'toy', + 'track', + 'trade', + 'traffic', + 'tragic', + 'train', + 'transfer', + 'trap', + 'trash', + 'travel', + 'tray', + 'treat', + 'tree', + 'trend', + 'trial', + 'tribe', + 'trick', + 'trigger', + 'trim', + 'trip', + 'trophy', + 'trouble', + 'truck', + 'true', + 'truly', + 'trumpet', + 'trust', + 'truth', + 'try', + 'tube', + 'tuition', + 'tumble', + 'tuna', + 'tunnel', + 'turkey', + 'turn', + 'turtle', + 'twelve', + 'twenty', + 'twice', + 'twin', + 'twist', + 'two', + 'type', + 'typical', + 'ugly', + 'umbrella', + 'unable', + 'unaware', + 'uncle', + 'uncover', + 'under', + 'undo', + 'unfair', + 'unfold', + 'unhappy', + 'uniform', + 'unique', + 'unit', + 'universe', + 'unknown', + 'unlock', + 'until', + 'unusual', + 'unveil', + 'update', + 'upgrade', + 'uphold', + 'upon', + 'upper', + 'upset', + 'urban', + 'urge', + 'usage', + 'use', + 'used', + 'useful', + 'useless', + 'usual', + 'utility', + 'vacant', + 'vacuum', + 'vague', + 'valid', + 'valley', + 'valve', + 'van', + 'vanish', + 'vapor', + 'various', + 'vast', + 'vault', + 'vehicle', + 'velvet', + 'vendor', + 'venture', + 'venue', + 'verb', + 'verify', + 'version', + 'very', + 'vessel', + 'veteran', + 'viable', + 'vibrant', + 'vicious', + 'victory', + 'video', + 'view', + 'village', + 'vintage', + 'violin', + 'virtual', + 'virus', + 'visa', + 'visit', + 'visual', + 'vital', + 'vivid', + 'vocal', + 'voice', + 'void', + 'volcano', + 'volume', + 'vote', + 'voyage', + 'wage', + 'wagon', + 'wait', + 'walk', + 'wall', + 'walnut', + 'want', + 'warfare', + 'warm', + 'warrior', + 'wash', + 'wasp', + 'waste', + 'water', + 'wave', + 'way', + 'wealth', + 'weapon', + 'wear', + 'weasel', + 'weather', + 'web', + 'wedding', + 'weekend', + 'weird', + 'welcome', + 'west', + 'wet', + 'whale', + 'what', + 'wheat', + 'wheel', + 'when', + 'where', + 'whip', + 'whisper', + 'wide', + 'width', + 'wife', + 'wild', + 'will', + 'win', + 'window', + 'wine', + 'wing', + 'wink', + 'winner', + 'winter', + 'wire', + 'wisdom', + 'wise', + 'wish', + 'witness', + 'wolf', + 'woman', + 'wonder', + 'wood', + 'wool', + 'word', + 'work', + 'world', + 'worry', + 'worth', + 'wrap', + 'wreck', + 'wrestle', + 'wrist', + 'write', + 'wrong', + 'yard', + 'year', + 'yellow', + 'you', + 'young', + 'youth', + 'zebra', + 'zero', + 'zone', + 'zoo' + ]; +} diff --git a/cw_solana/lib/solana_transaction_credentials.dart b/cw_solana/lib/solana_transaction_credentials.dart new file mode 100644 index 000000000..bd0c97f0b --- /dev/null +++ b/cw_solana/lib/solana_transaction_credentials.dart @@ -0,0 +1,12 @@ +import 'package:cw_core/crypto_currency.dart'; +import 'package:cw_core/output_info.dart'; + +class SolanaTransactionCredentials { + SolanaTransactionCredentials( + this.outputs, { + required this.currency, + }); + + final List outputs; + final CryptoCurrency currency; +} diff --git a/cw_solana/lib/solana_transaction_history.dart b/cw_solana/lib/solana_transaction_history.dart new file mode 100644 index 000000000..c03de19ad --- /dev/null +++ b/cw_solana/lib/solana_transaction_history.dart @@ -0,0 +1,78 @@ +import 'dart:convert'; +import 'dart:core'; +import 'package:cw_core/pathForWallet.dart'; +import 'package:cw_core/wallet_info.dart'; +import 'package:cw_solana/file.dart'; +import 'package:cw_solana/solana_transaction_info.dart'; +import 'package:mobx/mobx.dart'; +import 'package:cw_core/transaction_history.dart'; + +part 'solana_transaction_history.g.dart'; + +const transactionsHistoryFileName = 'solana_transactions.json'; + +class SolanaTransactionHistory = SolanaTransactionHistoryBase with _$SolanaTransactionHistory; + +abstract class SolanaTransactionHistoryBase extends TransactionHistoryBase + with Store { + SolanaTransactionHistoryBase({required this.walletInfo, required String password}) + : _password = password { + transactions = ObservableMap(); + } + + final WalletInfo walletInfo; + String _password; + + Future init() async => await _load(); + + @override + Future save() async { + try { + final dirPath = await pathForWalletDir(name: walletInfo.name, type: walletInfo.type); + final path = '$dirPath/$transactionsHistoryFileName'; + final transactionMaps = transactions.map((key, value) => MapEntry(key, value.toJson())); + final data = json.encode({'transactions': transactionMaps}); + await writeData(path: path, password: _password, data: data); + } catch (e, s) { + print('Error while saving solana transaction history: ${e.toString()}'); + print(s); + } + } + + @override + void addOne(SolanaTransactionInfo transaction) => transactions[transaction.id] = transaction; + + @override + void addMany(Map transactions) => + this.transactions.addAll(transactions); + + Future> _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; + } + + Future _load() async { + try { + final content = await _read(); + final txs = content['transactions'] as Map? ?? {}; + + txs.entries.forEach((entry) { + final val = entry.value; + + if (val is Map) { + final tx = SolanaTransactionInfo.fromJson(val); + _update(tx); + } + }); + } catch (e) { + print(e); + } + } + + void _update(SolanaTransactionInfo transaction) => transactions[transaction.id] = transaction; +} diff --git a/cw_solana/lib/solana_transaction_info.dart b/cw_solana/lib/solana_transaction_info.dart new file mode 100644 index 000000000..1b7610e34 --- /dev/null +++ b/cw_solana/lib/solana_transaction_info.dart @@ -0,0 +1,78 @@ +import 'package:cw_core/format_amount.dart'; +import 'package:cw_core/transaction_direction.dart'; +import 'package:cw_core/transaction_info.dart'; + +class SolanaTransactionInfo extends TransactionInfo { + SolanaTransactionInfo({ + required this.id, + required this.blockTime, + required this.to, + required this.from, + required this.direction, + required this.solAmount, + this.tokenSymbol = "SOL", + required this.isPending, + required this.txFee, + }) : amount = solAmount.toInt(); + + final String id; + final String? to; + final String? from; + final int amount; + final bool isPending; + final double solAmount; + final String tokenSymbol; + final DateTime blockTime; + final double txFee; + final TransactionDirection direction; + + String? _fiatAmount; + + @override + DateTime get date => blockTime; + + @override + String amountFormatted() { + String stringBalance = solAmount.toString(); + + if (stringBalance.toString().length >= 6) { + stringBalance = stringBalance.substring(0, 6); + } + return '$stringBalance $tokenSymbol'; + } + + @override + String fiatAmount() => _fiatAmount ?? ''; + + @override + void changeFiatAmount(String amount) => _fiatAmount = formatAmount(amount); + + @override + String feeFormatted() => '${txFee.toString()} SOL'; + + factory SolanaTransactionInfo.fromJson(Map data) { + return SolanaTransactionInfo( + id: data['id'] as String, + solAmount: data['solAmount'], + direction: parseTransactionDirectionFromInt(data['direction'] as int), + blockTime: DateTime.fromMillisecondsSinceEpoch(data['blockTime'] as int), + isPending: data['isPending'] as bool, + tokenSymbol: data['tokenSymbol'] as String, + to: data['to'], + from: data['from'], + txFee: data['txFee'], + ); + } + + Map toJson() => { + 'id': id, + 'solAmount': solAmount, + 'direction': direction.index, + 'blockTime': blockTime.millisecondsSinceEpoch, + 'isPending': isPending, + 'tokenSymbol': tokenSymbol, + 'to': to, + 'from': from, + 'txFee': txFee, + }; +} diff --git a/cw_solana/lib/solana_transaction_model.dart b/cw_solana/lib/solana_transaction_model.dart new file mode 100644 index 000000000..c16c49258 --- /dev/null +++ b/cw_solana/lib/solana_transaction_model.dart @@ -0,0 +1,47 @@ +class SolanaTransactionModel { + final String id; + + final String from; + + final String to; + + final double amount; + + // If this is an outgoing transaction + final bool isOutgoingTx; + + // The Program ID of this transaction, e.g, System Program, Token Program... + final String programId; + + // The DateTime from the UNIX timestamp of the block where the transaction was included + final DateTime blockTime; + + // The Transaction fee + final double fee; + + // The token symbol + final String tokenSymbol; + + SolanaTransactionModel({ + required this.id, + required this.to, + required this.from, + required this.amount, + required this.programId, + required int blockTimeInInt, + this.isOutgoingTx = false, + required this.tokenSymbol, + required this.fee, + }) : blockTime = DateTime.fromMillisecondsSinceEpoch(blockTimeInInt * 1000); + + factory SolanaTransactionModel.fromJson(Map json) => SolanaTransactionModel( + id: json['id'], + blockTimeInInt: int.parse(json["timeStamp"]) * 1000, + from: json["from"], + to: json["to"], + amount: double.parse(json["value"]), + programId: json["programId"], + fee: json['fee'], + tokenSymbol: json['tokenSymbol'], + ); +} diff --git a/cw_solana/lib/solana_wallet.dart b/cw_solana/lib/solana_wallet.dart new file mode 100644 index 000000000..f901a64be --- /dev/null +++ b/cw_solana/lib/solana_wallet.dart @@ -0,0 +1,510 @@ +import 'dart:async'; +import 'dart:convert'; +import 'dart:developer'; +import 'dart:io'; +import 'package:cw_core/cake_hive.dart'; +import 'package:cw_core/crypto_currency.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_solana/default_spl_tokens.dart'; +import 'package:cw_solana/file.dart'; +import 'package:cw_solana/solana_balance.dart'; +import 'package:cw_solana/solana_client.dart'; +import 'package:cw_solana/solana_exceptions.dart'; +import 'package:cw_solana/solana_transaction_credentials.dart'; +import 'package:cw_solana/solana_transaction_history.dart'; +import 'package:cw_solana/solana_transaction_info.dart'; +import 'package:cw_solana/solana_transaction_model.dart'; +import 'package:cw_solana/solana_wallet_addresses.dart'; +import 'package:cw_solana/spl_token.dart'; +import 'package:hex/hex.dart'; +import 'package:hive/hive.dart'; +import 'package:mobx/mobx.dart'; +import 'package:shared_preferences/shared_preferences.dart'; +import 'package:solana/metaplex.dart' as metaplex; +import 'package:solana/solana.dart'; +import 'package:web3dart/crypto.dart'; + +part 'solana_wallet.g.dart'; + +class SolanaWallet = SolanaWalletBase with _$SolanaWallet; + +abstract class SolanaWalletBase + extends WalletBase with Store { + SolanaWalletBase({ + required WalletInfo walletInfo, + String? mnemonic, + String? privateKey, + required String password, + SolanaBalance? initialBalance, + }) : syncStatus = const NotConnectedSyncStatus(), + _password = password, + _mnemonic = mnemonic, + _hexPrivateKey = privateKey, + _client = SolanaWalletClient(), + walletAddresses = SolanaWalletAddresses(walletInfo), + balance = ObservableMap.of( + {CryptoCurrency.sol: initialBalance ?? SolanaBalance(BigInt.zero.toDouble())}), + super(walletInfo) { + this.walletInfo = walletInfo; + transactionHistory = SolanaTransactionHistory(walletInfo: walletInfo, password: password); + + if (!CakeHive.isAdapterRegistered(SPLToken.typeId)) { + CakeHive.registerAdapter(SPLTokenAdapter()); + } + + _sharedPrefs.complete(SharedPreferences.getInstance()); + } + + final String _password; + final String? _mnemonic; + final String? _hexPrivateKey; + + // The Solana WalletPair + Ed25519HDKeyPair? _walletKeyPair; + + Ed25519HDKeyPair? get walletKeyPair => _walletKeyPair; + + // To access the privateKey bytes. + Ed25519HDKeyPairData? _keyPairData; + + late SolanaWalletClient _client; + + Timer? _transactionsUpdateTimer; + + late final Box splTokensBox; + + @override + WalletAddresses walletAddresses; + + @override + @observable + SyncStatus syncStatus; + + @override + @observable + late ObservableMap balance; + + Completer _sharedPrefs = Completer(); + + @override + Ed25519HDKeyPairData get keys { + if (_keyPairData == null) { + return Ed25519HDKeyPairData([], publicKey: const Ed25519HDPublicKey([])); + } + + return _keyPairData!; + } + + @override + String? get seed => _mnemonic; + + @override + String get privateKey => HEX.encode(_keyPairData!.bytes); + + Future init() async { + final boxName = "${walletInfo.name.replaceAll(" ", "_")}_${SPLToken.boxName}"; + + splTokensBox = await CakeHive.openBox(boxName); + + // Create WalletPair using either the mnemonic or the privateKey + _walletKeyPair = await getWalletPair( + mnemonic: _mnemonic, + privateKey: _hexPrivateKey, + ); + + // Extract the keyPairData containing both the privateKey bytes and the publicKey hex. + _keyPairData = await _walletKeyPair!.extract(); + + walletInfo.address = _walletKeyPair!.address; + + await walletAddresses.init(); + await transactionHistory.init(); + await save(); + } + + Future getWalletPair({String? mnemonic, String? privateKey}) async { + assert(mnemonic != null || privateKey != null); + + if (privateKey != null) { + final privateKeyBytes = hexToBytes(privateKey); + return await Wallet.fromPrivateKeyBytes(privateKey: privateKeyBytes); + } + + return Wallet.fromMnemonic(mnemonic!, account: 0, change: 0); + } + + @override + int calculateEstimatedFee(TransactionPriority priority, int? amount) => 0; + + @override + Future changePassword(String password) => throw UnimplementedError("changePassword"); + + @override + void close() { + _client.stop(); + _transactionsUpdateTimer?.cancel(); + } + + @action + @override + Future connectToNode({required Node node}) async { + try { + syncStatus = ConnectingSyncStatus(); + + final isConnected = _client.connect(node); + + if (!isConnected) { + throw Exception("Solana Node connection failed"); + } + + try { + await Future.wait([ + _updateBalance(), + _updateNativeSOLTransactions(), + _updateSPLTokenTransactions(), + ]); + } catch (e) { + log(e.toString()); + } + + _setTransactionUpdateTimer(); + + syncStatus = ConnectedSyncStatus(); + } catch (e) { + syncStatus = FailedSyncStatus(); + } + } + + @override + Future createTransaction(Object credentials) async { + final solCredentials = credentials as SolanaTransactionCredentials; + + final outputs = solCredentials.outputs; + + final hasMultiDestination = outputs.length > 1; + + await _updateBalance(); + + final CryptoCurrency transactionCurrency = + balance.keys.firstWhere((element) => element.title == solCredentials.currency.title); + + final walletBalanceForCurrency = balance[transactionCurrency]!.balance; + + double totalAmount = 0.0; + + if (hasMultiDestination) { + if (outputs.any((item) => item.sendAll || (item.formattedCryptoAmount ?? 0) <= 0)) { + throw SolanaTransactionWrongBalanceException(transactionCurrency); + } + + final totalAmountFromCredentials = + outputs.fold(0, (acc, value) => acc + (value.formattedCryptoAmount ?? 0)); + + totalAmount = totalAmountFromCredentials.toDouble(); + + if (walletBalanceForCurrency < totalAmount) { + throw SolanaTransactionWrongBalanceException(transactionCurrency); + } + } else { + final output = outputs.first; + + final totalOriginalAmount = double.parse(output.cryptoAmount ?? '0.0'); + + totalAmount = output.sendAll ? walletBalanceForCurrency : totalOriginalAmount; + + if (walletBalanceForCurrency < totalAmount) { + throw SolanaTransactionWrongBalanceException(transactionCurrency); + } + } + + String? tokenMint; + // Token Mint is only needed for transactions that are not native tokens(non-SOL transactions) + if (transactionCurrency.title != CryptoCurrency.sol.title) { + tokenMint = (transactionCurrency as SPLToken).mintAddress; + } + + final pendingSolanaTransaction = await _client.signSolanaTransaction( + tokenMint: tokenMint, + tokenTitle: transactionCurrency.title, + inputAmount: totalAmount, + ownerKeypair: _walletKeyPair!, + tokenDecimals: transactionCurrency.decimals, + destinationAddress: solCredentials.outputs.first.isParsedAddress + ? solCredentials.outputs.first.extractedAddress! + : solCredentials.outputs.first.address, + ); + + return pendingSolanaTransaction; + } + + @override + Future> fetchTransactions() async => {}; + + /// Fetches the native SOL transactions linked to the wallet Public Key + Future _updateNativeSOLTransactions() async { + final address = Ed25519HDPublicKey.fromBase58(_walletKeyPair!.address); + + final transactions = await _client.fetchTransactions(address); + + final Map result = {}; + + for (var transactionModel in transactions) { + result[transactionModel.id] = SolanaTransactionInfo( + id: transactionModel.id, + to: transactionModel.to, + from: transactionModel.from, + blockTime: transactionModel.blockTime, + direction: transactionModel.isOutgoingTx + ? TransactionDirection.outgoing + : TransactionDirection.incoming, + solAmount: transactionModel.amount, + isPending: false, + txFee: transactionModel.fee, + tokenSymbol: transactionModel.tokenSymbol, + ); + } + + transactionHistory.addMany(result); + + await transactionHistory.save(); + } + + /// Fetches the SPL Tokens transactions linked to the token account Public Key + Future _updateSPLTokenTransactions() async { + List splTokenTransactions = []; + + for (var token in balance.keys) { + if (token is SPLToken) { + final tokenTxs = await _client.getSPLTokenTransfers( + token.mintAddress, + token.symbol, + token.decimal, + _walletKeyPair!, + ); + + splTokenTransactions.addAll(tokenTxs); + } + } + + final Map result = {}; + + for (var transactionModel in splTokenTransactions) { + result[transactionModel.id] = SolanaTransactionInfo( + id: transactionModel.id, + to: transactionModel.to, + from: transactionModel.from, + blockTime: transactionModel.blockTime, + direction: transactionModel.isOutgoingTx + ? TransactionDirection.outgoing + : TransactionDirection.incoming, + solAmount: transactionModel.amount, + isPending: false, + txFee: transactionModel.fee, + tokenSymbol: transactionModel.tokenSymbol, + ); + } + + transactionHistory.addMany(result); + + await transactionHistory.save(); + } + + @override + Future rescan({required int height}) => throw UnimplementedError("rescan"); + + @override + Future save() async { + await walletAddresses.updateAddressesInBox(); + final path = await makePath(); + await write(path: path, password: _password, data: toJSON()); + await transactionHistory.save(); + } + + @action + @override + Future startSync() async { + try { + syncStatus = AttemptingSyncStatus(); + + await Future.wait([ + _updateBalance(), + _updateNativeSOLTransactions(), + _updateSPLTokenTransactions(), + ]); + + syncStatus = SyncedSyncStatus(); + } catch (e) { + syncStatus = FailedSyncStatus(); + } + } + + Future makePath() async => pathForWallet(name: walletInfo.name, type: walletInfo.type); + + String toJSON() => json.encode({ + 'mnemonic': _mnemonic, + 'private_key': privateKey, + 'balance': balance[currency]!.toJSON(), + }); + + static Future 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 = SolanaBalance.fromJSON(data['balance'] as String) ?? SolanaBalance(0.0); + + return SolanaWallet( + walletInfo: walletInfo, + password: password, + mnemonic: mnemonic, + privateKey: privateKey, + initialBalance: balance, + ); + } + + Future _updateBalance() async { + balance[currency] = await _fetchSOLBalance(); + await _fetchSPLTokensBalances(); + await save(); + } + + Future _fetchSOLBalance() async { + final balance = await _client.getBalance(_walletKeyPair!.address); + + return SolanaBalance(balance); + } + + Future _fetchSPLTokensBalances() async { + for (var token in splTokensBox.values) { + if (token.enabled) { + try { + final tokenBalance = + await _client.getSplTokenBalance(token.mintAddress, _walletKeyPair!.address) ?? + balance[token] ?? + SolanaBalance(0.0); + balance[token] = tokenBalance; + } catch (e) { + print('Error fetching spl token (${token.symbol}) balance ${e.toString()}'); + } + } else { + balance.remove(token); + } + } + } + + @override + Future? updateBalance() async => await _updateBalance(); + + List get splTokenCurrencies => splTokensBox.values.toList(); + + void addInitialTokens() { + final initialSPLTokens = DefaultSPLTokens().initialSPLTokens; + + for (var token in initialSPLTokens) { + splTokensBox.put(token.mintAddress, token); + } + } + + Future addSPLToken(SPLToken token) async { + await splTokensBox.put(token.mintAddress, token); + + if (token.enabled) { + final tokenBalance = + await _client.getSplTokenBalance(token.mintAddress, _walletKeyPair!.address) ?? + balance[token] ?? + SolanaBalance(0.0); + + balance[token] = tokenBalance; + } else { + balance.remove(token); + } + } + + Future deleteSPLToken(SPLToken token) async { + await token.delete(); + + balance.remove(token); + _updateBalance(); + } + + Future getSPLToken(String mintAddress) async { + // Convert SPL token mint address to public key + final mintPublicKey = Ed25519HDPublicKey.fromBase58(mintAddress); + + // Fetch token's metadata account + final token = await solanaClient!.rpcClient.getMetadata(mint: mintPublicKey); + + if (token == null) { + return null; + } + + return SPLToken.fromMetadata( + name: token.name, + mint: token.mint, + symbol: token.symbol, + mintAddress: mintAddress, + ); + } + + @override + Future 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(const Duration(seconds: 20), (_) { + _updateSPLTokenTransactions(); + _updateNativeSOLTransactions(); + _updateBalance(); + }); + } + + Future signSolanaMessage(String message) async { + // Convert the message to bytes + final messageBytes = utf8.encode(message); + + // Sign the message bytes with the wallet's private key + final signature = await _walletKeyPair!.sign(messageBytes); + + // Convert the signature to a hexadecimal string + final hex = bytesToHex(signature.bytes); + + return hex; + } + + SolanaClient? get solanaClient => _client.getSolanaClient; +} diff --git a/cw_solana/lib/solana_wallet_addresses.dart b/cw_solana/lib/solana_wallet_addresses.dart new file mode 100644 index 000000000..97a76fb99 --- /dev/null +++ b/cw_solana/lib/solana_wallet_addresses.dart @@ -0,0 +1,33 @@ +import 'package:cw_core/wallet_addresses.dart'; +import 'package:cw_core/wallet_info.dart'; +import 'package:mobx/mobx.dart'; + +part 'solana_wallet_addresses.g.dart'; + +class SolanaWalletAddresses = SolanaWalletAddressesBase with _$SolanaWalletAddresses; + +abstract class SolanaWalletAddressesBase extends WalletAddresses with Store { + SolanaWalletAddressesBase(WalletInfo walletInfo) + : address = '', + super(walletInfo); + + @override + String address; + + @override + Future init() async { + address = walletInfo.address; + await updateAddressesInBox(); + } + + @override + Future updateAddressesInBox() async { + try { + addressesMap.clear(); + addressesMap[address] = ''; + await saveAddressesInBox(); + } catch (e) { + print(e.toString()); + } + } +} diff --git a/cw_solana/lib/solana_wallet_creation_credentials.dart b/cw_solana/lib/solana_wallet_creation_credentials.dart new file mode 100644 index 000000000..881c30abd --- /dev/null +++ b/cw_solana/lib/solana_wallet_creation_credentials.dart @@ -0,0 +1,29 @@ +import 'package:cw_core/wallet_credentials.dart'; +import 'package:cw_core/wallet_info.dart'; + +class SolanaNewWalletCredentials extends WalletCredentials { + SolanaNewWalletCredentials({required String name, WalletInfo? walletInfo}) + : super(name: name, walletInfo: walletInfo); +} + +class SolanaRestoreWalletFromSeedCredentials extends WalletCredentials { + SolanaRestoreWalletFromSeedCredentials( + {required String name, + required String password, + required this.mnemonic, + WalletInfo? walletInfo}) + : super(name: name, password: password, walletInfo: walletInfo); + + final String mnemonic; +} + +class SolanaRestoreWalletFromPrivateKey extends WalletCredentials { + SolanaRestoreWalletFromPrivateKey( + {required String name, + required String password, + required this.privateKey, + WalletInfo? walletInfo}) + : super(name: name, password: password, walletInfo: walletInfo); + + final String privateKey; +} diff --git a/cw_solana/lib/solana_wallet_service.dart b/cw_solana/lib/solana_wallet_service.dart new file mode 100644 index 000000000..8abf1ffbb --- /dev/null +++ b/cw_solana/lib/solana_wallet_service.dart @@ -0,0 +1,118 @@ +import 'dart:io'; + +import 'package:bip39/bip39.dart' as bip39; +import 'package:collection/collection.dart'; +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_solana/solana_mnemonics.dart'; +import 'package:cw_solana/solana_wallet.dart'; +import 'package:cw_solana/solana_wallet_creation_credentials.dart'; +import 'package:hive/hive.dart'; + +class SolanaWalletService extends WalletService { + SolanaWalletService(this.walletInfoSource); + + final Box walletInfoSource; + + @override + Future create(SolanaNewWalletCredentials credentials) async { + final strength = credentials.seedPhraseLength == 24 ? 256 : 128; + + final mnemonic = bip39.generateMnemonic(strength: strength); + + final wallet = SolanaWallet( + walletInfo: credentials.walletInfo!, + mnemonic: mnemonic, + password: credentials.password!, + ); + + await wallet.init(); + wallet.addInitialTokens(); + return wallet; + } + + @override + WalletType getType() => WalletType.solana; + + @override + Future isWalletExit(String name) async => + File(await pathForWallet(name: name, type: getType())).existsSync(); + + @override + Future openWallet(String name, String password) async { + final walletInfo = + walletInfoSource.values.firstWhere((info) => info.id == WalletBase.idFor(name, getType())); + final wallet = await SolanaWalletBase.open( + name: name, + password: password, + walletInfo: walletInfo, + ); + + await wallet.init(); + await wallet.save(); + + return wallet; + } + + @override + Future 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 restoreFromKeys(SolanaRestoreWalletFromPrivateKey credentials) async { + final wallet = SolanaWallet( + password: credentials.password!, + privateKey: credentials.privateKey, + walletInfo: credentials.walletInfo!, + ); + + await wallet.init(); + wallet.addInitialTokens(); + await wallet.save(); + + return wallet; + } + + @override + Future restoreFromSeed(SolanaRestoreWalletFromSeedCredentials credentials) async { + if (!bip39.validateMnemonic(credentials.mnemonic)) { + throw SolanaMnemonicIsIncorrectException(); + } + + final wallet = SolanaWallet( + password: credentials.password!, + mnemonic: credentials.mnemonic, + walletInfo: credentials.walletInfo!, + ); + + await wallet.init(); + wallet.addInitialTokens(); + await wallet.save(); + + return wallet; + } + + @override + Future rename(String currentName, String password, String newName) async { + final currentWalletInfo = walletInfoSource.values + .firstWhere((info) => info.id == WalletBase.idFor(currentName, getType())); + final currentWallet = await SolanaWalletBase.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); + } +} diff --git a/cw_solana/lib/spl_token.dart b/cw_solana/lib/spl_token.dart new file mode 100644 index 000000000..0413990b1 --- /dev/null +++ b/cw_solana/lib/spl_token.dart @@ -0,0 +1,146 @@ +import 'package:cw_core/crypto_currency.dart'; +import 'package:cw_core/hive_type_ids.dart'; +import 'package:hive/hive.dart'; +import 'package:solana/metaplex.dart'; + +part 'spl_token.g.dart'; + +@HiveType(typeId: SPLToken.typeId) +class SPLToken extends CryptoCurrency with HiveObjectMixin { + @HiveField(0) + final String name; + + @HiveField(1) + final String symbol; + + @HiveField(2) + final String mintAddress; + + @HiveField(3) + final int decimal; + + @HiveField(4, defaultValue: false) + bool _enabled; + + @HiveField(5) + final String mint; + + @HiveField(6) + final String? iconPath; + + @HiveField(7) + final String? tag; + + SPLToken({ + required this.name, + required this.symbol, + required this.mintAddress, + required this.decimal, + required this.mint, + this.iconPath, + this.tag = 'SOL', + bool enabled = false, + }) : _enabled = enabled, + super( + name: mint.toLowerCase(), + title: symbol.toUpperCase(), + fullName: name, + tag: tag, + iconPath: iconPath, + decimals: decimal, + ); + + factory SPLToken.fromMetadata({ + required String name, + required String mint, + required String symbol, + required String mintAddress, + }) { + return SPLToken( + name: name, + symbol: symbol, + mintAddress: mintAddress, + decimal: 0, + mint: mint, + iconPath: '', + ); + } + + factory SPLToken.cryptoCurrency({ + required String name, + required String symbol, + required int decimals, + required String iconPath, + required String mint, + }) { + return SPLToken( + name: name, + symbol: symbol, + decimal: decimals, + mint: mint, + iconPath: iconPath, + mintAddress: '', + ); + } + + bool get enabled => _enabled; + + set enabled(bool value) => _enabled = value; + + SPLToken.copyWith(SPLToken other, String? icon, String? tag) + : name = other.name, + symbol = other.symbol, + mintAddress = other.mintAddress, + decimal = other.decimal, + _enabled = other.enabled, + mint = other.mint, + tag = other.tag, + iconPath = icon, + super( + title: other.symbol.toUpperCase(), + name: other.symbol.toLowerCase(), + decimals: other.decimal, + fullName: other.name, + tag: other.tag, + iconPath: icon, + ); + + static const typeId = SPL_TOKEN_TYPE_ID; + static const boxName = 'SPLTokens'; + + @override + bool operator ==(other) => + (other is SPLToken && other.mintAddress == mintAddress) || + (other is CryptoCurrency && other.title == title); + + @override + int get hashCode => mintAddress.hashCode; +} + +class NFT extends SPLToken { + final ImageInfo? imageInfo; + + NFT( + String mint, + String name, + String symbol, + String mintAddress, + int decimal, + String iconPath, + this.imageInfo, + ) : super( + name: name, + symbol: symbol, + mintAddress: mintAddress, + decimal: decimal, + mint: mint, + iconPath: iconPath, + ); +} + +class ImageInfo { + final String uri; + final OffChainMetadata? data; + + const ImageInfo(this.uri, this.data); +} diff --git a/cw_solana/pubspec.yaml b/cw_solana/pubspec.yaml new file mode 100644 index 000000000..c98b7492e --- /dev/null +++ b/cw_solana/pubspec.yaml @@ -0,0 +1,37 @@ +name: cw_solana +description: A new Flutter package project. +version: 0.0.1 +publish_to: none +homepage: https://cakewallet.com + +environment: + sdk: '>=3.0.6 <4.0.0' + flutter: ">=1.17.0" + +dependencies: + flutter: + sdk: flutter + solana: ^0.30.1 + cw_core: + path: ../cw_core + http: ^1.1.0 + hive: ^2.2.3 + bip39: ^1.0.6 + mobx: ^2.3.0+1 + shared_preferences: ^2.0.15 + web3dart: ^2.7.1 + bip32: ^2.0.0 + hex: ^0.2.0 + +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 + +flutter: + # assets: + # - images/a_dot_burr.jpeg + # - images/a_dot_ham.jpeg \ No newline at end of file diff --git a/cw_solana/test/cw_solana_test.dart b/cw_solana/test/cw_solana_test.dart new file mode 100644 index 000000000..42a5d8bdf --- /dev/null +++ b/cw_solana/test/cw_solana_test.dart @@ -0,0 +1,12 @@ +import 'package:flutter_test/flutter_test.dart'; + +import 'package:cw_solana/cw_solana.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); + }); +} diff --git a/ios/Runner/InfoBase.plist b/ios/Runner/InfoBase.plist index dde5dc3e2..a755754e3 100644 --- a/ios/Runner/InfoBase.plist +++ b/ios/Runner/InfoBase.plist @@ -200,6 +200,16 @@ polygon-wallet + + CFBundleTypeRole + Viewer + CFBundleURLName + solana-wallet + CFBundleURLSchemes + + solana-wallet + + CFBundleVersion $(CURRENT_PROJECT_VERSION) diff --git a/lib/core/address_validator.dart b/lib/core/address_validator.dart index 2ae9e3297..21f3c3557 100644 --- a/lib/core/address_validator.dart +++ b/lib/core/address_validator.dart @@ -1,6 +1,7 @@ import 'package:bitcoin_flutter/bitcoin_flutter.dart' as bitcoin; import 'package:cake_wallet/generated/i18n.dart'; import 'package:cake_wallet/core/validator.dart'; +import 'package:cake_wallet/solana/solana.dart'; import 'package:cw_core/crypto_currency.dart'; import 'package:cw_core/erc20_token.dart'; @@ -8,9 +9,7 @@ class AddressValidator extends TextValidator { AddressValidator({required CryptoCurrency type}) : super( errorMessage: S.current.error_text_address, - useAdditionalValidation: type == CryptoCurrency.btc - ? bitcoin.Address.validateAddress - : null, + useAdditionalValidation: type == CryptoCurrency.btc ? bitcoin.Address.validateAddress : null, pattern: getPattern(type), length: getLength(type)); @@ -130,6 +129,12 @@ class AddressValidator extends TextValidator { if (type is Erc20Token) { return [42]; } + + if (solana != null) { + final length = solana!.getValidationLength(type); + if (length != null) return length; + } + switch (type) { case CryptoCurrency.xmr: return null; @@ -192,11 +197,11 @@ class AddressValidator extends TextValidator { case CryptoCurrency.sc: return [76]; case CryptoCurrency.sol: + case CryptoCurrency.usdtSol: + case CryptoCurrency.usdcsol: return [32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44]; case CryptoCurrency.trx: return [34]; - case CryptoCurrency.usdcsol: - return [32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44]; case CryptoCurrency.usdt: return [34]; case CryptoCurrency.usdttrc20: @@ -286,6 +291,8 @@ class AddressValidator extends TextValidator { '|bitcoincash:q[0-9a-zA-Z]{42}([^0-9a-zA-Z]|\$)' '|([^0-9a-zA-Z]|^)q[0-9a-zA-Z]{41}([^0-9a-zA-Z]|\$)' '|([^0-9a-zA-Z]|^)q[0-9a-zA-Z]{42}([^0-9a-zA-Z]|\$)'; + case CryptoCurrency.sol: + return '([^0-9a-zA-Z]|^)[1-9A-HJ-NP-Za-km-z]{43,44}([^0-9a-zA-Z]|\$)'; default: return null; } diff --git a/lib/core/seed_validator.dart b/lib/core/seed_validator.dart index c77bfc08a..986e832ef 100644 --- a/lib/core/seed_validator.dart +++ b/lib/core/seed_validator.dart @@ -4,6 +4,7 @@ import 'package:cake_wallet/haven/haven.dart'; import 'package:cake_wallet/core/validator.dart'; import 'package:cake_wallet/entities/mnemonic_item.dart'; import 'package:cake_wallet/polygon/polygon.dart'; +import 'package:cake_wallet/solana/solana.dart'; import 'package:cw_core/wallet_type.dart'; import 'package:cake_wallet/monero/monero.dart'; import 'package:cake_wallet/nano/nano.dart'; @@ -37,6 +38,8 @@ class SeedValidator extends Validator { return nano!.getNanoWordList(language); case WalletType.polygon: return polygon!.getPolygonWordList(language); + case WalletType.solana: + return solana!.getSolanaWordList(language); default: return []; } diff --git a/lib/core/wallet_connect/chain_service.dart b/lib/core/wallet_connect/chain_service/chain_service.dart similarity index 100% rename from lib/core/wallet_connect/chain_service.dart rename to lib/core/wallet_connect/chain_service/chain_service.dart diff --git a/lib/core/wallet_connect/evm_chain_id.dart b/lib/core/wallet_connect/chain_service/eth/evm_chain_id.dart similarity index 86% rename from lib/core/wallet_connect/evm_chain_id.dart rename to lib/core/wallet_connect/chain_service/eth/evm_chain_id.dart index b71fb562e..0be21b1b2 100644 --- a/lib/core/wallet_connect/evm_chain_id.dart +++ b/lib/core/wallet_connect/chain_service/eth/evm_chain_id.dart @@ -1,4 +1,4 @@ -import 'package:cake_wallet/core/wallet_connect/evm_chain_service.dart'; +import 'package:cake_wallet/core/wallet_connect/chain_service/eth/evm_chain_service.dart'; enum EVMChainId { ethereum, diff --git a/lib/core/wallet_connect/evm_chain_service.dart b/lib/core/wallet_connect/chain_service/eth/evm_chain_service.dart similarity index 98% rename from lib/core/wallet_connect/evm_chain_service.dart rename to lib/core/wallet_connect/chain_service/eth/evm_chain_service.dart index 74bff7479..6f3c8fa98 100644 --- a/lib/core/wallet_connect/evm_chain_service.dart +++ b/lib/core/wallet_connect/chain_service/eth/evm_chain_service.dart @@ -3,7 +3,7 @@ import 'dart:developer'; import 'dart:typed_data'; import 'package:cake_wallet/core/wallet_connect/eth_transaction_model.dart'; -import 'package:cake_wallet/core/wallet_connect/evm_chain_id.dart'; +import 'package:cake_wallet/core/wallet_connect/chain_service/eth/evm_chain_id.dart'; import 'package:cake_wallet/core/wallet_connect/wc_bottom_sheet_service.dart'; import 'package:cake_wallet/generated/i18n.dart'; import 'package:cake_wallet/reactions/wallet_connect.dart'; @@ -20,8 +20,8 @@ import 'package:eth_sig_util/util/utils.dart'; import 'package:http/http.dart' as http; import 'package:walletconnect_flutter_v2/walletconnect_flutter_v2.dart'; import 'package:web3dart/web3dart.dart'; -import 'chain_service.dart'; -import 'wallet_connect_key_service.dart'; +import '../chain_service.dart'; +import '../../wallet_connect_key_service.dart'; class EvmChainServiceImpl implements ChainService { final AppStore appStore; diff --git a/lib/core/wallet_connect/chain_service/solana/entities/solana_sign_message.dart b/lib/core/wallet_connect/chain_service/solana/entities/solana_sign_message.dart new file mode 100644 index 000000000..e462adbb5 --- /dev/null +++ b/lib/core/wallet_connect/chain_service/solana/entities/solana_sign_message.dart @@ -0,0 +1,28 @@ +class SolanaSignMessage { + final String pubkey; + final String message; + + SolanaSignMessage({ + required this.pubkey, + required this.message, + }); + + factory SolanaSignMessage.fromJson(Map json) { + return SolanaSignMessage( + pubkey: json['pubkey'] as String, + message: json['message'] as String, + ); + } + + Map toJson() { + return { + 'pubkey': pubkey, + 'message': message, + }; + } + + @override + String toString() { + return 'SolanaSignMessage(pubkey: $pubkey, message: $message)'; + } +} diff --git a/lib/core/wallet_connect/chain_service/solana/entities/solana_sign_transaction.dart b/lib/core/wallet_connect/chain_service/solana/entities/solana_sign_transaction.dart new file mode 100644 index 000000000..2cdf4697e --- /dev/null +++ b/lib/core/wallet_connect/chain_service/solana/entities/solana_sign_transaction.dart @@ -0,0 +1,106 @@ +class SolanaSignTransaction { + final String? feePayer; + final String? recentBlockhash; + final String transaction; + final List? instructions; + + SolanaSignTransaction({ + required this.feePayer, + required this.recentBlockhash, + required this.instructions, + required this.transaction, + }); + + factory SolanaSignTransaction.fromJson(Map json) { + return SolanaSignTransaction( + feePayer:json['feePayer'] !=null ? json['feePayer'] as String: null, + recentBlockhash: json['recentBlockhash']!=null? json['recentBlockhash'] as String: null, + instructions:json['instructions']!=null? (json['instructions'] as List) + .map((e) => SolanaInstruction.fromJson(e as Map)) + .toList(): null, + transaction: json['transaction'] as String, + ); + } + + Map toJson() { + return { + 'feePayer': feePayer, + 'recentBlockhash': recentBlockhash, + 'instructions': instructions, + 'transaction': transaction, + }; + } + + @override + String toString() { + return 'SolanaSignTransaction(feePayer: $feePayer, recentBlockhash: $recentBlockhash, instructions: $instructions, transaction: $transaction)'; + } +} + +class SolanaInstruction { + final String programId; + final List keys; + final List data; + + SolanaInstruction({ + required this.programId, + required this.keys, + required this.data, + }); + + factory SolanaInstruction.fromJson(Map json) { + return SolanaInstruction( + programId: json['programId'] as String, + keys: (json['keys'] as List) + .map((e) => SolanaKeyMetadata.fromJson(e as Map)) + .toList(), + data: (json['data'] as List).map((e) => e as int).toList(), + ); + } + + Map toJson() { + return { + 'programId': programId, + 'keys': keys, + 'data': data, + }; + } + + @override + String toString() { + return 'SolanaInstruction(programId: $programId, keys: $keys, data: $data)'; + } +} + +class SolanaKeyMetadata { + final String pubkey; + final bool isSigner; + final bool isWritable; + + SolanaKeyMetadata({ + required this.pubkey, + required this.isSigner, + required this.isWritable, + }); + + factory SolanaKeyMetadata.fromJson(Map json) { + return SolanaKeyMetadata( + pubkey: json['pubkey'] as String, + isSigner: json['isSigner'] as bool, + isWritable: json['isWritable'] as bool, + ); + } + + Map toJson() { + return { + 'pubkey': pubkey, + 'isSigner': isSigner, + 'isWritable': isWritable, + }; + } + + @override + String toString() { + return 'SolanaKeyMetadata(pubkey: $pubkey, isSigner: $isSigner, isWritable: $isWritable)'; + } +} diff --git a/lib/core/wallet_connect/chain_service/solana/solana_chain_id.dart b/lib/core/wallet_connect/chain_service/solana/solana_chain_id.dart new file mode 100644 index 000000000..bdc8a7d20 --- /dev/null +++ b/lib/core/wallet_connect/chain_service/solana/solana_chain_id.dart @@ -0,0 +1,27 @@ +import 'solana_chain_service.dart'; + +enum SolanaChainId { + mainnet, + testnet, + devnet, +} + +extension SolanaChainIdX on SolanaChainId { + String chain() { + String name = ''; + + switch (this) { + case SolanaChainId.mainnet: + name = '4sGjMW1sUnHzSxGspuhpqLDx6wiyjNtZ'; + break; + case SolanaChainId.testnet: + name = '8E9rvCKLFQia2Y35HXjjpWzj8weVo44K'; + break; + case SolanaChainId.devnet: + name = ''; + break; + } + + return '${SolanaChainServiceImpl.namespace}:$name'; + } +} diff --git a/lib/core/wallet_connect/chain_service/solana/solana_chain_service.dart b/lib/core/wallet_connect/chain_service/solana/solana_chain_service.dart new file mode 100644 index 000000000..f5c696be6 --- /dev/null +++ b/lib/core/wallet_connect/chain_service/solana/solana_chain_service.dart @@ -0,0 +1,177 @@ +import 'dart:developer'; + +import 'package:cake_wallet/core/wallet_connect/chain_service/solana/entities/solana_sign_message.dart'; +import 'package:cake_wallet/core/wallet_connect/chain_service/solana/solana_chain_id.dart'; +import 'package:cake_wallet/core/wallet_connect/wc_bottom_sheet_service.dart'; +import 'package:cake_wallet/generated/i18n.dart'; +import 'package:cake_wallet/src/screens/wallet_connect/widgets/message_display_widget.dart'; +import 'package:cake_wallet/core/wallet_connect/models/connection_model.dart'; +import 'package:cake_wallet/src/screens/wallet_connect/widgets/connection_widget.dart'; +import 'package:cake_wallet/src/screens/wallet_connect/widgets/modals/web3_request_modal.dart'; +import 'package:solana/base58.dart'; +import 'package:solana/solana.dart'; +import 'package:walletconnect_flutter_v2/walletconnect_flutter_v2.dart'; +import '../chain_service.dart'; +import '../../wallet_connect_key_service.dart'; +import 'entities/solana_sign_transaction.dart'; + +class SolanaChainServiceImpl implements ChainService { + final BottomSheetService bottomSheetService; + final Web3Wallet wallet; + final WalletConnectKeyService wcKeyService; + + static const namespace = 'solana'; + static const solSignTransaction = 'solana_signTransaction'; + static const solSignMessage = 'solana_signMessage'; + + final SolanaChainId reference; + + final SolanaClient solanaClient; + + final Ed25519HDKeyPair? ownerKeyPair; + + SolanaChainServiceImpl({ + required this.reference, + required this.wcKeyService, + required this.bottomSheetService, + required this.wallet, + required this.ownerKeyPair, + required String webSocketUrl, + required Uri rpcUrl, + SolanaClient? solanaClient, + }) : solanaClient = solanaClient ?? + SolanaClient( + rpcUrl: rpcUrl, + websocketUrl: Uri.parse(webSocketUrl), + timeout: const Duration(minutes: 2), + ) { + for (final String event in getEvents()) { + wallet.registerEventEmitter(chainId: getChainId(), event: event); + } + wallet.registerRequestHandler( + chainId: getChainId(), + method: solSignTransaction, + handler: solanaSignTransaction, + ); + wallet.registerRequestHandler( + chainId: getChainId(), + method: solSignMessage, + handler: solanaSignMessage, + ); + } + + @override + String getNamespace() { + return namespace; + } + + @override + String getChainId() { + return reference.chain(); + } + + @override + List getEvents() { + return ['']; + } + + Future requestAuthorization(String? text) async { + // Show the bottom sheet + final bool? isApproved = await bottomSheetService.queueBottomSheet( + widget: Web3RequestModal( + child: ConnectionWidget( + title: S.current.signTransaction, + info: [ + ConnectionModel( + text: text, + ), + ], + ), + ), + ) as bool?; + + if (isApproved != null && isApproved == false) { + return 'User rejected signature'; + } + + return null; + } + + Future solanaSignTransaction(String topic, dynamic parameters) async { + log('received solana sign transaction request $parameters'); + + final solanaSignTx = + SolanaSignTransaction.fromJson(parameters as Map); + + final String? authError = await requestAuthorization('Confirm request to sign transaction?'); + + if (authError != null) { + return authError; + } + + try { + final message = + await solanaClient.rpcClient.getMessageFromEncodedTx(solanaSignTx.transaction); + + final sign = await ownerKeyPair?.signMessage( + message: message, + recentBlockhash: solanaSignTx.recentBlockhash ?? '', + ); + + if (sign == null) { + return ''; + } + + String signature = sign.signatures.first.toBase58(); + + print(signature); + print(signature.runtimeType); + + bottomSheetService.queueBottomSheet( + isModalDismissible: true, + widget: BottomSheetMessageDisplayWidget( + message: S.current.awaitDAppProcessing, + isError: false, + ), + ); + + return signature; + } catch (e) { + log('An error has occurred while signing transaction: ${e.toString()}'); + bottomSheetService.queueBottomSheet( + isModalDismissible: true, + widget: BottomSheetMessageDisplayWidget( + message: '${S.current.errorSigningTransaction}: ${e.toString()}', + ), + ); + return 'Failed'; + } + } + + Future solanaSignMessage(String topic, dynamic parameters) async { + log('received solana sign message request: $parameters'); + + final solanaSignMessage = SolanaSignMessage.fromJson(parameters as Map); + + final String? authError = await requestAuthorization('Confirm request to sign message?'); + + if (authError != null) { + return authError; + } + Signature? sign; + + try { + sign = await ownerKeyPair?.sign(base58decode(solanaSignMessage.message)); + } catch (e) { + print(e); + } + + if (sign == null) { + return ''; + } + + String signature = sign.toBase58(); + + return signature; + } +} diff --git a/lib/core/wallet_connect/wallet_connect_key_service.dart b/lib/core/wallet_connect/wallet_connect_key_service.dart index 33d721073..f05adad97 100644 --- a/lib/core/wallet_connect/wallet_connect_key_service.dart +++ b/lib/core/wallet_connect/wallet_connect_key_service.dart @@ -2,6 +2,7 @@ import 'package:cake_wallet/ethereum/ethereum.dart'; import 'package:cake_wallet/core/wallet_connect/models/chain_key_model.dart'; import 'package:cake_wallet/polygon/polygon.dart'; import 'package:cake_wallet/reactions/wallet_connect.dart'; +import 'package:cake_wallet/solana/solana.dart'; import 'package:cw_core/wallet_base.dart'; import 'package:cw_core/wallet_type.dart'; @@ -13,7 +14,6 @@ abstract class WalletConnectKeyService { /// If the chain is not found, returns an empty list. /// - [chain]: The chain to get the keys for. List getKeysForChain(WalletBase wallet); - } class KeyServiceImpl implements WalletConnectKeyService { @@ -23,6 +23,8 @@ class KeyServiceImpl implements WalletConnectKeyService { return ethereum!.getPrivateKey(wallet); case WalletType.polygon: return polygon!.getPrivateKey(wallet); + case WalletType.solana: + return solana!.getPrivateKey(wallet); default: return ''; } @@ -34,6 +36,8 @@ class KeyServiceImpl implements WalletConnectKeyService { return ethereum!.getPublicKey(wallet); case WalletType.polygon: return polygon!.getPublicKey(wallet); + case WalletType.solana: + return solana!.getPublicKey(wallet); default: return ''; } @@ -53,6 +57,14 @@ class KeyServiceImpl implements WalletConnectKeyService { privateKey: _getPrivateKeyForWallet(wallet), publicKey: _getPublicKeyForWallet(wallet), ), + ChainKeyModel( + chains: [ + 'solana:4sGjMW1sUnHzSxGspuhpqLDx6wiyjNtZ', // main-net + 'solana:8E9rvCKLFQia2Y35HXjjpWzj8weVo44K', // test-net + ], + privateKey: _getPrivateKeyForWallet(wallet), + publicKey: _getPublicKeyForWallet(wallet), + ), ]; return keys; } diff --git a/lib/core/wallet_connect/web3wallet_service.dart b/lib/core/wallet_connect/web3wallet_service.dart index ee560a0e0..4c71abe48 100644 --- a/lib/core/wallet_connect/web3wallet_service.dart +++ b/lib/core/wallet_connect/web3wallet_service.dart @@ -2,23 +2,27 @@ import 'dart:async'; import 'dart:developer'; import 'dart:typed_data'; -import 'package:cake_wallet/core/wallet_connect/evm_chain_id.dart'; -import 'package:cake_wallet/core/wallet_connect/evm_chain_service.dart'; +import 'package:cake_wallet/core/wallet_connect/chain_service/eth/evm_chain_id.dart'; +import 'package:cake_wallet/core/wallet_connect/chain_service/eth/evm_chain_service.dart'; import 'package:cake_wallet/core/wallet_connect/wallet_connect_key_service.dart'; import 'package:cake_wallet/generated/i18n.dart'; import 'package:cake_wallet/core/wallet_connect/models/auth_request_model.dart'; import 'package:cake_wallet/core/wallet_connect/models/chain_key_model.dart'; import 'package:cake_wallet/core/wallet_connect/models/session_request_model.dart'; import 'package:cake_wallet/reactions/wallet_connect.dart'; +import 'package:cake_wallet/solana/solana.dart'; import 'package:cake_wallet/src/screens/wallet_connect/widgets/connection_request_widget.dart'; import 'package:cake_wallet/src/screens/wallet_connect/widgets/message_display_widget.dart'; import 'package:cake_wallet/src/screens/wallet_connect/widgets/modals/web3_request_modal.dart'; import 'package:cake_wallet/store/app_store.dart'; +import 'package:cw_core/wallet_type.dart'; import 'package:eth_sig_util/eth_sig_util.dart'; import 'package:flutter/material.dart'; import 'package:mobx/mobx.dart'; import 'package:walletconnect_flutter_v2/walletconnect_flutter_v2.dart'; +import 'chain_service/solana/solana_chain_id.dart'; +import 'chain_service/solana/solana_chain_service.dart'; import 'wc_bottom_sheet_service.dart'; import 'package:cake_wallet/.secrets.g.dart' as secrets; @@ -114,14 +118,34 @@ abstract class Web3WalletServiceBase with Store { final newAuthRequests = _web3Wallet.completeRequests.getAll(); auth.addAll(newAuthRequests); - for (final cId in EVMChainId.values) { - EvmChainServiceImpl( - reference: cId, - appStore: appStore, - wcKeyService: walletKeyService, - bottomSheetService: _bottomSheetHandler, - wallet: _web3Wallet, - ); + if (isEVMCompatibleChain(appStore.wallet!.type)) { + for (final cId in EVMChainId.values) { + EvmChainServiceImpl( + reference: cId, + appStore: appStore, + wcKeyService: walletKeyService, + bottomSheetService: _bottomSheetHandler, + wallet: _web3Wallet, + ); + } + } + + if (appStore.wallet!.type == WalletType.solana) { + for (final cId in SolanaChainId.values) { + final node = appStore.settingsStore.getCurrentNode(appStore.wallet!.type); + final rpcUri = node.uri; + final webSocketUri = 'wss://${node.uriRaw}/ws${node.uri.path}'; + + SolanaChainServiceImpl( + reference: cId, + rpcUrl: rpcUri, + webSocketUrl: webSocketUri, + wcKeyService: walletKeyService, + bottomSheetService: _bottomSheetHandler, + wallet: _web3Wallet, + ownerKeyPair: solana!.getWalletKeyPair(appStore.wallet!), + ); + } } } diff --git a/lib/di.dart b/lib/di.dart index 0ee8b397b..74a425579 100644 --- a/lib/di.dart +++ b/lib/di.dart @@ -23,6 +23,7 @@ import 'package:cake_wallet/ionia/ionia_gift_card.dart'; import 'package:cake_wallet/ionia/ionia_tip.dart'; import 'package:cake_wallet/polygon/polygon.dart'; import 'package:cake_wallet/routes.dart'; +import 'package:cake_wallet/solana/solana.dart'; import 'package:cake_wallet/src/screens/anonpay_details/anonpay_details_page.dart'; import 'package:cake_wallet/src/screens/buy/buy_options_page.dart'; import 'package:cake_wallet/src/screens/buy/webview_page.dart'; @@ -873,6 +874,8 @@ Future setup({ return polygon!.createPolygonWalletService(_walletInfoSource); case WalletType.lightning: return lightning!.createLightningWalletService(_walletInfoSource, _unspentCoinsInfoSource); + case WalletType.solana: + return solana!.createSolanaWalletService(_walletInfoSource); default: throw Exception('Unexpected token: ${param1.toString()} for generating of WalletService'); } @@ -1184,7 +1187,7 @@ Future setup({ getIt.registerFactoryParam>( (homeSettingsViewModel, arguments) => EditTokenPage( homeSettingsViewModel: homeSettingsViewModel, - erc20token: arguments['token'] as Erc20Token?, + token: arguments['token'] as CryptoCurrency?, initialContractAddress: arguments['contractAddress'] as String?, ), ); diff --git a/lib/entities/default_settings_migration.dart b/lib/entities/default_settings_migration.dart index 68e76d423..019276227 100644 --- a/lib/entities/default_settings_migration.dart +++ b/lib/entities/default_settings_migration.dart @@ -30,6 +30,7 @@ const polygonDefaultNodeUri = 'polygon-bor.publicnode.com'; const cakeWalletBitcoinCashDefaultNodeUri = 'bitcoincash.stackwallet.com:50002'; const nanoDefaultNodeUri = 'rpc.nano.to'; const nanoDefaultPowNodeUri = 'rpc.nano.to'; +const solanaDefaultNodeUri = 'rpc.ankr.com'; Future defaultSettingsMigration( {required int version, @@ -186,10 +187,15 @@ Future defaultSettingsMigration( await rewriteSecureStoragePin(secureStorage: secureStorage); break; case 26: - /// commented out as it was a probable cause for some users to have white screen issues - /// maybe due to multiple access on Secure Storage at once - /// or long await time on start of the app - // await insecureStorageMigration(secureStorage: secureStorage, sharedPreferences: sharedPreferences); + + /// commented out as it was a probable cause for some users to have white screen issues + /// maybe due to multiple access on Secure Storage at once + /// or long await time on start of the app + // await insecureStorageMigration(secureStorage: secureStorage, sharedPreferences: sharedPreferences); + case 27: + await addSolanaNodeList(nodes: nodes); + await changeSolanaCurrentNodeToDefault( + sharedPreferences: sharedPreferences, nodes: nodes); break; default: break; @@ -384,6 +390,11 @@ Node getMoneroDefaultNode({required Box nodes}) { } } +Node? getSolanaDefaultNode({required Box nodes}) { + return nodes.values.firstWhereOrNull((Node node) => node.uriRaw == solanaDefaultNodeUri) ?? + nodes.values.firstWhereOrNull((node) => node.type == WalletType.solana); +} + Future insecureStorageMigration({ required SharedPreferences sharedPreferences, required FlutterSecureStorage secureStorage, @@ -673,6 +684,7 @@ Future checkCurrentNodes( final currentNanoPowNodeId = sharedPreferences.getInt(PreferencesKey.currentNanoPowNodeIdKey); final currentBitcoinCashNodeId = sharedPreferences.getInt(PreferencesKey.currentBitcoinCashNodeIdKey); + final currentSolanaNodeId = sharedPreferences.getInt(PreferencesKey.currentSolanaNodeIdKey); final currentMoneroNode = nodeSource.values.firstWhereOrNull((node) => node.key == currentMoneroNodeId); final currentBitcoinElectrumServer = @@ -691,6 +703,8 @@ Future checkCurrentNodes( powNodeSource.values.firstWhereOrNull((node) => node.key == currentNanoPowNodeId); final currentBitcoinCashNodeServer = nodeSource.values.firstWhereOrNull((node) => node.key == currentBitcoinCashNodeId); + final currentSolanaNodeServer = + nodeSource.values.firstWhereOrNull((node) => node.key == currentSolanaNodeId); if (currentMoneroNode == null) { final newCakeWalletNode = Node(uri: newCakeWalletMoneroUri, type: WalletType.monero); await nodeSource.add(newCakeWalletNode); @@ -750,6 +764,12 @@ Future checkCurrentNodes( await nodeSource.add(node); await sharedPreferences.setInt(PreferencesKey.currentPolygonNodeIdKey, node.key as int); } + + if (currentSolanaNodeServer == null) { + final node = Node(uri: solanaDefaultNodeUri, type: WalletType.solana); + await nodeSource.add(node); + await sharedPreferences.setInt(PreferencesKey.currentSolanaNodeIdKey, node.key as int); + } } Future resetBitcoinElectrumServer( @@ -861,3 +881,20 @@ Future changePolygonCurrentNodeToDefault( await sharedPreferences.setInt(PreferencesKey.currentPolygonNodeIdKey, nodeId); } + +Future addSolanaNodeList({required Box nodes}) async { + final nodeList = await loadDefaultSolanaNodes(); + for (var node in nodeList) { + if (nodes.values.firstWhereOrNull((element) => element.uriRaw == node.uriRaw) == null) { + await nodes.add(node); + } + } +} + +Future changeSolanaCurrentNodeToDefault( + {required SharedPreferences sharedPreferences, required Box nodes}) async { + final node = getSolanaDefaultNode(nodes: nodes); + final nodeId = node?.key as int? ?? 0; + + await sharedPreferences.setInt(PreferencesKey.currentSolanaNodeIdKey, nodeId); +} diff --git a/lib/entities/node_list.dart b/lib/entities/node_list.dart index aaac8a5c2..3c82a3f6c 100644 --- a/lib/entities/node_list.dart +++ b/lib/entities/node_list.dart @@ -149,6 +149,23 @@ Future> loadDefaultPolygonNodes() async { return nodes; } +Future> loadDefaultSolanaNodes() async { + final nodesRaw = await rootBundle.loadString('assets/solana_node_list.yml'); + final loadedNodes = loadYaml(nodesRaw) as YamlList; + final nodes = []; + + for (final raw in loadedNodes) { + if (raw is Map) { + final node = Node.fromMap(Map.from(raw)); + + node.type = WalletType.solana; + nodes.add(node); + } + } + + return nodes; +} + Future resetToDefault(Box nodeSource) async { final moneroNodes = await loadDefaultNodes(); final bitcoinElectrumServerList = await loadBitcoinElectrumServerList(); @@ -158,6 +175,7 @@ Future resetToDefault(Box nodeSource) async { final ethereumNodes = await loadDefaultEthereumNodes(); final nanoNodes = await loadDefaultNanoNodes(); final polygonNodes = await loadDefaultPolygonNodes(); + final solanaNodes = await loadDefaultSolanaNodes(); final nodes = moneroNodes + bitcoinElectrumServerList + @@ -166,7 +184,8 @@ Future resetToDefault(Box nodeSource) async { ethereumNodes + bitcoinCashElectrumServerList + nanoNodes + - polygonNodes; + polygonNodes + + solanaNodes; await nodeSource.clear(); await nodeSource.addAll(nodes); diff --git a/lib/entities/preferences_key.dart b/lib/entities/preferences_key.dart index 75e61b5e8..7adb2df7f 100644 --- a/lib/entities/preferences_key.dart +++ b/lib/entities/preferences_key.dart @@ -13,6 +13,7 @@ class PreferencesKey { static const currentBananoPowNodeIdKey = 'current_node_id_banano_pow'; static const currentFiatCurrencyKey = 'current_fiat_currency'; static const currentBitcoinCashNodeIdKey = 'current_node_id_bch'; + static const currentSolanaNodeIdKey = 'current_node_id_sol'; static const currentTransactionPriorityKeyLegacy = 'current_fee_priority'; static const currentBalanceDisplayModeKey = 'current_balance_display_mode'; static const shouldSaveRecipientAddressKey = 'save_recipient_address'; diff --git a/lib/entities/priority_for_wallet_type.dart b/lib/entities/priority_for_wallet_type.dart index 70b072c55..5fc0b5566 100644 --- a/lib/entities/priority_for_wallet_type.dart +++ b/lib/entities/priority_for_wallet_type.dart @@ -21,12 +21,13 @@ List priorityForWalletType(WalletType type) { return ethereum!.getTransactionPriorities(); case WalletType.bitcoinCash: return bitcoinCash!.getTransactionPriorities(); - // no such thing for nano/banano: - case WalletType.nano: - case WalletType.banano: - return []; case WalletType.polygon: return polygon!.getTransactionPriorities(); + // no such thing for nano/banano/solana: + case WalletType.nano: + case WalletType.banano: + case WalletType.solana: + return []; default: return []; } diff --git a/lib/entities/provider_types.dart b/lib/entities/provider_types.dart index 1a8399b5a..2f83cef10 100644 --- a/lib/entities/provider_types.dart +++ b/lib/entities/provider_types.dart @@ -68,6 +68,8 @@ class ProvidersHelper { return [ProviderType.askEachTime, ProviderType.onramper, ProviderType.robinhood]; case WalletType.polygon: return [ProviderType.askEachTime, ProviderType.dfx]; + case WalletType.solana: + return [ProviderType.askEachTime, ProviderType.onramper, ProviderType.robinhood]; case WalletType.none: case WalletType.haven: return []; @@ -90,6 +92,13 @@ class ProvidersHelper { return [ProviderType.askEachTime, ProviderType.moonpaySell]; case WalletType.polygon: return [ProviderType.askEachTime, ProviderType.dfx]; + case WalletType.solana: + return [ + ProviderType.askEachTime, + ProviderType.onramper, + ProviderType.robinhood, + ProviderType.moonpaySell, + ]; case WalletType.monero: case WalletType.nano: case WalletType.banano: diff --git a/lib/ethereum/cw_ethereum.dart b/lib/ethereum/cw_ethereum.dart index d7c174e1a..6e658788e 100644 --- a/lib/ethereum/cw_ethereum.dart +++ b/lib/ethereum/cw_ethereum.dart @@ -119,12 +119,13 @@ class CWEthereum extends Ethereum { } @override - Future addErc20Token(WalletBase wallet, Erc20Token token) async => - await (wallet as EthereumWallet).addErc20Token(token); + Future addErc20Token(WalletBase wallet, CryptoCurrency token) async { + await (wallet as EthereumWallet).addErc20Token(token as Erc20Token); + } @override - Future deleteErc20Token(WalletBase wallet, Erc20Token token) async => - await (wallet as EthereumWallet).deleteErc20Token(token); + Future deleteErc20Token(WalletBase wallet, CryptoCurrency token) async => + await (wallet as EthereumWallet).deleteErc20Token(token as Erc20Token); @override Future getErc20Token(WalletBase wallet, String contractAddress) async { @@ -153,4 +154,6 @@ class CWEthereum extends Ethereum { Web3Client? getWeb3Client(WalletBase wallet) { return (wallet as EthereumWallet).getWeb3Client(); } + + String getTokenAddress(CryptoCurrency asset) => (asset as Erc20Token).contractAddress; } diff --git a/lib/main.dart b/lib/main.dart index 213ce0cc4..8eee2e328 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -170,11 +170,11 @@ Future initializeAppConfigs() async { transactionDescriptions: transactionDescriptions, secureStorage: secureStorage, anonpayInvoiceInfo: anonpayInvoiceInfo, - initialMigrationVersion: 26); + initialMigrationVersion: 27); } Future initialSetup( - {required SharedPreferences sharedPreferences, + {required SharedPreferences sharedPreferences, required Box nodes, required Box powNodes, required Box walletInfoSource, diff --git a/lib/polygon/cw_polygon.dart b/lib/polygon/cw_polygon.dart index 6e5fbe2c6..0ee7457eb 100644 --- a/lib/polygon/cw_polygon.dart +++ b/lib/polygon/cw_polygon.dart @@ -119,12 +119,12 @@ class CWPolygon extends Polygon { } @override - Future addErc20Token(WalletBase wallet, Erc20Token token) async => - await (wallet as PolygonWallet).addErc20Token(token); + Future addErc20Token(WalletBase wallet, CryptoCurrency token) async => + await (wallet as PolygonWallet).addErc20Token(token as Erc20Token); @override - Future deleteErc20Token(WalletBase wallet, Erc20Token token) async => - await (wallet as PolygonWallet).deleteErc20Token(token); + Future deleteErc20Token(WalletBase wallet, CryptoCurrency token) async => + await (wallet as PolygonWallet).deleteErc20Token(token as Erc20Token); @override Future getErc20Token(WalletBase wallet, String contractAddress) async { @@ -153,4 +153,6 @@ class CWPolygon extends Polygon { Web3Client? getWeb3Client(WalletBase wallet) { return (wallet as PolygonWallet).getWeb3Client(); } + + String getTokenAddress(CryptoCurrency asset) => (asset as Erc20Token).contractAddress; } diff --git a/lib/reactions/fiat_rate_update.dart b/lib/reactions/fiat_rate_update.dart index 2b757ad44..fb1d4cd1a 100644 --- a/lib/reactions/fiat_rate_update.dart +++ b/lib/reactions/fiat_rate_update.dart @@ -4,9 +4,11 @@ import 'package:cake_wallet/entities/fiat_api_mode.dart'; import 'package:cake_wallet/entities/update_haven_rate.dart'; import 'package:cake_wallet/ethereum/ethereum.dart'; import 'package:cake_wallet/polygon/polygon.dart'; +import 'package:cake_wallet/solana/solana.dart'; import 'package:cake_wallet/store/app_store.dart'; import 'package:cake_wallet/store/dashboard/fiat_conversion_store.dart'; import 'package:cake_wallet/store/settings_store.dart'; +import 'package:cw_core/crypto_currency.dart'; import 'package:cw_core/erc20_token.dart'; import 'package:cw_core/wallet_type.dart'; import 'package:mobx/mobx.dart'; @@ -35,7 +37,7 @@ Future startFiatRateUpdate( torOnly: settingsStore.fiatApiMode == FiatApiMode.torOnly); } - Iterable? currencies; + Iterable? currencies; if (appStore.wallet!.type == WalletType.ethereum) { currencies = ethereum!.getERC20Currencies(appStore.wallet!).where((element) => element.enabled); @@ -46,6 +48,12 @@ Future startFiatRateUpdate( polygon!.getERC20Currencies(appStore.wallet!).where((element) => element.enabled); } + if (appStore.wallet!.type == WalletType.solana) { + currencies = + solana!.getSPLTokenCurrencies(appStore.wallet!).where((element) => element.enabled); + } + + if (currencies != null) { for (final currency in currencies) { () async { diff --git a/lib/reactions/on_current_wallet_change.dart b/lib/reactions/on_current_wallet_change.dart index 1ae1e4fd0..2cdb7ea11 100644 --- a/lib/reactions/on_current_wallet_change.dart +++ b/lib/reactions/on_current_wallet_change.dart @@ -3,6 +3,8 @@ import 'package:cake_wallet/entities/fiat_api_mode.dart'; import 'package:cake_wallet/entities/update_haven_rate.dart'; import 'package:cake_wallet/ethereum/ethereum.dart'; import 'package:cake_wallet/polygon/polygon.dart'; +import 'package:cake_wallet/solana/solana.dart'; +import 'package:cw_core/crypto_currency.dart'; import 'package:cw_core/erc20_token.dart'; import 'package:cw_core/transaction_history.dart'; import 'package:cw_core/balance.dart'; @@ -112,7 +114,7 @@ void startCurrentWalletChangeReaction( fiat: settingsStore.fiatCurrency, torOnly: settingsStore.fiatApiMode == FiatApiMode.torOnly); - Iterable? currencies; + Iterable? currencies; if (wallet.type == WalletType.ethereum) { currencies = ethereum!.getERC20Currencies(appStore.wallet!).where((element) => element.enabled); @@ -121,7 +123,11 @@ void startCurrentWalletChangeReaction( currencies = polygon!.getERC20Currencies(appStore.wallet!).where((element) => element.enabled); } - + if (wallet.type == WalletType.solana) { + currencies = + solana!.getSPLTokenCurrencies(appStore.wallet!).where((element) => element.enabled); + } + if (currencies != null) { for (final currency in currencies) { () async { diff --git a/lib/reactions/wallet_connect.dart b/lib/reactions/wallet_connect.dart index 4f5923e26..f4487123e 100644 --- a/lib/reactions/wallet_connect.dart +++ b/lib/reactions/wallet_connect.dart @@ -1,4 +1,5 @@ -import 'package:cake_wallet/core/wallet_connect/evm_chain_id.dart'; +import 'package:cake_wallet/core/wallet_connect/chain_service/eth/evm_chain_id.dart'; +import 'package:cake_wallet/core/wallet_connect/chain_service/solana/solana_chain_id.dart'; import 'package:cw_core/wallet_type.dart'; bool isEVMCompatibleChain(WalletType walletType) { @@ -11,12 +12,24 @@ bool isEVMCompatibleChain(WalletType walletType) { } } +bool isWalletConnectCompatibleChain(WalletType walletType) { + switch (walletType) { + case WalletType.polygon: + case WalletType.ethereum: + return true; + default: + return false; + } +} + String getChainNameSpaceAndIdBasedOnWalletType(WalletType walletType) { switch (walletType) { case WalletType.ethereum: return EVMChainId.ethereum.chain(); case WalletType.polygon: return EVMChainId.polygon.chain(); + case WalletType.solana: + return SolanaChainId.mainnet.chain(); default: return ''; } @@ -40,6 +53,8 @@ String getChainNameBasedOnWalletType(WalletType walletType) { return 'eth'; case WalletType.polygon: return 'polygon'; + case WalletType.solana: + return 'solana'; default: return ''; } @@ -51,6 +66,8 @@ String getTokenNameBasedOnWalletType(WalletType walletType) { return 'ETH'; case WalletType.polygon: return 'MATIC'; + case WalletType.solana: + return 'SOL'; default: return ''; } diff --git a/lib/solana/cw_solana.dart b/lib/solana/cw_solana.dart new file mode 100644 index 000000000..a86d6b0c6 --- /dev/null +++ b/lib/solana/cw_solana.dart @@ -0,0 +1,118 @@ +part of 'solana.dart'; + +class CWSolana extends Solana { + @override + List getSolanaWordList(String language) => SolanaMnemonics.englishWordlist; + + WalletService createSolanaWalletService(Box walletInfoSource) => + SolanaWalletService(walletInfoSource); + + @override + WalletCredentials createSolanaNewWalletCredentials({ + required String name, + WalletInfo? walletInfo, + }) => + SolanaNewWalletCredentials(name: name, walletInfo: walletInfo); + + @override + WalletCredentials createSolanaRestoreWalletFromSeedCredentials({ + required String name, + required String mnemonic, + required String password, + }) => + SolanaRestoreWalletFromSeedCredentials(name: name, password: password, mnemonic: mnemonic); + + @override + WalletCredentials createSolanaRestoreWalletFromPrivateKey({ + required String name, + required String privateKey, + required String password, + }) => + SolanaRestoreWalletFromPrivateKey(name: name, password: password, privateKey: privateKey); + + @override + String getAddress(WalletBase wallet) => (wallet as SolanaWallet).walletAddresses.address; + + @override + String getPrivateKey(WalletBase wallet) => (wallet as SolanaWallet).privateKey; + + @override + String getPublicKey(WalletBase wallet) => (wallet as SolanaWallet).keys.publicKey.toBase58(); + + @override + Ed25519HDKeyPair? getWalletKeyPair(WalletBase wallet) => (wallet as SolanaWallet).walletKeyPair; + + Object createSolanaTransactionCredentials( + List outputs, { + required CryptoCurrency currency, + }) => + SolanaTransactionCredentials( + outputs + .map((out) => OutputInfo( + fiatAmount: out.fiatAmount, + cryptoAmount: out.cryptoAmount, + address: out.address, + note: out.note, + sendAll: out.sendAll, + extractedAddress: out.extractedAddress, + isParsedAddress: out.isParsedAddress, + formattedCryptoAmount: out.formattedCryptoAmount)) + .toList(), + currency: currency, + ); + + Object createSolanaTransactionCredentialsRaw( + List outputs, { + required CryptoCurrency currency, + }) => + SolanaTransactionCredentials(outputs, currency: currency); + + @override + List getSPLTokenCurrencies(WalletBase wallet) { + final solanaWallet = wallet as SolanaWallet; + return solanaWallet.splTokenCurrencies; + } + + @override + Future addSPLToken(WalletBase wallet, CryptoCurrency token) async => + await (wallet as SolanaWallet).addSPLToken(token as SPLToken); + + @override + Future deleteSPLToken(WalletBase wallet, CryptoCurrency token) async => + await (wallet as SolanaWallet).deleteSPLToken(token as SPLToken); + + @override + Future getSPLToken(WalletBase wallet, String mintAddress) async { + final solanaWallet = wallet as SolanaWallet; + return await solanaWallet.getSPLToken(mintAddress); + } + + @override + CryptoCurrency assetOfTransaction(WalletBase wallet, TransactionInfo transaction) { + transaction as SolanaTransactionInfo; + if (transaction.tokenSymbol == CryptoCurrency.sol.title) { + return CryptoCurrency.sol; + } + + wallet as SolanaWallet; + return wallet.splTokenCurrencies + .firstWhere((element) => transaction.tokenSymbol == element.symbol); + } + + @override + double getTransactionAmountRaw(TransactionInfo transactionInfo) { + return (transactionInfo as SolanaTransactionInfo).solAmount.toDouble(); + } + + @override + String getTokenAddress(CryptoCurrency asset) => (asset as SPLToken).mintAddress; + + @override + List? getValidationLength(CryptoCurrency type) { + if (type is SPLToken) { + return [44]; + } + + return null; + } +} diff --git a/lib/src/screens/dashboard/desktop_widgets/desktop_wallet_selection_dropdown.dart b/lib/src/screens/dashboard/desktop_widgets/desktop_wallet_selection_dropdown.dart index a81a3f6e4..17a22a88f 100644 --- a/lib/src/screens/dashboard/desktop_widgets/desktop_wallet_selection_dropdown.dart +++ b/lib/src/screens/dashboard/desktop_widgets/desktop_wallet_selection_dropdown.dart @@ -37,6 +37,7 @@ class _DesktopWalletSelectionDropDownState extends State Image.asset( @@ -153,6 +154,8 @@ class _DesktopWalletSelectionDropDownState extends State { void initState() { super.initState(); - if (widget.erc20token != null) { - _contractAddressController.text = widget.erc20token!.contractAddress; - _tokenNameController.text = widget.erc20token!.name; - _tokenSymbolController.text = widget.erc20token!.symbol; - _tokenDecimalController.text = widget.erc20token!.decimal.toString(); + String? address; + + if (widget.token != null) { + address = widget.homeSettingsViewModel.getTokenAddressBasedOnWallet(widget.token!); + + _contractAddressController.text = address ?? ''; + _tokenNameController.text = widget.token!.name; + _tokenSymbolController.text = widget.token!.title; + _tokenDecimalController.text = widget.token!.decimals.toString(); } if (widget.initialContractAddress != null) { @@ -91,7 +96,7 @@ class _EditTokenPageBodyState extends State { } final contractAddress = _contractAddressController.text; - if (contractAddress.isNotEmpty && contractAddress != widget.erc20token?.contractAddress) { + if (contractAddress.isNotEmpty && contractAddress != address) { setState(() { _showDisclaimer = true; }); @@ -139,7 +144,9 @@ class _EditTokenPageBodyState extends State { style: TextStyle( fontSize: 14, fontWeight: FontWeight.normal, - color: Theme.of(context).extension()!.detailsTitlesColor, + color: Theme.of(context) + .extension()! + .detailsTitlesColor, ), ), ), @@ -172,12 +179,12 @@ class _EditTokenPageBodyState extends State { Expanded( child: PrimaryButton( onPressed: () async { - if (widget.erc20token != null) { - await widget.homeSettingsViewModel.deleteErc20Token(widget.erc20token!); + if (widget.token != null) { + await widget.homeSettingsViewModel.deleteToken(widget.token!); } Navigator.pop(context); }, - text: widget.erc20token != null ? S.of(context).delete : S.of(context).cancel, + text: widget.token != null ? S.of(context).delete : S.of(context).cancel, color: Colors.red, textColor: Colors.white, ), @@ -188,7 +195,7 @@ class _EditTokenPageBodyState extends State { onPressed: () async { if (_formKey.currentState!.validate() && (!_showDisclaimer || _disclaimerChecked)) { - await widget.homeSettingsViewModel.addErc20Token(Erc20Token( + await widget.homeSettingsViewModel.addToken(Erc20Token( name: _tokenNameController.text, symbol: _tokenSymbolController.text, contractAddress: _contractAddressController.text, @@ -214,14 +221,13 @@ class _EditTokenPageBodyState extends State { void _getTokenInfo() async { if (_contractAddressController.text.isNotEmpty) { - final token = - await widget.homeSettingsViewModel.getErc20Token(_contractAddressController.text); + final token = await widget.homeSettingsViewModel.getToken(_contractAddressController.text); if (token != null) { if (_tokenNameController.text.isEmpty) _tokenNameController.text = token.name; - if (_tokenSymbolController.text.isEmpty) _tokenSymbolController.text = token.symbol; + if (_tokenSymbolController.text.isEmpty) _tokenSymbolController.text = token.title; if (_tokenDecimalController.text.isEmpty) - _tokenDecimalController.text = token.decimal.toString(); + _tokenDecimalController.text = token.decimals.toString(); } } } diff --git a/lib/src/screens/dashboard/home_settings_page.dart b/lib/src/screens/dashboard/home_settings_page.dart index 618ba49ff..e841423c1 100644 --- a/lib/src/screens/dashboard/home_settings_page.dart +++ b/lib/src/screens/dashboard/home_settings_page.dart @@ -5,6 +5,7 @@ import 'package:cake_wallet/entities/sort_balance_types.dart'; import 'package:cake_wallet/generated/i18n.dart'; import 'package:cake_wallet/routes.dart'; import 'package:cake_wallet/src/screens/base_page.dart'; +import 'package:cake_wallet/src/widgets/cake_image_widget.dart'; import 'package:cake_wallet/src/screens/settings/widgets/settings_picker_cell.dart'; import 'package:cake_wallet/src/screens/settings/widgets/settings_switcher_cell.dart'; import 'package:cake_wallet/themes/extensions/address_theme.dart'; @@ -117,7 +118,7 @@ class HomeSettingsPage extends BasePage { return SettingsSwitcherCell( title: "${token.name} " - "(${token.symbol})", + "(${token.title})", value: token.enabled, onValueChange: (_, bool value) { _homeSettingsViewModel.changeTokenAvailability(token, value); @@ -128,20 +129,16 @@ class HomeSettingsPage extends BasePage { 'token': token, }); }, - leading: token.iconPath != null - ? Container( - child: Image.asset( - token.iconPath!, - height: 30.0, - width: 30.0, - ), - ) - : Container( + leading: CakeImageWidget( + imageUrl: token.iconPath, + height: 40, + width: 40, + displayOnError: Container( height: 30.0, width: 30.0, child: Center( child: Text( - token.symbol.substring(0, min(token.symbol.length, 2)), + token.title.substring(0, min(token.title.length, 2)), style: TextStyle(fontSize: 11), ), ), @@ -149,7 +146,8 @@ class HomeSettingsPage extends BasePage { shape: BoxShape.circle, color: Colors.grey.shade400, ), - ), + ), + ), decoration: BoxDecoration( color: Theme.of(context).cardColor, borderRadius: BorderRadius.circular(30), diff --git a/lib/src/screens/dashboard/pages/balance_page.dart b/lib/src/screens/dashboard/pages/balance_page.dart index 453adccf5..bb3ec70dc 100644 --- a/lib/src/screens/dashboard/pages/balance_page.dart +++ b/lib/src/screens/dashboard/pages/balance_page.dart @@ -6,6 +6,7 @@ import 'package:cake_wallet/reactions/wallet_connect.dart'; import 'package:cake_wallet/routes.dart'; import 'package:cake_wallet/src/screens/dashboard/pages/nft_listing_page.dart'; import 'package:cake_wallet/src/screens/dashboard/widgets/home_screen_account_widget.dart'; +import 'package:cake_wallet/src/widgets/cake_image_widget.dart'; import 'package:cake_wallet/src/screens/exchange_trade/information_page.dart'; import 'package:cake_wallet/src/widgets/introducing_card.dart'; import 'package:cake_wallet/store/settings_store.dart'; @@ -333,15 +334,11 @@ class BalanceRowWidget extends StatelessWidget { child: Center( child: Column( children: [ - currency.iconPath != null - ? Container( - child: Image.asset( - currency.iconPath!, - height: 40.0, - width: 40.0, - ), - ) - : Container( + CakeImageWidget( + imageUrl: currency.iconPath, + height: 40, + width: 40, + displayOnError: Container( height: 30.0, width: 30.0, child: Center( @@ -355,6 +352,7 @@ class BalanceRowWidget extends StatelessWidget { color: Colors.grey.shade400, ), ), + ), const SizedBox(height: 10), Text( currency.title, diff --git a/lib/src/screens/dashboard/pages/nft_details_page.dart b/lib/src/screens/dashboard/pages/nft_details_page.dart index bb642fd4b..15d2a2b5c 100644 --- a/lib/src/screens/dashboard/pages/nft_details_page.dart +++ b/lib/src/screens/dashboard/pages/nft_details_page.dart @@ -2,7 +2,7 @@ import 'package:cake_wallet/entities/wallet_nft_response.dart'; import 'package:cake_wallet/generated/i18n.dart'; import 'package:cake_wallet/src/screens/base_page.dart'; import 'package:cake_wallet/src/screens/dashboard/widgets/menu_widget.dart'; -import 'package:cake_wallet/src/screens/dashboard/widgets/nft_image_tile_widget.dart'; +import 'package:cake_wallet/src/widgets/cake_image_widget.dart'; import 'package:cake_wallet/src/widgets/gradient_background.dart'; import 'package:cake_wallet/themes/extensions/balance_page_theme.dart'; import 'package:cake_wallet/themes/extensions/dashboard_page_theme.dart'; @@ -94,7 +94,7 @@ class NFTDetailsPage extends BasePage { .syncedBackgroundColor, ), - child: NFTImageWidget( + child: CakeImageWidget( imageUrl: nftAsset.normalizedMetadata?.imageUrl, ), ), diff --git a/lib/src/screens/dashboard/widgets/menu_widget.dart b/lib/src/screens/dashboard/widgets/menu_widget.dart index f9a95cbe5..3c0bf06c4 100644 --- a/lib/src/screens/dashboard/widgets/menu_widget.dart +++ b/lib/src/screens/dashboard/widgets/menu_widget.dart @@ -18,24 +18,24 @@ class MenuWidget extends StatefulWidget { class MenuWidgetState extends State { MenuWidgetState() - : this.menuWidth = 0, - this.screenWidth = 0, - this.screenHeight = 0, - this.headerHeight = 120, - this.tileHeight = 60, - this.fromTopEdge = 50, - this.fromBottomEdge = 25, - this.moneroIcon = Image.asset('assets/images/monero_menu.png'), - this.bitcoinIcon = Image.asset('assets/images/bitcoin_menu.png'), - this.lightningIcon = Image.asset('assets/images/bitcoin_menu.png'), - this.litecoinIcon = Image.asset('assets/images/litecoin_menu.png'), - this.havenIcon = Image.asset('assets/images/haven_menu.png'), - this.ethereumIcon = Image.asset('assets/images/eth_icon.png'), - this.nanoIcon = Image.asset('assets/images/nano_icon.png'), - this.bananoIcon = Image.asset('assets/images/nano_icon.png'), + : this.menuWidth = 0, + this.screenWidth = 0, + this.screenHeight = 0, + this.headerHeight = 120, + this.tileHeight = 60, + this.fromTopEdge = 50, + this.fromBottomEdge = 25, + this.moneroIcon = Image.asset('assets/images/monero_menu.png'), + this.bitcoinIcon = Image.asset('assets/images/bitcoin_menu.png'), + this.lightningIcon = Image.asset('assets/images/bitcoin_menu.png'), + this.litecoinIcon = Image.asset('assets/images/litecoin_menu.png'), + this.havenIcon = Image.asset('assets/images/haven_menu.png'), + this.ethereumIcon = Image.asset('assets/images/eth_icon.png'), + this.nanoIcon = Image.asset('assets/images/nano_icon.png'), + this.bananoIcon = Image.asset('assets/images/nano_icon.png'), this.bitcoinCashIcon = Image.asset('assets/images/bch_icon.png'), - this.polygonIcon = Image.asset('assets/images/matic_icon.png'); - + this.polygonIcon = Image.asset('assets/images/matic_icon.png'), + this.solanaIcon = Image.asset('assets/images/sol_icon.png'); final largeScreen = 731; @@ -58,7 +58,7 @@ class MenuWidgetState extends State { Image nanoIcon; Image bananoIcon; Image polygonIcon; - + Image solanaIcon; @override void initState() { @@ -230,6 +230,8 @@ class MenuWidgetState extends State { return bananoIcon; case WalletType.polygon: return polygonIcon; + case WalletType.solana: + return solanaIcon; default: throw Exception('No icon for ${type.toString()}'); } diff --git a/lib/src/screens/dashboard/widgets/nft_tile_widget.dart b/lib/src/screens/dashboard/widgets/nft_tile_widget.dart index e7391b970..4c4d214e7 100644 --- a/lib/src/screens/dashboard/widgets/nft_tile_widget.dart +++ b/lib/src/screens/dashboard/widgets/nft_tile_widget.dart @@ -1,9 +1,8 @@ import 'package:cake_wallet/entities/wallet_nft_response.dart'; import 'package:cake_wallet/routes.dart'; -import 'package:cake_wallet/src/screens/dashboard/widgets/nft_image_tile_widget.dart'; +import 'package:cake_wallet/src/widgets/cake_image_widget.dart'; import 'package:cake_wallet/themes/extensions/balance_page_theme.dart'; import 'package:cake_wallet/themes/extensions/sync_indicator_theme.dart'; -import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; class NFTTileWidget extends StatelessWidget { @@ -38,7 +37,7 @@ class NFTTileWidget extends StatelessWidget { ), color: Theme.of(context).extension()!.syncedBackgroundColor, ), - child: NFTImageWidget( + child: CakeImageWidget( imageUrl: nftAsset.normalizedMetadata?.imageUrl, ), ), diff --git a/lib/src/screens/send/send_page.dart b/lib/src/screens/send/send_page.dart index 3746118d8..5870b1c4d 100644 --- a/lib/src/screens/send/send_page.dart +++ b/lib/src/screens/send/send_page.dart @@ -14,6 +14,7 @@ import 'package:cake_wallet/utils/payment_request.dart'; import 'package:cake_wallet/utils/request_review_handler.dart'; import 'package:cake_wallet/utils/responsive_layout_util.dart'; import 'package:cake_wallet/view_model/send/output.dart'; +import 'package:cw_core/wallet_type.dart'; import 'package:flutter/material.dart'; import 'package:flutter_mobx/flutter_mobx.dart'; import 'package:mobx/mobx.dart'; @@ -439,10 +440,17 @@ class SendPage extends BasePage { } if (state is TransactionCommitted) { + String alertContent; + if (sendViewModel.walletType == WalletType.solana) { + alertContent = + '${S.of(_dialogContext).send_success(sendViewModel.selectedCryptoCurrency.toString())}. ${S.of(_dialogContext).waitFewSecondForTxUpdate}'; + } else { + alertContent = S.of(_dialogContext).send_success( + sendViewModel.selectedCryptoCurrency.toString()); + } return AlertWithOneAction( alertTitle: '', - alertContent: S.of(_dialogContext).send_success( - sendViewModel.selectedCryptoCurrency.toString()), + alertContent: alertContent, buttonText: S.of(_dialogContext).ok, buttonAction: () { Navigator.of(_dialogContext).pop(); diff --git a/lib/src/screens/send/widgets/send_card.dart b/lib/src/screens/send/widgets/send_card.dart index 5f15c9c4d..6bd2d81e9 100644 --- a/lib/src/screens/send/widgets/send_card.dart +++ b/lib/src/screens/send/widgets/send_card.dart @@ -321,7 +321,7 @@ class SendCardState extends State with AutomaticKeepAliveClientMixin _presentReconnectAlert(context), ), - const StandardListSeparator(padding: EdgeInsets.symmetric(horizontal: 24)), if (dashboardViewModel.hasRescan) ...[ SettingsCellWithArrow( title: S.current.rescan, handler: (context) => Navigator.of(context).pushNamed(Routes.rescan), ), - const StandardListSeparator(padding: EdgeInsets.symmetric(horizontal: 24)), if (DeviceInfo.instance.isMobile) ...[ Observer(builder: (context) { return SettingsPickerCell( @@ -82,7 +80,6 @@ class ConnectionSyncPage extends BasePage { } }); }), - const StandardListSeparator(padding: EdgeInsets.symmetric(horizontal: 24)), Observer(builder: (context) { return SettingsSwitcherCell( title: S.current.sync_all_wallets, @@ -90,14 +87,12 @@ class ConnectionSyncPage extends BasePage { onValueChange: (_, bool value) => dashboardViewModel.setSyncAll(value), ); }), - const StandardListSeparator(padding: EdgeInsets.symmetric(horizontal: 24)), ], ], SettingsCellWithArrow( title: S.current.manage_nodes, handler: (context) => Navigator.of(context).pushNamed(Routes.manageNodes), ), - const StandardListSeparator(padding: EdgeInsets.symmetric(horizontal: 24)), Observer( builder: (context) { if (!dashboardViewModel.hasPowNodes) return const SizedBox(); @@ -108,16 +103,14 @@ class ConnectionSyncPage extends BasePage { title: S.current.manage_pow_nodes, handler: (context) => Navigator.of(context).pushNamed(Routes.managePowNodes), ), - const StandardListSeparator(padding: EdgeInsets.symmetric(horizontal: 24)), ], ); }, ), - if (isEVMCompatibleChain(dashboardViewModel.wallet.type)) ...[ + if (isWalletConnectCompatibleChain(dashboardViewModel.wallet.type)) ...[ WalletConnectTile( onTap: () => Navigator.of(context).pushNamed(Routes.walletConnectConnectionsListing), ), - const StandardListSeparator(padding: EdgeInsets.symmetric(horizontal: 24)), ], if (FeatureFlag.isInAppTorEnabled) SettingsCellWithArrow( diff --git a/lib/src/screens/settings/other_settings_page.dart b/lib/src/screens/settings/other_settings_page.dart index c58523185..fcf683050 100644 --- a/lib/src/screens/settings/other_settings_page.dart +++ b/lib/src/screens/settings/other_settings_page.dart @@ -26,7 +26,7 @@ class OtherSettingsPage extends BasePage { padding: EdgeInsets.only(top: 10), child: Column( children: [ - if (!_otherSettingsViewModel.changeRepresentativeEnabled) + if (_otherSettingsViewModel.displayTransactionPriority) SettingsPickerCell( title: S.current.settings_fee_priority, items: priorityForWalletType(_otherSettingsViewModel.walletType), @@ -61,7 +61,6 @@ class OtherSettingsPage extends BasePage { handler: (BuildContext context) => Navigator.of(context).pushNamed(Routes.readDisclaimer), ), - StandardListSeparator(padding: EdgeInsets.symmetric(horizontal: 24)), Spacer(), SettingsVersionCell( title: S.of(context).version(_otherSettingsViewModel.currentVersion)), diff --git a/lib/src/screens/settings/security_backup_page.dart b/lib/src/screens/settings/security_backup_page.dart index 56ba049ba..e559e9b15 100644 --- a/lib/src/screens/settings/security_backup_page.dart +++ b/lib/src/screens/settings/security_backup_page.dart @@ -37,7 +37,6 @@ class SecurityBackupPage extends BasePage { .shouldRequireTOTP2FAForAllSecurityAndBackupSettings, ), ), - StandardListSeparator(padding: EdgeInsets.symmetric(horizontal: 24)), SettingsCellWithArrow( title: S.current.create_backup, handler: (_) => _authService.authenticateAction( @@ -47,7 +46,6 @@ class SecurityBackupPage extends BasePage { .shouldRequireTOTP2FAForAllSecurityAndBackupSettings, ), ), - StandardListSeparator(padding: EdgeInsets.symmetric(horizontal: 24)), SettingsCellWithArrow( title: S.current.settings_change_pin, handler: (_) => _authService.authenticateAction( @@ -60,7 +58,6 @@ class SecurityBackupPage extends BasePage { .shouldRequireTOTP2FAForAllSecurityAndBackupSettings, ), ), - StandardListSeparator(padding: EdgeInsets.symmetric(horizontal: 24)), if (DeviceInfo.instance.isMobile) Observer(builder: (_) { return SettingsSwitcherCell( diff --git a/lib/src/screens/wallet_connect/widgets/pairing_item_widget.dart b/lib/src/screens/wallet_connect/widgets/pairing_item_widget.dart index 063de8ec3..0d425f904 100644 --- a/lib/src/screens/wallet_connect/widgets/pairing_item_widget.dart +++ b/lib/src/screens/wallet_connect/widgets/pairing_item_widget.dart @@ -1,4 +1,5 @@ import 'package:cake_wallet/generated/i18n.dart'; +import 'package:cake_wallet/src/widgets/cake_image_widget.dart'; import 'package:cake_wallet/themes/extensions/cake_text_theme.dart'; import 'package:cake_wallet/themes/extensions/receive_page_theme.dart'; import 'package:flutter/material.dart'; @@ -26,12 +27,11 @@ class PairingItemWidget extends StatelessWidget { '$year-${month.toString().padLeft(2, '0')}-${day.toString().padLeft(2, '0')}'; return ListTile( - leading: CircleAvatar( - backgroundImage: (metadata.icons.isNotEmpty - ? NetworkImage(metadata.icons[0]) - : const AssetImage( - 'assets/images/default_icon.png', - )) as ImageProvider, + leading: CakeImageWidget( + imageUrl: metadata.icons.isNotEmpty ? metadata.icons[0]: null, + displayOnError: CircleAvatar( + backgroundImage: AssetImage('assets/images/default_icon.png'), + ), ), title: Text( metadata.name, diff --git a/lib/src/screens/wallet_list/wallet_list_page.dart b/lib/src/screens/wallet_list/wallet_list_page.dart index c0b45cc61..7e431c5d8 100644 --- a/lib/src/screens/wallet_list/wallet_list_page.dart +++ b/lib/src/screens/wallet_list/wallet_list_page.dart @@ -104,6 +104,7 @@ class WalletListBodyState extends State { final bitcoinCashIcon = Image.asset('assets/images/bch_icon.png', height: 24, width: 24); final nanoIcon = Image.asset('assets/images/nano_icon.png', height: 24, width: 24); final polygonIcon = Image.asset('assets/images/matic_icon.png', height: 24, width: 24); + final solanaIcon = Image.asset('assets/images/sol_icon.png', height: 24, width: 24); final scrollController = ScrollController(); final double tileHeight = 60; Flushbar? _progressBar; @@ -316,6 +317,8 @@ class WalletListBodyState extends State { return nanoIcon; case WalletType.polygon: return polygonIcon; + case WalletType.solana: + return solanaIcon; default: return nonWalletTypeIcon; } diff --git a/lib/src/screens/dashboard/widgets/nft_image_tile_widget.dart b/lib/src/widgets/cake_image_widget.dart similarity index 51% rename from lib/src/screens/dashboard/widgets/nft_image_tile_widget.dart rename to lib/src/widgets/cake_image_widget.dart index d34ff02cb..14c62ad34 100644 --- a/lib/src/screens/dashboard/widgets/nft_image_tile_widget.dart +++ b/lib/src/widgets/cake_image_widget.dart @@ -2,25 +2,45 @@ import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:flutter_svg/flutter_svg.dart'; -class NFTImageWidget extends StatelessWidget { - const NFTImageWidget({ +class CakeImageWidget extends StatelessWidget { + CakeImageWidget({ required this.imageUrl, - }); + Widget? displayOnError, + this.height, + this.width, + }) : _displayOnError = displayOnError ?? Icon(Icons.error); final String? imageUrl; + final double? height; + final double? width; + final Widget? _displayOnError; @override Widget build(BuildContext context) { try { - if (imageUrl == null) return Icon(Icons.error); + if (imageUrl == null) return _displayOnError!; + + if (imageUrl!.contains('assets/images')) { + return Image.asset( + imageUrl!, + height: height, + width: width, + ); + } if (imageUrl!.contains('.svg')) { - return SvgPicture.network(imageUrl!); + return SvgPicture.network( + imageUrl!, + height: height, + width: width, + ); } return Image.network( imageUrl!, fit: BoxFit.cover, + height: height, + width: width, loadingBuilder: (BuildContext _, Widget child, ImageChunkEvent? loadingProgress) { if (loadingProgress == null) { return child; @@ -31,7 +51,7 @@ class NFTImageWidget extends StatelessWidget { errorBuilder: (_, __, ___) => Icon(Icons.error), ); } catch (_) { - return Icon(Icons.error); + return _displayOnError!; } } } diff --git a/lib/store/app_store.dart b/lib/store/app_store.dart index a5a2b95e0..7d61abfc5 100644 --- a/lib/store/app_store.dart +++ b/lib/store/app_store.dart @@ -41,7 +41,7 @@ abstract class AppStoreBase with Store { this.wallet = wallet; this.wallet!.setExceptionHandler(ExceptionHandler.onError); - if (isEVMCompatibleChain(wallet.type)) { + if (isWalletConnectCompatibleChain(wallet.type)) { await getIt.get().onDispose(); getIt.get().create(); await getIt.get().init(); diff --git a/lib/store/settings_store.dart b/lib/store/settings_store.dart index e1add830e..ff55be519 100644 --- a/lib/store/settings_store.dart +++ b/lib/store/settings_store.dart @@ -838,6 +838,7 @@ abstract class SettingsStoreBase with Store { final polygonNodeId = sharedPreferences.getInt(PreferencesKey.currentPolygonNodeIdKey); final nanoNodeId = sharedPreferences.getInt(PreferencesKey.currentNanoNodeIdKey); final nanoPowNodeId = sharedPreferences.getInt(PreferencesKey.currentNanoPowNodeIdKey); + final solanaNodeId = sharedPreferences.getInt(PreferencesKey.currentSolanaNodeIdKey); final moneroNode = nodeSource.get(nodeId); final bitcoinElectrumServer = nodeSource.get(bitcoinElectrumServerId); final litecoinElectrumServer = nodeSource.get(litecoinElectrumServerId); @@ -847,6 +848,7 @@ abstract class SettingsStoreBase with Store { final bitcoinCashElectrumServer = nodeSource.get(bitcoinCashElectrumServerId); final nanoNode = nodeSource.get(nanoNodeId); final nanoPowNode = powNodeSource.get(nanoPowNodeId); + final solanaNode = nodeSource.get(solanaNodeId); final packageInfo = await PackageInfo.fromPlatform(); final deviceName = await _getDeviceName() ?? ''; final shouldShowYatPopup = sharedPreferences.getBool(PreferencesKey.shouldShowYatPopup) ?? true; @@ -904,6 +906,10 @@ abstract class SettingsStoreBase with Store { powNodes[WalletType.nano] = nanoPowNode; } + if (solanaNode != null) { + nodes[WalletType.solana] = solanaNode; + } + final savedSyncMode = SyncMode.all.firstWhere((element) { return element.type.index == (sharedPreferences.getInt(PreferencesKey.syncModeKey) ?? 0); }); @@ -1191,6 +1197,7 @@ abstract class SettingsStoreBase with Store { final ethereumNodeId = sharedPreferences.getInt(PreferencesKey.currentEthereumNodeIdKey); final polygonNodeId = sharedPreferences.getInt(PreferencesKey.currentPolygonNodeIdKey); final nanoNodeId = sharedPreferences.getInt(PreferencesKey.currentNanoNodeIdKey); + final solanaNodeId = sharedPreferences.getInt(PreferencesKey.currentSolanaNodeIdKey); final moneroNode = nodeSource.get(nodeId); final bitcoinElectrumServer = nodeSource.get(bitcoinElectrumServerId); final litecoinElectrumServer = nodeSource.get(litecoinElectrumServerId); @@ -1199,7 +1206,7 @@ abstract class SettingsStoreBase with Store { final polygonNode = nodeSource.get(polygonNodeId); final bitcoinCashNode = nodeSource.get(bitcoinCashElectrumServerId); final nanoNode = nodeSource.get(nanoNodeId); - + final solanaNode = nodeSource.get(solanaNodeId); if (moneroNode != null) { nodes[WalletType.monero] = moneroNode; } @@ -1233,6 +1240,10 @@ abstract class SettingsStoreBase with Store { nodes[WalletType.nano] = nanoNode; } + if (solanaNode != null) { + nodes[WalletType.solana] = solanaNode; + } + // MIGRATED: useTOTP2FA = await SecureKey.getBool( @@ -1360,6 +1371,9 @@ abstract class SettingsStoreBase with Store { case WalletType.polygon: await _sharedPreferences.setInt(PreferencesKey.currentPolygonNodeIdKey, node.key as int); break; + case WalletType.solana: + await _sharedPreferences.setInt(PreferencesKey.currentSolanaNodeIdKey, node.key as int); + break; default: break; } diff --git a/lib/view_model/advanced_privacy_settings_view_model.dart b/lib/view_model/advanced_privacy_settings_view_model.dart index 75d7a9eb4..14033b368 100644 --- a/lib/view_model/advanced_privacy_settings_view_model.dart +++ b/lib/view_model/advanced_privacy_settings_view_model.dart @@ -28,7 +28,10 @@ abstract class AdvancedPrivacySettingsViewModelBase with Store { final SettingsStore _settingsStore; bool get hasSeedPhraseLengthOption => - type == WalletType.bitcoinCash || type == WalletType.ethereum; + type == WalletType.bitcoinCash || + type == WalletType.ethereum || + type == WalletType.polygon || + type == WalletType.solana; bool get hasSeedTypeOption => type == WalletType.monero; diff --git a/lib/view_model/dashboard/balance_view_model.dart b/lib/view_model/dashboard/balance_view_model.dart index aaaabed0c..3cce418a3 100644 --- a/lib/view_model/dashboard/balance_view_model.dart +++ b/lib/view_model/dashboard/balance_view_model.dart @@ -79,7 +79,8 @@ abstract class BalanceViewModelBase with Store { bool get isFiatDisabled => settingsStore.fiatApiMode == FiatApiMode.disabled; @computed - bool get isHomeScreenSettingsEnabled => isEVMCompatibleChain(wallet.type); + bool get isHomeScreenSettingsEnabled => + isEVMCompatibleChain(wallet.type) || wallet.type == WalletType.solana; @computed bool get hasAccounts => wallet.type == WalletType.monero; @@ -124,6 +125,7 @@ abstract class BalanceViewModelBase with Store { case WalletType.polygon: case WalletType.nano: case WalletType.banano: + case WalletType.solana: return S.current.xmr_available_balance; default: return S.current.confirmed; @@ -137,6 +139,7 @@ abstract class BalanceViewModelBase with Store { case WalletType.haven: case WalletType.ethereum: case WalletType.polygon: + case WalletType.solana: return S.current.xmr_full_balance; case WalletType.nano: case WalletType.banano: @@ -279,7 +282,18 @@ abstract class BalanceViewModelBase with Store { } @computed - bool get hasAdditionalBalance => !isEVMCompatibleChain(wallet.type); + bool get hasAdditionalBalance => _hasAdditionBalanceForWalletType(wallet.type); + + bool _hasAdditionBalanceForWalletType(WalletType type) { + switch (type) { + case WalletType.ethereum: + case WalletType.polygon: + case WalletType.solana: + return false; + default: + return true; + } + } @computed List get formattedBalances { diff --git a/lib/view_model/dashboard/home_settings_view_model.dart b/lib/view_model/dashboard/home_settings_view_model.dart index fc2c27a7c..6d31a5af8 100644 --- a/lib/view_model/dashboard/home_settings_view_model.dart +++ b/lib/view_model/dashboard/home_settings_view_model.dart @@ -3,6 +3,7 @@ import 'package:cake_wallet/entities/fiat_api_mode.dart'; import 'package:cake_wallet/entities/sort_balance_types.dart'; import 'package:cake_wallet/ethereum/ethereum.dart'; import 'package:cake_wallet/polygon/polygon.dart'; +import 'package:cake_wallet/solana/solana.dart'; import 'package:cake_wallet/store/settings_store.dart'; import 'package:cake_wallet/view_model/dashboard/balance_view_model.dart'; import 'package:cw_core/crypto_currency.dart'; @@ -16,14 +17,14 @@ class HomeSettingsViewModel = HomeSettingsViewModelBase with _$HomeSettingsViewM abstract class HomeSettingsViewModelBase with Store { HomeSettingsViewModelBase(this._settingsStore, this._balanceViewModel) - : tokens = ObservableSet() { + : tokens = ObservableSet() { _updateTokensList(); } final SettingsStore _settingsStore; final BalanceViewModel _balanceViewModel; - final ObservableSet tokens; + final ObservableSet tokens; @observable String searchText = ''; @@ -43,7 +44,7 @@ abstract class HomeSettingsViewModelBase with Store { @action void setPinNativeToken(bool value) => _settingsStore.pinNativeTokenAtTop = value; - Future addErc20Token(Erc20Token token) async { + Future addToken(CryptoCurrency token) async { if (_balanceViewModel.wallet.type == WalletType.ethereum) { await ethereum!.addErc20Token(_balanceViewModel.wallet, token); } @@ -52,23 +53,31 @@ abstract class HomeSettingsViewModelBase with Store { await polygon!.addErc20Token(_balanceViewModel.wallet, token); } + if (_balanceViewModel.wallet.type == WalletType.solana) { + await solana!.addSPLToken(_balanceViewModel.wallet, token); + } + _updateTokensList(); _updateFiatPrices(token); } - Future deleteErc20Token(Erc20Token token) async { + Future deleteToken(CryptoCurrency token) async { if (_balanceViewModel.wallet.type == WalletType.ethereum) { - await ethereum!.deleteErc20Token(_balanceViewModel.wallet, token); + await ethereum!.deleteErc20Token(_balanceViewModel.wallet, token as Erc20Token); } if (_balanceViewModel.wallet.type == WalletType.polygon) { - await polygon!.deleteErc20Token(_balanceViewModel.wallet, token); + await polygon!.deleteErc20Token(_balanceViewModel.wallet, token as Erc20Token); + } + + if (_balanceViewModel.wallet.type == WalletType.solana) { + await solana!.deleteSPLToken(_balanceViewModel.wallet, token); } _updateTokensList(); } - Future getErc20Token(String contractAddress) async { + Future getToken(String contractAddress) async { if (_balanceViewModel.wallet.type == WalletType.ethereum) { return await ethereum!.getErc20Token(_balanceViewModel.wallet, contractAddress); } @@ -77,12 +86,16 @@ abstract class HomeSettingsViewModelBase with Store { return await polygon!.getErc20Token(_balanceViewModel.wallet, contractAddress); } + if (_balanceViewModel.wallet.type == WalletType.solana) { + return await solana!.getSPLToken(_balanceViewModel.wallet, contractAddress); + } + return null; } CryptoCurrency get nativeToken => _balanceViewModel.wallet.currency; - void _updateFiatPrices(Erc20Token token) async { + void _updateFiatPrices(CryptoCurrency token) async { try { _balanceViewModel.fiatConvertationStore.prices[token] = await FiatConversionService.fetchPrice( @@ -92,20 +105,27 @@ abstract class HomeSettingsViewModelBase with Store { } catch (_) {} } - void changeTokenAvailability(Erc20Token token, bool value) async { + void changeTokenAvailability(CryptoCurrency token, bool value) async { token.enabled = value; + if (_balanceViewModel.wallet.type == WalletType.ethereum) { - ethereum!.addErc20Token(_balanceViewModel.wallet, token); + ethereum!.addErc20Token(_balanceViewModel.wallet, token as Erc20Token); } + if (_balanceViewModel.wallet.type == WalletType.polygon) { - polygon!.addErc20Token(_balanceViewModel.wallet, token); + polygon!.addErc20Token(_balanceViewModel.wallet, token as Erc20Token); } + + if (_balanceViewModel.wallet.type == WalletType.solana) { + solana!.addSPLToken(_balanceViewModel.wallet, token); + } + _refreshTokensList(); } @action void _updateTokensList() { - int _sortFunc(Erc20Token e1, Erc20Token e2) { + int _sortFunc(CryptoCurrency e1, CryptoCurrency e2) { int index1 = _balanceViewModel.formattedBalances.indexWhere((element) => element.asset == e1); int index2 = _balanceViewModel.formattedBalances.indexWhere((element) => element.asset == e2); @@ -138,6 +158,14 @@ abstract class HomeSettingsViewModelBase with Store { .toList() ..sort(_sortFunc)); } + + if (_balanceViewModel.wallet.type == WalletType.solana) { + tokens.addAll(solana! + .getSPLTokenCurrencies(_balanceViewModel.wallet) + .where((element) => _matchesSearchText(element)) + .toList() + ..sort(_sortFunc)); + } } @action @@ -153,10 +181,32 @@ abstract class HomeSettingsViewModelBase with Store { _updateTokensList(); } - bool _matchesSearchText(Erc20Token asset) { + bool _matchesSearchText(CryptoCurrency asset) { + final address = getTokenAddressBasedOnWallet(asset); + + // The homes settings would only be displayed for either of Ethereum, Polygon or Solana Wallets. + if (address == null) return false; + return searchText.isEmpty || asset.fullName!.toLowerCase().contains(searchText.toLowerCase()) || asset.title.toLowerCase().contains(searchText.toLowerCase()) || - asset.contractAddress == searchText; + address == searchText; + } + + String? getTokenAddressBasedOnWallet(CryptoCurrency asset) { + if (_balanceViewModel.wallet.type == WalletType.solana) { + return solana!.getTokenAddress(asset); + } + + if (_balanceViewModel.wallet.type == WalletType.ethereum) { + return ethereum!.getTokenAddress(asset); + } + + if (_balanceViewModel.wallet.type == WalletType.polygon) { + return polygon!.getTokenAddress(asset); + } + + // We return null if it's neither Polygin, Ethereum or Solana wallet (which is actually impossible because we only display home settings for either of these three wallets). + return null; } } diff --git a/lib/view_model/dashboard/transaction_list_item.dart b/lib/view_model/dashboard/transaction_list_item.dart index 18f55b3e5..ad40c8164 100644 --- a/lib/view_model/dashboard/transaction_list_item.dart +++ b/lib/view_model/dashboard/transaction_list_item.dart @@ -4,6 +4,7 @@ import 'package:cake_wallet/ethereum/ethereum.dart'; import 'package:cake_wallet/generated/i18n.dart'; import 'package:cake_wallet/nano/nano.dart'; import 'package:cake_wallet/polygon/polygon.dart'; +import 'package:cake_wallet/solana/solana.dart'; import 'package:cw_core/transaction_direction.dart'; import 'package:cw_core/transaction_info.dart'; import 'package:cake_wallet/store/settings_store.dart'; @@ -106,6 +107,14 @@ class TransactionListItem extends ActionListItem with Keyable { nano!.getTransactionAmountRaw(transaction).toString(), nanoUtil!.rawPerNano)), price: price); break; + case WalletType.solana: + final asset = solana!.assetOfTransaction(balanceViewModel.wallet, transaction); + final price = balanceViewModel.fiatConvertationStore.prices[asset]; + amount = calculateFiatAmountRaw( + cryptoAmount: solana!.getTransactionAmountRaw(transaction), + price: price, + ); + break; default: break; } diff --git a/lib/view_model/exchange/exchange_view_model.dart b/lib/view_model/exchange/exchange_view_model.dart index e5e68f9e4..42a15b2be 100644 --- a/lib/view_model/exchange/exchange_view_model.dart +++ b/lib/view_model/exchange/exchange_view_model.dart @@ -626,6 +626,10 @@ abstract class ExchangeViewModelBase extends WalletChangeListenerViewModel with depositCurrency = CryptoCurrency.maticpoly; receiveCurrency = CryptoCurrency.xmr; break; + case WalletType.solana: + depositCurrency = CryptoCurrency.sol; + receiveCurrency = CryptoCurrency.xmr; + break; default: break; } diff --git a/lib/view_model/node_list/node_list_view_model.dart b/lib/view_model/node_list/node_list_view_model.dart index 29ab1ed37..b78c95f70 100644 --- a/lib/view_model/node_list/node_list_view_model.dart +++ b/lib/view_model/node_list/node_list_view_model.dart @@ -78,6 +78,9 @@ abstract class NodeListViewModelBase with Store { case WalletType.polygon: node = getPolygonDefaultNode(nodes: _nodeSource)!; break; + case WalletType.solana: + node = getSolanaDefaultNode(nodes: _nodeSource)!; + break; default: throw Exception('Unexpected wallet type: ${_appStore.wallet!.type}'); } diff --git a/lib/view_model/restore/restore_from_qr_vm.dart b/lib/view_model/restore/restore_from_qr_vm.dart index 59297dfe9..d4ff5435f 100644 --- a/lib/view_model/restore/restore_from_qr_vm.dart +++ b/lib/view_model/restore/restore_from_qr_vm.dart @@ -3,6 +3,7 @@ import 'package:cake_wallet/bitcoin_cash/bitcoin_cash.dart'; import 'package:cake_wallet/ethereum/ethereum.dart'; import 'package:cake_wallet/nano/nano.dart'; import 'package:cake_wallet/polygon/polygon.dart'; +import 'package:cake_wallet/solana/solana.dart'; import 'package:cake_wallet/view_model/restore/restore_mode.dart'; import 'package:cake_wallet/view_model/restore/restore_wallet.dart'; import 'package:hive/hive.dart'; @@ -76,6 +77,9 @@ abstract class WalletRestorationFromQRVMBase extends WalletCreationVM with Store case WalletType.polygon: return polygon!.createPolygonRestoreWalletFromPrivateKey( name: name, password: password, privateKey: restoreWallet.privateKey!); + case WalletType.solana: + return solana!.createSolanaRestoreWalletFromPrivateKey( + name: name, password: password, privateKey: restoreWallet.privateKey!); default: throw Exception('Unexpected type: ${restoreWallet.type.toString()}'); } @@ -103,6 +107,9 @@ abstract class WalletRestorationFromQRVMBase extends WalletCreationVM with Store case WalletType.polygon: return polygon!.createPolygonRestoreWalletFromSeedCredentials( name: name, mnemonic: restoreWallet.mnemonicSeed ?? '', password: password); + case WalletType.solana: + return solana!.createSolanaRestoreWalletFromSeedCredentials( + name: name, mnemonic: restoreWallet.mnemonicSeed ?? '', password: password); default: throw Exception('Unexpected type: ${type.toString()}'); } diff --git a/lib/view_model/restore/wallet_restore_from_qr_code.dart b/lib/view_model/restore/wallet_restore_from_qr_code.dart index 547ebe7a6..cf145780f 100644 --- a/lib/view_model/restore/wallet_restore_from_qr_code.dart +++ b/lib/view_model/restore/wallet_restore_from_qr_code.dart @@ -35,6 +35,7 @@ class WalletRestoreFromQRCode { 'bitcoincash': WalletType.bitcoinCash, 'bitcoincash-wallet': WalletType.bitcoinCash, 'bitcoincash_wallet': WalletType.bitcoinCash, + 'solana-wallet': WalletType.solana, }; static bool _containsAssetSpecifier(String code) => _extractWalletType(code) != null; @@ -178,6 +179,14 @@ class WalletRestoreFromQRCode { return WalletRestoreMode.seed; } + if (type == WalletType.solana && credentials.containsKey('private_key')) { + final privateKey = credentials['private_key'] as String; + if (privateKey.isEmpty) { + throw Exception('Unexpected restore mode: private_key'); + } + return WalletRestoreMode.keys; + } + throw Exception('Unexpected restore mode: restore params are invalid'); } } diff --git a/lib/view_model/send/output.dart b/lib/view_model/send/output.dart index e40000139..cc39aca8b 100644 --- a/lib/view_model/send/output.dart +++ b/lib/view_model/send/output.dart @@ -148,9 +148,8 @@ abstract class OutputBase with Store { @computed String get estimatedFeeFiatAmount { try { - final currency = isEVMCompatibleChain(_wallet.type) - ? _wallet.currency - : cryptoCurrencyHandler(); + final currency = + isEVMCompatibleChain(_wallet.type) ? _wallet.currency : cryptoCurrencyHandler(); final fiat = calculateFiatAmountRaw( price: _fiatConversationStore.prices[currency]!, cryptoAmount: estimatedFee); return fiat; @@ -220,7 +219,6 @@ abstract class OutputBase with Store { final crypto = double.parse(fiatAmount.replaceAll(',', '.')) / _fiatConversationStore.prices[cryptoCurrencyHandler()]!; final cryptoAmountTmp = _cryptoNumberFormat.format(crypto); - if (cryptoAmount != cryptoAmountTmp) { cryptoAmount = cryptoAmountTmp; } @@ -252,6 +250,9 @@ abstract class OutputBase with Store { case WalletType.polygon: maximumFractionDigits = 12; break; + case WalletType.solana: + maximumFractionDigits = 12; + break; default: break; } diff --git a/lib/view_model/send/send_template_view_model.dart b/lib/view_model/send/send_template_view_model.dart index 007c4b8c0..f79fbddc7 100644 --- a/lib/view_model/send/send_template_view_model.dart +++ b/lib/view_model/send/send_template_view_model.dart @@ -52,7 +52,8 @@ abstract class SendTemplateViewModelBase with Store { bool get hasMultiRecipient => _wallet.type != WalletType.haven && _wallet.type != WalletType.ethereum && - _wallet.type != WalletType.polygon; + _wallet.type != WalletType.polygon && + _wallet.type != WalletType.solana; @computed CryptoCurrency get cryptoCurrency => _wallet.currency; diff --git a/lib/view_model/send/send_view_model.dart b/lib/view_model/send/send_view_model.dart index 885e2efe0..772150368 100644 --- a/lib/view_model/send/send_view_model.dart +++ b/lib/view_model/send/send_view_model.dart @@ -7,6 +7,7 @@ import 'package:cake_wallet/entities/contact_record.dart'; import 'package:cake_wallet/entities/wallet_contact.dart'; import 'package:cake_wallet/polygon/polygon.dart'; import 'package:cake_wallet/reactions/wallet_connect.dart'; +import 'package:cake_wallet/solana/solana.dart'; import 'package:cake_wallet/store/app_store.dart'; import 'package:cake_wallet/view_model/contact_list/contact_list_view_model.dart'; import 'package:cake_wallet/view_model/dashboard/balance_view_model.dart'; @@ -44,7 +45,7 @@ abstract class SendViewModelBase extends WalletChangeListenerViewModel with Stor void onWalletChange(wallet) { currencies = wallet.balance.keys.toList(); selectedCryptoCurrency = wallet.currency; - hasMultipleTokens = isEVMCompatibleChain(wallet.type); + hasMultipleTokens = isEVMCompatibleChain(wallet.type) || wallet.type == WalletType.solana; } SendViewModelBase( @@ -57,7 +58,8 @@ abstract class SendViewModelBase extends WalletChangeListenerViewModel with Stor ) : state = InitialExecutionState(), currencies = appStore.wallet!.balance.keys.toList(), selectedCryptoCurrency = appStore.wallet!.currency, - hasMultipleTokens = isEVMCompatibleChain(appStore.wallet!.type), + hasMultipleTokens = isEVMCompatibleChain(appStore.wallet!.type) || + appStore.wallet!.type == WalletType.solana, outputs = ObservableList(), _settingsStore = appStore.settingsStore, fiatFromSettings = appStore.settingsStore.fiatCurrency, @@ -100,6 +102,8 @@ abstract class SendViewModelBase extends WalletChangeListenerViewModel with Stor @computed bool get isBatchSending => outputs.length > 1; + bool get shouldDisplaySendALL => walletType != WalletType.solana; + @computed String get pendingTransactionFiatAmount { if (pendingTransaction == null) { @@ -297,6 +301,7 @@ abstract class SendViewModelBase extends WalletChangeListenerViewModel with Stor pendingTransaction = await wallet.createTransaction(_credentials()); state = ExecutedSuccessfullyState(); } catch (e) { + print('Failed with ${e.toString()}'); state = FailureState(e.toString()); } } @@ -351,7 +356,7 @@ abstract class SendViewModelBase extends WalletChangeListenerViewModel with Stor Object _credentials() { final priority = _settingsStore.priority[wallet.type]; - if (priority == null && wallet.type != WalletType.nano) { + if (priority == null && wallet.type != WalletType.nano && wallet.type != WalletType.solana) { throw Exception('Priority is null for wallet type: ${wallet.type}'); } @@ -377,6 +382,9 @@ abstract class SendViewModelBase extends WalletChangeListenerViewModel with Stor case WalletType.polygon: return polygon!.createPolygonTransactionCredentials(outputs, priority: priority!, currency: selectedCryptoCurrency); + case WalletType.solana: + return solana! + .createSolanaTransactionCredentials(outputs, currency: selectedCryptoCurrency); default: throw Exception('Unexpected wallet type: ${wallet.type}'); } diff --git a/lib/view_model/settings/other_settings_view_model.dart b/lib/view_model/settings/other_settings_view_model.dart index e44eb8fc7..263532d29 100644 --- a/lib/view_model/settings/other_settings_view_model.dart +++ b/lib/view_model/settings/other_settings_view_model.dart @@ -14,15 +14,14 @@ import 'package:package_info/package_info.dart'; part 'other_settings_view_model.g.dart'; -class OtherSettingsViewModel = OtherSettingsViewModelBase - with _$OtherSettingsViewModel; +class OtherSettingsViewModel = OtherSettingsViewModelBase with _$OtherSettingsViewModel; abstract class OtherSettingsViewModelBase with Store { OtherSettingsViewModelBase(this._settingsStore, this._wallet) : walletType = _wallet.type, currentVersion = '' { - PackageInfo.fromPlatform().then( - (PackageInfo packageInfo) => currentVersion = packageInfo.version); + PackageInfo.fromPlatform() + .then((PackageInfo packageInfo) => currentVersion = packageInfo.version); final priority = _settingsStore.priority[_wallet.type]; final priorities = priorityForWalletType(_wallet.type); @@ -33,8 +32,7 @@ abstract class OtherSettingsViewModelBase with Store { } final WalletType walletType; - final WalletBase, - TransactionInfo> _wallet; + final WalletBase, TransactionInfo> _wallet; @observable String currentVersion; @@ -57,12 +55,14 @@ abstract class OtherSettingsViewModelBase with Store { _wallet.type == WalletType.nano || _wallet.type == WalletType.banano; @computed - bool get isEnabledBuyAction => - !_settingsStore.disableBuy && _wallet.type != WalletType.haven; + bool get displayTransactionPriority => + !(changeRepresentativeEnabled || _wallet.type == WalletType.solana); @computed - bool get isEnabledSellAction => - !_settingsStore.disableSell && _wallet.type != WalletType.haven; + bool get isEnabledBuyAction => !_settingsStore.disableBuy && _wallet.type != WalletType.haven; + + @computed + bool get isEnabledSellAction => !_settingsStore.disableSell && _wallet.type != WalletType.haven; List get availableBuyProvidersTypes { return ProvidersHelper.getAvailableBuyProviderTypes(walletType); @@ -72,12 +72,10 @@ abstract class OtherSettingsViewModelBase with Store { ProvidersHelper.getAvailableSellProviderTypes(walletType); ProviderType get buyProviderType => - _settingsStore.defaultBuyProviders[walletType] ?? - ProviderType.askEachTime; + _settingsStore.defaultBuyProviders[walletType] ?? ProviderType.askEachTime; ProviderType get sellProviderType => - _settingsStore.defaultSellProviders[walletType] ?? - ProviderType.askEachTime; + _settingsStore.defaultSellProviders[walletType] ?? ProviderType.askEachTime; String getDisplayPriority(dynamic priority) { final _priority = priority as TransactionPriority; @@ -114,7 +112,6 @@ abstract class OtherSettingsViewModelBase with Store { _settingsStore.defaultBuyProviders[walletType] = buyProviderType; @action - ProviderType onSellProviderTypeSelected( - ProviderType sellProviderType) => + ProviderType onSellProviderTypeSelected(ProviderType sellProviderType) => _settingsStore.defaultSellProviders[walletType] = sellProviderType; } diff --git a/lib/view_model/transaction_details_view_model.dart b/lib/view_model/transaction_details_view_model.dart index 8117bb9c0..572e3b6a9 100644 --- a/lib/view_model/transaction_details_view_model.dart +++ b/lib/view_model/transaction_details_view_model.dart @@ -54,6 +54,9 @@ abstract class TransactionDetailsViewModelBase with Store { case WalletType.polygon: _addPolygonListItems(tx, dateFormat); break; + case WalletType.solana: + _addSolanaListItems(tx, dateFormat); + break; default: break; } @@ -131,6 +134,8 @@ abstract class TransactionDetailsViewModelBase with Store { return 'https://bananolooker.com/block/${txId}'; case WalletType.polygon: return 'https://polygonscan.com/tx/${txId}'; + case WalletType.solana: + return 'https://solscan.io/tx/${txId}'; default: return ''; } @@ -156,6 +161,8 @@ abstract class TransactionDetailsViewModelBase with Store { return S.current.view_transaction_on + 'bananolooker.com'; case WalletType.polygon: return S.current.view_transaction_on + 'polygonscan.com'; + case WalletType.solana: + return S.current.view_transaction_on + 'solscan.io'; default: return ''; } @@ -282,4 +289,21 @@ abstract class TransactionDetailsViewModelBase with Store { items.addAll(_items); } + + void _addSolanaListItems(TransactionInfo tx, DateFormat dateFormat) { + final _items = [ + StandartListItem(title: S.current.transaction_details_transaction_id, value: tx.id), + StandartListItem( + title: S.current.transaction_details_date, value: dateFormat.format(tx.date)), + StandartListItem(title: S.current.transaction_details_amount, value: tx.amountFormatted()), + if (tx.feeFormatted()?.isNotEmpty ?? false) + StandartListItem(title: S.current.transaction_details_fee, value: tx.feeFormatted()!), + if (showRecipientAddress && tx.to != null) + StandartListItem(title: S.current.transaction_details_recipient_address, value: tx.to!), + if (tx.from != null) + StandartListItem(title: S.current.transaction_details_source_address, value: tx.from!), + ]; + + items.addAll(_items); + } } diff --git a/lib/view_model/wallet_address_list/wallet_address_list_view_model.dart b/lib/view_model/wallet_address_list/wallet_address_list_view_model.dart index ffeeebb22..c5618b6ae 100644 --- a/lib/view_model/wallet_address_list/wallet_address_list_view_model.dart +++ b/lib/view_model/wallet_address_list/wallet_address_list_view_model.dart @@ -7,6 +7,7 @@ import 'package:cake_wallet/generated/i18n.dart'; import 'package:cake_wallet/haven/haven.dart'; import 'package:cake_wallet/monero/monero.dart'; import 'package:cake_wallet/polygon/polygon.dart'; +import 'package:cake_wallet/solana/solana.dart'; import 'package:cake_wallet/store/app_store.dart'; import 'package:cake_wallet/store/dashboard/fiat_conversion_store.dart'; import 'package:cake_wallet/store/settings_store.dart'; @@ -169,6 +170,21 @@ class PolygonURI extends PaymentURI { } } +class SolanaURI extends PaymentURI { + SolanaURI({required String amount, required String address}) + : super(amount: amount, address: address); + + @override + String toString() { + var base = 'solana:' + address; + if (amount.isNotEmpty) { + base += '?amount=${amount.replaceAll(',', '.')}'; + } + + return base; + } +} + abstract class WalletAddressListViewModelBase extends WalletChangeListenerViewModel with Store { WalletAddressListViewModelBase({ required AppStore appStore, @@ -271,6 +287,10 @@ abstract class WalletAddressListViewModelBase extends WalletChangeListenerViewMo return PolygonURI(amount: amount, address: address.address); } + if (wallet.type == WalletType.solana) { + return SolanaURI(amount: amount, address: address.address); + } + throw Exception('Unexpected type: ${type.toString()}'); } @@ -340,6 +360,12 @@ abstract class WalletAddressListViewModelBase extends WalletChangeListenerViewMo addressList.add(WalletAddressListItem(isPrimary: true, name: null, address: primaryAddress)); } + if (wallet.type == WalletType.solana) { + final primaryAddress = solana!.getAddress(wallet); + + addressList.add(WalletAddressListItem(isPrimary: true, name: null, address: primaryAddress)); + } + if (searchText.isNotEmpty) { return ObservableList.of(addressList.where((item) { if (item is WalletAddressListItem) { diff --git a/lib/view_model/wallet_keys_view_model.dart b/lib/view_model/wallet_keys_view_model.dart index 1a9bd56ce..7cd0d3a76 100644 --- a/lib/view_model/wallet_keys_view_model.dart +++ b/lib/view_model/wallet_keys_view_model.dart @@ -112,7 +112,8 @@ abstract class WalletKeysViewModelBase with Store { ]); } - if (isEVMCompatibleChain(_appStore.wallet!.type)) { + if (isEVMCompatibleChain(_appStore.wallet!.type) || + _appStore.wallet!.type == WalletType.solana) { items.addAll([ if (_appStore.wallet!.privateKey != null) StandartListItem(title: S.current.private_key, value: _appStore.wallet!.privateKey!), @@ -169,6 +170,8 @@ abstract class WalletKeysViewModelBase with Store { return 'polygon-wallet'; case WalletType.lightning: return 'lightning-wallet'; + case WalletType.solana: + return 'solana-wallet'; default: throw Exception('Unexpected wallet type: ${_appStore.wallet!.toString()}'); } diff --git a/lib/view_model/wallet_new_vm.dart b/lib/view_model/wallet_new_vm.dart index ef7c33e04..f950838ce 100644 --- a/lib/view_model/wallet_new_vm.dart +++ b/lib/view_model/wallet_new_vm.dart @@ -1,6 +1,7 @@ import 'package:cake_wallet/ethereum/ethereum.dart'; import 'package:cake_wallet/bitcoin_cash/bitcoin_cash.dart'; import 'package:cake_wallet/lightning/lightning.dart'; +import 'package:cake_wallet/solana/solana.dart'; import 'package:hive/hive.dart'; import 'package:mobx/mobx.dart'; import 'package:cake_wallet/monero/monero.dart'; @@ -37,19 +38,21 @@ abstract class WalletNewVMBase extends WalletCreationVM with Store { bool get hasLanguageSelector => type == WalletType.monero || type == WalletType.haven; int get seedPhraseWordsLength { - switch (type) { - case WalletType.monero: - if(advancedPrivacySettingsViewModel.isPolySeed) { - return 16; - } - return 25; - case WalletType.ethereum: - case WalletType.bitcoinCash: - return advancedPrivacySettingsViewModel.seedPhraseLength.value; - default: - return 24; - } + switch (type) { + case WalletType.monero: + if (advancedPrivacySettingsViewModel.isPolySeed) { + return 16; + } + return 25; + case WalletType.solana: + case WalletType.polygon: + case WalletType.ethereum: + case WalletType.bitcoinCash: + return advancedPrivacySettingsViewModel.seedPhraseLength.value; + default: + return 24; } + } bool get hasSeedType => type == WalletType.monero; @@ -68,8 +71,8 @@ abstract class WalletNewVMBase extends WalletCreationVM with Store { case WalletType.litecoin: return bitcoin!.createBitcoinNewWalletCredentials(name: name); case WalletType.haven: - return haven!.createHavenNewWalletCredentials( - name: name, language: options!.first as String); + return haven! + .createHavenNewWalletCredentials(name: name, language: options!.first as String); case WalletType.ethereum: return ethereum!.createEthereumNewWalletCredentials(name: name); case WalletType.bitcoinCash: @@ -78,6 +81,8 @@ abstract class WalletNewVMBase extends WalletCreationVM with Store { return nano!.createNanoNewWalletCredentials(name: name); case WalletType.polygon: return polygon!.createPolygonNewWalletCredentials(name: name); + case WalletType.solana: + return solana!.createSolanaNewWalletCredentials(name: name); default: throw Exception('Unexpected type: ${type.toString()}'); } diff --git a/lib/view_model/wallet_restore_view_model.dart b/lib/view_model/wallet_restore_view_model.dart index bc4e6af15..8ad9d830d 100644 --- a/lib/view_model/wallet_restore_view_model.dart +++ b/lib/view_model/wallet_restore_view_model.dart @@ -4,6 +4,7 @@ import 'package:cake_wallet/nano/nano.dart'; import 'package:cake_wallet/ethereum/ethereum.dart'; import 'package:cake_wallet/bitcoin_cash/bitcoin_cash.dart'; import 'package:cake_wallet/polygon/polygon.dart'; +import 'package:cake_wallet/solana/solana.dart'; import 'package:hive/hive.dart'; import 'package:mobx/mobx.dart'; import 'package:cake_wallet/store/app_store.dart'; @@ -28,11 +29,11 @@ abstract class WalletRestoreViewModelBase extends WalletCreationVM with Store { {required WalletType type}) : hasSeedLanguageSelector = type == WalletType.monero || type == WalletType.haven, hasBlockchainHeightLanguageSelector = type == WalletType.monero || type == WalletType.haven, - hasRestoreFromPrivateKey = - type == WalletType.ethereum || + hasRestoreFromPrivateKey = type == WalletType.ethereum || type == WalletType.polygon || type == WalletType.nano || - type == WalletType.banano, + type == WalletType.banano || + type == WalletType.solana, isButtonEnabled = false, mode = WalletRestoreMode.seed, super(appStore, walletInfoSource, walletCreationService, type: type, isRecovery: true) { @@ -45,6 +46,7 @@ abstract class WalletRestoreViewModelBase extends WalletCreationVM with Store { break; case WalletType.nano: case WalletType.banano: + case WalletType.solana: availableModes = [WalletRestoreMode.seed, WalletRestoreMode.keys]; break; default: @@ -104,22 +106,21 @@ abstract class WalletRestoreViewModelBase extends WalletCreationVM with Store { name: name, height: height, mnemonic: seed, password: password); case WalletType.ethereum: return ethereum!.createEthereumRestoreWalletFromSeedCredentials( - name: name, - mnemonic: seed, - password: password); + name: name, mnemonic: seed, password: password); case WalletType.bitcoinCash: return bitcoinCash!.createBitcoinCashRestoreWalletFromSeedCredentials( - name: name, - mnemonic: seed, - password: password); + name: name, mnemonic: seed, password: password); case WalletType.nano: return nano!.createNanoRestoreWalletFromSeedCredentials( + name: name, mnemonic: seed, password: password, derivationType: derivationType); + case WalletType.polygon: + return polygon!.createPolygonRestoreWalletFromSeedCredentials( name: name, mnemonic: seed, password: password, - derivationType: derivationType); - case WalletType.polygon: - return polygon!.createPolygonRestoreWalletFromSeedCredentials( + ); + case WalletType.solana: + return solana!.createSolanaRestoreWalletFromSeedCredentials( name: name, mnemonic: seed, password: password, @@ -166,16 +167,22 @@ abstract class WalletRestoreViewModelBase extends WalletCreationVM with Store { case WalletType.nano: return nano!.createNanoRestoreWalletFromKeysCredentials( - name: name, - password: password, - seedKey: options['private_key'] as String, - derivationType: options["derivationType"] as DerivationType); + name: name, + password: password, + seedKey: options['private_key'] as String, + derivationType: options["derivationType"] as DerivationType); case WalletType.polygon: return polygon!.createPolygonRestoreWalletFromPrivateKey( name: name, password: password, privateKey: options['private_key'] as String, ); + case WalletType.solana: + return solana!.createSolanaRestoreWalletFromPrivateKey( + name: name, + password: password, + privateKey: options['private_key'] as String, + ); default: break; } @@ -193,10 +200,8 @@ abstract class WalletRestoreViewModelBase extends WalletCreationVM with Store { switch (type) { case WalletType.nano: - return nanoUtil!.compareDerivationMethods( - mnemonic: mnemonic, - privateKey: seedKey, - node: node); + return nanoUtil! + .compareDerivationMethods(mnemonic: mnemonic, privateKey: seedKey, node: node); default: break; } diff --git a/model_generator.sh b/model_generator.sh index 9d46b88d9..a5b78089f 100755 --- a/model_generator.sh +++ b/model_generator.sh @@ -6,6 +6,7 @@ cd cw_haven && flutter pub get && flutter packages pub run build_runner build -- cd cw_nano && flutter pub get && flutter packages pub run build_runner build --delete-conflicting-outputs && cd .. cd cw_bitcoin_cash && flutter pub get && flutter packages pub run build_runner build --delete-conflicting-outputs && cd .. cd cw_lightning && flutter pub get && flutter packages pub run build_runner build --delete-conflicting-outputs && cd .. +cd cw_solana && flutter pub get && flutter packages pub run build_runner build --delete-conflicting-outputs && cd .. cd cw_ethereum && flutter pub get && cd .. cd cw_polygon && flutter pub get && cd .. flutter packages pub run build_runner build --delete-conflicting-outputs diff --git a/pubspec_base.yaml b/pubspec_base.yaml index 813fe6750..f3651a474 100644 --- a/pubspec_base.yaml +++ b/pubspec_base.yaml @@ -106,6 +106,7 @@ dependencies: flutter_svg: ^2.0.9 polyseed: ^0.0.2 nostr_tools: ^1.0.9 + solana: ^0.30.1 breez_sdk: git: @@ -160,6 +161,7 @@ flutter: - assets/nano_node_list.yml - assets/nano_pow_node_list.yml - assets/polygon_node_list.yml + - assets/solana_node_list.yml - assets/text/ - assets/faq/ - assets/animation/ diff --git a/res/values/strings_ar.arb b/res/values/strings_ar.arb index 01c6a4783..c6ec298ca 100644 --- a/res/values/strings_ar.arb +++ b/res/values/strings_ar.arb @@ -781,5 +781,6 @@ "you_pay": "انت تدفع", "you_will_get": "حول الى", "you_will_send": "تحويل من", - "yy": "YY" -} \ No newline at end of file + "yy": "YY", + "waitFewSecondForTxUpdate": "ﺕﻼﻣﺎﻌﻤﻟﺍ ﻞﺠﺳ ﻲﻓ ﺔﻠﻣﺎﻌﻤﻟﺍ ﺲﻜﻌﻨﺗ ﻰﺘﺣ ﻥﺍﻮﺛ ﻊﻀﺒﻟ ﺭﺎﻈﺘﻧﻻﺍ ﻰﺟﺮﻳ" +} diff --git a/res/values/strings_bg.arb b/res/values/strings_bg.arb index cbf4ff851..54ecf5042 100644 --- a/res/values/strings_bg.arb +++ b/res/values/strings_bg.arb @@ -781,5 +781,6 @@ "you_pay": "Вие плащате", "you_will_get": "Обръщане в", "you_will_send": "Обръщане от", - "yy": "гг" -} \ No newline at end of file + "yy": "гг", + "waitFewSecondForTxUpdate": "Моля, изчакайте няколко секунди, докато транзакцията се отрази в историята на транзакциите" +} diff --git a/res/values/strings_cs.arb b/res/values/strings_cs.arb index 492d2a4df..285533110 100644 --- a/res/values/strings_cs.arb +++ b/res/values/strings_cs.arb @@ -781,5 +781,6 @@ "you_pay": "Zaplatíte", "you_will_get": "Směnit na", "you_will_send": "Směnit z", - "yy": "YY" -} \ No newline at end of file + "yy": "YY", + "waitFewSecondForTxUpdate": "Počkejte několik sekund, než se transakce projeví v historii transakcí" +} diff --git a/res/values/strings_de.arb b/res/values/strings_de.arb index 70bfbad2d..002399aa0 100644 --- a/res/values/strings_de.arb +++ b/res/values/strings_de.arb @@ -784,5 +784,6 @@ "you_pay": "Sie bezahlen", "you_will_get": "Konvertieren zu", "you_will_send": "Konvertieren von", - "yy": "YY" -} \ No newline at end of file + "yy": "YY", + "waitFewSecondForTxUpdate": "Bitte warten Sie einige Sekunden, bis die Transaktion im Transaktionsverlauf angezeigt wird" +} diff --git a/res/values/strings_en.arb b/res/values/strings_en.arb index 68a348337..38e1313f6 100644 --- a/res/values/strings_en.arb +++ b/res/values/strings_en.arb @@ -781,5 +781,6 @@ "you_pay": "You Pay", "you_will_get": "Convert to", "you_will_send": "Convert from", - "yy": "YY" -} \ No newline at end of file + "yy": "YY", + "waitFewSecondForTxUpdate": "Kindly wait for a few seconds for transaction to reflect in transactions history" +} diff --git a/res/values/strings_es.arb b/res/values/strings_es.arb index d9b222d01..2f3ca878a 100644 --- a/res/values/strings_es.arb +++ b/res/values/strings_es.arb @@ -782,5 +782,6 @@ "you_pay": "Tú pagas", "you_will_get": "Convertir a", "you_will_send": "Convertir de", - "yy": "YY" -} \ No newline at end of file + "yy": "YY", + "waitFewSecondForTxUpdate": "Espere unos segundos para que la transacción se refleje en el historial de transacciones." +} diff --git a/res/values/strings_fr.arb b/res/values/strings_fr.arb index 87d6be4cf..0acd685ef 100644 --- a/res/values/strings_fr.arb +++ b/res/values/strings_fr.arb @@ -781,5 +781,6 @@ "you_pay": "Vous payez", "you_will_get": "Convertir vers", "you_will_send": "Convertir depuis", - "yy": "AA" -} \ No newline at end of file + "yy": "AA", + "waitFewSecondForTxUpdate": "Veuillez attendre quelques secondes pour que la transaction soit reflétée dans l'historique des transactions." +} diff --git a/res/values/strings_ha.arb b/res/values/strings_ha.arb index 9f2226a3c..92635c6fb 100644 --- a/res/values/strings_ha.arb +++ b/res/values/strings_ha.arb @@ -783,5 +783,6 @@ "you_pay": "Ka Bayar", "you_will_get": "Maida zuwa", "you_will_send": "Maida daga", - "yy": "YY" -} \ No newline at end of file + "yy": "YY", + "waitFewSecondForTxUpdate": "Da fatan za a jira ƴan daƙiƙa don ciniki don yin tunani a tarihin ma'amala" +} diff --git a/res/values/strings_hi.arb b/res/values/strings_hi.arb index c838ad785..e28fae871 100644 --- a/res/values/strings_hi.arb +++ b/res/values/strings_hi.arb @@ -783,5 +783,6 @@ "you_pay": "आप भुगतान करते हैं", "you_will_get": "में बदलें", "you_will_send": "से रूपांतरित करें", - "yy": "वाईवाई" -} \ No newline at end of file + "yy": "वाईवाई", + "waitFewSecondForTxUpdate": "लेन-देन इतिहास में लेन-देन प्रतिबिंबित होने के लिए कृपया कुछ सेकंड प्रतीक्षा करें" +} diff --git a/res/values/strings_hr.arb b/res/values/strings_hr.arb index b942ffa02..8dfcaad8e 100644 --- a/res/values/strings_hr.arb +++ b/res/values/strings_hr.arb @@ -781,5 +781,6 @@ "you_pay": "Vi plaćate", "you_will_get": "Razmijeni u", "you_will_send": "Razmijeni iz", - "yy": "GG" -} \ No newline at end of file + "yy": "GG", + "waitFewSecondForTxUpdate": "Pričekajte nekoliko sekundi da se transakcija prikaže u povijesti transakcija" +} diff --git a/res/values/strings_id.arb b/res/values/strings_id.arb index f3cf552cf..a826c536c 100644 --- a/res/values/strings_id.arb +++ b/res/values/strings_id.arb @@ -784,5 +784,6 @@ "you_pay": "Anda Membayar", "you_will_get": "Konversi ke", "you_will_send": "Konversi dari", - "yy": "YY" -} \ No newline at end of file + "yy": "YY", + "waitFewSecondForTxUpdate": "Mohon tunggu beberapa detik hingga transaksi terlihat di riwayat transaksi" +} diff --git a/res/values/strings_it.arb b/res/values/strings_it.arb index effd62c89..a17718e66 100644 --- a/res/values/strings_it.arb +++ b/res/values/strings_it.arb @@ -784,5 +784,6 @@ "you_pay": "Tu paghi", "you_will_get": "Converti a", "you_will_send": "Conveti da", - "yy": "YY" -} \ No newline at end of file + "yy": "YY", + "waitFewSecondForTxUpdate": "Attendi qualche secondo affinché la transazione venga riflessa nella cronologia delle transazioni" +} diff --git a/res/values/strings_ja.arb b/res/values/strings_ja.arb index 922037b1a..94f712325 100644 --- a/res/values/strings_ja.arb +++ b/res/values/strings_ja.arb @@ -782,5 +782,6 @@ "you_pay": "あなたが支払う", "you_will_get": "に変換", "you_will_send": "から変換", - "yy": "YY" -} \ No newline at end of file + "yy": "YY", + "waitFewSecondForTxUpdate": "取引履歴に取引が反映されるまで数秒お待ちください。" +} diff --git a/res/values/strings_ko.arb b/res/values/strings_ko.arb index bb520a54f..7149d8873 100644 --- a/res/values/strings_ko.arb +++ b/res/values/strings_ko.arb @@ -783,5 +783,6 @@ "you_will_get": "로 변환하다", "you_will_send": "다음에서 변환", "YY": "YY", - "yy": "YY" -} \ No newline at end of file + "yy": "YY", + "waitFewSecondForTxUpdate": "거래 내역에 거래가 반영될 때까지 몇 초 정도 기다려 주세요." +} diff --git a/res/values/strings_my.arb b/res/values/strings_my.arb index 5bfeaf273..8c2455290 100644 --- a/res/values/strings_my.arb +++ b/res/values/strings_my.arb @@ -781,5 +781,6 @@ "you_pay": "သင်ပေးချေပါ။", "you_will_get": "သို့ပြောင်းပါ။", "you_will_send": "မှပြောင်းပါ။", - "yy": "YY" -} \ No newline at end of file + "yy": "YY", + "waitFewSecondForTxUpdate": "ငွေပေးငွေယူ မှတ်တမ်းတွင် ရောင်ပြန်ဟပ်ရန် စက္ကန့်အနည်းငယ်စောင့်ပါ။" +} diff --git a/res/values/strings_nl.arb b/res/values/strings_nl.arb index c418e53ca..3e3a5ffd2 100644 --- a/res/values/strings_nl.arb +++ b/res/values/strings_nl.arb @@ -782,5 +782,6 @@ "you_pay": "U betaalt", "you_will_get": "Converteren naar", "you_will_send": "Converteren van", - "yy": "JJ" -} \ No newline at end of file + "yy": "JJ", + "waitFewSecondForTxUpdate": "Wacht een paar seconden totdat de transactie wordt weergegeven in de transactiegeschiedenis" +} diff --git a/res/values/strings_pl.arb b/res/values/strings_pl.arb index 71cb2b6c6..dd5a14157 100644 --- a/res/values/strings_pl.arb +++ b/res/values/strings_pl.arb @@ -781,5 +781,6 @@ "you_pay": "Płacisz", "you_will_get": "Konwertuj na", "you_will_send": "Konwertuj z", - "yy": "RR" -} \ No newline at end of file + "yy": "RR", + "waitFewSecondForTxUpdate": "Poczekaj kilka sekund, aż transakcja zostanie odzwierciedlona w historii transakcji" +} diff --git a/res/values/strings_pt.arb b/res/values/strings_pt.arb index 334b26e2f..705dab853 100644 --- a/res/values/strings_pt.arb +++ b/res/values/strings_pt.arb @@ -784,5 +784,6 @@ "you_pay": "Você paga", "you_will_get": "Converter para", "you_will_send": "Converter de", - "yy": "aa" -} \ No newline at end of file + "yy": "aa", + "waitFewSecondForTxUpdate": "Aguarde alguns segundos para que a transação seja refletida no histórico de transações" +} diff --git a/res/values/strings_ru.arb b/res/values/strings_ru.arb index e6de959ac..9adc49596 100644 --- a/res/values/strings_ru.arb +++ b/res/values/strings_ru.arb @@ -782,5 +782,6 @@ "you_pay": "Вы платите", "you_will_get": "Конвертировать в", "you_will_send": "Конвертировать из", - "yy": "ГГ" -} \ No newline at end of file + "yy": "ГГ", + "waitFewSecondForTxUpdate": "Пожалуйста, подождите несколько секунд, чтобы транзакция отразилась в истории транзакций." +} diff --git a/res/values/strings_th.arb b/res/values/strings_th.arb index c64721a00..5365d4007 100644 --- a/res/values/strings_th.arb +++ b/res/values/strings_th.arb @@ -781,5 +781,6 @@ "you_pay": "คุณจ่าย", "you_will_get": "แปลงเป็น", "you_will_send": "แปลงจาก", - "yy": "ปี" -} \ No newline at end of file + "yy": "ปี", + "waitFewSecondForTxUpdate": "กรุณารอสักครู่เพื่อให้ธุรกรรมปรากฏในประวัติการทำธุรกรรม" +} diff --git a/res/values/strings_tl.arb b/res/values/strings_tl.arb index 7e47d07ef..5a2e103e9 100644 --- a/res/values/strings_tl.arb +++ b/res/values/strings_tl.arb @@ -781,5 +781,6 @@ "you_pay": "Magbabayad ka", "you_will_get": "Mag -convert sa", "you_will_send": "I -convert mula sa", - "yy": "YY" -} \ No newline at end of file + "yy": "YY", + "waitFewSecondForTxUpdate": "Mangyaring maghintay ng ilang segundo para makita ang transaksyon sa history ng mga transaksyon" +} diff --git a/res/values/strings_tr.arb b/res/values/strings_tr.arb index 86ab454e2..ca9a991a7 100644 --- a/res/values/strings_tr.arb +++ b/res/values/strings_tr.arb @@ -781,5 +781,6 @@ "you_pay": "Şu kadar ödeyeceksin: ", "you_will_get": "Biçimine dönüştür:", "you_will_send": "Biçiminden dönüştür:", - "yy": "YY" -} \ No newline at end of file + "yy": "YY", + "waitFewSecondForTxUpdate": "İşlemin işlem geçmişine yansıması için lütfen birkaç saniye bekleyin" +} diff --git a/res/values/strings_uk.arb b/res/values/strings_uk.arb index 90102dc1f..97ff6dda9 100644 --- a/res/values/strings_uk.arb +++ b/res/values/strings_uk.arb @@ -782,5 +782,6 @@ "you_pay": "Ви платите", "you_will_get": "Конвертувати в", "you_will_send": "Конвертувати з", - "yy": "YY" -} \ No newline at end of file + "yy": "YY", + "waitFewSecondForTxUpdate": "Будь ласка, зачекайте кілька секунд, поки транзакція відобразиться в історії транзакцій" +} diff --git a/res/values/strings_ur.arb b/res/values/strings_ur.arb index 387db7354..b9bb6ec54 100644 --- a/res/values/strings_ur.arb +++ b/res/values/strings_ur.arb @@ -783,5 +783,6 @@ "you_pay": "تم ادا کرو", "you_will_get": "میں تبدیل کریں۔", "you_will_send": "سے تبدیل کریں۔", - "yy": "YY" -} \ No newline at end of file + "yy": "YY", + "waitFewSecondForTxUpdate": "۔ﮟﯾﺮﮐ ﺭﺎﻈﺘﻧﺍ ﺎﮐ ﮉﻨﮑﯿﺳ ﺪﻨﭼ ﻡﺮﮐ ﮦﺍﺮﺑ ﮯﯿﻟ ﮯﮐ ﮯﻧﺮﮐ ﯽﺳﺎﮑﻋ ﯽﮐ ﻦﯾﺩ ﻦﯿﻟ ﮟﯿﻣ ﺦﯾﺭﺎﺗ ﯽﮐ ﻦ" +} diff --git a/res/values/strings_yo.arb b/res/values/strings_yo.arb index 22e4a181b..c5e156f4b 100644 --- a/res/values/strings_yo.arb +++ b/res/values/strings_yo.arb @@ -782,5 +782,6 @@ "you_pay": "Ẹ sàn", "you_will_get": "Ṣe pàṣípààrọ̀ sí", "you_will_send": "Ṣe pàṣípààrọ̀ láti", - "yy": "Ọd" -} \ No newline at end of file + "yy": "Ọd", + "waitFewSecondForTxUpdate": "Fi inurere duro fun awọn iṣeju diẹ fun idunadura lati ṣe afihan ninu itan-akọọlẹ iṣowo" +} diff --git a/res/values/strings_zh.arb b/res/values/strings_zh.arb index 0ca23c9a6..456dd8caa 100644 --- a/res/values/strings_zh.arb +++ b/res/values/strings_zh.arb @@ -781,5 +781,6 @@ "you_pay": "你付钱", "you_will_get": "转换到", "you_will_send": "转换自", - "yy": "YY" -} \ No newline at end of file + "yy": "YY", + "waitFewSecondForTxUpdate": "请等待几秒钟,交易才会反映在交易历史记录中" +} diff --git a/scripts/android/pubspec_gen.sh b/scripts/android/pubspec_gen.sh index 5c22c6ddd..7c5b20a35 100755 --- a/scripts/android/pubspec_gen.sh +++ b/scripts/android/pubspec_gen.sh @@ -10,7 +10,7 @@ case $APP_ANDROID_TYPE in CONFIG_ARGS="--monero" ;; $CAKEWALLET) - CONFIG_ARGS="--monero --bitcoin --haven --ethereum --polygon --nano --bitcoinCash --lightning" + CONFIG_ARGS="--monero --bitcoin --haven --ethereum --polygon --nano --bitcoinCash --lightning --solana" ;; $HAVEN) CONFIG_ARGS="--haven" diff --git a/scripts/ios/app_config.sh b/scripts/ios/app_config.sh index 10e264c40..a669918ec 100755 --- a/scripts/ios/app_config.sh +++ b/scripts/ios/app_config.sh @@ -28,7 +28,7 @@ case $APP_IOS_TYPE in CONFIG_ARGS="--monero" ;; $CAKEWALLET) - CONFIG_ARGS="--monero --bitcoin --haven --ethereum --polygon --nano --bitcoinCash --lightning" + CONFIG_ARGS="--monero --bitcoin --haven --ethereum --polygon --nano --bitcoinCash --lightning --solana" ;; $HAVEN) diff --git a/scripts/macos/app_config.sh b/scripts/macos/app_config.sh index bcd5c23c6..56f7a3bf6 100755 --- a/scripts/macos/app_config.sh +++ b/scripts/macos/app_config.sh @@ -31,7 +31,7 @@ case $APP_MACOS_TYPE in $MONERO_COM) CONFIG_ARGS="--monero";; $CAKEWALLET) - CONFIG_ARGS="--monero --bitcoin --ethereum --polygon --nano --bitcoinCash --lightning";; #--haven + CONFIG_ARGS="--monero --bitcoin --ethereum --polygon --nano --bitcoinCash --lightning --solana";; #--haven esac cp -rf pubspec_description.yaml pubspec.yaml diff --git a/tool/configure.dart b/tool/configure.dart index b1e852945..d1516d941 100644 --- a/tool/configure.dart +++ b/tool/configure.dart @@ -8,6 +8,7 @@ const bitcoinCashOutputPath = 'lib/bitcoin_cash/bitcoin_cash.dart'; const nanoOutputPath = 'lib/nano/nano.dart'; const polygonOutputPath = 'lib/polygon/polygon.dart'; const lightningOutputPath = 'lib/lightning/lightning.dart'; +const solanaOutputPath = 'lib/solana/solana.dart'; const walletTypesPath = 'lib/wallet_types.g.dart'; const pubspecDefaultPath = 'pubspec_default.yaml'; const pubspecOutputPath = 'pubspec.yaml'; @@ -23,6 +24,7 @@ Future main(List args) async { final hasBanano = args.contains('${prefix}banano'); final hasPolygon = args.contains('${prefix}polygon'); final hasLightning = args.contains('${prefix}lightning'); + final hasSolana = args.contains('${prefix}solana'); await generateBitcoin(hasBitcoin); await generateMonero(hasMonero); @@ -32,6 +34,7 @@ Future main(List args) async { await generateNano(hasNano); await generatePolygon(hasPolygon); await generateLightning(hasLightning); + await generateSolana(hasSolana); // await generateBanano(hasEthereum); await generatePubspec( @@ -44,6 +47,7 @@ Future main(List args) async { hasBitcoinCash: hasBitcoinCash, hasPolygon: hasPolygon, hasLightning: hasLightning, + hasSolana: hasSolana, ); await generateWalletTypes( hasMonero: hasMonero, @@ -55,6 +59,7 @@ Future main(List args) async { hasBitcoinCash: hasBitcoinCash, hasPolygon: hasPolygon, hasLightning: hasLightning, + hasSolana: hasSolana, ); } @@ -582,13 +587,14 @@ abstract class Ethereum { int formatterEthereumParseAmount(String amount); double formatterEthereumAmountToDouble({TransactionInfo? transaction, BigInt? amount, int exponent = 18}); List getERC20Currencies(WalletBase wallet); - Future addErc20Token(WalletBase wallet, Erc20Token token); - Future deleteErc20Token(WalletBase wallet, Erc20Token token); + Future addErc20Token(WalletBase wallet, CryptoCurrency token); + Future deleteErc20Token(WalletBase wallet, CryptoCurrency token); Future getErc20Token(WalletBase wallet, String contractAddress); CryptoCurrency assetOfTransaction(WalletBase wallet, TransactionInfo transaction); void updateEtherscanUsageState(WalletBase wallet, bool isEnabled); Web3Client? getWeb3Client(WalletBase wallet); + String getTokenAddress(CryptoCurrency asset); } """; @@ -674,13 +680,14 @@ abstract class Polygon { int formatterPolygonParseAmount(String amount); double formatterPolygonAmountToDouble({TransactionInfo? transaction, BigInt? amount, int exponent = 18}); List getERC20Currencies(WalletBase wallet); - Future addErc20Token(WalletBase wallet, Erc20Token token); - Future deleteErc20Token(WalletBase wallet, Erc20Token token); + Future addErc20Token(WalletBase wallet, CryptoCurrency token); + Future deleteErc20Token(WalletBase wallet, CryptoCurrency token); Future getErc20Token(WalletBase wallet, String contractAddress); CryptoCurrency assetOfTransaction(WalletBase wallet, TransactionInfo transaction); void updatePolygonScanUsageState(WalletBase wallet, bool isEnabled); Web3Client? getWeb3Client(WalletBase wallet); + String getTokenAddress(CryptoCurrency asset); } """; @@ -978,6 +985,86 @@ abstract class NanoUtil { await outputFile.writeAsString(output); } +Future generateSolana(bool hasImplementation) async { + final outputFile = File(solanaOutputPath); + const solanaCommonHeaders = """ +import 'package:cake_wallet/view_model/send/output.dart'; +import 'package:cw_core/crypto_currency.dart'; +import 'package:cw_core/output_info.dart'; +import 'package:cw_core/transaction_info.dart'; +import 'package:cw_core/wallet_base.dart'; +import 'package:cw_core/wallet_credentials.dart'; +import 'package:cw_core/wallet_info.dart'; +import 'package:cw_core/wallet_service.dart'; +import 'package:hive/hive.dart'; + +"""; + const solanaCWHeaders = """ +import 'package:cw_solana/spl_token.dart'; +import 'package:cw_solana/solana_wallet.dart'; +import 'package:cw_solana/solana_mnemonics.dart'; +import 'package:cw_solana/solana_wallet_service.dart'; +import 'package:cw_solana/solana_transaction_info.dart'; +import 'package:cw_solana/solana_transaction_credentials.dart'; +import 'package:cw_solana/solana_wallet_creation_credentials.dart'; +import 'package:solana/solana.dart'; +"""; + const solanaCwPart = "part 'cw_solana.dart';"; + const solanaContent = """ +abstract class Solana { + List getSolanaWordList(String language); + WalletService createSolanaWalletService(Box walletInfoSource); + WalletCredentials createSolanaNewWalletCredentials( + {required String name, WalletInfo? walletInfo}); + WalletCredentials createSolanaRestoreWalletFromSeedCredentials( + {required String name, required String mnemonic, required String password}); + WalletCredentials createSolanaRestoreWalletFromPrivateKey( + {required String name, required String privateKey, required String password}); + + String getAddress(WalletBase wallet); + String getPrivateKey(WalletBase wallet); + String getPublicKey(WalletBase wallet); + Ed25519HDKeyPair? getWalletKeyPair(WalletBase wallet); + + Object createSolanaTransactionCredentials( + List outputs, { + required CryptoCurrency currency, + }); + + Object createSolanaTransactionCredentialsRaw( + List outputs, { + required CryptoCurrency currency, + }); + List getSPLTokenCurrencies(WalletBase wallet); + Future addSPLToken(WalletBase wallet, CryptoCurrency token); + Future deleteSPLToken(WalletBase wallet, CryptoCurrency token); + Future getSPLToken(WalletBase wallet, String contractAddress); + + CryptoCurrency assetOfTransaction(WalletBase wallet, TransactionInfo transaction); + double getTransactionAmountRaw(TransactionInfo transactionInfo); + String getTokenAddress(CryptoCurrency asset); + List? getValidationLength(CryptoCurrency type); +} + + """; + + const solanaEmptyDefinition = 'Solana? solana;\n'; + const solanaCWDefinition = 'Solana? solana = CWSolana();\n'; + + final output = '$solanaCommonHeaders\n' + + (hasImplementation ? '$solanaCWHeaders\n' : '\n') + + (hasImplementation ? '$solanaCwPart\n\n' : '\n') + + (hasImplementation ? solanaCWDefinition : solanaEmptyDefinition) + + '\n' + + solanaContent; + + if (outputFile.existsSync()) { + await outputFile.delete(); + } + + await outputFile.writeAsString(output); +} + Future generatePubspec( {required bool hasMonero, required bool hasBitcoin, @@ -987,7 +1074,8 @@ Future generatePubspec( required bool hasBanano, required bool hasBitcoinCash, required bool hasPolygon, - required bool hasLightning}) async { + required bool hasLightning, + required bool hasSolana}) async { const cwCore = """ cw_core: path: ./cw_core @@ -1028,6 +1116,10 @@ Future generatePubspec( cw_polygon: path: ./cw_polygon """; + const cwSolana = """ + cw_solana: + path: ./cw_solana + """; const cwEVM = """ cw_evm: path: ./cw_evm @@ -1070,6 +1162,10 @@ Future generatePubspec( output += '\n$cwPolygon'; } + if (hasSolana) { + output += '\n$cwSolana'; + } + if (hasHaven && !hasMonero) { output += '\n$cwSharedExternal\n$cwHaven'; } else if (hasHaven) { @@ -1105,7 +1201,8 @@ Future generateWalletTypes( required bool hasBanano, required bool hasBitcoinCash, required bool hasPolygon, - required bool hasLightning}) async { + required bool hasLightning, + required bool hasSolana}) async { final walletTypesFile = File(walletTypesPath); if (walletTypesFile.existsSync()) { @@ -1144,6 +1241,10 @@ Future generateWalletTypes( outputContent += '\tWalletType.polygon,\n'; } + if (hasSolana) { + outputContent += '\tWalletType.solana,\n'; + } + if (hasNano) { outputContent += '\tWalletType.nano,\n'; } diff --git a/tool/generate_secrets_config.dart b/tool/generate_secrets_config.dart index 2a9af690e..0dc040a59 100644 --- a/tool/generate_secrets_config.dart +++ b/tool/generate_secrets_config.dart @@ -6,6 +6,7 @@ import 'utils/utils.dart'; const configPath = 'tool/.secrets-config.json'; const evmChainsConfigPath = 'tool/.evm-secrets-config.json'; const bitcoinConfigPath = 'tool/.bitcoin-secrets-config.json'; +const solanaConfigPath = 'tool/.solana-secrets-config.json'; Future main(List args) async => generateSecretsConfig(args); @@ -20,9 +21,10 @@ Future generateSecretsConfig(List args) async { final configFile = File(configPath); final evmChainsConfigFile = File(evmChainsConfigPath); final bitcoinConfigFile = File(bitcoinConfigPath); + final solanaConfigFile = File(solanaConfigPath); final secrets = {}; - + secrets.addAll(extraInfo); secrets.removeWhere((key, dynamic value) { if (key.contains('--')) { @@ -52,6 +54,7 @@ Future generateSecretsConfig(List args) async { await configFile.writeAsString(secretsJson); secrets.clear(); + SecretKey.evmChainsSecrets.forEach((sec) { if (secrets[sec.name] != null) { return; @@ -71,4 +74,14 @@ Future generateSecretsConfig(List args) async { }); secretsJson = JsonEncoder.withIndent(' ').convert(secrets); await bitcoinConfigFile.writeAsString(secretsJson); + + SecretKey.solanaSecrets.forEach((sec) { + if (secrets[sec.name] != null) { + return; + } + + secrets[sec.name] = sec.generate(); + }); + secretsJson = JsonEncoder.withIndent(' ').convert(secrets); + await solanaConfigFile.writeAsString(secretsJson); } diff --git a/tool/import_secrets_config.dart b/tool/import_secrets_config.dart index 83e345f78..02061669b 100644 --- a/tool/import_secrets_config.dart +++ b/tool/import_secrets_config.dart @@ -8,6 +8,8 @@ const outputPath = 'lib/.secrets.g.dart'; const evmChainsConfigPath = 'tool/.evm-secrets-config.json'; const evmChainsOutputPath = 'cw_evm/lib/.secrets.g.dart'; +const solanaConfigPath = 'tool/.solana-secrets-config.json'; +const solanaOutputPath = 'cw_solana/lib/.secrets.g.dart'; Future main(List args) async => importSecretsConfig(); Future importSecretsConfig() async { @@ -21,6 +23,12 @@ Future importSecretsConfig() async { final evmChainsOutput = evmChainsInput.keys .fold('', (String acc, String val) => acc + generateConst(val, evmChainsInput)); + final solanaOutputFile = File(solanaOutputPath); + final solanaInput = + json.decode(File(solanaConfigPath).readAsStringSync()) as Map; + final solanaOutput = + solanaInput.keys.fold('', (String acc, String val) => acc + generateConst(val, solanaInput)); + if (outputFile.existsSync()) { await outputFile.delete(); } @@ -32,4 +40,10 @@ Future importSecretsConfig() async { } await evmChainsOutputFile.writeAsString(evmChainsOutput); + + if (solanaOutputFile.existsSync()) { + await solanaOutputFile.delete(); + } + + await solanaOutputFile.writeAsString(solanaOutput); } diff --git a/tool/utils/secret_key.dart b/tool/utils/secret_key.dart index e6ea18326..e25a27168 100644 --- a/tool/utils/secret_key.dart +++ b/tool/utils/secret_key.dart @@ -48,6 +48,10 @@ class SecretKey { SecretKey('breezApiKey', () => ''), SecretKey('breezInviteCode', () => ''), ]; + + static final solanaSecrets = [ + SecretKey('ankrApiKey', () => ''), + ]; final String name; final String Function() generate;