Docs

Group chat

This guide adds a private group chat (TAPI-27) to an application that already uses TapeAPI. A group is up to 32 TapeOut containers; one of them, the owner, keeps the member list. Messages are end-to-end encrypted and signed; whatever carries them (a relay or ChannelBus) sees ciphertext only.

A working example to start from: examples/group-chat/ (node examples/group-chat/index.mjs, over the public relay).

Before you start

Every member, the owner included, needs:

  • A circuit and its container. The container is the circuit's ERC-6551 account. It is the address a group knows a member by. It is not the wallet that holds the circuit.
  • A published channel identity. An X25519 key for invites and an Ed25519 key for signatures, generated by the application, authorised by the holder's wallet and published in the container's site: scripts/channel-keys.mjs (see Private channels) or api.tx.publishChannelKeys({ container, record }). Keep the identity file with its secret keys; the published record holds only public keys.
  • A transport. The free public relay 12.1013.tape (Public API), your own relay, or ChannelBus.

Check a member with await api.chain.channelKeys(container): it returns the published keys only while the current holder of the circuit authorised them.

Two rooms: the part that is easy to get wrong

A group uses two kinds of room, and a new member needs both:

RoomIdWhat goes thereWho reads it
Group roomgroup.roomepoch messages (the key and the encrypted member list) and group messagesevery member
Inbox roomchannel.inboxRoom(container, chainId), one per memberthe sealed invite that tells a new member the group existsthat member

createGroup and addMembers return only the epoch message (epochWire), which goes to the group room. A new member does not know the group room yet: it learns it from the invite, which the owner must create with group.inviteFor(member) and post to that member's inbox room. Post only the epoch message and the new member waits for ever; the relay is working, it just has nothing in the room the member reads.

deliverGroupUpdate does both in one call. Use it.

Owner

import { createTapeAPI, rpcUrlsFor, group as G, deliverGroupUpdate } from '@tapeapi/sdk'

const api = createTapeAPI({ rpcUrls: rpcUrlsFor(56), quorum: 2 })
const relay = { api, service: await api.resolve('12.1013.tape') }
const verifyMember = api.groupVerifier()                 // checks every member against its channel record

// Other members as the chain publishes them: container addresses, never wallets
const members = await Promise.all([bobContainer, carolContainer].map((c) => api.chain.channelKeys(c)))

const created = await G.createGroup({
  self: { container: myContainer, chainId: 56 }, identity: myIdentity, members, verifyMember,
  relays: [{ url: 'https://relay.tapeapi.fun/tapeapi/v1', container: relay.service.container }],
})
const group = created.group
const sent = await deliverGroupUpdate({ group, update: created, relayClients: [relay] })
// sent.deliveries: one entry per post, invites first, then the epoch message:
//   { what: 'invite', room, container, chainId, via: 'relay', ok: true, i: 0, epoch: '<room epoch>' }
//   { what: 'epoch',  room: group.room, via: 'relay', ok: true, i: 0, epoch: '<room epoch>' }

Membership changes return the same kind of update, and added says who is new:

const up = await group.addMembers([await api.chain.channelKeys(daveContainer)], { verifyMember })
up.added                                                 // [{ container, chainId, x25519, ed25519 }]: invited by default
await deliverGroupUpdate({ group, update: up, relayClients: [relay] })

await deliverGroupUpdate({ group, update: await group.removeMembers([carolContainer]), relayClients: [relay] })   // no invites
await deliverGroupUpdate({ group, update: await group.rotate(), relayClients: [relay] })                          // at least every 30 days

What deliverGroupUpdate does and returns:

  • Order. Invites to each member's inbox room first, then the epoch message to the group room (TAPI-27 §3.5).
  • Who is invited. invite: 'new' (the default: update.added), 'all' (every member but the owner), 'none', or a list of containers that must be in the current roster. Invites always use the roster's container and chainId, the ones the owner signed.
  • Several transports. relayClients and busClients are lists; every post goes to each entry of both. Each invite is sealed once, so a member that reads two transports sees one invite twice, not two invites.
  • Failures. Every post is tried. If any failed, the call then throws TapeAPIError('GROUP_DELIVERY'), whose message names the first failed room and whose data holds every delivery; pass throwOnError: false to get { ok: false, deliveries } instead. It never swallows an error.
  • Reposts. Without update it reposts the current epoch message (group.epochWire). TAPI-27 §3.5 recommends a repost every 10 minutes on a relay whose rooms live 15 minutes, and every 30 minutes on ChannelBus read through public nodes:
setInterval(() => deliverGroupUpdate({ group, relayClients: [relay] }).catch(report), 10 * 60_000)

Member

import { createTapeAPI, rpcUrlsFor, channel, group as G, checkGroupInvites } from '@tapeapi/sdk'

const api = createTapeAPI({ rpcUrls: rpcUrlsFor(56), quorum: 2 })
const relay = { api, service: await api.resolve('12.1013.tape') }
const self = { container: myContainer, chainId: 56 }    // the CONTAINER, on the chain it lives on
const cursors = new Map()                                // or your own store: see "Saving state"

const found = await checkGroupInvites({ self, identity: myIdentity, relayClients: [relay], cursors, waitMs: 20_000, checkSelf: true })
for (const { invite } of found.invites) {
  const ownerKeys = await api.chain.channelKeys(invite.owner.container)   // from the chain, never from the invite
  const g = G.joinGroup({ self, identity: myIdentity, invite, ownerKeys })
  let greeted = false
  const link = channel.relayTransport({ api, service: relay.service, inbound: g.room, outbound: g.room })
  link.start(async (wire) => {
    const t = channel.decodeWire(wire)
    if (t.groupEpoch) {
      await g.acceptEpoch(t.groupEpoch, { verifyMember: api.groupVerifier() })
      if (!greeted && g.epoch !== null) { greeted = true; await link.send(g.seal('hello')) }   // send only after the first epoch is accepted
    }
    if (t.groupMessage) { const m = g.open(t.groupMessage, { text: true }); if (!m.own) show(m.from, m.data) }
  }, { onError: report })
}
  • checkGroupInvites reads channel.inboxRoom(self.container, self.chainId) on each relay, keeps one cursor per relay and room with the relay's room epoch (the first read is after: -1, epoch: null), and returns { room, invites, skipped, skippedBy, failed }. Frames that are not a group invite for this container are skipped and counted; a TAPI-26 channel invite in the same inbox is counted as channelInvite, for your channel code.
  • checkSelf: true reads the container's channel record first and refuses unless it publishes this identity's X25519 key on this chainId: a wallet address, a wrong chainId or a stale identity file is reported at once instead of as an empty inbox. Pass holder (the wallet) and a mix-up of the two is refused without any chain read.
  • A relay that cannot be read is listed in failed (and ok is false); if none can be read, the call throws.
  • The invite only says where to look. The member accepts nothing but epoch messages the owner signed, and after the first one it uses the roster's relays and bus (g.roster.relays, g.roster.bus), which the owner signed.
  • A new member also finds older epoch messages in the group room. They do not open with its key and acceptEpoch refuses them ("not a member of it"); that is expected. Catch and continue.

Relay or ChannelBus

RelayChannelBus
Latency and costabout one round trip; the public relay is freeblock time; every post is a transaction paid in gas
What staysrooms (ciphertext) until 15 minutes after the last access, then cleared; the public relay keeps them in Durable Object storage, so an idle room survives Cloudflare recycling the instanceevents on chain, public for ever
Limitsinvites and epoch messages: 8 per source per room per 10 minutes on the reference relayup to 16,448 bytes per post
OwnerrelayClients: [{ api, service, payer? }]busClients: [{ address: MAINNET.channelBus, sendTx }]: your wallet sends, one transaction per room
MembercheckGroupInvites({ relayClients }), channel.relayTransportbusPrivacy.busPrivacyReader (reads the whole contract by default, see Read privacy) or channel.busReader on channel.inboxRoom(...) and group.room

Name both in createGroup({ relays, bus }) and deliver over both when the group matters: a member can read either.

Saving state and restarting

Nothing needs saving to stay safe; these keep a restart smooth:

  • Owner: save group.snapshot() (no secrets: the roster and the epoch). After a restart, G.resumeGroup({ self, identity, snapshot, verifyMember }) starts the next epoch at once (the old key is gone) and returns it as an update: deliverGroupUpdate({ group: resumed.group, update: resumed, relayClients: [relay] }). The resumed handle holds no key of the epoch before: a message members sent under it while the owner was away is refused with no key for epoch N (not in this handle's snapshot ...) and e.data.reason === 'snapshot', not as a forgery. A format-2 snapshot says v: 2 (1.2.0 wrote v: 1, which is still read): SDKs up to 1.2.0 refuse it instead of resuming the group as format 1, so an owner cannot be moved back to one of them.
  • Member: save g.snapshot() after sealing. After a restart, pass minEpoch: snapshot.epoch and lastSeq: snapshot.lastSeq to joinGroup: a relay replaying an older epoch is refused, and a clock that stepped back cannot make new messages look like replays. It also tells the restarted handle that the messages of its own it reads back from the room are its own, not another device's (below).
  • Cursors: cursors takes any { get(key), set(key, value) }, sync or async; back it with a file or a database. Keys are relay:<relay container>:<room>, values { after, epoch }. Keep the epoch with the index: an index without its room epoch is exactly the mistake below.
  • Identity: the identity file with the secret keys. Lose it and the member must publish a new identity, and the owner must add it again.

Errors a chat should handle

open() refuses with GROUP_INVALID; three refusals are normal events, told apart by e.data:

  • A message ahead of its epoch message (e.data.reason === 'not-yet', e.data.retryAfterEpoch: N). With several relays, or a relay and ChannelBus, a member's message can arrive before the owner's epoch message that makes its key. Keep it and open it again after acceptEpoch. If that epoch message is refused ("not a member of it"), the member was removed and the held messages can be dropped. The SDK does not buffer for you; a few lines do:
const held = []                                          // messages ahead of their epoch message, at most 256
function openOrHold(wire) {
  try { return g.open(wire, { text: true }) }
  catch (e) { if (e.data?.retryAfterEpoch !== undefined && held.length < 256) { held.push(wire); return null } throw e }
}
// after every accepted epoch message / 每接受一条纪元消息之后
for (const w of held.splice(0)) {
  try { const m = openOrHold(w); if (m && !m.own) show(m.from, m.data) }
  catch { /* dropped: its epoch expired, or this member is not in it */ }
}
  • An epoch gone (e.data.reason === 'expired'): the previous epoch is kept 10 minutes after the next one arrives, and nothing from before the member joined opens. Show a gap; nothing can bring it back.
  • The owner restarted (e.data.reason === 'snapshot', on a handle from resumeGroup): see "Saving state".

One identity is one device. Two devices (or two processes) holding the same identity each start their sequence numbers from their own clock, so everyone else refuses the messages of the one with the lower numbers as seq ... already seen (and e.data.mayBeOtherDevice: true). The SDK does not hide this: open() returns a message signed with this identity that this handle did not seal, in full, with otherDevice: true (not own), and g.otherDevice becomes { count, epoch, seq }. Tell the user to use one device, or give each device its own container and identity. A handle restarted without lastSeq takes its own earlier messages in the room for another device's; pass lastSeq from the snapshot.

Troubleshooting checklist

SymptomCauseFix
The owner created the group, members never get an invite, the relay returns 0 framesOnly the epoch message was posted, to the group room; the invites were never posted to the inbox roomsdeliverGroupUpdate({ group, update, relayClients: [relay] }), and check that deliveries has one invite per new member
The same, with invites postedWrong room: the inbox room was computed from the holder's wallet, not the container, or with another chainIdCompare the room of the owner's invite delivery with the room that checkGroupInvites returns. Use the container address and the chainId it lives on; checkSelf: true names the mistake
The invite at index 0 is never seenThe read reused the after cursor of another room (the group room) and sent no epoch, so the relay started past index 0Keep a cursor per room with its room epoch; the first read is after: -1, epoch: null. checkGroupInvites does this and ignores a stored cursor without an epoch
Invites or the epoch message vanish after a whileA relay clears a room 15 minutes after the last access (the public relay before 2026-09-29: within seconds of going idle)Repost the epoch message every 10 minutes (deliverGroupUpdate({ group, relayClients: [relay] })); re-invite members who have not joined (invite: 'all'); a member's stale cursor is reset by the new room epoch
Posting fails with too many invites / epoch messages from this source in this roomThe relay limits 0x03 / 0x04 frames per source per room (8 per 10 minutes on the reference relay)Wait retryAfterS seconds and deliver again; do not repost in a tight loop. Never swallow the error: deliverGroupUpdate throws GROUP_DELIVERY, and the failed entry of e.data.deliveries has error.rateLimited: true and error.retryAfterS
A mobile wallet never returns to the app when signing the channel keysThe app is served on a LAN HTTP address (http://192.168.x.x), which the wallet will not call backServe it through an HTTPS tunnel, and set WalletConnect's metadata.url to that exact HTTPS origin
A new member logs "not a member of it" for some epoch messagesOlder epochs in the group room were not made for itExpected: catch and continue; the epoch that added it opens
no key for epoch N with data.retryAfterEpochThe message arrived before its epoch message (several relays, or relay and ChannelBus)Hold it and open it again after acceptEpoch ("Errors a chat should handle")
One member's messages are refused as already seen, with data.mayBeOtherDeviceThe same identity sends from two devices; the one with the lower sequence numbers is refused by everyoneOne device per identity; the device itself sees otherDevice: true on the other's messages and g.otherDevice
A format-2 invite joins on an old client, then every frame fails with GROUP_INVALID (data.format: 2)The client predates format 2: it joins in silence and refuses the group's frames afterwardsCheck invite.format === 2 before joining and ask the user to update

Format 2 (experimental): before joining, and what the owner reads

Check the invite's format before joining. A client without format 2 (every SDK before 1.2) opens a format-2 invite and joinGroup succeeds in silence; only afterwards does every epoch message and group message fail with GROUP_INVALID and data.format: 2. Check first, so the user is told to update instead of seeing a group that never works:

const inv = G.openGroupInvite(wire, { self })            // or found.invites[i].invite
// G.MAX_MEMBERS_V2 is undefined in an SDK before 1.2: such a build must not join a format-2 group
if (inv.format === 2 && !G.MAX_MEMBERS_V2) return askToUpdate(inv)

An application that has not adopted format 2, whatever its SDK, makes the same check with its own flag.

What the owner reads on each epoch. The owner reuses its own positive verdict on an unchanged member for up to 24 hours (verifyReuseS in createGroup / resumeGroup, default 86,400 s). With 128 members, removing one or rotating reads no record, adding one reads one (the new member, once, past the cache), and the first epoch after the verdicts age out reads all 127: about 2,300 HTTP requests and 27 seconds at the default concurrency of 8 (about 18 requests and 1.7 s a record on BSC), at most once a day. SDK 1.2.0 did that full read on every epoch, and read an added member twice. A resumed owner has no verdicts, so its first epoch reads everyone. verifyReuseS: 0 goes back to reading every member on every epoch, for an owner that must drop a sold circuit at its next epoch rather than within a day (TAPI-27 §8).

Label versions (labels, since 1.8.1)

Groups have a version 2 too, TAPI-27 v2 (Stable (v2) since 2.0.0): labels that begin with tape-group/, and invites in the v2 inbox rooms of TAPI-26 v2. It was an option in 1.8.1 and is the default from 2.0; it is not format 2, and either format can use it.

  • With no labels, createGroup, checkGroupInvites (which reads the v2 inbox room) and joinGroup use version 2. deliverGroupUpdate and inviteFor follow the group's version (group.labels). For a group whose members are still on 1.x, everyone passes labels: 'v1' (deprecated in 2.x, not removed in 2.x).
  • A group keeps its version for life. A v2 owner's snapshot() says v: 3, labels: 'v2', so SDKs up to 1.8.0 refuse it instead of resuming the group under the v1 labels, and resumeGroup takes the version from it (a labels that disagrees is GROUP_INVALID). A 1.x snapshot (v: 1 or v: 2) is a v1 group and resumes as one in 2.0: upgrading the owner does not move an existing group to v2.
  • A member on the other version reads another inbox room and another group room, so it usually sees nothing; an epoch message of the other version that reaches it is refused with GROUP_INVALID, e.data.labels and e.data.peerLabels. The SDK never switches versions on its own.

Limits

  • At most 32 members per group. An experimental format 2 (TAPI-27 §3.8, createGroup({ format: 2 })) carries up to 128 in one wire message, with a binary roster and member checks done lazily: a message from a sender not yet checked comes with verified: false, so show it as unverified or use openVerified. Its members' entries carry no X25519 key, so check them with group.channelKeysVerifier(api), not api.groupVerifier(), which compares both keys and would find every member a mismatch. A member found to match is trusted for up to 24 hours (verifyReuseS, from the start of the check); one found not to match is refused for at most 60 seconds and then checked again, and that "no" always comes from a read past the client's cache, so a record a lagging node could not find does not silence anyone for long. An RPC failure is never a verdict. joinGroup of a format-1 group ignores verifyMember and verifyReuseS, so code for both formats can pass them to every invite. Format 1 clients (every SDK before 1.2) refuse a format-2 group with GROUP_INVALID, and one group never mixes formats. Past about 64 members, run your own relay (the public one is for testing and small groups), and for 100 or more keep the owner on an always-on host or in a Web Worker: building an epoch for 128 members takes seconds on a phone.
  • The owner is a single point: only the owner adds, removes and rotates, and there is no owner transfer. A group that needs a new owner is a new group.
  • Metadata is visible: a relay sees room ids, frame sizes, timing and the IP addresses that post and poll; anyone reading the group room sees the member count and message sizes and times. On ChannelBus all of that is public for ever. Content and the member list stay encrypted.
  • A removed member keeps everything it could read before its removal.
  • Not audited by a third party.

Edit this page on GitHub