strict-script strict-script

Examples

transfer

The sources of the example, as they are at the commit this site was built from. Examples says what each example is about, and the playground runs a text of the language in the page.

#bank.sts

examples/transfer/bank.sts
// A resource: a transaction has one owner, and is ended on every way out of the scope that holds it.

export resource Transaction { entries: string[] } end rollback

// The one way to get a transaction.
export function begin(): Transaction {
  { entries: [] }
}

export function debit(mut tx: Transaction, account: string, cents: number) {
  tx.entries = [...tx.entries, `${account} -${cents}`]
}

export function credit(mut tx: Transaction, account: string, cents: number) {
  tx.entries = [...tx.entries, `${account} +${cents}`]
}

// Takes the transaction for good, and gives what it wrote. Nobody can use it after.
export function commit(tx: Transaction): string[] {
  const written: { entries: string[] } = tx
  written.entries
}

// What is called when a transaction is still there at the end of the scope that held it.
export function rollback(tx: Transaction) {
  const dropped: { entries: string[] } = tx
  console.log(`rolled back ${dropped.entries.length} entries`)
}

#transfer.sts

examples/transfer/transfer.sts
// Ownership: a transaction is ended exactly once, and no line is written for the paths that fail.
import { Transaction, begin, commit, credit, debit, rollback } from "./bank.sts"

export function transfer(from: string, to: string, cents: number): Result<string[], "nothing-to-move"> {
  const tx = begin()                               // rolled back when its scope ends with it still there
  debit(mut tx, from, cents)
  if (cents <= 0) return Err("nothing-to-move")    // rolled back here
  credit(mut tx, to, cents)
  Ok(commit(tx))                                   // given away: any use of `tx` after this is refused
}

function check(cents: number): Result<number, string> {
  if (cents > 1000) Err("over the limit") else Ok(cents)
}

// The early return of `?` ends an open transaction too.
export function checked(from: string, to: string, cents: number): Result<string[], string> {
  const tx = begin()
  debit(mut tx, from, check(cents)?)
  credit(mut tx, to, cents)
  Ok(commit(tx))
}

export function main() {
  for (const cents of [250, 0]) {
    match transfer("ada", "grace", cents) {
      Ok(entries) => console.log(entries.join(", ")),
      Err(reason) => console.log(reason),
    }
  }
  match checked("ada", "grace", 5000) {
    Ok(entries) => console.log(entries.join(", ")),
    Err(reason) => console.log(reason),
  }
}
Esc

    Type a word of the language, a rule, a command: mut, extern, match-not-covered.