Skip to Content
Formulas

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

WhereWhat the formula works outNames it can useCLI
A state metricOne value from several reads at the same blockIts callsmetric define --call … --value
A group columnOne value per member of the groupIts calls, the group’s other columnsgroup column add --call … --formula
A table’s calculated columnOne value per rowIts calls, the row’s other columns, the row’s eventstable create or table update --formula
A table’s status ruleWhich label a row getsThe row’s columns and events--status
A table’s finish ruleWhen a row is finishedThe row’s columns and events--finished
An activity metricWhat each event adds, and which events countThe event’s fields, its reads, earlier fieldsmetric define --each … --value --where --field
An activity tableA figure on each event rowThe event’s fields, its readstable create --each … --field
A report lineA value summed over the report’s contractsIts calls--row "formula:<Label>=<expr>; call …"
A messageText with values from what happenedThe 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.

CallReads
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().memberOne 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

NameMeans
pooledA call, or an event’s field, by its name
{Requested}A column of the same row or group, by its label
swapInfo.fromAmountA member of a struct field
"0xA0b8…eB48"A quoted address or text
24h, 7d, 30m, 2wA duration, in seconds
true, false, nullLiterals

Operators

OperatorMeaning
+ - * /Arithmetic
^Power, any exponent: 1.0001 ^ (tick / 2)
< <= > >= == !=Comparison: yes or no
and or notCombine 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

FunctionReturns
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

FunctionReturns
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

FunctionReturns
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 * 100

Table rows

FunctionReturns
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

FunctionReturns
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

FunctionReturns
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 usd

What 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 contract

Only 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.

Last updated on