On Thursday, Nina changed the hold so that the payment used the total stored on the order. At 10:00 on Friday, a student who held one ticket saw “Pay $0.11 to TinyTickets?” on the payment page.
Two buyers paid the eleven cents and got no tickets. Leo forwarded their emails to Maya before 10:30.
“The page says $11.10, and the payment says eleven cents,” Leo wrote. “Which one is the price?”
Maya, Leo and TinyTickets are invented, and so are the numbers in their story.
Maya rolled the change back. The cause was one line: the order stores its total in dollars, and the payment service takes cents. Both are a number, so tsc accepted the line.
This module turns money from a plain number into a value object: a Cents type that tsc keeps apart from every other number. Then it parses amounts where they enter the code, so dollars, floats and the strings that PostgreSQL sends back stop at the edge.
After this module, you can:
- say why a plain
numberlets dollars, cents and float errors mix in money code, and keep every amount in whole cents - write a value object for money as a branded type in TypeScript, and read the
tscerror it gives for a plain number - parse money where it enters the code (a webhook, a database row, a
sum()), so the code inside works only with checked amounts - decide where rounding happens, keep that rule in one function, and format money only to print it
- say what a branded type costs, and when a
Moneyclass or a plain number is the better choice
Where the code stands
Module 4 left four bounded contexts and an anticorruption layer for the payment provider’s webhooks. Money is still a plain number. Shows stores a ticket’s price in whole dollars, Sales stores an order’s total in dollars and cents, and every other table uses cents. Figure 1 is the code figure from Module 4.
{Door} ..........> {Sales} <.......... {Payouts}
: : :
: v :
:.............> {Shows} <...............:
Inside {Sales}: routes/, services/, jobs/ ..> acl/ ACL ..> [Payment provider]
Only acl/ knows the provider's webhook body.
platform/ the pool, the job queue, settings, page layout, login, email,
the payment provider's client, the organizer dashboard.
Every context ..> platform/. app.ts and worker.ts ..> each #.
Figure 1: no part of the code owns money, so each file decides what a number means.
Two money bugs with one cause
Make Nina’s change. In src/sales/services/holds.ts, change the line that asks for the payment (an excerpt):
const payment = await createPayment(Number(order.amount_in_dollars), order.token);
Nina had a reason: the payment should use the total stored on the order, so the two can never differ. Run npm run check. It prints no errors.
Now add two tests at the end of app.test.ts:
test("a student ticket with the booking fee is charged $11.10", async () => {
const answer = await post(`/shows/${leoShow}/hold`, { ...buyer, student: "1" });
const payPage = await fetch(answer.headers.get("location")!);
assert.match(await payPage.text(), /Pay \$11\.10 to TinyTickets/);
});
test("the email for four tickets lists no booking fee", async () => {
const show = await pool.query("SELECT id FROM shows.shows WHERE name = 'Other Show'");
await post(`/shows/${show.rows[0].id}/hold`, { ...buyer, standard: "4" });
const order = await pool.query("SELECT token, payment_id FROM sales.orders WHERE quantity = 4");
const { token, payment_id } = order.rows[0];
await webhook({
id: "evt_3",
type: "payment.succeeded",
data: { payment_id, amount_cents: 8000, currency: "usd", metadata: { order_ref: token } },
});
await runOneJob();
const email = emails.at(-1)!;
assert.match(email.text, /Total: \$80\.00/);
assert.doesNotMatch(email.text, /Booking fee/);
});
The first test holds one student ticket for Leo’s $12 test show and reads the page that the pretend payment service shows the buyer. The second holds four $20 tickets for the other test show, pays for them, runs the email job, and reads the email. Four tickets pay no booking fee.
Pause and predict: a $12 student ticket costs $9.60, and the $1.50 booking fee makes $11.10.
order.amount_in_dollarsholds that total. What does the payment page ask the student to pay?
npm test
What you should see (an excerpt; paths are shortened, stack lines are cut, and your timings and IDs will differ):
✖ a student ticket with the booking fee is charged $11.10 (8.295441ms)
mail: caught an email to ana@tinytickets.example
✖ the email for four tickets lists no booking fee (21.278308ms)
...
ℹ tests 18
ℹ suites 0
ℹ pass 16
ℹ fail 2
...
✖ a student ticket with the booking fee is charged $11.10 (8.295441ms)
AssertionError [ERR_ASSERTION]: The input did not match the regular expression /Pay \$11\.10 to TinyTickets/. Input:
'<!doctype html>\n' +
'<title>Fake Pay</title>\n' +
'<h1>Fake Pay</h1>\n' +
'<p>Pay $0.11 to TinyTickets?</p>\n' +
...
✖ the email for four tickets lists no booking fee (21.278308ms)
AssertionError [ERR_ASSERTION]: The input did not match the regular expression /Total: \$80\.00/. Input:
'Hello Ana,\n' +
...
'4 x standard ticket, $20.00 each\n' +
'Booking fee, $1.50\n' +
'Total: $81.50\n' +
'Paid: $80.00 (payment pay_cca99a31912296ae)\n' +
The student is asked for $0.11. The column sales.orders.amount_in_dollars is numeric(10, 2), and pg returns a numeric as a string, "11.10". Number turns it into 11.1. createPayment takes cents, so it asked the payment service for 11.1 cents, and the service printed that as $0.11.
If the buyer presses Pay, the provider sends amount_cents: 11.1 back in the webhook. The layer from Module 4 refuses it, because 11.1 is not a whole number, and the order stays on hold until its 10 minutes run out. That is what the two buyers saw.
The second test fails for a different reason, with the same root. The worker does not use the price rule in pricing.ts. It keeps its own copy, in dollars, with count <= 4 where the rule says count < 4. So a buyer of four tickets reads “Total: $81.50” above “Paid: $80.00”.
Find every place where a number becomes money:
grep -rnE "in_dollars|/ 100|\* 100|toFixed" src
What you should see:
src/sales/db/orders.ts:7: quantity: number; lines: OrderLine[]; amount_in_dollars: string;
src/sales/db/orders.ts:18: lines, amount_in_dollars, hold_expires_at)
src/sales/pages/shows.ts:17:<p>A ticket costs $${show.price_in_dollars}. Students get 20% off, VIP costs $5 more.
src/sales/pages/shows.ts:41:<p>${order.quantity} tickets, $${order.amount_in_dollars}.</p>
src/sales/jobs/send-confirmation.ts:20: let price = show.price_in_dollars;
src/sales/jobs/send-confirmation.ts:27: lines.push(`${line.quantity} x ${line.kind} ticket, $${price.toFixed(2)} each`);
src/sales/jobs/send-confirmation.ts:41:Total: $${total.toFixed(2)}
src/sales/jobs/send-confirmation.ts:42:Paid: $${(payment.amountCents / 100).toFixed(2)} (payment ${payment.paymentId})
src/sales/services/pricing.ts:9: const base = priceInDollars * 100;
src/sales/services/orders.ts:31: priceCents: ticketPriceCents(show.price_in_dollars, line.kind),
src/sales/services/orders.ts:35: const expectedCents = Math.round(Number(order.amount_in_dollars) * 100);
src/sales/services/holds.ts:16: const totalCents = orderTotalCents(show.price_in_dollars, lines);
src/sales/services/holds.ts:24: amountInDollars: totalCents / 100,
src/sales/services/holds.ts:27: const payment = await createPayment(Number(order.amount_in_dollars), order.token);
src/platform/pages/organizer.ts:18: return `$${(cents / 100).toFixed(2)}`;
src/shows/db/shows.ts:11: price_in_dollars: number;
src/shows/db/shows.ts:15: to_char(doors_open, 'HH24:MI') AS doors_open, place, seats, price_in_dollars`;
Seventeen lines in eight files, and each one converts between units by hand. Figure 2 sorts them by unit.
Where it is stored Unit How the code reads it
[[shows.shows]] price_in_dollars whole dollars, 12 x 100 in pricing.ts; float dollars in the worker
[[sales.orders]] amount_in_dollars dollars and cents a string, "11.10"; Number(...) * 100 in orders.ts
[[sales.tickets]] price_cents cents, 960 a number
[[payouts.payouts]] *_cents cents a number; x 0.05 in payouts.ts
[Payment provider] amount_cents cents Payment.amountCents, a number
dashboard sum(price_cents) cents a string, typed as a number
Figure 2: one idea, money, in three forms: whole dollars, a string of dollars and cents, and cents.
That answers Leo’s question. TinyTickets has no single price, because nothing in the code says what an amount of money is. Every file decides for itself.
Money as a value
A JavaScript number is a binary float
Start with the worker’s copy of the price. Run this in a terminal:
node -p "[12 * 0.8, 12 * 0.8 + 1.5, 1200 * 0.8 + 150]"
What you should see (Node.js 26.13.1):
[ 9.600000000000001, 11.100000000000001, 1110 ]
A JavaScript number is an IEEE 754 binary64 value (ECMAScript, The Number Type). Most decimal fractions, such as 0.8 and 9.6, have no exact binary form, so dollar amounts pick up small errors. Whole cents are exact, up to Number.MAX_SAFE_INTEGER (9007199254740991), which is about $90 trillion.
The email hides the error with toFixed(2). But toFixed rounds the exact binary value of a number (ECMAScript, Number.prototype.toFixed), and 1.005 is stored as 1.00499999…
node -p "[(1.005).toFixed(2), new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' }).format(1.005)]"
What you should see:
[ '1.00', '$1.01' ]
Intl.NumberFormat is the built-in that formats a number for a language and region, with a currency’s symbol and its number of decimals (MDN). It starts from the shortest decimal string of the number, “1.005”, so it rounds the way a person would (ECMA-402, ToIntlMathematicalValue). Two built-ins give different cents for the same number. So a formatter should only print whole cents, never round them.
Rule: compute money in whole cents, and turn cents into dollars only to print them.
Whole cents do not fix Nina’s bug, though. 11.1 and 1110 are both numbers, and so is 12 for twelve dollars.
A value object is defined by its value
A value object is an object that describes something by its attributes alone and has no identity of its own. Evans’ Domain-Driven Design Reference (2015, p. 12) asks you to give it the behavior that belongs to it, and to keep its operations free of side effects. One line sums up the rule:
“Treat the value object as immutable.” (Evans, Domain-Driven Design Reference, p. 12)
Immutable means that a value never changes after it is made, so an operation returns a new value instead. $11.10 is the same amount on the order, on the payment and in the email. It has no ID, and nobody asks “which $11.10?”. In DDD, a value object is not the same as a JavaScript primitive value, but a primitive can be one.
Equality by value means that two value objects with the same attributes are equal (Fowler, “Value Object”, 2016). JavaScript compares objects by reference:
node -p "[({ cents: 1110 }) === ({ cents: 1110 }), 1110 === 1110]"
What you should see:
[ false, true ]
Fowler notes that a custom equals method helps in your own code, but library code such as includes ignores it. A number has no such problem. It is already immutable, and === already compares it by value.
It works because a value with no identity can be copied, stored and shared without one part of the code changing it under another. Fowler’s example is two variables that share one mutable date, so a change through one shows up in the other. The cost is that every change makes a new value, so arithmetic goes through functions that return one.
So in TypeScript, the smallest value object for money is a number that the type checker keeps apart from other numbers.
TypeScript compares shapes, so a brand gives Cents its own name
Structural typing means that TypeScript relates two types by their members, not by their names (TypeScript handbook, Type Compatibility). So two aliases of number are the same type. This compiles with no error:
type Dollars = number;
type Cents = number;
function charge(amount: Cents): void {}
const price: Dollars = 11.1;
charge(price);
TypeScript has no nominal types, where the name decides. The request for them, issue #202, has been open since 2014. The common workaround is a brand.
A branded type is a base type intersected with a property that no value has at run time, so a value gets the type only through a cast. Here is TinyTickets’ Cents:
declare const centsBrand: unique symbol;
export type Cents = number & { readonly [centsBrand]: true };
unique symbol is a type for one symbol tied to one declaration, so no other declaration can produce it (TypeScript 2.7 release notes). declare const emits no code. So at run time a Cents is a plain number: JSON.stringify, pg and === all see a number.
It works because tsc asks for the brand property, and a plain number has none. Step 2 shows the error. The costs are two:
- Arithmetic drops the brand.
Cents + Centsis anumber, so every operation is a function that returnsCents. - The cast
n as Centsis a promise thattsccannot check. Keep it in one function.
A brand cannot tell twelve dollars from twelve cents, either. It proves that a number came through the one function that makes Cents. That function, and the data it reads, must already be in cents.
Parse money where it enters
Alexis King’s “Parse, don’t validate” (2019) separates two kinds of check. A validator checks a value and returns nothing, so the program forgets what it learned. A parser takes less-structured input and returns a more precise type that keeps what the check found.
In TypeScript, isWholeCents(n: number): boolean is a validator. parseCents(input: unknown): Cents is a parser: after it, the type says the check happened. King asks that you parse at the boundary, before the program acts on the input. In TinyTickets, money enters at the webhook, at the database rows, and at the job payloads.
The layer from Module 4 is a validator for the amount. It checks Number.isInteger(amountCents), then passes on a plain number, and the rest of Sales cannot tell that the check ran.
Database rows are an edge with a trap. In PostgreSQL 18, sum(integer) returns bigint (PostgreSQL docs, Aggregate Functions). node-postgres returns bigint as a string, because some 64-bit values do not fit in a JavaScript number (pg-types). It returns integer as a number.
So TinyTickets parses in two ways. A column of type integer with a CHECK (... >= 0) holds only what parseCents would accept, and PostgreSQL checks it on every write. A row type may call that column Cents. A sum() arrives as a string, so it goes through parseCents.
The job queue is an edge too. Sales queues a Payment that is already parsed, and the worker reads it back from jsonb without a check. This module leaves it there, and Module 9 returns to the job queue.
PostgreSQL also has a money type. Its number of decimals and its output depend on the lc_monetary setting, and the docs warn against floating-point numbers for money (PostgreSQL docs, Monetary Types). TinyTickets stores whole cents in integer columns instead.
Rule: parse money once, where it enters, into a type that says it was checked.
Figure 3 shows where each amount enters after this module.
[Payment provider] --> {Sales} acl/payment-provider.ts amount_cents: unknown --> parseCents
[[shows.shows]] --> {Shows} db/shows.ts price_cents integer >= 0 --> Cents
[[sales.orders]] --> {Sales} db/orders.ts total_cents integer >= 0 --> Cents
[[sales.tickets]] --> {Sales} db/tickets.ts price_cents integer >= 0 --> Cents
[[sum() bigint]] --> platform/ db/dashboard.ts "3360", a string --> parseCents
Inside: pricing.ts and payouts.ts work on Cents, through addCents, multiplyCents, percentOf
Out: formatDollars for pages and emails; createPayment and sendTransfer take Cents
Figure 3: every amount becomes Cents where it enters, and becomes dollars only on its way out.
Where you round is a business rule
Whole cents still need rounding once a percent is involved. The site keeps 5% of each ticket’s price, and 5% of a $13.50 ticket is 67.5 cents. Figure 4 shows two places to round.
| Three $13.50 tickets | Rounded per ticket | Rounded once per show |
|---|---|---|
| What is rounded | 5% of 1350 = 67.5, three times | 5% of 4050 = 202.5, once |
| Fee | 68 + 68 + 68 = 204 cents | 203 cents |
Figure 4: the same 5% gives 204 or 203 cents, depending on where you round.
Neither answer is wrong in arithmetic. The story says “5% of each ticket’s price”, and the test from the starter project, “the fee is rounded per ticket”, expects 204. So TinyTickets rounds per ticket. The student discount is rounded per ticket too.
The booking fee raises the same kind of question. A student ticket is 960 cents, and the fee adds 150, which makes 1110. Taking 20% off the ticket and the fee together would give 1080. Design Patterns in Plain Words, Module 1, already settled it: the discount is on the tickets, then the fee is added.
A value object does not make these choices. Leo does, and the code writes his answer in one function with one test. TinyTickets’ percentOf computes amount * percent / 100 on whole cents, so the half is exact, and Math.round rounds it up. Floats get halves wrong:
node -p "[Math.round(0.7 * 0.05 * 100), Math.round(70 * 5 / 100)]"
What you should see:
[ 3, 4 ]
In dollars, 5% of $0.70 comes out as 3.4999999999999996 cents before rounding, so it rounds to 3. In whole cents it is exactly 3.5, so it rounds to 4.
One money type for three contexts
Shows, Sales and Payouts all handle money. Module 4 described a shared kernel as a small part of the model that two or more contexts share and change only when they all agree (Evans, Reference, p. 31). TinyTickets had none, and Cents is its first one.
It gets its own folder, src/money/, with its own #money entry. It does not go into src/platform/, because Module 3 keeps business rules out of shared code, and “money is a whole number of cents” is a rule. The boundary test from Module 3 already treats every folder of src/ the same way, so other code must import #money.
The cost is the cost of any shared kernel: a change to Cents reaches three contexts at once. So the kernel stays one file: a type and five functions.
Give money one type, step by step
Each step says why, what to do, the code, and what you should see. Work in the project folder Module 4 left, with Nina’s line and the two new tests from the problem section. The finished code is in the code/module-05/ folder of the course repository. If you kept the exercise from Module 4, your test counts are one higher.
Step 1: Write the money kernel
Why: money needs one type and one place for its operations before any code can use them.
What to do: save this as src/money/cents.ts:
// Money in TinyTickets: an amount in US cents, a whole number, never negative.
// Shows, Sales and Payouts share this file (see CONTEXT-MAP.md).
declare const centsBrand: unique symbol;
export type Cents = number & { readonly [centsBrand]: true };
// The only way to make Cents. Takes a number, or a string of digits such as
// pg returns for bigint and numeric, and throws on anything else.
export function parseCents(input: unknown): Cents {
const value = typeof input === "string" && /^\d+$/.test(input) ? Number(input) : input;
if (typeof value !== "number" || !Number.isSafeInteger(value) || value < 0) {
throw new RangeError(`Not an amount in cents: ${JSON.stringify(input)}`);
}
return value as Cents;
}
export function addCents(a: Cents, b: Cents): Cents {
return parseCents(a + b);
}
export function multiplyCents(amount: Cents, times: number): Cents {
return parseCents(amount * times);
}
// A whole percent of an amount, rounded half up: 5% of 1350 is 67.5, so 68.
export function percentOf(amount: Cents, percent: number): Cents {
return parseCents(Math.round((amount * percent) / 100));
}
const dollars = new Intl.NumberFormat("en-US", { style: "currency", currency: "USD" });
export function formatDollars(amount: Cents): string {
return dollars.format(amount / 100);
}
parseCents holds the only as Cents in the project. The other functions call it on their result, so an operation that leaves whole cents throws instead of returning a wrong Cents. Number.isSafeInteger refuses 11.1, NaN, Infinity and anything beyond 2^53 − 1. JSON.stringify in the message shows a string with its quotes, so "11.10" and 11.1 look different in a log.
formatDollars divides by 100 only to print. Cents divided by 100 have at most two decimals, so the shortest decimal string that Intl.NumberFormat starts from is exact.
Save the entry as src/money/index.ts:
// The public entry of the money kernel. Code outside src/money/ imports it as "#money".
export { addCents, formatDollars, multiplyCents, parseCents, percentOf } from "./cents.ts";
export type { Cents } from "./cents.ts";
In package.json, add the entry as the last line of "imports" (an excerpt):
"#platform": "./src/platform/index.ts",
"#money": "./src/money/index.ts"
And save the kernel’s tests as src/money/cents.test.ts:
import assert from "node:assert/strict";
import { test } from "node:test";
import { formatDollars, parseCents, percentOf } from "./cents.ts";
test("cents are a whole number that is never negative", () => {
assert.equal(parseCents(1110), 1110);
assert.equal(parseCents("3330"), 3330);
assert.throws(() => parseCents(11.1), /Not an amount in cents: 11.1/);
assert.throws(() => parseCents("11.10"), /Not an amount in cents: "11.10"/);
assert.throws(() => parseCents(-150), RangeError);
});
test("a percent of an amount is rounded half up", () => {
assert.equal(percentOf(parseCents(1350), 5), 68);
assert.equal(percentOf(parseCents(70), 5), 4);
assert.equal(percentOf(parseCents(1200), 80), 960);
});
test("cents are formatted as dollars once, at the end", () => {
assert.equal(formatDollars(parseCents(1110)), "$11.10");
assert.equal(formatDollars(parseCents(111000)), "$1,110.00");
});
The last line is the other way to get money wrong: 1110 cents read as dollars prints as $1,110.00. Run npm run check and npm test.
What you should see: npm run check prints no errors. The three new tests pass, and the two from the problem section still fail (an excerpt):
✔ cents are a whole number that is never negative (1.885249ms)
✔ a percent of an amount is rounded half up (0.183708ms)
✔ cents are formatted as dollars once, at the end (6.899235ms)
...
ℹ tests 21
ℹ suites 0
ℹ pass 19
ℹ fail 2
Commit the kernel alone:
git add src/money package.json
git commit -m "Add Cents, the money kernel"
Step 2: Ask for Cents where money leaves TinyTickets
Why: the payment service charges whatever createPayment sends. Its parameter is where a wrong unit costs a buyer money.
What to do: in src/platform/services/payments.ts, add the import at the top and change the type of two parameters (an excerpt):
import type { Cents } from "#money";
export async function createPayment(amountCents: Cents, orderRef: string): Promise<{ id: string; payUrl: string }> {
export async function sendTransfer(account: string, amountCents: Cents): Promise<string> {
Run npm run check.
What you should see:
src/payouts/jobs/pay-organizers.ts(10,64): error TS2345: Argument of type 'number' is not assignable to parameter of type 'Cents'.
Type 'number' is not assignable to type '{ readonly [centsBrand]: true; }'.
src/sales/services/holds.ts(27,39): error TS2345: Argument of type 'number' is not assignable to parameter of type 'Cents'.
Type 'number' is not assignable to type '{ readonly [centsBrand]: true; }'.
The second error is Nina’s line. tsc names the missing brand, [centsBrand], which a plain number does not have.
Now put the line back as it was before Nina’s change (an excerpt):
const payment = await createPayment(totalCents, order.token);
Run npm run check again. It prints the same two errors, because orderTotalCents returns a number. That is the point of the brand: tsc cannot tell 11.1 from 1110, so it asks where the number came from. Steps 3 to 6 make every amount come from parseCents or from a cents column.
Step 3: Store every amount in cents
Why: a brand cannot tell dollars from cents, so the data it reads must already be in cents.
What to do: save this as migrations/017_store_money_in_cents.sql:
-- Year 3: every amount of money is in cents (see "Money" in GLOSSARY.md).
-- USING converts the rows that are already there.
ALTER TABLE shows.shows ALTER COLUMN price_in_dollars TYPE integer USING price_in_dollars * 100;
ALTER TABLE shows.shows RENAME COLUMN price_in_dollars TO price_cents;
ALTER TABLE sales.orders ALTER COLUMN amount_in_dollars TYPE integer USING round(amount_in_dollars * 100);
ALTER TABLE sales.orders RENAME COLUMN amount_in_dollars TO total_cents;
-- An amount in cents is never negative, as in parseCents.
ALTER TABLE shows.shows ADD CHECK (price_cents >= 0);
ALTER TABLE sales.orders ADD CHECK (total_cents >= 0);
ALTER TABLE sales.tickets ADD CHECK (price_cents >= 0);
ALTER TABLE payouts.payouts ADD CHECK (gross_cents >= 0 AND fee_cents >= 0 AND amount_cents >= 0);
USING gives the expression that turns each old value into the new type, so 12 becomes 1200 and 11.10 becomes 1110. The CHECK constraints make PostgreSQL refuse a negative amount on every write. With them, every money column holds only what parseCents would accept.
Then change the types and the SQL that name the old columns (Figure 5). Each new import type { Cents } from "#money"; goes at the top of its file.
| File | Old | New |
|---|---|---|
src/shows/db/shows.ts |
price_in_dollars: number; in Show |
price_cents: Cents; |
src/shows/db/shows.ts |
price_in_dollars in columns |
price_cents |
src/sales/db/orders.ts |
amount_in_dollars: string; in Order |
total_cents: Cents; |
src/sales/db/orders.ts |
amountInDollars: number; in insertOrder |
totalCents: Cents; |
src/sales/db/orders.ts |
amount_in_dollars in the INSERT, r.amountInDollars |
total_cents, r.totalCents |
seed.ts |
price_in_dollars, the values 12 |
price_cents, 1200 |
app.test.ts |
price_in_dollars, the values 12 and 20 |
price_cents, 1200 and 2000 |
app.test.ts |
SELECT amount_in_dollars, status and [{ amount_in_dollars: "35.10", status: "pending" }] |
SELECT total_cents, status and [{ total_cents: 3510, status: "pending" }] |
Figure 5: the columns and the row types now say cents.
The last row shows the string from numeric going away. total_cents is an integer, so pg returns 3510, a number. Run npm run check.
What you should see:
src/payouts/jobs/pay-organizers.ts(10,64): error TS2345: Argument of type 'number' is not assignable to parameter of type 'Cents'.
Type 'number' is not assignable to type '{ readonly [centsBrand]: true; }'.
src/sales/jobs/send-confirmation.ts(20,22): error TS2339: Property 'price_in_dollars' does not exist on type 'Show'.
src/sales/pages/shows.ts(17,27): error TS2339: Property 'price_in_dollars' does not exist on type 'Show'.
src/sales/pages/shows.ts(41,40): error TS2339: Property 'amount_in_dollars' does not exist on type 'Order'.
src/sales/services/holds.ts(16,43): error TS2339: Property 'price_in_dollars' does not exist on type 'Show'.
src/sales/services/holds.ts(24,5): error TS2353: Object literal may only specify known properties, and 'amountInDollars' does not exist in type '{ token: string; showId: number; buyerName: string; buyerEmail: string; quantity: number; lines: OrderLine[]; totalCents: Cents; expiresAt: Date; }'.
src/sales/services/holds.ts(27,39): error TS2345: Argument of type 'number' is not assignable to parameter of type 'Cents'.
Type 'number' is not assignable to type '{ readonly [centsBrand]: true; }'.
src/sales/services/orders.ts(31,45): error TS2339: Property 'price_in_dollars' does not exist on type 'Show'.
src/sales/services/orders.ts(35,51): error TS2339: Property 'amount_in_dollars' does not exist on type 'Order'.
Nine errors, and each one is a line from the grep in the problem section. The worker’s copy of the price rule is on the list, because it read show.price_in_dollars.
Step 4: Compute every price in cents, in one place
Why: the errors point at the price rule and at its copy in the worker. One rule in cents fixes both bugs from the problem section.
What to do: replace src/sales/services/pricing.ts with this:
import { addCents, multiplyCents, parseCents, percentOf } from "#money";
import type { Cents } from "#money";
export type TicketKind = "standard" | "student" | "vip";
// One line of an order: how many tickets of one kind.
export type OrderLine = { kind: TicketKind; quantity: number };
export const ticketKinds: TicketKind[] = ["standard", "student", "vip"];
const VIP_EXTRA = parseCents(500);
const BOOKING_FEE = parseCents(150);
// Students get 20% off and VIP costs $5 more, rounded per ticket.
export function ticketPriceCents(showPrice: Cents, kind: TicketKind): Cents {
if (kind === "student") {
return percentOf(showPrice, 80);
}
if (kind === "vip") {
return addCents(showPrice, VIP_EXTRA);
}
return showPrice;
}
// Fewer than four tickets pay a $1.50 booking fee, with no student discount.
export function bookingFeeCents(lines: OrderLine[]): Cents {
const count = lines.reduce((sum, line) => sum + line.quantity, 0);
return count < 4 ? BOOKING_FEE : parseCents(0);
}
export function orderTotalCents(showPrice: Cents, lines: OrderLine[]): Cents {
let total = bookingFeeCents(lines);
for (const line of lines) {
total = addCents(total, multiplyCents(ticketPriceCents(showPrice, line.kind), line.quantity));
}
return total;
}
bookingFeeCents is new, so that the email can ask the rule instead of copying it. Every function takes Cents and returns Cents, so a price in dollars cannot reach the rule.
In src/sales/jobs/send-confirmation.ts, add two imports:
import { bookingFeeCents, ticketPriceCents } from "../services/pricing.ts";
import { formatDollars } from "#money";
Then replace everything from const lines: string[] = []; to the closing brace of if (count <= 4) with this (an excerpt):
// The same price rule as the hold, and the total stored on the order.
const lines = order.lines.map(
(line) => `${line.quantity} x ${line.kind} ticket, ${formatDollars(ticketPriceCents(show.price_cents, line.kind))} each`,
);
const fee = bookingFeeCents(order.lines);
if (fee > 0) {
lines.push(`Booking fee, ${formatDollars(fee)}`);
}
And print the stored total in the email’s text (an excerpt):
Total: ${formatDollars(order.total_cents)}
The email now prints the total that the buyer was asked to pay. Make the remaining changes in the table below.
| File | Old | New |
|---|---|---|
src/sales/services/holds.ts |
orderTotalCents(show.price_in_dollars, lines) |
orderTotalCents(show.price_cents, lines) |
src/sales/services/holds.ts |
amountInDollars: totalCents / 100, |
totalCents, |
src/sales/services/orders.ts |
ticketPriceCents(show.price_in_dollars, line.kind) |
ticketPriceCents(show.price_cents, line.kind) |
src/sales/services/orders.ts |
expectedCents, from Math.round(Number(order.amount_in_dollars) * 100) |
order.total_cents, in the comparison and in the message |
src/sales/pages/shows.ts |
$${show.price_in_dollars}, $${order.amount_in_dollars} |
${formatDollars(show.price_cents)}, ${formatDollars(order.total_cents)}, with import { formatDollars } from "#money"; |
src/sales/services/pricing.test.ts |
the argument 12 |
twelveDollars, with import { parseCents } from "#money"; and const twelveDollars = parseCents(1200); under the imports |
The check in markOrderPaid is now payment.amountCents !== order.total_cents. Both are numbers, so !== compares them by value. Run npm run check and npm test.
What you should see: one error is left, in Payouts:
src/payouts/jobs/pay-organizers.ts(10,64): error TS2345: Argument of type 'number' is not assignable to parameter of type 'Cents'.
Type 'number' is not assignable to type '{ readonly [centsBrand]: true; }'.
Node.js strips types without checking them, so the tests still run, and all 21 pass (an excerpt):
✔ a student ticket with the booking fee is charged $11.10 (7.459885ms)
✔ the email for four tickets lists no booking fee (22.711485ms)
...
ℹ tests 21
ℹ suites 0
ℹ pass 21
ℹ fail 0
The payment page asks for $11.10, and the email for four tickets has no booking fee.
Step 5: Parse the amount at the webhook
Why: Payment.amountCents is still a number. The layer from Module 4 checks the amount, and then the rest of Sales forgets that it did.
What to do: in src/sales/services/orders.ts, add import type { Cents } from "#money"; and change the type of the amount (an excerpt):
export type Payment = { orderToken: string; paymentId: string; amountCents: Cents };
Run npm run check.
What you should see:
src/payouts/jobs/pay-organizers.ts(10,64): error TS2345: Argument of type 'number' is not assignable to parameter of type 'Cents'.
Type 'number' is not assignable to type '{ readonly [centsBrand]: true; }'.
src/sales/acl/payment-provider.ts(42,54): error TS2322: Type 'number' is not assignable to type 'Cents'.
Type 'number' is not assignable to type '{ readonly [centsBrand]: true; }'.
The new error is in the layer, where the provider’s amount_cents becomes Sales’ amountCents. tsc now asks for a parse at the one place where the amount enters Sales. Before you change the layer, add a test for the webhook that the two buyers caused, at the end of app.test.ts:
test("a webhook with an amount in dollars is refused", async () => {
const answer = await webhook({
id: "evt_4",
type: "payment.succeeded",
data: { payment_id: "pay_4", amount_cents: 11.1, currency: "usd", metadata: { order_ref: "no-such-order" } },
});
assert.equal(answer.status, 400);
});
Run npm test. The test passes, because the layer’s Number.isInteger check refuses 11.1. Read the line the layer logs (an excerpt):
Error: Payment webhook evt_4 needs payment_id, amount_cents and metadata.order_ref; its data has payment_id, amount_cents, currency, metadata.
✔ a webhook with an amount in dollars is refused (1.37833ms)
The message says that amount_cents is needed, and that the body has it. The check knew the value was wrong, but it returned only “no”, so the message cannot say why. Now change the layer. In src/sales/acl/payment-provider.ts, add the import at the top:
import { parseCents } from "#money";
Replace the two lines that check the amount’s type with one line (an excerpt):
amountCents === undefined ||
And parse it in the last line (an excerpt):
return { result, payment: { orderToken, paymentId, amountCents: parseCents(amountCents) } };
A missing field still gets the message that lists the fields. A field that is there but is not whole cents now gets the parser’s message. Update the comment above the function to say so (an excerpt):
// Reads a body that nothing has checked yet. Returns undefined for the event
// types Sales does not use, and throws when a field Sales needs is missing,
// or when the amount is not a whole number of cents.
Last, the email’s “Paid” line in src/sales/jobs/send-confirmation.ts can use the formatter now (an excerpt):
Paid: ${formatDollars(payment.amountCents)} (payment ${payment.paymentId})
Run npm test.
What you should see: 22 tests pass, and the layer’s line names the problem (an excerpt):
RangeError: Not an amount in cents: 11.1
✔ a webhook with an amount in dollars is refused (1.174367ms)
Step 6: Give Payouts cents
Why: the last tsc error is the transfer to the organizer. Its amount comes from the 5% fee, which Payouts still computes with price * 0.05.
What to do: replace src/payouts/services/payouts.ts with this:
import { addCents, parseCents, percentOf } from "#money";
import type { Cents } from "#money";
export const SITE_FEE_PERCENT = 5;
// The site keeps 5% of each ticket's price, rounded per ticket.
export function payoutFor(ticketPrices: Cents[]): {
grossCents: Cents;
feeCents: Cents;
amountCents: Cents;
} {
let grossCents = parseCents(0);
let feeCents = parseCents(0);
for (const price of ticketPrices) {
grossCents = addCents(grossCents, price);
feeCents = addCents(feeCents, percentOf(price, SITE_FEE_PERCENT));
}
return { grossCents, feeCents, amountCents: parseCents(grossCents - feeCents) };
}
parseCents(grossCents - feeCents) throws if the fee were ever larger than the sales, instead of sending a negative transfer. Run npm run check.
What you should see (an excerpt):
src/payouts/jobs/pay-organizers.ts(9,30): error TS2345: Argument of type 'number[]' is not assignable to parameter of type 'Cents[]'.
Type 'number' is not assignable to type 'Cents'.
Type 'number' is not assignable to type '{ readonly [centsBrand]: true; }'.
src/payouts/services/payouts.test.ts(6,31): error TS2322: Type 'number' is not assignable to type 'Cents'.
The error moved back one call, to the prices that Payouts asks Sales for. tsc follows the money to where it comes from: listSoldTicketPrices in Sales. Make the changes in the table below.
| File | Old | New |
|---|---|---|
src/sales/db/tickets.ts |
price_cents: number in Ticket |
price_cents: Cents |
src/sales/db/tickets.ts |
priceCents: number; in insertTicket |
priceCents: Cents; |
src/sales/db/tickets.ts |
Promise<number[]> and pool.query<{ price_cents: number }> in listSoldTicketPrices |
Promise<Cents[]> and pool.query<{ price_cents: Cents }>, with import type { Cents } from "#money"; |
src/payouts/services/payouts.test.ts |
payoutFor([1200, 960, 1700]), payoutFor([1350, 1350, 1350]) |
payoutFor([1200, 960, 1700].map(parseCents)), payoutFor([1350, 1350, 1350].map(parseCents)), with import { parseCents } from "#money"; |
price_cents is an integer, so pg returns a number, and the migration’s CHECK keeps it whole and not negative. That is why the row type may say Cents without a call to parseCents.
What you should see: npm run check prints no errors, for the first time since Step 2, and npm test passes all 22 tests. Commit:
git add -A
git commit -m "Keep every amount of money in Cents"
Step 7: Parse the sums on the dashboard
Why: the organizer dashboard adds up prices with sum(). Its row type says gross_cents: number, and nothing has checked that.
What to do: break it first. At the top of app.test.ts, import the query:
import { loadDashboard } from "./src/platform/db/dashboard.ts";
Add a test at the end of the file:
test("the dashboard reads sales as cents", async () => {
const rows = await loadDashboard(1);
assert.equal(rows[0]!.gross_cents, 3360);
});
Leo’s test show sold two standard tickets and one student ticket earlier in the file: 1200 + 1200 + 960 = 3360 cents. Run npm test.
What you should see (an excerpt):
✖ the dashboard reads sales as cents (2.871153ms)
AssertionError [ERR_ASSERTION]: Expected values to be strictly equal:
'3360' !== 3360
sum() returned bigint, and pg returned it as the string '3360'. npm run check has no complaint, because pool.query<DashboardRow> is a cast: the type says what the code hopes the rows hold. The page still printed $33.60, because / 100 turns the string into a number. But row.gross_cents + 100 would give "3360100".
Now parse it. In src/platform/db/dashboard.ts, import the kernel:
import { parseCents } from "#money";
import type { Cents } from "#money";
Give the money fields of DashboardRow their type (an excerpt):
tickets_sold: number; gross_cents: Cents; seats_held: number; scanned: number;
payout_cents: Cents | null; paid_out_at: Date | null;
Type the query with the string that arrives (an excerpt):
// sum() returns bigint, and pg returns bigint as a string, such as "3360".
const result = await pool.query<Omit<DashboardRow, "gross_cents"> & { gross_cents: string }>(
And parse each row on the way out (an excerpt):
return result.rows.map((row) => ({ ...row, gross_cents: parseCents(row.gross_cents) }));
payout_cents comes from an integer column with a CHECK, so it needs no parse. The dashboard page still has its own dollars function with toFixed. In src/platform/pages/organizer.ts, delete that function, add import { formatDollars } from "#money";, and call formatDollars in its two places.
What you should see: npm run check prints no errors, and npm test passes all 23 tests. Commit:
git add -A
git commit -m "Parse the dashboard's sums into Cents"
tickets_sold, seats_held and scanned are counts from count() and sum(), so they arrive as strings too. They are not money, and Module 10 rebuilds the dashboard.
Step 8: Update the glossary, the map and the README
Why: the glossary’s open question about money has an answer now, and the map from Module 4 says TinyTickets has no shared kernel.
What to do: in GLOSSARY.md, add this entry before “Fee”:
## Money
An amount in US dollars and cents: a price, a total, a fee or a payout.
TinyTickets sells in one currency.
- Context: shared by Shows, Sales and Payouts, in the money kernel.
- Code: type `Cents` and `parseCents` (`src/money/cents.ts`, `#money`).
Every amount is a whole number of cents, in columns that end in `_cents`.
`formatDollars` prints one, at the end.
- Rounding: a percent of an amount is rounded half up, once per ticket.
- Do not say: dollars, for an amount the code stores or adds up.
In the same file, change the code line of “Fee” to - Code: `SITE_FEE_PERCENT` (`src/payouts/services/payouts.ts`). Replace the body of the “Booking fee” entry with these lines:
$1.50 that an order of fewer than four tickets pays. Students pay it in
full: the discount is on the tickets only.
- Context: Sales.
- Code: `bookingFeeCents` (`src/sales/services/pricing.ts`).
Then delete the “Open questions” section, because money was its last item.
In CONTEXT-MAP.md, add this section after “Between the contexts”:
## Shared kernel
{Shows} ..> money/ Shared kernel: src/money/cents.ts, through
{Sales} ..> money/ #money. The type Cents and the functions
{Payouts} ..> money/ that make and add it. Change it only when
all three contexts agree.
Add a third check at the end of the file, and end the sentence about src/platform/ in the first paragraph with “but it uses the money kernel too”:
grep -rnE "in_dollars|toFixed" src
In README.md, add a paragraph at the end of “Bounded contexts”:
`src/money/` is a shared kernel: the type `Cents`, which Shows, Sales and
Payouts all use for money. Every amount is a whole number of cents, and
`parseCents` is the only way to make one.
In its “Files” block, change 001 to 016 to 001 to 017, and add a line after src/payouts/:
src/money/ Cents, shared by Shows, Sales, Payouts #money
The code figure gets the kernel (Figure 6).
{Door} ..........> {Sales} <.......... {Payouts}
: : :
: v :
:.............> {Shows} <...............:
{Shows}, {Sales}, {Payouts} ..> money/ NEW the shared kernel: Cents, parseCents,
addCents, multiplyCents, percentOf,
formatDollars (#money)
Inside {Sales}: routes/, services/, jobs/ ..> acl/ ACL ..> [Payment provider]
Only acl/ knows the provider's webhook body.
platform/ the pool, the job queue, settings, page layout, login, email,
the payment provider's client, the organizer dashboard.
Every context ..> platform/. platform/ ..> money/.
app.ts and worker.ts ..> each #.
Legend, added in this module
money/ a shared kernel: one folder of the model that several contexts
import, changed only when they all agree
Figure 6: the arrows between contexts did not change; Shows, Sales, Payouts and platform/ now depend on one money kernel.
Run the checks and the new grep:
npm run check
npm test
grep -rnE "in_dollars|toFixed" src
What you should see: npm run check prints no errors, and grep prints nothing. npm test passes all 23 tests. The end of its output (from one run):
✔ four tickets or more pay no booking fee (0.180917ms)
✔ a context imports another context only through its # entry (11.485573ms)
ℹ tests 23
ℹ suites 0
ℹ pass 23
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
Commit:
git add -A
git commit -m "Name money in the glossary and the map"
How a student’s hold works now
Follow Dee, a student, through the new code (Figure 7):
- Dee sends the hold form for one student ticket. The route checks the form and calls
createHold. findShowreadsshows.shows.price_centsis anintegerwith aCHECK, sopgreturns 1200, andShowcalls itCents.orderTotalCentsasksticketPriceCents, which returnspercentOf(1200, 80), 960.bookingFeeCentsreturns 150 for one ticket.addCentsmakes 1110.insertOrderstorestotal_cents1110.createPayment(totalCents, ...)accepts it, because it isCents. The payment page says “Pay $11.10 to TinyTickets?”.- Dee presses Pay. The webhook’s
amount_centsgoes throughparseCentsin the layer and becomesPayment.amountCents. markOrderPaidcomparespayment.amountCentswithorder.total_centsusing!==, which compares two numbers by value. It writes a ticket withprice_cents960.- The worker builds the email from
ticketPriceCents,bookingFeeCentsandorder.total_cents, and prints each amount withformatDollars.
(Buyer) --> [Web app] {Sales} routes/holds.ts student: 1
{Shows} db/shows.ts [[shows.shows]] price_cents 1200 --> Cents
{Sales} services/pricing.ts 960 + 150 = 1110 Cents
{Sales} db/orders.ts [[sales.orders]] total_cents 1110
platform/ createPayment(Cents) --> [Payment provider] "Pay $11.10"
[Payment provider] --> {Sales} acl/ ACL amount_cents --> parseCents --> Payment
{Sales} services/orders.ts amountCents !== total_cents: throw; else paid
[Worker] {Sales} jobs/send-confirmation.ts formatDollars --> [Email service]
Figure 7: every amount on Dee’s path is Cents from the moment it enters until formatDollars prints it.
This is part of the email the pretend email service caught, from one run of the app with the seed data (an excerpt; your codes and IDs will differ):
1 x student ticket, $9.60 each
Booking fee, $1.50
Total: $11.10
Paid: $11.10 (payment pay_615505069acedb69)
Your ticket codes:
E07CA7C2 (student)
Going deeper
A brand, a class or a bigger number
A brand is one of several ways to give money its own type in TypeScript. Figure 8 compares them.
| Option | What it buys | What it costs | Choose it when |
|---|---|---|---|
number, named priceCents |
nothing enforced | nothing | a short script with one developer and one currency |
Branded Cents |
unit mix-ups fail in tsc; a plain number at run time |
functions for arithmetic; one cast to keep honest | one currency and many call sites, as in TinyTickets |
Money class with #cents and currency |
the currency travels with the amount; behavior in one place | an object per amount, an equals method, mapping at every edge |
several currencies, or rules that split amounts |
bigint cents |
exact beyond 2^53 | no mixing with number; JSON.stringify throws |
totals beyond about $90 trillion |
| A decimal type | exact decimal fractions | a dependency today | rates applied many times, such as interest or exchange |
Figure 8: five ways to type money, from cheapest to most capable.
A class with a #private field is nominal in practice. tsc does not accept one class where another is expected, even when both have a #cents field, because each private name belongs to its own class. But a class costs more at the edges than a brand. JSON.stringify cannot see #private fields:
node -p "JSON.stringify(new (class Money { #cents = 1110 })())"
{}
Node.js type stripping also limits how you write the class. A constructor with a parameter property, such as constructor(private readonly cents: number) {}, fails when Node.js runs it (an excerpt):
SyntaxError [ERR_UNSUPPORTED_TYPESCRIPT_SYNTAX]: TypeScript parameter property is not supported in strip-only mode
Parameter properties have behavior at run time, so Node.js does not strip them (Node.js docs, TypeScript). The course’s tsconfig.json sets erasableSyntaxOnly, which TypeScript 5.8 added, so tsc reports them before Node.js does (TypeScript 5.8 release notes). A value object class must declare its fields one by one.
bigint cents are exact at any size, but JSON.stringify({ total: 1110n }) throws TypeError: Do not know how to serialize a BigInt, so every JSON edge needs code.
The choice flips in three cases:
- A second currency, such as an organizer who sells in euros, moves you from
Centsto aMoneytype that carries its currency. - Fractional rates applied many times, such as interest, move you to a decimal type.
- Totals beyond 2^53 cents move you to
bigint.
None of them is true for TinyTickets, which sells in US dollars only.
What the authors meant, and where TypeScript differs
Evans asks for more than immutability. Every operation of a value object should be free of side effects (Reference, p. 21), and many should be closed (p. 24). Closure of operations means an operation whose argument and result have the same type as the value itself. addCents(Cents, Cents): Cents is closed, so you can chain it without leaving the type.
Fowler’s Money pattern (2003) names the two problems that a money type solves: mixing currencies, and rounding, where it is easy to lose cents. He describes a Money class.
Both describe value objects as objects. The TypeScript brand is a value object without an object: equality is ===, and the behavior lives in functions next to the type.
It keeps Evans’ three properties: no identity, no change after creation, and operations without side effects. Our reading is that a brand fits a value with one field, and a small class fits a value with several. Evans and Fowler do not make this split.
Vaughn Vernon’s Implementing Domain-Driven Design (2013) gives value objects a chapter of their own, chapter 6, according to the publisher’s table of contents.
King’s article makes the same point from the other side. Many TypeScript codebases check a value and keep its wide type. King argues that the type should change after the check, so that later code cannot act on unchecked input.
Schema libraries can build parsers like parseCents from a declared shape. Standard Schema is a shared interface that lets a tool accept any library that implements it. In our judgment, a library is worth adding when you parse many nested request bodies, and not for three money fields.
What changed recently
- TC39, the committee that writes the JavaScript standard, withdrew the proposal for Records and Tuples, which would have given JavaScript objects with
===by value. Its repository was archived in April 2025. - Its successor direction, Composites, is at Stage 2 (as of November 2026). A composite of
{ x: 1, y: 4 }would be===to another with the same fields. Stage 2 means it is not part of the language yet. - The Decimal proposal, for exact decimal numbers, is at Stage 1 (as of November 2026). The Amount proposal, a value with a precision and a unit such as a currency, is at Stage 2, and has no arithmetic. Until one ships, whole cents in a
numberstay the plain answer. - Node.js 26, an LTS release since October 2026, runs
.tsfiles by stripping their types. That is why the course writes classes without parameter properties.
When a money type is too much
Skip Cents in a script or a small app with a few prices, one currency and one developer. A name like priceCents and integer math cost nothing, and the brand would add functions and casts for few call sites.
The brand also costs every new developer one more idea, and every edge one more parse. In TinyTickets, three contexts, a payment service, a worker and a dashboard all touch money, so the cost pays for itself. With one file that touches money, it would not. These limits are our judgment.
Check yourself
- Why did
createPayment(Number(order.amount_in_dollars), order.token)type-check, and why did the buyer see $0.11?
Answer
Number(...) returns a number, and createPayment took a number, so tsc had nothing to compare. The column held dollars, pg returned the string "11.10", and Number made it 11.1. The payment service treats every amount as cents, so it asked for 11.1 cents, which it printed as $0.11.
- What makes
Centsa value object, and why does===work on it when it fails on{ cents: 1110 }?
Answer
It describes an amount by its value alone, it has no identity, it never changes, and its operations return new values without side effects. At run time it is a number, and JavaScript compares numbers by value. Two objects are === only when they are the same object.
- What does the
Centsbrand prove about a number, and what can it not tell?
Answer
It proves that the number came through parseCents, the only function with as Cents, or from a row type for a checked integer column. It cannot tell twelve dollars from twelve cents, so the data it reads must already be in cents. That is why Step 3 renamed and converted the columns.
- Why does the dashboard call
parseCentsongross_cents, whilelistSoldTicketPricesdoes not?
Answer
gross_cents comes from sum(), which returns bigint, and pg returns bigint as a string, such as '3360'. price_cents is an integer column with a CHECK (price_cents >= 0), so pg returns a number that PostgreSQL has already checked.
- Five percent of three $13.50 tickets is 204 or 203 cents. Which one does TinyTickets use, and who decides?
Answer
204, because the fee is 5% of each ticket’s price, rounded per ticket. Leo decides, because the place of rounding is a business rule. The code keeps his answer in percentOf, payoutFor and the test “the fee is rounded per ticket”.
Exercise: round the fee once per show
Leo asks what organizers would get if the fee were rounded once per show instead of once per ticket. Answer with code.
Change the test “the fee is rounded per ticket” first, so that it expects the per-show answer, and run it. Then change payoutFor until it passes. Undo both changes at the end, because the rule stays per ticket.
Solution
In src/payouts/services/payouts.test.ts, change the second test:
test("the fee is rounded once per show", () => {
assert.equal(payoutFor([1350, 1350, 1350].map(parseCents)).feeCents, 203);
});
Run node --test src/payouts/services/payouts.test.ts. It fails with 204 !== 203. In src/payouts/services/payouts.ts, change the comment and the body of payoutFor:
// The site keeps 5% of the show's sales, rounded once per show.
let grossCents = parseCents(0);
for (const price of ticketPrices) {
grossCents = addCents(grossCents, price);
}
const feeCents = percentOf(grossCents, SITE_FEE_PERCENT);
return { grossCents, feeCents, amountCents: parseCents(grossCents - feeCents) };
Now both payout tests pass. The first one, with tickets of 1200, 960 and 1700 cents, gives 193 either way, so only the half cents of the $13.50 tickets show the difference. For those three tickets, the organizer would get one cent more. Undo both files:
git checkout src/payouts
Cheat sheet
Cheat sheet
- A number is not money: binary floats (
12 * 0.8), and no unit, so dollars and cents mix.- Value object: described by its value, no identity, immutable, operations without side effects.
- Equality by value:
===works on a number; two objects are equal only if they are the same object.- Brand:
number & { readonly [centsBrand]: true };tscrefuses a plain number; it cannot tell dollars from cents.- Parse at the edge:
parseCents(unknown): Centsis the only cast; webhooks andsum()strings go through it.- Columns: whole cents in
integercolumns withCHECK (... >= 0); never dollars, floats ormoney.- Rounding: a business rule, in one function (
percentOf), per ticket in TinyTickets.- Printing:
Intl.NumberFormat, once, at the end; nevertoFixedfor money.- Cost: functions for arithmetic, a parse at every edge, one more idea; skip it for a few prices.
Figure 9 is the whole module in one picture.
Enter webhook, sum() strings parseCents(unknown) --> Cents, or throw
Enter integer columns with CHECK row types say Cents
Inside pricing.ts, payouts.ts addCents, multiplyCents, percentOf
Leave pages, emails formatDollars --> "$11.10"
Leave createPayment, sendTransfer take Cents only
Shared src/money/ (#money) the shared kernel of Shows, Sales, Payouts
Figure 9: money becomes Cents where it enters, stays Cents inside, and becomes dollars only to print.
Every amount in TinyTickets is now Cents, the dollars columns are gone, the worker uses the same price rule as the hold, and all 23 tests pass. Next, Module 6 looks at the order itself: it has an identity, and today it can end up both paid and cancelled.
Sources
- Eric Evans, Domain-Driven Design Reference: Definitions and Pattern Summaries, Domain Language, 2015 (CC BY 4.0). Value Objects (p. 12), Side-Effect-Free Functions (p. 21), Closure of Operations (p. 24), Shared Kernel (p. 31).
- Martin Fowler, “Value Object”, 2016, and “Money”, in the catalog of Patterns of Enterprise Application Architecture, 2003.
- Alexis King, “Parse, don’t validate”, 2019.
- Vaughn Vernon, Implementing Domain-Driven Design, Addison-Wesley, 2013: table of contents.
- ECMAScript: The Number Type,
Number.prototype.toFixed; ECMA-402:ToIntlMathematicalValue; MDN:Intl.NumberFormat()constructor. - TypeScript: Type Compatibility, TypeScript 2.7 release notes (
unique symbol), TypeScript 5.8 release notes (--erasableSyntaxOnly), issue #202. - PostgreSQL 18 documentation: Aggregate Functions, Monetary Types. node-postgres: pg-types.
- Node.js documentation: TypeScript.
- TC39 proposals: Record & Tuple, Composites, Decimal, Amount.
- Standard Schema.