Skip to content

Commit 84c96ef

Browse files
authored
Merge pull request #1280 from soramitsu/price-update-center
Price update center
2 parents 685e531 + 9e8e361 commit 84c96ef

256 files changed

Lines changed: 1201 additions & 3644 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

fearless.xcodeproj/project.pbxproj

Lines changed: 145 additions & 315 deletions
Large diffs are not rendered by default.

fearless.xcworkspace/xcshareddata/swiftpm/Package.resolved

Lines changed: 8 additions & 8 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

fearless/ApplicationLayer/Services/Balance/WalletBalanceSubscription/WalletBalanceBuilder.swift

Lines changed: 6 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -5,17 +5,15 @@ protocol WalletBalanceBuilderProtocol {
55
func buildBalance(
66
for accountInfos: [ChainAssetKey: AccountInfo?],
77
_ metaAccounts: [MetaAccountModel],
8-
_ chainAssets: [ChainAsset],
9-
_ prices: [PriceData]
8+
_ chainAssets: [ChainAsset]
109
) -> [MetaAccountId: WalletBalanceInfo]?
1110
}
1211

1312
final class WalletBalanceBuilder: WalletBalanceBuilderProtocol {
1413
func buildBalance(
1514
for accountInfos: [ChainAssetKey: AccountInfo?],
1615
_ metaAccounts: [MetaAccountModel],
17-
_ chainAssets: [ChainAsset],
18-
_ prices: [PriceData]
16+
_ chainAssets: [ChainAsset]
1917
) -> [MetaAccountId: WalletBalanceInfo]? {
2018
let walletBalanceMap = metaAccounts.reduce(
2119
[MetaAccountId: WalletBalanceInfo]()
@@ -27,8 +25,7 @@ final class WalletBalanceBuilder: WalletBalanceBuilderProtocol {
2725
let enabledAssetFiatBalanceInfo = countBalance(
2826
for: enabledChainAssets,
2927
wallet,
30-
accountInfos,
31-
prices
28+
accountInfos
3229
)
3330

3431
let enabledAssetFiatBalance = enabledAssetFiatBalanceInfo.totalBalance
@@ -48,7 +45,7 @@ final class WalletBalanceBuilder: WalletBalanceBuilderProtocol {
4845
dayChangePercent: dayChangePercent.isNaN ? .zero : dayChangePercent,
4946
dayChangeValue: totalDayChange,
5047
currency: wallet.selectedCurrency,
51-
prices: prices.filter { $0.currencyId == wallet.selectedCurrency.id },
48+
prices: PriceDataHelper.prices(for: wallet.selectedCurrency, from: chainAssets),
5249
accountInfos: accountInfos
5350
)
5451

@@ -63,8 +60,7 @@ final class WalletBalanceBuilder: WalletBalanceBuilderProtocol {
6360
private func countBalance(
6461
for chainAssets: [ChainAsset],
6562
_ metaAccount: MetaAccountModel,
66-
_ accountInfos: [ChainAssetKey: AccountInfo?],
67-
_ prices: [PriceData]
63+
_ accountInfos: [ChainAssetKey: AccountInfo?]
6864
) -> CountBalanceInfo {
6965
var accountInfosCount = 0
7066
var totalBalance: Decimal = .zero
@@ -84,7 +80,6 @@ final class WalletBalanceBuilder: WalletBalanceBuilderProtocol {
8480
let balance = getFiatBalance(
8581
for: chainAsset,
8682
accountInfo,
87-
prices,
8883
currency: metaAccount.selectedCurrency
8984
)
9085

@@ -126,16 +121,14 @@ final class WalletBalanceBuilder: WalletBalanceBuilderProtocol {
126121
private func getFiatBalance(
127122
for chainAsset: ChainAsset,
128123
_ accountInfo: AccountInfo?,
129-
_ prices: [PriceData],
130124
currency: Currency
131125
) -> AssetFiatBalanceInfo {
132126
let balanceDecimal = getBalance(
133127
for: chainAsset,
134128
accountInfo
135129
)
136130

137-
guard let priceId = chainAsset.asset.priceId,
138-
let priceData = prices.first(where: { $0.priceId == priceId && $0.currencyId == currency.id }),
131+
guard let priceData = chainAsset.asset.getPrice(for: currency),
139132
let priceDecimal = Decimal(string: priceData.price)
140133
else {
141134
return AssetFiatBalanceInfo(total: .zero, dayChange: .zero)

fearless/ApplicationLayer/Services/Balance/WalletBalanceSubscription/WalletBalanceSubscriptionAdapter.swift

Lines changed: 12 additions & 50 deletions
Original file line numberDiff line numberDiff line change
@@ -62,13 +62,8 @@ enum WalletBalanceListenerType {
6262
final class WalletBalanceSubscriptionAdapter: WalletBalanceSubscriptionAdapterProtocol, ChainAssetListBuilder {
6363
static let shared = createWalletBalanceAdapter()
6464

65-
// MARK: - PriceLocalStorageSubscriber
66-
67-
private let priceLocalSubscriber: PriceLocalStorageSubscriber
68-
6965
// MARK: - Private properties
7066

71-
private var pricesProvider: AnySingleValueProvider<[PriceData]>?
7267
private lazy var walletBalanceBuilder = {
7368
WalletBalanceBuilder()
7469
}()
@@ -84,7 +79,6 @@ final class WalletBalanceSubscriptionAdapter: WalletBalanceSubscriptionAdapterPr
8479
private lazy var accountInfos: [ChainAssetKey: AccountInfo?] = [:]
8580
private lazy var chainAssets: [ChainAsset] = []
8681
private lazy var wallets: [MetaAccountModel] = []
87-
private lazy var prices: [PriceData] = []
8882

8983
private let listenersLock = ReaderWriterLock()
9084
private let accountInfoWorkQueue = DispatchQueue(
@@ -96,13 +90,11 @@ final class WalletBalanceSubscriptionAdapter: WalletBalanceSubscriptionAdapterPr
9690

9791
private init(
9892
metaAccountRepository: AsyncAnyRepository<MetaAccountModel>,
99-
priceLocalSubscriber: PriceLocalStorageSubscriber,
10093
chainAssetFetcher: ChainAssetFetchingProtocol,
10194
eventCenter: EventCenterProtocol,
10295
logger: Logger,
10396
accountInfoFetchingProvider: AccountInfoFetchingProtocol
10497
) {
105-
self.priceLocalSubscriber = priceLocalSubscriber
10698
walletRepository = metaAccountRepository
10799
self.chainAssetFetcher = chainAssetFetcher
108100
self.eventCenter = eventCenter
@@ -212,8 +204,7 @@ final class WalletBalanceSubscriptionAdapter: WalletBalanceSubscriptionAdapterPr
212204
let walletBalances = walletBalanceBuilder.buildBalance(
213205
for: accountInfos,
214206
wallets,
215-
chainAssets,
216-
prices
207+
chainAssets
217208
)
218209
return walletBalances
219210
}
@@ -222,8 +213,6 @@ final class WalletBalanceSubscriptionAdapter: WalletBalanceSubscriptionAdapterPr
222213
self.chainAssets = chainAssets
223214
self.wallets = (self.wallets + wallets).uniq(predicate: { $0.metaId })
224215
subscribeToAccountInfo(for: wallets, chainAssets)
225-
let currencies = self.wallets.map { $0.selectedCurrency }
226-
subscribeToPrices(for: chainAssets, currencies: currencies)
227216
}
228217

229218
private func fetchInitialData() {
@@ -294,14 +283,6 @@ final class WalletBalanceSubscriptionAdapter: WalletBalanceSubscriptionAdapterPr
294283
}
295284
}
296285

297-
private func subscribeToPrices(for chainAssets: [ChainAsset], currencies: [Currency]?) {
298-
var uniqueQurrencies: [Currency]? = currencies
299-
if let currencies = currencies {
300-
uniqueQurrencies = Array(Set(currencies))
301-
}
302-
pricesProvider = priceLocalSubscriber.subscribeToPrices(for: chainAssets, currencies: uniqueQurrencies, listener: self)
303-
}
304-
305286
private func notify(
306287
listener: WalletBalanceSubscriptionListener,
307288
result: WalletBalancesResult
@@ -395,8 +376,6 @@ extension WalletBalanceSubscriptionAdapter: EventVisitorProtocol {
395376
let wallet = wallets[safe: index] {
396377
if wallet.selectedCurrency != event.account.selectedCurrency {
397378
wallets[index] = event.account
398-
let currencies = wallets.map { $0.selectedCurrency }
399-
subscribeToPrices(for: chainAssets, currencies: currencies)
400379
}
401380
if wallet.networkManagmentFilter != event.account.networkManagmentFilter {
402381
wallets[index] = event.account
@@ -432,6 +411,17 @@ extension WalletBalanceSubscriptionAdapter: EventVisitorProtocol {
432411
subscribeToAccountInfo(for: wallets, chainAssets)
433412
}
434413
}
414+
415+
func processPricesUpdated() {
416+
Task {
417+
self.chainAssets = try await chainAssetFetcher.fetchAwait(
418+
shouldUseCache: false,
419+
filters: [.enabledChains],
420+
sortDescriptors: []
421+
)
422+
buildAndNotifyIfNeeded(with: wallets.map { $0.metaId }, updatedChainAssets: chainAssets)
423+
}
424+
}
435425
}
436426

437427
// MARK: - AccountInfoSubscriptionAdapterHandler
@@ -464,32 +454,6 @@ extension WalletBalanceSubscriptionAdapter: AccountInfoSubscriptionAdapterHandle
464454
}
465455
}
466456

467-
// MARK: - PriceLocalSubscriptionHandler
468-
469-
extension WalletBalanceSubscriptionAdapter: PriceLocalSubscriptionHandler {
470-
func handlePrices(result: Result<[PriceData], Error>) {
471-
switch result {
472-
case let .success(prices):
473-
self.prices = prices
474-
buildAndNotifyIfNeeded(with: wallets.map { $0.metaId }, updatedChainAssets: chainAssets)
475-
case let .failure(error):
476-
let unwrappedListeners = listenersLock.concurrentlyRead {
477-
listeners.compactMap {
478-
if let target = $0.target as? WalletBalanceSubscriptionListener {
479-
return target
480-
}
481-
482-
return nil
483-
}
484-
}
485-
unwrappedListeners.forEach { listener in
486-
notify(listener: listener, result: .failure(error))
487-
}
488-
logger.error("WalletBalanceFetcher error: \(error.localizedDescription)")
489-
}
490-
}
491-
}
492-
493457
private extension WalletBalanceSubscriptionAdapter {
494458
static func createWalletBalanceAdapter() -> WalletBalanceSubscriptionAdapter {
495459
let chainRepository = ChainRepositoryFactory().createRepository(
@@ -498,7 +462,6 @@ private extension WalletBalanceSubscriptionAdapter {
498462
)
499463
let accountRepositoryFactory = AccountRepositoryFactory(storageFacade: UserDataStorageFacade.shared)
500464
let accountRepositoryAsync = accountRepositoryFactory.createAsyncMetaAccountRepository(for: nil, sortDescriptors: [])
501-
let priceLocalSubscriber = PriceLocalStorageSubscriberImpl.shared
502465

503466
let chainAssetFetching = ChainAssetsFetching(
504467
chainRepository: AnyDataProviderRepository(chainRepository),
@@ -519,7 +482,6 @@ private extension WalletBalanceSubscriptionAdapter {
519482

520483
return WalletBalanceSubscriptionAdapter(
521484
metaAccountRepository: accountRepositoryAsync,
522-
priceLocalSubscriber: priceLocalSubscriber,
523485
chainAssetFetcher: chainAssetFetching,
524486
eventCenter: EventCenter.shared,
525487
logger: logger,

fearless/Common/DataProvider/Subscription/PriceLocalStorageSubscriber.swift

Lines changed: 2 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -194,15 +194,7 @@ final class PriceLocalStorageSubscriberImpl: PriceLocalStorageSubscriber {
194194
&& wrapper.currencies.contains(where: { $0.id == price.currencyId }) == true
195195
}
196196

197-
switch wrapper.handler {
198-
case .price:
199-
guard let chainAsset = wrapper.chainAssets.first, let priceData = finalValue.first else {
200-
return
201-
}
202-
listener.handlePrice(result: .success(priceData), chainAsset: chainAsset)
203-
case .prices:
204-
listener.handlePrices(result: .success(finalValue))
205-
}
197+
listener.handlePrices(result: .success(finalValue), for: wrapper.chainAssets)
206198
}
207199
}
208200

@@ -211,11 +203,7 @@ final class PriceLocalStorageSubscriberImpl: PriceLocalStorageSubscriber {
211203
guard let listener = wrapper.listener.target as? PriceLocalSubscriptionHandler else {
212204
return
213205
}
214-
if wrapper.chainAssets.count == 1, let chainAsset = wrapper.chainAssets.first {
215-
listener.handlePrice(result: .failure(error), chainAsset: chainAsset)
216-
} else {
217-
listener.handlePrices(result: .failure(error))
218-
}
206+
listener.handlePrices(result: .failure(error), for: wrapper.chainAssets)
219207
}
220208
}
221209

fearless/Common/DataProvider/Subscription/PriceLocalSubscriptionHandler.swift

Lines changed: 1 addition & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -2,21 +2,7 @@ import Foundation
22
import SSFModels
33

44
protocol PriceLocalSubscriptionHandler: AnyObject {
5-
func handlePrice(
6-
result: Result<PriceData?, Error>,
7-
chainAsset: ChainAsset
8-
)
9-
10-
func handlePrices(result: Result<[PriceData], Error>)
11-
}
12-
13-
extension PriceLocalSubscriptionHandler {
14-
func handlePrices(result _: Result<[PriceData], Error>) {}
15-
16-
func handlePrice(
17-
result _: Result<PriceData?, Error>,
18-
chainAsset _: ChainAsset
19-
) {}
5+
func handlePrices(result: Result<[PriceData], Error>, for chainAssets: [ChainAsset])
206
}
217

228
extension CrowdloanLocalSubscriptionHandler {

fearless/Common/EventCenter/EventVisitor.swift

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@ protocol EventVisitorProtocol: AnyObject {
2828
func processChainsSetupCompleted()
2929
func processLogout()
3030
func processAccountScoreSettingsChanged()
31+
func processPricesUpdated()
3132
}
3233

3334
extension EventVisitorProtocol {
@@ -58,4 +59,5 @@ extension EventVisitorProtocol {
5859
func processChainsSetupCompleted() {}
5960
func processLogout() {}
6061
func processAccountScoreSettingsChanged() {}
62+
func processPricesUpdated() {}
6163
}
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
import Foundation
2+
3+
struct PricesUpdated: EventProtocol {
4+
func accept(visitor: any EventVisitorProtocol) {
5+
visitor.processPricesUpdated()
6+
}
7+
}

0 commit comments

Comments
 (0)