Skip to content

Fix pending recovery and liquidation request handling - #14

Merged
zk-bits merged 1 commit into
mainfrom
codex/wip-recovery-liquidation-fixes
Jun 2, 2026
Merged

Fix pending recovery and liquidation request handling#14
zk-bits merged 1 commit into
mainfrom
codex/wip-recovery-liquidation-fixes

Conversation

@zk-bits

@zk-bits zk-bits commented Jun 2, 2026

Copy link
Copy Markdown
Contributor

Summary

  • clear pending vault and send state when chain/explorer confirms the transaction
  • add an escape path from vault error screens so users are not trapped behind a failing Continue button
  • harden liquidation execution against stale vault history and repo Tx1ID mismatches by resolving the latest unspent vault prevout and normalizing request txids from signed PSBTs

Validation

  • Full Jest suite passed: 263 suites / 5120 tests
  • Typecheck passed
  • Focused liquidation and recovery tests passed
  • git diff --cached --check passed

Summary by CodeRabbit

Bug Fixes

  • Improved pending transaction tracking and reconciliation to reliably detect blockchain confirmations
  • Enhanced vault liquidation validation to better identify stale opportunities and prevent processing errors

New Features

  • Added Cancel button to vault input screen for improved workflow control

@coderabbitai

coderabbitai Bot commented Jun 2, 2026

Copy link
Copy Markdown

Review Change Stack

Caution

Review failed

The pull request is closed.

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Free

Run ID: 9e989165-8737-4c2c-85e6-706f7c83a819

📥 Commits

Reviewing files that changed from the base of the PR and between 34d7c1b and 10255cb.

📒 Files selected for processing (13)
  • contexts/VaultContext.tsx
  • contexts/__tests__/VaultContext.test.tsx
  • hooks/liquidation/__tests__/useLiquidationExecution.test.ts
  • hooks/liquidation/useLiquidationExecution.ts
  • jest.setup.js
  • screens/vault/VaultInputScreen.tsx
  • screens/vault/__tests__/VaultInputScreen.test.tsx
  • services/__tests__/reconciliationWorker.test.ts
  • services/liquidation/__tests__/execution.test.ts
  • services/liquidation/execution.ts
  • services/reconciliationWorker.ts
  • utils/__tests__/liquidationErrors.test.ts
  • utils/liquidationErrors.ts

📝 Walkthrough

Walkthrough

This PR enhances vault transaction handling by improving confirmation flow with chain fallback guards, refactoring liquidation execution to support vault history selection and transaction ID normalization, integrating pending transaction reconciliation into the main cycle, and adding UI improvements to the vault input screen. The changes span contexts, services, hooks, and utilities with supporting test coverage and error pattern expansion.

Changes

Vault Operations & Transaction Handling

Layer / File(s) Summary
Vault Transaction Confirmation Flow Enhancement
contexts/VaultContext.tsx, contexts/__tests__/VaultContext.test.tsx
Vault provider's confirmation effect now destructures vault data explicitly, guards on-chain checks with a ref-backed pending-key cache, and triggers async refresh of both vault state and transaction history when chain-confirmed. Pending transaction clearance is immediate in-store; confirmation logic computes deterministic keys and checks against fetched history before invoking fallback chain checks with proper cleanup sequencing. Tests validate the chain-confirmation-before-history-update scenario.
Liquidation Execution with Vault History & Prevout Refinement
services/liquidation/execution.ts, services/liquidation/__tests__/execution.test.ts
Execution flow now accepts optional vault_id, selects the latest usable vault history transaction (instead of first), computes prevout from that selection, and resolves the latest unspent on-chain prevout. A new normalization layer derives liquid_txhex/liquid_txid and vault_txhex/vault_txid from provided PSBTs or hex, with expanded consistency assertions validating PSBT-hex-txid relationships. Repo request passes through normalization before Guardian submission. Tests mock history selection, prevout resolution, and normalization with comprehensive assertions for happy and failure paths.
Liquidation Hook Integration with Vault ID
hooks/liquidation/useLiquidationExecution.ts, hooks/liquidation/__tests__/useLiquidationExecution.test.ts
Hook parameter type updated to accept optional vaultId in vaultData; execution call now includes vault_id derived from that parameter alongside existing credential fields. Test fixtures and call expectations updated to match new shape.
Reconciliation Worker Pending Transaction Tracking
services/reconciliationWorker.ts, services/__tests__/reconciliationWorker.test.ts
Reconciliation cycle gains pending-transaction reconciliation step with isolated error handling. New reconcileConfirmedPendingTransactions() queries pending txids via API, confirms when explorer indicates completion, and returns checked/confirmed/pending/error counts. Cycle result gains pendingTransactions field; conditional branching queues only transaction-history refresh when pending changes detected. Tests validate confirmation and non-confirmation paths with explicit API call and store interaction assertions.
Vault Input Screen UI with Cancel Button
screens/vault/VaultInputScreen.tsx, screens/vault/__tests__/VaultInputScreen.test.tsx
Footer action buttons now grouped in footerActions container with new disabled-aware "Cancel" button alongside "Continue". Cancel button respects press-lock pattern and disables during loading. Stylesheet extended with footer layout and cancel-button styling. Test suite validates error rendering and cancel/continue button press handling.
Error Pattern Detection & Jest Mocking Updates
utils/liquidationErrors.ts, utils/__tests__/liquidationErrors.test.ts, jest.setup.js
Stale liquidation opportunity detection expanded with two new patterns for "repo vault tx1id" mismatches. Jest React Native mock extended with Pressable and KeyboardAvoidingView component exports. Tests verify updated error pattern matching.

Sequence Diagram(s)

sequenceDiagram
  participant VaultProvider
  participant useVaultDataFetch
  participant PendingTxStore
  participant ChainConfirmation
  
  VaultProvider->>useVaultDataFetch: Destructure vault data, transactions, fetch functions
  VaultProvider->>PendingTxStore: Check pending vault transaction
  VaultProvider->>VaultProvider: Compute pending tx confirmation key
  VaultProvider->>VaultProvider: Derive isInHistory, isApplied from vault data
  alt Transaction Applied or In History
    VaultProvider->>PendingTxStore: Clear pending transaction immediately
    alt Confirmation source is 'chain'
      VaultProvider->>useVaultDataFetch: Async refresh vault state
      VaultProvider->>useVaultDataFetch: Async refresh vault transactions
    end
  else No Confirmation Yet
    VaultProvider->>ChainConfirmation: Guard check (key differs from ref)
    ChainConfirmation->>ChainConfirmation: Query on-chain confirmation
    ChainConfirmation->>PendingTxStore: Clear on confirmation
  end
Loading
flowchart
  FetchHistory["Fetch Vault History with vaultId"]
  SelectLatest["selectLatestUsableVaultHistoryTransaction"]
  ComputePrevout["Compute prevout from selected tx"]
  ResolveUnspent["resolveLatestUnspentVaultPrevout"]
  BuildProfile["buildVaultProfile with resolved prevout"]
  NormalizeRepoRequest["normalizeRepoRequestTxids<br/>(derive liquid_*/vault_* fields)"]
  AssertConsistent["assertRepoRequestTxidsConsistent<br/>(validate PSBT-hex-txid)"]
  SubmitGuardian["Submit to Guardian"]
  
  FetchHistory --> SelectLatest
  SelectLatest --> ComputePrevout
  ComputePrevout --> ResolveUnspent
  ResolveUnspent --> BuildProfile
  BuildProfile --> NormalizeRepoRequest
  NormalizeRepoRequest --> AssertConsistent
  AssertConsistent --> SubmitGuardian
Loading
sequenceDiagram
  participant runCycle
  participant PendingTxStore
  participant ExplorerAPI
  participant ConfirmTx
  
  runCycle->>PendingTxStore: Get pending transaction ids
  runCycle->>ExplorerAPI: reconcileConfirmedPendingTransactions
  loop For each pending txid
    ExplorerAPI->>ExplorerAPI: getWithRetry(getTxApiUrl(txid))
    alt Explorer confirms: confirmed=true
      ExplorerAPI->>ConfirmTx: confirmTransaction(txid)
      ExplorerAPI->>ExplorerAPI: Count confirmed++
    else Explorer not confirmed or error
      ExplorerAPI->>ExplorerAPI: Count pending++ or errors++
    end
  end
  ExplorerAPI-->>runCycle: PendingTransactionReconciliationResult
  runCycle->>runCycle: Compute pendingTransactionsChanged
  alt pendingTransactionsChanged
    runCycle->>runCycle: Queue transaction-history refresh only
  end
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~50 minutes

Poem

A vault once trembled with pending txids untamed,
But now with refguards and history proclaimed—
Prevouts resolve, liquidations align,
And reconciliation threads through each line.
~rabbit 🐰✨


Note

🎁 Summarized by CodeRabbit Free

Your organization is on the Free plan. CodeRabbit will generate a high-level summary and a walkthrough for each pull request. For a comprehensive line-by-line review, please upgrade your subscription to CodeRabbit Pro by visiting https://app.coderabbit.ai/login.

Comment @coderabbitai help to get the list of available commands and usage tips.

@zk-bits
zk-bits merged commit 9b1e6dc into main Jun 2, 2026
1 of 2 checks passed
@zk-bits
zk-bits deleted the codex/wip-recovery-liquidation-fixes branch June 2, 2026 17:07
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant