navid/haze / 13ba2f33894c67a16c9bf8afb859ffc1b9f11d054fe58f1e57ae1d2d57994a9b / samples/baseline_3/sample4.hz

sample4.hz

← samples/baseline_3 · 2791 bytes · raw · download

// Bank account: contracts over immutable data, braced style.

const MAX_BALANCE i64 = 1_000_000_000

type Account {
    id      i32
    balance i64
}

type Transfer {
    src Account
    dst Account
}

pure fn solvent(a Account) bool => a.balance >= 0 && a.balance <= MAX_BALANCE

contract Solvent(a Account) {
    pre solvent(a)
}

contract Funded(a Account, amt i64) {
    pre {
        amt > 0
        amt <= a.balance
    }
}

contract Room(a Account, amt i64) {
    pre {
        amt > 0
        a.balance + amt <= MAX_BALANCE
    }
}

fn deposit(a Account, amt i64) Account
    : Solvent(a)
    : Room(a, amt)
    : post r => r.id == a.id
    : post r => r.balance == a.balance + amt
    : post r => solvent(r)
    =>  Account{ id = a.id, balance = a.balance + amt }

fn withdraw(a Account, amt i64) Account
    : Solvent(a)
    : Funded(a, amt)
    : post r => r.id == a.id
    : post r => r.balance == a.balance - amt
    : post r => solvent(r)
    => Account{ id = a.id, balance = a.balance - amt }

fn transfer(src Account, dst Account, amt i64) Transfer
    : Solvent(src)
    : Solvent(dst)
    : Funded(src, amt)
    : Room(dst, amt)
    : pre src.id != dst.id
    : post r => r.src.id == src.id && r.dst.id == dst.id
    : post r => r.src.balance == src.balance - amt
    : post r => r.dst.balance == dst.balance + amt
    : post r => solvent(r.src) && solvent(r.dst)
    => Transfer{ src = withdraw(src, amt), dst = deposit(dst, amt) }


// Deposit `amt` once a month for `months` months.
fn save(a Account, amt i64, months i64) Account
    : Solvent(a)
    : pre amt > 0
    : pre months >= 0
    : pre a.balance + amt * months <= MAX_BALANCE
    : post r => r.id == a.id
    : post r => r.balance == a.balance + amt * months
    : post r => solvent(r)
{
    var acc = a
    for i in 0..months
        : invariant acc.balance == a.balance + amt * i
    {
        acc = deposit(acc, amt)
    }
    return acc
}

fn main() {
    const alice = Account{ id = 1, balance = 100 }
    const bob   = Account{ id = 2, balance = 50 }

    const a1 = deposit(alice, 25)
    print(a1.balance)               // 125

    const a2 = withdraw(a1, 100)
    print(a2.balance)               // 25

    const t = transfer(a2, bob, 20)
    print(t.src.balance)            // 5
    print(t.dst.balance)            // 70

    const s = save(t.src, 10, 3)
    print(s.balance)                // 35

    // Each of these should be rejected at compile time:
    //
    // withdraw(a2, 1000)           // pre `amt <= a.balance` not provable (a2.balance == 25)
    // transfer(a2, a2, 5)          // pre `src.id != dst.id` not provable
    // deposit(a2, 0)               // pre `amt > 0` not provable
    // save(a2, 1000000000, 2)      // pre `a.balance + amt * months <= MAX_BALANCE` not provable
}