amounts 0.1.0 → 0.2.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.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 494f30811e40cd1e304c944fe6033f33d1c64f2a6e962e3636e2d43eb702db4d
4
- data.tar.gz: 1b1f175209a0b3adb1cb48ad0c8429dcb5f3e0f0fe2558ee0cbbd8616b3a4714
3
+ metadata.gz: 9a77f5a9506149f307e11d78c1063e9951c149302eaace9b35e924cf92ce4102
4
+ data.tar.gz: ade0b4aca169538a4b9e17d3e4ab412f19cbe343aff7b540de6936b814373751
5
5
  SHA512:
6
- metadata.gz: c70c23049b1f4932b122628c71a8fa66d079e387f8a2b9f6ff967dc3cbfb2921628eb7b633afaf54bd9f47a785f90b9f2ccc78e50d46a129d8b418c5cd3aacf7
7
- data.tar.gz: 700869d84355a4bcc8bd126fe93ea05c9e9574dad67d88124f091b28161eef45056c10e4507fbc62467868a9515822b0522b1c0074437e6fba9ee838573f6ee9
6
+ metadata.gz: 0c9225c174016b40143bd049c8673312a0ceffcb32244b5ce9a613cdb2342d768faf67141ea0aeb30fe5c91d89bbf720860dae27fb77413e401d9e1877723b9b
7
+ data.tar.gz: 1c0dd2ff180fc3589c4a722bd0789e37b9afb7d71599680c77fcd299b2e07366df31d439647c5927ff9a8f50d1d89c07ec8de1da05fae72d9570be78e8731020
data/CHANGELOG.md CHANGED
@@ -1,5 +1,72 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.2.0 - 2026-11-14
4
+
5
+ ### Added
6
+
7
+ - `amount_changes` and `saved_amount_changes` on models with `has_amount`:
8
+ Rails' `changes` and `saved_changes` with each amount by name, as
9
+ `[before, after]` Amounts, in place of its component columns. Rails' own
10
+ change hashes are unchanged.
11
+ - `Model.amount_column_values(attributes)` turns attributes, with amounts by
12
+ name, into column values for `insert_all`, `upsert_all` and their variants,
13
+ which skip attribute writers. Each amount is cast as its writer would cast
14
+ it and replaced by its component columns (all of them even for `nil`, so
15
+ rows share keys); other keys pass through. A fixed-symbol amount in another
16
+ symbol raises `Amount::TypeMismatch`, since bulk writes skip validations.
17
+ - SQL aggregates for `has_amount` attributes that return Amounts:
18
+ `sum_amount`, `minimum_amount`, `maximum_amount` and `average_amount`. Each
19
+ runs one query in the scope of the relation it's called on, so `where`,
20
+ `group` and associations apply. Grouped, the result is keyed like Rails'
21
+ `group(...).sum`. A multi-symbol attribute with more than one symbol in
22
+ scope, or in one group, raises `Amount::TypeMismatch`; group by its symbol
23
+ column for one Amount per symbol. A fixed-symbol sum over no rows is zero;
24
+ other empty results are `nil`. `average_amount` truncates toward zero to a
25
+ whole atomic unit, as `Amount#/` does. Grouping by an association name
26
+ raises `ArgumentError` (group by its foreign key). On SQLite, aggregates
27
+ past 64 bits raise `integer overflow` or come back inexact; PostgreSQL is
28
+ exact.
29
+
30
+ ### Changed
31
+
32
+ - **Breaking:** a model with `has_amount` serializes each amount by its name,
33
+ as its exact compact string, in place of its component columns:
34
+ `as_json` gives `"owed" => "USD|10.06"`, not `"owed_atomic" => "1006.0"`
35
+ (`serializable_hash` holds the Amount). `only:` and `except:` take the
36
+ amount's name. `has_amount` includes this into the declaring model;
37
+ `ActiveRecord::Base` and models without amounts are unchanged.
38
+
39
+ Migration: JSON readers that read `<name>_atomic` / `<name>_symbol` read
40
+ `<name>` instead and parse it with `Amount.parse`. Code that needs the raw
41
+ columns reads them from `attributes`
42
+ (`record.attributes.slice("owed_atomic")`).
43
+ - **Breaking:** `Amount#as_json` (and so `to_json`) writes the exact compact
44
+ string: whole units with exactly the symbol's `decimals` places
45
+ (`"USDC|1.500000"`, `"SOL|1.123456789"`). It previously returned `to_s`,
46
+ which rounds down to `ui_decimals`, so JSON silently dropped digits past it
47
+ (`"SOL|1.1234"` for 1.123456789 SOL).
48
+
49
+ Migration: clients that read the value with `Amount.parse` or as a number
50
+ need no change. Where JSON output was compared as a string (tests,
51
+ fixtures) or shown to people, expect the longer form, or use `to_s` or `ui`
52
+ for display.
53
+
54
+ ### Fixed
55
+
56
+ - `Amount#/` by a scalar computes the quotient exactly (in `Rational`) before
57
+ truncating it toward zero. It divided in `BigDecimal`, which rounds the
58
+ quotient to a limited precision, so large amounts divided by small decimals
59
+ came out wrong: 10^40 atomic units divided by `BigDecimal("7e-21")` was off
60
+ by 1429 atomic units. Results that were already exact are unchanged.
61
+ `average_amount` divides this way.
62
+ - A subclass of a model with `has_amount` (STI included) inherits its
63
+ parent's amount definitions. It previously started with none, so
64
+ `amount_attribute_definitions`, `amount_atomic_column` and friends raised
65
+ `KeyError` on the subclass, and so did the `amount:` validator and the
66
+ `have_amount_column` matcher for inherited amounts. Amounts a subclass
67
+ declares stay off its parent and siblings. `amount_attribute_definitions`
68
+ is now a `class_attribute` holding a frozen Hash.
69
+
3
70
  ## 0.1.0 - 2026-11-02
4
71
 
5
72
  ### Added
data/README.md CHANGED
@@ -150,6 +150,10 @@ Amount.new("10", :USDC) / 2
150
150
  # => #<Amount USDC|5.0>
151
151
  ```
152
152
 
153
+ The quotient is computed exactly and truncated toward zero to a whole atomic
154
+ unit: `Amount.new(3, :USDC, from: :atomic) / 2` is 1 atomic unit, and `-3 / 2`
155
+ is -1.
156
+
153
157
  `split` and `allocate` return explicit remainders:
154
158
 
155
159
  ```ruby
@@ -409,6 +413,15 @@ payload = amount.to_h
409
413
  Amount.load(payload)
410
414
  ```
411
415
 
416
+ `as_json` (and so `to_json`) writes the exact compact string: whole units with
417
+ exactly the symbol's `decimals` places. It ignores display settings and never
418
+ rounds, so `Amount.parse` reads it back exactly. Use `to_s` or `ui` for display.
419
+
420
+ ```ruby
421
+ Amount.of_usdc("1.5").as_json # => "USDC|1.500000"
422
+ { amount: Amount.of_usdc("1.5") }.to_json # => '{"amount":"USDC|1.500000"}'
423
+ ```
424
+
412
425
  ## Registry API
413
426
 
414
427
  ```ruby
@@ -482,6 +495,34 @@ Writers accept:
482
495
  - `Hash` payloads
483
496
  - raw numeric values for fixed-symbol attributes only
484
497
 
498
+ A subclass (STI included) inherits its parent's amounts. Amounts it declares
499
+ itself stay off the parent and its other subclasses.
500
+
501
+ `as_json`, `to_json` and `serializable_hash` write each amount by its name, as
502
+ its exact compact string, in place of its columns. `only:` and `except:` take the
503
+ amount's name, and the raw columns stay readable through `attributes`.
504
+ `amount_changes` and `saved_amount_changes` are `changes` and `saved_changes`
505
+ with amounts by name. Rails' own change hashes stay keyed by column:
506
+
507
+ ```ruby
508
+ holding.as_json # => { "id" => 1, "amount" => "USDC|1.500000", "fee" => "SOL|0.250000000" }
509
+
510
+ holding.update!(amount: "USDC|2")
511
+ holding.saved_amount_changes # => { "amount" => [#<Amount USDC $1.50>, #<Amount USDC $2.00>] }
512
+ ```
513
+
514
+ `insert_all` and `upsert_all` skip writers, so `amount_column_values` turns
515
+ amounts by name into their columns first. It casts like the writer, raises
516
+ `Amount::TypeMismatch` for a fixed-symbol amount in another symbol, and gives
517
+ every column of a `nil` amount so rows share keys:
518
+
519
+ ```ruby
520
+ Holding.amount_column_values(amount: "USDC|1.50", fee: 0.25)
521
+ # => { "amount_atomic" => 1500000, "amount_symbol" => "USDC", "fee_atomic" => 250000000 }
522
+
523
+ Holding.insert_all(rows.map { |row| Holding.amount_column_values(row) })
524
+ ```
525
+
485
526
  Scopes:
486
527
 
487
528
  ```ruby
@@ -494,6 +535,23 @@ Holding.where_amount_between("USDC|1.00", "USDC|5.00")
494
535
  Holding.amount_in(:USDC)
495
536
  ```
496
537
 
538
+ Aggregates run in SQL and return Amounts, one query each, in the scope they're
539
+ called on (`where`, `group` and associations apply):
540
+
541
+ ```ruby
542
+ Holding.sum_amount(:fee) # => #<Amount SOL ...>
543
+ Holding.minimum_amount(:fee)
544
+ Holding.maximum_amount(:fee)
545
+ Holding.average_amount(:fee) # truncated toward zero, like Amount#/
546
+ Holding.group(:amount_symbol).sum_amount(:amount) # => { "USDC" => #<Amount USDC ...>, "SOL" => ... }
547
+ ```
548
+
549
+ Symbols never mix: a multi-symbol attribute with more than one symbol in scope
550
+ (or in one group) raises `Amount::TypeMismatch`, so group by its symbol column for
551
+ one Amount per symbol. A fixed-symbol sum over no rows is zero; otherwise an
552
+ empty set gives `nil`. Group by a column or SQL expression, not an association
553
+ name.
554
+
497
555
  Suggested check constraint for multi-symbol amounts:
498
556
 
499
557
  ```sql
@@ -532,7 +590,7 @@ for free.
532
590
 
533
591
  ### SQLite Note
534
592
 
535
- The adapter supports SQLite for general integration tests and development, but SQLite does not preserve `DECIMAL(78,0)` values above 64-bit range exactly under ActiveRecord's default numeric handling. For exact wei-scale persistence, use PostgreSQL or another database with true arbitrary-precision numeric behavior.
593
+ The adapter supports SQLite for general integration tests and development, but SQLite does not preserve `DECIMAL(78,0)` values above 64-bit range exactly under ActiveRecord's default numeric handling, and its sums and averages past that range either raise `integer overflow` or come back inexact (Rails' own `sum` too). For exact wei-scale persistence, use PostgreSQL or another database with true arbitrary-precision numeric behavior.
536
594
 
537
595
  ### PostgreSQL Dummy App
538
596
 
@@ -35,17 +35,21 @@ class Amount
35
35
  end
36
36
 
37
37
  def write(record, value)
38
- if value.nil?
39
- record.write_attribute(atomic_column, nil)
40
- record.write_attribute(symbol_column, nil) unless fixed_symbol?
41
- return nil
42
- end
38
+ column_values(value).each { |column, column_value| record.write_attribute(column, column_value) }
39
+ value
40
+ end
43
41
 
42
+ # The component column values that store `value`, an Amount or `nil`.
43
+ # Every component column is present, so rows built from it share keys.
44
+ #
45
+ # @param value [Amount, nil]
46
+ # @return [Hash{String => Integer, String, nil}]
47
+ def column_values(value)
44
48
  # The Integer itself, not its string: Rails 8.1 cuts a String cast to an
45
49
  # integer column to 16 bytes, which silently truncates large values.
46
- record.write_attribute(atomic_column, value.atomic)
47
- record.write_attribute(symbol_column, value.symbol.to_s) unless fixed_symbol?
48
- value
50
+ values = { atomic_column => value&.atomic }
51
+ values[symbol_column] = value&.symbol&.to_s unless fixed_symbol?
52
+ values
49
53
  end
50
54
 
51
55
  def build_from_values(values)
@@ -0,0 +1,127 @@
1
+ # frozen_string_literal: true
2
+
3
+ class Amount
4
+ module ActiveRecord
5
+ # Aggregates `has_amount` attributes in SQL and returns Amounts.
6
+ #
7
+ # Each method runs one query in the scope of the relation it is called
8
+ # on, so `where` and `group` apply. Ungrouped, it returns one Amount (or
9
+ # `nil`); grouped, it returns a Hash keyed like Rails' `group(...).sum`,
10
+ # by the group's value, or by an array of values for several groups.
11
+ # Group by a column or SQL expression; grouping by an association name
12
+ # raises `ArgumentError` (group by its foreign key instead).
13
+ #
14
+ # Amounts of different symbols never combine: a multi-symbol attribute
15
+ # with more than one symbol in scope, or in one group, raises
16
+ # {Amount::TypeMismatch}. Group by its symbol column for one Amount per
17
+ # symbol.
18
+ #
19
+ # @example
20
+ # UsageRecord.sum_amount(:cost) # => #<Amount USDP ...>
21
+ # UsageRecord.group(:kind).sum_amount(:cost) # => { "search" => #<Amount USDP ...> }
22
+ # UsageRecord.group(:quantity_symbol).sum_amount(:quantity)
23
+ module Calculations
24
+ # A fixed-symbol sum over no rows is zero; a multi-symbol one is `nil`.
25
+ #
26
+ # @param name [Symbol, String] a `has_amount` attribute
27
+ # @return [Amount, Hash, nil]
28
+ # @raise [Amount::TypeMismatch] when amounts of more than one symbol meet
29
+ def sum_amount(name)
30
+ # SQL's SUM is NULL over no rows, and `none` runs no query at all;
31
+ # Rails' `sum` is zero for both. `deserialize(0)` is that zero for a
32
+ # fixed symbol and `nil` for a multi-symbol attribute.
33
+ zero = amount_attribute_definitions.fetch(name.to_sym).type.deserialize(0)
34
+ aggregate_amount(name, :sum) { |sum| sum || zero } || zero
35
+ end
36
+
37
+ # @param name [Symbol, String] a `has_amount` attribute
38
+ # @return [Amount, Hash, nil] `nil` over no rows
39
+ # @raise [Amount::TypeMismatch] when amounts of more than one symbol meet
40
+ def minimum_amount(name)
41
+ aggregate_amount(name, :minimum) { |minimum| minimum }
42
+ end
43
+
44
+ # @param name [Symbol, String] a `has_amount` attribute
45
+ # @return [Amount, Hash, nil] `nil` over no rows
46
+ # @raise [Amount::TypeMismatch] when amounts of more than one symbol meet
47
+ def maximum_amount(name)
48
+ aggregate_amount(name, :maximum) { |maximum| maximum }
49
+ end
50
+
51
+ # The sum divided by the number of amounts, truncated toward zero to a
52
+ # whole atomic unit, as `Amount#/` does. The sum and the count come from
53
+ # the same query.
54
+ #
55
+ # @param name [Symbol, String] a `has_amount` attribute
56
+ # @return [Amount, Hash, nil] `nil` over no rows
57
+ # @raise [Amount::TypeMismatch] when amounts of more than one symbol meet
58
+ def average_amount(name)
59
+ aggregate_amount(name, :sum, :count) { |sum, count| sum / count unless count.zero? }
60
+ end
61
+
62
+ private
63
+
64
+ # Plucks the caller's groups, the symbol and the aggregates as
65
+ # `[*groups, symbol, atomic, *rest]`, then yields each group's first
66
+ # aggregate as an Amount, with the rest as they came.
67
+ def aggregate_amount(name, *operations)
68
+ definition = amount_attribute_definitions.fetch(name.to_sym)
69
+ groups = amount_group_values
70
+ atomic = arel_table[definition.atomic_column]
71
+
72
+ rows = amount_aggregate_scope(definition)
73
+ .pluck(*groups, amount_symbol_select(definition),
74
+ *operations.map { |operation| atomic.public_send(operation) })
75
+
76
+ results = rows.group_by { |row| amount_group_key(row.first(groups.size)) }
77
+ .transform_values do |group_rows|
78
+ yield(*amount_group_values_of(definition, group_rows.map { |row| row.drop(groups.size) }))
79
+ end
80
+
81
+ groups.empty? ? results[[]] : results
82
+ end
83
+
84
+ # The caller passed these to `group`, which takes raw SQL; `pluck` takes
85
+ # a SQL string only wrapped in `Arel.sql`.
86
+ def amount_group_values
87
+ all.group_values.map do |group|
88
+ reflection = group.respond_to?(:to_sym) && _reflect_on_association(group)
89
+ if reflection
90
+ raise ArgumentError,
91
+ "group by #{reflection.foreign_key}, not the #{group} association, to aggregate amounts"
92
+ end
93
+
94
+ group.is_a?(String) ? ::Arel.sql(group) : group
95
+ end
96
+ end
97
+
98
+ # A multi-symbol attribute is grouped by its symbol too, so each row is
99
+ # one symbol's aggregate. Rows without an amount are left out.
100
+ def amount_aggregate_scope(definition)
101
+ return all if definition.fixed_symbol?
102
+
103
+ where.not(definition.symbol_column => nil).group(definition.symbol_column)
104
+ end
105
+
106
+ def amount_symbol_select(definition)
107
+ return ::Arel::Nodes.build_quoted(definition.symbol.to_s) if definition.fixed_symbol?
108
+
109
+ arel_table[definition.symbol_column]
110
+ end
111
+
112
+ def amount_group_key(values)
113
+ values.size == 1 ? values.first : values
114
+ end
115
+
116
+ def amount_group_values_of(definition, rows)
117
+ unless rows.size == 1
118
+ raise ::Amount::TypeMismatch,
119
+ "#{definition.name} has more than one symbol in scope: #{rows.map(&:first).join(', ')}"
120
+ end
121
+
122
+ symbol, atomic, *rest = rows.first
123
+ [definition.type.deserialize(atomic, symbol), *rest]
124
+ end
125
+ end
126
+ end
127
+ end
@@ -0,0 +1,43 @@
1
+ # frozen_string_literal: true
2
+
3
+ class Amount
4
+ module ActiveRecord
5
+ # Change hashes with each `has_amount` attribute by its name, as
6
+ # `[before, after]` Amounts, in place of its component columns.
7
+ # `has_amount` includes it into the model that declares an amount.
8
+ #
9
+ # Rails' own `changes` and `saved_changes` are left as they are, keyed
10
+ # by column, for the code and gems that read them that way.
11
+ #
12
+ # @example
13
+ # subscription.update!(owed: Amount.of_usd("10.06"))
14
+ # subscription.saved_changes # => { "owed_atomic" => [0, 1006], ... }
15
+ # subscription.saved_amount_changes # => { "owed" => [#<Amount USD $0.00>, #<Amount USD $10.06>], ... }
16
+ module Dirty
17
+ # Like `changes`: the changes not yet saved.
18
+ #
19
+ # @return [ActiveSupport::HashWithIndifferentAccess]
20
+ def amount_changes
21
+ amounts_in_place_of_column_changes(changes) { |definition| definition.change(self) }
22
+ end
23
+
24
+ # Like `saved_changes`: the changes the last save made.
25
+ #
26
+ # @return [ActiveSupport::HashWithIndifferentAccess]
27
+ def saved_amount_changes
28
+ amounts_in_place_of_column_changes(saved_changes) { |definition| definition.saved_change(self) }
29
+ end
30
+
31
+ private
32
+
33
+ def amounts_in_place_of_column_changes(column_changes)
34
+ self.class.amount_attribute_definitions.each_value do |definition|
35
+ change = yield(definition)
36
+ definition.component_columns.each { |column| column_changes.delete(column) }
37
+ column_changes[definition.name.to_s] = change if change
38
+ end
39
+ column_changes
40
+ end
41
+ end
42
+ end
43
+ end
@@ -4,9 +4,20 @@ class Amount
4
4
  module ActiveRecord
5
5
  # Provides `has_amount` for ActiveRecord models.
6
6
  module Model
7
+ # The definitions are a class attribute, so a subclass (STI included)
8
+ # sees its parent's amounts. `has_amount` assigns a new Hash rather than
9
+ # changing the inherited one, so a subclass's amounts stay its own.
10
+ def self.extended(base)
11
+ base.class_attribute :amount_attribute_definitions, instance_accessor: false, default: {}.freeze
12
+ end
13
+
7
14
  def has_amount(name, symbol: nil)
15
+ # Into this model only; a repeat `include` does nothing, and
16
+ # subclasses inherit them.
17
+ include Serialization, Dirty
18
+
8
19
  definition = AttributeDefinition.new(name, symbol:)
9
- amount_attribute_definitions[definition.name] = definition
20
+ self.amount_attribute_definitions = amount_attribute_definitions.merge(definition.name => definition).freeze
10
21
 
11
22
  define_amount_reader(definition)
12
23
  define_amount_writer(definition)
@@ -24,10 +35,6 @@ class Amount
24
35
  @model_name ||= ::ActiveModel::Name.new(self, nil, "AnonymousModel")
25
36
  end
26
37
 
27
- def amount_attribute_definitions
28
- @amount_attribute_definitions ||= {}
29
- end
30
-
31
38
  def amount_component_columns(name)
32
39
  amount_attribute_definition(name).component_columns
33
40
  end
@@ -0,0 +1,34 @@
1
+ # frozen_string_literal: true
2
+
3
+ class Amount
4
+ module ActiveRecord
5
+ # Prepares `has_amount` attributes for Rails' bulk writes (`insert_all`,
6
+ # `upsert_all` and their variants), which skip attribute writers and take
7
+ # column values only.
8
+ module Persistence
9
+ # Turns attributes, with amounts by name, into column values. Each
10
+ # amount is cast as its writer would cast it and replaced by its
11
+ # component columns, all of them even for `nil`, so rows share keys.
12
+ # Any other key passes through.
13
+ #
14
+ # @param attributes [Hash] attributes keyed by String or Symbol
15
+ # @return [Hash]
16
+ # @raise [Amount::TypeMismatch] when a fixed-symbol amount has another
17
+ # symbol (the writer records this as a validation error instead;
18
+ # `insert_all` doesn't validate)
19
+ # @example
20
+ # UsageRecord.amount_column_values("cost" => "USDP|0.0042", "kind" => "model_call")
21
+ # # => { "cost_atomic" => 42000000, "kind" => "model_call" }
22
+ #
23
+ # UsageRecord.insert_all(rows.map { |row| UsageRecord.amount_column_values(row) })
24
+ def amount_column_values(attributes)
25
+ attributes.each_with_object({}) do |(key, value), columns|
26
+ definition = amount_attribute_definitions[key.to_sym]
27
+ next columns[key] = value unless definition
28
+
29
+ columns.merge!(definition.column_values(definition.type.cast(value)))
30
+ end
31
+ end
32
+ end
33
+ end
34
+ end
@@ -0,0 +1,57 @@
1
+ # frozen_string_literal: true
2
+
3
+ class Amount
4
+ module ActiveRecord
5
+ # Writes each `has_amount` attribute by its name, as the amount, in place
6
+ # of its component columns: `as_json` gives `"owed" => "USD|10.06"`
7
+ # rather than `"owed_atomic" => 1006`. `has_amount` includes it into the
8
+ # model that declares an amount.
9
+ #
10
+ # `only:` and `except:` take the amount's name. An amount whose columns
11
+ # weren't all selected keeps the columns that were. The raw columns stay
12
+ # readable through Rails' `attributes`.
13
+ #
14
+ # @example
15
+ # subscription.as_json # => { "id" => 1, "owed" => "USD|10.06" }
16
+ # subscription.as_json(only: :owed) # => { "owed" => "USD|10.06" }
17
+ module Serialization
18
+ # @param options [Hash, nil] Rails' options
19
+ # @return [Hash]
20
+ def serializable_hash(options = nil)
21
+ definitions = self.class.amount_attribute_definitions.values
22
+ options = amount_names_as_columns(options ? options.dup : {}, definitions)
23
+
24
+ amounts_in_place_of_columns(super(options), definitions)
25
+ end
26
+
27
+ private
28
+
29
+ # Rails filters `only:` and `except:` by column, so an amount's name
30
+ # becomes its component columns.
31
+ def amount_names_as_columns(options, definitions)
32
+ columns = definitions.to_h { |definition| [definition.name.to_s, definition.component_columns] }
33
+
34
+ %i[only except].each do |key|
35
+ next unless options.key?(key)
36
+
37
+ options[key] = Array(options[key]).flat_map { |name| columns.fetch(name.to_s) { name.to_s } }
38
+ end
39
+ options
40
+ end
41
+
42
+ # Each amount takes its atomic column's place; its symbol column drops out.
43
+ def amounts_in_place_of_columns(hash, definitions)
44
+ serialized = definitions.select { |definition| (definition.component_columns - hash.keys).empty? }
45
+ by_atomic_column = serialized.to_h { |definition| [definition.atomic_column, definition] }
46
+ symbol_columns = serialized.reject(&:fixed_symbol?).map(&:symbol_column)
47
+
48
+ hash.each_with_object({}) do |(key, value), result|
49
+ definition = by_atomic_column[key]
50
+ next result[definition.name.to_s] = public_send(definition.name) if definition
51
+
52
+ result[key] = value unless symbol_columns.include?(key)
53
+ end
54
+ end
55
+ end
56
+ end
57
+ end
@@ -7,7 +7,11 @@ require_relative "active_record/attribute_definition"
7
7
  require_relative "active_record/amount_validator"
8
8
  require_relative "active_record/type"
9
9
  require_relative "active_record/migration_methods"
10
+ require_relative "active_record/serialization"
11
+ require_relative "active_record/dirty"
10
12
  require_relative "active_record/model"
13
+ require_relative "active_record/calculations"
14
+ require_relative "active_record/persistence"
11
15
 
12
16
  class Amount
13
17
  # Optional Rails integration for ActiveRecord models and migrations.
@@ -47,6 +51,8 @@ class Amount
47
51
  end
48
52
 
49
53
  ::ActiveRecord::Base.extend(Model)
54
+ ::ActiveRecord::Base.extend(Calculations)
55
+ ::ActiveRecord::Base.extend(Persistence)
50
56
  ::ActiveRecord::Base.include(InstanceMethods)
51
57
  end
52
58
  end
@@ -75,7 +75,10 @@ class Amount
75
75
  ensure_scalar!(other)
76
76
  raise ZeroDivisionError if other.zero?
77
77
 
78
- build((BigDecimal(@atomic) / Amount.coerce_decimal(other)).to_i)
78
+ # In Rational, so the quotient is exact before it's truncated toward
79
+ # zero. BigDecimal division rounds the quotient to a limited
80
+ # precision, which for a large amount can be off by many atomic units.
81
+ build((Rational(@atomic) / Amount.coerce_decimal(other).to_r).truncate)
79
82
  end
80
83
  end
81
84
 
@@ -51,9 +51,26 @@ class Amount
51
51
  }
52
52
  end
53
53
 
54
+ # The exact compact string: whole units with exactly `decimals` places.
55
+ # Unlike `to_s`, it ignores the display settings and never rounds, so
56
+ # `Amount.parse` reads it back exactly.
57
+ #
54
58
  # @return [String]
59
+ # @example
60
+ # Amount.of_usdc("1.5").as_json # => "USDC|1.500000"
55
61
  def as_json(*)
56
- to_s
62
+ whole, fraction = atomic.abs.divmod(10**decimals)
63
+ number = decimals.zero? ? whole.to_s : "#{whole}.#{fraction.to_s.rjust(decimals, '0')}"
64
+
65
+ "#{symbol}|#{'-' if atomic.negative?}#{number}"
66
+ end
67
+
68
+ # Without ActiveSupport, the `json` library writes an object through
69
+ # `to_s`, so `to_json` goes through {#as_json} explicitly.
70
+ #
71
+ # @return [String]
72
+ def to_json(*args)
73
+ as_json.to_json(*args)
57
74
  end
58
75
  end
59
76
  end
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  class Amount
4
- VERSION = "0.1.0"
4
+ VERSION = "0.2.0"
5
5
  end
@@ -151,6 +151,14 @@ class AmountActiveRecordAmountValidatorTest < Minitest::Test
151
151
  refute greater_than_one_model.new(amount: "SOL|0.5").valid?
152
152
  end
153
153
 
154
+ def test_subclass_accepts_valid_inherited_amount
155
+ assert SubValidatedHolding.new(reserve: "USDC|1.25", amount: "USDC|100.00").valid?
156
+ end
157
+
158
+ def test_subclass_rejects_inherited_amount_with_wrong_symbol
159
+ refute SubValidatedHolding.new(reserve: "USDC|1.25", amount: "USD|100.00").valid?
160
+ end
161
+
154
162
  private
155
163
 
156
164
  def validated(**attributes)
@@ -184,8 +184,33 @@ class AmountActiveRecordAttributeDefinitionTest < Minitest::Test
184
184
  assert_equal 300, grouped_sums["USD"]
185
185
  end
186
186
 
187
+ def test_column_values_of_multi_symbol_amount
188
+ assert_equal({ "amount_atomic" => 1_500_000, "amount_symbol" => "USDC" },
189
+ definition(:amount).column_values(Amount.new("1.5", :USDC)))
190
+ end
191
+
192
+ def test_column_values_of_fixed_symbol_amount_omit_symbol_column
193
+ assert_equal({ "fee_atomic" => 250_000_000 }, definition(:fee).column_values(Amount.new("0.25", :SOL)))
194
+ end
195
+
196
+ def test_column_values_of_nil_multi_symbol_amount_keep_every_column
197
+ assert_equal({ "amount_atomic" => nil, "amount_symbol" => nil }, definition(:amount).column_values(nil))
198
+ end
199
+
200
+ def test_column_values_of_nil_fixed_symbol_amount
201
+ assert_equal({ "fee_atomic" => nil }, definition(:fee).column_values(nil))
202
+ end
203
+
204
+ def test_column_values_hold_atomic_as_integer
205
+ assert_kind_of Integer, definition(:amount).column_values(Amount.new(10**30, :SOL, from: :atomic))["amount_atomic"]
206
+ end
207
+
187
208
  private
188
209
 
210
+ def definition(name)
211
+ Holding.amount_attribute_definitions.fetch(name)
212
+ end
213
+
189
214
  def amount_written_holding
190
215
  Holding.new.tap { |holding| holding.amount = Amount.new("1.5", :USDC) }
191
216
  end
@@ -0,0 +1,165 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "../../test_helper"
4
+ require_relative "../../support/active_record_test_support"
5
+
6
+ class AmountActiveRecordCalculationsTest < Minitest::Test
7
+ include ActiveRecordTestSetup
8
+
9
+ # Two USDC holdings with SOL fees, one USD holding without a fee, and one
10
+ # holding with neither. Every holding's reserve is USDC|1.25.
11
+ def setup
12
+ super
13
+ Holding.create!(amount: "USDC|1.5", fee: "SOL|0.1")
14
+ Holding.create!(amount: "USDC|2", fee: "SOL|0.2")
15
+ Holding.create!(amount: "USD|3")
16
+ Holding.create!
17
+ end
18
+
19
+ def test_sum_amount_of_fixed_symbol
20
+ assert_equal Amount.new("0.3", :SOL), Holding.sum_amount(:fee)
21
+ end
22
+
23
+ def test_sum_amount_of_fixed_symbol_over_no_rows_is_zero
24
+ assert_equal Amount.new(0, :SOL), Holding.where(id: nil).sum_amount(:fee)
25
+ end
26
+
27
+ def test_sum_amount_of_fixed_symbol_on_none_is_zero
28
+ assert_equal Amount.new(0, :SOL), Holding.none.sum_amount(:fee)
29
+ end
30
+
31
+ def test_sum_amount_of_multi_symbol_with_one_symbol_in_scope
32
+ assert_equal Amount.new("3.5", :USDC), Holding.amount_in(:USDC).sum_amount(:amount)
33
+ end
34
+
35
+ def test_sum_amount_of_multi_symbol_over_no_rows_is_nil
36
+ assert_nil Holding.where(id: nil).sum_amount(:amount)
37
+ end
38
+
39
+ def test_sum_amount_with_mixed_symbols_raises_type_mismatch
40
+ assert_raises(Amount::TypeMismatch) { Holding.sum_amount(:amount) }
41
+ end
42
+
43
+ def test_sum_amount_with_mixed_symbols_names_the_symbols
44
+ assert_match(/amount has more than one symbol in scope: USD, USDC/,
45
+ error_from(Amount::TypeMismatch) { Holding.sum_amount(:amount) }.message)
46
+ end
47
+
48
+ def test_sum_amount_grouped_by_symbol_column
49
+ assert_equal({ "USD" => Amount.new("3", :USD), "USDC" => Amount.new("3.5", :USDC) },
50
+ Holding.group(:amount_symbol).sum_amount(:amount))
51
+ end
52
+
53
+ def test_sum_amount_of_fixed_symbol_grouped
54
+ assert_equal({ nil => Amount.new(0, :SOL), "USD" => Amount.new(0, :SOL), "USDC" => Amount.new("0.3", :SOL) },
55
+ Holding.group(:amount_symbol).sum_amount(:fee))
56
+ end
57
+
58
+ def test_sum_amount_grouped_by_two_columns_keys_by_array
59
+ assert_equal({ %w[USDC USD] => Amount.new("3", :USD), %w[USDC USDC] => Amount.new("3.5", :USDC) },
60
+ Holding.group(:reserve_symbol, :amount_symbol).sum_amount(:amount))
61
+ end
62
+
63
+ def test_sum_amount_grouped_by_sql_expression
64
+ assert_equal({ "USD" => Amount.new("3", :USD), "USDC" => Amount.new("3.5", :USDC) },
65
+ Holding.group("UPPER(amount_symbol)").sum_amount(:amount))
66
+ end
67
+
68
+ # `pluck` refuses a raw SQL string like this one unless it's wrapped in
69
+ # `Arel.sql`; Rails' `group(...).sum` accepts it.
70
+ def test_sum_amount_grouped_by_raw_sql_expression
71
+ assert_equal({ "none" => Amount.new(0, :SOL), "USD" => Amount.new(0, :SOL), "USDC" => Amount.new("0.3", :SOL) },
72
+ Holding.group("COALESCE(amount_symbol, 'none')").sum_amount(:fee))
73
+ end
74
+
75
+ def test_sum_amount_grouped_by_arel_node
76
+ assert_equal({ "USD" => Amount.new("3", :USD), "USDC" => Amount.new("3.5", :USDC) },
77
+ Holding.group(Holding.arel_table[:amount_symbol]).sum_amount(:amount))
78
+ end
79
+
80
+ def test_sum_amount_grouped_on_none_is_empty
81
+ assert_empty Holding.none.group(:amount_symbol).sum_amount(:fee)
82
+ end
83
+
84
+ def test_sum_amount_with_mixed_symbols_in_one_group_raises_type_mismatch
85
+ assert_raises(Amount::TypeMismatch) { Holding.group(:reserve_symbol).sum_amount(:amount) }
86
+ end
87
+
88
+ def test_sum_amount_grouped_by_association_raises_argument_error
89
+ assert_raises(ArgumentError) { ChildHolding.group(:parent).sum_amount(:fee) }
90
+ end
91
+
92
+ def test_sum_amount_grouped_by_association_names_its_foreign_key
93
+ assert_match(/group by parent_id, not the parent association/,
94
+ error_from(ArgumentError) { ChildHolding.group(:parent).sum_amount(:fee) }.message)
95
+ end
96
+
97
+ def test_sum_amount_of_inherited_amount
98
+ assert_equal Amount.new("0.3", :SOL), SubHolding.sum_amount(:fee)
99
+ end
100
+
101
+ def test_minimum_amount
102
+ assert_equal Amount.new("0.1", :SOL), Holding.minimum_amount(:fee)
103
+ end
104
+
105
+ def test_minimum_amount_over_no_rows_is_nil
106
+ assert_nil Holding.where(id: nil).minimum_amount(:fee)
107
+ end
108
+
109
+ def test_minimum_amount_with_mixed_symbols_raises_type_mismatch
110
+ assert_raises(Amount::TypeMismatch) { Holding.minimum_amount(:amount) }
111
+ end
112
+
113
+ def test_maximum_amount
114
+ assert_equal Amount.new("0.2", :SOL), Holding.maximum_amount(:fee)
115
+ end
116
+
117
+ def test_maximum_amount_grouped_by_symbol_column
118
+ assert_equal({ "USD" => Amount.new("3", :USD), "USDC" => Amount.new("2", :USDC) },
119
+ Holding.group(:amount_symbol).maximum_amount(:amount))
120
+ end
121
+
122
+ def test_average_amount_counts_only_rows_with_an_amount
123
+ assert_equal Amount.new("0.15", :SOL), Holding.average_amount(:fee)
124
+ end
125
+
126
+ def test_average_amount_truncates_toward_zero
127
+ holdings_with_atomic_fees(1, 2)
128
+
129
+ assert_equal Amount.new(1, :SOL, from: :atomic), Holding.average_amount(:fee)
130
+ end
131
+
132
+ def test_average_amount_of_negative_amounts_truncates_toward_zero
133
+ holdings_with_atomic_fees(-1, -2)
134
+
135
+ assert_equal Amount.new(-1, :SOL, from: :atomic), Holding.average_amount(:fee)
136
+ end
137
+
138
+ def test_average_amount_over_no_rows_is_nil
139
+ assert_nil Holding.where(id: nil).average_amount(:fee)
140
+ end
141
+
142
+ def test_average_amount_grouped_by_symbol_column
143
+ assert_equal({ "USD" => Amount.new("3", :USD), "USDC" => Amount.new("1.75", :USDC) },
144
+ Holding.group(:amount_symbol).average_amount(:amount))
145
+ end
146
+
147
+ def test_average_amount_of_group_without_amounts_is_nil
148
+ assert_nil Holding.group(:amount_symbol).average_amount(:fee).fetch("USD")
149
+ end
150
+
151
+ def test_average_amount_with_mixed_symbols_raises_type_mismatch
152
+ assert_raises(Amount::TypeMismatch) { Holding.average_amount(:amount) }
153
+ end
154
+
155
+ def test_rails_average_still_works
156
+ assert_equal BigDecimal("150000000"), Holding.average(:fee_atomic)
157
+ end
158
+
159
+ private
160
+
161
+ def holdings_with_atomic_fees(*atomics)
162
+ Holding.delete_all
163
+ atomics.each { |atomic| Holding.create!(fee: Amount.new(atomic, :SOL, from: :atomic)) }
164
+ end
165
+ end
@@ -0,0 +1,70 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "../../test_helper"
4
+ require_relative "../../support/active_record_test_support"
5
+
6
+ class AmountActiveRecordDirtyTest < Minitest::Test
7
+ include ActiveRecordTestSetup
8
+
9
+ def setup
10
+ super
11
+ @holding = Holding.create!(amount: "USDC|10.06", fee: "SOL|0.5")
12
+ end
13
+
14
+ def test_amount_changes_keys_a_changed_amount_by_name
15
+ @holding.amount = "USD|3"
16
+
17
+ assert_equal({ "amount" => [Amount.new("10.06", :USDC), Amount.new("3", :USD)] }, @holding.amount_changes)
18
+ end
19
+
20
+ def test_amount_changes_reports_a_cleared_amount
21
+ @holding.fee = nil
22
+
23
+ assert_equal({ "fee" => [Amount.new("0.5", :SOL), nil] }, @holding.amount_changes)
24
+ end
25
+
26
+ def test_amount_changes_keeps_other_attribute_changes
27
+ @holding.parent_id = 7
28
+
29
+ assert_equal({ "parent_id" => [nil, 7] }, @holding.amount_changes)
30
+ end
31
+
32
+ def test_amount_changes_of_unchanged_record_is_empty
33
+ assert_empty @holding.amount_changes
34
+ end
35
+
36
+ def test_amount_changes_reads_with_symbol_keys
37
+ @holding.amount = "USD|3"
38
+
39
+ assert_equal [Amount.new("10.06", :USDC), Amount.new("3", :USD)], @holding.amount_changes[:amount]
40
+ end
41
+
42
+ def test_saved_amount_changes_keys_a_saved_amount_by_name
43
+ @holding.update!(fee: "SOL|0.75")
44
+
45
+ assert_equal({ "fee" => [Amount.new("0.5", :SOL), Amount.new("0.75", :SOL)] }, @holding.saved_amount_changes)
46
+ end
47
+
48
+ def test_saved_amount_changes_of_created_record
49
+ assert_equal [nil, Amount.new("10.06", :USDC)], @holding.saved_amount_changes["amount"]
50
+ end
51
+
52
+ def test_changes_stay_keyed_by_column
53
+ @holding.amount = "USD|3"
54
+
55
+ assert_equal %w[amount_atomic amount_symbol], @holding.changes.keys
56
+ end
57
+
58
+ def test_saved_changes_stay_keyed_by_column
59
+ @holding.update!(fee: "SOL|0.75")
60
+
61
+ assert_equal %w[fee_atomic], @holding.saved_changes.keys
62
+ end
63
+
64
+ def test_saved_amount_changes_of_inherited_amount
65
+ sub = SubHolding.find(@holding.id)
66
+ sub.update!(fee: "SOL|0.75")
67
+
68
+ assert_equal [Amount.new("0.5", :SOL), Amount.new("0.75", :SOL)], sub.saved_amount_changes["fee"]
69
+ end
70
+ end
@@ -28,6 +28,38 @@ class AmountActiveRecordModelTest < Minitest::Test
28
28
  assert_includes holding.errors[:amount], "raw numeric assignment requires a fixed symbol"
29
29
  end
30
30
 
31
+ def test_subclass_inherits_amount_attribute_definitions
32
+ assert_equal %i[amount fee reserve], SubHolding.amount_attribute_definitions.keys
33
+ end
34
+
35
+ def test_subclass_resolves_inherited_atomic_column
36
+ assert_equal "fee_atomic", SubHolding.amount_atomic_column(:fee)
37
+ end
38
+
39
+ def test_subclass_resolves_inherited_component_columns
40
+ assert_equal %w[amount_atomic amount_symbol], SubHolding.amount_component_columns(:amount)
41
+ end
42
+
43
+ def test_subclass_adds_its_own_amount
44
+ assert_equal %i[amount fee reserve bonus], BonusHolding.amount_attribute_definitions.keys
45
+ end
46
+
47
+ def test_subclass_amount_does_not_reach_parent
48
+ refute_includes Holding.amount_attribute_definitions.keys, :bonus
49
+ end
50
+
51
+ def test_subclass_amount_does_not_reach_sibling
52
+ refute_includes SubHolding.amount_attribute_definitions.keys, :bonus
53
+ end
54
+
55
+ def test_model_without_amounts_has_no_definitions
56
+ assert_empty ::ActiveRecord::Base.amount_attribute_definitions
57
+ end
58
+
59
+ def test_definitions_are_not_readable_from_a_record
60
+ refute_respond_to Holding.new, :amount_attribute_definitions
61
+ end
62
+
31
63
  private
32
64
 
33
65
  def wrong_symbol_fee_holding
@@ -0,0 +1,53 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "../../test_helper"
4
+ require_relative "../../support/active_record_test_support"
5
+
6
+ class AmountActiveRecordPersistenceTest < Minitest::Test
7
+ include ActiveRecordTestSetup
8
+
9
+ def test_amount_column_values_replaces_multi_symbol_amount_with_its_columns
10
+ assert_equal({ "amount_atomic" => 1_500_000, "amount_symbol" => "USDC" },
11
+ Holding.amount_column_values("amount" => "USDC|1.5"))
12
+ end
13
+
14
+ def test_amount_column_values_replaces_fixed_symbol_amount_with_its_column
15
+ assert_equal({ "fee_atomic" => 250_000_000 }, Holding.amount_column_values("fee" => "SOL|0.25"))
16
+ end
17
+
18
+ def test_amount_column_values_accepts_symbol_keys
19
+ assert_equal({ "fee_atomic" => 250_000_000 }, Holding.amount_column_values(fee: "SOL|0.25"))
20
+ end
21
+
22
+ def test_amount_column_values_casts_numeric_for_fixed_symbol
23
+ assert_equal({ "fee_atomic" => 250_000_000 }, Holding.amount_column_values("fee" => 0.25))
24
+ end
25
+
26
+ def test_amount_column_values_accepts_an_amount
27
+ assert_equal({ "fee_atomic" => 250_000_000 }, Holding.amount_column_values("fee" => Amount.new("0.25", :SOL)))
28
+ end
29
+
30
+ def test_amount_column_values_passes_other_keys_through
31
+ assert_equal({ "fee_atomic" => 250_000_000, :parent_id => 7 },
32
+ Holding.amount_column_values("fee" => 0.25, :parent_id => 7))
33
+ end
34
+
35
+ def test_amount_column_values_keeps_every_column_of_nil_amount
36
+ assert_equal({ "amount_atomic" => nil, "amount_symbol" => nil }, Holding.amount_column_values("amount" => nil))
37
+ end
38
+
39
+ def test_amount_column_values_raises_for_wrong_fixed_symbol
40
+ assert_raises(Amount::TypeMismatch) { Holding.amount_column_values("fee" => "USDC|1") }
41
+ end
42
+
43
+ def test_amount_column_values_of_inherited_amount
44
+ assert_equal({ "fee_atomic" => 250_000_000 }, SubHolding.amount_column_values("fee" => 0.25))
45
+ end
46
+
47
+ def test_amount_column_values_rows_insert_with_insert_all
48
+ Holding.insert_all([Holding.amount_column_values("amount" => "USDC|1.5"),
49
+ Holding.amount_column_values("amount" => nil)])
50
+
51
+ assert_equal [Amount.new("1.5", :USDC), nil], Holding.order(:id).map(&:amount)
52
+ end
53
+ end
@@ -0,0 +1,75 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "../../test_helper"
4
+ require_relative "../../support/active_record_test_support"
5
+
6
+ class AmountActiveRecordSerializationTest < Minitest::Test
7
+ include ActiveRecordTestSetup
8
+
9
+ def setup
10
+ super
11
+ @holding = Holding.create!(amount: "USDC|10.06", fee: "SOL|1.123456789")
12
+ end
13
+
14
+ def test_serializes_amounts_in_place_of_their_columns
15
+ assert_equal %w[id amount fee reserve bonus_atomic parent_id], @holding.as_json.keys
16
+ end
17
+
18
+ def test_serializes_multi_symbol_amount_as_exact_compact_string
19
+ assert_equal "USDC|10.060000", @holding.as_json["amount"]
20
+ end
21
+
22
+ def test_serializes_fixed_symbol_amount_as_exact_compact_string
23
+ assert_equal "SOL|1.123456789", @holding.as_json["fee"]
24
+ end
25
+
26
+ def test_serializes_nil_amount_as_nil
27
+ assert_nil Holding.create!.as_json["fee"]
28
+ end
29
+
30
+ def test_serializable_hash_holds_the_amount
31
+ assert_equal Amount.new("1.123456789", :SOL), @holding.serializable_hash["fee"]
32
+ end
33
+
34
+ def test_only_takes_an_amount_name
35
+ assert_equal({ "fee" => "SOL|1.123456789" }, @holding.as_json(only: :fee))
36
+ end
37
+
38
+ def test_only_takes_amount_names_with_columns
39
+ assert_equal({ "id" => @holding.id, "amount" => "USDC|10.060000" }, @holding.as_json(only: %i[id amount]))
40
+ end
41
+
42
+ def test_except_takes_an_amount_name
43
+ assert_equal %w[id fee bonus_atomic parent_id], @holding.as_json(except: %i[amount reserve]).keys
44
+ end
45
+
46
+ def test_to_json_writes_amounts
47
+ assert_equal '{"fee":"SOL|1.123456789"}', @holding.to_json(only: :fee)
48
+ end
49
+
50
+ def test_keeps_columns_of_partly_selected_amount
51
+ assert_equal %w[id amount_atomic], Holding.select(:id, :amount_atomic).first.as_json.keys
52
+ end
53
+
54
+ def test_serializes_amounts_of_included_association
55
+ child = ChildHolding.create!(parent: @holding)
56
+
57
+ assert_equal({ "fee" => "SOL|1.123456789" }, child.as_json(only: :id, include: { parent: { only: :fee } })["parent"])
58
+ end
59
+
60
+ def test_serializes_inherited_amount
61
+ assert_equal "SOL|1.123456789", SubHolding.find(@holding.id).as_json["fee"]
62
+ end
63
+
64
+ def test_serializes_amount_a_subclass_adds
65
+ assert_equal "SOL|2.000000000", BonusHolding.create!(bonus: "SOL|2").as_json["bonus"]
66
+ end
67
+
68
+ def test_included_only_into_models_with_amounts
69
+ refute_includes ::ActiveRecord::Base.ancestors, Amount::ActiveRecord::Serialization
70
+ end
71
+
72
+ def test_included_once_per_model
73
+ assert_equal 1, BonusHolding.ancestors.count(Amount::ActiveRecord::Serialization)
74
+ end
75
+ end
@@ -121,6 +121,39 @@ class AmountCalculableTest < Minitest::Test
121
121
  assert_raises(ZeroDivisionError) { Amount.new(1, :USDC) / 0 }
122
122
  end
123
123
 
124
+ def test_division_by_integer
125
+ assert_equal Amount.new("5", :USDC), Amount.new("10", :USDC) / 2
126
+ end
127
+
128
+ def test_division_by_integer_truncates_toward_zero
129
+ assert_equal Amount.new(1, :USDC, from: :atomic), Amount.new(3, :USDC, from: :atomic) / 2
130
+ end
131
+
132
+ def test_division_of_negative_amount_truncates_toward_zero
133
+ assert_equal Amount.new(-1, :USDC, from: :atomic), Amount.new(-3, :USDC, from: :atomic) / 2
134
+ end
135
+
136
+ def test_division_by_decimal
137
+ assert_equal Amount.new("4", :USDC), Amount.new("10", :USDC) / BigDecimal("2.5")
138
+ end
139
+
140
+ def test_division_of_large_amount_by_integer_is_exact
141
+ assert_equal Amount.new((10**38) - 1, :SOL, from: :atomic),
142
+ Amount.new((3 * (10**38)) - 1, :SOL, from: :atomic) / 3
143
+ end
144
+
145
+ # BigDecimal division rounded this quotient, which came out 1429 atomic
146
+ # units off.
147
+ def test_division_of_large_amount_by_small_decimal_is_exact
148
+ assert_equal Amount.new(1_428_571_428_571_428_571_428_571_428_571_428_571_428_571_428_571_428_571_428_571, :SOL, from: :atomic),
149
+ Amount.new(10**40, :SOL, from: :atomic) / BigDecimal("0.000000000000000000007")
150
+ end
151
+
152
+ def test_division_of_large_negative_amount_by_small_decimal_is_exact
153
+ assert_equal Amount.new(-1_428_571_428_571_428_571_428_571_428_571_428_571_428_571_428_571_428_571_428_571, :SOL, from: :atomic),
154
+ Amount.new(-(10**40), :SOL, from: :atomic) / BigDecimal("0.000000000000000000007")
155
+ end
156
+
124
157
  def test_cross_type_addition_via_explicit_conversion
125
158
  gold = Amount.new("0.0001", :GOLD)
126
159
  usdc = Amount.new("100", :USDC)
@@ -53,18 +53,56 @@ class AmountSerializableTest < Minitest::Test
53
53
  assert_match(/missing key/, error_from(Amount::InvalidInput) { Amount.load({}) }.message)
54
54
  end
55
55
 
56
- def test_as_json_returns_compact_string
57
- assert_equal "USDC|1.50", Amount.new("1.5", :USDC).as_json
56
+ def test_as_json_returns_compact_string_with_all_decimals
57
+ assert_equal "USDC|1.500000", Amount.new("1.5", :USDC).as_json
58
58
  end
59
59
 
60
60
  def test_to_json_returns_quoted_compact_string
61
- assert_equal '"USDC|1.50"', Amount.new("1.5", :USDC).to_json
61
+ assert_equal '"USDC|1.500000"', Amount.new("1.5", :USDC).to_json
62
+ end
63
+
64
+ def test_as_json_keeps_digits_past_ui_decimals
65
+ assert_equal "SOL|1.123456789", Amount.new("1.123456789", :SOL).as_json
66
+ end
67
+
68
+ def test_as_json_pads_whole_amount_to_all_decimals
69
+ assert_equal "SOL|42.000000000", Amount.new("42", :SOL).as_json
70
+ end
71
+
72
+ def test_as_json_writes_zero_without_sign
73
+ assert_equal "SOL|0.000000000", Amount.new("-0", :SOL).as_json
74
+ end
75
+
76
+ def test_as_json_writes_negative_amount
77
+ assert_equal "SOL|-1.500000000", Amount.new("-1.5", :SOL).as_json
78
+ end
79
+
80
+ def test_as_json_writes_negative_smallest_unit
81
+ assert_equal "SOL|-0.000000001", Amount.new(-1, :SOL, from: :atomic).as_json
82
+ end
83
+
84
+ def test_as_json_writes_large_amount_exactly
85
+ assert_equal "SOL|123456789012345678901234567890.123456789",
86
+ Amount.new("123456789012345678901234567890.123456789", :SOL).as_json
87
+ end
88
+
89
+ def test_as_json_of_whole_symbol_has_no_decimal_point
90
+ Amount.register :TOKENS, decimals: 0
91
+
92
+ assert_equal "TOKENS|42", Amount.new(42, :TOKENS).as_json
93
+ end
94
+
95
+ def test_as_json_round_trips_through_parse
96
+ amounts = ["1.123456789", "-1.5", "0", "0.000000001", "98765432109876543210.987654321"]
97
+ .map { |value| Amount.new(value, :SOL) }
98
+
99
+ assert_equal amounts, amounts.map { |amount| Amount.parse(amount.as_json) }
62
100
  end
63
101
 
64
102
  def test_as_json_works_when_nested_in_hash
65
103
  hash = { amount: Amount.new("1.5", :USDC) }
66
104
 
67
- assert_equal({ "amount" => "USDC|1.50" }, JSON.parse(hash.to_json))
105
+ assert_equal({ "amount" => "USDC|1.500000" }, JSON.parse(hash.to_json))
68
106
  end
69
107
 
70
108
  def test_load_rejects_unknown_serialization_version
@@ -69,8 +69,38 @@ class PostgreSQLIntegrationTest < Minitest::Test
69
69
  assert_equal({ "USDC" => 1_500_000, "USD" => 300 }, Holding.group(:amount_symbol).sum(:amount_atomic))
70
70
  end
71
71
 
72
+ def test_postgresql_sum_amount_is_exact_past_64_bits
73
+ holdings_with_atomic_amounts(10**30, (10**30) + 1)
74
+
75
+ assert_equal (2 * (10**30)) + 1, Holding.sum_amount(:amount).atomic
76
+ end
77
+
78
+ def test_postgresql_average_amount_is_exact_past_64_bits
79
+ holdings_with_atomic_amounts(10**30, (10**30) + 3)
80
+
81
+ assert_equal (10**30) + 1, Holding.average_amount(:amount).atomic
82
+ end
83
+
84
+ def test_postgresql_sum_amount_of_fixed_symbol
85
+ Holding.create!(fee: "SOL|0.1")
86
+ Holding.create!(fee: "SOL|0.2")
87
+
88
+ assert_equal Amount.new("0.3", :SOL), Holding.sum_amount(:fee)
89
+ end
90
+
91
+ def test_postgresql_sum_amount_grouped_by_symbol_column
92
+ create_usdc_and_usd_holdings
93
+
94
+ assert_equal({ "USDC" => Amount.new("1.5", :USDC), "USD" => Amount.new("3", :USD) },
95
+ Holding.group(:amount_symbol).sum_amount(:amount))
96
+ end
97
+
72
98
  private
73
99
 
100
+ def holdings_with_atomic_amounts(*atomics)
101
+ atomics.each { |atomic| Holding.create!(amount: Amount.new(atomic, :SOL, from: :atomic)) }
102
+ end
103
+
74
104
  # The USDC holding; a USD holding is created alongside.
75
105
  def create_usdc_and_usd_holdings
76
106
  usdc = Holding.create!(amount: "USDC|1.50")
@@ -17,6 +17,8 @@ AmountTestSupport.register_active_record_types!
17
17
  t.amount :amount, null: true
18
18
  t.amount :fee, symbol: :SOL, null: true
19
19
  t.amount :reserve, precision: 40, default: "USDC|1.25", null: false
20
+ t.amount :bonus, symbol: :SOL, null: true
21
+ t.integer :parent_id
20
22
  end
21
23
  end
22
24
 
@@ -26,6 +28,20 @@ class Holding < ::ActiveRecord::Base
26
28
  has_amount :reserve
27
29
  end
28
30
 
31
+ # Inherits Holding's amounts unchanged.
32
+ class SubHolding < Holding
33
+ end
34
+
35
+ # Adds an amount of its own on top of Holding's.
36
+ class BonusHolding < Holding
37
+ has_amount :bonus, symbol: :SOL
38
+ end
39
+
40
+ # Belongs to another holding, for grouping by an association.
41
+ class ChildHolding < Holding
42
+ belongs_to :parent, class_name: "Holding", optional: true
43
+ end
44
+
29
45
  class ValidatedHolding < ::ActiveRecord::Base
30
46
  self.table_name = "holdings"
31
47
 
@@ -49,6 +65,10 @@ class ValidatedHolding < ::ActiveRecord::Base
49
65
  }
50
66
  end
51
67
 
68
+ # Inherits ValidatedHolding's amounts and validations unchanged.
69
+ class SubValidatedHolding < ValidatedHolding
70
+ end
71
+
52
72
  # Empty tables and the ActiveRecord test types before each test; an empty
53
73
  # registry after it.
54
74
  module ActiveRecordTestSetup
metadata CHANGED
@@ -1,14 +1,14 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: amounts
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.1.0
4
+ version: 0.2.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Seb Scholl
8
8
  autorequire:
9
9
  bindir: bin
10
10
  cert_chain: []
11
- date: 2026-11-02 00:00:00.000000000 Z
11
+ date: 2026-11-14 00:00:00.000000000 Z
12
12
  dependencies:
13
13
  - !ruby/object:Gem::Dependency
14
14
  name: bigdecimal
@@ -47,12 +47,16 @@ files:
47
47
  - lib/amount/active_record.rb
48
48
  - lib/amount/active_record/amount_validator.rb
49
49
  - lib/amount/active_record/attribute_definition.rb
50
+ - lib/amount/active_record/calculations.rb
51
+ - lib/amount/active_record/dirty.rb
50
52
  - lib/amount/active_record/locale/en.yml
51
53
  - lib/amount/active_record/migration_methods.rb
52
54
  - lib/amount/active_record/model.rb
55
+ - lib/amount/active_record/persistence.rb
53
56
  - lib/amount/active_record/railtie.rb
54
57
  - lib/amount/active_record/rspec.rb
55
58
  - lib/amount/active_record/rspec/matchers.rb
59
+ - lib/amount/active_record/serialization.rb
56
60
  - lib/amount/active_record/type.rb
57
61
  - lib/amount/compact.rb
58
62
  - lib/amount/concerns/allocatable.rb
@@ -85,8 +89,12 @@ files:
85
89
  - lib/generators/amount/active_record/templates/registry.rb.tt
86
90
  - test/amount/active_record/amount_validator_test.rb
87
91
  - test/amount/active_record/attribute_definition_test.rb
92
+ - test/amount/active_record/calculations_test.rb
93
+ - test/amount/active_record/dirty_test.rb
88
94
  - test/amount/active_record/migration_methods_test.rb
89
95
  - test/amount/active_record/model_test.rb
96
+ - test/amount/active_record/persistence_test.rb
97
+ - test/amount/active_record/serialization_test.rb
90
98
  - test/amount/active_record/type_test.rb
91
99
  - test/amount/active_record_test.rb
92
100
  - test/amount/compact_test.rb