Skip to content
LogoLogo

View and pure

Each function declares how much it may do: pure reads only its arguments, view also reads state, and a plain function may also write, emit, and defer. The compiler checks each body, and everything it calls, against the declaration.

view-and-pure.lithe
(* Every function declares its effect. The compiler checks that the body does
   no more than it says.
 
     pure function      reads only its arguments
     view function      also reads storage and the Evm context
     function           also writes storage, emits events, and defers calls *)
 
storage is record {
  rateBps : uint;
}
 
pure function fee(const amount : uint; const rateBps : uint) : uint is
  amount * rateBps / 10_000
 
view function currentFee(const amount : uint) : uint is
  fee(amount, storage.rateBps)
 
function setRate(const rateBps : uint) is {
  storage.rateBps := rateBps;
}
 
(* `external` exposes a function in the ABI. External views are `view` in the ABI,
   external pure functions are `pure`. *)
external pure function quote(const amount : uint; const rateBps : uint) : uint is
  fee(amount, rateBps)
 
external view function preview(const amount : uint) : uint is
  currentFee(amount)
 
external function configure(const rateBps : uint) is {
  setRate(rateBps);
}

Violations are compile errors that name what went wrong:

declared effect is weaker than the body's: pure function `who` reads `Evm.sender`
declared effect is weaker than the body's: view function `mid` calls `bump`, which is stateful