Metakit / Domain types and row aggregates
Currency-safe money (Money) and fixed-scale decimals (Decimal)
Money.make(currency, options) creates an integer-backed Effect Schema in minor units (cents by default, scale: 2). Money.add and Money.sub require both operands to share the same currency and scale at compile time. For dimensionless fixed-scale numbers (tax rates, weights, percentages), use Decimal.make({ scale }). Both store a safe integer count of units of 10^-scale and offer the same operations: add, sub, neg, mulInt (multiply by a whole number), mul (multiply by a decimal, below), min, max, lt, lte, gt, gte, is, isNot, between, parse and format.
import { Schema } from 'effect'
import { Expr, Num } from '@doeixd/metakit'
import { Decimal, Money } from '@doeixd/metakit/domain'
const Usd = Money.make('USD')
const Invoice = Schema.Struct({
subtotal: Usd,
discount: Usd,
}).pipe(Expr.refine($ => Expr.all(Num.gte($.subtotal, 0), Num.lte($.discount, $.subtotal))))
const totalExpr = Expr.in({ row: Invoice }, ({ row }) => Money.sub(row.subtotal, row.discount))
const total = Expr.eval(totalExpr, {
row: { subtotal: Money.minor(Usd, 25_00), discount: Money.minor(Usd, 5_00) },
})
const text = Money.format(Usd, total)
// total -> 2000 (typed as MoneyValue<'USD', 2>), text -> '20.00 USD'
const tax = Decimal.roundHalfEven(150, 100) // 2 (banker's rounding)
void taxWhat happened: Money.minor(Usd, 25_00) builds 25.00 USD as the integer 2500, Money.sub took one amount from the other as integers, and Money.format wrote 2000 back as '20.00 USD'. Decimal.roundHalfEven(150, 100) rounds 150 / 100 = 1.5 to the even neighbour, 2.
Passing a Money.make('EUR') field to Money.sub alongside a USD field is a TypeScript error, and so is formatting an amount under the Schema of another currency or scale. Money.minor(money, amount), Money.parse(money, text) and Money.format(money, amount) take the Money.make Schema first and read the currency and the scale from it, so you state neither again (a currency code string is a type error, and a Schema that is not a Money.make one throws); Decimal.format(value, { scale }) takes the scale the value's type carries. Money.minor, Decimal.units, parse and roundHalfEven refuse anything that is not a safe integer (beyond ±(2^53 - 1) units a JavaScript number is no longer exact), and format throws on one.
Multiplying two amounts
Decimal.mul(left, right, { leftScale, rightScale, scale }) multiplies two decimals into one at scale, rounding half-even (an exact half goes to the even neighbour, so repeated roundings do not drift upward). Money.mul(amount, rate, { rateScale }) multiplies an amount by a decimal rate into the amount's currency and scale. You state each operand's scale because the stored integer does not carry it; the types refuse a scale that is not the operand's own, and an operand read from a field is checked against its Schema.
const Line = Schema.Struct({ net: Usd, vat: Decimal.make({ scale: 3 }) })
const vatExpr = Expr.in({ row: Line }, ({ row }) => Money.mul(row.net, row.vat, { rateScale: 3 }))
const vat = Expr.eval(vatExpr, {
row: { net: Money.minor(Usd, 12_35), vat: Decimal.units(200, 3) },
})
// vat -> 247 (2.47 USD: 12.35 x 0.200)Both build one core operation, num.mulScaled (Num.mulScaled(left, right, { shift }) builds it directly, with the number of decimal places the product moves down: leftScale + rightScale - scale, or a negative number to move it up). Its operands are integer counts of units, the product a * b is computed exactly in integers, and a missing operand gives null. The product, an operand and the result must each stay within ±(2^53 − 1): anything else is refused, not rounded and not null (Expr.evalResult returns the refusal, Expr.eval throws it, and a rule that meets one does not hold). The product is checked before it is rounded, so MAX_SAFE_INTEGER units at scale 2 times 1.00 is refused although its result would fit. Each reader either does what evaluation does or refuses by name:
| Reader | What it does with a decimal product |
|---|---|
Expr.eval, Expr.judge and partial evaluation | Exact, as above. Expr.judge answers False for a product it refuses, the refusal as its witness. |
@doeixd/metakit/sql and @doeixd/metakit/drizzle (SQLite and Postgres) | Integer arithmetic only: an exact half goes to the even neighbour on both, and the answer is NULL where evaluation refuses. Postgres forms the product as numeric, which cannot overflow, and SQLite carries an overflowing product on as a float that lands past the bound, so neither raises nor returns a wrong number. A column that is not known to be an integer (a Schema.Finite field, say) is refused by name; use a Schema.Int, Decimal or Money field. |
The interval and zone checker (Abstract) | Bounds the result from the operands' intervals, rounding each end half-even. It says a product has a value only where the operands are integers and the product stays in range, so a rule over unbounded operands is not proved. |
The Z3 prover (@doeixd/metakit/prove) | Exact over integers, with the solver's div and mod. A product of two unbounded fields is non-linear, so the solver may give up and answer Unknown; an operand that is not an integer sort is Unknown. |
Rows.sum (@doeixd/metakit/aggregates) | Takes a decimal product as its contribution, as it takes any integer-valued expression. |
import * as Rows from '@doeixd/metakit/aggregates'
const totalVat = Rows.sum(Line, $ => Money.mul($.net, $.vat, { rateScale: 3 }))
totalVat.evaluate([{ net: Money.minor(Usd, 12_35), vat: Decimal.units(200, 3) }])
// 247SQL returns NULL for a refused product. A Null.isNull test of a row's decimal product lowers to SQL that returns true for a missing operand and NULL for overflow. A WHERE clause keeps only rows where the test gives true.
SQL also tests for refusal inside Null.coalesce, Eq.is, Eq.isNot, Eq.in, Bool.or, negated Bool.and, a Match with a fallback, and related-row folds. For example, when a comparison refuses, Bool.or gives NULL even if its other branch is true. If SQL cannot express an operand's refusal at one of these positions, lowering names it in SqlUnsupportedError. A custom operation that may refuse inside Null.coalesce gives this error even with a registered SQL implementation.
Num.add, Num.sub and Num.mul use the same range tests. A refused operand or result past ±(2^53 − 1) gives NULL in SQL for both integer and Schema.Finite fields. Lowering evaluates arithmetic over request values alone before generating SQL and reports any refusal at that point.
opProperties declares no property of num.mulScaled. Commutativity holds (either order gives one answer, which a test checks) but no reader reads it for this operation. The unit that leaves a product alone is 10^shift, which depends on the call and which one row of the table cannot name, and the result is monotone in an operand only for operands of one sign, where the checker reads a direction that holds for every value.