Skip to content

feat: hooks first architecture#563

Merged
jonybur merged 34 commits into
mainfrom
feat/hooks-first-architecture
Nov 11, 2025
Merged

feat: hooks first architecture#563
jonybur merged 34 commits into
mainfrom
feat/hooks-first-architecture

Conversation

@jonybur
Copy link
Copy Markdown
Contributor

@jonybur jonybur commented Nov 3, 2025

Vault Architecture - Hooks-First Pattern

Core Principles

  1. Business Logic in Hooks - All business logic, orchestration, and state management lives in custom hooks
  2. Pure Service Functions - Services contain only pure functions for calculations and transformations
  3. Presentational Components - Components are purely presentational with no business logic
  4. Composable Patterns - Hooks can be composed to create complex behaviors from simple pieces

Architecture Layers

┌─────────────────────────────────────────────┐
│         Presentation Layer                   │
│  Components (Pure UI, no business logic)     │
└────────────────┬────────────────────────────┘
                 │
┌────────────────▼────────────────────────────┐
│         Business Logic Layer                 │
│  Hooks (Orchestration, State, Side Effects)  │
└────────────────┬────────────────────────────┘
                 │
┌────────────────▼────────────────────────────┐
│           Service Layer                      │
│  Pure Functions (Calculations, Validations)  │
└────────────────┬────────────────────────────┘
                 │
┌────────────────▼────────────────────────────┐
│             API Layer                        │
│  Data Fetching (React Query, API Clients)    │
└─────────────────────────────────────────────┘

Directory Structure

src/
├── components/           # Presentational components only
│   └── [feature]/       # Feature-specific components
│
├── hooks/               # Business logic hooks
│   ├── [feature]/      # Feature-specific hooks
│   │   ├── use[Feature]Flow.ts      # Main orchestration
│   │   ├── use[Feature]Form.ts      # Form logic
│   │   └── use[Feature]State.ts     # State management
│   └── shared/         # Shared hooks
│
├── services/           # Pure service functions
│   ├── [feature]/     # Feature-specific services
│   │   ├── calculations.ts
│   │   ├── validations.ts
│   │   └── transformers.ts
│   └── shared/        # Shared services
│
├── api/               # API layer
│   ├── queries/       # React Query queries
│   ├── mutations/     # React Query mutations
│   └── clients/       # Raw API clients
│
├── types/             # TypeScript definitions
├── utils/             # Utility functions
└── constants/         # Application constants

Benefits of This Architecture

  1. Clear Separation - Business logic is clearly separated from UI
  2. Testability - Each layer can be tested independently
  3. Reusability - Hooks and services can be reused across components
  4. Developer Experience - Familiar React patterns
  5. Progressive Migration - Can migrate feature by feature

Migrated to New Architecture

Deposit Flow (Partial)

  • DepositFormModal - Form entry and validation
  • DepositSignModal - Transaction signing and submission
  • DepositOverview - Deposit list and state management
  • Overview - Global deposit state coordination

Status: Core deposit entry and signing migrated, but review and success modals still use old architecture

Not Yet Migrated (Old Architecture)

Deposit Flow (Remaining)

  • DepositReviewModal - Transaction review before signing
  • DepositSuccessModal - Success confirmation
  • BroadcastSignModal - Bitcoin transaction broadcasting
  • BroadcastSuccessModal - Broadcast success confirmation
  • PayoutSignModal - Payout transaction signing

Redeem Flow (Complete)

  • RedeemFormModal - Redeem request form
  • RedeemReviewModal - Redeem transaction review
  • RedeemSignModal - Redeem transaction signing
  • RedeemSuccessModal - Redeem success confirmation

Position Management

  • All position-related components still use old architecture

Market Operations

  • All market-related components still use old architecture

Summary

Migrated: 4 components (deposit form, sign, overview, coordination)
Not Migrated: 16+ components (review modals, redeem flow, position, market)
Migration Progress: Approximately 20%

Jonathan Bursztyn added 8 commits November 1, 2025 20:47
- Add comprehensive architecture options documentation
- Compare Clean Layers, Feature Modules, and Hooks-First approaches
- Document decision framework and migration strategies
- Choose Hooks-First architecture for implementation
- Create calculations service for deposit fees and UTXO selection
- Add validation functions with consistent result format
- Implement data transformers for deposit operations
- Extract business logic from components into pure functions
- Add main deposit flow orchestration hook
- Create validation hook with UTXO and balance checks
- Implement transaction creation and submission hook
- Separate business logic from UI components using hooks pattern
- Provide step-by-step migration instructions
- Include code examples for common patterns
- Add testing strategy for each layer
- Document benefits and next steps for team adoption
- Fix undefined type check in useDepositFlow
- Remove unused imports and variables
- Correct LocalStorageStatus enum values in transformers
- Update PeginDisplayLabel types to match state machine
- Handle empty strings and edge cases properly
- Validate decimal point count (prevent multiple decimals)
- Handle strings with only decimals (e.g., '.5')
- Add regex validation for final satoshi string
- Return 0n for invalid inputs instead of throwing
- Use bigint arithmetic throughout instead of Number conversion
- Avoid precision loss for values >= 2^53
- Handle fractional part with string padding and trimming
- Maintain correct decimal place handling
- Analyze code merged from main against new architecture
- Verify all changes are compliant with hooks-first pattern
- Document positive patterns (error utilities, useBorrowUI)
- Identify areas for future migration
- Provide integration recommendations
Copilot AI review requested due to automatic review settings November 3, 2025 16:13
@jonybur jonybur changed the title Feat/hooks first architecture feat: hooks first architecture Nov 3, 2025
Copy link
Copy Markdown
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull Request Overview

This PR introduces a hooks-first architecture to improve code organization in the vault service. The refactoring separates business logic (in hooks) from pure utility functions (in services) and presentational code (in components), following a React-centric approach for better maintainability.

Key Changes:

  • Created a three-layer service architecture with calculations, validations, and transformers
  • Implemented deposit flow orchestration using custom React hooks
  • Added comprehensive architecture documentation with migration guides

Reviewed Changes

Copilot reviewed 14 out of 14 changed files in this pull request and generated 5 comments.

Show a summary per file
File Description
services/vault/src/services/deposit/validations.ts Pure validation functions for deposit amounts, balances, UTXOs, providers, and BTC addresses
services/vault/src/services/deposit/transformers.ts Data transformation functions for converting between formats and user-friendly displays
services/vault/src/services/deposit/calculations.ts Pure calculation functions for fees, UTXO selection, and transaction sizing
services/vault/src/services/deposit/index.ts Barrel export aggregating all deposit service functions
services/vault/src/hooks/deposit/useDepositValidation.ts Hook for deposit validation logic integrating service functions
services/vault/src/hooks/deposit/useDepositTransaction.ts Hook for transaction creation and submission
services/vault/src/hooks/deposit/useDepositFlow.ts Main orchestration hook managing the complete deposit flow
services/vault/src/hooks/deposit/index.ts Barrel export for deposit hooks and types
services/vault/MIGRATION_GUIDE.md Comprehensive guide for migrating features to the new architecture
services/vault/ARCHITECTURE_OPTION_3.md Detailed documentation of the hooks-first architecture pattern
services/vault/ARCHITECTURE_OPTION_2.md Alternative feature-based modular architecture documentation
services/vault/ARCHITECTURE_OPTION_1.md Alternative clean layered architecture documentation
services/vault/ARCHITECTURE_COMPARISON.md Comparison of architecture options with recommendations
services/vault/ARCHITECTURE.md Main architecture documentation for the chosen hooks-first pattern
Comments suppressed due to low confidence (1)

services/vault/MIGRATION_GUIDE.md:1

  • Contains an unusual memory reference marker [[memory:10537065]] that appears to be an artifact or debug reference. This should be removed from the documentation.
# Migration Guide - Hooks-First Architecture

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment thread services/vault/src/services/deposit/transformers.ts Outdated
Comment thread services/vault/src/services/deposit/transformers.ts Outdated
Comment thread services/vault/src/services/deposit/calculations.ts
Comment thread services/vault/src/hooks/deposit/useDepositTransaction.ts Outdated
Comment thread services/vault/src/hooks/deposit/useDepositValidation.ts Outdated
@jonybur
Copy link
Copy Markdown
Contributor Author

jonybur commented Nov 3, 2025

@copilot

Copy link
Copy Markdown
Contributor

Copilot AI commented Nov 3, 2025

@jonybur I've opened a new pull request, #564, to work on those changes. Once the pull request is ready, I'll request review from you.

Jonathan Bursztyn added 7 commits November 3, 2025 16:35
Comment thread services/vault/src/services/deposit/transformers.ts Outdated
Comment thread services/vault/src/services/deposit/transformers.ts Outdated
Comment thread services/vault/src/services/deposit/transformers.ts Outdated
Comment thread services/vault/src/services/deposit/transformers.ts Outdated
Comment thread services/vault/src/services/deposit/transformers.ts Outdated
Comment thread services/vault/src/services/deposit/transformers.ts Outdated
Comment thread services/vault/src/services/deposit/transformers.ts Outdated
Comment thread services/vault/src/services/deposit/transformers.ts Outdated
gbarkhatov
gbarkhatov previously approved these changes Nov 10, 2025
Copy link
Copy Markdown
Contributor

@gbarkhatov gbarkhatov left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@jonybur approving
My suggestion for future is that we split such issues into multiple sub issues
I would review 3-5 PRs instead of such a big one, step by step - with tests being a part of another PR for sure
Code wise looks good, moving into a proper direction. As long as functionality is there, I think we are okay to merge it

providers,
isLoadingProviders,
amountSats,
// estimatedFees, // TODO: Display estimated fees in UI
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do we have a ticket for that? Let's resolve once ticket is there, point to this line of code (or PR comment)

jrwbabylonlab
jrwbabylonlab previously approved these changes Nov 11, 2025
@jonybur jonybur merged commit f997a6e into main Nov 11, 2025
4 checks passed
@jonybur jonybur deleted the feat/hooks-first-architecture branch November 11, 2025 01:59
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.

6 participants