Skip to content

Commit

Permalink
add cancellation function in transaction status screen when transacti…
Browse files Browse the repository at this point in the history
…on is submitted but not yet confirmed.
  • Loading branch information
nuo-xu committed Dec 9, 2024
1 parent 195b7d5 commit e8e6b7c
Show file tree
Hide file tree
Showing 6 changed files with 463 additions and 167 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -76,8 +76,10 @@ public class TransactionConfirmationStore: ObservableObject, WalletObserverStore
isTxSubmitting = false
}
if activeTxStatus == .submitted || activeTxStatus == .signed || activeTxStatus == .error {
closeTxStatusStore()
activeTxStatusStore = openActiveTxStatusStore()
Task { @MainActor in
closeTxStatusStore()
activeTxStatusStore = await openActiveTxStatusStore()
}
}
}
}
Expand Down Expand Up @@ -185,8 +187,6 @@ public class TransactionConfirmationStore: ObservableObject, WalletObserverStore
private var txServiceObserver: TxServiceObserver?
private var walletServiceObserver: WalletServiceObserver?

private var cancelTxMap: [BraveWallet.TransactionInfo: [BraveWallet.TransactionInfo]] = [:]

var isObserving: Bool {
txServiceObserver != nil && walletServiceObserver != nil
}
Expand Down Expand Up @@ -365,14 +365,59 @@ public class TransactionConfirmationStore: ObservableObject, WalletObserverStore
}
}

func openActiveTxStatusStore() -> TransactionStatusStore {
@MainActor func parseTransaction(
_ txInfo: BraveWallet.TransactionInfo
) async -> ParsedTransaction? {
let allAccountsForCoin = await keyringService.allAccounts().accounts.filter {
$0.coin == txInfo.coin
}
guard let network = allNetworks.first(where: { $0.chainId == txInfo.chainId })
else { return nil }

let allTokens =
await blockchainRegistry.allTokens(chainId: network.chainId, coin: txInfo.coin) + tokenInfoCache
let userAssets = await assetManager.getAllUserAssetsInNetworkAssets(
networks: [network],
includingUserDeleted: true
).flatMap { $0.tokens }

return txInfo.parsedTransaction(
allNetworks: allNetworks,
accountInfos: allAccountsForCoin,
userAssets: userAssets,
allTokens: allTokens,
assetRatios: assetRatios,
nftMetadata: [:],
currencyFormatter: currencyFormatter
)
}

@MainActor func openActiveTxStatusStore() async -> TransactionStatusStore {
var followUpAction = TransactionStatusStore.FollowUpAction.none
if case .ethSend(let detail) = activeParsedTransaction.details,
let fromValue = BDouble(detail.fromAmount),
fromValue == 0, activeTransaction.ethTxData.isEmpty
{
// loop through allTx to find if there is a tx that has the same chain id, coin type, nonce and from address
// maxFeePerGas/gasPrice is smaller than this active tx
if let txInfo = allTxs.first(where: {
$0.id != activeTransaction.id &&
$0.coin == activeTransaction.coin &&
$0.chainId == activeTransaction.chainId &&
$0.ethTxNonce == activeTransaction.ethTxNonce &&
$0.fromAddress == activeTransaction.fromAddress
}), let parsedTx = await parseTransaction(txInfo) {
followUpAction = .cancel(toCancelParsedTx: parsedTx)
}
}
let txStatusStore = TransactionStatusStore(
activeTxStatus: activeTxStatus,
activeTxParsed: activeParsedTransaction,
txProviderError: transactionProviderErrorRegistry[activeTransactionId],
keyringService: keyringService,
rpcService: rpcService,
txService: txService
txService: txService,
followUpAction: followUpAction
)
return txStatusStore
}
Expand All @@ -382,6 +427,15 @@ public class TransactionConfirmationStore: ObservableObject, WalletObserverStore
self.activeTxStatusStore = nil
}

func updateAllTx(with txId: String) async -> Bool {
// cancel or speed up only supported for .eth
guard let txInfo = await txService.transactionInfo(coinType: .eth, txMetaId: txId),
txInfo.txStatus == .unapproved
else { return false }
onUnapprovedTxAdded(txInfo)
return true
}

private func clearTrasactionInfoBeforeUpdate() {
// clear fields that could have dynamic async changes
fiat = ""
Expand Down Expand Up @@ -913,16 +967,6 @@ public class TransactionConfirmationStore: ObservableObject, WalletObserverStore
)
}

@MainActor func cancelActiveTx() async -> Bool {
let (success, metaId, errMsg) = await txService.speedupOrCancelTransaction(
coinType: activeParsedTransaction.transaction.coin,
chainId: activeParsedTransaction.transaction.chainId,
txMetaId: activeParsedTransaction.transaction.id,
cancel: true
)
return success
}

func updateGasFeeAndLimits(
for transaction: BraveWallet.TransactionInfo,
maxPriorityFeePerGas: String,
Expand Down Expand Up @@ -1063,26 +1107,12 @@ public class TransactionConfirmationStore: ObservableObject, WalletObserverStore

func onUnapprovedTxAdded(_ txInfo: BraveWallet.TransactionInfo) {
Task { @MainActor in
guard !allTxs.contains(where: { $0.id == txInfo.id }) else { return }
allTxs.insert(txInfo, at: 0)
activeTransactionId = txInfo.id
await prepare()
}
}

func isActiveTxCancelling() -> BraveWallet.TransactionInfo? {
if cancelTxMap.keys.contains(where: { $0.id == activeTransactionId }) {
return nil
}
var toCancelTx: BraveWallet.TransactionInfo?
for (key, value) in cancelTxMap {
if value.contains(where: { tx in
tx.id == activeTransactionId
}) {
toCancelTx = key
break
}
}
return toCancelTx
}
}

struct TransactionProviderError {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,20 @@ import Strings
public class TransactionStatusStore: ObservableObject, WalletObserverStore {
@Published var activeTxStatus: BraveWallet.TransactionStatus {
didSet {
print("Debug - tx status changed to \(activeTxStatus)")
originalTxStatus = activeTxStatus
}
}
@Published var txProviderError: TransactionProviderError?

enum FollowUpAction: Equatable {
case cancel(toCancelParsedTx: ParsedTransaction)
case speedup
case none
}

private(set) var followUpAction: FollowUpAction

private let keyringService: BraveWalletKeyringService
private let rpcService: BraveWalletJsonRpcService
private let txService: BraveWalletTxService
Expand All @@ -34,13 +43,23 @@ public class TransactionStatusStore: ObservableObject, WalletObserverStore {
originalTxParsed
}

var isCancelAvailable: Bool {
guard activeParsedTx.transaction.coin == .eth else { return false }
if case .cancel(_) = followUpAction {
return false
} else {
return true
}
}

init(
activeTxStatus: BraveWallet.TransactionStatus,
activeTxParsed: ParsedTransaction,
txProviderError: TransactionProviderError?,
keyringService: BraveWalletKeyringService,
rpcService: BraveWalletJsonRpcService,
txService: BraveWalletTxService
txService: BraveWalletTxService,
followUpAction: FollowUpAction
) {
self.activeTxStatus = activeTxStatus
self.originalTxStatus = activeTxStatus
Expand All @@ -49,6 +68,7 @@ public class TransactionStatusStore: ObservableObject, WalletObserverStore {
self.keyringService = keyringService
self.rpcService = rpcService
self.txService = txService
self.followUpAction = followUpAction

self.setupObservers()
}
Expand All @@ -62,7 +82,7 @@ public class TransactionStatusStore: ObservableObject, WalletObserverStore {
self.txServiceObserver = TxServiceObserver(
txService: txService,
_onNewUnapprovedTx: { _ in
// should only handle tx speed up and tx cancellation
// tx speed up and cancellation will be handled inside `TxConfirmationStore`
},
_onUnapprovedTxUpdated: { _ in
// should only handle tx speed up and tx cancellation
Expand All @@ -88,4 +108,19 @@ public class TransactionStatusStore: ObservableObject, WalletObserverStore {
for: txNetwork.coin
)
}

@MainActor func handleTransactionFollowUpAction(
_ action: TransactionFollowUpAction
) async -> (String?, String?) {
let (success, txId, error) = await txService.speedupOrCancelTransaction(
coinType: activeParsedTx.transaction.coin,
chainId: activeParsedTx.transaction.chainId,
txMetaId: activeParsedTx.transaction.id,
cancel: action == .cancel
)
if success {
return (txId, nil)
}
return (nil, error)
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -152,6 +152,20 @@ struct TransactionConfirmationView: View {
onViewInActivity: {
onDismiss()
onViewInActivity()
},
onCancelCreated: { txId in
Task { @MainActor in
// fetch and update `confirmationStore.unapprovedTxs` with this new tx with `txId`
if await confirmationStore.updateAllTx(with: txId) == false {
if confirmationStore.unapprovedTxs.count == 0 {
onDismiss()
}
}
// update activeTransactionId
confirmationStore.updateActiveTxIdAfterSignedClosed()
// close tx status store
confirmationStore.closeTxStatusStore()
}
}
)
}
Expand Down
Loading

0 comments on commit e8e6b7c

Please sign in to comment.