From 36d40ade39fe253959bfa9da42530088e2aad684 Mon Sep 17 00:00:00 2001 From: Ivan Babich Date: Sat, 6 May 2023 08:59:21 +0300 Subject: [PATCH] [PWN-8361] Swiftlint --- .../Sources/History/EmptyStreamSource.swift | 1 + .../History/MultipleStreamsSource.swift | 1 + .../Solana/SolanaAccountsService.swift | 10 ++++- .../Moonpay/Provider/Moonpay.Provider.swift | 2 +- .../BindingPhoneNumberState.swift | 6 +-- .../ThrottleState/ThrottleState.swift | 2 - .../RestoreICloud/ICloudAccount.swift | 2 +- .../RestoreICloud/RestoreICloudState.swift | 10 ++--- .../RestoreSeed/RestoreSeedState.swift | 2 +- .../RestoreSocial/RestoreSocialState.swift | 6 +-- .../WormholeSendUserActionConsumer.swift | 10 ----- .../Wormhole/WormholeSendInputLogic.swift | 2 +- .../Wormhole/WormholeSendInputState.swift | 6 +-- .../Solend/SolendActionServiceImpl.swift | 6 +-- .../Solend/SolendDataServiceImpl.swift | 8 ++-- .../EthereumTransaction+Extensions.swift | 2 +- Scripts/swiftlint.sh | 39 +++++++++++++++++++ .../SellTransactionDetailsCoordinator.swift | 2 - .../Coordinators/SendEmptyCoordinator.swift | 3 +- .../SolendDepositsCoordinator.swift | 11 +++--- .../Coordinators/TabBar/HomeCoordinator.swift | 2 +- .../TabBar/TabBarCoordinator.swift | 10 ++--- p2p_wallet/Extensions/Wallet+Extensions.swift | 6 +-- p2p_wallet/Scenes/Main/Buy/BuyViewModel.swift | 5 ++- ...ndableListTransactionItem+UserAction.swift | 14 ++----- .../History/New/NewHistoryCoordinator.swift | 7 ++-- .../InvestSolendBannerViewModel.swift | 2 +- ...efaultSolendDepositFeePayingStrategy.swift | 13 ++++--- ...faultSolendWithdrawFeePayingStrategy.swift | 13 ++++--- .../DepositSolendViewModel.swift | 12 +++--- .../Deposits/SolendDepositsViewModel.swift | 4 +- .../InvestSolend/InvestSolendViewModel.swift | 6 +-- .../SolendTopUpForContinueViewModel.swift | 3 +- .../Scenes/Main/NewHome/HomeViewModel.swift | 2 +- .../AccountList/HomeAccountsView.swift | 6 +-- .../AccountList/HomeAccountsViewModel.swift | 2 +- .../Subview/Empty/HomeEmptyViewModel.swift | 6 +-- .../ReceiveFundsViaLinkViewModel.swift | 1 - .../Sell/Pending/SellPendingCoordinator.swift | 8 ++-- .../Scenes/Main/Sell/SellViewModel.swift | 5 +-- .../SendInputFeePromptViewModel.swift | 2 +- .../SendTransactionDetailViewModel.swift | 9 +++-- .../Main/Send/Input/SendInputViewModel.swift | 29 +++++--------- .../AmountView/SendInputAmountViewModel.swift | 4 +- .../RecipientSearchViewModel.swift | 7 ++-- .../Main/Send/Send\320\241oordinator.swift" | 4 +- .../SendTransactionStatusViewModel.swift | 2 +- .../Providers/JupiterTokensRepository.swift | 5 +-- .../Scenes/Main/Swap/Swap/SwapViewModel.swift | 28 +++++++++---- ...RendableDetailTransaction+UserAction.swift | 2 +- ...lTransaction+WormholeClaimUserAction.swift | 2 +- ...ilTransaction+WormholeSendUserAction.swift | 3 +- ...RendableAccountDetails+SolanaAccount.swift | 4 +- .../Send/WormholeSendInputAdapter.swift | 30 +++++++------- .../Wormhole/Send/WormholeSendInputView.swift | 2 +- .../Send/WormholeSendInputViewModel.swift | 6 ++- .../Scenes/TabBar/TabBarViewModel.swift | 2 +- .../BuyProcessingServiceType.swift | 13 ++++--- .../Buy/Exchange/NewBuyExchangeService.swift | 2 +- .../LogManagerLoggers/LoggerSwiftLogger.swift | 2 +- .../NameServiceUserDefaultCache.swift | 5 ++- .../Repositories/WalletsRepository.swift | 2 +- .../Services/Storage/UserWalletManager.swift | 1 - .../TransactionHandler+Extensions.swift | 2 +- .../TransactionHandler.swift | 14 +++---- project.yml | 3 ++ 66 files changed, 237 insertions(+), 206 deletions(-) create mode 100755 Scripts/swiftlint.sh diff --git a/Packages/KeyAppKit/Sources/History/EmptyStreamSource.swift b/Packages/KeyAppKit/Sources/History/EmptyStreamSource.swift index 3026d3af20..abc7aad792 100644 --- a/Packages/KeyAppKit/Sources/History/EmptyStreamSource.swift +++ b/Packages/KeyAppKit/Sources/History/EmptyStreamSource.swift @@ -3,6 +3,7 @@ // import Foundation +import SolanaSwift public class EmptyStreamSource: HistoryStreamSource { public init() {} diff --git a/Packages/KeyAppKit/Sources/History/MultipleStreamsSource.swift b/Packages/KeyAppKit/Sources/History/MultipleStreamsSource.swift index 800e8a6e8c..bd96d90970 100644 --- a/Packages/KeyAppKit/Sources/History/MultipleStreamsSource.swift +++ b/Packages/KeyAppKit/Sources/History/MultipleStreamsSource.swift @@ -3,6 +3,7 @@ // import Foundation +import SolanaSwift /// The class that merges many sources into one and represents as single stream of sequential transactions. /// diff --git a/Packages/KeyAppKit/Sources/KeyAppBusiness/Solana/SolanaAccountsService.swift b/Packages/KeyAppKit/Sources/KeyAppBusiness/Solana/SolanaAccountsService.swift index 0ea8534b6d..00be764271 100644 --- a/Packages/KeyAppKit/Sources/KeyAppBusiness/Solana/SolanaAccountsService.swift +++ b/Packages/KeyAppKit/Sources/KeyAppBusiness/Solana/SolanaAccountsService.swift @@ -27,6 +27,12 @@ public final class SolanaAccountsService: NSObject, AccountsService { public var statePublisher: AnyPublisher, Never> { stateSubject.eraseToAnyPublisher() } public var state: AsyncValueState<[Account]> { stateSubject.value } + + public var wallets: [Wallet] { + state.value.map(\.data) + } + + public var nativeWallet: Wallet? { accounts.state.value.nativeAccount?.data } public init( accountStorage: SolanaAccountStorage, @@ -170,8 +176,8 @@ public final class SolanaAccountsService: NSObject, AccountsService { public extension Array where Element == SolanaAccountsService.Account { /// Helper method for quickly extraction native account. - var nativeWallet: Element? { - first(where: { $0.data.isNativeSOL }) + var nativeAccount: Element? { + first { $0.data.isNativeSOL } } var totalAmountInCurrentFiat: Double { diff --git a/Packages/KeyAppKit/Sources/Moonpay/Provider/Moonpay.Provider.swift b/Packages/KeyAppKit/Sources/Moonpay/Provider/Moonpay.Provider.swift index ecd7bd0e0d..fbd81dd425 100644 --- a/Packages/KeyAppKit/Sources/Moonpay/Provider/Moonpay.Provider.swift +++ b/Packages/KeyAppKit/Sources/Moonpay/Provider/Moonpay.Provider.swift @@ -190,7 +190,7 @@ extension Moonpay { } public func getCountries() async throws -> [MoonpayCountry] { - var components = URLComponents(string: api.endpoint + "v3/countries")! + let components = URLComponents(string: api.endpoint + "v3/countries")! var urlRequest = URLRequest(url: components.url!) urlRequest.httpMethod = "GET" let (data, _) = try await URLSession.shared.data(from: urlRequest) diff --git a/Packages/KeyAppKit/Sources/Onboarding/CreateWalletFlow/CreateWalletState/BindingPhoneNumberState.swift b/Packages/KeyAppKit/Sources/Onboarding/CreateWalletFlow/CreateWalletState/BindingPhoneNumberState.swift index a6e7496359..abc180d94b 100644 --- a/Packages/KeyAppKit/Sources/Onboarding/CreateWalletFlow/CreateWalletState/BindingPhoneNumberState.swift +++ b/Packages/KeyAppKit/Sources/Onboarding/CreateWalletFlow/CreateWalletState/BindingPhoneNumberState.swift @@ -99,7 +99,7 @@ public enum BindingPhoneNumberState: Codable, State, Equatable { ) } - let account = try await Account( + let account = try await KeyPair( phrase: data.seedPhrase.components(separatedBy: " "), network: .mainnetBeta, derivablePath: .default @@ -142,7 +142,7 @@ public enum BindingPhoneNumberState: Codable, State, Equatable { case let .enterOTP(resendCounter, channel, phoneNumber, data): switch event { case let .enterOTP(opt): - let account = try await Account( + let account = try await KeyPair( phrase: data.seedPhrase.components(separatedBy: " "), network: .mainnetBeta, derivablePath: .default @@ -184,7 +184,7 @@ public enum BindingPhoneNumberState: Codable, State, Equatable { return .finish(.success(metadata: metaData)) case .resendOTP: - let account = try await Account( + let account = try await KeyPair( phrase: data.seedPhrase.components(separatedBy: " "), network: .mainnetBeta, derivablePath: .default diff --git a/Packages/KeyAppKit/Sources/Onboarding/CreateWalletFlow/ThrottleState/ThrottleState.swift b/Packages/KeyAppKit/Sources/Onboarding/CreateWalletFlow/ThrottleState/ThrottleState.swift index 9f052642a3..b0b871b46e 100644 --- a/Packages/KeyAppKit/Sources/Onboarding/CreateWalletFlow/ThrottleState/ThrottleState.swift +++ b/Packages/KeyAppKit/Sources/Onboarding/CreateWalletFlow/ThrottleState/ThrottleState.swift @@ -67,8 +67,6 @@ enum ThrottleState: Codable, State, Equatable { } else { throw ThrottleError.overheating(until: until) } - default: - throw StateMachineError.invalidEvent } } } diff --git a/Packages/KeyAppKit/Sources/Onboarding/RestoreWalletFlow/RestoreICloud/ICloudAccount.swift b/Packages/KeyAppKit/Sources/Onboarding/RestoreWalletFlow/RestoreICloud/ICloudAccount.swift index 1c12707c54..16d5ca71e6 100644 --- a/Packages/KeyAppKit/Sources/Onboarding/RestoreWalletFlow/RestoreICloud/ICloudAccount.swift +++ b/Packages/KeyAppKit/Sources/Onboarding/RestoreWalletFlow/RestoreICloud/ICloudAccount.swift @@ -23,7 +23,7 @@ public struct ICloudAccount: Codable, Hashable { self.phrase = phrase self.derivablePath = derivablePath - let account = try await Account( + let account = try await KeyPair( phrase: phrase.components(separatedBy: " "), network: .mainnetBeta, derivablePath: derivablePath diff --git a/Packages/KeyAppKit/Sources/Onboarding/RestoreWalletFlow/RestoreICloud/RestoreICloudState.swift b/Packages/KeyAppKit/Sources/Onboarding/RestoreWalletFlow/RestoreICloud/RestoreICloudState.swift index 447692a6fe..17685656d3 100644 --- a/Packages/KeyAppKit/Sources/Onboarding/RestoreWalletFlow/RestoreICloud/RestoreICloudState.swift +++ b/Packages/KeyAppKit/Sources/Onboarding/RestoreWalletFlow/RestoreICloud/RestoreICloudState.swift @@ -52,14 +52,14 @@ public enum RestoreICloudState: Codable, State, Equatable { } return .chooseWallet(accounts: accounts) - case let .restoreRawWallet(name, phrase, derivablePath): + case let .restoreRawWallet(_, phrase, derivablePath): return .finish(result: .successful(phrase: phrase, derivablePath: derivablePath)) default: throw StateMachineError.invalidEvent } - case let .chooseWallet(accounts): + case .chooseWallet: switch event { case let .restoreWallet(icloudAccount): return .finish(result: .successful( @@ -71,13 +71,13 @@ public enum RestoreICloudState: Codable, State, Equatable { default: throw StateMachineError.invalidEvent } - case let .finish(result): + case .finish: throw StateMachineError.invalidEvent } } - private func account(from icloudAccount: ICloudAccount) async throws -> Account { - let account = try await Account( + private func account(from icloudAccount: ICloudAccount) async throws -> KeyPair { + let account = try await KeyPair( phrase: icloudAccount.phrase.components(separatedBy: " "), network: .mainnetBeta, derivablePath: icloudAccount.derivablePath diff --git a/Packages/KeyAppKit/Sources/Onboarding/RestoreWalletFlow/RestoreSeed/RestoreSeedState.swift b/Packages/KeyAppKit/Sources/Onboarding/RestoreWalletFlow/RestoreSeed/RestoreSeedState.swift index 5de5bc806d..72666c5718 100644 --- a/Packages/KeyAppKit/Sources/Onboarding/RestoreWalletFlow/RestoreSeed/RestoreSeedState.swift +++ b/Packages/KeyAppKit/Sources/Onboarding/RestoreWalletFlow/RestoreSeed/RestoreSeedState.swift @@ -46,7 +46,7 @@ public enum RestoreSeedState: Codable, State, Equatable { throw StateMachineError.invalidEvent } - case let .chooseDerivationPath(phrase): + case .chooseDerivationPath: switch event { case let .restoreWithSeed(phrase, path): return .finish(result: .successful(phrase: phrase, path: path)) diff --git a/Packages/KeyAppKit/Sources/Onboarding/RestoreWalletFlow/RestoreSocial/RestoreSocialState.swift b/Packages/KeyAppKit/Sources/Onboarding/RestoreWalletFlow/RestoreSocial/RestoreSocialState.swift index 88b15666d5..27bd07bc3c 100644 --- a/Packages/KeyAppKit/Sources/Onboarding/RestoreWalletFlow/RestoreSocial/RestoreSocialState.swift +++ b/Packages/KeyAppKit/Sources/Onboarding/RestoreWalletFlow/RestoreSocial/RestoreSocialState.swift @@ -70,7 +70,7 @@ public indirect enum RestoreSocialState: Codable, State, Equatable { throw StateMachineError.invalidEvent } - case let .signInProgress(tokenID, email, deviceShare, customResult, backState): + case let .signInProgress(_, _, _, _, backState): switch event { case let .signInTorus(tokenID, email, deviceShare, customResult): if let deviceShare = deviceShare { @@ -110,7 +110,7 @@ public indirect enum RestoreSocialState: Codable, State, Equatable { throw StateMachineError.invalidEvent } - case let .notFoundCustom(result, email): + case let .notFoundCustom(result, _): switch event { case let .signInCustom(socialProvider): let (value, email) = try await provider.authService.auth(type: socialProvider) @@ -147,7 +147,7 @@ public indirect enum RestoreSocialState: Codable, State, Equatable { throw StateMachineError.invalidEvent } - case let .expiredSocialTryAgain(result, socialProvider, _, deviceShare): + case .expiredSocialTryAgain: throw StateMachineError.invalidEvent case .finish: diff --git a/Packages/KeyAppKit/Sources/Send/Wormhole/UserAction/WormholeSendUserActionConsumer.swift b/Packages/KeyAppKit/Sources/Send/Wormhole/UserAction/WormholeSendUserActionConsumer.swift index 2e197bbc88..79cbcc4069 100644 --- a/Packages/KeyAppKit/Sources/Send/Wormhole/UserAction/WormholeSendUserActionConsumer.swift +++ b/Packages/KeyAppKit/Sources/Send/Wormhole/UserAction/WormholeSendUserActionConsumer.swift @@ -157,16 +157,6 @@ public class WormholeSendUserActionConsumer: UserActionConsumer { Task { [weak self] in await self?.database.set(for: action.message, action) - /// Network fee in Solana network. - let transactionFee: CryptoAmount = [action.fees.networkFee, action.fees.bridgeFee] - .compactMap { $0 } - .map(\.asCryptoAmount) - .reduce(CryptoAmount(token: SolanaToken.nativeSolana), +) - - /// Account creation fee in Solana network. - let accountCreationFee = action.fees.messageAccountRent? - .asCryptoAmount ?? CryptoAmount(token: SolanaToken.nativeSolana) - /// Preparing transaction guard let data = Data(base64Encoded: action.transaction.transaction, options: .ignoreUnknownCharacters), diff --git a/Packages/KeyAppKit/Sources/Send/Wormhole/WormholeSendInputLogic.swift b/Packages/KeyAppKit/Sources/Send/Wormhole/WormholeSendInputLogic.swift index 89758598cb..115607ef03 100644 --- a/Packages/KeyAppKit/Sources/Send/Wormhole/WormholeSendInputLogic.swift +++ b/Packages/KeyAppKit/Sources/Send/Wormhole/WormholeSendInputLogic.swift @@ -40,7 +40,7 @@ enum WormholeSendInputLogic { }), // Native account - availableAccounts.nativeWallet, + availableAccounts.nativeAccount, ].compactMap { $0 } // Account with high amount in fiat diff --git a/Packages/KeyAppKit/Sources/Send/Wormhole/WormholeSendInputState.swift b/Packages/KeyAppKit/Sources/Send/Wormhole/WormholeSendInputState.swift index 9ab59e31f8..9c15ee85ca 100644 --- a/Packages/KeyAppKit/Sources/Send/Wormhole/WormholeSendInputState.swift +++ b/Packages/KeyAppKit/Sources/Send/Wormhole/WormholeSendInputState.swift @@ -90,8 +90,6 @@ public enum WormholeSendInputState: Equatable { return .error(input: input, output: nil, error: .calculationFeeFailure) } - var alert: WormholeSendInputAlert? - if fees.resultAmount == nil { let error: WormholeSendInputError @@ -148,7 +146,7 @@ public enum WormholeSendInputState: Equatable { fees: fees, relayContext: relayContext ), - alert: alert + alert: nil ) case let .updateInput(newInput): @@ -187,7 +185,7 @@ public enum WormholeSendInputState: Equatable { return .calculating(newInput: input) } - case let .initializingFailure(input, error): + case .initializingFailure: return self } } diff --git a/Packages/KeyAppKit/Sources/Solend/SolendActionServiceImpl.swift b/Packages/KeyAppKit/Sources/Solend/SolendActionServiceImpl.swift index af167b56b4..bfc1a8b99f 100644 --- a/Packages/KeyAppKit/Sources/Solend/SolendActionServiceImpl.swift +++ b/Packages/KeyAppKit/Sources/Solend/SolendActionServiceImpl.swift @@ -20,11 +20,9 @@ public class SolendActionServiceImpl: SolendActionService { private let relayService: RelayService private let relayContextManager: RelayContextManager - private var owner: Account { + private var owner: KeyPair { get throws { - guard let account = userAccountStorage.account else { - throw SolanaError.unauthorized - } + guard let account = userAccountStorage.account else { throw SolanaError.unauthorized } return account } } diff --git a/Packages/KeyAppKit/Sources/Solend/SolendDataServiceImpl.swift b/Packages/KeyAppKit/Sources/Solend/SolendDataServiceImpl.swift index a9c3dbade1..2bbd900d57 100644 --- a/Packages/KeyAppKit/Sources/Solend/SolendDataServiceImpl.swift +++ b/Packages/KeyAppKit/Sources/Solend/SolendDataServiceImpl.swift @@ -16,10 +16,10 @@ private struct SolendDataCache: Codable { let lastUpdate: Date? } -public class SolendDataServiceImpl: SolendDataService { - // Variables +public final class SolendDataServiceImpl: SolendDataService { + private let solend: Solend - private var owner: Account + private var owner: KeyPair private var lendingMark: String private let cache: SolendCache @@ -83,7 +83,7 @@ public class SolendDataServiceImpl: SolendDataService { } } - public init(solend: Solend, owner: Account, lendingMark: String, cache: SolendCache? = nil) { + public init(solend: Solend, owner: KeyPair, lendingMark: String, cache: SolendCache? = nil) { self.solend = solend self.owner = owner self.lendingMark = lendingMark diff --git a/Packages/KeyAppKit/Sources/Wormhole/EthereumTransaction+Extensions.swift b/Packages/KeyAppKit/Sources/Wormhole/EthereumTransaction+Extensions.swift index e2991139db..b47f05ba36 100644 --- a/Packages/KeyAppKit/Sources/Wormhole/EthereumTransaction+Extensions.swift +++ b/Packages/KeyAppKit/Sources/Wormhole/EthereumTransaction+Extensions.swift @@ -48,7 +48,7 @@ public extension EthereumTransaction { let toBytes = array[3].bytes, let value = array[4].bigUInt, let data = array[5].bytes, - let chainID = array[6].uint + array[6].uint != nil else { throw EthereumSignedTransaction.Error.rlpItemInvalid } diff --git a/Scripts/swiftlint.sh b/Scripts/swiftlint.sh new file mode 100755 index 0000000000..3b4816755d --- /dev/null +++ b/Scripts/swiftlint.sh @@ -0,0 +1,39 @@ +if [ "${CONFIGURATION}" = "Release" ]; then + echo "Swiftlint is disabled in Release mode" + exit 0 +fi + +START_DATE=$(date +"%s") + +SWIFT_LINT=/opt/homebrew/bin/swiftlint + +if [[ -e "${SWIFT_LINT}" ]]; then + echo "[I] Found SwiftLint at ${SWIFT_LINT}" +fi + +if [[ ! -e "${SWIFT_LINT}" ]]; then + echo "[!] SwifLint is not installed." + echo "[!] Expected location is '${SWIFT_LINT}'" + echo "[!] Please install it. eg. 'brew install swiftlint'" + exit 1 +fi + +echo "[I] SwiftLint version: $(${SWIFT_LINT} version)" + +# Run for unstaged, staged, new files, excluded for deleted files +git diff --diff-filter=d --name-only -- "*.swift" | while read filename; do + $SWIFT_LINT lint --path "$filename"; +done + +git diff --cached --diff-filter=d --name-only -- "*.swift" | while read filename; do + $SWIFT_LINT lint --path "$filename"; +done + +git ls-files --others --exclude-standard -- "*.swift" | while read filename; do + $SWIFT_LINT lint --path "$filename"; +done + +END_DATE=$(date +"%s") + +DIFF=$(($END_DATE - $START_DATE)) +echo "SwiftLint took $(($DIFF / 60)) minutes and $(($DIFF % 60)) seconds to complete." diff --git a/p2p_wallet/Coordinators/SellTransactionDetailsCoordinator.swift b/p2p_wallet/Coordinators/SellTransactionDetailsCoordinator.swift index 6ba1319d14..a0d5e8ef7c 100644 --- a/p2p_wallet/Coordinators/SellTransactionDetailsCoordinator.swift +++ b/p2p_wallet/Coordinators/SellTransactionDetailsCoordinator.swift @@ -15,8 +15,6 @@ import SafariServices private typealias Result = SellTransactionDetailsCoorditor.Result final class SellTransactionDetailsCoorditor: Coordinator { - @Injected private var walletsRepository: WalletsRepository - private let viewController: UIViewController private let strategy: Strategy private let transaction: SellDataServiceTransaction diff --git a/p2p_wallet/Coordinators/SendEmptyCoordinator.swift b/p2p_wallet/Coordinators/SendEmptyCoordinator.swift index 9561817f04..93855a491b 100644 --- a/p2p_wallet/Coordinators/SendEmptyCoordinator.swift +++ b/p2p_wallet/Coordinators/SendEmptyCoordinator.swift @@ -13,7 +13,8 @@ import SolanaSwift import UIKit final class SendEmptyCoordinator: Coordinator { - @Injected private var walletsRepository: WalletsRepository + + // Dependencies @Injected private var analyticsManager: AnalyticsManager private let navigationController: UINavigationController diff --git a/p2p_wallet/Coordinators/SolendDepositsCoordinator.swift b/p2p_wallet/Coordinators/SolendDepositsCoordinator.swift index 5f5e64f517..f42cc9ec91 100644 --- a/p2p_wallet/Coordinators/SolendDepositsCoordinator.swift +++ b/p2p_wallet/Coordinators/SolendDepositsCoordinator.swift @@ -11,6 +11,7 @@ import SolanaSwift import Solend import SwiftUI import UIKit +import KeyAppBusiness final class SolendDepositsCoordinator: Coordinator { private let controller: UINavigationController @@ -50,11 +51,11 @@ final class SolendDepositsCoordinator: Coordinator { return } - let wallets: WalletsRepository = Resolver.resolve() + let accountsService: SolanaAccountsService = Resolver.resolve() - let tokenAccount: Wallet? = wallets - .getWallets() - .first(where: { (wallet: Wallet) -> Bool in asset.mintAddress == wallet.mintAddress }) + let tokenAccount: Wallet? = accountsService + .wallets + .first { (wallet: Wallet) -> Bool in asset.mintAddress == wallet.mintAddress } if (tokenAccount?.amount ?? 0) > 0 { // User has a token @@ -72,7 +73,7 @@ final class SolendDepositsCoordinator: Coordinator { .store(in: &subscriptions) } else { // User doesn't have a token - let hasAnotherToken: Bool = wallets.getWallets().first(where: { ($0.lamports ?? 0) > 0 }) != nil + let hasAnotherToken: Bool = accountsService.wallets.first { ($0.lamports ?? 0) > 0 } != nil let coordinator = SolendTopUpForContinueCoordinator( navigationController: controller, model: .init( diff --git a/p2p_wallet/Coordinators/TabBar/HomeCoordinator.swift b/p2p_wallet/Coordinators/TabBar/HomeCoordinator.swift index ac43352b87..7206dff929 100644 --- a/p2p_wallet/Coordinators/TabBar/HomeCoordinator.swift +++ b/p2p_wallet/Coordinators/TabBar/HomeCoordinator.swift @@ -112,7 +112,7 @@ final class HomeCoordinator: Coordinator { return coordinate(to: BuyCoordinator(navigationController: navigationController, context: .fromHome)) .map { _ in () } .eraseToAnyPublisher() - case let .receive(publicKey): + case .receive: if available(.ethAddressEnabled) { let coordinator = SupportedTokensCoordinator( presentation: SmartCoordinatorPushPresentation(navigationController) diff --git a/p2p_wallet/Coordinators/TabBar/TabBarCoordinator.swift b/p2p_wallet/Coordinators/TabBar/TabBarCoordinator.swift index 0163be4859..05680bd7a1 100644 --- a/p2p_wallet/Coordinators/TabBar/TabBarCoordinator.swift +++ b/p2p_wallet/Coordinators/TabBar/TabBarCoordinator.swift @@ -14,10 +14,10 @@ import Sell import SolanaSwift final class TabBarCoordinator: Coordinator { - // MARK: - Dependencies - + + // Dependencies @Injected private var userWalletManager: UserWalletManager - @Injected private var walletsRepository: WalletsRepository + @Injected private var accountsService: SolanaAccountsService @Injected private var analyticsManager: AnalyticsManager @Injected private var sellDataService: any SellDataService @@ -90,7 +90,7 @@ final class TabBarCoordinator: Coordinator { .sink { [weak self] url in guard let self = self else { return } - UIApplication.dismissCustomPresentedViewController() { + UIApplication.dismissCustomPresentedViewController { let claimCoordinator = ReceiveFundsViaLinkCoordinator( presentingViewController: UIApplication.topmostViewController() ?? self.tabBarController, url: url @@ -263,7 +263,7 @@ final class TabBarCoordinator: Coordinator { case .swap: routeToSwap(nc: navigationController, source: .actionPanel) case .send: - if walletsRepository.getWallets().count > 0 { + if accountsService.state.value.map(\.data).count > 0 { analyticsManager.log(event: .sendViewed(lastScreen: "main_screen")) let sendCoordinator = SendCoordinator( rootViewController: navigationController, diff --git a/p2p_wallet/Extensions/Wallet+Extensions.swift b/p2p_wallet/Extensions/Wallet+Extensions.swift index 022f302b4f..91f74da9c6 100644 --- a/p2p_wallet/Extensions/Wallet+Extensions.swift +++ b/p2p_wallet/Extensions/Wallet+Extensions.swift @@ -9,11 +9,7 @@ import Foundation import SolanaSwift extension Array where Element == Wallet { - var totalAmountInCurrentFiat: Double { - reduce(0) { $0 + $1.amountInCurrentFiat } - } - var isTotalAmountEmpty: Bool { - contains(where: { $0.amount > 0 }) == false + contains { $0.amount > 0 } == false } } diff --git a/p2p_wallet/Scenes/Main/Buy/BuyViewModel.swift b/p2p_wallet/Scenes/Main/Buy/BuyViewModel.swift index 90d02ee42e..3b6a00dc1c 100644 --- a/p2p_wallet/Scenes/Main/Buy/BuyViewModel.swift +++ b/p2p_wallet/Scenes/Main/Buy/BuyViewModel.swift @@ -8,6 +8,7 @@ import SolanaSwift import SwiftyUserDefaults import UIKit import Moonpay +import KeyAppBusiness let MoonpayLicenseURL = "https://www.moonpay.com/legal/licenses" @@ -56,7 +57,7 @@ final class BuyViewModel: ObservableObject { // Dependencies @Injected private var moonpayProvider: Moonpay.Provider @Injected var exchangeService: BuyExchangeService - @Injected var walletsRepository: WalletsRepository + @Injected private var accountsService: SolanaAccountsService @Injected private var analyticsManager: AnalyticsManager @Injected private var pricesService: PricesServiceType @@ -539,7 +540,7 @@ final class BuyViewModel: ObservableObject { // HACK let paymentMethod = isGBPBankTransferEnabled ? "gbp_bank" : selectedPayment.rawValue let provider = try factory.create( - walletRepository: walletsRepository, + accountsService: accountsService, fromCurrency: from, amount: amount, toCurrency: to, diff --git a/p2p_wallet/Scenes/Main/History/New/Model/RendableListTransactionItem+UserAction.swift b/p2p_wallet/Scenes/Main/History/New/Model/RendableListTransactionItem+UserAction.swift index 763303bffc..9c728c6085 100644 --- a/p2p_wallet/Scenes/Main/History/New/Model/RendableListTransactionItem+UserAction.swift +++ b/p2p_wallet/Scenes/Main/History/New/Model/RendableListTransactionItem+UserAction.swift @@ -62,27 +62,21 @@ struct RendableListUserActionTransactionItem: RendableListTransactionItem { var title: String { switch userAction { - case let transaction as WormholeClaimUserAction: + case _ as WormholeClaimUserAction: return "Wormhole" - - case let transaction as WormholeSendUserAction: + case _ as WormholeSendUserAction: return "Wormhole" - default: return "Unknown" } - - return "Unknown" } var subtitle: String { switch userAction { - case let transaction as WormholeClaimUserAction: + case _ as WormholeClaimUserAction: return "Claim" - - case let transaction as WormholeSendUserAction: + case _ as WormholeSendUserAction: return "Send" - default: return "Unknown" } diff --git a/p2p_wallet/Scenes/Main/History/New/NewHistoryCoordinator.swift b/p2p_wallet/Scenes/Main/History/New/NewHistoryCoordinator.swift index d94d58b991..6c3b994074 100644 --- a/p2p_wallet/Scenes/Main/History/New/NewHistoryCoordinator.swift +++ b/p2p_wallet/Scenes/Main/History/New/NewHistoryCoordinator.swift @@ -13,8 +13,9 @@ import Sell import Send import SolanaSwift import SwiftUI +import KeyAppBusiness -class NewHistoryCoordinator: SmartCoordinator { +final class NewHistoryCoordinator: SmartCoordinator { var viewModel: HistoryViewModel! override func build() -> UIViewController { @@ -163,10 +164,10 @@ class NewHistoryCoordinator: SmartCoordinator { return } - let walletsRepository = Resolver.resolve(WalletsRepository.self) + let accountsService = Resolver.resolve(SolanaAccountsService.self) coordinate(to: SendCoordinator( rootViewController: viewController, - preChosenWallet: walletsRepository.nativeWallet, + preChosenWallet: accountsService.nativeWallet, preChosenRecipient: Recipient( address: transaction.depositWallet, category: .solanaAddress, diff --git a/p2p_wallet/Scenes/Main/InvestSolend/Banner/ViewModel/InvestSolendBannerViewModel.swift b/p2p_wallet/Scenes/Main/InvestSolend/Banner/ViewModel/InvestSolendBannerViewModel.swift index 9e4437d44c..982bdb28ca 100644 --- a/p2p_wallet/Scenes/Main/InvestSolend/Banner/ViewModel/InvestSolendBannerViewModel.swift +++ b/p2p_wallet/Scenes/Main/InvestSolend/Banner/ViewModel/InvestSolendBannerViewModel.swift @@ -11,7 +11,7 @@ import Sentry import SolanaSwift class InvestSolendBannerViewModel: ObservableObject { - @Injected private var priceService: PricesServiceType + @Injected private var priceService: PricesService @Published var state: InvestSolendBannerState = .pending diff --git a/p2p_wallet/Scenes/Main/InvestSolend/DepositWithdraw/Business/DefaultSolendDepositFeePayingStrategy.swift b/p2p_wallet/Scenes/Main/InvestSolend/DepositWithdraw/Business/DefaultSolendDepositFeePayingStrategy.swift index c34957a4d4..8aa0f3a6d8 100644 --- a/p2p_wallet/Scenes/Main/InvestSolend/DepositWithdraw/Business/DefaultSolendDepositFeePayingStrategy.swift +++ b/p2p_wallet/Scenes/Main/InvestSolend/DepositWithdraw/Business/DefaultSolendDepositFeePayingStrategy.swift @@ -8,16 +8,17 @@ import OrcaSwapSwift import Resolver import SolanaSwift import Solend +import KeyAppBusiness -class DefaultSolendWithdrawFeePayingStrategy: SolendFeePayingStrategy { +final class DefaultSolendWithdrawFeePayingStrategy: SolendFeePayingStrategy { let orca: OrcaSwap let actionService: SolendActionService - let wallets: WalletsRepository + let accountsService: SolanaAccountsService - init(orca: OrcaSwap, actionService: SolendActionService, wallets: WalletsRepository) { + init(orca: OrcaSwap, actionService: SolendActionService, accountsService: SolanaAccountsService) { self.orca = orca self.actionService = actionService - self.wallets = wallets + self.accountsService = accountsService } func calculate(amount: Lamports, symbol: String, mintAddress: String) async throws -> SolendFeePaying { @@ -33,7 +34,7 @@ class DefaultSolendWithdrawFeePayingStrategy: SolendFeePayingStrategy { payingFeeTokenMint: try PublicKey(string: mintAddress) ) - guard let nativeAccount = wallets.nativeWallet else { + guard let nativeAccount = accountsService.nativeWallet else { throw SolendFeePayingStrategyError.invalidNativeWallet } @@ -48,7 +49,7 @@ class DefaultSolendWithdrawFeePayingStrategy: SolendFeePayingStrategy { ) guard - let userSplAccount: Wallet = wallets.getWallets().first(where: { $0.token.address == mintAddress }), + let userSplAccount = accountsService.wallets.first(where: { $0.token.address == mintAddress }), let feeInToken = feeInToken else { return nativeFeePaying diff --git a/p2p_wallet/Scenes/Main/InvestSolend/DepositWithdraw/Business/DefaultSolendWithdrawFeePayingStrategy.swift b/p2p_wallet/Scenes/Main/InvestSolend/DepositWithdraw/Business/DefaultSolendWithdrawFeePayingStrategy.swift index fe6a83fdd9..4f6c2d87d9 100644 --- a/p2p_wallet/Scenes/Main/InvestSolend/DepositWithdraw/Business/DefaultSolendWithdrawFeePayingStrategy.swift +++ b/p2p_wallet/Scenes/Main/InvestSolend/DepositWithdraw/Business/DefaultSolendWithdrawFeePayingStrategy.swift @@ -8,16 +8,17 @@ import OrcaSwapSwift import Resolver import SolanaSwift import Solend +import KeyAppBusiness -class DefaultSolendDepositFeePayingStrategy: SolendFeePayingStrategy { +final class DefaultSolendDepositFeePayingStrategy: SolendFeePayingStrategy { let orca: OrcaSwap let actionService: SolendActionService - let wallets: WalletsRepository + let accountsService: SolanaAccountsService - init(orca: OrcaSwap, actionService: SolendActionService, wallets: WalletsRepository) { + init(orca: OrcaSwap, actionService: SolendActionService, accountsService: SolanaAccountsService) { self.orca = orca self.actionService = actionService - self.wallets = wallets + self.accountsService = accountsService } func calculate(amount: Lamports, symbol: String, mintAddress: String) async throws -> SolendFeePaying { @@ -33,7 +34,7 @@ class DefaultSolendDepositFeePayingStrategy: SolendFeePayingStrategy { payingFeeTokenMint: try PublicKey(string: mintAddress) ) - guard let nativeAccount = wallets.nativeWallet else { + guard let nativeAccount = accountsService.nativeWallet else { throw SolendFeePayingStrategyError.invalidNativeWallet } @@ -48,7 +49,7 @@ class DefaultSolendDepositFeePayingStrategy: SolendFeePayingStrategy { ) guard - let userSplAccount: Wallet = wallets.getWallets().first(where: { $0.token.address == mintAddress }), + let userSplAccount: Wallet = accountsService.wallets.first(where: { $0.token.address == mintAddress }), let feeInToken = feeInToken else { return nativeTokenStrategy diff --git a/p2p_wallet/Scenes/Main/InvestSolend/DepositWithdraw/DepositSolendViewModel.swift b/p2p_wallet/Scenes/Main/InvestSolend/DepositWithdraw/DepositSolendViewModel.swift index 49481addf8..396017fd07 100644 --- a/p2p_wallet/Scenes/Main/InvestSolend/DepositWithdraw/DepositSolendViewModel.swift +++ b/p2p_wallet/Scenes/Main/InvestSolend/DepositWithdraw/DepositSolendViewModel.swift @@ -6,6 +6,7 @@ import Resolver import SolanaSwift import Solend import Sentry +import KeyAppBusiness enum DepositSolendViewModelError { case invalidFeePayer @@ -20,12 +21,12 @@ class DepositSolendViewModel: ObservableObject { .deposit: DefaultSolendDepositFeePayingStrategy( orca: Resolver.resolve(), actionService: Resolver.resolve(), - wallets: Resolver.resolve() + accountsService: Resolver.resolve() ), .withdraw: DefaultSolendWithdrawFeePayingStrategy( orca: Resolver.resolve(), actionService: Resolver.resolve(), - wallets: Resolver.resolve() + accountsService: Resolver.resolve() ), ] private var subscriptions = Set() @@ -48,9 +49,10 @@ class DepositSolendViewModel: ObservableObject { private let finishSubject = PassthroughSubject() var finish: AnyPublisher { finishSubject.eraseToAnyPublisher() } + // Dependencies @Injected private var notificationService: NotificationService @Injected private var priceService: PricesServiceType - @Injected private var walletRepository: WalletsRepository + @Injected private var accountsService: SolanaAccountsService @Published var focusSide: DepositWithdrawInputViewActiveSide = .left /// Is loading fees @@ -120,7 +122,7 @@ class DepositSolendViewModel: ObservableObject { /// Balance for selected Token private var currentWallet: Wallet? { - walletRepository.getWallets().filter { $0.token.address == self.invest.asset.mintAddress }.first + accountsService.wallets.filter { $0.token.address == self.invest.asset.mintAddress }.first } /// Rate for selected pair Token -> Fiat @@ -462,7 +464,7 @@ class DepositSolendViewModel: ObservableObject { } private func availableDepositModels() -> [TokenToDepositView.Model] { - let wallets = walletRepository.getWallets() + let wallets = accountsService.wallets return market.compactMap { asset, market, _ in let wallet = wallets .first { wallet in diff --git a/p2p_wallet/Scenes/Main/InvestSolend/Deposits/SolendDepositsViewModel.swift b/p2p_wallet/Scenes/Main/InvestSolend/Deposits/SolendDepositsViewModel.swift index 36553d3f0c..b18d873d81 100644 --- a/p2p_wallet/Scenes/Main/InvestSolend/Deposits/SolendDepositsViewModel.swift +++ b/p2p_wallet/Scenes/Main/InvestSolend/Deposits/SolendDepositsViewModel.swift @@ -8,10 +8,8 @@ import Solend class SolendDepositsViewModel: ObservableObject { private var subscriptions = Set() - // MARK: - Services - + // Dependencies @Injected private var priceService: PricesService - @Injected private var walletRepository: WalletsRepository private let dataService: SolendDataService // MARK: - State diff --git a/p2p_wallet/Scenes/Main/InvestSolend/InvestSolendViewModel.swift b/p2p_wallet/Scenes/Main/InvestSolend/InvestSolendViewModel.swift index caa4e1086c..0c9da4f4bf 100644 --- a/p2p_wallet/Scenes/Main/InvestSolend/InvestSolendViewModel.swift +++ b/p2p_wallet/Scenes/Main/InvestSolend/InvestSolendViewModel.swift @@ -26,9 +26,9 @@ enum InvestSolendError { } @MainActor -class InvestSolendViewModel: ObservableObject { - // MARK: - Services - +final class InvestSolendViewModel: ObservableObject { + + // Dependencies @Injected private var notificationService: NotificationService let dataService: SolendDataService let actionService: SolendActionService diff --git a/p2p_wallet/Scenes/Main/InvestSolend/TopUpForContinue/ViewModel/SolendTopUpForContinueViewModel.swift b/p2p_wallet/Scenes/Main/InvestSolend/TopUpForContinue/ViewModel/SolendTopUpForContinueViewModel.swift index 43f475576c..f425342dfa 100644 --- a/p2p_wallet/Scenes/Main/InvestSolend/TopUpForContinue/ViewModel/SolendTopUpForContinueViewModel.swift +++ b/p2p_wallet/Scenes/Main/InvestSolend/TopUpForContinue/ViewModel/SolendTopUpForContinueViewModel.swift @@ -10,6 +10,7 @@ import Foundation import Resolver import SolanaSwift import Solend +import KeyAppBusiness class SolendTopUpForContinueViewModel: ObservableObject { private var subscriptions = Set() @@ -70,7 +71,7 @@ class SolendTopUpForContinueViewModel: ObservableObject { } func swapOrReceiveClicked() { - let walletsRepository: WalletsRepository = Resolver.resolve() + let walletsRepository: SolanaAccountsService = Resolver.resolve() if withoutAnyTokens { guard let key = try? PublicKey(string: walletsRepository.nativeWallet?.pubkey) else { return } diff --git a/p2p_wallet/Scenes/Main/NewHome/HomeViewModel.swift b/p2p_wallet/Scenes/Main/NewHome/HomeViewModel.swift index 8525469ff3..16f1ac5c80 100644 --- a/p2p_wallet/Scenes/Main/NewHome/HomeViewModel.swift +++ b/p2p_wallet/Scenes/Main/NewHome/HomeViewModel.swift @@ -59,7 +59,7 @@ class HomeViewModel: ObservableObject { } func copyToClipboard() { - clipboardManager.copyToClipboard(solanaAccountsService.state.value.nativeWallet?.data.pubkey ?? "") + clipboardManager.copyToClipboard(solanaAccountsService.state.value.nativeAccount?.data.pubkey ?? "") notificationsService.showToast(title: "🖤", text: L10n.addressWasCopiedToClipboard, haptic: true) analyticsManager.log(event: .mainCopyAddress) } diff --git a/p2p_wallet/Scenes/Main/NewHome/Subview/AccountList/HomeAccountsView.swift b/p2p_wallet/Scenes/Main/NewHome/Subview/AccountList/HomeAccountsView.swift index 60cb1f978b..8b4e61810a 100644 --- a/p2p_wallet/Scenes/Main/NewHome/Subview/AccountList/HomeAccountsView.swift +++ b/p2p_wallet/Scenes/Main/NewHome/Subview/AccountList/HomeAccountsView.swift @@ -31,11 +31,7 @@ struct HomeAccountsView: View { } } .customRefreshable { - do { - try await viewModel.refresh() - } catch { - error.capture() - } + await viewModel.refresh() } .onReceive(viewModel.$scrollOnTheTop) { _ in DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) { diff --git a/p2p_wallet/Scenes/Main/NewHome/Subview/AccountList/HomeAccountsViewModel.swift b/p2p_wallet/Scenes/Main/NewHome/Subview/AccountList/HomeAccountsViewModel.swift index 0b45ce5531..38b161e4ed 100644 --- a/p2p_wallet/Scenes/Main/NewHome/Subview/AccountList/HomeAccountsViewModel.swift +++ b/p2p_wallet/Scenes/Main/NewHome/Subview/AccountList/HomeAccountsViewModel.swift @@ -158,7 +158,7 @@ final class HomeAccountsViewModel: BaseViewModel, ObservableObject { func actionClicked(_ action: WalletActionType) { switch action { case .receive: - guard let pubkey = try? PublicKey(string: solanaAccountsService.state.value.nativeWallet?.data.pubkey) + guard let pubkey = try? PublicKey(string: solanaAccountsService.state.value.nativeAccount?.data.pubkey) else { return } navigation.send(.receive(publicKey: pubkey)) case .buy: diff --git a/p2p_wallet/Scenes/Main/NewHome/Subview/Empty/HomeEmptyViewModel.swift b/p2p_wallet/Scenes/Main/NewHome/Subview/Empty/HomeEmptyViewModel.swift index 30ae024f37..ea3c19c41f 100644 --- a/p2p_wallet/Scenes/Main/NewHome/Subview/Empty/HomeEmptyViewModel.swift +++ b/p2p_wallet/Scenes/Main/NewHome/Subview/Empty/HomeEmptyViewModel.swift @@ -18,7 +18,7 @@ final class HomeEmptyViewModel: BaseViewModel, ObservableObject { @Injected private var analyticsManager: AnalyticsManager @Injected private var walletsRepository: WalletsRepository - @Injected private var pricesService: PricesServiceType + @Injected private var pricesService: PricesService @Injected private var solanaAccountsService: SolanaAccountsService // MARK: - Properties @@ -60,7 +60,7 @@ final class HomeEmptyViewModel: BaseViewModel, ObservableObject { } func receiveClicked() { - guard let pubkey = try? PublicKey(string: solanaAccountsService.state.value.nativeWallet?.data.pubkey) else { return } + guard let pubkey = try? PublicKey(string: solanaAccountsService.state.value.nativeAccount?.data.pubkey) else { return } navigation.send(.receive(publicKey: pubkey)) } @@ -163,7 +163,7 @@ extension HomeEmptyViewModel { } } -private extension PricesServiceType { +private extension PricesService { func fiatAmount(mint: String) -> String? { guard let price = currentPrice(mint: mint)?.value else { return nil } return "\(Defaults.fiat.symbol) \(price.toString(minimumFractionDigits: 2, maximumFractionDigits: 2))" diff --git a/p2p_wallet/Scenes/Main/ReceiveFundsViaLink/ViewModel/ReceiveFundsViaLinkViewModel.swift b/p2p_wallet/Scenes/Main/ReceiveFundsViaLink/ViewModel/ReceiveFundsViaLinkViewModel.swift index bfa7dde305..780d78f333 100644 --- a/p2p_wallet/Scenes/Main/ReceiveFundsViaLink/ViewModel/ReceiveFundsViaLinkViewModel.swift +++ b/p2p_wallet/Scenes/Main/ReceiveFundsViaLink/ViewModel/ReceiveFundsViaLinkViewModel.swift @@ -19,7 +19,6 @@ final class ReceiveFundsViaLinkViewModel: BaseViewModel, ObservableObject { @Injected private var analyticsManager: AnalyticsManager @Injected private var sendViaLinkDataService: SendViaLinkDataService @Injected private var tokensRepository: SolanaTokensRepository - @Injected private var walletsRepository: WalletsRepository // Subjects private let closeSubject = PassthroughSubject() diff --git a/p2p_wallet/Scenes/Main/Sell/Pending/SellPendingCoordinator.swift b/p2p_wallet/Scenes/Main/Sell/Pending/SellPendingCoordinator.swift index 42bd1109af..41bc5364d3 100644 --- a/p2p_wallet/Scenes/Main/Sell/Pending/SellPendingCoordinator.swift +++ b/p2p_wallet/Scenes/Main/Sell/Pending/SellPendingCoordinator.swift @@ -5,6 +5,7 @@ import UIKit import Send import Resolver import Sell +import KeyAppBusiness enum SellPendingCoordinatorResult { case transactionRemoved @@ -15,9 +16,8 @@ enum SellPendingCoordinatorResult { final class SellPendingCoordinator: Coordinator { - // MARK: - Dependencies - - @Injected private var walletsRepository: WalletsRepository + // Dependencies + @Injected private var accountsService: SolanaAccountsService // MARK: - Properties @@ -75,7 +75,7 @@ final class SellPendingCoordinator: Coordinator { coordinate(to: SendCoordinator( rootViewController: navigationController, - preChosenWallet: walletsRepository.nativeWallet, + preChosenWallet: accountsService.nativeWallet, preChosenRecipient: Recipient( address: transaction.depositWallet, category: .solanaAddress, diff --git a/p2p_wallet/Scenes/Main/Sell/SellViewModel.swift b/p2p_wallet/Scenes/Main/Sell/SellViewModel.swift index 0ad9585015..3b94f11a40 100644 --- a/p2p_wallet/Scenes/Main/Sell/SellViewModel.swift +++ b/p2p_wallet/Scenes/Main/Sell/SellViewModel.swift @@ -25,10 +25,9 @@ enum SellViewModelInputError: Error, Equatable { private let decimals = 2 @MainActor -class SellViewModel: BaseViewModel, ObservableObject { - - // MARK: - Dependencies +final class SellViewModel: BaseViewModel, ObservableObject { + // Dependencies @Injected private var walletRepository: WalletsRepository @Injected private var dataService: any SellDataService @Injected private var actionService: any SellActionService diff --git a/p2p_wallet/Scenes/Main/Send/Input/Details/FeePrompt/SendInputFeePromptViewModel.swift b/p2p_wallet/Scenes/Main/Send/Input/Details/FeePrompt/SendInputFeePromptViewModel.swift index 9f13166308..1065266715 100644 --- a/p2p_wallet/Scenes/Main/Send/Input/Details/FeePrompt/SendInputFeePromptViewModel.swift +++ b/p2p_wallet/Scenes/Main/Send/Input/Details/FeePrompt/SendInputFeePromptViewModel.swift @@ -17,7 +17,7 @@ final class SendInputFeePromptViewModel: BaseViewModel, ObservableObject { init(feeToken: Wallet, feeInToken: FeeAmount, availableFeeTokens: [Wallet]) { title = L10n.thisAddressDoesnTHaveAnAccountForThisToken - let priceService = Resolver.resolve(PricesServiceType.self) + let priceService = Resolver.resolve(PricesService.self) let price = priceService.currentPrice(mint: feeToken.token.address) let feeInFiat = (feeInToken.accountBalances.convertToBalance(decimals: feeToken.token.decimals) * price?.value) self.feeInFiat = feeInFiat diff --git a/p2p_wallet/Scenes/Main/Send/Input/Details/SendTransactionDetails/SendTransactionDetailViewModel.swift b/p2p_wallet/Scenes/Main/Send/Input/Details/SendTransactionDetails/SendTransactionDetailViewModel.swift index 5cf1ea26f7..d7a386a683 100644 --- a/p2p_wallet/Scenes/Main/Send/Input/Details/SendTransactionDetails/SendTransactionDetailViewModel.swift +++ b/p2p_wallet/Scenes/Main/Send/Input/Details/SendTransactionDetails/SendTransactionDetailViewModel.swift @@ -11,6 +11,7 @@ import Resolver import Send import SolanaSwift import SwiftUI +import KeyAppBusiness final class SendTransactionDetailViewModel: BaseViewModel, ObservableObject { let cancelSubject = PassthroughSubject() @@ -18,13 +19,15 @@ final class SendTransactionDetailViewModel: BaseViewModel, ObservableObject { let longTapped = PassthroughSubject() private let stateMachine: SendInputStateMachine - @Injected private var pricesService: PricesServiceType - @Injected private var walletsRepository: WalletsRepository + + // Dependencies + @Injected private var pricesService: PricesService + @Injected private var accountsService: SolanaAccountsService @Injected private var notificationsService: NotificationService @Injected private var clipboardManager: ClipboardManagerType private lazy var feeWalletsService: SendChooseFeeService = SendChooseFeeServiceImpl( - wallets: walletsRepository.getWallets(), + wallets: accountsService.wallets, feeRelayer: Resolver.resolve(), orcaSwap: Resolver.resolve() ) diff --git a/p2p_wallet/Scenes/Main/Send/Input/SendInputViewModel.swift b/p2p_wallet/Scenes/Main/Send/Input/SendInputViewModel.swift index dc60c7e95d..6799ff5a0c 100644 --- a/p2p_wallet/Scenes/Main/Send/Input/SendInputViewModel.swift +++ b/p2p_wallet/Scenes/Main/Send/Input/SendInputViewModel.swift @@ -13,6 +13,8 @@ import Send import SolanaPricesAPIs import SolanaSwift +// swiftlint:disable file_length + final class SendInputViewModel: BaseViewModel, ObservableObject { enum Status { case initializing @@ -92,10 +94,8 @@ final class SendInputViewModel: BaseViewModel, ObservableObject { private let preChosenAmount: Double? private let allowSwitchingMainAmountType: Bool - // MARK: - Dependencies - - private let walletsRepository: WalletsRepository - private let pricesService: PricesServiceType + // Dependencies + private let pricesService: PricesService @Injected private var analyticsManager: AnalyticsManager init( @@ -110,9 +110,8 @@ final class SendInputViewModel: BaseViewModel, ObservableObject { self.preChosenAmount = preChosenAmount self.allowSwitchingMainAmountType = allowSwitchingMainAmountType - let repository = Resolver.resolve(WalletsRepository.self) - walletsRepository = repository - let wallets = repository.getWallets() + let accountsService = Resolver.resolve(SolanaAccountsService.self) + let wallets = accountsService.wallets let pricesService = Resolver.resolve(PricesService.self) self.pricesService = pricesService @@ -223,7 +222,7 @@ final class SendInputViewModel: BaseViewModel, ObservableObject { } switch nextState.status { - case .error(reason: .initializeFailed(_)): + case .error(reason: .initializeFailed): self.status = .initializingFailed default: self.status = .ready @@ -264,7 +263,7 @@ private extension SendInputViewModel { .sink { [weak self] value in guard let self = self else { return } switch value.status { - case .error(reason: .networkConnectionError(_)): + case .error(reason: .networkConnectionError): self.handleConnectionError() default: self.inputAmountViewModel.maxAmountToken = value.maxAmountInputInToken @@ -466,7 +465,7 @@ private extension SendInputViewModel { isEnabled: false, title: L10n.insufficientFundsToCoverFees ) - case .error(reason: .initializeFailed(_)): + case .error(reason: .initializeFailed): inputAmountViewModel.isError = false actionButtonData = SliderActionButtonData( isEnabled: true, @@ -540,14 +539,6 @@ private extension SendInputViewModel { handleError(text: L10n.youHaveNoInternetConnection) } - func handleInitializingError() { - handleError(text: L10n.initializingError) - } - - func handleUnknownError() { - handleError(text: L10n.somethingWentWrong) - } - func handleError(text: String) { snackbar.send(SnackBar(title: "🥺", text: text, buttonTitle: L10n.hide, buttonAction: { SnackBar.hide() })) } @@ -598,7 +589,7 @@ private extension SendInputViewModel { logSendClickCreateLink(symbol: token.symbol, amount: amountInToken, pubkey: sourceWallet.pubkey ?? "") } - let transaction = SendTransaction(state: currentState) { + _ = SendTransaction(state: currentState) { try await createTransactionExecution( isSendingViaLink: isSendingViaLink, isFakeSendTransaction: isFakeSendTransaction, diff --git a/p2p_wallet/Scenes/Main/Send/Input/Subviews/AmountView/SendInputAmountViewModel.swift b/p2p_wallet/Scenes/Main/Send/Input/Subviews/AmountView/SendInputAmountViewModel.swift index fabe339812..e790fcd97f 100644 --- a/p2p_wallet/Scenes/Main/Send/Input/Subviews/AmountView/SendInputAmountViewModel.swift +++ b/p2p_wallet/Scenes/Main/Send/Input/Subviews/AmountView/SendInputAmountViewModel.swift @@ -58,14 +58,14 @@ final class SendInputAmountViewModel: BaseViewModel, ObservableObject { private var tokenChangedEvent = CurrentValueSubject(.init(token: .nativeSolana)) // MARK: - Dependencies - private let pricesService: PricesServiceType + private let pricesService: PricesService init(initialToken: Wallet) { fiat = Defaults.fiat token = initialToken countAfterDecimalPoint = Constants.fiatDecimals mainAmountType = Defaults.isTokenInputTypeChosen ? .token : .fiat - pricesService = Resolver.resolve(PricesServiceType.self) + pricesService = Resolver.resolve(PricesService.self) super.init() diff --git a/p2p_wallet/Scenes/Main/Send/RecipentSearch/RecipientSearchViewModel.swift b/p2p_wallet/Scenes/Main/Send/RecipentSearch/RecipientSearchViewModel.swift index c0482643a0..89ffe5da41 100644 --- a/p2p_wallet/Scenes/Main/Send/RecipentSearch/RecipientSearchViewModel.swift +++ b/p2p_wallet/Scenes/Main/Send/RecipentSearch/RecipientSearchViewModel.swift @@ -201,10 +201,11 @@ class RecipientSearchViewModel: ObservableObject { } else { isSearching = true searchTask = Task { [weak self] in + guard let self else { return } let result = await recipientSearchService.search( input: currentSearchTerm, - config: config, - preChosenToken: preChosenWallet?.token + config: self.config, + preChosenToken: self.preChosenWallet?.token ) guard !Task.isCancelled else { return } @@ -218,7 +219,7 @@ class RecipientSearchViewModel: ObservableObject { { try? await Task.sleep(nanoseconds: autoSelectTheOnlyOneResultMode.delay!) guard !Task.isCancelled else { return } - autoSelectTheOnlyOneResult(result: result, fromQR: fromQR) + self.autoSelectTheOnlyOneResult(result: result, fromQR: fromQR) } } } diff --git "a/p2p_wallet/Scenes/Main/Send/Send\320\241oordinator.swift" "b/p2p_wallet/Scenes/Main/Send/Send\320\241oordinator.swift" index 4bcaa4ef29..a311149631 100644 --- "a/p2p_wallet/Scenes/Main/Send/Send\320\241oordinator.swift" +++ "b/p2p_wallet/Scenes/Main/Send/Send\320\241oordinator.swift" @@ -22,8 +22,8 @@ enum SendSource: String { } final class SendCoordinator: Coordinator { - // MARK: - Dependencies - + + // Dependencies @Injected var walletsRepository: WalletsRepository @Injected private var sendViaLinkDataService: SendViaLinkDataService diff --git a/p2p_wallet/Scenes/Main/Send/TransactionStatus/SendTransactionStatusViewModel.swift b/p2p_wallet/Scenes/Main/Send/TransactionStatus/SendTransactionStatusViewModel.swift index 151496f0aa..c740a3050f 100644 --- a/p2p_wallet/Scenes/Main/Send/TransactionStatus/SendTransactionStatusViewModel.swift +++ b/p2p_wallet/Scenes/Main/Send/TransactionStatus/SendTransactionStatusViewModel.swift @@ -7,7 +7,7 @@ import TransactionParser final class SendTransactionStatusViewModel: BaseViewModel, ObservableObject { @Injected private var transactionHandler: TransactionHandler - @Injected private var priceService: PricesServiceType + @Injected private var priceService: PricesService let close = PassthroughSubject() let errorMessageTap = PassthroughSubject() diff --git a/p2p_wallet/Scenes/Main/Swap/Providers/JupiterTokensRepository.swift b/p2p_wallet/Scenes/Main/Swap/Providers/JupiterTokensRepository.swift index 32a91da473..91805524a7 100644 --- a/p2p_wallet/Scenes/Main/Swap/Providers/JupiterTokensRepository.swift +++ b/p2p_wallet/Scenes/Main/Swap/Providers/JupiterTokensRepository.swift @@ -21,11 +21,10 @@ final class JupiterTokensRepositoryImpl: JupiterTokensRepository { var status: AnyPublisher { statusSubject.eraseToAnyPublisher() } - // MARK: - Dependencies - + + // Dependencies private let jupiterClient: JupiterAPI private let localProvider: JupiterTokensProvider - @Injected private var walletsRepository: WalletsRepository @Injected private var tokensRepositoryCache: SolanaTokensRepositoryCache // MARK: - Private params diff --git a/p2p_wallet/Scenes/Main/Swap/Swap/SwapViewModel.swift b/p2p_wallet/Scenes/Main/Swap/Swap/SwapViewModel.swift index c7b0fff4ea..8b27d5f9ba 100644 --- a/p2p_wallet/Scenes/Main/Swap/Swap/SwapViewModel.swift +++ b/p2p_wallet/Scenes/Main/Swap/Swap/SwapViewModel.swift @@ -1,4 +1,6 @@ +import Foundation import Combine +import KeyAppBusiness import Resolver import Jupiter import SolanaSwift @@ -13,15 +15,17 @@ final class SwapViewModel: BaseViewModel, ObservableObject { case success } - // MARK: - Dependencies + // Dependencies @Injected private var swapWalletsRepository: JupiterTokensRepository @Injected private var notificationService: NotificationService @Injected private var transactionHandler: TransactionHandler @Injected private var analyticsManager: AnalyticsManager @Injected private var userWalletManager: UserWalletManager - @Injected private var walletsRepository: WalletsRepository + @Injected private var accountsService: SolanaAccountsService + @Injected private var clipboardManager: ClipboardManagerType // MARK: - Actions + let switchTokens = PassthroughSubject() let tryAgain = PassthroughSubject() let changeFromToken = PassthroughSubject() @@ -30,9 +34,12 @@ final class SwapViewModel: BaseViewModel, ObservableObject { let isViewAppeared = PassthroughSubject() // MARK: - Params + var fromTokenInputViewModel: SwapInputViewModel var toTokenInputViewModel: SwapInputViewModel + // MARK: - To View + @Published var initializingState: InitializingState = .loading @Published var arePricesLoading: Bool = false @@ -57,6 +64,8 @@ final class SwapViewModel: BaseViewModel, ObservableObject { private var timer: Timer? private let source: JupiterSwapSource private var wasMinToastShown = false // Special flag not to show toast again if state has not changed + + // MARK: - Init init( stateMachine: JupiterSwapStateMachine, @@ -134,7 +143,7 @@ final class SwapViewModel: BaseViewModel, ObservableObject { } ) - UIPasteboard.general.string = logsInfo.jsonString + clipboardManager.copyToClipboard(logsInfo.jsonString ?? "") errorLogs = nil notificationService.showToast(title: "✅", text: "Logs copied to clipboard") } @@ -186,16 +195,17 @@ private extension SwapViewModel { .store(in: &subscriptions) Publishers.CombineLatest( - walletsRepository.dataPublisher.removeDuplicates(), + accountsService.statePublisher, isViewAppeared.eraseToAnyPublisher().removeDuplicates() ) - .filter { [weak self] userWallets, isViewAppeared in + .map { ($0.0.value, $0.1) } + .filter { [weak self] _, isViewAppeared in // update user wallets only when initializingState is success and view is appeared self?.initializingState == .success && isViewAppeared } - .sinkAsync { [weak self] userWallets, isViewAppeared in + .sinkAsync { [weak self] accounts, _ in await self?.stateMachine.accept( - action: .updateUserWallets(userWallets: userWallets) + action: .updateUserWallets(userWallets: accounts.map { $0.data }) ) } .store(in: &subscriptions) @@ -463,12 +473,14 @@ private extension SwapViewModel { let formatter = NumberFormatter() formatter.maximumFractionDigits = 2 formatter.minimumFractionDigits = 0 - let slippageString = formatter.string(from: NSNumber(floatLiteral: slippage)) ?? String(format: "%.2f", slippage) + let number = slippage as NSNumber + let slippageString = formatter.string(from: number) ?? String(format: "%.2f", slippage) return slippageString + "%" } } // MARK: - Analytics + extension SwapViewModel { func logSettingsClick() { analyticsManager.log(event: .swapSettingsClick) diff --git a/p2p_wallet/Scenes/Main/TransactionDetailView/Model/RendableDetailTransaction+UserAction.swift b/p2p_wallet/Scenes/Main/TransactionDetailView/Model/RendableDetailTransaction+UserAction.swift index e788ce78b4..ecc1afff3a 100644 --- a/p2p_wallet/Scenes/Main/TransactionDetailView/Model/RendableDetailTransaction+UserAction.swift +++ b/p2p_wallet/Scenes/Main/TransactionDetailView/Model/RendableDetailTransaction+UserAction.swift @@ -48,7 +48,7 @@ struct RendableAbstractUserActionTransaction: RendableTransactionDetail { return L10n.transactionSubmitted case .ready: return L10n.transactionSucceeded - case let .error(error): + case .error: return L10n.transactionFailed } } diff --git a/p2p_wallet/Scenes/Main/TransactionDetailView/Model/RendableDetailTransaction+WormholeClaimUserAction.swift b/p2p_wallet/Scenes/Main/TransactionDetailView/Model/RendableDetailTransaction+WormholeClaimUserAction.swift index 47c857f7c6..67c3a88341 100644 --- a/p2p_wallet/Scenes/Main/TransactionDetailView/Model/RendableDetailTransaction+WormholeClaimUserAction.swift +++ b/p2p_wallet/Scenes/Main/TransactionDetailView/Model/RendableDetailTransaction+WormholeClaimUserAction.swift @@ -37,7 +37,7 @@ struct RendableWormholeClaimUserActionDetail: RendableTransactionDetail { return L10n.transactionSubmitted case .ready: return L10n.transactionSucceeded - case let .error(error): + case .error: return L10n.transactionFailed } } diff --git a/p2p_wallet/Scenes/Main/TransactionDetailView/Model/RendableDetailTransaction+WormholeSendUserAction.swift b/p2p_wallet/Scenes/Main/TransactionDetailView/Model/RendableDetailTransaction+WormholeSendUserAction.swift index 862b8ff85e..25cdd78a6c 100644 --- a/p2p_wallet/Scenes/Main/TransactionDetailView/Model/RendableDetailTransaction+WormholeSendUserAction.swift +++ b/p2p_wallet/Scenes/Main/TransactionDetailView/Model/RendableDetailTransaction+WormholeSendUserAction.swift @@ -37,7 +37,7 @@ struct RendableWormholeSendUserActionDetail: RendableTransactionDetail { return L10n.transactionSubmitted case .ready: return L10n.transactionSucceeded - case let .error(error): + case .error: return L10n.transactionFailed } } @@ -85,7 +85,6 @@ struct RendableWormholeSendUserActionDetail: RendableTransactionDetail { ) let cryptoFormatter = CryptoFormatter() - let currencyFormatter = CurrencyFormatter() if let arbiterFee = userAction.fees.arbiter { result.append( diff --git a/p2p_wallet/Scenes/Main/WalletDetail/New/Model/RendableAccountDetails+SolanaAccount.swift b/p2p_wallet/Scenes/Main/WalletDetail/New/Model/RendableAccountDetails+SolanaAccount.swift index 74456bbdd4..f873ee9df1 100644 --- a/p2p_wallet/Scenes/Main/WalletDetail/New/Model/RendableAccountDetails+SolanaAccount.swift +++ b/p2p_wallet/Scenes/Main/WalletDetail/New/Model/RendableAccountDetails+SolanaAccount.swift @@ -22,13 +22,11 @@ struct RendableNewSolanaAccountDetails: RendableAccountDetails { } var amountInFiat: String { - account.amountInFiatDouble.fiatAmountFormattedString() + Double(account.amountInFiat?.value.description ?? "")?.fiatAmountFormattedString() ?? "" } var actions: [RendableAccountDetailsAction] { - var walletActions: [RendableAccountDetailsAction] if account.data.isNativeSOL || account.data.token.symbol == "USDC" { - walletActions = [.buy, .receive(.solanaAccount(account)), .send, .swap(account.data)] return [.buy, .receive(.solanaAccount(account)), .send, .swap(account.data)] } else { return [.receive(.solanaAccount(account)), .send, .swap(account.data)] diff --git a/p2p_wallet/Scenes/Main/Wormhole/Send/WormholeSendInputAdapter.swift b/p2p_wallet/Scenes/Main/Wormhole/Send/WormholeSendInputAdapter.swift index d4c8e0f414..3aff36f197 100644 --- a/p2p_wallet/Scenes/Main/Wormhole/Send/WormholeSendInputAdapter.swift +++ b/p2p_wallet/Scenes/Main/Wormhole/Send/WormholeSendInputAdapter.swift @@ -13,18 +13,18 @@ import Send import Wormhole struct WormholeSendInputStateAdapter: Equatable { - let cryptoFormatter: CryptoFormatter = .init() - let currencyFormatter: CurrencyFormatter = .init() + let cryptoFormatter = CryptoFormatter() + let currencyFormatter = CurrencyFormatter() let state: WormholeSendInputState var input: WormholeSendInputBase? { switch state { - case let .ready(input, output, alert): + case let .ready(input, _, _): return input case let .calculating(newInput): return newInput - case let .error(input, output, error): + case let .error(input, _, _): return input case .initializingFailure: return nil @@ -33,11 +33,11 @@ struct WormholeSendInputStateAdapter: Equatable { var output: WormholeSendOutputBase? { switch state { - case let .ready(input, output, alert): + case let .ready(_, output, _): return output - case let .calculating(newInput): + case .calculating: return nil - case let .error(input, output, error): + case let .error(_, output, _): return output case .initializingFailure: return nil @@ -84,11 +84,11 @@ struct WormholeSendInputStateAdapter: Equatable { var fees: String { switch state { - case let .ready(input, output, alert): + case let .ready(_, output, _): return "Fees: \(currencyFormatter.string(amount: output.fees.totalInFiat))" - case let .calculating(newInput): + case .calculating: return "" - case let .error(input, output, error): + case let .error(_, output, _): if let output { return "Fees: \(currencyFormatter.string(amount: output.fees.totalInFiat))" } else { @@ -101,11 +101,11 @@ struct WormholeSendInputStateAdapter: Equatable { var feesLoading: Bool { switch state { - case let .ready(input, output, alert): + case .ready: return false - case let .calculating(newInput): + case .calculating: return true - case let .error(input, output, error): + case .error: return false case .initializingFailure: return false @@ -114,7 +114,7 @@ struct WormholeSendInputStateAdapter: Equatable { var inputColor: UIColor { switch state { - case let .error(input, output, error) where error == .maxAmountReached: + case let .error(_, _, error) where error == .maxAmountReached: return Asset.Colors.rose.color default: return Asset.Colors.night.color @@ -123,7 +123,7 @@ struct WormholeSendInputStateAdapter: Equatable { var sliderButton: SliderActionButtonData { switch state { - case let .error(input, output, error): + case let .error(input, _, error): let text: String switch error { case .maxAmountReached: diff --git a/p2p_wallet/Scenes/Main/Wormhole/Send/WormholeSendInputView.swift b/p2p_wallet/Scenes/Main/Wormhole/Send/WormholeSendInputView.swift index 91f11c32a3..72c71a7635 100644 --- a/p2p_wallet/Scenes/Main/Wormhole/Send/WormholeSendInputView.swift +++ b/p2p_wallet/Scenes/Main/Wormhole/Send/WormholeSendInputView.swift @@ -68,7 +68,7 @@ struct WormholeSendInputView: View { // Account view SendInputTokenView( wallet: viewModel.adapter.inputAccount?.data ?? Wallet(token: .eth), - amountInFiat: viewModel.adapter.inputAccount?.amountInFiatDouble ?? 0.0, + amountInFiat: viewModel.inputAccountFiatAmount, isChangeEnabled: true, skeleton: viewModel.adapter.inputAccountSkeleton ) { diff --git a/p2p_wallet/Scenes/Main/Wormhole/Send/WormholeSendInputViewModel.swift b/p2p_wallet/Scenes/Main/Wormhole/Send/WormholeSendInputViewModel.swift index 5b16f7208a..8f7572776a 100644 --- a/p2p_wallet/Scenes/Main/Wormhole/Send/WormholeSendInputViewModel.swift +++ b/p2p_wallet/Scenes/Main/Wormhole/Send/WormholeSendInputViewModel.swift @@ -58,6 +58,10 @@ class WormholeSendInputViewModel: BaseViewModel, ObservableObject { @Published var actionButtonData = SliderActionButtonData.zero @Published var isSliderOn = false @Published var showFinished = false + + var inputAccountFiatAmount: Double { + Double(adapter.inputAccount?.amountInFiat?.value.description ?? "") ?? 0.0 + } let changeTokenPressed = PassthroughSubject() @@ -352,7 +356,7 @@ extension WormholeSendInputViewModel { supportedToken.contains(account.data.token.address) } - if let nativeWallet = solanaAccountsService.state.value.nativeWallet { + if let nativeWallet = solanaAccountsService.state.value.nativeAccount { availableBridgeAccounts.append(nativeWallet) } diff --git a/p2p_wallet/Scenes/TabBar/TabBarViewModel.swift b/p2p_wallet/Scenes/TabBar/TabBarViewModel.swift index 013b6acb3a..98f7266a3d 100644 --- a/p2p_wallet/Scenes/TabBar/TabBarViewModel.swift +++ b/p2p_wallet/Scenes/TabBar/TabBarViewModel.swift @@ -14,7 +14,7 @@ import SolanaSwift final class TabBarViewModel { // Dependencies @Injected private var socket: Socket - @Injected private var pricesService: PricesServiceType + @Injected private var pricesService: PricesService @Injected private var authenticationHandler: AuthenticationHandlerType @Injected private var notificationService: NotificationService diff --git a/p2p_wallet/Services/Buy/BuyProccessing/BuyProcessingServiceType.swift b/p2p_wallet/Services/Buy/BuyProccessing/BuyProcessingServiceType.swift index 16ea27863e..15ccda4a1e 100644 --- a/p2p_wallet/Services/Buy/BuyProccessing/BuyProcessingServiceType.swift +++ b/p2p_wallet/Services/Buy/BuyProccessing/BuyProcessingServiceType.swift @@ -3,6 +3,7 @@ // import Foundation +import KeyAppBusiness protocol BuyProcessingServiceType { func getUrl() -> String @@ -10,14 +11,14 @@ protocol BuyProcessingServiceType { protocol BuyProcessingFactory { func create( - walletRepository: WalletsRepository, + accountsService: SolanaAccountsService, crypto: Buy.CryptoCurrency, initialAmount: Double, currency: Buy.FiatCurrency ) throws -> BuyProcessingServiceType func create( - walletRepository: WalletsRepository, + accountsService: SolanaAccountsService, fromCurrency: BuyCurrencyType, amount: Double, toCurrency: BuyCurrencyType, @@ -28,7 +29,7 @@ protocol BuyProcessingFactory { extension Buy { class MoonpayBuyProcessingFactory: BuyProcessingFactory { func create( - walletRepository: WalletsRepository, + accountsService: SolanaAccountsService, crypto: CryptoCurrency, initialAmount: Double, currency: FiatCurrency @@ -41,14 +42,14 @@ extension Buy { .secretConfig("MOONPAY_PRODUCTION_API_KEY")! : .secretConfig("MOONPAY_STAGING_API_KEY")!, currencyCode: crypto.moonpayCode, - walletAddress: walletRepository.nativeWallet?.pubkey, + walletAddress: accountsService.nativeWallet?.pubkey, baseCurrencyCode: currency.moonpayCode, baseCurrencyAmount: initialAmount ) } func create( - walletRepository: WalletsRepository, + accountsService: SolanaAccountsService, fromCurrency: BuyCurrencyType, amount: Double, toCurrency: BuyCurrencyType, @@ -69,7 +70,7 @@ extension Buy { .secretConfig("MOONPAY_PRODUCTION_API_KEY")! : .secretConfig("MOONPAY_STAGING_API_KEY")!, currencyCode: to.moonpayCode, - walletAddress: walletRepository.nativeWallet?.pubkey, + walletAddress: accountsService.nativeWallet?.pubkey, baseCurrencyCode: from.moonpayCode, baseCurrencyAmount: amount, paymentMethod: paymentMethod == "card" ? .creditDebitCard : diff --git a/p2p_wallet/Services/Buy/Exchange/NewBuyExchangeService.swift b/p2p_wallet/Services/Buy/Exchange/NewBuyExchangeService.swift index 679ec5feba..4c0d67f5f1 100644 --- a/p2p_wallet/Services/Buy/Exchange/NewBuyExchangeService.swift +++ b/p2p_wallet/Services/Buy/Exchange/NewBuyExchangeService.swift @@ -24,7 +24,7 @@ struct MoonpayExchange: BuyExchangeService { fatalError() } - let baseAmount = input.currency is Buy.Currency ? input.amount : nil + let baseAmount = input.amount let quoteAmount = input.currency is Buy.CryptoCurrency ? input.amount : nil do { diff --git a/p2p_wallet/Services/Logger/LogManagerLoggers/LoggerSwiftLogger.swift b/p2p_wallet/Services/Logger/LogManagerLoggers/LoggerSwiftLogger.swift index 1c651dc963..4e477ca7d2 100644 --- a/p2p_wallet/Services/Logger/LogManagerLoggers/LoggerSwiftLogger.swift +++ b/p2p_wallet/Services/Logger/LogManagerLoggers/LoggerSwiftLogger.swift @@ -10,7 +10,7 @@ class LoggerSwiftLogger: LogManagerLogger { var supportedLogLevels: [LogLevel] = [.error, .info, .request, .response, .event, .warning, .debug] func log(event: String, logLevel: LogLevel, data: String?) { - queue.async { [unowned self] in + queue.async { // LoggerSwift.Logger.log( // event: mapEventLogLeverToLoggerSwiftEvent(logLevel), // message: event + " " + (data ?? "") diff --git a/p2p_wallet/Services/NameServiceUserDefaultCache.swift b/p2p_wallet/Services/NameServiceUserDefaultCache.swift index b05fcf7fd1..1e5ea88f73 100644 --- a/p2p_wallet/Services/NameServiceUserDefaultCache.swift +++ b/p2p_wallet/Services/NameServiceUserDefaultCache.swift @@ -8,6 +8,7 @@ import Foundation import NameService import Resolver +import KeyAppBusiness class NameServiceUserDefaultCache: NameServiceCacheType { @Injected private var nameStorage: NameStorageType @@ -25,9 +26,9 @@ class NameServiceUserDefaultCache: NameServiceCacheType { } func getName(for owner: String) -> NameServiceSearchResult? { - let walletsRepository: WalletsRepository = Resolver.resolve() + let accountsService: SolanaAccountsService = Resolver.resolve() - if walletsRepository.getWallets().contains(where: { $0.pubkey == owner }), + if accountsService.wallets.contains(where: { $0.pubkey == owner }), let name = nameStorage.getName() { return .registered(name) diff --git a/p2p_wallet/Services/Repositories/WalletsRepository.swift b/p2p_wallet/Services/Repositories/WalletsRepository.swift index ef03350e43..4702a6f0c4 100644 --- a/p2p_wallet/Services/Repositories/WalletsRepository.swift +++ b/p2p_wallet/Services/Repositories/WalletsRepository.swift @@ -61,7 +61,7 @@ class WalletsRepositoryImpl: NSObject, WalletsRepository { } var nativeWallet: SolanaSwift.Wallet? { - solanaAccountsService.state.value.nativeWallet?.data + solanaAccountsService.state.value.nativeAccount?.data } func getWallets() -> [SolanaSwift.Wallet] { diff --git a/p2p_wallet/Services/Storage/UserWalletManager.swift b/p2p_wallet/Services/Storage/UserWalletManager.swift index e65f0b5392..f091eec621 100644 --- a/p2p_wallet/Services/Storage/UserWalletManager.swift +++ b/p2p_wallet/Services/Storage/UserWalletManager.swift @@ -74,7 +74,6 @@ class UserWalletManager: ObservableObject { try await Resolver.resolve(SendHistoryLocalProvider.self).save(nil) // Save device share - print(deviceShare) if let deviceShare = deviceShare, ethAddress != nil { try storage.save(deviceShare: deviceShare) } diff --git a/p2p_wallet/Services/TransactionHandler/TransactionHandler+Extensions.swift b/p2p_wallet/Services/TransactionHandler/TransactionHandler+Extensions.swift index 67a8581bc3..8ccc798b7f 100644 --- a/p2p_wallet/Services/TransactionHandler/TransactionHandler+Extensions.swift +++ b/p2p_wallet/Services/TransactionHandler/TransactionHandler+Extensions.swift @@ -140,7 +140,7 @@ extension TransactionHandler { var value = transactionsSubject.value if let currentValue = value[safe: index] { - var newValue = update(currentValue) + let newValue = update(currentValue) // update value[index] = newValue diff --git a/p2p_wallet/Services/TransactionHandler/TransactionHandler.swift b/p2p_wallet/Services/TransactionHandler/TransactionHandler.swift index 35a49db129..7555ab0cf5 100644 --- a/p2p_wallet/Services/TransactionHandler/TransactionHandler.swift +++ b/p2p_wallet/Services/TransactionHandler/TransactionHandler.swift @@ -32,14 +32,14 @@ protocol TransactionHandlerType { var onNewTransaction: AnyPublisher<(trx: PendingTransaction, index: Int), Never> { get } } -class TransactionHandler: TransactionHandlerType { - // MARK: - Dependencies - +final class TransactionHandler: TransactionHandlerType { + + // Dependencies @Injected var notificationsService: NotificationService @Injected var analyticsManager: AnalyticsManager @Injected var apiClient: SolanaAPIClient - @Injected var walletsRepository: WalletsRepository - @Injected var pricesService: PricesServiceType + @Injected var accountsService: SolanaAccountsService + @Injected var pricesService: PricesService @Injected var socket: SolanaAccountsObservableService @Injected var errorObserver: ErrorObserver @@ -131,14 +131,14 @@ class TransactionHandler: TransactionHandlerType { return false } .compactMap { pt -> ParsedTransaction? in - pt.parse(pricesService: pricesService, authority: walletsRepository.nativeWallet?.pubkey) + pt.parse(pricesService: pricesService, authority: accountsService.nativeWallet?.pubkey) } } func getProcessingTransaction() -> [ParsedTransaction] { transactionsSubject.value .compactMap { pt -> ParsedTransaction? in - pt.parse(pricesService: pricesService, authority: walletsRepository.nativeWallet?.pubkey) + pt.parse(pricesService: pricesService, authority: accountsService.nativeWallet?.pubkey) } } diff --git a/project.yml b/project.yml index e1805498ce..0679429679 100644 --- a/project.yml +++ b/project.yml @@ -167,6 +167,9 @@ targets: - "**/GoogleService-Info.plist" - path: README.MD preBuildScripts: + - script: | + sh Scripts/swiftlint.sh + name: "[SCRIPT] Swiftlint" - script: | # Name of the resource we're selectively copying GOOGLESERVICE_INFO_PLIST=GoogleService-Info.plist