-
Notifications
You must be signed in to change notification settings - Fork 63
Expand file tree
/
Copy pathSendTxConfirmViewModel.swift
More file actions
305 lines (278 loc) · 12.8 KB
/
Copy pathSendTxConfirmViewModel.swift
File metadata and controls
305 lines (278 loc) · 12.8 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
import Foundation
import core
import gdk
import greenaddress
import UIKit
import BreezSDK
import LiquidWalletKit
enum VerifyAddressState {
case noneed
case unverified
case verified
}
class SendTxConfirmViewModel {
var transaction: gdk.Transaction?
var subaccount: WalletItem?
var wm: WalletManager? { WalletManager.current }
var mainAccount: Account? { AccountsRepository.shared.current }
var denominationType: DenominationType
var isFiat = false
var isJade: Bool { mainAccount?.isJade ?? false }
var session: SessionManager? {
guard let subaccount = subaccount else { return nil }
if isJade && BleHwManager.shared.walletManager != nil {
if BleHwManager.shared.isConnected() {
return BleHwManager.shared.walletManager?.getSession(for: subaccount)
}
}
return WalletManager.current?.getSession(for: subaccount)
}
var sendTransaction: SendTransactionSuccess?
var error: Error?
var txType: TxType
var unsignedPsbt: String?
var signedPsbt: String?
var bcurUnsignedPsbt: BcurEncodedData?
var importSignedPsbt = false
var isWithdraw: Bool { withdrawData != nil }
var withdrawData: LnUrlWithdrawRequestData?
var hasWithdrawNote: Bool { withdrawNote != nil && withdrawNote != "" }
var withdrawNote: String? {
guard let withdrawData = withdrawData else { return nil }
return withdrawData.defaultDescription
}
var withdrawAmount: UInt64 = 0
var txAddresses: [gdk.Address]? {
transaction?.addressees.compactMap { Address(address: $0.address, subtype: $0.subtype, userPath: $0.userPath, isGreedy: $0.isGreedy) }
}
var pay: PreparePayResponse?
internal init(transaction: gdk.Transaction?, subaccount: WalletItem?, denominationType: DenominationType, isFiat: Bool, txType: TxType, unsignedPsbt: String?, signedPsbt: String?) {
self.transaction = transaction
self.subaccount = subaccount
self.denominationType = denominationType
self.isFiat = isFiat
self.txType = txType
self.unsignedPsbt = unsignedPsbt
self.signedPsbt = signedPsbt
self.importSignedPsbt = signedPsbt != nil
self.verifyAddressState = (txType == .redepositExpiredUtxos && (AccountsRepository.shared.current?.isHW ?? false) && !(subaccount?.session?.networkType.liquid ?? false)) ? .unverified : .noneed
}
var isLightning: Bool { subaccount?.networkType == .lightning }
var isConsolitating: Bool { txType == .redepositExpiredUtxos }
var hasHW: Bool { mainAccount?.isHW ?? false }
var addressee: Addressee? { transaction?.addressees.first }
var address: String? { addressee?.address }
var assetId: String { addressee?.assetId ?? subaccount?.gdkNetwork.getFeeAsset() ?? "btc" }
var sendAll: Bool { addressee?.isGreedy ?? false}
var satoshi: Int64? { addressee?.satoshi }
var asset: AssetInfo? { wm?.info(for: assetId) }
var isLiquid: Bool { transaction?.subaccount?.gdkNetwork.liquid ?? false }
var assetImage: UIImage? {
if multiAddressees {
return wm?.image(for: transaction?.feeAsset ?? "btc")
}
if isLightning {
return UIImage(named: "ic_lightning_btc")
}
return wm?.image(for: assetId)
}
var note: String? {
get { isWithdraw ? withdrawNote : transaction?.memo }
set { transaction?.memo = newValue }
}
var amount: Balance? { Balance.fromSatoshi( isWithdraw ? withdrawAmount : satoshi ?? 0, assetId: assetId) }
var fee: Balance? { Balance.fromSatoshi(transaction?.fee ?? 0, assetId: transaction?.feeAsset ?? "btc") }
var total: Balance? {
let feeAsset = session?.gdkNetwork.getFeeAsset()
var amount = satoshi ?? 0
if feeAsset == assetId {
amount += Int64(transaction?.fee ?? 0)
}
return Balance.fromSatoshi(amount, assetId: assetId)
}
var amountDenomText: String? { amount?.toText(denominationType) }
var amountFiatText: String? { amount?.toFiatText() }
var feeDenomText: String? { fee?.toText(denominationType) }
var feeFiatText: String? { fee?.toFiatText() }
var totalDenomText: String? { total?.toText(denominationType) }
var totalFiatText: String? { total?.toFiatText() }
var amountText: String? { isFiat ? amountFiatText : amountDenomText }
var subamountText: String? { isFiat ? amountDenomText : amountFiatText}
var feeText: String? { isFiat ? feeFiatText : feeDenomText }
var totalText: String? { isFiat ? totalFiatText : totalDenomText }
var conversionText: String? { isFiat ? totalDenomText : totalFiatText }
var addressTitle: String { isLightning ? "id_recipient".localized : isConsolitating ? "id_your_redeposit_address".localized : "id_address".localized }
var amountTitle: String { isWithdraw ? "id_amount_to_receive".localized : isConsolitating ? "id_redepositing".localized : "id_recipient_receives".localized }
var recipientReceivesHidden: Bool { isConsolitating }
var verifyAddressState: VerifyAddressState
var multiAddressees: Bool {
if txType != .redepositExpiredUtxos {
return false
}
return (transaction?.addressees.count ?? 0) > 1 ? true : false
}
func getAssetIcons() -> [UIImage] {
transaction?.addressees.compactMap { $0.assetId }.compactMap { self.wm?.image(for: $0) } ?? []
}
func enableExportPsbt() -> Bool {
wm?.isWatchonly ?? false && session?.networkType.singlesig ?? false && txType != .sweep && !importSignedPsbt
}
func needConnectHw() -> Bool {
mainAccount?.isHW ?? false
}
func needExportPsbt() -> Bool {
wm?.isWatchonly ?? false && session?.networkType.singlesig ?? false && txType != .sweep && signedPsbt == nil
}
private func sendTx() async throws -> SendTransactionSuccess {
guard let session = session,
var tx = transaction else {
throw TransactionError.invalid(localizedDescription: "Invalid transaction")
}
if let error = tx.error {
throw TransactionError.invalid(localizedDescription: error)
}
if isLiquid {
tx = try await session.blindTransaction(tx: tx)
}
tx = try await session.signTransaction(tx: tx)
if let error = tx.error {
throw TransactionError.invalid(localizedDescription: error)
}
self.transaction = tx
if tx.isSweep {
return try await session.broadcastTransaction(BroadcastTransactionParams(transaction: tx.transaction))
} else {
return try await session.sendTransaction(tx: tx)
}
}
func exportPsbt() async throws {
guard let session = session,
var tx = transaction else {
throw TransactionError.invalid(localizedDescription: "Invalid transaction")
}
if isLiquid {
tx = try await session.blindTransaction(tx: tx)
}
unsignedPsbt = try await session.getPsbt(tx: tx)
let params = BcurEncodeParams(urType: "crypto-psbt", data: unsignedPsbt)
guard let res = try await session.bcurEncode(params: params) else {
throw TransactionError.invalid(localizedDescription: "Invalid bcur")
}
bcurUnsignedPsbt = res
}
func sendPsbt() async throws -> SendTransactionSuccess {
guard let session = session else {
throw TransactionError.invalid(localizedDescription: "id_invalid_session".localized)
}
guard let psbt = signedPsbt else {
throw TransactionError.invalid(localizedDescription: "id_invalid_psbt".localized)
}
return try await session.broadcastTransaction(BroadcastTransactionParams(psbt: psbt, memo: transaction?.memo, simulateOnly: false))
}
func signPsbt() async throws {
guard let session = session else {
throw TransactionError.invalid(localizedDescription: "Invalid session")
}
guard let psbt = unsignedPsbt else {
throw TransactionError.invalid(localizedDescription: "Invalid psbt")
}
let utxos = try await session.getUtxos(GetUnspentOutputsParams(subaccount: subaccount?.pointer ?? 0, numConfs: 0))
let res = try await session.signPsbt(params: SignPsbtParams(psbt: psbt, utxos: utxos.unspentOutputs))
self.signedPsbt = res.psbt
}
func send() async throws -> SendTransactionSuccess {
AnalyticsManager.shared.startSendTransaction()
AnalyticsManager.shared.startFailedTransaction()
let withMemo = !(transaction?.memo?.isEmpty ?? true)
let transSgmt = AnalyticsManager.TransactionSegmentation(
transactionType: transaction?.txType ?? .transaction,
addressInputType: .paste,
sendAll: sendAll)
do {
if signedPsbt != nil {
sendTransaction = try await sendPsbt()
} else if unsignedPsbt != nil {
try await signPsbt()
sendTransaction = try await sendPsbt()
} else {
sendTransaction = try await sendTx()
}
AnalyticsManager.shared.endSendTransaction(
account: AccountsRepository.shared.current,
walletItem: subaccount,
transactionSgmt: transSgmt,
withMemo: withMemo)
if sendAll { AnalyticsManager.shared.emptiedAccount = subaccount }
return sendTransaction!
} catch {
AnalyticsManager.shared.failedTransaction(
account: AccountsRepository.shared.current,
walletItem: subaccount,
transactionSgmt: transSgmt,
withMemo: withMemo,
prettyError: error.description() ?? "",
nodeId: wm?.lightningSession?.nodeState?.id
)
self.error = error
throw error
}
}
func sendHWConfirmViewModel() -> SendHWConfirmViewModel {
SendHWConfirmViewModel(
isLedger: wm?.isLedger ?? false,
tx: transaction!,
denomination: denominationType,
subaccount: self.subaccount,
isMultiAddressees: self.multiAddressees)
}
func tempSendHWConfirmViewModel() -> SendHWConfirmViewModel {
SendHWConfirmViewModel(
isLedger: wm?.isLedger ?? false,
tx: transaction!,
denomination: denominationType,
subaccount: self.subaccount)
}
func urlForTx() -> URL? {
return URL(string: (subaccount?.gdkNetwork.txExplorerUrl ?? "") + (sendTransaction?.txHash ?? ""))
}
func urlForTxUnblinded() -> URL? {
return URL(string: (subaccount?.gdkNetwork.txExplorerUrl ?? "") + (sendTransaction?.txHash ?? "") + (transaction?.blindingUrlString(address: address) ?? ""))
}
func withdrawLnurl(desc: String) async throws -> LnUrlWithdrawSuccessData? {
guard let withdrawData = withdrawData else {
throw TransactionError.failure(localizedDescription: "id_data_not_available".localized, paymentHash: "")
}
let res = try wm?.lightningSession?.lightBridge?.withdrawLnurl(requestData: withdrawData, amount: withdrawAmount, description: desc)
switch res {
case .errorStatus(let data):
throw TransactionError.failure(localizedDescription: data.reason.localized, paymentHash: "")
case .timeout(let data):
throw TransactionError.failure(localizedDescription: "id_timeout".localized, paymentHash: "")
case .ok(let data):
return data
case .none:
throw TransactionError.failure(localizedDescription: "id_data_not_available".localized, paymentHash: "")
}
}
func validateHW(_ address: gdk.Address) async throws -> Bool {
guard let subaccount = subaccount else {
throw GaError.GenericError("id_invalid_subaccount".localized)
}
return try await BleHwManager.shared.validateAddress(account: subaccount, address: address)
}
func sendVerifyOnDeviceViewModel(_ address: gdk.Address) -> HWDialogVerifyOnDeviceViewModel? {
guard let address = address.address else { return nil }
let account = AccountsRepository.shared.current
return HWDialogVerifyOnDeviceViewModel(isLedger: account?.isLedger ?? false,
address: address,
isRedeposit: true,
isDismissible: false)
}
func showSignTransactionViaQR() -> Bool {
wm?.isWatchonly ?? false && [.bitcoinSS, .testnetSS, .liquidSS, .testnetLiquidSS]
.contains(session?.networkType) && txType != .sweep && !importSignedPsbt
}
func showSignTransaction() -> Bool {
txType == .sweep || !(wm?.isWatchonly ?? false) || (mainAccount?.isHW ?? false) || importSignedPsbt
}
}