MiniChain docs

MiniChain docs

A MiniChain is a small chain that lives entirely inside one Ethereum contract. You deposit ETH, deploy programs into it, call them, and withdraw.

Not externally auditedNot yet deployed to mainnet

What it is

One contract, MiniChain, holds a ledger of internal ETH balances, the code and storage of every program deployed into it, and two interpreters that run that code. The programs are called guests. A guest is not an Ethereum contract: it has no address on Ethereum, wallets and block explorers cannot see it, and it never runs as native bytecode. It exists only as data inside the MiniChain, which executes it step by step.

Ethereum
ETH in through deposit, or attached to transact, deploy and create
ETH out through withdraw or a relayed withdrawFor
One MiniChain contract (a 44-byte proxy with its own storage and ETH)
LedgerInternal ETH per address, nonces, and a running hash of every operation.
GuestsImmutable code and private storage for each deployed program.
Two interpretersMiniVM for purpose-written programs, and an EVM interpreter for Solidity bytecode.
Everything inside the solid frame is state of one contract. Ethereum supplies ordering and finality; there are no validators, sequencer or blocks of its own.
  • ETH is the only asset. Every internal wei is backed by a wei the contract holds. There is no separate token.
  • Two virtual machines. MiniVM is a compact 16-register instruction set. The EVM interpreter runs ordinary Solidity output; the published Uniswap V2 bytecode and a standard ERC-721 run in it unmodified.
  • Each chain has an owner. A MiniChain is an ERC-721 token in MiniChainRegistry. Its holder collects half of the chain's fees and may name it. The other half goes to the holder of MiniChain #1.
  • Nobody can pause or upgrade a chain. The fee rate and split are constants in the code. The holder of token 1 can replace the contract that mints new chains and the contract that draws the artwork, and nothing else.
  • A chain can be temporary. It may be launched with a public end date at least 30 days away. See End dates before you deposit into one.

What it is not

  • Not a way to make transactions cheaper. Every MiniChain transaction is an Ethereum transaction, and interpreting a guest costs more gas than running the same logic natively. See the numbers below.
  • Not a rollup or an L2. Nothing is batched off-chain or proven. There is no bridge, sequencer or validator set.
  • Not a complete EVM. The interpreter counts steps, not gas, and has fixed limits. See gaps and deviations.
  • Not a separate network. There is no MiniChain RPC, wallet network or transaction format. You call the contract on its host chain.
  • Not a state commitment. head is a hash chain of operations. It is not a Merkle root of balances or storage.
  • Not audited, and not on mainnet. The tests cover what is implemented. They are not a security audit. Nothing has been deployed to a network.

The honest trade-offs

A MiniChain gives a group of programs their own ledger, their own fee stream and an owner. It does not give them scale. These measurements come from the project's benchmark suite (Foundry gasleft() deltas with a zero base fee, not transaction receipts):

WorkloadNativeMiniVM programSolidity, interpreted
Counter, first add43,96195,233171,433
Counter, later add26,82678,136154,336
Token swap (Uniswap V2 Router02 against MiniUni)93,225143,665 to 160,8192,794,304
NFT mint (Solady ERC-721 against MiniNFT)73,029228,588255,802
Host gas. MiniUni and MiniNFT do far less than the contracts they are set beside, so those rows compare costs, not equivalent programs.

The project's own summary: an interpreter inside Ethereum does not create cheaper or additional execution capacity. It costs roughly four times native for a trivial call and 20 to 30 times for a call-heavy application such as a Uniswap swap. On top of the gas, each transaction pays the chain's owners a fee equal to a tenth of its gas cost at the base fee. See Fees.

Quick start

You need Foundry and Python 3. Run everything from the repository root. The first two steps need no wallet, RPC URL or ETH.

1. Build and run the tests

python3 tools/install_dependencies.py
forge build
forge test --offline -vv
python3 -m unittest discover -s tools -p 'test_*.py' -v

The installer reuses pinned dependencies if they are already in the folder and downloads them otherwise. The first build may download Solidity 0.8.26. The README records the baseline as 376 Solidity tests and 12 Python tests passing.

2. Run the whole flow in one script

forge script script/Demo.s.sol:Demo --offline

The script deposits 1 ETH, deploys a counter, adds 7, sends 0.25 internal ETH to a second account, and withdraws it as real ETH. It runs locally and broadcasts nothing. The output includes:

COUNTER_RESULT 7
ALICE_INTERNAL_ETH_WEI 750000000000000000
BOB_WITHDRAWN_ETH_WEI 250000000000000000
BACKING_ETH_WEI 750000000000000000
VIRTUAL_HISTORY_HEIGHT 5

The last three lines of the output show the chain's owner, the fee one transaction pays at a 10 gwei base fee, and the owner collecting it.

3. Start a local node and deploy

In one terminal:

anvil

In another, deploy a whole system: the renderer, the registry, the shared code, and MiniChain #1. The account that broadcasts receives token 1, or the address in OWNER if you set that variable.

export ETH_RPC_URL=http://127.0.0.1:8545
export PK=<one of the private keys anvil printed>
export ME=$(cast wallet address --private-key $PK)

forge script script/Deploy.s.sol:Deploy --rpc-url $ETH_RPC_URL --private-key $PK --broadcast

# The script prints RENDERER, REGISTRY, IMPLEMENTATION, MINTER, MINICHAIN_1, OWNER, GENESIS_EXPIRY.
export MINICHAIN=<the MINICHAIN_1 address>

Do not name the variable CHAIN. cast reads an environment variable of that name as its own --chain option and rejects the address.

To give MiniChain #1 an end date, set GENESIS_EXPIRY to a Unix time at least 30 days away before running the script. Unset, it never ends.

4. Deposit

cast send $MINICHAIN "deposit(address)" $ME --value 1ether --private-key $PK
cast call $MINICHAIN "balances(address)(uint256)" $ME      # 1000000000000000000

5. Deploy a program

examples/counter.hex is the assembled 20-byte counter. deploy returns the guest's address, which cast send does not show, so simulate the call first to learn it. The simulation uses your current nonce, so it predicts the address the real call will produce.

CODE=$(cat examples/counter.hex)
SALT=$(cast hash-zero)

COUNTER=$(cast call $MINICHAIN "deploy(uint8,bytes,bytes32)(address)" 1 $CODE $SALT --from $ME)
cast send $MINICHAIN "deploy(uint8,bytes,bytes32)" 1 $CODE $SALT --private-key $PK
cast call $MINICHAIN "vmKind(address)(uint8)" $COUNTER       # 1, a MiniVM program

6. Call it

The counter adds the first word of its input to storage slot 0. Give it a budget of 1,000 steps; it uses 5.

cast send $MINICHAIN "transact(address,uint256,bytes,uint256)" \
  $COUNTER 0 $(cast abi-encode "f(uint256)" 7) 1000 --private-key $PK

cast call $MINICHAIN "storageAt(address,uint256)(uint256)" $COUNTER 0   # 7

The counter writes storage on every call, so it cannot be called through the read-only read: that reverts with StaticViolation. Read its slot with storageAt instead. For a guest with a real view function, see read.

7. Withdraw

cast send $MINICHAIN "withdraw(uint256,address)" 0.25ether $ME --private-key $PK

cast call $MINICHAIN "balances(address)(uint256)" $ME    # a little under 0.75 ether
cast call $MINICHAIN "height()(uint64)"                  # 4: deposit, deploy, transaction, withdraw
cast call $MINICHAIN "feesAccrued()(uint256)"            # what steps 5 and 6 paid the owners

Your balance is slightly below 0.75 ether because anvil has a base fee, so the deployment and the call each paid a fee in internal ETH. The deposit and the withdrawal are free of it.

Concepts

Internal ETH and backing

deposit(beneficiary) holds the ETH you send and credits exactly that many internal wei to beneficiary. From then on it moves inside the ledger: between accounts, into and out of guests, and to the owners as fees. withdraw burns internal wei and releases the same amount of real ETH.

The invariant is that all internal balances, uncollected fees included, sum to totalDeposits, and the contract's real ETH is at least that amount. A fee is a transfer inside the ledger, so it does not change the backing. Two things sit outside the invariant:

  • ETH forced into the contract without a deposit is not credited to anyone and cannot be withdrawn.
  • A chain created with an end date can be swept once that date has passed, which sends all of its ETH to the owner whatever the internal balances say, after the owner of MiniChain #1 has been paid its half of any unclaimed fees.

Accounts

Your account inside a MiniChain is your Ethereum address. There is no registration: an address has a balance once something is deposited or sent to it, and it acts by calling the contract or by signing a request that someone else relays. A guest's address is an account too, with a balance, but it can never sign or call the contract's entry points. An address that holds guest code is rejected as a sender with VirtualAccountCannotSign.

Guests

A guest is code plus private storage, stored inside the MiniChain under a virtual address. Its code is immutable. A guest can:

  • read and write its own storage, and nobody else's;
  • hold internal ETH and send it to any account;
  • call other guests, of either kind;
  • emit logs, which leave the contract as VirtualLog events.

A guest cannot mint ETH, write the contract's own storage, withdraw to Ethereum, or change anything on the host chain. The only host calls a guest can cause are the contract's calls to itself, calls to the host's pure precompiles, and, for Solidity guests, read-only calls to host contracts. A guest that is badly written or deliberately locked can strand its own balance; nothing can recover it.

The two virtual machines

MiniVMEVM interpreter
Kind1 (MINI_VM)2 (EVM_VM)
Code16-register instruction set written in MiniVM assemblySolidity compiler output for Cancun
Installed withdeploy(1, code, salt). Every instruction is validated first.create(initCode, …) to run a constructor, or deploy(2, runtime, salt) to upload finished runtime code
Input and outputRaw calldata, read a word at a time. Returns one 32-byte word.Ordinary ABI calldata and return data
Calls to othersOne input word, one return word. A failed child fails the caller.CALL, STATICCALL, DELEGATECALL, CALLCODE; a failed child can be caught
Reads the host chainNoYes, through HOST_GATEWAY
Cost of a counter add78,136 gas154,336 gas

The two can call each other. An EVM guest may CALL or DELEGATECALL a MiniVM program, and a MiniVM program may call an EVM guest with its one-word input.

Adding your own VM

A chain's owner can launch it with up to eight VMs of their own choosing, called engines, besides the two built in. Each is a contract on Ethereum. They become kinds 3 upwards, in the order given, and the list can never be changed afterwards: launch(id, expiry, engines) is the only moment. A guest is deployed to one with deploy(kind, code, salt), and guests of every VM can call each other.

Sandboxed engineTrusted engine
How the chain runs itAn ordinary call. The engine asks the chain to store, pay and log for the guest it is running.DELEGATECALL, as the built-in EVM interpreter is run. The engine reads and writes the chain's storage directly.
What it can touchThe storage and balance of its own guests, and nothing elseEverything: any balance, any guest, the fees and the end date
AllowedAlwaysOnly while trustedEnginesAllowed is on in the registry. It is off unless the owner of token 1 turns it on.
What the chain says about itselfhasTrustedEngine() is false, and the token's Engines attribute is SandboxedhasTrustedEngine() is true for good, and the attribute is Trusted

Check a chain's engines before depositing. A chain with a trusted engine is only as safe as that engine's code: it can move anyone's balance. And on any chain, the guests of an added VM are only as safe as their engine, which decides what their code means. Guests of MiniVM and the EVM, your own balance, the fees and the end date are out of a sandboxed engine's reach.

Writing a sandboxed engine

An engine implements one function. The chain calls it with the frame to run, the guest's stored code and a step budget, and it returns whether the guest succeeded, the steps it used and the return data. examples/CounterEngine.sol is a complete one in about twenty lines.

interface ISandboxEngine {
    function run(ChainState.Frame calldata frame, bytes calldata code, uint256 budget)
        external
        returns (bool ok, uint256 used, bytes memory result);
}

An engine keeps no guest state of its own. While it runs a guest it calls these on the chain that called it:

Function on the chainWhat it does
storageAt(account, slot), balances(account)Read any storage slot or balance. These are the ordinary public views.
sandboxStore(slot, value)Write a storage slot of the guest now running
sandboxTransfer(to, amount)Send internal ETH from the guest now running
sandboxLog(topics, data)Emit a VirtualLog from the guest now running, with up to four topics
sandboxCall(target, value, data, budget)Call another account, which sees the guest as its caller. Returns (ok, used, result); a failed call is undone and the caller carries on. budget is cut to the steps the guest has left, and the chain charges the guest at least what its calls used, whatever the engine reports.
sandboxStaticCall(frame, target, data, budget)The same without letting the target change anything. frame is the frame the engine was given.
  • Only the running guest. The four writing functions take no account: they act on whichever guest the chain is running at that moment, and fail with NotEngine for any caller but that guest's engine. An engine cannot use them when nothing of its own is running.
  • Static frames. When frame.isStatic is set the chain calls the engine with STATICCALL, so Ethereum itself refuses every write. Only reads and sandboxStaticCall work there. This is what keeps read and an EVM guest's STATICCALL read-only whatever the engine does.
  • Failures. To report a guest's revert, return ok false: the chain undoes everything that call did. If the engine itself reverts with a reason, a chain function it called refused (not enough balance, say), or it returns something that is not the three values, the guest has failed in the same way and has used its whole budget: a calling guest sees a failed call and carries on. Only a revert with no data, which is what running out of host gas looks like, fails the whole transaction with HostCallFailed.
  • Steps. The engine counts its own steps, adding what each nested call reports. Reporting more than the budget fails the transaction with StepLimit. The count is the engine's word: Ethereum gas, not steps, is what bounds an engine's work.
  • No borrowed code. A sandboxed guest runs only as itself. An EVM guest's DELEGATECALL to one fails.
  • No stipend. A call that sends value gets the budget it is given and nothing more.

Writing a trusted engine

A trusted engine inherits ChainState, so its storage layout matches the chain's, and implements ITrustedEngine.run(frame, code, mode, budget), the same function the EVM interpreter has. It makes nested calls through the chain's own guestCall. Nothing limits it, which is why the registry refuses it by default.

Steps versus gas

Every virtual transaction carries a step budget, maxSteps. One instruction of either VM costs one step, whatever it does, and all nested calls share the one budget. A transaction that runs out fails with StepLimit. The budget must be between 1 and MAX_STEPS (1,000,000).

Steps are not gas. They bound how much interpreting a transaction may do; they do not price it. What you pay for is the host gas the interpreter burns, which varies widely per step: a storage write or a memory copy costs far more gas than an addition. The host gas limit remains the real ceiling and can be reached before the step budget is.

TransactionStepsHost gas
MiniUni buy, repeat buyer31143,665
MiniUni sell39156,633
Solidity guest returning its caller83170,803
Uniswap V2 token-to-token swap4,1562,794,304

Inside an EVM guest, the GAS opcode returns the remaining step budget and GASLIMIT returns 1,000,000. A value transfer grants the recipient a stipend of 2,300 steps (CALL_STIPEND), under which it may log, read and make zero-value calls but not write storage, move value or create, so Solidity's transfer and send behave as contracts expect. A call that sends value with a gas operand of 2,300 or less runs on the stipend alone. Such a frame also has a fixed host gas allowance of 500,000 (STIPEND_HOST_GAS), so a recipient cannot spend the sender's host gas.

Blocks, head and height

A MiniChain has no blocks of its own in the usual sense. Instead, every successful operation commits one entry to a hash chain: height goes up by one, and head becomes the hash of the previous head, the new height and a hash describing the operation. The indexer and explorer call each entry a block.

Each commit emits BlockCommitted(number, previousHash, blockHash, operationHash).
OperationWhat its operationHash is the keccak256(abi.encode(…)) of
Deposit"deposit", payer, beneficiary, amount
Withdrawal"withdraw", account, recipient, amount
Deployment"deploy", creator, nonce, account, kind, keccak256(runtimeCode)
Creation"create", from, nonce, account, value, maxSteps, keccak256(initCode)
Transaction"transaction", from, to, value, nonce, maxSteps, keccak256(data), keccak256(result)
Fee claim"claim", chainOwner, genesisOwner, amount

Three consequences are worth knowing:

  • One Ethereum transaction can commit more than one block. ETH attached to transact, deploy or create is deposited first, which is its own block, and each successful item of a batch is one more.
  • A call that only reads still commits a block if it is sent through transact. Use read for views.
  • head commits to the history of operations, not to state. You cannot prove a balance against it.

A failed operation commits nothing. The whole call is undone: balances, storage, events, history and the nonce. The caller still pays Ethereum for the gas.

Nonces

Each account has one nonce, readable as nonces(address), starting at zero. Deployments, creations, transactions and relayed withdrawals all consume the same sequence.

  • Direct calls (transact, deploy, create) take the next nonce themselves. You do not pass one.
  • Signed requests (execute, executeBatch, withdrawFor) must carry the signer's current nonce, or they fail with InvalidNonce.
  • A direct withdraw and a deposit use no nonce.
  • A failed operation uses no nonce, so a signed transaction that failed stays valid and can be submitted again until its deadline.
  • A guest's nonce starts at one, as on Ethereum, and counts the contracts it creates.

Addresses of guests

The address of a guest depends on how it is created.

Created byAddress
deploy, create, or a signed creationLow 160 bits of keccak256(abi.encode(miniChain, block.chainid, creator, nonce, salt)). A signed creation uses a zero salt.
A guest's CREATEEthereum's formula on the virtual creator: keccak256(rlp([creator, nonce]))
A guest's CREATE2Ethereum's formula: keccak256(0xff ++ creator ++ salt ++ keccak256(initCode))

Because the address is predictable, it can be funded before the code exists, and the balance is kept when the code is installed. Funding a future address gives the funder no rights over it. An address that already has code, or whose nonce has been used, cannot be deployed to: that fails with AddressOccupied.

Using a chain

Everything below is a function of the MiniChain contract, called on its host chain. Signatures are copied from src/MiniChain.sol and src/ChainState.sol. Every function that changes state fails with ChainExpired once a chain has reached its end date, and with Reentrancy if entered again from inside itself.

Moving ETH in and out

deposit(address beneficiary) external payable

Holds msg.value as backing and credits that many internal wei to beneficiary, which may be any address, including a guest or an address where a guest will later be deployed.

Who may call
Anyone, for any beneficiary.
Fee
None.
Emits
Deposited(payer, beneficiary, amount), BlockCommitted
Fails with
InvalidAddress if the beneficiary is the zero address or the MiniChain itself; ZeroAmount if no ETH is attached.

withdraw(uint256 amount, address payable recipient) external

Burns amount of the caller's internal ETH and sends the same amount of real ETH to recipient. Guests cannot withdraw; they pay users internally, and the users withdraw.

Who may call
The account that holds the balance.
Fee
None. It uses no nonce.
Emits
Withdrawn(account, recipient, amount), BlockCommitted
Fails with
InvalidAddress if the recipient is the zero address or the MiniChain; ZeroAmount; InsufficientBalance; VirtualAccountCannotSign if the caller's address holds guest code; ETHTransferFailed if the recipient rejects the ETH.

withdrawFor(Withdrawal request, bytes signature) external

Relays a signed withdrawal, so an account that was funded by someone else and holds no ETH on the host chain can still leave. The amount and the recipient are part of what is signed. The relayer pays the gas and is not reimbursed.

struct Withdrawal {
    address from;
    address payable recipient;
    uint256 amount;
    uint256 nonce;
    uint256 deadline;
}
Who may call
Anyone holding a valid signature from request.from.
Fee
None. It consumes the signer's next nonce, the same sequence as execute.
Emits
Withdrawn, BlockCommitted
Fails with
Expired if block.timestamp is past the deadline; InvalidNonce; InvalidSignature; then everything withdraw can fail with.

withdrawalHash(Withdrawal request) returns the EIP-712 digest to sign. The benchmark measured a relayed withdrawal at 128,735 gas for the relayer.

Deploying guests

deploy(uint8 kind, bytes runtimeCode, bytes32 salt) external payable returns (address account)

Installs finished code at a new virtual address. kind is 1 for a MiniVM program, which is validated instruction by instruction, 2 for EVM runtime bytecode, which is stored as it is, or 3 upwards for a VM the chain was launched with, whose code is also stored as it is. No constructor runs. Any ETH attached is deposited to the caller first.

Who may call
Any account that is not itself a guest.
Fee
Yes, with no cap.
Emits
ContractDeployed(creator, account, kind, codeHash), BlockCommitted, then VirtualTransfer for the fee. Deposited and a block of its own first if ETH was attached.
Fails with
InvalidVM for any other kind; CodeTooLarge if the code is empty or over 24,575 bytes; InvalidCode(pc) or InvalidOpcode(pc, opcode) for a malformed MiniVM program; AddressOccupied; InsufficientBalance if the caller cannot cover the fee.

deployAndCall(uint8 kind, bytes runtimeCode, bytes32 salt, uint256 value, bytes data, uint256 maxSteps) external payable returns (address account, bytes result)

Does what deploy does and then what transact does to the new account, as one Ethereum transaction with one fee. Use it for a program whose first caller gains something, such as MiniUni's seeder or MiniNFT's creator: deployed on its own, such a program can be called by anyone before its deployer. If the call fails, nothing is deployed.

Who may call
Any account that is not itself a guest.
Fee
Yes, with no cap.
Emits
What deploy emits, then what transact emits, and one VirtualTransfer for the fee. It commits two blocks and uses two of the caller's nonces.
Fails with
Anything deploy or transact fails with.

create(bytes initCode, bytes32 salt, uint256 value, uint256 maxSteps) external payable returns (address account)

Runs EVM creation code, so a Solidity constructor executes with the caller as msg.sender, and installs the runtime it returns, immutables included. Append ABI-encoded constructor arguments to the creation code as usual. value internal wei is sent to the new contract.

Who may call
Any account that is not itself a guest.
Fee
Yes, with no cap.
Emits
ContractDeployed, any logs the constructor emits as VirtualLog, BlockCommitted, VirtualTransfer for value and fee.
Fails with
InvalidStepBudget; CodeTooLarge if the creation code is empty or over 49,152 bytes; DataTooLarge if the constructor returns more than 24,575 bytes of runtime; GuestReverted(data) if the constructor reverts; InvalidCode(0) if the runtime starts with 0xEF; AddressOccupied; InsufficientBalance.

Transacting

transact(address target, uint256 value, bytes data, uint256 maxSteps) external payable returns (bytes result)

Submits a virtual transaction from the caller's own account: sends value internal wei to target and, if it has code, runs it with data. Any ETH attached is deposited to the caller first, so a new user can fund and transact in one call. A plain transfer to an account without code uses empty data.

Who may call
Any account that is not itself a guest.
Fee
Yes, with no cap. Use execute with your own account and an empty signature if you want a maxFee.
Emits
VirtualTransfer for each movement of internal ETH, VirtualLog for guest logs, TransactionExecuted(from, to, nonce, steps, result), BlockCommitted, then VirtualTransfer for the fee.
Fails with
InvalidStepBudget if maxSteps is zero or over 1,000,000; DataTooLarge over 4,096 bytes; InvalidAddress if the target is the zero address or the MiniChain; InsufficientBalance; NoContract if data is sent to an account without code; GuestReverted(data) carrying the guest's own revert bytes; StepLimit; and the other execution errors.

read(address target, bytes data, uint256 maxSteps) external returns (bytes result)

Calls a guest without a transaction and returns what it returns. The guest runs in a static frame: it can read, and any write, log or transfer of value fails. Nothing is committed and no fee is charged. The guest sees the host caller as msg.sender.

It is not declared view, because it reaches the EVM engine by DELEGATECALL, but it writes nothing, so it works with eth_call from a front end and with STATICCALL from a host contract (through the IMiniChainReader interface). It keeps working after a chain's end date.

# Who owns token 1 of a MiniNFT collection?
cast call $MINICHAIN "read(address,bytes,uint256)(bytes)" \
  $NFT $(cast abi-encode "f(uint256)" 1) 1000
Who may call
Anyone.
Fails with
InvalidStepBudget; GuestReverted(data); StaticViolation if the guest tries to write; Reentrancy while the chain is executing a transaction, so a guest cannot read its own chain's unfinished state.

Calling transact through eth_call is different: that simulates a state-changing call and needs a valid from.

Signed transactions

A transaction can be signed off-chain and submitted by anyone. The signer is the virtual sender; the Ethereum msg.sender is only the relayer. The relayer pays the host gas and is not reimbursed; the signer pays the chain's fee, up to the maxFee they signed. Relaying is meant for a sponsor, such as an app covering its users' gas, or for a user batching their own transactions. Nothing here makes relaying for strangers break even.

struct Transaction {
    address from;
    address to;
    uint256 value;
    uint256 nonce;
    uint256 deadline;
    uint256 maxSteps;
    uint256 maxFee;   // the most internal wei the signer will pay in fees for this transaction
    bytes data;
}

execute(Transaction txn, bytes signature) external returns (bytes result)

Runs one signed transaction. If txn.to is the zero address it is a contract creation, as on Ethereum: data is the creation code, the salt is zero, and the result is the ABI-encoded new address.

Who may call
Anyone with a valid signature. The account txn.from may call it for itself with an empty signature.
Signature
EIP-712, from an EOA or an ERC-1271 wallet contract on the host chain. Guests cannot sign.
Fee
Yes, paid by txn.from, capped by txn.maxFee.
Emits
As transact or create.
Fails with
Expired past the deadline; InvalidNonce; InvalidSignature; FeeTooHigh if the fee would exceed maxFee; VirtualAccountCannotSign; then everything transact or create can fail with.

The EIP-712 types

The domain is name: "MiniChain", version: "1", the host chainId, and verifyingContract set to the MiniChain's address, so a signature is valid on one MiniChain on one host chain only. transactionHash(txn) and withdrawalHash(request) return the full digests; they are not personal-message hashes.

Transaction(address from,address to,uint256 value,uint256 nonce,uint256 deadline,uint256 maxSteps,uint256 maxFee,bytes data)

Withdrawal(address from,address recipient,uint256 amount,uint256 nonce,uint256 deadline)

Signing and relaying a counter call with cast, where $PK is the signer's key and $RELAYER_PK the relayer's:

NONCE=$(cast call $MINICHAIN "nonces(address)(uint256)" $ME)
DATA=$(cast abi-encode "f(uint256)" 5)

cat > tx.json <<EOF
{
  "types": {
    "EIP712Domain": [
      {"name": "name", "type": "string"},
      {"name": "version", "type": "string"},
      {"name": "chainId", "type": "uint256"},
      {"name": "verifyingContract", "type": "address"}
    ],
    "Transaction": [
      {"name": "from", "type": "address"},
      {"name": "to", "type": "address"},
      {"name": "value", "type": "uint256"},
      {"name": "nonce", "type": "uint256"},
      {"name": "deadline", "type": "uint256"},
      {"name": "maxSteps", "type": "uint256"},
      {"name": "maxFee", "type": "uint256"},
      {"name": "data", "type": "bytes"}
    ]
  },
  "primaryType": "Transaction",
  "domain": {"name": "MiniChain", "version": "1", "chainId": $(cast chain-id), "verifyingContract": "$MINICHAIN"},
  "message": {"from": "$ME", "to": "$COUNTER", "value": "0", "nonce": "$NONCE", "deadline": "1900000000",
              "maxSteps": "1000", "maxFee": "1000000000000000", "data": "$DATA"}
}
EOF

SIG=$(cast wallet sign --private-key $PK --data --from-file tx.json)

cast send $MINICHAIN \
  "execute((address,address,uint256,uint256,uint256,uint256,uint256,bytes),bytes)" \
  "($ME,$COUNTER,0,$NONCE,1900000000,1000,1000000000000000,$DATA)" $SIG \
  --private-key $RELAYER_PK

A relayed withdrawal is the same with the Withdrawal type (from, recipient, amount, nonce, deadline) and withdrawFor((address,address,uint256,uint256,uint256),bytes).

Batches

executeBatch(Transaction[] txns, bytes[] signatures) external returns (BatchResult[] results)

Runs several signed transactions in one Ethereum transaction, in order. Each behaves exactly as it would through execute, but runs in its own self-call, so one that fails for any reason (signature, nonce, deadline, guest revert, fee) is undone alone and the rest still run.

struct BatchResult {
    bool success;
    bytes result;   // the return data, or the error it failed with
}
Who may call
Anyone. The caller may leave the signature empty for transactions sent from its own account, and one signer may queue consecutive nonces.
Fee
Each successful transaction pays its own, with a smaller overhead allowance. A failed one pays nothing and uses no nonce, so it can be submitted again.
Emits
For each failure, TransactionFailed(from, nonce, index, reason). For each success, what execute emits.
Fails with
LengthMismatch if the two arrays differ in length. Failures of single transactions do not fail the batch. An empty batch returns an empty array.

Batching saves the 21,000 intrinsic gas on every transaction after the first, plus storage and code that stay warm between them. Three interpreted counter calls measured 605,784 gas relayed separately and 494,267 batched, 18% less. Signers pay less too, because their fee follows the gas.

Reading state

FunctionReturns
balances(address)Internal ETH of an account or guest, in wei
nonces(address)The account's next nonce
vmKind(address)0 for no code, 1 MiniVM, 2 EVM
codeAt(address)A guest's code
storageAt(address, uint256)One storage slot of a guest. This is the ground truth for any guest's state.
totalDeposits()The sum of all internal balances
height()Number of operations committed (uint64)
head()The current hash of the operation history
expiry()The end date as a Unix time, or zero if the chain never ends (uint64)
owner()Whoever holds this chain's token in the registry
feesAccrued()Fees collected and not yet claimed
feesClaimed()All fees ever claimed
totalFees()All fees ever collected, claimed or not
registry()The MiniChainRegistry that created this chain
engine()The EVM interpreter contract every MiniChain delegates to
transactionHash(Transaction)The EIP-712 digest of a transaction
withdrawalHash(Withdrawal)The EIP-712 digest of a withdrawal request

Functions you cannot call

Four external functions exist for the system's own use. batchItem and guestCall can be called only by the MiniChain itself and otherwise fail with OnlySelf. initialize(uint64) and sweep(address payable) can be called only by the registry and otherwise fail with OnlyRegistry. claimFees is covered under Fees.

Fees

transact, execute, executeBatch, create and deploy charge the virtual sender a fee in internal ETH. Deposits, withdrawals and fee claims are free. A transaction that reverts pays no fee, because the whole call is undone.

The formula

fee = (host gas measured + FEE_OVERHEAD_GAS) × block.basefee / FEE_DIVISOR
    = (host gas measured + 37,700) × block.basefee / 10

That is a tenth of what the transaction costs in host gas, priced at the base fee so that tips do not change it. The contract measures gas from the start of the call to the moment it charges the fee. The 37,700 stands in for what it cannot measure from inside: the 21,000 intrinsic gas of the Ethereum transaction, the proxy's hop to the shared code, the reentrancy lock, and the fee's own bookkeeping. It is set slightly low on purpose. In the cases the project measured, the fee came to between 88% and 100% of a tenth of the real gas cost, and never above it. Calldata gas is not counted. A host transaction pays its intrinsic gas once, so when a contract uses a MiniChain several times in one host transaction, only the first use carries the 37,700 and each later one carries 10,000.

  • Who pays. The virtual sender: the caller of transact, deploy or create, or the signer of a relayed transaction. A sender who cannot cover the fee reverts the transaction with InsufficientBalance.
  • Cap. Only signed transactions carry a maxFee. Exceeding it fails with FeeTooHigh.
  • Zero base fee. Where block.basefee is zero nothing is charged.
  • What charging costs. About 12,000 host gas per transaction, and about 17,000 more for the first fee a chain collects and the first after each claim, because the fee balance starts from zero.
  • What guests see. Nothing. The fee is charged after the guest finishes and shows only as the sender's lower balance. GASPRICE and BASEFEE read zero inside a guest.

Overhead constants

ConstantValueMeaning
FEE_DIVISOR10The fee is the gas cost at the base fee divided by this
FEE_SHARE_DIVISOR2The owner of MiniChain #1 receives the fees divided by this
FEE_OVERHEAD_GAS37,700Gas added for a single transaction
BATCH_ITEM_OVERHEAD_GAS10,000Gas added for each transaction in a batch: the bookkeeping alone
BATCH_SHARED_GAS23,700What a batch costs once (intrinsic gas and the proxy's hop), divided equally among its transactions

Inside a batch of n transactions the allowance is 10,000 + 23,700 / n in place of 37,700. For one transaction that is 33,700, a little less than execute allows. Across batches of 1 to 40 transactions the project measured total fees between 88% and 98% of a tenth of the batch's gas cost, furthest below for a batch of one, where execute is the better choice anyway.

Work out a fee
Gas the fee is charged on
Fee, in internal ETH
To the chain's owner
To the owner of MiniChain #1

The defaults are the benchmark's MiniVM counter add at a 20 gwei base fee: 85,610 gas charged, against 89,169 gas for the whole transaction, a fee of 9.6% of its gas cost.

The 50/50 split and claiming

Fees accumulate as the internal balance of the MiniChain's own address, which no account or guest can pay into or spend. Each fee appears as a VirtualTransfer from the payer to that address.

claimFees() external returns (uint256 amount)

Pays out everything accrued, as internal ETH on this chain: amount / 2 to the owner of MiniChain #1 and the rest to this chain's owner, so an odd wei goes to the chain's owner. Each then withdraws like any other account.

Who may call
Anyone, so neither owner depends on the other.
Emits
Two VirtualTransfer events from the MiniChain's address, then BlockCommitted.
Fails with
ZeroAmount if nothing has accrued; ChainExpired after the end date, when unclaimed fees can only leave through sweep.

The benchmark measured one claim at 104,281 gas.

  • The recipients are whoever holds the two tokens when the fees are claimed. Unclaimed fees are therefore sold with a token.
  • On MiniChain #1 both halves go to the same owner.
  • Once MiniChain #1 has reached an end date of its own, every other chain's owner receives the whole fee. See the special case.
  • The rate and the split are constants in the shared code. Nobody can change them for existing or future chains of a registry.

What the fee is, and what Ethereum burns

A MiniChain transaction pays twice, to two different places.

To Ethereum, in real ETH. The gas of the Ethereum transaction, paid by whoever submits it. The base fee part is burned by Ethereum and the tip goes to the block proposer, as for any transaction. To the chain's owner, in internal ETH. Half of the MiniChain fee: about a twentieth of the burned amount. To the owner of MiniChain #1, in internal ETH. The other half.
Drawn to scale for a fee of exactly a tenth. Tips are not shown.

The MiniChain fee is not burned and does not replace anything. It is an extra tenth on top of the gas, and it goes to the two owners. What is burned is Ethereum's own base fee, on the full gas of every MiniChain transaction. A rollup batches its users' transactions so that each pays Ethereum very little; a MiniChain does the opposite, since each of its transactions is a whole Ethereum transaction that costs more gas than its native equivalent.

The fee follows the host's base fee. On a chain with a very low base fee it is close to nothing, and an L2's separate data fee is not included in it. On a host chain that pays the base fee to its operator instead of burning it, the operator could generate fees cheaply, which matters for minting.

Writing MiniVM programs

MiniVM is a small register machine with its own assembly language. A program has 16 unsigned 256-bit registers, r0 to r15, which start at zero on every call; its own storage; and instructions for arithmetic, comparison, bit operations, hashing, internal ETH transfers, logs, jumps and calls to other guests. It is deliberately not the EVM, and it is not ABI-compatible with Solidity contracts.

The complete counter, 20 bytes:

# Add the first calldata word to storage slot zero, then return the total.
# r0 starts at zero and is used as both the slot and calldata offset.
CALLDATALOAD r1, r0
SLOAD r2, r0
ADD r2, r2, r1
SSTORE r0, r2
RETURN r2

Encoding

Every instruction starts with four bytes: the opcode and three operand bytes, A, B and C. Reserved bytes must be zero.

InstructionBytesLayout
CONST36Four bytes, then a 32-byte big-endian literal
CALL, LOG3, LOG48Four bytes, then a fourth register and three zero bytes
JUMP, JUMPI4B and C hold an absolute byte offset, which must be the start of an instruction
Everything else4Opcode, A, B, C

deploy validates every opcode, register, reserved byte and jump target before installing a program, and rejects a bad one with InvalidCode(pc) or InvalidOpcode(pc, opcode). Running off the end of the code is a successful empty return.

The instruction set

OpcodeAssemblyWhat it does
00STOPReturn empty bytes
01CONST A, valueA = the following 32-byte literal
02MOV A, BA = B
03ADD A, B, CA = B + C, wrapping modulo 2256
04SUB A, B, CA = B − C, wrapping
05MUL A, B, CA = B × C, wrapping
06DIV A, B, CA = B / C, or 0 if C is 0
07EQ A, B, CA = 1 if B equals C, otherwise 0
08LT A, B, CA = 1 if B is less than C, otherwise 0
09AND A, B, CBitwise AND
0aOR A, B, CBitwise OR
0bXOR A, B, CBitwise XOR
0cNOT A, BBitwise NOT
0dSHL A, B, CA = B shifted left by C; 0 for shifts of 256 or more
0eSHR A, B, CA = B shifted right by C; 0 for shifts of 256 or more
10CALLER AThe virtual caller's address
11ADDRESS AThis program's own virtual address
12CALLVALUE AInternal ETH sent with this call
13CALLDATALOAD A, BRead 32 bytes of input at offset B, zero-padded past the end
14CALLDATASIZE ALength of the input in bytes
15BALANCE A, BInternal ETH of address B (its low 160 bits)
16SLOAD A, BA = this program's storage at slot B
17SSTORE A, BThis program's storage at slot A = B
18TRANSFER A, BMove B internal wei from this program to address A, without running the recipient's code
19REQUIRE ARevert with no data if A is 0
1aRETURN AReturn A as one 32-byte word
1bREVERT ARevert with A as one 32-byte word of data
20JUMP labelJump to the label. A must be 0.
21JUMPI A, labelJump if A is not 0
22CALL A, B, C, DCall address B with C internal wei and D as its one input word; A receives the first word returned
23HASH A, B, CA = keccak256(abi.encode(B, C))
24LOG3 A, B, C, DEmit a log with topics A, B, C and D as one 32-byte data word
25LOG4 A, B, C, DEmit a log with topics A, B, C, D and no data
  • Reverts. A top-level REQUIRE or REVERT fails the transaction with GuestReverted(data). A failed CALL fails the calling program too; MiniVM has no way to catch it. An EVM guest further up that made the call with CALL or STATICCALL can.
  • Calls. CALL passes exactly one 32-byte word and reads one back. The target sees the calling program as CALLER, not the original sender. Depth is limited to 8 below the root.
  • Logs. Both forms leave the contract as VirtualLog(account, topics, data). LOG3 can express an ERC-20 Transfer and LOG4 an ERC-721 Transfer, which is how the indexer sees MiniVM tokens.
  • Read-only frames. Inside read or an EVM STATICCALL, SSTORE, the logs, and any TRANSFER or CALL carrying value fail with StaticViolation. On a value-transfer stipend the same applies except that logs are allowed.
  • Input. CALLDATALOAD zero-pads short data, so a program should check CALLDATASIZE itself where truncation would be unsafe.

The assembler

tools/mini_asm.py is a dependency-free Python script that assembles and disassembles. It is an assembler, not a compiler: there are no macros, imports, variables or optimisations.

python3 tools/mini_asm.py examples/counter.mini                              # print 0x-prefixed hex
python3 tools/mini_asm.py examples/counter.mini --output examples/counter.hex
python3 tools/mini_asm.py --disassemble examples/counter.hex
python3 -m unittest discover -s tools -v
  • Opcodes and registers are case-insensitive. Commas between operands are optional.
  • Constants are decimal or 0x hexadecimal, from 0 to 2256 − 1.
  • Comments start with #, ; or //.
  • Labels are case-sensitive identifiers that begin with a letter or underscore, followed by a colon. A jump must land on an instruction start; a literal, an extension or the end of the program is rejected.
  • The assembler refuses programs over 8,192 bytes, a tighter limit than the chain's 24,575.
  • Disassembly is lossless for valid programs; generated labels such as L0024 name absolute byte offsets.
    CONST r1, 5
    CONST r2, 1
again:
    SUB r1, r1, r2
    JUMPI r1, again
    RETURN r1

After editing an example, regenerate its .hex file and update the matching bytecode in examples/ExamplePrograms.sol; the Python tests check that the three agree.

Walk through MiniUni

examples/miniuni.mini is a constant-product pool on Uniswap V2's curve in one 712-byte program. It trades internal ETH against a single token, and that token has no program of its own: its balances are slots in the pool's storage. Whoever seeds the pool gives the token its name and ticker, which cannot be changed afterwards.

Storage slotHolds
0The token reserve held by the pool
1The seeder, who earns the fee
2The token's name: up to 32 bytes of text, padded with zeros
3The token's ticker, likewise
An address, as a numberThe tokens owned by that address

Calling convention

CallETH sentInputReturns
Seed (the first call)Requiredabi.encode(bytes32 name, bytes32 ticker), neither emptyThe supply created: 1,000,000 tokens with 18 decimals
BuyThe ETH to spendabi.encode(uint256 minTokensOut)Tokens received
SellNoneabi.encode(uint256 tokensIn, uint256 minEthOut)ETH received
ReadNoneabi.encode(uint256 slot)That storage slot: 2 is the name, 3 the ticker, an address its balance. Changes nothing

The program opens by loading the token reserve and the ETH sent, and branches on whether the pool has been seeded:

    SLOAD r4, r0            # token reserve
    CALLVALUE r1            # ETH sent with this call
    JUMPI r4, trade
    REQUIRE r1              # seeding needs ETH
    CALLDATALOAD r6, r0     # the token's name
    REQUIRE r6
    CONST r7, 32
    CALLDATALOAD r8, r7     # and its ticker
    REQUIRE r8
    CONST r3, 2
    SSTORE r3, r6
    CONST r3, 3
    SSTORE r3, r8
    CONST r4, 1000000000000000000000000
    SSTORE r0, r4
    CONST r3, 1
    CALLER r5
    SSTORE r3, r5           # the seeder earns the fee from now on
    ADDRESS r2
    CONST r7, 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef
    LOG3 r7, r0, r2, r4     # Transfer(0, pool, supply)
    RETURN r4

The fee-to-seeder rule

Every trade pays a 0.3% fee, in ETH, to whoever seeded the pool. A program cannot know who deployed it, so the seeder is simply the first caller that sends ETH. Deploy and seed together, with deployAndCall, which does both as one transaction, or someone else can seed your pool first and earn its fee for good.

Buy:   fee    = ethIn × 3 / 1000
       tokens = (ethIn − fee) × tokenReserve / (ethReserve + ethIn − fee)

Sell:  eth    = tokensIn × ethReserve / (tokenReserve + tokensIn)
       fee    = eth × 3 / 1000
       seller receives eth − fee
  • The fee leaves the pool by a TRANSFER to the seeder, so trading does not deepen the pool. Rounding always favours the pool.
  • A trade that would return less than the minimum fails at a REQUIRE, so it reverts with empty data.
  • Every token movement is logged as an ERC-20 Transfer(from, to, amount), with the pool's own address standing for its reserve, so an indexer can rebuild balances from logs alone.
  • There are no liquidity shares: the seeding ETH cannot be taken back out. Tokens cannot be sent between users.
  • A trade takes 31 to 39 steps and about 145,000 to 160,000 host gas.
# Deploy and seed in one transaction, with 0.5 ether, naming the token.
SEED=$(cast abi-encode "f(bytes32,bytes32)" $(cast format-bytes32-string "Mini Dollar") $(cast format-bytes32-string "MUSD"))
SIG="deployAndCall(uint8,bytes,bytes32,uint256,bytes,uint256)"
POOL=$(cast call $MINICHAIN "$SIG(address,bytes)" 1 $(cat examples/miniuni.hex) $SALT 0.5ether $SEED 1000 --from $ME | head -1)
cast send $MINICHAIN "$SIG" 1 $(cat examples/miniuni.hex) $SALT 0.5ether $SEED 1000 --private-key $PK

# Buy with 0.1 ether and no minimum.
cast send $MINICHAIN "transact(address,uint256,bytes,uint256)" $POOL 0.1ether $(cast abi-encode "f(uint256)" 0) 1000 --private-key $PK

cast call $MINICHAIN "storageAt(address,uint256)(uint256)" $POOL 0      # token reserve
cast parse-bytes32-string $(cast call $MINICHAIN "storageAt(address,uint256)(bytes32)" $POOL 3)   # ticker
cast call $MINICHAIN "storageAt(address,uint256)(uint256)" $POOL $ME    # your tokens

# Sell 1,000 tokens with no minimum.
cast send $MINICHAIN "transact(address,uint256,bytes,uint256)" $POOL 0 $(cast abi-encode "f(uint256,uint256)" 1000ether 0) 1000 --private-key $PK

Walk through MiniNFT

examples/mininft.mini is a collection in 420 bytes, with a supply cap and a mint price that goes to its creator. The storage slot numbered by a token id holds its owner, and tokens are numbered from 1 in the order they are minted. Slot 0 holds the collection's metadata hash, the 32-byte SHA-256 digest of an IPFS directory. Each token's metadata is then at ipfs://{cid}/{tokenId}, which the explorer builds from the hash.

CallInputETH to sendReturns
Create the collectionabi.encode(bytes32 hash, uint256 cap, uint256 price)NoneThe creator. Works once, for whoever calls first, so deploy and create together
Mintabi.encode(uint256(0), address to)Exactly the priceThe new token's id
Transferabi.encode(uint256 tokenId, address to)NoneThe new owner
Readabi.encode(uint256 slot)NoneThat storage slot
SlotHolds
A token idIts owner, or zero if it has not been minted
0The metadata hash; zero means the collection has none
2256 − 1The creator, who is paid for every mint
2256 − 2The supply cap; zero means there is none
2256 − 3The price of a mint, in wei; zero means free
2256 − 4How many tokens have been minted
    CONST r15, 1
    SUB r14, r0, r15        # slot -1: the creator
    SUB r13, r14, r15       # slot -2: the supply cap
    SUB r12, r13, r15       # slot -3: the price
    SUB r11, r12, r15       # slot -4: how many are minted
    CALLDATALOAD r1, r0     # first word: a token id, zero to mint, or the slot asked for
    CALLVALUE r10
    CALLDATASIZE r3
    CONST r4, 32
    EQ r5, r3, r4
    JUMPI r5, query         # one word: a read
    SLOAD r9, r14           # the creator
    CALLDATALOAD r6, r4     # second word: the recipient
    CALLER r8
    JUMPI r9, ready
    EQ r5, r10, r0          # the first call creates the collection
    REQUIRE r5              # and takes no ETH
    ADD r7, r4, r4
    ADD r5, r7, r4
    EQ r5, r5, r3
    REQUIRE r5              # exactly three words, so a mint cannot create it by mistake
    CALLDATALOAD r7, r7     # third word: the price
    SSTORE r0, r1           # the metadata hash
    SSTORE r13, r6          # the supply cap
    SSTORE r12, r7
    SSTORE r14, r8          # the caller is the creator from now on
    RETURN r8
ready:
    CONST r7, 0xffffffffffffffffffffffffffffffffffffffff
    AND r6, r6, r7          # keep only the 160 address bits
    REQUIRE r6
    SLOAD r2, r11           # minted so far
    JUMPI r1, move
    SLOAD r7, r12
    EQ r5, r10, r7
    REQUIRE r5              # exactly the price
    SLOAD r3, r13
    LT r5, r2, r3           # under the cap
    EQ r3, r3, r0           # or there is none
    OR r5, r5, r3
    REQUIRE r5
    ADD r1, r2, r15         # the new token's id
    SSTORE r11, r1
    SSTORE r1, r6
    CONST r7, 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef
    LOG4 r7, r0, r6, r1     # Transfer(0, recipient, token id)
    TRANSFER r9, r10        # the price, to the creator
    RETURN r1
move:
    EQ r5, r10, r0
    REQUIRE r5              # a transfer takes no ETH
    LT r5, r2, r1
    EQ r5, r5, r0
    REQUIRE r5              # the token has been minted
    SLOAD r3, r1            # its owner
    EQ r5, r3, r8
    REQUIRE r5              # is the caller
    SSTORE r1, r6
    CONST r7, 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef
    LOG4 r7, r3, r6, r1     # Transfer(owner, recipient, token id)
    RETURN r6
query:
    EQ r5, r10, r0
    REQUIRE r5              # a read takes no ETH
    SLOAD r2, r1
    RETURN r2
  • A program has no constructor and cannot know who deployed it, so the first call stands in for one. Make it with deployAndCall, which deploys and calls as one transaction, so nobody else can call first. It must be exactly three words, which keeps an early mint or transfer from creating the collection by mistake. Nothing it sets can be changed afterwards.
  • Anyone may mint, for any recipient, until the cap is reached. The price goes straight to the creator's internal balance, and a call that sends any other amount fails, so no call leaves ETH behind in the program.
  • A token moves only when its owner calls. The recipient may not be zero, so a token is never destroyed.
  • The settings sit in the last four storage slots, which no token can ever be numbered, and a transfer is refused for any id that has not been minted.
  • A one-word read writes nothing, so it works through read, and it is what another MiniVM program can reach through CALL.
  • Each mint and transfer is logged as an ERC-721 Transfer(from, to, tokenId); a mint has from zero.
  • There are no approvals or balances, and the only metadata is the one hash for the whole collection.
  • The benchmark measured a mint at 228,588 gas (35 steps) and a transfer at 128,120 (32 steps).

Three smaller examples sit beside these: the counter, an owner-only vault, and a forwarder that shows why a nested call does not carry the original sender's authority.

Running Solidity

Kind 2 interprets EVM bytecode. The reference target is Solidity 0.8.26 compiling for Cancun. The interpreter is EvmVM, a second contract that the MiniChain reaches only by DELEGATECALL, so it runs against the MiniChain's own storage. Addresses, balances, storage and logs are all virtual.

Creating contracts

There are three ways to install a Solidity contract.

HowWhat runs
create(initCode, salt, value, maxSteps)The constructor, with the calling wallet as msg.sender. The bytes it returns become the code, immutables included.
A signed Transaction with to zeroThe same, through execute, with a zero salt
deploy(2, runtimeCode, salt)Nothing. The runtime bytecode is stored as given, so storage the constructor would have set stays empty.
// From a Foundry script or test, as script/IndexerDemo.s.sol does:
address token = chain.create(type(DemoToken).creationCode, bytes32("token"), 0, 20000);
chain.transact(token, 0, abi.encodeCall(ERC20.transfer, (bob, 250 ether)), 20000);
  • Append ABI-encoded constructor arguments to the creation code, as usual.
  • The returned runtime may be empty (the account then exists without code), may not exceed 24,575 bytes, and may not start with 0xEF.
  • Guests can create contracts themselves with CREATE and CREATE2. A failed constructor returns 0 to the creating contract and its effects are undone; the creator's nonce still advances.
  • Solidity external libraries must have their address linked into the bytecode before upload. No linking tool is provided.

What the interpreter supports

FamilyInstructions and behaviour
HaltSTOP, running off the end of code, SELFDESTRUCT (Cancun: pays out, keeps code and storage)
ArithmeticADD, MUL, SUB, DIV, SDIV, MOD, SMOD, ADDMOD, MULMOD, EXP, SIGNEXTEND
Comparison and bitsLT, GT, SLT, SGT, EQ, ISZERO, AND, OR, XOR, NOT, BYTE, SHL, SHR, SAR
HashingKECCAK256 over bounded guest memory
Identity and valueADDRESS, BALANCE, ORIGIN, CALLER, CALLVALUE, SELFBALANCE, all over virtual accounts
Input and codeCALLDATALOAD, CALLDATASIZE, CALLDATACOPY, CODESIZE, CODECOPY, EXTCODESIZE, EXTCODECOPY, EXTCODEHASH
EnvironmentBLOCKHASH, COINBASE, TIMESTAMP, NUMBER, PREVRANDAO, GASLIMIT, CHAINID, GASPRICE, BASEFEE, BLOBHASH, BLOBBASEFEE, GAS
CallsCALL, CALLCODE, DELEGATECALL, STATICCALL to virtual accounts, to precompiles 0x01 to 0x11 and 0x100, and to the host gateway
CreationCREATE, CREATE2 with Ethereum's address derivation
Return bufferRETURNDATASIZE, RETURNDATACOPY; reading past the end fails
StackPOP, PUSH0, PUSH1 to PUSH32, DUP1 to DUP16, SWAP1 to SWAP16
MemoryMLOAD, MSTORE, MSTORE8, MSIZE, MCOPY
StorageSLOAD, SSTORE per virtual contract; TLOAD, TSTORE per virtual transaction
ControlJUMP, JUMPI, JUMPDEST, PC; destinations inside PUSH data are rejected
LogsLOG0 to LOG4, emitted on the host as VirtualLog(account, topics, data)
OutputRETURN, REVERT; revert bytes are wrapped in GuestReverted(bytes) at the host boundary

The test suite runs real compiler output natively and as a guest and requires identical results. It covers ERC-20 and ERC-721 contracts, constructors with arguments and immutables, factories using new and new{salt:}, try/catch, a delegating proxy, the precompiles, transient storage, and Uniswap V2 as published: the factory, pair, Router02 and WETH9 bytecode from Uniswap's npm packages, covering liquidity, token and ETH swaps and a signed permit.

Calls between guests

  • Caught failures. Every child frame runs in a host self-call, so a failed child's storage, transfers, logs and transient storage are undone and the parent continues with 0 on its stack.
  • Budget. The CALL gas operand caps the child's share of the step budget, and the parent always keeps one 64th of what remains. A child that halts abnormally forfeits its whole budget.
  • Stipend. A CALL that transfers value adds 2,300 steps to the child's budget.
  • No child is run when the caller's balance is below the value (0 is pushed), or when a CALL or STATICCALL targets the zero address or the MiniChain itself (it succeeds if it carries no value, and fails otherwise).
  • Depth. Frames nest 8 deep below the root. A frame at that depth which calls or creates again reverts as a whole with DepthLimit, so its caller sees a failed call. Ethereum pushes 0 and lets the frame continue; here that would let a caller choose the depth at which a contract runs, and so make its inner calls fail quietly.
  • Codeless targets accept any calldata, receive the value and return nothing.
  • Host gas. If a child runs out of host gas, or the host cannot store the code a child created, the whole transaction reverts with HostCallFailed. Otherwise a relayer could choose a gas limit that forces a guest's child call to fail. A frame on the stipend is the exception: it has its own allowance and simply fails. A contract called with a large step budget can still use enough host gas to fail the transaction that called it; only the stipend bounds that.

The block environment

OpcodeValue inside a guest
TIMESTAMP, NUMBER, COINBASE, PREVRANDAO, BLOCKHASH, CHAINIDThe host block's values
ORIGINThe authorised sender of the outer virtual transaction: for a relayed transaction the signer, never the relayer
GASThe remaining shared step budget
GASLIMIT1,000,000, the step cap
GASPRICE, BASEFEE, BLOBBASEFEE, BLOBHASHZero

CHAINID is the host's. A guest's own EIP-712 domain is therefore not unique across two MiniChains on one host chain unless it also binds the MiniChain's address.

What it does not do

  • No EVM gas. One opcode is one step, except that creating a contract also costs one step for each 32 bytes of code it stores. There is no opcode schedule, memory gas, warm and cold access, or refunds.
  • Fixed limits. 1,024 stack words, 65,536 bytes of memory, 4,096 bytes of call data, return data and log data.
  • SELFDESTRUCT never deletes an account, including in the transaction that created it.
  • A precompile costs steps for the host gas it uses, one step per unit, within the gas operand as its allowance: ecrecover costs a little over 3,000 steps and an empty pairing check a little over 45,000. One that fails returns 0, as on Ethereum.
  • Calls to the zero address fail, unlike on Ethereum.
  • One address is not an account: calls to HOST_GATEWAY read the host chain.
  • No Ethereum envelope. No transaction formats, RPC methods, receipts, block or state roots, or fork transitions.
  • Not run against upstream fixtures. No Ethereum execution fixtures have been run. Every undefined opcode fails explicitly.

Reading the host chain with HostReader

A Solidity guest can read real contracts on the host chain, such as a price feed or a token balance. A call to the reserved address HOST_GATEWAY is carried out on the host with STATICCALL, so it can read anything and change nothing. Its input is 20 bytes of host target followed by the calldata for that target. The HostReader library in src/HostReader.sol wraps it:

library HostReader {
    // STATICCALL `target` on the host chain with `data`, using up to all remaining steps.
    function read(address target, bytes memory data)
        internal view returns (bool ok, bytes memory out);

    // The same, with at most `gasLimit` host gas (and that many steps).
    function read(address target, bytes memory data, uint256 gasLimit)
        internal view returns (bool ok, bytes memory out);

    // Call `guest` on the MiniChain at `chain` read-only, giving it `maxSteps` there.
    function readChain(address chain, address guest, bytes memory data, uint256 maxSteps)
        internal view returns (bool ok, bytes memory out);
}
(bool ok, bytes memory out) = HostReader.read(feed, abi.encodeCall(IFeed.latestAnswer, ()));
  • Failure. A failed read returns ok == false and never reverts the guest by itself. Return data over 4,096 bytes counts as a failed read with no data.
  • Cost. A read may use one unit of host gas per step it is given, and is charged one step for each unit it uses, so maxSteps has to cover it. A simple getter cost about 5,000 steps in the benchmark, and reading a guest on another MiniChain about 110,000.
  • Host gas. The MiniChain checks that the whole allowance is available before the read and otherwise reverts with HostCallFailed. Whoever submits the transaction cannot make a read fail by supplying too little gas. They can make it cheaper, with an access list, so give a read you depend on room to spare.
  • Caller. The host contract sees the MiniChain as msg.sender, for every guest.
  • Value cannot be sent to the gateway.
  • Other MiniChains. readChain calls another chain's read through the gateway. A guest cannot read its own chain this way, because read refuses to run while its chain is executing. Its own chain's plain getters do answer through the gateway; guestCall and batchItem are refused.
  • MiniVM programs have no instruction for any of this.

Reads import trust. A guest's results then depend on contracts outside the MiniChain, and are no longer reproducible from the MiniChain's own history. Read only contracts you trust. The registry's idOf tells you whether an address is a genuine MiniChain; it says nothing about the guests deployed on it.

Owning a MiniChain

Every MiniChain is created by a MiniChainRegistry, an ERC-721 collection (name MiniChain, symbol MINICHAIN) in which each token is the ownership of one chain. Token ids count up from 1. A chain's owner() is whoever holds its token, so selling or transferring the token transfers the chain.

What an owner has

  • Half of the chain's fees, claimable by anyone on the owner's behalf with claimFees().
  • The right to name the chain.
  • If the chain was created with an end date, whatever ETH is left in it once that date has passed.

An owner cannot change the fee rate, pause or upgrade the chain, move its end date, or touch anyone's balance before that date.

The registry

Deploying the registry creates the whole system in its constructor: the shared MiniChain code, the EVM engine, MiniChain #1, and the default minter. The renderer is deployed separately and passed in.

constructor(address owner_, IChainRenderer renderer_, uint64 genesisExpiry)

Each MiniChain is a 44-byte minimal proxy of one shared implementation, with its own storage and ETH, created at an address fixed by its id. A token therefore always stands for a genuine MiniChain running the same code. The implementation itself is locked and cannot be used as a chain. Minting a token measured 61,155 gas and launching its chain 94,026.

FunctionWhat it doesWho may call
mint(address to)Mints the token of a new MiniChain to to and returns its id. Nothing is deployed yetThe minter contract only
launch(uint256 id, uint64 expiry)Deploys the token's MiniChain, fixes its end date (zero for none) and returns its address. Works once per tokenThe token's owner
launch(uint256 id, uint64 expiry, Engine[] engines)The same, with up to eight VMs of the owner's choosing. Each is (address engine, bool trusted). Fails with TrustedEnginesNotAllowed if one is trusted and that is switched offThe token's owner
setTrustedEnginesAllowed(bool allowed)Allows or stops the launching of chains with trusted engines. Off to begin with. Chains already launched are unaffectedThe owner of token 1
trustedEnginesAllowed()Whether that is onView
launched(uint256 id)Whether the token's MiniChain has been launchedView
setName(uint256 id, string name_)Names a chain, or clears the name with an empty stringThe token's owner
sweep(uint256 id)Sends all ETH of a chain past its end date to the token's ownerAnyone
setMinter(address minter_)Replaces the contract allowed to mintThe owner of token 1
setRenderer(IChainRenderer renderer_)Replaces the contract that draws the tokensThe owner of token 1
chainOf(uint256 id)The MiniChain a token stands for. The address is fixed by the id and known before launchView
idOf(address)The token of a MiniChain, or zero for any other addressView
nameOf(uint256)The name its owner gave a chain, or emptyView
feeRecipients(address chain)Returns (chainOwner, genesisOwner); reverts if chain is not a MiniChain of this registryView
tokenURI(uint256 id)Metadata and artwork, drawn from the chain's live stateView
contractURI()Metadata for the collection as a wholeView
totalSupply(), minter(), renderer(), implementation()How many chains exist, and the three contracts the registry points toView

The standard ERC-721 functions (ownerOf, transferFrom, approve and the rest) come from Solady's implementation. supportsInterface also reports ERC-4906 (0x49064906).

Minting and the milestone minter

A MiniChain comes into being in two steps. First its token is minted: nothing is deployed, the token is the right to launch a chain, and its artwork is an uncut stone with the status Unlaunched. Then the token's owner calls launch(id, expiry) on the registry, whenever they choose, which deploys the chain and fixes its end date. An unlaunched token can be sold, and then its buyer launches it. MiniChain #1 is launched as the registry is deployed.

Only the registry's minter contract can mint. The default is MilestoneMinter, which allows one more MiniChain for every 0.01 ETH of fees MiniChain #1 has ever collected, and lets the owner of MiniChain #1 give others away. The registry itself never mints more than 512 tokens, whatever the minter:

uint256 public constant FEES_PER_MINT = 0.01 ether;
uint256 public constant MAX_SUPPLY = 512;   // also a constant of the registry

function mintable() public view returns (uint256) {
    if (!mintingOpen) return 0;
    uint256 allowed = 1 + granted + IFeeTotal(registry.chainOf(1)).totalFees() / FEES_PER_MINT;
    if (allowed > MAX_SUPPLY) allowed = MAX_SUPPLY;
    uint256 supply = registry.totalSupply();
    return allowed > supply ? allowed - supply : 0;
}

function mint(address to) external returns (uint256 id)
function mintFor(address[] calldata to, uint256[] calldata quantity) external
  • Minting is free apart from gas and open to anyone. Whoever calls mint first chooses who receives the token. A token counts toward the supply whether or not it has been launched. With nothing available it fails with NothingToMint.
  • Earned mints are closed to begin with: mintingOpen is false and mintable() returns zero. Fees count from the start, and what they have earned can be minted once the owner of token 1 calls setMintingOpen(true). They can close it again with false. mintFor works either way.
  • mintFor gives tokens away: quantity[i] tokens to to[i]. Only the owner of token 1 can call it, and it needs no fees to have been earned. granted counts the tokens given away; they do not use up earned mints, but they share the limit of 512. One token costs about 60,000 gas to mint, so send a long list in several calls.
  • The registry refuses token 513 with SupplyCapReached. This check is in MiniChainRegistry, so a replacement minter cannot pass it.
  • Unused mints accumulate. Only MiniChain #1's fees count, and claiming them does not reset the count, because totalFees() includes claimed fees.
  • 0.01 ETH of fees is 0.1 ETH of gas spent on MiniChain #1 at the base fee.
REGISTRY=$(cast call $MINICHAIN "registry()(address)")
MINTER=$(cast call $REGISTRY "minter()(address)")

cast call $MINTER "mintable()(uint256)"
cast send $MINTER "mint(address)" $ME --private-key $PK

# Later, as the token's owner. 0: a chain that never ends.
ID=$(cast call $REGISTRY "totalSupply()(uint256)")
cast send $REGISTRY "launch(uint256,uint64)" $ID 0 --private-key $PK
cast call $REGISTRY "chainOf(uint256)(address)" $ID

Names

The owner of a chain names it with setName(id, name) on the registry.

  • Up to 24 characters (MAX_NAME_LENGTH): the letters a to z and A to Z, digits, hyphens, and spaces that are not at either end. Anything else fails with InvalidName, which keeps a name safe to print in the metadata and the artwork.
  • An empty string clears the name.
  • The name stays with the token when it is sold, and the new owner can change it.
  • Names are not unique. Two chains can carry the same name, so the id is always shown beside it. A named token's metadata reads Name (MiniChain #5), and its artwork shows the name with MINICHAIN #5 beneath.
cast send $REGISTRY "setName(uint256,string)" 1 "Genesis" --private-key $PK
cast call $REGISTRY "nameOf(uint256)(string)" 1

Fee recipients

When fees are claimed, the chain asks the registry who should receive them:

function feeRecipients(address chain) external view returns (address chainOwner, address genesisOwner) {
    chainOwner = ownerOf(idOf[chain]);
    uint256 end = MiniChain(chainOf(GENESIS)).expiry();
    genesisOwner = end != 0 && block.timestamp >= end ? chainOwner : ownerOf(GENESIS);
}

Both are looked up at the moment of the claim. Fees that have accrued and not been claimed belong to whoever holds the two tokens then, so they move with a token when it is sold.

What the owner of token 1 can and cannot do

CanCannot
Receive half of every chain's fees, until MiniChain #1 reaches an end date of its ownChange the fee rate or the 50/50 split, for existing or future chains of this registry
Replace the minter with setMinter. A new minter can apply any rule, including none, and the zero address stops minting.Pause, upgrade or end any chain, or move an end date
Replace the renderer with setRenderer, which changes how every token is drawn and describedTouch any balance, guest or history on any chain
Decide, with setTrustedEnginesAllowed, whether new chains may be launched with trusted engines. It is off to begin with.Add an engine to a chain, remove one, or change what a launched chain runs
Everything any owner can do, on MiniChain #1Rename or sweep a chain it does not own

The default minting rule is a default, not a guarantee. Because the owner of token 1 can install any minter, they decide how the collection grows, including minting freely to themselves. What they cannot change is the supply cap: MAX_SUPPLY, 512, is a constant of the registry.

setMinter emits MinterChanged. setTrustedEnginesAllowed emits TrustedEnginesAllowed. setRenderer emits RendererChanged, an ERC-4906 BatchMetadataUpdate(1, type(uint256).max) so marketplaces refresh every token, and ContractURIUpdated. All three fail with NotGenesisOwner for anyone else.

End dates

Read this before depositing into a chain that has an end date. From that date the chain stops for good, withdrawals included, and everything still in it goes to its owner: your balance, guests' balances and unclaimed fees. Withdraw before the date. Check expiry() on the chain; zero means it never ends.

Setting one

An end date is chosen when a chain is launched and at no other time. launch(id, expiry) takes a Unix time, or zero for a chain that never ends. Holding an unlaunched token uses up none of a chain's life.

  • The 30-day minimum. A non-zero expiry must be at least MIN_LIFETIME (30 days) after the block that launches the chain, or the launch fails with ExpiryTooSoon.
  • Fixed. The registry writes it once through initialize. Nobody, the owner included, can change it, remove it, or add one to a chain launched without it.
  • Public. It is readable as expiry() on the chain, the registry emits ChainExpiry(id, expiry) at launch, and the token's metadata carries an Expires date.
# A chain that ends 90 days from now.
cast send $REGISTRY "launch(uint256,uint64)" $ID $(( $(date +%s) + 90*24*60*60 )) --private-key $PK

cast call $MINICHAIN "expiry()(uint64)"      # 0 means this chain never ends

What stops

Before the end dateEverything works. The chain is an ordinary MiniChain.
From the end dateNothing that changes the chain is accepted. Reads still work.
After a sweepThe ETH is with the owner. The token, its name and its history remain.
The date is at least 30 days after creation. The chain stops at the first block whose timestamp is at or past it.

Every operation that changes a chain ends by committing a block, and the commit refuses once block.timestamp >= expiry, with ChainExpired. So from that second on:

StopsStill works
depositread, and every view: balances, storage, code, head, height
withdraw, withdrawForThe token: it stays with its owner, keeps its name, and can be transferred or renamed
transact, execute, deploy, createtokenURI, which now reports Status: Ended and a grey stone
claimFeessweep on the registry
Every item of an executeBatch, each reported as failedPast events, which the indexer and explorer still show

Sweep

// MiniChainRegistry
function sweep(uint256 id) external returns (uint256 amount)

Anyone may call sweep(id) on the registry for a chain that has reached its end date. It first settles the fees nobody claimed: the half owed to the owner of MiniChain #1 is sent there as ETH, in a way that cannot be refused. Then it sends all the rest of the ETH the chain holds to whoever owns the token at that moment. Internal balances are not consulted and are worthless afterwards. Once MiniChain #1 has itself reached its end date, there is no such half and everything goes to the token's owner.

  • It emits Swept(to, amount) on the chain, once for each of the two payments, and ChainSwept(id, chain, owner, amount) on the registry, where amount is what the token's owner received.
  • It fails with NotExpired for a chain without an end date or before the date, and with ETHTransferFailed if the owner is a contract that rejects ETH.
  • The token is not destroyed. Its artwork turns grey and still, at the size and cut the stone had when the chain stopped.
  • Only the registry can call the chain's own sweep(address payable); anyone else gets OnlyRegistry.

Remaining balances go to the owner. That includes other users' internal ETH, the balances of guest contracts such as pools, and fees nobody claimed, including the half that would have gone to the owner of MiniChain #1. There is no grace period and no way to recover a balance afterwards.

The special case of MiniChain #1

MiniChain #1 can be given an end date too, but only when the registry is deployed, through the constructor's genesisExpiry (the deploy script reads it from GENESIS_EXPIRY). The same 30-day minimum applies. From that date:

  • MiniChain #1 itself stops like any other chain and can be swept to its owner.
  • Its owner's half of every other chain's fees goes to that chain's own owner instead, who then receives the whole fee.
  • The split is decided when fees are claimed, so fees still unclaimed at that date go entirely to each chain's owner.
  • MiniChain #1 collects no further fees, so under the default MilestoneMinter the number of chains that fees earn stops growing. The owner of token 1 can still give tokens away, up to the limit of 512.
  • Whoever holds token 1 can still replace the minter and the renderer.

Artwork

Each token is drawn as a gemstone: an animated SVG built entirely on-chain by MiniChainRenderer from the chain's live state, so tokenURI needs no server or IPFS. The token fixes what the stone is. What the chain does decides the rest.

What is fixed for a token

Everything fixed comes from one number, keccak256(abi.encodePacked(chain, id)), so it follows from the chain's address and id and never changes.

AttributeHow it is chosen
StoneOne of 14. Ruby, Garnet, Topaz, Citrine, Peridot, Emerald, Aquamarine, Sapphire, Tanzanite, Amethyst, Rose Quartz and Opal each come up 3 times in 40. Diamond and Onyx come up 2 times in 40.
HueThe stone's own hue, shifted by up to 8 degrees either way, so no two rubies are quite the same red. An opal can be any hue.
CutOne of 11, equally likely: Round, Oval, Emerald, Asscher, Princess, Hexagon, Trillion, Pear, Marquise, Shield, Starburst
CornersSet by the cut: 6 for Hexagon and Trillion; 8 for Emerald, Asscher, Princess and Marquise; 10 for Pear and Shield; 12 for Starburst; 8, 10 or 12 for Round and Oval
TableFlat or Pointed, evenly: whether the middle of the stone is one flat face or comes to a point
BackdropVelvet (dark), or Paper (light) for one token in eight. Its hue is set off from the stone's.

What the chain's activity changes

What the chain doesWhat changesRule
Commits operationsThe cut gets finer: more rows of facetsOne row, and one more at 10, 100, 1,000 and 10,000 operations, up to 5
Commits any operationThe light moves and every facet is reshadedThe light's direction is head modulo 360 degrees; each facet's shade and shimmer also derive from head
Holds ETHThe stone growsSize in thousandths = 350 + 99 × ln(1 + ETH held / 1.4), capped at 1,000
Earns feesIt gains glints1 + ⌊log2(1 + fees / 0.01 ETH)⌋, up to 10
Reaches its end dateIt turns grey and still, with no glintsA filter removes all colour; size and cut stay as they were
Preview the numbers for any state
Facet rows
Facets
Size
Glints

The drawing is a schematic of a round cut built with the renderer's ring construction; it is not the on-chain image. For that, call image(id, chain, name, activity) on the renderer, which is pure, so any state can be previewed without a chain being in it.

ETH held015101005001,000
Size, % of full354050557793100
Fees earned, ETH, at least00.010.030.070.150.310.631.272.555.11
Glints12345678910

What each attribute means

Every input to the picture is also in the token's metadata, in this order.

AttributeMeaning
NameThe owner's name for the chain. Present only if one is set.
StoneWhat the gem is made of
CutThe shape of its outline
StatusUnlaunched until the owner launches the chain, then Live, or Ended once it has reached its end date
TableFlat or Pointed
BackdropVelvet or Paper
Facet rows1 to 5, from the number of operations
Facets2 × corners × rows, plus the table: one face if flat, one per corner if pointed. The finest stone has 132.
Glints1 to 10, from the fees earned; 0 for an ended chain
SizeThe stone's size as a percentage of full size, from the ETH held
OperationsThe chain's height
ETH heldtotalDeposits, in ether to four decimal places
Fees earnedtotalFees, in ether to four decimal places
ChainThe MiniChain's address, checksummed
EnginesBuilt-in for a chain with only MiniVM and the EVM, Sandboxed if it was launched with added VMs, or Trusted if any of them is trusted. Absent until the chain is launched.
ExpiresThe end date, shown as a date. Present only for a chain that has one.

The renderer exposes each rule as a function: rows(height), glints(fees), scale(deposits), facets(id, chain, height), stone(id, chain), cut(id, chain), crown(id, chain) for the table, and backdrop(id, chain). contractURI() gives the collection's own image: one fixed opal, cut as finely as a stone can be.

tokenURI is a view, read through eth_call and never paid for in a transaction. For an unused chain it measured 1,350,073 gas and returned 7,585 bytes; the finest stone measured 3,263,492 gas for a 13,039-byte SVG.

Indexer and explorer

Wallets and block explorers cannot see what happens inside a MiniChain, because guests are not contracts on the host chain. But everything needed to rebuild it is emitted by the one MiniChain contract. indexer/ is a Ponder project that reads those events and serves an API, the explorer and these pages.

The tables

TableHoldsBuilt from
eth_balanceInternal ETH per account, wallets and guests alikeDeposited, Withdrawn, VirtualTransfer
guest_contractEvery guest: address, creator, kind, code hashContractDeployed
token_balanceFungible balances per token and holderVirtualLog carrying an ERC-20-shaped Transfer (three topics, one data word)
nft_ownerCurrent NFT owners; burned tokens are removedVirtualLog carrying an ERC-721-shaped Transfer (four topics)
token_transferHistory of every token movementBoth of the above
blockOne row per operation, with a kind: deposit, withdraw, deploy, call, claim or otherBlockCommitted, described by the events emitted before it
activityEvery event, tied to the MiniChain block it belongs toAll events
cursorA single row: the last committed height and the operation in progressBookkeeping

Guest logs from both VMs arrive in the same VirtualLog(account, topics, data) envelope. Uncollected fees appear as the eth_balance of the MiniChain's own address, and a claim moves them to the two owners' rows.

The API

Responses are JSON. Integers of any size are decimal strings, and ETH amounts are in wei.

EndpointReturns
/chainThe indexed chain as it stands, read from the node: height, head, totals, fees, owner, name, end date, artwork and attributes
/registryHow many MiniChains exist, how many are launched, how many more may be minted, and the newest with their artwork. ?limit=, default 12. ?launched=1 lists launched chains only, always with MiniChain #1.
/blocksMiniChain blocks, newest first. ?limit= from 1 to 200, default 25, and ?before= a block number.
/blocks/:numberOne block with its events
/tx/:hashThe blocks committed by one host transaction
/activityRecent events. ?account= for one address, ?limit= default 50.
/accountsHolders of internal ETH, largest first, with the kind of each
/contractsGuest contracts, newest first
/tokensTokens, with holder counts
/appsCopies of MiniUni and MiniNFT, recognised by their code, with reserves and seeder, or price, cap, creator, items and owners
/address/:addressEverything about one address: holdings, nonce, contract, what it has issued, transfers and events
/holdings/:addressInternal ETH, token balances and NFTs of one address
/graphqlA GraphQL API over all tables
curl http://127.0.0.1:42069/holdings/0x70997970C51812dc3A010C7d01b50e0d17dc79C8
{
  "address": "0x70997970c51812dc3a010c7d01b50e0d17dc79c8",
  "eth": "…",
  "tokens": [{ "token": "0x…", "balance": "…" }],
  "nfts": [{ "token": "0x…", "tokenId": "…" }]
}

The same server hosts the pages: the landing page at /, the explorer at /explorer, and these docs at /docs. Each is a single HTML file in explorer/ with no build step, read fresh on every request.

Running them

You need Foundry and Node 18.14 or later. From the repository root, start a node and generate some activity:

anvil                                   # terminal 1
forge script script/IndexerDemo.s.sol:IndexerDemo --rpc-url http://127.0.0.1:8545 --broadcast

The script deploys a MiniChain, MiniUni, MiniNFT, an ERC-20 and an ERC-721, makes trades and transfers from two test accounts, and prints the addresses and expected balances. Then start the indexer:

cd indexer
pnpm install
MINICHAIN_REGISTRY=<REGISTRY address printed by the script> pnpm dev

Open http://127.0.0.1:42069/explorer. The indexer follows every MiniChain the registry has launched; choose one from the list at the right of the explorer's header. Each endpoint below answers for one chain: add ?chain= with a token id or a chain's address, or leave it off for MiniChain #1.

VariableDefault
MINICHAIN_REGISTRYRequired: the registry whose MiniChains to follow
MINICHAIN_RPC_URLhttp://127.0.0.1:8545
MINICHAIN_CHAIN_ID31337
MINICHAIN_START_BLOCK0; set it to the block the registry was deployed in

Set them in the environment or in indexer/.env.local. The script accepts MNEMONIC to use accounts other than anvil's well-known ones, and MINICHAIN to use an existing chain.

What the indexer cannot know

  • It indexes one MiniChain. Other chains of the registry appear in /registry with what the node says about them, without blocks or balances.
  • Tokens are recognised by the shape of their events, not by a registry, so any guest can emit Transfer logs and appear as a token. Decide which token addresses you trust.
  • Balances are sums of logged transfers. A token whose logs do not match its real state is reported wrongly; storageAt on the MiniChain is the ground truth. A token that emits no standard Transfer is invisible.
  • It has only been run against a local anvil node.

Reference

Events

MiniChain

EventEmitted when
Deposited(address indexed payer, address indexed beneficiary, uint256 amount)ETH is deposited, directly or attached to a call
Withdrawn(address indexed account, address indexed recipient, uint256 amount)Internal ETH is withdrawn
TransactionExecuted(address indexed from, address indexed to, uint256 nonce, uint256 steps, bytes result)A virtual transaction succeeds; steps is what it used
TransactionFailed(address indexed from, uint256 nonce, uint256 index, bytes reason)A transaction in a batch failed and left no trace
BlockCommitted(uint256 indexed number, bytes32 previousHash, bytes32 blockHash, bytes32 operationHash)Any operation is committed
EngineAdded(uint8 indexed kind, address indexed engine, bool trusted)The chain is launched with an added VM; once per engine
VirtualTransfer(address indexed from, address indexed to, uint256 amount)Internal ETH moves between accounts, including fees and claims
VirtualLog(address indexed account, bytes32[] topics, bytes data)A guest emits a log; account is the guest
ContractDeployed(address indexed creator, address indexed account, uint8 kind, bytes32 codeHash)Guest code is installed
Swept(address indexed to, uint256 amount)An ended chain's ETH is sent to its owner

MiniChainRegistry

EventEmitted when
ChainCreated(uint256 indexed id, address indexed chain, address indexed owner)A token's MiniChain is launched
ChainClaimed(uint256 indexed id, address indexed chain, address indexed owner)A token is minted; chain is where its MiniChain will be
ChainExpiry(uint256 indexed id, uint256 expiry)A MiniChain is launched with an end date
ChainSwept(uint256 indexed id, address indexed chain, address indexed owner, uint256 amount)An ended chain is swept
MinterChanged(address indexed minter)The minter is set or replaced
TrustedEnginesAllowed(bool allowed)The owner of token 1 allows or stops trusted engines for new chains
RendererChanged(address indexed renderer)The renderer is set or replaced
NameChanged(uint256 indexed id, string name)A chain is named or its name cleared
MetadataUpdate(uint256 tokenId)ERC-4906: one token's metadata changed (on a name change)
BatchMetadataUpdate(uint256 fromTokenId, uint256 toTokenId)ERC-4906: every token's metadata changed (on a renderer change)
ContractURIUpdated()ERC-7572: the collection's metadata changed

The registry also emits the standard ERC-721 events.

Errors

Entry points

ErrorMeaning
ZeroAmount()A deposit or withdrawal of nothing, or a claim with no fees accrued
InvalidVM()deploy with a kind the chain does not have, or a DELEGATECALL to a sandboxed guest
NotEngine()A sandbox function called by anyone but the engine of the guest now running
InvalidEngine(), TooManyEngines()A launch with an engine address that has no code, or with more than eight
TrustedEnginesNotAllowed()A launch with a trusted engine while the registry has that switched off
InvalidNonce()A signed request does not carry the signer's current nonce
InvalidSignature()The signature does not match the sender
Expired()A signed request is past its deadline. Not to be confused with ChainExpired.
VirtualAccountCannotSign()The sender's address holds guest code
InvalidStepBudget()maxSteps is zero or above 1,000,000
FeeTooHigh()The fee would exceed the signed maxFee
LengthMismatch()A batch's transactions and signatures differ in number
ChainExpired()The chain has reached its end date and commits nothing more
NotExpired()sweep on a chain with no end date, or before it
OnlyRegistry()initialize or the chain's sweep called by anyone but the registry
OnlySelf()batchItem or guestCall called by anyone but the MiniChain
Reentrancy()An entry point was entered while another was running; also read during a transaction
ETHTransferFailed()The recipient of a withdrawal or sweep rejected the ETH

Ledger and execution

ErrorMeaning
InvalidAddress()The zero address or the MiniChain's own address where an account is required
InsufficientBalance()Not enough internal ETH for a value, a withdrawal or the fee
StepLimit()The step budget ran out
DepthLimit()A call went deeper than 8 below the root
DataTooLarge()Call input, return data or log data over 4,096 bytes, or a constructor returning over 24,575
CodeTooLarge()Code is empty or over its size limit
InvalidCode(uint256 pc)A malformed MiniVM program at byte pc, or EVM runtime starting with 0xEF
InvalidOpcode(uint256 pc, uint8 opcode)An undefined opcode
GuestReverted(bytes data)The guest reverted; data is its own revert data
StaticViolation()A write, log, creation or value transfer in a read-only or stipend-only frame
AddressOccupied()The address already has code or a used nonce
NoContract()A transaction sent data to an account without code
HostCallFailed()The host transaction has too little gas left for a child frame, a precompile or a host read. Never catchable by a guest.
ChildReverted(uint256 used, bytes data)Internal envelope between frames; you should not see it
EvmStackUnderflow(), EvmStackOverflow()The EVM stack went below empty or above 1,024 words
EvmMemoryLimit()EVM memory would exceed 65,536 bytes
EvmBadJump(uint256 destination)A jump to something that is not a JUMPDEST
EvmReturnDataBounds()RETURNDATACOPY past the end of the return buffer

Registry and minter

ErrorMeaning
NotMinter()mint on the registry called by anyone but the minter
NotTokenOwner()setName or launch by someone who does not own the token
AlreadyLaunched()launch of a token whose chain exists already
NotLaunched()sweep of a token whose chain has not been launched
InvalidName()A name that is too long or has a character that is not allowed
ExpiryTooSoon()An end date less than 30 days away
NotGenesisOwner()setMinter, setRenderer or setTrustedEnginesAllowed by anyone but the owner of token 1
NothingToMint()MilestoneMinter.mint when mintable() is zero
SupplyCapReached()A mint when 512 tokens exist, from any minter
LengthMismatch()MilestoneMinter.mintFor with lists of different lengths. It also fails with NotGenesisOwner for any caller but the owner of token 1
TokenDoesNotExist()A token id that has not been minted

Constants and limits

ConstantValueMeaning
MAX_CODE_SIZE24,575Bytes of guest code. One below Ethereum's limit, because code is stored in a data contract behind a STOP byte.
MAX_INIT_SIZE49,152Bytes of EVM creation code
MAX_DATA_SIZE4,096Bytes of call input, return data or log data
MAX_STEPS1,000,000Instructions per outer virtual transaction
MAX_DEPTH8Nested calls below the root
MAX_ENGINES8VMs a chain can be launched with, besides the two built in
CALL_STIPEND2,300Steps granted to the recipient of a value transfer
MINI_VM, EVM_VM1, 2The two kinds of guest
HOST_GATEWAY0x8cF1…3345address(uint160(uint256(keccak256("MiniChain.host")))), in full 0x8cF13341074D1A304Ab3cC46aC9a242229033345
FEE_DIVISOR10See Fees
FEE_SHARE_DIVISOR2
FEE_OVERHEAD_GAS37,700
BATCH_ITEM_OVERHEAD_GAS10,000
BATCH_SHARED_GAS23,700
GENESIS1The token that controls minting and shares in every chain's fees
MAX_NAME_LENGTH24Characters in a chain's name
MIN_LIFETIME30 daysThe least time a chain with an end date must be given
FEES_PER_MINT0.01 etherFees MiniChain #1 must collect per additional chain (default minter)
MAX_SUPPLY512MiniChains there can ever be, enforced by the registry
MAX_ROWS5Rows of facets on a stone
MAX_GLINTS10Glints on a stone
Other limitsValue
MiniVM registers16
EVM stack1,024 words
EVM memory65,536 bytes
Program size the assembler accepts8,192 bytes
Size of each MiniChain proxy44 bytes

Security notes and known limitations

MiniChain has not been externally audited and is not yet deployed to mainnet. The tests cover the implemented surface; they are not a security audit, and no upstream Ethereum execution fixtures have been run. Do not put in ETH you cannot afford to lose.

Your funds

  • End dates take everything. On a chain with an end date, whatever is not withdrawn before it goes to the owner. Check expiry() first. See End dates.
  • Guests can lock funds. A badly written or deliberately locked guest can strand its own internal balance. Guest code is immutable, and no administrator can rescue it.
  • MiniUni's seed is permanent. It has no liquidity shares, so the seeding ETH cannot be taken back out, and whoever seeds a pool first earns its fee.
  • Forced ETH is lost. ETH sent to a MiniChain without a deposit is credited to nobody.
  • Failed transactions still cost gas. A failure undoes everything inside the MiniChain, but the caller or relayer has paid Ethereum.
  • transact has no fee cap. The fee follows the base fee of the block that includes the transaction. Only signed transactions carry a maxFee.

What you are trusting

  • The shared code. Every chain of a registry runs one implementation, which holds real ETH and cannot be upgraded. A bug in it cannot be patched.
  • A chain's engines. A chain launched with a trusted engine is only as safe as that engine: it can move any balance. Check hasTrustedEngine(), or the token's Engines attribute, before depositing. A sandboxed engine controls only the guests deployed to it.
  • Guests are whatever their authors deployed. A genuine MiniChain says nothing about the programs on it. Names are not unique, and anyone can deploy a guest that emits token-shaped logs.
  • Host reads. A guest that reads the host chain depends on the contracts it reads, and its results cannot be reproduced from MiniChain history alone.
  • The owner of token 1 can replace the minter and the renderer, and can allow new chains to be launched with trusted engines. A new renderer changes what every token's metadata says.
  • Relayers are never reimbursed, and can choose when, or whether, to submit what you signed, until its deadline. A signed transaction that failed can be submitted again.
  • ERC-1271 signatures come from wallet contracts on the host chain, whose own logic decides what counts as valid.

Known limitations

  • Cost. Interpreting spends several hundred host gas per guest instruction. A Uniswap V2 swap costs about 2.8 million gas against about 93,000 natively. The project's notes call these numbers far too expensive for mainnet use, and plausible only where host gas is cheap.
  • No state commitment. head is a history hash. Nothing can be proven about balances or storage from it.
  • No consensus of its own. No validators, sequencer, or separate finality. Ordering and finality are the host chain's.
  • Incomplete EVM. No gas schedule, fixed memory and data limits, and the deviations listed above. Contracts that depend on exact gas behaviour will not behave as on Ethereum.
  • One untested property. The tests assert that a failed child's storage and transfers are undone, but cannot assert the same for its logs, because Foundry's log recorder keeps logs from reverted calls.
  • Guest EIP-712 domains. CHAINID is the host's, so a guest's signatures can be replayed on another MiniChain of the same host unless its domain binds the MiniChain's address.
  • Host chains that do not burn the base fee. There, the operator could earn fees, and therefore mints under the default minter, cheaply.
  • Invisible to wallets. Guest tokens and NFTs exist only inside the MiniChain. There is no bridge for them, and outside tools do not see guest events as transfers.
  • Tooling. No linker for Solidity libraries, no high-level language for MiniVM, and the indexer has only been run against a local node.