Money, currency rates and dated parameters
base supplies the money services of hook H41 and the dated parameter table of hook H35. Everything below is
exact decimal arithmetic: no f64 appears on any path. Design and decisions:
docs/design/m3-base-c-money.md; contract: ADR 0046 D1-D3.
Exact arithmetic and rounding
Section titled “Exact arithmetic and rounding”erp_sdk::money holds the pure primitives (no database, also built for WASM). A quotient stays an exact ratio
until you name a rounding boundary; the mode is always explicit.
use erp_sdk::Decimal;use erp_sdk::money::{ExactRatio, Increment, RoundingMode, canonical_string, parse_decimal};
# fn main() -> Result<(), erp_sdk::money::MoneyError> {// 24,000,000 x 11/12 is 22,000,000 before any rounding; 1/3 never becomes a finite decimal.let share = ExactRatio::quotient(Decimal::from(11), Decimal::from(12))?;let wages = ExactRatio::from_decimal(parse_decimal("24000000")?)?;let owed = wages.checked_mul(&share)?;assert_eq!(owed.to_string(), "22000000");let third = ExactRatio::quotient(Decimal::ONE, Decimal::from(3))?;assert_eq!(third.to_string(), "1/3");
// Currency rounding: half away from zero to an increment (a cash increment works too).let cent = Increment::new(parse_decimal("0.01")?)?;let rounded = cent.quantize(parse_decimal("2.675")?, RoundingMode::HalfAwayFromZero)?;assert_eq!(canonical_string(rounded), "2.68");let nickel = Increment::new(parse_decimal("0.05")?)?;assert_eq!(canonical_string(nickel.quantize(parse_decimal("1.03")?, RoundingMode::HalfAwayFromZero)?), "1.05");
// `is_zero` rounds the amount you give it; `compare` rounds both sides first. They differ:let (a, b) = (parse_decimal("0.006")?, parse_decimal("0.002")?);assert!(cent.is_zero(a - b, RoundingMode::HalfAwayFromZero)?);assert_ne!(cent.compare(a, b, RoundingMode::HalfAwayFromZero)?, std::cmp::Ordering::Equal);# Ok(())# }Refused, never rounded to fit: a numerator or denominator over 4096 bits, a zero denominator, a zero or negative
increment, a quantized result outside the decimal range (coefficient below 2^96, at most 28 decimals), a decimal
text with an exponent, whitespace, +, more than 64 bytes or more than 28 decimals. Money errors convert to
Validation errors.
Rates and conversion
Section titled “Rates and conversion”res.currency.rate stores, per currency, root company (or none: shared) and day, the rate as units of the currency
per unit of the company currency (numeric, exact, strictly positive). Rules of RateBook:
- Rates belong to the root company of the company you pass; a root company rate wins over a shared one.
- The candidate is the latest rate strictly before the date (Odoo 20;
SPEC-BASE-061), or on or before it withRateDateRule::OnOrBefore. - With no earlier rate, the earliest later one is used and marked
RateOrigin::LaterFallback. - The company’s own currency needs no row (rate one,
RateOrigin::ReferenceCurrency). - Any other currency without a rate is a
UserErrornaming currency, company and date. There is no rate of one.
use erp_addon_base::money::{self, RateBook, RoundingTable};use erp_sdk::money::RateDateRule;use erp_sdk::prelude::*;
# async fn demo(env: &Env, tx: &mut Transaction, usd: RecId, eur: RecId, company: RecId, day: Date)# -> Result<()> {// One call: exact product, rounded once to the target currency (half away from zero).let eur_amount = money::convert(env, tx, Decimal::from(100), usd, eur, company, day).await?;
// Many pairs: one book (two statements), then pure lookups. The snapshot names the rates used.let book = RateBook::load(env, tx, company, day, RateDateRule::StrictlyBefore, &[usd, eur]).await?;let snapshot = book.snapshot(usd, eur)?;let exact = snapshot.convert_exact(Decimal::from(100))?;
// Per-currency rounding helpers.let table = RoundingTable::load(env, tx, &[eur]).await?;let eur_rounding = table.get(eur)?;assert_eq!(eur_rounding.round(eur_amount)?, eur_amount);let _ = (exact, eur_rounding.is_zero(eur_amount)?);# Ok(())# }The caller needs read access to res.currency and res.currency.rate and the company must be one of the caller’s
companies; the rate statement itself reads the root company’s rows directly, as Odoo’s sudo() read does.
convert_with returns the amount, the unrounded ExactRatio and the FxSnapshot to store with a booking.
Rate types
Section titled “Rate types”Every rate belongs to a rate type (res.currency.rate.type, ADR 0140 D2): spot, monthly_average, closing,
historical, budget and tax are seeded, with a stable unique code. A rate is unique per currency, company, type
and day; a rate created without a type is a spot rate, and a type that still has rates cannot be deleted. Each type
carries its date rule (strictly_before for spot, historical and budget; on_or_before for tax, monthly_average and
closing) and a later_fallback flag (only spot).
The default spot type cannot be deleted, assigned a different code (or cleared), or archived, even before it has rates. These operations return a UserError naming spot; a mixed-recordset operation is refused as a whole. Its label and sequence remain editable, and writing the same code or setting it active is allowed. Other types retain their ordinary lifecycle rules.
RateBook::load is unchanged: it reads spot rows under the rule you pass and keeps the earliest-later fallback.
RateBook::load_typed reads one named type under that type’s rule and fallback:
use erp_addon_base::money::RateBook;use erp_sdk::prelude::*;
# async fn demo(env: &Env, tx: &mut Transaction, usd: RecId, idr: RecId, company: RecId, day: Date)# -> Result<()> {let book = RateBook::load_typed(env, tx, company, day, "tax", &[usd, idr]).await?;assert_eq!(book.rate_type().code(), "tax");let snapshot = book.snapshot(usd, idr)?; // a missing tax rate is a UserError naming "Rate type: tax."# let _ = snapshot;# Ok(())# }Lookups never leave their type: a missing tax rate is an error, never a spot rate. An unknown type code is Missing; an archived type is
still read. FxSnapshot does not carry the type; the booking that freezes evidence records
book.rate_type().id() itself. Upgrading a database that predates rate types gives every
existing rate the spot type (base 1.6 pre-migration). A forced re-initialisation (reinit) of a populated rate table skips that migration and is refused by the schema step,
and a rate table above the large-table threshold needs the manual key change the schema step names. Per-company
date-rule overrides and rate coverage certificates belong to later slices.
Decimal precision
Section titled “Decimal precision”decimal.precision rows name a usage (unique) with 0 to 28 digits. precision_get answers Odoo’s default 2 for
an unconfigured usage; precision_defined returns None instead, for callers that must not accept the default.
The lookup reads the table as the system (administrator-only table, public digits), so any user can resolve a usage.
field_scale(env, tx, "model", "field") resolves one field: Places(n) for fixed or named digits, Unrounded
for digits = 0, Currency { currency_field } for a monetary field.
Native field descriptions now resolve named precision from the table too. fields_get is async:
pass a mutable transaction and await the description. Only selected readable fields whose digits
attribute is requested trigger this metadata lookup. Cached digits live only in that transaction;
creating, changing or deleting precision rows invalidates them, and rollback discards them.
Missing usages still resolve to (16, 2); lookup failures are returned to the caller.
Named-digit writes follow the scale rejection policy below; fixed-digit rounding remains unchanged.
use erp_sdk::{Records, Result, Transaction};
# async fn describe_price(items: &Records, tx: &mut Transaction) -> Result<()> {let fields = items.fields_get(tx, Some(&["price"]), Some(&["digits"])).await?;if let Some(price) = fields.get("price") { let _digits = price.get("digits");}# Ok(())# }Monetary field mutation
Section titled “Monetary field mutation”A monetary field uses its resolved currency_field to round amounts through the
base addon’s exact increment service, half away from zero. Create inputs and
computed outputs are normalized before dependent computations consume them;
typed set, dynamic set_value, and write share this conversion path. Default,
related and delegated currencies are resolved from the same call’s final values.
Without a currency, the Decimal keeps its precision. A currency-only write keeps
the current amount; assign the amount again when it needs rounding in the new currency.
The resolved currency field must be a many2one to res.currency, including when
inherited or related; a different field kind or comodel is rejected during registry
composition. Related currency paths may traverse many2one hops only; a one2many
or many2many hop is rejected even if the path ends in res.currency.
A shared write of zero or null skips currency admission and rounding, so it can clear
amounts across different currencies. For a shared nonzero amount, only non-null currency
ids count: no currency preserves precision, one real currency rounds the value for the
whole set (including rows without a currency), and distinct real currencies return
Validation. A same-call currency replacement for the whole recordset can resolve that
ambiguity. Independent create rows and compute outputs may use different currencies.
Currency identity and rounding-data lookup use narrowly scoped sudo, so a hidden
currency field or denied currency read alone does not block amount normalization.
The amount mutation still needs the caller’s model/field write access, record rules
and company admission; currency lookup grants no amount-write rights. Computed output
publication retains its declared compute_sudo environment and company bounds,
including related/delegated native currency computes. If that compute needs a denied
input, normalization returns Access; result-lookup sudo does not grant input access.
Parity: divergent — ADR 0087. This intentionally differs from upstream sudo
currency access. Supplied in-memory new-record amounts and monetary defaults are also
normalized before cache publication and dependent consumption, a stronger contract
than upstream new() with validation disabled (Parity: divergent — ADR 0087).
Rounding is not cached across operations or rollback. These r1 requirements are
recorded in ADR 0087; implementation validation is tracked in the monetary
design/readiness note.
Explicit/default zero or null amounts do not force currency precomputation solely for rounding; ordinary declared dependencies still apply. Onchange normalizes scalar amounts before cache publication and dependent computation, including same-call currencies and staged relation links in root, persisted-origin and nested forms. First calls for new forms use staged native currency inputs, including non-triggering reads; later calls preserve the existing currency unless a declared dependency changes. No-currency values keep their precision; failures preserve form isolation.
When a declared dependency changes, synchronous currency computes use staged scalar
inputs before rounding. Non-triggering reads alone keep the stored currency;
comparison uses normalized dependency values and only affected records are projected.
Initial in-memory fills evaluate staged inputs without caching provisional defaults.
An async currency compute joins same-call monetary admission only when it is
registered candidate (see Candidate currency computes).
For a nonzero, non-null amount, a same-call dependency change to an async currency
compute without candidate, or an explicit create amount needing such a late currency,
returns Programming before amount publication; the message names the candidate
flag as the fix. Async
currency values already computed from unchanged inputs remain readable.
Candidate currency computes
Section titled “Candidate currency computes”#[compute(candidate, depends = ["selected_currency_id"])]async fn _currency( this: &RecordSet<Invoice>, tx: &mut ReadTx<'_>, out: &mut Assign<'_, Invoice>,) -> Result<()> { let selected = tx.mapped(this, Invoice::SELECTED_CURRENCY_ID).await?; for (i, currency) in selected.into_iter().enumerate() { out.set(i, Invoice::CURRENCY_ID, currency)?; } Ok(())}A candidate compute is an async compute that receives ReadTx, a read-only view of
the transaction, instead of &mut Transaction. The view offers get / mapped (ORM
reads) and query (guarded SQL, see below). It has no write, no extension<T>(), no
after_commit and no way back to the mutable transaction, so none of those compile.
Rules:
- Visibility. ORM reads of the compute’s own batch show the staged values of its
declared
dependsandreads. Reading another field of the batch is aProgrammingerror: declare it. ORM reads of other records see the transaction as it is before the mutation. SQL sees the database as it was before the mutation: it never sees the staged inputs or cache writes not yet flushed. Compute from the declared fields; use SQL only for other rows. - SQL guard.
queryis meant forSELECTstatements and refuses, withProgramming, data-changing keywords,SELECT ... INTO, locking clauses (FOR UPDATE,FOR SHARE),set_config, the advisory-lock anddblinkfamilies,nextval,setval,pg_sleep,lo_*functions, and text that cannot be read with certainty. This is a lexical deny-list, not a proof that a statement is read-only: aSELECTthat calls a volatile function of your own, or one the list does not name, is not caught. Keep candidate SQL to plain reads. - Direct fields only. A candidate may not declare dependencies or reads through a
relation (
a_id.b); the registry refuses it when it is built. - Reads of other records.
get/mappedof records outside the batch read through the transaction under the usual rules, so they can trigger those records’ own computes. Reads of the compute’s own batch from the staged values skip the field read checks that the lazy recompute path applies. Both points are pending lead confirmation (ADR 0087). - Registration.
candidateneeds anasync fn, cannot be anoverrideand has nosuper(), and its second parameter is&mut ReadTx<'_>; each is a compile error. A candidate and a non-candidate implementation of one method, or two implementations of a candidate method, are a registry-build error. - Execution. On create the candidate runs on the precompute synthetic ids, so no INSERT
precedes admission. It runs once per accepted mutation: its result is used for admission
and then published with the write, with no rollback or replay. Recompute chunks
(
recompute_batch) each run it once; admission is over the whole recordset, and amounts are published only after every currency is admitted. A provider error leaves nothing published or inserted. Onchange runs it for the preview only and memoizes nothing, so a later lazy read may run it again (an exception to “once per accepted mutation”, pending lead confirmation). - Access.
compute_sudo, the caller’s access checks and the narrow currency-lookup elevation are unchanged: withcompute_sudo = falsean input the caller may not read is anAccesserror; amount-write rights are not elevated.
In-memory amounts accept persisted currencies. An in-memory currency is refused
with Programming before publication (support for new in-memory currencies is planned). A present currency requires the private native
res.currency._round_monetary adapter; absence is an error rather than unrounded success.
Upsert compatibility: all typed and dynamic business-key upserts on models containing a monetary field are refused before key planning or SQL, including empty calls and operations which omit the monetary field. Use ordinary create/write until rounding is integrated with atomic conflict updates and accumulation. This restriction is accepted in ADR 0087.
Size bounds of one monetary operation
Section titled “Size bounds of one monetary operation”One write, create, default fill, new-record or onchange call that stages monetary
values, and every create on a model with a monetary field (its own or through _inherits), is
bounded: at most 200,000 target records and at most 2,000,000 staged
monetary cells. A cell is one monetary field of one record that the operation actually
stages (the fields you write or supply, plus the computed monetary outputs of a create or
recompute and the monetary inputs a same-call currency projection stages again); a model with
many monetary fields only counts the ones present. An operation over either bound is refused
with Validation, naming the limit, before
anything is published: the database and the written fields are untouched, and the cache and pending recomputes are as they were, with one documented exception: a refusal caused only by cells that a same-call currency projection adds can come after a stored sibling’s pending recompute (of an editable computed monetary field) was brought up to date in the cache. Split a
bulk import or a mass update into several calls (the JSON-2 API already accepts at most 100,000
create documents per call). The bound includes reads that fill monetary defaults of more than
200,000 uncached in-memory records. The numbers are internal constants, not part of the Rust API.
Odoo has no such bound (Parity: divergent, lead decision 2026-10-31); operations of that size that
were admitted before are refused now.
Dated parameters
Section titled “Dated parameters”ir.dated.parameter rows give a key (lower-case words joined by dots), an optional company, date_from, an optional
date_to (both ends inclusive, empty is unbounded) and a typed value (decimal, integer, boolean, text).
Periods of one key in one scope cannot overlap; the database enforces it. The nearest scope wins: the company’s own value, then its parent’s up to the root company
(a branch inherits from its root and may override it), then the shared one; a date with nothing in force is a UserError.
use erp_addon_base::dated_parameter::resolve_many;use erp_sdk::prelude::*;
# async fn demo(env: &Env, tx: &mut Transaction, company: RecId, day: Date) -> Result<()> {// One search for all keys the rule or report needs; bind `entries()` as variables.let rates = resolve_many(env, tx, &["payroll.pension_rate", "payroll.max_lines"], company, day).await?;let pension: Decimal = rates.decimal("payroll.pension_rate")?;let max_lines: i64 = rates.integer("payroll.max_lines")?;for (key, value) in rates.entries() { let _ = (key, value);}let _ = (pension, max_lines);# Ok(())# }The reader goes through the ORM search of the model, so access rights and record rules apply, and the company must be one of the caller’s.
Named digits on writes
Section titled “Named digits on writes”A numeric field declared with digits = "Product Price" uses the transaction-visible
decimal.precision value as a write limit. Excess significant fractional digits raise a
Validation error naming the model, field, usage and permitted digits. The ORM does not round
such values. 1.2300 fits a two-place usage because trailing zeroes are lossless. Apply the
appropriate explicit rounding rule before writing values produced by a conversion.
Typed/dynamic mutations, defaults, stored computed outputs and upserts obey this admission
boundary. Fixed-digit fields retain their existing rounding contract; unrounded numeric fields
retain exact values. The metadata cache’s Transaction::set_precision override does not alter
authoritative write policy. Unknown usages and an absent precision model retain the documented
two-place default; an installed adapter that fails is an error rather than a fallback.
Precision lookups remain a private base service. Applications do not gain access to the precision table through writing a field. The write cache belongs to one transaction and is cleared by precision mutations, invalidation and rollback. Existing transactions retain their PostgreSQL isolation snapshot; a new transaction sees committed configuration. A database-wide guard against lowering a setting over historical rows remains an outstanding ADR 0079 D6 obligation.
Wide grids and canonical fractions
Section titled “Wide grids and canonical fractions”A carrying value can need a coefficient larger than Decimal’s 96-bit range. GridValue
keeps a signed coefficient below 2^256 and an explicitly selected scale from 0 through 28.
It is distinct from booked money. GridValue::quantize uses HalfAwayFromZero and returns
both the finite value and the exact signed precision remainder:
use erp_sdk::money::{CanonicalFraction, ExactNumericError, GridValue};
# fn main() -> Result<(), ExactNumericError> {let third = CanonicalFraction::parse("1", "3")?;let result = GridValue::quantize(third.as_ratio(), 18)?;assert_eq!(result.value().to_string(), "0.333333333333333333");assert_eq!(result.remainder().as_ratio().to_string(), "1/3000000000000000000");# Ok(())# }The chosen scale is part of the numerical policy. Parsing and rescale refuse nonzero
finer digits and coefficient overflow; they never round to fit. Canonical output removes
trailing zeroes, and negative-zero input is refused. checked_add and checked_sub
retain the left operand’s grid and require the right operand to rescale exactly.
CanonicalFraction::parse admits canonical signed integer text for the numerator and
positive denominator, each below 2^4096. It rejects non-reduced pairs and accepts zero only
as 0/1. from_ratio retains an already validated arithmetic result. The representation
has no unchecked raw constructor or direct deserialization.
With the database feature enabled, bind GridValue and the fraction’s numerator() and
denominator() directly as numeric parameters. Decode both fraction components as
CanonicalInteger and call CanonicalFraction::new on the complete pair. A component
alone is not a valid fraction. Numeric decoding returns minimal significant scale;
rescale a decoded grid value to its frozen policy before using it. Admit a decoded carry
with validate_carry(&increment): it uses the larger of scale 18 and the normalized
increment scale, enforces the 256-bit coefficient bound, and admits signed values up to
half the increment. An odd increment at the finest grid may have an unrepresentable
half-increment endpoint, which is refused rather than rounded.
erp_sql::exact_numeric supplies grid_check, carry_check, and fraction_check for
unconstrained numeric columns. They quote validated column names and reject invalid
required values explicitly, including NULL and non-finite values. Grid checks take an
explicit nullable-column flag. These definitions do not install constraints or authorize
writes; the owning addon must install them and protect complete-pair writes. SQL sees
normalized numeric values, so lexical negative zero must be rejected at text admission.