-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathCurrencyRepo.kt
More file actions
278 lines (244 loc) · 9.75 KB
/
CurrencyRepo.kt
File metadata and controls
278 lines (244 loc) · 9.75 KB
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
package to.bitkit.repositories
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.currentCoroutineContext
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import to.bitkit.R
import to.bitkit.data.CacheStore
import to.bitkit.data.SettingsStore
import to.bitkit.di.BgDispatcher
import to.bitkit.env.Env
import to.bitkit.models.BTC_SCALE
import to.bitkit.models.BitcoinDisplayUnit
import to.bitkit.models.ConvertedAmount
import to.bitkit.models.FxRate
import to.bitkit.models.PrimaryDisplay
import to.bitkit.models.SATS_IN_BTC
import to.bitkit.models.STUB_RATE
import to.bitkit.models.ToastText
import to.bitkit.models.asBtc
import to.bitkit.models.formatCurrency
import to.bitkit.services.CurrencyService
import to.bitkit.ui.shared.toast.Toaster
import to.bitkit.utils.Logger
import java.math.BigDecimal
import java.math.RoundingMode
import javax.inject.Inject
import javax.inject.Named
import javax.inject.Singleton
import kotlin.time.Clock
import kotlin.time.ExperimentalTime
@OptIn(ExperimentalTime::class)
@Suppress("TooManyFunctions", "LongParameterList")
@Singleton
class CurrencyRepo @Inject constructor(
@BgDispatcher private val bgDispatcher: CoroutineDispatcher,
private val currencyService: CurrencyService,
private val settingsStore: SettingsStore,
private val cacheStore: CacheStore,
private val clock: Clock,
@Named("enablePolling") private val enablePolling: Boolean,
private val toaster: Toaster,
) : AmountInputHandler {
private val repoScope = CoroutineScope(bgDispatcher + SupervisorJob())
private val _currencyState = MutableStateFlow(CurrencyState())
val currencyState: StateFlow<CurrencyState> = _currencyState.asStateFlow()
@Volatile
private var isRefreshing = false
private val fxRatePollingFlow: Flow<Unit>
get() = flow {
while (currentCoroutineContext().isActive) {
emit(Unit)
delay(Env.fxRateRefreshInterval)
}
}.flowOn(bgDispatcher)
init {
if (enablePolling) {
startPolling()
}
observeStaleData()
collectCachedData()
}
private fun startPolling() {
repoScope.launch {
fxRatePollingFlow.collect {
refresh()
}
}
}
private fun observeStaleData() {
repoScope.launch {
currencyState
.map { it.hasStaleData }
.distinctUntilChanged()
.collect { isStale ->
if (isStale) {
toaster.error(
title = ToastText(R.string.currency__rates_error_title),
body = ToastText(R.string.currency__rates_error_body),
)
}
}
}
}
private fun collectCachedData() {
repoScope.launch {
combine(
settingsStore.data.distinctUntilChanged(),
cacheStore.data.distinctUntilChanged()
) { settings, cache ->
val selectedRate = cache.cachedRates.firstOrNull { rate ->
rate.quote == settings.selectedCurrency
}
_currencyState.value.copy(
rates = cache.cachedRates,
selectedCurrency = settings.selectedCurrency,
displayUnit = settings.displayUnit,
primaryDisplay = settings.primaryDisplay,
currencySymbol = selectedRate?.currencySymbol ?: "$",
error = null,
hasStaleData = false,
)
}.collect { newState ->
_currencyState.update { newState }
}
}
}
suspend fun triggerRefresh() = withContext(bgDispatcher) {
refresh()
}
private suspend fun refresh() {
if (isRefreshing) return
isRefreshing = true
runCatching {
val fetchedRates = currencyService.fetchLatestRates()
cacheStore.update { it.copy(cachedRates = fetchedRates) }
_currencyState.update {
it.copy(
error = null,
hasStaleData = false,
lastSuccessfulRefresh = clock.now().toEpochMilliseconds(),
)
}
Logger.debug("Currency rates refreshed successfully", context = TAG)
}.onFailure { e ->
Logger.error("Currency rates refresh failed", e, context = TAG)
_currencyState.update { it.copy(error = e) }
_currencyState.value.lastSuccessfulRefresh?.let { lastUpdatedAt ->
val isStale = clock.now().toEpochMilliseconds() - lastUpdatedAt > Env.fxRateStaleThreshold
_currencyState.update { it.copy(hasStaleData = isStale) }
}
}
isRefreshing = false
}
suspend fun switchUnit() = withContext(bgDispatcher) {
settingsStore.update { it.copy(primaryDisplay = it.primaryDisplay.not()) }
}
override suspend fun switchUnit(unit: PrimaryDisplay): PrimaryDisplay = withContext(bgDispatcher) {
unit.not().also { nextValue ->
setPrimaryDisplayUnit(nextValue)
}
}
suspend fun setPrimaryDisplayUnit(unit: PrimaryDisplay) = withContext(bgDispatcher) {
settingsStore.update { it.copy(primaryDisplay = unit) }
}
suspend fun setBtcDisplayUnit(unit: BitcoinDisplayUnit) = withContext(bgDispatcher) {
settingsStore.update { it.copy(displayUnit = unit) }
}
suspend fun setSelectedCurrency(currency: String) = withContext(bgDispatcher) {
settingsStore.update { it.copy(selectedCurrency = currency) }
refresh()
}
fun getCurrentRate(currency: String): FxRate {
val rates = _currencyState.value.rates
val rate = rates.firstOrNull { it.quote == currency }
return checkNotNull(rate) {
"Rate not found for currency: $currency in: ${rates.joinToString { it.quote }}"
}
}
fun convertSatsToFiat(
sats: Long,
currency: String? = null,
): Result<ConvertedAmount> = runCatching {
val targetCurrency = currency ?: _currencyState.value.selectedCurrency
val rate = getCurrentRate(targetCurrency)
val (fiatValue, formatted) = convertSatsToFiatPair(sats, targetCurrency).getOrThrow()
ConvertedAmount(
value = fiatValue,
formatted = formatted,
symbol = rate.currencySymbol,
currency = rate.quote,
flag = rate.currencyFlag,
sats = sats,
)
}
fun convertSatsToFiatPair(
sats: Long,
currency: String? = null,
): Result<Pair<BigDecimal, String>> = runCatching {
val targetCurrency = currency ?: _currencyState.value.selectedCurrency
val rate = getCurrentRate(targetCurrency)
val btcAmount = sats.asBtc()
val fiatValue = btcAmount.multiply(BigDecimal.valueOf(rate.rate))
val formatted = checkNotNull(fiatValue.formatCurrency()) {
"Failed to format value: $fiatValue for currency: $targetCurrency"
}
return@runCatching fiatValue to formatted
}
fun convertFiatToSats(
fiatValue: BigDecimal,
currency: String? = null,
): Result<ULong> = runCatching {
val targetCurrency = currency ?: _currencyState.value.selectedCurrency
val rate = getCurrentRate(targetCurrency)
val btcAmount = fiatValue.divide(BigDecimal.valueOf(rate.rate), BTC_SCALE, RoundingMode.HALF_UP)
val satsDecimal = btcAmount.multiply(BigDecimal(SATS_IN_BTC))
val roundedSats = satsDecimal.setScale(0, RoundingMode.HALF_UP)
roundedSats.toLong().toULong()
}
fun convertFiatToSats(fiat: Double, currency: String?) = convertFiatToSats(BigDecimal.valueOf(fiat), currency)
companion object {
private const val TAG = "CurrencyRepo"
}
// MARK: - AmountHandler
override fun convertFiatToSats(fiat: Double) = convertFiatToSats(BigDecimal.valueOf(fiat)).getOrDefault(0u).toLong()
override fun convertSatsToFiatString(sats: Long): String = convertSatsToFiatPair(sats).getOrNull()?.second ?: ""
}
data class CurrencyState(
val rates: List<FxRate> = emptyList(),
val error: Throwable? = null,
val hasStaleData: Boolean = false,
val selectedCurrency: String = "USD",
val currencySymbol: String = "$",
val displayUnit: BitcoinDisplayUnit = BitcoinDisplayUnit.MODERN,
val primaryDisplay: PrimaryDisplay = PrimaryDisplay.BITCOIN,
val lastSuccessfulRefresh: Long? = null,
)
interface AmountInputHandler {
fun convertSatsToFiatString(sats: Long): String
fun convertFiatToSats(fiat: Double): Long
suspend fun switchUnit(unit: PrimaryDisplay): PrimaryDisplay
companion object {
fun stub(state: CurrencyState = CurrencyState()) = object : AmountInputHandler {
override fun convertSatsToFiatString(sats: Long): String {
return sats.asBtc().multiply(BigDecimal.valueOf(STUB_RATE)).formatCurrency() ?: ""
}
override fun convertFiatToSats(fiat: Double) = (fiat / STUB_RATE * SATS_IN_BTC).toLong()
override suspend fun switchUnit(unit: PrimaryDisplay) = unit.not()
}
}
}