monetra 1.2.0 → 2.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,150 +1,286 @@
1
1
  # Monetra
2
2
 
3
- **Monetra** is a currency-aware, integer-based money engine designed for financial correctness. It explicitly avoids floating-point arithmetic and enforces strict monetary invariants.
3
+ A TypeScript library for handling monetary values with precision.
4
4
 
5
- It is intended for use in wallet-based financial systems where correctness is paramount.
5
+ [![npm version](https://img.shields.io/npm/v/monetra.svg)](https://www.npmjs.com/package/monetra)
6
+ [![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](LICENSE)
7
+ [![TypeScript](https://img.shields.io/badge/TypeScript-5.0+-blue.svg)](https://www.typescriptlang.org/)
8
+ [![Zero Dependencies](https://img.shields.io/badge/Dependencies-0-brightgreen.svg)]()
6
9
 
7
- ![License](https://img.shields.io/badge/license-MIT-blue.svg)
8
- ![TypeScript](https://img.shields.io/badge/language-TypeScript-blue.svg)
9
- ![Coverage](https://img.shields.io/badge/coverage-100%25-brightgreen.svg)
10
+ ---
10
11
 
11
- ## Features
12
+ ## Overview
12
13
 
13
- - **No floating-point arithmetic**: All values are stored in minor units (BigInt).
14
- - ❌ **No silent rounding**: Rounding must be explicit.
15
- - ❌ **No implicit currency conversion**: Operations between different currencies throw errors.
16
- - ✅ **Immutable**: All operations return new objects.
17
- - ✅ **Locale-aware formatting**: Built on `Intl` standards.
18
- - ✅ **Allocation Engine**: Deterministic splitting of funds (e.g., 33% / 33% / 34%).
19
- - ✅ **Smart Syntax**: Intuitive API that accepts numbers and strings directly.
20
- - ✅ **Multi-Currency Wallets**: Built-in `MoneyBag` for managing portfolios.
21
- - ✅ **Currency Conversion**: Robust `Converter` with exchange rate support.
22
- - ✅ **Financial Primitives**: Helpers for tax, discounts, and splitting.
23
- - ✅ **Ledger System**: Immutable, cryptographically verifiable transaction history.
24
- - ✅ **Financial Math**: Standard formulas for loans (PMT), TVM (FV/PV), and Investment (NPV/IRR).
25
- - ✅ **Crypto & Tokens**: Support for high-precision tokens (18 decimals) and custom currencies.
26
-
27
- ## Table of Contents
28
-
29
- - [Quick Start](#quick-start)
30
- - [Core Concepts](#core-concepts)
31
- - [Usage Examples](#usage-examples)
32
- - [Documentation](#documentation)
33
- - [Testing](#testing)
34
- - [Contributing](#contributing)
35
- - [Security](#security)
36
- - [License](#license)
14
+ Monetra is a zero-dependency TypeScript library that handles monetary values using integer arithmetic. By storing amounts in minor units (cents, satoshis, wei) as `BigInt`, it avoids the floating-point precision errors inherent in JavaScript's `number` type.
37
15
 
38
- ## Quick Start
16
+ ```typescript
17
+ // JavaScript floating-point issue
18
+ 0.1 + 0.2 === 0.3; // false (0.30000000000000004)
19
+
20
+ // Monetra
21
+ import { money } from "monetra";
22
+ money("0.10", "USD").add("0.20").equals(money("0.30", "USD")); // true
23
+ ```
24
+
25
+ ---
39
26
 
40
- ### Installation
27
+ ## Installation
41
28
 
42
29
  ```bash
43
30
  npm install monetra
44
- # or
31
+ ```
32
+
33
+ ```bash
45
34
  yarn add monetra
46
- # or
35
+ ```
36
+
37
+ ```bash
47
38
  pnpm add monetra
48
39
  ```
49
40
 
41
+ **Requirements:** Node.js 18+ or modern browsers with BigInt support.
42
+
43
+ ---
44
+
45
+ ## Features
46
+
47
+ - **Integer-based storage** - All values stored as `BigInt` in minor units
48
+ - **Explicit rounding** - Six rounding modes (HALF_UP, HALF_DOWN, HALF_EVEN, FLOOR, CEIL, TRUNCATE)
49
+ - **Currency support** - ISO 4217 currencies with automatic precision handling
50
+ - **Custom tokens** - Define cryptocurrencies and tokens with up to 18 decimal places
51
+ - **Allocation** - Split amounts without losing cents
52
+ - **Financial calculations** - Compound interest, loan amortization, NPV, IRR
53
+ - **Ledger** - Append-only transaction log with hash chain verification
54
+ - **Currency conversion** - Rate management with historical lookups
55
+ - **Multi-currency** - MoneyBag for aggregating different currencies
56
+ - **Immutable** - All operations return new instances
57
+ - **Type-safe** - Full TypeScript support with strict types
58
+
59
+ ---
60
+
61
+ ## Quick Start
62
+
50
63
  ### Basic Usage
51
64
 
52
65
  ```typescript
53
- import { money, USD } from "monetra";
66
+ import { money, Money, RoundingMode } from "monetra";
67
+
68
+ // Create money from string (major units)
69
+ const price = money("19.99", "USD");
54
70
 
55
- // Create money easily
56
- const price = money("10.50", "USD"); // $10.50
57
- const tax = price.percentage(10); // $1.05
71
+ // Create from minor units (cents)
72
+ const tax = Money.fromMinor(199, "USD");
58
73
 
59
- // Smart arithmetic
60
- const total = price.add(tax); // $11.55
61
- const discounted = total.subtract("2.00"); // $9.55
74
+ // Arithmetic
75
+ const subtotal = price.add(tax);
76
+ const total = subtotal.multiply(2);
62
77
 
63
- console.log(discounted.format()); // "$9.55"
78
+ // Formatting
79
+ console.log(total.format()); // "$43.96"
80
+ console.log(total.format({ locale: "de-DE" })); // "43,96 $"
64
81
  ```
65
82
 
66
- ## Core Concepts
83
+ ### Allocation
67
84
 
68
- ### Integer-Only Representation
85
+ Split money without losing cents:
69
86
 
70
- Monetra stores all values in minor units (e.g., cents) using `BigInt`. This avoids the precision errors common with floating-point math.
87
+ ```typescript
88
+ const bill = money("100.00", "USD");
89
+ const shares = bill.split(3);
90
+ // [money("33.34"), money("33.33"), money("33.33")]
71
91
 
72
- - `$10.50` is stored as `1050n`.
73
- - `¥100` is stored as `100n`.
92
+ // Verify sum equals original
93
+ shares.reduce((a, b) => a.add(b)).equals(bill); // true
94
+ ```
74
95
 
75
- ### Immutability
96
+ ### Rounding
76
97
 
77
- Money objects are immutable. Operations like `add` or `multiply` return new instances.
98
+ Operations that produce fractional minor units require explicit rounding:
78
99
 
79
100
  ```typescript
80
- const a = Money.fromMajor("10.00", USD);
81
- const b = a.add(Money.fromMajor("5.00", USD));
101
+ const price = money("100.00", "USD");
102
+
103
+ // Division requires rounding mode
104
+ const third = price.divide(3, { rounding: RoundingMode.HALF_UP });
105
+ console.log(third.format()); // "$33.33"
82
106
 
83
- console.log(a.format()); // "$10.00" (unchanged)
84
- console.log(b.format()); // "$15.00"
107
+ // Or use allocate for lossless division
108
+ const parts = price.allocate([1, 1, 1]);
109
+ // ["$33.34", "$33.33", "$33.33"]
85
110
  ```
86
111
 
87
- ### Explicit Rounding
112
+ ### Custom Tokens
88
113
 
89
- Operations that result in fractional minor units (like multiplication) require an explicit rounding mode.
114
+ Define cryptocurrencies or custom tokens:
90
115
 
91
116
  ```typescript
92
- const m = Money.fromMajor("10.00", USD);
93
- // m.multiply(0.333); // Throws RoundingRequiredError
94
- m.multiply(0.333, { rounding: RoundingMode.HALF_UP }); // OK
117
+ import { defineToken, money } from "monetra";
118
+
119
+ const USDC = defineToken({
120
+ code: "USDC",
121
+ symbol: "USDC",
122
+ decimals: 6,
123
+ type: "crypto",
124
+ });
125
+
126
+ const balance = money("1000.50", USDC);
127
+ console.log(balance.format()); // "1,000.50 USDC"
95
128
  ```
96
129
 
97
- ## Usage Examples
130
+ ### Financial Calculations
131
+
132
+ ```typescript
133
+ import { money, futureValue, pmt, loan } from "monetra";
134
+
135
+ // Future value of investment
136
+ const principal = money("10000", "USD");
137
+ const future = futureValue(principal, {
138
+ rate: 0.07,
139
+ years: 10,
140
+ compoundingPerYear: 12,
141
+ });
142
+ console.log(future.format()); // "$20,096.61"
143
+
144
+ // Monthly loan payment
145
+ const payment = pmt({
146
+ principal: money("200000", "USD"),
147
+ annualRate: 0.065,
148
+ years: 30,
149
+ });
150
+ console.log(payment.format()); // "$1,264.14"
151
+ ```
98
152
 
99
- ### Allocation (Splitting Funds)
153
+ ### Ledger
100
154
 
101
- Split money without losing a cent. Remainders are distributed deterministically using the largest remainder method.
155
+ Track transactions with verification:
102
156
 
103
157
  ```typescript
104
- const pot = Money.fromMajor("100.00", USD);
105
- const [part1, part2, part3] = pot.allocate([1, 1, 1]);
158
+ import { Ledger, money } from "monetra";
159
+
160
+ const ledger = new Ledger("USD");
106
161
 
107
- // part1: $33.34
108
- // part2: $33.33
109
- // part3: $33.33
110
- // Sum: $100.00
162
+ ledger.credit("account", money("1000.00", "USD"), "Deposit");
163
+ ledger.debit("account", money("50.00", "USD"), "Purchase");
164
+
165
+ console.log(ledger.getBalance("account").format()); // "$950.00"
166
+ console.log(ledger.verify()); // true
111
167
  ```
112
168
 
169
+ ---
170
+
171
+ ## API Summary
172
+
173
+ ### Money Class
174
+
175
+ | Method | Description |
176
+ | ----------------------------------- | ------------------------------------ |
177
+ | `money(amount, currency)` | Create Money from string or number |
178
+ | `Money.fromMinor(cents, currency)` | Create from minor units |
179
+ | `Money.fromMajor(amount, currency)` | Create from major units (string) |
180
+ | `Money.zero(currency)` | Create zero amount |
181
+ | `.add(other)` | Add two Money values |
182
+ | `.subtract(other)` | Subtract Money values |
183
+ | `.multiply(factor, options?)` | Multiply by scalar |
184
+ | `.divide(divisor, options)` | Divide by scalar (requires rounding) |
185
+ | `.percentage(percent, rounding?)` | Calculate percentage |
186
+ | `.split(n)` | Split into n equal parts |
187
+ | `.allocate(ratios)` | Allocate by ratios |
188
+ | `.format(options?)` | Format for display |
189
+ | `.equals(other)` | Check equality |
190
+ | `.lessThan(other)` | Compare values |
191
+ | `.greaterThan(other)` | Compare values |
192
+ | `.isPositive()` | Check if positive |
193
+ | `.isNegative()` | Check if negative |
194
+ | `.isZero()` | Check if zero |
195
+
196
+ ### Financial Functions
197
+
198
+ | Function | Description |
199
+ | ----------------------------------------- | --------------------------------------------- |
200
+ | `futureValue(principal, options)` | Calculate future value with compound interest |
201
+ | `presentValue(futureAmount, options)` | Calculate present value |
202
+ | `pmt(options)` | Calculate loan payment amount |
203
+ | `loan(options)` | Generate amortization schedule |
204
+ | `npv(initialInvestment, cashFlows, rate)` | Net present value |
205
+ | `irr(initialInvestment, cashFlows)` | Internal rate of return |
206
+
207
+ ### Classes
208
+
209
+ | Class | Description |
210
+ | ----------- | --------------------------------------------- |
211
+ | `Ledger` | Append-only transaction log with verification |
212
+ | `Converter` | Currency conversion with rate management |
213
+ | `MoneyBag` | Multi-currency aggregation |
214
+
215
+ ---
216
+
113
217
  ## Documentation
114
218
 
115
- For more detailed information, please refer to the documentation in the `docs` folder:
219
+ Full documentation is available in the [docs](docs/index.md) directory:
116
220
 
117
- 1. [Core Concepts](docs/001-CORE-CONCEPTS.md)
118
- 2. [Ledger System](docs/002-LEDGER-SYSTEM.md)
119
- 3. [Financial Math](docs/003-FINANCIAL-MATH.md)
120
- 4. [Tokens & Crypto](docs/004-TOKENS-AND-CRYPTO.md)
121
- 5. [API Reference](docs/005-API-REFERENCE.md)
221
+ **Getting Started**
122
222
 
123
- ## Testing
223
+ - [Installation & Setup](docs/getting-started.md)
224
+ - [Core Concepts](docs/core-concepts.md)
225
+
226
+ **API Reference**
227
+
228
+ - [Money](docs/api/money.md) - Core monetary value class
229
+ - [Ledger](docs/api/ledger.md) - Transaction log with verification
230
+ - [Financial](docs/api/financial.md) - Financial calculations
231
+ - [Currency & Tokens](docs/api/currency.md) - Currency and token definitions
232
+
233
+ **Guides**
124
234
 
125
- We maintain 100% test coverage to ensure financial correctness.
235
+ - [Allocation & Splitting](docs/guides/allocation.md)
236
+ - [Formatting & Parsing](docs/guides/formatting.md)
237
+ - [Custom Tokens](docs/guides/custom-tokens.md)
238
+ - [Error Handling](docs/guides/error-handling.md)
239
+
240
+ **Framework Examples**
241
+
242
+ - [React.js](docs/examples/react.md)
243
+ - [Vue.js](docs/examples/vue.md)
244
+ - [Node.js](docs/examples/node.md)
245
+
246
+ **Reference**
247
+
248
+ - [Best Practices](docs/best-practices.md)
249
+ - [Library Comparison](docs/comparison.md)
250
+
251
+ ---
252
+
253
+ ## Testing
126
254
 
127
255
  ```bash
128
- # Run all tests
256
+ # Run tests
129
257
  npm test
130
258
 
131
- # Run tests in watch mode
259
+ # Watch mode
132
260
  npm run test:watch
133
261
 
134
- # Generate coverage report
262
+ # Coverage report
135
263
  npm run test:coverage
136
264
  ```
137
265
 
266
+ ---
267
+
138
268
  ## Contributing
139
269
 
140
- Contributions are welcome! Please see [CONTRIBUTING.md](CONTRIBUTING.md) for details on how to get started.
270
+ See [CONTRIBUTING.md](CONTRIBUTING.md) for guidelines.
271
+
272
+ Check our [Project Roadmap](https://github.com/users/zugobite/projects/2) to see what we're working on.
141
273
 
142
- We also have a [Code of Conduct](CODE_OF_CONDUCT.md) that all contributors are expected to follow.
274
+ Please review our [Code of Conduct](CODE_OF_CONDUCT.md) before contributing.
275
+
276
+ ---
143
277
 
144
278
  ## Security
145
279
 
146
- If you discover a security vulnerability, please review our [Security Policy](SECURITY.md) for instructions on how to report it responsibly.
280
+ Report security vulnerabilities according to our [Security Policy](SECURITY.md).
281
+
282
+ ---
147
283
 
148
284
  ## License
149
285
 
150
- This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
286
+ MIT - see [LICENSE](LICENSE) for details.