-
Notifications
You must be signed in to change notification settings - Fork 9
/
AccountPortfoliosClient+State.swift
380 lines (329 loc) · 13.5 KB
/
AccountPortfoliosClient+State.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
import Foundation
// MARK: - Definition
extension AccountPortfoliosClient {
struct AccountPortfolio: Sendable, Hashable, CustomDebugStringConvertible {
/// The visible account to consumers of this portfolio. It has already removed any reference to hidden resources.
var account: OnLedgerEntity.OnLedgerAccount
/// The original account, without any modifications made. Necessary for whenever we need to update the hidden resources.
private let originalAccount: OnLedgerEntity.OnLedgerAccount
private(set) var hiddenResources: [ResourceIdentifier]
var poolUnitDetails: Loadable<[OnLedgerEntitiesClient.OwnedResourcePoolDetails]> = .idle
var stakeUnitDetails: Loadable<IdentifiedArrayOf<OnLedgerEntitiesClient.OwnedStakeDetails>> = .idle
var isCurrencyAmountVisible: Bool = true
var fiatCurrency: FiatCurrency = .usd
var debugDescription: String {
account.debugDescription
}
init(account: OnLedgerEntity.OnLedgerAccount, hiddenResources: [ResourceIdentifier]) {
self.originalAccount = account
self.hiddenResources = hiddenResources
self.account = Self.removeHiddenResourcesFromAccount(account: account, hiddenResources: hiddenResources)
}
mutating func updateHiddenResources(hiddenResources: [ResourceIdentifier]) {
self.hiddenResources = hiddenResources
self.account = Self.removeHiddenResourcesFromAccount(account: originalAccount, hiddenResources: hiddenResources)
}
private static func removeHiddenResourcesFromAccount(account: OnLedgerEntity.OnLedgerAccount, hiddenResources: [ResourceIdentifier]) -> OnLedgerEntity.OnLedgerAccount {
var modified = account
// Remove every hidden fungible resource
modified.fungibleResources.nonXrdResources.removeAll(where: { resource in
hiddenResources.contains(.fungible(resource.resourceAddress))
})
// Remove every hidden non fungible resource
modified.nonFungibleResources.removeAll(where: { resource in
hiddenResources.contains(.nonFungible(resource.resourceAddress))
})
// Remove every hidden pool unit
modified.poolUnitResources.poolUnits.removeAll(where: { poolUnit in
hiddenResources.contains(.poolUnit(poolUnit.resourcePoolAddress))
})
return modified
}
}
/// Internal state that holds all loaded portfolios.
actor State {
typealias TokenPrices = [ResourceAddress: Decimal192]
let portfoliosSubject: AsyncCurrentValueSubject<Loadable<[AccountAddress: AccountPortfolio]>> = .init(.loading)
var tokenPrices: Result<TokenPrices, Error> = .success([:])
var selectedCurrency: FiatCurrency = .usd
var isCurrencyAmountVisible: Bool = true
// Useful for DEBUG mode, when we want to display proper resources fiat worth on mainnet
// but use random prices on testnets; as one resources from mainnet have prices.
var gateway: Gateway = .mainnet
}
}
// MARK: - Portfolio Setters/Getters
extension AccountPortfoliosClient.State {
func setRadixGateway(_ gateway: Gateway) {
self.gateway = gateway
}
func handlePortfolioUpdate(_ portfolio: AccountPortfoliosClient.AccountPortfolio) {
var portfolio = portfolio
applyFiatWorth(&portfolio)
setOrUpdateAccountPortfolio(portfolio)
}
func handlePortfoliosUpdate(_ portfolios: [AccountPortfoliosClient.AccountPortfolio]) {
var portfolios = portfolios
portfolios.mutateAll(applyFiatWorth)
setOrUpdateAccountPortfolios(portfolios)
}
func updatePortfoliosHiddenResources(hiddenResources: [ResourceIdentifier]) {
if var existingPortfolios = portfoliosSubject.value.values.wrappedValue.map({ Array($0) }) {
existingPortfolios.mutateAll { portfolio in
portfolio.updateHiddenResources(hiddenResources: hiddenResources)
}
applyTokenPrices(to: &existingPortfolios)
setOrUpdateAccountPortfolios(existingPortfolios)
}
}
func portfolioForAccount(_ address: AccountAddress) -> AnyAsyncSequence<AccountPortfoliosClient.AccountPortfolio> {
portfoliosSubject.compactMap { $0[address].unwrap()?.wrappedValue }.removeDuplicates().eraseToAnyAsyncSequence()
}
private func setOrUpdateAccountPortfolio(_ portfolio: AccountPortfoliosClient.AccountPortfolio) {
portfoliosSubject.value.mutateValue {
$0.updateValue(portfolio, forKey: portfolio.account.address)
}
}
private func setOrUpdateAccountPortfolios(_ portfolios: [AccountPortfoliosClient.AccountPortfolio]) {
var newValue: [AccountAddress: AccountPortfoliosClient.AccountPortfolio] = portfoliosSubject.value.wrappedValue ?? [:]
for portfolio in portfolios {
newValue[portfolio.account.address] = portfolio
}
portfoliosSubject.value = .success(newValue)
}
}
// MARK: - Fiat worth setters
extension AccountPortfoliosClient.State {
func applyFiatWorth(_ portfolio: inout AccountPortfoliosClient.AccountPortfolio) {
applyTokenPrices(to: &portfolio)
applyCurrencyVisibility(to: &portfolio)
applyFiatCurrency(to: &portfolio)
}
func setTokenPrices(_ tokenPrices: Result<TokenPrices, Error>) {
self.tokenPrices = tokenPrices
if var existingPortfolios = portfoliosSubject.value.values.wrappedValue.map({ Array($0) }) {
applyTokenPrices(to: &existingPortfolios)
setOrUpdateAccountPortfolios(existingPortfolios)
}
}
func setIsCurrencyAmountVisble(_ isVisible: Bool) {
self.isCurrencyAmountVisible = isVisible
if var existingPortfolios = portfoliosSubject.value.values.wrappedValue.map({ Array($0) }) {
applyCurrencyVisibility(to: &existingPortfolios)
setOrUpdateAccountPortfolios(existingPortfolios)
}
}
func setSelectedCurrency(_ currency: FiatCurrency) {
self.selectedCurrency = currency
if var existingPortfolios = portfoliosSubject.value.values.wrappedValue.map({ Array($0) }) {
applyFiatCurrency(to: &existingPortfolios)
setOrUpdateAccountPortfolios(existingPortfolios)
}
}
func applyTokenPrices(to portfolios: inout [AccountPortfoliosClient.AccountPortfolio]) {
portfolios.mutateAll(applyTokenPrices)
}
func applyTokenPrices(to portfolio: inout AccountPortfoliosClient.AccountPortfolio) {
portfolio.updateFiatWorth(calculateWorth(gateway))
}
func applyCurrencyVisibility(to portfolio: inout AccountPortfoliosClient.AccountPortfolio) {
portfolio.isCurrencyAmountVisible = isCurrencyAmountVisible
portfolio.updateFiatWorth(value: isCurrencyAmountVisible, to: \.isVisible)
}
func applyCurrencyVisibility(to portfolios: inout [AccountPortfoliosClient.AccountPortfolio]) {
portfolios.mutateAll(applyCurrencyVisibility)
}
func applyFiatCurrency(to portfolio: inout AccountPortfoliosClient.AccountPortfolio) {
portfolio.fiatCurrency = self.selectedCurrency
portfolio.updateFiatWorth(value: selectedCurrency, to: \.currency)
}
func applyFiatCurrency(to portfolios: inout [AccountPortfoliosClient.AccountPortfolio]) {
portfolios.mutateAll(applyFiatCurrency)
}
}
// MARK: - Stake and Pool details handling
extension AccountPortfoliosClient.State {
func calculateWorth(_ gateway: Gateway) -> (ResourceAddress, ExactResourceAmount) -> FiatWorth? {
{ resourceAddress, amount in
let worth: FiatWorth.Worth? = {
guard case let .success(tokenPrices) = self.tokenPrices else {
return .unknown
}
let price = {
#if DEBUG
if gateway != .mainnet {
if resourceAddress == .mainnetXRD {
return tokenPrices[resourceAddress]
} else {
return tokenPrices.values.randomElement()
}
} else {
return tokenPrices[resourceAddress]
}
#else
return tokenPrices[resourceAddress]
#endif
}()
return price.map { .known($0 * amount.nominalAmount) }
}()
return worth.map {
.init(
isVisible: self.isCurrencyAmountVisible,
worth: $0,
currency: self.selectedCurrency
)
}
}
}
func set(poolDetails: Loadable<[OnLedgerEntitiesClient.OwnedResourcePoolDetails]>, forAccount address: AccountAddress) {
guard var portfolio = portfoliosSubject.value.wrappedValue?[address] else {
return
}
portfolio.poolUnitDetails = poolDetails.map { details in
var details = details
details.updateFiatWorth(calculateWorth(gateway))
return details
}
setOrUpdateAccountPortfolio(portfolio)
}
func set(stakeUnitDetails: Loadable<IdentifiedArrayOf<OnLedgerEntitiesClient.OwnedStakeDetails>>, forAccount address: AccountAddress) {
guard var portfolio = portfoliosSubject.value.wrappedValue?[address] else {
return
}
portfolio.stakeUnitDetails = stakeUnitDetails.map { details in
var details = details
details.updateFiatWorth(calculateWorth(gateway))
return details
}
setOrUpdateAccountPortfolio(portfolio)
}
}
// MARK: Fiat Worth changes
private extension AccountPortfoliosClient.AccountPortfolio {
mutating func updateFiatWorth<T>(value: T, to keyPath: WritableKeyPath<FiatWorth, T>) {
updateFiatWorth { _, worth in
var worth = worth.fiatWorth
worth?[keyPath: keyPath] = value
return worth
}
}
mutating func updateFiatWorth(_ change: (ResourceAddress, ExactResourceAmount) -> FiatWorth?) {
account.fungibleResources.updateFiatWorth(change)
stakeUnitDetails.mutateValue { $0.updateFiatWorth(change) }
poolUnitDetails.mutateValue { $0.updateFiatWorth(change) }
}
}
extension ResourceAmount {
mutating func updateFiatWorth(
resourceAddress: ResourceAddress,
change: (ResourceAddress, ExactResourceAmount) -> FiatWorth?
) {
switch self {
case var .exact(exactAmount):
exactAmount.fiatWorth = change(resourceAddress, exactAmount)
self = .exact(exactAmount)
case var .atLeast(exactAmount):
exactAmount.fiatWorth = change(resourceAddress, exactAmount)
self = .atLeast(exactAmount)
case var .atMost(exactAmount):
exactAmount.fiatWorth = change(resourceAddress, exactAmount)
self = .atMost(exactAmount)
case var .between(minExactAmount, maxExactAmount):
minExactAmount.fiatWorth = change(resourceAddress, minExactAmount)
maxExactAmount.fiatWorth = change(resourceAddress, maxExactAmount)
self = .between(minimum: minExactAmount, maximum: maxExactAmount)
case var .predicted(predicted, guaranteed):
predicted.fiatWorth = change(resourceAddress, predicted)
guaranteed.fiatWorth = change(resourceAddress, guaranteed)
self = .predicted(predicted: predicted, guaranteed: guaranteed)
case .unknown:
return
}
}
}
private extension OnLedgerEntity.OwnedFungibleResources {
mutating func updateFiatWorth(_ change: (ResourceAddress, ExactResourceAmount) -> FiatWorth?) {
xrdResource.mutate { resource in
resource.amount.updateFiatWorth(resourceAddress: .mainnetXRD, change: change)
}
nonXrdResources.mutateAll { resource in
resource.amount.updateFiatWorth(resourceAddress: resource.resourceAddress, change: change)
}
nonXrdResources.sort(by: <)
}
}
private extension MutableCollection where Element == OnLedgerEntitiesClient.OwnedResourcePoolDetails {
mutating func updateFiatWorth(_ change: (ResourceAddress, ExactResourceAmount) -> FiatWorth?) {
mutateAll { detail in
detail.xrdResource?.redemptionValue.mutate { amount in
amount.updateFiatWorth(resourceAddress: .mainnetXRD, change: change)
}
detail.nonXrdResources.mutateAll { resource in
let address = resource.resource.resourceAddress
resource.redemptionValue.mutate { amount in
amount.updateFiatWorth(resourceAddress: address, change: change)
}
}
}
}
}
private extension MutableCollection where Element == OnLedgerEntitiesClient.OwnedStakeDetails {
mutating func updateFiatWorth(_ change: (ResourceAddress, ExactResourceAmount) -> FiatWorth?) {
mutateAll { detail in
var stakeUnitResource = detail.stakeUnitResource
stakeUnitResource.mutate {
$0.amount.updateFiatWorth(resourceAddress: .mainnetXRD, change: {
change(
$0,
detail.xrdRedemptionValue(exactAmount: $1)
)
})
}
detail.stakeClaimTokens.mutate {
$0.stakeClaims.mutateAll { token in
token.claimAmount.fiatWorth = change(.mainnetXRD, token.claimAmount)
}
}
detail.stakeUnitResource = stakeUnitResource
}
}
}
// MARK: - Account portfolio fiat worth
extension AccountPortfoliosClient.AccountPortfolio {
var totalFiatWorth: Loadable<FiatWorth> {
poolUnitDetails.concat(stakeUnitDetails).map { poolUnitDetails, stakeUnitDetails in
let totalFiatWorth = account.fungibleResources.fiatWorth + stakeUnitDetails.fiatWorth + poolUnitDetails.fiatWorth
return .init(isVisible: isCurrencyAmountVisible, worth: totalFiatWorth, currency: fiatCurrency)
}
.errorFallback(.unknownWorth(isVisible: isCurrencyAmountVisible, currency: fiatCurrency))
}
}
private extension OnLedgerEntity.OwnedFungibleResources {
var fiatWorth: FiatWorth.Worth {
let xrdFiatWorth = xrdResource?.amount.exactAmount?.fiatWorth?.worth ?? .zero
let nonXrdFiatWorth = nonXrdResources.compactMap(\.amount.exactAmount?.fiatWorth?.worth).reduce(.zero, +)
return xrdFiatWorth + nonXrdFiatWorth
}
}
private extension Collection<OnLedgerEntitiesClient.OwnedStakeDetails> {
var fiatWorth: FiatWorth.Worth {
reduce(.zero) { partialResult, stakeUnitDetail in
let stakeUnitFiatWorth = stakeUnitDetail.stakeUnitResource?.amount.exactAmount?.fiatWorth?.worth ?? .zero
let stakeClaimsFiatWorth = stakeUnitDetail
.stakeClaimTokens?
.stakeClaims
.compactMap(\.claimAmount.fiatWorth?.worth)
.reduce(.zero, +) ?? .zero
return partialResult + stakeUnitFiatWorth + stakeClaimsFiatWorth
}
}
}
private extension Collection<OnLedgerEntitiesClient.OwnedResourcePoolDetails> {
var fiatWorth: FiatWorth.Worth {
reduce(.zero) { partialResult, poolUnitDetail in
let xrdFiatWorth = poolUnitDetail.xrdResource?.redemptionValue?.exactAmount?.fiatWorth?.worth ?? .zero
let nonXrdFiatWorth = poolUnitDetail.nonXrdResources.compactMap(\.redemptionValue?.exactAmount?.fiatWorth?.worth).reduce(.zero, +)
return partialResult + xrdFiatWorth + nonXrdFiatWorth
}
}
}