Libraries and Using
Cambrian offers two complementary ways to reuse pure helpers: named
library blocks and using … for T method-call sugar.
library Name { … }
A library is a named scope of pure fn, const, and type items only. Bodies
may not touch entity state, msg::*, or temporal references — the same purity
envelope as a free pure fn.
library SafeMath {
pure fn add(a: u256, b: u256) -> u256
where (a + b >= a) : throw Overflow() { a + b }
pure fn sub(a: u256, b: u256) -> u256
where (a >= b) : throw Underflow() { a - b }
}
Call library functions with a qualifier, or attach them via using (below).
using Lib for T
Attach every suitable function from a library as a method on type T:
using SafeMath for u256;
entity Vault {
routes {
deposit(amount: u256) => [
m_balance := m_balance.add(amount)
]
}
m_balance: u256 {
in deposit(amount) => m_balance.add(amount)
}
}
recv.fn(args) rewrites to Lib.fn(recv, args) (or the free pure fn form)
before codegen. Chained calls such as x.add(1).mul(2) work when each step’s
return type matches the next receiver.
using { fn1, fn2 } for T
Attach selected free pure fns without a library wrapper:
pure fn double(x: u256) -> u256 { x * 2 }
pure fn triple(x: u256) -> u256 { x * 3 }
using { double, triple } for u256;
entity Foo {
routes {
bump() => []
}
m_n: u256 {
in bump() => m_n.double().triple()
}
}
Rules of thumb
- The first parameter of each attached function must match the
fortype. - Method names must not collide with built-in methods on
Vec,HashMap,String, orAddress. - Libraries and free
pure fns may live in imported.camfiles. See Program Structure and the Contract Standard Library.
EVM lowering
Each Cambrian library becomes a Solidity library with internal pure
(or equivalent) functions. Call sites use LibName.fn(args). Free pure fns
outside a library remain top-level Solidity helpers.