Currency¶
Purpose¶
How the backend represents amounts and currencies, and how a member's primary currency is chosen. Read this before storing, validating or summing any amount.
Mental model¶
An amount is always an int64 count of minor units plus an ISO 4217 code:
{"amount_minor": 1050, "currency": "USD"} is 10.50 US dollars, and
{"amount_minor": 1050, "currency": "JPY"} is 1,050 yen. There are no floats,
no decimal columns and no unit-less amounts. Two currencies never mix:
arithmetic across currencies is an error, and the only conversion is the
approximate one at a reference rate (see Conversion).
The currency package¶
backend/internal/platform/currency is the pure core: types and maths, no HTTP, Redis or config, so models and domains import it freely. The infra-backed rate source is the currency/fx subpackage, which imports currency, never the reverse.
| Piece | Behavior |
|---|---|
Code |
Named string type for an ISO 4217 code. IsValid() is true only for an active currency; Exponent() is its minor-unit digit count (JPY 0, USD 2, BHD 3), or -1. |
Kind |
currency, fund, special (metals, SDR, test and no-currency codes) or historic. Only currency can carry an amount. |
Lookup, Active |
The table row for any code; every active currency sorted by code. |
ParseCode(s) |
API-input validation: trims, upper-cases, and returns ErrUnknownCode or ErrInactiveCode. |
Amount |
{Minor int64, Code}, JSON amount_minor + currency. New validates; UnmarshalJSON validates the same way, so a bound request field is always usable. |
Add, Sub, Sum, Neg |
Same-code only (ErrMismatch), range-checked (ErrOutOfRange). |
ParseDecimal(s, c), Decimal() |
Plain 12.50 strings for logs, fixtures and plain text. Locale-aware input parsing and display formatting live in the frontend. |
SplitEqual(n), AllocateEqual(total, n) |
Equal split that sums exactly to the total. The leftover minor units go one each to the first shares, so the caller orders participants first. |
Convert(a, to, rate) |
Applies a *big.Rat rate exactly, rounding half to even at the target exponent. The rate comes from the caller (normally fx). |
ForRegion, DefaultFor, LocaleRegion |
Region (ISO 3166 alpha-2) to its current legal-tender currency, first-match defaulting, and the region subtag of a BCP 47 tag. |
Primary currency¶
user_profiles.primary_currency (character(3), nullable) holds the code a
member picked in Hub → Preferences. NULL means they never picked one.
models.User.PrimaryCurrency() resolves the effective value, and
UserResponse.primary_currency always carries it:
- the stored code, when it is still an active currency;
- else the currency of
home_country, then of the profilecountry, then of the region inlanguage(ja-JPgives JPY); - else
currency.Fallback(USD).
A derived default is not written back, so it follows the member's country until
they choose. PATCH /api/v1/auth/profile with primary_currency stores an
active code (case-insensitive), rejects anything else with 400
VALIDATION_FAILED, and "" clears the choice back to the derived default.
Conversion¶
backend/internal/platform/currency/fx supplies reference rates for display and suggestions only. It has no domain concepts and no routes. A domain that needs rates (cost splitting, travel prices) declares a rate port in its deps.go, receives *fx.Frankfurter through Wire (ProvideRateProvider in internal/wiring/providers.go), and returns converted values in its own responses. There is no public rates endpoint.
| Piece | Behavior |
|---|---|
RateProvider.Rate(ctx, from, to, date) |
Reference rate for a pair on a date (zero or future means today). Returns fx.Rate{From, To, Value *big.Rat, AsOf, Source}, or ErrRateUnavailable. Same currency is always 1. |
ErrRateUnavailable |
The normal "no rate" outcome: disabled, unknown or inactive code, pair not covered, or the provider failing (timeout, 429, 5xx). Callers hide the approximation; it is not an error to log. |
currency.Convert(a, to, rate.Value) |
Applies a fetched rate (see the package table above). |
Frankfurter |
The provider: the public Frankfurter v2 API's blended daily feed (GET /v2/rates?base=&date=). |
Rates come from the public Frankfurter API at https://api.frankfurter.dev: central-bank reference rates, blended into one daily feed, no API key. A request carries only a currency code and a date, never user data. Only the blended /v2/rates endpoint is called, never provider-specific ones.
- One fetch per base and day. A miss fetches every quote for the base in one call and caches the set in Redis for 24 h (
fx:rates:frankfurter:{BASE}:{date}). Concurrent misses on a pod share one request. - Negative cache. A timeout, 429, 5xx or unparseable body caches an empty set for 5 min, so an outage is not hammered; a rejected base (4xx) or an empty answer for 24 h.
AsOfis per quote. A quote that did not publish that day carries its last publication date, which can precede the requested date.- Config.
fx.base_urlin everyconfig*.yaml(envFX_BASE_URL),fx.timeout(default 3s). An empty base URL disables the provider; tests build it that way. Self-hosting Frankfurter for guaranteed availability is a config change to its URL (plusfx.allow_privatefor an in-cluster host).
A converted amount is never stored as truth:
- Display conversion ("¥3,200 · ≈ $29.00") is approximate and recomputed when shown.
- A cross-currency settlement stores the two amounts the members agreed; the implied rate is shown from those, never recomputed from a reference rate.
- A real payment always uses the payment provider's own price.
Metrics: fx_requests_total{provider, status} and fx_request_duration_seconds{provider}; cache hits make no request.
Invariants and gotchas¶
- ISO exponents, not CLDR display digits. CLDR shows some currencies with fewer decimals than ISO defines (IDR, COP, HUF). Amounts are stored in ISO minor units; the frontend formatter keeps every stored digit visible.
MaxAmountis 2^53 - 1. Larger values would lose precision as a JSON number in JavaScript, soNewrefuses them.- Persist splits. Store the shares
SplitEqualreturns; recomputing on read can move the extra unit to someone else after the participant set changes. - Stored amounts are never converted. A reference rate only suggests a value the member confirms or labels an approximation.
- Refreshing the table.
backend/scripts/gen/gen-currencies.pyregenerates both copies; see Scripts.
Related¶
- Frontend formatting, parsing and the currency picker: Localization
- Profile preference write path: User