Skip to content

Commit

Permalink
Merge branch 'dev' of https://github.com/tonkeeper/android into dev
Browse files Browse the repository at this point in the history
  • Loading branch information
polstianka committed Oct 2, 2024
2 parents e29804b + 49a5693 commit b401994
Show file tree
Hide file tree
Showing 10 changed files with 58 additions and 50 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,16 @@ import android.content.Context
import com.android.billingclient.api.*
import com.android.billingclient.api.BillingClient.ProductType
import com.tonapps.extensions.MutableEffectFlow
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.flow.asSharedFlow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.shareIn

class BillingManager(
context: Context,
scope: CoroutineScope,
) {

private var billingClient: BillingClient
Expand All @@ -21,6 +25,9 @@ class BillingManager(
private val _productsFlow = MutableStateFlow<List<ProductDetails>?>(null)
val productsFlow = _productsFlow.asStateFlow()

private val _madePurchaseFlow = MutableEffectFlow<Unit>()
val madePurchaseFlow = _madePurchaseFlow.shareIn(scope, SharingStarted.Lazily, 1)

private val purchasesUpdatedListener = PurchasesUpdatedListener { billingResult, purchases ->
if (billingResult.responseCode == BillingClient.BillingResponseCode.OK && purchases != null) {
_purchasesFlow.tryEmit(purchases)
Expand Down Expand Up @@ -48,6 +55,12 @@ class BillingManager(
isInitialized = false
}
})

notifyPurchase()
}

private fun notifyPurchase() {
_madePurchaseFlow.tryEmit(Unit)
}

fun getProducts(
Expand Down Expand Up @@ -94,6 +107,7 @@ class BillingManager(
suspend fun consumeProduct(purchase: Purchase) {
val params = ConsumeParams.newBuilder().setPurchaseToken(purchase.purchaseToken).build()
billingClient.consumePurchase(params)
notifyPurchase()
}

suspend fun restorePurchases() {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,11 +1,9 @@
package com.tonapps.tonkeeper.ui.screen.battery.recharge

import android.os.Bundle
import android.util.Log
import android.view.Gravity
import android.view.View
import android.view.ViewGroup.inflate
import androidx.annotation.StringRes
import androidx.appcompat.widget.AppCompatTextView
import androidx.appcompat.widget.LinearLayoutCompat
import androidx.lifecycle.lifecycleScope
Expand All @@ -20,7 +18,6 @@ import com.tonapps.tonkeeper.ui.base.ScreenContext
import com.tonapps.tonkeeper.ui.screen.battery.BatteryScreen
import com.tonapps.tonkeeper.ui.screen.battery.recharge.entity.BatteryRechargeEvent
import com.tonapps.tonkeeper.ui.screen.battery.recharge.list.Adapter
import com.tonapps.tonkeeper.ui.screen.root.RootViewModel
import com.tonapps.tonkeeper.ui.screen.send.contacts.SendContactsScreen
import com.tonapps.tonkeeper.ui.screen.send.main.SendContact
import com.tonapps.tonkeeper.ui.screen.token.picker.TokenPickerScreen
Expand All @@ -35,15 +32,11 @@ import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach
import kotlinx.coroutines.flow.take
import kotlinx.coroutines.launch
import org.koin.androidx.viewmodel.ext.android.activityViewModel
import org.koin.androidx.viewmodel.ext.android.viewModel
import org.koin.core.parameter.parametersOf
import uikit.base.BaseFragment
import uikit.extensions.collectFlow
import uikit.extensions.doKeyboardAnimation
import uikit.extensions.hideKeyboard
import uikit.extensions.pinToBottomInsets
import uikit.widget.FrescoView
import uikit.widget.InputView
import java.util.UUID
Expand Down Expand Up @@ -161,17 +154,19 @@ class BatteryRechargeScreen(wallet: WalletEntity): BaseListWalletScreen<ScreenCo
finish()
}

private fun sing(request: SignRequestEntity) {
private fun sign(request: SignRequestEntity) {
viewModel.sign(request).catch {
showError(it.bestMessage)
}.onEach {
onSuccess()
postDelayed(1000) {
onSuccess()
}
}.launchIn(lifecycleScope)
}

private fun onEvent(event: BatteryRechargeEvent) {
when (event) {
is BatteryRechargeEvent.Sign -> sing(event.request)
is BatteryRechargeEvent.Sign -> sign(event.request)
is BatteryRechargeEvent.Error -> showError()
is BatteryRechargeEvent.MaxAmountError -> {
val message = requireContext().getString(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,7 @@ import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import org.ton.block.AddrStd
import uikit.extensions.collectFlow
import java.math.BigDecimal

class BatteryRechargeViewModel(
app: Application,
Expand Down Expand Up @@ -142,7 +143,7 @@ class BatteryRechargeViewModel(
val hasEnoughTonBalance = ton.balance.value >= Coins.of(0.1)
val hasBatteryBalance = batteryBalance.balance > Coins.ZERO
val rechargeMethod = getRechargeMethod(wallet, token)
val shouldMinusReservedAmount = batteryBalance.reservedBalance == Coins.ZERO || args.isGift
val shouldMinusReservedAmount = batteryBalance.reservedBalance.value == BigDecimal.ZERO || args.isGift

val batteryReservedAmount = rechargeMethod.fromTon(api.config.batteryReservedAmount)

Expand Down Expand Up @@ -200,6 +201,9 @@ class BatteryRechargeViewModel(
formattedRemaining = CurrencyFormatter.format(
currency = token.symbol, value = remainingBalance
),
formattedMinAmount = CurrencyFormatter.format(
currency = token.symbol, value = minAmount
),
isInsufficientBalance = remainingBalance.isNegative,
isLessThanMin = isLessThanMin,
formattedCharges = charges.toString(),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ sealed class Item(type: Int) : BaseListItem(type) {
data class Amount(
val symbol: String,
val formattedRemaining: CharSequence,
val formattedMinAmount: CharSequence,
val isInsufficientBalance: Boolean,
val isLessThanMin: Boolean,
val formattedCharges: CharSequence,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,21 +22,28 @@ class AmountHolder(
amountView.doOnValueChange = onValueChange
amountView.suffix = item.symbol
currencyView.text = item.formattedCharges
applyAvailable(item.formattedRemaining, item.isInsufficientBalance, item.isLessThanMin)
applyAvailable(item.formattedRemaining, item.formattedMinAmount, item.isInsufficientBalance, item.isLessThanMin)
amountView.focus()
}

override fun onUnbind() {
super.onUnbind()

amountView.setValue(0.0)
}

private fun applyAvailable(
formattedRemaining: CharSequence,
formattedMinAmount: CharSequence,
isInsufficientBalance: Boolean,
isLessThanMin: Boolean
) {
if (isInsufficientBalance) {
availableView.setText(Localization.insufficient_balance)
availableView.setTextColor(context.accentRedColor)
} else if (isLessThanMin) {
availableView.text = getString(Localization.insufficient_balance)
availableView.setTextColor(context.textSecondaryColor)
availableView.text = context.getString(Localization.minimum_amount, formattedMinAmount)
availableView.setTextColor(context.accentRedColor)
} else {
availableView.text =
context.getString(Localization.remaining_balance, formattedRemaining)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@ import uikit.span.ClickableSpanCompat
import uikit.widget.FrescoView
import uikit.widget.HeaderView
import uikit.widget.InputView
import uikit.widget.LoadableButton
import uikit.widget.ProcessTaskView
import uikit.widget.SlideBetweenView
import java.util.UUID
Expand Down Expand Up @@ -86,7 +87,7 @@ class SendScreen(wallet: WalletEntity) : WalletContextScreen(R.layout.fragment_s
private lateinit var statusView: AppCompatTextView
private lateinit var maxView: View
private lateinit var commentInput: InputView
private lateinit var button: Button
private lateinit var button: LoadableButton
private lateinit var taskContainerView: View
private lateinit var addressActionsView: View
private lateinit var confirmButton: Button
Expand Down Expand Up @@ -441,6 +442,8 @@ class SendScreen(wallet: WalletEntity) : WalletContextScreen(R.layout.fragment_s
reviewRecipientFeeView.setLoading()
reviewRecipientFeeView.subtitleView.isEnabled = false
confirmButton.isEnabled = false
button.isEnabled = false
button.isLoading = true
} else {
reviewRecipientFeeView.value = "${event.format}".withCustomSymbol(requireContext())
reviewRecipientFeeView.description =
Expand Down Expand Up @@ -468,6 +471,8 @@ class SendScreen(wallet: WalletEntity) : WalletContextScreen(R.layout.fragment_s
reviewRecipientFeeView.subtitleView.isEnabled = true
reviewRecipientFeeView.setDefault()
confirmButton.isEnabled = true
button.isEnabled = true
button.isLoading = false
}
}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package com.tonapps.tonkeeper.ui.screen.send.main

import android.app.Application
import android.util.Log
import androidx.lifecycle.viewModelScope
import com.tonapps.blockchain.ton.contract.WalletFeature
import com.tonapps.blockchain.ton.extensions.equalsAddress
Expand All @@ -23,7 +22,6 @@ import com.tonapps.tonkeeper.ui.screen.send.main.state.SendAmountState
import com.tonapps.tonkeeper.ui.screen.send.main.state.SendDestination
import com.tonapps.tonkeeper.ui.screen.send.main.state.SendTransaction
import com.tonapps.tonkeeper.ui.screen.send.main.state.SendTransferType
import com.tonapps.tonkeeper.usecase.emulation.EmulationUseCase
import com.tonapps.tonkeeper.usecase.sign.SignUseCase
import com.tonapps.wallet.api.API
import com.tonapps.wallet.api.SendBlockchainState
Expand Down Expand Up @@ -92,21 +90,6 @@ class SendViewModel(
private val signUseCase: SignUseCase
) : BaseWalletVM(app) {

private companion object {

private val ONE_HUNDRED = BigDecimal("100")
private val MIN_PERCENTAGE = BigDecimal("99.7")

private fun isInsufficientBalance(balance: BigDecimal, amount: BigDecimal): Boolean {
try {
val percentage = amount.divide(balance, 4, RoundingMode.HALF_UP).multiply(ONE_HUNDRED).setScale(2, RoundingMode.HALF_UP)
return percentage >= MIN_PERCENTAGE
} catch (e: Throwable) {
return false
}
}
}

private val isNft: Boolean
get() = nftAddress.isNotBlank()

Expand Down Expand Up @@ -433,21 +416,22 @@ class SendViewModel(
val tokenBalance = token.balance.value
val tokenAmount = getTokenAmount()
val isSendAll = tokenBalance == tokenAmount // || userInputFlow.value.max
val withRelayer = sendTransferType is SendTransferType.Gasless || sendTransferType is SendTransferType.Battery
if (token.isTon) {
if (isSendAll) {
onContinue()
} else {
val tonAmountWithFee = fee + tokenAmount
if (isInsufficientBalance(tokenBalance.value, tonAmountWithFee.value)) {
showInsufficientBalance(tonBalance, tonAmountWithFee)
val totalAmount = fee + tokenAmount
if (!withRelayer && totalAmount.value > tokenBalance.value) {
showInsufficientBalance(tonBalance, totalAmount)
} else {
onContinue()
}
}
} else {
val isGasless = sendTransferType is SendTransferType.Gasless
if (!isGasless && isInsufficientBalance(tonBalance.value, fee.value)) {
showInsufficientBalance(tonBalance, fee)
val totalAmount = fee + TransferEntity.BASE_FORWARD_AMOUNT
if (!withRelayer && totalAmount.value > tonBalance.value) {
showInsufficientBalance(tonBalance, totalAmount)
} else {
onContinue()
}
Expand All @@ -462,10 +446,11 @@ class SendViewModel(
}

private suspend fun showInsufficientBalance(balance: Coins, required: Coins) {
val batteryBalance = getBatteryBalance()
_uiEventFlow.tryEmit(SendEvent.InsufficientBalance(
balance = balance,
required = required,
withRechargeBattery = sendTransferType is SendTransferType.Battery,
withRechargeBattery = !api.config.batteryDisabled && batteryBalance.balance.value == BigDecimal.ZERO,
singleWallet = 1 >= getWalletCount()
))
}
Expand Down Expand Up @@ -494,20 +479,16 @@ class SendViewModel(
}

fun next() {
showIfInsufficientBalance {
startSendFlow()
}
}

private fun startSendFlow() {
_uiEventFlow.tryEmit(SendEvent.Confirm)
combine(
transferFlow.take(1),
tokensFlow.take(1)
) { transfer, tokens ->
val (coins, isSupportGasless) = calculateFee(transfer)
eventFee(transfer, tokens, coins, isSupportGasless)
}.filterNotNull().onEach {
showIfInsufficientBalance {
_uiEventFlow.tryEmit(SendEvent.Confirm)
}
_uiEventFlow.tryEmit(it)
}.flowOn(Dispatchers.IO).launchIn(viewModelScope)
}
Expand Down Expand Up @@ -627,7 +608,7 @@ class SendViewModel(

sendTransferType = SendTransferType.Gasless(
excessesAddress = excessesAddress,
gaslessFee = Coins.of(commission, transfer.token.decimals)
gaslessFee = Coins.ofNano(commission, transfer.token.decimals)
)

return Pair(Coins.ofNano(commission, transfer.token.decimals), true)
Expand Down Expand Up @@ -798,7 +779,7 @@ class SendViewModel(
val additionalGifts = if (sendTransferType is SendTransferType.Gasless) {
listOf(
transfer.gaslessInternalGift(
jettonAmount = Coins.ONE,
jettonAmount = (sendTransferType as SendTransferType.Gasless).gaslessFee,
batteryAddress = (sendTransferType as SendTransferType.Gasless).excessesAddress
)
)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ class WalletViewModel(
}
}.map { !it }

private val _streamFlow = combine(updateWalletSettings, _lastLtFlow) { _, lastLt -> lastLt }
private val _streamFlow = combine(updateWalletSettings, billingManager.madePurchaseFlow, _lastLtFlow) { _, _, lastLt -> lastLt }

init {
collectFlow(transactionManager.getEventsFlow(wallet)) { event ->
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -158,7 +158,7 @@

</uikit.widget.ColumnLayout>

<Button
<uikit.widget.LoadableButton
style="@style/Widget.App.Button"
android:id="@+id/button"
android:layout_width="match_parent"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ abstract class BaseListHolder<I: BaseListItem>(

fun unbind() {
item = null
onUnbind()
}

@CallSuper
Expand Down

0 comments on commit b401994

Please sign in to comment.