Global Leaderboard (Snap Cloud)
Build a global leaderboard for a SPECS Lens on Snap Cloud with the Global Leaderboard example: one best score per user, stored and ranked by RPC functions.
- Snapchat: not supported
- SPECS: fully supported
- Camera Kit Web: not supported
- Camera Kit Mobile: not supported
- SnapchatNot supported
- SPECSFully supported
- Camera Kit WebNot supported
- Camera Kit MobileNot supported
The Global Leaderboard example in the Snap Cloud Examples package builds a leaderboard shared by every user of your Lens, backed by two Supabase RPC (remote procedure call) functions. The backend stores scores on the server and keeps only each user's best score.
On SPECS, the Snap Cloud Global Leaderboard replaces the Leaderboard module (LeaderboardModule). It needs a one-time database setup, and it has no friends mode and no automatic reset intervals. See Migrating a Lens to SPECS 27.
For the full reference, see the Snap Cloud documentation site.
What the Global Leaderboard provides
- One row per user: each user keeps only their best score.
- Authenticated submission: submitting a score requires the user to be signed in with their SPECS Account.
- Public retrieval: reading the leaderboard doesn't require sign-in.
- Either sort order: highest score first, or lowest score first, for example for golf or time trials.
- UI integration: works with UI Kit's ScrollWindow and the package's row prefabs.
How the leaderboard backend works
The backend is one table and two RPC functions:
| RPC | Sign-in required | Purpose |
|---|---|---|
submit_score | Yes | Inserts the user's score, or updates it when the new score is better. Keeps only each user's best score. |
get_top_scores | No | Returns the top N scores (1 to 100) with display names. Used for the public leaderboard display. |
The table, game_leaderboard_scores, stores user_id, displayname, score, and updated_at. Row level security (RLS) is turned on and no role has direct access to the table: every read and write goes through the RPC functions. A third function, leaderboard_healthcheck(), reports whether the table and both RPCs exist.
Find the Global Leaderboard example
The Snap Cloud Examples package contains the Global Leaderboard example: install it from the Asset Library (see Examples). The example lives in Example6-GlobalLeaderboard and includes:
- SQL:
ExternalServicesExamples/global-leaderboard-sql-query/global-leaderboard-sql.sql, the table and RPC functions. - Setup guide:
ExternalServicesExamples/_guides/global-leaderboard-guide.md, step-by-step instructions. - Lens scripts:
SupabaseLeaderboardService,GlobalLeaderboard,LeaderboardRowInstantiator,LeaderboardRowItem, and a tap game,PinchGameController. - Prefabs:
ScrollViewListItemandGlobalLeaderboard, ready for a ScrollWindow.
Create the leaderboard table and RPC functions
Run this SQL once in your Snap Cloud dashboard, under SQL Editor. It's the SQL that ships in the package.
/*
Global Leaderboard (Minimal Clean Version)
- One row per user (best score only)
- Stores: displayname + score
- Uses SECURITY DEFINER RPC for writes
- Public read via RPC
- RLS enabled
- No direct table access
Objects created:
table: public.game_leaderboard_scores
function: public.submit_score(p_score, p_displayname, p_sort_mode)
function: public.get_top_scores(p_limit, p_sort_mode)
function: public.leaderboard_healthcheck()
*/
begin;
-- =========================
-- 1) Table
-- =========================
create table if not exists public.game_leaderboard_scores (
user_id uuid primary key references auth.users(id) on delete cascade,
displayname text not null,
score double precision not null,
updated_at timestamptz not null default now()
);
create index if not exists game_leaderboard_scores_score_idx
on public.game_leaderboard_scores (score);
create index if not exists game_leaderboard_scores_updated_at_idx
on public.game_leaderboard_scores (updated_at desc);
-- updated_at trigger
create or replace function public.set_updated_at()
returns trigger
language plpgsql
as $$
begin
new.updated_at = now();
return new;
end;
$$;
drop trigger if exists trg_game_leaderboard_scores_updated_at on public.game_leaderboard_scores;
create trigger trg_game_leaderboard_scores_updated_at
before update on public.game_leaderboard_scores
for each row execute function public.set_updated_at();
alter table public.game_leaderboard_scores enable row level security;
-- =========================
-- 2) RPC: submit_score
-- =========================
create or replace function public.submit_score(
p_score double precision,
p_displayname text,
p_sort_mode text default 'desc' -- 'desc' = higher better, 'asc' = lower better
)
returns void
language plpgsql
security definer
set search_path = public
as $$
declare
v_uid uuid := auth.uid();
v_existing_score double precision;
v_should_update boolean := false;
begin
if v_uid is null then
raise exception 'Not authenticated';
end if;
if p_displayname is null or length(trim(p_displayname)) = 0 then
raise exception 'displayname is required';
end if;
if p_score is null then
raise exception 'score is required';
end if;
if p_sort_mode not in ('asc', 'desc') then
raise exception 'Invalid sort mode. Use asc or desc.';
end if;
select score
into v_existing_score
from public.game_leaderboard_scores
where user_id = v_uid;
if not found then
insert into public.game_leaderboard_scores (user_id, displayname, score)
values (v_uid, p_displayname, p_score);
return;
end if;
if p_sort_mode = 'desc' then
v_should_update := p_score > v_existing_score;
else
v_should_update := p_score < v_existing_score;
end if;
update public.game_leaderboard_scores
set
displayname = p_displayname,
score = case when v_should_update then p_score else score end
where user_id = v_uid;
end;
$$;
-- =========================
-- 3) RPC: get_top_scores
-- =========================
create or replace function public.get_top_scores(
p_limit integer,
p_sort_mode text default 'desc'
)
returns table (
displayname text,
score double precision
)
language plpgsql
security definer
set search_path = public
as $$
begin
if p_limit is null or p_limit < 1 or p_limit > 100 then
raise exception 'p_limit must be between 1 and 100';
end if;
if p_sort_mode not in ('asc', 'desc') then
raise exception 'Invalid sort mode. Use asc or desc.';
end if;
if p_sort_mode = 'desc' then
return query
select s.displayname, s.score
from public.game_leaderboard_scores s
order by s.score desc, s.updated_at desc
limit p_limit;
else
return query
select s.displayname, s.score
from public.game_leaderboard_scores s
order by s.score asc, s.updated_at desc
limit p_limit;
end if;
end;
$$;
-- =========================
-- 4) Optional: healthcheck
-- =========================
create or replace function public.leaderboard_healthcheck()
returns json
language plpgsql
security definer
set search_path = public
as $$
declare
v_table_exists boolean;
v_submit_exists boolean;
v_get_exists boolean;
begin
select exists (
select 1 from information_schema.tables
where table_schema = 'public' and table_name = 'game_leaderboard_scores'
) into v_table_exists;
select exists (
select 1 from pg_proc p
join pg_namespace n on n.oid = p.pronamespace
where n.nspname = 'public' and p.proname = 'submit_score'
) into v_submit_exists;
select exists (
select 1 from pg_proc p
join pg_namespace n on n.oid = p.pronamespace
where n.nspname = 'public' and p.proname = 'get_top_scores'
) into v_get_exists;
return json_build_object(
'ok', (v_table_exists and v_submit_exists and v_get_exists),
'version', '2.0.0',
'table', v_table_exists,
'rpc_submit_score', v_submit_exists,
'rpc_get_top_scores', v_get_exists
);
end;
$$;
-- =========================
-- 5) Lockdown
-- =========================
revoke all on table public.game_leaderboard_scores from anon, authenticated;
revoke all on function public.submit_score(double precision, text, text) from public;
grant execute on function public.submit_score(double precision, text, text) to authenticated;
revoke all on function public.get_top_scores(integer, text) from public;
grant execute on function public.get_top_scores(integer, text) to anon, authenticated;
revoke all on function public.leaderboard_healthcheck() from public;
grant execute on function public.leaderboard_healthcheck() to anon, authenticated;
commit;
To check the setup, run select public.leaderboard_healthcheck(); in the SQL Editor. It returns "ok": true when the table and both RPCs exist.
Add the Global Leaderboard to your Lens
Once your project has the table and RPCs:
- Drag the
SnapCloudExamples__PLACE_IN_SCENEprefab from the Snap Cloud Examples package into your scene. It holds three panels side by side: Get Started, Media Suite, and Global Leaderboard. - If you want only the leaderboard, disable the other two panels.
- In the Supabase panel, select Import Credentials on your project: see Import the project credentials.
- Drag the
SupabaseProjectasset into the Supabase Project field of the prefab's[SnapCloudRequirements]object.SupabaseLeaderboardServicereads the project from there. - On the
GlobalLeaderboardcomponent, turn off Ascending if higher scores should rank first. It's on by default, which ranks the lowest score first. - Run the Lens, select Start on the tap game panel, and pinch until the countdown ends. The game submits your score and shows the refreshed leaderboard.
The game submits the user's display name when it's available, and the Display Name input (default Player) otherwise, for example in Lens Studio.
Leaderboard scripts in the Snap Cloud Examples package
The two scripts below are condensed from the package. SupabaseLeaderboardService handles authentication and the RPC calls, and GlobalLeaderboard connects them to a game. The package's versions add logging and readiness checks.
SupabaseLeaderboardService: authentication and RPC calls
import {
createClient,
type SupabaseClient,
} from 'SupabaseClient.lspkg/supabase-snapcloud';
import { SnapCloudRequirements } from 'SnapCloudExamples.lspkg/SnapCloudRequirements';
export type TopScoreRow = { displayname: string; score: number };
@component
export class SupabaseLeaderboardService extends BaseScriptComponent {
@input snapCloudRequirements: SnapCloudRequirements;
private client: SupabaseClient | null = null;
private initialized = false;
private authed = false;
onAwake() {
this.createEvent('OnDestroyEvent').bind(() => {
try {
this.client?.removeAllChannels?.();
} catch (_) {}
});
}
/** Create the Supabase client the first time it's needed */
private init(): void {
if (this.initialized) return;
globalThis.supabaseModule = require('LensStudio:SupabaseModule');
const project = this.snapCloudRequirements.getSupabaseProject();
this.client = createClient(project.url, project.publicToken, {
realtime: { heartbeatIntervalMs: 2500 },
});
this.initialized = true;
}
/** Make sure there's a session before calling RPCs that require sign-in */
private async ensureAuthed(): Promise<void> {
this.init();
if (!this.client) throw new Error('Client not initialized');
if (this.authed) return;
// Reuse an existing session if there is one
const { data: sessionData } = await this.client.auth.getSession();
if (sessionData?.session) {
this.authed = true;
return;
}
// Sign in the user with their SPECS Account
const { data, error } = await this.client.auth.signInWithIdToken({
provider: 'snapchat',
token: '',
});
if (error) throw new Error('Auth failed: ' + error.message);
if (!data?.session) throw new Error('Auth did not return a session');
this.authed = true;
}
/** Submit the signed-in user's score (keeps the personal best only) */
async submitScore(
score: number,
displayname: string,
sortMode: string = 'desc'
): Promise<void> {
await this.ensureAuthed();
const { error } = await this.client!.rpc('submit_score', {
p_score: score,
p_displayname: displayname,
p_sort_mode: sortMode,
});
if (error) throw new Error('submit_score failed: ' + error.message);
}
/** Fetch the top N scores; no sign-in required */
async getTopScores(
limit: number,
sortMode: string = 'desc'
): Promise<TopScoreRow[]> {
this.init();
if (!this.client) throw new Error('Client not initialized');
const { data, error } = await this.client.rpc('get_top_scores', {
p_limit: limit,
p_sort_mode: sortMode,
});
if (error) throw new Error('get_top_scores failed: ' + error.message);
return (data || []) as TopScoreRow[];
}
}
GlobalLeaderboard: game integration
import {
SupabaseLeaderboardService,
type TopScoreRow,
} from './SupabaseLeaderboardService';
export type LeaderboardEntryUI = {
rank: number;
displayname: string;
score: number;
};
@component
export class GlobalLeaderboard extends BaseScriptComponent {
@input supabaseService: SupabaseLeaderboardService;
@input ascending: boolean = true; // true = lowest score first; false = highest score first
@input itemsCount: number = 10;
onAwake() {
this.createEvent('OnStartEvent').bind(() => {
this.refresh().catch((e) => print('Leaderboard init error: ' + e));
});
}
/** Call this from your game when a round ends */
async submitScore(score: number, displayName: string): Promise<void> {
if (!Number.isFinite(score)) throw new Error('Invalid score: ' + score);
const name = String(displayName).trim();
if (!name) throw new Error('Display name is required');
await this.supabaseService.submitScore(
score,
name,
this.ascending ? 'asc' : 'desc'
);
await this.refresh();
}
/** Refresh the leaderboard display; call it any time */
async refresh(): Promise<void> {
const rows = await this.supabaseService.getTopScores(
this.itemsCount,
this.ascending ? 'asc' : 'desc'
);
const entries: LeaderboardEntryUI[] = rows.map(
(row: TopScoreRow, i: number) => ({
rank: i + 1,
displayname: row.displayname || '---',
score: Number(row.score || 0),
})
);
// Pass the entries to your UI, for example by instantiating row prefabs
entries.forEach((entry) => {
print(`#${entry.rank} ${entry.displayname} ${entry.score}`);
// rowInstantiator.render(entries); // connect your UI component here
});
}
}
Tips for the Global Leaderboard
- Sign in only when needed.
SupabaseLeaderboardServicecreates the client the first timesubmitScoreorgetTopScoresis called, and signs in only forsubmitScore.getTopScoresneeds no sign-in, so the leaderboard can show before the user is signed in. - Writes go through SECURITY DEFINER. The table grants nothing to
anonorauthenticated, so users can't insert or update rows directly, for example through the REST API.submit_scoreruns with the privileges of the function's owner, which lets it write the row, and it usesauth.uid()to write only the current user's row. - Sort mode. Pass
'asc'for time trials or puzzles where the lowest score wins, for example the fastest completion time. Pass'desc'for arcade games where the highest score wins.GlobalLeaderboardpasses the same mode to both RPCs, sosubmit_scorecompares scores the same way the list ranks them. The client chooses the mode, so always pass the same one for a given leaderboard. - Show rows with a prefab. In the package,
LeaderboardRowInstantiatorcreates a pool of row prefab instances andLeaderboardRowItemfills in each row's rank, name, and score text. CallrowInstantiator.render(entries)afterrefresh()completes to use them with your own UI. Its default row step moves each row along the X axis (-4, 0, 0); change the step for a vertical list.
Related
- Examples: install the Snap Cloud Examples package.
- Get Started: create the Snap Cloud project the leaderboard uses.
- Databases: tables and row level security in Snap Cloud.
- Migrating a Lens to SPECS 27: move from the Leaderboard module to Snap Cloud.
- ScrollWindow: the UI Kit component the row prefabs fit into.