Relay & Subscription
The paid relay mesh: the Subscription contract that keeps the registry, the RelayNode contract each operator runs, how fees are quoted and paid, how clients register and resolve each other, and how encrypted mail moves between relays. Companion pages: Contact & Handshake and Groups & Contracts.
1. Overview — two contracts, one market
Offline delivery needs someone to hold your mail. Undertown makes that a market with two contract types, deployed per network:
| Contract | One per… | Role |
|---|---|---|
Subscription |
network | The registry: which user pays which relay, until when; which relays are registered and unblocked; fees in USD; the price feed. |
RelayNode |
relay operator | The relay's own record: owner, per-period fee, contact code (where its signed Contact lives), deny flags, group registrations. |
A user subscribes to a relay (paying in native currency, priced in USD);
a relay registers on the Subscription contract (also paid); and every
handshake later — client registration, relay-to-relay transfer, resolution —
falls back to the same on-chain question: hasSubscription(wallet, relay).
2. The Subscription contract
uint256 REGISTRATION_PERIOD = 10 days // one billing period uint256 MAX_REGISTRATION_PERIODS = 109 // relay may register up to ~3 years ahead struct SubscriptionEntry { address relayContract; uint256 expiresAt; } address admin; // deployer address priceFeed; // Chainlink feed (or zero for manual) uint256 manualNativePrice; // wei-per-USD when no feed uint256 registrationFeeUSD; // relay operators, per 10-day period uint256 subscriptionFeeUSD; // users, per add/renew call mapping(address => SubscriptionEntry[]) subscriptions; mapping(address => uint256) registeredUntil; // relay => paid until mapping(address => bool) blockedRelays;
Key functions, by role:
| Role | Function | Effect |
|---|---|---|
| user | addSubscription(relay) payable | Pay the quoted total; the Subscription contract forwards to the relay's subscribe() and records your expiry. |
| user | renewSubscription(relay) payable | Extend expiresAt by the paid periods. |
| user | removeSubscription(relay) | End the subscription (no refund of elapsed time). |
| operator | registerRelay(relay) payable | Pay registration periods for a RelayNode; rejected if a subscription period would outlive the registration. |
| relay | removeSubscriber(wallet, relay) | A relay ends its own relationship with a subscriber. |
| admin | blockRelay / unblockRelay / adminForceUnregister / pruneRelayList | Curation: bad relays disappear from discovery and can be force-removed (their registered slots cleaned). |
| admin | setRegistrationFee / setSubscriptionFee / setPriceFeed / setManualNativePrice / setMetadata / withdraw | Market configuration and treasury. |
| view | getSubscriptions(wallet), hasSubscription(wallet, relay), getActiveRelays(), isRelayRegistered(relay), getRegisteredUntil(relay), getBlockedRelays() | Everything the mesh needs to verify claims — these views are what handshakes call. |
3. The RelayNode contract
address owner // the operator (set at deploy) address immutable subscriptionContract // permanently wired to one registry string contactCode // base58 Contact — the relay's network identity string name, description, site // discovery metadata uint256 feeUSD // user fee per 10-day period bool denyNewUsers, denyRenew // operator switches mapping(address => address[]) userRegisteredGroups; // groups each user linked (max 20)
contactCodestores the relay's base58 contact code — the same signed-Contact format users carry (see Contact & Handshake). Discovery needs no phonebook: read the contract, verify the signature, dial the multiaddrs inside.subscribe(user, feeNative, periods)is callable only by the Subscription contract (onlySubscription). It verifies the payment matchesfeeUSD × periods, refunds any excess to the user, and emitsSubscribed. This cross-contract call is what makes "add subscription" atomic: one transaction, both ledgers.isSubscribed(wallet)delegates to the immutable registry'shasSubscription(wallet, this)— the same check the registration handshake and groupaddRelayMemberrely on.registerWithGroup(group)lets a subscriber link this relay to a group they belong to (max 20 per user) — the trigger behind group relay membership (Groups & Contracts, section 8).- Owner-only switches:
setFee,setMetadata,updateContact,setDenyNewUsers,setDenyRenew,withdraw.
4. Pricing — from USD to wei
Fees are authored in USD so operators can think in dollars while users pay in native currency. The conversion has two branches, and the client mirrors the contract's arithmetic exactly (same truncation, same overflow behavior):
// Chainlink feed configured: native = feeUSD × 1e18 × 1e8 / answer // answer: 8-decimal feed price // Manual price set (feed = 0x0): native = feeUSD × manualNativePrice // operator pins wei-per-USD
- Per-fee conversion, then sum — a total quote converts each fee (subscription + relay) separately and adds the results; converting the sum instead can differ by 1 wei, and the client asserts the contract's ordering.
- Checked math — the client's quoting helpers overflow (revert) exactly where Solidity 0.8 would, and treat non-positive feed answers as typed
InvalidPriceerrors, mirroring the contract'srequire(price > 0). - Simulate before spend — every payable operation runs an
eth_callfirst, so on-chain revert reasons ("Insufficient payment", "Relay registration expires before subscription period") surface in the dialog before gas is spent. - Pay exactly the quote — the wallet sends the wei the quote produced; the relay's
subscribe()refunds any overpayment automatically.
5. Operator lifecycle
- Deployment is a CLI job (
utdeploy) — unlike group contracts, infrastructure contracts are not deployed in-app. - Registration periods (10 days each, up to 109) must always cover any user subscription sold:
addSubscriptionreverts with "Relay registration expires before subscription period" otherwise. Operators therefore renew registration ahead of demand. denyNewUsersstops new subscriptions while honoring existing ones;denyRenewstops renewals too — a graceful way to sunset a relay.- The operator's contact code is how clients find the relay's multiaddrs; updating it is a single
updateContacttransaction.
6. Subscriber lifecycle
All of this is driven from Settings → Relays & Subscriptions (or the 33-tool MCP surface, section 10):
- Browse — pick a tracked contract + chain; the app calls
getActiveRelays()and per-relay metadata to render name, description, and fee. - Quote —
subscription.quote_addreturns the exact breakdown: subscription fee (USD & wei) + relay fee (USD & wei) = total in ETH, with the price-source hint. Nothing is sent until you confirm. - Subscribe —
subscription.addbroadcastsaddSubscription; success surfaces the tx hash and refreshes your list. Expiry comes back fromSubscriptionEntry.expiresAt. - Renew — same flow with
renewSubscription; expiry extends by the purchased periods. - Remove —
removeSubscription(a plain, non-payable transaction — no quote needed).
Tracking a contract. The app only browses Subscription contracts it
tracks. Tracking writes the chain:0xaddress entry into your signed
Contact (subscriptions: line) and re-signs it — which is what lets your
peers, and the relay mesh, trust which networks you belong to. Untracked contract? The
settings tab offers a one-click "Track this contract" recovery.
7. Client registration at the relay
An on-chain subscription is entitlement; registration is how the relay learns who its clients actually are. It is the wallet-signed challenge-response covered fully in Contact & Handshake §9. In brief:
relay.client_register→ challenge (single-use nonce, bound to the relay's own address, 5-minute TTL) →relay.client_confirmwith a wallet ECDSA signature over the frozen canonical message.- The relay re-verifies the signature, re-checks
hasSubscriptionon-chain (10-minute cache, RPC errors never cached), and admits the client to the verified set for 10 minutes; renewal is a fresh handshake. - Failures are typed (
bad_signature,no_subscription,challenge_expired,rate_limited, …) and rate-limited 5 per 10 minutes per claimed wallet. - Registration grants delivery service only — the relay caches ciphertext and holds no decryption keys.
8. Resolution — finding a recipient's relay
When you send to someone served by a different relay, your relay must find theirs. It asks the registry, never a contact book:
Subscription.getSubscriptions(recipient) // unexpired entries only
│
▼ for each: RelayNode(relay).contactCode()
base58 contact code ──► decode ──► verify wallet signature
│
▼ trusted multiaddrs of the recipient's relay
dial & transfer
- The relay filters out its own address and verifies every Contact signature before trusting the addresses inside.
- There is an executable test proving the resolver never reads user contact tables — the registry is the only source of routing truth.
- For client-to-client delivery, a second tier exists (your Contact's
directthenrelayaddresses), but cross-relay routing is registry-only. - Results are cached 10 minutes and invalidated the moment the recipient's Contact signature changes.
9. Relay → relay transfer
With the destination resolved, the holding relay dials the recipient's relay for a single ephemeral transfer, gated by the three-factor handshake (full detail in Contact & Handshake and the narrative in the blog post):
- Sender's signature — a routing authorization the client signed at push time, listing the exact posts, both relays, both users, and a 1-hour expiry.
- The registry's word — on-chain:
isRelayRegistered(relayA),hasSubscription(sender, relayA),hasSubscription(recipient, relayB). - Operator challenge — a fresh nonce signed by relayA's contract owner, recovered against a live
owner()read.
The queue behind it is built for failure:
| Parameter | Value | Meaning |
|---|---|---|
TRANSFER_MAX_POSTS | 64 | Per-connection chunk; oversized batches are split, each chunk covered by the same authorization. |
TRANSFER_MAX_BYTES | 256 KiB | Per-connection byte cap. |
| Routing-auth TTL | 1 hour | Authorizations expire; nothing is delivered without a valid one. |
| Queue entry TTL | 24 hours | Unroutable entries die of old age. |
| Per-target cap | 2 MiB | Bounded memory per recipient. |
| Attempts / backoff | 5 · 30 s × 2ⁿ (cap 1 h) | Exponential retry between sweeps (60 s). |
| Dead-letter store | 500 entries | Bounded graveyard with per-post reasons. |
| Session TTL | 5 minutes | One transfer per connection; the session is consumed on ack. |
Everything crossing that handshake is ciphertext — the
enc: payload plus routing clocks. Live end-to-end tests assert both relay
databases end with zero plaintext rows; only the recipient's device, holding the channel
key, ever decrypts.
10. The tool surface (MCP)
Every operation above is scriptable over the built-in MCP server — 33 tools, no deploy surface:
| Group | Tools |
|---|---|
| Config | subscription_set_contracts (re-signs your Contact; needs password), subscription_get_contracts |
| User | subscription_add, subscription_renew, subscription_remove, subscription_list, subscription_has, subscription_quote_add, subscription_quote_renew |
| Relay (user) | relay_get_info, relay_quote_register, relay_groups_register, relay_groups_unregister, relay_groups_list |
| Relay (owner) | relay_owner_set_fee, relay_owner_set_metadata, relay_owner_update_contact, relay_owner_set_deny_new_users, relay_owner_set_deny_renew, relay_owner_withdraw |
| Admin | subscription_admin_set_registration_fee, set_subscription_fee, set_metadata, set_price_feed, set_manual_price, block_relay, unblock_relay, force_unregister, withdraw, prune_relays, blocked_list |
| Discovery | subscription_active_relays, subscription_relay_info |
Every write funnels through the password/session-key path and simulates with
eth_call before broadcasting; owner-only relay operations are guard-checked
against owner() before a transaction is even built.
11. Security notes
- The registry is the only routing truth. Neither relays nor clients take anyone's word about who is served where — they read
getSubscriptions()and verify the contact code's signature. - Fees cannot be gamed. Quotes mirror contract math branch-for-branch with checked arithmetic; payment is exact; overpayment is refunded on-chain; underpayment reverts with the contract's own reason string.
- Operators are accountable. Registration is paid, time-boxed, prunable by admins, and blockable — with every state change emitting an event.
- Cross-contract calls are privilege-walled.
subscribe()is reachable only from the immutable Subscription contract;addRelayMemberonly from a RelayNode proving a live subscription. - Entitlement ≠ access. A subscription buys delivery. Decryption needs the channel key, and the relay never holds one.
- Everything is reproducible. Golden-vector tests pin the quoting math; live end-to-end tests pin the delivery path against real deployed contracts.