Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Introduction

Mordecai is a decentralized platform for peer-to-peer software. It combines two independent systems:

Pear Applications          ← UI, game logic, chat, media, simulation
      │
Holepunch Network          ← peer discovery, encrypted transport,
      │                      replicated storage, app distribution
Settlement Chain           ← identity, currency, ownership, contracts
      │
Consensus                  ← deterministic ordering + finality

The defining principle: applications are distributed programs; the blockchain is a distributed trust engine. They are deliberately kept apart.

  • Your app’s data — chat, documents, game moves, media — lives in signed, append-only Hypercore feeds, replicated directly between the peers who care about it. No servers, no consensus, no fees.
  • Only economic state — balances, ownership, escrow, the app registry — goes through the chain, where a fixed validator set orders transactions, executes contracts deterministically, and finalizes blocks with BFT quorum certificates.

A marketplace listing, seller conversation, image set, and reputation trail can replicate directly between interested users. The chain only gets involved when a purchase needs one public answer: payment transferred, ownership moved, or escrow released. That ratio — everything local and peer-to-peer except the few operations that need global trust — is the whole design.

What every application gets for free

By building on the SDK, an application inherits (spec principle 5):

  • Identity — the user’s Ed25519 wallet key works in every app; the same key signs transactions, owns Hypercore feeds, and answers login challenges.
  • Payments — native currency transfers and contract calls are one SDK method, not a payment-processor integration.
  • Ownership & contracts — deploy WASM contracts (written in Rust or the Pythonic DSL) for escrow, marketplaces, wagers, governance.
  • Distribution — apps are registered on-chain and fetched from the swarm, verified against the on-chain hash. No app store.
  • Replication — append-only feeds with authenticated history, live sync, and offline catch-up.

How to read this book

  • Quickstart gets a devnet running and money moving in five minutes.
  • Architecture explains each layer and the boundaries between them.
  • Building P2P Applications is the developer guide: what belongs on-chain vs off, the SDK surface, identity, and publishing.
  • Smart Contracts covers the execution model, a step-by-step DSL tutorial, the full language reference, and the raw Rust ABI.
  • Examples walks through the shipped apps and contracts.
  • Reference documents the CLIs, the RPC API, and the repo.

The normative sources remain the specifications in the repository root (SPEC_PT_01–03.md) and IMPLEMENTATION_PLAN.md; this book documents the system as actually built.

Field Guide

Six starting points, from your first peer to your first payment. Run these examples from your Mordecai checkout in a POSIX shell. Keep your data directories: they hold your node identities.

Get the tools

Install Node.js 20 or newer, pnpm 10, Git, curl, and mdBook 0.5.2. Then build the checkout; the examples below use its CLI directly.

git clone https://github.com/StuartFarmer/mordecai.git
cd mordecai
pnpm install
pnpm build
pnpm mordecai --help

Ready when: help lists the l1 and app command groups.

Already have a checkout? Run pnpm install and pnpm build there. The build includes this book in every node’s gateway; mdBook is only needed at build time. Prebuilt WASM is included; Rust and Python are only needed to rebuild contracts. See Repository Layout & Building for tooling.

Join a network

Get the L1 network’s exact genesis.json from its operator and save it in your checkout. Its hash determines which network you join.

pnpm mordecai l1 connect \
  --dir ./my-node \
  --genesis ./genesis.json \
  --port 8787

Your node syncs, verifies, and serves chain data. Open http://localhost:8787 for its homepage and http://localhost:8787/docs/ for this book. A key in the genesis validator set also votes.

Keep this terminal open and use another for the next steps. After Ctrl-C, repeat the command to resume. The saved identity and genesis are reused. For a private DHT, add the operator’s --bootstrap host:port.

Starting your own L1 instead?

init creates a new network with this node as its default validator. It does not join the network you are browsing.

pnpm mordecai l1 init --dir ./new-network --chain-id my-network
pnpm mordecai l1 start --dir ./new-network --port 8789

Add --alloc <address>=<amount> to init to fund an account in genesis. Create its wallet first. Share ./new-network/genesis.json with peers.

Create a wallet

Create an encrypted keystore and choose a passphrase at the hidden prompt. The wallet tool is a separate CLI.

node packages/wallet/dist/cli.js create --keystore ./wallet.json
node packages/wallet/dist/cli.js address --keystore ./wallet.json

You get an address and a 24-word recovery phrase. Save the phrase privately; share only your address.

A new wallet starts unfunded. Receive funds from an existing holder or the network operator before sending a payment. Wallet keys and node keys are separate identities. See Wallets, Identity & Sessions.

Create an app network

An app chain can run independently of L1. First create its persistent validator identity:

pnpm mordecai app init --dir ./my-app

init creates the key only. Save this complete starter as app.mjs in the checkout root to start the first peer.

import { readKeyFile } from './packages/node/dist/index.js';
import { AppChain } from './packages/appchain/dist/index.js';

const keyPair = readKeyFile('./my-app/peer.key');
const app = await AppChain.start({
  appId: 'com.example.world',
  chainValidators: [keyPair.publicKey],
  keyPair,
  dir: './my-app',
  gateway: { port: 8788 },
});

console.log(`App gateway: http://localhost:${app.node.gateway.port}`);
const stop = async () => {
  await app.stop();
  process.exit(0);
};
process.once('SIGINT', stop);
process.once('SIGTERM', stop);

Run it and leave the terminal open:

node app.mjs

Your single-validator app chain is reachable at port 8788. Share the machine’s reachable IP or domain with others; localhost only reaches their own machine.

This creates the network. Your app’s UI and contract rules are separate. Registration on L1 is optional and currently uses the SDK’s publishApp(...); there is no CLI publish command. For more, see How-To: Run Your App on Its Own Chain.

Join an app

Replace the example URL with an existing app peer’s gateway. Direct joining needs no settlement node.

pnpm mordecai app connect \
  --dir ./joined-app \
  --app https://game.example.com

Your peer syncs the app chain, seeds its advertised data, and prints its own gateway URL. Joining does not execute the app bundle.

To try the starter on the same machine, use --app http://localhost:8788. Every joined app peer can introduce the next one.

Join by a registered app ID

Use an L1 node’s 64-character hexadecimal RPC key, printed at its startup. An app ID needs a registry entry; the independent starter above does not create one.

pnpm mordecai app connect \
  --dir ./registered-app \
  --app com.example.world \
  --settlement-node '<l1-rpc-key-hex>'

Send a payment

For a browser-only walkthrough, see Web Wallet → Faucet → Hex. Every gateway provides /wallet.html: generate or load a key, download a private backup, read the balance, and claim from the same node’s faucet. The wallet uses in-memory keys and unencrypted test backups, distinct from the CLI keystore.

Get test CAI from a faucet

On a node with a faucet enabled, open its homepage, enter your public wallet address in Get test CAI, and submit. You never need to share your mnemonic, keystore, or passphrase. Each claim sends 10,000 CAI base units; the faucet pays the fee. Follow View transaction and wait for confirmation before spending.

Claims are limited to one per address and IP per minute, and 100 per hour per gateway. A node without a configured faucet shows a disabled form. If a claim is submitted but confirmation is unavailable, check the transaction or your balance before requesting again.

Node operators: create a separate wallet with the wallet CLI, fund its address on your network, set MORDECAI_FAUCET_PASSPHRASE to that wallet’s passphrase, then add --faucet-keystore ./faucet-wallet.json when starting the node or standalone gateway. For a new chain, l1 init --alloc '<faucet-address>=1000000000' can fund it at genesis. An existing chain needs an ordinary transfer; editing its genesis would create a different network. Keep this wallet separate from validator keys and other spending wallets. Never place its secret in the public node config.

For this MVP, limits reset on restart and one faucet gateway must own the wallet. The IP limit uses the socket address, so users behind the same reverse proxy share a cooldown. Run node apps/devnet/devnet.mjs for a temporary funded faucet on the first printed node website.

Send from your wallet

Use your funded wallet and the intended L1 gateway. Run these steps in the same terminal, from the checkout root. Replace values in angle brackets before signing.

Read the chain and your account

GATEWAY=http://localhost:8787
ADDRESS=$(node packages/wallet/dist/cli.js address --keystore ./wallet.json)
curl -fsS "$GATEWAY/api/head"
curl -fsS "$GATEWAY/api/account/$ADDRESS"

Use chainId from the head and nonce exactly as returned by your account. Amounts and fees are integers in base units. This example sends 1,000 units and sets a fee limit of 1,000; your balance must cover the amount and the actual fee.

Sign locally

node packages/wallet/dist/cli.js transfer \
  --keystore ./wallet.json \
  --to '<recipient-address>' \
  --amount 1000 \
  --nonce '<nonce>' \
  --chain-id '<chain-id>' \
  --max-fee 1000 > transfer.json

Enter your passphrase when prompted. Continue only if signing succeeds. transfer.json contains the signed transaction and hash; no payment has been submitted yet.

Submit, then check the receipt

curl -fsS "$GATEWAY/api/tx" \
  -H 'content-type: application/json' \
  --data-binary @transfer.json
TX_HASH=$(node -p "require('./transfer.json').hash")
curl -sS "$GATEWAY/api/tx/$TX_HASH"

A returned hash means the node accepted your submission. The payment is complete when its receipt reports success: true.

A 404 means this node has no receipt yet; wait and check again. If the receipt says success: false, inspect error. Wait for the receipt and re-read your nonce before the next payment. Only the signed transaction goes to the gateway; your keystore and recovery phrase stay with you.

Quickstart

Requirements: Node ≥ 20 with corepack and mdBook 0.5.2 for building the bundled documentation (see toolchains). Rust (with the wasm32-unknown-unknown target) and Python 3 are only needed if you want to rebuild WASM artifacts or compile DSL contracts — prebuilt artifacts are committed.

git clone <repo> && cd zechariah
pnpm install
pnpm build        # typecheck + emit all packages and bundle documentation
pnpm test         # the full suite: 150+ tests incl. multi-validator devnets

Try the browser demos

After building, run node scripts/node-demo.mjs and open http://127.0.0.1:8790. Create or load a wallet in Wallet, download its backup, and claim test CAI in Faucet. The Demos menu includes Hex, Frontier, Outpost, Chess, Microblog, and Bounties. The same wallet works across every tab.

The launcher preserves its chains, worlds, posts and deployment journal under .mordecai-demo/. Restarting keeps that state; do not delete it to update the UI. Wallet keys stay in the browser tab and must be loaded again after a page reload. Use another wallet or browser tab to play an opponent, tip an author, or answer a bounty.

1. Run a local devnet

node apps/devnet/devnet.mjs 4

This spins up an in-process DHT testnet and four consensus validators, and prints:

node-0  rpc key: f414d2a9d2a1…      ← dial any of these over the DHT
faucet address:   rb6rdrgkf19z…
faucet mnemonic:  video cheese twice …   ← a funded wallet for playing
dht bootstrap:    127.0.0.1:49737

Leave it running. Everything below talks to it via the printed bootstrap address and RPC keys.

2. Create a wallet and move money

export MORDECAI_WALLET_PASSPHRASE=dev
node packages/wallet/dist/cli.js create --keystore alice.json
node packages/wallet/dist/cli.js address --keystore alice.json

Sign a transfer (the CLI prints the canonical signed transaction as hex):

node packages/wallet/dist/cli.js transfer \
  --keystore alice.json --to <address> --amount 1000 \
  --nonce 0 --chain-id mordecai-devnet

Programmatic submission goes through the SDK (next step) or the RPC client; see CLI Tools for the full command reference.

3. Talk to the chain from code

import { Mordecai } from '@mordecai/sdk';
import { Wallet } from '@mordecai/wallet';

const { wallet, mnemonic } = Wallet.create(); // or Wallet.fromMnemonic(faucet)
const app = Mordecai.connect({
  wallet,
  nodeKey: Buffer.from('<rpc key hex>', 'hex'),
  storageDir: './app-data',
  chainId: 'mordecai-devnet',
  bootstrap: [{ host: '127.0.0.1', port: 49737 }],
});

const receipt = await app.transfer('<address>', 250_000n);
console.log(receipt.success, receipt.height); // finalized, with block height

4. Deploy a contract written in Python-like DSL

./compiler/mordecaic check compiler/examples/chess_wager.pysc
./compiler/mordecaic build compiler/examples/chess_wager.pysc -o build/wager --wasm
const { contractId } = await app.deploy(wasmBytes);
await app.execute(contractId, 'create', new Uint8Array(0), 100_000n); // 100k stake attached

5. Run the flagship example

The chess app plays a full wagered match — escrow on-chain, every move peer-to-peer — in under two seconds:

pnpm vitest run apps/chess

From here: read What a P2P App Is (and Isn’t) before designing your app — the on-chain/off-chain split is the one decision that shapes everything else.

Host the demo on Railway

The root Dockerfile builds and serves the website, documentation, wallet, faucet and all six demos in one service. It compiles all seven required demo contracts with Rust 1.94.1 and builds the book with mdBook 0.5.2. Only the HTTP gateway is public; the demo validators communicate inside the container.

Create the service

  1. Push the branch containing the Dockerfile to GitHub. In Railway, create a project and connect that repository and branch. Keep the root directory at the repository root. Railway detects the Dockerfile automatically.

  2. Attach a persistent volume to this service at /data before deploying. The launcher refuses to start on Railway without a volume. Image builds do not create the live network or its keys.

  3. Use these settings:

    SettingValue
    BuildDockerfile at repository root
    Start commandLeave empty; the image starts node scripts/node-demo.mjs
    Volume mount/data
    DEMO_DIR/data (already the image default)
    PORT8790, or Railway’s supplied port
    Healthcheck path/api/head
    Healthcheck timeout300 seconds
    Restart policyAlways
    Replicas1
    Serverless / sleepDisabled
  4. Deploy, then select Networking → Generate Domain. Match its target port to PORT. Railway provides HTTPS; a custom domain is optional. The first start creates the test network and deploys contracts before the gateway becomes ready.

  5. Open the generated URL. Create a new demo wallet, download its backup, claim test CAI, and choose a demo. Check the deployment with:

    node scripts/check-node-demo.mjs https://YOUR-SERVICE.up.railway.app
    

This command reads public endpoints; it does not create accounts or spend tokens. No wallet secrets, faucet keys, or local chain data are copied into the image. The first deployment generates its own identities on the volume. Local wallets, balances and worlds are not migrated automatically.

Railway’s older railway.json/railway.toml format is deprecated for new services. This setup uses Docker autodetection and service settings, without adding a deployment SDK to the application.

Persistence and updates

/data holds node identities, chain history, the deployment journal, Chess rooms, Microblog posts and tip associations. Bounties and game state are in the chains. Keep this volume attached across deployments and enable volume backups. Stop the service before making a manual filesystem copy so it is consistent.

Use a single service and volume. Expect a brief interruption when redeploying. Never clear /data merely to fix a failed deployment: that would create a different network and lose the existing demo state. If logs report a bootstrap payload mismatch after changing a contract, roll back the image and prepare a versioned contract migration.

The image builds contracts with a pinned Rust version. Changing that compiler or contract source can change deployment bytes, so treat those changes as network upgrades. Keep the same HEX_TIMEOUT_MS for an existing volume.

Railway proxy handling

On Railway the launcher enables MORDECAI_TRUST_RAILWAY_PROXY=1. The gateway uses Railway’s X-Real-IP for per-visitor faucet/feed limits, and X-Forwarded-Host for same-origin checks on Chess and Microblog writes. API responses are not cached. Outside Railway, forwarded headers are ignored unless explicitly enabled.

Expose this service through Railway’s HTTP/HTTPS edge only. Do not add a public TCP proxy or an alternative direct route to its gateway port while proxy trust is enabled. Review forwarded headers before adding another CDN in front.

Test locally with Docker

docker build --platform linux/amd64 -t mordecai-demo .
docker volume create mordecai-demo-data
docker run -d --name mordecai-demo -p 127.0.0.1:8791:8790 \
  --mount source=mordecai-demo-data,target=/data mordecai-demo
docker logs -f mordecai-demo

Once the gateway is ready, open http://127.0.0.1:8791 or run the check command against that URL. docker restart mordecai-demo reuses the same data. The image forwards termination signals to the launcher for orderly shutdown.

This is a public test-CAI demo, with all validators on one host. Faucet limits reset on restart, public posts require operator moderation, and the data store is intended for a small demo. Bounty submissions are public and permanent. A public demo does not make this a production or independently operated settlement network.

References: Docker deployment, volumes, network headers, healthchecks, and current configuration options.

Host the demo on Render

The root render.yaml Blueprint runs the node website, wallet, faucet, book and all six demos in one Docker web service. It includes a persistent disk at /data, port 10000, and the /api/head readiness check.

Deploy

  1. Open Deploy to Render. Alternatively, select New → Blueprint, connect StuartFarmer/mordecai, select branch main, and use render.yaml.

  2. Review the proposed resources and current cost. The Blueprint selects the paid 0.5c-512mb plan (formerly Starter), a 1 GB disk, and Frankfurt. Render’s free web services cannot attach persistent disks and are unsuitable for keeping this demo’s balances and worlds. No separate database is needed.

  3. Deploy the Blueprint. Leave the Docker start command unchanged. The first start creates the network and deploys its contracts before the health check passes. The launcher refuses to run on Render without a disk mounted at /data.

  4. Open the service’s HTTPS onrender.com URL. Create a demo wallet, download its backup, claim test CAI, and choose a demo. Verify all endpoints with:

    node scripts/check-node-demo.mjs https://YOUR-SERVICE.onrender.com
    

The smallest paid instance is a starting point for a small demo, not a measured concurrent-player capacity. Watch memory, CPU and disk usage; increase the plan or disk size as needed. Review the actual charge shown by Render before deploying.

Data and updates

Keep one instance and its disk. /data stores node identities, chain history, contract deployment receipts, Chess rooms and Microblog posts. The first deploy creates a new network; local wallets and balances are not migrated.

Code auto-deploys are disabled. To update, use Manual Deploy → Deploy latest commit after reviewing changes. Blueprint configuration changes can still auto-sync; set Auto Sync → No on the Blueprint if you want manual approval for those too. Deployments with a disk have a brief outage.

Never delete /data to resolve a deployment error. Back up the disk, keep the same contract compiler and HEX_TIMEOUT_MS, and plan migrations for changes to contract deployment bytes. A bootstrap payload mismatch should be investigated or rolled back rather than resetting the network.

Proxy and local verification

Render routes public requests through Cloudflare. The launcher enables MORDECAI_TRUST_RENDER_PROXY=1 and uses CF-Connecting-IP for visitor limits. It does not trust arbitrary entries in X-Forwarded-For. Same-origin writes use the request’s Host; Railway’s forwarded-host handling remains disabled. Keep the gateway behind Render’s public HTTP edge and do not proxy untrusted private-network requests directly to it with these headers.

To exercise Render startup locally, use a separate test volume:

docker build --platform linux/amd64 -t mordecai-demo .
docker run -d --name mordecai-render -p 127.0.0.1:8791:10000 \
  -e RENDER=true -e PORT=10000 \
  --mount source=mordecai-render-data,target=/data mordecai-demo
node scripts/check-node-demo.mjs http://127.0.0.1:8791

Wait for the gateway to become ready before running the check. Restarting the container retains the same network on the volume. All validators run on one host; this is a test-CAI demo, not a production settlement network. Public posts need operator moderation and bounty submissions are public and permanent.

References: Blueprint fields, persistent disks, compute plans, pricing, Render’s edge, and Cloudflare visitor headers.

The Two Planes

Most blockchains try to be the application platform. Mordecai deliberately does not. It splits the world into an application plane (fast, free, peer-to-peer, scaled by the users themselves) and a settlement plane (small, deterministic, globally agreed).

                          User
                            │
                     Pear Application
                            │
        ┌───────────────────┴───────────────────┐
        │                                       │
   Hypercore APIs                        Blockchain APIs
        │                                       │
 HyperDHT / Hyperswarm                Wallet / Contracts
        │                                       │
        └───────────────────┬───────────────────┘
                            │
                    Settlement Chain
                            │
                       Consensus (BFT)
                            │
                  Deterministic Global State

Layer map

Layer (spec §25)What it doesPackage(s)
L5 ApplicationsUI, game logic, media, simulationapps/*
L4 SDKswallet, payments, feeds, install@mordecai/sdk, @mordecai/wallet, @mordecai/pear-integration
L3 Smart contractsescrow, ownership, marketplaces@mordecai/vm, contracts/*, compiler/
L2 Settlement chainaccounts, blocks, consensus, RPC@mordecai/protocol, state, chain, consensus, node, rpc
L1 Holepunch networkdiscovery, transport, replication@mordecai/networking
L0 CryptographyEd25519, BLAKE2b, keystores@mordecai/crypto

Each layer depends only on the ones beneath it. Applications never touch consensus; consensus never executes application logic.

The core rule

Can every node deterministically reach the same conclusion?

If yes, the logic may belong on-chain (and only if it also needs global trust). If no — anything involving wall-clock time, network calls, randomness, media, or user interaction — it belongs in the application plane. This single question resolves nearly every design decision; the worked examples are in Three Kinds of State and What a P2P App Is (and Isn’t).

Division of labor at runtime

Connecting a native node starts all services for the selected network: state verification and replication, chain storage and serving, feed seeding, RPC, and an HTTP gateway. App connections automatically seed the registered bundle; apps select additional data feeds by key.

  • Validators do all of that and participate in consensus. Their keys are listed in the network’s fixed validator set.
  • Peers do all of that without proposing or voting. Their keys are not in the validator set. There is no separate seeder or gateway role to choose when connecting.

A node serves either the settlement chain or one application’s chain. An app-chain connection discovers configuration through a peer URL or an app ID resolved by settlement RPC; direct discovery requires no settlement. Neither path downloads settlement history. Browser-only clients still use a running node’s HTTP gateway because browsers cannot join the native DHT.

Three Kinds of State

Every piece of data in a Mordecai application belongs to exactly one of three categories (spec §3). Getting this classification right is the most important design decision an app developer makes.

Ephemeral state

Exists only while the app runs: mouse positions, voice chat, live cursors, network sessions, temporary AI context. Never stored, never replicated, never on-chain. Plain in-memory application code.

Shared state

Persistent application data that should replicate between peers but needs no universal agreement: chat history, documents, game moves and replays, images, community content.

Shared state lives in Hypercore feeds:

  • Append-only — history can’t be rewritten.
  • Signed — every entry is authenticated by the feed owner’s key; a peer relaying your chess moves cannot forge them.
  • Replicated on demand — peers holding a feed serve it to peers who want it, directly over encrypted connections.

Shared state is authentic but not authoritative: you can prove who wrote what and in what order, but nothing forces every node in the world to store or agree on it. That’s exactly right for application data.

Economic state

Information every participant must agree on forever: wallet balances, contract storage, token ownership, escrow, the application registry.

Economic state lives on-chain, in a key-value store committed to by a Merkle root in every block header:

PrefixContents
a: + pubkeyaccount {balance, nonce}
cc: + contract iddeployed WASM code
cs: + contract id + keyper-contract isolated storage
app: + app idregistry entries (owner, pear key, version, bundle hash)

It changes only through signed transactions, executed identically by every validator, finalized by BFT quorum. It is intentionally small — consensus is the expensive tier.

Worked examples (spec §15)

AppOff-chain (feeds)On-chain
Chessboard state, moves, clocks, chat, spectatorstournament entry, wagers, escrow, payout
Redditposts, comments, votes, mod logscommunity ownership, mod permissions, treasury
Marketplaceproduct images, search, reviewslistings, ownership, escrow, settlement
AI serviceprompts, inference, conversationmicropayments, subscriptions, usage accounting

The pattern: scarce things on-chain, everything else off. Currency, ownership, escrow, identity, governance — on-chain. Content, computation, communication — off.

A fourth lane: group state

Shared state assumes one author per feed. Some app data is genuinely multi-writer — two players contending for the same tile, a guild world’s resources — but still only matters to the app’s own peers, not to everyone. That data belongs on an app chain: the same chain stack, instantiated per-app by its players, anchored back to L1 by quorum attestation. The classification question generalizes to who has to agree? — nobody (feed), the app’s peers (app chain), everyone (L1).

Networking: Holepunch

The entire networking layer is the Holepunch stack — chosen because it is the most mature peer-to-peer toolkit in the JS ecosystem, and because the settlement chain itself can dogfood it.

The pieces

  • HyperDHT — a distributed hash table for peer discovery. Peers are addressed by public key, never IP; the DHT also performs NAT hole-punching so two home machines connect directly.
  • Hyperswarm — encrypted connection management over the DHT. Peers join 32-byte topics; the swarm finds other members and maintains direct Noise-encrypted sockets to them.
  • Hypercore — the append-only, signed, replicated log described in Three Kinds of State.
  • Corestore — manages many Hypercores in one storage directory and multiplexes them all over each swarm connection.

The @mordecai/networking wrapper

Applications use two classes:

const net = Network.create({ storageDir, bootstrap? });

const feed = await net.createFeed('chat');    // locally writable, named
await feed.append('hello');
await net.joinFeed(feed);                     // announce on the DHT

const remote = await net.openFeed(key);       // read-only, filled by peers
const first  = await remote.get(0);           // requests the block, waits

Every swarm connection replicates the whole Corestore: once two peers are connected for any feed, every feed they both have open syncs over that same socket. This is why a chess opponent’s reply feed needs no extra handshake — opening it by key is enough.

Practical rule: to wait for new data, prefer feed.get(index) (which actively requests the block from connected peers and resolves when it arrives) over polling feed.update() (which passively waits for announcements and can stall).

The chain runs on the same stack

The settlement chain has no separate TCP infrastructure:

  • Validators discover each other on a swarm topic derived from the genesis hash and gossip transactions, proposals, and votes over those connections (@mordecai/consensus).
  • Client RPC is @hyperswarm/rpc: applications dial a node by its public key over the DHT — no server URLs, works across NATs.
  • Lagging nodes catch up via block_request/block_response messages on the same mesh, verifying each block’s quorum certificate independently.

What networking does not guarantee

Peer discovery, encrypted transport, content authenticity, and efficient replication — yes. Economic correctness, ownership, identity, or global truth — never. A feed proves who said what; only the chain proves who owns what. (Spec §6, “Networking Guarantees”.)

The Settlement Chain

The chain is a deterministic trust engine shared by every application. It maintains accounts, executes contracts, and nothing else — no file storage, no app hosting, no media.

Accounts and identity

An identity is an Ed25519 keypair. The address is the z32-encoded public key (the same encoding hyperdht uses — one keypair works as wallet, feed owner, and app login). An account is {balance: u64, nonce: u64}; the nonce is a strictly sequential counter providing replay protection.

Transactions

Five payload kinds:

PayloadEffect
transfermove native currency
deploy_contractstore validated WASM; contract id = H(sender ‖ nonce ‖ code)
execute_contractinvoke an action, optionally attaching value
register_appcreate an owner-gated registry entry
update_appnew version/hash, only by the registering key

Every transaction carries chainId (cross-network replay protection), nonce, sender, maxFee, and an Ed25519 signature over a domain-separated canonical preimage.

Lifecycle

app builds payload → wallet signs → RPC submit_tx → mempool
  → gossip to validators → proposer includes it in a block
  → all validators execute identically → ≥2/3 vote → finalized
  → app polls waitForTx → receipt {success, fee, events, returnData}

Inclusion vs execution failure

Two distinct failure levels, both deterministic:

  • Non-includable (bad signature, wrong chain id, nonce mismatch, can’t cover the fee reserve, invalid WASM): the transaction cannot appear in a valid block at all. Proposers drop it; a block containing one is itself invalid.
  • Execution failure (insufficient balance, contract require/abort, out of fuel): the transaction is included; its payload effects revert atomically, but the fee is charged and the nonce consumed — so a failed transaction can never be replayed.

Fees

fee = FLAT_FEE + bytes + ceil(fuelUsed / FUEL_PER_FEE), always ≤ maxFee, paid to the block proposer. For contract calls, the sender’s balance must cover maxFee + value at inclusion; the unused reserve is refunded after execution. A hard MAX_FUEL cap bounds worst-case execution regardless of how high a fee the sender offers.

Blocks and state commitment

A block header binds: height, previous-block hash, timestamp, proposer, the Merkle root of its transactions, and the state root — a Merkle commitment over the entire key-value state after execution. Every validator recomputes the state root; any divergence is detected immediately. Block 0’s prevHash is the hash of the genesis config itself, tying the whole history to the exact initial conditions.

Execution uses layered overlays: each block builds a write set over the persistent store; each transaction gets a child overlay (discarded on failure); each cross-contract call gets a grandchild. Commit is atomic per block, and reopening a data directory verifies the stored state against the head’s state root.

Consensus

Mordecai v1 runs a deliberately simple fixed-validator BFT protocol (@mordecai/consensus). The goals, in order: safety (no two conflicting finalized blocks), immediate finality (no reorgs, ever), and simplicity. Open participation is explicitly out of scope for v1.

The protocol

  • The validator set is fixed in the genesis config. Quorum is ⌊2n/3⌋ + 1 votes.
  • The proposer for (height, round) is validators[(height + round) mod n] — a deterministic round-robin.
  • The proposer drafts a block from its mempool, validates it fully without committing, broadcasts it, and votes for its hash.
  • Every validator that receives the proposal re-executes it against its own head; if the state root matches, it votes.
  • A validator votes for at most one block hash per height and stays locked on it. When any hash gathers a quorum of votes, everyone holding the verified block commits it, storing the votes as the block’s finality certificate.
  • If a proposer is silent past the round timeout, the round increments and the next validator may propose.

Blocks are produced on demand — when there are pending transactions — not on a fixed tick, so an idle chain writes nothing.

Why one-vote-per-height is safe

Two conflicting quorums would require ≥ n/3 validators to vote for two different hashes at the same height. Honest validators never do (they lock on their first vote), so safety holds under the standard < n/3 Byzantine assumption — without implementing full Tendermint rounds.

The trade-off is liveness: there is no unlock rule, so if a proposer crashes after some validators voted but before quorum, that height can stall until those validators restart. This is a documented v1 gap (see the Threat Model); the common failure — a validator that is simply down when its proposer turn comes — is handled cleanly by round rotation and is covered by tests.

Certificates and catch-up

Every finalized block stores its quorum votes. This makes blocks self-verifying: a brand-new node syncs by requesting block ranges from any peer on the consensus mesh and, for each block, independently checks the proposer signature, re-executes every transaction, compares state roots, and verifies that the certificate carries ≥ quorum valid validator signatures over the block hash. The serving peer is completely untrusted.

Transaction gossip

Any node’s RPC accepts a transaction; after mempool admission it is broadcast to the mesh so every validator holds it. Mempools order per-sender by nonce and only feed proposers contiguous nonce runs.

What’s tested

The suite (packages/consensus, packages/node) proves: four validators converge to identical heads with ≥ quorum certificates; the chain keeps committing after the next-up proposer is killed (round skip); a late-joining observer syncs from genesis with certificate verification; and an RPC-submitted transfer settles identically on validators that never saw the submission.

The Contract VM

Contract execution must be bit-identical on every validator — any divergence forks the chain. Mordecai gets this with an unusual but simple construction: the wasmi interpreter, itself compiled to WebAssembly, running inside the node’s JS engine.

V8 (node process)
 └─ mordecai_vm_runtime.wasm        ← wasmi interpreter + validation (Rust)
     └─ contract.wasm           ← the contract, INTERPRETED by wasmi
          imports "env.*"  → bridged to →  "host.*" → JS state overlay

Why this design

  • Determinism: contracts are interpreted with wasmi’s deterministic fuel metering. The host JIT (V8) never executes contract code directly, so JIT tiering, platform float quirks, and timing never leak in.
  • Fuel: wasmi counts instructions exactly; the JS host separately meters host-call costs (storage reads/writes, transfers, events). Both meters are deterministic; out of fuel is the same on every validator.
  • Portability: the runtime artifact (packages/vm/wasm/) is committed, so JS-only development and CI need no Rust toolchain.
  • The wasmtime-native-binding route was evaluated first and rejected — the npm binding is unmaintained (see IMPLEMENTATION_PLAN.md D1).

Validation at deploy

A module is deployable only if it passes the runtime’s validator:

  • parses under a restricted feature set — no floats, no SIMD, no threads (the classic nondeterminism vectors are rejected wholesale);
  • imports nothing outside the contract ABI (env.*);
  • exports its linear memory.

Both the mempool and block execution enforce this, so invalid code never reaches state.

Execution limits

LimitValue
memory4 MiB
storage key / value256 B / 64 KiB
event size / count4 KiB / 64 per tx
return data64 KiB
cross-contract call depth4
fuelmin(MAX_FUEL, (maxFee − staticFee) × FUEL_PER_FEE)

Isolation and revert

Each contract owns a storage namespace (cs:<contract-id>:) that no other contract can touch; the only interaction is message passing via the call host function, and each sub-call executes in its own overlay so a failed callee reverts cleanly while the caller decides what to do with the status. A failed top-level action reverts everything — storage writes, attached value, payouts — while still consuming the fee and nonce.

The environment available to contracts (caller, attached value, block height, storage, transfer, emit, call) is documented in Rust Contracts & the ABI; no clock, randomness, network, or filesystem exists by construction.

App Chains

An app chain is the same chain stack that runs L1 — Chain, ConsensusEngine, the VM, the DSL — instantiated by an app’s own peers with a per-app genesis (SPEC_APPCHAINS.md). It is not new infrastructure: the node is a library, and an app chain is a second instantiation of it, discovered over the same swarm (topic = genesis hash), exactly the way an app instantiates a Hypercore feed.

That completes the state model. Ask of any piece of data: who has to agree to it?

who must agree?laneprimitive
nobody (one author)shared statehypercore feed
the app’s peersapp chainChain + VM + DSL, per-app
everyone (money)L1the settlement chain

A feed answers “what did this peer say, in order?” — single writer, no consensus needed. An app chain answers “what did the group decide, in order?” — the data structure you need the moment two players contend for the same tile. L1 answers “what does everyone owe everyone?” An app chain is, almost literally, a hypercore feed with a state machine and a referee attached.

Design invariants

  1. No value bridging. Nothing mints on an app chain against an L1 deposit. App-chain resources are native to it and die with it.
  2. Payments stay on L1. The only cross-chain artifact is the anchor: a quorum-attested statement “our chain reached state root R at height H”, optionally carrying one outcome call.
  3. L1 trusts exactly the app’s registered quorum for that app’s results, and nothing else. The blast radius of a corrupt app chain is the pot voluntarily staked against it. No shared bridge, no pooled risk.
  4. Anchors make forgetting safe. Once an epoch is anchored, the app chain’s block history is disposable. The permanent record is ~100 bytes on L1.
  5. Relayers are untrusted. Anyone may submit an anchor transaction; the attestation signatures are the authority.

How anchoring works

The registry entry (spec §17) carries the app chain’s validator set (chainValidators). From it, every joiner derives the same genesis — chainId = "app:" + appId, validators, fee-float allocations — so the genesis hash, which is the swarm topic, needs no coordination.

Each validator signs an attestation over anchorSigningBytes = domain ‖ l1ChainId ‖ appId ‖ epoch ‖ appHeight ‖ stateRoot ‖ call, and only signs what its own chain agrees with — a local lookup, no proofs. Signatures from more than 2/3 of the registered set make an anchor payload, relayed to L1 inside an ordinary fee-paying transaction. Execution verifies the quorum against the registry, requires a strictly increasing epoch (replay protection), records an:<appId> → {epoch, appHeight, stateRoot}, and — if an outcome call is present — runs it with a special sender:

appAddress(appId) = BLAKE2b-256("mordecai:app-sender:v1" ‖ appId)

A 32-byte account with no private key. Only an anchor quorum can act as it, so a contract authorizes its app with one line of ordinary DSL:

require(sender == config.game, "only the game may report")

No new DSL builtins, no host functions, no merkle proofs, no oracle. “The app chain calls an L1 function” is literally what happens.

Trust model, stated plainly

A quorum-signed state root gives finality attestation, not validity. If an app’s quorum colludes it can anchor a lie — and the damage is confined to whatever was voluntarily staked against that app on L1 (invariant 3). Because execution is deterministic and blocks replicate as feeds, anyone can replay and detect a bad anchor; automated adjudication (fraud proofs) is deliberately post-v1. Disputes and challenge windows are contract patterns, not protocol features: hold payouts N blocks, let a competing certificate freeze settlement.

Known v0.1 gap: co-signers vet the attested state root but not the outcome call’s semantics — a colluding quorum could mis-settle its own app’s escrow. Per-app call vetting on the co-signer is the next hardening step.

Lifecycle

Player-run chains are ephemeral by design. Spin a genesis per match or season, run at game-speed block intervals for ~zero fees, anchor the outcome, let the chain evaporate. L1 keeps the anchor and the settlement; peers keep the block history exactly as long as anyone cares to seed it — the same retention model as every other feed.

Wire Format & Protocol

Everything consensus-visible — transactions, blocks, votes, gossip — is encoded by @mordecai/protocol, a zero-dependency canonical codec. Canonical bytes are what get hashed and signed, so the format’s one rule is: every structure has exactly one valid byte representation, and decoding rejects anything encoding could not have produced.

Encoding rules

  • Fixed-width little-endian integers; u64 values are JS bigints end to end (never number — currency amounts must not lose precision).
  • Variable-length fields carry a u32 length prefix and a hard maximum, enforced on both encode and decode.
  • Strings are UTF-8, decoded in fatal mode.
  • Decode must consume every byte (Reader.finish()), or it fails — no trailing-byte malleability.

Domain separation

Signing preimages are prefixed with a domain tag so bytes signed for one purpose can never validate as another:

DomainSigns
mordecai:tx:v1transactions (by the sender)
mordecai:block:v1block headers (by the proposer)
mordecai:vote:v1consensus votes (by each validator)

Hashing is BLAKE2b-256 throughout. A transaction id is the hash of its full encoding; a block hash is the hash of its encoded header; a contract id is H("mordecai:contract:v1" ‖ sender ‖ nonce ‖ code).

Golden vectors

packages/protocol/test/vectors/golden.json pins the exact bytes of every structure. Any change to these vectors is a consensus-breaking protocol change and must be treated as one (regenerate deliberately with UPDATE_VECTORS=1 pnpm --filter @mordecai/protocol test). The vectors also serve as a conformance target for future non-JS implementations.

Gossip messages

Validator-to-validator traffic (length-prefixed frames over hyperswarm sockets, 16 MiB cap):

MessagePurpose
hello {height}advertise head; triggers catch-up in laggards
tx {bytes}relay an admitted transaction (canonical bytes, never re-encoded)
proposal {round, block}proposer’s block for the next height
vote {vote}signed pre-commit
block_request {from, count} / block_response {[block, votes[]]…}certificate-verified sync

Transport identity is deliberately unauthenticated — proposals and votes carry their own signatures, and sync responses are verified against certificates, so a malicious peer can waste bandwidth but never inject state.

Threat Model

The canonical threat model lives at docs/threat-model.md in the repository, next to the code it constrains. It is included here verbatim.

Threat Model (v1, first pass)

Scope: the v1 platform as defined in IMPLEMENTATION_PLAN.md — a fixed-validator settlement chain running over Holepunch, WASM contracts, and Pear applications with wallet integration. This document tracks what each layer trusts, what it must defend against, and which gaps v1 knowingly ships with. It follows the security boundaries in SPEC_PT_03 §26.

Assets

  • Private keys — user wallets, validator keys, app developer keys.
  • Economic state — balances, contract storage, the app registry.
  • Consensus integrity — one canonical, final block history.
  • Application authenticity — the bundle a user installs is the bundle the registered developer signed.
  • Availability — the chain keeps producing blocks; apps keep working peer-to-peer even when the chain is unreachable.

Trust boundaries

Identity / signatures

Every state transition is a signed transaction. Nothing unsigned is accepted.

  • Signing preimages are domain-separated (mordecai:tx:v1, mordecai:block:v1, mordecai:vote:v1) so bytes signed for one purpose can never validate as another.
  • chain_id in every signed message prevents cross-network replay; per-sender nonces prevent same-network replay.
  • Canonical encoding (one valid byte form per structure, enforced on decode) prevents malleability: a third party cannot produce a second valid encoding of a signed message.

Consensus

  • Safety assumption: fewer than 1/3 of the fixed validator set is Byzantine. With ≥ 2/3 pre-commits required for finality, two conflicting blocks cannot both finalize under that assumption.
  • Every validator re-executes every transaction; a proposer cannot invent state. State roots are cross-checked; divergence is detectable immediately.
  • Proposer timestamps are bounded by consensus rules and never read by contract execution (no wall-clock in the deterministic path).

Contracts (WASM sandbox)

  • Deterministic instruction set only: modules containing float opcodes are rejected at deploy; no clock, randomness, network, or filesystem host functions exist.
  • Fuel metering bounds execution; memory, call-depth, and storage-size caps bound resources. Out-of-fuel is a deterministic failure, identical on every validator.
  • Storage isolation: a contract can write only its own namespace. Cross- contract effects happen only via message passing (call), and the callee enforces its own rules.

Applications / wallet

  • Applications are trusted only by the user running them (§26). They never hold keys. They request signatures through the wallet, which mediates with per-app session permissions; payment-signing requires explicit user approval. “Auto-authenticate” must never mean “auto-sign.”
  • The registry binds app_id → pear_key → developer key. Installation verifies the bundle signature against the registry entry, not against whatever peer served the bytes.

Networking (Holepunch)

  • Hypercore guarantees feed authenticity and append-only history; it guarantees nothing about economic truth. No node treats gossip content as valid until signatures and consensus rules check out.
  • Transport is encrypted (Noise); peers are identified by public key, not IP.

Adversaries considered in v1

AdversaryVectorMitigation
Malicious peerSends malformed/oversized messagesStrict canonical decode, hard size limits, per-peer backoff
Malicious tx authorReplay, malleability, fee griefingNonces, chain_id, canonical encoding, max_fee + fuel accounting
Malicious proposerInvalid block, bad timestamp, censorshipFull re-execution by all validators, timestamp bounds, round-robin rotation
< 1/3 Byzantine validatorsEquivocation, vote withholding2/3 finality threshold; liveness degrades but safety holds
Malicious contractResource exhaustion, storage escapeFuel/memory/depth caps, namespace isolation, float rejection
Malicious appPhishing signatures, draining walletWallet-mediated signing, per-app permissions, explicit payment approval
Fake app distributorServing a tampered bundleRegistry-anchored developer signatures verified before launch

Known gaps accepted in v1 (must be revisited)

  1. ≥ 1/3 Byzantine validators breaks safety; the validator set is static and permissioned. Staking/rotation/slashing are post-v1.
  2. Consensus liveness under mid-vote proposer failure. v1 validators vote for at most one block hash per height and stay locked (so two conflicting quorums are impossible), but there is no Tendermint-style unlock: if a proposer crashes after some validators voted but before quorum, that height can stall until those validators restart. Safety is never at risk; full lock/unlock rounds are post-v1.
  3. No fee market — flat fees; a funded spammer can fill blocks. Mempool per-sender caps are a stopgap.
  4. Network-level DoS on the DHT/swarm (eclipse, sybil peers) is mitigated only by validator-to-validator direct connections, not solved.
  5. Key recovery — mnemonic backup only; no social recovery or rotation of a compromised wallet key.
  6. Privacy — all economic state is public; no confidentiality goals in v1.
  7. Light clients trust the block-log Hypercore feed plus quorum signatures; no fraud/validity proofs yet.

Each gap should either be closed or explicitly re-accepted at every subsequent milestone review.

What a P2P App Is (and Isn’t)

A Mordecai application is ordinary software that happens to be distributed. It runs on the user’s machine, renders its own UI, talks directly to other users’ machines, and consults the blockchain only when money or ownership changes hands. If you have built a client-server app, the mental shift is:

There is no server. The users who care about some data are its infrastructure. The chain is not your database — it is your escrow agent, land registry, and payment rail.

A p2p app IS

  • Locally executed. Game logic, rendering, AI inference, media playback all happen on-device. Apps keep working offline and sync when peers reappear.
  • Peer-replicated. Persistent app data lives in signed append-only feeds; peers exchange them directly (see Three Kinds of State).
  • Wallet-native. The user’s key is their account in every app — authentication is a signature over a challenge, not a password.
  • Economically able. Payments, escrow, and ownership are one SDK call, because every app shares the settlement chain.

A p2p app is NOT

  • A dApp in the Ethereum sense. Application logic does not run on-chain. There is no “web page that calls a contract for everything.” The contract is a small deterministic settlement program; the app is the product.
  • Trustless end to end. The chain is authoritative; the app is trusted only by the user running it (a malicious app can lie to its own user’s screen — which is why signing authority lives outside the app; see Wallets, Identity & Sessions).
  • Automatically consistent. Two peers’ feeds are each internally ordered, but there is no global order across writers. If your app needs universal agreement on something, that thing is economic state and belongs on-chain — or it needs an application-level merge rule (chess interleaves two single-writer feeds by ply; a forum would need multi-writer structures, a known v1 gap).

The design worksheet

For every piece of data, ask in order:

  1. Does anyone need it after the session ends? No → ephemeral, plain memory.
  2. Must every participant in the world agree on it, forever? No → shared state, put it in a feed. This should be ~95% of your data.
  3. Is it scarce — money, ownership, a unique name, an escrowed promise? Yes → economic state: a transfer, a registry entry, or a contract.

Then design the contract as the referee of last resort, not the game engine: it should verify claims and move value, never simulate gameplay. The wagered-chess contract never sees a chess move — it escrows two stakes and pays out when both players sign the same result. The signed move feeds exist as dispute evidence, not as contract inputs.

Trust boundaries you inherit

  • Feed entries are unforgeable but not unhostable — assume anything you put in a feed may be mirrored forever.
  • Whoever holds a feed’s key can append; nobody can rewrite. Design around append-only (e.g. “tombstone” entries instead of deletes).
  • The chain’s word is final: if the app’s local view disagrees with a finalized receipt, the receipt wins.

The SDK

@mordecai/sdk is the application-facing runtime (spec §22): one object that gives an app its identity, payments, contracts, app distribution, and replicated state.

import { Mordecai } from '@mordecai/sdk';

const app = Mordecai.connect({
  wallet, // any Signer: a local Wallet, or a RemoteSigner (see Identity)
  nodeKey, // RPC public key of any chain node (32 bytes)
  storageDir, // where this app's feeds live
  chainId, // e.g. 'mordecai-devnet'
  bootstrap, // optional; defaults to the public DHT
});

Blockchain API

Every call signs with the next account nonce, submits over hyperswarm RPC, and waits for finality — the returned TxInfo is a finalized receipt:

const r = await app.transfer(toAddress, 250_000n);
// r: { success, height, fee, events: hex[], returnData: hex, error? }

const { contractId } = await app.deploy(wasmBytes);

const r2 = await app.execute(
  contractId,
  'buy', // action (exported by the contract)
  new ContractArgs().u64(itemId).encode(), // args (see below)
  50_000n, // attached value (escrowed payment)
);

const acct = await app.account(); // { balance, nonce } as strings

A failed contract call returns success: false with the contract’s abort message in error — the fee was charged, but every state effect (including attached value) was reverted.

Argument encoding

ContractArgs matches the contract-side ArgReader and DSL parameters — values in declaration order:

new ContractArgs().u64(id).address(pubkey).str('hello').bool(true).encode();

(u64 = 8 bytes LE; bool rides as u64 0/1; str/bytes are u32-length-prefixed; address is a length-prefixed 32-byte key.)

Identity API

const auth = await app.authenticate(challengeBytes);
// { address, publicKey, signature } — verify with @mordecai/crypto verify()

Use this for app-level login: the counterparty sends a fresh challenge, the user’s signature proves control of the address. Never reuse challenges.

Shared-state API

const feed = await app.createFeed('chess-moves'); // writable, deterministic per name
await feed.append('e4');
await app.joinFeed(feed); // announce on the DHT

const theirs = await app.openFeed(key); // by 32-byte feed key
const move = await theirs.get(0); // requests + waits

App distribution API

await app.publishApp({ appId, version, bundle }); // feed + on-chain registration
const { entry, bundle } = await app.installApp(appId); // fetched + hash-verified

Details in Publishing & Installing Apps.

Patterns

  • One Mordecai per app instance. It owns a Corestore and an RPC session.
  • Sequential transactions per wallet. Nonces are strictly ordered; submit queries the account nonce each time, so awaiting each call is the simple correct pattern.
  • Events are polled, not pushed (v1): waitForTx polls the receipt. For app-to-app signaling, prefer feeds — that’s what they’re for.

Wallets, Identity & Sessions

One key, everywhere

An identity is an Ed25519 keypair. Because Hypercore uses the same scheme, one key serves as: the wallet (signs transactions), the feed owner (signs shared state), and the login (signs app challenges). The address is the z32-encoded public key.

@mordecai/wallet manages keys:

  • Wallet.create() → wallet + a 24-word BIP39 mnemonic (the only backup — shown once, never stored).
  • Keystore files encrypt the seed with argon2id + XChaCha20-Poly1305; the address is stored in the clear so tools can display it without the passphrase.
  • mordecai-wallet CLI: create, address, transfer (see CLI Tools).

The Signer boundary

Applications never hold keys. They program against the Signer interface:

interface Signer {
  address: string;
  publicKey: Uint8Array;
  signTransaction(params): Transaction | Promise<Transaction>;
  signMessage(message): Uint8Array | Promise<Uint8Array>;
}

A local Wallet implements it directly (fine for tools and tests). Real apps get a RemoteSigner instead — a proxy whose keys live in another process.

The wallet daemon (@mordecai/pear-integration)

The threat model’s rule is auto-authenticate must never mean auto-sign, and it is enforced by a process boundary:

┌────────────── app process ──────────────┐   ┌────────── wallet daemon ─────────┐
│ Mordecai.connect({ wallet: remoteSigner })  │──▶│ WalletDaemon                      │
│ RemoteSigner (no key material)          │IPC│  · unlocked Wallet (the keys)     │
└─────────────────────────────────────────┘   │  · per-app SessionGrant           │
                                              │  · allowance meter                │
                                              │  · ApprovalPrompt hook (UI seam)  │
                                              └───────────────────────────────────┘
// shell / daemon side
const daemon = await WalletDaemon.start({
  wallet,
  grants: { 'com.example.chess': { auth: true, spendLimit: 1_000_000n } },
  approve: async (req) => showPromptToUser(req),  // the future Pear wallet UI
});

// app side
const signer = await RemoteSigner.connect(daemon.publicKey, 'com.example.chess');
const app = Mordecai.connect({ wallet: signer, ... });

Enforcement is entirely daemon-side:

  • auth grant gates challenge signing — an app without it cannot even prove the user’s identity.
  • spendLimit is a session allowance; every transaction’s worst case (amount + attached value + maxFee) burns it down.
  • Overages escalate to the ApprovalPrompt with the app id, a payload summary, the cost, and the remaining allowance. Deny is the default.
  • Unknown app ids are refused at hello.

The transport is @hyperswarm/rpc, so the daemon can be local IPC today and a phone-as-signer tomorrow without app changes.

Publishing & Installing Apps

App distribution needs no store and no CDN: bundles travel peer-to-peer, and the chain is the authority on what code is legitimate (spec §17).

The registry

An on-chain entry per application id:

FieldMeaning
ownerthe developer key that registered it (only it may update)
pearKeythe Hypercore feed key holding the bundle
versiondisplay version
contractAddressthe app’s companion contract, or zeros
metadataHashBLAKE2b-256 of the bundle — the trust anchor

register_app creates an entry (first come, first served per app id); update_app replaces version/key/hash and is rejected for anyone but the owner. Both emit receipt events (app:registered:<id>).

Publishing

const { pearKey, tx } = await app.publishApp({
  appId: 'com.example.chess',
  version: '1.0.0',
  bundle: bundleBytes,
});

This appends the bundle to a feed, announces it on the DHT, and registers (appId, feedKey, hash) on-chain in one finalized transaction. Publishing a new version = append/replace the bundle feed + update_app with the new hash. Keep seeding the feed (your machine, a friendly peer, or any user who installed it — replication is store-and-forward).

Installing

const { entry, bundle } = await app.installApp('com.example.chess');

or from the command line:

mordecai-launcher install com.example.chess \
  --node <rpc-key-hex> --out ./chess [--bootstrap host:port]

Both do the same three steps:

  1. Registry lookup — ask any chain node for the entry.
  2. Swarm fetch — open the bundle feed by key and download from whoever has it. The serving peer is completely untrusted.
  3. Verify — recompute BLAKE2b-256 of the bundle and compare with the on-chain metadataHash. Mismatch → refuse to install.

The security property: a compromised mirror, a malicious peer, or even the developer’s own hijacked feed cannot ship different code than what the registered developer key committed to on-chain. Updates re-verify — new code runs only after a new hash is registered by the owner.

What launching means (today vs. the Pear shell)

Today the launcher writes the verified bundle plus its registry metadata to disk; running it under the real Pear desktop shell (pear run) — with the wallet-approval UI wired to the daemon’s ApprovalPrompt — is the remaining product milestone (see Roadmap). Everything underneath (verified install, sessions, remote signing) is built and tested.

The Web Gateway

Browsers can’t join HyperDHT — no UDP, no holepunching — so nothing in the network is reachable from a web page by itself. The gateway (@mordecai/gateway) is the browser-facing edge: a small HTTP server any node operator can run that translates JSON into hyperswarm RPC and serves a static frontend bundle.

GET  /api/connect                    public app-network connection document
GET  /api/config                     operator-provided app config
GET  /api/head                       chain head
GET  /api/account/<z32>              balance + nonce
GET  /api/tx/<hash>                  tx status (404 until it lands)
POST /api/tx {"tx": "<hex>"}         submit a signed, encoded transaction
GET  /api/app/<appId>                registry entry + latest anchor
GET  /api/contract/<id>/state[?prefix=<hex>]   contract storage entries
/*                                   static frontend (SPA fallback)

Every Node.start(...) and AppChain.join(...) starts this gateway automatically, for validators and ordinary peers alike. The connect CLIs print its HTTP URL; library callers use node.gateway.port (or app.node.gateway.port). Supply gateway: { port, staticDir, config } to customize it. Without a port, the library chooses an available one.

Without a custom staticDir (CLI: --static), the gateway serves a built-in Mordecai landing page at /. Its assets are bundled locally, and the page polls /api/head for the chain ID, height, and latest block hash. If chain data cannot be fetched, the readout shows the node as unavailable and retries automatically. Custom frontends continue to use SPA fallback; unknown paths on the default page return 404.

The landing page links to the full mdBook at /docs/, including the Field Guide for joining the network, creating a wallet, starting an app network, joining an app, and signing and submitting a payment. The old /guide, /guide/, and /guide.html URLs redirect to that chapter. A custom staticDir replaces both the built-in homepage and documentation.

node scripts/node-demo.mjs starts the persistent demo site on port 8790. Its Demos menu shares the in-memory wallet across Hex, Frontier, Outpost, Chess, Microblog and Bounties. Games receive a revocable signing/transaction interface, never the private key. Microblog posts are signed off-chain; tip attribution is stored before the browser broadcasts a reviewed payment. Bounty rewards and public responses live on the settlement chain. See the Microblog and Bounties guides.

pnpm build builds the packages and bundles the book in packages/gateway/public/docs/. Install mdBook 0.5.2 on the build machine; running the built node needs no mdBook process. After documentation edits, pnpm build:docs refreshes the bundled book. Missing documentation pages and assets return 404 rather than falling back to the homepage.

A separate gateway is still available when you want an independent web edge. Run one from code (Gateway.start({...})) or the CLI:

mordecai-gateway --node <rpc-key-hex> [--port 8787] [--static <dir>] \
             [--config <file.json>] [--bootstrap host:port,…]

Direct peer discovery

App nodes publish GET /api/connect independently of /api/config. The document contains version 1, appId, the serving peer’s nodeKey, genesisHash, ordered chainValidators, feedKeys, optional DHT bootstrap endpoints, and optional settlement metadata. Keys and hashes are 32-byte hex strings. The application chain derives its genesis from the app ID and validator set and checks it against genesisHash.

Only public connection fields are advertised. Frontend configuration, operator files and wallet keys are not copied into the connection document. Settlement-only gateways return 404 unless explicitly configured to advertise an app connection.

mordecai app connect --app <peer-url> uses this endpoint without contacting settlement. Fetches have a ten-second timeout and a 1 MiB response limit. A reverse proxy can expose a gateway under a path prefix; direct connection appends /api/connect to that prefix.

Why gateways are safe to not trust

Transactions arrive already signed — the browser holds the key and signs with @noble/curves over the same canonical bytes sodium signs in the wallet daemon (transactionSigningBytes). State is decoded client-side from raw storage entries. A gateway can refuse service; it cannot forge, tamper, or spend. Gateways are therefore interchangeable: any of N independent operators can serve any app, and the escape hatch from the web tier is always the real thing — install the app over the swarm.

An app-chain node’s built-in gateway gives a browser the same JSON surface for game state — that’s how the outpost example serves a two-chain UI from plain fetch() (see Outpost).

Working example: scripts/frontier-demo.mjs + apps/frontier-web — the frontier land game played entirely from a browser, with in-browser signing and no backend beyond the gateway.

How-To: Run Your App on Its Own Chain

This walks through the whole app-chain lifecycle with @mordecai/appchain: start or discover, join, play, and optionally anchor and settle. The finished version of every step is packages/appchain/test/market.test.ts and scripts/outpost-demo.mjs.

When you want one

Use a feed when one author owns the data. Use an app chain when the group’s agreement is the data: contended game state, shared rules, anything that must survive any single player leaving — and especially anything L1 money will settle on. Contracts encode the referee (legality, resources, outcomes); the app keeps everything else (rendering, search, AI, UI).

Start without settlement

App networks can run independently. Create a persistent identity first:

mordecai app init --dir ./game

Then start the first peer from your app’s Node.js entry point:

import { readKeyFile } from '@mordecai/node';
import { AppChain } from '@mordecai/appchain';

const keyPair = readKeyFile('./game/peer.key');
const game = await AppChain.start({
  appId: 'com.example.game',
  chainValidators: [keyPair.publicKey],
  keyPair,
  dir: './game',
  gateway: { port: 8787 },
  // feedKeys: [bundleFeedKey, sharedDataFeedKey],
});

Share the machine’s reachable gateway URL. Another participant can join:

mordecai app connect --dir ./my-game --app http://192.168.1.20:8787

Or use AppChain.connect('http://192.168.1.20:8787', { dir: './my-game' }). The peer reads /api/connect, verifies the connection document’s structure and genesis hash, and joins the advertised native peer network. The URL is an introduction, not a permanent central server. Every joined app peer serves the same network configuration with its own RPC key.

Both roles seed the advertised feed keys and run HTTP access. A key in chainValidators also votes; every other key participates without voting. The source URL supplies the initial trust configuration. An existing data directory rejects a different genesis rather than switching networks.

Settlement is optional. When you register this app later, use the same app ID and validator order so the derived genesis stays identical. Settlement contracts and anchoring remain separate setup. You may advertise optional settlement: { nodeKey, chainId, bootstrap } metadata from AppChain.start. Direct joins do not contact that settlement node automatically.

The following sections describe the registry-based entry path and optional settlement integration.

1. Register the app with its validator set

The registry entry is the root of trust. For a match or guild world, the validators are simply the players’ wallet keys:

await mordecai.publishApp({
  appId: 'com.example.outpost',
  version: '1.0.0',
  bundle,
  chainValidators: [alice.publicKey, bob.publicKey],
});

Rotation is an owner-gated update_app with a new set; the current set at execution time judges each anchor.

2. Join the chain

Every peer derives the same genesis from the registry entry alone:

import { AppChain } from '@mordecai/appchain';

const game = await AppChain.join(l1Rpc, 'com.example.outpost', {
  dir: './outpost-chain',
  // keyPair: myKeys, // optional; otherwise creates/reuses dir/peer.key
  blockIntervalMs: 300, // game speed, not L1 speed
});
await game.waitForPeers(1); // let the mesh form before the first move

Joining starts the HTTP gateway, chain verification and replication for both roles. It also downloads and seeds the registered app bundle. game.node.gateway.port is the browser API port; game.node.network provides feed access. Pass feedKeys for other app-selected feeds, or call game.node.network.seedFeed(key) for feeds discovered while running. These dynamic subscriptions must be selected again when the app reconnects. No bundle is automatically executed.

Validators automatically answer anchor_sign on their node endpoint — dialed by the same keys the registry publishes, so there is no extra discovery. Ordinary peers sync, verify, store and serve data without voting.

3. Deploy the rules and play

The app chain runs the same VM and DSL as L1, so game rules are ordinary contracts, deployed and executed with the same transaction format — just against chainId: "app:" + appId, at your block interval, with fees that cost nothing real (the genesis gives validators a fee float; app-chain currency is valueless by design). Moves never touch L1.

4. Anchor, with an outcome

One validator runs the daemon (any validator; several is fine — epochs come from L1, so they converge):

import { AnchorDaemon } from '@mordecai/appchain';

const daemon = new AnchorDaemon({
  chain: game.chain,
  appId: 'com.example.outpost',
  validators: [alice.publicKey, bob.publicKey],
  keyPair: myKeys,
  l1: { chainId, nodeKey, bootstrap },
  relayer, // any funded L1 account; untrusted
  epochIntervalMs: 5_000, // or call daemon.anchorNow() yourself
  outcome: async (chain) => {
    // Read your own chain, decide what L1 should hear. One call per epoch.
    const fills = await chain.getContractState(gameContract, prefix('s:Delivery:'));
    return pickSettlement(fills) ?? null; // {contract, action, args} | null
  },
});

The daemon builds the attestation from the chain head, self-signs, collects co-signatures (each co-signer refuses anything its own chain disagrees with), and relays the anchor to L1. Nothing anchors while the chain is idle.

5. Gate the L1 contract on the app

The receiving contract needs exactly one line of authorization:

contract GoodsMarket:
    config:
        game: address          # set to appAddress(appId) at init

    action settle(order_id: int, seller: address):
        require(sender == config.game, "only the game may settle")
        ...

appAddress(appId) is exported by @mordecai/chain (node side) and @mordecai/sdk (app side, Bare-safe). Design the contract so the app’s authority is scoped: it can report outcomes, never touch stakes it wasn’t given, and a cancel_after(deadline) refund path covers the quorum dissolving without reporting.

6. What to test

Mirror market.test.ts: the happy path (escrow → play → anchored outcome → payout), then the adversarial set — replayed anchors (stale epoch), sub-quorum and outsider signatures, direct calls impersonating the app, double settlement. All of those are receipt-level assertions against in-process chains; the whole suite runs in seconds.

Ops notes

  • Old data dirs: anchors shipped with PROTOCOL_VERSION 2; devnets from before it need fresh data dirs.
  • Browser UIs: use the node’s built-in gateway; pass gateway: { port, staticDir, config } to configure it. Its JSON surface is identical to L1’s.
  • Disposal: after the last anchor of a season, the chain’s data dirs can be deleted. L1 keeps the anchor and the settlement forever.

The Contract Model

Smart contracts are deterministic economic programs — not applications (spec §11). A contract executes only when a transaction invokes it, runs to completion in a fuel-bounded sandbox, and exits. It cannot render, wait, schedule, or talk to the network.

What contracts define / don’t

Contracts defineContracts never do
ownership rules, escrowrendering, UI
payment logic, settlementnetworking, storage replication
marketplaces, wagers, auctionsgameplay simulation
permissions, governanceAI, media

Deploy

deploy_contract with the WASM bytes. The module is validated (no floats / SIMD / threads, only ABI imports — see The Contract VM) and stored in consensus state. The contract id is H("mordecai:contract:v1" ‖ sender ‖ nonce ‖ code) — deterministic, returned in the receipt’s returnData.

A contract id is also an account: contracts hold native currency balances, receive attached value, and pay out with transfer.

Execute

execute_contract { contract, action, args, value }:

  1. If value > 0, it moves from the sender to the contract’s account before the action runs (the contract sees it as attached_value).
  2. The exported action function runs against the contract’s isolated storage namespace, metered by fuel bought with maxFee.
  3. Outcomes:
    • return 0 → success; storage writes, payouts, and events commit; returnData carries whatever the contract set.
    • abort / non-zero return / trap / out of fuel → everything reverts, including the attached value — but the fee is charged and the nonce consumed. The abort message lands in the receipt’s error.

This all-or-nothing semantic is what makes patterns like “attach the exact price; the contract pays the seller and flips ownership” safe — there is no partial state in which the buyer paid but didn’t receive.

Events and return data

emit(bytes) appends to the receipt’s event list (≤64 events, ≤4 KiB each, kept only on success). set_return(bytes) fills returnData. Both surface through RPC get_tx, so apps read outcomes from receipts — there is no on-chain event log to query separately.

Cross-contract calls

Contracts interact only by message passing (spec §12): call(contract, action, args, value) runs the callee with the calling contract as caller, in its own overlay, sharing the fuel budget, to a depth of 4. The callee’s status comes back; its storage stays its own.

Two ways to write one

  • The Pythonic DSL (recommended): tutorial and reference. Compiles to Rust and then WASM with checked arithmetic and enforced structure.
  • Rust directly against contracts/runtime-rs: Rust Contracts & the ABI. Full control; you enforce your own discipline.

Both compile to the identical ABI — the chain cannot tell them apart.

Tutorial: A Wager Contract in the DSL

We’ll build the escrow contract the chess app uses, from scratch. It’s the full compiler/examples/chess_wager.pysc that ships in the repo.

The job: two players each escrow a stake; the game happens elsewhere (off-chain, over feeds); when both players report the same winner, the pot pays out. The contract is the referee of last resort — it never sees a chess move.

1. Declare the contract and its state

contract ChessWager:

    state Meta[int]:
        next_id: int = 0

    state Match[int]:
        creator: address
        opponent: address
        stake: int
        # 0 = open, 1 = active, 2 = settled or cancelled
        phase: int = 0
        creator_reported: bool = False
        opponent_reported: bool = False
        creator_pick: address
        opponent_pick: address

state Name[key_type]: declares a map in the contract’s isolated storage. Fields with defaults are optional at construction; a map whose fields all have defaults (like Meta) reads as the default instance when missing — which is how Meta[0].next_id works before anything is written.

2. Create a match — money in

    action create():
        require(value > 0, "attach a stake to create a match")
        match_id = Meta[0].next_id
        Meta[0].next_id += 1
        Match[match_id] = Match(
            creator=sender,
            opponent=sender,
            stake=value,
            creator_pick=sender,
            opponent_pick=sender,
        )
        emit("match created")

Three builtins do the heavy lifting: sender (the signing key), value (currency attached to this call — already credited to the contract’s account when the action runs), and require(cond, msg) — on failure the whole call aborts and everything reverts, including the attached value. Fields without a natural initial value (opponent, the picks) are seeded with sender as a placeholder; phase guards against reading them as meaningful.

3. Join — matching stake, no self-play

    action join(match_id: int):
        m = Match[match_id]
        require(m.phase == 0, "match is not open")
        require(sender != m.creator, "cannot play against yourself")
        require(value == m.stake, "attached value must match the stake")
        m.opponent = sender
        m.phase = 1
        emit("match joined")

m = Match[match_id] binds a state handle; reading a missing entry of a non-defaultable map aborts with no such Match entry. Writes through the handle persist immediately. After join, the contract’s account holds 2 × stake.

4. Settle — money out, only on agreement

    action report(match_id: int, winner: address):
        m = Match[match_id]
        require(m.phase == 1, "match is not active")
        require(winner == m.creator or winner == m.opponent,
                "winner must be one of the players")
        if sender == m.creator:
            m.creator_pick = winner
            m.creator_reported = True
        elif sender == m.opponent:
            m.opponent_pick = winner
            m.opponent_reported = True
        else:
            require(False, "only the players can report a result")

        if m.creator_reported and m.opponent_reported:
            if m.creator_pick == m.opponent_pick:
                m.phase = 2
                transfer(m.creator_pick, m.stake + m.stake)
                emit("match settled")

transfer(to, amount) pays out of the contract’s own balance and aborts the action if it can’t. Note the disagreement case: each player reports once (the flags), so a disputed match simply never settles and the pot stays escrowed. A production version would add a timeout or arbiter path; the signed move feeds exist precisely as dispute evidence.

Add cancel (creator-only, phase 0, refunds the stake) and you have the complete shipped contract.

5. Compile, deploy, drive it

./compiler/mordecaic check  compiler/examples/chess_wager.pysc
./compiler/mordecaic build  compiler/examples/chess_wager.pysc -o build/wager --wasm
const { contractId } = await app.deploy(wasm);
await alice.execute(contractId, 'create', new Uint8Array(0), 100_000n);
await bob.execute(contractId, 'join', new ContractArgs().u64(0n).encode(), 100_000n);
// … play chess over feeds …
await alice.execute(contractId, 'report', new ContractArgs().u64(0n).address(aliceKey).encode());
await bob.execute(contractId, 'report', new ContractArgs().u64(0n).address(aliceKey).encode());
// → receipt events include "match settled"; alice's balance grew by 2×stake

The end-to-end version of exactly this flow is the test in apps/chess/test/chess.test.ts.

DSL Language Reference

The Mordecai contract language is a small, deliberately constrained, Python-like language (spec §21). Source files use the .pysc extension and compile through mordecaic: parse → static verification → generated Rust → wasm32. Only verified deterministic code reaches the chain; the compiler guarantees checked arithmetic (overflow aborts), per-map storage prefixes, atomic revert on failure, and write-once config — regardless of what the source does.

File structure

contract Name:

    config:                     # optional; at most one block
        field: type

    state MapName[key_type]:    # any number of maps
        field: type
        field: type = default   # literal defaults for int/str/bool

    action name(param: type, ...):
        ...statements...

Types

Exactly four scalars: int (u64, checked), str (UTF-8), bool, address (a 32-byte key). No floats, ever. State-map keys may be int or address. Address fields cannot have defaults.

Builtins

NameTypeMeaning
senderaddressthe transaction signer, or the calling contract in sub-calls
valueintnative currency attached to this call
heightintheight of the block being executed

All three are read-only.

Statements

require(cond)                       # abort with "requirement failed"
require(cond, "message")            # abort with your message; all effects revert

x = expr                            # bind a local (type fixed at first assignment)
x += expr / x -= expr               # int only, checked

m = Map[key]                        # bind a state handle
m.field = expr                      # field writes persist immediately
Map[key] = Map(field=expr, ...)     # construct/overwrite an entry
Map[key].field += expr              # in-place entry update

transfer(to_addr, amount)           # pay from the CONTRACT's balance; aborts on failure
emit("message")                     # append a receipt event

if cond: ... elif cond: ... else: ...

There are no loops, no functions, no imports, no recursion, no randomness, no clock (v1 keeps deterministic bounds trivially). while, for, def, return, class, floats, and f-strings are rejected at parse time.

Expressions

  • Arithmetic: +, - (int, checked — overflow/underflow aborts).
  • Comparison: ==, != on any scalar; <, <=, >, >= on int only. No chained comparisons.
  • Boolean: and, or, not.
  • exists(Map[key]) → bool.
  • byte_len(text) → int: UTF-8 byte length of a str. Use this to bound public text stored by a contract; multibyte characters can occupy more than one byte.
  • config.field — read-only access to config.
  • Map[key].field — read a field without binding.

State semantics

  • Reading a missing entry of a map whose fields all have defaults yields the default instance. Reading a missing entry otherwise aborts (no such <Map> entry).
  • Constructing an entry requires every field without a default.
  • State handles (m = Map[k]) cannot be reassigned, compared, or passed around as values — access their fields.

Config and init

If a config: block exists, the compiler generates an init(...) action taking the config fields in declaration order. It can be called exactly once (anyone may call it — deploy and init in one breath); every other action that touches config aborts until then. Config is immutable after.

Action ABI

Each action becomes an exported WASM function. Callers encode arguments in declaration order with the SDK’s ContractArgs (u64 LE for int, u64 0/1 for bool, length-prefixed UTF-8 for str, length-prefixed 32 bytes for address). Match ids and similar values your contract creates are best emitted as events or made derivable (e.g. sequential).

Compiler CLI

./compiler/mordecaic check  contract.pysc          # parse + verify only
./compiler/mordecaic build  contract.pysc -o out/  # emit the cargo project
./compiler/mordecaic build  contract.pysc -o out/ --wasm   # …and compile it

Reserved words you can’t use as identifiers include the statement keywords, the builtins, and names the generated Rust uses (config, key, storage, Rust keywords). The verifier reports collisions with line numbers.

Rust Contracts & the ABI

The DSL is a frontend; the actual contract interface is a small WASM ABI that any language can target. Rust contracts use the mordecai-contract crate (contracts/runtime-rs) — the shipped counter and marketplace contracts are written this way.

Shape of a contract

#![allow(unused)]
fn main() {
use mordecai_contract as c;

#[unsafe(no_mangle)]
pub extern "C" fn buy() -> i32 {          // one export per action
    let mut args = c::ArgReader::new();
    let item_id = args.u64();

    let Some(raw) = c::storage_get(&key(item_id)) else {
        c::fail("no such item");          // abort: everything reverts
    };
    // ... decode, check, mutate ...
    c::storage_set(&key(item_id), &encoded);
    c::emit(b"sold");
    0                                     // 0 = success; non-zero = failure
}
}

Compile with crate-type = ["cdylib"] to wasm32-unknown-unknown (scripts/build-wasm.sh shows the exact invocation). The module must export its memory (Rust cdylibs do by default) and import nothing beyond the ABI below — validation enforces this at deploy.

The mordecai-contract API

FunctionMeaning
storage_get(key) -> Option<Vec<u8>>read own namespace
storage_set(key, value) / storage_del(key)write / delete (key ≤ 256 B, value ≤ 64 KiB)
caller() -> [u8; 32]tx sender, or calling contract id in sub-calls
attached_value() -> u64currency attached to this call (already credited)
block_height() -> u64height of the enclosing block
args() -> Vec<u8> / ArgReaderraw argument bytes / cursor (u64, bytes, address)
set_return(bytes)fill the receipt’s returnData
emit(bytes)append a receipt event (≤ 4 KiB, ≤ 64/tx)
fail(msg) -> !abort with a message; all effects revert
transfer(&to, amount) -> boolpay from the contract’s balance
call_contract(&id, action, args, value) -> i32message another contract (depth ≤ 4)

That is the entire environment. No clock, no randomness, no I/O — if it isn’t in this table, a contract can’t do it, which is exactly what makes execution reproducible across validators.

Discipline the DSL gives you for free

Hand-written Rust must self-enforce what the DSL compiler guarantees:

  • Checked arithmetic. Release-profile Rust wraps on overflow — use checked_add/checked_sub (or overflow-checks = true) for anything touching balances.
  • Deterministic encodings. Fixed field order, little-endian integers, length-prefixed strings. Never serialize a HashMap.
  • No panics with meaning. panic = "abort" traps generically; prefer c::fail("reason") so users see why.
  • No floats anywhere — validation rejects the whole module if LLVM emits a single float opcode (test with VmRuntime.validate before deploying).

Testing without a chain

@mordecai/vm executes a module directly against an in-memory host — see packages/vm/test/vm.test.ts for the pattern (map-backed storage, captured events, fuel assertions). Full-chain tests deploy through a real Chain as in packages/chain/test/contracts.test.ts.

Web wallet → faucet → Hex

Hex is the example for bringing your own browser wallet. One operator runs the demo network; players only need a browser and their own test-wallet keys.

Run Hex inside the node site

pnpm build
node scripts/node-demo.mjs

Open http://127.0.0.1:8790. Create/load a wallet, use the Faucet tab, then choose Demos → Hex. The same in-memory wallet signs game actions and L1 stakes; no second key import is needed. Closing it in Wallet disconnects Hex. Create a room and use Copy room link to invite another player with a different wallet. A fresh visitor can join from that link. The same Demos menu also opens Frontier, Outpost, and Chess, using the loaded wallet. Frontier and Outpost each have one persistent shared world; Chess uses invitation rooms.

The node-demo L1 faucet grants 10,000,000 base units, enough for the default 1,000,000-unit stake plus fees. Hex requests app-chain fee tokens separately. The existing address/IP cooldown applies, so two browsers sharing an IP must wait a minute between faucet claims. Public users reach one HTTP origin; the app API is mounted at /api/demos/hex/api/.

The launcher stores identities, chain data and signed deployment records in .mordecai-demo/ (git-ignored). Restart with that directory to resume balances, rooms and contracts. Back up the directory privately: it contains unencrypted operator test keys with restrictive file permissions. Do not run two hosts on one data directory. Keep the same contract binaries and timeout configuration; changed bootstrap payloads fail explicitly rather than redeploying silently.

Use PORT=8805 DEMO_DIR=/path/to/demo node scripts/node-demo.mjs to choose the HTTP port and data directory. This starts a persistent local test network; it does not attach to a different running preview chain. For public HTTPS, terminate TLS in front of this HTTP origin and keep the process/data directory persistent. No domain or public deployment is configured by this command.

Start the standalone demo

From the repository root:

pnpm build
pnpm --filter @mordecai/example-hex-web build
node scripts/hex-demo.mjs

The script starts a fresh three-validator L1, a two-validator Hex app chain, contracts, faucets, and settlement. It prints these default URLs:

ServiceURL
Hex gamehttp://127.0.0.1:8787
Web wallet on Hex’s L1http://127.0.0.1:8787/wallet.html
App-chain APIhttp://127.0.0.1:8788
Demo faucet for both chainshttp://127.0.0.1:8789

To choose different ports, use PORT=8800 node scripts/hex-demo.mjs; the app API and demo faucet use the next two ports. Leave the terminal running. Ctrl-C stops the demo. Each restart creates a new network with fresh balances and games.

1. Create and back up a wallet

Open the web wallet on the Hex gateway and click Create wallet. The browser generates an Ed25519 key and displays its public address. Click Download private key before leaving the page.

The JSON backup contains an unencrypted private key. Keep it private and use this wallet only for test tokens. The page holds the key in memory; reloading or closing it clears the loaded wallet. Neither the gateway nor the faucet receives your key. The explicit Show private key button reveals its 64 hexadecimal characters when needed.

To return to an existing wallet, load its JSON backup or paste the private key. Both a 32-byte Ed25519 seed (64 hex characters) and a 64-byte libsodium secret key (128 hex characters) are accepted. The latter’s public-key half is verified. This web backup is distinct from the CLI’s encrypted keystore; mnemonic and encrypted CLI-keystore import are not implemented.

2. Claim test CAI

Open the Faucet tab; it is pre-filled with your loaded wallet’s public address. Click Get test CAI, wait for Transfer confirmed, and check that the balance increased by 10,000 base units. View transaction opens the receipt.

This generic faucet has a one-minute address/IP cooldown and a 100-claim hourly limit. Its funds are on Hex’s L1 network because you opened the wallet from that gateway. A wallet opened on another node reads and funds that node’s network.

Send tokens or submit a transaction

On the standard node site, choose Wallet in the top navigation (/#/wallet). Home/Wallet/Faucet navigation keeps the loaded key in memory. Wallet shows the create/load controls until a wallet is open. Close wallet clears its draft and returns to those controls. Documentation, API, and GitHub open separately. Custom demo sites expose the same wallet at /wallet.html.

After funding, enter a recipient address and a whole number of CAI base units under Send CAI. Choose Review transfer, check the network, recipient, amount, and maximum fee, then Confirm and send. The 1,000-unit fee ceiling must fit in your balance alongside the amount; the receipt shows the actual fee.

To sign another transaction with the loaded wallet, expand Sign and submit a transaction. Paste an unsigned hexadecimal payload and set its maximum fee. The wallet supplies the network, sender, nonce, and signature; review the decoded details and choose Confirm and send. The payload supports every protocol transaction type. This field takes payload bytes, not a complete signed transaction.

For example, prepare a contract-call payload in a script using the protocol package:

import { encodePayload } from '@mordecai/protocol';

const payload = encodePayload({
  kind: 'execute_contract',
  contract: Buffer.from(contractAddressHex, 'hex'),
  action: 'play',
  args: encodedActionArguments, // Uint8Array in the contract's expected format
  value: 0n,
});
console.log(Buffer.from(payload).toString('hex'));

Use the actual contract address, action, and encoded arguments from your dapp. The wallet checks the payload format and funds; the node validates the contract call. Failed execution may still charge a transaction fee.

The session list tracks submissions until a receipt reports confirmation or failure. If the response is lost, keep the tab open and use Retry the same transaction: it sends identical bytes. Do not create another payment merely because confirmation is delayed. History and pending state clear on reload.

3. Load the same wallet into Hex

Click Back to node or game, then load the downloaded JSON file in Hex’s wallet chooser. You can also paste the same private key. Check that the address matches your web wallet. Existing Hex users can choose Use saved Hex wallet; their legacy saved key is preserved. New imported or generated keys are kept in memory, so load them again after refreshing.

Hex’s separate demo faucet automatically supplies the larger test amounts needed for this game: 10,000,000 L1 units and 1,000,000,000 app-chain fee units when either balance is low. Wait for the funding message before creating or joining a game. The two faucets use separate funded wallets, so they do not share transaction nonces. The old demo faucet is a local demonstration service, not a hardened public faucet.

4. Play with a second wallet

  1. Player A enters a new game code, such as my-first-hex, and clicks create game. The default stake is 1,000,000 test CAI units on L1.
  2. Player B opens the same site in another browser/profile or on another machine, creates a different wallet, and enters the same code. Click join game to match the stake. Two copies of the same private key are the same player.
  3. Red moves first. Click an empty hexagon on your turn. Red connects top to bottom; blue connects left to right.
  4. When a player connects their edges, the browser submits the winning path. Alternatively, resign to test settlement quickly. A player who takes more than three minutes forfeits when the opponent’s browser claims the timeout.
  5. Wait for pot paid out on L1. The anchor daemon carries the game outcome to L1, which pays the winner’s address. Refresh that wallet’s L1 balance.

For another player on a different machine, replace 127.0.0.1 with the host’s reachable address. This demo uses HTTP and adjacent ports; expose it only on a trusted test network. Public HTTPS hosting needs matching routes for the app API and demo faucet as well.

What carries between networks?

Your private key determines one public address, usable on multiple chains. Balances, transaction nonces, and game state belong to each chain separately. Funding mordecai-preview does not fund mordecai-hex-devnet, even with the same address. There is no token bridge in this walkthrough. The Hex app chain’s fee float is separate from the L1 CAI escrow and is valueless by design.

The integrated Frontier and Outpost demos share this wallet and settlement L1. Their standalone scripts retain the separate Alice/Bob development-account mode. Outpost has its own app-chain fee faucet; use Fund app fees inside Outpost before claiming land or delivering goods.

Chess: browser rooms and native P2P matches

The node site offers Demos → Chess. Load a wallet in Wallet, fund it from Faucet, and create a room with a positive integer stake in base units. Copy the invitation to another browser with a different wallet. The creator plays white; the joiner matches the stake and plays black. Extra visitors can spectate.

Select a piece and destination to move; choose a promotion piece before moving a pawn onto its last rank. The board validates legal moves, checkmate, stalemate, repetition and other automatic draws. Players can resign or offer/accept a draw. Both players must then use Report result on L1. The page keeps settlement pending until confirmed contract state closes the wager. Each side’s report is shown separately; submitting a local game result does not itself pay out.

Active stakes can remain locked if a player refuses to report or abandons a match. There is no automatic adjudication or active-match timeout. Only the creator can cancel before an opponent joins. Matching draw reports refund each stake, less transaction fees already paid. Keep enough balance for fees.

The browser uses a same-origin signed-message relay, not direct HyperDHT. Messages bind the chain, deployed contract, room, sequence, previous hash and action to the wallet signature. Host and browser replay the same signatures and rules using chess.js 1.4.0, distributed under its BSD-2-Clause license. The host verifies confirmed wager membership before accepting play. A room-key mapping on L1 binds each creation to its match even when several users create simultaneously. A host can withhold service, but cannot forge player messages.

Room histories survive host restart. Reopen the invitation and load the same wallet to resume. Retry an uncertain move with Retry identical signed message; accepted identical retries do not append again. If registration was interrupted after creating the wager, use Recover room registration and, if needed, paste the confirmed creation hash from Wallet history. Only public receipt hashes are saved by the game. Closing or replacing a wallet revokes further sends/signatures.

apps/chess remains the native Hypercore example. Its transport and WagerClient API are unchanged; the browser client lives in apps/chess-web.

The split

ConcernWhereMechanism
moves, turn orderoff-chaintwo Hypercore feeds, one per player
chat, clocks, spectatingoff-chainmore feeds (not in the demo)
stakes, escrow, payouton-chainChessWager contract (written in the DSL)
identityboththe same key signs feeds and transactions

Playing (src/match.ts)

Each player owns one append-only feed; the host plays white. Moves interleave by ply — white’s feed holds plies 0, 2, 4…, black’s 1, 3, 5… — so the merged game is deterministic without any coordination protocol:

const hosted = await ChessMatch.host(alice, 'match-0'); // white
const black = await ChessMatch.join(bob, 'match-0', hosted.feedKey);
const white = await hosted.acceptOpponent(alice, black.feedKey);

await white.move('e4');
await black.waitForOpponent(); // 'e4' — get()-driven, resolves on arrival
await black.move('e5');

move() enforces turn alternation locally; because every entry is signed by its author’s key, neither player can forge or reorder the other’s moves — the pair of feeds is tamper-evident dispute evidence.

Move legality is deliberately the client’s job. Both clients validate; if your opponent’s client sends an illegal move, yours refuses to continue and you have their signed feed to prove it. The contract stays a referee of outcomes, not a rules engine.

The wager (src/wager.ts + compiler/examples/chess_wager.pysc)

The contract is walked through line by line in the DSL tutorial. The client wrapper is thin:

const wager = new WagerClient(app, contractId);
await wager.create(100_000n); // escrow stake as attached value
await wager.join(0n, 100_000n); // opponent matches it
await wager.report(0n, winnerAddress); // each player, after the game
await wager.cancel(0n); // creator only, before join

What the e2e test proves

apps/chess/test/chess.test.ts, against real consensus over a real DHT:

  • escrow accumulates exactly 2 × stake in the contract account;
  • a wrong-stake join fails with the contract’s message and reverts its attached value;
  • cancel-after-join is rejected;
  • moves flow both directions peer-to-peer with turn enforcement;
  • two matching reports settle: the winner receives the full pot, the contract balance returns to zero, match settled appears in the events;
  • a second settlement attempt fails (match is not active).

A lesson this example taught

The move-wait originally polled feed.update() and could stall forever — update() waits passively for peer announcements. The fix (and the rule of thumb now in the networking chapter): use feed.get(index), which actively requests the block and resolves when it arrives.

Browser contract additions

create_room(room: address) creates an ordinary sequential match and records Room[room].match_plus_one. The 32-byte room identifier is generated in the browser, and registration verifies the confirmed create transaction and signer. Native create(), join(), report() and cancel() retain their interfaces. draw(match_id) records a player’s draw report and refunds both stakes only when both players agree. A later winner report clears that player’s draw choice.

Tests cover signature tampering, wrong deployment/room, sequence replay, illegal moves, self-join, conflicting concurrent appends, exact retries and persisted recovery. Real-network escrow tests cover concurrent room creation, mutual draws, creator cancellation and the original native winner payout.

The Marketplace Contract

contracts/marketplace (Rust) is the spec Phase 4 milestone contract and the reference for hand-written contracts against the raw ABI. Items have an owner, a price, and a for-sale flag; buying is atomic.

Actions

ActionArgsValueEffect
listprice u64—new item owned by caller; returns id (u64 LE)
buyitem idexactly the pricepays the seller, flips owner, marks off-sale
cancelitem id—owner takes it off sale
relistitem id, price—owner puts it back on sale
get_itemitem id—returns owner(32) ‖ price(8 LE) ‖ for_sale(1)

The atomic-trade pattern

buy is the canonical use of attached value:

#![allow(unused)]
fn main() {
if c::attached_value() != item.price { c::fail("attached value must equal price"); }
if !c::transfer(&item.owner, item.price) { c::fail("payout failed"); }
store_item(id, &Item { owner: buyer, price: item.price, for_sale: false });
}

The buyer’s payment was credited to the contract before the action ran; the contract forwards it to the seller and transfers ownership in the same atomic action. Any failure — wrong price, item off sale, buying your own item — aborts, and the buyer’s attached value comes back automatically. There is no state in which money moved but ownership didn’t.

Storage layout

item:<id LE8> → owner(32) ‖ price(8 LE) ‖ for_sale(1), plus next_id. Hand-rolled fixed-order encoding — deterministic by construction, cheap to decode. (The DSL generates the equivalent codec automatically.)

Tests

packages/chain/test/contracts.test.ts covers the full trade (list → buy → ownership flip → seller paid), the refund path on wrong attached value, re-buy of an off-sale item, and — via the follower-replay test — that marketplace blocks re-execute to identical state roots on other validators.

The e2e marketplace application (UI over this contract) is future example-suite work; the contract itself is production-shaped.

Land: State Maps & Config

compiler/examples/land.pysc is the DSL conformance example — a tiny land game exercising every core language feature: config, two state maps (one int-keyed, one address-keyed), defaults, exists, and the height builtin. It also shows the shape of a game economy done on-chain-lightly.

contract Land:

    config:
        max_tiles: int

    state Tile[int]:
        owner: address
        building: str = ""
        last_harvest_height: int = 0

    state Account[address]:
        wood: int = 0
        wheat: int = 0

    action claim_tile(tile_id: int):
        require(tile_id < config.max_tiles, "tile is off the map")
        require(not exists(Tile[tile_id]), "tile is already claimed")
        Tile[tile_id] = Tile(owner=sender, last_harvest_height=height)
        Account[sender].wood += 25

    action harvest(tile_id: int):
        tile = Tile[tile_id]
        require(tile.owner == sender, "only the tile owner can do that")
        require(tile.building == "farm", "tile has no farm to harvest")
        grown = height - tile.last_harvest_height
        require(grown > 0, "nothing to harvest yet")
        Account[sender].wheat += grown
        tile.last_harvest_height = height

(Plus transfer_tile and build_farm — see the file.)

Things to notice

  • config + generated init. max_tiles is set once by calling init(100) after deploy; every action reading config aborts until then, and nothing can change it after.
  • exists() for first-claim semantics — the idiomatic “create-if-absent, reject-if-present” check.
  • height as the only clock. Wheat “grows” per block. Two harvests in the same block: the first collects, the second hits nothing to harvest yet — deterministic time, no wall clock. (The e2e test asserts exactly this pair of outcomes.)
  • Account[address] maps — per-user inventories keyed by the caller’s key: the standard pattern for balances of anything that isn’t the native currency.

Where it runs in CI

packages/chain/test/dsl-e2e.test.ts compiles this file with mordecaic (when a Rust/Python toolchain is present), deploys the result, and asserts the require messages, the one-shot init, and the height-driven harvest behavior against a real chain — the spec Phase 7 milestone, executed on every full test run.

Frontier in the Browser

Frontier is the land-economy contract (claim tiles, build farms and lumbermills, harvest by block height, trade wood↔wheat through an escrowed on-chain order book) played from a plain web page — the proof of the web tier: open a URL, click a tile, own land, with no wallet extension and no backend beyond a gateway.

Shared node demo

Start the persistent node with node scripts/hex-demo.mjs after building the node and demo bundles. Open Wallet, load or create a wallet, fund test CAI in Faucet, then select Demos → Frontier. The game uses that wallet without another key import. Closing or replacing the wallet revokes its signing facade. Each action reserves up to 500,000 base units for fees; the Wallet tab records transaction receipts and handles uncertain submission retries.

This is one persistent world of 144 tiles on mordecai-demo. Claim wilderness, build a farm or lumbermill for 10 wood, and harvest resources. Growth follows block height: waiting alone does not produce resources. Trade wood and wheat through escrowed orders with a second wallet, or transfer a tile to a complete, valid recipient wallet address. A full world remains full; players can trade or transfer land rather than resetting other players’ progress.

The shared deployment uses journaled frontier-deploy and frontier-init steps. Restarting the node reuses its existing contract and world, alongside Hex and existing balances. Public configuration contains only chain ID and contract address. No player seed is passed to the embedded client or stored by it.

Standalone development demo

pnpm build && pnpm --filter @mordecai/example-frontier-web build
node scripts/frontier-demo.mjs     # → http://127.0.0.1:8787

The demo starts a 3-validator devnet, deploys compiler/examples/frontier.pysc, funds two dev accounts, and serves apps/frontier-web from the gateway. Switch between alice and bob in the UI to trade against yourself.

How the standalone client works

  • Signing in the browser. Keys derive from seeds in /api/config (devnet custody); @noble/curves signs the same canonical transactionSigningBytes the wallet daemon signs with sodium. The gateway never sees a key. ~65 KB gzipped, total.
  • State reads. One GET /api/contract/<id>/state sweep returns raw storage entries; the client decodes the DSL layout (s:<Map>: keys, fields in declared order) into tiles, accounts, and orders — the same pattern any explorer or indexer would use.
  • Gateway reads. Transactions are signed by the player; displayed state and receipts are read from the connected gateway. The browser does not independently verify consensus proofs.

The contract itself is walked through in Land (frontier is land plus a second building kind and the escrowed market). The on-chain behavior is pinned by packages/chain/test/frontier-e2e.test.ts; the HTTP surface by packages/gateway/test/gateway.test.ts.

Outpost: Goods, Orders and Settlement

Outpost is a cross-chain goods exchange: buy goods, fulfill orders and watch payment settle. The order book leads the interface; land and harvesting live in a collapsed Supply & production panel. Frontier is the land and trading game; Outpost focuses on the fulfillment and payment flow.

The production economy runs on a player-run app chain, the goods market runs on L1, and one wallet identity acts on both — the Ed25519 key that holds CAI on L1 is the same key that owns tiles and wood in the game. L1 currency buys in-game items with no bridge anywhere.

pnpm build && pnpm --filter @mordecai/example-outpost-web build
node scripts/outpost-demo.mjs      # → http://127.0.0.1:8787

The trade loop

  1. bob (L1) — place_order("wood", 10) with 1000 CAI attached. goods_market.pysc escrows it. Wood does not exist on L1; the order is a claim on something that only exists in the game.
  2. alice (app chain) — claims land, harvests, clicks deliver: outpost.pysc moves 10 wood from her game account to bob’s — keyed by the same addresses they use on L1 — and records a Delivery.
  3. the anchor daemon — next epoch, the app’s quorum (alice’s and bob’s validator keys) attests the game’s state root plus one outcome call: settle(order_id, alice). The market contract checks only sender == config.game and releases the escrow to alice.

CAI never left L1. Wood never left the game. The anchor carried judgment — “order 0 was delivered by alice” — not value. Alice’s L1 balance after the demo is her starting balance + exactly 1000: her only L1 transaction ever was being paid.

The two contracts

compiler/examples/outpost.pysc (app chain) is frontier’s land economy plus the cross-chain hook:

action deliver(order_id: int, buyer: address, good: str, amount: int):
    require(not exists(Delivery[order_id]), "order already delivered")
    ...move goods from sender to buyer...
    Delivery[order_id] = Delivery(seller=sender, buyer=buyer,
                                  good=good, amount=amount)

compiler/examples/goods_market.pysc (L1) escrows and settles:

action place_order(good: str, amount: int):
    require(value > 0, "attach the payment as value")   # escrow
    ...

action settle(order_id: int, seller: address):
    require(sender == config.game, "only the game may settle deliveries")
    o = Order[order_id]
    require(o.phase == 0, "order is not open")
    o.phase = 1
    transfer(seller, o.price)

The settlement logic that connects them — “which delivered orders are still open?” — is the anchor daemon’s outcome callback in scripts/outpost-demo.mjs: ~25 lines of JS reading both chains’ state and emitting one settle call per epoch.

The web client

apps/outpost-web is one page speaking to two gateways: game moves and world reads go to the app-chain gateway (:8788), market orders and balances to the L1 gateway (:8787). One seed signs on both chains, in the browser. Delivered orders show “awaiting verified anchor and L1 payment…” until confirmed L1 state shows “Paid on L1”. The standalone demo targets ~5s anchor epochs, but confirmation can take longer. The latest anchor and both chain heights remain visible in the UI.

What it proves

Every layer of the architecture in one flow: registry as root of trust, deterministic per-app genesis, group state under BFT at game speed for ~zero fees, quorum-attested outcomes as the only cross-chain artifact, one identity across all lanes, and a browser UI over untrusted gateways. The protocol-level proof is packages/appchain/test/market.test.ts; adversarial cases (replay, impersonation, double settlement) are all asserted there.

On the node site

Open Wallet, then Demos → Outpost. Your wallet signs game moves on the shared Outpost app chain and market orders on the node’s existing L1. Use the Faucet tab for L1 test CAI and Fund app fees for the separate game fee balance. The embedded demo never imports the development accounts or operator seeds. World state, validator identities and deployment receipts survive host restarts.

Place a buy order to escrow L1 test CAI for goods. Another wallet can fulfill it from available inventory. Suppliers can open Supply & production to claim a tile, build and harvest as app-chain block height advances. Delivering the exact buyer, good and amount lets the next signed anchor settle payment; confirmed L1 state determines payout. A mismatched delivery cannot release payment or block other valid orders, but it occupies that order’s delivery slot: its buyer can cancel and create a new order.

This is not an atomic exchange: cancellation racing a delivery can leave test goods transferred without payment. Cancelled orders are shown separately from confirmed payouts. The standalone launcher retains its separate, temporary development network and Alice/Bob account mode.

Microblog: Posts and Tips

Open Demos → Microblog on a running node site. Anyone can read its chronological feed. Publishing a short post is free: the shared Wallet signs it, and this node stores it off-chain. A wallet address identifies the signing key, not a verified person.

Publish and share

  1. Open Wallet, create or load a test wallet, and save its backup. Return to Microblog through the same navigation.
  2. Write up to 280 Unicode characters (maximum 2 KiB). Select Publish post to sign and submit that exact text.
  3. Open the post’s timestamp to get a permanent link. Posts display plain text, so markup is not executed.

If acknowledgement is uncertain, Retry identical signed post resubmits the same signed record without creating a duplicate. Accepted posts survive refresh and host restart. Text is public; do not include secrets or private information.

Tip an author

Use Faucet to obtain CAI test tokens. On another wallet’s post, select Tip, enter a positive whole number of CAI base units, then Review tip. Check the post, complete recipient address, network, amount and separate maximum fee. Cancel sends nothing. Send tip sends a direct transfer to the verified author; there is no custody or platform commission. Self-tips are disabled.

The node first durably saves a signed association between this post and the prepared transaction hash. The browser then broadcasts through the shared Wallet coordinator. A tip counts only after the node verifies the signed transfer, successful receipt, and the exact transaction at the receipt’s block position. Failed or unavailable receipts never increase totals. The label Confirmed tips linked on this node excludes ordinary unlinked transfers and other hosts’ feeds.

The app shows pending links after reload or restart and never automatically sends a payment on reconnection. A pending link may never have been broadcast. For uncertain submissions, keep the wallet tab open and use Wallet to check the receipt or retry the same transaction bytes. Do not create another transfer merely because a receipt is unavailable. Confirmation means successful inclusion reported by this node; CAI here is a test token.

Hide a post

The author can open Manage your post → Sign and hide post. The signed request removes its text from this node’s feed and direct view, leaving a payment tombstone. No new tips can be linked to a hidden post; previously submitted transfers can still settle. Hiding does not refund payments or erase downloaded copies, local records or backups.

Host operation

The demo launcher enables the service and persists its stable feed identity and signed records under microblog/ in the node’s data directory. Back up that whole directory with restricted permissions; run only one process against it. The local service exposes operator hide(id) and block(address) methods, with no unauthenticated administrative HTTP endpoint.

This small feed is intended for a local or trusted test network. It uses an in-memory index and atomically replaces its durable file after writes. Write limits per source and wallet are basic abuse controls, not Sybil prevention. Receipt checks have bounded concurrency and deadlines; node outages leave links pending while the feed remains usable. Define content-removal and backup-retention procedures before public deployment, and migrate the store when feed size requires an indexed database. Replies, following, rich media, ranking and federation are outside this demo.

Information Bounties

Open Bounties in the node site to browse public questions with funded rewards. Each question reserves its full reward in an L1 contract. The creator chooses one response, and a successful award transfers the whole reward to that response’s author.

This is a test CAI demo. It does not finance real-world work. Creator discretion means no guaranteed award, even if useful responses exist.

Fund and answer a question

  1. Open Wallet, load a test wallet, and obtain test tokens from Faucet if needed. Browsing does not require a wallet.
  2. In Bounties, enter a title, the request and acceptance criteria, a whole-number reward, and a submission duration. Include any requested sources or publication terms in the original request; it cannot be edited after funding.
  3. Select Review funding. Check the network, contract, sender, reward, fee limit, and exact submission and award deadline heights. Cancel review sends nothing. Confirm and send publishes and funds the request atomically.
  4. Wait for confirmation. The board lists requests from confirmed contract state. A typed reward or pending transaction is not a funded listing.
  5. Load a different test wallet to respond. Read the criteria, enter a public answer and any source URLs, then review and confirm. The response’s wallet address is its immutable payout recipient. The creator cannot respond to their own bounty.

The title accepts at most 160 UTF-8 bytes, and each request or response accepts at most 8,192 UTF-8 bytes. Some characters use several bytes. The contract enforces these limits independently of the browser. There are no uploads or submission edits; a correction is a new response.

Deadlines and the quick demo

The default submission duration is 5 blocks, with 100, 500 and 2,000-block alternatives. Review shows the exact closing height before you send. Once submissions close, the creator has a fixed 100-block award window.

This demo chain advances with network activity. Waiting five seconds does not mean five blocks have passed. Funding, a response, and other confirmed transactions advance the chain; use ordinary test-wallet transfers if you need to advance the remaining blocks for a walkthrough. Every transaction may cost a fee. Browser clocks do not enforce deadlines, and a stalled chain delays closure and refunds.

For a bounty with submission end S and award end A = S + 100:

Chain heightAvailable actions
Before SOther wallets may respond. The creator may cancel only while there are no confirmed responses.
At S through A - 1Submissions and cancellation are closed. Only the creator may select a response and award the reward.
At A or laterAwards are closed. Anyone may trigger a refund, always to the creator.

The contract checks the height at transaction execution. A response prepared just before the boundary can fail if it is included too late.

Select, cancel or refund

After submissions close, load the creator’s wallet, select the bounty, and use Review award to this response. Check the immutable response ID, author address and full reward. Confirming a successful award both records the winner and transfers the reward in one transaction. Selection is irreversible, and non-winners receive nothing.

Before any response, Review cancellation returns the reward to the creator if submissions are still open. Once somebody has responded, the creator cannot cancel. If the creator selects nobody before the award window ends, Review refund to creator becomes available to any wallet. Its caller pays the transaction fee; the reward goes only to the creator. Even a bounty with zero responses follows this final refund deadline after submissions close.

Network fees are separate from the reward and are never refunded. The contract prevents a second payout, cancellation after an award, and spending another bounty’s reserved reward. It does not judge response quality, guarantee impartiality, settle disputes, or imply a copyright transfer.

Public information and recovery

Public and permanent. Do not include confidential sources, personal records, credentials or unpublished sensitive evidence. Titles, requests, responses, addresses and monetary actions are public chain data. This is not a confidential whistleblower channel. Source URLs are displayed as plain text and are not fetched by the node; linked content can change or disappear. Removing a frontend listing cannot erase chain history or copies.

Each transaction shows its confirmation state. A timeout or lost response means confirmation unknown, not failed or paid. Open Wallet to inspect the pending hash and retry the same signed transaction. Do not create a new payment to resolve an unknown result. Failed execution can still consume a fee.

After a successful receipt the app reloads contract state and checks the matching request, response or settlement before showing completion. If that reload fails, it says the transaction is confirmed but bounty status is unavailable. Current-session receipt links expose the hash, inclusion height and actual fee.

After reloading the page, find a bounty using its ID. Its immutable content, phase, winner, creation height and settlement height remain recoverable from the contract. Historical transaction-hash discovery and durable local Wallet history are not implemented; this page’s receipt hash and tab-local pending history can be lost on reload. Closing a browser does not schedule refunds.

For contract source, build commands, tests and measured message costs, see compiler/examples/information_bounties.pysc and apps/bounties-web/README.md in the repository. The board currently reads the whole contract state and is intended for a small demo. Public-service moderation and real-value operation require separate work.

CLI Tools

Build with pnpm build. The unified entry point is mordecai, with l1 for settlement and app for application networks. From a checkout, use pnpm mordecai ... or node bin/mordecai.mjs ...; linking the root package makes mordecai available on PATH. Other tools retain their own commands.

mordecai --help
mordecai l1 --help
mordecai app --help

Connect a node

Every connection starts chain sync, verification, storage, data serving, and an HTTP gateway. The configured validator set determines the role: validators also propose and vote; peers do everything else.

Settlement (mordecai l1)

mordecai l1 connect --dir <path> --genesis <file> [--port <port>]

On first connection, creates node.key and saves the supplied genesis. Subsequent connections reuse them; --genesis is then optional. Use the network’s exact genesis: its hash determines which peers you discover.

The lower-level commands remain available:

mordecai l1 init --dir <path> [--chain-id <id>] \
                  [--alloc <address>=<amount>]... [--validator <address>]...
mordecai l1 join --dir <path> --genesis <file>
mordecai l1 start --dir <path>

init creates a new network, defaulting to this node as its sole validator. join prepares a directory for an existing network without starting it. start resumes an initialized directory.

l1 start and l1 connect accept --faucet-keystore <file> to enable the homepage’s test CAI faucet. Set MORDECAI_FAUCET_PASSPHRASE in the process environment and fund the dedicated wallet on that chain. The standalone gateway (node packages/gateway/dist/cli.js --node <rpc-key-hex>) accepts the same flag. Without it, the faucet is disabled. See the field guide for funding and claim limits.

App network (mordecai app)

# Direct discovery: no settlement RPC required
mordecai app connect --dir ./game --app http://192.168.1.20:8787
mordecai app connect --dir ./game --app 192.168.1.20:8787

# Named lookup: settlement RPC required
mordecai app connect --dir ./game --app com.example.game \
                     --settlement-node <rpc-key-hex>

--app accepts an explicit HTTP(S) URL, an IP address (optionally with a port), or a registered app ID. IPv6 ports use brackets: [::1]:8787. Domain URLs need a scheme; game.example.com alone is treated as an app ID. URLs may include a gateway path prefix or the full /api/connect endpoint. --l1-node remains an alias for --settlement-node; conflicting values fail.

Direct lookup fetches a bounded, validated connection document from the peer’s HTTP gateway. It never requires a settlement network or falls back to one. Named lookup requires the settlement node explicitly and reads its app registry. Optional settlement information in a peer document is only metadata until an action such as --anchor uses it.

Both paths create or reuse peer.key, derive the same genesis, seed the advertised app feeds, and start all services. Every joined app peer also serves /api/connect. Registry lookup automatically includes the registered bundle. Additional app data feeds can be supplied with repeatable --feed <hex-key>. start is an alias for connect.

To prepare a validator identity before connecting:

mordecai app init --dir <path>

Include that public key in the app’s local or registered validator set. The ordinary connect command then votes automatically and answers anchor_sign. No role flag is required. Preserve the data directory across restarts.

Both CLIs accept --bootstrap host:port,..., --block-interval <ms>, --static <frontend-dir> and --config <file.json>. HTTP uses --port, then the PORT environment variable, otherwise an available port. Startup prints the role, RPC key and HTTP URL. HTTP binds all interfaces.

App validators may additionally use --anchor --l1-chain-id <id> --relayer <file> [--epoch-interval <ms>]. This relays state-root anchors using the funded relayer; application outcomes still use the library’s AnchorDaemon.outcome hook.

mordecai-wallet (packages/wallet/dist/cli.js)

mordecai-wallet create   --keystore <path> [--force]
mordecai-wallet address  --keystore <path>
mordecai-wallet transfer --keystore <path> --to <address> --amount <n> \
                     --nonce <n> --chain-id <id> [--max-fee <n>]

The passphrase comes from --passphrase, MORDECAI_WALLET_PASSPHRASE, or a hidden prompt. create prints the address and the 24-word mnemonic (write it down — it is the only backup). transfer prints the signed canonical transaction as hex plus its hash, ready for submit_tx.

mordecai-launcher (packages/sdk/dist/launcher-cli.js)

mordecai-launcher install <appId> --node <rpc-key-hex> --out <dir> \
                      [--bootstrap host:port,...]

Registry lookup → swarm fetch → verify against the on-chain hash → write bundle.bin + app.json (the registry entry) into --out. Refuses on any hash mismatch.

mordecaic (compiler/mordecaic, Python 3)

./compiler/mordecaic check <contract.pysc>
./compiler/mordecaic build <contract.pysc> -o <dir> [--wasm] [--runtime-path <p>]

See the DSL reference.

Devnet launcher (apps/devnet/devnet.mjs)

node apps/devnet/devnet.mjs [validators=4]

In-process DHT testnet + N consensus validators; prints RPC keys, the DHT bootstrap address, node website URLs, and a funded faucet wallet (address + mnemonic). Node 0 enables the homepage faucet. Data lives in a fresh temp dir per run; Ctrl-C tears everything down.

Repo scripts

pnpm build | test | lint | format      # workspace-wide
pnpm build:docs                       # refresh the book bundled with each node
./scripts/build-wasm.sh                # rebuild ALL wasm artifacts:
                                       #   VM runtime, Rust contracts,
                                       #   DSL examples → contracts/dist
python3 -m unittest discover compiler/tests   # DSL compiler unit tests
mdbook serve docs                      # this book, live-reloading

RPC API

Every node serves RPC over @hyperswarm/rpc: clients dial the node’s public key through the DHT — no host/port, works across NATs. The typed client is NodeRpcClient (@mordecai/rpc); the SDK wraps it further.

import { NodeRpcClient } from '@mordecai/rpc';
const rpc = NodeRpcClient.connect(nodeKeyBytes, { bootstrap });

Requests and responses are JSON envelopes ({ok: true, result} / {ok: false, error}); u64 values travel as decimal strings, byte fields as lowercase hex.

Methods

get_head → HeadInfo

{ chainId, height, headHash, stateRoot, timestampMs } — the finalized head.

get_account { address } → AccountInfo

{ address, balance, nonce }. Contract accounts work too (pass the z32-encoded contract id).

submit_tx { tx: hex } → { hash }

Canonical encoded signed transaction. Admission errors (bad signature, nonce too low, fee reserve not covered, invalid WASM, duplicate) come back as envelope errors. Success means admitted, not finalized — poll get_tx. On consensus nodes, admission also gossips the tx to the mesh.

get_tx { hash } → TxInfo | null

{ hash, height, index, success, fee, events: hex[], returnData: hex, error? } — null until the transaction lands in a finalized block. The client’s waitForTx(hash, {timeoutMs, intervalMs}) polls this.

get_block { height } → BlockInfo | null

Header fields plus the canonical encoded transactions (hex) — decode with @mordecai/protocol if you need their contents.

get_app { appId } → AppInfo | null

{ appId, owner, pearKey, version, contractAddress, metadataHash } — the registry entry that installs verify against.

Client conveniences

const hash = await rpc.submitTx(encodeTransaction(tx));
const info = await rpc.waitForTx(hash, { timeoutMs: 30_000 });

Notes

  • Trust: an RPC node can lie by omission (hide a tx, stale head) but cannot forge state that contradicts consensus you verify elsewhere; run your own non-validator node if that matters to you.
  • Events are pull-based in v1 — no subscription stream yet; receipts carry events and waitForTx polls. Feeds are the push channel between apps.

Repository Layout & Building

zechariah/
  SPEC_PT_01..03.md        the platform specification (normative)
  IMPLEMENTATION_PLAN.md   v1 decisions (D1–D8) and milestones (M0–M7)
  docs/                    this book (mdBook) + threat-model.md
  packages/
    protocol/        canonical wire codec; tx/block/vote/gossip schemas; golden vectors
    crypto/          Ed25519, BLAKE2b-256, z32 addresses, keystores, mnemonics
    networking/      Network/Feed over Hyperswarm + Corestore
    state/           KV store (LevelDB), overlays, Merkle state commitment
    vm/              contract executor (wasmi-in-wasm) + runtime/ (Rust crate)
    chain/           genesis, execution, fees, mempool, blocks, registry
    consensus/       BFT engine, peer hub, certificates, block sync
    node/            node orchestration + mordecai l1 CLI
    rpc/             hyperswarm-RPC server + typed client
    wallet/          Wallet, Signer, keystore files, mordecai-wallet CLI
    sdk/             Mordecai (app runtime), ContractArgs, mordecai-launcher
    pear-integration/ WalletSession, WalletDaemon, RemoteSigner
  contracts/
    runtime-rs/      mordecai-contract: the Rust contract ABI bindings
    counter/ marketplace/   hand-written Rust contracts
    dist/            committed .wasm artifacts (Rust + DSL examples)
  compiler/
    mordecaic            the DSL compiler CLI (Python 3, stdlib only)
    mordecaidsl/         parser, typechecker, Rust codegen
    examples/        land.pysc, chess_wager.pysc
  apps/
    devnet/          local devnet launcher
    chess/           the example application

Toolchains

  • Node ≥ 20 + corepack — required for the packages. pnpm is pinned via packageManager; pnpm install && pnpm build && pnpm test.
  • Rust (wasm32-unknown-unknown) + Python 3 — only to rebuild wasm artifacts (scripts/build-wasm.sh) or compile your own DSL contracts. All shipped WASM artifacts are committed; tests that need the contract toolchain self-skip without it.
  • mdBook 0.5.2 — required by pnpm build to bundle this book into packages/gateway/public/docs/. Install a prebuilt mdBook release, or use cargo install mdbook --version 0.5.2 --locked if Rust is available. Run pnpm build:docs after documentation edits, or mdbook serve docs for live-reloading author previews. Built nodes serve the book at /docs/ without a separate documentation server or mdBook installation.

Testing conventions

  • Unit + integration tests are vitest, colocated in each package’s test/ (plus apps/*/test/). Tests import package sources via aliases in vitest.config.ts. Build first for CLI integration tests and bundled documentation route tests, which also exercise generated artifacts.
  • Integration tests spin up real components: in-process DHT testnets (hyperdht/testnet), real multi-validator consensus, real RPC over the swarm. Nothing chain-related is mocked.
  • Never run cargo/other sync subprocesses inside a vitest worker — a synchronous call blocks the event loop, so vitest’s own timeouts cannot fire and the run hangs silently. Precompile artifacts instead (this is a hard-won lesson; see scripts/build-wasm.sh).
  • Golden vectors (packages/protocol/test/vectors/) pin the wire format; changing them is a consensus break. Regenerate only deliberately with UPDATE_VECTORS=1.

CI

GitHub Actions (.github/workflows/ci.yml) runs install → build → lint → format check → tests on every push/PR. CI installs mdBook 0.5.2 before the build; prebuilt WASM keeps the contract toolchain optional.

Roadmap & Limitations

Where the implementation stands

Against the spec’s phased roadmap (SPEC_PT_03 §27):

PhaseStatus
0 Architecture✅ specs, plan, threat model
1 Networking foundation✅ feeds, swarms, replication
2 Settlement chain✅ single-sequencer and multi-validator BFT
3 Wallet & identity✅ wallets, keystores, Signer, sessions
4 Smart contracts✅ wasmi-in-wasm VM, marketplace contract
5 Application registry✅ on-chain registry + verified install
6 Pear runtime integration✅ SDK, wallet daemon + RemoteSigner (shell UI pending)
7 Pythonic DSL✅ mordecaic: parse → verify → Rust → wasm32
8 Example applications◐ chess shipped; marketplace/reddit/AI/wiki pending
9 Economic primitives◐ escrow + marketplace as patterns; no reusable library yet
10 Platform ecosystem◐ CLIs + this book; explorer/package manager pending

The spec §28 vertical slice — install from registry, wallet auth, p2p state sync, on-chain payment, finalized confirmation, keep playing — passes end to end on a multi-validator devnet (packages/sdk/test/vertical.test.ts).

Beyond the original phases, the feat/app-chains line adds two tiers on top (SPEC_APPCHAINS.md):

  • The web tier — the HTTP gateway, contract-state reads, and browser clients with in-browser signing (frontier-web).
  • App chains — per-app consensus with anchored outcomes (architecture, how-to), proven by the outpost cross-chain goods market.

Known limitations (deliberate v1 scope)

Security-relevant items are tracked in the Threat Model; the headline ones:

  • Permissioned validators. The set is fixed at genesis; staking, rotation, and slashing are future work. Safety needs < 1/3 Byzantine.
  • Consensus liveness gap. One-vote-per-height locking has no unlock: a proposer crash mid-vote can stall a height (never fork it) until the locked validators restart. (Missed-gossip stalls are healed — locked proposals re-broadcast on stall rounds — but the crash case remains.)
  • Anchors attest, they don’t prove. An app chain’s quorum can anchor a lie; the blast radius is confined to stakes voluntarily placed against that app. Co-signers vet state roots but not outcome-call semantics yet — per-app call vetting is the next hardening step. Fraud proofs are deliberately out of scope.
  • Flat fees, no fee market — a funded spammer can fill blocks.
  • Single-writer feeds only. Community-style apps (forums, wikis) need multi-writer structures (Autobase) — the biggest platform gap for the remaining example apps.
  • Pull-based events. Receipt polling instead of subscriptions.
  • Full-scan state root. Fine at devnet scale; swap for an incremental commitment behind the existing StateCommitment interface when it hurts.
  • The Pear desktop shell. The approval-UI seam (ApprovalPrompt), the daemon, and remote signing are built and tested; hosting apps in the actual Pear/Bare shell with a real prompt window is product work that can’t be validated headlessly.

Natural next steps

  1. Bare-compat audit of the app-side packages ("bare" export conditions).
  2. The Pear shell: wallet UI over WalletDaemon, launcher → pear run.
  3. Autobase adoption + the Reddit-style example.
  4. Economic-primitives library in the DSL (auction, subscription, DAO) — the wager contract is the template.
  5. Explorer + event subscriptions on the RPC.