# Contracts and the VM
**AresLang, the ARES container, the StarW VM, and the contract layer — as they are in this tree.**
This file has two readers and serves both without choosing between them.
The first is writing a contract. Read Part I, Part VII and **Known limits**. The parts you can
skip are marked; the parts you cannot are the ones that will otherwise cost you money.
The second is reimplementing the VM so that it agrees with this one byte for byte and state
root for state root. Read all of it, and treat every cited `file.ts:line` as the normative
text — this document explains the code, it does not replace it. Where the two disagree, the
code is right and this file is a bug.
**Line numbers are as of commit `9220195`.** They move;
the symbol named beside each one does not, and `npm run citations` re-reads every citation
written as a symbol in backticks followed by its `src/path.ts:NNN`. §6.5.1 and the record-size
entries under **Known limits** were written against that commit; the rest carry their original
citations.
Every gas number here is taken from the opcode table in `runtime/vm.ts:169` or from a run
recorded in a test that asserts it exactly. Where a cost is not measured anywhere, this file
says **unmeasured** rather than estimating it.
House names, from `docs/NAMING.md`: **AresLang** is the language, **STARW VM** the engine,
**Sindri** the contract state ledger, **Nidavellir** the host environment, **Glasir** the
state tree, **Hephaestus** the standard library, **Daedalus** the template catalogue.
---
## Table of contents
- [Part I — AresLang](#part-i--areslang)
- [Part II — The ARES container](#part-ii--the-ares-container)
- [Part III — Storage encoding, and the fork it caused](#part-iii--storage-encoding-and-the-fork-it-caused)
- [Part IV — The StarW VM](#part-iv--the-starw-vm)
- [Part V — Determinism](#part-v--determinism)
- [Part VI — Sindri: the contract state ledger](#part-vi--sindri-the-contract-state-ledger)
- [Part VII — Daedalus: the templates](#part-vii--daedalus-the-templates)
- [Part VIII — Hephaestus: the standard library](#part-viii--hephaestus-the-standard-library)
- [Known limits](#known-limits)
---
# Part I — AresLang
## 1.1 What a contract is
One file, one `contract` block, and nothing outside it. There are no imports, no modules, no
includes and no preprocessor. `parseContract` `runtime/parser.ts:347` parses exactly one contract and then
`expectEof()` — trailing text is a syntax error, not a second declaration.
```
contract := 'contract' IDENT '{' member* '}'
member := stateDecl | eventDecl | functionDecl
stateDecl := 'state' IDENT ':' type ('=' expression)? ';'
eventDecl := 'event' IDENT '(' paramList? ')' ';'
functionDecl := ('view')? 'fn' IDENT '(' paramList? ')' ('->' scalarType)? block
```
The grammar in full is at `runtime/parser.ts:4-24`. A contract with zero functions is refused
(`parseContract` `runtime/parser.ts:372`) because a contract nobody can call is a contract nobody deployed on
purpose.
The source text is the whole of what a contract is. A deploy record carries **source**, not
bytecode (`src/core/contract-state.ts:498-505`), and every node recompiles it. That makes
`runtime/compiler.ts` consensus code: two nodes on different compiler versions derive
different bytecode and therefore different addresses from the same record, which is why
`ARES_COMPILER_VERSION` (`runtime/compiler.ts:82`, currently `areslang-1.2.0`) is committed
with the contract rather than left as a build detail.
## 1.2 Types
Five scalar types, and that is the entire value domain (`runtime/parser.ts:27`):
| Type | Runtime representation | Zero |
|---|---|---|
| `uint` | `bigint`, non-negative by the type system | `0n` |
| `int` | `bigint`, arbitrary precision | `0n` |
| `bool` | `boolean` | `false` |
| `address` | `string` — a refined `string` | `""` |
| `string` | `string`, a sequence of UTF-16 code units | `""` |
At runtime there are only three: `bigint`, `string`, `boolean`
(`AresValue` `runtime/bytecode.ts:75`). `uint`/`int` and `address`/`string` are distinctions the **compiler**
maintains and the VM does not carry.
**There is no floating point, and there is no fixed width.** Integers are arbitrary precision,
so `+` and `*` cannot wrap. What they can do is get large, which is priced and then refused —
see §4.6.
Assignability (`assignable` `runtime/compiler.ts:449`):
- `uint` widens to `int`. Every `uint` is an `int`.
- `int` does **not** narrow to `uint`. That direction is exactly how a negative balance gets
written, and it is refused at compile time.
- `address` and `string` are mutually assignable. They are the same value at runtime and
differ only in the ABI and in what `validateArgs` will accept as an argument (§6.7).
Equality is only meaningful inside a family (`runtime/compiler.ts:923`): `1 == "1"` is a
compile error, not a `false`.
### 1.2.1 `uint` subtraction is the reason the compiler has types
`runtime/compiler.ts:796-808`. When both operands are `uint`, `-` compiles to `SUBU`, the
checked unsigned subtract, which **reverts** rather than producing a negative. Every other
combination compiles to `SUB` and yields `int`.
That single decision is what the type checker exists for. `balances[from] - amount` is the
line in every token ever written. On a machine with fixed width the unchecked version wraps
`0 - 1` to the largest representable number and the attacker's balance becomes astronomical;
on this machine, which has no width to wrap past, it produces a **negative** balance that
every later `>=` reads as "plenty". Different arithmetic, same theft. Neither wrapping nor
saturation is an answer, because both invent a number nobody asked for. `SUBU` reverts and the
whole call is undone (`runtime/vm.ts:405-428`).
Unary minus is signed by definition, uses the unchecked `SUB`, and yields `int`
(`runtime/compiler.ts:637-646`). So `-balance` is an `int` and cannot be stored back into a
`uint` slot: the sign stays visible in the type instead of being lost.
## 1.3 State
```ares
state supply: uint = 0;
state contractOwner: address = caller;
state balances: map
;
state allowances: map>;
```
A scalar state variable is one flat storage slot named by its identifier. An initializer is an
arbitrary expression, evaluated in a compiler-generated function called `__init`
(`ARES_INIT_FUNCTION` `runtime/compiler.ts:100`) that Sindri runs once at deployment
(`src/core/contract-state.ts:726`).
**`caller` inside a state initializer is the authenticated deployer.** That is why no template
in `templates/` needs a `claimOwnership` call and none has a window in which a stranger could
claim it. Sindri authenticates the deployer *before* it runs the initializer
(`src/core/contract-state.ts:709-711`), precisely because an unauthenticated deployer is an
unauthenticated `CALLER` inside the function that usually sets ownership.
`__init` is reserved: a contract that declares a function by that name is refused
(`runtime/compiler.ts:75`).
### 1.3.1 Maps
A map is **only ever a state declaration**. There is no map value, no map argument, no map
return, and no map literal. `balances[addr]` names a storage slot and that is the whole of it
(`runtime/parser.ts:20-23`).
Consequences, all enforced:
- A map cannot be assigned as a whole (`runtime/compiler.ts:332`).
- A map is not a value and cannot be read bare (`runtime/compiler.ts:621`).
- A partly-indexed map is still a map, so `allowances[owner]` is a compile error
(`runtime/compiler.ts:707`).
- A map state declaration cannot have an initializer (`runtime/parser.ts:337-343`). An
initializer would have to enumerate entries, which is the unbounded, order-sensitive
construct that must not exist on a deployment path.
- Nesting is bounded at `MAX_MAP_DEPTH = 8` (`runtime/parser.ts:37`). "Two is an allowance
table; eight is a mistake."
A map owns no storage of its own. Every entry is an ordinary slot in the contract's flat
storage, under a name derived from the map name and the key values — Part III.
**An entry nobody wrote reads back as the zero of its declared value type**, fixed by the
descriptor carried in the instruction rather than guessed at runtime
(`mapZeroValue` `runtime/bytecode.ts:258`).
There is no way to iterate a map, count its entries, or delete one. That is deliberate; see
Known limits.
## 1.4 Functions, `view`, and the ABI
```ares
fn transfer(to: address, amount: uint) -> uint { ... }
view fn balanceOf(who: address) -> uint { ... }
```
Parameters and returns are scalars only. A function returns at most one value.
Parameters arrive on the VM stack in call order and are bound to locals in reverse
(`runtime/compiler.ts:159-163`). Every function ends with an emitted `HALT`
(`runtime/compiler.ts:166`), so falling off the end is a normal, successful return.
### `view`
`view` is enforced in three independent places, and none of the three is load-bearing alone.
1. **Compile time.** A `view` function cannot assign a state variable
(`runtime/compiler.ts:339`), write a map (`runtime/compiler.ts:527`), emit an event
(`runtime/compiler.ts:393`), or call `transfer` (`runtime/compiler.ts:570`).
2. **Execution time.** Sindri sets `readOnly` from the ABI's `stateMutability`
(`src/core/contract-state.ts:788`), and the VM refuses `STORE`, `MSTORE`, `EMIT` and
`TRANSFER` outright while it is set (`requireWritable` `runtime/vm.ts:626`). The
compile-time check only covers code *this node compiled*; this covers a module that arrived
as bytes.
3. **After the fact.** Sindri compares the storage the call produced against the storage it
started with and refuses the record if they differ
(`src/core/contract-state.ts:811-813`).
Separately, the host itself refuses a paying view at the seam
(`src/core/contract-state.ts:399`), because Sindri knows the mutability before it builds the
host and can give the contract a revert it can reason about instead of having its whole record
refused.
### ABI derivation
The ABI is derived from the source in the same pass that produces the bytecode
(`buildAbi` `runtime/compiler.ts:230`). It is not written by hand and there is no place to
write one:
- every `fn` becomes `{ type: 'function', name, inputs, outputs, stateMutability }`, where
`stateMutability` is `'view'` or `'nonpayable'` — never `'payable'`, because a call record
carries no value;
- every `event` becomes `{ type: 'event', name, inputs }`.
A caller *may* pass a declared ABI to `compileAresContract`, in which case it is compared
against the derived one and a mismatch is a compile error
(`runtime/areslang.ts:62-64`, `abiMatches` `runtime/areslang.ts:98`). The comparison is over
a canonical form sorted by `type:name` with byte ordering, not locale ordering
(`runtime/areslang.ts:86-98`). So the ABI and the code cannot drift: there is only one of
them, and the other is an assertion about it.
## 1.5 Statements
`let`, assignment, indexed assignment, `transfer(...)` as a statement, `return`, `if`/`else`,
`while`, `for`, `require`, `emit` (`runtime/parser.ts:412-512`).
**`require(condition, "message")`** — the message defaults to `"requirement failed"`
(`runtime/parser.ts:468`) and travels to the caller verbatim as `revertReason`. The condition
must be `bool`; a `uint` condition is a compile error (`runtime/compiler.ts:386`).
**`emit Name(args...)`** — the event must be declared, the arity must match, and every
argument must be assignable to the declared parameter type (`runtime/compiler.ts:392-407`).
The compiler pushes the arguments, then pushes the arity, then emits `EMIT` with the event
name as the operand.
**`while (cond) { ... }`** — nothing bounds the trip count except the gas meter, and nothing
else can: whether the loop terminates is the halting problem, and the meter is the decidable
answer to it (`runtime/compiler.ts:427-443`).
**`for (i in from..to) { ... }`** — half-open, evaluated once. Chosen over a C-style
three-clause header deliberately (`runtime/compiler.ts:455-468`): a three-clause header lets
the body and the step clause conspire to make the trip count unbounded, at which point `for`
is `while` with extra syntax. Here `from` and `to` are evaluated once into slots the body
cannot reach — the bound slot is named `for$bound$N` and `$` cannot occur in an AresLang
identifier (`runtime/compiler.ts:489-490`) — and the loop variable is immutable inside the
body (`runtime/compiler.ts:350-355`). The trip count is exactly `max(0, to - from)` and can be
reasoned about by a reader, an auditor and a gas estimator.
Two nested loops cannot share a variable name (`forLoop` `runtime/compiler.ts:734`).
A local may not shadow a state variable (`runtime/compiler.ts:280`).
## 1.6 Expressions
Precedence, highest binding last (`runtime/parser.ts:235-240`):
```
|| 1
&& 2
== != 3
< > <= >= 4
+ - 5
* / % 6
```
`+` on two text operands is concatenation; the types decide, so there is no runtime coercion
anywhere (`runtime/compiler.ts:786-793`).
### `&&` and `||` short-circuit
This is compiler 1.2.0's change and it is worth reading the reason
(`runtime/compiler.ts:768-780`). They used to emit left, right, then `AND`/`OR`, so both sides
always ran and the guard every author writes was a trap:
```ares
require(divisor != 0 && total / divisor > 2, "...")
```
reverted with `division by zero` — having checked the divisor and then divided by it anyway.
The cost was paid in reverts nobody could explain from the source.
They now compile to `JZ`/`JMP` (`runtime/compiler.ts:853-887`), which the container already
carried, so a module compiled before this still decodes and runs exactly as it did. What
changed is the bytecode produced from a given source, and since a deploy record carries source
that every node recompiles, that is a consensus change — hence the version bump to
`areslang-1.2.0`.
Measured effect: the `onlyOwnerOrRole` guard fell from 119 gas to **60** when the caller is
the owner (`stdlib/gas.ts:370` table, `routine: "onlyOwnerOrRole('MINTER') — caller is the
owner"`), and short-circuiting took 50 gas off every escrow payout by itself
(`tests/integration/template-catalogue.integration.test.ts:392`).
`AND` (0x27) and `OR` (0x28) remain in the instruction set. Nothing emits them any more.
## 1.7 Builtins and context words
Four **context words** are reserved keywords, read as bare identifiers
(`runtime/parser.ts:61-65`):
| Word | Opcode | Type | Reads |
|---|---|---|---|
| `caller` | `CALLER` | `address` | the authenticated caller of this call |
| `self` | `SELF` | `address` | this contract's own address |
| `timestamp` | `TIMESTAMP` | `uint` | the **sealed header's** `producedAtMs` of the block this call is in |
| `height` | `HEIGHT` | `uint` | the height of the block this call is in |
Three **builtins** are ordinary identifiers in call position, so none of their names is
reserved and `state balance: uint;` keeps working (`runtime/parser.ts:56-59`,
`runtime/compiler.ts:725-762`):
| Call | Opcode | Signature |
|---|---|---|
| `len(text)` | `LEN` | `(string\|address) -> uint`, in UTF-16 code units |
| `concat(a, b)` | `CONCAT` | `(text, text) -> string` |
| `balance(addr)` | `BALANCE` | `(address) -> uint`, spendable STR at that address |
And one **effect statement**:
| Statement | Opcode | Notes |
|---|---|---|
| `transfer(to, amount);` | `TRANSFER` | `amount` must be `uint`. An `int` amount is refused at compile time — "a signed transfer is a withdrawal wearing a deposit's clothes" (`runtime/compiler.ts:580-584`). Calling it as an expression is a compile error with its own message (`runtime/compiler.ts:756`). |
## 1.8 Events
`event Transfer(from: address, to: address, amount: uint);`
Events are **not in the state root** and that is deliberate
(`src/core/contract-state.ts:48-54`): an event is a log of how state was reached, not the
state itself, and every event is already determined by the code, the storage it read and the
arguments it was called with — all of which are committed. Folding a running event hash into
the leaf would make the root depend on execution *history* rather than on the position the
chain is in, and two nodes holding identical contracts and identical storage would then
disagree.
So the feed is a **node-local index and not chain state**: nothing commits to it, and no state
root disagrees with a wrong one. It is kept per contract (`ContractAccount.events`) and carried
in the snapshot, and it is **bounded** — the newest `SINDRI_EVENT_RETENTION` = 1024 per contract,
with `SindriLedger.eventsDropped(address)` reporting how many fell off. Read that number beside
the feed before calling the feed a history.
What this does **not** touch is value: balances are in Yggdrasil's own state root and storage is
in the leaf above, both covered by the root comparison a snapshot restore performs. A wrong feed
can make a node *say* something untrue about how the chain got where it is; it cannot move a
coin, change a slot, or make a peer accept a block. `docs/design/CONTRACT_EVENT_COMMITMENT.md`
works the whole question out, measures it, and argues against committing the feed.
## 1.9 What AresLang deliberately does not have
This section is the one a contract author most needs and most often skips.
### No user-defined functions
Not to another contract, and **not to the contract's own second function**. `parsePrimary`
accepts a call expression only for the fixed builtin set, and `valueCall` ends with *"AresLang
has no user-defined functions yet, so an unknown call is always a mistake and never a forward
reference"* (`runtime/compiler.ts:760-762`).
What it costs a contract author:
- **Every shared routine is copied.** `templates/staking-token.ares` copies its reward accrual
block verbatim into `stake`, `claim` and `unstake`, with `ACCRUAL BEGIN` / `ACCRUAL END`
markers, and a test extracts all three and fails if they are not character-for-character the
same (`tests/integration/template-staking.integration.test.ts:343`). A reward formula that
differed between `claim` and `unstake` would be a hole that pays out on whichever path is
more generous. The same shape appears in `templates/dao-treasury.ares`, whose proposal block
appears three times and is checked the same way
(`tests/integration/template-dao-treasury.integration.test.ts:470`).
- **A library cannot be a library.** `stdlib/` is source text composed into the contract before
compilation, not code called at runtime — Part VIII.
- The upside, stated because it is real: there is no recursion, no dynamic dispatch, and no
delegate-call library whose bug is centrally exploitable. Duplication instead of shared fate
is the better half of that trade (`stdlib/source.ts:29-40`).
### No cross-contract calls
There is no `CALL`, no `delegatecall`, no host callback of any kind. The entire outward
surface is `AresHost` (`runtime/vm.ts:43-50`): `selfAddress`, `blockTimestampMs`,
`blockHeight`, `balanceOf`, `transfer`. That list is the whole attack surface
(`src/core/contract-state.ts:70-79`).
What it costs a contract author, taken from `templates/README.md:93-102`:
- A multisig cannot execute an arbitrary call on another contract. `templates/multisig.ares`
can pay native STR out of its own balance and nothing else.
- A staking contract for a ZK13 token must **be** the token contract, because it could never
move a holder's balance held in another contract's storage. Hence
`templates/staking-token.ares`.
- Allowances (`approve`/`transferFrom`) are deliberately absent from every template. An
allowance exists so another *contract* can spend on a holder's behalf; with no call opcode it
is a stored permission nothing can use, and a chain-wide stock of forgotten approvals that
all become live on the day one ships.
- A balance recorded at a contract address can never move, because a contract cannot be
`caller`. Sending a ZK13 token or an NFT to a contract address is **permanent loss**, and no
template can detect the case to refuse it.
### No constructor arguments
There is no constructor. `__init` takes zero parameters (`runtime/compiler.ts:143`) and runs
the state initializers and nothing else.
What it costs a contract author: **configuration is source**. To set a token's name, cap or
decimals you edit the `state` declarations in the template
(`templates/zk13-token.ares:61-77`). That changes the bytecode, which changes the address —
which is correct, because different code is a different contract, and the address commits to
the bytecode (`contracts/registry.ts:99-109`). It also means a deployment cannot be
parameterised at deploy time by a script that does not touch the source, and it means every
distinct configuration is a distinct compile.
A subtler consequence: because `compileInitializer` walks only `declaration.initial`
*expressions* (`runtime/compiler.ts:125-144`), and `transfer` is a statement, **an initializer
can never move value**. Any initialisation that needs a payment needs a second call.
### No value on a call record
A call record carries no value (`ContractCallRecord`, `src/core/contract-state.ts:508-516`).
There is no `msg.value` and no deposit hook. A contract is funded by an ordinary STR transfer
to its address, which works only **after** it is deployed, because the ledger's receive gate
answers from the deployed set and not from the shape of the address string.
The consequence is the sharpest limit in the whole catalogue: **a contract cannot see who paid
it.** Native staking, a token sale, a shared vault and a tip jar are not writable today, and no
amount of contract code fixes it (`templates/README.md:66-81`).
### No other absences worth naming
No upgrade path, no proxy, no `setCode` anywhere in Sindri — bytecode is in the address
preimage. No map iteration, no map deletion, no enumeration of anything. No string indexing,
slicing or comparison beyond equality and length. No arrays. No structs. No `else if` chain
sugar beyond nested `if`/`else`. No domain accessor: a contract **cannot** ask whether an
address holds a proved STR.domain, which is why a domain-bound NFT is not writable
(`templates/nft-collection.ares:12-21`).
## 1.10 Compile-time bounds and error positions
Syntax errors carry a line and column: `AresSyntaxError` puts them in the message
(`runtime/parser.ts:72-77`), and `AresCompileError` does the same when it has a position
(`runtime/compiler.ts:57-62`). Two tests pin it:
`tests/integration/areslang-v2.integration.test.ts:727` for a type error and `:745` for a
syntax error in the v2 grammar.
`MAX_NESTING_DEPTH = 256` (`runtime/parser.ts:269`) bounds the **abstract syntax tree**, not
the parser's own recursion, and the difference is where the bound used to leak.
`parseExpressionInner` consumes a run of same-precedence operators *iteratively* while building
a *left-deep* tree, so `1 + 1 + 1 + ...` cost the parser one frame and the compiler one frame
per term. A flat operator chain therefore sailed through a depth bound that counted only
recursive calls and blew the compiler's stack — around **twelve thousand terms** was a
`RangeError` out of `compileAresSource`, from source that parsed cleanly. `chargeSpine`
(`chargeSpine` `runtime/parser.ts:337`) charges every node the loop adds to the left spine against the same
budget; the postfix index loop `a[b][c][d]` is charged the same way
(`runtime/parser.ts:572-590`).
`CodeEmitter` carries the same bound independently (`runtime/compiler.ts:261`, `enter` at
`:301`) for trees that did not come from `parseContract` — an AST assembled by tooling, a
future front end, a test. A node compiling contract source it did not write is handling
untrusted input, and an unexpected error class there is a crash rather than a rejection.
**None of these bounds the source text.** `MAX_NESTING_DEPTH` bounds the shape of the tree and
the compiler bounds the shape of what it emits; neither says how long a contract may be. The
answer to *"how big can a contract be on this chain"* is not in the compiler at all — it is
`MAX_RECORD_BYTES` in `src/core/blockchain.ts`, which bounds the whole deploy **record**
including `source` and `bytecodeHex`, and refuses at the submit door rather than at compile
time. **§6.5.1.**
---
# Part II — The ARES container
`runtime/bytecode.ts`.
## 2.1 The property the format exists for
A compiled contract is a real, decodable byte module — **not a digest of its source**. Anything
that can be deployed can be disassembled back into the exact instruction stream the VM will
execute (`runtime/bytecode.ts:1-21`).
The property is stronger than "decodes without error". It is:
> **decode ∘ encode is the identity on modules, and encode ∘ decode is the identity on bytes.**
The second direction is the one that matters and the one that keeps getting lost. A contract
address is `sha256("ares-contract:" + name + bytecodeHex + deployer + salt)`
(`contracts/registry.ts:105`). If two distinct containers can decode to one module, then
re-encoding gives bytes that are not the ones deployed, and **the address no longer identifies
the instruction stream the VM will run**. That is not a tidiness concern; it is the whole basis
of on-chain verification.
`tests/integration/areslang-v2.integration.test.ts:643` round-trips a module containing every
opcode, byte for byte.
## 2.2 Layout
```
magic "ARES" 4 bytes, ASCII
version u8
functionCount u16 big-endian
per function:
nameLength u8 (bytes of UTF-8, not code units)
name nameLength bytes of UTF-8
paramCount u8
instructionCount u32 big-endian
instructions instructionCount encoded instructions, in order
```
Every multi-byte integer is big-endian (`ByteWriter`, `runtime/bytecode.ts:602-624`).
One encoded instruction:
```
opcode u8
operandKind u8
operand depends on operandKind
```
Operand kinds (`runtime/bytecode.ts:300-304`):
| Kind | Byte | Payload |
|---|---|---|
| `OPERAND_NONE` | `0x00` | nothing |
| `OPERAND_INT` | `0x01` | `u8` sign (1 = negative) + `u8` byte length + big-endian magnitude |
| `OPERAND_STRING` | `0x02` | `u16` byte length + UTF-8 bytes |
| `OPERAND_BOOL` | `0x03` | `u8`, 1 = true |
| `OPERAND_INDEX` | `0x04` | `u32` |
Integer zero encodes as sign 0, length 0, no magnitude bytes (`writeBigInt`,
`runtime/bytecode.ts:560-570`). The sign byte exists so negative intermediates survive a round
trip.
**Jump targets are instruction indices, not byte offsets.** That is what lets a module
round-trip through encode/decode with no offset patching
(`runtime/bytecode.ts:19-20`).
The decoder requires the reader to be exhausted at the end: trailing bytes are an error
(`runtime/bytecode.ts:376`).
## 2.3 Opcodes
`runtime/bytecode.ts:82-92`. Thirty-seven opcodes.
| Code | Op | Operand kind | Min version |
|---|---|---|---|
| `0x01` | `PUSH` | INT / STRING / BOOL | 1 |
| `0x02` | `POP` | NONE | 1 |
| `0x03` | `DUP` | NONE | 1 |
| `0x10` | `ADD` | NONE | 1 |
| `0x11` | `SUB` | NONE | 1 |
| `0x12` | `MUL` | NONE | 1 |
| `0x13` | `DIV` | NONE | 1 |
| `0x14` | `MOD` | NONE | 1 |
| `0x15` | `SUBU` | NONE | **2** |
| `0x20`–`0x25` | `EQ` `NEQ` `LT` `GT` `LTE` `GTE` | NONE | 1 |
| `0x26`–`0x28` | `NOT` `AND` `OR` | NONE | 1 |
| `0x29` | `CONCAT` | NONE | **2** |
| `0x2a` | `LEN` | NONE | **2** |
| `0x30` | `LOAD` | STRING (slot name) | 1 |
| `0x31` | `STORE` | STRING (slot name) | 1 |
| `0x32` | `LLOAD` | INDEX | 1 |
| `0x33` | `LSTORE` | INDEX | 1 |
| `0x34` | `MLOAD` | STRING (map descriptor) | **2** |
| `0x35` | `MSTORE` | STRING (map descriptor) | **2** |
| `0x40` | `JMP` | INDEX | 1 |
| `0x41` | `JZ` | INDEX | 1 |
| `0x50` | `REQUIRE` | STRING (revert message) | 1 |
| `0x51` | `EMIT` | STRING (event name) | 1 |
| `0x52` | `CALLER` | NONE | 1 |
| `0x53` | `SELF` | NONE | **2** |
| `0x54` | `TIMESTAMP` | NONE | **2** |
| `0x55` | `HEIGHT` | NONE | **2** |
| `0x56` | `BALANCE` | NONE | **2** |
| `0x57` | `TRANSFER` | NONE | **2** |
| `0x60` | `RET` | NONE | 1 |
| `0x61` | `HALT` | NONE | 1 |
A map descriptor operand is `name|depth|valueTag`, where `valueTag` is one of `u i b a s`
(`encodeMapDescriptor` `runtime/bytecode.ts:234`). `|` cannot occur in an AresLang identifier
`[A-Za-z_][A-Za-z0-9_]*`, so the split is unambiguous and needs no escaping. `depth` is
validated to `1..8` on both encode and decode.
## 2.4 Versioning
`ARES_BYTECODE_VERSION = 2`, `ARES_MIN_BYTECODE_VERSION = 1`
(`runtime/bytecode.ts:45-48`).
Adding an opcode changes what a module *means*, so the version is not decoration. Two rules
hold it together and both are enforced in code rather than by convention
(`runtime/bytecode.ts:32-43`):
1. **A module declaring an older version may not contain a newer opcode.** Checked on decode
(`runtime/bytecode.ts:426-432`) and on encode (`runtime/bytecode.ts:322-328`). Without it, a
v2 opcode byte smuggled into a module labelled v1 would decode on a new node and be an
"unknown opcode byte" on an old one. Two nodes disagreeing about what the same bytes do is a
fork.
2. **A module declaring a newer version is refused outright, loudly, naming both versions**
(`runtime/bytecode.ts:353-359`). A node that met a v3 module and guessed would be executing
instructions it does not have. The chain sees a record that fails to decode, which is a
rejected record on every node running this version — the same answer everywhere, which is
what matters.
The compiler stamps the **lowest** version that can honestly carry the module, not the newest
it knows (`moduleRequiredVersion` `runtime/bytecode.ts:144`; used at
`runtime/compiler.ts:92-93`). A contract that uses nothing past v1 stays a v1 module and stays
deployable on a node that has not upgraded.
Four tests pin this: `tests/integration/areslang-v2.integration.test.ts:658` (stamps the
lowest), `:667` (refuses a newer module), `:677` (refuses an old module carrying a new opcode),
`:689` (refuses to stamp a module older than its instructions), `:699` (still runs a genuine v1
module).
## 2.5 The operand-kind check
`assertOperandKind`, `runtime/bytecode.ts:468`.
`encodeInstruction` picks the operand kind from the **opcode** — a `LOAD` gets a string, a
`JMP` gets an index — but the decoder used to take whatever kind the byte said and hand it to
the VM. So a hand-built container could carry `LOAD` with an `OPERAND_INT`: it decoded, and
re-encoding the decoded module wrote the operand back as a `STRING`, producing **different
bytes from the ones deployed**.
The round trip is the property that a deployed container and the instruction stream the VM
runs are the same object, so the decoder has to be exactly as strict as the encoder, not merely
able to read what the encoder writes.
At execution such an instruction reverts anyway with `expected storage key`, which is a *worse*
place to find out: by then it is a per-call failure inside a module the chain already accepted
and bound an address to.
`PUSH` is the one opcode whose operand kind is genuinely the value's rather than the opcode's,
and it accepts INT, STRING or BOOL and nothing else (`runtime/bytecode.ts:477-483`).
Pinned by `tests/integration/areslang-hardening.integration.test.ts:189`.
## 2.6 Fatal UTF-8
`runtime/bytecode.ts:519-539`.
The default `TextDecoder` is lenient: it replaces every invalid byte with U+FFFD and returns a
string. That silently breaks the one property this format exists to provide. A container
carrying a lone `0x80` where a string operand should be decoded to a module whose operand was
U+FFFD, and re-encoding that module produced `ef bf bd` — **different bytes from the ones that
were deployed**. Two distinct containers decoded to one module.
So the decoder is `new TextDecoder('utf-8', { fatal: true })` and malformed bytes are refused,
on every node, at the same byte. It covers both string operands (`readString`,
`runtime/bytecode.ts:555`) and function names (`runtime/bytecode.ts:367`).
The **encode side mirrors it** (`writeString`, `runtime/bytecode.ts:541-553`). `TextEncoder`
has no fatal mode — it replaces an unpaired surrogate with U+FFFD and reports nothing — so a
module holding one would encode to bytes that decode back as a *different* module. The encoder
therefore tests `/\p{Surrogate}/u` and refuses to write it.
Pinned by `tests/integration/areslang-hardening.integration.test.ts:167` (string operand),
`:180` (function name), `:203` (refusing to encode a surrogate).
## 2.7 Jump validation
`assertJumpsInRange` `runtime/bytecode.ts:578`.
The VM sets its program counter from a jump operand, and its loop condition is
`pointer < program.length`. A `JMP 9999` in a four-instruction function therefore did not fail:
**it fell straight out of the loop and returned `success: true` with the working storage
committed** — a call that skipped its own `require`s and its own effects and still reported
that it had run. Nothing downstream could tell that apart from a normal return, because it *is*
a normal return.
Decode is the right place for the check: the function's instruction count is known there, it
costs once per deployment rather than once per jump per call, and a module that cannot be
executed correctly should be refused before an address is bound to it. Every node running this
version refuses the same bytes.
**One-past-the-end is allowed.** Running off the end is already how the VM returns normally, so
`JMP` to exactly `length` is another spelling of `HALT` — and the compiler's own
`patch(jump, instructions.length)` produces it (`runtime/compiler.ts:419`, `:421`, `:441`,
`:512`, `:869`, `:871`, `:885`).
The VM checks again at execution (`jumpTarget` `runtime/vm.ts:1257`), because `run` also takes
a raw instruction array that never passed through a decoder, and a control-flow bug must not be
able to manufacture a successful-looking result at any entrance.
Pinned by `tests/integration/areslang-hardening.integration.test.ts:233`, `:248`, `:266`,
`:276`.
## 2.8 Worked example: a minimal module
```ares
contract Tiny {
view fn one() -> uint { return 1; }
}
```
compiles to two functions — `__init` (empty, just `HALT`) and `one`. The `one` function is
`PUSH 1`, `RET`, `HALT`. Encoded:
```
41 52 45 53 "ARES"
01 version 1 (nothing here needs v2)
00 02 functionCount = 2
06 nameLength 6
5f 5f 69 6e 69 74 "__init"
00 paramCount 0
00 00 00 01 instructionCount 1
61 00 HALT, OPERAND_NONE
03 nameLength 3
6f 6e 65 "one"
00 paramCount 0
00 00 00 03 instructionCount 3
01 01 00 01 01 PUSH, OPERAND_INT, sign 0, length 1, magnitude 0x01
60 00 RET, OPERAND_NONE
61 00 HALT, OPERAND_NONE
```
Note the version byte: `moduleRequiredVersion` found no v2 opcode, so this module is stamped
v1 and runs on a node that has not upgraded.
---
# Part III — Storage encoding, and the fork it caused
This is the best worked example of a determinism bug in this tree, and it is written up in
full because the class of defect it belongs to is the one that ends chains.
## 3.1 Contract storage is flat
A contract's storage is a `Map` and nothing else. There is no map object to
serialise, so there is nothing whose serialisation could differ between nodes
(`runtime/bytecode.ts:136-147`).
Sindri folds that map into a Glasir tree, keyed by `glasirKey(slotName)` =
`sha256("glasir:key:v1|" + slotName)` (`src/core/glasir.ts:193`), with the leaf value
`slotCommitment(key, value)` = `sha256("sindri:slot:v1|" + key.length + "|" + key + "|" +
encodeAresValue(value))` (`slotCommitment` `src/core/contract-state.ts:1888`).
A Glasir root is a function of the **set** of (key, valueHash) pairs and of nothing else. So as
long as the slot **name** is a pure, injective function of (map name, key values), two nodes
that wrote the same entries reach the same root regardless of the order they wrote them in.
`tests/integration/areslang-v2.integration.test.ts:186` and `:805` assert exactly that: the
same entries written in different orders reach the same storage set and the same contract
state root.
## 3.2 `mapSlotKey` and `encodeMapKeyPart`
`runtime/bytecode.ts:252-266`.
```
slotName := mapName '#' part ('#' part)*
part := 'i:' decimal -- bigint
| 'b:' ('0'|'1') -- boolean
| 's:' length ':' text -- text, all printable ASCII
| 'u:' length ':' hex -- text, otherwise; 4 lowercase hex per UTF-16 unit
```
`length` is the count of **UTF-16 code units**, not bytes.
Three properties, each doing separate work:
- **Type-tagged**, so the integer `1`, the string `"1"` and the boolean `true` are three
different entries rather than three spellings of one.
- **Length-prefixed**, so a key containing the separator cannot be read as two shorter keys:
`s:3:a#b` and `s:1:a` + `s:1:b` are distinguishable by any reader that honours the length.
- **Printable-ASCII-only in the output**, which is §3.3.
A plain state variable is an identifier and can never contain `#`, so a map entry can never
collide with a scalar slot, and two maps cannot collide with each other
(`runtime/bytecode.ts:263-264`).
Injectivity across the whole shape space is pinned by
`tests/integration/areslang-hardening.integration.test.ts:105`, which asserts eleven distinct
key tuples produce eleven distinct slot names, and by
`tests/integration/areslang-v2.integration.test.ts:168`.
Readable form, which is why the escape is not applied to everything:
```
mapSlotKey('balances', ['alice']) === 'balances#s:5:alice'
mapSlotKey('roles', ['MINTER', 'zk13str_x']) === 'roles#s:6:MINTER#s:9:zk13str_x'
```
(`tests/integration/areslang-hardening.integration.test.ts:123`.)
## 3.3 The defect: two distinct keys, one Glasir leaf
Read `runtime/bytecode.ts:220-251` and `src/core/contract-state.ts:1504-1523`. Both sides had
the same bug and both are fixed the same way.
A slot name is a JavaScript string, which is a sequence of UTF-16 code units and **may contain
an unpaired surrogate**. Sindri folds the slot into a Glasir leaf keyed by `sha256(name)`, and
every UTF-8 encoder in Node — `TextEncoder`, `createHash().update(s, 'utf8')`, `Buffer` —
replaces each unpaired surrogate with U+FFFD.
So `m["\uD800"]` and `m["�"]` were **two distinct entries in the VM's storage map and one
leaf in the tree.**
The reproduction is one string literal and two ordinary signed calls, with no hostile bytecode
anywhere:
```ares
contract Collide {
state notes: map;
fn put(k: string, v: uint) -> uint { notes[k] = v; return v; }
}
```
Call `put("\uD800", 11)` then `put("�", 22)`, and then the same two calls in the other
order. With one shared leaf, the second write overwrote the first, so the two orders committed
to different values. That test is
`tests/integration/areslang-hardening.integration.test.ts:71`.
**Why that made a restarted node disagree with one that stayed up.** `foldStorage` walks
`account.dirty` in insertion order (`src/core/contract-state.ts:1247`), while `loadSnapshot`
rebuilds the dirty set from a snapshot that is sorted by key
(`src/core/contract-state.ts:1032`, `:1059`). Insertion order and sorted order are different
orders. With an injective encoding that difference is invisible, because a Glasir root does not
depend on fold order. With the collision it was not invisible: the last write into the shared
leaf won, and the two nodes performed the writes in different orders. **A node that restarted
computed a different contract state root than a node that stayed up, from the same chain and
the same records.** A permanent chain fork out of one string literal, with no attacker
involved. This is recorded verbatim at
`tests/integration/storage-commitment.integration.test.ts:8-23`.
The same collision existed on the **value** side, not only the name side. Before the fix:
```
sha256('s:1:\uD800') === sha256('s:1:�')
```
which is asserted, verbatim and deliberately, at
`tests/integration/storage-commitment.integration.test.ts:79-84` — the naive encoder is kept in
the test so that if someone restores it, a test fails rather than a chain.
## 3.4 The fix, and why it is printable-ASCII passthrough
Injectivity is restored by making the encoded output **pure printable ASCII in every case**
(`isPlainSlotUnit` `runtime/bytecode.ts:271`: `0x20 <= unit <= 0x7e`;
`isPrintableAscii` `src/core/contract-state.ts:1914`: identical range):
- `s::` when every code unit is printable ASCII. UTF-8 leaves those bytes alone, so
the name reaches the hasher unchanged.
- `u::` otherwise — four lowercase hex digits per UTF-16 code unit. Fixed width, so
distinct code-unit sequences stay distinct, and no surrogate ever reaches an encoder.
The two forms cannot be confused because the tags differ and an `s` body contains no character
outside printable ASCII by construction.
**Escaping only what needs it was a deliberate choice with two reasons.** It keeps
`balances#s:53:zk13str_...` readable in an explorer, and it keeps a slot name a quarter of the
length it would otherwise be on every map entry the chain stores forever. But the load-bearing
reason is migration: **every key and every value the shipped templates use is ASCII, so no
existing commitment moves.** That is asserted directly at
`tests/integration/storage-commitment.integration.test.ts:37-41`. A blanket hex encoding would
have been simpler and would have moved every contract root already on a chain.
The property is stated as a property rather than as a patch on one pair of inputs:
`tests/integration/areslang-hardening.integration.test.ts:52` takes six slot names — a lone
high surrogate, a lone low surrogate, an astral character, `café`, a space, plain ASCII — and
asserts each survives a strict UTF-8 round trip unchanged and that all six remain distinct.
A related trap the fix has to avoid: an encoder that iterated code **points** instead of code
units would encode U+1F600 as the concatenation of its two halves, colliding a one-character
string with a two-character one. Pinned at
`tests/integration/storage-commitment.integration.test.ts:64`.
## 3.5 `encodeAresValue`
`src/core/contract-state.ts:1504`. The same four forms, applied to the stored **value** rather
than the key part:
```
i: bigint
b:0 / b:1 boolean
s:: printable-ASCII text
u:: any other text
```
It is used in three places, which is why fixing it in one was not enough:
1. `slotCommitment` — the storage leaf (`slotCommitment` `src/core/contract-state.ts:1889`).
2. `canonicalRecord` — the block's contract-records root
(`canonicalRecord` `src/core/contract-state.ts:1838`).
3. `callAuthorizationPayload` — the bytes a caller signs
(`callAuthorizationPayload` `src/core/contract-state.ts:1721`).
A collision in (3) would let one signature authorise two different calls.
## 3.6 Pricing a slot name before it exists
`mapSlotKeyLength` `runtime/bytecode.ts:344`.
`MLOAD` and `MSTORE` are priced by the length of the slot name they build, and gas for a piece
of work has to be charged **before** the work: a charge that lands afterwards has already let
the allocation happen, so the meter is always one instruction behind the machine. The key
values are on the stack before any name exists and their sizes fix the name's length exactly,
so the price is knowable in advance — `mapSlotKeyLength` computes it *without* producing the
name.
It mirrors `encodeMapKeyPart` and must keep mirroring it. That is not left to discipline:
`tests/integration/areslang-v2.integration.test.ts` asserts it equals `mapSlotKey(...).length`
over every shape of key, and
`tests/integration/areslang-hardening.integration.test.ts:379` asserts the same, so a change to
one and not the other fails a test rather than silently mispricing a map.
---
# Part IV — The StarW VM
`runtime/vm.ts`.
## 4.1 Execution model
One function of one module, one `run` call, one flat interpreter loop
(`runtime/vm.ts:365`). There are no frames, no call stack, and no way to enter a second
function from inside the first.
State per execution:
| | |
|---|---|
| `writes` | `new Map()` — a **write-set** over `options.storage`, which is read through and never written. It used to be a whole copy of the contract's storage, made on every call (audit C13) |
| `stack` | seeded with the call arguments in call order (`runtime/vm.ts:234`) |
| `locals` | `Map`, indices assigned by the compiler (`runtime/vm.ts:235`) |
| `events` | appended by `EMIT` |
| `transfers` | appended by `TRANSFER` after the host accepted it |
| `pointer` | instruction index |
| `gasUsed` | monotonically increasing |
Bounds:
| Constant | Value | Where |
|---|---|---|
| `DEFAULT_GAS_LIMIT` | 1,000,000 | `DEFAULT_GAS_LIMIT` `runtime/vm.ts:212` |
| `MAX_STACK_DEPTH` | 1,024 | `MAX_STACK_DEPTH` `runtime/vm.ts:213` |
| `MAX_INTEGER_BITS` | 4,096 | `MAX_INTEGER_BITS` `runtime/vm.ts:245` |
| `MAX_STRING_LENGTH` | 65,535 UTF-16 code units | `MAX_STRING_LENGTH` `runtime/vm.ts:262` |
| `GAS_BACKWARD_JUMP` | 20 | `GAS_BACKWARD_JUMP` `runtime/vm.ts:361` |
| `MAX_RECORD_GAS_LIMIT` | 10,000,000 | `src/core/blockchain.ts:224` |
| `MAX_BLOCK_GAS` | 60,000,000 | `src/core/blockchain.ts:233` |
Return paths:
- `RET` pops one value and returns it as `returnValue` (`runtime/vm.ts:644`).
- `HALT` returns with no `returnValue` (`runtime/vm.ts:655`).
- Falling off the end returns with `returnValue = stack.at(-1)`
(`runtime/vm.ts:666-675`).
`executeFunction` checks arity against the module's `paramCount` and **throws** — not reverts —
on a mismatch (`executeFunction` `runtime/vm.ts:460`), because that is a caller error, not a contract failure.
## 4.2 Stack and locals
`push` refuses at `MAX_STACK_DEPTH` (`runtime/vm.ts:198`); `pop` reverts on underflow
(`runtime/vm.ts:280`). `popInt` and `popText` revert with the observed type when the value on
top is the wrong one (`runtime/vm.ts:291`, `:297`).
Locals are a sparse map, not a frame. `LLOAD` of an unwritten slot **reverts** rather than
reading a zero (`runtime/vm.ts:550`) — a contract that read an uninitialised local and got `0`
would produce a confident wrong answer.
`DUP` pops and pushes twice, so it duplicates the top of the stack
(`runtime/vm.ts:385-390`).
`EMIT` pops an arity from the stack and then splices that many values off it
(`runtime/vm.ts:635-643`). A count that is negative or exceeds the stack reverts with
`malformed event arity`.
## 4.3 Argument limits
`assertArgWithinLimits` `runtime/vm.ts:1225`, called for every argument at
`runtime/vm.ts:363`, **inside** the try, so an oversized argument is a metered revert the
ledger already handles rather than a throw out of the sandbox.
This was a real hole. `CONCAT` refused to *build* a string past `MAX_STRING_LENGTH` and
`chargeArithmetic` refused to build an integer past `MAX_INTEGER_BITS`, which made both look
like invariants of the machine. They were not: **an argument is placed on the stack by the
caller, not by an opcode**, so a 300 KB string parameter or a million-bit integer parameter
walked past both and could be written to storage by an `MSTORE` that never touched either
check. A limit with an unguarded entrance is a comment, not a limit.
The ceiling is inclusive: a value exactly at the limit is accepted
(`tests/integration/areslang-hardening.integration.test.ts:331`).
## 4.4 The opcode gas table
`GAS_COSTS`, `runtime/vm.ts:169-184`. Anything absent costs `DEFAULT_OPCODE_GAS = 1`
(`runtime/vm.ts:185`).
| Op | Charge | Notes |
|---|---:|---|
| `PUSH` `POP` `DUP` | 1 | |
| `ADD` `SUB` `MUL` | 1 + size (§4.6) | |
| `DIV` `MOD` | 1 | **not** size-charged; see Known limits |
| `SUBU` | 3 | `SUB` is 1; the checked version adds a comparison and a branch |
| `EQ` `NEQ` `LT` `GT` `LTE` `GTE` `NOT` `AND` `OR` | 1 | |
| `LEN` | 2 | reads one field of a value already on the stack, crosses no boundary |
| `CONCAT` | 6 + 1 + ⌈result/32⌉ | the cost is the copy, and the copy is proportional to what comes out |
| `LOAD` | 50 | a tree lookup |
| `STORE` | 200 | four times a read: it dirties a slot, costing a Glasir path recomputation at seal, and it grows state every node keeps forever |
| `MLOAD` | 55 + 1 + ⌈slotLen/32⌉ | a `LOAD` plus the slot name it has to build. Five over `LOAD`, not fifty — the extra work really is small |
| `MSTORE` | 220 + 1 + ⌈slotLen/32⌉ | a `STORE` plus 20: a map write usually **creates** a leaf rather than replacing one |
| `JMP` `JZ` forward | 1 | |
| `JMP` `JZ` backward | 20 | one loop iteration's fixed overhead |
| `REQUIRE` | 5 | |
| `EMIT` | 100 | flat, regardless of arity or payload size |
| `CALLER` | 1 | |
| `SELF` `TIMESTAMP` `HEIGHT` | 2 | one immutable field of the block, through a host call. Twice a `DUP` because it is a call; nowhere near a `LOAD` because it touches no tree |
| `BALANCE` | 400 | a lookup in **Yggdrasil**, a different tree with its own cache miss. Priced above `STORE` so that walking the ledger by probing addresses in a loop is not a cheap way to scan it |
| `TRANSFER` | 2,100 | the most expensive instruction in the machine. Ten times `MSTORE` puts roughly 470 in a default-limit call, which is a batch payout and not a drain |
| `RET` `HALT` | 1 | |
The `+ 1` on `CONCAT`, `MLOAD` and `MSTORE` is not a typo: the size surcharge is applied by
calling `charge('PUSH', n)`, and `PUSH` itself costs 1
(`runtime/vm.ts:354`, `:501`). A reimplementation that charges `55 + ⌈slotLen/32⌉` for `MLOAD`
will disagree with this one on every map read.
The shape of the table is the argument: **stack ops cost 1, state ops cost hundreds, value ops
cost thousands**, because that is the ratio of the real work behind them.
### Derived costs
A `while` loop's per-iteration floor is `condition + JZ (1) + body + JMP backward (20)`. An
empty `while (true)` is `PUSH true (1) + JZ (1) + JMP (20)` = **22 gas per turn**, so it
reverts after roughly 45,000 turns at the default limit — milliseconds, not a hung node
(`runtime/vm.ts:187-199`).
A `for` loop's per-iteration overhead, read off the emitted stream at
`runtime/compiler.ts:494-512`: `LLOAD` + `LLOAD` + `LT` + `JZ` = 4 before the body, and
`LLOAD` + `PUSH` + `ADD` + `LSTORE` + backward `JMP` = 24 after it, so **28 gas plus the
body**.
`tests/integration/areslang-v2.integration.test.ts:279` asserts gas grows with the trip count,
and `:292` asserts a backward jump is priced above a forward one.
## 4.5 Gas is charged before the work it prices
This is the single most important rule in the file and it is applied in three places.
**The main loop charges before the switch** (`runtime/vm.ts:371-376`). A jump whose target is
not ahead of the program counter closes a loop and pays the iteration price; both operands are
fixed by the module, so this is the same charge on every node.
**`chargeArithmetic` prices from the operands, not the result**
(`runtime/vm.ts:251-278`). Charging the result meant multiplying two 4,096-bit numbers into an
8,192-bit one and only *then* discovering it was over the ceiling — the meter always paid for
the last instruction after the machine had already done it, which is the one instruction an
attacker gets for free. The operand widths bound the result exactly (`a*b` at most
`bits(a)+bits(b)`, `a±b` at most one bit past the wider), they are known before anything is
computed, and they are the same two numbers on every node.
The bound is slightly conservative and that is stated rather than hidden: an integer sitting
exactly on `MAX_INTEGER_BITS` can no longer be added to anything, because the bound says 4,097
even where the sum would have fitted in 4,096. Real contracts work in tens or hundreds of bits,
so the fuzzy edge is four thousand bits from anything anyone writes.
**`popSlot` prices the slot name before building it** (`runtime/vm.ts:336-356`). The charge
used to sit *after* the build, reading `slot.length` off a name the machine had already
allocated. `mapSlotKeyLength` gives the identical number from the key sizes alone, so this is
the same price, charged in time.
`tests/integration/areslang-hardening.integration.test.ts:350` asserts a multiply is priced
from its operands so the oversized product is never built; `:365` the same for an add; `:379`
that a slot name's cost is known without building it; `:406` that a map read still charges the
same total it always did.
**Why "the same total" matters.** A change that moves *when* a charge lands must not move
*how much* it is, or every gas figure in every template header and the whole catalogue table
becomes wrong at once.
## 4.6 The integer ceiling
`MAX_INTEGER_BITS = 4,096`. Beyond this, arithmetic is a denial of service, not maths
(`runtime/vm.ts:110-111`).
`bitWidth` is `magnitude.toString(2).length`, with `bitWidth(0n) = 1`
(`runtime/vm.ts:760`). Base 2 is a power of two, so the conversion is linear.
Charging: nothing extra below 65 bits; above that, `1 + ⌈bits/64⌉`
(`runtime/vm.ts:277`). A flat cost per opcode is blind to bigint width: 24 straight-line
squarings build a 32 MB integer and block the event loop for seconds while spending 0.7% of the
limit.
A `RangeError` out of oversized bigint arithmetic is caught and turned into a metered revert
rather than rethrown out of the sandbox (`runtime/vm.ts:679-691`).
`tests/integration/areslang-v2.integration.test.ts:376` asserts integers are exact and not
modular on the way up; `:400` that arithmetic which is a denial of service rather than maths is
still refused.
## 4.7 `SUBU`
`runtime/vm.ts:405-428`. Pops right, pops left, computes `left - right`, and **reverts** with
`arithmetic underflow: L - R is negative and this is a uint` when the result would be negative.
It is not size-charged, because its result can only be smaller than its left operand.
It is the instruction the compiler emits for every `uint - uint`. See §1.2.1 for why the answer
is a revert and not wrapping or saturation.
`tests/integration/areslang-v2.integration.test.ts:350` asserts it reverts on underflow instead
of producing a huge or negative balance.
## 4.8 Revert semantics, and why they are total
Every failure inside the machine is an `AresRevert` (`runtime/vm.ts:353`), caught at
`runtime/vm.ts:693`. What comes back:
```ts
{
success: false,
reverted: true,
revertReason: error.message,
stack, // as it was when the revert fired
writes: new Map(), // nothing the call wrote survives it
events: [], // discarded
transfers, // KEPT — see below
gasUsed, // kept: the work was done
}
```
**Storage is total.** Writes land in a write-set and the revert path returns an empty one, so a
reverted call cannot leave partial state behind. The result's `storage` is still the caller's
original map on a revert, built on first read from the map it was handed. There is no undo log to get
wrong, because there is nothing to undo.
**Events are total.** Discarded entirely on a revert, and Sindri discards them again
(`src/core/contract-state.ts:855`).
**Transfers are the exception, deliberately.** The VM applies a transfer through the host the
moment it executes, because a `balance()` read afterwards has to agree with it, and it cannot
undo one on a later revert. So `transfers` is reported **even on a revert**
(`runtime/vm.ts:686-689`): *"Suppressing them here is how a reverted call keeps the money."*
The ledger is responsible for running the whole call inside its own journal and rolling them
back — which Sindri does, by never settling a journal for a call that did not succeed (§6.4).
`tests/integration/areslang-v2.integration.test.ts:509` asserts transfers are reported on a
revert so the ledger knows what to undo.
A revert **is not** a throw. Anything that escapes `run` as a plain `Error` would propagate out
of `applyCall` and turn a contract-level failure into a refusal of the whole block record —
different outcomes, both visible in consensus. Hence `readDescriptor`
(`runtime/vm.ts:303-319`) wraps `decodeMapDescriptor`'s plain `Error` into a revert, and hence
every `AresHost` implementation in `contract-state.ts` throws `AresRevert` to refuse
(`src/core/contract-state.ts:80-84`). A host refusal becomes
`transfer reverted: ` (`runtime/vm.ts:610-616`).
## 4.9 The host, and refusing rather than defaulting
`AresHost` (`runtime/vm.ts:43-50`) is a **declaration**: the VM calls it, the ledger implements
it. Passing it in rather than reaching for anything global is the point — the VM cannot
accidentally read a clock or a live balance, because it has no way to reach one except through
the object it was handed.
A VM built with **no** host refuses the host opcodes rather than answering them with a default
(`requireHost`, `runtime/vm.ts:321-330`). A contract that silently read a zero balance, an
epoch-zero timestamp or an empty self address is worse than one that will not run, because it
produces a confident wrong answer instead of an error.
The host is bound **per call** in production (`ExecuteOptions.host`, `runtime/vm.ts:88-96`),
because block time and height change every block while a ledger holds one VM for its lifetime.
`SindriLedger` constructs its VM with no default host at all
(`src/core/contract-state.ts:599-606`).
Host answers are validated on arrival: a `blockTimestampMs` that is not a safe integer reverts
(`runtime/vm.ts:573-577`) — a host bug that reaches arithmetic is a fork, so it is refused where
it is still one call — and a non-bigint balance reverts (`runtime/vm.ts:594`).
`tests/integration/areslang-v2.integration.test.ts:414` asserts every host opcode is refused
when no host was supplied; `:546` that a fractional timestamp is refused.
## 4.10 Reentrancy is structurally impossible, not prevented
`stdlib/value.ts:173-189` states it as a fact with an audit trail:
```
reachable: false
reason: 'there is no call opcode, no call expression, and TRANSFER runs no recipient code —
nothing inside a call can hand control to code that calls back in'
guardShipped: false
guardCostIfShipped: 458
```
The three legs:
1. **There is no `CALL` opcode.** The opcode table (`runtime/bytecode.ts:82`) has no entry for
it, and there is no operand kind that could carry a target.
2. **There is no call expression.** `valueCall` accepts three builtin names and rejects
everything else (`runtime/compiler.ts:725-762`).
3. **`TRANSFER` runs no recipient code.** It calls `host.transfer(to, amount)`, and the
production host's `transfer` posts a journal entry —
`ValueJournal.transfer` `src/core/contract-state.ts:330` — which burns and mints on the value ledger
(`src/core/contract-state.ts:147-150`). A recipient address is a string, not a program.
So no reentrancy guard ships, and shipping one would be worse than not: it would cost 458 gas
per protected function to defend against a state that cannot be reached, and it would teach
authors that the guard is what makes it safe.
`ValueJournal`'s own comment records what would change (`src/core/contract-state.ts:196-201`):
*"There is no contract-to-contract CALL opcode, so a transfer cannot re-enter this contract and
find a journal it can see but not settle. If one is ever added, the reentrancy question has to
be answered here before the opcode ships."*
And the preferred fix, if the day comes (`stdlib/value.ts:185-187`): a VM rule that a contract
may not be re-entered while a frame of it is on the stack. Zero gas, cannot be forgotten, and
forbids recursion that does not exist yet. **Internal calls, if they ever land, must forbid
recursion first and relax later, because the reverse order is not available**
(`stdlib/source.ts:273-276`).
## 4.11 `readOnly`
`ExecuteOptions.readOnly` (`runtime/vm.ts:97-104`) refuses every effect: `STORE`, `MSTORE`,
`EMIT`, `TRANSFER`. It exists because the compile-time `view` check only covers code this node
compiled; this covers a module that arrived as bytes.
## 4.12 Second line of defence on a map write
`assertMapValue` `runtime/vm.ts:1197`. The compiler already type-checks every
`balances[k] = v`, but a module that arrived as bytes is checked again here, so a
hand-assembled `MSTORE` cannot put a negative number in a `map` and call it a
balance.
`tests/integration/areslang-v2.integration.test.ts:222` asserts exactly that, from hand-written
bytecode.
---
# Part V — Determinism
**Determinism is the property everything else is subordinate to.** Every node re-executes every
contract record in every block and must reach the same answer
(`runtime/vm.ts:20-27`).
## 5.1 What is banned, and why
| Banned | Why | Enforced by |
|---|---|---|
| **Clocks** | `Date.now()` is a different number on every node and therefore a different state root on every node. | A test scans EVERY file in `runtime/`, `stdlib/` and `contracts/`, with comments and string literals stripped, and fails on `Date.now(`, `new Date(`, `Math.random(`, `performance.now(`, `process.hrtime`, `randomBytes(`, `randomUUID(`, `localeCompare(`, `toLocaleString(`, `Intl.`, a `sort()` with no comparator, or a `for...in` (`tests/integration/determinism.integration.test.ts`). Until 2026-09-12 this column said *no import of it in `runtime/`*, which was a true description of the tree and not a mechanism — nothing failed if somebody added one. Time arrives only as `AresHost.blockTimestampMs()`, which is the **sealed header's** timestamp (`runtime/vm.ts:566-579`), and Nidavellir reverts rather than answering zero when the chain supplied none (`src/core/contract-state.ts:368-373`). | Time arrives only as `AresHost.blockTimestampMs()`, which is the **sealed header's** timestamp (`runtime/vm.ts:566-579`), and Nidavellir reverts rather than answering zero when the chain supplied none (`src/core/contract-state.ts:368-373`). |
| **Randomness** | There is no source of randomness two nodes agree on. Randomness derived from block data is chosen by the producer, which is worse than none (`docs/ARESLANG_STDLIB.md:529`). | No opcode, no builtin, no host method. |
| **Floating point** | There is no float type, no float literal and no float arithmetic. Division by zero reverts (`runtime/vm.ts:438`) rather than producing `Infinity`; modulo by zero reverts (`:443`). There is no quiet zero and no NaN. | The type system (`AresType` `runtime/parser.ts:40`) and `AresValue` (`runtime/bytecode.ts:64`). A non-integer numeric operand is refused at encode (`runtime/bytecode.ts:583`) and at `normalizeOperand` (`runtime/vm.ts:1274`). |
| **Locale** | `localeCompare` consults the runtime's ICU data, so two nodes differing only in how their Node binary was built order the same strings differently — which silently changes mempool order, the genesis hash and the fork-choice winner. | A test reads `runtime/areslang.ts` and `runtime/vm.ts` (among nine other consensus files) and fails on any `localeCompare` outside a comment (`tests/integration/determinism.integration.test.ts:22-37`), and a second scan in the same file covers every file in `runtime/`, `stdlib/` and `contracts/` for that and eleven other hazards. Ordering is `compareBytes`, which is byte order — and the two diverge exactly where every address on this chain has its two underscores (`:39-50`). |
| **Iteration order reaching a result** | A `Map`'s iteration order is insertion order in this engine and a consensus split in the next. | `ValueJournal` keeps an explicit ordered `moves` array and says so (`src/core/contract-state.ts:205-210`). Sindri sorts every listing and every snapshot by `compareBytes` (`src/core/contract-state.ts:990`, `:1032`, `:1036`). The Glasir root is a function of the leaf **set**, so fold order cannot reach it (`src/core/contract-state.ts:44-46`). |
| **Non-injective encodings** | Two distinct values reaching one hash is a fork. | Part III, plus `canonicalStringify` refusing non-finite numbers, `undefined`, functions and symbols rather than writing `null` (`tests/integration/determinism.integration.test.ts:66-92`). |
## 5.2 What is allowed, and why each is deterministic
Each of these carries its own justification in the code, because "obviously fine" is how the
UTF-8 collision got in.
- **String concatenation** — JavaScript concatenation is defined over UTF-16 code unit
sequences with no locale, normalisation or collation anywhere in it, so every engine produces
the identical sequence (`runtime/vm.ts:491-494`).
- **`.length`** — the count of UTF-16 code units, which the language specifies exactly. It is
not a byte count and does not depend on an encoder, a locale or a normalisation form
(`runtime/vm.ts:505-508`).
- **Map slot names** — a pure function of the descriptor and the key values: no hashing, no map
iteration, nothing that could order differently on another node
(`runtime/vm.ts:336-350`).
- **`SELF`** — derived at deployment from data the chain committed to, and unchanged for the
life of the contract (`runtime/vm.ts:560-564`).
- **`TIMESTAMP`** — the sealed header's timestamp of the block this call belongs to; the same
number on the producer and on every node replaying that block a year later
(`runtime/vm.ts:566-571`).
- **`HEIGHT`** — the height of the block being executed, which is a property of the chain and
not of the node. Never "the chain tip as this node currently sees it", which differs between
a producer and a node three blocks behind (`runtime/vm.ts:581-587`).
- **`BALANCE`** — committed ledger state as of this block, which is the assumption every other
part of consensus already rests on (`runtime/vm.ts:588-591`).
- **`TRANSFER`** — the VM decides nothing. It hands the ledger an address and an amount and the
ledger applies its own rules; every node runs the same rules over the same state and reaches
the same outcome, **including the same rejection** (`runtime/vm.ts:600-604`).
- **Gas** — every number is per opcode and fixed, so gas used is a pure function of the
instruction stream and the values on the stack (`runtime/vm.ts:166-167`). The backward-jump
charge depends only on the instruction's own operand and the program counter
(`runtime/vm.ts:196-198`).
## 5.3 The height read is at H, not H−3
`DEFERRED_DEPTH = 3` (`src/core/blockchain.ts:190`), so a header at H commits to the state root
as of H−3. **The lag applies to the commitment, never to the read**
(`src/core/contract-state.ts:161-172`, and again at `src/core/blockchain.ts:2399-2402`).
A contract executing in the block at H reads H. Reading H−3 would let a time-locked contract be
unlocked three blocks early and would make a contract that branches on height disagree with
itself across a reorg boundary.
## 5.4 The 13-process cross-process result
`npm run testnet` (`scripts/testnet.mjs`), recorded at `docs/BUILD_STATUS.md:32` and
`:41-68`.
Thirteen OS processes, thirteen data directories, thirteen sealed keystores, thirteen producer
keys, real TCP, real Bifrost handshakes. Each node is told about node 1 and nobody else; the
resulting peer counts of 4 to 12 are Praeco discovery working rather than a pre-wired mesh.
**Result: all thirteen converge on one head and one state root, and each validates its own
chain from genesis.** All thirteen produce, in turn, under Tyr's slot schedule — 13 distinct
producers, every block sealed by the leader of its slot, slots strictly increasing, and all
thirteen agreeing on who sealed every height. The harness compares the roots explicitly
(`scripts/testnet.mjs:1325`, `every node computed the same state root`).
That is the cross-process determinism evidence this document rests on: thirteen independently
computed chains, not one process compared with itself.
**What it does not prove**, stated as plainly as the run deserves
(`docs/BUILD_STATUS.md:54-66`, `scripts/testnet.mjs:66-73`):
- One machine is one clock, so the half of the slot rotation where nodes disagree about which slot it is
cannot be tested at all.
- Nobody went offline, so "an absent leader costs one slot and the chain continues" is
**unmeasured**.
- Nobody misbehaved, so zero equivocation alarms is an absence of misbehaviour, not a
demonstration that the alarm fires.
- One disk, one kernel, one failure domain. No hostile peers, no packet loss, no partitions, no
independent operators.
It is a working network. It is not evidence of a safe one.
A different-state-root-at-the-same-head failure is called out in the runbook as the worst
outcome the harness can report: *"The blocks agree and the nodes computed different state from
them — a determinism bug, which is the class of defect this codebase treats as most serious"*
(`docs/TESTNET.md:248-251`).
---
# Part VI — Sindri: the contract state ledger
`src/core/contract-state.ts`.
## 6.1 Why the class exists
Contract state used to live in a `Map` on `ContractExecutor`, which is process memory and
nothing else. All three of the worst consequences at once
(`src/core/contract-state.ts:28-38`):
- the state root did not move when a contract was deployed or executed, so the chain committed
to none of it;
- two nodes replaying the same chain could hold arbitrarily different contract storage and both
return `validateChain() === accepted`, which is a silent fork with no error anywhere;
- a restart or a snapshot restore lost every contract and every slot it owned, and the next
call threw `unknown contract address` against a chain that says the contract is there.
## 6.2 The commitment structure
Two levels, both `GlasirTree` — the same sparse Merkle tree the token ledgers use. Using Glasir
rather than a second bespoke hash means the root is order-independent **by construction**
instead of by a sort somebody has to remember to keep
(`src/core/contract-state.ts:40-46`).
- **Outer tree**: contract accounts under `glasirKey("sindri:contract:" + address)` and caller
nonces under `glasirKey("sindri:caller:" + address)`, namespaced so the two can never collide
(`src/core/contract-state.ts:1558-1565`).
- **Inner tree**, one per contract: storage slots under `glasirKey(slotName)`, leaf value
`slotCommitment` (`src/core/contract-state.ts:1245-1255`).
The account leaf (`accountCommitment` `src/core/contract-state.ts:1863`) is
`sha256` over `"sindri:contract:v1" | address | name | bytecodeHex | sha256(canonicalAbi) |
compilerVersion | deployer | salt | storageRoot`. **The address is included as well as being
the key**, so a leaf cannot be lifted from one contract to another.
`stateRootHex()` flushes the dirty sets and returns the outer root
(`stateRootHex` `src/core/contract-state.ts:818`). It is a function of the *set* of contracts, their code,
their deployer and their storage — not of deployment order, not of write order, not of how many
times a slot was overwritten on the way to its current value.
`verify()` re-derives every address from its own name, code, deployer and salt and re-decodes
its bytecode (`src/core/contract-state.ts:1086`). An address that does not re-derive means a
leaf was lifted from somewhere else, which is the shape a state-injection attack takes.
## 6.3 Address derivation
```
address = formatAddress(sha256("ares-contract:" + name + ":" + bytecodeHex + ":" + deployer + ":" + salt).slice(0, 40))
```
`contracts/registry.ts:105-108`. Contract addresses share the account address space, so the
ledger needs no second address format.
**A contract account is keyless, and that is the security argument for letting it hold value.**
This address is the truncation of a SHA-256 digest and of nothing else — there is no seed and no
private key anywhere that produces it, so to sign as a contract one would have to invert
SHA-256. It is deliberately the same construction as `feelessPoolAddress`
(`contracts/registry.ts:87-91`).
The consequence is the one that matters: **no transaction can ever spend from a contract
account**, because the transfer path needs a signature and a nonce from the sender and no key
exists to make them. The only debit path is the `TRANSFER` opcode of the bytecode this address
derives from, executed inside a block from a record every node replays. So the authorisation for
value leaving a contract is *the code committed at that address, run on the arguments the block
carries* — not the deployer, who has no power the code does not give them, and not this node's
opinion (`src/core/contract-state.ts:326-341`).
That statement is checkable rather than promised: code that would spend differently is a
different address, and the state root commits to both.
The catalogue is keyed **by bytecode, never by name**
(`contracts/registry.ts:8-24`). It used to be a `Map`, which turned a
contract name into a chain-wide first-come claim — and the name was taken at compile time,
before the initializer ran, so a deployment whose initializer reverted burned the name
permanently for a contract that never existed.
## 6.4 The value journal
`ValueJournal`, `src/core/contract-state.ts:202-317`. The same shape as the working copy of
storage, for the same reason: a call that moves value and then reverts must leave no trace.
- One journal per execution, never shared and never reused
(`journalFor` `src/core/contract-state.ts:1552`). A journal that outlived its call would be
a pending transfer looking for something to settle it.
- Balances are read **through** the journal (`balanceOf`, `:238`), so a contract that transfers
and then reads its own balance sees the money gone — the same world its next `require` will
be checked against.
- Sufficiency is checked against the journal's view, not the ledger's, so two transfers in one
call cannot each pass on the same balance (`:287-291`).
- `moves` is an ordered array, and it is the only thing anything downstream is allowed to read
(`:205-210`).
- `settle()` is **all or nothing** (`:307-316`): the aggregate is re-checked against the real
ledger before the first posting, so there is no sequence of events in which half a call's
transfers land.
Every rule a transfer must pass (`:250-296`):
| Check | Revert message |
|---|---|
| integer amount | `transfer amount must be an integer` |
| positive amount | `transfer amount must be positive` |
| non-empty recipient | `transfer needs a recipient` |
| **valid address, checksum and all** | `transfer recipient is not a valid address: …` |
| not self | `a contract cannot transfer to itself` |
| **not a Hnitbjorg account, unless it is a deployed contract** | `refusing to credit a reserved account: …` |
| funded, against the journal | `contract … holds N minor STR, cannot transfer M` |
The address check is applied here *as well as* in `validateArgs`, because an argument is not the
only way an address arrives: a recipient can be read out of storage, concatenated, or defaulted
from an uninitialised `state owner: address = ""` — none of which passes through the ABI. This
is the last point before value moves (`:254-262`).
**The receive gate is exactly the transfer path's, and was relaxed in the same movement.** It
used to require an allocated STR.domain, on this argument: if a contract could pay an address
with no allocated domain, routing value through a two-line contract would be the way to put STR
anywhere at all, and "every SourceLess user holds an STR.domain" would hold for everyone except
anyone who bothered to deploy. That argument was sound while the *ordinary transfer path* refused
a domainless recipient. It does not, since the domainless-recipient change
(`docs/book/LEDGER_AND_STATE.md` §2.2.1) — so a contract refusing one would not defend a rule, it
would only mean an escrow, a payroll or a vesting schedule cannot pay somebody a person can pay.
What is still refused is a **Hnitbjorg** account (`src/core/hnitbjorg.ts`): the Echo vault and the
Feeless Pool, whose ledger balances are compared against books kept beside them. Both directions
call `reservedAccountRefusal`, so they cannot drift. The one exception is another deployed
contract, and it is not a hole: a contract address is a hash with no key behind it, and its
balance is not a book kept anywhere else — the ledger *is* its balance. Value does not escape
through the exception, because the next hop out
of *that* contract is checked by this same rule.
**The gate answer is cached for the length of one call** (`:212-229`). `hasAllocationFor` walks
every allocation when the wallet is not a proved one — measured at **4.2 ns per allocation**, so
**0.43 ms per check against a registry holding 100,000 allocations**. AresLang has loops, and a
payout loop at 2,100 gas per transfer fits roughly 470 of them inside a default gas limit, so
that is **0.2 s of scanning per call record**, growing with the size of the network. The cache
is correct because nothing can change the answer mid-call: there is no contract-to-contract
call, so no identity record can be applied while the journal is open, and block execution is
single-threaded. It bounds the repeat case, not the distinct case; the real fix is an index in
the registry, which is not that file.
**Contracts move STR and nothing else, deliberately** (`contractValuePort`,
`src/core/contract-state.ts:124-152`). A contract that could move CCOS would be moving value on
the financial ledger; one that could move WNFT would be moving domain identity. Each is a policy
question with an owner, and none is answered by "the contract asked". `move` burns from the
source before minting to the destination, so the pair conserves supply exactly and a token at
its cap does not refuse a transfer that conserves supply.
## 6.5 `applyDeploy`
`src/core/contract-state.ts:695-763`. Order, and every step of it is load-bearing:
1. Exactly one of `source` / `compiled` (`:696`).
2. Compile (or accept the pre-compiled), then `assertDeployable`
(`:700-701`, `:1567`): non-empty name, non-empty lowercase-hex bytecode, at least one
function in the ABI.
3. Derive the address; refuse a collision, naming the salt as the fix (`:704-707`).
4. **Authenticate the deployer before executing anything** (`:709-711`). An unauthenticated
deployer is an unauthenticated `CALLER` inside the initializer, where state ownership is
usually set.
5. Assert the STARW machine can execute at all, before spending any of its gas
(`:714-715`).
6. Decode the module and run `__init` with a full host (`:717-731`).
7. If the initializer reverted, **throw and leave the ledger untouched** — no account, no
reserved name, no consumed nonce, no execution record (`:733-738`). It used to burn the
name chain-wide.
8. Insert the account, mark it dirty, consume the nonce, settle the journal
(`:740-759`).
9. Record the STARW execution (`:761`).
A deployment's gas is **unmeasured for post-mining**, and is left unmeasured rather than
guessed: the ledger returns a runtime for a deploy and does not report the gas its initializer
burned, so there is no measured cost to mint against
(`src/core/blockchain.ts:3825-3829`).
### 6.5.1 How big a contract can be — `MAX_RECORD_BYTES`
**383,616 canonical bytes, for the whole deploy record.** That is
`MAX_RECORD_BYTES` (`src/core/blockchain.ts:1789`) =
`MAX_BLOCK_BYTES` (`src/core/blockchain.ts:1225`, 400,000) −
`BLOCK_ENVELOPE_HEADROOM_BYTES` (`src/core/blockchain.ts:1708`, 16,384). The record is the thing
measured, not the source: `name`, `source` **and** `bytecodeHex`, plus the caller, the salt and
the gas limit, serialised by `canonicalStringify` (`src/core/canonical.ts:3`).
The headroom is itself measured rather than chosen. The block's running byte budget counts
**records only** — the header, the block hash, the attestations and the JSON structure around
them are not records and are not counted — and without a reserve the assembly overshot by
**1,127 bytes** on a block built right up to the limit (`src/core/blockchain.ts:2489-2493`).
16,384 is that with room to spare, deliberately, because the backstop firing means shipping a
block no peer can receive.
**The defect this closes is the part worth the space.** `MAX_BLOCK_BYTES` bounded the block and
**nothing bounded the record**, which made the block bound a *wedge* rather than a cut-off.
`produceBlock` spends a running budget and stops at the first record the remaining budget cannot
cover, leaving it queued. That is exactly right for a record that does not fit **this** block. It
is permanently wrong for a record that fits **no** block: the budget resets to the same value on
every block, so an oversized record is skipped at index 0 forever and everything behind it in the
queue starves.
Nothing else caught it on the way in. Styx's `matchesShape` checks that `source` is declared and
is a string, never how long it is; the gas gate bounds **execution**, not bytes; and the compiler
bounds tree depth, not text length (§1.10).
**Measured on this branch**, with the auditor's scenario reproduced exactly
(`tests/integration/record-size-gate.integration.test.ts:38-44`): one proved deployer submits a
**420,653-byte** deploy record and then an ordinary one, and five blocks are produced. Result:
**2 queued, 0 sealed, 0 refused.** The ordinary record was perfectly sealable and was starved.
And it **survived a restart**, because the pending queue goes into `chainSnapshot()` and comes
back through `submitContractRecord`, so the wedge is durable rather than a bad afternoon. The
behaviour that preceded this one *dropped* the oversized record instead — 0 queued, 0 sealed —
which loses one record; wedging the pipeline is worse.
**The rule is split in two, and each half is enforced where it is true.**
| | |
|---|---|
| **At the door** — `assertRecordFitsABlock` (`src/core/blockchain.ts:1831`), called by every `submit*` | A record **no block could ever carry** is REFUSED. It never occupies a queue slot. |
| **In the loop** — `fits` (`src/core/blockchain.ts:8251`) | A record that does not fit **this** block WAITS: unchanged, still queued, and the next block starts with a budget it is known to fit inside. |
**The two halves depend on each other and neither is correct alone.** The loop's `break` is only
safe because the door refuses the permanent cases — with the budget reset to full on every block,
a `false` from `fits` is then always a statement about what *this block has already spent* and
never about the record. And the door's refusal is only tolerable because a record that merely
arrived at a busy moment is not refused by it. The comment at `src/core/blockchain.ts:2518-2528`
states the dependency in that direction; `MAX_RECORD_BYTES` states it in the other.
**The refusal message says explicitly that this is not "try again later"**, and that is not
politeness. `recordFitsABlock` (`src/core/blockchain.ts:1799`) returns the measured size and the
budget, so the answer is a number rather than an adjective, and then says *"This is not a full
block and waiting will not help."* The queue-full refusal a few lines from every call site —
*"the contract record queue is full (…); try again after the next block"*
(`src/core/blockchain.ts:1041-1043`) — says exactly the opposite, and **"the block is full" and
"this will never fit" are the two answers a submitter must not confuse.**
**Contract and governance records are the kinds this actually bounds**, because they are the
kinds with an unbounded field: `source` and `bytecodeHex` on a deploy, `title` on a proposal.
The others are already bounded by their own shapes — an allocation or a registration by the
68-character domain cap, a transaction by `payloadHashHex` being a hash and everything else
being addresses and integers. **The gate is applied at every door anyway** (eleven call sites:
contract, governance, identity, collateral, wrap, domain burn, wNFT transfer, domain claim,
domain proof, transaction), because *"this kind happens to be bounded today"* is a property of a
shape someone may widen, and a gate that is only on some doors is a defect this file has been
bitten by repeatedly. `tests/integration/record-size-gate.integration.test.ts:275-285` asserts
the ordering constants that make every one of those `break`s safe: `MAX_RECORD_BYTES` below
`MAX_BLOCK_BYTES`, and `MAX_RECORD_GAS_LIMIT` at or below `MAX_BLOCK_GAS`.
**One precision, for a reimplementer.** Both the record gate and the block backstop measure
`canonicalStringify(x).length` — UTF-16 **code units**, not UTF-8 bytes — and the error message
calls them bytes. For the ASCII JSON every shipped template produces the two are equal. They are
not equal for a `source` carrying non-ASCII, where the wire form is larger than the number
compared. Both gates use the same measure, so they cannot disagree with **each other**; whether
the wire itself agrees is **unmeasured here** and belongs to the network layer. A reimplementation
must use code units to stay byte-identical with this one.
## 6.6 `applyCall`
`src/core/contract-state.ts:778-859`. Order:
1. Resolve the account and the ABI entry; **`validateArgs` first**, so an argument the ABI does
not admit is rejected before a single opcode runs (`:779-783`).
2. Authenticate the caller (§6.8).
3. Assert the machine can execute.
4. Run, with `readOnly` set from `stateMutability` and a host carrying a
`readOnlyReason` for a view (`:788-806`).
5. If it succeeded and it was a view, compare storage and **throw** if it changed
(`:811-813`). Checked before anything is written, so this throw also leaves the ledger
untouched.
6. Consume the nonce **whether or not the contract reverted** (`:816-817`): the signature was
valid and has now been seen, so the same authorization can never be submitted again.
7. On success only: `assertTransfersAgree`, then settle value, then commit storage, then append
events (`:828-842`).
**Value first, then storage** (`:836-838`). `settle` is the only step left that can throw — it
re-checks the aggregate against the real ledger — and a throw there must leave the storage leaf
untouched as well, so the two are ordered rather than interleaved. Storage commitment cannot
fail, so nothing can land half-applied.
`assertTransfersAgree` (`:1663`) compares the VM's list of what a call *asked for* against the
journal's list of what *passed the ledger's rules*, exactly and in order. Two lists of the same
events kept on two sides of a seam is a thing that drifts, and the drift would otherwise be
invisible: the balances would move, the block would seal, and the disagreement would surface as
a state root mismatch on some other node.
The rollback story above `applyCall` is in `acceptBlock`
(`src/core/blockchain.ts:2360-2364`): everything from that point runs against a snapshot that is
thrown away unless the whole block applies. *"A partially applied block is worse than a rejected
one, because it is invisible."*
## 6.7 `validateArgs`
`src/core/contract-state.ts:1587`. Typed argument validation, run before the first opcode.
`address` is the interesting case (`:1604-1620`). `address` and `string` used to share a
branch, so the only thing an `address` parameter ensured was that it was text:
`transfer("", 1000)` passed ABI validation and reached the opcodes. **Every payout template —
escrow, vesting, multisig, staking, a treasury — has that shape**, so the whole class is closed
here with `isValidAddress`, checksum included. A mistyped address is refused rather than
credited to an account nobody holds the key for.
`uint` additionally requires non-negative (`:1595-1597`).
## 6.8 The caller gate
Two independent gates, at two layers, answering two different questions.
**Sindri asks: is the caller who they claim to be?** `CallerAuthenticationMode`
(`CallerAuthenticationMode` `src/core/contract-state.ts:497`) is `signed` by default
(`:613-614`) — *"a default that quietly accepts an unauthenticated caller is the bug this
exists to close"*. `unauthenticated-local` is legitimate for a local simulation or a
single-process tool, never for anything a peer can reach, and a call site that wants it has to
say so.
`assertAuthorization` (`:1162-1173`) checks three separate facts and all three are needed:
1. the public key must **derive** to the claimed address, or anyone could present their own key
beside somebody else's address;
2. the signature must verify over **the exact call**, or a signature for one function could be
replayed against another;
3. the nonce must be the one this ledger expects, or a captured authorization could be
resubmitted forever.
The signed payload binds a **chain** (`callAuthorizationPayload`, `:1326`). Contract addresses
derive from name, bytecode, deployer and salt, so the same deployment sits at the same address
on every SourceLess chain — mainnet, a testnet, a fork — and without the binding an
authorization captured on one verified and executed on another wherever the caller's nonce
lined up. A ledger constructed without one gets `UNBOUND_CHAIN`
(`:1315`), deliberately not a valid genesis hash.
Deploy authorizations are signed over the **compiled code**, not the source text
(`signDeployAuthorization`, `:1395`), and the declared deployer must equal the signer
(`:1138-1140`).
**The chain asks: is that account entitled to be here at all?** `contractCallerGate`
(`src/core/blockchain.ts:749-770`) requires a **proved** STR.domain to deploy or call — the
1000 STR lock is the only cost standing between a fee-free chain and unbounded spam, and this
path used to walk around it. A deployed contract is admitted as an actor without a domain,
because the account that funded it was gated when it did so.
This is chain policy and is deliberately **not** enforced inside Sindri
(`src/core/blockchain.ts:701-704`): Sindri proves the caller *is* who they claim, which is a
different question from whether that account is entitled to be here, and Sindri does not hold
the domain registry that could answer the second.
The same gate runs on the follower path over records already sealed
(`src/core/blockchain.ts:2382-2386`), because admission is node-local and a record already in a
block has to be judged identically by everyone — *"or a producer could seal work its followers
would refuse and the chain would split on who was allowed to speak rather than on what was
said."*
A companion gate bounds the budget: `contractGasGate`
(`src/core/blockchain.ts:736-747`) refuses a non-positive or non-integer `gasLimit` and anything
above `MAX_RECORD_GAS_LIMIT = 10,000,000`, and `acceptBlock` caps the sum at
`MAX_BLOCK_GAS = 60,000,000` (`src/core/blockchain.ts:2393-2397`). The reason is measured:
**~6.4 ns per gas unit**, so a single record declaring 1e9 gas took **5.7 seconds** to produce,
6.2 to accept on every follower, and 6.6 on every full `validateChain()`; thirty-two records at
1e8 in one block took **20.4 seconds** (`src/core/blockchain.ts:211-223`). Ten million bounds
one record at roughly 60 ms.
## 6.9 `simulateCall`
`src/core/contract-state.ts:878-947`. Runs a call and throws the result away. **The answer-now
path, and the only one a query may take.**
The reason is a real incident (`:861-877`): `applyCall` mutates — it consumes the caller's
nonce, commits storage, appends events and records a STARW execution — all of which belong to
block execution. Calling it to answer a question instead **moved contract state on one node,
outside any block, and the producer's own chain stopped validating three blocks later** when
the replayed ledger no longer matched the committed root. That was reachable through one
documented, signed API call.
So `simulateCall`:
- executes against `new Map(account.storage)`, a copy, so a VM that writes through cannot reach
the real storage (`:910`);
- takes a journal that is **never settled** (`:902-905`), so a simulated transfer checks every
rule a real one checks — recipient gate, sufficiency, the balance the previous transfer left —
and posts nothing;
- consumes no nonce, which is why **no signature is required**: an unsigned simulation cannot be
replayed against the chain, because it never touched the chain;
- checks nothing about identity, because a simulation proves nothing about identity
(`:882`);
- reports event `sequence: -1`, deliberately not drawn from `eventSequence`, because a
simulation must not advance a counter the state root commits to (`:941-943`);
- **does not default the block position to a clock, nor to the head**
(`:885-895`). A simulation that names neither is answered with a host that reverts on
`TIMESTAMP` and `HEIGHT` — a visible "you did not say when" rather than a confident answer at
time zero.
It answers *"what would happen if this caller made this call against the state I hold right
now"*, which is the question a caller actually has, and is not a promise about what happens when
the call is sealed.
## 6.10 Records and snapshots
`ContractDeployRecord` carries `source`, `deployer`, `salt`, `gasLimit`, `authorization`;
`ContractCallRecord` carries `address`, `functionName`, `args`, `gasLimit`, `caller`,
`authorization` (`:498-516`). `applyRecord` is the single entry point a replay needs
(`:957`).
`contractRecordsRootHex` hashes records **in order** (`:1429`), unlike the state root — *"a
block's contents are a sequence and two orderings of the same calls are two different blocks
that reach two different states. That is the opposite property from the state root, and
deliberately so."*
`snapshot()` is sorted throughout (`:1021-1038`) so equal state produces an identical snapshot,
and `loadSnapshot` re-decodes each module from the committed bytecode
(`:1060-1062`) so a snapshot cannot restore a module that differs from the code the root commits
to.
`attachValue` refuses to **replace** a bound value port (`:628-633`): swapping the value backend
under a chain that has already executed would leave balances on one ledger and the contracts
that own them pointing at another, with nothing reporting it.
## 6.11 Post-mining
SourceLess charges the caller nothing. `postMineForContractRecord`
(`postMineForContractRecord` `src/core/blockchain.ts:18675`) mints STR into the Feeless Pool at
`EXECUTION_COST_MINOR_PER_GAS = 1n` (`src/core/blockchain.ts:349`), and `computePostMining` caps
the mint at 10% of the declared gas limit — so
```
minted = min(gasUsed, gasLimit / 10)
```
**Declare a gas limit of at least ten times what you expect to burn.** A call that declares
100,000 and burns 50,000 is covered to 10,000; the other 40,000 is reported as `uncoveredMinor`
and nobody pays it. The call still succeeds, so this is not a visible failure — it is the
network absorbing an unfunded cost, and a contract that systematically under-declares drains
the fee-free model quietly (`stdlib/gas.ts:44-56`).
Every template header therefore ends with a "declare at least N" line, and every N is ten times
the sum of that template's measured entry points.
---
# Part VII — Daedalus: the templates
`templates/`. Seven contracts, each a single `.ares` file whose header states what it is for,
what it enforces, how it is typically misused, and what it costs in gas
(`templates/README.md`).
**Every gas number below is from the table asserted exactly at
`tests/integration/template-catalogue.integration.test.ts:550-602`**, measured on compiler
`areslang-1.2.0` — a constant the same test pins at `:397`, so a codegen change fails the test
rather than silently invalidating every header.
The catalogue-wide assertion: every entry point is under 5,000 gas
(`:606-608`), and the most expensive is a single `TRANSFER` (2,100) plus a `BALANCE` (400) plus
book-keeping.
Facts common to all seven:
- **You must hold a proved STR.domain** to deploy or call anything (§6.8).
- **The deployer is the owner.** `state owner: address = caller;` runs in the initializer with
the authenticated deployer as `caller`, so no template needs a `claimOwnership` call and none
has a window in which a stranger could claim it.
- **Editing a constant changes the address.** Different code is a different contract.
- **A contract cannot see who paid it.** Templates that hold native STR are funded by plain
transfers and have no per-depositor accounting.
- **A recipient may be any well-formed address**, including one with no STR.domain at all. Only a
Hnitbjorg account is refused, and then the paying call reverts at the ledger — whole, with
nothing moved.
## 7.1 `zk13-token.ares` — ZK13Token
**For:** a fungible asset whose ledger lives in this contract's own storage, committed through
Sindri into the chain state root. The reference implementation of
`docs/ZK13_TOKEN_STANDARD.md`, with every view, function, event and `require` message spelled
exactly as the standard spells them, so a wallet can recognise a refusal without parsing prose.
**Enforces:** supply moves only through `mint` and `burn`; `transfer` moves it by exactly
zero. Minting closes permanently and `setMinter` cannot reopen it. The owner can pause and hand
over ownership in two steps but **cannot move anybody else's balance** — there is no
`setBalance`, no `adjust`, no `transferFrom`. A self-transfer is refused, so the classic
debit-then-credit inflation bug cannot be reached at all.
### The exploit that was executed and closed: mint → burn → mint outrunning the cap
`templates/zk13-token.ares:12-18`, closed and pinned at
`tests/integration/template-zk13-token.integration.test.ts:272-297`.
The cap was tested against `supply`, which `burn` lowers. So mint 1,000 / burn 1,000 gave the
room back, and **four rounds issued 4,000 tokens against a cap of 1,000 without a single revert,
on a chain that stayed valid.** A cap that burning reopens is not a cap.
The fix is a second counter, `issuedEver`, which only ever goes up
(`templates/zk13-token.ares:82`), and the cap bounds **lifetime issuance** rather than
circulating supply. The test now asserts that after mint-then-burn the circulating supply is
zero, `lifetimeIssued()` is 1,000, and the next mint — of 1,000 or of a single unit — reverts
with `supply cap`.
`supplyCap` **ships at 0, which is uncapped**, and that is deliberate rather than lazy: a
template cannot invent a cap for a token it knows nothing about, and a plausible-looking
placeholder reads as a decision somebody made.
**Measured gas:** mint 1,135, transfer 826, burn 774, proposeOwner 412, acceptOwnership 612,
setPaused 363, setMinter 471, closeMinting 470. Declare at least 12,000.
## 7.2 `escrow.ares` — Escrow
**For:** a buyer funds the contract, the seller performs, the buyer or the arbiter releases; if
nobody releases, the buyer takes it back after a deadline fixed at setup.
**Enforces:** the seller cannot pay themselves — `release` refuses any caller who is not the
buyer or the arbiter, and pays the address stored in `seller`, never the caller. The buyer
cannot take the money back early: `timeoutRefund` reads the **block's** timestamp and there is
no time argument anywhere in the ABI. It closes exactly once.
### The exploit that was executed and closed: arbiter self-dealing
`templates/escrow.ares:12-16`, closed and pinned at
`tests/integration/template-escrow.integration.test.ts:61-105`.
The buyer transfers in first — a mistake the header now warns about, but a mistake somebody
makes — and **the arbiter then opens the escrow naming itself the seller and calls `release`.
One call, the whole balance.** And in status 0 there was no exit at all, so the money had been
hostage from the moment it arrived. The mirror works too: an arbiter that names itself the
*buyer* takes the same money through `refund`.
`open` now refuses a buyer or a seller equal to the arbiter, in both directions, with
`the arbiter cannot be the seller` / `the arbiter cannot be the buyer`. The test also asserts
that status 0 has no exit and cannot have one — all three paying paths revert with
`escrow is not open` — because with no buyer and no seller recorded there is nobody the
contract could honestly pay. The money comes back the way it always did: open with two real
parties and let the deadline return it to the buyer.
**What the arbiter can still do, declared:** send the money to either party at any time before
the deadline. That is custody, it is visible in the ABI as `arbiterIs()`, and the promise
that was bought is narrower and honest — every path the arbiter can take now pays somebody
else.
**Measured gas:** open 1,258, release 3,235, refund 3,235, timeoutRefund 3,233. Declare at least
33,000.
## 7.3 `vesting.ares` — Vesting
**For:** a grantor funds the contract, then starts a schedule; from the cliff onwards the
beneficiary draws the linearly vested share.
**Enforces:** nothing is payable before the cliff, on the block's clock, with no time argument
in the ABI. **Every release pays `vested - alreadyReleased`, never `vested`** — the classic
vesting bug is paying the vested total on every call, which pays the whole schedule repeatedly.
The sum of everything ever paid is exactly `total`. `release` pays the stored beneficiary and
any caller may trigger it, because a beneficiary without gas is not a beneficiary who cannot be
paid. **The grantor keeps no power after `start`**: no revoke, no cancel, no accelerate, no
sweep — a grantor sweep is a revocation power wearing a support tool's clothes.
**No executed exploit is recorded against this template.** What the test attacks is: the
beneficiary drawing before the cliff, the caller drawing the whole schedule twice, the grantor
trying to take it back, and the release the ledger refuses — which must roll the `released`
counter back with the money, or the grant quietly shrinks by the amount of a payment that never
happened (`tests/integration/template-vesting.integration.test.ts:4-11`).
**The limit that shapes it:** `start` snapshots `balance(self)` as the granted total, because
the contract cannot see who paid it or when. **Anything transferred in after `start` is
stranded.** `start` refuses a zero balance but cannot refuse a *partial* one.
**Measured gas:** start 1,962, release 3,105 during the linear period, 2,890 after the end date.
Declare at least 32,000.
## 7.4 `multisig.ares` — Multisig
**For:** shared custody of native STR. Any owner proposes; the payment happens once `threshold`
distinct owners approve that exact proposal.
**What it can do, stated precisely:** pay native STR out of its own balance, to an address named
in a proposal. It **cannot** execute an arbitrary call on another contract, cannot move a ZK13
token held elsewhere, and cannot act as a general-purpose wallet — there are no cross-contract
calls. *"If you need more than that, this template is not a smaller version of what you need —
it is a different thing, and the thing you need does not exist yet."*
**Enforces:** one owner is one approval; a second `approve` from the same owner reverts rather
than incrementing, so M-of-N cannot be cleared by one key calling M times. An approval binds the
exact action — `to` and `amount` are written once at `propose` and no function edits them. A
proposal executes at most once, and only an owner may trigger it. The owner set and threshold
are frozen at `seal`, so "M-of-N can lower M to 1" is not a state this contract can reach.
**No executed exploit is recorded.** The test that matters is the signer who must not count
twice: *“if one owner can clear an M-of-N by calling `approve` M times, the contract is a 1-of-N
wearing a multisig's clothes and every other guarantee here is decoration”*
(`tests/integration/template-multisig.integration.test.ts:4-11`).
**The price of the freeze, and it is a real one:** a lost key is permanent. There is no
rotation, and the code is immutable.
**Counting approvals by iterating an owner list is the misuse to avoid.** This contract keeps a
counter: at 55 gas per map read plus 20 per loop iteration, a few thousand owners is a contract
that becomes permanently uncallable with the funds behind the frozen function. `maxOwners` is
bounded at 20 as a limit on how far a setup mistake can go, not as a gas limit — nothing
iterates.
**Measured gas:** addOwner 919, seal 736, propose 1,391, approve 938, execute 3,380. Declare at
least 34,000. Execute at 3,380 is the most expensive entry point in the whole catalogue.
## 7.5 `dao-treasury.ares` — DaoTreasury
**What it governs:** this contract's own balance, and nothing else. It is **not** SourceLess
governance — chain-wide parameters belong to the Althing, and no contract can touch any of it.
*"A DAO template that presents itself as SourceLess governance is presenting authority it does
not have, and this one does not."*
**Enforces:** the electorate is **frozen at proposal time** — a proposal records the epoch and
the member count at that instant. Both directions are bugs in live-membership tallying:
admitting a large member mid-vote defeats a proposal that had already passed, and removing
members shrinks the threshold until an existing minority's votes clear it. One member one vote.
A strict majority of the frozen roll: `yes * 2 > roll`, so a tie does not pass. Three kinds of
proposal — pay, admit, remove — and no fourth, deliberately the Althing's three, *"because a
governance system that can change anything is a governance system that can be used to steal."*
### The exploit that was executed and closed: the four-call steward drain
`templates/dao-treasury.ares:45-60`, closed and pinned at
`tests/integration/template-dao-treasury.integration.test.ts:143-186`.
An earlier version claimed "the steward cannot spend" on the grounds that no function moving
value checks `steward`. An audit executed the counterexample on a real chain:
> **remove all five members, admit yourself, propose a payment to yourself, vote once against a
> roll of one, execute. Whole treasury, four calls, chain still valid.**
The reasoning that makes the fix total rather than a patch: a steward that can admit members can
admit members **it controls**, and nothing in this contract — nothing on this chain, from inside
a contract — can tell an independent member from an address the steward holds the key to. So a
live steward is, in the limit, a majority of any future roll. The self-admit ban and the roll
floor stop that particular sequence; they cannot stop a steward that simply admits four
addresses it owns.
So the template **separates the two powers in time** instead of trying to bound one of them.
`propose` refuses to run while `stewardActive` is true. Therefore, while the steward has any
power over the roll, **no value can leave this contract by any path** — `execute` can only pay a
proposal, `propose` is the only thing that creates one, and `propose` is shut. After
`renounceSteward()`, which is one-way, the steward has no power over the roll at all. The two
states are exclusive by construction, which is the only way the promise can be kept.
The test walks the original attack step by step and asserts each step's revert reason:
`the roll cannot fall below its floor`, `the steward cannot sit on the roll`,
`the steward still holds the roll`, `no such proposal` — and that nothing moved in either
direction at any step.
**The order is: admit, renounce, fund, propose.** *"DO NOT FUND A TREASURY WHOSE
`stewardHasPower()` IS STILL TRUE. It cannot spend, but it can still decide, alone, who will."*
**After renunciation the roll is self-governing, not frozen**, and the reason is stated: a sealed
roll would make a lost key permanent, because every proposal needs a strict majority of the
*whole* roll, so a dead seat is a vote against everything. What that costs is stated plainly — a
majority of the roll can admit anybody, including addresses one member controls. *"A DAO's
members can always vote to do something foolish; the property this template keeps is that no
single key can."*
**Measured gas:** admit 1,500, remove 1,386, renounceSteward 673, propose 2,716, proposeAdmit
2,777, proposeRemove 2,838, vote 1,199, execute 3,338 on a payment, 2,051 on an admission,
1,994 on a removal. Declare at least 34,000.
## 7.6 `staking-token.ares` — StakingToken
**Why the token and the staking are one contract:** because they have to be. A ZK13 token's
ledger lives in its own contract storage and there are no cross-contract calls, so a separate
staking contract could never move a holder's balance — and a balance recorded at a staking
contract's address could never move again at all, because a contract cannot be `caller`. The
same reasoning is why it does not stake **native STR**: the contract cannot see who paid it.
**Enforces:** a staker can never withdraw more principal than they staked (`unstake` is a
checked subtraction against that staker's own slot, keyed by `caller`) and can never touch
another staker's position (every position is keyed by `caller` and no argument names whose
position to move). Reward accrues from the block's timestamp, comes only out of the declared
pool, and can never mint supply out of nothing. `totalSupply` is unchanged by staking — staked
tokens move to `self`, which is a balance slot like any other.
### Exploit 1, executed and closed: the pause freezing principal
`templates/staking-token.ares:30-32`, closed and pinned at
`tests/integration/template-staking.integration.test.ts:253-291`.
In the earlier template `unstake` required `frozen == false`. So **one bool set by one key froze
every staker's own tokens for as long as that key stayed silent — with no renounce and no second
key anywhere in the contract that could end it. That is confiscation with an off switch.**
`unstake` is now the one mutating function the pause does not gate. The test pauses the
contract, asserts `stake`, `claim` and `transfer` all revert with `paused`, and then asserts
`unstake` succeeds and returns **every unit** of the principal — while paying not one unit of
reward, because a pause holds the pool, which is the contract's money, and never the stake,
which is the staker's.
### Exploit 2, executed and closed: mint → burn → mint
The same cap defect as §7.1, on the same terms — *"measured on this template before the fix:
4,000 issued against a cap of 1,000"* (`templates/staking-token.ares:33-36`). Closed the same
way and pinned at `tests/integration/template-staking.integration.test.ts:394`.
### The reward that used to be destroyed
Before `rewardOwed` existed, a claim against a short pool paid the clamped amount and restarted
the clock, and the difference was gone
(`templates/staking-token.ares:52-60`). Now a shortfall is **carried as a debt**, readable as
`rewardOwedOf(account)`, and a debt outlives the stake that earned it — `claim` accepts a caller
with a debt and no position. The test asserts a full year's 50,000 accrual survives an unstake
taken while paused, and is claimable afterwards
(`tests/integration/template-staking.integration.test.ts:277-286`).
What the debt does **not** promise is stated: nothing mints to cover it, a refill is taken by
whoever settles first, and *"the ordering is a race"*.
**The accrual block appears three times and must stay identical.** With no user-defined
functions it cannot be factored out, so it is copied verbatim between `ACCRUAL BEGIN` and
`ACCRUAL END` markers into `stake`, `claim` and `unstake`, and a test extracts all three and
fails if they are not character-for-character the same
(`tests/integration/template-staking.integration.test.ts:343`).
`maxAccrualMs` caps the accrual window at 730 days, which is what keeps
`staked * elapsed * rate` from growing without bound until it reverts at the 4,096-bit integer
ceiling and strands the position (`templates/staking-token.ares:99-101`).
**Measured gas:** mint 1,135, transfer 826, burn 774, fundRewards 1,272, stake 2,276 on a fresh
position and 2,560 on a top-up that settles a reward, claim 2,200, unstake 3,603 and 2,509 while
paused. Declare at least 38,000.
## 7.7 `nft-collection.ares` — NFTCollection
**This is not a domain WNFT, and it cannot be made into one.** The native WNFT is one per
STR.domain, minted by the domain registry, backed by 1000 STR locked, and non-transferable.
Nothing in this contract is any of that. A **domain-bound** NFT is not writable today because
`AresHost` has no domain accessor: a contract cannot ask whether an address holds a proved
domain. Storing a domain string and treating it as proof verifies nothing, and case folding —
`STR.Treasury` beside `STR.treasury` — is an impersonation primitive the contract cannot even
detect. *"A template that lets a user believe they are minting a domain WNFT is the most
dangerous mislabelling available on this chain."*
**Enforces:** only the holder of a token can move it — `transferToken` compares
`tokenOwner[id]` to `caller`, and there is no `from` argument, no operator and no approval
mechanism, so there is no second authority. An id is minted at most once. The cap is fixed at
deployment. Minting closes permanently. The contract owner cannot take a token from a holder.
The pause freezes mint, transfer and burn and freezes no view.
**No executed exploit is recorded.** The property under test is the simplest and most important
one, and the last test in the file is the one that keeps the WNFT distinction honest
(`tests/integration/template-nft.integration.test.ts:4-16`).
**No enumeration of a holder's tokens**, deliberately: that would be iteration over
caller-controlled data, which is how a contract becomes permanently uncallable at a size
discovered in production. `ownedCount` is a counter; an indexer builds the list from `Transfer`
events.
**Measured gas:** mint 1,214, transferToken 1,110, burnToken 804, setPaused 363, setMinter 471,
closeMinting 470. Declare at least 13,000.
---
# Part VIII — Hephaestus: the standard library
`stdlib/`. The house name is Hephaestus, the smith who forged the armour of Ares
(`docs/NAMING.md:68`).
## 8.1 What it is
**It is not callable code.** AresLang has no user-defined function calls, so a routine a
contract calls at runtime cannot exist, and nothing in the directory pretends otherwise
(`stdlib/source.ts:14-28`).
Hephaestus is a set of **source patterns**: real AresLang declarations and statements, held as
text, composed into the author's contract *before* a single token is lexed. `compose()`
(`stdlib/index.ts:79`) assembles them and hands `compileAresContract` one ordinary source
string, so everything downstream behaves exactly as it does for a hand-written contract: one
parse, one ABI derived from that text, one instruction stream, no drift.
Three kinds, and the difference matters (`stdlib/index.ts:25-29`):
- a **module** contributes whole `state`, `event` and `fn` declarations;
- a **guard** is one AresLang statement, pasted at the head of a function the author wrote;
- an **expression** is a fragment that goes inside one of the author's own statements.
## 8.2 The surface
`stdlib/index.ts:11-23`:
| Export | Kind | What |
|---|---|---|
| `ownable()` | module | one owner, set to the authenticated deployer, handed over in two steps |
| `roles()` | module | `map>` role table, owner-granted, self-renounceable |
| `pausable()` | module | emergency stop; pause may be delegated, unpause is owner-only |
| `ONLY_OWNER`, `onlyRole`, `onlyOwnerOrRole` | guard | access checks |
| `WHEN_NOT_PAUSED`, `WHEN_PAUSED` | guard | pause checks |
| `requireAtLeast/AtMost/Positive` | guard | bounds that are policy, not machine limits |
| `mulDiv`, `ceilDiv`, `basisPoints`, `minInto`, `maxInto` | expression | the arithmetic that is genuinely error-prone here |
| `requireAddressShape/NonEmpty/TextAtMost/Distinct/NotSelf` | guard | text and address checks |
| `setDeadlineFromNow`, `afterDeadline`, `beforeDeadline`, `afterHeight` | pattern | schedules no caller can move |
| `payout`, `requireSolvent`, `bindSelfBalance` | pattern | value, in checks-effects-interactions order |
| `compose`, `composeSource` | composer | assembles the above into one AresLang source text |
| `HEPHAESTUS_GAS`, `measureMarginalGas`, `probeHost` | measurement | the published costs and the probes that produced them |
`HEPHAESTUS_VERSION = 'hephaestus-1.0.0'` (`stdlib/source.ts:72`), moving when a routine's
emitted source changes, because bytecode moves with it. Every revert message is prefixed
`hephaestus/` (`stdlib/source.ts:82`), so a caller reading a reason can tell a library rule from
the author's own logic.
## 8.3 Why it is not in the compiler
`stdlib/source.ts:44-68`. `docs/ARESLANG_STDLIB.md` §7 recommends declaration forms the
*compiler* expands. **This library disagrees, and the disagreement is the design.**
A compiler expansion is code every node must run identically forever and cannot change without a
fork. Putting `require(caller == owner, ...)` in there makes an access-control policy a
consensus rule: the day someone wants a different message, a different slot name or a three-key
owner, the fix is a hard fork. The document's own boundary rule — *"put it in the VM only when
no bytecode could compute it"* — argues against its own recommendation, because a bytecode
sequence computes every one of these routines perfectly well.
The objection §7 raises against a textual prelude is that it makes the deployed bytecode differ
from the source the author wrote. That objection is entirely about *where* the splice happens.
Here it happens before compilation, in ordinary application code, and the composed text **is**
the source. So **Hephaestus adds no opcode, no keyword, and no compiler branch**; `runtime/` is
untouched except for a pointer comment (`runtime/areslang.ts:13-33`). That is the strongest
statement available that the language is already sufficient.
## 8.4 The measured costs
`HEPHAESTUS_GAS` `stdlib/gas.ts:373`. Every number is the **marginal** cost of one routine —
the gas a contract spends because the routine is there — produced by compiling two contracts
that differ only in that routine, running both on the real VM, and subtracting
(`measureMarginalGas` `stdlib/gas.ts:134`). Nothing is counted by hand from the opcode table
and nothing is estimated. `tests/integration/hephaestus.integration.test.ts` re-measures every
probe and fails if a published number is wrong by one unit.
The probe host is built from fixed block fields — no clock, no live ledger, no randomness — so a
measurement is reproducible on any machine (`probeHost` `stdlib/gas.ts:99`), and the probe addresses are
fixed, well-formed, and explicitly not random values (`stdlib/gas.ts:87-89`).
| Routine | Marginal gas |
|---|---:|
| `ONLY_OWNER` | 57 |
| `onlyRole('MINTER')` | 66 |
| `onlyOwnerOrRole('MINTER')`, caller is the owner | 60 |
| `WHEN_NOT_PAUSED` | 56 |
| `requirePositive(amount)` | 8 |
| `requireAtMost(amount, cap)` | 57 (8 when the ceiling is a literal) |
| `requireAddressShape(to)` | 10 |
| `requireNonEmpty(text)` | 10 |
| `requireNotSelf(to)` | 9 |
| `afterDeadline(unlockAtMs)` | 58 |
| `setDeadlineFromNow(...)` | 212 |
| `mulDiv(amount, bps, 10000)` | 4 |
| `ceilDiv(amount, unit)` | 8 |
| `minInto(take, wanted, available)` | 8 |
| `requireSolvent(amount)` | 409 |
| `payout(held, to, amount)` | 2,413 |
Two consequences shape every routine (`stdlib/gas.ts:37-42`):
- **A state read costs fifty times a local read.** Bind once: `let held = balances[caller];`.
Reading the same map entry three times costs three `MLOAD`s.
- **A guard costs 8 to 60; the write it protects costs 200 to 2,100. There is no economic
argument for omitting one.**
`requireAddressShape` is honest about its limits: it catches **length only** — no prefix, no
checksum — and is redundant on an `address` *parameter*, which `validateArgs` already
checksummed for free (§6.7).
`payout` at 2,413 is 85% `TRANSFER`. *"Never put one in a loop whose trip count a caller
chooses: bound the count in the contract, or offer a pull-payment function each recipient calls
for itself."*
## 8.5 What it deliberately does not contain
`stdlib/index.ts:62-71`: no upgrade or proxy pattern (contracts are immutable by construction; a
proxy would teach authors to hand one key the power to replace the contract under its holders);
no reentrancy guard (§4.10); no `safeAdd`/`safeSub`/`safeDiv`/`safeMul` (nothing to guard — no
wrap, `uint - uint` is already `SUBU`, a zero divisor already reverts); no map enumeration of any
kind; no `setBalance` or `forceTransfer` (a mint that can also debit is a confiscation
primitive); no per-account freeze; nothing reading a wall clock or a random source; no
allowance-spending mechanism that assumes a spender contract.
## 8.6 The honest note
**No shipped template imports Hephaestus.** All seven `.ares` files in `templates/` are
hand-written AresLang with no `compose()` anywhere; a grep for `stdlib` or `hephaestus` across
`templates/*.ares` returns nothing. The library is measured, tested and documented, and it is
used by its own integration test and by nothing that ships in the catalogue.
That is a real gap between two parts of this tree, not a design decision either of them
records. A reader choosing between them should know that the templates are the artefacts with
adversarial tests deployed on a real chain, and Hephaestus is the artefact with per-routine gas
measurements.
**MEASURED, 2026-09-12, and now recorded in the library itself.** A comment-stripped scan of
`src/`, `runtime/`, `consensus/`, `contracts/`, `scripts/` and `templates/` for `stdlib/`,
`compose(`, `HEPHAESTUS` and `measureFunctionGas` finds every hit inside `stdlib/`; the only
external callers are `tests/integration/hephaestus.integration.test.ts` and
`tests/helpers/hephaestus-contracts.ts`. The verdict — **DORMANT** — and what reaching it would
take now stand at the top of `stdlib/index.ts`, where somebody opening the library reads them
before the surface table, rather than only here. Neither of the two routes (a template replaced
by a `compose()` spec, or a CLI verb that offers the library to an author) has been taken: both
are product decisions about the catalogue and the CLI surface, and wiring one to close a
documentation gap would be the wrong reason to make either.
---
# Reimplementing this layer: the conformance vectors
`spec/agent_handoff_contracts.md` states what this desk owes a second implementation: *compiler
output format, runtime ABI behavior, gas profile*. **Until 2026-09-12 none of the three was
vectored** — a grep of `spec/conformance-vectors.json` for `ares|bytecode|opcode|contract|gas`
returned zero — so a second STARW had nothing to check itself against, and the failure mode when
it diverged was a chain fork rather than a red test.
The `contracts` section of `spec/conformance-vectors.json` now carries all three. It is
**generated, never hand-written**: `npm run vectors` (`scripts/conformance-vectors.mjs`) rebuilds
the file from the built tree, and **a diff there is a change to what this chain considers
canonical, never a cosmetic one.**
| Published | What a reimplementation does with it |
|---|---|
| `compilerVersion`, `container.magic`, `container.version`, `container.minVersion` | Refuses to compare anything if these differ. Every number below is relative to one compiler. |
| `container.opcodeBytes` | The byte for all 38 opcodes. A decoder written from prose guesses these; a wrong guess is a module two nodes disagree about. |
| `container.opcodesWithNoCompilerPath` | `POP`, `DUP`, `AND`, `OR` — implement them anyway, for the reason under *Other sharp edges*. |
| `gasProfile` | The per-opcode table, the default, the backward-jump charge, and every ceiling: gas limit, stack depth, integer bits, string length. |
| `host` | The fixture every call below runs against: a fixed self address, block timestamp, height, balance table, and the exact message its `transfer` throws when the contract holds too little. Reproduce the host and the calls reproduce. |
| `modules[]` | Three fixed sources, each with its full container hex, the sha256 of those bytes, the ABI **derived** from the source, its state variables, and what `__init` leaves in storage. |
| `modules[].calls[]` | Twenty-two calls: arguments, caller, read-only flag, the storage each starts from, then `success`, `revertReason`, `returnValue`, `gasUsed`, `events`, `transfers` and the storage the ledger would commit. Reverts and an out-of-gas loop are included, because refusing identically matters as much as succeeding identically. |
| `refusedContainers[]` | Eleven containers that must be refused, each a valid module with exactly one defect — bad magic, a trailing byte, a truncation, a future version, a v2 opcode in a v1 module, an unknown opcode byte, a wrong operand kind, a jump outside its function, and invalid UTF-8 in a name and in an operand. Assembled byte by byte rather than by the encoder, because an adversarial container built by the encoder under test can only hold bytes that encoder is willing to write. |
Two tests hold it to the code, and they do different jobs.
`tests/integration/conformance-vectors-contracts.integration.test.ts` **re-derives** every value
from `runtime/` rather than re-running the generator — a test that called the generator would
prove the generator is deterministic and nothing about whether the numbers are right — and
`tests/integration/areslang-refusals.integration.test.ts` asserts every refusal in the VM and the
container, each with a positive control proving the refusal was REACHED rather than the input
dying earlier.
`gasUsed` is an exact number, not an estimate: gas is a pure function of the instruction stream
and the values on the stack, and the meter is what decides when a call reverts. A
reimplementation that is close is wrong.
---
# Known limits
Everything here is true of the code as it is. A VM reference that omits its DoS surface is worse
than none.
## What a contract cannot do on this chain
| | |
|---|---|
| **Call another contract** | No `CALL`, no `delegatecall`, no host callback. A multisig cannot act on another contract; a token cannot be staked outside its own contract; an allowance cannot be spent by anything. |
| **Call its own second function** | No internal calls either. Every shared routine is copied, and the copies are kept identical by tests that compare them character for character. |
| **Recurse** | Follows from the above. |
| **Receive value with a call** | A call record carries no value; there is no `msg.value` and no deposit hook. **A contract cannot see who paid it.** Native staking, token sales, shared vaults and tip jars are not writable, and no contract code fixes it. |
| **Take constructor arguments** | Configuration is source, and editing it changes the address. |
| **Ask about identity** | `AresHost` has no domain accessor. A domain-bound NFT, a domain-gated airdrop and a "verified holders only" rule are not writable from bytecode. |
| **Iterate, count or delete a map entry** | There is no enumeration primitive at all, deliberately: the gas limit is per call and the code is immutable, so a map whose size a caller controls becomes permanently uncallable at some size. |
| **Move anything but STR** | The value port is STR-only by construction; there is no token parameter on the host interface. |
| **Be upgraded** | Bytecode is in the address preimage and there is no `setCode` anywhere in Sindri. A bug is permanent; a lost owner key is permanent; a paused-forever contract is permanent. |
| **Be `caller`** | A contract has no key and cannot originate a call. **Any fungible balance or NFT sent to a contract address can never move again.** No template can detect the case to refuse it. |
| **Be deployed above 383,616 canonical bytes** | `MAX_RECORD_BYTES` bounds the whole deploy record — `source` and `bytecodeHex` together — and `submitContractRecord` refuses over it at the door rather than queueing it. The refusal is permanent and says so; it is not "try again later". **§6.5.1.** |
## What gas does not price
This is the DoS surface, stated rather than implied.
**State growth is not priced beyond the write.** `MSTORE` costs 220 plus the slot-name
surcharge, whether it overwrites an existing slot or creates a permanent new one. At the default
limit that is roughly 4,500 new slots per call, and at `MAX_RECORD_GAS_LIMIT = 10,000,000`
roughly 45,000. Every one of them is a Glasir leaf every node keeps forever, and there is no
deletion primitive to reclaim any of it. The opcode table's own justification for the 20-gas
premium over `MLOAD` acknowledges this — *"a permanent addition to state"* — but 20 gas is a
rounding error against permanence.
**Value size is not priced either, and there is no storage cap.** `STORE` and `MSTORE` price the
slot name and never the value, so a 65,535-character string costs the same write as a `uint`.
Audit C12 measured one 1,000,000-gas call writing 203 MB of logical committed state by storing
one shared string in many slots, and about 256 MB of resident state per 10,000,000 gas with
distinct strings. Closing it changes gas and therefore block validity, so it is a scheduled
consensus rule awaiting an owner decision, not a fix in place.
**Event payload size is not priced at all.** `EMIT` is a flat 100 gas regardless of arity or of
how large the arguments are. Arguments come off the stack, so arity is bounded by
`MAX_STACK_DEPTH = 1,024` and each string argument is bounded by `MAX_STRING_LENGTH = 65,535`
code units. Events are not in the state root, and they are appended to `account.events`, which used to be
unpruned and carried in full in every snapshot: a contract emitting in a loop grew every node's
memory and every snapshot without paying for it. That is now **measured and bounded**. One record
at `MAX_RECORD_GAS_LIMIT` emits 76,333 events and one block of six such records retained 457,998
of them for 85.4 MiB of snapshot growth — from 918 canonical bytes of records, an amplification of
about 97,600×, at no cost to the caller on a feeless chain. Retention is now capped at
`SINDRI_EVENT_RETENTION` = 1024 per contract, applied on append and again on snapshot load so the
bound holds against the disk too. The figures and the reasoning are in
`docs/design/CONTRACT_EVENT_COMMITMENT.md`.
**`DIV` and `MOD` are not size-charged.** `chargeArithmetic` is called for `ADD`, `SUB` and
`MUL` and not for `DIV` or `MOD` (`runtime/vm.ts:436-447`), so dividing two 4,096-bit integers
costs 1 gas. It is bounded — the operands cannot exceed the ceiling — but it is not proportional
to the work.
**`SUBU` is not size-charged** either, at a flat 3. Its result can only shrink, so this is
bounded, but a reimplementation must match the flat charge exactly.
**Identity-gate scanning is bounded per call, not per network.** `hasAllocationFor` walks every
allocation for a non-proved wallet at a measured 4.2 ns each. The per-call cache bounds the
repeat case; **the distinct case is not bounded**, and the cost grows with the size of the
registry. The fix is an index in the registry, which does not exist yet
(`src/core/contract-state.ts:212-229`).
**Deployment gas is unmeasured for post-mining**, and is left unmeasured rather than guessed
(`src/core/blockchain.ts:3825-3829`).
**Under-declared gas limits are absorbed silently by the network.** `minted = min(gasUsed,
gasLimit / 10)`, and a call that under-declares still succeeds — it just leaves an
`uncoveredMinor` nobody pays. There is no penalty and no alarm.
## The migration hazard from the storage-encoding change
Part III changed two encodings: `encodeMapKeyPart` (`runtime/bytecode.ts:299`), which names a
storage slot, and `encodeAresValue` (`src/core/contract-state.ts:1892`), which commits a stored
value and canonicalises a call argument.
**Printable ASCII is unchanged and therefore does not migrate.** `s::` is byte-identical
to what the old encoder produced for any string whose code units are all in `0x20..0x7e`, which
is every key and every value the shipped templates store, every address, every role name and
every ticker anyone has written. That is asserted directly at
`tests/integration/storage-commitment.integration.test.ts:37-41` and was the reason the fix took
this shape instead of hex-encoding everything.
**Anything outside printable ASCII does migrate, and there is no migration path.** A slot whose
name or whose value contains any code unit below `0x20` or above `0x7e` — a newline, a tab, an
accented character, an emoji, a surrogate — encoded as `s::` under the old rules and
encodes as `u::` under the new ones. Concretely, for such a slot:
- its **name** changes, so `glasirKey(name)` changes, so it is a **different leaf** in the
contract's storage tree — the old leaf is orphaned and the new one is empty until the slot is
rewritten;
- its **value commitment** changes, so the storage root changes even if the name did not;
- consequently the contract's `accountCommitment` changes, and the **contract state root
changes**;
- and `canonicalRecord` changes for any historical call carrying such an argument, so
`contractRecordsRootHex` changes for any block that carried one — which means the block's
`recordsRootHex` no longer verifies (`src/core/blockchain.ts:445`).
**Nothing is deployed, so the cost today is zero.** It would not be zero later. Any chain that
had already stored a non-ASCII map key or a non-ASCII string value before this change would fail
to validate from genesis after it, at the first block containing one, and there is no upgrade
routine anywhere in this tree that rewrites slots or re-derives roots. A network that reaches
that state has to hard-fork at a named height or re-genesis.
A reimplementation must therefore treat the printable-ASCII boundary as **normative and exact**:
`0x20 <= unit <= 0x7e` inclusive, tested per UTF-16 code unit, four lowercase hex digits per unit
otherwise, and the length prefix counted in code units and not bytes. An implementation that
used a different boundary — `isPrintable`, a Unicode category, ASCII including control
characters, or code points instead of code units — would produce different slot names for the
same contract and would fork from this one at the first non-ASCII write.
## Other sharp edges worth knowing
- **A jump target may be exactly one past the end**, and that is a normal return, not a fault.
A reimplementation that rejects it will refuse modules this compiler emits.
- **`POP`, `DUP`, `AND` and `OR` are in the instruction set and no compiler path emits them.**
A reimplementation must still execute all four, and the reason is **not** the one an earlier
version of this section gave. It said *a module compiled before 1.2.0 may contain them*; no
such module can reach a node here, because a deploy record carries SOURCE and every node
recompiles it with the current compiler, so the only bytecode that ever reaches a chain is
bytecode this compiler produced. The real reasons are recorded beside the opcode table as
`OPS_WITH_NO_COMPILER_PATH` (`runtime/bytecode.ts`) and checked by
`tests/integration/areslang-opcode-disposition.integration.test.ts`, which fails both if the
compiler starts emitting one and if the VM stops executing one: an opcode BYTE is part of the
container format forever (0x02, 0x03, 0x27, 0x28 can never be reassigned), `POP`/`DUP` are
stack shuffles an emitter that leaves exactly one value per expression has nothing to shuffle
for, and `AND`/`OR` pop two already-evaluated values and therefore cannot express the
short-circuiting `&&`/`||` of 1.2.0. **Dormant by design, not a missing language feature.**
- **Gas is a pure function of the instruction stream and the values on the stack.** Any change
to codegen moves the whole published gas table. `ARES_COMPILER_VERSION` is asserted in the
catalogue test (`tests/integration/template-catalogue.integration.test.ts:397`) precisely so
that a codegen change fails loudly rather than leaving every template header quoting numbers
that are no longer true.
- **`simulateCall` authenticates nothing.** It commits nothing either, but it will happily
execute as any caller and report the result, so it reveals what any address could do against
current state.
- **A revert still consumes the nonce.** The signature was valid and has been seen
(`src/core/contract-state.ts:816-817`).
- **A `view` that mutates is a thrown record, not a revert.** It refuses the whole record rather
than returning `success: false` (`src/core/contract-state.ts:811-813`).
- **A record that no block can carry is refused, not queued — and until `9220195` it was
queued.** `MAX_RECORD_BYTES` (`src/core/blockchain.ts:1789`) is 383,616 canonical bytes and
`assertRecordFitsABlock` (`src/core/blockchain.ts:1831`) sits at every `submit*` door.
Contract deploys and governance proposals are the record kinds this actually bounds, because
they are the ones with an unbounded field. **Before it existed the block bound was a wedge
rather than a cut-off**: an oversized record sat at the head of the queue being skipped on
every block forever, starving everything behind it and surviving a restart through
`chainSnapshot()`. Measured on this branch: a 420,653-byte deploy queued ahead of an ordinary
one gave **2 queued, 0 sealed** across five blocks. **§6.5.1.**
- **Two refusals a submitter must not confuse.** *"No block can carry it"* is permanent and the
message says waiting will not help; *"the contract record queue is full; try again after the
next block"* is the opposite answer, and it is raised a few lines away in the same method
(`src/core/blockchain.ts:1041-1043`). A client that retries on the first one retries forever.