Home / Learn / 5 Contracts and the verifier

Release v0.4.0Edition 0.2

5.6 Day-to-day: billing

Page 7 of 11

5.6.1 What the billing step must do

Now the program from the start of the chapter. The store's billing step receives the lines of an invoice and a coupon. It prices the lines, takes the coupon off, splits the total between the customer's store credit and a card, and checks each refund the customer asks for against what was paid. Each rule of the business becomes one of the tools of this chapter:

Rule How the program states it
Money is never negative the refined kind Cents (section 5.3)
A rate is between 0 and 100, a line orders 1 to 99 units the refined kind Percent, and a range on a field
A coupon never takes off more than the invoice is worth ensures result <= amount on discount (section 5.2)
Store credit pays first, and the two parts add up to the total two ensures on pay
A refund never pays back more than was paid requires asked <= paid on refund (section 5.1), and a guard in its caller
Where the two money rules come from two requirements (section 5.5)

The verifier proves them all before the program runs. The invoice of this chapter has two lines; an invoice of any number of lines needs a list, which section 10.1 teaches. The parts below build the module in order, one declaration or a few at a time.

5.6.2 The rules and the kinds

The module opens with two requirements, which name the store's rules in the words of its billing policy, and the kinds, which carry the facts that hold of every value:

day-to-day/src/billing.unathe rules and the kindsuna
requirement BILLING_1
  text "A coupon or store credit never makes a customer pay less than 0 or more than the subtotal"
  source policy "Store billing rules"
  owner billing
  status active

requirement BILLING_2
  text "A refund never pays back more than the customer paid"
  source policy "Store billing rules"
  owner billing
  status active

--- An amount of money in cents. It is never negative.
pub kind Cents = Int where it >= 0

--- A share in whole percent.
pub kind Percent = Int in 0..100

--- One line of an invoice.
pub kind Line
  sku: Text
  unit_cents: Cents
  quantity: Int in 1..99

--- A coupon on the whole invoice.
pub kind Coupon = NoCoupon | PercentOff(rate: Percent) | CentsOff(amount: Cents)

--- How an invoice is paid: from store credit first, and the rest by card.
pub kind Payment
  credit: Cents
  card: Cents

5.6.3 Pricing the lines

line_total multiplies a price by a quantity: a product of two values, which the solver cannot read, so it binds the product and guards it, as Giving the solver the fact shows. subtotal adds the two lines. The sum of two Cents is never negative, a fact the solver reads at once, so subtotal needs no guard:

day-to-day/src/billing.unauna
--- What one line costs. The guard handles a case that cannot happen, since both factors
--- are at least 0; the solver cannot see that for itself.
pub line_total(line: Line) -> Cents
=
  let total = line.unit_cents * line.quantity
  if total < 0 then 0 else total

--- The sum of an invoice of two lines.
pub subtotal(first: Line, second: Line) -> Cents = line_total(first) + line_total(second)

5.6.4 The coupon

discount promises that it never takes off more than the amount. Each arm of its when (section 4.3) keeps the promise: no coupon takes 0, a percentage takes part of the amount, and a coupon worth more than the amount takes all of it and no more. percent_of multiplies two values, so it has the guard too, and its own ensures gives discount the fact it needs about that arm:

day-to-day/src/billing.unauna
--- `rate` percent of `amount`, rounded down. The guard cannot fire: both factors are at
--- least 0, and `rate` is at most 100.
percent_of(amount: Cents, rate: Percent) -> Cents
  ensures result <= amount
=
  let part = amount * rate / 100
  if part < 0 or part > amount then 0 else part

--- What a coupon takes off `amount`: never more than `amount`.
pub discount(amount: Cents, coupon: Coupon) -> Cents
  ensures result <= amount
  derived from BILLING_1
=
  when coupon
    is NoCoupon -> 0
    is PercentOff(rate) -> percent_of(amount, rate)
    is CentsOff(off) -> if off > amount then amount else off

5.6.5 Paying

pay splits a total between store credit and card. Its two clauses are the whole rule: the two parts add up to the total, and the credit used is never more than the customer has. The verifier proves both on both branches, and also that total - credit is a Cents where credit < total:

day-to-day/src/billing.unauna
--- Splits `total` between store credit and card, credit first.
pub pay(total: Cents, credit: Cents) -> Payment
  ensures result.credit + result.card == total
  ensures result.credit <= credit
  derived from BILLING_1
=
  if credit >= total then Payment(credit: total, card: 0) else Payment(credit: credit, card: total - credit)

5.6.6 Refunding

refund requires that the customer asks for no more than was paid. Its body only returns what was asked, and its ensures follows from its requires. The rule lives in the header, where every caller must meet it:

day-to-day/src/billing.unauna
--- What a refund pays back: what was asked, which may not be more than what was paid.
pub refund(paid: Cents, asked: Cents) -> Cents
  requires asked <= paid
  ensures result <= paid
  derived from BILLING_2
=
  asked

line_text writes one line of the invoice. refund_line is a caller of refund. It writes one line of the refund report, and it guards the call: when the customer asks for more than was paid, it says so, and it calls refund only in the else branch, where asked > paid is false, so asked <= paid holds. money writes an amount for a person to read, and divides and takes the remainder by the literal 100 only, so it has no division obligation at all:

day-to-day/src/billing.unauna
--- An amount for a person to read, such as 19.90.
pub money(cents: Cents) -> Text
=
  let rest = cents mod 100
  if rest < 10 then "{cents / 100}.0{rest}" else "{cents / 100}.{rest}"

--- One line of the invoice as it is printed.
pub line_text(line: Line) -> Text = "{line.quantity} x {line.sku} at {money(line.unit_cents)}: {money(line_total(line))}"

--- One line of the refund report: the refund, or why it is refused.
pub refund_line(paid: Cents, asked: Cents) -> Text
=
  if asked > paid
    "refund {money(asked)}: refused, only {money(paid)} was paid"
  else
    let back = refund(paid, asked: asked)
    "refund {money(back)}: paid back"

The contracts leave some things open on purpose. discount does not say how a percentage is rounded, and refund_line does not promise its exact words. Those are choices of the business, not rules of safety, and the examples in section 5.7 pin them down. A contract states what must never break, and an example states what the answer is for one case.

5.6.7 Running it

main prices two lines, applies a 10% coupon, pays with 50.00 of store credit, and checks two refunds:

day-to-day/src/billing.unacheckrununa
--- Prices an invoice of two lines, pays it, and checks two refunds.
pub main() -> Unit
  uses @console: Console[print]
=
  let lamp = Line(sku: "LAMP-01", unit_cents: 1990, quantity: 2)
  let desk = Line(sku: "DESK-02", unit_cents: 14900, quantity: 1)
  @console.print(line_text(lamp))
  @console.print(line_text(desk))
  let gross = subtotal(lamp, second: desk)
  let off = discount(gross, coupon: PercentOff(rate: 10))
  let total: Cents = gross - off
  let payment = pay(total, credit: 5000)
  @console.print("subtotal {money(gross)}, coupon -{money(off)}, total {money(total)}")
  @console.print("store credit {money(payment.credit)}, card {money(payment.card)}")
  @console.print(refund_line(total, asked: 3980))
  @console.print(refund_line(total, asked: 20000))

Look at let total: Cents = gross - off. Subtracting two Cents can give a negative number, so the verifier must prove gross - off >= 0. It can, but only because discount promises off <= gross. Remove that ensures, and this line no longer checks, as a caller that needs a promise the callee does not make shows. Contracts compose this way: each function's promise is the next function's fact.

In the day-to-day directory, una run . prints:

Output
2 x LAMP-01 at 19.90: 39.80
1 x DESK-02 at 149.00: 149.00
subtotal 188.80, coupon -18.88, total 169.92
store credit 50.00, card 119.92
refund 39.80: paid back
refund 200.00: refused, only 169.92 was paid

The second refund asks for 200.00 of an invoice of 169.92, so refund_line refuses it and never calls refund.

5.6.8 Tracing a rule to its proof

As in Following a rule to its proof, una trace BILLING_2 lists the function derived from the refund rule, its contract, and the proof of each obligation:

Terminal
$ una trace BILLING_2
requirement BILLING_2 (active)
  text "A refund never pays back more than the customer paid"
  source policy "Store billing rules"
  owner billing
billing.refund
  requires asked <= paid
  ensures result <= paid
  proven   ob-204eda00affc refinement    result >= 0
  proven   ob-ef9bbe64fc88 postcondition result <= paid

A person who answers for the refund policy can read this instead of the code: the rule, the function that implements it, the clauses of its header, and the proof. una trace BILLING_1 lists discount and pay the same way.

5.6.9 The whole program

The whole file, to read in one piece or to copy:

day-to-day/src/billing.unathe whole programcheckruntestuna
module billing

-- The billing step of a store: it prices an invoice, takes a coupon off, splits the payment
-- between store credit and card, and checks each refund against what was paid.

requirement BILLING_1
  text "A coupon or store credit never makes a customer pay less than 0 or more than the subtotal"
  source policy "Store billing rules"
  owner billing
  status active

requirement BILLING_2
  text "A refund never pays back more than the customer paid"
  source policy "Store billing rules"
  owner billing
  status active

--- An amount of money in cents. It is never negative.
pub kind Cents = Int where it >= 0

--- A share in whole percent.
pub kind Percent = Int in 0..100

--- One line of an invoice.
pub kind Line
  sku: Text
  unit_cents: Cents
  quantity: Int in 1..99

--- A coupon on the whole invoice.
pub kind Coupon = NoCoupon | PercentOff(rate: Percent) | CentsOff(amount: Cents)

--- How an invoice is paid: from store credit first, and the rest by card.
pub kind Payment
  credit: Cents
  card: Cents

--- What one line costs. The guard handles a case that cannot happen, since both factors
--- are at least 0; the solver cannot see that for itself.
pub line_total(line: Line) -> Cents
=
  let total = line.unit_cents * line.quantity
  if total < 0 then 0 else total

--- The sum of an invoice of two lines.
pub subtotal(first: Line, second: Line) -> Cents = line_total(first) + line_total(second)

--- `rate` percent of `amount`, rounded down. The guard cannot fire: both factors are at
--- least 0, and `rate` is at most 100.
percent_of(amount: Cents, rate: Percent) -> Cents
  ensures result <= amount
=
  let part = amount * rate / 100
  if part < 0 or part > amount then 0 else part

--- What a coupon takes off `amount`: never more than `amount`.
pub discount(amount: Cents, coupon: Coupon) -> Cents
  ensures result <= amount
  derived from BILLING_1
=
  when coupon
    is NoCoupon -> 0
    is PercentOff(rate) -> percent_of(amount, rate)
    is CentsOff(off) -> if off > amount then amount else off

--- Splits `total` between store credit and card, credit first.
pub pay(total: Cents, credit: Cents) -> Payment
  ensures result.credit + result.card == total
  ensures result.credit <= credit
  derived from BILLING_1
=
  if credit >= total then Payment(credit: total, card: 0) else Payment(credit: credit, card: total - credit)

--- What a refund pays back: what was asked, which may not be more than what was paid.
pub refund(paid: Cents, asked: Cents) -> Cents
  requires asked <= paid
  ensures result <= paid
  derived from BILLING_2
=
  asked

--- An amount for a person to read, such as 19.90.
pub money(cents: Cents) -> Text
=
  let rest = cents mod 100
  if rest < 10 then "{cents / 100}.0{rest}" else "{cents / 100}.{rest}"

--- One line of the invoice as it is printed.
pub line_text(line: Line) -> Text = "{line.quantity} x {line.sku} at {money(line.unit_cents)}: {money(line_total(line))}"

--- One line of the refund report: the refund, or why it is refused.
pub refund_line(paid: Cents, asked: Cents) -> Text
=
  if asked > paid
    "refund {money(asked)}: refused, only {money(paid)} was paid"
  else
    let back = refund(paid, asked: asked)
    "refund {money(back)}: paid back"

--- Prices an invoice of two lines, pays it, and checks two refunds.
pub main() -> Unit
  uses @console: Console[print]
=
  let lamp = Line(sku: "LAMP-01", unit_cents: 1990, quantity: 2)
  let desk = Line(sku: "DESK-02", unit_cents: 14900, quantity: 1)
  @console.print(line_text(lamp))
  @console.print(line_text(desk))
  let gross = subtotal(lamp, second: desk)
  let off = discount(gross, coupon: PercentOff(rate: 10))
  let total: Cents = gross - off
  let payment = pay(total, credit: 5000)
  @console.print("subtotal {money(gross)}, coupon -{money(off)}, total {money(total)}")
  @console.print("store credit {money(payment.credit)}, card {money(payment.card)}")
  @console.print(refund_line(total, asked: 3980))
  @console.print(refund_line(total, asked: 20000))

example "two lines add up"
  do subtotal(Line(sku: "LAMP-01", unit_cents: 1990, quantity: 2), second: Line(sku: "DESK-02", unit_cents: 14900, quantity: 1))
  expect result == 18880

example "a coupon worth more than the invoice takes the whole invoice"
  do discount(1000, coupon: CentsOff(amount: 1500))
  expect result == 1000

example "ten percent is rounded down"
  do discount(18885, coupon: PercentOff(rate: 10))
  expect result == 1888

example "store credit pays first"
  do pay(16992, credit: 5000)
  expect result.credit == 5000
  expect result.card == 11992

example "credit larger than the total leaves nothing for the card"
  do pay(1990, credit: 5000)
  expect result.card == 0

example "a refund within what was paid pays back what was asked"
  do refund(16992, asked: 3980)
  expect result == 3980

example "a refund of more than was paid is refused"
  do refund_line(16992, asked: 20000)
  expect result == "refund 200.00: refused, only 169.92 was paid"

example "an amount below 10 cents keeps its zero"
  do money(1905)
  expect result == "19.05"

Next:5.7 Testing it