Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(wallet): Cancel & Speed Up Tx in Tx Status Screen #26947

Merged
merged 5 commits into from
Dec 16, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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,44 @@ 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 {
let followUpAction = await determineFollowUpAction()
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 +412,62 @@ 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
}

@MainActor private func determineFollowUpAction() async -> TransactionStatusStore.FollowUpAction {
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
// gasFee of this active tx should be bigger than the original one
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
&& activeTransaction.ethTxData.isEmpty
}), let parsedTx = await parseTransaction(txInfo) {
if let activeTxGasFee = BDouble(activeParsedTransaction.gasFee?.fee ?? "0"),
let originalTxGasFee = BDouble(parsedTx.gasFee?.fee ?? "0"),
activeTxGasFee > originalTxGasFee
{
return .cancel(originalParsedTx: parsedTx)
}
}
} else if activeTransaction.coin == .eth {
// loop through allTx to find if there is a tx that has the same chain id, coin type, nonce, from address,
// to address, data and value
// gasFee of this active tx should be bigger than the original one
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
&& $0.ethTxToAddress == activeTransaction.ethTxToAddress
&& $0.ethTxData == activeTransaction.ethTxData
&& $0.ethTxValue == activeTransaction.ethTxValue
}), let parsedTx = await parseTransaction(txInfo) {
if let activeTxGasFee = BDouble(activeParsedTransaction.gasFee?.fee ?? "0"),
let originalTxGasFee = BDouble(parsedTx.gasFee?.fee ?? "0"),
activeTxGasFee > originalTxGasFee
{
return .speedUp(originalParsedTx: parsedTx)
}
}
}
return .none
}

private func clearTrasactionInfoBeforeUpdate() {
// clear fields that could have dynamic async changes
fiat = ""
Expand Down Expand Up @@ -913,16 +999,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 +1139,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 @@ -11,27 +11,40 @@ import Preferences
import Strings

public class TransactionStatusStore: ObservableObject, WalletObserverStore {
@Published var activeTxStatus: BraveWallet.TransactionStatus {
didSet {
originalTxStatus = activeTxStatus
}
}
@Published var activeTxStatus: BraveWallet.TransactionStatus
@Published var txProviderError: TransactionProviderError?
@Published var isOriginalTxConfirmed: Bool = false

enum FollowUpAction: Equatable {
case cancel(originalParsedTx: ParsedTransaction)
case speedUp(originalParsedTx: ParsedTransaction)
case none
}

private(set) var followUpAction: FollowUpAction

private let keyringService: BraveWalletKeyringService
private let rpcService: BraveWalletJsonRpcService
private let txService: BraveWalletTxService
private var txServiceObserver: TxServiceObserver?

private var originalTxParsed: ParsedTransaction
private var originalTxStatus: BraveWallet.TransactionStatus

var isObserving: Bool {
txServiceObserver != nil
}

var activeParsedTx: ParsedTransaction {
originalTxParsed
var activeParsedTx: ParsedTransaction

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

var isSpeedUpAvailable: Bool {
return activeParsedTx.transaction.coin == .eth
}

init(
Expand All @@ -40,15 +53,16 @@ public class TransactionStatusStore: ObservableObject, WalletObserverStore {
txProviderError: TransactionProviderError?,
keyringService: BraveWalletKeyringService,
rpcService: BraveWalletJsonRpcService,
txService: BraveWalletTxService
txService: BraveWalletTxService,
followUpAction: FollowUpAction
) {
self.activeTxStatus = activeTxStatus
self.originalTxStatus = activeTxStatus
self.originalTxParsed = activeTxParsed
self.activeParsedTx = activeTxParsed
self.txProviderError = txProviderError
self.keyringService = keyringService
self.rpcService = rpcService
self.txService = txService
self.followUpAction = followUpAction

self.setupObservers()
}
Expand All @@ -62,7 +76,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 @@ -71,6 +85,22 @@ public class TransactionStatusStore: ObservableObject, WalletObserverStore {
guard let self else { return }
if self.activeParsedTx.transaction.id == txInfo.id {
self.activeTxStatus = txInfo.txStatus
} else {
if case .cancel(let originalParsedTx) = followUpAction,
originalParsedTx.transaction.id == txInfo.id,
txInfo.txStatus == .confirmed
{
// cancel tx is submitted
// but the original tx is confirmed
isOriginalTxConfirmed = true
} else if case .speedUp(let originalParsedTx) = followUpAction,
originalParsedTx.transaction.id == txInfo.id,
txInfo.txStatus == .confirmed
{
// speed up tx is submitted
// but the original tx is confirmed
isOriginalTxConfirmed = true
}
}
}
)
Expand All @@ -88,4 +118,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()
},
onFollowUpTxCreated: { 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
Loading