Skip to content

Commit

Permalink
fix: send or move FT Token balance,GitHub:469 & 470
Browse files Browse the repository at this point in the history
  • Loading branch information
zhouxl committed Oct 31, 2024
1 parent 515e4c6 commit 3c66017
Show file tree
Hide file tree
Showing 5 changed files with 169 additions and 60 deletions.
31 changes: 15 additions & 16 deletions FRW/Modules/MultiBackup/ViewModel/BackupUploadViewModel.swift
Original file line number Diff line number Diff line change
Expand Up @@ -142,8 +142,8 @@ class BackupUploadViewModel: ObservableObject {
case .idle:
Task {
do {
buttonState = .loading
DispatchQueue.main.async {
self.buttonState = .loading
self.mnemonicBlur = true
}
try await MultiBackupManager.shared.preLogin(with: currentType)
Expand All @@ -162,7 +162,10 @@ class BackupUploadViewModel: ObservableObject {
case .upload:
Task {
do {
buttonState = .loading
DispatchQueue.main.async {
self.buttonState = .loading
}

try await MultiBackupManager.shared.backupKey(on: currentType)
toggleProcess(process: .regist)
onClickButton()
Expand All @@ -175,14 +178,18 @@ class BackupUploadViewModel: ObservableObject {
case .regist:
Task {
do {
buttonState = .loading
DispatchQueue.main.async {
self.buttonState = .loading
}

try await MultiBackupManager.shared.syncKeyToServer(on: currentType)
DispatchQueue.main.async {
self.mnemonicBlur = false
self.buttonState = .enabled
}
toggleProcess(process: .finish)
// onClickButton()
buttonState = .enabled

} catch {
buttonState = .enabled
HUD.dismissLoading()
Expand All @@ -204,17 +211,9 @@ class BackupUploadViewModel: ObservableObject {
}

func toggleProcess(process: BackupProcess) {
hasError = false
self.process = process
// switch self.process {
// case .idle:
// <#code#>
// case .upload:
// <#code#>
// case .regist:
// <#code#>
// case .finish:
// <#code#>
// }
DispatchQueue.main.async {
self.hasError = false
self.process = process
}
}
}
6 changes: 3 additions & 3 deletions FRW/Modules/Wallet/MoveAsset/MoveTokenView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -168,15 +168,15 @@ extension MoveTokenView {
var body: some View {
VStack(spacing: 12) {
HStack {
TextField("", text: $viewModel.inputText)
TextField("", text: $viewModel.showBalance)
.keyboardType(.decimalPad)
.disableAutocorrection(true)
.modifier(PlaceholderStyle(showPlaceHolder: viewModel.inputText.isEmpty,
.modifier(PlaceholderStyle(showPlaceHolder: viewModel.showBalance.isEmpty,
placeholder: "0.00",
font: .inter(size: 30, weight: .w700),
color: Color.Theme.Text.black3))
.font(.inter(size: 30, weight: .w700))
.onChange(of: viewModel.inputText) { text in
.onChange(of: viewModel.showBalance) { text in
viewModel.inputTextDidChangeAction(text: text)
}
.focused($isAmountFocused)
Expand Down
109 changes: 93 additions & 16 deletions FRW/Modules/Wallet/MoveAsset/ViewModel/MoveTokenViewModel.swift
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,9 @@ import Flow
class MoveTokenViewModel: ObservableObject {
@Published var inputDollarNum: Double = 0

@Published var inputText: String = ""
@Published var showBalance: String = ""
var actualBalance: String = ""

@Published var inputTokenNum: Double = 0
@Published var amountBalance: Double = 0
@Published var coinRate: Double = 0
Expand All @@ -22,6 +24,8 @@ class MoveTokenViewModel: ObservableObject {
@Published var fromContact = Contact(address: "", avatar: "", contactName: "", contactType: nil, domain: nil, id: -1, username: nil)
@Published var toContact = Contact(address: "", avatar: "", contactName: "", contactType: nil, domain: nil, id: -1, username: nil)

private var minBalance: Double? = nil

var token: TokenModel
@Binding var isPresent: Bool

Expand All @@ -30,6 +34,9 @@ class MoveTokenViewModel: ObservableObject {
_isPresent = isPresent
loadUserInfo()
refreshTokenData()
Task {
await fetchMinFlowBalance()
}
}

private func loadUserInfo() {
Expand Down Expand Up @@ -57,12 +64,30 @@ class MoveTokenViewModel: ObservableObject {
}
}

private func fetchMinFlowBalance() async {
do {
self.minBalance = try await FlowNetwork.minFlowBalance()
log.debug("[Flow] min balance:\(self.minBalance ?? 0.001)")
} catch {
self.minBalance = 0.001
}
}

private func updateBalance(_ text: String) {
guard !text.isEmpty else {
showBalance = ""
actualBalance = ""
return
}

}

func changeTokenModelAction(token: TokenModel) {
if token.contractId == self.token.contractId {
return
}
self.token = token
inputText = ""
updateBalance("")
errorType = .none
refreshTokenData()
}
Expand All @@ -78,46 +103,89 @@ class MoveTokenViewModel: ObservableObject {
}

func refreshSummary() {
if inputText.isEmpty {
if showBalance.isEmpty {
inputTokenNum = 0.0
inputDollarNum = 0.0
errorType = .none
return
}

if !inputText.isNumber {
if !showBalance.isNumber {
inputTokenNum = 0.0
inputDollarNum = 0.0
errorType = .formatError
return
}
inputTokenNum = inputText.doubleValue

actualBalance = showBalance.doubleValue
.formatCurrencyString(digits: token.decimal)
inputTokenNum = actualBalance.doubleValue
inputDollarNum = inputTokenNum * coinRate * CurrencyCache.cache.currentCurrencyRate

if inputTokenNum > amountBalance {
errorType = .insufficientBalance
return
}

// if amountBalance - inputTokenNum < 0.001 {
// errorType = .belowMinimum
// return
// }
if !allowZero() {
errorType = .insufficientBalance
return
}
errorType = .none
}

func maxAction() {
let num = max(amountBalance, 0)
inputText = num.formatCurrencyString()
refreshSummary()
updateState()
Task {
let num = await updateAmountIfNeed(inputAmount: amountBalance)
DispatchQueue.main.async {
self.showBalance = num.formatCurrencyString()
self.actualBalance = num.formatCurrencyString(digits: self.token.decimal)
self.refreshSummary()
self.updateState()
}
}
}

private func isFromFlowToCoa() -> Bool {
return token.isFlowCoin && fromContact.walletType == .flow && toContact.walletType == .evm
}

private func allowZero() -> Bool {
guard isFromFlowToCoa() else {
return true
}
return false
}

private func updateAmountIfNeed(inputAmount: Double) async -> Double {
guard isFromFlowToCoa() else {
return max(inputAmount, 0)
}
if self.minBalance == nil {
HUD.loading()
await fetchMinFlowBalance()
HUD.dismissLoading()
}
// move fee
let num = max(
inputAmount - (
minBalance ?? WalletManager.minDefaultBlance
) - WalletManager.moveFee,
0
)
return num
}


private func updateState() {
buttonState = isReadyForSend ? .enabled : .disabled
DispatchQueue.main.async {
self.buttonState = self.isReadyForSend ? .enabled : .disabled
}

}

var isReadyForSend: Bool {
return errorType == .none && inputText.isNumber && !inputText.isEmpty
return errorType == .none && showBalance.isNumber && !showBalance.isEmpty
}

var currentBalance: String {
Expand Down Expand Up @@ -233,10 +301,19 @@ extension MoveTokenViewModel {
Task {
do {
log.info("[EVM] fund Coa balance")
let maxAmount = await updateAmountIfNeed(
inputAmount: amountBalance
)
guard maxAmount >= self.inputTokenNum else {
HUD.error(title: "Insufficient_balance::message".localized)
return
}
DispatchQueue.main.async {
self.buttonState = .loading
}
let amount = self.inputTokenNum.decimalValue
log.debug("[amount] move \(self.inputTokenNum)")
log.debug("[amount] move \(amount.description)")
let txid = try await FlowNetwork.fundCoa(amount: amount)
let holder = TransactionManager.TransactionHolder(id: txid, type: .transferCoin)
TransactionManager.shared.newTransaction(holder: holder)
Expand Down
56 changes: 31 additions & 25 deletions FRW/Modules/Wallet/Send/WalletSendAmountViewModel.swift
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ class WalletSendAmountViewModel: ObservableObject {
@Published var inputText: String = ""
@Published var inputTokenNum: Double = 0
@Published var inputDollarNum: Double = 0
var actualBalance: String = ""

@Published var exchangeType: WalletSendAmountView.ExchangeType = .token
@Published var errorType: WalletSendAmountView.ErrorType = .none
Expand Down Expand Up @@ -159,26 +160,30 @@ extension WalletSendAmountViewModel {
errorType = .formatError
return
}

actualBalance = inputText.doubleValue
.formatCurrencyString(digits: token.decimal)
if exchangeType == .token {
inputTokenNum = inputText.doubleValue
inputTokenNum = actualBalance.doubleValue
inputDollarNum = inputTokenNum * coinRate * CurrencyCache.cache.currentCurrencyRate
} else {
inputDollarNum = inputText.doubleValue
inputDollarNum = actualBalance.doubleValue
if coinRate == 0 {
inputTokenNum = 0
} else {
inputTokenNum = inputDollarNum / CurrencyCache.cache.currentCurrencyRate / coinRate
}
}

if inputTokenNum > amountBalance {
errorType = .insufficientBalance
return
}

if token.isFlowCoin, EVMAccountManager.shared.selectedAccount == nil {
if amountBalance - inputTokenNum < minBalance {
if token.isFlowCoin, WalletManager.shared.isCoa(targetContact.address) {
let validBalance = (
Decimal(amountBalance) - Decimal(minBalance)
).doubleValue
if validBalance < inputTokenNum {
errorType = .belowMinimum
return
}
Expand All @@ -205,51 +210,52 @@ extension WalletSendAmountViewModel {

extension WalletSendAmountViewModel {
func inputTextDidChangeAction(text _: String) {
// let filtered = text.filter {"0123456789.".contains($0)}
//
// if filtered.contains(".") {
// let splitted = filtered.split(separator: ".")
// if splitted.count >= 2 {
// let preDecimal = String(splitted[0])
// let afterDecimal = String(splitted[1])
// inputText = "\(preDecimal).\(afterDecimal)"
// } else {
// inputText = filtered
// }
// } else {
// inputText = filtered
// }

refreshInput()
}

func maxAction() {
exchangeType = .token
if token.isFlowCoin && EVMAccountManager.shared.selectedAccount == nil {
if token.isFlowCoin && WalletManager.shared
.isCoa(targetContact.address) && WalletManager.shared.isMain() {
Task {
do {
let topAmount = try await FlowNetwork.minFlowBalance()
let num = max(amountBalance - topAmount, 0)
inputText = num.formatCurrencyString()
let num = max(
amountBalance - topAmount - WalletManager.moveFee,
0
)
DispatchQueue.main.async {
self.inputText = num.formatCurrencyString()
}

actualBalance = num.formatCurrencyString(digits: token.decimal)
} catch {
let num = max(amountBalance - minBalance, 0)
inputText = num.formatCurrencyString()
DispatchQueue.main.async {
self.inputText = num.formatCurrencyString()
}
actualBalance = num.formatCurrencyString(digits: token.decimal)
log.error("[Flow] min flow balance error")
}
}
} else {
let num = max(amountBalance, 0)
inputText = num.formatCurrencyString()
actualBalance = num.formatCurrencyString(digits: token.decimal)
}
}

func toggleExchangeTypeAction() {
if exchangeType == .token, coinRate != 0 {
exchangeType = .dollar
inputText = inputDollarNum.formatCurrencyString()
actualBalance = inputDollarNum
.formatCurrencyString(digits: token.decimal)
} else {
exchangeType = .token
inputText = inputTokenNum.formatCurrencyString()
actualBalance = inputTokenNum
.formatCurrencyString(digits: token.decimal)
}
}

Expand Down
Loading

0 comments on commit 3c66017

Please sign in to comment.