Back to Drift City
SOURCE / PINNED RELEASE

Made of little things.

Drift City

Release
098731aa0f0f…
Author-recorded commit
2822ea0a4f5b…
License
LICENSE
Author’s source reference
nostr://npub12lm3rxsva8kfempyjkxupt09e02n3fezurkyadyqfejdc5e0r2kscqty6r/wss%3A%2F%2Fgit.napplet.soy%2F/n-a4c0039c855

Archive hash verified: b3323e408235502b…. The source-to-build association is the author’s claim; it has not been independently rebuilt.

src/online.ts
import { cvm, identity, storage } from '@napplet/sdk';
import backend from '../.napplet-space/soy-backend.json';
import { runtimeHasDomain } from './domain-availability.js';

/**
 * Accounts and the shared leaderboards.
 *
 * An account is the player's Nostr identity, through the host (read-only: its public
 * key, and its name and picture from its profile); signed out, a guest with a name they
 * type. Each account's own records (its longest drift, how many races it's won) and its
 * car designs (see paint-designs.ts) are kept in the napplet's storage under its key.
 *
 * The leaderboards are the host's shared boards (soyLI's backend, docs/napplet-backend.md):
 * the longest single drift (milliseconds) and the races won, each player's best kept.
 * They're casual: the game reports the scores. Without the backend (an older host, or
 * none), the game works the same and the boards say so.
 */

export interface Account {
  /** The Nostr public key (hex), or 'guest'. */
  id: string;
  name: string;
  picture: string | null;
  signedIn: boolean;
}

export interface Records {
  /** The longest single drift, milliseconds. */
  longestDrift: number;
  racesWon: number;
}

export interface BoardRow {
  name: string;
  score: number;
  own: boolean;
}

export type BoardId = 'longest-drift-v1' | 'races-won-v1';

const canStore = runtimeHasDomain('storage');
const canSignIn = runtimeHasDomain('identity');
const canShare = runtimeHasDomain('cvm');

/** Names on the boards and in the menu: plain text, trimmed, at most 24 characters. */
export function cleanName(s: string): string {
  // eslint-disable-next-line no-control-regex
  return s.replace(/[\u0000-\u001f\u007f]/g, '').trim().slice(0, 24);
}

export class Online {
  account: Account = { id: 'guest', name: 'Guest', picture: null, signedIn: false };
  records: Records = { longestDrift: 0, racesWon: 0 };
  /** The account (or its records) changed. */
  onChange: () => void = () => undefined;
  private guestName = 'Guest';

  /** Who's playing: the host's identity if signed in (and when that changes), else the guest. */
  async start(): Promise<void> {
    if (canStore) this.guestName = cleanName((await storage.getItem('guest-name').catch(() => null)) ?? '') || 'Guest';
    await this.use(canSignIn ? await identity.getPublicKey().catch(() => '') : '');
    if (canSignIn) identity.onChanged((pubkey) => void this.use(pubkey));
  }

  get canSignIn(): boolean {
    return canSignIn;
  }

  get canShare(): boolean {
    return canShare;
  }

  /** The guest's name (when signed out). */
  async setGuestName(name: string): Promise<void> {
    this.guestName = cleanName(name) || 'Guest';
    if (canStore) await storage.setItem('guest-name', this.guestName).catch(() => undefined);
    if (!this.account.signedIn) {
      this.account = { ...this.account, name: this.guestName };
      this.onChange();
    }
  }

  private async use(pubkey: string): Promise<void> {
    if (pubkey) {
      const profile = await identity.getProfile().catch(() => null);
      const name = cleanName(profile?.displayName || profile?.name || '') || `${pubkey.slice(0, 8)}…`;
      this.account = { id: pubkey, name, picture: profile?.picture ?? null, signedIn: true };
    } else this.account = { id: 'guest', name: this.guestName, picture: null, signedIn: false };
    this.records = await this.loadRecords();
    this.onChange();
  }

  /** Storage key for something of this account's. */
  key(what: string): string {
    return `${what}:${this.account.id}`;
  }

  private async loadRecords(): Promise<Records> {
    const r: Records = { longestDrift: 0, racesWon: 0 };
    if (!canStore) return r;
    try {
      const v = JSON.parse((await storage.getItem(this.key('records'))) ?? 'null') as Partial<Records> | null;
      if (v && Number.isFinite(v.longestDrift)) r.longestDrift = Math.max(0, Math.round(v.longestDrift!));
      if (v && Number.isInteger(v.racesWon)) r.racesWon = Math.max(0, v.racesWon!);
    } catch {
      // Keep the zeros.
    }
    return r;
  }

  private async saveRecords(): Promise<void> {
    if (canStore) await storage.setItem(this.key('records'), JSON.stringify(this.records)).catch(() => undefined);
  }

  /** A drift ended, ms long: a new longest is kept and sent to the board. Returns whether it was. */
  async drift(ms: number): Promise<boolean> {
    ms = Math.round(ms);
    if (ms <= this.records.longestDrift || ms > 3_600_000) return false;
    this.records.longestDrift = ms;
    this.onChange();
    await this.saveRecords();
    void this.submit('longest-drift-v1', ms);
    return true;
  }

  /** A race won: counted, and the count sent to the board. */
  async raceWon(): Promise<void> {
    this.records.racesWon++;
    this.onChange();
    await this.saveRecords();
    void this.submit('races-won-v1', this.records.racesWon);
  }

  /** On first opening the boards: this account's records sent up (in case they were set offline). */
  async sync(): Promise<void> {
    if (this.records.longestDrift > 0) await this.submit('longest-drift-v1', this.records.longestDrift);
    if (this.records.racesWon > 0) await this.submit('races-won-v1', this.records.racesWon);
  }

  private async call(tool: string, args: Record<string, unknown>): Promise<Record<string, unknown>> {
    const result = backend.provider ? await cvm.callTool(backend.provider, tool, args) : await cvm.registry.call('soy.boards.v1', tool, args as never);
    if (result.isError) {
      const text = (result.content ?? []).filter((c) => c.type === 'text').map((c) => (c as { text: string }).text).join('\n');
      throw new Error(text || 'The leaderboard did not answer');
    }
    return (result.structuredContent ?? {}) as Record<string, unknown>;
  }

  private async submit(board: BoardId, score: number): Promise<void> {
    if (!canShare) return;
    await this.call('soy_board_submit', { napplet: backend.napplet, board, score, name: this.account.name }).catch((err) => console.warn('leaderboard', err));
  }

  /** The top of a board: names (as plain text) and scores, this player's row marked, and their own best. */
  async read(board: BoardId, limit = 20): Promise<{ rows: BoardRow[]; own: BoardRow | null }> {
    if (!canShare) throw new Error('Leaderboards need a host with the shared backend.');
    const r = await this.call('soy_board_read', { napplet: backend.napplet, board, limit });
    const rows = (r.rows as { actor: string; score: number; name: string }[] | undefined) ?? [];
    const own = r.own as { actor: string; score: number; name: string } | null | undefined;
    return {
      rows: rows.map((x) => ({ name: cleanName(String(x.name ?? '')) || 'Player', score: Number(x.score) || 0, own: !!own && x.actor === own.actor })),
      own: own ? { name: cleanName(String(own.name ?? '')) || 'You', score: Number(own.score) || 0, own: true } : null,
    };
  }
}