# Functions reference

Public function reference for the Wavedash SDK

Source: https://docs.wavedash.com/sdk/functions

A reference for the public Wavedash SDK functions documented across these guides. Each entry shows the JavaScript signature and a brief description. For full usage examples, see the linked feature page.

## Initialization

Functions for setting up the SDK and managing the connection lifecycle. See [SDK setup](/sdk/setup) for details.

| Function | Description |
|----------|-------------|
| `Wavedash` (default export of `@wvdsh/sdk-js`) | The SDK singleton. Install `@wvdsh/sdk-js` and `import Wavedash from "@wvdsh/sdk-js"` for fully-typed access. Same instance is also reachable as `window.Wavedash`. |
| `init(config?)` | Initializes the SDK, applies configuration options, and signals load-complete. Returns `true` on first call, `false` if already initialized. Call once before using any other SDK method. See [SDK setup](/sdk/setup) for supported fields. |
| `readyForEvents()` | Flushes the deferred event queue. Call after your game finishes loading if you passed `deferEvents: true` to `init()`. Otherwise `init()` calls this automatically. |
| `updateLoadProgressZeroToOne(progress)` | Reports load progress (0.0 – 1.0) to the Wavedash shell so it can render a loading bar. Call repeatedly while assets download or the runtime boots. |
| `loadComplete()` | Signals that the game is ready for the player to interact with. Idempotent. `init()` calls this internally, so you only need to call it directly if you want to signal load-complete before running `init()` (e.g., from a splash screen). |
| `loadScript(src)` | Convenience wrapper that appends a `<script>` tag to the page and resolves once it loads. Useful when you need to lazy-load a third-party library. |
| `initialized` *(getter)* | `true` once `init()` has been called. |
| `eventsReady` *(getter)* | `true` once the deferred event queue has been flushed. |
| `gameLoaded` *(getter)* | `true` once `loadComplete()` has fired. |

```typescript
import Wavedash from "@wvdsh/sdk-js";

function init(config?: WavedashConfig): boolean;

function readyForEvents(): void;

function updateLoadProgressZeroToOne(progress: number): void;

function loadComplete(): void;

function loadScript(src: string): Promise<void>;

readonly initialized: boolean;
readonly eventsReady: boolean;
readonly gameLoaded: boolean;
```

## Overlay

| Function | Description |
|----------|-------------|
| `toggleOverlay()` | Shows or hides the Wavedash in-game overlay (friends list, invites, settings). Wire it to a pause button or a keyboard shortcut. |

```typescript
function toggleOverlay(): void;
```

## Launch params

Read URL parameters that were passed when the game was launched. See [SDK setup](/sdk/setup#launch-params) for details.

| Function | Description |
|----------|-------------|
| `getLaunchParams()` | Returns the key-value mapping of `wvdsh_`-prefixed URL query params that were present when the game launched. |

```typescript
function getLaunchParams(): GameLaunchParams;
```

## Players

Identity, friends, avatars, and presence. See [Player identity](/sdk/players) for details.

| Function | Description |
|----------|-------------|
| `getUser()` | Returns the signed-in player's profile object. |
| `getUserId()` | Returns the player's stable string ID. |
| `getUsername()` | Returns the player's display name. |
| `getUserJwt()` | Returns a short-lived signed JWT you can forward to your own backend to authenticate the player. |
| `listFriends()` | Fetches the current player's friends list. |
| `getUserAvatarUrl(userId, size)` | Returns an avatar URL for a user at the given size. |
| `updateUserPresence(data)` | Sets the player's presence status visible to friends. |

```typescript
function getUser(): User;

function getUserId(): Id<"users">;

function getUsername(): string;

function getUserJwt(): Promise<WavedashResponse<string>>;

function listFriends(): Promise<WavedashResponse<Friend[]>>;

function getUserAvatarUrl(
  userId: Id<"users">,
  size: AvatarSize
): string | null;

function updateUserPresence(
  data: Record<string, string | number | boolean | null>
): Promise<WavedashResponse<boolean>>;
```

### Avatar sizes

`Wavedash.AvatarSize` exposes preset pixel values. Pass any preset (or a custom pixel size) to `getUserAvatarUrl`.

| Constant | Pixels | Use case |
|----------|--------|----------|
| `Wavedash.AvatarSize.SMALL` | 64 | Lists, compact UI |
| `Wavedash.AvatarSize.MEDIUM` | 128 | Profile cards, chat |
| `Wavedash.AvatarSize.LARGE` | 256 | Full profile view |

## Fullscreen

Request, exit, and check fullscreen state. See [Fullscreen](/sdk/fullscreen) for details.

| Function | Description |
|----------|-------------|
| `requestFullscreen(fullscreen)` | Asks the host to enter (`true`) or exit (`false`) fullscreen. Resolves to `true` if the host accepted, `false` if the browser rejected. Must be called from a user gesture to enter. |
| `toggleFullscreen()` | Flips the current fullscreen state. Resolves to `true` if the host accepted, `false` otherwise. Must be called from a user gesture when entering. |
| `isFullscreen()` | Returns whether the game is currently presented in fullscreen. |

```typescript
function requestFullscreen(fullscreen: boolean): Promise<boolean>;

function toggleFullscreen(): Promise<boolean>;

function isFullscreen(): boolean;
```

## Mute

Mute, unmute, and check mute state. See [Audio](/sdk/audio) for details.

| Function | Description |
|----------|-------------|
| `requestMute(muted)` | Asks the host to mute (`true`) or unmute (`false`). Resolves to `true` if the change was applied, `false` if it was rejected — the host won't let the game unmute over an explicit player mute. |
| `toggleMute()` | Flips the current mute state. Resolves to `true` if the change was applied, `false` otherwise. |
| `isMuted()` | Returns whether the game is currently muted. |

When `requestMute` / `toggleMute` actually change the mute state, the SDK emits a [`Wavedash.MUTE_CHANGED`](/sdk/events#mute-events) event with the new state. A rejected request (or one that doesn't change anything) emits nothing.

```typescript
function requestMute(muted: boolean): Promise<boolean>;

function toggleMute(): Promise<boolean>;

function isMuted(): boolean;
```

## Achievements & stats

Track player statistics and unlock achievements. See [Achievements & stats](/sdk/achievements) for details.

| Function | Description |
|----------|-------------|
| `requestStats()` | Fetches player stats from the server. |
| `getStat(statId)` | Returns the local value of a stat after `requestStats()` has resolved. |
| `setStat(statId, value, storeNow?)` | Sets a stat value locally. Pass `storeNow: true` to schedule a persist. |
| `getAchievement(achievementId)` | Returns whether an achievement is unlocked. |
| `setAchievement(achievementId, storeNow?)` | Unlocks an achievement. Pass `storeNow: true` to schedule a persist. |
| `storeStats()` | Immediately flushes all pending stat and achievement changes to the server. |

```typescript
function requestStats(): Promise<WavedashResponse<boolean>>;

function getStat(statId: string): number;

function setStat(
  statId: string,
  value: number,
  storeNow?: boolean
): boolean;

function getAchievement(achievementId: string): boolean;

function setAchievement(
  achievementId: string,
  storeNow?: boolean
): boolean;

function storeStats(): boolean;
```

## Leaderboards

Competitive scoreboards with rankings. See [Leaderboards](/sdk/leaderboards) for details.

| Function | Description |
|----------|-------------|
| `getLeaderboard(name)` | Fetches a leaderboard by name. Fails if it doesn't exist — use `getOrCreateLeaderboard` to create on miss. |
| `getOrCreateLeaderboard(name, sortOrder, displayType)` | Gets an existing leaderboard or creates one with the given settings. |
| `uploadLeaderboardScore(leaderboardId, score, keepBest, ugcId?)` | Submits a score. When `keepBest` is true, only updates if the score improves. |
| `listLeaderboardEntries(leaderboardId, start, count, friendsOnly?)` | Fetches a page of top entries. |
| `listLeaderboardEntriesAroundUser(leaderboardId, countAhead, countBehind, friendsOnly?)` | Fetches entries surrounding the current player's rank. |
| `getMyLeaderboardEntries(leaderboardId)` | Fetches the current player's own entries. |
| `getLeaderboardEntryCount(leaderboardId)` | Returns the cached total entry count (returns `-1` if not yet queried). |

```typescript
function getLeaderboard(
  name: string
): Promise<WavedashResponse<Leaderboard>>;

function getOrCreateLeaderboard(
  name: string,
  sortOrder: LeaderboardSortOrder,
  displayType: LeaderboardDisplayType
): Promise<WavedashResponse<Leaderboard>>;

function uploadLeaderboardScore(
  leaderboardId: Id<"leaderboards">,
  score: number,
  keepBest: boolean,
  ugcId?: Id<"userGeneratedContent">
): Promise<WavedashResponse<UpsertedLeaderboardEntry>>;

function listLeaderboardEntries(
  leaderboardId: Id<"leaderboards">,
  start: number,
  count: number,
  friendsOnly?: boolean
): Promise<WavedashResponse<LeaderboardEntry[]>>;

function listLeaderboardEntriesAroundUser(
  leaderboardId: Id<"leaderboards">,
  countAhead: number,
  countBehind: number,
  friendsOnly?: boolean
): Promise<WavedashResponse<LeaderboardEntry[]>>;

function getMyLeaderboardEntries(
  leaderboardId: Id<"leaderboards">
): Promise<WavedashResponse<LeaderboardEntry[]>>;

function getLeaderboardEntryCount(
  leaderboardId: Id<"leaderboards">
): number;
```

## Lobbies

Multiplayer room management. See [Multiplayer lobbies](/multiplayer/lobbies) for details.

| Function | Description |
|----------|-------------|
| `createLobby(visibility, maxPlayers)` | Creates and joins a new lobby and returns its ID. |
| `joinLobby(lobbyId)` | Joins an existing lobby. |
| `leaveLobby(lobbyId)` | Leaves a lobby. |
| `listAvailableLobbies(friendsOnly?)` | Lists lobbies that the player can join. |
| `getLobbyUsers(lobbyId)` | Returns the list of users currently in a lobby. |
| `getLobbyHostId(lobbyId)` | Returns the user ID of the lobby host. |
| `getNumLobbyUsers(lobbyId)` | Returns how many users are in a lobby. |
| `sendLobbyMessage(lobbyId, message)` | Sends a chat message to the lobby. |
| `inviteUserToLobby(lobbyId, userId)` | Sends a lobby invite to another user. |
| `setLobbyData(lobbyId, key, value)` | Sets a metadata key on the lobby (host only). |
| `getLobbyData(lobbyId, key)` | Reads a metadata key from the lobby. |
| `deleteLobbyData(lobbyId, key)` | Removes a metadata key from the lobby (host only). |
| `getLobbyInviteLink(copyToClipboard?)` | Generates a shareable invite link for the current lobby. |

```typescript
function createLobby(
  visibility: LobbyVisibility,
  maxPlayers: number
): Promise<WavedashResponse<Id<"lobbies">>>;

function joinLobby(
  lobbyId: Id<"lobbies">
): Promise<WavedashResponse<boolean>>;

function leaveLobby(
  lobbyId: Id<"lobbies">
): Promise<WavedashResponse<Id<"lobbies">>>;

function listAvailableLobbies(
  friendsOnly?: boolean
): Promise<WavedashResponse<Lobby[]>>;

function getLobbyUsers(
  lobbyId: Id<"lobbies">
): LobbyUser[];

function getLobbyHostId(
  lobbyId: Id<"lobbies">
): Id<"users"> | null;

function getNumLobbyUsers(
  lobbyId: Id<"lobbies">
): number;

function sendLobbyMessage(
  lobbyId: Id<"lobbies">,
  message: string
): boolean;

function inviteUserToLobby(
  lobbyId: Id<"lobbies">,
  userId: Id<"users">
): Promise<WavedashResponse<boolean>>;

function setLobbyData(
  lobbyId: Id<"lobbies">,
  key: string,
  value: string | number | null
): boolean;

function getLobbyData(
  lobbyId: Id<"lobbies">,
  key: string
): string | number | boolean | null;

function deleteLobbyData(
  lobbyId: Id<"lobbies">,
  key: string
): boolean;

function getLobbyInviteLink(
  copyToClipboard?: boolean
): Promise<WavedashResponse<string>>;
```

## P2P networking

Peer-to-peer messaging over WebRTC. See [Multiplayer networking](/multiplayer/networking) for details.

| Function | Description |
|----------|-------------|
| `broadcastP2PMessage(channel, reliable, payload)` | Sends a message to every connected peer. |
| `sendP2PMessage(userId, channel, reliable, payload)` | Sends a message to a single peer. |
| `readP2PMessageFromChannel(channel)` | Reads the next queued message from a channel, or `null` if empty. |
| `drainP2PChannelToBuffer(channel)` | Reads all queued messages into a tightly packed binary buffer for high-performance engines. |
| `getP2PMaxPayloadSize()` | Returns the maximum payload bytes for a single P2P message, derived from `P2PConfig.messageSize`. |
| `getP2PMaxIncomingMessages()` | Returns the configured max incoming messages per channel queue. |
| `getP2POutgoingMessageBuffer()` | Returns a pre-allocated scratch `Uint8Array` your game can write outgoing payload bytes into before calling `sendP2PMessage`. Used by engine SDKs for zero-copy handoff. |

```typescript
function broadcastP2PMessage(
  channel: number,
  reliable: boolean,
  payload: Uint8Array,
  payloadSize?: number
): boolean;

function sendP2PMessage(
  userId: Id<"users"> | undefined,
  channel: number,
  reliable: boolean,
  payload: Uint8Array,
  payloadSize?: number
): boolean;

function readP2PMessageFromChannel(
  channel: number
): P2PMessage | null;

function drainP2PChannelToBuffer(
  channel: number
): Uint8Array;

function getP2PMaxPayloadSize(): number;

function getP2PMaxIncomingMessages(): number;

function getP2POutgoingMessageBuffer(): Uint8Array;
```

In Unity, the equivalent is the static property `Wavedash.SDK.MAX_PAYLOAD_SIZE` (read once at `Init()` time and cached).

## Cloud saves

Remote file storage synced across devices. See [Cloud saves](/sdk/cloud-saves) for details.

| Function | Description |
|----------|-------------|
| `writeLocalFile(path, data)` | Writes a file to the local virtual filesystem. |
| `readLocalFile(path)` | Reads a file from the local virtual filesystem. |
| `uploadRemoteFile(path)` | Uploads a local file to the player's cloud storage. |
| `downloadRemoteFile(path)` | Downloads a file from cloud storage to the local filesystem. |
| `remoteFileExists(path)` | Checks whether a remote file exists. Sends a lightweight HEAD request — cheaper than attempting a download. |
| `deleteRemoteFile(path)` | Deletes a file from cloud storage. **JavaScript SDK only** — call it from Unity/Godot through JS interop. |
| `downloadRemoteDirectory(path)` | Downloads an entire directory from cloud storage. |
| `listRemoteDirectory(path)` | Lists files in a cloud storage directory. |

```typescript
function writeLocalFile(
  path: string,
  data: Uint8Array
): Promise<boolean>;

function readLocalFile(
  path: string
): Promise<Uint8Array | null>;

function uploadRemoteFile(
  path: string
): Promise<WavedashResponse<string>>;

function downloadRemoteFile(
  path: string
): Promise<WavedashResponse<string>>;

function remoteFileExists(
  path: string
): Promise<WavedashResponse<boolean>>;

function deleteRemoteFile(
  path: string
): Promise<WavedashResponse<string>>;

function downloadRemoteDirectory(
  path: string
): Promise<WavedashResponse<string>>;

function listRemoteDirectory(
  path: string
): Promise<WavedashResponse<RemoteFileMetadata[]>>;
```

## User-generated content

Replays, screenshots, levels, and other player-created files. See [User-generated content](/sdk/ugc) for details.

| Function | Description |
|----------|-------------|
| `createUGCItem(type, title?, description?, visibility?, localPath?)` | Creates a new UGC item and returns its ID. All args except `type` are optional — omit `localPath` to create metadata first and upload later via `updateUGCItem`. |
| `updateUGCItem(ugcId, updates?)` | Updates metadata and/or replaces the file on an existing UGC item. Pass only the fields you want to change in `updates`; any omitted field is untouched. |
| `deleteUGCItem(ugcId)` | Deletes a UGC item: removes it from the game's UGC library and frees the user's storage quota by the size of the deleted upload. |
| `downloadUGCItem(ugcId, localPath)` | Downloads a UGC item to the local filesystem. |
| `listUGCItems(args?)` | Lists UGC items with optional filters (`createdBy`, `ugcType`, `titleSearch`) and pagination (`numItems`, `continueCursor`). Returns `{ page, isDone, continueCursor }`. |

```typescript
function createUGCItem(
  type: UGCType,
  title?: string,
  description?: string,
  visibility?: UGCVisibility,
  localPath?: string
): Promise<WavedashResponse<Id<"userGeneratedContent">>>;

function updateUGCItem(
  ugcId: Id<"userGeneratedContent">,
  updates?: {
    title?: string;
    description?: string;
    visibility?: UGCVisibility;
    filePath?: string;
  }
): Promise<WavedashResponse<Id<"userGeneratedContent">>>;

function deleteUGCItem(
  ugcId: Id<"userGeneratedContent">
): Promise<WavedashResponse<Id<"userGeneratedContent">>>;

function downloadUGCItem(
  ugcId: Id<"userGeneratedContent">,
  localPath: string
): Promise<WavedashResponse<Id<"userGeneratedContent">>>;

function listUGCItems(
  args?: {
    createdBy?: Id<"users">;
    ugcType?: UGCType;
    titleSearch?: string;
    numItems?: number;
    continueCursor?: string;
  }
): Promise<WavedashResponse<PaginatedUGCItems>>;
```

## Paid content

Check ownership and open the paywall for Paid Content offers. See [Paid content](/sdk/paid-content) for details.

| Function | Description |
|----------|-------------|
| `isEntitled(contentIdentifier)` | Returns whether the player owns the given paid content. A UI hint; Wavedash enforces access when serving the files. |
| `getEntitlements()` | Returns every paid-content identifier the player owns for this game. |
| `triggerPaywall(contentIdentifier)` | Opens the Wavedash paywall for the content. Resolves `true` immediately if already owned; otherwise resolves with whether the purchase completed. |

```typescript
function isEntitled(
  contentIdentifier: string
): Promise<WavedashResponse<boolean>>;

function getEntitlements(): Promise<WavedashResponse<string[]>>;

function triggerPaywall(
  contentIdentifier: string
): Promise<WavedashResponse<boolean>>;
```

## Events

Subscribe to SDK events. See [Events reference](/sdk/events) for the full event list.

| Function | Description |
|----------|-------------|
| `on(eventName, listener)` | Registers a strongly-typed listener for an SDK event. listener receives the event payload. Returns an unsubscribe function. |
| `off(eventName, listener)` | Removes a listener previously registered with `on()`. Pass the same listener function you registered. |

```typescript
function on<K extends keyof WavedashEventMap>(
  eventName: K,
  listener: (payload: WavedashEventMap[K]) => void
): () => void;

function off<K extends keyof WavedashEventMap>(
  eventName: K,
  listener: (payload: WavedashEventMap[K]) => void
): void;
```
