Rust Core Internals (hesabyar-core)
Relevant source files
The following files were used as context for generating this wiki page:
- rust/hesabyar-core/README.md
- rust/hesabyar-core/src/analytics.rs
- rust/hesabyar-core/src/dashboard.rs
- rust/hesabyar-core/src/ai_validation.rs
- rust/hesabyar-core/src/excel.rs
- rust/uniffi/hesabyar_core/uniffi/hesabyar_core/hesabyar_core.kt
- app/src/main/java/io/github/mojri/hesabyar/rust/RustBridge.kt
- README.md
The hesabyar-core module serves as the shared native engine for the Hesabyar application. Extracted from the original Kotlin codebase to improve performance and maintainability, it encapsulates critical business logic including Persian Natural Language Processing (NLP), financial analytics, Jalali calendar conversions, and secure data handling. By leveraging Rust's memory safety and high performance, the core ensures that "hot" code paths—such as date conversions and transaction parsing—are executed efficiently across different platforms.
The module interfaces with the Android application via UniFFI, which automatically generates Kotlin bindings, eliminating the need for manual JNI (Java Native Interface) boilerplate. This architecture allows the core to remain platform-independent while providing 20+ exported functions to the JVM layer.
Sources: README.md:16-24, rust/hesabyar-core/README.md:3-15
Module Architecture and Data Flow
The Rust core is structured as a workspace member with specific responsibilities assigned to sub-modules. It operates as a stateless library that receives data from the Kotlin layer, processes it using Rust-native algorithms, and returns structured results.
Component Map
| Component | Responsibility | File Path |
|---|---|---|
| FFI Layer | UniFFI bridge for Kotlin interaction | ffi/mod.rs |
| Analytics | Transaction aggregation and burn rates | analytics.rs |
| Dashboard | Real-time balance and savings rate | dashboard.rs |
| AI Validation | Sanitizing and coercing AI-generated data | ai_validation.rs |
| Calendar | Jalali ↔ Gregorian bidirectional conversion | calendar.rs |
| Excel | Generating .xlsx reports from binary data | excel.rs |
| Crypto | AES-256-GCM encryption for backups | crypto.rs |
Sources: rust/hesabyar-core/README.md:38-60, README.md:103-128
System Integration Flow
The diagram below illustrates how a request from the Android UI travels through the Kotlin Bridge to the Rust Core.
The integration relies on RustBridge.kt as the primary mediator, using HesabyarCore (the generated UniFFI object) to invoke native methods.
Sources: app/src/main/java/io/github/mojri/hesabyar/rust/RustBridge.kt:20-50, README.md:130-142
Financial Engines
Analytics Aggregation
The analytics engine processes raw transaction lists to produce monthly summaries and category breakdowns. It uses the Jalali calendar exclusively for grouping income and expenses.
- Logic: It aggregates transactions by
(year, month)keys and calculates burn rates based on total expenses. - Key Data Structure:
AnalyticsDataincludes lists ofMonthlyData,CategoryBreakdown, andDebtSummary.
Sources: rust/hesabyar-core/src/analytics.rs:11-30, rust/uniffi/hesabyar_core/uniffi/hesabyar_core/hesabyar_core.kt:700-715
Dashboard Computation
Unlike a rolling window, the dashboard focuses on the current Jalali month. It calculates the current balance, monthly income/expense, and specific financial ratios.
- Savings Rate: Calculated as
(Monthly Income - Monthly Expenses) / Monthly Income, clamped between 0.0 and 1.0. - Debt-to-Income: A ratio derived from active loans and upcoming installments against monthly income.
AI Validation and Data Sanitization
The ai_validation module is critical for handling non-deterministic outputs from LLMs (like Gemini). It ensures that AI-generated transaction JSON or financial advice meets application constraints.
AI Transaction Repair
When parsing AI-generated JSON, the core performs "repairs" to maintain data integrity:
- Type Coercion: Unknown transaction types default to
EXPENSE. - Category Normalization: Maps 200+ fine-grained AI categories to 8 core DB categories (e.g., "Personal Care" → "Shopping").
- Confidence Clamping: Ensures confidence scores stay within
0.0to1.0. - Amount Invariant: Enforces the
1 Toman == 10 Rialsrule by multiplying AI-extracted Toman values by 10.
Sources: rust/hesabyar-core/src/ai_validation.rs:120-150, rust/hesabyar-core/src/ai_validation.rs:54-70
Advice Sanitization
For free-form text advice, the core implements safety checks and length limits.
| Check | Action | Source |
|---|---|---|
| Length | Truncates text at 10,000 characters | ai_validation.rs:240 |
| XSS Prevention | Strips <script> and javascript: tags | ai_validation.rs:259 |
| Language | Issues warning if no Persian characters are detected | ai_validation.rs:290 |
Sources: rust/hesabyar-core/src/ai_validation.rs:245-295
Reporting and Excel Generation
The core provides high-performance Excel report generation using rust_xlsxwriter. This allows the app to export financial summaries directly to .xlsx format with proper RTL (Right-to-Left) support for Persian text.
- Workflow: The Kotlin layer provides
WorkbookDatacontaining pre-formatted strings. The Rust core handles style application (colors, borders, bold fonts) and file serialization. - RTL Support: Every sheet is explicitly set to
right_to_left(true)to support Persian alignment.
Sources: rust/hesabyar-core/src/excel.rs:36-55, rust/hesabyar-core/src/excel.rs:65-75
Core Invariants and Constraints
The following technical constraints are enforced at the Rust core level and must be observed by all consumers:
- Money Representation: All monetary values must be
i64(Long) representing Rial. - Currency Conversion: The conversion factor is hardcoded:
1 Toman = 10 Rials. Conversational shorthands are handled in the NLP parser, but the storage unit is always Rial. - Calendar: All monthly aggregations and dashboard views must use the Jalali calendar boundaries.
- No Unsafe Code: The core is written entirely in safe Rust to guarantee memory safety.
Sources: rust/hesabyar-core/README.md:83-88, README.md:144-150, rust/uniffi/hesabyar_core/uniffi/hesabyar_core/hesabyar_core.kt:1310-1325
Conclusion
The hesabyar-core library is the backbone of the application's financial intelligence. By centralizing logic in Rust, the project achieves a high degree of reliability and performance, particularly for Persian NLP and complex financial analytics. Its integration through UniFFI provides a type-safe and efficient bridge to the Android Kotlin layer, ensuring that critical financial calculations remain consistent across the entire platform.