Nostr replaceable event mutation overwrite

From divinevideo/divine-mobile · View interactive version

Nostr replaceable event mutation overwrite is an AI agent skill from the GitHub repository divinevideo/divine-mobile. Fix silent data loss when mutating Nostr replaceable events (Kind 0 profile, Kind 3 contact/follow list, Kind 10002 relay list, etc.) in client apps. Use when: (1) Following someone wipes the user's entire follow list, (2) Updating profile metadata loses existing fields, (3) Fresh browser session or

How to use this skill

Skill file

Nostr Replaceable Event Mutation Overwrite

Problem

Nostr replaceable events (Kind 0, 3, 10002, etc.) use a full-replace model: publishing a new

event completely replaces the previous one. If a client publishes a mutation based on stale,

incomplete, or null cached state, it silently overwrites the canonical version on relays, causing

data loss. The most common case is follow list (Kind 3) wipes when a user follows someone before

the client has loaded their existing contact list.

Context / Trigger Conditions

Solution

1. Always Fetch Fresh State Inside the Mutation

Fetch the current revision inside the mutation, before publishing. Filter by author and

kind, and include the d tag for an addressable event. Only compare cached or locally

accepted revisions of that same event. See the follow example below.

2. Newest Wins, Per NIP-01

Order the relay's version against the cached one by created_at, and on an exact tie by

the lower event id. That is the rule relays themselves apply, so it is the only choice

that converges. Use the publisher's timestamp policy to give the replacement a later

created_at than the selected base.

Do not compare tag counts. "Use whichever has MORE data" looks safe and is not: the

newer, authoritative list is shorter whenever the user removed someone, so preferring

the longer copy silently resurrects every unfollow, unmuted account, or deleted relay —

and republishes it. The heuristic cannot tell "this copy is stale" from "the user removed

something", because those two produce the identical shape.

A source that carries no timestamp at all — a bare cached array, a derived REST index —

has unknowable freshness, not old freshness. It may seed an empty state, but it must lose

to any copy that can name a created_at.

Worked example, including the persistence migration that gives the local cache a

timestamp to be ordered by: divinevideo/divine-mobile#8266.

3. Refuse to Publish When the Read Did Not Finish

A read for the current version has three outcomes, not two:

and there is no locally accepted revision to preserve. The mutation can create the first event.

omitted the newest revision. Keep the edit local and retry later, even if the read returned

an older revision or a cached copy exists.

Many clients do not throw on an unfinished read. They return whatever arrived, so a

catch block never sees the failure. Find out how your client reports an unfinished read

before trusting one. Section 4 covers divine-mobile.

4. In divine-mobile, Ask NostrClient Whether the Read Finished

NostrClient reports timeouts and relay CLOSED in the read result. Choose the network relay URLs

that must answer for the event you are replacing. For a single contact-list coordinate,

read each of those relays separately:

if (requiredRelays.isEmpty) return false;
final reads = await Future.wait([
  for (final url in requiredRelays)
    nostrClient.readEvents(
      [
        Filter(authors: [pubkey], kinds: const [EventKind.contactList], limit: 2),
      ],
      tempRelays: [url],
      relayTypes: RelayType.onlyTemp,
      useCache: false,
      requireAllRelaysSettled: true,
    ),
]);
if (reads.any(
  (read) => !read.isComplete || read.possiblyCapped || read.events.length > 1,
)) {
  return false;
}
final candidates = [for (final read in reads) ...read.events];
// Select the newest revision from candidates, then apply the pending edit.

EOSE answer pass when the relay advertises no result cap. A smaller advertised cap, a

more hint, or rejected events may still leave the read inconclusive. The example also

refuses multiple revisions from one relay because the client may already have trimmed that

answer. NIP-01 replaceable events

with a timestamp-only sort when a limit trims the result, so a shared limit can drop the

lowest ID among events tied for newest across relays.

you are about to replace.

A default read can return timedOut: false after CLOSED, a dropped socket, or the

one-second settle window. Leave acceptRelayClosedWhenOthersAnswered disabled when the

mutation needs the refusing relay's answer.

When a relay finishes with a more hint and no usable event, it can be complete and still

have withheld the only matching revision. This example rejects potentially capped reads.

Use the cap flag or other evidence that the newest revision was included before publishing.

to the named relay. Otherwise a cache relay can complete a read with no network answer.

during dispatch while another relay returns a complete answer. Reading each required relay

separately exposes a missed request. queryEventsOnFreshConnections also checks required

relay participation when called with requiredRelays, but does not report caps.

repository uses three seconds and withholds the publish if the read expires.

follow_repository.dart, _readAuthoritative in profile_pins_repository.dart, and

_publishForPubkey in relay_list_repository.dart. These callers use their existing relay

scopes. divinevideo/divine-mobile#8258 lists the tests that fail if the checks are removed.

5. Apply to Both Directions

Apply this pattern to ALL mutation directions (follow AND unfollow, add AND remove relay,

update AND clear profile fields). The unfollow path is just as dangerous as follow.

Within a client, serialize edits to the same event from the read through the publish

acknowledgement. Remember the accepted revision before the next edit starts because a relay

can acknowledge a publish before serving the revision on a read.

Verification

Cold-start overwrite:

  1. Open the app in a private/incognito browser window
  2. Log in with an account that has multiple follows
  3. Navigate to a profile and tap Follow IMMEDIATELY (before the page fully loads)
  4. Check that the follow count increased by 1 (not reset to 1)

Cross-device removal — the case a tag-count heuristic passes and still corrupts:

  1. On a second client, unfollow two of several accounts
  2. Cold-start the first client and confirm the removals are still gone
  3. Follow one new account there, then read the relay's kind 3 back and confirm

the two removed accounts did not reappear in its p tags

Partial read:

  1. Have one relay return an older contact list and finish the read. Have the other relay

refuse the read (CLOSED) or accept the request and stay silent.

  1. Follow someone and confirm the failed read leaves the publish count at zero. Retry with

the second relay returning a newer list and a plain EOSE. Check that the publish preserves

that list and adds the follow, including when the relay does not advertise a result cap.

Also verify that a cache-only answer, a missed required relay, or an empty answer with a

more hint cannot authorize a publish.

Example

A follow mutation that assumes nostr.query rejects when a required relay fails to finish

or the newest revision may have been omitted. If the client returns partial answers, check

settlement and truncation before using the events. The illustrative publishEvent helper

returns the signed revision after relay acceptance and rejects if it cannot assign a valid

timestamp later than newerThan.

The client shares a store of last accepted revisions by account. Follow and unfollow use

the same TanStack Query v5 scope in the same query client. Mutation scopes

type ContactList = {
  id: string;
  created_at: number;
  tags: string[][];
  content: string;
};

function newest(events: (ContactList | null | undefined)[]) {
  return events.filter((event) => event != null).sort((a, b) => {
    if (a.created_at !== b.created_at) return b.created_at - a.created_at;
    if (a.id === b.id) return 0;
    return a.id < b.id ? -1 : 1;
  })[0];
}

export function useFollowUser(pubkey: string) {
  const { nostr } = useNostr();

  return useMutation({
    scope: { id: `contact-list:${pubkey}` },
    mutationFn: async (targetPubkey: string) => {
      let events: ContactList[];
      try {
        events = await nostr.query(
          [{ kinds: [3], authors: [pubkey] }],
          { signal: AbortSignal.timeout(5000) },
        );
      } catch {
        throw new Error('Could not confirm your follow list. Please try again.');
      }

      const base = newest([...events, lastAcceptedContactList(pubkey)]);
      const tags = [...(base?.tags ?? [])];
      if (tags.some(([kind, value]) => kind === 'p' && value === targetPubkey)) return;
      tags.push(['p', targetPubkey]);
      const accepted = await publishEvent(
        { pubkey, kind: 3, tags, content: base?.content ?? '' },
        { newerThan: base?.created_at },
      );
      rememberAcceptedContactList(pubkey, accepted);
      return accepted;
    },
  });
}

Notes

(contacts), Kind 10002 (relay list), Kind 10000 (mute list), Kind 30000+ (addressable)

tap quickly

stale cache - the fix must be inside the mutation itself

silent. Erring short is safe: an expired read is a failed read, and a failed read

publishes nothing

belt-and-suspenders approach

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.