Freenet Decentralized Application Builder
Build decentralized applications on Freenet following the architecture patterns established in River (decentralized chat).
How Freenet Applications Work
Freenet is a platform for building decentralized applications that run without centralized servers. Apps store and exchange data through a global, peer-to-peer Key-Value Store shared by every Freenet node.
The keys in that store are not arbitrary strings — they're derived from small pieces of WebAssembly called contracts that define how each value is allowed to change. The next two sections introduce the kinds of components that make up a Freenet app, then explain exactly how contract keys are formed and why that makes the system trustless.
The Three Kinds of Components in a Freenet App
A Freenet app is built from three kinds of components — contracts, delegates, and a UI. Most non-trivial apps have multiple contracts and multiple delegates, each handling a different concern.
1. Contracts (Network State)
A Freenet app typically has one or more contracts, each defining a different kind of shared state. River has a single room contract today, but a more complex app might have several (e.g. rooms, user profiles, invitations, search indexes), and each one is a separate contract crate that compiles to its own WASM.
- Role: Closer to a database table than a database. The contract WASM defines the schema (state shape) and the rules for validation and merging. Each instance of the contract — there can be many — behaves like an independent row in that table, so a chat app can have thousands of "room" rows all governed by the same room-contract WASM. (How rows are addressed is covered in How Contract Keys Work below.)
- Location: Runs on the public network (untrusted peers).
- Functionality:
- Defines what state is valid
- Defines how state can be modified (validate / update / summarize / delta)
- State: Holds the actual application data for that instance (arbitrary bytes).
- Constraint: Cannot hold private keys or secrets — all state is public unless encrypted by the client.
2. Delegates (Local Trust Zone)
A Freenet app may have one or more delegates, each handling a different local responsibility — key management, secret storage, background sync, notifications, and so on. Delegates are the local counterpart to contracts: where contracts hold shared state on the network, delegates hold private state on the user's device.
- Role: Trusted middleware between the user and the network.
- Location: Runs locally on the user's device, inside the Freenet kernel.
- Functionality:
- Trust Zone: Safely stores secrets, private keys, and user data
- Computation: Performs signing, encryption, and complex logic before publishing to the network
- Background Tasks: Can run continuously to monitor contracts or handle notifications even when the UI is closed
3. The User Interface (Frontend)
A single UI typically talks to all of an app's contracts and delegates.
- Role: Interaction layer for the user
- Location: Web Browser (SPA) or native app
- Functionality:
- Connects to the local Freenet Kernel via WebSocket/HTTP
- Built using standard web frameworks (Dioxus, React, Vue, etc.)
- Agnostic to underlying P2P network complexity
- How it is published and addressed: the UI ships as the state of a web
container contract — a generic, pre-built contract whose params are your
32-byte publisher key. Because neither key input contains your UI, your
webapp has one permanent URL and is upgraded in place:
fdev website update
publishes v2 to the same address users bookmarked. Do not design around a
rotating URL, and do not build a redirect contract to work around one. See
references/web-container-contract.md.
"Native app" above means desktop. Freenet does not currently support running a full node on mobile devices. Do not recommend or generate a production mobile wrapper without clearly warning about likely bandwidth, battery, thermal, CPU, and background-execution problems. Treat any such work as experimental, require explicit resource measurements before calling it viable, and do not represent it as an official Freenet client without approval from the Freenet Project.
How Contract Keys Work (and Why Freenet is Trustless)
Now that contracts have been introduced, here's how they're addressed in the network.
The key for a piece of data is derived from the cryptographic hash of the contract's WebAssembly (WASM) code, combined with a set of contract parameters that identify a specific instance.
- The WASM hash ties the identity of the data to its logic — change the code, and the key changes.
- The parameters distinguish independent instances of the same contract code. Tying back to the database-table analogy: the WASM is the table schema, and each parametrized instance is a row with its own key and its own state.
- This is what makes the network "trustless" — you don't have to trust the peer that holds the data, because the data is self-verifying against the contract code referenced in the key.
Data Synchronization & Consistency
Freenet solves "Eventual Consistency" using a specific mathematical requirement:
Join-semilattice: The function that merges updates must be associative, commutative and idempotent.
- Order Independent: It shouldn't matter what order updates arrive in
- If Peer A merges Update X then Y, and Peer B merges Update Y then X, they must end up with the same result
- Redelivery-safe:
merge(A, A) == A. Delivery is at-least-once, so the same update will arrive twice — after a retry, a re-subscribe, or anti-entropy. A merge that changes the state on re-application never settles. This is the requirement most often missed; see references/contract-patterns.md → "Merge Law Requirements" for why identity is not the same thing, and for the property tests.
A contract must not read the host clock. freenet_stdlib::time::now() is deprecated for contracts as of freenet-core v0.2.132. The merge has to be a function of its inputs — that requirement is why replicas converge — so a merge that reads the wall clock isn't merely breaking the laws above; they stop being well-formed statements about it. Two peers eleven minutes apart can produce different states from the same delta and neither is wrong. Today a node logs a warning on loading such a contract and fdev verify-merge reports a host_clock_import diagnostic; nothing traps yet, but the call is staged to trap (freenet-core#5465), and when it does the failure is per-call rather than a refusal to load, so no re-key is needed. Carry a client-signed timestamp in state and enforce only monotonicity instead — with clear eyes about what that costs, since a client timestamp is an untrusted hint and can't do anti-grief. Delegates are unaffected. See references/state-authorization-patterns.md → "Time Handling".
Check your contract against all of this rather than trusting it:
fdev verify-merge --wasm your_contract.wasm --state s1.bin --state s2.bin
It exercises the merge laws against a real corpus, and separately reports code diagnostics — host_clock_import being the one that exists today. A code diagnostic never fails the command: it describes the code, not a law the contract broke.
Efficiency: Peers exchange Summaries (compact representations) and Deltas (patches/diffs) rather than re-downloading full state.
Requirement: get_state_delta must not ship state to a peer that already has it. When the requester's summary shows it holds everything you have, the delta carries no information, so it must not contain the state or approach the state's size. It should be a literally empty StateDelta (vec![]), which is the unambiguous "converged" answer and what freenet-scaffold produces for you; a few tens of bytes of encoding framing from serializing an all-empty struct is acceptable. What matters is delta size relative to state size: 20 bytes against a 500 KB state is fine, a state-sized delta is a broken delta mechanism that re-ships everything on every reconciliation, forever. Your summary must likewise be far smaller than your state. Core is adding a probe for contracts that get this wrong, and it currently costs the network real bandwidth. Full detail, code shapes, and a test are in references/contract-patterns.md → "The Delta to an Up-to-Date Peer".
State and summaries must serialize canonically
Use deterministic maps everywhere in state AND summaries: BTreeMap/BTreeSet, never HashMap/HashSet. Peers decide they have converged by comparing state bytes, so two peers holding the same logical state in a different byte order heal forever without ever agreeing. Canonical encoding is a platform requirement (freenet-core #5320), and the merge laws are checked on exact bytes because of it. A HashMap serializes in nondeterministic order (ciborium), so two identical states can summarize to different bytes and core's byte-level convergence check misfires — spurious heals, or missed ones. The same caution applies to any map inside whatever summarize returns.
Beyond that, make sure your state genuinely converges through summarize / delta / apply, and test that it does, rather than assuming a live broadcast reaches every peer.
Previously documented here as a live limitation, now fixed.
freenet/freenet-core#4857
("State updates permanently lost for rarely-changing fields") is CLOSED. A
ContractQueueFull drop was silent, and the sender cached its own summary as
the receiver's on send-Ok, so it believed the peer was current and never
re-sent — leaving rarely-changing fields (config, permissions, ban lists)
diverged until the ~5-minute InterestSync heartbeat happened to correct them.
The shipped fix has the queue-full receiver emit a ResyncRequest, which makes
the sender clear its poisoned summary and re-send full state. It is throttled to
one per (contract, peer) per 30s, because
#4251 showed that one
request per dropped delta amplifies into a full-state storm onto the same
saturated queue; #4862
hardened it against bridge backpressure. See RESYNC_REQUEST_MIN_INTERVAL in
crates/core/src/ring/interest.rs.
Do not design around multi-minute staleness on rarely-changing fields, and
do not treat a ban list or permission field as needing to ride alongside a
frequently-changing one. The earlier guidance to do so is retired.
Keep summaries small — it is measured, and it is expensive
Summaries are ~23.7% of all outbound bytes on the Freenet network, and the fleet-mean summary is 16,675 bytes against a protocol digest-entry size of 21 bytes (freenet-core#5153). A fat summary is not a local inefficiency: it ships to every interested peer on every ~5-minute anti-entropy heartbeat whether or not anything changed, and it sets the floor for how cheaply a peer can be brought up to date.
Every rule below is checkable in review and grounded in a measured finding from River.
Every summary field must be read by delta(). Grep each field name against the delta() bodies. A field nothing reads is dead weight re-sent forever.
A value that is only ever compared for equality must be a fixed-width digest, never the thing it fingerprints. River carried raw Ed25519 signatures in member_info purely to run >; replacing them with a 16-byte digest measured 135.27 → 28.01 bytes per entry. The DM summary still does this for a bare contains() at 66 bytes/entry — 19,803 bytes at its cap, larger than the whole rest of the summary (freenet/river#596).
Size a digest by who controls the colliding inputs, not by taste. If a party can grind both sides of the comparison, 64 bits is a ~2^32 birthday search — hours on commodity hardware — so use 128. If the attacker controls only one side, 64 may do. Write the threat model in the doc comment. A collision here is not a crash; it is a record that silently never propagates.
Assert the encoding; never derive it. The same 64 bytes cost 66 CBOR bytes as a byte string and 119 as a derived tuple — ciborium maps serialize_tuple to an array where every byte ≥ 24 costs two. River quoted 66 for a type that actually encoded at 119, and the wrong number survived an issue, a PR body, and a review. Hand-write Serialize with serialize_bytes for any fixed-size byte array, and pin it with a golden vector: one fixed input, one fixed expected digest, one fixed expected byte length. A randomised digest oracle misses byte-order bugs intermittently.
Measure size with realistic key values, not small integers. A FastHash(i) for small i encodes in 1-3 CBOR bytes; a real key's encodes in 9. A test built from 0..N understates the per-entry cost by ~30% and will pass review.
A summary should be O(1) or sub-linear in the collections it describes — or justify the linearity in writing. A flat enumeration grows without bound as your app succeeds. If you keep it linear, state the element cap that bounds it and check cap × per-entry against your budget. River's is fully linear; at 200 members × 1000 messages it measures 16,723 bytes.
A lossy summary is legal when apply_delta is idempotent — exploit that. K fixed buckets each holding an 8-byte digest of that bucket's contents makes the summary constant-size: measured K=16 → 145 bytes, independent of N, against 3,894 bytes for the flat form at 139 members. get_state_delta may then return a superset of the true delta, which is sound only if applying an already-held element is a no-op — verify that first. The trade is real: one changed element resends its whole bucket. It wins because summaries go out on every heartbeat while deltas fire only on change, so measure your summary-broadcast : state-change ratio before committing.
A capped or pruning collection needs a retention horizon in the summary. Without one, delta() is a pure set difference: the receiver prunes what it just received, neither summary changes, and the pair re-sends forever. Publish the oldest key held, only at capacity, so it strictly increases each exchange and the loop provably terminates.
Nothing in a summary should reveal information the recipient is not entitled to. A summary goes to more peers, more often, than state does. River's DM summary advertises every DM in the room to every member, participant or not, leaking exact DM volume.
A summary is a wire-format commitment: changing it re-keys the contract and strands every existing copy. Which hash, how wide, which bytes in which order, and how it serializes are all frozen at publish. Keep a registry of past generations (River keeps legacy_room_contracts.toml, 31 entries) and expect every abandoned generation to keep costing anti-entropy bandwidth indefinitely — one stranded River generation is currently doing 3,829 failed summary comparisons against zero update events (freenet-core#5158). Batch summary changes rather than shipping them one at a time.
Advanced Capabilities
- Subscriptions: Clients can subscribe to contracts and get notified of changes immediately (real-time apps)
- Contract Interoperability: Cross-contract reads are implemented and working.
validate_state can return ValidateResult::RequestRelated(Vec<ContractInstanceId>);
the host fetches those contracts and re-invokes with RelatedContracts populated
(fetch_related_for_validation_network in
crates/core/src/contract/executor/runtime/contract_ops.rs, on both the PUT and
UPDATE paths). The machinery behind it is real: a related fetch that would block the
serial contract loop is deferred to an off-loop waiter, bounded by
MAX_INFLIGHT_DEFERRALS = 256 with an RAII guard giving exactly-once resume, and an
over-cap op surfaces MissingRelated rather than growing unboundedly
(freenet-core#4391, crates/core/src/contract.rs). freenet-core#2870 ("Complete
related contract mechanism implementation") is still open but is itself partly stale —
the UPDATE-path todo!() it cites at runtime.rs:946 no longer exists.
The thing to get right is not whether it works, but what you are allowed to read.
A contract's verdict must be a function of its inputs, or replicas diverge. Reading
another contract widens the input set to something that changes underneath you:
- Reading an immutable fact (a certificate, a signed key) is safe — every peer gets
the same answer forever.
- Reading a monotonic fact in the once-true-always-true direction is safe.
- Gating validity on mutable or growing state is not. "Reject if the other party has
more than N entries" flips from valid to invalid as their state grows, so peers
validating at different moments disagree and never converge. That class of rule belongs
in client-side policy, not in
validate_state.
Practical limits:
- One round only. A
RequestRelated is fetched and retried exactly once; a
second is an error (contract/executor/runtime/contract_ops.rs:431-432), capped at
MAX_RELATED_CONTRACTS_PER_REQUEST = 10 ids. No chained dependencies.
- On the client-facing UPDATE surface,
UpdateData::RelatedStateAndDelta is the form
you send; bare UpdateData::RelatedState / RelatedDelta are rejected from
ContractRequest::Update and reserved for the runtime's own request-related
orchestration, which surfaces RelatedState to your WASM itself.
- A related fetch that times out can wedge an UPDATE merge (freenet-core#4077, open).
- Related state resolved during validation is captured, since v0.2.131
(2026-08-24) — freenet-core#5393 and #5402. Before that, a contract whose validity
depended on another contract was permanently unjudgeable, and an unjudgeable
contract reads exactly like a clean one. Note issue #5376 closed on 2026-09-06, a
fortnight after the code shipped: a close date is bookkeeping; the release tag is
what makes a mechanism available. Checking that for yourself has its own trap —
this repo squash-merges, so the SHAs an issue timeline cites are branch commits that
never exist in
main. Searching the log for them, or for the issue number, finds
nothing in any tag and reads exactly like "never shipped". Go by PR number, and
confirm with merge-base --is-ancestor <merge-sha> <tag>.
- Judgeable is not judged. The verifier never fetches related state; it replays
only what the bundle already carries, mapping any
RequestRelated straight to
Inconclusive::RelatedRequired (conformance/verifier.rs:997-1005). Production is
stricter — the executor fetches and re-validates once at depth=1
(executor_impl.rs:2461) — and that path is never exercised by the verifier.
Capture also keeps only the most-recently-observed state per related contract, so a
defect needing a specific or older one yields no verdict at all: measured 1,567 of
5,856 replayed cases inconclusive for want of related state, five contracts with no
verdict on any case (conformance/capture.rs:108-125). That file states the intent
plainly — "depending on related state must not be a way to escape conformance
checking" — and coverage starvation is how it still can.
fdev verify-merge --state <files> is blind to related contracts. The
non---bundle path leaves related unconditionally empty
(fdev/src/conformance.rs:912-915), so a contract of this shape comes back 100%
inconclusive on every property — which, skimmed for violations, reads as a clean
bill. Check on the --bundle path, confirm the bundle reports related_entries > 0,
count the explicit verdicts, and treat inconclusive as not a pass. Exit code 4
means violations were found and the JSON is complete.
freenet-scaffold's #[composable] has no inter-contract awareness
(freenet-core#2870), so cross-contract dependencies are hand-rolled.
The mechanism with code, and which of the two paths to request related state
from, is in references/state-authorization-patterns.md →
"Related-Contracts Mechanism".
Development Workflow
Follow these phases in order.
Building on an app you do NOT own — reading River rooms, using the
ghostkeys delegate, indexing another project's contracts? Do not hardcode
their contract or delegate key. It is BLAKE3(BLAKE3(wasm) ‖ params), so it
moves on every re-key of theirs, including a bare version bump, and the
failure is silent: every read comes back looking like "this user has nothing
stored". Pinning a version of their crate does not help — that pins you to
their view of the key as of their release, which is the thing that went stale.
Fetch their key at runtime instead: resolve their author-signed pointer if
they publish one, and otherwise read it from their webapp bundle, which is
what ghostkeys does today. Pointer adoption is thin, so expect the fallback to
be the path for most apps right now. Either beats a compiled-in constant. See
references/building-on-other-apps.md.
Working on an app that already exists? Before anything else, check whether
it hardcodes a delegate key belonging to a platform delegate it does not own
(ghostkeys being the one in use today). That constant goes stale on every
re-key of that delegate — including a bare version bump — and the failure is
silent: every request comes back looking like "this user has nothing stored".
One grep, and the fix is a runtime fetch. See
references/delegate-patterns.md → "Depending on Someone Else's Delegate".
This broke every ghostkeys integration in August 2026 and was found by a
confused user rather than by any test.
Already shipped v1 and here to UPGRADE? (bump freenet-stdlib, ship a new
contract/delegate version, or fix a bug that re-keys the WASM) — go straight to
references/upgrade-and-migration.md → "Upgrading a Freenet dApp — the painless
path", the single start-to-finish playbook. A routine WASM/stdlib bump is
low-risk and mechanical when you designed for it at v1, not "recreate
everything and all invites die" — River's live 0.6→0.8 stdlib re-key (verified
2026-07-12) auto-migrated every room on refresh, kept every invite and the
78-member Official room intact, and needed no recreation. The phases below build
a new dApp; the playbook ties the upgrade steps together (v1 design
precondition → reproducible builds → register the outgoing hash → freenet-migrate
→ publish → do NOT recreate instances or warn of dead invites).
Phase 1: Contract Design (Shared State)
Start by listing each kind of shared state your app needs — each kind becomes its own contract crate. Then design each one in turn using the questions below.
Key questions (per contract):
- What data must all users see consistently for this concern?
- How should conflicts be resolved when two users update simultaneously?
- What cryptographic verification is needed?
- What are the state components and their relationships?
- What parameters distinguish one instance from another (e.g. room owner key, profile owner key)?
- If users reference each other (messaging, contacts, profiles), what is the user-facing identifier? It should be short, self-certifying, and stable across WASM upgrades — derived from a key, never a contract key. See
identity-and-addressing.md.
- How is each record inside this state identified, and does that id cover every term a reader will later rely on it to bind? A writer-supplied nonce, or an id that hashes only some of a record's terms, lets one author sign two different records under one id — and under a first-writer-wins merge that is permanent divergence that cannot heal, because both peers' summaries already name the id. Derive ids from content, compute them in the contract, and have exactly one function decide "are these the same thing". Get this right before launch: changing a derivation afterwards makes every published record unverifiable, which is a breaking change to users' data. See
contract-patterns.md → "Record Identity".
- Can strangers write to this contract? If so, what stops one attacker minting ten thousand keys and flooding it? There is no server to host a CAPTCHA, so the mechanisms available are proof-of-work and ghost keys (a blind-signed certificate proving an anonymous donation — a cost the attacker cannot beat with better hardware, and not burned as waste heat). The recommended shape is both: proof-of-work as the always-sufficient default, with a ghost key offered as a way to skip the wait, surfaced while the grind is running and the user is blocked anyway. That lets you set difficulty by what deters an attacker rather than by what your slowest device tolerates, while never pricing anyone out. See
identity-and-addressing.md → "Cryptographic CAPTCHA". Present the choice to the developer rather than picking silently: ghost keys cost their users money, that money funds Freenet, and the mint is centralized (verification is not). Those are product and architecture decisions, not technical details to settle on the developer's behalf.
- How large can this contract's state realistically grow? Keep each contract instance's state small — target well under 4 MB, not just under the host's 50 MiB hard cap. A GET transfers the entire state before the UI can render anything, so state size is felt directly as load latency, and
validate_state/update_state/summarize_state WASM execution cost scales with it too. If a kind of data can grow without bound (message history, uploaded files, a membership list that only grows), don't let one contract instance absorb all of it — shard by the natural unit of write concurrency instead (one contract per room, per user, per time-window, per shard-key, etc.), so each instance stays small regardless of how large the dataset gets in aggregate. See state-authorization-patterns.md → "State Size Budget".
Implementation steps:
- Define state structure using
#[composable] macro from freenet-scaffold
- Implement
ComposableState trait for each component
- Implement
ContractInterface trait for the contract
- Ensure all state updates satisfy the merge laws (associative, commutative, idempotent), and that
get_state_delta returns a negligible delta (ideally zero bytes, never state-sized) when the requester's summary already matches your state (see contract-patterns.md)
- Every field in state must be covered by a cryptographic signature -- contracts run on untrusted peers who can modify unsigned fields. Write a test for each signed field verifying that tampering causes verification failure. See contract-patterns.md for versioned signature patterns when adding fields later.
- Plan contract upgrade from v1 — it's low-risk and mechanical when you design for it. The property that makes it mechanical is that a new contract version accepts old contract state, so migration is pure data transfer and any client can carry a user forward — including a user who never opens your app again. Once you have users that stops being a preference and becomes a constraint on which changes you may make: a change to how a record's identity is derived breaks it by construction, and is a breaking change to users' data rather than an internal refactor. See
upgrade-and-migration.md → "A New Version Must Accept Old State". A WASM change moves the contract key, but if you anchor your app's durable references on a stable identity anchor independent of the WASM — an owner/user key, fixed singleton params, a DID, or an index contract mapping a stable name → current key (options in upgrade-and-migration.md step 1) — the upgrade is transparent: the client re-derives the new contract key from the unchanged anchor, so invites, share links and membership survive. River's 0.6→0.8 re-key on the live network kept every room and invite; recreation is only for deliberately rotating the anchor itself, never for a routine contract/stdlib bump. State is carried forward by a backward probe from a committed legacy-code-hash registry, packaged by the freenet-migrate crate (0.6.0, with freenet-migrate-build 0.2.0) — do not hand-roll it. Read the freenet-app-migration skill before writing any of it, if you have it: it owns the migration doctrine — when to probe, which probe outcomes may seal a completion marker, and the failure modes that lose data with a green build. It ships separately from this plugin, so if it is not installed, contract-patterns.md and upgrade-and-migration.md carry the same rules and are enough to build against. See contract-patterns.md → "Contract WASM Upgrade & State Migration" for the key-derivation mechanism, upgrade-and-migration.md for the operational discipline, and the freenet-migrate-adoption skill for swapping an existing hand-rolled sweep over to the crate.
- Read
state-authorization-patterns.md before designing the second iteration. It captures cross-cutting patterns (per-item vs bundled signatures, replay protection via monotonic counter / tombstones / cross-context binding, signed-payload hygiene, why a contract must not read the host clock and what to carry instead, related-contracts limits, wire-format stability) that bite on every contract beyond the trivial.
References:
references/contract-patterns.md — ContractInterface, the merge laws, composable state, basic signatures.
references/state-authorization-patterns.md — authentication, replay protection, signed-payload hygiene, time (contracts must not read the host clock), related-contracts, wire-format stability, common pitfalls.
references/identity-and-addressing.md — short self-certifying user-facing addresses, keeping large (post-quantum) keys out of identifiers, identity that survives WASM upgrades, and blocking bots without a server (ghost keys vs proof-of-work).
Phase 2: Delegate Design (Private State)
Determine what private data each user needs stored locally and split it across delegates by responsibility (e.g. one delegate per trust boundary or per long-running background task). Most apps need at least one delegate; many need several.
Know the limits before you lean on a delegate for background work. A
delegate runs only when something pokes it: there is no scheduled wakeup
(freenet-core#3972). Its contract GET reads the local store only, and its
contract subscribe registers no network demand, so subscribing does not keep a
contract alive in the network (freenet-core#4669). Both are open with no fix
merged as of 2026-08-30.
Test that work against a real node: freenet local never runs the loop that
services a delegate's contract requests, so a delegate's GET, PUT, UPDATE and
SUBSCRIBE all silently do nothing there (freenet-core#5273).
references/delegate-patterns.md → "Delegate Capabilities" has the verified
detail and the current state.
Key questions (per delegate):
- What user-specific data needs persistence? (keys, preferences, cached data)
- What signing/encryption operations are needed?
- What permissions are needed for sensitive operations?
- Does a platform delegate already do this? Delegates are callable across apps, so some responsibilities are worth borrowing rather than building. ghostkeys is the one that exists today: it holds the user's ghost-key identities and signs on your behalf, and it renders the user's allow/deny prompt itself, so you implement no permission flow. See
identity-and-addressing.md → "Cryptographic CAPTCHA" for what it is for, how it pairs with proof-of-work as an escape hatch rather than replacing it, and the two caveats worth relaying to the developer: the mint is centralized, and Freenet has a funding interest in you choosing it.
Implementation steps:
- Define request/response message types
- Implement
DelegateInterface trait
- Handle secret storage operations (Store, Get, Delete, List)
- Implement cryptographic operations (signing, encryption)
- Design for secret migration from v1 -- when delegate WASM changes, the delegate key changes and all stored secrets become inaccessible. There is no
ExportSecrets request in the stdlib wire protocol and no node-level copy-forward. The mechanism messages each old delegate key via DelegateRequest::ApplicationMessages, re-running the old WASM to read its secrets, and folds the signing keys forward (encryption secrets are re-derived) — so only a predecessor whose already-deployed WASM answers can be recovered from, which makes this forward-only. freenet-migrate ships that answer as handle_export_request (since 0.3.0) for you to call from your delegate; River needs no special handler only because its chat delegate already answered a general-purpose GetRequest/ListRequest over its own secret namespace, which most delegates do not. Every release shipped without an export answer adds one permanently unrecoverable generation — see delegate-patterns.md → "A delegate migration is forward-only". Keep a committed registry of old delegate keys and migrate promptly — the re-run breaks after a stdlib/ABI bump (freenet/river#204). See delegate-patterns.md for the mechanism; freenet-migrate codifies the delegate registry and build codegen, but delegate secret carry-forward has no core mechanism and never will — a node-level attempt (RegisterDelegateWithPredecessors) was built, shipped, then found forgeable and disabled as a security fix (freenet-core#5199), and after three rejected trust-model designs, app-level migration is settled standing policy, not an interim measure. App-level does not mean bespoke: freenet-migrate ships the delegate-side entry points (migrate_delegate_secrets, register_delegate_with_migration, unchanged since 0.5.0; crates.io is now 0.6.0, whose break is contract-half only), and River, Delta and ghostkeys all drive them on main at 0.5.0. Note that River and Delta run the crate's walk alongside their existing hand-rolled sweep, which stays authoritative for now; retiring the sweep is a later release, after the walk field-validates. See delegate-patterns.md → "Delegate secret migration: no core mechanism, and why" for the full history, the freenet-migrate-adoption skill for the swap procedure, and freenet-core#2776 for live status. See upgrade-and-migration.md for the operational discipline (resumable/interrupted-migration recovery, migration telemetry, and the upgrade test harness).
Reference: references/delegate-patterns.md
Phase 3: UI Design
Build the user interface connecting to contracts and delegates. Two approaches:
Option A: Dioxus (Rust → WASM)
Best for: teams already in Rust, complex state logic shared with contracts.
Implementation steps:
- Set up Dioxus project with WASM target
- Implement WebSocket connection to Freenet gateway
- Create synchronizer for contract state subscriptions
- Implement delegate communication for private storage
- Build reactive UI components
- Vendor your stylesheets, fonts, and scripts. The gateway serves every
webapp under a same-origin CSP — CDN
<link> / <script> tags from
cdn.jsdelivr.net, cdnjs.cloudflare.com, fonts.googleapis.com, etc.
are blocked in production even though they work in dx serve /
vite dev. See references/ui-patterns.md "Gateway CSP: Vendor Your
Assets".
Option B: TypeScript + Vite
Best for: web developers, faster iteration, familiar tooling (npm, SCSS, etc.).
Implementation steps:
- Set up Vite project with
@freenetorg/freenet-stdlib (TypeScript package)
- Use
FreenetWsApi class for WebSocket connection (handles FlatBuffers serialization)
- Pass empty string auth token to
FreenetWsApi constructor (sandbox blocks cookie reading)
- Use Vite
define to inject contract hashes and delegate key bytes at build time
- For delegate communication, dynamically import internal FlatBuffers types (
ClientRequestT, ApplicationMessagesT, etc.)
- Build reactive UI with vanilla TS, or any framework (React, Vue, Svelte)
Validate the UI in a real browser (both options)
A Freenet UI's real render path only runs in a browser. A Dioxus UI ships as a
WASM bundle, so rendering a component tree to a string in a Rust test does not
exercise the compiled bundle, its event handlers, or its asset paths, and both
options reach the node over a WebSocket that unit tests never touch.
Drive the UI with Playwright (or equivalent browser automation) from
the first screen onward, not only at release time. Treat "I built the
component" as unfinished until a browser has loaded it and a script has clicked
through it.
- Serve the UI locally (
dx serve for Dioxus, vite dev for TypeScript) and
drive it with Playwright against mock or offline data, so render correctness,
navigation, and form validation gate every PR. This is the offline tier in
references/production-smoke-testing.md, which has a starter spec.
- Assert the browser console is clean in every flow. WASM panics, failed
requests, and CSP blocks surface only as console or network errors, so a UI
that looks correct in a screenshot can still be panicking on every
interaction.
- Once a local node is running, re-run the same flows against the
gateway-served webapp (the
iso tier). Reaching your app there needs
frameLocator and an absolute-URL goto, because the gateway wraps every
webapp in an iframe shell.
For interactive debugging rather than scripted specs, the Playwright MCP browser
tools drive a running dx serve or local node directly. See the local-dev
skill, "Debugging with Playwright".
References:
references/ui-patterns.md - WebSocket connection models, gateway CSP,
serving large binary assets from a dedicated contract, framework-specific
patterns.
references/production-smoke-testing.md - the four test tiers, the
development-loop browser-validation recipe, and the iframe-shell Playwright
idioms.
Phase 4: Build, Test, and Deploy
Set up the build system, CI, and deployment pipeline.
Implementation steps:
Set up build orchestration — either Makefile.toml (cargo-make) or plain Makefile
Add a preflight task that runs fmt, clippy, tests, and migration checks before publish
Add GitHub Actions CI workflow (runs on push and PRs)
Back up contract state to the delegate for network resilience
Add a production-liveness smoke test. A ~50-line Playwright spec
asserting the gateway-hosted webapp mounts, vendored CSS loaded, and the
browser console is clean catches CSP blocks, iframe-shell mistakes, and
broken archives that no unit test reaches. See
references/production-smoke-testing.md.
Check the gateway port, and make the build reproducible. The
gateway runs on 7509 — older docs and scripts still reference 50509.
For byte-reproducible webapp archives across build hosts, invoke tar
with the GNU flags listed under "Tooling Preflight" in
references/build-system.md.
Contracts need more than reproducible tars, and this part is not
optional — the WASM bytes are the contract's address. Build them through
one canonical script that remaps CARGO_HOME, RUSTUP_HOME and the repo
root, and that refuses the build if any build-machine path survives into the
WASM. Remapping only your own source path leaves the cargo registry's absolute
paths in the bytes, which binds every contract to the machine that b
…(truncated)
1---2name: dapp-builder3description: Build and maintain decentralized applications on Freenet using river as a template. Guides through designing contracts (shared state), delegates (private state), and UI, and through upgrading a live dApp safely. Use when user wants to create a new Freenet dApp, design contract state, implement delegates, build a Freenet-connected UI, OR upgrade an existing dApp — bump freenet-stdlib, ship a new contract/delegate version (v2), fix a bug that re-keys the WASM, or migrate state across a contract/delegate key change without breaking invites or losing data. Also use when INTEGRATING with a contract or delegate published by another app — reading another project's contract state, depending on a platform delegate, or deciding how to address someone else's artifact so it survives their re-keys.4license: LGPL-3.05---67# Freenet Decentralized Application Builder89Build decentralized applications on Freenet following the architecture patterns established in River (decentralized chat).1011## How Freenet Applications Work1213Freenet is a platform for building decentralized applications that run without centralized servers. Apps store and exchange data through a global, peer-to-peer **Key-Value Store** shared by every Freenet node.1415The keys in that store are not arbitrary strings — they're derived from small pieces of WebAssembly called **contracts** that define how each value is allowed to change. The next two sections introduce the kinds of components that make up a Freenet app, then explain exactly how contract keys are formed and why that makes the system trustless.1617## The Three Kinds of Components in a Freenet App1819A Freenet app is built from three *kinds* of components — contracts, delegates, and a UI. Most non-trivial apps have **multiple contracts and multiple delegates**, each handling a different concern.2021### 1. Contracts (Network State)2223A Freenet app typically has **one or more contracts**, each defining a different kind of shared state. River has a single room contract today, but a more complex app might have several (e.g. rooms, user profiles, invitations, search indexes), and each one is a separate contract crate that compiles to its own WASM.2425- **Role:** Closer to a **database table** than a database. The contract WASM defines the *schema* (state shape) and the *rules* for validation and merging. Each instance of the contract — there can be many — behaves like an independent row in that table, so a chat app can have thousands of "room" rows all governed by the same room-contract WASM. (How rows are addressed is covered in *How Contract Keys Work* below.)26- **Location:** Runs on the public network (untrusted peers).27- **Functionality:**28 - Defines what state is valid29 - Defines how state can be modified (validate / update / summarize / delta)30- **State:** Holds the actual application data for that instance (arbitrary bytes).31- **Constraint:** Cannot hold private keys or secrets — all state is public unless encrypted by the client.3233### 2. Delegates (Local Trust Zone)3435A Freenet app may have **one or more delegates**, each handling a different local responsibility — key management, secret storage, background sync, notifications, and so on. Delegates are the local counterpart to contracts: where contracts hold *shared* state on the network, delegates hold *private* state on the user's device.3637- **Role:** Trusted middleware between the user and the network.38- **Location:** Runs locally on the user's device, inside the Freenet kernel.39- **Functionality:**40 - **Trust Zone:** Safely stores secrets, private keys, and user data41 - **Computation:** Performs signing, encryption, and complex logic before publishing to the network42 - **Background Tasks:** Can run continuously to monitor contracts or handle notifications even when the UI is closed4344### 3. The User Interface (Frontend)4546A single UI typically talks to *all* of an app's contracts and delegates.4748- **Role:** Interaction layer for the user49- **Location:** Web Browser (SPA) or native app50- **Functionality:**51 - Connects to the local Freenet Kernel via WebSocket/HTTP52 - Built using standard web frameworks (Dioxus, React, Vue, etc.)53 - Agnostic to underlying P2P network complexity54- **How it is published and addressed:** the UI ships as the *state* of a **web55 container contract** — a generic, pre-built contract whose params are your56 32-byte publisher key. Because neither key input contains your UI, **your57 webapp has one permanent URL and is upgraded in place**: `fdev website update`58 publishes v2 to the same address users bookmarked. Do not design around a59 rotating URL, and do not build a redirect contract to work around one. See60 `references/web-container-contract.md`.6162**"Native app" above means desktop.** Freenet does not currently support running a full node on mobile devices. Do not recommend or generate a production mobile wrapper without clearly warning about likely bandwidth, battery, thermal, CPU, and background-execution problems. Treat any such work as experimental, require explicit resource measurements before calling it viable, and do not represent it as an official Freenet client without approval from the Freenet Project.6364## How Contract Keys Work (and Why Freenet is Trustless)6566Now that contracts have been introduced, here's how they're addressed in the network.6768The key for a piece of data is derived from the **cryptographic hash of the contract's WebAssembly (WASM) code**, combined with a set of **contract parameters** that identify a specific instance.6970- The WASM hash ties the *identity* of the data to its *logic* — change the code, and the key changes.71- The parameters distinguish independent instances of the same contract code. Tying back to the database-table analogy: the WASM is the table schema, and each parametrized instance is a row with its own key and its own state.72- This is what makes the network "trustless" — you don't have to trust the peer that holds the data, because the data is self-verifying against the contract code referenced in the key.7374## Data Synchronization & Consistency7576Freenet solves "Eventual Consistency" using a specific mathematical requirement:7778**Join-semilattice:** The function that merges updates must be associative, commutative and *idempotent*.79- Order Independent: It shouldn't matter what order updates arrive in80- If Peer A merges Update X then Y, and Peer B merges Update Y then X, they must end up with the same result81- Redelivery-safe: `merge(A, A) == A`. Delivery is at-least-once, so the same update *will* arrive twice — after a retry, a re-subscribe, or anti-entropy. A merge that changes the state on re-application never settles. This is the requirement most often missed; see `references/contract-patterns.md` → "Merge Law Requirements" for why identity is not the same thing, and for the property tests.8283**A contract must not read the host clock.** `freenet_stdlib::time::now()` is deprecated for contracts as of freenet-core **v0.2.132**. The merge has to be a function of its inputs — that requirement *is* why replicas converge — so a merge that reads the wall clock isn't merely breaking the laws above; they stop being well-formed statements about it. Two peers eleven minutes apart can produce different states from the same delta and neither is wrong. Today a node logs a warning on loading such a contract and `fdev verify-merge` reports a `host_clock_import` diagnostic; nothing traps *yet*, but the call is staged to **trap** (freenet-core#5465), and when it does the failure is per-call rather than a refusal to load, so no re-key is needed. Carry a client-signed timestamp in state and enforce only monotonicity instead — with clear eyes about what that costs, since a client timestamp is an untrusted hint and can't do anti-grief. **Delegates are unaffected.** See `references/state-authorization-patterns.md` → "Time Handling".8485**Check your contract against all of this rather than trusting it:**8687```bash88fdev verify-merge --wasm your_contract.wasm --state s1.bin --state s2.bin89```9091It exercises the merge laws against a real corpus, and separately reports code diagnostics — `host_clock_import` being the one that exists today. A code diagnostic never fails the command: it describes the code, not a law the contract broke.9293**Efficiency:** Peers exchange **Summaries** (compact representations) and **Deltas** (patches/diffs) rather than re-downloading full state.9495**Requirement: `get_state_delta` must not ship state to a peer that already has it.** When the requester's summary shows it holds everything you have, the delta carries no information, so it must not contain the state or approach the state's size. It *should* be a literally empty `StateDelta` (`vec![]`), which is the unambiguous "converged" answer and what `freenet-scaffold` produces for you; a few tens of bytes of encoding framing from serializing an all-empty struct is acceptable. What matters is delta size relative to state size: 20 bytes against a 500 KB state is fine, a state-sized delta is a broken delta mechanism that re-ships everything on every reconciliation, forever. Your summary must likewise be far smaller than your state. Core is adding a probe for contracts that get this wrong, and it currently costs the network real bandwidth. Full detail, code shapes, and a test are in `references/contract-patterns.md` → "The Delta to an Up-to-Date Peer".9697### State and summaries must serialize canonically9899**Use deterministic maps everywhere in state AND summaries: `BTreeMap`/`BTreeSet`, never `HashMap`/`HashSet`.** Peers decide they have converged by comparing state bytes, so two peers holding the same logical state in a different byte order heal forever without ever agreeing. Canonical encoding is a platform requirement (freenet-core #5320), and the merge laws are checked on exact bytes because of it. A `HashMap` serializes in nondeterministic order (ciborium), so two identical states can summarize to different bytes and core's byte-level convergence check misfires — spurious heals, or missed ones. The same caution applies to any map inside whatever `summarize` returns.100101Beyond that, make sure your state genuinely converges through `summarize` / `delta` / `apply`, and test that it does, rather than assuming a live broadcast reaches every peer.102103> **Previously documented here as a live limitation, now fixed.**104> [freenet/freenet-core#4857](https://github.com/freenet/freenet-core/issues/4857)105> ("State updates permanently lost for rarely-changing fields") is **CLOSED**. A106> `ContractQueueFull` drop was silent, and the sender cached its own summary as107> the receiver's on send-Ok, so it believed the peer was current and never108> re-sent — leaving rarely-changing fields (config, permissions, ban lists)109> diverged until the ~5-minute InterestSync heartbeat happened to correct them.110>111> The shipped fix has the queue-full receiver emit a `ResyncRequest`, which makes112> the sender clear its poisoned summary and re-send full state. It is throttled to113> one per (contract, peer) per 30s, because114> [#4251](https://github.com/freenet/freenet-core/issues/4251) showed that one115> request per dropped delta amplifies into a full-state storm onto the same116> saturated queue; [#4862](https://github.com/freenet/freenet-core/pull/4862)117> hardened it against bridge backpressure. See `RESYNC_REQUEST_MIN_INTERVAL` in118> `crates/core/src/ring/interest.rs`.119>120> Do **not** design around multi-minute staleness on rarely-changing fields, and121> do not treat a ban list or permission field as needing to ride alongside a122> frequently-changing one. The earlier guidance to do so is retired.123124### Keep summaries small — it is measured, and it is expensive125126Summaries are **~23.7% of all outbound bytes on the Freenet network**, and the fleet-mean summary is **16,675 bytes** against a protocol digest-entry size of 21 bytes (freenet-core#5153). A fat summary is not a local inefficiency: it ships to every interested peer on every ~5-minute anti-entropy heartbeat whether or not anything changed, and it sets the floor for how cheaply a peer can be brought up to date.127128Every rule below is checkable in review and grounded in a measured finding from River.1291301. **Every summary field must be read by `delta()`.** Grep each field name against the `delta()` bodies. A field nothing reads is dead weight re-sent forever.1311322. **A value that is only ever compared for equality must be a fixed-width digest, never the thing it fingerprints.** River carried raw Ed25519 signatures in `member_info` purely to run `>`; replacing them with a 16-byte digest measured **135.27 → 28.01 bytes per entry**. The DM summary still does this for a bare `contains()` at 66 bytes/entry — 19,803 bytes at its cap, larger than the whole rest of the summary (freenet/river#596).1331343. **Size a digest by who controls the colliding inputs, not by taste.** If a party can grind *both* sides of the comparison, 64 bits is a ~2^32 birthday search — hours on commodity hardware — so use 128. If the attacker controls only one side, 64 may do. Write the threat model in the doc comment. A collision here is not a crash; it is a record that silently never propagates.1351364. **Assert the encoding; never derive it.** The *same* 64 bytes cost **66 CBOR bytes** as a byte string and **119** as a derived tuple — ciborium maps `serialize_tuple` to an array where every byte ≥ 24 costs two. River quoted 66 for a type that actually encoded at 119, and the wrong number survived an issue, a PR body, and a review. Hand-write `Serialize` with `serialize_bytes` for any fixed-size byte array, and pin it with a **golden vector**: one fixed input, one fixed expected digest, one fixed expected byte length. A randomised digest oracle misses byte-order bugs intermittently.1371385. **Measure size with realistic key values, not small integers.** A `FastHash(i)` for small `i` encodes in 1-3 CBOR bytes; a real key's encodes in 9. A test built from `0..N` understates the per-entry cost by ~30% and will pass review.1391406. **A summary should be O(1) or sub-linear in the collections it describes — or justify the linearity in writing.** A flat enumeration grows without bound as your app succeeds. If you keep it linear, state the element cap that bounds it and check `cap × per-entry` against your budget. River's is fully linear; at 200 members × 1000 messages it measures 16,723 bytes.1411427. **A lossy summary is legal when `apply_delta` is idempotent — exploit that.** K fixed buckets each holding an 8-byte digest of that bucket's contents makes the summary constant-size: measured **K=16 → 145 bytes, independent of N**, against 3,894 bytes for the flat form at 139 members. `get_state_delta` may then return a *superset* of the true delta, which is sound only if applying an already-held element is a no-op — verify that first. The trade is real: one changed element resends its whole bucket. It wins because summaries go out on every heartbeat while deltas fire only on change, so **measure your summary-broadcast : state-change ratio before committing.**1431448. **A capped or pruning collection needs a retention horizon in the summary.** Without one, `delta()` is a pure set difference: the receiver prunes what it just received, neither summary changes, and the pair re-sends forever. Publish the oldest key *held*, only at capacity, so it strictly increases each exchange and the loop provably terminates.1451469. **Nothing in a summary should reveal information the recipient is not entitled to.** A summary goes to more peers, more often, than state does. River's DM summary advertises every DM in the room to every member, participant or not, leaking exact DM volume.14714810. **A summary is a wire-format commitment: changing it re-keys the contract and strands every existing copy.** Which hash, how wide, which bytes in which order, and how it serializes are all frozen at publish. Keep a registry of past generations (River keeps `legacy_room_contracts.toml`, 31 entries) and expect every abandoned generation to keep costing anti-entropy bandwidth indefinitely — one stranded River generation is currently doing 3,829 failed summary comparisons against **zero** update events (freenet-core#5158). Batch summary changes rather than shipping them one at a time.149150## Advanced Capabilities151152- **Subscriptions:** Clients can subscribe to contracts and get notified of changes immediately (real-time apps)153- **Contract Interoperability:** Cross-contract reads are implemented and working.154 `validate_state` can return `ValidateResult::RequestRelated(Vec<ContractInstanceId>)`;155 the host fetches those contracts and re-invokes with `RelatedContracts` populated156 (`fetch_related_for_validation_network` in157 `crates/core/src/contract/executor/runtime/contract_ops.rs`, on both the PUT and158 UPDATE paths). The machinery behind it is real: a related fetch that would block the159 serial contract loop is deferred to an off-loop waiter, bounded by160 `MAX_INFLIGHT_DEFERRALS = 256` with an RAII guard giving exactly-once resume, and an161 over-cap op surfaces `MissingRelated` rather than growing unboundedly162 (freenet-core#4391, `crates/core/src/contract.rs`). freenet-core#2870 ("Complete163 related contract mechanism implementation") is still open but is itself partly stale —164 the UPDATE-path `todo!()` it cites at runtime.rs:946 no longer exists.165166**The thing to get right is not whether it works, but what you are allowed to read.**167A contract's verdict must be a function of its inputs, or replicas diverge. Reading168another contract widens the input set to something that changes underneath you:169170- Reading an **immutable** fact (a certificate, a signed key) is safe — every peer gets171 the same answer forever.172- Reading a **monotonic** fact in the once-true-always-true direction is safe.173- **Gating validity on mutable or growing state is not.** "Reject if the other party has174 more than N entries" flips from valid to invalid as their state grows, so peers175 validating at different moments disagree and never converge. That class of rule belongs176 in client-side policy, not in `validate_state`.177178Practical limits:179180- **One round only.** A `RequestRelated` is fetched and retried **exactly once**; a181 second is an error (`contract/executor/runtime/contract_ops.rs:431-432`), capped at182 `MAX_RELATED_CONTRACTS_PER_REQUEST = 10` ids. No chained dependencies.183- On the client-facing UPDATE surface, `UpdateData::RelatedStateAndDelta` is the form184 you send; bare `UpdateData::RelatedState` / `RelatedDelta` are rejected from185 `ContractRequest::Update` and reserved for the runtime's own request-related186 orchestration, which surfaces `RelatedState` to your WASM itself.187- A related fetch that times out can wedge an UPDATE merge (freenet-core#4077, open).188- Related state resolved during *validation* **is** captured, since **v0.2.131189 (2026-08-24)** — freenet-core#5393 and #5402. Before that, a contract whose validity190 depended on another contract was permanently unjudgeable, and an unjudgeable191 contract reads exactly like a clean one. Note issue #5376 closed on 2026-09-06, a192 fortnight after the code shipped: **a close date is bookkeeping; the release tag is193 what makes a mechanism available.** Checking that for yourself has its own trap —194 this repo squash-merges, so the SHAs an issue timeline cites are branch commits that195 never exist in `main`. Searching the log for them, or for the issue number, finds196 nothing in any tag and reads exactly like "never shipped". Go by PR number, and197 confirm with `merge-base --is-ancestor <merge-sha> <tag>`.198- **Judgeable is not judged.** The verifier never *fetches* related state; it replays199 only what the bundle already carries, mapping any `RequestRelated` straight to200 `Inconclusive::RelatedRequired` (`conformance/verifier.rs:997-1005`). Production is201 stricter — the executor fetches and re-validates once at depth=1202 (`executor_impl.rs:2461`) — and that path is never exercised by the verifier.203 Capture also keeps only the most-recently-observed state per related contract, so a204 defect needing a specific or older one yields no verdict at all: measured 1,567 of205 5,856 replayed cases inconclusive for want of related state, five contracts with no206 verdict on *any* case (`conformance/capture.rs:108-125`). That file states the intent207 plainly — "depending on related state must not be a way to escape conformance208 checking" — and coverage starvation is how it still can.209- **`fdev verify-merge --state <files>` is blind to related contracts.** The210 non-`--bundle` path leaves `related` unconditionally empty211 (`fdev/src/conformance.rs:912-915`), so a contract of this shape comes back 100%212 inconclusive on every property — which, skimmed for violations, reads as a clean213 bill. Check on the `--bundle` path, confirm the bundle reports `related_entries > 0`,214 count the explicit verdicts, and treat **inconclusive as not a pass**. Exit code 4215 means violations were found and the JSON is complete.216- `freenet-scaffold`'s `#[composable]` has no inter-contract awareness217 (freenet-core#2870), so cross-contract dependencies are hand-rolled.218219The mechanism with code, and which of the two paths to request related state220from, is in `references/state-authorization-patterns.md` →221"Related-Contracts Mechanism".222223---224225## Development Workflow226227Follow these phases in order.228229> **Building on an app you do NOT own** — reading River rooms, using the230> ghostkeys delegate, indexing another project's contracts? Do not hardcode231> their contract or delegate key. It is `BLAKE3(BLAKE3(wasm) ‖ params)`, so it232> moves on every re-key of theirs, including a bare version bump, and the233> failure is silent: every read comes back looking like "this user has nothing234> stored". Pinning a version of their crate does not help — that pins you to235> their view of the key as of their release, which is the thing that went stale.236> Fetch their key at runtime instead: resolve their author-signed pointer if237> they publish one, and otherwise read it from their webapp bundle, which is238> what ghostkeys does today. Pointer adoption is thin, so expect the fallback to239> be the path for most apps right now. Either beats a compiled-in constant. See240> `references/building-on-other-apps.md`.241>242> **Working on an app that already exists?** Before anything else, check whether243> it hardcodes a *delegate key* belonging to a platform delegate it does not own244> (ghostkeys being the one in use today). That constant goes stale on every245> re-key of that delegate — including a bare version bump — and the failure is246> silent: every request comes back looking like "this user has nothing stored".247> One grep, and the fix is a runtime fetch. See248> `references/delegate-patterns.md` → "Depending on Someone Else's Delegate".249> This broke every ghostkeys integration in August 2026 and was found by a250> confused user rather than by any test.251>252> **Already shipped v1 and here to UPGRADE?** (bump `freenet-stdlib`, ship a new253> contract/delegate version, or fix a bug that re-keys the WASM) — go straight to254> **`references/upgrade-and-migration.md` → "Upgrading a Freenet dApp — the painless255> path"**, the single start-to-finish playbook. A routine WASM/stdlib bump is256> **low-risk and mechanical when you designed for it at v1**, not "recreate257> everything and all invites die" — River's live 0.6→0.8 stdlib re-key (verified258> 2026-07-12) auto-migrated every room on refresh, kept every invite and the259> 78-member Official room intact, and needed no recreation. The phases below build260> a *new* dApp; the playbook ties the upgrade steps together (v1 design261> precondition → reproducible builds → register the outgoing hash → `freenet-migrate`262> → publish → do NOT recreate instances or warn of dead invites).263264### Phase 1: Contract Design (Shared State)265266Start by listing each *kind* of shared state your app needs — each kind becomes its own contract crate. Then design each one in turn using the questions below.267268**Key questions (per contract):**269- What data must all users see consistently for this concern?270- How should conflicts be resolved when two users update simultaneously?271- What cryptographic verification is needed?272- What are the state components and their relationships?273- What parameters distinguish one instance from another (e.g. room owner key, profile owner key)?274- If users reference each other (messaging, contacts, profiles), what is the user-facing identifier? It should be short, self-certifying, and stable across WASM upgrades — derived from a key, never a contract key. See `identity-and-addressing.md`.275- How is each *record inside* this state identified, and does that id cover every term a reader will later rely on it to bind? A writer-supplied nonce, or an id that hashes only some of a record's terms, lets one author sign two different records under one id — and under a first-writer-wins merge that is **permanent divergence that cannot heal**, because both peers' summaries already name the id. Derive ids from content, compute them in the contract, and have exactly one function decide "are these the same thing". Get this right before launch: changing a derivation afterwards makes every published record unverifiable, which is a breaking change to users' data. See `contract-patterns.md` → "Record Identity".276- Can strangers write to this contract? If so, what stops one attacker minting ten thousand keys and flooding it? There is no server to host a CAPTCHA, so the mechanisms available are proof-of-work and ghost keys (a blind-signed certificate proving an anonymous donation — a cost the attacker cannot beat with better hardware, and not burned as waste heat). **The recommended shape is both**: proof-of-work as the always-sufficient default, with a ghost key offered as a way to *skip the wait*, surfaced while the grind is running and the user is blocked anyway. That lets you set difficulty by what deters an attacker rather than by what your slowest device tolerates, while never pricing anyone out. See `identity-and-addressing.md` → "Cryptographic CAPTCHA". **Present the choice to the developer rather than picking silently**: ghost keys cost their users money, that money funds Freenet, and the mint is centralized (verification is not). Those are product and architecture decisions, not technical details to settle on the developer's behalf.277- How large can this contract's state realistically grow? **Keep each contract instance's state small — target well under 4 MB, not just under the host's 50 MiB hard cap.** A GET transfers the *entire* state before the UI can render anything, so state size is felt directly as load latency, and `validate_state`/`update_state`/`summarize_state` WASM execution cost scales with it too. If a kind of data can grow without bound (message history, uploaded files, a membership list that only grows), don't let one contract instance absorb all of it — shard by the natural unit of write concurrency instead (one contract per room, per user, per time-window, per shard-key, etc.), so each instance stays small regardless of how large the *dataset* gets in aggregate. See `state-authorization-patterns.md` → "State Size Budget".278279**Implementation steps:**2801. Define state structure using `#[composable]` macro from freenet-scaffold2812. Implement `ComposableState` trait for each component2823. Implement `ContractInterface` trait for the contract2834. Ensure all state updates satisfy the merge laws (associative, commutative, idempotent), and that `get_state_delta` returns a negligible delta (ideally zero bytes, never state-sized) when the requester's summary already matches your state (see `contract-patterns.md`)2845. **Every field in state must be covered by a cryptographic signature** -- contracts run on untrusted peers who can modify unsigned fields. Write a test for each signed field verifying that tampering causes verification failure. See contract-patterns.md for versioned signature patterns when adding fields later.2856. **Plan contract upgrade from v1 — it's low-risk and mechanical when you design for it.** The property that makes it mechanical is that **a new contract version accepts old contract state**, so migration is pure data transfer and *any* client can carry a user forward — including a user who never opens your app again. Once you have users that stops being a preference and becomes a constraint on which changes you may make: a change to how a record's identity is derived breaks it by construction, and is a breaking change to users' data rather than an internal refactor. See `upgrade-and-migration.md` → "A New Version Must Accept Old State". A WASM change moves the contract key, but if you anchor your app's durable references on a **stable identity anchor independent of the WASM** — an owner/user key, fixed singleton params, a DID, or an index contract mapping a stable name → current key (options in `upgrade-and-migration.md` step 1) — the upgrade is transparent: the client re-derives the new contract key from the *unchanged* anchor, so invites, share links and membership survive. River's 0.6→0.8 re-key on the live network kept every room and invite; recreation is only for deliberately rotating the anchor itself, never for a routine contract/stdlib bump. State is carried forward by a backward probe from a committed legacy-code-hash registry, packaged by the `freenet-migrate` crate (0.6.0, with `freenet-migrate-build` 0.2.0) — do not hand-roll it. **Read the `freenet-app-migration` skill before writing any of it, if you have it**: it owns the migration doctrine — when to probe, which probe outcomes may seal a completion marker, and the failure modes that lose data with a green build. It ships separately from this plugin, so if it is not installed, `contract-patterns.md` and `upgrade-and-migration.md` carry the same rules and are enough to build against. See `contract-patterns.md` → "Contract WASM Upgrade & State Migration" for the key-derivation mechanism, `upgrade-and-migration.md` for the operational discipline, and the `freenet-migrate-adoption` skill for swapping an existing hand-rolled sweep over to the crate.2867. **Read `state-authorization-patterns.md` before designing the second iteration.** It captures cross-cutting patterns (per-item vs bundled signatures, replay protection via monotonic counter / tombstones / cross-context binding, signed-payload hygiene, why a contract must not read the host clock and what to carry instead, related-contracts limits, wire-format stability) that bite on every contract beyond the trivial.287288References:289- `references/contract-patterns.md` — `ContractInterface`, the merge laws, composable state, basic signatures.290- `references/state-authorization-patterns.md` — authentication, replay protection, signed-payload hygiene, time (contracts must not read the host clock), related-contracts, wire-format stability, common pitfalls.291- `references/identity-and-addressing.md` — short self-certifying user-facing addresses, keeping large (post-quantum) keys out of identifiers, identity that survives WASM upgrades, and blocking bots without a server (ghost keys vs proof-of-work).292293### Phase 2: Delegate Design (Private State)294295Determine what private data each user needs stored locally and split it across delegates by responsibility (e.g. one delegate per trust boundary or per long-running background task). Most apps need at least one delegate; many need several.296297> **Know the limits before you lean on a delegate for background work.** A298> delegate runs only when something pokes it: there is no scheduled wakeup299> (freenet-core#3972). Its contract GET reads the local store only, and its300> contract subscribe registers no network demand, so subscribing does not keep a301> contract alive in the network (freenet-core#4669). Both are open with no fix302> merged as of 2026-08-30.303> Test that work against a real node: `freenet local` never runs the loop that304> services a delegate's contract requests, so a delegate's GET, PUT, UPDATE and305> SUBSCRIBE all silently do nothing there (freenet-core#5273).306> `references/delegate-patterns.md` → "Delegate Capabilities" has the verified307> detail and the current state.308309**Key questions (per delegate):**310- What user-specific data needs persistence? (keys, preferences, cached data)311- What signing/encryption operations are needed?312- What permissions are needed for sensitive operations?313- Does a **platform delegate** already do this? Delegates are callable across apps, so some responsibilities are worth borrowing rather than building. [ghostkeys](https://github.com/freenet/ghostkeys) is the one that exists today: it holds the user's ghost-key identities and signs on your behalf, and it renders the user's allow/deny prompt itself, so you implement no permission flow. See `identity-and-addressing.md` → "Cryptographic CAPTCHA" for what it is for, how it pairs with proof-of-work as an escape hatch rather than replacing it, and the two caveats worth relaying to the developer: the mint is centralized, and Freenet has a funding interest in you choosing it.314315**Implementation steps:**3161. Define request/response message types3172. Implement `DelegateInterface` trait3183. Handle secret storage operations (Store, Get, Delete, List)3194. Implement cryptographic operations (signing, encryption)3205. **Design for secret migration from v1** -- when delegate WASM changes, the delegate key changes and all stored secrets become inaccessible. There is **no `ExportSecrets` request in the stdlib wire protocol** and no node-level copy-forward. The mechanism messages each old delegate key via `DelegateRequest::ApplicationMessages`, re-running the old WASM to read its secrets, and folds the signing keys forward (encryption secrets are re-derived) — so **only a predecessor whose already-deployed WASM answers can be recovered from**, which makes this forward-only. `freenet-migrate` ships that answer as `handle_export_request` (since 0.3.0) for you to call from your delegate; River needs no *special* handler only because its chat delegate already answered a general-purpose `GetRequest`/`ListRequest` over its own secret namespace, which most delegates do not. Every release shipped without an export answer adds one permanently unrecoverable generation — see delegate-patterns.md → "A delegate migration is forward-only". Keep a committed registry of old delegate keys and migrate promptly — the re-run breaks after a stdlib/ABI bump (freenet/river#204). See delegate-patterns.md for the mechanism; `freenet-migrate` codifies the delegate registry and build codegen, but delegate secret carry-forward has no core mechanism and never will — a node-level attempt (`RegisterDelegateWithPredecessors`) was built, shipped, then found forgeable and disabled as a security fix (freenet-core#5199), and after three rejected trust-model designs, app-level migration is settled standing policy, not an interim measure. App-level does not mean bespoke: `freenet-migrate` ships the delegate-side entry points (`migrate_delegate_secrets`, `register_delegate_with_migration`, unchanged since 0.5.0; crates.io is now 0.6.0, whose break is contract-half only), and River, Delta and ghostkeys all drive them on `main` at 0.5.0. Note that River and Delta run the crate's walk *alongside* their existing hand-rolled sweep, which stays authoritative for now; retiring the sweep is a later release, after the walk field-validates. See delegate-patterns.md → "Delegate secret migration: no core mechanism, and why" for the full history, the `freenet-migrate-adoption` skill for the swap procedure, and freenet-core#2776 for live status. See `upgrade-and-migration.md` for the operational discipline (resumable/interrupted-migration recovery, migration telemetry, and the upgrade test harness).321322Reference: `references/delegate-patterns.md`323324### Phase 3: UI Design325326Build the user interface connecting to contracts and delegates. Two approaches:327328#### Option A: Dioxus (Rust → WASM)329330Best for: teams already in Rust, complex state logic shared with contracts.331332**Implementation steps:**3331. Set up Dioxus project with WASM target3342. Implement WebSocket connection to Freenet gateway3353. Create synchronizer for contract state subscriptions3364. Implement delegate communication for private storage3375. Build reactive UI components3386. **Vendor your stylesheets, fonts, and scripts.** The gateway serves every339 webapp under a same-origin CSP — CDN `<link>` / `<script>` tags from340 `cdn.jsdelivr.net`, `cdnjs.cloudflare.com`, `fonts.googleapis.com`, etc.341 are blocked in production even though they work in `dx serve` /342 `vite dev`. See `references/ui-patterns.md` "Gateway CSP: Vendor Your343 Assets".344345#### Option B: TypeScript + Vite346347Best for: web developers, faster iteration, familiar tooling (npm, SCSS, etc.).348349**Implementation steps:**3501. Set up Vite project with `@freenetorg/freenet-stdlib` (TypeScript package)3512. Use `FreenetWsApi` class for WebSocket connection (handles FlatBuffers serialization)3523. Pass empty string auth token to `FreenetWsApi` constructor (sandbox blocks cookie reading)3534. Use Vite `define` to inject contract hashes and delegate key bytes at build time3545. For delegate communication, dynamically import internal FlatBuffers types (`ClientRequestT`, `ApplicationMessagesT`, etc.)3556. Build reactive UI with vanilla TS, or any framework (React, Vue, Svelte)356357#### Validate the UI in a real browser (both options)358359A Freenet UI's real render path only runs in a browser. A Dioxus UI ships as a360WASM bundle, so rendering a component tree to a string in a Rust test does not361exercise the compiled bundle, its event handlers, or its asset paths, and both362options reach the node over a WebSocket that unit tests never touch.363**Drive the UI with Playwright (or equivalent browser automation) from364the first screen onward, not only at release time.** Treat "I built the365component" as unfinished until a browser has loaded it and a script has clicked366through it.3673681. Serve the UI locally (`dx serve` for Dioxus, `vite dev` for TypeScript) and369 drive it with Playwright against mock or offline data, so render correctness,370 navigation, and form validation gate every PR. This is the `offline` tier in371 `references/production-smoke-testing.md`, which has a starter spec.3722. Assert the browser console is clean in every flow. WASM panics, failed373 requests, and CSP blocks surface only as console or network errors, so a UI374 that looks correct in a screenshot can still be panicking on every375 interaction.3763. Once a local node is running, re-run the same flows against the377 gateway-served webapp (the `iso` tier). Reaching your app there needs378 `frameLocator` and an absolute-URL `goto`, because the gateway wraps every379 webapp in an iframe shell.380381For interactive debugging rather than scripted specs, the Playwright MCP browser382tools drive a running `dx serve` or local node directly. See the `local-dev`383skill, "Debugging with Playwright".384385References:386- `references/ui-patterns.md` - WebSocket connection models, gateway CSP,387 serving large binary assets from a dedicated contract, framework-specific388 patterns.389- `references/production-smoke-testing.md` - the four test tiers, the390 development-loop browser-validation recipe, and the iframe-shell Playwright391 idioms.392393### Phase 4: Build, Test, and Deploy394395Set up the build system, CI, and deployment pipeline.396397**Implementation steps:**3981. Set up build orchestration — either `Makefile.toml` (cargo-make) or plain `Makefile`3992. Add a preflight task that runs fmt, clippy, tests, and migration checks before publish4003. Add GitHub Actions CI workflow (runs on push and PRs)4014. Back up contract state to the delegate for network resilience4025. **Add a production-liveness smoke test.** A ~50-line Playwright spec403 asserting the gateway-hosted webapp mounts, vendored CSS loaded, and the404 browser console is clean catches CSP blocks, iframe-shell mistakes, and405 broken archives that no unit test reaches. See406 `references/production-smoke-testing.md`.4076. **Check the gateway port, and make the build reproducible.** The408 gateway runs on `7509` — older docs and scripts still reference `50509`.409 For byte-reproducible webapp archives across build hosts, invoke `tar`410 with the GNU flags listed under "Tooling Preflight" in411 `references/build-system.md`.412413 **Contracts need more than reproducible tars, and this part is not414 optional** — the WASM bytes *are* the contract's address. Build them through415 one canonical script that remaps `CARGO_HOME`, `RUSTUP_HOME` **and** the repo416 root, and that refuses the build if any build-machine path survives into the417 WASM. Remapping only your own source path leaves the cargo registry's absolute418 paths in the bytes, which binds every contract to the machine that b419420…(truncated)