Formulas
A formula works out a value from other values: a ratio, a difference, a share, a price in dollars. It is how a metric, a column or a report line shows a figure a contract does not hold directly.
pooled / shares
{Requested} - {Paid}
usd(abs(amount0) * fee / 1000000, t0)Every computed value in contract.dev uses the same formula language. What a formula can name depends on where it is used.
Where formulas are used
| Where | What the formula works out | Names it can use | CLI |
|---|---|---|---|
| A state metric | One value from several reads at the same block | Its calls | metric define --call … --value |
| A group column | One value per member of the group | Its calls, the group’s other columns | group column add --call … --formula |
| A table’s calculated column | One value per row | Its calls, the row’s other columns, the row’s events | table create or table update --formula |
| A table’s status rule | Which label a row gets | The row’s columns and events | --status |
| A table’s finish rule | When a row is finished | The row’s columns and events | --finished |
| An activity metric | What each event adds, and which events count | The event’s fields, its reads, earlier fields | metric define --each … --value --where --field |
| An activity table | A figure on each event row | The event’s fields, its reads | table create --each … --field |
| A report line | A value summed over the report’s contracts | Its calls | --row "formula:<Label>=<expr>; call …" |
| A message | Text with values from what happened | The event’s fields, the row’s columns | --message "… {expr} …" |
Alert rules use the same operators, over the value being watched: see Notifications.
Calls
A call reads one thing from the chain and gives it a name the formula uses.
| Call | Reads |
|---|---|
name=view() | A view function’s result: pooled=getTotalPooledEther() |
name=view(args) with <args> | A view with arguments: debt=accountDebt(address) with id() |
name=view() on <target> | A view on another contract: bal=balanceOf(address) on 0xA0b8… with self |
name=view().member | One output of a view that returns several: paid=getWithdrawalBatch(uint32).normalizedAmountPaid with id() |
name=balance(<target>) | The chain’s own coin held by an account: eth=balance(self) |
name=slot(<target>, <key>) | One storage word: owner=slot(self, keccak({Lender}, 3)) |
A target is self (the contract the value is on), a 0x… address, or a view with no arguments that answers with an address, such as asset() or token0(). An argument is a literal, self, the row’s id id(), a column {Label}, or an earlier call by name.
decimals <n> scales a call’s result down by 10^n: pooled=getTotalPooledEther() decimals 18. A call that returns an array answers a list.
Names
| Name | Means |
|---|---|
pooled | A call, or an event’s field, by its name |
{Requested} | A column of the same row or group, by its label |
swapInfo.fromAmount | A member of a struct field |
"0xA0b8…eB48" | A quoted address or text |
24h, 7d, 30m, 2w | A duration, in seconds |
true, false, null | Literals |
Operators
| Operator | Meaning |
|---|---|
+ - * / | Arithmetic |
^ | Power, any exponent: 1.0001 ^ (tick / 2) |
< <= > >= == != | Comparison: yes or no |
and or not | Combine conditions |
list[i] | A list’s element, from 0 |
Numbers are exact decimals, to 36 places. A value that is unknown anywhere in arithmetic makes the result unknown; an unknown condition does not hold.
Functions
Numbers
| Function | Returns |
|---|---|
abs(x) | The size of a number, sign dropped |
min(a, b, …) · max(a, b, …) | The least or the greatest |
round(x) · round(x, places) | Rounded, half to even |
floor(x) · ceil(x) | Rounded down or up |
sqrt(x) · ln(x) · exp(x) | Square root, natural log, e to a power |
if(condition, then, else) | One of two values |
first(a, b, …) | The first of its arguments that is known |
Tokens and dollars
| Function | Returns |
|---|---|
amount(raw, token) | A base-unit amount in whole tokens, scaled by the token’s decimals |
usd(raw, token) | A base-unit amount in dollars |
price(token) | One token in dollars |
On an event, dollars are at the token’s price on the day the event happened. Elsewhere they are at the price now. A token is its address: asset(), token0(), an event field that holds an address, a column, or a quoted "0x…". Nothing is inferred from a field’s name: an amount is in a token only when the formula names it.
Lists
| Function | Returns |
|---|---|
len(list) | How many elements |
sum(list) | The elements added up |
indexOf(list, x) | The position of x, from 0 |
contains(list, x) | Whether x is in the list |
keccak(a, b, …) | The keccak-256 hash of its arguments: a mapping’s storage key |
Earlier readings
ago(call, 7d) is what a call answered that long before the reading, from 1 minute to 365 days. It works in state metrics, group columns and report lines:
(rate - ago(rate, 7d)) / ago(rate, 7d) * 365 / 7 * 100Table rows
| Function | Returns |
|---|---|
id() | The row’s id |
now() · found() | The time now; when the row was found |
seen(Event) | Whether the row has had this event |
at(Event) | When the row last had this event |
latest(Event) | Whether this is the row’s most recent event |
timeIn({Status}) · since({Status}) | How long, or since when, a status column has held its label |
inList() | Whether the row’s id is still in the list the table reads |
failed({Column}) | Whether a read for the row got no answer |
contract() · asset() · token0() · token1() | The row’s contract, and the tokens it answers with |
A calculated column also adds up the row’s events by name: sum(Event.field), count(Event), min, max, first, last.
Split columns
A column split by a field keeps one total per value: --sum "Transfer.value:Holdings by token" keeps a total for each token, and by tickLower,tickUpper one for each price range. each({Column}, formula) works the formula out for every part and gives back the list; inside it, amount is the part’s total and the split’s fields go by their names. sum() adds the list up.
sum(each({Holdings}, usd(amount, token)))A calculated column is worked out again on every refresh, so this is what is held now, at today’s prices.
sum(WithdrawalQueued.normalizedAmount) - sum(WithdrawalExecuted.normalizedAmount)Events
| Function | Returns |
|---|---|
emitter() | The contract that emitted the event |
sender() | The address that signed the transaction |
time() · block() · tx() | The event’s block time, block and transaction |
event() | The event’s name, when several are counted |
Messages
| Function | Returns |
|---|---|
name(address) | What an address is called: its label or ENS name, else the short address |
symbol(token) | A token’s symbol |
door() | The contract the signer called, such as the router a swap came through |
Examples
A share price, as a state metric:
contract-dev metric define "stETH per share" --on steth \
--call "pooled=getTotalPooledEther() decimals 18" --call "shares=getTotalShares() decimals 18" \
--value "pooled / shares"What each market holds above what it must, as a group column:
contract-dev group column add markets --label "Headroom" \
--call "held=totalAssets()" --call "required=coverageLiquidity()" \
--formula "held - required" --token "asset()" --show usdWhat is still owed on each withdrawal round, as a table column:
contract-dev table update "Withdrawal rounds" \
--formula "Outstanding=max({Requested} - {Paid}, 0); token asset(); show usd"Swap fees in dollars, as an activity metric:
contract-dev metric define "Swap fees" --on tag:pools --each Swap \
--read "fee=fee()" --read "t0=token0()" \
--value "usd(abs(amount0) * fee / 1000000, t0)" --split contractOnly the large swaps, with the pool’s token read for each event:
--read "t0=token0()" --where "usd(abs(amount0), t0) > 100000"What a protocol’s pools hold, from Uniswap v4’s liquidity changes kept per price range and each pool’s price after its last swap:
contract-dev table update Pools \
--sum "ModifyLiquidity.liquidityDelta:Liquidity on id from PoolManager by tickLower,tickUpper" \
--event "Swap.id from PoolManager" --formula "Price=last(Swap.sqrtPriceX96)" \
--formula "Deposits=sum(each({Liquidity}, usd(amount * (s(tickUpper) - p) / (p * s(tickUpper)), {Token 0}) + usd(amount * (p - s(tickLower)), {Token 1})))"Here s(t) stands for 1.0001 ^ (t / 2) and p for min(max({Price} / 2 ^ 96, s(tickLower)), s(tickUpper)), written out in full in the formula.
A row’s label from its events:
--status "Stage: Expired=latest(WithdrawalBatchExpired); Paying=seen(WithdrawalBatchPayment); Queued"See Metrics, Tables and the CLI reference for each command’s flags.