Groups & Contracts

How Undertown groups work as on-chain smart contracts: the contract itself, ownership and admin management, the three ways to join, relay membership, channels and group keys. Everything below mirrors the open-source Solidity contracts.

1. Overview — the group is the contract

A Undertown group is not a row in someone's database. It is a smart contract deployed on a blockchain network — one of two flavors:

ContractJoining model
GroupPublic Anyone calls addYourself() and is active immediately — no approval.
GroupPrivate addYourself() puts you in a bounded pending queue; an admin must approve (or you redeem an invite, or an admin adds you directly).

Both inherit from GroupBase, which owns all shared state: membership, roles, invites, relay registration, and the event log. The contract is the single source of truth — whoever the contract says is a member, is a member; whoever it says is blocked, is blocked. Your app mirrors that state locally in a per-contract runtime environment (message cache, sync engine, watchdog) but never overrides it.

2. What the contract stores

address  creator                        // set at deployment; the group's owner
enum UserStatus { None, Pending, Active, Blocked }
struct UserInfo {
  UserStatus status;                    // membership state machine
  bool       isAdmin;                   // admin flag (Active required to exercise)
  uint64     joinedAt;                  // activation timestamp
  uint64     userNonce;                 // monotonic membership counter
}
mapping(address => UserInfo) userInfo;
uint64 nextUserNonce;                    // never reused — incremented on every activation & block
struct Invite { uint256 limit; uint256 used; address creator; bool exists; }
address[] groupRelays;                   // RelayNode contracts serving this group

The userNonce deserves attention: it is assigned from a monotonic counter on every activation and is incremented again whenever the user is blocked — the contract's own documentation calls this out as the hook for key rotation. A re-activated member never carries the same nonce as before.

3. Roles & permissions

The deployer is the creator (owner). At construction they are automatically the first Active member and admin, receiving userNonce = 1. Admin power is status-aware: the isAdmin() view requires Active && isAdmin, so a blocked admin has no powers — including over other users. The creator can never be blocked and never lose the admin flag (setAdmin(creator, false) reverts).

FunctionCallerEffect
addYourself()anyonePublic: None → Active. Private: None → Pending (queue cap: 20).
addUser(addr)adminDirect activation, or approval of a pending request.
approveRequest / rejectRequest (+batch)adminPrivate only: resolve one or many pending requests.
createInvite(limit)adminMint an invite that can be redeemed limit times.
useInvite(id)anyone not BlockedRedeem: Pending/None → Active; no-op upgrade if already Active.
setAdmin(addr, bool)adminGrant/revoke admin. Target must be Active; creator's flag is permanent.
blockUser(addr)admin→ Blocked, userNonce++ (key rotation). Creator is immune.
unblockUser(addr)adminBlocked → Active.
removeUser(addr)the user or adminSelf-leave or removal: everything reset to None, UserRemoved emitted.
recoverCreator()creatorEmergency self-recovery: un-block, re-admin, or re-activate the creator.
addRelayMember(user)a RelayNode contractRegister that relay as a group relay (see section 8).
removeRelayMember(relay)adminRemove a group relay (O(1) swap-and-pop).

Deployment = ownership. Whoever deploys the contract is its creator: the constructor takes an _owner argument (passing 0x0 means msg.sender), grants that address the first membership and admin flag, and emits UserAdded + AdminRoleSet in the same transaction. There is no separate "transfer ownership" step to forget — ownership simply is the deployer's wallet from block one.

4. Deploying a group

Group contracts are deployed from the app. The Add-Contract wizard collects a name, the target network, and the privacy choice, then sends a single contract.deploy packet to the local backend:

{
  "name":                 "my-group",       // display label
  "is_private":           false,            // GroupPublic vs GroupPrivate
  "network_id":           "<added network>",// must exist in your networks table
  "require_user_approval": true,            // pending-queue behavior hint
  "password":             "..."             // unlocks the session wallet key
}

The backend validates the network, unlocks the signing session, and broadcasts the constructor transaction signed by your wallet — you are the owner from the moment the contract exists. Once confirmed, the address lands in your contract registry and sidebar. Deployment costs gas on the target network.

Group contracts are the only contracts deployed in-app. The infrastructure contracts — Subscription and RelayNode — are deployed with the separate utdeploy CLI by relay operators.

5. Joining a public group

One transaction, instant activation:

The UserAdded event is the protocol's "welcome": members watching the chain (and relays serving the group) learn a new member exists. Your app calls the same flow via its join packet, which invokes addYourself() through the group orchestrator and returns the transaction hash.

6. Joining a private group

Three paths in, one state machine:

Path A — request & approval

The pending queue is hard-capped at 20 entries (MAX_PENDING_USERS) — a gas-griefing guard so strangers cannot balloon the admin's approval costs. Approvals and rejections come in single and batch flavors (approveRequests(address[])), and every transition frees the queue slot atomically with an O(1) swap-and-pop — no scans, bounded gas.

Path B — invites

An admin mints an invite with a usage limit (createInvite(limit)) and shares the numeric id out-of-band. Anyone who is not blocked calls useInvite(id): the invite's counter increments, and the caller becomes Active. If they were Pending, their queue slot is freed in the same transaction. Already-active members can redeem an invite too — it simply records InviteUsed without changing state.

Path C — direct add

An admin calls addUser(yourAddress) directly. In a private group this doubles as approval: a Pending target is dequeued and activated; a None target is activated without ever being in the queue.

7. Leaving, removal, blocking

8. Relay membership

Groups also admit a special kind of member: relays. When one of your subscribed users is an active group member, the user's RelayNode contract calls addRelayMember(user) — with the relay contract itself as msg.sender, attesting on-chain that isSubscribed(user) is true. The group checks both claims and registers the relay (deduplicated). This is how the paid relay mesh and group messaging connect: a relay proves, contract-to-contract, that it legitimately serves a group member before the group accepts it as a delivery node. Admins can drop any relay with removeRelayMember.

9. Channels & group keys

Within a group, channels are the encryption scopes. Every message carries a channel number, and channel ranges have semantics the client enforces:

RangeMeaningWho writes
100–109AnnouncementsAdmin only (write-only for everyone else)
110–129General discussionAll active members
130–139Admin-onlyAdmins only

Members of a channel share a group symmetric key — that is what makes it a scope. Keys come in two types, admin and user, matching the channel classes above. At rest they are never plaintext: each key is stored AES-GCM-encrypted under your wallet's local crypt key (12-byte nonce, 16-byte salt, authenticated ciphertext — tampering is detected on decrypt).

Distribution to a new member is a request-response over the encrypted DM channel between two peers:

channel 51 (request):  GroupKeyRequest  { key_type: "admin" | "user" }
channel 50 (response): GroupKeyResponse { key_type, ... key material }   // encrypted transport

The peer holding the key answers only over the encrypted DM session, so key material never touches an unencrypted hop. Blocking a user rotates the nonce precisely so stale key material can be detected and re-keyed.

10. Messaging & sync

Once you hold a channel key, sending is local-first: the message is written to your local per-contract environment (cache, clock ranges), then flows peer-to-peer to the other members — the same store-and-forward machinery described in The Relay Mesh, Explained, with group relays (section 8) serving members who are offline. Incoming messages are validated against the sender's on-chain status and the channel's write rules before acceptance; the contract's events (UserAdded, UserRemoved, UserBlocked, …) keep every member's local view of the roster honest.

Group discovery needs no server either: when you pair with another peer, the P2P sync exchanges contract participation, and groups you belong to appear in your sidebar automatically. Join by address (or invite) and the rest — members, channels, keys, history — arrives over the mesh.

11. Security notes

← back to documentation