8 suggestions
Optional improvements
[suggestion] · Qt property compatibility leaks implicit integer conversion to C++ callers
BitcoinAmountField::value() returns implicitly convertible QAmount, bypassing the new amount restrictions for GUI callers; no current caller computing or sending a wrong amount was found.
Location: src/qt/bitcoinamountfield.h:35 (head).
Details and suggested fix
Both amount-widget getters return QAmount, whose implicit operator qint64() permits if (field->value()), field->value() <= 0, floating-point multiplication and amount-by-amount multiplication through built-in operators. The current SendCoinsEntry::validate() correctly uses <= 0*sats, but the raw-integer form would still compile. Keep value() returning CAmount and give Q_PROPERTY a separate reader, such as qint64 valueSats() const { return value().Int(); }. The property can retain its name, type and existing setValue(qint64) writer. This removes QAmount; deliberate conversions such as the custom-fee settings cast would use .Int().
[suggestion] · CAmount construction bypasses unsigned narrowing checks
The class loses brace-initialization narrowing checks and retains pre-existing unsigned-promotion hazards; no current caller supplying a negative amount or out-of-range unsigned value through these paths was found.
Location: src/consensus/amount.h:39 (head).
Details and suggested fix
non_bool_integral accepts uint64_t, and m_sats(sats) converts it without a list-initialization narrowing check. Consequently, CAmount{u64} accepts a non-constant operand that the typedef rejected. The scalar *, / and % operators also evaluate their expressions using the usual signed/unsigned promotions before constructing the result, so division of a negative amount by uint64_t can produce a positive quotient. That arithmetic hazard is unchanged from base. Constrain construction and scalar operands to integral types whose full range fits int64_t, and require checked int64_t conversions at intentional unsigned sites. For example, FeeFrac::EvaluateFee already documents its result-in-range precondition and guards its unsigned fast path with a non-negative fee check.
[suggestion] · The BTC test helper makes fractional targets platform-dependent
On extended-precision long double targets, 25.33 * BTC and 1.9 * BTC truncate one satoshi below their previous values, making the coin-selection fixtures platform-dependent; no failing assertion was established.
Location: src/wallet/test/coinselector_tests.cpp:39 (head).
Details and suggested fix
BTCUnit::operator* accepts long double, but the unsuffixed literals first round to double before promotion. With binary64 double and 80-bit or quad long double, truncating the products gives 2532999999 and 189999999 satoshis, whereas the previous 25.33L * COIN and 1.9L * COIN give 2533000000 and 190000000. When both floating-point types have double precision, the products round back to the exact integers. These fixtures feed tests with exact selected-input and attempt-count assertions. Replace the fractional expressions with exact integer arithmetic, such as 2533 * COIN / 100 and 19 * COIN / 10, and remove the floating-point helper.
[suggestion] · Compile-time amount restrictions lack regression coverage
The updated amount_tests.cpp checks runtime values but never asserts that forbidden construction, comparison or multiplication expressions stay ill-formed.
Location: src/consensus/amount.h:38 (head).
Details and suggested fix
The existing checks exercise valid expressions, so they do not protect the rejection behavior supplied by the deleted default constructor, explicit integral constructor and constrained operators. Add static_asserts rejecting default construction, construction from bool, double and long double, and implicit conversion from int64_t, alongside a positive construction check. Use small templated requires-expression helpers to reject CAmount * CAmount, CAmount * double and CAmount < int, while accepting CAmount * int and CAmount + CAmount. These checks would detect accidental relaxation of the interface without changing runtime behavior.
[suggestion] · USDT amount arguments no longer have their documented scalar type
Documented int64 tracepoint arguments now receive CAmount objects, leaving their encoding dependent on unverified class handling in external sys/sdt.h; no build or decoding failure was established.
Location: src/wallet/spend.cpp:1480 (head).
Details and suggested fix
With ENABLE_TRACING, TRACEPOINT forwards arguments unchanged to STAP_PROBEV. The create-transaction fee conditionals, selected-coin amounts and mempool fee arguments therefore reach that macro as CAmount objects rather than the previous int64_t values. The external header determines operand handling and size/signedness metadata. Extract .Int() from each amount argument, including the complete conditional expressions, to preserve the documented scalar interface without depending on class-operand support. The updated UTXO-cache probes in coins.cpp already use this conversion.
[suggestion] · The CAmount IPC builder bypasses integer-range checks
The current Int64 amount mappings are safe, but the custom CustomBuildField bypasses checks that normally reject a narrower wire type.
Location: src/ipc/capnp/common-types.h:150 (head).
Details and suggested fix
The generic builder calls BuildPrimitive, whose integral overload asserts that the Cap'n Proto field covers the C++ value type's full range. The new amount overload instead calls output.set(value.Int()) directly. An amount mapped to Int32 would consequently narrow at the setter rather than fail compilation, and the reader's widening conversion would not catch that mismatch. Restore the existing invariant with output.set(BuildPrimitive(invoke_context, value.Int(), TypeList<decltype(output.get())>()));. This preserves the behavior of the current Int64 mappings.
[suggestion] · Orphanage resource ratios are now typed as monetary amounts
Changing FeeFrac::fee to CAmount makes latency counts and memory usage require monetary wrappers and a 1*sats ratio threshold, although the computed DoS scores are unchanged.
Location: src/node/txorphanage.cpp:166 (head).
Details and suggested fix
GetDosScore() constructs amounts from m_total_latency_score and m_total_usage, while LimitOrphans() expresses the dimensionless ratio-one threshold as FeeFrac{1*sats, 1}. These values represent resource accounting, not money, so the new wrappers make CAmount identify non-monetary quantities at existing call sites. Use a non-monetary ratio representation for the orphanage, preserving the current wide cross-product comparisons and reversed-denominator tie-break. That keeps FeeFrac fee-typed without labeling counts and bytes as satoshis.
[suggestion] · Fee-delta insertion adds a lambda and a second map lookup
PrioritiseTransaction() hand-codes get-or-insert-zero, which std::map::try_emplace provides directly without changing fee-delta behavior.
Location: src/txmempool.cpp:682 (head).
Details and suggested fix
For a previously unseen transaction ID, the lambda searches mapDeltas with find() and then searches it again through emplace(). The enclosing scope already holds cs. Replace the lambda with CAmount& delta{mapDeltas.try_emplace(hash, 0*sats).first->second};. This preserves the existing value when present and constructs zero only for a missing key, without requiring a default constructor or an additional lock annotation. The saturation, mempool-entry update and zero-delta erase remain unchanged.
Background
Ralph's summary of historical context for the behaviour affected by this change. The historical record reviewed here is incomplete.
Documented decisions
The original typedef was a deliberate compromise: name monetary values explicitly while making unchanged behavior easier to verify. In the 2014 class proposal, reviewers emphasized limited testing and review capacity, identical int64_t arithmetic—including division and rounding—and the risk of broad consensus-sensitive changes. The class proposal was closed in favor of the typedef proposal.
The pinned base still uses typedef int64_t CAmount; the head introduces a class throughout consensus, node, wallet, and interface code. Historically, the distinction was not merely coding style: introducing an abstraction and preserving existing monetary semantics were separate questions requiring different levels of verification.
Source 1 · Source 2 · Source 3 · Source 4 · Source 5
Compiler-enforced monetary semantics were also an explicit historical goal. The original class author argued that a typedef leaves hidden assumptions about integer representation and permits new dependencies to appear undetected; a restricted arithmetic API and explicit conversions would expose those assumptions. Later discussion identified analyzability and future type-safety improvements as benefits for Bitcoin itself, distinct from the original motivation of sharing code with other chains.
The head's explicit integral-only constructor, exclusion of bool, amount-specific comparisons, and explicit Int() extraction address this historical distinction between naming a type and enforcing its interface. The older motivation supports understanding the abstraction's purpose, not a conclusion about the present implementation.
Source 1 · Source 2 · Source 3 · Source 4
Exact decimal conversion at interfaces was introduced to avoid deviations from passing monetary values through floating point. The 2015 AmountFromValue/ValueFromAmount change used UniValue's string representation and fixed-point parsing and formatting to eliminate double-to-integer and integer-to-double conversions.
The affected RPC path still parses decimal text into int64_t, explicitly constructs CAmount, and then checks MoneyRange. This history explains why banning implicit floating-point construction serves a different purpose from accepting decimal BTC amounts at an API boundary: decimal input can be converted exactly without making floating-point arithmetic part of the amount abstraction.
MAX_MONEY is a consensus-critical validity bound, not a calculation of the actual circulating or eventual money supply. Its historical explanatory comment expressly warns that changing this sanity check could cause a fork in unusual circumstances involving coin-creation or overflow behavior.
Both pinned versions retain MAX_MONEY = 21,000,000 * COIN and a separate MoneyRange predicate. Validation checks individual outputs and accumulated totals, and input validation separately checks accumulated inputs and fees. A representational refactor therefore interacts with established consensus checks whose meaning is independent of whether CAmount is a typedef or class.
Negative monetary quantities have deliberate non-consensus uses. The 2016 negative-feerate discussion explained that prioritisetransaction adjustments can precede transaction acceptance, that applying -X and then X should restore the starting state, and that flooring adjusted fees at zero would discard transaction ordering information. The associated patch corrected platform-dependent signed/unsigned arithmetic and documented that CAmount can be negative.
The head retains a signed int64_t representation and permits negative CAmounts while MoneyRange rejects negative valid-money values. The transaction representation also retains its -1 null-output sentinel. This helps explain why a general amount type has historically covered more than the range of valid transaction output values.
Historical amount-type discussions distinguished core arithmetic and serialization from human-facing conversion. Pieter Wuille argued for a minimally dependent core-data-structures library and against embedding human formatting or conversion utilities in the money type. The proposal subsequently moved FormatMoney and ParseMoney back into util; serialization as int64_t was discussed as an appropriate responsibility of the amount abstraction.
The head adds serialization of CAmount's underlying integer while FormatMoney, ParseMoney, and RPC fixed-point parsing remain separate. The relevant historical constraint is dependency separation and preserving protocol representation, not a blanket objection to encapsulating amounts.
Source 1 · Source 2 · Source 3 · Source 4
Ralph's inferences
The affected behavior separates three concerns: which expressions programmers may write, which values the representation can hold, and which values consensus accepts. The head strengthens the first concern without turning every constructed CAmount into an already-validated monetary value.
The class requires explicit initialization, restricts construction and arithmetic, and introduces the sats unit, but still stores a signed integer and leaves MoneyRange and transaction-level checks separate. Consequently, compile-time type safety, negative internal bookkeeping, and consensus range enforcement should be understood as distinct design constraints rather than interchangeable protections.