-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathBlocktankRepo.kt
More file actions
369 lines (318 loc) · 13.1 KB
/
BlocktankRepo.kt
File metadata and controls
369 lines (318 loc) · 13.1 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
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
package to.bitkit.repositories
import com.synonym.bitkitcore.CreateCjitOptions
import com.synonym.bitkitcore.CreateOrderOptions
import com.synonym.bitkitcore.IBtEstimateFeeResponse2
import com.synonym.bitkitcore.IBtInfo
import com.synonym.bitkitcore.IBtOrder
import com.synonym.bitkitcore.IcJitEntry
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.currentCoroutineContext
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.onEach
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import to.bitkit.data.CacheStore
import to.bitkit.di.BgDispatcher
import to.bitkit.env.Env
import to.bitkit.ext.nowTimestamp
import to.bitkit.services.CoreService
import to.bitkit.services.LightningService
import to.bitkit.utils.Logger
import to.bitkit.utils.ServiceError
import java.math.BigDecimal
import javax.inject.Inject
import javax.inject.Named
import javax.inject.Singleton
import kotlin.math.ceil
import kotlin.math.min
@Singleton
class BlocktankRepo @Inject constructor(
@BgDispatcher private val bgDispatcher: CoroutineDispatcher,
private val coreService: CoreService,
private val lightningService: LightningService,
private val currencyRepo: CurrencyRepo,
private val cacheStore: CacheStore,
@Named("enablePolling") private val enablePolling: Boolean,
) {
private val repoScope = CoroutineScope(bgDispatcher + SupervisorJob())
private val _blocktankState = MutableStateFlow(BlocktankState())
val blocktankState: StateFlow<BlocktankState> = _blocktankState.asStateFlow()
@Volatile
private var isRefreshing = false
init {
startPolling()
observePaidOrders()
repoScope.launch {
refreshInfo()
refreshOrders()
}
}
private fun startPolling() {
if (!enablePolling) return
flow {
while (currentCoroutineContext().isActive) {
emit(Unit)
delay(Env.blocktankOrderRefreshInterval)
}
}.flowOn(bgDispatcher)
.onEach { refreshOrders() }
.launchIn(repoScope)
}
private fun observePaidOrders() {
repoScope.launch {
cacheStore.data
.map { it.paidOrders }
.distinctUntilChanged()
.map { it.keys }
.collect { paidOrderIds ->
_blocktankState.update { state ->
state.copy(
paidOrders = state.orders.filter { order -> order.id in paidOrderIds },
)
}
}
}
}
suspend fun refreshInfo() = withContext(bgDispatcher) {
try {
// Load from cache first
val cachedInfo = coreService.blocktank.info(refresh = false)
_blocktankState.update { it.copy(info = cachedInfo) }
// Then refresh from server
val info = coreService.blocktank.info(refresh = true)
_blocktankState.update { it.copy(info = info) }
Logger.debug("Blocktank info refreshed", context = TAG)
} catch (e: Throwable) {
Logger.error("Failed to refresh blocktank info", e, context = TAG)
}
}
suspend fun refreshOrders() = withContext(bgDispatcher) {
if (isRefreshing) return@withContext
isRefreshing = true
try {
Logger.debug("Refreshing blocktank orders…", context = TAG)
val paidOrderIds = cacheStore.data.first().paidOrders.keys
// Sync instantly from cache
val cachedOrders = coreService.blocktank.orders(refresh = false)
val cachedCjitEntries = coreService.blocktank.cjitOrders(refresh = false)
_blocktankState.update { state ->
state.copy(
orders = cachedOrders,
cjitEntries = cachedCjitEntries,
paidOrders = cachedOrders.filter { order -> order.id in paidOrderIds },
)
}
// Then refresh from server
val orders = coreService.blocktank.orders(refresh = true)
val cjitEntries = coreService.blocktank.cjitOrders(refresh = true)
_blocktankState.update { state ->
state.copy(
orders = orders,
cjitEntries = cjitEntries,
paidOrders = orders.filter { order -> order.id in paidOrderIds },
)
}
Logger.debug(
"Orders refreshed: ${orders.size} orders, ${cjitEntries.size} cjit entries",
context = TAG
)
} catch (e: Throwable) {
Logger.error("Failed to refresh orders", e, context = TAG)
} finally {
isRefreshing = false
}
}
suspend fun refreshMinCjitSats() = withContext(bgDispatcher) {
try {
val lspBalance = getDefaultLspBalance(clientBalance = 0u)
val fees = estimateOrderFee(
spendingBalanceSats = 0u,
receivingBalanceSats = lspBalance,
).getOrThrow()
val minimum = (ceil(fees.feeSat.toDouble() * 1.1 / 1000) * 1000).toInt()
_blocktankState.update { it.copy(minCjitSats = minimum) }
Logger.debug("Updated minCjitSats to: $minimum", context = TAG)
} catch (e: Throwable) {
Logger.error("Failed to refresh minCjitSats", e, context = TAG)
}
}
suspend fun createCjit(
amountSats: ULong,
description: String = Env.DEFAULT_INVOICE_MESSAGE,
): Result<IcJitEntry> = withContext(bgDispatcher) {
try {
val nodeId = lightningService.nodeId ?: throw ServiceError.NodeNotStarted
val lspBalance = getDefaultLspBalance(clientBalance = amountSats)
val channelSizeSat = amountSats + lspBalance
val cjitEntry = coreService.blocktank.createCjit(
channelSizeSat = channelSizeSat,
invoiceSat = amountSats,
invoiceDescription = description,
nodeId = nodeId,
channelExpiryWeeks = DEFAULT_CHANNEL_EXPIRY_WEEKS,
options = CreateCjitOptions(source = DEFAULT_SOURCE, discountCode = null)
)
repoScope.launch { refreshOrders() }
Result.success(cjitEntry)
} catch (e: Throwable) {
Logger.error("Failed to create CJIT", e, context = TAG)
Result.failure(e)
}
}
suspend fun createOrder(
spendingBalanceSats: ULong,
receivingBalanceSats: ULong = spendingBalanceSats * 2u,
channelExpiryWeeks: UInt = DEFAULT_CHANNEL_EXPIRY_WEEKS,
): Result<IBtOrder> = withContext(bgDispatcher) {
try {
val options = defaultCreateOrderOptions(clientBalanceSat = spendingBalanceSats)
Logger.info(
"Buying channel with lspBalanceSat: $receivingBalanceSats, channelExpiryWeeks: $channelExpiryWeeks, options: $options",
context = TAG,
)
val order = coreService.blocktank.newOrder(
lspBalanceSat = receivingBalanceSats,
channelExpiryWeeks = channelExpiryWeeks,
options = options,
)
repoScope.launch { refreshOrders() }
Result.success(order)
} catch (e: Throwable) {
Logger.error("Failed to create order", e, context = TAG)
Result.failure(e)
}
}
suspend fun estimateOrderFee(
spendingBalanceSats: ULong,
receivingBalanceSats: ULong,
channelExpiryWeeks: UInt = DEFAULT_CHANNEL_EXPIRY_WEEKS,
): Result<IBtEstimateFeeResponse2> = withContext(bgDispatcher) {
Logger.info("Estimating order fee for spendingSats=$spendingBalanceSats, receivingSats=$receivingBalanceSats")
try {
val options = defaultCreateOrderOptions(clientBalanceSat = spendingBalanceSats)
val estimate = coreService.blocktank.estimateFee(
lspBalanceSat = receivingBalanceSats,
channelExpiryWeeks = channelExpiryWeeks,
options = options,
)
Logger.debug("Estimated order fee: '$estimate'")
Result.success(estimate)
} catch (e: Throwable) {
Logger.error("Failed to estimate order fee", e, context = TAG)
Result.failure(e)
}
}
suspend fun openChannel(orderId: String): Result<IBtOrder> = withContext(bgDispatcher) {
try {
Logger.debug("Opening channel for order: '$orderId'", context = TAG)
val order = coreService.blocktank.open(orderId)
// Update the order in state
val updatedOrders = _blocktankState.value.orders.toMutableList()
val index = updatedOrders.indexOfFirst { it.id == order.id }
if (index != -1) {
updatedOrders[index] = order
}
_blocktankState.update { state -> state.copy(orders = updatedOrders) }
Result.success(order)
} catch (e: Throwable) {
Logger.error("Failed to open channel for order: $orderId", e, context = TAG)
Result.failure(e)
}
}
suspend fun getOrder(
orderId: String,
refresh: Boolean = false,
): Result<IBtOrder?> = withContext(bgDispatcher) {
try {
if (refresh) {
refreshOrders()
}
val order = _blocktankState.value.orders.find { it.id == orderId }
Result.success(order)
} catch (e: Throwable) {
Logger.error("Failed to get order: $orderId", e, context = TAG)
Result.failure(e)
}
}
private suspend fun defaultCreateOrderOptions(clientBalanceSat: ULong): CreateOrderOptions {
val nodeId = lightningService.nodeId ?: throw ServiceError.NodeNotStarted
val timestamp = nowTimestamp().toString()
val signature = lightningService.sign("channelOpen-$timestamp")
return CreateOrderOptions(
clientBalanceSat = clientBalanceSat,
lspNodeId = null,
couponCode = "",
source = DEFAULT_SOURCE,
discountCode = null,
zeroConf = true,
zeroConfPayment = false,
zeroReserve = true,
clientNodeId = nodeId,
signature = signature,
timestamp = timestamp,
refundOnchainAddress = null,
announceChannel = false,
)
}
suspend fun getDefaultLspBalance(clientBalance: ULong): ULong = withContext(bgDispatcher) {
if (_blocktankState.value.info == null) {
refreshInfo()
}
val maxLspBalance = _blocktankState.value.info?.options?.maxChannelSizeSat ?: 0uL
// Calculate thresholds in sats
val threshold1 = currencyRepo.convertFiatToSats(BigDecimal(225), EUR_CURRENCY).getOrNull()
val threshold2 = currencyRepo.convertFiatToSats(BigDecimal(495), EUR_CURRENCY).getOrNull()
val defaultLspBalanceSats = currencyRepo.convertFiatToSats(BigDecimal(450), EUR_CURRENCY).getOrNull()
Logger.debug("getDefaultLspBalance - clientBalance: $clientBalance", context = TAG)
Logger.debug("getDefaultLspBalance - maxLspBalance: $maxLspBalance", context = TAG)
Logger.debug(
"getDefaultLspBalance - defaultLspBalance: $defaultLspBalanceSats",
context = TAG
)
if (threshold1 == null || threshold2 == null || defaultLspBalanceSats == null) {
Logger.error("Failed to get rates for lspBalance calculation", context = TAG)
throw ServiceError.CurrencyRateUnavailable
}
// Safely calculate lspBalance to avoid arithmetic overflow
var lspBalance: ULong = 0u
if (defaultLspBalanceSats > clientBalance) {
lspBalance = defaultLspBalanceSats - clientBalance
}
if (clientBalance > threshold1) {
lspBalance = clientBalance
}
if (clientBalance > threshold2) {
lspBalance = maxLspBalance
}
return@withContext min(lspBalance, maxLspBalance)
}
suspend fun resetState() = withContext(bgDispatcher) {
_blocktankState.update { BlocktankState() }
}
companion object {
private const val TAG = "BlocktankRepo"
private const val DEFAULT_CHANNEL_EXPIRY_WEEKS = 6u
private const val DEFAULT_SOURCE = "bitkit-android"
private const val EUR_CURRENCY = "EUR"
}
}
data class BlocktankState(
val orders: List<IBtOrder> = emptyList(),
val paidOrders: List<IBtOrder> = emptyList(),
val cjitEntries: List<IcJitEntry> = emptyList(),
val info: IBtInfo? = null,
val minCjitSats: Int? = null,
)